diff --git a/packages/api/migrations/0034_run_enrollments.sql b/packages/api/migrations/0034_run_enrollments.sql new file mode 100644 index 00000000..ed9c0aaf --- /dev/null +++ b/packages/api/migrations/0034_run_enrollments.sql @@ -0,0 +1,38 @@ +CREATE TABLE app.credential_proxy_states ( + tenant_id uuid PRIMARY KEY REFERENCES app.tenants(id) ON DELETE CASCADE, + proxy_identity text NOT NULL, + boot_epoch uuid NOT NULL, + disabled_at timestamptz, + revoked_at timestamptz, + updated_at timestamptz NOT NULL DEFAULT now() +); + +CREATE TABLE app.credential_run_grants ( + tenant_id uuid NOT NULL, + run_id uuid NOT NULL, + vm_identity text NOT NULL, + proxy_identity text NOT NULL, + boot_epoch uuid NOT NULL, + grant_revision bigint NOT NULL CHECK (grant_revision > 0), + revoked_at timestamptz, + created_at timestamptz NOT NULL DEFAULT now(), + PRIMARY KEY (tenant_id, run_id), + FOREIGN KEY (tenant_id, run_id) REFERENCES app.job_runs(tenant_id, id) ON DELETE CASCADE +); + +CREATE TABLE app.credential_run_enrollments ( + tenant_id uuid NOT NULL, + id uuid NOT NULL, + run_id uuid NOT NULL, + token_digest bytea NOT NULL UNIQUE, + vm_identity text NOT NULL, + proxy_identity text NOT NULL, + boot_epoch uuid NOT NULL, + grant_revision bigint NOT NULL CHECK (grant_revision > 0), + expires_at timestamptz NOT NULL, + consumed_at timestamptz, + created_at timestamptz NOT NULL DEFAULT now(), + PRIMARY KEY (tenant_id, id), + FOREIGN KEY (tenant_id, run_id) REFERENCES app.credential_run_grants(tenant_id, run_id) ON DELETE CASCADE +); +CREATE INDEX credential_run_enrollments_expiry ON app.credential_run_enrollments(expires_at) WHERE consumed_at IS NULL; diff --git a/packages/api/src/postgres/run-enrollment-repository.ts b/packages/api/src/postgres/run-enrollment-repository.ts new file mode 100644 index 00000000..328ad692 --- /dev/null +++ b/packages/api/src/postgres/run-enrollment-repository.ts @@ -0,0 +1,103 @@ +import type { Database } from "./database"; + +export type RunEnrollmentBinding = { + tenantId: string; + runId: string; + vmIdentity: string; + proxyIdentity: string; + bootEpoch: string; +}; + +export type ConsumedRunEnrollment = RunEnrollmentBinding & { grantRevision: number; enrollmentId: string }; + +const uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; +function validateBinding(binding: RunEnrollmentBinding): void { + if (!uuid.test(binding.tenantId) || !uuid.test(binding.runId) || !uuid.test(binding.bootEpoch)) throw new TypeError("Enrollment tenant, run, and boot epoch must be UUIDs"); + for (const [name, value] of [["vmIdentity", binding.vmIdentity], ["proxyIdentity", binding.proxyIdentity]] as const) { + if (typeof value !== "string" || !value.trim() || value.length > 255) throw new TypeError(`${name} must contain 1 to 255 characters`); + } +} + +const digest = async (token: string) => new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(token))); +const activeStates = "('starting','running','blocked')"; + +/** Durable, one-use enrollments. Only a SHA-256 digest of each random token is stored. */ +export class RunEnrollmentRepository { + constructor(private database: Database) {} + + async setProxyState(input: { tenantId: string; proxyIdentity: string; bootEpoch: string; disabled?: boolean; revoked?: boolean }): Promise { + if (!uuid.test(input.tenantId) || !uuid.test(input.bootEpoch)) throw new TypeError("tenantId and bootEpoch must be UUIDs"); + if (!input.proxyIdentity.trim() || input.proxyIdentity.length > 255) throw new TypeError("proxyIdentity must contain 1 to 255 characters"); + await this.database.pool.query(`INSERT INTO app.credential_proxy_states(tenant_id,proxy_identity,boot_epoch,disabled_at,revoked_at) + VALUES ($1,$2,$3,CASE WHEN $4 THEN now() END,CASE WHEN $5 THEN now() END) + ON CONFLICT (tenant_id) DO UPDATE SET proxy_identity=excluded.proxy_identity,boot_epoch=excluded.boot_epoch,disabled_at=excluded.disabled_at,revoked_at=excluded.revoked_at,updated_at=now()`, + [input.tenantId, input.proxyIdentity, input.bootEpoch, input.disabled ?? false, input.revoked ?? false]); + } + + async authorizeRun(binding: RunEnrollmentBinding, grantRevision: number): Promise { + validateBinding(binding); + if (!Number.isSafeInteger(grantRevision) || grantRevision < 1) throw new TypeError("grantRevision must be a positive safe integer"); + return this.database.transaction(async client => { + const valid = await client.query(`SELECT 1 FROM app.job_runs r JOIN app.credential_proxy_states p ON p.tenant_id=r.tenant_id + WHERE r.tenant_id=$1 AND r.id=$2 AND r.state IN ${activeStates} AND p.proxy_identity=$3 AND p.boot_epoch=$4 AND p.disabled_at IS NULL AND p.revoked_at IS NULL`, + [binding.tenantId, binding.runId, binding.proxyIdentity, binding.bootEpoch]); + if (!valid.rowCount) return false; + const saved = await client.query(`INSERT INTO app.credential_run_grants(tenant_id,run_id,vm_identity,proxy_identity,boot_epoch,grant_revision,revoked_at) + VALUES ($1,$2,$3,$4,$5,$6,NULL) ON CONFLICT (tenant_id,run_id) DO UPDATE SET vm_identity=excluded.vm_identity,proxy_identity=excluded.proxy_identity,boot_epoch=excluded.boot_epoch,grant_revision=excluded.grant_revision,revoked_at=NULL + WHERE app.credential_run_grants.grant_revision < excluded.grant_revision RETURNING grant_revision`, + [binding.tenantId, binding.runId, binding.vmIdentity, binding.proxyIdentity, binding.bootEpoch, grantRevision]); + if (saved.rowCount) return true; + const current = await client.query(`SELECT 1 FROM app.credential_run_grants WHERE tenant_id=$1 AND run_id=$2 AND vm_identity=$3 AND proxy_identity=$4 AND boot_epoch=$5 AND grant_revision=$6 AND revoked_at IS NULL`, + [binding.tenantId, binding.runId, binding.vmIdentity, binding.proxyIdentity, binding.bootEpoch, grantRevision]); + return Boolean(current.rowCount); + }); + } + + async revokeRun(tenantId: string, runId: string): Promise { + const result = await this.database.pool.query("UPDATE app.credential_run_grants SET revoked_at=now() WHERE tenant_id=$1 AND run_id=$2 AND revoked_at IS NULL", [tenantId, runId]); + return Boolean(result.rowCount); + } + + async issue(binding: RunEnrollmentBinding, expiresAt: Date, now = new Date()): Promise<{ enrollmentId: string; token: string; grantRevision: number } | null> { + validateBinding(binding); + if (!(expiresAt instanceof Date) || !Number.isFinite(expiresAt.getTime()) || expiresAt <= now) throw new TypeError("expiresAt must be in the future"); + const token = Buffer.from(crypto.getRandomValues(new Uint8Array(32))).toString("base64url"); + const tokenDigest = await digest(token), enrollmentId = crypto.randomUUID(); + const result = await this.database.transaction(async client => { + const rows = await client.query<{ grant_revision: string | number }>(`SELECT g.grant_revision FROM app.credential_run_grants g + JOIN app.credential_proxy_states p ON p.tenant_id=g.tenant_id + JOIN app.job_runs r ON r.tenant_id=g.tenant_id AND r.id=g.run_id + WHERE g.tenant_id=$1 AND g.run_id=$2 AND g.vm_identity=$3 AND g.proxy_identity=$4 AND g.boot_epoch=$5 + AND g.revoked_at IS NULL AND p.proxy_identity=g.proxy_identity AND p.boot_epoch=g.boot_epoch + AND p.disabled_at IS NULL AND p.revoked_at IS NULL AND r.state IN ${activeStates} + FOR UPDATE OF g,p,r`, [binding.tenantId, binding.runId, binding.vmIdentity, binding.proxyIdentity, binding.bootEpoch]); + const revision = rows.rows[0]?.grant_revision; + if (revision === undefined) return null; + await client.query("UPDATE app.credential_run_enrollments SET consumed_at=$3 WHERE tenant_id=$1 AND run_id=$2 AND consumed_at IS NULL", [binding.tenantId, binding.runId, now]); + await client.query(`INSERT INTO app.credential_run_enrollments(tenant_id,id,run_id,token_digest,vm_identity,proxy_identity,boot_epoch,grant_revision,expires_at) + VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9)`, [binding.tenantId, enrollmentId, binding.runId, Buffer.from(tokenDigest), binding.vmIdentity, binding.proxyIdentity, binding.bootEpoch, revision, expiresAt]); + return Number(revision); + }); + return result === null ? null : { enrollmentId, token, grantRevision: result }; + } + + async consume(token: string, binding: RunEnrollmentBinding, now = new Date()): Promise { + validateBinding(binding); + if (typeof token !== "string" || token.length < 32 || token.length > 128 || !Number.isFinite(now.getTime())) return null; + const tokenDigest = Buffer.from(await digest(token)); + return this.database.transaction(async client => { + const result = await client.query<{ id: string; grant_revision: string | number }>(`UPDATE app.credential_run_enrollments e + SET consumed_at=$7 + FROM app.credential_run_grants g, app.credential_proxy_states p, app.job_runs r + WHERE e.tenant_id=$1 AND e.token_digest=$2 AND e.run_id=$3 AND e.vm_identity=$4 AND e.proxy_identity=$5 AND e.boot_epoch=$6 + AND e.consumed_at IS NULL AND e.expires_at>$7 + AND g.tenant_id=e.tenant_id AND g.run_id=e.run_id AND g.vm_identity=e.vm_identity AND g.proxy_identity=e.proxy_identity AND g.boot_epoch=e.boot_epoch + AND g.grant_revision=e.grant_revision AND g.revoked_at IS NULL + AND p.tenant_id=e.tenant_id AND p.proxy_identity=e.proxy_identity AND p.boot_epoch=e.boot_epoch AND p.disabled_at IS NULL AND p.revoked_at IS NULL + AND r.tenant_id=e.tenant_id AND r.id=e.run_id AND r.state IN ${activeStates} + RETURNING e.id,e.grant_revision`, [binding.tenantId, tokenDigest, binding.runId, binding.vmIdentity, binding.proxyIdentity, binding.bootEpoch, now]); + const row = result.rows[0]; + return row ? { ...binding, enrollmentId: row.id, grantRevision: Number(row.grant_revision) } : null; + }); + } +} diff --git a/packages/api/src/postgres/schema.ts b/packages/api/src/postgres/schema.ts index f478ad50..7330a743 100644 --- a/packages/api/src/postgres/schema.ts +++ b/packages/api/src/postgres/schema.ts @@ -50,6 +50,15 @@ export const integrationRecords = app.table("integration_records", { export const integrationChanges = app.table("integration_changes", { tenantId: uuid("tenant_id").notNull().references(() => integrationCollections.tenantId, { onDelete: "cascade" }), revision: bigint("revision", { mode: "number" }).notNull(), id: uuid("id").notNull(), idempotencyKey: uuid("idempotency_key").notNull(), operation: text("operation").$type<"upsert" | "delete">().notNull(), recordId: uuid("record_id").notNull(), kind: text("kind").$type<"bearer" | "model">().notNull(), name: text("name").notNull(), origin: text("origin"), description: text("description"), encryptedPayload: text("encrypted_payload"), createdAt: createdAt(), }, t => [primaryKey({ columns: [t.tenantId, t.revision] }), unique().on(t.tenantId, t.idempotencyKey), index("integration_changes_page").on(t.tenantId, t.revision), check("integration_changes_operation_check", sql`${t.operation} IN ('upsert','delete')`), check("integration_changes_kind_check", sql`${t.kind} IN ('bearer','model')`), check("integration_changes_origin_check", sql`(${t.kind} = 'bearer' AND ${t.origin} IS NOT NULL) OR (${t.kind} = 'model' AND ${t.origin} IS NULL)`), check("integration_changes_payload_check", sql`(${t.operation} = 'upsert' AND ${t.encryptedPayload} IS NOT NULL) OR (${t.operation} = 'delete' AND ${t.encryptedPayload} IS NULL)`)]); +export const credentialProxyStates = app.table("credential_proxy_states", { + tenantId: uuid("tenant_id").primaryKey().references(() => tenants.id, { onDelete: "cascade" }), proxyIdentity: text("proxy_identity").notNull(), bootEpoch: uuid("boot_epoch").notNull(), disabledAt: timestamp("disabled_at", { withTimezone: true }), revokedAt: timestamp("revoked_at", { withTimezone: true }), updatedAt: updatedAt(), +}); +export const credentialRunGrants = app.table("credential_run_grants", { + tenantId: uuid("tenant_id").notNull(), runId: uuid("run_id").notNull(), vmIdentity: text("vm_identity").notNull(), proxyIdentity: text("proxy_identity").notNull(), bootEpoch: uuid("boot_epoch").notNull(), grantRevision: bigint("grant_revision", { mode: "number" }).notNull(), revokedAt: timestamp("revoked_at", { withTimezone: true }), createdAt: createdAt(), +}, t => [primaryKey({ columns: [t.tenantId, t.runId] }), foreignKey({ columns: [t.tenantId, t.runId], foreignColumns: [jobRuns.tenantId, jobRuns.id] }).onDelete("cascade"), check("credential_run_grants_revision_check", sql`${t.grantRevision} > 0`)]); +export const credentialRunEnrollments = app.table("credential_run_enrollments", { + tenantId: uuid("tenant_id").notNull(), id: uuid("id").notNull(), runId: uuid("run_id").notNull(), tokenDigest: bytea("token_digest").notNull(), vmIdentity: text("vm_identity").notNull(), proxyIdentity: text("proxy_identity").notNull(), bootEpoch: uuid("boot_epoch").notNull(), grantRevision: bigint("grant_revision", { mode: "number" }).notNull(), expiresAt: timestamp("expires_at", { withTimezone: true }).notNull(), consumedAt: timestamp("consumed_at", { withTimezone: true }), createdAt: createdAt(), +}, t => [primaryKey({ columns: [t.tenantId, t.id] }), unique().on(t.tokenDigest), foreignKey({ columns: [t.tenantId, t.runId], foreignColumns: [credentialRunGrants.tenantId, credentialRunGrants.runId] }).onDelete("cascade"), index("credential_run_enrollments_expiry").on(t.expiresAt).where(sql`${t.consumedAt} is null`), check("credential_run_enrollments_revision_check", sql`${t.grantRevision} > 0`)]); export const linearWorkspaces = app.table("linear_workspaces", { organizationId: uuid("organization_id").primaryKey(), tenantId: uuid("tenant_id").notNull().unique().references(() => tenants.id, { onDelete: "cascade" }) }); export const githubInstallations = app.table("github_installations", { installationId: bigint("installation_id", { mode: "number" }).primaryKey(), tenantId: uuid("tenant_id").notNull().references(() => tenants.id, { onDelete: "cascade" }), accountLogin: text("account_login").notNull(), accountType: text("account_type").notNull(), state: text("state").$type<"active" | "suspended">().notNull(), updatedAt: updatedAt() }, t => [unique().on(t.tenantId, t.installationId), check("github_installations_state_check", sql`${t.state} in ('active','suspended')`)]); export const githubSetupStates = app.table("github_setup_states", { tenantId: uuid("tenant_id").notNull().references(() => tenants.id, { onDelete: "cascade" }), nonce: text("nonce").notNull(), expiresAt: timestamp("expires_at", { withTimezone: true }).notNull(), usedAt: timestamp("used_at", { withTimezone: true }) }, t => [primaryKey({ columns: [t.tenantId, t.nonce] })]); @@ -146,7 +155,7 @@ export const runRelations = relations(runs, ({ one, many }) => ({ export const databaseSchema = { schemaMigrations, tenants, oauthConnections, oauthConsentPreviews, authUsers, authAccounts, authResetTokens, authSessions, oauthDeviceAuthorizations, members, accessTokens, - connections, integrationCollections, integrationRecords, integrationChanges, linearWorkspaces, githubInstallations, githubSetupStates, projects, jobs, vmImageVerifications, skills, jobSkills, triggers, webhookConditionsCutover, invocations, manualInvocationPermissions, jobRuns, runCredentials, runs, runArtifacts, + connections, integrationCollections, integrationRecords, integrationChanges, credentialProxyStates, credentialRunGrants, credentialRunEnrollments, linearWorkspaces, githubInstallations, githubSetupStates, projects, jobs, vmImageVerifications, skills, jobSkills, triggers, webhookConditionsCutover, invocations, manualInvocationPermissions, jobRuns, runCredentials, runs, runArtifacts, runTraceEvents, runActivity, activeClaims, scheduleState, automaticWakes, lifecycleDeliveries, lifecycleEvents, jobEditDeliveries, jobEvents, webhookDeliveries, webhookDeliveryEvents, pendingVerifications, tailFingerprints, wakeHints, runTraceCursors, runTraceChunks, runTraceProjections, traceReplayLimits, traceReplayOperations, diff --git a/packages/api/src/run-enrollment-service.ts b/packages/api/src/run-enrollment-service.ts new file mode 100644 index 00000000..f35dba67 --- /dev/null +++ b/packages/api/src/run-enrollment-service.ts @@ -0,0 +1,22 @@ +import type { RunEnrollmentBinding, ConsumedRunEnrollment, RunEnrollmentRepository } from "./postgres/run-enrollment-repository"; + +export class RunEnrollmentUnavailableError extends Error { + constructor() { super("Run enrollment is expired, revoked, disabled, or no longer active"); this.name = "RunEnrollmentUnavailableError"; } +} + +/** Control path used by Factorize to issue a one-use token and authenticate its proxy redemption. */ +export class RunEnrollmentService { + constructor(private repository: RunEnrollmentRepository) {} + + async enroll(binding: RunEnrollmentBinding, expiresAt: Date, now = new Date()): Promise<{ enrollmentId: string; token: string; grantRevision: number }> { + const enrollment = await this.repository.issue(binding, expiresAt, now); + if (!enrollment) throw new RunEnrollmentUnavailableError(); + return enrollment; + } + + async authenticate(token: string, binding: RunEnrollmentBinding, now = new Date()): Promise { + const enrollment = await this.repository.consume(token, binding, now); + if (!enrollment) throw new RunEnrollmentUnavailableError(); + return enrollment; + } +} diff --git a/packages/api/test/fly-machines-client.test.ts b/packages/api/test/fly-machines-client.test.ts index bc39fe14..9b5bf80c 100644 --- a/packages/api/test/fly-machines-client.test.ts +++ b/packages/api/test/fly-machines-client.test.ts @@ -116,31 +116,29 @@ describe("bounded Fly Machines client", () => { it("times out a stalled response and reconciles an ambiguous create by operation id", async () => { const machines: FlyMachine[] = []; let createCount = 0; - let markCreateReceived!: () => void; - const createReceived = new Promise(resolve => { markCreateReceived = resolve; }); + let markCommitted!: () => void; + const committed = new Promise(resolve => { markCommitted = resolve; }); const origin = await fakeFly(async (req, res) => { if (req.method === "GET") return json(res, 200, machines); if (req.method === "POST") { createCount++; - markCreateReceived(); let raw = ""; for await (const chunk of req) raw += chunk; const body = JSON.parse(raw); const machine = { id: "m-created", config: body.config }; machines.push(machine); + markCommitted(); + markCommitted(); // Commit the resource but leave the response stalled past the client's deadline. res.writeHead(200, { "content-type": "application/json" }); } }); - const client = createFlyMachinesClient({ token, apiOrigin: origin, timeoutMs: 1_000, maxRetries: 0 }); + const client = createFlyMachinesClient({ token, apiOrigin: origin, timeoutMs: 250, maxRetries: 0 }); + const creation = client.createMachine("app", { image: "image" }, "op-ambiguous"); let deadline: ReturnType | undefined; - let created: FlyMachine; try { - const creation = client.createMachine("app", { image: "image" }, "op-ambiguous"); - await Promise.race([createReceived, new Promise((_, reject) => { - deadline = setTimeout(() => reject(new Error("Fake Fly server did not receive the ambiguous create")), 5_000); - })]); - created = await creation; + await Promise.race([committed, new Promise((_, reject) => { deadline = setTimeout(() => reject(new Error("Fake Fly server did not commit the bounded create")), 5_000); })]); } finally { if (deadline) clearTimeout(deadline); } + const created = await creation; expect(created.id).toBe("m-created"); expect(createCount).toBe(1); }); diff --git a/packages/api/test/run-enrollment.postgres.test.ts b/packages/api/test/run-enrollment.postgres.test.ts new file mode 100644 index 00000000..a23277e2 --- /dev/null +++ b/packages/api/test/run-enrollment.postgres.test.ts @@ -0,0 +1,92 @@ +import { afterAll, beforeAll, describe, expect, it } from "vitest"; +import { Database } from "../src/postgres/database"; +import { RunEnrollmentRepository, type RunEnrollmentBinding } from "../src/postgres/run-enrollment-repository"; +import { RunEnrollmentService } from "../src/run-enrollment-service"; + +const url = process.env.AUTH_TEST_DATABASE_URL; + +describe.skipIf(!url)("single-use run enrollments (PostgreSQL)", () => { + let db: Database; + const tenants: string[] = []; + beforeAll(async () => { + db = new Database({ connectionString: url, max: 24, maxUses: Infinity }); + expect((await db.pool.query("SELECT to_regclass('app.credential_run_enrollments') AS enrollments")).rows[0]?.enrollments).toBe("app.credential_run_enrollments"); + }, 30_000); + afterAll(async () => { if (db) { await db.pool.query("DELETE FROM app.tenants WHERE id=ANY($1::uuid[])", [tenants]); await db.close(); } }); + + async function fixture(state = "running") { + const tenantId = crypto.randomUUID(), jobId = crypto.randomUUID(), triggerId = crypto.randomUUID(), invocationId = crypto.randomUUID(), runId = crypto.randomUUID(); + const proxyIdentity = `proxy-${crypto.randomUUID()}`, bootEpoch = crypto.randomUUID(), vmIdentity = `vm-${crypto.randomUUID()}`; + tenants.push(tenantId); + await db.pool.query("INSERT INTO app.tenants(id) VALUES ($1)", [tenantId]); + await db.pool.query("INSERT INTO app.projects(tenant_id,id,name) VALUES ($1,md5(($1::uuid)::text || ':default')::uuid,'Default')", [tenantId]); + await db.pool.query("INSERT INTO app.jobs(tenant_id,id,project_id,name,slug,encrypted_prompt_template,execution_config,concurrency_limit) VALUES ($1,$2,md5(($1::uuid)::text || ':default')::uuid,'Enrollment test','enrollment-test','test','{}',1)", [tenantId, jobId]); + await db.pool.query("INSERT INTO app.triggers(tenant_id,id,job_id,kind,slug) VALUES ($1,$2,$3,'manual','manual')", [tenantId, triggerId, jobId]); + await db.pool.query("INSERT INTO app.invocations(tenant_id,id,job_id,source,claim_key,trigger_id,context) VALUES ($1,$2,$3,'manual','enrollment-test',$4,'{}')", [tenantId, invocationId, jobId, triggerId]); + await db.pool.query("INSERT INTO app.job_runs(tenant_id,id,job_id,invocation_id,state,encrypted_prompt) VALUES ($1,$2,$3,$4,$5,'test')", [tenantId, runId, jobId, invocationId, state]); + const binding: RunEnrollmentBinding = { tenantId, runId, vmIdentity, proxyIdentity, bootEpoch }; + const repository = new RunEnrollmentRepository(db); + const service = new RunEnrollmentService(repository); + await repository.setProxyState({ tenantId, proxyIdentity, bootEpoch }); + expect(await repository.authorizeRun(binding, 7)).toBe(true); + return { binding, repository, service, tenantId, runId, proxyIdentity, bootEpoch }; + } + async function enrollment(f: Awaited>, lifetime = 60_000) { + const now = new Date("2030-01-01T00:00:00.000Z"); + const issued = await f.service.enroll(f.binding, new Date(now.getTime() + lifetime), now); + return { ...issued, now }; + } + + it("atomically consumes one token once across barrier-synchronized concurrent callers", async () => { + const f = await fixture(), issued = await enrollment(f), count = 24; + let arrivals = 0, release!: () => void; + const barrier = new Promise(resolve => { release = resolve; }); + const results = await Promise.allSettled(Array.from({ length: count }, async () => { + arrivals += 1; + if (arrivals === count) release(); + await barrier; + return f.service.authenticate(issued.token, f.binding, issued.now); + })); + expect(results.filter(result => result.status === "fulfilled")).toHaveLength(1); + expect(results.filter(result => result.status === "rejected")).toHaveLength(count - 1); + const persisted = (await db.pool.query("SELECT token_digest,consumed_at,grant_revision FROM app.credential_run_enrollments WHERE tenant_id=$1 AND id=$2", [f.tenantId, issued.enrollmentId])).rows[0]; + expect(persisted.token_digest.toString("base64url")).not.toBe(issued.token); + expect(persisted.consumed_at).toEqual(issued.now); + expect(persisted.grant_revision).toBe("7"); + }, 20_000); + + it("rejects expiry, disconnect replay, a changed proxy epoch, ended runs, cross-tenant use, and revoked or disabled grants", async () => { + const now = new Date("2030-01-01T00:00:00.000Z"); + const expired = await fixture(), old = await enrollment(expired, 1); + await expect(expired.service.authenticate(old.token, expired.binding, new Date(now.getTime() + 1))).rejects.toThrow(); + + const disconnected = await fixture(), lost = await enrollment(disconnected); + const reconnected = await enrollment(disconnected); + await expect(disconnected.service.authenticate(lost.token, disconnected.binding, lost.now)).rejects.toThrow(); + await expect(disconnected.service.authenticate(reconnected.token, disconnected.binding, reconnected.now)).resolves.toMatchObject({ grantRevision: 7 }); + await expect(disconnected.service.authenticate(reconnected.token, disconnected.binding, reconnected.now)).rejects.toThrow(); + + const revised = await fixture(), priorRevision = await enrollment(revised); + expect(await revised.repository.authorizeRun(revised.binding, 8)).toBe(true); + await expect(revised.service.authenticate(priorRevision.token, revised.binding, priorRevision.now)).rejects.toThrow(); + + const restarted = await fixture(), oldEpoch = await enrollment(restarted); + await restarted.repository.setProxyState({ tenantId: restarted.tenantId, proxyIdentity: restarted.proxyIdentity, bootEpoch: crypto.randomUUID() }); + await expect(restarted.service.authenticate(oldEpoch.token, restarted.binding, oldEpoch.now)).rejects.toThrow(); + + const ended = await fixture(), endedEnrollment = await enrollment(ended); + await db.pool.query("UPDATE app.job_runs SET state='succeeded' WHERE tenant_id=$1 AND id=$2", [ended.tenantId, ended.runId]); + await expect(ended.service.authenticate(endedEnrollment.token, ended.binding, endedEnrollment.now)).rejects.toThrow(); + + const tenantScoped = await fixture(), scoped = await enrollment(tenantScoped); + await expect(tenantScoped.service.authenticate(scoped.token, { ...tenantScoped.binding, tenantId: crypto.randomUUID() }, scoped.now)).rejects.toThrow(); + + const revoked = await fixture(), revokedEnrollment = await enrollment(revoked); + await revoked.repository.revokeRun(revoked.tenantId, revoked.runId); + await expect(revoked.service.authenticate(revokedEnrollment.token, revoked.binding, revokedEnrollment.now)).rejects.toThrow(); + + const disabled = await fixture(), disabledEnrollment = await enrollment(disabled); + await disabled.repository.setProxyState({ tenantId: disabled.tenantId, proxyIdentity: disabled.proxyIdentity, bootEpoch: disabled.bootEpoch, disabled: true }); + await expect(disabled.service.authenticate(disabledEnrollment.token, disabled.binding, disabledEnrollment.now)).rejects.toThrow(); + }, 30_000); +});