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
12 changes: 12 additions & 0 deletions .changeset/35939-sso-unmounted-404.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
---
'@objectstack/plugin-auth': patch
---

fix(plugin-auth): a kernel without SSO answers 404 again on the SSO discovery endpoints, with no error log

Clause-②: no
Metadata-protocol: none

Since SSO discovery began connecting only to addresses that are public at connect time, a kernel that does not mount SSO (the default without `OS_SSO_ENABLED` or `plugins.sso`) answered `POST /sso/register`, `/sign-in/sso` and `/sso/callback/*` with `503 SERVICE_UNAVAILABLE` ("SSO is unavailable: this server cannot judge its reads of an identity provider") and logged one error line per request. The discovery scope opened on the path alone, while the adapter observer it requires is mounted only with SSO.

The scope now opens only when the built auth instance mounts the vendor's `sso` plugin, read off the composed plugin list rather than the configuration re-read at request time. A kernel without SSO answers the vendor's own 404 on those paths and logs nothing. A kernel that mounts SSO is judged exactly as before: provider reads go through the connect-time guard, and a context whose adapter is not observed is still refused `503` before the endpoint runs. No configuration, export or response shape changes.
11 changes: 8 additions & 3 deletions packages/plugins/plugin-auth/src/auth-manager-request-routing.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ import { SESSION_ERASURE_PATHS } from './session-tombstone.js';
import { envelopeVendorAdminRefusal } from './vendor-admin-refusal-envelope.js';
import { OAUTH_REVOKE_PATH } from './mcp-token-revocation.js';
import { ssoCallbackOf } from './sso-oidc-refusal-cause.js';
import { isSsoDiscoveryEgressPath } from './sso-discovery-egress.js';
import { isSsoDiscoveryEgressPath, mountsSsoEndpoints } from './sso-discovery-egress.js';
import { samlSingleLogoutProviderId, SIGN_OUT_ENDPOINT_PATH } from './sso-sign-out-of-idp.js';
import type { ScimRequestScope } from './scim-connection-service.js';

