Multiplayer agent harness for work.
Provision administrators after opted-in trusted OIDC sign-in (#1170)
Regan Bell56bbd92ea30c
diff --git a/plugins/portal/README.md b/plugins/portal/README.mdindex e22e0148f..83f11f5aa 100644--- a/plugins/portal/README.md+++ b/plugins/portal/README.md@@ -47,7 +47,16 @@ restrictions do not apply to this separate route.The route verifies OIDC signature, issuer, audience, nonce, PKCE and subject binding,and consumes login state through core's durable replay store. Principals are scopedto the issuer and subject, without automatic linking to email or Slack identities.-No administrator role is assigned. Company login and Slack integration retain their+No administrator role is assigned by default. To provision administrators on this+entry path, set `PORTAL_TRUSTED_OIDC_ADMIN=1` on portal and set core's+`TRUSTED_OIDC_ADMIN_ISSUER` to the exact trusted issuer. This requires a distinct+`PORTAL_IDENTITY_SECRET` and durable replay storage. After verified provider login,+portal submits a short-lived, single-use, purpose-bound assertion; core creates a+normal durable organization-admin grant before portal issues the session. Primary+login and impersonation cannot request this promotion. Deactivated users stay blocked.+Existing sessions need a fresh trusted sign-in. Revoking a grant removes admin access+until the next successful trusted sign-in; disabling provisioning prevents future+grants but does not remove existing ones. Company login and Slack integration retain theirexisting configuration. Deployment CLI secret wiring, account linking, and livequalification are pending; this is not a released deployment feature.diff --git a/plugins/portal/src/index.ts b/plugins/portal/src/index.tsindex 0d59cfe1a..bd515d9e0 100644--- a/plugins/portal/src/index.ts+++ b/plugins/portal/src/index.ts@@ -1,3 +1,4 @@+import { provisionTrustedAdmin } from "./trusted-admin.ts";import { createServer, type IncomingMessage, type ServerResponse } from "node:http";import { pathToFileURL } from "node:url";import { ADMIN_LOGIN_SCRIPT, ADMIN_LOGIN_SCRIPT_HASH, openAdminLogin } from "./admin-login.ts";@@ -205,6 +206,16 @@ const sessionKey = deriveKey(SESSION_SECRET ?? DEV_SECRET, "portal.session.v1");const tmpKey = deriveKey(SESSION_SECRET ?? DEV_SECRET, "portal.tmp.v1");const impersonateKey = deriveKey(SESSION_SECRET ?? DEV_SECRET, "portal.impersonate.v1");const trustedOidc = trustedEntryConfig(process.env, PUBLIC_URL);+const trustedAdminEnabled = process.env.PORTAL_TRUSTED_OIDC_ADMIN === "1";+if (+ trustedAdminEnabled &&+ (!trustedOidc ||+ !CORE_SIGNING_SECRET ||+ !PORTAL_IDENTITY_SECRET ||+ PORTAL_IDENTITY_SECRET.length < 32 ||+ PORTAL_IDENTITY_SECRET === CORE_SIGNING_SECRET)+)+ throw new Error("Trusted administrator provisioning requires trusted OIDC and a distinct portal identity secret");const trustedEntry = trustedOidc? createTrustedEntry(trustedOidc, SESSION_SECRET ?? DEV_SECRET, (key, expiresAt) =>claimOnce(coreClaimStore(CORE, CORE_SIGNING_SECRET, "portal"), key, expiresAt),@@ -1269,6 +1280,19 @@ async function trustedAuth(req: IncomingMessage, res: ServerResponse, url: URL):setSession(res, [clearCookie(cookieName, path, SECURE_COOKIES)]);try {const identity = await trustedEntry.finish(readCookie(req.headers.cookie, cookieName), url);+ if (trustedAdminEnabled) {+ await provisionTrustedAdmin(+ {+ core: CORE,+ signingSecret: CORE_SIGNING_SECRET!,+ identitySecret: PORTAL_IDENTITY_SECRET!,+ org: ORG,+ issuer: trustedOidc!.issuer,+ },+ identity.subject,+ );+ adminCache.delete(identity.sub);+ }setAuthenticatedSession(res, identity.sub, identity.name);res.writeHead(302, {location: sanitizeReturnTo(identity.returnTo, PUBLIC_URL, APPS_DOMAIN),diff --git a/plugins/portal/src/trusted-admin.ts b/plugins/portal/src/trusted-admin.tsnew file mode 100644index 000000000..3ad29fede--- /dev/null+++ b/plugins/portal/src/trusted-admin.ts@@ -0,0 +1,30 @@+import { randomUUID } from "node:crypto";+import { CompactSign } from "jose";+import { signedHeaders, withSourceAuthNonce } from "../../chassis/src/core-client.ts";++export async function provisionTrustedAdmin(+ config: { core: string; signingSecret: string; identitySecret: string; org: string; issuer: string },+ subject: string,+ fetchImpl: typeof fetch = fetch,+): Promise<void> {+ const claims = {+ purpose: "trusted-entry-admin",+ issuer: config.issuer,+ subject,+ org: `org:${config.org}`,+ exp: Date.now() + 60_000,+ jti: randomUUID(),+ };+ const assertion = await new CompactSign(Buffer.from(JSON.stringify(claims)))+ .setProtectedHeader({ alg: "HS256" })+ .sign(Buffer.from(config.identitySecret));+ const path = withSourceAuthNonce("/v1/auth/trusted/admin", config.signingSecret);+ const body = JSON.stringify({ assertion });+ const response = await fetchImpl(`${config.core}${path}`, {+ method: "POST",+ headers: signedHeaders(config.signingSecret, "POST", path, body),+ body,+ signal: AbortSignal.timeout(5_000),+ });+ if (!response.ok) throw new Error("Trusted administrator provisioning failed");+}diff --git a/plugins/portal/src/trusted-entry.ts b/plugins/portal/src/trusted-entry.tsindex f4e2e08ab..3581659cf 100644--- a/plugins/portal/src/trusted-entry.ts+++ b/plugins/portal/src/trusted-entry.ts@@ -84,6 +84,7 @@ export function createTrustedEntry(if (typeof claims.sub !== "string" || claims.sub !== info.sub)throw new Error("Trusted identity subject mismatch");return {+ subject: claims.sub,sub: trustedPrincipal(cfg.issuer, claims.sub),name: typeof info.name === "string" ? info.name.trim().slice(0, 200) : "",returnTo: tmp.returnTo,diff --git a/plugins/portal/test/trusted-admin-routes.test.ts b/plugins/portal/test/trusted-admin-routes.test.tsnew file mode 100644index 000000000..2425f5187--- /dev/null+++ b/plugins/portal/test/trusted-admin-routes.test.ts@@ -0,0 +1,2 @@+process.env.TRUSTED_ADMIN_ROUTE_TEST = "1";+await import("./trusted-entry-routes.test.ts");diff --git a/plugins/portal/test/trusted-entry-routes.test.ts b/plugins/portal/test/trusted-entry-routes.test.tsindex bf3b27d51..b57899449 100644--- a/plugins/portal/test/trusted-entry-routes.test.ts+++ b/plugins/portal/test/trusted-entry-routes.test.ts@@ -3,11 +3,15 @@ import assert from "node:assert/strict";import { createServer } from "node:http";import type { AddressInfo } from "node:net";import { createHash } from "node:crypto";-import { exportJWK, generateKeyPair, SignJWT } from "jose";+import { exportJWK, generateKeyPair, SignJWT, compactVerify } from "jose";import { deriveKey, openSession } from "../src/session.ts";+const adminEnabled = process.env.TRUSTED_ADMIN_ROUTE_TEST === "1";const claims = new Set<string>();let claimAvailable = true;+let adminAvailable = true;+let adminRequests = 0;+const identitySecret = "trusted-route-identity-secret-distinct-32";const codes = new Map<string, { nonce: string; challenge: string }>();const { privateKey, publicKey } = await generateKeyPair("ES256", { extractable: true });let issuer = "";@@ -41,6 +45,19 @@ const upstream = createServer((req, res) => {}if (url.pathname === "/userinfo")return res.end(JSON.stringify({ sub: "person-7", name: "Test Founder", email: "[email protected]" }));+ if (url.pathname === "/v1/auth/trusted/admin") {+ adminRequests++;+ let body = "";+ for await (const chunk of req) body += chunk;+ const { payload } = await compactVerify(JSON.parse(body).assertion, Buffer.from(identitySecret));+ const grant = JSON.parse(Buffer.from(payload).toString());+ assert.equal(grant.purpose, "trusted-entry-admin");+ assert.equal(grant.subject, "person-7");+ assert.equal(grant.issuer, issuer);+ assert.equal(grant.org, "org:test-company");+ res.statusCode = adminAvailable ? 200 : 503;+ return res.end(JSON.stringify({ ok: adminAvailable }));+ }if (url.pathname === "/v1/auth/broker/claim") {if (!claimAvailable) {res.statusCode = 503;@@ -69,6 +86,8 @@ Object.assign(process.env, {CORE_ORG_ID: "test-company",CORE_API_URL: issuer,CORE_SIGNING_SECRET: "test-core-secret",+ PORTAL_IDENTITY_SECRET: identitySecret,+ PORTAL_TRUSTED_OIDC_ADMIN: adminEnabled ? "1" : "0",WEB_UI_UPSTREAM: issuer,ADMIN_UPSTREAM: issuer,OIDC_AUTH_ENDPOINT: "https://primary.example.test/authorize",@@ -105,11 +124,13 @@ async function start() {}test("primary login still selects the original provider", async () => {+ const before = adminRequests;const response = await fetch(`${base}/auth/login`, { redirect: "manual" });const url = new URL(response.headers.get("location")!);assert.equal(url.origin, "https://primary.example.test");assert.equal(url.searchParams.get("client_id"), "primary-client");assert.match(response.headers.getSetCookie()[0]!, /^portal_oidc_tmp=/);+ assert.equal(adminRequests, before);});test("trusted route issues an ordinary scoped session, clears transient cookies, and rejects replay", async () => {@@ -117,6 +138,7 @@ test("trusted route issues an ordinary scoped session, clears transient cookies,const response = await fetch(login.callback, { redirect: "manual", headers: { cookie: login.cookie } });assert.equal(response.status, 302);assert.equal(response.headers.get("location"), "/");+ assert.equal(adminRequests, adminEnabled ? 1 : 0);const cookies = response.headers.getSetCookie();assert.ok(cookies.some((cookie) => cookie.startsWith("portal_trusted_tmp=") && cookie.includes("Max-Age=0")));const sessionCookie = cookies@@ -144,3 +166,15 @@ test("durable claim service failure cannot issue a session", async () => {claimAvailable = true;}});++test("admin provisioning failure cannot issue a session", { skip: !adminEnabled }, async () => {+ const login = await start();+ adminAvailable = false;+ try {+ const response = await fetch(login.callback, { redirect: "manual", headers: { cookie: login.cookie } });+ assert.equal(response.status, 400);+ assert.ok(!response.headers.getSetCookie().some((cookie) => cookie.startsWith("portal_session=")));+ } finally {+ adminAvailable = true;+ }+});diff --git a/src/admin/admin-grant-store.ts b/src/admin/admin-grant-store.tsindex e692f8aed..9d3013f88 100644--- a/src/admin/admin-grant-store.ts+++ b/src/admin/admin-grant-store.ts@@ -19,6 +19,7 @@ export function grantKey(principalId: string, scopeId: ScopeId, role: AdminRole)export interface AdminGrantPersistence {all(): Promise<AdminGrant[]>;put(g: AdminGrant): Promise<void>;+ insertIfAbsent(g: AdminGrant): Promise<boolean>;remove(principalId: string, scopeId: ScopeId, role: AdminRole): Promise<void>;}@@ -32,6 +33,10 @@ export function createMapAdminGrantPersistence(async put(g) {await map.put(grantKey(g.principalId, g.scopeId, g.role), g);},+ async insertIfAbsent(g) {+ if (!map.insertIfAbsent) throw new Error("admin grant storage requires atomic insertion");+ return map.insertIfAbsent(grantKey(g.principalId, g.scopeId, g.role), g);+ },async remove(principalId, scopeId, role) {await map.delete(grantKey(principalId, scopeId, role));},@@ -43,6 +48,7 @@ export const createMemoryAdminGrantPersistence = (): AdminGrantPersistence => crexport interface AdminGrantStore {list(): Promise<AdminGrant[]>;add(g: AdminGrant): Promise<void>;+ addIfAbsent(g: AdminGrant): Promise<boolean>;revoke(principalId: string, scopeId: ScopeId, role: AdminRole): Promise<void>;}@@ -78,6 +84,10 @@ export function createAdminGrantStore(await ensureSeeded();await persist.put(g);},+ async addIfAbsent(g) {+ await ensureSeeded();+ return persist.insertIfAbsent(g);+ },async revoke(principalId, scopeId, role) {await ensureSeeded();await persist.remove(principalId, scopeId, role);diff --git a/src/admin/admin-service.ts b/src/admin/admin-service.tsindex 7b491f1b6..c6d71d4a5 100644--- a/src/admin/admin-service.ts+++ b/src/admin/admin-service.ts@@ -1,3 +1,4 @@+import { createHash } from "node:crypto";import { orgId as configOrgId } from "../config.ts";import type { Principal, ScopeId } from "../types.ts";import { parseScopeId, scopeId } from "../types.ts";@@ -35,6 +36,7 @@ export interface AdminService {canAdminister(principal: Principal, target: ScopeId): Promise<boolean>;adminStatusOf(principal: Principal): Promise<AdminStatus>;listGrants(): Promise<AdminGrant[]>;+ provisionTrustedEntry(issuer: string, subject: string): Promise<{ grant: AdminGrant; created: boolean }>;createGrant(actor: Principal, input: { principalId: string; role: AdminRole; scopeId: ScopeId }): Promise<AdminGrant>;revokeGrant(actor: Principal, principalId: string, scope: ScopeId, role: AdminRole): Promise<void>;}@@ -68,6 +70,7 @@ export function bootAdminGrantSeed(rawAdminGrants: string | undefined, orgId: stexport interface AdminServiceOptions {now?: () => number;+ trustedOidcAdminIssuer?: string;}export function createAdminService(store?: AdminGrantStore, opts: AdminServiceOptions = {}): AdminService {@@ -96,6 +99,24 @@ export function createAdminService(store?: AdminGrantStore, opts: AdminServiceOpasync adminStatusOf(principal) {return adminStatusFromGrants(await grants.list(), principal.id);},+ async provisionTrustedEntry(issuer, subject) {+ if (!opts.trustedOidcAdminIssuer || issuer !== opts.trustedOidcAdminIssuer)+ throw new AdminError(403, "trusted administrator provisioning is not enabled for this issuer");+ if (!subject || subject.length > 255 || Buffer.from(subject).toString("utf8") !== subject)+ throw new AdminError(400, "invalid trusted subject");+ const principalId = `oidc:${createHash("sha256").update(issuer).digest("hex")}:${Buffer.from(subject).toString("base64url")}`;+ const existing = (await grants.list()).find((g) => g.principalId === principalId && g.role === "org_admin");+ if (existing) return { grant: existing, created: false };+ const grant: AdminGrant = {+ principalId,+ role: "org_admin",+ scopeId: scopeId("org", orgId),+ grantedBy: `trusted-oidc:${issuer}`,+ createdAt: now(),+ };+ const created = await grants.addIfAbsent(grant);+ return { grant, created };+ },listGrants() {return grants.list();},diff --git a/src/admin/postgres-admin-grant-store.ts b/src/admin/postgres-admin-grant-store.tsindex 3af1307e4..791308735 100644--- a/src/admin/postgres-admin-grant-store.ts+++ b/src/admin/postgres-admin-grant-store.ts@@ -40,6 +40,15 @@ export function createPostgresAdminGrantStore(connectionString: string): AdminGr[g.principalId, g.scopeId, g.role, g.grantedBy ?? null, g.createdAt ?? null],);},+ async insertIfAbsent(g) {+ const result = await pg.query(+ `INSERT INTO admin_grants (principal_id, scope_id, role, granted_by, created_at)+ VALUES ($1, $2, $3, $4, $5)+ ON CONFLICT (principal_id, scope_id, role) DO NOTHING`,+ [g.principalId, g.scopeId, g.role, g.grantedBy ?? null, g.createdAt ?? null],+ );+ return (result.rowCount ?? 0) > 0;+ },async remove(principalId, scopeId, role) {await pg.query("DELETE FROM admin_grants WHERE principal_id = $1 AND scope_id = $2 AND role = $3", [principalId,diff --git a/src/api/routes/auth-broker.ts b/src/api/routes/auth-broker.tsindex 6e15cc988..aeb486c21 100644--- a/src/api/routes/auth-broker.ts+++ b/src/api/routes/auth-broker.ts@@ -1,6 +1,9 @@+import { createHash } from "node:crypto";+import { verifySignedPayload } from "../../auth/signed-token.ts";+import { AdminError } from "../../admin/admin-service.ts";import { sendJson } from "../http.ts";import { externalMemberActive } from "../../identity/external-members.ts";-import { isObj, authorizeAdmin, orgScope, audit } from "./shared.ts";+import { isObj, authorizeAdmin, orgScope, audit, activePrincipal } from "./shared.ts";import { type ApiCtx, type Route } from "./route.ts";const NAMESPACE = "authbroker:";@@ -98,7 +101,54 @@ async function brokerSession(ctx: ApiCtx): Promise<void> {return sendJson(res, 200, await deps.brokerSessions.create(email, idleS, absoluteS));}+async function trustedAdmin(ctx: ApiCtx): Promise<void> {+ const { deps, res, body } = ctx;+ const secret = deps.portalIdentitySecret;+ if (!secret || secret.length < 32 || secret === ctx.secret || !deps.admin || !deps.replayDedupe?.durable)+ return sendJson(res, 503, { error: "not_configured" });+ const assertion = isObj(body) && typeof body.assertion === "string" ? body.assertion : "";+ const claims = await verifySignedPayload(assertion, secret);+ const now = Date.now();+ if (+ !isObj(claims) ||+ claims.purpose !== "trusted-entry-admin" ||+ claims.org !== orgScope() ||+ typeof claims.issuer !== "string" ||+ typeof claims.subject !== "string" ||+ !claims.subject ||+ claims.subject.length > 255 ||+ claims.imp !== undefined ||+ typeof claims.exp !== "number" ||+ !Number.isFinite(claims.exp) ||+ claims.exp <= now ||+ claims.exp > now + 60_000 ||+ typeof claims.jti !== "string" ||+ !/^[a-f0-9-]{36}$/.test(claims.jti)+ )+ return sendJson(res, 403, { error: "invalid_assertion" });+ const principalId = `oidc:${createHash("sha256").update(claims.issuer).digest("hex")}:${Buffer.from(claims.subject).toString("base64url")}`;+ if (!(await activePrincipal(deps, principalId))) return sendJson(res, 403, { error: "inactive_principal" });+ if (!(await deps.replayDedupe.claim(`trusted-admin:${claims.jti}`, claims.exp)))+ return sendJson(res, 409, { error: "assertion_already_used" });+ try {+ const { grant, created } = await deps.admin.provisionTrustedEntry(claims.issuer, claims.subject);+ if (created)+ audit(deps, {+ principalId: grant.grantedBy!,+ action: "grant.create",+ resource: `${grant.principalId}/org_admin`,+ scopeLabel: grant.scopeId,+ });+ return sendJson(res, 200, { ok: true });+ } catch (error) {+ if (error instanceof AdminError)+ return sendJson(res, error.status, { error: "grant_failed", message: error.message });+ throw error;+ }+}+export const authBrokerRoutes: ReadonlyArray<Route<ApiCtx>> = [+ { method: "POST", path: "/v1/auth/trusted/admin", auth: "source", handle: trustedAdmin },{ method: "POST", path: "/v1/auth/broker/sessions", auth: "source", handle: brokerSession },{ method: "POST", path: "/v1/auth/broker/sessions/use", auth: "source", handle: brokerSession },{ method: "POST", path: "/v1/auth/broker/sessions/revoke", auth: "source", handle: brokerSession },diff --git a/src/api/user-scoped-routes.ts b/src/api/user-scoped-routes.tsindex 495efa5f7..eb90ad3d3 100644--- a/src/api/user-scoped-routes.ts+++ b/src/api/user-scoped-routes.ts@@ -129,6 +129,7 @@ const SYSTEM: Rule[] = [pat("POST", "/v1/blobs"),pat("POST", "/v1/egress-audit"),pat("POST", "/v1/auth/broker/claim"),+ pat("POST", "/v1/auth/trusted/admin"),pat("POST", "/v1/auth/broker/sessions"),pat("POST", "/v1/auth/broker/sessions/use"),pat("PUT", "/v1/deployment-layer"),diff --git a/src/config.ts b/src/config.tsindex e266475e7..2ec51f0da 100644--- a/src/config.ts+++ b/src/config.ts@@ -85,6 +85,7 @@ export interface Config {piSystemCacheSplit: boolean;sessionTapeMode: "shadow" | "serve";adminGrants?: string;+ trustedOidcAdminIssuer?: string;emailAuthPrincipals?: string[];emailAuthDomain?: string;resendApiKey?: string;@@ -1272,6 +1273,7 @@ export function loadConfig(env: NodeJS.ProcessEnv = process.env): Config {...(modelProvider ? { modelProvider } : {}),providerBaseUrls,...(modelGateway ? { modelGateway } : {}),+ ...(env.TRUSTED_OIDC_ADMIN_ISSUER ? { trustedOidcAdminIssuer: env.TRUSTED_OIDC_ADMIN_ISSUER } : {}),...(env.ADMIN_GRANTS ? { adminGrants: env.ADMIN_GRANTS } : {}),...(env.AUTH_ALLOWED_EMAILS? {diff --git a/src/wiring.ts b/src/wiring.tsindex 202923bfa..dc5af77a0 100644--- a/src/wiring.ts+++ b/src/wiring.ts@@ -1367,7 +1367,7 @@ export function buildApp(const adminGrantStore = createAdminGrantStore(adminGrantPersist, {seed: bootAdminGrantSeed(config.adminGrants, config.orgId, !!config.databaseUrl),});- const admin = createAdminService(adminGrantStore);+ const admin = createAdminService(adminGrantStore, { trustedOidcAdminIssuer: config.trustedOidcAdminIssuer });const { strategy: memoryStrategy, memory } = createMemoryStrategy(config.memoryStrategy, {harness: harness.models,memory: baseMemory,diff --git a/test/persistence-init-retry.test.ts b/test/persistence-init-retry.test.tsindex 8c6a7e187..a860da5dc 100644--- a/test/persistence-init-retry.test.ts+++ b/test/persistence-init-retry.test.ts@@ -41,6 +41,9 @@ test("admin grants: a failed seed is retried on the next call (rejection not caclet failures = 1;const rows: AdminGrant[] = [];const persist: AdminGrantPersistence = {+ async insertIfAbsent() {+ throw new Error("not exercised");+ },async all() {if (failures > 0) {failures--;diff --git a/test/postgres-admin-grants.test.ts b/test/postgres-admin-grants.test.tsindex c3754257c..21f178ad3 100644--- a/test/postgres-admin-grants.test.ts+++ b/test/postgres-admin-grants.test.ts@@ -78,3 +78,14 @@ test(assert.deepEqual(ids, ["promoted-at-runtime", "seed-admin"], "redeploy preserves both seed + runtime grants");},);++test("concurrent administrator provisioning preserves the first grant", { skip }, async () => {+ const store = createPostgresAdminGrantStore(URL!);+ const candidates = Array.from({ length: 8 }, (_, i) => grant({ createdAt: i, grantedBy: `issuer-${i}` }));+ const inserted = await Promise.all(candidates.map((g) => store.insertIfAbsent(g)));+ assert.equal(inserted.filter(Boolean).length, 1);+ const winner = candidates[inserted.indexOf(true)]!;+ assert.deepEqual(await store.all(), [winner]);+ assert.equal(await createPostgresAdminGrantStore(URL!).insertIfAbsent(grant({ createdAt: 999 })), false);+ assert.deepEqual(await store.all(), [winner]);+});diff --git a/test/trusted-admin.test.ts b/test/trusted-admin.test.tsnew file mode 100644index 000000000..41b4595c8--- /dev/null+++ b/test/trusted-admin.test.ts@@ -0,0 +1,126 @@+import "./support/auto-fake-sprites.ts";+import test from "node:test";+import assert from "node:assert/strict";+import { mkdtempSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import type { AddressInfo } from "node:net";+import { createServer } from "../src/api/server.ts";+import { buildApp } from "../src/wiring.ts";+import { testConfig } from "./support/test-config.ts";+import { mintSignedPayload } from "../src/auth/signed-token.ts";+import { signRequest } from "../src/auth/source-auth.ts";+import { createMemoryReplayDedupe } from "../src/auth/replay-dedupe.ts";+import { trustedPrincipal } from "../plugins/portal/src/trusted-entry.ts";+import { provisionTrustedAdmin } from "../plugins/portal/src/trusted-admin.ts";++const signingSecret = "core-test-secret".repeat(3);+const identitySecret = "portal-test-secret".repeat(3);+const issuer = "https://identity.example.test";+function start(enabled = true) {+ const built = buildApp(+ testConfig({+ dataDir: mkdtempSync(join(tmpdir(), "trusted-admin-")),+ orgId: "default-org",+ ...(enabled ? { trustedOidcAdminIssuer: issuer } : {}),+ }),+ );+ const server = createServer(built.app, {+ signingSecret,+ capabilitySecret: "capability-secret".repeat(3),+ portalIdentitySecret: identitySecret,+ requireSignedPortalIdentity: true,+ replayDedupe: { ...createMemoryReplayDedupe(), durable: true },+ admin: built.admin,+ identity: built.identity,+ auditLog: built.auditLog,+ });+ server.listen(0);+ return {+ built,+ base: `http://127.0.0.1:${(server.address() as AddressInfo).port}`,+ close: () => new Promise<void>((resolve) => server.close(() => resolve())),+ };+}+function claims(overrides: Record<string, unknown> = {}) {+ return {+ purpose: "trusted-entry-admin",+ issuer,+ subject: "founder-7",+ org: "org:default-org",+ exp: Date.now() + 55_000,+ jti: crypto.randomUUID(),+ ...overrides,+ };+}+async function send(base: string, payload: unknown, key = identitySecret, sourceSigned = true) {+ const path = `/v1/auth/trusted/admin?nonce=${crypto.randomUUID()}`;+ const body = JSON.stringify({ assertion: await mintSignedPayload(payload, key) });+ const ts = Math.floor(Date.now() / 1000);+ return fetch(base + path, {+ method: "POST",+ body,+ headers: {+ "content-type": "application/json",+ ...(sourceSigned+ ? { "x-timestamp": String(ts), "x-signature": signRequest(signingSecret, ts, `POST\n${path}\n${body}`) }+ : {}),+ },+ });+}++test("portal provisioning creates a durable ordinary grant once and preserves existing grants", async (t) => {+ const s = start();+ t.after(s.close);+ const config = { core: s.base, signingSecret, identitySecret, org: "default-org", issuer };+ await Promise.all(Array.from({ length: 8 }, () => provisionTrustedAdmin(config, "founder-7")));+ const principal = { id: trustedPrincipal(issuer, "founder-7"), type: "internal" as const };+ assert.equal((await s.built.admin.adminStatusOf(principal)).isAdmin, true);+ const first = await s.built.admin.listGrants();+ await provisionTrustedAdmin(config, "founder-7");+ assert.deepEqual(await s.built.admin.listGrants(), first);+ assert.equal((await s.built.auditLog.events()).filter((e) => e.action === "grant.create").length, 1);+ assert.equal((await s.built.admin.adminStatusOf({ id: "founder-7", type: "internal" })).isAdmin, false);+ assert.equal((await s.built.admin.adminStatusOf({ id: "[email protected]", type: "internal" })).isAdmin, false);+});++test("provisioning rejects forged, unrelated, expired, impersonated, and replayed assertions", async (t) => {+ const s = start();+ t.after(s.close);+ for (const invalid of [+ { purpose: "session" },+ { org: "org:other" },+ { issuer: "https://other.example.test" },+ { exp: Date.now() - 1 },+ { exp: Date.now() + 120_000 },+ { exp: null },+ { subject: "" },+ { subject: "x".repeat(256) },+ { subject: "\ud800" },+ { imp: "operator" },+ { jti: "" },+ ])+ assert.ok((await send(s.base, claims(invalid))).status >= 400, JSON.stringify(invalid));+ assert.equal((await send(s.base, claims(), signingSecret)).status, 403);+ assert.ok((await send(s.base, claims(), identitySecret, false)).status >= 400);+ assert.equal(+ (await send(s.base, { p: trustedPrincipal(issuer, "founder-7"), exp: Date.now() + 55_000 })).status,+ 403,+ );+ assert.ok(!(await s.built.admin.listGrants()).some((g) => g.principalId.startsWith("oidc:")));+ const payload = claims();+ assert.equal((await send(s.base, payload)).status, 200);+ assert.equal((await send(s.base, payload)).status, 409);+});++test("provisioning needs core opt-in and never reactivates a deactivated founder", async (t) => {+ const disabled = start(false);+ t.after(disabled.close);+ assert.equal((await send(disabled.base, claims())).status, 403);+ const s = start();+ t.after(s.close);+ const id = trustedPrincipal(issuer, "founder-7");+ await s.built.identity.deactivate(id);+ assert.equal((await send(s.base, claims())).status, 403);+ assert.equal((await s.built.admin.adminStatusOf({ id, type: "internal" })).isAdmin, false);+});