// End-to-end test: boots all three services on spare ports and walks the
// whole story — SSO login, consent, token exchange, scopes, revocation.
// Run with: npm test
import { after, before, describe, test } from "node:test";
import assert from "node:assert/strict";
import { mkdtempSync } from "node:fs";
import { tmpdir } from "node:os";
import path from "node:path";
import { randomUUID } from "node:crypto";
import type { Server } from "node:http";
// Settings must exist BEFORE config.ts is imported, hence the dynamic imports below.
process.env.IDP_URL = "http://localhost:5100";
process.env.BROKER_URL = "http://localhost:5101";
process.env.API_URL = "http://localhost:5102";
process.env.KEYS_DIR = mkdtempSync(path.join(tmpdir(), "broker-keys-"));
const { ensureKeys, privateKeyFor } = await import("../src/shared/keys.js");
await ensureKeys();
const { SignJWT, decodeJwt } = await import("jose");
const { createIdpApp } = await import("../src/idp/server.js");
const { createBrokerApp } = await import("../src/broker/server.js");
const { createResourceApp } = await import("../src/resource/server.js");
const { IDP_URL, BROKER_URL, API_URL, ACCESS_TOKEN_TTL_SECONDS } = await import("../src/config.js");
const servers: Server[] = [];
/** A tiny browser: remembers cookies, follows redirects by hand. */
class Browser {
cookies = new Map<string, string>();
async go(url: string, init: RequestInit = {}): Promise<Response> {
const host = new URL(url).host;
const jar = [...this.cookies].filter(([k]) => k.startsWith(host + "|")).map(([k, v]) => `${k.split("|")[1]}=${v}`);
const r = await fetch(url, { ...init, redirect: "manual", headers: { ...(init.headers ?? {}), cookie: jar.join("; ") } });
for (const c of r.headers.getSetCookie()) {
const [pair] = c.split(";");
const [k, v] = pair.split("=");
this.cookies.set(`${host}|${k}`, v);
}
const loc = r.headers.get("location");
return loc && r.status >= 300 && r.status < 400 ? this.go(new URL(loc, url).toString()) : r;
}
post(url: string, form: Record<string, string>) {
return this.go(url, { method: "POST", headers: { "content-type": "application/x-www-form-urlencoded" }, body: new URLSearchParams(form) });
}
}
/** Pull every hidden input of the first <form> out of an HTML page. */
const hiddenInputs = (html: string) =>
Object.fromEntries([...html.matchAll(/name="([^"]+)" value="([^"]*)"/g)].map((m) => [m[1], m[2].replace(/&#(\d+);/g, (_, n) => String.fromCharCode(+n))]));
async function loginOidc(b: Browser, userId: string) {
const loginPage = await (await b.go(`${BROKER_URL}/login/oidc`)).text();
const form = { ...hiddenInputs(loginPage), userId };
return b.post(`${IDP_URL}/authorize/login`, form);
}
async function delegate(b: Browser, scopes: string[], ttl = "3600") {
const body = new URLSearchParams({ agentId: "calendar-assistant", ttl });
scopes.forEach((s) => body.append("scopes", s));
const html = await (await b.go(`${BROKER_URL}/delegate`, {
method: "POST", headers: { "content-type": "application/x-www-form-urlencoded" }, body,
})).text();
return html.match(/dgr_[A-Za-z0-9_-]+/)![0];
}
async function assertion(aud = `${BROKER_URL}/token`) {
return new SignJWT({}).setProtectedHeader({ alg: "ES256" })
.setIssuer("calendar-assistant").setSubject("calendar-assistant").setAudience(aud)
.setIssuedAt().setExpirationTime("60s").setJti(randomUUID())
.sign(await privateKeyFor("agent-calendar-assistant"));
}
async function exchange(handle: string, scope: string, actorToken?: string) {
const r = await fetch(`${BROKER_URL}/token`, {
method: "POST",
headers: { "content-type": "application/x-www-form-urlencoded" },
body: new URLSearchParams({
grant_type: "urn:ietf:params:oauth:grant-type:token-exchange",
subject_token: handle, subject_token_type: "urn:acme:params:oauth:token-type:delegation-grant",
actor_token: actorToken ?? (await assertion()), actor_token_type: "urn:ietf:params:oauth:token-type:jwt",
audience: API_URL, scope,
}),
});
return { status: r.status, body: (await r.json()) as Record<string, string> };
}
const api = (token: string, method = "GET") =>
fetch(`${API_URL}/calendar/events`, {
method, headers: { authorization: `Bearer ${token}`, "content-type": "application/json" },
body: method === "POST" ? JSON.stringify({ title: "t" }) : undefined,
});
before(async () => {
const start = (app: ReturnType<typeof createIdpApp>, url: string) =>
new Promise<void>((ok) => servers.push(app.listen(Number(new URL(url).port), () => ok())));
await start(createIdpApp(), IDP_URL);
await start(createBrokerApp(), BROKER_URL);
await start(createResourceApp(), API_URL);
});
after(() => servers.forEach((s) => { s.closeAllConnections(); s.close(); }));
describe("Enterprise SSO & Agent Delegation Broker", () => {
test("OIDC login → consent → 5-minute scoped token → API call", async () => {
const alice = new Browser();
const home = await (await loginOidc(alice, "u-alice")).text();
assert.match(home, /Signed in as <b>Alice Anand/);
const handle = await delegate(alice, ["calendar:read", "calendar:write"]);
const { status, body } = await exchange(handle, "calendar:read");
assert.equal(status, 200);
const claims = decodeJwt(body.access_token);
assert.equal(claims.exp! - claims.iat!, ACCESS_TOKEN_TTL_SECONDS, "token lives exactly 5 minutes");
assert.equal(claims.sub, "u-alice");
assert.deepEqual(claims.act, { sub: "calendar-assistant" });
assert.equal(claims.scope, "calendar:read", "down-scoped to only what was asked");
const list = await api(body.access_token);
assert.equal(list.status, 200);
const data = (await list.json()) as { events: { owner: string }[] };
assert.ok(data.events.every((e) => e.owner === "u-alice"), "agent only sees Alice's data");
assert.equal((await api(body.access_token, "POST")).status, 403, "read token cannot write");
const write = await exchange(handle, "calendar:write");
assert.equal((await api(write.body.access_token, "POST")).status, 201);
});
test("SAML login works and a tampered assertion is rejected", async () => {
const bob = new Browser();
const idpPage = await (await bob.go(`${BROKER_URL}/login/saml`)).text();
const posted = await (await bob.post(`${IDP_URL}/saml/login`, { ...hiddenInputs(idpPage), userId: "u-bob" })).text();
const { SAMLResponse, RelayState } = hiddenInputs(posted);
const evil = Buffer.from(Buffer.from(SAMLResponse, "base64").toString().replace("u-bob", "u-alice")).toString("base64");
const rejected = await bob.post(`${BROKER_URL}/saml/acs`, { SAMLResponse: evil, RelayState });
assert.equal(rejected.status, 401, "signature check catches tampering");
// Fresh attempt with the genuine assertion (new RelayState cookie).
const page2 = await (await bob.go(`${BROKER_URL}/login/saml`)).text();
const posted2 = await (await bob.post(`${IDP_URL}/saml/login`, { ...hiddenInputs(page2), userId: "u-bob" })).text();
const ok = await bob.post(`${BROKER_URL}/saml/acs`, hiddenInputs(posted2));
assert.match(await ok.text(), /Signed in as <b>Bob Banerjee.*SAML/s);
});
test("users can't delegate scopes they don't have themselves", async () => {
const bob = new Browser();
await loginOidc(bob, "u-bob"); // Bob is in "sales", not "calendar-power-users"
const handle = await delegate(bob, ["calendar:read", "calendar:write"]);
assert.equal((await exchange(handle, "calendar:write")).status, 400);
});
test("a stolen grant handle is useless without the agent's key; assertions can't be replayed", async () => {
const alice = new Browser();
await loginOidc(alice, "u-alice");
const handle = await delegate(alice, ["calendar:read"]);
const forged = await new SignJWT({}).setProtectedHeader({ alg: "HS256" }).setIssuer("calendar-assistant")
.setSubject("calendar-assistant").setAudience(`${BROKER_URL}/token`).setIssuedAt().setExpirationTime("60s")
.setJti(randomUUID()).sign(new TextEncoder().encode("guessed-secret-guessed-secret-32b"));
assert.equal((await exchange(handle, "calendar:read", forged)).status, 401);
const once = await assertion();
assert.equal((await exchange(handle, "calendar:read", once)).status, 200);
assert.equal((await exchange(handle, "calendar:read", once)).status, 401, "replay blocked");
});
test("manual revocation kills a live token immediately", async () => {
const alice = new Browser();
await loginOidc(alice, "u-alice");
const handle = await delegate(alice, ["calendar:read"]);
const { body } = await exchange(handle, "calendar:read");
assert.equal((await api(body.access_token)).status, 200);
const jti = String(decodeJwt(body.access_token).jti);
await alice.post(`${BROKER_URL}/tokens/${jti}/revoke`, {});
assert.equal((await api(body.access_token)).status, 401, "still unexpired, but revoked");
});
test("automatic revocation: scope-escalation tripwire", async () => {
const alice = new Browser();
await loginOidc(alice, "u-alice");
const handle = await delegate(alice, ["calendar:read"]);
const good = await exchange(handle, "calendar:read");
assert.equal((await exchange(handle, "calendar:read mail:send")).status, 400);
assert.equal((await exchange(handle, "calendar:read")).body.error, "invalid_grant", "grant is dead");
assert.equal((await api(good.body.access_token)).status, 401, "earlier tokens die too");
});
test("automatic revocation: IdP deprovisioning pushes a security event", async () => {
const alice = new Browser();
await loginOidc(alice, "u-alice");
const handle = await delegate(alice, ["calendar:read"]);
const { body } = await exchange(handle, "calendar:read");
await new Browser().post(`${IDP_URL}/admin/users/u-alice/deprovision`, {});
assert.equal((await api(body.access_token)).status, 401);
assert.equal((await exchange(handle, "calendar:read")).status, 400);
assert.doesNotMatch(await (await alice.go(`${BROKER_URL}/`)).text(), /Signed in as/, "session killed");
await new Browser().post(`${IDP_URL}/admin/users/u-alice/reactivate`, {});
});
test("forged security events are ignored", async () => {
const r = await fetch(`${BROKER_URL}/events`, {
method: "POST", headers: { "content-type": "application/secevent+jwt" }, body: "not.a.jwt",
});
assert.equal(r.status, 400);
});
});