Expand Down Expand Up @@ -233,8 +233,13 @@ export async function handleRequest(this: Pick<RequestRoutingHost, 'config' | 'b
// scope entered inside a hook never reaches. Only reads at origins the
// request's provider configuration names are judged (the global before-hook
// names a registration's, the observed adapter a stored provider's as the
// vendor reads it); every other read is sent as it was.
const runHandler = isSsoDiscoveryEgressPath(this.betterAuthEndpointPath(request))
// vendor reads it); every other read is sent as it was. The scope opens only
// where the built instance mounts the vendor's `sso` plugin
// (`mountsSsoEndpoints`): a kernel without SSO serves none of these paths,
// so the vendor answers its own 404 and no provider read can happen, while
// a kernel that mounts it is judged exactly as before — an unobserved
// adapter there is still refused 503.
const runHandler = isSsoDiscoveryEgressPath(this.betterAuthEndpointPath(request)) && mountsSsoEndpoints(auth)
? (): Promise<Response> => this.runSsoDiscoveryEgress(runVendorHandler)
: runVendorHandler;

Expand Down
4 changes: 3 additions & 1 deletion packages/plugins/plugin-auth/src/auth-manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4475,7 +4475,9 @@ export class AuthManager {
* makes is sent as it was. A context whose adapter is not observed (a view
* that does not hand its reads on through the observed one) is answered
* `503 SERVICE_UNAVAILABLE` before the endpoint runs, so nothing is read or
* sent: its provider reads could not be judged.
* sent: its provider reads could not be judged. Reached only when the built
* instance mounts the vendor's `sso` plugin (`mountsSsoEndpoints`, judged in
* `handleRequest`): a kernel without SSO answers the vendor's own 404.
*/
private async runSsoDiscoveryEgress(run: () => Promise<Response>): Promise<Response> {
const [{ runInSsoDiscoveryEgressScope, observesSsoProviderReads }, guard, auth] = await Promise.all([
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -660,6 +660,75 @@ describe('a request whose auth context adapter is not the observed view is refus
});
});

describe('the discovery scope follows the composition: a kernel that does not mount SSO answers the vendor\'s 404 and logs nothing', () => {
afterEach(() => {
vi.unstubAllEnvs();
});

interface Kernel {
manager: AuthManager;
logger: { warn: ReturnType<typeof vi.fn>; error: ReturnType<typeof vi.fn>; info: ReturnType<typeof vi.fn> };
}

function kernel(plugins: Record<string, unknown>): Kernel {
const logger = { warn: vi.fn(), error: vi.fn(), info: vi.fn() };
const manager = new AuthManager({
secret: SECRET,
baseUrl: BASE,
dataEngine: createMemoryEngine(),
trustedOrigins: [BASE],
plugins,
logger,
} as unknown as ConstructorParameters<typeof AuthManager>[0]);
return { manager, logger };
}

const doors: ReadonlyArray<readonly [path: string, request: () => Request]> = [
['POST /sso/register', () => new Request(`${AUTH}/sso/register`, {
method: 'POST',
headers: { 'content-type': 'application/json', origin: BASE },
body: JSON.stringify(registration('unmounted-register', 'https://idp.acme.example')),
})],
['POST /sign-in/sso', () => new Request(`${AUTH}/sign-in/sso`, {
method: 'POST',
headers: { 'content-type': 'application/json', origin: BASE },
body: JSON.stringify({ providerId: 'unmounted-oidc', callbackURL: `${BASE}/after` }),
})],
['GET /sso/callback/:providerId', () => new Request(`${AUTH}/sso/callback/unmounted-oidc?code=idp-code&state=any-state`)],
];

const compositions: ReadonlyArray<readonly [name: string, plugins: Record<string, unknown>]> = [
['plugins.sso false', { sso: false }],
['plugins.sso unset and OS_SSO_ENABLED unset (the default)', {}],
];

describe.each(compositions)('%s', (_name, plugins) => {
it.each(doors)('%s answers 404, and nothing is logged at error level', async (_door, request) => {
vi.stubEnv('OS_SSO_ENABLED', undefined);
const { manager, logger } = kernel(plugins);
const res = await manager.handleRequest(request());
expect(res.status, await res.clone().text()).toBe(404);
expect(logger.error).not.toHaveBeenCalled();
const lines = [...logger.warn.mock.calls, ...logger.info.mock.calls].map((call) => String(call[0]));
expect(lines.filter((line) => line.includes('SSO request refused'))).toEqual([]);
});
});

it('CONTROL: a kernel that mounted SSO keeps the scope when OS_SSO_ENABLED is unset after the build: an unobserved context adapter is still answered 503', async () => {
vi.stubEnv('OS_SSO_ENABLED', 'true');
const { manager, logger } = kernel({});
const ctx = await ((await manager.getAuthInstance()) as any).$context;
// The configuration re-read at request time now says "no SSO"; the
// composition that answers the request still mounts it.
vi.stubEnv('OS_SSO_ENABLED', undefined);
ctx.adapter = { ...ctx.adapter };
const res = await manager.handleRequest(doors[0]![1]());
expect(res.status, await res.clone().text()).toBe(503);
expect(await res.json()).toMatchObject({ success: false, error: { code: 'SERVICE_UNAVAILABLE' } });
expect(logger.error).toHaveBeenCalledTimes(1);
});
});

describe('the SSO discovery scope judges only the reads it names', () => {
/** A guard that answers every read itself, recording it. */
function recordingGuard(): { guard: EgressGuard; sent: string[] } {
Expand Down
14 changes: 14 additions & 0 deletions packages/plugins/plugin-auth/src/sso-discovery-egress.ts
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,20 @@ export function isSsoDiscoveryEgressPath(endpointPath: string | undefined): bool
return endpointPath.startsWith('/sso/callback/');
}

/**
* Whether the built auth instance mounts the vendor's `sso` plugin, the one
* thing that serves the endpoints {@link isSsoDiscoveryEgressPath} names. Read
* off the composition that answers the request (its plugin list), never off
* the configuration re-read at request time, which can disagree with the lazy
* build. A plugin list that cannot be read answers `true`: a composition this
* cannot see into is judged as one that mounts SSO, so the scope opens.
*/
export function mountsSsoEndpoints(auth: unknown): boolean {
const plugins = (auth as { options?: { plugins?: unknown } } | null | undefined)?.options?.plugins;
if (!Array.isArray(plugins)) return true;
return plugins.some((plugin) => (plugin as { id?: unknown } | null)?.id === 'sso');
}

/**
* The guard SSO discovery sends through: the platform's outbound-request
* guard with a policy that refuses every address that is not public and
Expand Down
Loading