Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions .changeset/34168-authorize-gate-refusal-reason.md
Original file line number Diff line number Diff line change
@@ -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.
5 changes: 5 additions & 0 deletions packages/plugins/plugin-auth/src/auth-manager-after-hook.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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`).
Expand Down
24 changes: 16 additions & 8 deletions packages/plugins/plugin-auth/src/auth-manager-before-hook.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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),
});
}
}
Expand Down
8 changes: 7 additions & 1 deletion packages/plugins/plugin-auth/src/auth-manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -970,8 +971,13 @@ export interface AuthManagerOptions extends Partial<AuthConfig> {
* may only obtain a code for an env client (`project_<envId>`) 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<boolean>;
oidcAuthorizeGate?: (params: { userId: string; clientId: string }) => OidcAuthorizeGateAnswer | Promise<OidcAuthorizeGateAnswer>;

/**
* The host's own check on `POST /organization/delete`: answer a
Expand Down
51 changes: 51 additions & 0 deletions packages/plugins/plugin-auth/src/auth-plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -726,6 +726,8 @@ export class AuthPlugin implements Plugin {
private authSettingsBinding: Promise<void> | null = null;
/** [#26020] The per-address window of the signed-out invitation preview counts here; set in `init()`. */
private invitationPreviewCounters: (() => Promise<CounterStore>) | null = null;
/** The per-address window of the signed-out application-name read counts here; set in `init()`. */
private oauthClientNameCounters: (() => Promise<CounterStore>) | null = null;

constructor(options: AuthPluginOptions = {}) {
this.options = {
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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<string, string>;
const answer = await answerOAuthClientName(
{
queries: (c.req.queries() ?? {}) as Record<string, string[]>,
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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 2 additions & 0 deletions packages/plugins/plugin-auth/src/auth-route-ledger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading
Loading