Skip to content

feat(server): mintTenantOwnerHandoff for passwordless owner builds (planning#2511) - #1997

Open
NorOldBurden wants to merge 7 commits into
mainfrom
feat/2511-owner-handoff
Open

NorOldBurden wants to merge 7 commits into
mainfrom
feat/2511-owner-handoff

Conversation

@NorOldBurden

@NorOldBurden NorOldBurden commented Nov 14, 2026 •

Copy link
Copy Markdown
Contributor

Implements the platform half of constructive-io/constructive-planning#2511, stacked on constructive-io/constructive-db#4356. Merge #4356 first, and regenerate the tenant auth module in the same step; this mutation calls the procedure it adds.

Rules touched: R12, R13

Why

A platform account that signed in with Google, an emailed link or a phone code has no password, so the build's tenant sign-in, which only accepts sign_in(email, password), cannot run. The tenant owner already exists with the platform user's UUID. What was missing is a way to turn the platform session's proof into a tenant session.

Flow

desktop (platform session, Google/email/phone)
  │  mintTenantOwnerHandoff(databaseId, codeChallenge, deviceToken?)
  ▼
platform mutation (this PR)                          tenant realm
  ├─ database.owner_id = jwt.claims.user_id?  ─────── no → NOT_DATABASE_OWNER
  ├─ DELETE the caller's unexpired sign_in_evidence row
  │     bound to jwt.claims.session_id               none → STEP_UP_REQUIRED
  ├─ resolve the platform auth schema through
  │     function_resolution.user_auth_module_registrations (login lane)
  ├─ resolve the tenant's auth private schema
  ├─ pg_namespace preflight for that schema          missing → TENANT_AUTH_NOT_IN_SERVED_DATABASE
  ├─ sign_in_platform_identity(method, identifier,
  │     'bearer', false, device_token) ─────────────► owner, MFA/require_mfa/device
  ├─ userId != caller?                               yes → OWNER_MISMATCH
  ├─ mfa/device pending? → return the challenge, no code
  └─ mint_native_handoff(token, NULL, challenge, true) → one-time code
  ▼
desktop: exchange_native_handoff(code, verifier, 'refresh_token') → session

Protections

  • Ownership is catalog state, metaschema_public.database.owner_id, never a client-supplied id.
  • The proof is bound to the session, not the credential. The browser hand-off rotates the credential in place on exchange and refresh, so current_session_id() survives where current_token_id() would not.
  • The consume is one DELETE. There is no consumed_at column and no UPDATE grant; a caller cannot rewrite the identifier it proved, and a retry finds no row.
  • The evidence read is scoped by an explicit user_id filter and the owner RLS policy.
  • The tenant's MFA, require_mfa and device policy run inside the tenant procedure. The returned user id is checked before any challenge or code leaves the mutation.
  • The plugin is registered only when the preset is built for the platform database. A tenant API never gets the field.
  • The platform auth schema resolves through function_resolution.user_auth_module_registrations on the connection-login lane. Missing platform claim → UNAUTHENTICATED, no row → PLATFORM_AUTH_NOT_PROVISIONED.

Fixes in this round

  • fail() sets extensions.code, so STEP_UP_REQUIRED, NOT_DATABASE_OWNER, TENANT_AUTH_NOT_PROVISIONED, TENANT_SIGN_IN_FAILED, OWNER_MISMATCH and TENANT_AUTH_NOT_IN_SERVED_DATABASE reach clients as codes instead of INTERNAL_SERVER_ERROR. The hand-off codes are registered in packages/errors; the public ones no longer log at error level or carry an errorId.
  • The owner check runs before the MFA and device early returns, so a challenge minted for another tenant user is refused before its userId, mfaChallengeToken or deviceToken is returned.
  • deviceToken is an input and reaches sign_in_platform_identity as its fifth argument, so a retry after the user approves the device finds the approved row instead of minting a new one.
  • Evidence is spent with DELETE ... RETURNING; the row lock is gone because it would require an UPDATE grant the evidence table deliberately does not have.
  • The pg_namespace preflight turns a tenant schema this server does not serve into TENANT_AUTH_NOT_IN_SERVED_DATABASE instead of a raw 42883.

Verification

  • owner-handoff-plugin.test.ts: 6/6. The cases assert the DELETE filters session_id = jwt_private.current_session_id(), the refusal reaches extensions.code through the real formatter, another user's MFA challenge is refused, the caller's challenge is returned with its tokens, the device token reaches the fifth argument, and a schema outside the served database is refused. Red first: with only the new input added, all six failed.
  • packages/errors: 45/45, including registry-sync.
  • npx tsc --noEmit -p graphql/server: 10 pre-existing errors in files this PR does not touch; none in the changed files. The plugin folder is excluded from that project, so a focused check of the plugin and test was also run; it shows only the two pre-existing grafastContext().get errors that the same file has at the base commit.
  • eslint on the plugin, the new test and the registry: 0 errors.
  • The DELETE statement was exercised on local PostgreSQL 18 in a rolled-back transaction: it spends the newest unexpired row for the caller's session, leaves the other session and the expired row, and a replay returns none.
  • CI on 0836d0f16: all 19 checks pass.
  • No end-to-end GraphQL mutation against provisioned platform and tenant databases, and no live test of the delete grant or the login-lane resolver. Those need #4356 deployed and the tenant module regenerated.

Limits

  • One GraphQL server serves one configured Postgres database today, so the tenant procedure must be in that database. A managed physical database for a tenant is refused with TENANT_AUTH_NOT_IN_SERVED_DATABASE; split placement stays out of scope.
  • An org-owned database stores the organization UUID in owner_id, so the hand-off answers NOT_DATABASE_OWNER. The desktop provisions personal databases today. Recorded in constructive-io/constructive-planning#2538.
  • A device approval returned by completeMfaChallenge still has no platform device token to retry with, so that path stays a hard error.

Related

  • constructive-io/constructive-db#4356: the tenant half and the evidence table.
  • constructive-io/constructive-desktop#285: the desktop call site.
  • constructive-io/constructive-planning#2511 and #2512: the issues.
  • constructive-io/constructive-planning#2538: the org-owned database follow-up.

…lanning#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).
- 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.
@NorOldBurden
NorOldBurden marked this pull request as ready for review November 15, 2026 04:05
@luxor-code-review

luxor-code-review Bot commented Nov 15, 2026 •

Copy link
Copy Markdown

Review complete. 🟠 1 high

💬 Inline comments (1)

🧹 Nitpicks (1) — 🟢 1 low
  • 🟢 Empty-string userId can violate the UUID scalar (owner-handoff-plugin.ts:171) — The result coerces a missing tenant user_id to an empty string with String(row.user_id ?? '') (graphql/server/src/plugins/owner-handoff-plugin.ts:171), and the MFA/device-challenge path returns that payload immediately before any user-id check.

This PR wires a new OwnerHandoffPlugin into the platform GraphQL preset: it extends the schema with an ownerHandOff mutation that validates a code challenge, consumes step-up evidence row under a transactional lock, and calls the tenant auth extension to sign in the platform identity and mint a native hand-off token. The plugin is registered only when the platform flag is set in buildPreset, mirroring the existing webauthn plugin wiring.

Files Change
graphql/server/src/plugins/owner-handoff-plugin.ts New PostGraphile v5 plugin: ownerHandOff mutation with evidence consumption, code-challenge validation, and cross-schema SQL calls.
graphql/server/src/middleware/graphile.ts Registers OwnerHandoffPlugin in the preset plugins list, gated on the platform flag.

Reviewed commit: 1fa4f15

@luxor-code-review luxor-code-review Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Adds a platform-side owner-hand-off GraphQL mutation that consumes step-up evidence and mints a native hand-off token, registered conditionally via a new PostGraphile plugin.

Key findings

Comment on lines +67 to +71
function fail(code: string, message: string): never {
const error = new Error(`${code}: ${message}`) as Error & { code: string };
error.code = code;
throw error;
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟠 bug · high

Fail error codes never reach clients

The plugin's fail() throws a plain Error with a custom .code property and a "CODE: message" prefix (graphql/server/src/plugins/owner-handoff-plugin.ts:67-71), but the error pipeline never reads a .code property: parse() in @constructive-io/errors resolves codes only from PG DETAIL JSON, extensions.code, an entirely-ALL_CAPS message token, or a SQLSTATE.

Every hand-off rejection (STEP_UP_REQUIRED, NOT_DATABASE_OWNER, TENANT_SIGN_IN_FAILED, OWNER_MISMATCH, ...) therefore falls into the no-code branch of formatError, which stamps extensions.code = INTERNAL_SERVER_ERROR and logs it as an internal error under a random errorId. The desktop client that must branch on these codes cannot distinguish any of them, breaking the challenge hand-off flow.

📋 Prompt for AI Agents

In graphql/server/src/plugins/owner-handoff-plugin.ts lines 67-71, replace the fail() helper with the pattern used in graphql/server/src/plugins/webauthn-plugin.ts lines 66-70: create new Error(message) and set err.extensions = { code } instead of error.code = code plus a ${code}: ${message} message prefix. Then register the codes not yet in packages/errors/src/generated (STEP_UP_REQUIRED, NOT_DATABASE_OWNER, TENANT_AUTH_NOT_PROVISIONED, TENANT_SIGN_IN_FAILED, OWNER_MISMATCH) as public-class errors, so they surface to clients with their real code instead of INTERNAL_SERVER_ERROR.

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.
…lete

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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant