diff --git a/.changeset/34168-authorize-gate-refusal-reason.md b/.changeset/34168-authorize-gate-refusal-reason.md new file mode 100644 index 00000000000..2ba439d1fb1 --- /dev/null +++ b/.changeset/34168-authorize-gate-refusal-reason.md @@ -0,0 +1,26 @@ +--- +'@objectstack/plugin-auth': patch +'@object-ui/console': patch +'@object-ui/i18n': patch +--- + +feat(plugin-auth): the environment-access refusal can carry the host's reason and sentence to the sign-in page, and the sign-in page names the application on a hand-off + +Clause-②: yes (widening) +Metadata-protocol: none + +`AuthManagerOptions.oidcAuthorizeGate` (the ADR-0069 D5.1 environment-access gate) may now answer `{ allowed: false, reason, message }` in place of `false`: a reason code from the host's own closed set and the sentence the refused person reads. The refusal then carries both: + +- the `403` envelope keeps `code: ENV_ACCESS_DENIED`, gains `reason`, and its `message` is the host's sentence; +- the redirect back to a registered `redirect_uri` keeps `error=access_denied`, sends the host's sentence as `error_description`, and adds `objectstack_error_reason` (RFC 6749 §8.2 asks an unregistered parameter to carry a vendor prefix); +- the readable refusal page shows the host's sentence, HTML-escaped, beside the signed-in account. + +Nothing the host answers is trusted as markup or as a URL fragment. A reason outside `[a-z_]{1,40}` is dropped and the refusal stands. A sentence with a control character or an angle bracket, or longer than 300 characters, is replaced by the fixed sentence. On the redirect, a sentence outside the character set RFC 6749 §4.1.2.1 allows for `error_description` (printable ASCII without `"` and `\`) is also replaced by the fixed sentence. + +On the environment, the OAuth callback for the platform identity provider keeps a valid `objectstack_error_reason` on its redirect to the Console sign-in page. The sign-in page shows its own sentence for `not_member` and `invitation_pending` (in every Console language); any other reason, or none, keeps the existing `access_denied` sentence. The organization's name is carried only inside the host's sentence. + +The sign-in page reads the client name only for the client its signed request names: on an OAuth hand-off it asks the new `GET /api/v1/auth/oauth2/client-name` and says "Sign in to continue to NAME". Any other answer keeps the host line ("Continue to HOST"). The read is rate-limited per client address (a fixed window of 10 reads per 60 seconds, counted in the kernel `cache` service when one is registered); over the limit it answers `429` `RATE_LIMIT_EXCEEDED` with `Retry-After`. + +Unchanged: a gate that answers a boolean is answered byte for byte as before on all three doors; who is admitted (an object refuses only when it says `allowed: false`; any other answer keeps the truthiness the gate was always read with); which `redirect_uri` is followed. + +Upgrade note: a host may return the refusal object only once it runs this plugin-auth release or later. An older plugin-auth reads any object as an admission. diff --git a/packages/plugins/plugin-auth/src/auth-manager-after-hook.ts b/packages/plugins/plugin-auth/src/auth-manager-after-hook.ts index 75555575c32..91c1dc4fcee 100644 --- a/packages/plugins/plugin-auth/src/auth-manager-after-hook.ts +++ b/packages/plugins/plugin-auth/src/auth-manager-after-hook.ts @@ -48,6 +48,7 @@ import { passwordSignInDoorOf } from './auth-manager-sign-in-lockout.js'; import { narrowDirectoryForExternalCaller } from './external-directory-door.js'; import { SESSION_SCOPING_REFUSAL } from './organization-access-policy.js'; import { refuseIntrospectionForBannedSubject } from './oauth-token-read-ban-refusal.js'; +import { carryRefusalReasonOnCallback } from './oauth-callback-refusal-reason.js'; import { rotateCallerBearerOnImpersonation } from './impersonation-bearer-rotation.js'; import { stampInvitationDeliveryOutcome } from './invitation-delivery-outcome.js'; import { retireExpiredInvitationsOnReissue } from './invitation-expired-supersede.js'; @@ -230,6 +231,10 @@ export async function globalAfterHook(this: AfterHookHost, ctx: any) { // See `sso-provider-lifecycle.ts`. if (ctx?.path === SSO_PROVIDER_DELETE_PATH) await this.settleSsoProviderDelete(ctx); + // A refused platform sign-in: the environment's callback hands the host's + // reason on to the sign-in page (`oauth-callback-refusal-reason.ts`). + carryRefusalReasonOnCallback(ctx); + // Ruling record 6866334319: an OIDC provider saved with "sign out of the // company sign-in too" on keeps the end_session_endpoint its before-hook // read (`sso-sign-out-of-idp.ts`). diff --git a/packages/plugins/plugin-auth/src/auth-manager-before-hook.ts b/packages/plugins/plugin-auth/src/auth-manager-before-hook.ts index e54b5de9f1e..a5cd29986c9 100644 --- a/packages/plugins/plugin-auth/src/auth-manager-before-hook.ts +++ b/packages/plugins/plugin-auth/src/auth-manager-before-hook.ts @@ -69,7 +69,7 @@ import { LAST_LOCAL_CREDENTIAL_CODE, LAST_LOCAL_CREDENTIAL_MESSAGE, } from './last-local-credential.js'; -import { answerRefusedAuthorization } from './oauth-authorize-refusal.js'; +import { answerRefusedAuthorization, gateAnswerRefuses, refusalDetailOf } from './oauth-authorize-refusal.js'; import { refuseRequestNamingDifferentAccounts } from './one-account-per-request.js'; import { SSO_ONLY_RESET_UNREADABLE_MESSAGE, @@ -601,19 +601,27 @@ export async function globalBeforeHook( // D5.1 host contract is `(userId, clientId)` and the control plane // derives org membership / app assignment from the user itself. if (actor?.userId) { - let allowed = true; + // The first refusing answer, kept: a boolean `false`, or the host's + // refusal object with its reason and sentence. + let refusal: { answer: unknown } | undefined; for (const clientId of clientIds) { - allowed = await this.config.oidcAuthorizeGate({ userId: actor.userId, clientId }); - if (!allowed) break; + const answer: unknown = await this.config.oidcAuthorizeGate({ userId: actor.userId, clientId }); + if (gateAnswerRefuses(answer)) { + refusal = { answer }; + break; + } } - if (!allowed) { + if (refusal) { // The refusal, delivered by who is asking (`oauth-authorize-refusal.ts`): - // the `403` envelope for a fetch or an API client, unchanged; for a - // browser navigating here, `access_denied` back to the client's - // REGISTERED `redirect_uri`, or a readable page when there is none. + // the `403` envelope for a fetch or an API client; for a browser + // navigating here, `access_denied` back to the client's REGISTERED + // `redirect_uri`, or a readable page when there is none. A boolean + // refusal is answered as it always was; a refusal object adds the + // host's validated reason and sentence (`refusalDetailOf`). return answerRefusedAuthorization(ctx, { userId: actor.userId, consoleUrl: this.getConsolePageUrl('/'), + detail: refusalDetailOf(refusal.answer), }); } } diff --git a/packages/plugins/plugin-auth/src/auth-manager.ts b/packages/plugins/plugin-auth/src/auth-manager.ts index 26461f3f794..4f4c656280e 100644 --- a/packages/plugins/plugin-auth/src/auth-manager.ts +++ b/packages/plugins/plugin-auth/src/auth-manager.ts @@ -323,6 +323,7 @@ import { resolveTurnstileKeys } from './turnstile-sign-up.js'; import { assertTrustedAppSchemes, registeredAppSchemesOf } from './one-time-token-handoff.js'; import type { MintScimConnectionCredentialInput, MintedScimConnectionCredential } from './scim-connection-service.js'; import type { OrganizationBoundaryJudge } from './scim-group-projection.js'; +import type { OidcAuthorizeGateAnswer, OidcAuthorizeGateRefusal } from './oauth-authorize-refusal.js'; /** * Detect WebContainer (StackBlitz) environment. @@ -970,8 +971,13 @@ export interface AuthManagerOptions extends Partial { * may only obtain a code for an env client (`project_`) of an org * they belong to. Unset (open editions / self-host, where the OP is not a * multi-tenant issuer) = allow. Host is expected to fail CLOSED on error. + * + * In place of `false` the gate may answer an {@link OidcAuthorizeGateRefusal} + * (`{ allowed: false, reason, message }`) to say why: the refusal then + * carries the reason and the host's sentence to the caller + * (`oauth-authorize-refusal.ts`). A boolean is answered as it always was. */ - oidcAuthorizeGate?: (params: { userId: string; clientId: string }) => boolean | Promise; + oidcAuthorizeGate?: (params: { userId: string; clientId: string }) => OidcAuthorizeGateAnswer | Promise; /** * The host's own check on `POST /organization/delete`: answer a diff --git a/packages/plugins/plugin-auth/src/auth-plugin.ts b/packages/plugins/plugin-auth/src/auth-plugin.ts index ea11e122e3d..ecdb609c70e 100644 --- a/packages/plugins/plugin-auth/src/auth-plugin.ts +++ b/packages/plugins/plugin-auth/src/auth-plugin.ts @@ -726,6 +726,8 @@ export class AuthPlugin implements Plugin { private authSettingsBinding: Promise | null = null; /** [#26020] The per-address window of the signed-out invitation preview counts here; set in `init()`. */ private invitationPreviewCounters: (() => Promise) | null = null; + /** The per-address window of the signed-out application-name read counts here; set in `init()`. */ + private oauthClientNameCounters: (() => Promise) | null = null; constructor(options: AuthPluginOptions = {}) { this.options = { @@ -901,6 +903,16 @@ export class AuthPlugin implements Plugin { 'The limit is still enforced, but PER NODE: an N-node deployment admits up to N× the configured ' + 'previews per address per window', }); + // The signed-out application-name read (`oauth-client-name.ts`): the + // same per-address window, under its own subject. + this.oauthClientNameCounters = createLazyCounterStore({ + resolveCache, + logger: ctx.logger, + subject: 'signed-out application name rate limit', + degradedImpact: + 'The limit is still enforced, but PER NODE: an N-node deployment admits up to N× the configured ' + + 'reads per address per window', + }); } this.applyEnvSocialProviderFallbacks(authConfig); @@ -5312,6 +5324,45 @@ export class AuthPlugin implements Plugin { } }); + // ──────────────────────────────────────────────────────────────────── + // The application name for a sign-in hand-off: the sign-in page reads the + // client name only for the client its signed request names. The reasons + // for each answer live in oauth-client-name.ts. It never reads the + // session, and it is rate-limited per client address (ADR-0121 D6), like + // the invitation preview above. Ledgered `public` in auth-route-ledger.ts. + rawApp.get(`${basePath}/oauth2/client-name`, async (c: any) => { + try { + const counters = this.oauthClientNameCounters; + const mgr = this.authManager!; + if (!counters) { + ctx.logger.error('[AuthPlugin] oauth2/client-name: the rate-limit store was never wired; refusing'); + return c.json( + { success: false, error: { code: 'INTERNAL_ERROR', message: 'The application name is unavailable.' } }, + 500, + { 'Cache-Control': 'no-store' }, + ); + } + const { answerOAuthClientName } = await import('./oauth-client-name.js'); + const headers = (c.req.header() ?? {}) as Record; + const answer = await answerOAuthClientName( + { + queries: (c.req.queries() ?? {}) as Record, + clientAddress: mgr.resolveClientAddress({ headers, ...transportOf(c) }), + }, + { + getAuthContext: () => mgr.getAuthContext(), + getDataEngine: () => mgr.getDataEngine() as any, + counterStore: counters, + }, + ); + return c.json(answer.body, answer.status as any, answer.headers); + } catch (error) { + const err = error instanceof Error ? error : new Error(String(error)); + ctx.logger.error('[AuthPlugin] oauth2/client-name failed', err); + return c.json({ success: false, error: { code: 'INTERNAL_ERROR', message: 'The application name is unavailable.' } }, 500); + } + }); + // ──────────────────────────────────────────────────────────────────── // The mobile sign-in hand-off: a session signed in in the SYSTEM browser // is handed to a REGISTERED app scheme as a single-use, one-minute token diff --git a/packages/plugins/plugin-auth/src/auth-route-ledger.conformance.test.ts b/packages/plugins/plugin-auth/src/auth-route-ledger.conformance.test.ts index 6278391c6d9..9b83888fb5d 100644 --- a/packages/plugins/plugin-auth/src/auth-route-ledger.conformance.test.ts +++ b/packages/plugins/plugin-auth/src/auth-route-ledger.conformance.test.ts @@ -248,6 +248,12 @@ describe('auth route ledger hygiene', () => { // it to the same proof — better-auth serves no address read. 'GET /api/v1/auth/client-address', 'GET /api/v1/auth/config', + // The sign-in hand-off's application name, on this pin's own terms: + // `auth-plugin.ts` mounts it itself (a `rawApp.get` on the + // `${basePath}/oauth2/client-name` template, ahead of the catch-all), + // and the `live.has(route)` loop below holds it to the same proof — + // the vendor serves no route on that path. + 'GET /api/v1/auth/oauth2/client-name', // On this pin's own terms: `auth-plugin.ts` mounts it itself (a // `rawApp.get` on the `${basePath}/one-time-token/handoff` // template, ahead of the catch-all), and the `live.has(route)` loop diff --git a/packages/plugins/plugin-auth/src/auth-route-ledger.ts b/packages/plugins/plugin-auth/src/auth-route-ledger.ts index 3e1d13fe2b4..61808c2736e 100644 --- a/packages/plugins/plugin-auth/src/auth-route-ledger.ts +++ b/packages/plugins/plugin-auth/src/auth-route-ledger.ts @@ -181,6 +181,8 @@ export const AUTH_ROUTE_LEDGER: readonly AuthRouteLedgerEntry[] = [ { route: 'GET /api/v1/auth/oauth2/get-client', family: 'oauth-provider', source: 'better-auth', disposition: 'sdk', client: 'oauth.applications.get', requires: 'oidcProvider' }, { route: 'GET /api/v1/auth/oauth2/get-clients', family: 'oauth-provider', source: 'better-auth', disposition: 'sdk', client: 'oauth.applications.list', requires: 'oidcProvider' }, { route: 'GET /api/v1/auth/oauth2/public-client', family: 'oauth-provider', source: 'better-auth', disposition: 'sdk', client: 'oauth.applications.getPublic', requires: 'oidcProvider' }, + // The application name a sign-in hand-off shows (`oauth-client-name.ts`). + { route: 'GET /api/v1/auth/oauth2/client-name', family: 'oauth-provider', source: 'objectstack', disposition: 'public', note: 'no SDK method builds this URL — the Console sign-in page reads it on an OAuth hand-off. The sign-in page reads the client name only for the client its signed request names: it answers a caller with NO session, admitted by the signed authorization request this server put on the sign-in URL (oauth_query, verified with the provider\'s own verifyOAuthQueryParams, not expired), for the one client_id inside it; the URL\'s client_id must equal that one. Returns exactly { client_name }. One uniform 404 for a signature that does not verify or has expired, a client_id that differs, an unknown, disabled or unnamed client; closed query set { client_id, oauth_query }; Cache-Control no-store. The mount is unconditional: with no OAuth provider there is no signed request, so every call answers the 404' }, { route: 'GET /api/v1/auth/bootstrap-status', family: 'objectstack-mount', source: 'objectstack', disposition: 'sdk', client: 'auth.bootstrapStatus' }, { route: 'GET /api/v1/auth/config', family: 'objectstack-mount', source: 'objectstack', disposition: 'sdk', client: 'auth.getConfig' }, // Direct sign-in's start door (`direct-sign-in.ts`): mounted only while the diff --git a/packages/plugins/plugin-auth/src/oauth-authorize-refusal.test.ts b/packages/plugins/plugin-auth/src/oauth-authorize-refusal.test.ts index 7aacabebb34..7cca5ca66f4 100644 --- a/packages/plugins/plugin-auth/src/oauth-authorize-refusal.test.ts +++ b/packages/plugins/plugin-auth/src/oauth-authorize-refusal.test.ts @@ -15,6 +15,7 @@ * the allowing control mints a code on the very same request. */ +import { createHash } from 'node:crypto'; import { describe, it, expect, vi, beforeEach, afterEach, afterAll } from 'vitest'; import { AuthManager } from './auth-manager'; import { createMemoryEngine } from './impersonation-bearer-rotation.test'; @@ -25,7 +26,12 @@ import { ENV_ACCESS_DENIED_MESSAGE, OAUTH_ACCESS_DENIED_ERROR, OAUTH_END_SESSION_PATH, + OAUTH_REFUSAL_REASON_PARAM, + REFUSAL_MESSAGE_MAX_LENGTH, } from './oauth-authorize-refusal'; +import { answerOAuthClientName, OAUTH_CLIENT_NAME_NOT_FOUND, OAUTH_CLIENT_NAME_RATE_LIMIT } from './oauth-client-name'; +import { InProcessCounterStore, type CounterStore } from './rate-limit-storage'; +import { PLATFORM_IDP_PROVIDER_ID } from './implicit-account-linking'; const SECRET = 'test-secret-at-least-32-chars-long-authorize-refusal'; const PASSWORD = 'S3cure!Passw0rd-authorize-refusal'; @@ -68,14 +74,16 @@ interface GateCall { const arrange = async () => { const engine = createMemoryEngine(); - // `allow` admits every client; `admitted` admits the clients it names. - const gate = { allow: false, admitted: new Set(), calls: [] as GateCall[] }; + // `allow` admits every client; `admitted` admits the clients it names; + // `answer`, when set, is what the gate answers for every client instead. + const gate = { allow: false, admitted: new Set(), calls: [] as GateCall[], answer: undefined as unknown }; const manager = new AuthManager({ secret: SECRET, baseUrl: ORIGIN, dataEngine: engine, oidcAuthorizeGate: (params: GateCall) => { gate.calls.push({ userId: params.userId, clientId: params.clientId }); + if (gate.answer !== undefined) return gate.answer; return gate.allow || gate.admitted.has(params.clientId); }, } as any); @@ -155,7 +163,7 @@ const arrange = async () => { ); }; - return { manager, gate, userId, register, clientRow, authorize, authorizeForm, call, cookie }; + return { manager, engine, gate, userId, register, clientRow, authorize, authorizeForm, call, cookie }; }; const codeRequest = (clientId: string, redirectUri: string): Record => ({ @@ -600,3 +608,502 @@ describe('the environment-access gate judges every pass that resumes an authoriz }); } }); + +describe("a refused /oauth2/authorize carries the host's reason when the gate answers a refusal object", () => { + /** The cloud control plane's answer for a signed-in account that is not a member of the organization. */ + const NOT_MEMBER = { + allowed: false, + reason: 'not_member', + message: 'You are not a member of Acme Corp. Ask an administrator of Acme Corp to invite you.', + } as const; + + type Rig = Awaited>; + type Door = 'envelope' | 'redirect' | 'page'; + + /** The same refused request, delivered through one door. */ + const refuse = async (rig: Rig, door: Door): Promise => { + const clientId = await rig.register(ENV_CALLBACK, 'web'); + const res = door === 'envelope' + ? await rig.authorize(codeRequest(clientId, ENV_CALLBACK), CONSOLE_FETCH) + : door === 'redirect' + ? await rig.authorize(codeRequest(clientId, ENV_CALLBACK), NAVIGATION) + : await rig.authorize(codeRequest(clientId, 'https://attacker.example/cb'), NAVIGATION); + expect(rig.gate.calls).toEqual([{ userId: rig.userId, clientId }]); + return res; + }; + + /** Every byte a door answers with: status, the headers a refusal sets, and the body (or the redirect target). */ + const bytesOf = async (res: Response) => ({ + status: res.status, + contentType: res.headers.get('content-type'), + location: res.headers.get('location'), + body: await res.text(), + }); + + describe('CONTROL: a boolean gate answers byte for byte as before', () => { + // The literals below were read off this suite at the merge base, before + // the gate could answer anything but a boolean; they hold there and here. + const PAGE_SHA256_AT_MERGE_BASE = '60b2309f3a19756c308cd06e4277a3c1c22595c738ed42f15f26c93c1a410c70'; + const PAGE_SENTENCE = `

