Files
Charis 597d1ce56e fix(studio): pass caller options to grant-gated query factories (#53088)
## Context

Grant-gated query factories returned `queryFn: skipToken` when the
caller had no grant. TanStack Query keeps one options object per cache
entry, overwritten by whichever observer rendered last. When that was a
grant-less observer, invalidation refetched with `skipToken` and failed
with `Missing queryFn`, breaking the query for every other observer on
the key. #53075 patched two call sites; this fixes the factories.

## Changes

- New `grantedQueryOptions` helper (`data/granted-query-options.ts`).
Without a grant, the factory sets `queryFn: undefined` instead of
`skipToken`, so TanStack borrows the query function from a subscribed
observer that has one. The caller's `enabled` applies only when the
factory has a query function.
- `apiKeysQueryOptions`, `revealedApiKeysQueryOptions`,
`branchesQueryOptions`, `branchQueryOptions` and
`branchDiffQueryOptions` take caller options as a second argument. Call
sites change from `useQuery({ ...f(vars), enabled })` to
`useQuery(f(vars, { enabled }))`, so callers can't override the grant
gate.
- New type-aware `fga/no-spread-granted-query-options` lint rule
(error). `grantedQueryOptions` returns a type-only brand, and the rule
flags any spread or `Object.assign` of a branded value, however it was
built or named.
- Restores typed linting as a separate pass
(`eslint.type-checks.config.cjs`, run by `pnpm lint` via
`lint:type-checks`), as #44678 did. Enabling type info in the main
config changes what other plugins report, so it stays separate.
- `studio-queries` skill documents the pattern.

Callers still pass their own grant, so the UI gates on the same grant
the request carries.

## Testing

- `data/api-keys/api-keys-query.test.tsx`: a granted and a grant-less
component share the key, with the grant-less one rendering last;
invalidation via the delete mutation refetches successfully. Fails on
master with `Missing queryFn`.
- `data/granted-query-options.test.ts`: `enabled` gating, factory fields
win over caller fields, `select` type inference.
- Lint rule cases in `scripts/__tests__/fga-eslint-rules.test.ts`.

🤖 Generated with [Claude Code](https://claude.com/claude-code)
2026-11-06 11:04:00 -05:00

142 lines
3.8 KiB
TypeScript

import { apiKeysKeys } from './keys'
import { get, handleError } from '@/data/fetchers'
import { grantedQueryOptions, type GrantedQueryCallerOptions } from '@/data/granted-query-options'
import type { StudioError } from '@/lib/errors/studio-errors'
import type { GrantFor } from '@/lib/grants'
type LegacyKeys = {
api_key: string
description?: string | null
hash?: string | null
id?: string | null
inserted_at?: string | null
name: string
prefix?: string | null
secret_jwt_template?: { role: string } | null
type: 'legacy' | null
updated_at?: string | null
}
type SecretKeys = {
api_key: string
description?: string
hash: string
id: string
inserted_at: string
name: string
prefix: string
secret_jwt_template: { role: string }
type: 'secret'
updated_at?: string
}
type PublishableKeys = {
api_key: string
description?: string
hash?: string
id: string
inserted_at: string
name: string
prefix?: string
secret_jwt_template?: { role: string } | null
type: 'publishable'
updated_at?: string
}
export type APIKey = LegacyKeys | SecretKeys | PublishableKeys
export type APIKeysGrant = GrantFor<'get', '/v1/projects/{ref}/api-keys'>
export type RevealedAPIKeysGrant = GrantFor<'get', '/v1/projects/{ref}/api-keys', 'reveal'>
export type APIKeysVariables = {
projectRef?: string
grant?: APIKeysGrant
}
export type RevealedAPIKeysVariables = {
projectRef?: string
grant?: RevealedAPIKeysGrant
}
/** The wrapper sets the `reveal` query param from the grant's variant. */
async function getAPIKeys(
{ projectRef, grant }: { projectRef: string; grant: APIKeysGrant | RevealedAPIKeysGrant },
signal?: AbortSignal
) {
const { data, error } = await get(`/v1/projects/{ref}/api-keys`, {
params: { path: { ref: projectRef } },
signal,
grant,
})
if (error) handleError(error)
// [Jonny]: Overriding the types here since some stuff is not actually nullable or optional
return data as unknown as APIKey[]
}
export type APIKeysData = Awaited<ReturnType<typeof getAPIKeys>>
export type APIKeysError = StudioError
/** Keys without their secret values (`reveal=false`). Needs a plain grant. */
export const apiKeysQueryOptions = <TData = APIKeysData>(
{ projectRef, grant }: APIKeysVariables,
options?: GrantedQueryCallerOptions<
APIKeysData,
APIKeysError,
TData,
ReturnType<typeof apiKeysKeys.list>
>
) =>
grantedQueryOptions(
{
queryKey: apiKeysKeys.list(projectRef, false),
queryFn:
projectRef && grant ? ({ signal }) => getAPIKeys({ projectRef, grant }, signal) : undefined,
},
options
)
/** Keys with their secret values (`reveal=true`). Needs the `reveal` grant. */
export const revealedApiKeysQueryOptions = <TData = APIKeysData>(
{ projectRef, grant }: RevealedAPIKeysVariables,
options?: GrantedQueryCallerOptions<
APIKeysData,
APIKeysError,
TData,
ReturnType<typeof apiKeysKeys.list>
>
) =>
grantedQueryOptions(
{
queryKey: apiKeysKeys.list(projectRef, true),
queryFn:
projectRef && grant ? ({ signal }) => getAPIKeys({ projectRef, grant }, signal) : undefined,
},
options
)
const EmptyKey = {
anonKey: undefined,
serviceKey: undefined,
publishableKey: undefined,
secretKey: undefined,
allSecretKeys: [],
}
export const getKeys = (apiKeys: APIKey[] = []) => {
if (!Array.isArray(apiKeys)) {
return EmptyKey
}
const anonKey = apiKeys.find((x) => x.name === 'anon')
const serviceKey = apiKeys.find((x) => x.name === 'service_role')
// [Joshen] For now I just want 1 of each, I don't need all
const publishableKey = apiKeys.find((x) => x.type === 'publishable')
const secretKey = apiKeys.find((x) => x.type === 'secret')
const allSecretKeys = apiKeys.filter((x) => x.type === 'secret')
return { anonKey, serviceKey, publishableKey, secretKey, allSecretKeys }
}