Skip to content

Commit 70847b8

Browse files
committed
test(plugin-auth): pin the SCIM credential door end to end
Claude-Session: https://claude.ai/code/session_016WV4cycHNJyS5MXHqaGsFE Co-Authored-By: Claude <noreply@anthropic.com>
1 parent c8b4b5f commit 70847b8

1 file changed

Lines changed: 383 additions & 0 deletions

File tree

Lines changed: 383 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,383 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* [#30958] The platform-admin door that mints and revokes SCIM connection
5+
* credentials — `POST /api/v1/auth/admin/scim/mint-credential` and
6+
* `POST /api/v1/auth/admin/scim/revoke-credential` — end to end.
7+
*
8+
* ## What is real
9+
*
10+
* The two mounts are the plugin's REAL route registration on a real Hono app
11+
* (the `request-json-body-refusal.test.ts` harness), so the shared
12+
* `judgePlatformAdmin` gate in front of them is inside the system under test.
13+
* Behind them sits a real `AuthManager` with SCIM on, over a real `ObjectQL` on
14+
* better-sqlite3 `:memory:`: the bearer the mint answers is driven into the
15+
* vendor's own `POST /scim/v2/Users`, verified by the production
16+
* `verifyBearerToken` wiring, so a mint that digested with the wrong key, or a
17+
* revoke that wrote nothing, fails at the IdP's door and not at a helper.
18+
*
19+
* Only the session is chosen per case: the gate reads it through the auth
20+
* service's in-process `getSession`, which the harness answers with a platform
21+
* admin, a signed-in member, or nobody.
22+
*
23+
* ## The secret is shown once
24+
*
25+
* Every case that mints asserts the plaintext bearer is in the mint's answer
26+
* and NOWHERE else this file can see: not in the credential row, not in any
27+
* `sys_audit_log` row, not in any line the plugin logger or the console was
28+
* handed. The keyed digest is held to the same absence everywhere but its own
29+
* column.
30+
*/
31+
32+
import { describe, it, expect, vi, beforeAll, afterAll, afterEach } from 'vitest';
33+
import { Hono } from 'hono';
34+
import { ObjectQL } from '@objectstack/objectql';
35+
import { SqlDriver } from '@objectstack/driver-sql';
36+
import { envelopeViolations } from '@objectstack/spec/api';
37+
import type { PluginContext } from '@objectstack/core';
38+
import { AuthPlugin } from './auth-plugin.js';
39+
import { AuthManager } from './auth-manager.js';
40+
import { authIdentityObjects } from './manifest.js';
41+
import { createTenancyService } from './tenancy-service.js';
42+
import { SCIM_BEARER_PREFIX, SCIM_CREDENTIAL_OBJECT, digestScimBearerToken } from './scim-connection-service.js';
43+
// The mounts load this module with a dynamic `import()` on first request; paid
44+
// here at collection instead of inside the first case.
45+
import './scim-connection-admin.js';
46+
import 'better-auth';
47+
import 'better-auth/plugins';
48+
import 'better-auth/plugins/admin';
49+
import 'better-auth/plugins/organization';
50+
import '@better-auth/scim';
51+
52+
const ORIGIN = 'http://localhost:3000';
53+
const AUTH = `${ORIGIN}/api/v1/auth`;
54+
const SECRET = 'test-secret-at-least-32-chars-long-30958';
55+
const SYSTEM = { context: { isSystem: true } } as const;
56+
const DEFAULT_ORG = 'org_default';
57+
const OTHER_ORG = 'org_other';
58+
59+
const ADMIN = { user: { id: 'usr_platform_admin', email: 'admin@example.test', isPlatformAdmin: true }, session: {} };
60+
const MEMBER = { user: { id: 'usr_member', email: 'member@example.test', isPlatformAdmin: false, role: 'user' }, session: {} };
61+
62+
/**
63+
* The columns `sys_audit_log` declares that this door writes — the fixture the
64+
* plugin-auth harness carries, since plugin-audit (the object's owner) is not a
65+
* dependency of this package.
66+
*/
67+
const sysAuditLog = {
68+
name: 'sys_audit_log',
69+
label: 'Audit Log',
70+
// As the real object declares it (ADR-0131 D7): a deployment-level ledger
71+
// with no injected organization column.
72+
systemFields: { tenant: false },
73+
fields: {
74+
id: { name: 'id', type: 'text' as const, primaryKey: true },
75+
action: { name: 'action', type: 'text' as const },
76+
user_id: { name: 'user_id', type: 'text' as const },
77+
actor: { name: 'actor', type: 'text' as const },
78+
object_name: { name: 'object_name', type: 'text' as const },
79+
record_id: { name: 'record_id', type: 'text' as const },
80+
metadata: { name: 'metadata', type: 'textarea' as const },
81+
},
82+
};
83+
84+
let engine: ObjectQL;
85+
let manager: AuthManager;
86+
let app: Hono;
87+
let session: unknown = ADMIN;
88+
const logger = { info: vi.fn(), error: vi.fn(), warn: vi.fn(), debug: vi.fn() };
89+
const consoleSpies: Array<ReturnType<typeof vi.spyOn>> = [];
90+
91+
beforeAll(async () => {
92+
engine = new ObjectQL();
93+
engine.registerDriver(
94+
new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true }),
95+
true,
96+
);
97+
await engine.init();
98+
for (const object of [...authIdentityObjects, sysAuditLog]) {
99+
engine.registry.registerObject(object as never, '@objectstack/plugin-auth');
100+
}
101+
await engine.syncSchemas();
102+
await engine.insert('sys_organization', { id: DEFAULT_ORG, name: 'Default Organization', slug: 'default' }, SYSTEM);
103+
await engine.insert('sys_organization', { id: OTHER_ORG, name: 'Other Organization', slug: 'other' }, SYSTEM);
104+
105+
manager = new AuthManager({
106+
secret: SECRET,
107+
baseUrl: ORIGIN,
108+
dataEngine: engine as never,
109+
getTenancy: () => createTenancyService({ requested: 'isolated', probeIsolation: () => true }),
110+
plugins: { scim: true, organization: true },
111+
} as never);
112+
// The gate reads the caller through the auth service's in-process session read.
113+
vi.spyOn(manager, 'getApi').mockImplementation(async () => ({ getSession: async () => session }) as never);
114+
115+
const ctx = {
116+
registerService: vi.fn(),
117+
getService: vi.fn((name: string) => (name === 'manifest' ? { register: vi.fn() } : undefined)),
118+
getServices: vi.fn(() => new Map()),
119+
hook: vi.fn(),
120+
trigger: vi.fn(),
121+
logger,
122+
getKernel: vi.fn(),
123+
} as unknown as PluginContext;
124+
const plugin = new AuthPlugin({ secret: SECRET, plugins: { oidcProvider: false } });
125+
await plugin.init(ctx);
126+
(plugin as unknown as { authManager: AuthManager }).authManager = manager;
127+
app = new Hono();
128+
(plugin as unknown as { registerAuthRoutes(server: unknown, c: PluginContext): void })
129+
.registerAuthRoutes({ getRawApp: () => app, getPort: () => 0 }, ctx);
130+
131+
for (const method of ['log', 'info', 'warn', 'error', 'debug'] as const) {
132+
consoleSpies.push(vi.spyOn(console, method));
133+
}
134+
}, 60_000);
135+
136+
afterEach(() => {
137+
session = ADMIN;
138+
});
139+
140+
afterAll(() => {
141+
for (const spy of consoleSpies) spy.mockRestore();
142+
});
143+
144+
// ── Requests ────────────────────────────────────────────────────────────────
145+
146+
async function door(path: 'mint-credential' | 'revoke-credential', body: unknown): Promise<{ status: number; body: any; cacheControl: string | null }> {
147+
const res = await app.request(`${AUTH}/admin/scim/${path}`, {
148+
method: 'POST',
149+
headers: { origin: ORIGIN, 'content-type': 'application/json' },
150+
body: JSON.stringify(body),
151+
});
152+
return { status: res.status, body: await res.json(), cacheControl: res.headers.get('cache-control') };
153+
}
154+
155+
/** `POST /Users` as an identity provider sends it, with `token` as the bearer. */
156+
async function provision(token: string, localPart: string): Promise<Response> {
157+
const email = `${localPart}@example.com`;
158+
return manager.handleRequest(
159+
new Request(`${AUTH}/scim/v2/Users`, {
160+
method: 'POST',
161+
headers: { origin: ORIGIN, authorization: `Bearer ${token}`, 'content-type': 'application/scim+json' },
162+
body: JSON.stringify({
163+
schemas: ['urn:ietf:params:scim:schemas:core:2.0:User'],
164+
userName: email,
165+
name: { givenName: localPart, familyName: 'Example' },
166+
emails: [{ value: email, primary: true, type: 'work' }],
167+
active: true,
168+
}),
169+
}),
170+
);
171+
}
172+
173+
// ── Reads ───────────────────────────────────────────────────────────────────
174+
175+
async function credentialRows(connectionId: string): Promise<Array<Record<string, unknown>>> {
176+
return (await engine.find(SCIM_CREDENTIAL_OBJECT, { where: { connection_id: connectionId } }, SYSTEM)) as never;
177+
}
178+
179+
async function auditRows(credentialId: string): Promise<Array<Record<string, unknown>>> {
180+
return (await engine.find('sys_audit_log', { where: { record_id: credentialId } }, SYSTEM)) as never;
181+
}
182+
183+
/** Every line the plugin logger and the console were handed, as one string. */
184+
function everythingLogged(): string {
185+
const calls = [
186+
...Object.values(logger).flatMap((fn) => fn.mock.calls),
187+
...consoleSpies.flatMap((spy) => spy.mock.calls),
188+
];
189+
return calls.map((args) => args.map((a) => (a instanceof Error ? `${a.message} ${a.stack}` : typeof a === 'string' ? a : JSON.stringify(a))).join(' ')).join('\n');
190+
}
191+
192+
/** The bearer and its digest appear in no audit row and no log line. */
193+
async function expectSecretNowhereElse(token: string, credentialId: string): Promise<void> {
194+
const digest = digestScimBearerToken(SECRET, token);
195+
const audit = JSON.stringify(await engine.find('sys_audit_log', {}, SYSTEM));
196+
expect(audit).not.toContain(token);
197+
expect(audit).not.toContain(digest);
198+
const logged = everythingLogged();
199+
expect(logged).not.toContain(token);
200+
expect(logged).not.toContain(digest);
201+
// At rest (read below the engine, as `credential-at-rest-posture.test.ts`
202+
// does) the row holds the digest and never the bearer.
203+
const driver = (engine as unknown as { getDriver(o: string): { find(o: string, q: unknown): Promise<unknown> } })
204+
.getDriver(SCIM_CREDENTIAL_OBJECT);
205+
const atRest = ((await driver.find(SCIM_CREDENTIAL_OBJECT, { where: { id: credentialId } })) as Array<Record<string, unknown>>)[0];
206+
expect(atRest.token_digest).toBe(digest);
207+
expect(JSON.stringify(atRest)).not.toContain(token);
208+
// Through the engine — even a system read — the digest column is not served
209+
// at all (`internal: true`), so no read the data API builds on can return it.
210+
const served = JSON.stringify(await engine.find(SCIM_CREDENTIAL_OBJECT, { where: { id: credentialId } }, SYSTEM));
211+
expect(served).toContain(credentialId);
212+
expect(served).not.toContain(digest);
213+
expect(served).not.toContain(token);
214+
}
215+
216+
// ── The cases ───────────────────────────────────────────────────────────────
217+
218+
describe('[#30958] mint: the platform admin gets a bearer the SCIM plugin accepts, shown once', () => {
219+
it('an admin mints, and SCIM POST /Users with that bearer answers 201', async () => {
220+
const minted = await door('mint-credential', { connectionId: 'okta-30958', label: 'first rotation' });
221+
expect(minted.status, JSON.stringify(minted.body)).toBe(200);
222+
expect(envelopeViolations(minted.body)).toEqual([]);
223+
expect(minted.cacheControl).toBe('no-store');
224+
const { token, credentialId, connectionId, expiresAt } = minted.body.data;
225+
expect(typeof token).toBe('string');
226+
expect(token.startsWith(SCIM_BEARER_PREFIX)).toBe(true);
227+
expect(connectionId).toBe('okta-30958');
228+
expect(expiresAt).toBeNull();
229+
230+
const created = await provision(token, 'mint-30958');
231+
expect(created.status, `SCIM POST /Users: ${await created.clone().text()}`).toBe(201);
232+
233+
// The row the mint stored: owned by the Default Organization, minted by the admin, active.
234+
const [row] = await credentialRows('okta-30958');
235+
expect(row.id).toBe(credentialId);
236+
expect(row.organization_id).toBe(DEFAULT_ORG);
237+
expect(row.user_id).toBe(ADMIN.user.id);
238+
expect(row.label).toBe('first rotation');
239+
expect(Boolean(row.active)).toBe(true);
240+
241+
// One audit row, naming the admin and the connection.
242+
const audit = await auditRows(credentialId);
243+
expect(audit).toHaveLength(1);
244+
expect(audit[0]).toMatchObject({ action: 'create', user_id: ADMIN.user.id, actor: ADMIN.user.id, object_name: SCIM_CREDENTIAL_OBJECT });
245+
expect(JSON.parse(String(audit[0].metadata))).toEqual({ event: 'scim_credential_minted', connectionId: 'okta-30958' });
246+
247+
await expectSecretNowhereElse(token, credentialId);
248+
}, 30_000);
249+
250+
it('the owning organization is the one the request names, which must exist', async () => {
251+
const named = await door('mint-credential', { connectionId: 'entra-other-org', organizationId: OTHER_ORG });
252+
expect(named.status, JSON.stringify(named.body)).toBe(200);
253+
expect((await credentialRows('entra-other-org'))[0].organization_id).toBe(OTHER_ORG);
254+
255+
const unknown = await door('mint-credential', { connectionId: 'entra-nowhere', organizationId: 'org_missing' });
256+
expect(unknown.status).toBe(400);
257+
expect(unknown.body.error.code).toBe('INVALID_REQUEST');
258+
expect(await credentialRows('entra-nowhere')).toEqual([]);
259+
});
260+
261+
it('a malformed request is refused before anything is stored', async () => {
262+
for (const body of [
263+
{},
264+
{ connectionId: '' },
265+
{ connectionId: ' padded ' },
266+
{ connectionId: 42 },
267+
{ connectionId: 'x'.repeat(256) },
268+
{ connectionId: 'okta-bad-expiry', expiresAt: 'not-a-date' },
269+
{ connectionId: 'okta-bad-expiry', expiresAt: new Date(Date.now() - 60_000).toISOString() },
270+
{ connectionId: 'okta-bad-label', label: 7 },
271+
]) {
272+
const res = await door('mint-credential', body);
273+
expect(res.status, JSON.stringify(body)).toBe(400);
274+
expect(res.body.error.code).toBe('INVALID_REQUEST');
275+
}
276+
expect(await credentialRows('okta-bad-expiry')).toEqual([]);
277+
expect(await credentialRows('okta-bad-label')).toEqual([]);
278+
});
279+
280+
it('a future expiry is stored and answered', async () => {
281+
const at = new Date(Date.now() + 86_400_000).toISOString();
282+
const res = await door('mint-credential', { connectionId: 'okta-expiring', expiresAt: at });
283+
expect(res.status, JSON.stringify(res.body)).toBe(200);
284+
expect(res.body.data.expiresAt).toBe(at);
285+
expect(new Date(String((await credentialRows('okta-expiring'))[0].expires_at)).toISOString()).toBe(at);
286+
});
287+
288+
it('refused 503 while SCIM is off, and nothing is stored', async () => {
289+
const off = vi.spyOn(manager, 'isScimWired').mockReturnValue(false);
290+
try {
291+
const res = await door('mint-credential', { connectionId: 'okta-scim-off' });
292+
expect(res.status).toBe(503);
293+
expect(res.body.error.code).toBe('SERVICE_UNAVAILABLE');
294+
expect(await credentialRows('okta-scim-off')).toEqual([]);
295+
} finally {
296+
off.mockRestore();
297+
}
298+
});
299+
});
300+
301+
describe('[#30958] only the platform admin mints or revokes', () => {
302+
it('a signed-in non-admin is refused 403 and an anonymous caller 401, on both doors, and nothing moves', async () => {
303+
const minted = await door('mint-credential', { connectionId: 'okta-gate' });
304+
expect(minted.status).toBe(200);
305+
const { credentialId, token } = minted.body.data;
306+
307+
for (const [caller, status, code] of [[MEMBER, 403, 'PERMISSION_DENIED'], [null, 401, 'UNAUTHENTICATED']] as const) {
308+
session = caller;
309+
const mint = await door('mint-credential', { connectionId: 'okta-gate-refused' });
310+
expect(mint.status, JSON.stringify(mint.body)).toBe(status);
311+
expect(mint.body.error.code).toBe(code);
312+
expect(mint.body.data).toBeUndefined();
313+
const revoke = await door('revoke-credential', { credentialId });
314+
expect(revoke.status, JSON.stringify(revoke.body)).toBe(status);
315+
expect(revoke.body.error.code).toBe(code);
316+
}
317+
session = ADMIN;
318+
319+
expect(await credentialRows('okta-gate-refused')).toEqual([]);
320+
expect(Boolean((await credentialRows('okta-gate'))[0].active)).toBe(true);
321+
expect(await auditRows(credentialId)).toHaveLength(1); // the mint's own, nothing more
322+
expect((await provision(token, 'gate-30958')).status).toBe(201);
323+
}, 30_000);
324+
});
325+
326+
describe('[#30958] revoke: the bearer is refused from the next request on; rotate = mint + revoke', () => {
327+
it('a revoked bearer answers 401, its rotation successor still provisions, and each revoke is audited once', async () => {
328+
const old = (await door('mint-credential', { connectionId: 'okta-rotate' })).body.data;
329+
const next = (await door('mint-credential', { connectionId: 'okta-rotate', label: 'rotation 2' })).body.data;
330+
expect(old.credentialId).not.toBe(next.credentialId);
331+
expect((await provision(old.token, 'rotate-before')).status).toBe(201);
332+
333+
const revoked = await door('revoke-credential', { credentialId: old.credentialId });
334+
expect(revoked.status, JSON.stringify(revoked.body)).toBe(200);
335+
expect(envelopeViolations(revoked.body)).toEqual([]);
336+
expect(revoked.body.data).toEqual({ credentialId: old.credentialId, connectionId: 'okta-rotate', active: false });
337+
338+
const refused = await provision(old.token, 'rotate-after-old');
339+
expect(refused.status).toBe(401);
340+
expect(String(((await refused.json()) as { status?: unknown }).status)).toBe('401');
341+
expect((await provision(next.token, 'rotate-after-new')).status).toBe(201);
342+
343+
// The row is kept, switched off.
344+
const rows = await credentialRows('okta-rotate');
345+
expect(rows).toHaveLength(2);
346+
expect(Boolean(rows.find((r) => r.id === old.credentialId)!.active)).toBe(false);
347+
expect(Boolean(rows.find((r) => r.id === next.credentialId)!.active)).toBe(true);
348+
349+
const audit = await auditRows(old.credentialId);
350+
expect(audit.map((r) => r.action).sort()).toEqual(['create', 'update']);
351+
const revokeRow = audit.find((r) => r.action === 'update')!;
352+
expect(revokeRow).toMatchObject({ user_id: ADMIN.user.id, actor: ADMIN.user.id, object_name: SCIM_CREDENTIAL_OBJECT });
353+
expect(JSON.parse(String(revokeRow.metadata))).toEqual({ event: 'scim_credential_revoked', connectionId: 'okta-rotate' });
354+
355+
// Already revoked: 409, nothing written, no second audit row.
356+
const again = await door('revoke-credential', { credentialId: old.credentialId });
357+
expect(again.status).toBe(409);
358+
expect(again.body.error.code).toBe('RESOURCE_CONFLICT');
359+
expect(await auditRows(old.credentialId)).toHaveLength(2);
360+
361+
await expectSecretNowhereElse(old.token, old.credentialId);
362+
await expectSecretNowhereElse(next.token, next.credentialId);
363+
}, 30_000);
364+
365+
it('an unknown credential is 404, a missing id 400, and revoke serves while SCIM is off', async () => {
366+
const unknown = await door('revoke-credential', { credentialId: 'cred_missing' });
367+
expect(unknown.status).toBe(404);
368+
expect(unknown.body.error.code).toBe('RESOURCE_NOT_FOUND');
369+
const missing = await door('revoke-credential', {});
370+
expect(missing.status).toBe(400);
371+
expect(missing.body.error.code).toBe('INVALID_REQUEST');
372+
373+
const minted = (await door('mint-credential', { connectionId: 'okta-revoke-while-off' })).body.data;
374+
const off = vi.spyOn(manager, 'isScimWired').mockReturnValue(false);
375+
try {
376+
const res = await door('revoke-credential', { credentialId: minted.credentialId });
377+
expect(res.status, JSON.stringify(res.body)).toBe(200);
378+
} finally {
379+
off.mockRestore();
380+
}
381+
expect((await provision(minted.token, 'revoked-while-off')).status).toBe(401);
382+
}, 30_000);
383+
});

0 commit comments

Comments
 (0)