You are signed in as ${EMAIL}, and this account does not have access to this environment.

`; + + it('the envelope', async () => { + const rig = await arrange(); + const res = await bytesOf(await refuse(rig, 'envelope')); + expect(res.status).toBe(403); + expect(res.location).toBeNull(); + expect(JSON.parse(res.body)).toEqual({ code: ENV_ACCESS_DENIED_CODE, message: ENV_ACCESS_DENIED_MESSAGE }); + }); + + it('the redirect', async () => { + const rig = await arrange(); + const res = await bytesOf(await refuse(rig, 'redirect')); + expect(res.status).toBe(302); + expect(res.body).toBe(''); + const location = new URL(res.location ?? ''); + expect(`${location.origin}${location.pathname}`).toBe(ENV_CALLBACK); + expect([...location.searchParams]).toEqual([ + ['error', OAUTH_ACCESS_DENIED_ERROR], + ['error_description', ENV_ACCESS_DENIED_MESSAGE], + ['state', STATE], + ['iss', ISSUER], + ]); + }); + + it('the page', async () => { + const rig = await arrange(); + const res = await bytesOf(await refuse(rig, 'page')); + expect(res.status).toBe(403); + expect(res.contentType).toBe('text/html; charset=utf-8'); + expect(res.body).toContain(PAGE_SENTENCE); + expect(createHash('sha256').update(res.body).digest('hex')).toBe(PAGE_SHA256_AT_MERGE_BASE); + }); + + }); + + it('a refusal object whose reason and sentence are both refused answers the same bytes as `false`, on every door', async () => { + for (const door of ['envelope', 'redirect', 'page'] as const) { + const boolean = await arrange(); + const object = await arrange(); + object.gate.answer = { allowed: false, reason: 'Not-A-Code', message: 'no' }; + expect(await bytesOf(await refuse(object, door)), door).toEqual(await bytesOf(await refuse(boolean, door))); + } + }); + + it('the envelope keeps code ENV_ACCESS_DENIED and gains the reason; the message is the host\'s sentence', async () => { + const rig = await arrange(); + rig.gate.answer = NOT_MEMBER; + + const res = await refuse(rig, 'envelope'); + + expect(res.status).toBe(403); + expect(await res.json()).toEqual({ code: ENV_ACCESS_DENIED_CODE, message: NOT_MEMBER.message, reason: 'not_member' }); + }); + + it('the redirect keeps error=access_denied, sends the host\'s sentence as error_description and the reason as its own parameter', async () => { + const rig = await arrange(); + rig.gate.answer = NOT_MEMBER; + + const res = await refuse(rig, 'redirect'); + + expect(res.status).toBe(302); + const location = new URL(res.headers.get('location') ?? ''); + expect(`${location.origin}${location.pathname}`).toBe(ENV_CALLBACK); + expect([...location.searchParams]).toEqual([ + ['error', OAUTH_ACCESS_DENIED_ERROR], + ['error_description', NOT_MEMBER.message], + [OAUTH_REFUSAL_REASON_PARAM, 'not_member'], + ['state', STATE], + ['iss', ISSUER], + ]); + expect(location.searchParams.has('code')).toBe(false); + }); + + it('the page shows the host\'s sentence, escaped, beside the signed-in account', async () => { + const rig = await arrange(); + rig.gate.answer = { ...NOT_MEMBER, message: 'You are not a member of "Smith & Sons". Ask them to invite you.' }; + + const res = await refuse(rig, 'page'); + + expect(res.status).toBe(403); + const html = await res.text(); + expect(html).toContain( + `

You are signed in as ${EMAIL}. You are not a member of "Smith & Sons". Ask them to invite you.

`, + ); + expect(html).not.toContain('does not have access to this environment.

'); + }); + + const refusedReasons: ReadonlyArray<[string, unknown]> = [ + ['upper case', 'NOT_MEMBER'], + ['a digit', 'not_member2'], + ['a hyphen', 'not-member'], + ['markup', '