mirror of
https://github.com/supabase/supabase.git
synced 2026-12-04 15:39:13 +00:00
docs/tutorial-template
6
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
395a54f2b7 |
feat(studio): gate jwt signing keys, legacy api keys, and third-party auth on grants (#53241)
Resolves [FE-4732](https://linear.app/supabase/issue/FE-4732/grants-rollout-jwt-signing-keys-legacy-api-keys-and-third-party-auth). ## Changes Gates the JWT signing keys, legacy API keys, and third-party auth endpoints on grants instead of `unguarded.migrating`, and replaces their V2 permission guards with `useGrant`: - **Data layer (11 sites):** `data/jwt-signing-keys/*`, `data/api-keys/legacy-api-keys-status-query`, `data/api-keys/legacy-api-key-toggle-mutation`, and `data/third-party-auth/*`. Queries become grant-gated query option factories; mutations take the grant in their variables. - **Consumers:** the JWT settings page, the JWT signing keys table and its dialogs, `jwt-settings`, `ToggleLegacyApiKeys`, `Project/APIKeys`, and the third-party auth page, form, and create dialogs. Each consumer renders denied and error states. - **JWT signing keys table:** - It's gated only on the signing keys reads (`GET signing-keys` and `GET signing-keys/legacy`, both `auth_signing_keys_read`). - The legacy API keys status is only used by the revoke dialogs. If it can't be read, revoking the legacy JWT secret fails closed: the user sees the "disable legacy API keys first" warning, with copy explaining why, instead of the confirm modal. - **Legacy JWT secret query:** a 404 (secret not imported as a signing key yet) resolves to `null` and shows the "Migrate JWT secret" panel. Other errors now render an error instead of being treated as "not migrated". - **Write actions:** - `getWriteGrantTooltip` moves from `APIKeys.utils` to `lib/grants` and takes a resource noun. Disabled write actions use it to explain why they're disabled. - New `getWriteGrantToastMessage`: handlers that run without a grant now show a toast instead of silently doing nothing. This includes the API keys handlers from #52966. ## Permission changes - **Legacy API keys toggle and status** (`GET`/`PUT /v1/projects/{ref}/api-keys/legacy`): the guard moves from `auth_signing_keys_read`/`_write` to the endpoint annotation, `api_gateway_keys_read`/`_write`. The annotation was confirmed against the backend controller (FE-4728). As a result, the JWT signing keys table's legacy revoke check now depends on `api_gateway_keys_read`. - **API keys last-used analytics** (`/platform/projects/{ref}/analytics/endpoints/api_keys.last_used.otel`): this endpoint uses legacy permissions (`analytics:Read` on `logflare`), not FGA. Its check moves from the V2 `auth_signing_keys_read` check to `useAsyncCheckPermissions(PermissionAction.ANALYTICS_READ, 'logflare')`. - Every other guard already matched its annotation: - `auth_signing_keys_read`/`_write` for signing keys - `auth_config_read`/`_write` for third-party auth ## Testing - Data layer: `jwt-signing-keys.test.ts`, `legacy-api-keys.test.ts`, and `third-party-auth.test.ts` cover every migrated fetcher, check that factories stay disabled without a grant, and cover legacy-key 404 vs. 500. - `jwt-secret-keys-table/index.platform.test.tsx`: - Legacy status denied: the table still renders, and revoking the legacy key shows only the warning. - Legacy status known enabled or disabled. - Signing keys read denied. - Legacy key 404 vs. 500. - `create-key-dialog.platform.test.tsx`: triggering create without a grant shows the toast and sends no request. - `ToggleLegacyApiKeys.platform.test.tsx`, `ThirdPartyAuthForm.platform.test.tsx`, and `settings/jwt/index.platform.test.tsx`: granted, denied, error, and partial-permission cases. - `lib/grants.test.ts`: the tooltip and toast helpers. 🤖 Generated with [Claude Code](https://claude.com/claude-code) |
||
|
|
1353178ac9 |
feat(studio): add read/write grant variants for pg-meta query (#53185)
Resolves FE-4729. First PR of the SQL grants series (FE-4697).
## What
Adds the mechanism for read and write grants on `POST
/platform/pg-meta/{ref}/query`. Every caller keeps `unguarded.migrating`
until its domain PR.
- `fga-refinements.ts`: `read` (`database_read`) and `write`
(`database_write`) variants, with `variantRequired`.
- `@supabase/pg-meta`: a `WriteSqlFragment` brand and `asWriteSql()`.
`safeSql` and `joinSqlFragments` return `WriteSqlFragment` when any
input is one, so composing write SQL keeps the brand.
- `executeSql`: overloads tie the grant to the SQL type. Write SQL needs
a write grant; other SQL takes a read or write grant.
## Notes
- The write check is type-only. Nothing in a pg-meta query request marks
it as a write, so the development-only `assertGrant` can't detect one.
The branch variants make the same trade-off, and the backend enforces
permissions either way.
- SQL written from scratch still needs `asWriteSql` where it's built.
Domain PRs mark their builders.
- Server-side callers (AI tools) will use `unguarded.byDesign`: they
forward the user's token, so the platform API enforces permissions.
FE-4750 applies this.
## Testing
- Type tests: grant/raw-client equality for both variants, rejection of
plain and unknown-variant grants, read/write brand invariance,
`executeSql` and `mutate()` rejecting write SQL with a read grant, and
brand propagation through `safeSql` and `joinSqlFragments`.
- `unguarded.migrating` count unchanged.
|
||
|
|
9391f60ec9 |
test(studio): add shared permissions mocks and testGrant helper (#52312)
## Problem Components and fetchers are moving to endpoint-bound FGA grants, so more tests need to mock `/platform/profile/permissions/v2` and mint grants. Each test file currently defines its own permissions response type and mock, and `testGrant` lives inside `guarded-fetch.test.ts`. Resolves [FE-4692](https://linear.app/supabase/issue/FE-4692/test-infra-global-msw-handler-for-v2-permissions-and-testgrant). ## Solution * `tests/lib/permissions-fixtures.ts`: shared `PermissionsV2Response` type, `ALL_FGA_PERMISSIONS`, `allPermissionsFor(slugs)` (grants everything at the org level), and `NO_PERMISSIONS`. * `tests/lib/msw-permissions.ts`: `mockPermissions(response)` and `mockPermissionsError({ status, message })` on top of `addAPIMock`. * `tests/lib/test-grant.ts`: `testGrant(endpoint, { variant, organizationSlug, projectRef, permissionsProjectRef })` for unit tests of fetchers and query options, moved out of `guarded-fetch.test.ts`. * Existing tests that mocked the v2 endpoint now use the shared helpers. `IndirectTaxDeclarationModal.test.tsx` keeps its own `addAPIMock` because a test asserts the request was served. * Documented in `apps/studio/tests/README.md` and the `studio-mock-api-tests` skill. |
||
|
|
254e24b170 |
feat(studio): require grants in fetch wrappers for FGA-annotated endpoints (#52238)
## Problem Resolves FE-4689 and FE-4690. Builds on #52105. Studio's fetch wrappers don't know which FGA permissions an endpoint requires, so a UI guard and the request it protects can drift apart. This makes the `grant` minted by `useGrant`/`getGrant`/`ensureGrant` part of the request itself: calling an annotated endpoint without a matching grant is a compile error. ## Solution ### What changed - **Fetch wrappers** (`data/fetchers.ts`, `data/guarded-fetch.ts`): `get`/`post`/`put`/`patch`/`del` keep their names, so no imports change. - The `grant` option is required for endpoints annotated with `x-fga-permissions`, and forbidden for unannotated ones. - It accepts a `Grant` for that exact endpoint (or one of its variants) or `unguarded`. - The wrapper strips the grant before calling openapi-fetch. - `head`/`trace`/`options` are unchanged. - **Owned params**: refinements can declare query params the wrapper sets from the grant's variant (`ownedQuery`). These params are removed from the init type (`Omit<Query, Owned> & { [K in Owned]?: never }`), so callers can't pass them. Nothing uses this yet: the api-keys `reveal` variant is the first. - **`assertGrant`** runs in development only and throws `GrantAssertionError`. It checks: - the endpoint; - a missing grant; - the variant against `when(init)` predicates; - the path `ref` against the grant's project, also accepting the parent project ref for a grant minted on a branch; - the path `slug` against the grant's organization. - **Escape hatches**: - `unguarded.migrating` for unmigrated call sites. - `unguarded.byDesign('reason')` for calls that intentionally skip the check. - **Grants** now record `permissionsProjectRef`, the ref permissions were evaluated against. It's required once the scope is resolved. - **Readable errors**: a missing or wrong grant reports the caller's own init type plus the expected `grant` type, instead of openapi-fetch's full options type. Under `noErrorTruncation`, the old message was tens of KB per call site. - **`executeSql`** now requires a grant for `POST /platform/pg-meta/{ref}/query`, so every caller counts as unmigrated. - **Codemod**: added `grant: unguarded.migrating` at every existing call site that hits an annotated endpoint, including all `executeSql` callers. No behavior change. A follow-up lint rule ratchets the count down. - **Dependencies**: adds `openapi-typescript-helpers` (the version openapi-fetch already uses) for the helper types. Only openapi-fetch's unexported `InitParam` is copied locally. ### Type-level notes - The grant is checked in the parameter type rather than in `Init`'s constraint. That way `Init` is still inferred from the argument, which keeps both the return type and the error message tied to the caller's code. - The grant is replaced rather than intersected. Intersecting a wrong grant with the expected one can reduce the init type to `never`, which then accepts the call. - `NoInfer<Path>` stops a grant's endpoint from becoming an inference candidate for the path. ## Review instructions ### Tests - `data/guarded-fetch.test.ts`: - Type equality with the raw client: required params and body, template-literal paths, `parseAs`, `signal`/`headers`, optional-init endpoints, and `unguarded`. An openapi-fetch upgrade that breaks the local `InitParam` copy fails typecheck. - Negative type cases: - a missing or `undefined` grant; - a missing init on an annotated endpoint; - a grant for a different path or method; - any grant or `unguarded` on an unannotated endpoint; - a forged grant; - params and body still checked; - an unknown path. - `guardMethod` and `assertGrant` runtime behavior, including branch-parent refs and org slugs. - Variant and owned-param tests are deferred to the api-keys (`reveal`) and pg-meta (`read`/`write`) PRs, since no refinements exist yet. 1. Run `pnpm typecheck` and confirm Studio passes. Then remove a `grant: unguarded.migrating` and check that the error is short and names the expected grant. 2. Run `pnpm test:studio`. 3. Skim the codemod commit: it only adds `grant: unguarded.migrating` and the `unguarded` import. ## Checklist Check all before review: - [ ] I have read [CONTRIBUTING.md](https://github.com/supabase/supabase/blob/master/CONTRIBUTING.md) - [ ] If I wrote a new docs topic or edited an existing topic, I used the `/write-the-docs` or `/edit-the-docs` skill, which applies the docs [style guide](https://github.com/supabase/supabase/tree/master/apps/docs/style-guide) |
||
|
|
60b51d74d5 |
Audit existing unit tests + Remove redundant ones (#52215)
## Context
_TLDR: Changes here speeds up unit tests on CI from ~14 minutes to ~3
minutes_ 😂
_TLDR 2: The file changes are solely only test files +
`studio-unit-tests.yml`_
We've currently got a lot of unit tests in the repository which while
great for coverage, hasn't been ideally written. There's a lot of
redundancy + overly specific tests that break easily, and our current
unit test takes about 15 minutes to run in the GHA per PR. Hence am
doing a audit clean up of all existing unit tests in the studio repo.
## Changes involved
- `.test.ts` files now run in `node`, `.test.tsx` in `jsdom`
- jsdom costs about 1s of setup per file. A `.ts` test that needs the
DOM opts in with `// @vitest-environment jsdom` (46 files do).
- Removed redundant and over-specific tests
- Duplicates are merged into `test.each`. Tests that only covered
libraries, existed for coverage, or asserted class names and snapshots
are deleted. 19 files are merged into a sibling or deleted.
- Fixed about 15 tests that couldn't fail
- Examples: unawaited assertions, fixtures equal to the default, and a
`semverGte` test calling `semverLte`.
- Sped up the slowest files
- Real sleeps are replaced with fake timers, `user.type` with paste, and
Radix option queries are scoped to the open listbox. For example,
`RestoringState` went from 18s to 0.3s and
`useTableEditorFiltersSort.navigation` from 20s to 3s.
- These ^ already shave down the unit tests time from 14 mins to 9 mins,
but am also sharding unit tests across 4 jobs to increase speed up
further which then shaves down time to 3 mins now
|
||
|
|
1bcc472d64 |
feat(studio): add Grant type and useGrant/getGrant/ensureGrant (#52105)
## Problem
Resolves FE-4688.
Core types and minting for endpoint-bound FGA grants. A `Grant<E, V>` is
minted by checking the user's v2 permissions against the generated
`fgaRequirements` map for endpoint `E` (and optional variant `V`).
Nothing consumes grants yet: the fetch wrappers that require them come
in a follow-up PR.
## Solution
### What changed
- **`lib/grants.ts`** (new)
- `Grant<E, V>`: the brand is a function type, so it's invariant in both
the endpoint and the variant. A grant only satisfies its exact endpoint
and variant.
- `GrantResult` is `loading | granted | denied | error`, and `.grant` is
defined only when granted.
- `GrantFor<Method, Path>` resolves to the grant type for an annotated
endpoint, or `never` otherwise.
- Minting functions:
- `getGrant` is pure.
- `useGrant` resolves org and project from the URL unless the scope
overrides them.
- `ensureGrant` is for imperative code and prefetch.
- Self-hosted always mints. A failed permissions request returns
`error`. Grants are never part of query keys.
- **`lib/fga-refinements.ts`** (new): an empty map defining the shape
for named variants. Each entry records the base annotation it was
written against, so typecheck fails if that annotation changes.
- **`permissions-query-v2.ts`**: adds a `permissionsQueryOptionsV2`
factory. `usePermissionsQueryV2` is now a thin wrapper around it, with
the same signature and the same 5-minute `staleTime`.
- **`doPermissionsCheckV2`**:
- Now accepts OR-of-AND requirement groups. Existing single-permission
and flat-list calls behave as before.
- Empty input never grants, including an empty group.
- **`usePermissionScopeV2`**: org/project/branch-parent resolution
extracted from the V2 hook, so `useGrant` and
`useAsyncCheckPermissionsV2` share one implementation.
- **Invalidation**: the role assign, unassign, and update mutations,
`UpdateRolesConfirmationModal`, and project creation now invalidate the
v2 permissions query.
- **knip**: temporary `files` ignore for `lib/grants.ts` until its first
consumer lands.
### Behavior change
`useAsyncCheckPermissionsV2` with an explicit `projectRef` equal to the
URL's project ref now resolves branch projects to their parent before
checking. Previously, any explicit ref skipped that resolution, so users
with project-scoped roles were denied on branch projects. An explicit
ref that differs from the URL ref is still used as-is.
## Review instructions
### Tests
- Unit tests for `doPermissionsCheckV2` with OR-of-AND groups.
- `lib/grants.test.ts`:
- `getGrant`, `useGrant`, and `ensureGrant` across OR-of-AND groups,
branch projects, explicit scope, self-hosted, and loading/denied/error
states.
- Type tests: a grant can't be used for a different endpoint, a plain
object isn't a grant, `GrantFor`, and status narrowing.
The type test that a grant without a variant can't satisfy a variant
parameter moves to the api-keys refinement PR, since no endpoint has
variants yet.
1. Run `pnpm test:studio` and confirm the `doPermissionsCheckV2` and
`lib/grants` tests pass.
2. Run `pnpm typecheck` to confirm the grant type tests hold.
3. Check the branch-project behavior in `useAsyncCheckPermissionsV2`
with an explicit `projectRef` matching the URL's project ref.
## Checklist
Check all before review:
- [ ] I have read
[CONTRIBUTING.md](https://github.com/supabase/supabase/blob/master/CONTRIBUTING.md)
- [ ] If I wrote a new docs topic or edited an existing topic, I used
the `/write-the-docs` or `/edit-the-docs` skill, which applies the docs
[style
guide](https://github.com/supabase/supabase/tree/master/apps/docs/style-guide)
|