From e3d4931ffcfb3a4a890eb8c4a22b7202d19cc2d6 Mon Sep 17 00:00:00 2001 From: Gefei Hou Date: Fri, 13 Nov 2026 21:04:58 -0800 Subject: [PATCH 1/6] feat(server): mintTenantOwnerHandoff for passwordless owner builds (planning#2511) The platform half of planning#2511, on top of constructive-db#4356. A platform account that signed in with Google, an emailed link, or a phone code has no password, so it cannot satisfy a tenant's sign_in. The platform's sign-in procedures now record what that sign-in proved (method + identifier, bound to the session and credential); this mutation turns that evidence into the owner's tenant session. - ownership comes from metaschema_public.database.owner_id, never the client - the evidence row must be the caller's, bound to jwt.claims.token_id, unexpired and unconsumed; UPDATE and read are one statement, so it cannot be replayed - the tenant's sign_in_platform_identity resolves the owner from the identifier and applies the tenant's MFA / device policy - the no-MFA path mints a one-time PKCE-bound hand-off code with the tenant's mint_native_handoff(..., challenge_only => true); a pending MFA or device approval returns the challenge instead of a code - registered only on the platform database's APIs; a tenant never authors a session for another tenant The SQL path is covered end-to-end by packages/metaschema/__tests__/auth/sign-in-platform-identity.test.ts in constructive-db (ownership, credential-bound consume, tenant sign-in, mint, one-time replay, column-scope refusal). --- graphql/server/src/middleware/graphile.ts | 5 + .../src/plugins/owner-handoff-plugin.ts | 290 ++++++++++++++++++ 2 files changed, 295 insertions(+) create mode 100644 graphql/server/src/plugins/owner-handoff-plugin.ts diff --git a/graphql/server/src/middleware/graphile.ts b/graphql/server/src/middleware/graphile.ts index 735bb14423..f0b94b1cc0 100644 --- a/graphql/server/src/middleware/graphile.ts +++ b/graphql/server/src/middleware/graphile.ts @@ -26,6 +26,7 @@ import { HandlerCreationError } from '../errors/api-errors'; import { respondWithGraphQLError } from '../errors/graphql-response'; import { AuthCookiePlugin } from '../plugins/auth-cookie-plugin'; import { createErrorEventsPlugin } from '../plugins/error-events-plugin'; +import { OwnerHandoffPlugin } from '../plugins/owner-handoff-plugin'; import { RequestProtectionPlugin } from '../plugins/request-protection-plugin'; import { WebauthnPlugin } from '../plugins/webauthn-plugin'; import type { ApiOptions, DatabaseSettings } from '../types'; @@ -118,6 +119,10 @@ const buildPreset = ( // Only when the tenant provisioned the WebAuthn module; the policy // itself is read per request from `req.api.webauthnSettings`. ...(webauthn ? [WebauthnPlugin] : []), + // planning#2511: the platform's passwordless owner hand-off. Registered + // only on the platform database's own APIs — a tenant must never mint a + // session into another tenant. + ...(platform ? [OwnerHandoffPlugin] : []), // Only registered when the compute module is provisioned for this // database — all schema/table names come from the constructive // metaschema (express-context compute module loader); the plugin has diff --git a/graphql/server/src/plugins/owner-handoff-plugin.ts b/graphql/server/src/plugins/owner-handoff-plugin.ts new file mode 100644 index 0000000000..d6ae810e20 --- /dev/null +++ b/graphql/server/src/plugins/owner-handoff-plugin.ts @@ -0,0 +1,290 @@ +import '../middleware/types'; + +import { QuoteUtils } from '@pgsql/quotes'; +import { context as grafastContext, lambda, object, type Step } from 'grafast'; +import type { GraphileConfig } from 'graphile-config'; +import { extendSchema, gql } from 'graphile-utils'; + +/** + * Passwordless owner hand-off (constructive-planning#2511). + * + * A platform account that signed in with Google, an emailed link, or a phone + * code has no password, so it cannot satisfy the tenant's `sign_in`. The + * platform realm's sign-in procedures already recorded what that sign-in + * proved in `sign_in_evidence` (method + a proven identifier, bound to the + * session and the credential it minted). This mutation turns that evidence + * into the owner's tenant session: + * + * 1. the caller must own the target database (never a client-supplied id); + * 2. the evidence row must belong to this caller and to the credential this + * request presented (`jwt.claims.token_id`), and be unexpired/unconsumed; + * 3. the tenant's own `sign_in_platform_identity` resolves the owner from the + * identifier and applies the tenant's MFA / device policy; + * 4. the tenant mints a one-time, PKCE-bound hand-off code that the desktop + * exchanges for the session. + * + * The row is consumed by the same statement that reads it, so a retry after a + * crash cannot replay a proof. + */ + +interface PgClient { + query(opts: { text: string; values?: unknown[] }): Promise<{ rows: Array> }>; +} + +type WithPgClient = ( + pgSettings: Record | null, + cb: (client: PgClient) => Promise +) => Promise; + +export interface OwnerHandoffInput { + /** The signed-in platform user (jwt.claims.user_id). */ + userId: string; + /** The credential this request presented (jwt.claims.token_id). */ + tokenId: string | null; + /** The platform database serving the request (where evidence lives). */ + platformDatabaseId: string; + /** The tenant database to sign the owner into. */ + databaseId: string; + /** S256 challenge the desktop will present at the exchange. */ + codeChallenge: string; +} + +export interface OwnerHandoffResult { + code: string | null; + userId: string; + mfaRequired: boolean; + mfaSetupRequired: boolean; + deviceApprovalRequired: boolean; + mfaChallengeToken: string | null; +} + +const isUuid = (value: unknown): value is string => + typeof value === 'string' && /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(value); + +// PKCE S256: 43 base64url characters (32 random bytes). The tenant's +// native_handoff_guard_stmts enforces the same shape when the code is minted. +const S256_CHALLENGE = /^[-_A-Za-z0-9]{43}$/; + +function fail(code: string, message: string): never { + const error = new Error(`${code}: ${message}`) as Error & { code: string }; + error.code = code; + throw error; +} + +const authPrivateSchemaSql = ` + SELECT auth_private.schema_name + FROM metaschema_modules_public.identity_providers_module providers + JOIN metaschema_public.schema auth_private ON auth_private.id = providers.private_schema_id + WHERE providers.database_id = $1 + LIMIT 1 +`; + +const platformEvidenceSchemaSql = ` + SELECT auth_private.schema_name + FROM metaschema_modules_public.user_auth_module uam + JOIN metaschema_public.schema auth_private ON auth_private.id = uam.private_schema_id + WHERE uam.database_id = $1 + LIMIT 1 +`; + +/** + * The SQL half, kept separate from the GraphQL wiring so it can be exercised + * against a real database. Runs as the request role, with the request's claims + * already applied: the evidence policy scopes reads to the caller, and the + * tenant procedures are granted to `authenticated`. + */ +export const mintTenantOwnerHandoff = async ( + tx: PgClient, + input: OwnerHandoffInput +): Promise => { + if (!isUuid(input.userId)) fail('UNAUTHENTICATED', 'a platform session is required'); + if (!isUuid(input.databaseId)) fail('BAD_REQUEST', 'databaseId must be a uuid'); + if (!S256_CHALLENGE.test(input.codeChallenge)) { + fail('BAD_REQUEST', 'codeChallenge must be a 43-character base64url S256 challenge'); + } + + // Ownership is the platform's own row, not a client claim. A missing row and + // someone else's row answer the same way: the caller may not learn which + // database ids exist. + const database = await tx.query({ + text: 'SELECT owner_id::text AS owner_id FROM metaschema_public.database WHERE id = $1', + values: [input.databaseId] + }); + const ownerId = database.rows[0]?.owner_id; + if (typeof ownerId !== 'string') fail('DATABASE_NOT_FOUND', 'no such database'); + if (ownerId !== input.userId) fail('NOT_DATABASE_OWNER', 'only the database owner may hand off a session'); + + const evidenceSchema = await tx.query({ + text: platformEvidenceSchemaSql, + values: [input.platformDatabaseId] + }); + const evidenceSchemaName = evidenceSchema.rows[0]?.schema_name; + if (typeof evidenceSchemaName !== 'string') { + fail('TENANT_AUTH_NOT_PROVISIONED', 'the platform realm has no auth module'); + } + + // Consume and read in one statement: the subselect locks the row, and the + // outer UPDATE stamps it, so two concurrent calls cannot both spend it. + const evidenceTable = QuoteUtils.quoteQualifiedIdentifier(evidenceSchemaName, 'sign_in_evidence'); + const evidence = await tx.query({ + text: ` + UPDATE ${evidenceTable} AS evidence + SET consumed_at = now() + WHERE evidence.id = ( + SELECT candidate.id + FROM ${evidenceTable} AS candidate + WHERE candidate.user_id = $1 + AND candidate.credential_id = jwt_private.current_token_id() + AND candidate.consumed_at IS NULL + AND candidate.expires_at > now() + ORDER BY candidate.auth_time DESC + LIMIT 1 + FOR UPDATE SKIP LOCKED + ) + RETURNING evidence.method, evidence.identifier, evidence.user_id::text AS user_id + `, + values: [input.userId] + }); + + const proven = evidence.rows[0]; + if (!proven || typeof proven.method !== 'string' || typeof proven.identifier !== 'string') { + fail('STEP_UP_REQUIRED', 'sign in again to prove an identifier'); + } + if (proven.user_id !== input.userId) { + fail('OWNER_MISMATCH', 'the proved identity does not belong to the caller'); + } + + const tenant = await tx.query({ + text: authPrivateSchemaSql, + values: [input.databaseId] + }); + const tenantAuthSchema = tenant.rows[0]?.schema_name; + if (typeof tenantAuthSchema !== 'string') { + fail('TENANT_AUTH_NOT_PROVISIONED', 'the target database has no auth module'); + } + + const signIn = QuoteUtils.quoteQualifiedIdentifier(tenantAuthSchema, 'sign_in_platform_identity'); + const session = await tx.query({ + text: `SELECT * FROM ${signIn}($1, $2)`, + values: [proven.method, proven.identifier] + }); + const row = session.rows[0]; + if (!row) fail('TENANT_SIGN_IN_FAILED', 'sign_in_platform_identity returned no row'); + + const result: OwnerHandoffResult = { + code: null, + userId: String(row.user_id ?? ''), + mfaRequired: row.mfa_required === true, + mfaSetupRequired: row.mfa_setup_required === true, + deviceApprovalRequired: row.device_approval_required === true, + mfaChallengeToken: typeof row.mfa_challenge_token === 'string' ? row.mfa_challenge_token : null + }; + + // A challenged owner finishes on the tenant's existing MFA/device path; no + // hand-off code exists until the session does. + if (result.mfaRequired || result.deviceApprovalRequired) return result; + if (result.userId !== input.userId) { + fail('OWNER_MISMATCH', 'the tenant session belongs to a different user'); + } + + const accessToken = row.access_token; + if (typeof accessToken !== 'string' || !accessToken) { + fail('TENANT_SIGN_IN_FAILED', 'sign_in_platform_identity minted no access token'); + } + + // No redirect URI: the caller is the app, not a browser. challenge_only lets + // the tenant mint the PKCE-bound code without one. + const mint = QuoteUtils.quoteQualifiedIdentifier(tenantAuthSchema, 'mint_native_handoff'); + const handoff = await tx.query({ + text: `SELECT ${mint}($1, NULL, $2, true) AS code`, + values: [accessToken, input.codeChallenge] + }); + const code = handoff.rows[0]?.code; + if (typeof code !== 'string' || !code) fail('TENANT_SIGN_IN_FAILED', 'mint_native_handoff returned no code'); + + result.code = code; + return result; +}; + +interface ResolvedArgs { + input: { databaseId?: unknown; codeChallenge?: unknown } | null; + withPgClient: WithPgClient; + pgSettings: Record | null; +} + +const resolveArgs = (fieldArgs: any): Step => + object({ + input: fieldArgs.getRaw('input'), + withPgClient: grafastContext().get('withPgClient'), + pgSettings: grafastContext().get('pgSettings') + }) as unknown as Step; + +/** + * Platform-only: a tenant must never author a session for another tenant, so + * this plugin is registered only on the platform database's own APIs. + */ +export const OwnerHandoffPlugin: GraphileConfig.Plugin = { + ...extendSchema(() => ({ + typeDefs: gql` + input MintTenantOwnerHandoffInput { + clientMutationId: String + """The tenant database the caller owns.""" + databaseId: UUID! + """S256 PKCE challenge the desktop will present at the exchange.""" + codeChallenge: String! + } + + type MintTenantOwnerHandoffPayload { + """One-time code to exchange for the tenant session; null when a challenge is pending.""" + code: String + """The tenant user the session belongs to (the platform user's UUID).""" + userId: UUID + """An enrolled factor must be completed before a session exists.""" + mfaRequired: Boolean! + """The tenant requires MFA but the owner has no factor enrolled yet.""" + mfaSetupRequired: Boolean! + """A new device must be approved by email before a session exists.""" + deviceApprovalRequired: Boolean! + """Token for the tenant's completeMfaChallenge path.""" + mfaChallengeToken: String + } + + extend type Mutation { + """ + Sign the owner of \`databaseId\` into that database's tenant without a + password, using the platform sign-in this session already proved. + """ + mintTenantOwnerHandoff(input: MintTenantOwnerHandoffInput!): MintTenantOwnerHandoffPayload + } + `, + plans: { + Mutation: { + mintTenantOwnerHandoff(_$mutation: any, fieldArgs: any) { + return lambda(resolveArgs(fieldArgs), async ({ input, withPgClient, pgSettings }: ResolvedArgs) => { + const userId = pgSettings?.['jwt.claims.user_id']; + const tokenId = pgSettings?.['jwt.claims.token_id'] ?? null; + const platformDatabaseId = pgSettings?.['jwt.claims.database_id']; + if (!userId) fail('UNAUTHENTICATED', 'a platform session is required'); + + const databaseId = input?.databaseId; + const codeChallenge = input?.codeChallenge; + if (typeof databaseId !== 'string' || typeof codeChallenge !== 'string') { + fail('BAD_REQUEST', 'databaseId and codeChallenge are required'); + } + + return withPgClient(pgSettings, (tx) => + mintTenantOwnerHandoff(tx, { + userId, + tokenId, + platformDatabaseId: String(platformDatabaseId ?? ''), + databaseId, + codeChallenge + }) + ); + }); + } + } + } + })), + name: 'OwnerHandoffPlugin' +}; From 5b5556d77962d9c928b33d289e88f1e1e74174ec Mon Sep 17 00:00:00 2001 From: Gefei Hou Date: Fri, 13 Nov 2026 21:28:07 -0800 Subject: [PATCH 2/6] fix(server): address review findings on the owner hand-off - Resolve the tenant auth private schema from user_auth_module.private_schema_id rather than identity_providers_module.private_schema_id: the identity-provider module is optional in some presets while the auth module is not, so the hand-off would have failed for a tenant that enabled auth without identity providers. - Return the tenant's device token when a device approval is pending; without it the desktop cannot continue on the tenant's approve_device path. - Answer NOT_DATABASE_OWNER for both a missing database and someone else's, as the comment already claimed: a distinct NOT_FOUND let a caller probe database ids. --- .../src/plugins/owner-handoff-plugin.ts | 28 ++++++++++--------- 1 file changed, 15 insertions(+), 13 deletions(-) diff --git a/graphql/server/src/plugins/owner-handoff-plugin.ts b/graphql/server/src/plugins/owner-handoff-plugin.ts index d6ae810e20..c6c7509406 100644 --- a/graphql/server/src/plugins/owner-handoff-plugin.ts +++ b/graphql/server/src/plugins/owner-handoff-plugin.ts @@ -56,6 +56,7 @@ export interface OwnerHandoffResult { mfaSetupRequired: boolean; deviceApprovalRequired: boolean; mfaChallengeToken: string | null; + deviceToken: string | null; } const isUuid = (value: unknown): value is string => @@ -71,15 +72,10 @@ function fail(code: string, message: string): never { throw error; } +// The auth module's own row names the private schema, so this works for a +// tenant that enabled auth but no identity provider — `identity_providers_module` +// is optional in a few presets, `user_auth_module` is not. const authPrivateSchemaSql = ` - SELECT auth_private.schema_name - FROM metaschema_modules_public.identity_providers_module providers - JOIN metaschema_public.schema auth_private ON auth_private.id = providers.private_schema_id - WHERE providers.database_id = $1 - LIMIT 1 -`; - -const platformEvidenceSchemaSql = ` SELECT auth_private.schema_name FROM metaschema_modules_public.user_auth_module uam JOIN metaschema_public.schema auth_private ON auth_private.id = uam.private_schema_id @@ -104,18 +100,19 @@ export const mintTenantOwnerHandoff = async ( } // Ownership is the platform's own row, not a client claim. A missing row and - // someone else's row answer the same way: the caller may not learn which + // someone else's row answer the same way, so the caller cannot probe which // database ids exist. const database = await tx.query({ text: 'SELECT owner_id::text AS owner_id FROM metaschema_public.database WHERE id = $1', values: [input.databaseId] }); const ownerId = database.rows[0]?.owner_id; - if (typeof ownerId !== 'string') fail('DATABASE_NOT_FOUND', 'no such database'); - if (ownerId !== input.userId) fail('NOT_DATABASE_OWNER', 'only the database owner may hand off a session'); + if (ownerId !== input.userId) { + fail('NOT_DATABASE_OWNER', 'only the database owner may hand off a session'); + } const evidenceSchema = await tx.query({ - text: platformEvidenceSchemaSql, + text: authPrivateSchemaSql, values: [input.platformDatabaseId] }); const evidenceSchemaName = evidenceSchema.rows[0]?.schema_name; @@ -177,7 +174,10 @@ export const mintTenantOwnerHandoff = async ( mfaRequired: row.mfa_required === true, mfaSetupRequired: row.mfa_setup_required === true, deviceApprovalRequired: row.device_approval_required === true, - mfaChallengeToken: typeof row.mfa_challenge_token === 'string' ? row.mfa_challenge_token : null + mfaChallengeToken: typeof row.mfa_challenge_token === 'string' ? row.mfa_challenge_token : null, + // Pending device approval finishes on the tenant's existing approve_device + // path, which needs this token; without it the desktop cannot continue. + deviceToken: typeof row.out_device_token === 'string' ? row.out_device_token : null }; // A challenged owner finishes on the tenant's existing MFA/device path; no @@ -247,6 +247,8 @@ export const OwnerHandoffPlugin: GraphileConfig.Plugin = { deviceApprovalRequired: Boolean! """Token for the tenant's completeMfaChallenge path.""" mfaChallengeToken: String + """Device token for the tenant's device-approval path.""" + deviceToken: String } extend type Mutation { From 1fa4f151d4ba8c8a707a5519146000127d94520e Mon Sep 17 00:00:00 2001 From: Gefei Hou Date: Sat, 14 Nov 2026 19:57:22 -0800 Subject: [PATCH 3/6] refactor(server): drop the unused tokenId input from the owner hand-off --- graphql/server/src/plugins/owner-handoff-plugin.ts | 4 ---- 1 file changed, 4 deletions(-) diff --git a/graphql/server/src/plugins/owner-handoff-plugin.ts b/graphql/server/src/plugins/owner-handoff-plugin.ts index c6c7509406..c985a98f51 100644 --- a/graphql/server/src/plugins/owner-handoff-plugin.ts +++ b/graphql/server/src/plugins/owner-handoff-plugin.ts @@ -39,8 +39,6 @@ type WithPgClient = ( export interface OwnerHandoffInput { /** The signed-in platform user (jwt.claims.user_id). */ userId: string; - /** The credential this request presented (jwt.claims.token_id). */ - tokenId: string | null; /** The platform database serving the request (where evidence lives). */ platformDatabaseId: string; /** The tenant database to sign the owner into. */ @@ -264,7 +262,6 @@ export const OwnerHandoffPlugin: GraphileConfig.Plugin = { mintTenantOwnerHandoff(_$mutation: any, fieldArgs: any) { return lambda(resolveArgs(fieldArgs), async ({ input, withPgClient, pgSettings }: ResolvedArgs) => { const userId = pgSettings?.['jwt.claims.user_id']; - const tokenId = pgSettings?.['jwt.claims.token_id'] ?? null; const platformDatabaseId = pgSettings?.['jwt.claims.database_id']; if (!userId) fail('UNAUTHENTICATED', 'a platform session is required'); @@ -277,7 +274,6 @@ export const OwnerHandoffPlugin: GraphileConfig.Plugin = { return withPgClient(pgSettings, (tx) => mintTenantOwnerHandoff(tx, { userId, - tokenId, platformDatabaseId: String(platformDatabaseId ?? ''), databaseId, codeChallenge From 16f768a8f146ad4c5f6389ac7299169dcb22d74e Mon Sep 17 00:00:00 2001 From: Gefei Hou Date: Sat, 14 Nov 2026 20:06:48 -0800 Subject: [PATCH 4/6] ci: run the checks on the merged head From 3b7f354acd53c8b476c3ba2a1c5f91e451418d1a Mon Sep 17 00:00:00 2001 From: Gefei Hou Date: Sun, 15 Nov 2026 02:53:02 -0800 Subject: [PATCH 5/6] fix(graphql): resolve the platform auth schema on the server lane MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The owner hand-off read `metaschema_modules_public.user_auth_module` for the platform database as the request role (`authenticated`). That row is owned by the platform actor, not the caller's org, so RLS hid it and every mutation answered `TENANT_AUTH_NOT_PROVISIONED`. Read it through `function_resolution.user_auth_module_registrations` — a SECURITY DEFINER reader granted to the serving login — on the connection's own lane, the same lane the module loaders use. The tenant lookup stays on the request lane, where the caller's org membership makes it visible. Bind the evidence to the platform session rather than the credential that wrote it: `exchange_native_handoff` and `refresh_access_token` rotate the credential in place, so the id the desktop presents is never the one `sign_in_identity` wrote. The session id survives the rotation and still names exactly one sign-in. --- .../src/plugins/owner-handoff-plugin.ts | 83 ++++++++++++++++--- 1 file changed, 70 insertions(+), 13 deletions(-) diff --git a/graphql/server/src/plugins/owner-handoff-plugin.ts b/graphql/server/src/plugins/owner-handoff-plugin.ts index c985a98f51..918302ff42 100644 --- a/graphql/server/src/plugins/owner-handoff-plugin.ts +++ b/graphql/server/src/plugins/owner-handoff-plugin.ts @@ -16,8 +16,10 @@ import { extendSchema, gql } from 'graphile-utils'; * into the owner's tenant session: * * 1. the caller must own the target database (never a client-supplied id); - * 2. the evidence row must belong to this caller and to the credential this - * request presented (`jwt.claims.token_id`), and be unexpired/unconsumed; + * 2. the evidence row must belong to this caller and to the platform session + * this request belongs to (`jwt.claims.session_id`), and be + * unexpired/unconsumed — the browser hand-off rotates the credential, so + * the session is what survives to bind the proof; * 3. the tenant's own `sign_in_platform_identity` resolves the owner from the * identifier and applies the tenant's MFA / device policy; * 4. the tenant mints a one-time, PKCE-bound hand-off code that the desktop @@ -39,8 +41,11 @@ type WithPgClient = ( export interface OwnerHandoffInput { /** The signed-in platform user (jwt.claims.user_id). */ userId: string; - /** The platform database serving the request (where evidence lives). */ - platformDatabaseId: string; + /** + * The platform realm's private auth schema (where `sign_in_evidence` lives), + * resolved by the wiring on the server lane — see `platformAuthSchemaSql`. + */ + platformAuthSchema: string; /** The tenant database to sign the owner into. */ databaseId: string; /** S256 challenge the desktop will present at the exchange. */ @@ -72,7 +77,8 @@ function fail(code: string, message: string): never { // The auth module's own row names the private schema, so this works for a // tenant that enabled auth but no identity provider — `identity_providers_module` -// is optional in a few presets, `user_auth_module` is not. +// is optional in a few presets, `user_auth_module` is not. Only the tenant row +// is read here: it belongs to the caller's org, so the request role sees it. const authPrivateSchemaSql = ` SELECT auth_private.schema_name FROM metaschema_modules_public.user_auth_module uam @@ -81,6 +87,18 @@ const authPrivateSchemaSql = ` LIMIT 1 `; +// The platform realm's row is owned by the platform actor, not by the caller's +// org, so RLS hides it from the request role — and `metaschema_modules_public` +// hides it from table reads by the serving login too (NOBYPASSRLS). The +// platform login is granted EXECUTE on this SECURITY DEFINER reader instead +// (constructive-db `function_resolution`), the same reader the module loaders +// use; it projects the schema name and nothing else. +const platformAuthSchemaSql = ` + SELECT private_schema AS schema_name + FROM function_resolution.user_auth_module_registrations($1::uuid) + LIMIT 1 +`; + /** * The SQL half, kept separate from the GraphQL wiring so it can be exercised * against a real database. Runs as the request role, with the request's claims @@ -109,17 +127,21 @@ export const mintTenantOwnerHandoff = async ( fail('NOT_DATABASE_OWNER', 'only the database owner may hand off a session'); } - const evidenceSchema = await tx.query({ - text: authPrivateSchemaSql, - values: [input.platformDatabaseId] - }); - const evidenceSchemaName = evidenceSchema.rows[0]?.schema_name; - if (typeof evidenceSchemaName !== 'string') { + // Resolved on the server lane before this transaction: the request role + // cannot see the platform realm's module row (see `platformAuthSchemaSql`). + const evidenceSchemaName = input.platformAuthSchema; + if (typeof evidenceSchemaName !== 'string' || !evidenceSchemaName) { fail('TENANT_AUTH_NOT_PROVISIONED', 'the platform realm has no auth module'); } // Consume and read in one statement: the subselect locks the row, and the // outer UPDATE stamps it, so two concurrent calls cannot both spend it. + // + // The proof is bound to the *session*, not the credential that wrote it: the + // browser hand-off rotates that credential in place (`exchange_native_handoff` + // and `refresh_access_token` each mint a new id for the same session), so the + // credential id the desktop presents is never the one the sign-in wrote. The + // session id survives the rotation and still names exactly one sign-in. const evidenceTable = QuoteUtils.quoteQualifiedIdentifier(evidenceSchemaName, 'sign_in_evidence'); const evidence = await tx.query({ text: ` @@ -129,7 +151,7 @@ export const mintTenantOwnerHandoff = async ( SELECT candidate.id FROM ${evidenceTable} AS candidate WHERE candidate.user_id = $1 - AND candidate.credential_id = jwt_private.current_token_id() + AND candidate.session_id = jwt_private.current_session_id() AND candidate.consumed_at IS NULL AND candidate.expires_at > now() ORDER BY candidate.auth_time DESC @@ -217,6 +239,24 @@ const resolveArgs = (fieldArgs: any): Step => pgSettings: grafastContext().get('pgSettings') }) as unknown as Step; +/** + * The connection's own login, no request role. It is the only lane that holds + * EXECUTE on the privileged module readers (the webauthn plugin uses the same + * lane for the same reason), so a request role can never widen it. + */ +const resolvePlatformAuthSchema = async ( + withPgClient: WithPgClient, + platformDatabaseId: string +): Promise => + withPgClient(null, async (client) => { + const { rows } = await client.query({ + text: platformAuthSchemaSql, + values: [platformDatabaseId] + }); + const name = rows[0]?.schema_name; + return typeof name === 'string' && name ? name : undefined; + }); + /** * Platform-only: a tenant must never author a session for another tenant, so * this plugin is registered only on the platform database's own APIs. @@ -264,6 +304,11 @@ export const OwnerHandoffPlugin: GraphileConfig.Plugin = { const userId = pgSettings?.['jwt.claims.user_id']; const platformDatabaseId = pgSettings?.['jwt.claims.database_id']; if (!userId) fail('UNAUTHENTICATED', 'a platform session is required'); + // The API resolved this request's database id; without it there is + // no platform realm to read and no evidence to consume. + if (!isUuid(platformDatabaseId)) { + fail('UNAUTHENTICATED', 'a platform session is required'); + } const databaseId = input?.databaseId; const codeChallenge = input?.codeChallenge; @@ -271,10 +316,22 @@ export const OwnerHandoffPlugin: GraphileConfig.Plugin = { fail('BAD_REQUEST', 'databaseId and codeChallenge are required'); } + // The platform realm's auth schema is registry knowledge, hidden + // from the request role; resolve it on the server lane, then run + // every caller-scoped read and the tenant procedures on the request + // lane. + const platformAuthSchema = await resolvePlatformAuthSchema( + withPgClient, + platformDatabaseId + ); + if (!platformAuthSchema) { + fail('TENANT_AUTH_NOT_PROVISIONED', 'the platform realm has no auth module'); + } + return withPgClient(pgSettings, (tx) => mintTenantOwnerHandoff(tx, { userId, - platformDatabaseId: String(platformDatabaseId ?? ''), + platformAuthSchema, databaseId, codeChallenge }) From 0836d0f16dcc9619fee55cf1a0557336593079d2 Mon Sep 17 00:00:00 2001 From: Gefei Hou Date: Mon, 16 Nov 2026 20:37:44 -0800 Subject: [PATCH 6/6] fix(server): surface owner hand-off refusals and spend evidence by delete The passwordless owner hand-off returned every expected refusal as INTERNAL_SERVER_ERROR, could return another tenant user's challenge before checking the owner, created a new unapproved device on every retry, and kept consumed evidence rows forever. - fail() carries extensions.code, so the refusal codes reach clients and the formatter classifies them instead of logging them as internal errors. The hand-off codes are registered; the platform realm and tenant realm get distinct not-provisioned codes. - OWNER_MISMATCH runs before the MFA and device early returns, so a challenge for a different tenant user is refused before its tokens are exposed. - deviceToken is an input and reaches sign_in_platform_identity as its fifth argument, so a retry after approval reuses the approved device. - Evidence is consumed with DELETE ... RETURNING. The proof is one-time without a row lock, which keeps the table free of UPDATE grants. - A pg_namespace preflight names the co-location assumption and refuses a tenant schema the server does not serve. --- .../__tests__/owner-handoff-plugin.test.ts | 194 ++++++++++++++++++ .../src/plugins/owner-handoff-plugin.ts | 81 +++++--- packages/errors/src/registry.ts | 39 ++++ 3 files changed, 284 insertions(+), 30 deletions(-) create mode 100644 graphql/server/src/plugins/__tests__/owner-handoff-plugin.test.ts diff --git a/graphql/server/src/plugins/__tests__/owner-handoff-plugin.test.ts b/graphql/server/src/plugins/__tests__/owner-handoff-plugin.test.ts new file mode 100644 index 0000000000..fb5e85eeb8 --- /dev/null +++ b/graphql/server/src/plugins/__tests__/owner-handoff-plugin.test.ts @@ -0,0 +1,194 @@ +import { GraphQLError } from 'graphql'; + +import { formatError } from '../../middleware/format-error'; +import { mintTenantOwnerHandoff, type OwnerHandoffInput } from '../owner-handoff-plugin'; + +const userId = '0192f0c4-1d2e-7c3a-9b4d-5e6f7a8b9c0d'; +const otherUserId = '0192f0c4-1d2e-7c3a-9b4d-5e6f7a8b9c0e'; +const databaseId = '0192f0c4-1d2e-7c3a-9b4d-5e6f7a8b9c0f'; +const codeChallenge = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQ'; + +type Statement = { text: string; values?: unknown[] }; +type Response = { rows: Array> }; + +const input = (overrides: Partial = {}): OwnerHandoffInput => ({ + userId, + platformAuthSchema: 'platform_auth_private', + databaseId, + codeChallenge, + ...overrides +}); + +const ownerRow = { rows: [{ owner_id: userId }] }; +const evidenceRow = { + rows: [{ method: 'email', identifier: 'owner@example.com', user_id: userId }] +}; +const tenantAuthSchemaRow = { rows: [{ schema_name: 'constructive_auth_private' }] }; +const servedSchemaRow = { rows: [{ '?column?': 1 }] }; +const handoffCodeRow = { rows: [{ code: 'handoff-code' }] }; + +const signedInRow = (overrides: Record = {}): Response => ({ + rows: [ + { + user_id: userId, + access_token: 'cnc_live_bt_test', + mfa_required: false, + mfa_setup_required: false, + device_approval_required: false, + mfa_challenge_token: null, + out_device_token: null, + ...overrides + } + ] +}); + +const fakeClient = (...responses: Response[]) => { + const statements: Statement[] = []; + return { + statements, + query: async (statement: Statement) => { + statements.push(statement); + const response = responses.shift(); + if (!response) throw new Error(`unexpected query: ${statement.text}`); + return response; + } + }; +}; + +const findStatement = (statements: Statement[], fragment: string): Statement => { + const statement = statements.find((candidate) => candidate.text.includes(fragment)); + if (!statement) throw new Error(`no statement containing ${fragment}`); + return statement; +}; + +const expectNoStatement = (statements: Statement[], fragment: string): void => { + expect(statements.some((statement) => statement.text.includes(fragment))).toBe(false); +}; + +describe('mintTenantOwnerHandoff', () => { + it('deletes the evidence row selected for this session instead of marking it consumed', async () => { + const client = fakeClient( + ownerRow, + evidenceRow, + tenantAuthSchemaRow, + servedSchemaRow, + signedInRow(), + handoffCodeRow + ); + + const result = await mintTenantOwnerHandoff(client, input()); + + expect(result.code).toBe('handoff-code'); + const spend = findStatement(client.statements, 'sign_in_evidence'); + expect(spend.text).toContain('DELETE FROM platform_auth_private.sign_in_evidence AS evidence'); + expect(spend.text).toContain('candidate.session_id = jwt_private.current_session_id()'); + expect(spend.text).not.toContain('credential_id'); + expect(spend.text).not.toContain('consumed_at'); + expect(spend.values).toEqual([userId]); + }); + + it('reports a missing proof as STEP_UP_REQUIRED that reaches the client extensions.code', async () => { + const client = fakeClient(ownerRow, { rows: [] }); + + const refusal = await mintTenantOwnerHandoff(client, input()).then( + () => { + throw new Error('expected the hand-off to refuse'); + }, + (error: Error & { extensions?: Record }) => error + ); + + expect(refusal).toMatchObject({ extensions: { code: 'STEP_UP_REQUIRED' } }); + const formatted = formatError( + new GraphQLError(refusal.message, { + path: ['mintTenantOwnerHandoff'], + originalError: refusal + }) + ); + expect(formatted.extensions?.code).toBe('STEP_UP_REQUIRED'); + }); + + it('refuses an MFA challenge minted for another tenant user', async () => { + const client = fakeClient( + ownerRow, + evidenceRow, + tenantAuthSchemaRow, + servedSchemaRow, + signedInRow({ + user_id: otherUserId, + mfa_required: true, + mfa_challenge_token: 'challenge-for-another-user', + out_device_token: 'device-for-another-user' + }) + ); + + await expect(mintTenantOwnerHandoff(client, input())).rejects.toMatchObject({ + extensions: { code: 'OWNER_MISMATCH' } + }); + expectNoStatement(client.statements, 'mint_native_handoff'); + }); + + it('returns a pending challenge to the caller it belongs to', async () => { + const client = fakeClient( + ownerRow, + evidenceRow, + tenantAuthSchemaRow, + servedSchemaRow, + signedInRow({ + mfa_required: true, + mfa_challenge_token: 'challenge', + out_device_token: 'device-token' + }) + ); + + const result = await mintTenantOwnerHandoff(client, input()); + + expect(result).toMatchObject({ + code: null, + userId, + mfaRequired: true, + mfaChallengeToken: 'challenge', + deviceToken: 'device-token' + }); + expectNoStatement(client.statements, 'mint_native_handoff'); + }); + + it('passes the device token to the tenant procedure so an approved device is reused', async () => { + const withToken = fakeClient( + ownerRow, + evidenceRow, + tenantAuthSchemaRow, + servedSchemaRow, + signedInRow(), + handoffCodeRow + ); + await mintTenantOwnerHandoff(withToken, input({ deviceToken: 'approved-device-token' })); + + const signIn = findStatement(withToken.statements, 'sign_in_platform_identity'); + expect(signIn.text).toBe( + 'SELECT * FROM constructive_auth_private.sign_in_platform_identity($1, $2, \'bearer\', false, $3)' + ); + expect(signIn.values).toEqual(['email', 'owner@example.com', 'approved-device-token']); + + const withoutToken = fakeClient( + ownerRow, + evidenceRow, + tenantAuthSchemaRow, + servedSchemaRow, + signedInRow(), + handoffCodeRow + ); + await mintTenantOwnerHandoff(withoutToken, input()); + + const signInWithoutToken = findStatement(withoutToken.statements, 'sign_in_platform_identity'); + expect(signInWithoutToken.values).toEqual(['email', 'owner@example.com', null]); + }); + + it('refuses a tenant auth schema that is not in this server database', async () => { + const client = fakeClient(ownerRow, evidenceRow, tenantAuthSchemaRow, { rows: [] }); + + await expect(mintTenantOwnerHandoff(client, input())).rejects.toMatchObject({ + extensions: { code: 'TENANT_AUTH_NOT_IN_SERVED_DATABASE' } + }); + expectNoStatement(client.statements, 'sign_in_platform_identity'); + }); +}); diff --git a/graphql/server/src/plugins/owner-handoff-plugin.ts b/graphql/server/src/plugins/owner-handoff-plugin.ts index 918302ff42..a9fa440b61 100644 --- a/graphql/server/src/plugins/owner-handoff-plugin.ts +++ b/graphql/server/src/plugins/owner-handoff-plugin.ts @@ -12,21 +12,20 @@ import { extendSchema, gql } from 'graphile-utils'; * code has no password, so it cannot satisfy the tenant's `sign_in`. The * platform realm's sign-in procedures already recorded what that sign-in * proved in `sign_in_evidence` (method + a proven identifier, bound to the - * session and the credential it minted). This mutation turns that evidence - * into the owner's tenant session: + * session). This mutation turns that evidence into the owner's tenant session: * * 1. the caller must own the target database (never a client-supplied id); * 2. the evidence row must belong to this caller and to the platform session - * this request belongs to (`jwt.claims.session_id`), and be - * unexpired/unconsumed — the browser hand-off rotates the credential, so - * the session is what survives to bind the proof; + * this request belongs to (`jwt.claims.session_id`), and be unexpired. The + * browser hand-off rotates the credential, so the session is what survives + * to bind the proof; * 3. the tenant's own `sign_in_platform_identity` resolves the owner from the * identifier and applies the tenant's MFA / device policy; * 4. the tenant mints a one-time, PKCE-bound hand-off code that the desktop * exchanges for the session. * - * The row is consumed by the same statement that reads it, so a retry after a - * crash cannot replay a proof. + * The statement that reads the proof also deletes it, so a retry after a crash + * cannot replay it. */ interface PgClient { @@ -50,6 +49,8 @@ export interface OwnerHandoffInput { databaseId: string; /** S256 challenge the desktop will present at the exchange. */ codeChallenge: string; + /** Token for a device awaiting approval, so a retry finds the approved row. */ + deviceToken?: string; } export interface OwnerHandoffResult { @@ -70,8 +71,10 @@ const isUuid = (value: unknown): value is string => const S256_CHALLENGE = /^[-_A-Za-z0-9]{43}$/; function fail(code: string, message: string): never { - const error = new Error(`${code}: ${message}`) as Error & { code: string }; - error.code = code; + // `extensions.code` is what formatError lifts onto the response; without it + // the refusal reads as INTERNAL_SERVER_ERROR. + const error = new Error(`${code}: ${message}`) as Error & { extensions?: Record }; + error.extensions = { code }; throw error; } @@ -131,32 +134,27 @@ export const mintTenantOwnerHandoff = async ( // cannot see the platform realm's module row (see `platformAuthSchemaSql`). const evidenceSchemaName = input.platformAuthSchema; if (typeof evidenceSchemaName !== 'string' || !evidenceSchemaName) { - fail('TENANT_AUTH_NOT_PROVISIONED', 'the platform realm has no auth module'); + fail('PLATFORM_AUTH_NOT_PROVISIONED', 'the platform realm has no auth module'); } - // Consume and read in one statement: the subselect locks the row, and the - // outer UPDATE stamps it, so two concurrent calls cannot both spend it. - // - // The proof is bound to the *session*, not the credential that wrote it: the - // browser hand-off rotates that credential in place (`exchange_native_handoff` - // and `refresh_access_token` each mint a new id for the same session), so the - // credential id the desktop presents is never the one the sign-in wrote. The - // session id survives the rotation and still names exactly one sign-in. + // Delete-on-consume: one DELETE spends the newest proof for this session, so + // a retry deletes nothing and is refused. No row lock is taken; it would + // require an UPDATE grant that this table deliberately does not have. The + // row is bound to the session, not the credential that recorded it, because + // the browser hand-off rotates that credential in place and only the session + // id survives. const evidenceTable = QuoteUtils.quoteQualifiedIdentifier(evidenceSchemaName, 'sign_in_evidence'); const evidence = await tx.query({ text: ` - UPDATE ${evidenceTable} AS evidence - SET consumed_at = now() + DELETE FROM ${evidenceTable} AS evidence WHERE evidence.id = ( SELECT candidate.id FROM ${evidenceTable} AS candidate WHERE candidate.user_id = $1 AND candidate.session_id = jwt_private.current_session_id() - AND candidate.consumed_at IS NULL AND candidate.expires_at > now() ORDER BY candidate.auth_time DESC LIMIT 1 - FOR UPDATE SKIP LOCKED ) RETURNING evidence.method, evidence.identifier, evidence.user_id::text AS user_id `, @@ -180,10 +178,26 @@ export const mintTenantOwnerHandoff = async ( fail('TENANT_AUTH_NOT_PROVISIONED', 'the target database has no auth module'); } + // Co-location assumption: the evidence read and the tenant session share one + // transaction, so the tenant auth schema has to live in this server's + // database. A tenant on its own physical database would otherwise fail with + // 42883 deep inside the procedure call. + const served = await tx.query({ + text: 'SELECT 1 FROM pg_namespace WHERE nspname = $1', + values: [tenantAuthSchema] + }); + if (served.rows.length === 0) { + fail('TENANT_AUTH_NOT_IN_SERVED_DATABASE', 'the tenant auth schema is not in this server\'s database'); + } + const signIn = QuoteUtils.quoteQualifiedIdentifier(tenantAuthSchema, 'sign_in_platform_identity'); + // The tenant procedure defaults credential_kind to 'bearer' and remember_me to + // false. Both are spelled out only to reach the device token in fifth place: + // a retry after the user approves the device must find the approved row + // instead of minting a new device. const session = await tx.query({ - text: `SELECT * FROM ${signIn}($1, $2)`, - values: [proven.method, proven.identifier] + text: `SELECT * FROM ${signIn}($1, $2, 'bearer', false, $3)`, + values: [proven.method, proven.identifier, input.deviceToken ?? null] }); const row = session.rows[0]; if (!row) fail('TENANT_SIGN_IN_FAILED', 'sign_in_platform_identity returned no row'); @@ -200,13 +214,16 @@ export const mintTenantOwnerHandoff = async ( deviceToken: typeof row.out_device_token === 'string' ? row.out_device_token : null }; - // A challenged owner finishes on the tenant's existing MFA/device path; no - // hand-off code exists until the session does. - if (result.mfaRequired || result.deviceApprovalRequired) return result; + // The check runs before the challenge early return: a challenge minted for + // another tenant user must not hand back that user's tokens. if (result.userId !== input.userId) { fail('OWNER_MISMATCH', 'the tenant session belongs to a different user'); } + // A challenged owner finishes on the tenant's existing MFA/device path; no + // hand-off code exists until the session does. + if (result.mfaRequired || result.deviceApprovalRequired) return result; + const accessToken = row.access_token; if (typeof accessToken !== 'string' || !accessToken) { fail('TENANT_SIGN_IN_FAILED', 'sign_in_platform_identity minted no access token'); @@ -227,7 +244,7 @@ export const mintTenantOwnerHandoff = async ( }; interface ResolvedArgs { - input: { databaseId?: unknown; codeChallenge?: unknown } | null; + input: { databaseId?: unknown; codeChallenge?: unknown; deviceToken?: unknown } | null; withPgClient: WithPgClient; pgSettings: Record | null; } @@ -270,6 +287,8 @@ export const OwnerHandoffPlugin: GraphileConfig.Plugin = { databaseId: UUID! """S256 PKCE challenge the desktop will present at the exchange.""" codeChallenge: String! + """Device token from a pending-approval result, so the retry finds the approved device.""" + deviceToken: String } type MintTenantOwnerHandoffPayload { @@ -312,6 +331,7 @@ export const OwnerHandoffPlugin: GraphileConfig.Plugin = { const databaseId = input?.databaseId; const codeChallenge = input?.codeChallenge; + const deviceToken = input?.deviceToken; if (typeof databaseId !== 'string' || typeof codeChallenge !== 'string') { fail('BAD_REQUEST', 'databaseId and codeChallenge are required'); } @@ -325,7 +345,7 @@ export const OwnerHandoffPlugin: GraphileConfig.Plugin = { platformDatabaseId ); if (!platformAuthSchema) { - fail('TENANT_AUTH_NOT_PROVISIONED', 'the platform realm has no auth module'); + fail('PLATFORM_AUTH_NOT_PROVISIONED', 'the platform realm has no auth module'); } return withPgClient(pgSettings, (tx) => @@ -333,7 +353,8 @@ export const OwnerHandoffPlugin: GraphileConfig.Plugin = { userId, platformAuthSchema, databaseId, - codeChallenge + codeChallenge, + deviceToken: typeof deviceToken === 'string' && deviceToken ? deviceToken : undefined }) ); }); diff --git a/packages/errors/src/registry.ts b/packages/errors/src/registry.ts index 1beeb24bea..7397136752 100644 --- a/packages/errors/src/registry.ts +++ b/packages/errors/src/registry.ts @@ -375,6 +375,45 @@ export const registry = { http: 403, message: 'Additional verification is required to continue.' }), + // Passwordless owner hand-off (planning#2511). These are expected refusals + // from the platform mutation, not internal errors. + NOT_DATABASE_OWNER: defineError({ + code: 'NOT_DATABASE_OWNER', + class: 'public', + http: 403, + message: 'Only the owner of this database can sign in to its app session.' + }), + OWNER_MISMATCH: defineError({ + code: 'OWNER_MISMATCH', + class: 'public', + http: 403, + message: 'The identity the platform proved does not belong to this account.' + }), + TENANT_AUTH_NOT_PROVISIONED: defineError({ + code: 'TENANT_AUTH_NOT_PROVISIONED', + class: 'public', + http: 409, + message: 'This app database has no sign-in module yet.' + }), + TENANT_SIGN_IN_FAILED: defineError({ + code: 'TENANT_SIGN_IN_FAILED', + class: 'public', + http: 400, + message: 'The app database could not sign in this account. Try again.' + }), + PLATFORM_AUTH_NOT_PROVISIONED: defineError({ + code: 'PLATFORM_AUTH_NOT_PROVISIONED', + class: 'internal', + http: 503, + message: 'The platform auth realm is not provisioned.' + }), + TENANT_AUTH_NOT_IN_SERVED_DATABASE: defineError({ + code: 'TENANT_AUTH_NOT_IN_SERVED_DATABASE', + class: 'internal', + http: 503, + message: + 'The app database is not served by this server. The deployment must serve both from the same Postgres instance.' + }), MFA_REQUIRED: defineError({ code: 'MFA_REQUIRED', class: 'public',