From b1edf5e060049434b3021aa8db41d09b9cfae344 Mon Sep 17 00:00:00 2001 From: "exe.dev user" Date: Mon, 16 Nov 2026 18:45:24 +0000 Subject: [PATCH 01/28] Add vendor run identity verification primitives --- docs/vendor-run-identity.md | 36 +++++ packages/api/src/vendor-run-identity.ts | 135 ++++++++++++++++++ packages/api/test/vendor-run-identity.test.ts | 78 ++++++++++ 3 files changed, 249 insertions(+) create mode 100644 docs/vendor-run-identity.md create mode 100644 packages/api/src/vendor-run-identity.ts create mode 100644 packages/api/test/vendor-run-identity.test.ts diff --git a/docs/vendor-run-identity.md b/docs/vendor-run-identity.md new file mode 100644 index 00000000..87317825 --- /dev/null +++ b/docs/vendor-run-identity.md @@ -0,0 +1,36 @@ +# Vendor run identity verification + +`packages/api/src/vendor-run-identity.ts` verifies signed OIDC identity tokens +against provider trust configuration and the run/VM association loaded by +Factorize. Callers must reject access unless the referenced run is still active. +Issuer discovery and its JWKS URI must come from the provider's OIDC metadata; +the verifier never trusts URLs or keys supplied by a guest. + +The verifier allows only RS256 and ES256, validates the signature, exact issuer, +audience, configured subject, issue and expiry times, and active run. It binds +Fly identities to the signed `machine_id` claim. It binds exe.dev identities +to a server-side record of a unique WIF integration attached to the exact VM. +The exe.dev WIF subject is integration-scoped and is not treated as a VM ID. +Unknown key IDs trigger a JWKS refresh to support signing-key rotation; invalid +or expired tokens fail closed, so guests must renew with the vendor before the +token expires. + +## Vendor evidence + +* exe.dev's [GCP Workload Identity Federation guide](https://exe.dev/docs/integrations-gcp-wif.md) + documents `--attach=vm:`, integration-generated issuer and subject, + short-lived OIDC tokens, a per-integration token endpoint reachable only by + VMs to which the integration is attached, and HTTP 403 when the integration + is not attached to the VM. Factorize must create and record a unique + per-run integration attached to the run-owned VM. A team-wide or + tag-attached integration does not establish an exclusive VM binding. +* Fly.io's [OIDC workload identity guide](https://fly.io/blog/oidc-cloud-roles/) + documents signed machine tokens, a machine-specific `machine_id`, an + app-scoped issuer, short-lived tokens, and key publication. Factorize must + pin the app issuer/audience and compare the signed machine ID to the + provisioned machine. + +This module is the verification primitive for the first identity milestone. +Proxy admission, vendor token acquisition/renewal wiring, and replacement of +the existing proxy identity are later milestones and must not use a shared +secret fallback. diff --git a/packages/api/src/vendor-run-identity.ts b/packages/api/src/vendor-run-identity.ts new file mode 100644 index 00000000..82c424f8 --- /dev/null +++ b/packages/api/src/vendor-run-identity.ts @@ -0,0 +1,135 @@ +/** Vendor signed identity verification primitives for run-owned VMs. + * + * Trust configuration is supplied by the provider provisioner. Callers must + * obtain issuer and JWKS locations from the provider's verified OIDC + * discovery document and must load expected bindings from Factorize state. + */ +export type VendorIdentityProvider = "exe.dev" | "fly.io"; + +export type VendorRunBinding = { + provider: VendorIdentityProvider; + runId: string; + activeRunId: string; + vmId: string; + issuer: string; + audience: string; + /** Exact provider subject configured/recorded at VM provisioning. */ + subject?: string; + /** exe.dev proves VM ownership by attaching one unique WIF integration to one VM. */ + exeAttachment?: { integrationName: string; attachedVmId: string; mode: "vm" }; + /** Maximum token age, in seconds. */ + maxTokenAgeSeconds?: number; +}; + +export type VendorIdentity = { + provider: VendorIdentityProvider; + issuer: string; + subject: string; + audience: string; + runId: string; + vmId: string; + expiresAt: number; + keyId: string; +}; + +export type JwksResolver = (keyId: string, refresh: boolean) => Promise; + +type JwtHeader = { alg?: unknown; kid?: unknown; typ?: unknown }; +type JwtClaims = Record & { iss?: unknown; sub?: unknown; aud?: unknown; exp?: unknown; iat?: unknown; nbf?: unknown; machine_id?: unknown }; + +function decodePart(value: string): Uint8Array { + if (!/^[A-Za-z0-9_-]+$/.test(value)) throw new Error("Invalid vendor identity token encoding"); + const binary = atob(value.replaceAll("-", "+").replaceAll("_", "/") + "=".repeat((4 - value.length % 4) % 4)); + const output = new Uint8Array(binary.length); + for (let i = 0; i < binary.length; i++) output[i] = binary.charCodeAt(i); + return output; +} + +function jsonPart(value: string): T { + try { return JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(decodePart(value))) as T; } + catch { throw new Error("Invalid vendor identity token payload"); } +} + +function audiences(value: unknown): string[] { + if (typeof value === "string") return [value]; + if (Array.isArray(value) && value.every(item => typeof item === "string")) return value; + return []; +} + +function providerVmId(provider: VendorIdentityProvider, claims: JwtClaims, binding: VendorRunBinding): string | null { + if (provider === "fly.io") return typeof claims.machine_id === "string" ? claims.machine_id : null; + const attachment = binding.exeAttachment; + if (!attachment || attachment.mode !== "vm" || !attachment.integrationName || attachment.attachedVmId !== binding.vmId) return null; + // exe.dev's WIF subject identifies an integration. Its documented + // per-VM attachment is the binding; the subject itself is not a VM ID. + return attachment.attachedVmId; +} + +async function verifySignature(alg: string, jwk: JsonWebKey, signingInput: string, signature: Uint8Array): Promise { + if (alg === "RS256" && (jwk.kty === "RSA" || jwk.kty === "RSA-PSS")) { + const key = await crypto.subtle.importKey("jwk", jwk, { name: "RSASSA-PKCS1-v1_5", hash: "SHA-256" }, false, ["verify"]); + return crypto.subtle.verify("RSASSA-PKCS1-v1_5", key, signature, new TextEncoder().encode(signingInput)); + } + if (alg === "ES256" && jwk.kty === "EC" && jwk.crv === "P-256") { + const key = await crypto.subtle.importKey("jwk", jwk, { name: "ECDSA", namedCurve: "P-256" }, false, ["verify"]); + return crypto.subtle.verify({ name: "ECDSA", hash: "SHA-256" }, key, signature, new TextEncoder().encode(signingInput)); + } + return false; +} + +/** Verify a vendor JWT and bind it to the exact active run and provisioned VM. */ +export async function verifyVendorRunIdentity(options: { + token: string; + binding: VendorRunBinding; + resolveKey: JwksResolver; + nowSeconds?: number; + clockSkewSeconds?: number; +}): Promise { + const { token, binding } = options; + const parts = token.split("."); + if (parts.length !== 3 || parts.some(part => !part)) throw new Error("Invalid vendor identity token"); + const header = jsonPart(parts[0]!); + const claims = jsonPart(parts[1]!); + if ((header.alg !== "RS256" && header.alg !== "ES256") || typeof header.kid !== "string" || !header.kid) throw new Error("Unsupported vendor identity signature"); + const key = await options.resolveKey(header.kid, false) ?? await options.resolveKey(header.kid, true); + if (!key || !(await verifySignature(header.alg, key, `${parts[0]}.${parts[1]}`, decodePart(parts[2]!)))) throw new Error("Invalid vendor identity signature"); + + const now = options.nowSeconds ?? Math.floor(Date.now() / 1000), skew = options.clockSkewSeconds ?? 30; + const maxAge = binding.maxTokenAgeSeconds ?? 900; + const aud = audiences(claims.aud); + if (claims.iss !== binding.issuer || !aud.includes(binding.audience) || (aud.length > 1 && claims.azp !== binding.audience)) throw new Error("Vendor identity issuer or audience mismatch"); + if (typeof claims.sub !== "string" || !claims.sub || (binding.subject && claims.sub !== binding.subject)) throw new Error("Vendor identity subject mismatch"); + if (typeof claims.exp !== "number" || !Number.isFinite(claims.exp) || claims.exp <= now) throw new Error("Vendor identity has expired"); + if (typeof claims.iat !== "number" || !Number.isFinite(claims.iat) || claims.iat > now + skew || claims.exp - claims.iat > maxAge + skew) throw new Error("Vendor identity lifetime is invalid"); + if (claims.nbf !== undefined && (typeof claims.nbf !== "number" || !Number.isFinite(claims.nbf) || claims.nbf > now + skew)) throw new Error("Vendor identity is not yet valid"); + if (!binding.runId || binding.runId !== binding.activeRunId) throw new Error("Vendor identity is not bound to an active run"); + const vmId = providerVmId(binding.provider, claims, binding); + if (!vmId || vmId !== binding.vmId) throw new Error("Vendor identity VM mismatch"); + + return { provider: binding.provider, issuer: binding.issuer, subject: claims.sub, audience: binding.audience, runId: binding.runId, vmId, expiresAt: claims.exp, keyId: header.kid }; +} + +/** A bounded JWKS cache. Unknown kids force one refresh so key rotation fails closed. */ +export function createJwksResolver(options: { jwksUri: string; fetcher?: typeof fetch; ttlMs?: number; now?: () => number }): JwksResolver { + const fetcher = options.fetcher ?? fetch, ttlMs = options.ttlMs ?? 5 * 60_000, now = options.now ?? Date.now; + let keys = new Map(), expiresAt = 0; + const load = async (force: boolean) => { + if (!force && keys.size && now() < expiresAt) return; + const response = await fetcher(options.jwksUri, { headers: { accept: "application/json" } }); + if (!response.ok) throw new Error(`Vendor signing keys unavailable (${response.status})`); + const body = await response.json() as { keys?: unknown }; + if (!Array.isArray(body.keys)) throw new Error("Vendor signing keys response is invalid"); + const next = new Map(); + for (const candidate of body.keys) { + if (!candidate || typeof candidate !== "object") continue; + const jwk = candidate as JsonWebKey & { kid?: unknown; use?: unknown; alg?: unknown }; + if (typeof jwk.kid === "string" && jwk.kid && (jwk.use === undefined || jwk.use === "sig")) next.set(jwk.kid, jwk); + } + if (!next.size) throw new Error("Vendor signing keys response contains no usable keys"); + keys = next; expiresAt = now() + ttlMs; + }; + return async (keyId, refresh) => { + await load(refresh); + return keys.get(keyId); + }; +} diff --git a/packages/api/test/vendor-run-identity.test.ts b/packages/api/test/vendor-run-identity.test.ts new file mode 100644 index 00000000..65ce4494 --- /dev/null +++ b/packages/api/test/vendor-run-identity.test.ts @@ -0,0 +1,78 @@ +import { beforeAll, describe, expect, it } from "vitest"; +import { createJwksResolver, verifyVendorRunIdentity, type VendorRunBinding } from "../src/vendor-run-identity"; + +const now = 1_800_000_000; +let privateKey: CryptoKey, publicJwk: JsonWebKey; + +function encode(value: unknown) { return btoa(String.fromCharCode(...new TextEncoder().encode(JSON.stringify(value)))).replaceAll("+", "-").replaceAll("/", "_").replace(/=+$/, ""); } + +async function token(claims: Record, kid = "key-1", key = privateKey) { + const head = encode({ alg: "RS256", typ: "JWT", kid }), body = encode(claims), input = `${head}.${body}`; + const signature = new Uint8Array(await crypto.subtle.sign("RSASSA-PKCS1-v1_5", key, new TextEncoder().encode(input))); + return `${input}.${btoa(String.fromCharCode(...signature)).replaceAll("+", "-").replaceAll("/", "_").replace(/=+$/, "")}`; +} + +const flyBinding: VendorRunBinding = { provider: "fly.io", runId: "run-1", activeRunId: "run-1", vmId: "machine-1", issuer: "https://oidc.fly.io/factorize-app", audience: "factorize-run", subject: "org:factorize-app:run-machine", maxTokenAgeSeconds: 600 }; +const claims = { iss: flyBinding.issuer, sub: flyBinding.subject, aud: flyBinding.audience, iat: now - 10, exp: now + 100, machine_id: flyBinding.vmId }; + +beforeAll(async () => { + const pair = await crypto.subtle.generateKey({ name: "RSASSA-PKCS1-v1_5", modulusLength: 2048, publicExponent: new Uint8Array([1, 0, 1]), hash: "SHA-256" }, true, ["sign", "verify"]); + privateKey = pair.privateKey; + publicJwk = await crypto.subtle.exportKey("jwk", pair.publicKey); + (publicJwk as JsonWebKey & { kid: string }).kid = "key-1"; +}); + +describe("vendor run identity", () => { + it("accepts a signed Fly identity bound to the provisioned machine and active run", async () => { + const identity = await verifyVendorRunIdentity({ token: await token(claims), binding: flyBinding, nowSeconds: now, resolveKey: async kid => kid === "key-1" ? publicJwk : undefined }); + expect(identity).toMatchObject({ provider: "fly.io", runId: "run-1", vmId: "machine-1", subject: flyBinding.subject, keyId: "key-1" }); + }); + + it("accepts renewed vendor tokens for the same VM while an expired token is rejected", async () => { + const original = await token({ ...claims, exp: now - 1 }); + const renewed = await token({ ...claims, iat: now, exp: now + 300 }); + await expect(verifyVendorRunIdentity({ token: original, binding: flyBinding, nowSeconds: now, resolveKey: async () => publicJwk })).rejects.toThrow("expired"); + await expect(verifyVendorRunIdentity({ token: renewed, binding: flyBinding, nowSeconds: now, resolveKey: async () => publicJwk })).resolves.toMatchObject({ runId: "run-1", vmId: "machine-1" }); + }); + + it.each([ + ["wrong issuer", { ...claims, iss: "https://attacker.example" }, flyBinding], + ["wrong audience", { ...claims, aud: "other" }, flyBinding], + ["wrong subject", { ...claims, sub: "org:another-app:machine" }, flyBinding], + ["expired token", { ...claims, exp: now - 1 }, flyBinding], + ["future token", { ...claims, nbf: now + 100 }, flyBinding], + ["wrong machine", { ...claims, machine_id: "machine-2" }, flyBinding], + ["inactive run", claims, { ...flyBinding, activeRunId: "run-2" }], + ["wrong run binding", claims, { ...flyBinding, runId: "run-2" }], + ] as const)("rejects %s", async (_case, payload, binding) => { + await expect(verifyVendorRunIdentity({ token: await token(payload), binding, nowSeconds: now, resolveKey: async () => publicJwk })).rejects.toThrow(); + }); + + it("requires an exact per-VM exe.dev attachment in addition to the integration subject", async () => { + const binding: VendorRunBinding = { provider: "exe.dev", runId: "run-1", activeRunId: "run-1", vmId: "factorize-run-1", issuer: "https://exe.dev/issuer/team-workload", audience: "factorize-run", subject: "sub-integration-1", exeAttachment: { integrationName: "factorize-run-1", attachedVmId: "factorize-run-1", mode: "vm" } }; + const payload = { iss: binding.issuer, sub: binding.subject, aud: binding.audience, iat: now - 10, exp: now + 100 }; + await expect(verifyVendorRunIdentity({ token: await token(payload), binding, nowSeconds: now, resolveKey: async () => publicJwk })).resolves.toMatchObject({ provider: "exe.dev", vmId: binding.vmId }); + await expect(verifyVendorRunIdentity({ token: await token({ ...payload, sub: "sub-other-integration" }), binding, nowSeconds: now, resolveKey: async () => publicJwk })).rejects.toThrow("subject mismatch"); + await expect(verifyVendorRunIdentity({ token: await token(payload), binding: { ...binding, exeAttachment: { ...binding.exeAttachment!, attachedVmId: "another-vm" } }, nowSeconds: now, resolveKey: async () => publicJwk })).rejects.toThrow("VM mismatch"); + await expect(verifyVendorRunIdentity({ token: await token(payload), binding: { ...binding, exeAttachment: undefined }, nowSeconds: now, resolveKey: async () => publicJwk })).rejects.toThrow("VM mismatch"); + }); + + it("refreshes signing keys when a rotated key ID is not in the cached JWKS", async () => { + const next = await crypto.subtle.generateKey({ name: "RSASSA-PKCS1-v1_5", modulusLength: 2048, publicExponent: new Uint8Array([1, 0, 1]), hash: "SHA-256" }, true, ["sign", "verify"]); + const rotated = await crypto.subtle.exportKey("jwk", next.publicKey) as JsonWebKey & { kid: string }; + rotated.kid = "key-2"; + const fetches: string[] = []; + const resolver = createJwksResolver({ jwksUri: "https://issuer.example/keys", now: () => now * 1000, fetcher: async (_url, init) => { + fetches.push(String(init?.headers ? "requested" : "missing-accept")); + return Response.json({ keys: fetches.length === 1 ? [publicJwk] : [rotated] }); + } }); + const identity = await verifyVendorRunIdentity({ token: await token(claims, "key-2", next.privateKey), binding: flyBinding, nowSeconds: now, resolveKey: resolver }); + expect(identity.keyId).toBe("key-2"); + expect(fetches).toHaveLength(2); + }); + + it("rejects signatures from keys outside the configured issuer key set", async () => { + const other = await crypto.subtle.generateKey({ name: "RSASSA-PKCS1-v1_5", modulusLength: 2048, publicExponent: new Uint8Array([1, 0, 1]), hash: "SHA-256" }, true, ["sign", "verify"]); + await expect(verifyVendorRunIdentity({ token: await token(claims, "key-1", other.privateKey), binding: flyBinding, nowSeconds: now, resolveKey: async () => publicJwk })).rejects.toThrow("signature"); + }); +}); From e210cef9dcdac86e2acdb1c91544502e9fba59a8 Mon Sep 17 00:00:00 2001 From: "exe.dev user" Date: Mon, 16 Nov 2026 18:49:06 +0000 Subject: [PATCH 02/28] Pin vendor identity discovery and signing keys --- docs/vendor-run-identity.md | 6 ++-- packages/api/src/vendor-run-identity.ts | 30 +++++++++++++++++++ packages/api/test/vendor-run-identity.test.ts | 15 +++++++++- 3 files changed, 48 insertions(+), 3 deletions(-) diff --git a/docs/vendor-run-identity.md b/docs/vendor-run-identity.md index 87317825..4d4e2005 100644 --- a/docs/vendor-run-identity.md +++ b/docs/vendor-run-identity.md @@ -3,8 +3,10 @@ `packages/api/src/vendor-run-identity.ts` verifies signed OIDC identity tokens against provider trust configuration and the run/VM association loaded by Factorize. Callers must reject access unless the referenced run is still active. -Issuer discovery and its JWKS URI must come from the provider's OIDC metadata; -the verifier never trusts URLs or keys supplied by a guest. +Issuer discovery is pinned to the documented exe.dev or Fly.io HTTPS origin; +the discovery response must repeat the configured issuer, and its JWKS URI +must stay on that vendor origin. The verifier never trusts URLs or keys +supplied by a guest. The verifier allows only RS256 and ES256, validates the signature, exact issuer, audience, configured subject, issue and expiry times, and active run. It binds diff --git a/packages/api/src/vendor-run-identity.ts b/packages/api/src/vendor-run-identity.ts index 82c424f8..b66a5dfd 100644 --- a/packages/api/src/vendor-run-identity.ts +++ b/packages/api/src/vendor-run-identity.ts @@ -34,6 +34,8 @@ export type VendorIdentity = { export type JwksResolver = (keyId: string, refresh: boolean) => Promise; +export type VendorIssuerTrust = { issuer: string; jwksUri: string; resolveKey: JwksResolver }; + type JwtHeader = { alg?: unknown; kid?: unknown; typ?: unknown }; type JwtClaims = Record & { iss?: unknown; sub?: unknown; aud?: unknown; exp?: unknown; iat?: unknown; nbf?: unknown; machine_id?: unknown }; @@ -133,3 +135,31 @@ export function createJwksResolver(options: { jwksUri: string; fetcher?: typeof return keys.get(keyId); }; } + +/** Load an OIDC issuer's signing keys only from the documented vendor origin. */ +export async function discoverVendorIssuerTrust(options: { + provider: VendorIdentityProvider; + issuer: string; + fetcher?: typeof fetch; + ttlMs?: number; + now?: () => number; +}): Promise { + let issuerUrl: URL; + try { issuerUrl = new URL(options.issuer); } + catch { throw new Error("Vendor issuer URL is invalid"); } + const expectedOrigin = options.provider === "fly.io" ? "https://oidc.fly.io" : "https://exe.dev"; + if (issuerUrl.protocol !== "https:" || issuerUrl.origin !== expectedOrigin || issuerUrl.username || issuerUrl.password || issuerUrl.search || issuerUrl.hash) throw new Error("Vendor issuer URL is not trusted"); + if (options.provider === "exe.dev" && !/^\/issuer\/[A-Za-z0-9-]+\/?$/.test(issuerUrl.pathname)) throw new Error("exe.dev issuer path is invalid"); + if (options.provider === "fly.io" && !/^\/[A-Za-z0-9-]+\/?$/.test(issuerUrl.pathname)) throw new Error("Fly.io issuer path is invalid"); + const issuer = options.issuer.replace(/\/$/, ""); + const discoveryUrl = `${issuer}/.well-known/openid-configuration`; + const response = await (options.fetcher ?? fetch)(discoveryUrl, { headers: { accept: "application/json" } }); + if (!response.ok) throw new Error(`Vendor issuer metadata unavailable (${response.status})`); + const metadata = await response.json() as { issuer?: unknown; jwks_uri?: unknown }; + if (metadata.issuer !== issuer || typeof metadata.jwks_uri !== "string") throw new Error("Vendor issuer metadata does not match the configured issuer"); + let jwksUrl: URL; + try { jwksUrl = new URL(metadata.jwks_uri); } + catch { throw new Error("Vendor signing keys URL is invalid"); } + if (jwksUrl.protocol !== "https:" || jwksUrl.origin !== expectedOrigin || jwksUrl.username || jwksUrl.password || jwksUrl.search || jwksUrl.hash) throw new Error("Vendor signing keys URL is not trusted"); + return { issuer, jwksUri: jwksUrl.href, resolveKey: createJwksResolver({ jwksUri: jwksUrl.href, fetcher: options.fetcher, ttlMs: options.ttlMs, now: options.now }) }; +} diff --git a/packages/api/test/vendor-run-identity.test.ts b/packages/api/test/vendor-run-identity.test.ts index 65ce4494..f460e8db 100644 --- a/packages/api/test/vendor-run-identity.test.ts +++ b/packages/api/test/vendor-run-identity.test.ts @@ -1,5 +1,5 @@ import { beforeAll, describe, expect, it } from "vitest"; -import { createJwksResolver, verifyVendorRunIdentity, type VendorRunBinding } from "../src/vendor-run-identity"; +import { createJwksResolver, discoverVendorIssuerTrust, verifyVendorRunIdentity, type VendorRunBinding } from "../src/vendor-run-identity"; const now = 1_800_000_000; let privateKey: CryptoKey, publicJwk: JsonWebKey; @@ -75,4 +75,17 @@ describe("vendor run identity", () => { const other = await crypto.subtle.generateKey({ name: "RSASSA-PKCS1-v1_5", modulusLength: 2048, publicExponent: new Uint8Array([1, 0, 1]), hash: "SHA-256" }, true, ["sign", "verify"]); await expect(verifyVendorRunIdentity({ token: await token(claims, "key-1", other.privateKey), binding: flyBinding, nowSeconds: now, resolveKey: async () => publicJwk })).rejects.toThrow("signature"); }); + + it("loads issuer keys only from matching HTTPS metadata on the vendor origin", async () => { + const calls: string[] = []; + const trust = await discoverVendorIssuerTrust({ provider: "fly.io", issuer: flyBinding.issuer, fetcher: async input => { + calls.push(String(input)); + return Response.json({ issuer: flyBinding.issuer, jwks_uri: "https://oidc.fly.io/keys" }); + } }); + expect(trust).toMatchObject({ issuer: flyBinding.issuer, jwksUri: "https://oidc.fly.io/keys" }); + expect(calls).toEqual([`${flyBinding.issuer}/.well-known/openid-configuration`]); + await expect(discoverVendorIssuerTrust({ provider: "fly.io", issuer: flyBinding.issuer, fetcher: async () => Response.json({ issuer: "https://attacker.example", jwks_uri: "https://attacker.example/keys" }) })).rejects.toThrow("metadata does not match"); + await expect(discoverVendorIssuerTrust({ provider: "fly.io", issuer: "https://attacker.example/app", fetcher: fetch })).rejects.toThrow("not trusted"); + await expect(discoverVendorIssuerTrust({ provider: "exe.dev", issuer: "https://exe.dev/issuer/team-workload", fetcher: async () => Response.json({ issuer: "https://exe.dev/issuer/team-workload", jwks_uri: "https://attacker.example/keys" }) })).rejects.toThrow("keys URL is not trusted"); + }); }); From ce993d4515a60d019e27e8bb2e7f4cae4780e6c1 Mon Sep 17 00:00:00 2001 From: "exe.dev user" Date: Mon, 16 Nov 2026 19:08:12 +0000 Subject: [PATCH 03/28] Persist verified vendor run identity bindings --- docs/vendor-run-identity.md | 16 ++- .../0048_vendor_run_identity_bindings.sql | 25 +++++ .../vendor-run-identity-repository.ts | 97 +++++++++++++++++++ packages/api/src/vendor-run-identity.ts | 3 +- .../test/vendor-run-identity.postgres.test.ts | 63 ++++++++++++ packages/api/test/vendor-run-identity.test.ts | 2 +- 6 files changed, 199 insertions(+), 7 deletions(-) create mode 100644 packages/api/migrations/0048_vendor_run_identity_bindings.sql create mode 100644 packages/api/src/postgres/vendor-run-identity-repository.ts create mode 100644 packages/api/test/vendor-run-identity.postgres.test.ts diff --git a/docs/vendor-run-identity.md b/docs/vendor-run-identity.md index 4d4e2005..349652e9 100644 --- a/docs/vendor-run-identity.md +++ b/docs/vendor-run-identity.md @@ -2,7 +2,12 @@ `packages/api/src/vendor-run-identity.ts` verifies signed OIDC identity tokens against provider trust configuration and the run/VM association loaded by -Factorize. Callers must reject access unless the referenced run is still active. +Factorize. `VendorRunIdentityRepository` stores verified claim bindings in +PostgreSQL without storing JWTs. Each provider has one immutable VM, issuer, +subject, audience, and run binding; renewal can extend its validity window but +cannot change those values. VM and issuer/subject/audience uniqueness is +enforced across tenants. Revoked, expired, or inactive-run bindings are not +returned as active. Issuer discovery is pinned to the documented exe.dev or Fly.io HTTPS origin; the discovery response must repeat the configured issuer, and its JWKS URI must stay on that vendor origin. The verifier never trusts URLs or keys @@ -32,7 +37,8 @@ token expires. pin the app issuer/audience and compare the signed machine ID to the provisioned machine. -This module is the verification primitive for the first identity milestone. -Proxy admission, vendor token acquisition/renewal wiring, and replacement of -the existing proxy identity are later milestones and must not use a shared -secret fallback. +Fixture tests exercise the verifier and PostgreSQL repository independently; +they do not establish live vendor behavior. Vendor token acquisition and +renewal are not yet connected to execution provisioning, so this repository is +not yet an admission path. Proxy admission and replacement of the existing +proxy identity are later milestones and must not use a shared-secret fallback. diff --git a/packages/api/migrations/0048_vendor_run_identity_bindings.sql b/packages/api/migrations/0048_vendor_run_identity_bindings.sql new file mode 100644 index 00000000..fd743872 --- /dev/null +++ b/packages/api/migrations/0048_vendor_run_identity_bindings.sql @@ -0,0 +1,25 @@ +CREATE TABLE app.vendor_run_identity_bindings ( + tenant_id uuid NOT NULL, + run_id uuid NOT NULL, + provider text NOT NULL CHECK (provider IN ('exe.dev','fly.io')), + vm_id text NOT NULL CHECK (length(vm_id) BETWEEN 1 AND 255), + issuer text NOT NULL CHECK (length(issuer) BETWEEN 1 AND 512), + subject text NOT NULL CHECK (length(subject) BETWEEN 1 AND 512), + audience text NOT NULL CHECK (length(audience) BETWEEN 1 AND 512), + issued_at timestamptz NOT NULL, + expires_at timestamptz NOT NULL, + revoked_at timestamptz, + created_at timestamptz NOT NULL DEFAULT now(), + updated_at timestamptz NOT NULL DEFAULT now(), + PRIMARY KEY (tenant_id, run_id, provider), + UNIQUE (provider, vm_id), + UNIQUE (provider, issuer, subject, audience), + CHECK (expires_at > issued_at), + FOREIGN KEY (tenant_id, run_id) REFERENCES app.job_runs(tenant_id, id) ON DELETE CASCADE +); + +CREATE INDEX vendor_run_identity_bindings_active + ON app.vendor_run_identity_bindings(tenant_id, run_id, provider) + WHERE revoked_at IS NULL; + +INSERT INTO app.schema_migrations(version) VALUES ('0048_vendor_run_identity_bindings') ON CONFLICT DO NOTHING; diff --git a/packages/api/src/postgres/vendor-run-identity-repository.ts b/packages/api/src/postgres/vendor-run-identity-repository.ts new file mode 100644 index 00000000..af613acb --- /dev/null +++ b/packages/api/src/postgres/vendor-run-identity-repository.ts @@ -0,0 +1,97 @@ +import type { Database } from "./database"; +import type { VendorIdentity, VendorIdentityProvider } from "../vendor-run-identity"; + +const uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; +const activeStates = "('starting','running','blocked')"; + +export type VendorRunIdentityBinding = { + tenantId: string; + runId: string; + provider: VendorIdentityProvider; + vmId: string; + issuer: string; + subject: string; + audience: string; + issuedAt: Date; + expiresAt: Date; + revokedAt: Date | null; +}; + +function validate(input: { tenantId: string; identity: VendorIdentity; issuedAt: number }): void { + if (!uuid.test(input.tenantId) || !uuid.test(input.identity.runId)) throw new TypeError("Vendor identity tenant and run IDs must be UUIDs"); + for (const [name, value, max] of [ + ["vmId", input.identity.vmId, 255], ["issuer", input.identity.issuer, 512], + ["subject", input.identity.subject, 512], ["audience", input.identity.audience, 512], + ] as const) { + if (typeof value !== "string" || !value.trim() || value.length > max) throw new TypeError(`${name} must contain 1 to ${max} characters`); + } + if (!Number.isSafeInteger(input.issuedAt) || !Number.isSafeInteger(input.identity.expiresAt) || input.identity.expiresAt <= input.issuedAt) throw new TypeError("Vendor identity validity interval is invalid"); + if (!input.identity.keyId || input.identity.keyId.length > 255) throw new TypeError("Vendor identity key ID is invalid"); +} + +function matches(row: VendorRunIdentityBinding, identity: VendorIdentity): boolean { + return row.provider === identity.provider && row.runId === identity.runId && row.vmId === identity.vmId + && row.issuer === identity.issuer && row.subject === identity.subject && row.audience === identity.audience; +} + +/** Persists verified identity claims, never the bearer JWT. A run's provider + * identity is immutable; renewal can extend its expiry but cannot rebind it. */ +export class VendorRunIdentityRepository { + constructor(private readonly database: Database) {} + + async persistVerified(input: { tenantId: string; identity: VendorIdentity; issuedAt: number; now?: Date }): Promise { + validate(input); + const now = input.now ?? new Date(); + if (!Number.isFinite(now.getTime())) throw new TypeError("now must be a valid date"); + const issuedAt = new Date(input.issuedAt * 1000), expiresAt = new Date(input.identity.expiresAt * 1000); + if (expiresAt <= now) throw new TypeError("Vendor identity has expired"); + + return this.database.transaction(async client => { + const active = await client.query(`SELECT 1 FROM app.job_runs WHERE tenant_id=$1 AND id=$2 AND state IN ${activeStates} FOR UPDATE`, [input.tenantId, input.identity.runId]); + if (!active.rowCount) throw new Error("Vendor identity run is not active"); + + const current = await client.query(`SELECT tenant_id AS "tenantId",run_id AS "runId",provider,vm_id AS "vmId",issuer,subject,audience,issued_at AS "issuedAt",expires_at AS "expiresAt",revoked_at AS "revokedAt" + FROM app.vendor_run_identity_bindings WHERE tenant_id=$1 AND run_id=$2 AND provider=$3 FOR UPDATE`, [input.tenantId, input.identity.runId, input.identity.provider]); + const existing = current.rows[0]; + if (existing) { + if (existing.revokedAt) throw new Error("Vendor identity binding is revoked"); + if (!matches(existing, input.identity)) throw new Error("Vendor identity does not match the persisted run binding"); + const renewed = await client.query(`UPDATE app.vendor_run_identity_bindings + SET issued_at=$4,expires_at=$5,updated_at=$6 + WHERE tenant_id=$1 AND run_id=$2 AND provider=$3 AND revoked_at IS NULL + RETURNING tenant_id AS "tenantId",run_id AS "runId",provider,vm_id AS "vmId",issuer,subject,audience,issued_at AS "issuedAt",expires_at AS "expiresAt",revoked_at AS "revokedAt"`, + [input.tenantId, input.identity.runId, input.identity.provider, issuedAt, expiresAt, now]); + if (!renewed.rows[0]) throw new Error("Vendor identity binding is revoked"); + return renewed.rows[0]; + } + + try { + const saved = await client.query(`INSERT INTO app.vendor_run_identity_bindings(tenant_id,run_id,provider,vm_id,issuer,subject,audience,issued_at,expires_at) + VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9) + RETURNING tenant_id AS "tenantId",run_id AS "runId",provider,vm_id AS "vmId",issuer,subject,audience,issued_at AS "issuedAt",expires_at AS "expiresAt",revoked_at AS "revokedAt"`, + [input.tenantId, input.identity.runId, input.identity.provider, input.identity.vmId, input.identity.issuer, input.identity.subject, input.identity.audience, issuedAt, expiresAt]); + return saved.rows[0]!; + } catch (error) { + if ((error as { code?: unknown })?.code === "23505") throw new Error("Vendor VM or subject is already bound to another run"); + throw error; + } + }); + } + + async getActive(input: { tenantId: string; runId: string; provider: VendorIdentityProvider; now?: Date }): Promise { + if (!uuid.test(input.tenantId) || !uuid.test(input.runId)) throw new TypeError("Vendor identity tenant and run IDs must be UUIDs"); + const now = input.now ?? new Date(); + const result = await this.database.pool.query(`SELECT b.tenant_id AS "tenantId",b.run_id AS "runId",b.provider,b.vm_id AS "vmId",b.issuer,b.subject,b.audience,b.issued_at AS "issuedAt",b.expires_at AS "expiresAt",b.revoked_at AS "revokedAt" + FROM app.vendor_run_identity_bindings b JOIN app.job_runs r ON r.tenant_id=b.tenant_id AND r.id=b.run_id + WHERE b.tenant_id=$1 AND b.run_id=$2 AND b.provider=$3 AND b.revoked_at IS NULL AND b.expires_at>$4 AND r.state IN ${activeStates}`, + [input.tenantId, input.runId, input.provider, now]); + return result.rows[0] ?? null; + } + + async revoke(input: { tenantId: string; runId: string; provider: VendorIdentityProvider; now?: Date }): Promise { + if (!uuid.test(input.tenantId) || !uuid.test(input.runId)) throw new TypeError("Vendor identity tenant and run IDs must be UUIDs"); + const result = await this.database.pool.query(`UPDATE app.vendor_run_identity_bindings SET revoked_at=$4,updated_at=$4 + WHERE tenant_id=$1 AND run_id=$2 AND provider=$3 AND revoked_at IS NULL`, [input.tenantId, input.runId, input.provider, input.now ?? new Date()]); + return Boolean(result.rowCount); + } +} diff --git a/packages/api/src/vendor-run-identity.ts b/packages/api/src/vendor-run-identity.ts index b66a5dfd..69e14992 100644 --- a/packages/api/src/vendor-run-identity.ts +++ b/packages/api/src/vendor-run-identity.ts @@ -28,6 +28,7 @@ export type VendorIdentity = { audience: string; runId: string; vmId: string; + issuedAt: number; expiresAt: number; keyId: string; }; @@ -108,7 +109,7 @@ export async function verifyVendorRunIdentity(options: { const vmId = providerVmId(binding.provider, claims, binding); if (!vmId || vmId !== binding.vmId) throw new Error("Vendor identity VM mismatch"); - return { provider: binding.provider, issuer: binding.issuer, subject: claims.sub, audience: binding.audience, runId: binding.runId, vmId, expiresAt: claims.exp, keyId: header.kid }; + return { provider: binding.provider, issuer: binding.issuer, subject: claims.sub, audience: binding.audience, runId: binding.runId, vmId, issuedAt: claims.iat, expiresAt: claims.exp, keyId: header.kid }; } /** A bounded JWKS cache. Unknown kids force one refresh so key rotation fails closed. */ diff --git a/packages/api/test/vendor-run-identity.postgres.test.ts b/packages/api/test/vendor-run-identity.postgres.test.ts new file mode 100644 index 00000000..515bd97b --- /dev/null +++ b/packages/api/test/vendor-run-identity.postgres.test.ts @@ -0,0 +1,63 @@ +import { afterAll, beforeAll, describe, expect, it } from "vitest"; +import { Database } from "../src/postgres/database"; +import { VendorRunIdentityRepository } from "../src/postgres/vendor-run-identity-repository"; +import type { VendorIdentity } from "../src/vendor-run-identity"; + +const url = process.env.AUTH_TEST_DATABASE_URL; + +describe.skipIf(!url)("durable vendor run identity bindings (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.vendor_run_identity_bindings') AS bindings")).rows[0]?.bindings).toBe("app.vendor_run_identity_bindings"); + }, 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", identityOverrides: Partial = {}) { + const tenantId = crypto.randomUUID(), jobId = crypto.randomUUID(), triggerId = crypto.randomUUID(), invocationId = crypto.randomUUID(), runId = 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,'Identity test','identity-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','identity-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 identity: VendorIdentity = { + provider: "fly.io", runId, vmId: `fm-${crypto.randomUUID()}`, issuer: "https://oidc.fly.io/factorize-test", + subject: `test:factorize-test:${crypto.randomUUID()}`, audience: `factorize://runs/${runId}`, issuedAt: 1_800_000_000, + expiresAt: 1_800_000_600, keyId: "fixture-key", ...identityOverrides, + }; + return { tenantId, runId, identity, repository: new VendorRunIdentityRepository(db), now: new Date(identity.issuedAt * 1000) }; + } + + it("persists one verified identity, renews expiry without rebinding, and rejects mismatches", async () => { + const f = await fixture(); + const first = await f.repository.persistVerified({ tenantId: f.tenantId, identity: f.identity, issuedAt: f.identity.issuedAt, now: f.now }); + expect(first).toMatchObject({ tenantId: f.tenantId, runId: f.runId, provider: "fly.io", vmId: f.identity.vmId, issuer: f.identity.issuer, subject: f.identity.subject, audience: f.identity.audience }); + expect(await f.repository.getActive({ tenantId: f.tenantId, runId: f.runId, provider: "fly.io", now: f.now })).toMatchObject({ subject: f.identity.subject }); + + const renewed = { ...f.identity, issuedAt: f.identity.issuedAt + 60, expiresAt: f.identity.expiresAt + 60 }; + await expect(f.repository.persistVerified({ tenantId: f.tenantId, identity: renewed, issuedAt: renewed.issuedAt, now: new Date(renewed.issuedAt * 1000) })).resolves.toMatchObject({ vmId: f.identity.vmId, expiresAt: new Date(renewed.expiresAt * 1000) }); + await expect(f.repository.persistVerified({ tenantId: f.tenantId, identity: { ...renewed, vmId: "different-machine" }, issuedAt: renewed.issuedAt, now: new Date(renewed.issuedAt * 1000) })).rejects.toThrow("does not match the persisted run binding"); + }); + + it("enforces VM and subject uniqueness and rejects revoked, expired, and inactive bindings", async () => { + const original = await fixture(); + await original.repository.persistVerified({ tenantId: original.tenantId, identity: original.identity, issuedAt: original.identity.issuedAt, now: original.now }); + const another = await fixture(); + await expect(another.repository.persistVerified({ tenantId: another.tenantId, identity: { ...another.identity, vmId: original.identity.vmId }, issuedAt: another.identity.issuedAt, now: another.now })).rejects.toThrow("already bound to another run"); + await expect(another.repository.persistVerified({ tenantId: another.tenantId, identity: { ...another.identity, subject: original.identity.subject, audience: original.identity.audience }, issuedAt: another.identity.issuedAt, now: another.now })).rejects.toThrow("already bound to another run"); + + expect(await original.repository.revoke({ tenantId: original.tenantId, runId: original.runId, provider: "fly.io", now: original.now })).toBe(true); + expect(await original.repository.getActive({ tenantId: original.tenantId, runId: original.runId, provider: "fly.io", now: original.now })).toBeNull(); + await expect(original.repository.persistVerified({ tenantId: original.tenantId, identity: original.identity, issuedAt: original.identity.issuedAt, now: original.now })).rejects.toThrow("binding is revoked"); + + const ended = await fixture("succeeded"); + await expect(ended.repository.persistVerified({ tenantId: ended.tenantId, identity: ended.identity, issuedAt: ended.identity.issuedAt, now: ended.now })).rejects.toThrow("run is not active"); + + const expired = await fixture(); + await expired.repository.persistVerified({ tenantId: expired.tenantId, identity: expired.identity, issuedAt: expired.identity.issuedAt, now: expired.now }); + expect(await expired.repository.getActive({ tenantId: expired.tenantId, runId: expired.runId, provider: "fly.io", now: new Date(expired.identity.expiresAt * 1000) })).toBeNull(); + }, 30_000); +}); diff --git a/packages/api/test/vendor-run-identity.test.ts b/packages/api/test/vendor-run-identity.test.ts index f460e8db..0b2e4371 100644 --- a/packages/api/test/vendor-run-identity.test.ts +++ b/packages/api/test/vendor-run-identity.test.ts @@ -25,7 +25,7 @@ beforeAll(async () => { describe("vendor run identity", () => { it("accepts a signed Fly identity bound to the provisioned machine and active run", async () => { const identity = await verifyVendorRunIdentity({ token: await token(claims), binding: flyBinding, nowSeconds: now, resolveKey: async kid => kid === "key-1" ? publicJwk : undefined }); - expect(identity).toMatchObject({ provider: "fly.io", runId: "run-1", vmId: "machine-1", subject: flyBinding.subject, keyId: "key-1" }); + expect(identity).toMatchObject({ provider: "fly.io", runId: "run-1", vmId: "machine-1", subject: flyBinding.subject, issuedAt: now - 10, keyId: "key-1" }); }); it("accepts renewed vendor tokens for the same VM while an expired token is rejected", async () => { From 6d9b91c4f2815839bdd08edf75361c14a9127dd3 Mon Sep 17 00:00:00 2001 From: "exe.dev user" Date: Mon, 16 Nov 2026 19:26:41 +0000 Subject: [PATCH 04/28] Add documented vendor identity token sources --- docs/vendor-run-identity.md | 18 ++++-- packages/api/src/vendor-run-token-sources.ts | 55 +++++++++++++++++++ .../api/test/vendor-run-token-sources.test.ts | 35 ++++++++++++ 3 files changed, 103 insertions(+), 5 deletions(-) create mode 100644 packages/api/src/vendor-run-token-sources.ts create mode 100644 packages/api/test/vendor-run-token-sources.test.ts diff --git a/docs/vendor-run-identity.md b/docs/vendor-run-identity.md index 349652e9..bdd7c4d9 100644 --- a/docs/vendor-run-identity.md +++ b/docs/vendor-run-identity.md @@ -37,8 +37,16 @@ token expires. pin the app issuer/audience and compare the signed machine ID to the provisioned machine. -Fixture tests exercise the verifier and PostgreSQL repository independently; -they do not establish live vendor behavior. Vendor token acquisition and -renewal are not yet connected to execution provisioning, so this repository is -not yet an admission path. Proxy admission and replacement of the existing -proxy identity are later milestones and must not use a shared-secret fallback. +`packages/api/src/vendor-run-token-sources.ts` implements the documented guest +token requests: exe.dev WIF `GET https://.int.exe.xyz/token` and +Fly `POST http://localhost/v1/tokens/oidc` through the Machine's +`/.fly/api` Unix socket with the configured `aud`. Renewal repeats the provider +request and must pass the same verifier and immutable binding. Focused source +tests use deterministic response fixtures; they do not establish live vendor +behavior. + +The token sources are not yet invoked by execution provisioning, and verified +identities are not yet persisted from a launch. This branch therefore remains +an incomplete implementation checkpoint, not an admission path. Proxy +admission and replacement of the existing proxy identity are later milestones +and must not use a shared-secret fallback. diff --git a/packages/api/src/vendor-run-token-sources.ts b/packages/api/src/vendor-run-token-sources.ts new file mode 100644 index 00000000..8ddb2b93 --- /dev/null +++ b/packages/api/src/vendor-run-token-sources.ts @@ -0,0 +1,55 @@ +/** Documented provider token sources used by run-owned guests. + * + * These helpers only acquire a token. Callers must verify the signed claims + * against the provisioned VM and active run before persisting or using it. + */ +import type { JobGuest } from "./machine-job-execution-backend"; + +const jwt = /^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/; + +function requireJwt(value: string): string { + const token = value.trim(); + if (!jwt.test(token)) throw new Error("Vendor identity endpoint returned an invalid token"); + return token; +} + +/** exe.dev documents the WIF integration's /token endpoint as returning + * `{ token: "" }` on its integration-only hostname. */ +export async function acquireExeDevWifToken(input: { + integrationName: string; + fetcher?: typeof fetch; +}): Promise { + if (!/^[A-Za-z0-9][A-Za-z0-9-]{0,62}$/.test(input.integrationName)) throw new TypeError("Invalid exe.dev WIF integration name"); + const response = await (input.fetcher ?? fetch)(`https://${input.integrationName}.int.exe.xyz/token`, { + headers: { accept: "application/json" }, + signal: AbortSignal.timeout(10_000), + }); + if (!response.ok) throw new Error(`exe.dev WIF token request failed (${response.status})`); + let body: unknown; + try { body = await response.json(); } catch { throw new Error("exe.dev WIF token response is invalid"); } + if (!body || typeof body !== "object" || typeof (body as { token?: unknown }).token !== "string") throw new Error("exe.dev WIF token response is invalid"); + return requireJwt((body as { token: string }).token); +} + +/** Fly documents POST /v1/tokens/oidc with `aud`; inside a Machine the + * documented Machines API is exposed on the /.fly/api Unix socket. */ +export async function acquireFlyMachineOidcToken(input: { + guest: Pick; + audience: string; +}): Promise { + if (!input.audience.trim() || input.audience.length > 512) throw new TypeError("Invalid Fly OIDC audience"); + const response = await input.guest.run([ + "curl", "--fail", "--silent", "--show-error", "--max-time", "10", + "--unix-socket", "/.fly/api", "-X", "POST", + "-H", "Content-Type: application/json", + "--data", JSON.stringify({ aud: input.audience }), + "http://localhost/v1/tokens/oidc", + ]); + if (!response.ok) throw new Error("Fly Machine OIDC token request failed"); + return requireJwt(response.stdout); +} + +/** Renewal deliberately uses the same vendor source, producing a fresh + * short-lived token which must pass the same verifier and immutable binding. */ +export const renewExeDevWifToken = acquireExeDevWifToken; +export const renewFlyMachineOidcToken = acquireFlyMachineOidcToken; diff --git a/packages/api/test/vendor-run-token-sources.test.ts b/packages/api/test/vendor-run-token-sources.test.ts new file mode 100644 index 00000000..7ce76433 --- /dev/null +++ b/packages/api/test/vendor-run-token-sources.test.ts @@ -0,0 +1,35 @@ +import { describe, expect, it, vi } from "vitest"; +import { acquireExeDevWifToken, acquireFlyMachineOidcToken, renewExeDevWifToken, renewFlyMachineOidcToken } from "../src/vendor-run-token-sources"; + +const token = "eyJhbGciOiJSUzI1NiJ9.eyJzdWIiOiJmaXh0dXJlIn0.c2lnbmF0dXJl"; + +describe("vendor run identity token sources", () => { + it("requests an exe.dev WIF token from the exact integration host and supports renewal", async () => { + const fetcher = vi.fn(async () => Response.json({ token })); + await expect(acquireExeDevWifToken({ integrationName: "factorize-run-123", fetcher })).resolves.toBe(token); + await expect(renewExeDevWifToken({ integrationName: "factorize-run-123", fetcher })).resolves.toBe(token); + expect(fetcher).toHaveBeenCalledTimes(2); + expect(fetcher).toHaveBeenCalledWith("https://factorize-run-123.int.exe.xyz/token", expect.objectContaining({ headers: { accept: "application/json" } })); + }); + + it("requests Fly OIDC with the configured audience over the Machine API socket and supports renewal", async () => { + const run = vi.fn(async () => ({ ok: true, exitCode: 0, stdout: token, stderr: "" })); + const guest = { run }; + await expect(acquireFlyMachineOidcToken({ guest, audience: "https://factorize.example/vendor-run" })).resolves.toBe(token); + await expect(renewFlyMachineOidcToken({ guest, audience: "https://factorize.example/vendor-run" })).resolves.toBe(token); + expect(run).toHaveBeenCalledTimes(2); + expect(run).toHaveBeenCalledWith([ + "curl", "--fail", "--silent", "--show-error", "--max-time", "10", "--unix-socket", "/.fly/api", "-X", "POST", + "-H", "Content-Type: application/json", "--data", JSON.stringify({ aud: "https://factorize.example/vendor-run" }), + "http://localhost/v1/tokens/oidc", + ]); + }); + + it("rejects invalid provider configuration and malformed or failed responses", async () => { + await expect(acquireExeDevWifToken({ integrationName: "not a host" })).rejects.toThrow("integration name"); + await expect(acquireFlyMachineOidcToken({ guest: { run: vi.fn() }, audience: " " })).rejects.toThrow("audience"); + await expect(acquireExeDevWifToken({ integrationName: "wif", fetcher: async () => Response.json({ token: "not-a-jwt" }) })).rejects.toThrow("invalid token"); + await expect(acquireExeDevWifToken({ integrationName: "wif", fetcher: async () => new Response("", { status: 403 }) })).rejects.toThrow("(403)"); + await expect(acquireFlyMachineOidcToken({ guest: { run: async () => ({ ok: false, exitCode: 22, stdout: "", stderr: "not logged" }) }, audience: "factorize" })).rejects.toThrow("request failed"); + }); +}); From 4b55553817fafc8098fae5cc211fbe1b5808ff63 Mon Sep 17 00:00:00 2001 From: "exe.dev user" Date: Mon, 16 Nov 2026 19:52:07 +0000 Subject: [PATCH 05/28] Wire vendor VM identity into execution provisioning --- docs/vendor-run-identity.md | 23 +++-- packages/api/src/exe-vm-backend.ts | 91 ++++++++++++++++++- packages/api/src/execution.ts | 4 +- packages/api/src/fly-job-execution-backend.ts | 1 + .../api/src/machine-job-execution-backend.ts | 20 ++++ packages/api/src/postgres/run-scheduler.ts | 19 +++- .../src/vendor-run-identity-provisioning.ts | 57 ++++++++++++ packages/api/test/execution-backend.test.ts | 22 ++++- .../test/fly-job-execution-backend.test.ts | 14 +++ .../test/vendor-run-identity.postgres.test.ts | 36 +++++++- 10 files changed, 270 insertions(+), 17 deletions(-) create mode 100644 packages/api/src/vendor-run-identity-provisioning.ts diff --git a/docs/vendor-run-identity.md b/docs/vendor-run-identity.md index bdd7c4d9..f8b159d5 100644 --- a/docs/vendor-run-identity.md +++ b/docs/vendor-run-identity.md @@ -40,13 +40,18 @@ token expires. `packages/api/src/vendor-run-token-sources.ts` implements the documented guest token requests: exe.dev WIF `GET https://.int.exe.xyz/token` and Fly `POST http://localhost/v1/tokens/oidc` through the Machine's -`/.fly/api` Unix socket with the configured `aud`. Renewal repeats the provider -request and must pass the same verifier and immutable binding. Focused source -tests use deterministic response fixtures; they do not establish live vendor -behavior. +`/.fly/api` Unix socket with the configured `aud`. Provisioning creates a +uniquely named exe.dev WIF integration attached only to the run VM, reads its +issuer and subject back from the provider inventory, and verifies the returned +token before starting the job. Fly provisioning verifies its token against the +configured app issuer and the returned Machine ID. The scheduler persists only +verified claim bindings. Active VM polls renew through the same token source, +verifier, active-run check, and immutable repository update; provider cleanup +removes the per-run exe.dev integration after verifying its VM attachment. -The token sources are not yet invoked by execution provisioning, and verified -identities are not yet persisted from a launch. This branch therefore remains -an incomplete implementation checkpoint, not an admission path. Proxy -admission and replacement of the existing proxy identity are later milestones -and must not use a shared-secret fallback. +Focused backend tests use deterministic token and provider response fixtures, +and the PostgreSQL repository tests cover immutable renewal, revocation, +expiry, duplicate bindings, and inactive runs. They do not establish live +vendor behavior. No live exe.dev or Fly token was observed in development or +validation. The existing proxy admission and proxy identity remain outside this +milestone; vendor verification does not add a shared-secret fallback. diff --git a/packages/api/src/exe-vm-backend.ts b/packages/api/src/exe-vm-backend.ts index d4ffb8c0..a55e5d7e 100644 --- a/packages/api/src/exe-vm-backend.ts +++ b/packages/api/src/exe-vm-backend.ts @@ -17,6 +17,11 @@ export function vmNameFor(runId: string): string { return `factorize-${suffix}`; } +export function exeWifIntegrationNameFor(runId: string): string { + return `fzrun-${runId.replaceAll("-", "").toLowerCase().slice(0, 32)}`; +} +type ExeWifConfiguration = { integrationName: string; issuer: string; subject: string; audience: string }; + export function isOwnedVmName(vm: string): boolean { return /^factorize-[a-z0-9](?:[a-z0-9-]{0,47}[a-z0-9])?$/.test(vm); } @@ -53,9 +58,59 @@ export class ExeVmBackend implements ExecutionBackend { readonly kind = "exe-vm"; readonly capabilities = capabilities; - constructor(private readonly connection: Pick & { image?: string } | ExeRunConnection) {} + constructor( + private readonly connection: Pick & { image?: string } | ExeRunConnection, + private readonly vendorIdentityVerifier?: (input: { provider: "exe.dev" | "fly.io"; vmId: string; token: string; integrationName?: string; expectedIssuer?: string; expectedSubject?: string }) => Promise, + ) {} + + reserve(runId: string): RunHandle { return { backendKind: this.kind, id: vmNameFor(runId), runProxyName: runProxyName(runId), operationId: runId, vendorIdentityIntegrationName: exeWifIntegrationNameFor(runId) }; } + + private async exeWifToken(vm: string, integrationName: string): Promise { + const command = `curl --fail --silent --show-error https://${integrationName}.int.exe.xyz/token | python3 -c 'import json,sys;v=json.load(sys.stdin);t=v.get("token");sys.stdout.write(t if isinstance(t,str) else "")'`; + const result = await this.api(`ssh ${shellAtom(vm)} ${shellAtom(command)}`); + if (!result.ok || !/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/.test(result.body.trim())) throw new Error("exe.dev WIF token request failed"); + return result.body.trim(); + } + + private async ensureExeWif(vm: string, runId: string, create = true): Promise { + const name = exeWifIntegrationNameFor(runId), audience = `factorize://runs/${runId}`; + if (create) { + const created = await this.api(`integrations add wif --name=${shellAtom(name)} --audience=${shellAtom(audience)} --consumer=gcp --attach=${shellAtom(`vm:${vm}`)}`); + if (!created.ok) throw new Error(`exe.dev WIF integration setup failed (${created.status})`); + } + const listed = await this.api("integrations list --json"); + if (!listed.ok) throw new Error("exe.dev WIF integration could not be verified"); + try { + const parsed = JSON.parse(listed.body), integrations = Array.isArray(parsed) ? parsed : parsed.integrations; + const matches = Array.isArray(integrations) ? integrations.filter((item: any) => item?.name === name && item?.type === "wif") : []; + if (matches.length !== 1) throw new Error(); + const config = matches[0].config; + if (typeof config?.issuer_id !== "string" || !/^[A-Za-z0-9-]+$/.test(config.issuer_id) || typeof config?.subject !== "string" || !config.subject || config.audience !== audience) throw new Error(); + if (!Array.isArray(matches[0].attachments) || matches[0].attachments.length !== 1 || matches[0].attachments[0] !== `vm:${vm}`) throw new Error(); + return { integrationName: name, issuer: `https://exe.dev/issuer/${config.issuer_id}`, subject: config.subject, audience }; + } catch { throw new Error("exe.dev WIF integration metadata is invalid"); } + } - reserve(runId: string): RunHandle { return { backendKind: this.kind, id: vmNameFor(runId), runProxyName: runProxyName(runId) }; } + private async removeExeWif(vm: string, runId: string, name: string): Promise { + if (name !== exeWifIntegrationNameFor(runId)) throw new Error("Refusing to remove an unrelated exe.dev WIF integration"); + const listed = await this.api("integrations list --json"); + if (!listed.ok) throw new Error("exe.dev WIF cleanup could not verify integration ownership"); + let integrations: any[]; + try { + const parsed = JSON.parse(listed.body); + integrations = Array.isArray(parsed) ? parsed : parsed.integrations; + if (!Array.isArray(integrations)) throw new Error(); + } catch { throw new Error("exe.dev WIF cleanup inventory is invalid"); } + const matches = integrations.filter(item => item?.name === name); + if (!matches.length) return; + const audience = `factorize://runs/${runId}`; + if (matches.length !== 1 || matches[0]?.type !== "wif" || matches[0]?.config?.audience !== audience + || !Array.isArray(matches[0]?.attachments) || matches[0].attachments.length !== 1 || matches[0].attachments[0] !== `vm:${vm}`) { + throw new Error("exe.dev WIF ownership or attachment does not match"); + } + const removed = await this.api(`integrations remove ${shellAtom(name)}`); + if (!removed.ok && removed.status !== 404) throw new Error("exe.dev WIF removal failed"); + } private async api(command: string): Promise { const response = await fetch(API, { method: "POST", headers: { Authorization: `Bearer ${this.connection.apiToken}`, "Content-Type": "text/plain" }, body: command }); @@ -150,6 +205,10 @@ export class ExeVmBackend implements ExecutionBackend { if (!request.code && (!connection.agentKind || !request.harness)) throw new Error("The job is missing its agent harness launch plan"); if (request.traceSources) validateTraceSources(request.traceSources); const handle: RunHandle = request.reservation ?? { backendKind: this.kind, id: vmNameFor(request.runId) }; + if (request.verifyVendorIdentity ?? this.vendorIdentityVerifier) { + handle.operationId ??= request.runId; + handle.vendorIdentityIntegrationName ??= exeWifIntegrationNameFor(request.runId); + } const vm = this.vm(handle); let proxy: ExeRunProxy | undefined, plan: Awaited> | undefined; if (request.runProxy) { @@ -184,6 +243,18 @@ export class ExeVmBackend implements ExecutionBackend { } } + const verifyVendorIdentity = request.verifyVendorIdentity ?? this.vendorIdentityVerifier; + if (verifyVendorIdentity) { + try { + const integration = await this.ensureExeWif(vm, request.runId); + handle.vendorIdentityIntegrationName = integration.integrationName; + const token = await this.exeWifToken(vm, integration.integrationName); + await verifyVendorIdentity({ provider: "exe.dev", vmId: vm, token, integrationName: integration.integrationName, expectedIssuer: integration.issuer, expectedSubject: integration.subject }); + } catch (error) { + return { handle, destinationUrl: `https://${vm}.exe.xyz/`, capabilities, observation: { state: "failed", detail: error instanceof Error ? error.message : "exe.dev vendor identity provisioning failed", failure: { source: "system", code: "vendor_identity_failed", reason: "exe.dev vendor identity provisioning failed" } } }; + } + } + const code = request.code, output = request.traceSources?.primary.formatVersion === "codex-exec-jsonl" ? request.traceSources.primary.path : "/tmp/factorize.log", unit = vm; const launchPayload = JSON.stringify({ version: 1, runId: request.runId, ...(code ? { code } : { prompt: request.prompt, harness: request.harness }), ...(request.traceSources ? { traceSources: request.traceSources } : {}) }); const launchPayloadPath = "/home/exedev/.factorize-job/launch.json"; @@ -214,6 +285,16 @@ export class ExeVmBackend implements ExecutionBackend { async inspect(handle: RunHandle): Promise { const vm = this.vm(handle); + if (handle.operationId && handle.vendorIdentityIntegrationName && this.vendorIdentityVerifier) { + try { + const integration = await this.ensureExeWif(vm, handle.operationId, false); + if (integration.integrationName !== handle.vendorIdentityIntegrationName) throw new Error("WIF integration changed"); + const token = await this.exeWifToken(vm, handle.vendorIdentityIntegrationName); + await this.vendorIdentityVerifier({ provider: "exe.dev", vmId: vm, token, integrationName: integration.integrationName, expectedIssuer: integration.issuer, expectedSubject: integration.subject }); + } catch { + return { state: "failed", detail: "exe.dev vendor identity renewal failed", failure: { source: "system", code: "vendor_identity_renewal_failed", reason: "exe.dev vendor identity renewal failed" } }; + } + } const inspect = `sudo systemctl show ${shellAtom(vm)} --property=LoadState,ActiveState,SubState,Result,ExecMainCode,ExecMainStatus`; let response: BackendCommandResult; try { response = await this.api(`ssh ${shellAtom(vm)} ${shellAtom(inspect)}`); } @@ -316,6 +397,12 @@ export class ExeVmBackend implements ExecutionBackend { try { await new ExeRunProxy(command => this.api(command)).remove(handle.runProxyName, vm.slice("factorize-".length)); } catch { proxyError = "Run proxy cleanup failed; retry required"; } } + if (handle.vendorIdentityIntegrationName) { + try { + if (!handle.operationId) throw new Error("WIF run identity is unavailable"); + await this.removeExeWif(vm, handle.operationId, handle.vendorIdentityIntegrationName); + } catch { proxyError ??= "exe.dev WIF integration cleanup failed; retry required"; } + } const result = await this.deleteVm(vm); return { state: result.ok && !proxyError ? "stopped" : "failed", detail: proxyError ?? (result.ok ? undefined : `VM deletion failed (${result.status}): ${result.body.slice(0, 300)}`), command: result }; } diff --git a/packages/api/src/execution.ts b/packages/api/src/execution.ts index 4e4e5f53..954f3b15 100644 --- a/packages/api/src/execution.ts +++ b/packages/api/src/execution.ts @@ -21,10 +21,12 @@ export interface LaunchRequest { traceSources?: TraceSources; harness?: { executable: string; args: string[]; env: Record }; code?: { script: string; context: Record }; + /** Server-side only; the token is consumed before any job payload is launched. */ + verifyVendorIdentity?: (input: { provider: "exe.dev" | "fly.io"; vmId: string; token: string; integrationName?: string; expectedIssuer?: string; expectedSubject?: string }) => Promise; } /** Opaque to orchestration. Only the backend that created it may interpret id. */ -export interface RunHandle { backendKind: string; id: string; runProxyName?: string; /** Stable provider operation key retained across a scheduler restart. */ operationId?: string; } +export interface RunHandle { backendKind: string; id: string; runProxyName?: string; /** Stable provider operation key retained across a scheduler restart. */ operationId?: string; vendorIdentityIntegrationName?: string; } export interface ExecutionObservation { systemd?: import("./harness-diagnostics").ExecutionDiagnostics["systemd"]; diff --git a/packages/api/src/fly-job-execution-backend.ts b/packages/api/src/fly-job-execution-backend.ts index aceda92e..bb151492 100644 --- a/packages/api/src/fly-job-execution-backend.ts +++ b/packages/api/src/fly-job-execution-backend.ts @@ -17,6 +17,7 @@ export class FlyJobExecutionBackend extends MachineJobExecutionBackend { }), vmIdentity: machine => `fly:${options.app}:${machine.id}`, proxyAddress: { host: `${options.app}.internal`, port: 9090 }, + vendorIdentityAudience: options.vendorIdentityAudience ?? (runId => `factorize://runs/${runId}`), }); } } diff --git a/packages/api/src/machine-job-execution-backend.ts b/packages/api/src/machine-job-execution-backend.ts index 1d29461c..8aa93795 100644 --- a/packages/api/src/machine-job-execution-backend.ts +++ b/packages/api/src/machine-job-execution-backend.ts @@ -7,6 +7,7 @@ import type { ArtifactCollectionRequest, ArtifactCollector, ExecutionTerminator, import { sourceCommand } from "./trace-source"; import { FACTORIZE_JOB_LAUNCHER } from "./factorize-job-launcher"; import { FACTORIZE_FLY_TUNNEL_HELPER } from "./fly-job-tunnel-helper"; +import { acquireFlyMachineOidcToken } from "./vendor-run-token-sources"; const SUPPORTED_CODEX_CLI_VERSION = "codex-cli 0.167.1"; @@ -51,6 +52,8 @@ export class MachineJobExecutionBackend implements ExecutionBackend, JobResultRe proxyBootEpoch?: string; proxyGuest?: ProxyGuest; destinationUrl?: (machine: JobMachine) => string; + vendorIdentityAudience?: (runId: string) => string; + verifyVendorIdentity?: (input: { provider: "exe.dev" | "fly.io"; vmId: string; token: string; integrationName?: string; expectedIssuer?: string; expectedSubject?: string }) => Promise; }, ) {} @@ -93,6 +96,13 @@ export class MachineJobExecutionBackend implements ExecutionBackend, JobResultRe } await this.options.machines.startMachine(this.options.app, machine.id); const guest = this.options.guest(machine); + const verifyVendorIdentity = request.verifyVendorIdentity ?? this.options.verifyVendorIdentity; + if (this.kind === "fly" && verifyVendorIdentity) { + const audience = this.options.vendorIdentityAudience?.(request.runId); + if (!audience) throw new Error("Fly vendor identity audience is unavailable"); + const token = await acquireFlyMachineOidcToken({ guest, audience }); + await verifyVendorIdentity({ provider: "fly.io", vmId: machine.id, token }); + } const tunnelPrerequisites = request.runProxy ? " && command -v node >/dev/null && command -v openssl >/dev/null" : ""; const installed = await guest.run(["/bin/sh", "-c", `command -v python3 >/dev/null && command -v runuser >/dev/null${tunnelPrerequisites} && id exedev >/dev/null && mkdir -p /usr/local/bin && install -d -o exedev -g exedev -m 0700 /home/exedev/.factorize-job && cat > /usr/local/bin/factorize-job && chmod 0755 /usr/local/bin/factorize-job`], FACTORIZE_JOB_LAUNCHER); if (!installed.ok) throw new Error(request.runProxy @@ -159,6 +169,16 @@ export class MachineJobExecutionBackend implements ExecutionBackend, JobResultRe const machine = await this.options.machines.inspectMachine(this.options.app, id); switch (String(machine.state ?? "").toLowerCase()) { case "started": { + const runId = handle.operationId; + const audience = runId && this.options.vendorIdentityAudience?.(runId); + if (runId && audience && this.options.verifyVendorIdentity) { + try { + const token = await acquireFlyMachineOidcToken({ guest: this.options.guest({ id }), audience }); + await this.options.verifyVendorIdentity({ provider: "fly.io", vmId: id, token }); + } catch { + return { state: "failed", detail: "Fly Machine vendor identity renewal failed", failure: { source: "system", code: "vendor_identity_renewal_failed", reason: "Fly Machine vendor identity renewal failed" } }; + } + } try { const result = await this.options.guest(machine).run(["/usr/sbin/runuser", "-u", "exedev", "--", "/usr/local/bin/factorize-job", "status"]); if (result.ok) { diff --git a/packages/api/src/postgres/run-scheduler.ts b/packages/api/src/postgres/run-scheduler.ts index 060d69de..54b7efdf 100644 --- a/packages/api/src/postgres/run-scheduler.ts +++ b/packages/api/src/postgres/run-scheduler.ts @@ -28,6 +28,7 @@ import { FlyExecutionConfigurationRepository } from "./fly-execution-configurati import { createFlyMachinesClient } from "../fly-machines-client"; import { FlyJobExecutionBackend, flyJobGuest } from "../fly-job-execution-backend"; import { createFlyCredentialProxyGuest } from "../fly-credential-proxy-provisioner"; +import { verifyAndPersistVendorRunIdentity } from "../vendor-run-identity-provisioning"; /** Host runners may supply infrastructure without patching scheduler internals. */ export type RunBackendFactory = (run: PersistedRun) => ExecutionBackend | undefined | Promise; @@ -122,6 +123,16 @@ export class RunScheduler { private connections(run: PersistedRun) { return new ConnectionRepository(this.database, run.tenantId, this.env.CREDENTIAL_ENCRYPTION_KEY); } + private vendorIdentityVerifier(run: PersistedRun, expectedIssuer?: string) { + return async (input: { provider: "exe.dev" | "fly.io"; vmId: string; token: string; integrationName?: string; expectedIssuer?: string; expectedSubject?: string }) => { + await verifyAndPersistVendorRunIdentity({ + database: this.database, tenantId: run.tenantId, runId: run.id, provider: input.provider, + vmId: input.vmId, token: input.token, audience: `factorize://runs/${run.id}`, + integrationName: input.integrationName, expectedIssuer: input.expectedIssuer ?? expectedIssuer, expectedSubject: input.expectedSubject, + }); + }; + } + private hasCapability(backend: ExecutionBackend, method: keyof T): backend is ExecutionBackend & T { return typeof (backend as unknown as Record)[method] === "function"; } @@ -150,13 +161,15 @@ export class RunScheduler { proxyIdentity: rows[0]!.proxy_identity, proxyBootEpoch: rows[0]!.boot_epoch, proxyGuest: createFlyCredentialProxyGuest({ app, machine: proxy[2]!, token: connection }), + vendorIdentityAudience: runId => `factorize://runs/${runId}`, + verifyVendorIdentity: this.vendorIdentityVerifier(run, `https://oidc.fly.io/${app}`), }); } const kind = run.executionConfig.backendKind ?? (run.executionConfig.agentKind === "Amp" ? "amp" : "exe-vm"); if (kind === "amp") { const connection = await this.connections(run).get(`amp:${id}`); if (!connection) throw new Error("Amp connection is unavailable"); return new AmpBackend(connection); } if (kind !== "exe-vm") throw new Error(`Unsupported execution backend: ${String(kind)}`); const connection = await this.connections(run).get(`exe:${id}`); if (!connection) throw new Error("exe.dev connection is unavailable"); - return new ExeVmBackend({ ...connection, tags: Array.isArray(run.executionConfig.tags) ? run.executionConfig.tags : [], image: typeof run.executionConfig.image === "string" ? run.executionConfig.image : undefined, model: String(run.executionConfig.model ?? ""), effort: String(run.executionConfig.effort ?? "") }); + return new ExeVmBackend({ ...connection, tags: Array.isArray(run.executionConfig.tags) ? run.executionConfig.tags : [], image: typeof run.executionConfig.image === "string" ? run.executionConfig.image : undefined, model: String(run.executionConfig.model ?? ""), effort: String(run.executionConfig.effort ?? "") }, this.vendorIdentityVerifier(run)); } private async launch(run: PersistedRun) { @@ -176,7 +189,7 @@ export class RunScheduler { const runToken = await issueRunCredential(this.env, run.tenantId, run.id, run.executionConfig.runScopes); const reservation = backend.reserve?.(run.id) ?? null; if (reservation) await this.runs.recordLaunchHandle(run, reservation); - const launched = await backend.launch({ runId: run.id, reservation: reservation ?? undefined, prompt: "", runProxy: { targetOrigin: this.env.APP_ORIGIN, credential: runToken }, code: { script: run.executionConfig.script, context } }); + const launched = await backend.launch({ runId: run.id, reservation: reservation ?? undefined, prompt: "", runProxy: { targetOrigin: this.env.APP_ORIGIN, credential: runToken }, code: { script: run.executionConfig.script, context }, verifyVendorIdentity: this.vendorIdentityVerifier(run) }); await this.runs.markLaunched(run, launched.handle, launched.destinationUrl, launched.capabilities); if (launched.observation.state === "failed") await this.runs.recordObservation(run, launched.observation); return; @@ -189,7 +202,7 @@ export class RunScheduler { const prompt = await decrypt(run.encryptedPrompt, this.env.CREDENTIAL_ENCRYPTION_KEY); const reservation = backend.reserve?.(run.id) ?? null; if (reservation) await this.runs.recordLaunchHandle(run, reservation); - const launched = await backend.launch({ runId: run.id, reservation: reservation ?? undefined, prompt: `${prompt}${JOB_RESULT_INSTRUCTIONS}${runProxyInstructions(run.id)}`, runProxy: { targetOrigin: this.env.APP_ORIGIN, credential: runToken }, traceSources: sources, harness: { executable: harness.executable, args: harness.args, env: harness.env } }); + const launched = await backend.launch({ runId: run.id, reservation: reservation ?? undefined, prompt: `${prompt}${JOB_RESULT_INSTRUCTIONS}${runProxyInstructions(run.id)}`, runProxy: { targetOrigin: this.env.APP_ORIGIN, credential: runToken }, traceSources: sources, harness: { executable: harness.executable, args: harness.args, env: harness.env }, verifyVendorIdentity: this.vendorIdentityVerifier(run) }); await this.runs.markLaunched(run, launched.handle, launched.destinationUrl, launched.capabilities, sources); if (launched.observation.state === "failed") await this.runs.recordObservation(run, launched.observation); } diff --git a/packages/api/src/vendor-run-identity-provisioning.ts b/packages/api/src/vendor-run-identity-provisioning.ts new file mode 100644 index 00000000..73248210 --- /dev/null +++ b/packages/api/src/vendor-run-identity-provisioning.ts @@ -0,0 +1,57 @@ +import type { Database } from "./postgres/database"; +import { VendorRunIdentityRepository } from "./postgres/vendor-run-identity-repository"; +import { discoverVendorIssuerTrust, verifyVendorRunIdentity, type VendorIdentityProvider } from "./vendor-run-identity"; + +function issuerFromToken(token: string): string { + try { + const payload = token.split(".")[1]; + if (!payload) throw new Error(); + const claims = JSON.parse(atob(payload.replaceAll("-", "+").replaceAll("_", "/"))) as { iss?: unknown }; + if (typeof claims.iss !== "string") throw new Error(); + return claims.iss; + } catch { + throw new Error("Vendor identity token has no valid issuer"); + } +} + +/** Verify a provider token against the provisioned machine and durably bind it + * to the active run. Only claim metadata is persisted; the JWT is discarded. */ +export async function verifyAndPersistVendorRunIdentity(input: { + database: Database; + tenantId: string; + runId: string; + provider: VendorIdentityProvider; + vmId: string; + token: string; + audience: string; + integrationName?: string; + expectedIssuer?: string; + expectedSubject?: string; + now?: Date; +}) { + const repository = new VendorRunIdentityRepository(input.database); + const now = input.now ?? new Date(); + const prior = await repository.getActive({ tenantId: input.tenantId, runId: input.runId, provider: input.provider, now }); + const issuer = issuerFromToken(input.token); + if (input.expectedIssuer && issuer !== input.expectedIssuer) throw new Error("Vendor identity issuer mismatch"); + const trust = await discoverVendorIssuerTrust({ provider: input.provider, issuer }); + const identity = await verifyVendorRunIdentity({ + token: input.token, + resolveKey: trust.resolveKey, + nowSeconds: Math.floor(now.getTime() / 1000), + binding: { + provider: input.provider, + runId: input.runId, + activeRunId: input.runId, + vmId: input.vmId, + issuer: prior?.issuer ?? trust.issuer, + audience: prior?.audience ?? input.audience, + ...((prior?.subject ?? input.expectedSubject) ? { subject: prior?.subject ?? input.expectedSubject } : {}), + ...(input.provider === "exe.dev" && input.integrationName ? { + exeAttachment: { integrationName: input.integrationName, attachedVmId: input.vmId, mode: "vm" as const }, + } : {}), + }, + }); + if (identity.audience !== input.audience) throw new Error("Vendor identity audience mismatch"); + return repository.persistVerified({ tenantId: input.tenantId, identity, issuedAt: identity.issuedAt, now }); +} diff --git a/packages/api/test/execution-backend.test.ts b/packages/api/test/execution-backend.test.ts index 34bf9f51..d1ff97d7 100644 --- a/packages/api/test/execution-backend.test.ts +++ b/packages/api/test/execution-backend.test.ts @@ -25,7 +25,7 @@ function launchPayload(command: string): any { describe("ExeVmBackend", () => { it("reserves its legacy VM and proxy handle for scheduler recovery", () => { const runId = "00000000-0000-4000-8000-000000000001"; - expect(new ExeVmBackend(connection).reserve(runId)).toEqual({ backendKind: "exe-vm", id: vmNameFor(runId), runProxyName: runProxyName(runId) }); + expect(new ExeVmBackend(connection).reserve(runId)).toEqual({ backendKind: "exe-vm", id: vmNameFor(runId), runProxyName: runProxyName(runId), operationId: runId, vendorIdentityIntegrationName: "fzrun-00000000000040008000000000000001" }); }); it("defines the supported effort choices by agent", () => { expect(effortOptions.codex).toEqual(["minimal", "low", "medium", "high", "xhigh"]); @@ -110,6 +110,26 @@ describe("ExeVmBackend", () => { expect(requests[1]).toContain("systemctl show"); }); + it("acquires a per-VM exe.dev WIF identity and verifies it before starting the job", async () => { + const requests: string[] = [], token = "eyJhbGciOiJSUzI1NiJ9.eyJpc3MiOiJodHRwczovL2V4ZS5kZXYvaXNzdWVyL3Rlc3QifQ.c2ln"; + vi.stubGlobal("fetch", vi.fn(async (_url: string, init: RequestInit) => { + const command = String(init.body); requests.push(command); + if (command.startsWith("new ")) return new Response("created", { headers: { "X-Exe-Exit": "0" } }); + if (command.startsWith("integrations add wif")) return new Response("Added integration", { headers: { "X-Exe-Exit": "0" } }); + if (command === "integrations list --json") return new Response(JSON.stringify([{ name: "fzrun-00000000000040008000000000000001", type: "wif", config: { issuer_id: "test", subject: "sub-test", audience: "factorize://runs/00000000-0000-4000-8000-000000000001" }, attachments: ["vm:factorize-00000000-0000-4000-8000-000000000001"] }]), { headers: { "X-Exe-Exit": "0" } }); + if (command.includes("/token")) return new Response(token, { headers: { "X-Exe-Exit": "0" } }); + return new Response("started", { headers: { "X-Exe-Exit": "0" } }); + })); + const verify = vi.fn(async () => undefined); + const runId = "00000000-0000-4000-8000-000000000001"; + const launched = await new ExeVmBackend(connection).launch({ runId, prompt: "work", harness: agentDriver("codex").launch(runId, {}), verifyVendorIdentity: verify }); + expect(launched.observation.state).toBe("running"); + expect(requests[1]).toContain("integrations add wif"); + expect(requests[1]).toContain("--attach='vm:factorize-00000000-0000-4000-8000-000000000001'"); + expect(verify).toHaveBeenCalledWith({ provider: "exe.dev", vmId: "factorize-00000000-0000-4000-8000-000000000001", token, integrationName: "fzrun-00000000000040008000000000000001", expectedIssuer: "https://exe.dev/issuer/test", expectedSubject: "sub-test" }); + expect(requests.indexOf(requests.find(value => value.includes("sudo systemd-run"))!)).toBeGreaterThan(requests.indexOf(requests.find(value => value.includes("/token"))!)); + }); + it("generates standard I/O settings accepted by systemd", async () => { const requests: string[] = []; vi.stubGlobal("fetch", vi.fn(async (_url: string, init: RequestInit) => { diff --git a/packages/api/test/fly-job-execution-backend.test.ts b/packages/api/test/fly-job-execution-backend.test.ts index 5305f682..d5974ada 100644 --- a/packages/api/test/fly-job-execution-backend.test.ts +++ b/packages/api/test/fly-job-execution-backend.test.ts @@ -49,6 +49,20 @@ describe("Fly job execution backend", () => { expect(JSON.stringify(f.machines.createMachine.mock.calls)).not.toContain("echo ok"); }); + it("verifies the Fly Machine OIDC token before installing or launching the job", async () => { + const f = fixture(); + const token = "eyJhbGciOiJSUzI1NiJ9.eyJpc3MiOiJodHRwczovL29pZGMuZmx5LmlvL2ZhY3Rvcml6ZS10ZXN0In0.c2ln"; + f.guest.run.mockResolvedValueOnce({ ok: true, exitCode: 0, stdout: token, stderr: "" }); + const verify = vi.fn(async () => undefined); + const runId = "11111111-1111-4111-8111-111111111111"; + const backend = new FlyJobExecutionBackend({ app: "factorize-test", image: "ghcr.io/acme/code:v1", region: "iad", size: "shared-cpu-1x", machines: f.machines, guest: () => f.guest, verifyVendorIdentity: verify }); + const receipt = await backend.launch({ runId, prompt: "work" }); + expect(receipt.observation.state).toBe("running"); + expect(f.guest.run.mock.calls[0]?.[0]).toContain("http://localhost/v1/tokens/oidc"); + expect(verify).toHaveBeenCalledWith({ provider: "fly.io", vmId: "machine-1", token }); + expect(verify.mock.invocationCallOrder[0]).toBeLessThan(f.guest.run.mock.invocationCallOrder.at(-1)!); + }); + it("reports a nonzero Fly guest process exit as a failed run", async () => { const f = fixture(); f.machines.inspectMachine.mockResolvedValue({ ...machine, state: "started" }); diff --git a/packages/api/test/vendor-run-identity.postgres.test.ts b/packages/api/test/vendor-run-identity.postgres.test.ts index 515bd97b..cad3d1aa 100644 --- a/packages/api/test/vendor-run-identity.postgres.test.ts +++ b/packages/api/test/vendor-run-identity.postgres.test.ts @@ -1,7 +1,8 @@ -import { afterAll, beforeAll, describe, expect, it } from "vitest"; +import { afterAll, beforeAll, describe, expect, it, vi } from "vitest"; import { Database } from "../src/postgres/database"; import { VendorRunIdentityRepository } from "../src/postgres/vendor-run-identity-repository"; import type { VendorIdentity } from "../src/vendor-run-identity"; +import { verifyAndPersistVendorRunIdentity } from "../src/vendor-run-identity-provisioning"; const url = process.env.AUTH_TEST_DATABASE_URL; @@ -60,4 +61,37 @@ describe.skipIf(!url)("durable vendor run identity bindings (PostgreSQL)", () => await expired.repository.persistVerified({ tenantId: expired.tenantId, identity: expired.identity, issuedAt: expired.identity.issuedAt, now: expired.now }); expect(await expired.repository.getActive({ tenantId: expired.tenantId, runId: expired.runId, provider: "fly.io", now: new Date(expired.identity.expiresAt * 1000) })).toBeNull(); }, 30_000); + + it("verifies a signed Fly token before persisting and renewing its active VM binding", async () => { + const f = await fixture(); + const issuer = f.identity.issuer, audience = `factorize://runs/${f.runId}`, subject = f.identity.subject; + const pair = await crypto.subtle.generateKey({ name: "RSASSA-PKCS1-v1_5", modulusLength: 2048, publicExponent: new Uint8Array([1, 0, 1]), hash: "SHA-256" }, true, ["sign", "verify"]); + const jwk = await crypto.subtle.exportKey("jwk", pair.publicKey); + const base64url = (value: Uint8Array) => Buffer.from(value).toString("base64url"); + const sign = async (issuedAt: number, machineId = f.identity.vmId) => { + const header = base64url(new TextEncoder().encode(JSON.stringify({ alg: "RS256", kid: "fixture-key" }))); + const payload = base64url(new TextEncoder().encode(JSON.stringify({ iss: issuer, sub: subject, aud: audience, iat: issuedAt, exp: issuedAt + 600, machine_id: machineId }))); + const input = `${header}.${payload}`; + const signature = new Uint8Array(await crypto.subtle.sign("RSASSA-PKCS1-v1_5", pair.privateKey, new TextEncoder().encode(input))); + return `${input}.${base64url(signature)}`; + }; + const now = Math.floor(Date.now() / 1000); + const fetcher = vi.fn(async (url: string | URL | Request) => String(url).endsWith("/.well-known/openid-configuration") + ? Response.json({ issuer, jwks_uri: `${issuer}/keys` }) + : Response.json({ keys: [{ ...jwk, kid: "fixture-key", use: "sig" }] })); + vi.stubGlobal("fetch", fetcher); + try { + const first = await sign(now - 5); + await expect(verifyAndPersistVendorRunIdentity({ database: db, tenantId: f.tenantId, runId: f.runId, provider: "fly.io", vmId: f.identity.vmId, token: first, audience, expectedIssuer: issuer, now: new Date(now * 1000) })) + .resolves.toMatchObject({ provider: "fly.io", vmId: f.identity.vmId, issuer, subject, audience }); + const renewed = await sign(now + 30); + await expect(verifyAndPersistVendorRunIdentity({ database: db, tenantId: f.tenantId, runId: f.runId, provider: "fly.io", vmId: f.identity.vmId, token: renewed, audience, expectedIssuer: issuer, now: new Date((now + 30) * 1000) })) + .resolves.toMatchObject({ expiresAt: new Date((now + 630) * 1000) }); + await expect(verifyAndPersistVendorRunIdentity({ database: db, tenantId: f.tenantId, runId: f.runId, provider: "fly.io", vmId: f.identity.vmId, token: await sign(now + 60, "another-machine"), audience, expectedIssuer: issuer, now: new Date((now + 60) * 1000) })) + .rejects.toThrow("VM mismatch"); + await f.repository.revoke({ tenantId: f.tenantId, runId: f.runId, provider: "fly.io", now: new Date((now + 60) * 1000) }); + await expect(verifyAndPersistVendorRunIdentity({ database: db, tenantId: f.tenantId, runId: f.runId, provider: "fly.io", vmId: f.identity.vmId, token: await sign(now + 90), audience, expectedIssuer: issuer, now: new Date((now + 90) * 1000) })) + .rejects.toThrow("binding is revoked"); + } finally { vi.unstubAllGlobals(); } + }, 30_000); }); From b311a6860135270337ffde794fbfe420edf207c1 Mon Sep 17 00:00:00 2001 From: "exe.dev user" Date: Mon, 16 Nov 2026 20:01:01 +0000 Subject: [PATCH 06/28] Bind Fly identity subject to the provisioned machine --- packages/api/src/fly-job-execution-backend.ts | 3 ++- .../api/src/machine-job-execution-backend.ts | 11 ++++++++--- packages/api/src/postgres/run-scheduler.ts | 6 ++++-- .../api/test/fly-job-execution-backend.test.ts | 6 +++--- .../test/vendor-run-identity.postgres.test.ts | 18 ++++++++++-------- 5 files changed, 27 insertions(+), 17 deletions(-) diff --git a/packages/api/src/fly-job-execution-backend.ts b/packages/api/src/fly-job-execution-backend.ts index bb151492..5cfa879c 100644 --- a/packages/api/src/fly-job-execution-backend.ts +++ b/packages/api/src/fly-job-execution-backend.ts @@ -7,7 +7,7 @@ type SharedOptions = ConstructorParameters[0] /** Preserves persisted Fly handles while sharing the complete guest lifecycle. */ export class FlyJobExecutionBackend extends MachineJobExecutionBackend { - constructor(options: Omit & { region: string; size: string }) { + constructor(options: Omit & { region: string; size: string; organizationName?: string }) { super({ ...options, kind: "fly", @@ -18,6 +18,7 @@ export class FlyJobExecutionBackend extends MachineJobExecutionBackend { vmIdentity: machine => `fly:${options.app}:${machine.id}`, proxyAddress: { host: `${options.app}.internal`, port: 9090 }, vendorIdentityAudience: options.vendorIdentityAudience ?? (runId => `factorize://runs/${runId}`), + ...(options.organizationName ? { vendorIdentitySubject: machine => machine.name ? `${options.organizationName}:${options.app}:${machine.name}` : "" } : {}), }); } } diff --git a/packages/api/src/machine-job-execution-backend.ts b/packages/api/src/machine-job-execution-backend.ts index 8aa93795..00877abf 100644 --- a/packages/api/src/machine-job-execution-backend.ts +++ b/packages/api/src/machine-job-execution-backend.ts @@ -1,5 +1,5 @@ import type { ExecutionBackend, ExecutionObservation, LaunchReceipt, LaunchRequest, RunHandle } from "./execution"; -export type JobMachine = { id: string; state?: string; config?: { metadata?: Record } }; +export type JobMachine = { id: string; name?: string; state?: string; config?: { metadata?: Record } }; export type JobMachineConfig = Record & { metadata?: Record }; import { createHash } from "node:crypto"; import { safeDiagnosticText } from "./harness-diagnostics"; @@ -53,6 +53,7 @@ export class MachineJobExecutionBackend implements ExecutionBackend, JobResultRe proxyGuest?: ProxyGuest; destinationUrl?: (machine: JobMachine) => string; vendorIdentityAudience?: (runId: string) => string; + vendorIdentitySubject?: (machine: JobMachine) => string; verifyVendorIdentity?: (input: { provider: "exe.dev" | "fly.io"; vmId: string; token: string; integrationName?: string; expectedIssuer?: string; expectedSubject?: string }) => Promise; }, ) {} @@ -101,7 +102,9 @@ export class MachineJobExecutionBackend implements ExecutionBackend, JobResultRe const audience = this.options.vendorIdentityAudience?.(request.runId); if (!audience) throw new Error("Fly vendor identity audience is unavailable"); const token = await acquireFlyMachineOidcToken({ guest, audience }); - await verifyVendorIdentity({ provider: "fly.io", vmId: machine.id, token }); + const expectedSubject = this.options.vendorIdentitySubject?.(machine); + if (this.options.vendorIdentitySubject && !expectedSubject) throw new Error("Fly vendor identity subject is unavailable"); + await verifyVendorIdentity({ provider: "fly.io", vmId: machine.id, token, ...(expectedSubject ? { expectedSubject } : {}) }); } const tunnelPrerequisites = request.runProxy ? " && command -v node >/dev/null && command -v openssl >/dev/null" : ""; const installed = await guest.run(["/bin/sh", "-c", `command -v python3 >/dev/null && command -v runuser >/dev/null${tunnelPrerequisites} && id exedev >/dev/null && mkdir -p /usr/local/bin && install -d -o exedev -g exedev -m 0700 /home/exedev/.factorize-job && cat > /usr/local/bin/factorize-job && chmod 0755 /usr/local/bin/factorize-job`], FACTORIZE_JOB_LAUNCHER); @@ -174,7 +177,9 @@ export class MachineJobExecutionBackend implements ExecutionBackend, JobResultRe if (runId && audience && this.options.verifyVendorIdentity) { try { const token = await acquireFlyMachineOidcToken({ guest: this.options.guest({ id }), audience }); - await this.options.verifyVendorIdentity({ provider: "fly.io", vmId: id, token }); + const expectedSubject = this.options.vendorIdentitySubject?.(machine); + if (this.options.vendorIdentitySubject && !expectedSubject) throw new Error("Fly vendor identity subject is unavailable"); + await this.options.verifyVendorIdentity({ provider: "fly.io", vmId: id, token, ...(expectedSubject ? { expectedSubject } : {}) }); } catch { return { state: "failed", detail: "Fly Machine vendor identity renewal failed", failure: { source: "system", code: "vendor_identity_renewal_failed", reason: "Fly Machine vendor identity renewal failed" } }; } diff --git a/packages/api/src/postgres/run-scheduler.ts b/packages/api/src/postgres/run-scheduler.ts index 54b7efdf..f94e7d9c 100644 --- a/packages/api/src/postgres/run-scheduler.ts +++ b/packages/api/src/postgres/run-scheduler.ts @@ -141,11 +141,13 @@ export class RunScheduler { if (supplied) return supplied; const id = String(run.executionConfig.connectionId ?? ""); if (run.backendKind === "fly" || run.executionConfig.executionProvider === "fly") { - const [connection, configuration] = await Promise.all([ + const [connection, connectionDetails, configuration] = await Promise.all([ new FlyConnectionRepository(this.database, run.tenantId, this.env.CREDENTIAL_ENCRYPTION_KEY).token(), + new FlyConnectionRepository(this.database, run.tenantId, this.env.CREDENTIAL_ENCRYPTION_KEY).get(), new FlyExecutionConfigurationRepository(this.database, run.tenantId).get(id), ]); if (!connection) throw new Error("Fly connection is unavailable"); + if (!connectionDetails) throw new Error("Fly connection is unavailable"); if (!configuration) throw new Error("Fly execution configuration is unavailable"); const { rows } = await this.database.pool.query<{ proxy_identity: string; boot_epoch: string }>( "SELECT proxy_identity, boot_epoch FROM app.credential_proxy_states WHERE tenant_id=$1 AND disabled_at IS NULL AND revoked_at IS NULL", @@ -156,7 +158,7 @@ export class RunScheduler { const app = proxy[1]!; const machines = createFlyMachinesClient({ token: connection }); return new FlyJobExecutionBackend({ - app, image: configuration.image, region: configuration.region, size: configuration.size, + app, organizationName: connectionDetails.organizationName, image: configuration.image, region: configuration.region, size: configuration.size, machines, guest: machine => flyJobGuest({ app, machine: machine.id, token: connection }), proxyIdentity: rows[0]!.proxy_identity, proxyBootEpoch: rows[0]!.boot_epoch, diff --git a/packages/api/test/fly-job-execution-backend.test.ts b/packages/api/test/fly-job-execution-backend.test.ts index d5974ada..4fb05940 100644 --- a/packages/api/test/fly-job-execution-backend.test.ts +++ b/packages/api/test/fly-job-execution-backend.test.ts @@ -2,7 +2,7 @@ import { describe, expect, it, vi } from "vitest"; import { FlyJobExecutionBackend } from "../src/fly-job-execution-backend"; import { agentDriver } from "../src/agent-driver"; -const machine = { id: "machine-1", state: "created" }; +const machine = { id: "machine-1", name: "machine-name", state: "created" }; function fixture() { const machines = { findMachineByOperationId: vi.fn(async () => machine), @@ -55,11 +55,11 @@ describe("Fly job execution backend", () => { f.guest.run.mockResolvedValueOnce({ ok: true, exitCode: 0, stdout: token, stderr: "" }); const verify = vi.fn(async () => undefined); const runId = "11111111-1111-4111-8111-111111111111"; - const backend = new FlyJobExecutionBackend({ app: "factorize-test", image: "ghcr.io/acme/code:v1", region: "iad", size: "shared-cpu-1x", machines: f.machines, guest: () => f.guest, verifyVendorIdentity: verify }); + const backend = new FlyJobExecutionBackend({ app: "factorize-test", organizationName: "factorize-org", image: "ghcr.io/acme/code:v1", region: "iad", size: "shared-cpu-1x", machines: f.machines, guest: () => f.guest, verifyVendorIdentity: verify }); const receipt = await backend.launch({ runId, prompt: "work" }); expect(receipt.observation.state).toBe("running"); expect(f.guest.run.mock.calls[0]?.[0]).toContain("http://localhost/v1/tokens/oidc"); - expect(verify).toHaveBeenCalledWith({ provider: "fly.io", vmId: "machine-1", token }); + expect(verify).toHaveBeenCalledWith({ provider: "fly.io", vmId: "machine-1", token, expectedSubject: "factorize-org:factorize-test:machine-name" }); expect(verify.mock.invocationCallOrder[0]).toBeLessThan(f.guest.run.mock.invocationCallOrder.at(-1)!); }); diff --git a/packages/api/test/vendor-run-identity.postgres.test.ts b/packages/api/test/vendor-run-identity.postgres.test.ts index cad3d1aa..ea94c6f3 100644 --- a/packages/api/test/vendor-run-identity.postgres.test.ts +++ b/packages/api/test/vendor-run-identity.postgres.test.ts @@ -26,7 +26,7 @@ describe.skipIf(!url)("durable vendor run identity bindings (PostgreSQL)", () => 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 identity: VendorIdentity = { provider: "fly.io", runId, vmId: `fm-${crypto.randomUUID()}`, issuer: "https://oidc.fly.io/factorize-test", - subject: `test:factorize-test:${crypto.randomUUID()}`, audience: `factorize://runs/${runId}`, issuedAt: 1_800_000_000, + subject: `factorize-org:factorize-test:${crypto.randomUUID()}`, audience: `factorize://runs/${runId}`, issuedAt: 1_800_000_000, expiresAt: 1_800_000_600, keyId: "fixture-key", ...identityOverrides, }; return { tenantId, runId, identity, repository: new VendorRunIdentityRepository(db), now: new Date(identity.issuedAt * 1000) }; @@ -64,13 +64,13 @@ describe.skipIf(!url)("durable vendor run identity bindings (PostgreSQL)", () => it("verifies a signed Fly token before persisting and renewing its active VM binding", async () => { const f = await fixture(); - const issuer = f.identity.issuer, audience = `factorize://runs/${f.runId}`, subject = f.identity.subject; + const issuer = f.identity.issuer, audience = `factorize://runs/${f.runId}`, subject = `factorize-org:factorize-test:factorize-run`; const pair = await crypto.subtle.generateKey({ name: "RSASSA-PKCS1-v1_5", modulusLength: 2048, publicExponent: new Uint8Array([1, 0, 1]), hash: "SHA-256" }, true, ["sign", "verify"]); const jwk = await crypto.subtle.exportKey("jwk", pair.publicKey); const base64url = (value: Uint8Array) => Buffer.from(value).toString("base64url"); - const sign = async (issuedAt: number, machineId = f.identity.vmId) => { + const sign = async (issuedAt: number, machineId = f.identity.vmId, tokenSubject = subject) => { const header = base64url(new TextEncoder().encode(JSON.stringify({ alg: "RS256", kid: "fixture-key" }))); - const payload = base64url(new TextEncoder().encode(JSON.stringify({ iss: issuer, sub: subject, aud: audience, iat: issuedAt, exp: issuedAt + 600, machine_id: machineId }))); + const payload = base64url(new TextEncoder().encode(JSON.stringify({ iss: issuer, sub: tokenSubject, aud: audience, iat: issuedAt, exp: issuedAt + 600, machine_id: machineId }))); const input = `${header}.${payload}`; const signature = new Uint8Array(await crypto.subtle.sign("RSASSA-PKCS1-v1_5", pair.privateKey, new TextEncoder().encode(input))); return `${input}.${base64url(signature)}`; @@ -82,15 +82,17 @@ describe.skipIf(!url)("durable vendor run identity bindings (PostgreSQL)", () => vi.stubGlobal("fetch", fetcher); try { const first = await sign(now - 5); - await expect(verifyAndPersistVendorRunIdentity({ database: db, tenantId: f.tenantId, runId: f.runId, provider: "fly.io", vmId: f.identity.vmId, token: first, audience, expectedIssuer: issuer, now: new Date(now * 1000) })) + await expect(verifyAndPersistVendorRunIdentity({ database: db, tenantId: f.tenantId, runId: f.runId, provider: "fly.io", vmId: f.identity.vmId, token: first, audience, expectedIssuer: issuer, expectedSubject: subject, now: new Date(now * 1000) })) .resolves.toMatchObject({ provider: "fly.io", vmId: f.identity.vmId, issuer, subject, audience }); const renewed = await sign(now + 30); - await expect(verifyAndPersistVendorRunIdentity({ database: db, tenantId: f.tenantId, runId: f.runId, provider: "fly.io", vmId: f.identity.vmId, token: renewed, audience, expectedIssuer: issuer, now: new Date((now + 30) * 1000) })) + await expect(verifyAndPersistVendorRunIdentity({ database: db, tenantId: f.tenantId, runId: f.runId, provider: "fly.io", vmId: f.identity.vmId, token: renewed, audience, expectedIssuer: issuer, expectedSubject: subject, now: new Date((now + 30) * 1000) })) .resolves.toMatchObject({ expiresAt: new Date((now + 630) * 1000) }); - await expect(verifyAndPersistVendorRunIdentity({ database: db, tenantId: f.tenantId, runId: f.runId, provider: "fly.io", vmId: f.identity.vmId, token: await sign(now + 60, "another-machine"), audience, expectedIssuer: issuer, now: new Date((now + 60) * 1000) })) + await expect(verifyAndPersistVendorRunIdentity({ database: db, tenantId: f.tenantId, runId: f.runId, provider: "fly.io", vmId: f.identity.vmId, token: await sign(now + 60, "another-machine"), audience, expectedIssuer: issuer, expectedSubject: subject, now: new Date((now + 60) * 1000) })) .rejects.toThrow("VM mismatch"); + await expect(verifyAndPersistVendorRunIdentity({ database: db, tenantId: f.tenantId, runId: f.runId, provider: "fly.io", vmId: f.identity.vmId, token: await sign(now + 60, f.identity.vmId, "another-org:factorize-test:machine-name"), audience, expectedIssuer: issuer, expectedSubject: subject, now: new Date((now + 60) * 1000) })) + .rejects.toThrow("subject mismatch"); await f.repository.revoke({ tenantId: f.tenantId, runId: f.runId, provider: "fly.io", now: new Date((now + 60) * 1000) }); - await expect(verifyAndPersistVendorRunIdentity({ database: db, tenantId: f.tenantId, runId: f.runId, provider: "fly.io", vmId: f.identity.vmId, token: await sign(now + 90), audience, expectedIssuer: issuer, now: new Date((now + 90) * 1000) })) + await expect(verifyAndPersistVendorRunIdentity({ database: db, tenantId: f.tenantId, runId: f.runId, provider: "fly.io", vmId: f.identity.vmId, token: await sign(now + 90), audience, expectedIssuer: issuer, expectedSubject: subject, now: new Date((now + 90) * 1000) })) .rejects.toThrow("binding is revoked"); } finally { vi.unstubAllGlobals(); } }, 30_000); From 1367265977dc934a2c340b0de2613a9fac5d6474 Mon Sep 17 00:00:00 2001 From: "exe.dev user" Date: Mon, 16 Nov 2026 20:25:16 +0000 Subject: [PATCH 07/28] Store bearer credentials with Factorize-managed encryption --- packages/api-client/src/schema.d.ts | 19 ++-- packages/api/src/api-contract.ts | 18 ++-- packages/api/src/flow-service.ts | 11 +-- .../encrypted-integration-repository.ts | 16 +++- packages/api/test/api-contract.test.ts | 11 +++ packages/api/test/docker-code-job.e2e.test.ts | 6 +- ...encrypted-integration-api.postgres.test.ts | 37 ++++---- .../features/settings/bearer-integrations.tsx | 36 ++------ packages/app/test/settings.browser.test.mjs | 89 ++++--------------- .../credential-proxy/src/decrypted-grants.mjs | 26 ++++-- .../test/decrypted-grants.test.mjs | 23 +++-- .../test/fly-guest-helper.e2e.test.mjs | 2 +- packages/docs/openapi.yaml | 29 +++--- 13 files changed, 146 insertions(+), 177 deletions(-) diff --git a/packages/api-client/src/schema.d.ts b/packages/api-client/src/schema.d.ts index d728a542..00b27998 100644 --- a/packages/api-client/src/schema.d.ts +++ b/packages/api-client/src/schema.d.ts @@ -216,8 +216,8 @@ export interface paths { cookie?: never; }; /** - * List encrypted bearer integrations - * @description Requires an interactive owner browser session. Returns safe metadata and user-encrypted ciphertext; credentials are never decrypted or revealed. + * List bearer integration metadata + * @description Requires an interactive owner browser session. Returns secret-safe metadata only; stored bearer credentials are never returned. * * Requires the integrations:read scope. * @@ -226,8 +226,8 @@ export interface paths { get: operations["get_api_v1_integrations_bearer"]; put?: never; /** - * Create an encrypted bearer integration - * @description Requires an interactive owner browser session. Accepts only user-encrypted ciphertext, never an unlock key or plaintext credential. + * Create a bearer integration + * @description Requires an interactive owner browser session. Accepts the secret over the authenticated connection and encrypts it with Factorize-managed storage before persistence. The secret is never returned. * * Requires the integrations:write scope. * @@ -249,8 +249,8 @@ export interface paths { }; get?: never; /** - * Update an encrypted bearer integration - * @description Requires an interactive owner browser session and the current collection revision. Accepts only user-encrypted ciphertext. + * Update a bearer integration + * @description Requires an interactive owner browser session and the current collection revision. Accepts a replacement secret and encrypts it with Factorize-managed storage before persistence. The secret is never returned. * * Requires the integrations:write scope. * @@ -3351,7 +3351,7 @@ export interface operations { }; requestBody?: never; responses: { - /** @description Encrypted bearer integration records */ + /** @description Bearer integration metadata */ 200: { headers: { [name: string]: unknown; @@ -3366,7 +3366,6 @@ export interface operations { origin: string; description: string | null; revision: number; - encryptedPayload: string; }[]; }; }; @@ -3400,7 +3399,7 @@ export interface operations { /** Format: uri */ origin: string; description: string | null; - encryptedPayload: string; + token: string; }; }; }; @@ -3447,7 +3446,7 @@ export interface operations { /** Format: uri */ origin: string; description: string | null; - encryptedPayload: string; + token: string; }; }; }; diff --git a/packages/api/src/api-contract.ts b/packages/api/src/api-contract.ts index bf564905..f429b7be 100644 --- a/packages/api/src/api-contract.ts +++ b/packages/api/src/api-contract.ts @@ -121,12 +121,12 @@ const accessTokenBody = z.object({ }); const bearerIntegrationMetadata = z.object({ id: z.uuid(), name: z.string(), origin: z.string(), description: z.string().nullable(), - revision: z.number().int().nonnegative(), encryptedPayload: z.string(), + revision: z.number().int().nonnegative(), }); const bearerIntegrationCreate = z.object({ id: z.uuid(), expectedRevision: z.number().int().nonnegative(), idempotencyKey: z.uuid(), name: z.string().trim().min(1).max(120), origin: z.string().url().max(2048), - description: z.string().max(500).nullable(), encryptedPayload: z.string().min(1).max(65_536), + description: z.string().max(500).nullable(), token: z.string().min(1).max(32_768), }).strict(); const bearerIntegrationUpdate = bearerIntegrationCreate.omit({ id: true }); const bearerIntegrationDelete = z.object({ expectedRevision: z.number().int().nonnegative(), idempotencyKey: z.uuid() }).strict(); @@ -263,18 +263,18 @@ export const API_ROUTES: RouteContract[] = [ responses: { "200": { description: "Key generation replaced", content: { "application/json": { schema: jsonSchema(z.object({ generationId: z.uuid(), revision: z.number().int().nonnegative(), duplicate: z.boolean() }), "output") } } } }, }, (service, { body }) => service.replaceUnlockKeyGeneration(body), { body: unlockKeyGenerationReplacement, maxBodyBytes: 12_000_000, ownerSession: true }), route("GET", "/api/v1/integrations/bearer", "flows:read", { - summary: "List encrypted bearer integrations", - description: "Requires an interactive owner browser session. Returns safe metadata and user-encrypted ciphertext; credentials are never decrypted or revealed.", - responses: { "200": { description: "Encrypted bearer integration records", content: { "application/json": { schema: jsonSchema(bearerIntegrationList, "output") } } } }, + summary: "List bearer integration metadata", + description: "Requires an interactive owner browser session. Returns secret-safe metadata only; stored bearer credentials are never returned.", + responses: { "200": { description: "Bearer integration metadata", content: { "application/json": { schema: jsonSchema(bearerIntegrationList, "output") } } } }, }, service => service.listBearerIntegrations(), { ownerSession: true }), route("POST", "/api/v1/integrations/bearer", "flows:write", { - summary: "Create an encrypted bearer integration", - description: "Requires an interactive owner browser session. Accepts only user-encrypted ciphertext, never an unlock key or plaintext credential.", + summary: "Create a bearer integration", + description: "Requires an interactive owner browser session. Accepts the secret over the authenticated connection and encrypts it with Factorize-managed storage before persistence. The secret is never returned.", responses: { "201": { description: "Created integration", content: { "application/json": { schema: jsonSchema(bearerIntegrationWriteResult, "output") } } } }, }, (service, { body }) => service.createBearerIntegration(body), { body: bearerIntegrationCreate, maxBodyBytes: 70_000, ownerSession: true }), route("PUT", "/api/v1/integrations/bearer/{integrationId}", "flows:write", { - summary: "Update an encrypted bearer integration", - description: "Requires an interactive owner browser session and the current collection revision. Accepts only user-encrypted ciphertext.", + summary: "Update a bearer integration", + description: "Requires an interactive owner browser session and the current collection revision. Accepts a replacement secret and encrypts it with Factorize-managed storage before persistence. The secret is never returned.", responses: { "200": { description: "Updated integration", content: { "application/json": { schema: jsonSchema(bearerIntegrationWriteResult, "output") } } } }, }, (service, { params, body }) => service.updateBearerIntegration(params.integrationId, body), { body: bearerIntegrationUpdate, maxBodyBytes: 70_000, ownerSession: true }), route("DELETE", "/api/v1/integrations/bearer/{integrationId}", "flows:write", { diff --git a/packages/api/src/flow-service.ts b/packages/api/src/flow-service.ts index e2693ffd..92785696 100644 --- a/packages/api/src/flow-service.ts +++ b/packages/api/src/flow-service.ts @@ -539,8 +539,8 @@ export class ApiService { async saveTailIntegration(input: any) { await this.authorize("integrations:write"); return this.integrations().saveTail(input); } async testTailIntegration(id: string) { await this.authorize("integrations:write"); const result = await this.integrations().testTail(id); if (!result) throw new ServiceError(404, "not_found", "Integration not found"); return result; } private encryptedIntegrations() { return new EncryptedIntegrationRepository(databaseFor(this.env), this.auth.tenantId, this.env.CREDENTIAL_ENCRYPTION_KEY); } - private async bearerWrite(input: { id: string; expectedRevision: number; idempotencyKey: string; name: string; origin: string; description: string | null; encryptedPayload?: string; operation: "upsert" | "delete" }) { - try { return await this.encryptedIntegrations().write({ ...input, kind: "bearer" }); } + private async bearerWrite(input: { id: string; expectedRevision: number; idempotencyKey: string; name: string; origin: string; description: string | null; token?: string; operation: "upsert" | "delete" }) { + try { return await this.encryptedIntegrations().write({ ...input, managedSecret: input.token, kind: "bearer" }); } catch (error) { if (error instanceof StaleIntegrationRevisionError) throw new ServiceError(409, "stale_revision", `${error.resyncRequired ? "Integration change history expired; fetch the current collection to resynchronize. " : "The integration collection changed. "}Current revision is ${error.currentRevision}.`); if (error instanceof IntegrationIdempotencyConflictError) throw new ServiceError(409, "conflict", "The idempotency key was already used for a different integration change."); @@ -556,14 +556,15 @@ export class ApiService { async listBearerIntegrations() { await this.authorizeOwnerSession("integrations:read"); const [revision, records] = await Promise.all([this.encryptedIntegrations().revision(), this.encryptedIntegrations().records("bearer")]); - return { revision, integrations: records }; + // Secret values are only read by the server-side credential control path. + return { revision, integrations: records.map(({ encryptedPayload: _secret, ...record }) => record) }; } - async createBearerIntegration(input: { id: string; expectedRevision: number; idempotencyKey: string; name: string; origin: string; description: string | null; encryptedPayload: string }) { + async createBearerIntegration(input: { id: string; expectedRevision: number; idempotencyKey: string; name: string; origin: string; description: string | null; token: string }) { await this.authorizeOwnerSession("integrations:write"); this.validateBearerOrigin(input.origin); if ((await this.encryptedIntegrations().records("bearer")).some(record => record.id === input.id)) throw new ServiceError(409, "conflict", "Integration already exists."); return this.bearerWrite({ ...input, operation: "upsert" }); } - async updateBearerIntegration(id: string, input: { expectedRevision: number; idempotencyKey: string; name: string; origin: string; description: string | null; encryptedPayload: string }) { + async updateBearerIntegration(id: string, input: { expectedRevision: number; idempotencyKey: string; name: string; origin: string; description: string | null; token: string }) { await this.authorizeOwnerSession("integrations:write"); this.validateBearerOrigin(input.origin); const existing = (await this.encryptedIntegrations().records("bearer")).find(record => record.id === id); if (!existing) throw new ServiceError(404, "not_found", "Integration not found."); diff --git a/packages/api/src/postgres/encrypted-integration-repository.ts b/packages/api/src/postgres/encrypted-integration-repository.ts index a83dbdcb..fd916f20 100644 --- a/packages/api/src/postgres/encrypted-integration-repository.ts +++ b/packages/api/src/postgres/encrypted-integration-repository.ts @@ -9,6 +9,8 @@ export type IntegrationWrite = IntegrationMetadata & { operation: "upsert" | "delete"; /** Ciphertext produced with the user's unlock key. This repository never interprets it. */ encryptedPayload?: string; + /** Plaintext bearer value accepted only by the owner-session credential API. */ + managedSecret?: string; }; export type IntegrationChange = IntegrationMetadata & { revision: number; @@ -19,6 +21,8 @@ export type IntegrationChange = IntegrationMetadata & { export type GenerationRecord = IntegrationMetadata & { revision: number; encryptedPayload: string | null; deletedAt: Date | null }; export type GenerationChange = IntegrationMetadata & { revision: number; idempotencyKey: string; operation: "upsert" | "delete"; encryptedPayload: string | null }; +const MANAGED_BEARER_PREFIX = "factorize-managed-bearer-v1:"; + export class StaleIntegrationRevisionError extends Error { constructor(readonly currentRevision: number, readonly resyncRequired = false) { super(resyncRequired ? "Integration change history expired; fetch the current collection before continuing" : "Integration collection revision is stale"); this.name = "StaleIntegrationRevisionError"; } } @@ -63,7 +67,9 @@ function validate(change: IntegrationWrite): void { if (change.description !== null && change.description.length > 500) throw new IntegrationValidationError("description must be at most 500 characters"); if (change.kind === "bearer" && (!change.origin || change.origin.length > 2048)) throw new IntegrationValidationError("bearer integrations require an origin of at most 2048 characters"); if (change.kind === "model" && change.origin !== null) throw new IntegrationValidationError("model accounts do not have an origin"); - if (change.operation === "upsert" && (typeof change.encryptedPayload !== "string" || !isUserCiphertext(change.encryptedPayload))) throw new IntegrationValidationError("upserts require a valid user-encrypted AES-GCM ciphertext envelope"); + if (change.operation === "upsert" && !(typeof change.managedSecret === "string" && change.managedSecret.length > 0 && change.managedSecret.length <= 32_768) + && !(typeof change.encryptedPayload === "string" && isUserCiphertext(change.encryptedPayload))) throw new IntegrationValidationError("upserts require a credential value"); + if (change.kind !== "bearer" && change.managedSecret !== undefined) throw new IntegrationValidationError("managed secrets are only supported for bearer integrations"); if (change.operation === "delete" && change.encryptedPayload !== undefined) throw new IntegrationValidationError("deletions cannot contain ciphertext"); } @@ -83,9 +89,10 @@ export class EncryptedIntegrationRepository { const { rows } = await this.database.pool.query("SELECT revision,operation,record_id,kind,name,origin,description,encrypted_payload FROM app.integration_changes WHERE tenant_id=$1 AND idempotency_key=$2", [this.tenantId, input.idempotencyKey]); const row = rows[0]; if (!row) return null; + const suppliedPayload = input.managedSecret === undefined ? input.encryptedPayload : `${MANAGED_BEARER_PREFIX}${input.managedSecret}`; const sameCiphertext = row.encrypted_payload === null ? input.operation === "delete" && input.encryptedPayload === undefined - : input.operation === "upsert" && typeof input.encryptedPayload === "string" && await decrypt(row.encrypted_payload, this.serverEncryptionKey) === input.encryptedPayload; + : input.operation === "upsert" && typeof suppliedPayload === "string" && await decrypt(row.encrypted_payload, this.serverEncryptionKey) === suppliedPayload; if (row.record_id !== input.id || row.kind !== input.kind || row.name !== input.name || row.origin !== input.origin || row.description !== input.description || row.operation !== input.operation || !sameCiphertext) { throw new IntegrationIdempotencyConflictError(); @@ -106,11 +113,12 @@ export class EncryptedIntegrationRepository { async write(input: IntegrationWrite): Promise<{ revision: number; duplicate: boolean }> { validate(input); - const encryptedPayload = input.operation === "upsert" ? await encrypt(input.encryptedPayload!, this.serverEncryptionKey) : null; + const suppliedPayload = input.managedSecret === undefined ? input.encryptedPayload : `${MANAGED_BEARER_PREFIX}${input.managedSecret}`; + const encryptedPayload = input.operation === "upsert" ? await encrypt(suppliedPayload!, this.serverEncryptionKey) : null; const metadata = [input.id, input.kind, input.name, input.origin, input.description, input.operation, encryptedPayload]; return this.database.transaction(async client => { const existing = async () => (await client.query("SELECT revision,operation,record_id,kind,name,origin,description,encrypted_payload FROM app.integration_changes WHERE tenant_id=$1 AND idempotency_key=$2", [this.tenantId, input.idempotencyKey])).rows[0]; - const isSame = async (row: StoredChange) => row.record_id === metadata[0] && row.kind === metadata[1] && row.name === metadata[2] && row.origin === metadata[3] && row.description === metadata[4] && row.operation === metadata[5] && (row.encrypted_payload === null ? encryptedPayload === null : encryptedPayload !== null && await decrypt(row.encrypted_payload, this.serverEncryptionKey) === input.encryptedPayload); + const isSame = async (row: StoredChange) => row.record_id === metadata[0] && row.kind === metadata[1] && row.name === metadata[2] && row.origin === metadata[3] && row.description === metadata[4] && row.operation === metadata[5] && (row.encrypted_payload === null ? encryptedPayload === null : encryptedPayload !== null && await decrypt(row.encrypted_payload, this.serverEncryptionKey) === suppliedPayload); const duplicate = await existing(); if (duplicate) { if (!await isSame(duplicate)) throw new IntegrationIdempotencyConflictError(); diff --git a/packages/api/test/api-contract.test.ts b/packages/api/test/api-contract.test.ts index abfbcb01..bd3a686b 100644 --- a/packages/api/test/api-contract.test.ts +++ b/packages/api/test/api-contract.test.ts @@ -89,6 +89,17 @@ describe("versioned API contract", () => { expect(openapi.paths["/api/v1/model-accounts/{accountId}"].delete).toBeDefined(); expect(openapi.paths["/api/v1/model-accounts"].get).toBeDefined(); }); + it("accepts bearer secrets only at the owner session boundary and publishes metadata only", () => { + const list = API_ROUTES.find(item => item.method === "GET" && item.path === "/api/v1/integrations/bearer"); + const create = API_ROUTES.find(item => item.method === "POST" && item.path === "/api/v1/integrations/bearer"); + const input = { id: "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa", expectedRevision: 0, idempotencyKey: "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb", name: "Build service", origin: "https://api.example.test", description: null, token: "server-managed-secret" }; + expect(list?.ownerSession).toBe(true); + expect(create?.ownerSession).toBe(true); + expect(create?.body?.safeParse(input).success).toBe(true); + expect(create?.body?.safeParse({ ...input, unlockKey: "must-not-be-accepted" }).success).toBe(false); + expect(create?.body?.safeParse({ ...input, encryptedPayload: "legacy-user-ciphertext" }).success).toBe(false); + expect(list?.documentation.responses["200"].content["application/json"].schema.properties.integrations.items.properties.encryptedPayload).toBeUndefined(); + }); it("accepts code jobs without agent prompts or models and rejects missing scripts", () => { const code = { name: "Export", slug: "export", executionType: "code", script: "#!/bin/sh\nprintf '{\"status\":\"succeeded\"}' > \"$FACTORIZE_RESULT_PATH\"", executionConfigId: "exe", triggers: [] }; expect(jobInputSchema.safeParse(code).success).toBe(true); diff --git a/packages/api/test/docker-code-job.e2e.test.ts b/packages/api/test/docker-code-job.e2e.test.ts index f96a885f..377f7028 100644 --- a/packages/api/test/docker-code-job.e2e.test.ts +++ b/packages/api/test/docker-code-job.e2e.test.ts @@ -99,8 +99,7 @@ it("runs saved code through the real API, encrypted grant, mTLS proxy and schedu const verification = await encrypt("factorize-unlock-key-verification-v1", generationId, "unlock-verification", "factorize", 0); await json("/unlock-key/verification", "POST", { generationId, encryptedVerification: JSON.stringify({ version: 1, algorithm: "A256GCM", nonce: Buffer.from(verification.nonce).toString("base64url"), ciphertext: Buffer.from(verification.ciphertext).toString("base64url") }) }); expect((await json("/unlock-key/verification")).verification.generationId).toBe(generationId); - const encrypted = await encrypt(upstreamSecret, integrationId, "bearer", upstreamOrigin, 1); - await json("/integrations/bearer", "POST", { id: integrationId, expectedRevision: 0, idempotencyKey: randomUUID(), name: "Fake API", origin: upstreamOrigin, description: null, encryptedPayload: `${Buffer.from(encrypted.nonce).toString("base64")}.${Buffer.from(encrypted.ciphertext).toString("base64")}` }); + await json("/integrations/bearer", "POST", { id: integrationId, expectedRevision: 0, idempotencyKey: randomUUID(), name: "Fake API", origin: upstreamOrigin, description: null, token: upstreamSecret }); const script = `#!/bin/bash\nset -eu\nnode --input-type=module <<'JS'\nimport fs from 'node:fs';\nimport net from 'node:net';\nconst marker=${JSON.stringify(marker)};\nconst direct=await new Promise(resolve=>{const s=net.connect({host:${JSON.stringify(fakeAddress)},port:8443}); s.setTimeout(1000,()=>{s.destroy();resolve(false)});s.once('connect',()=>{s.destroy();resolve(true)});s.once('error',()=>resolve(false))});\nif(direct)throw new Error('network isolation failed');\nconst base=process.env.FACTORIZE_PROXY_URL;\nconst list=await (await fetch(base+'/integrations',{signal:AbortSignal.timeout(10000)})).json();\nconst integration=list.integrations.find(x=>x.id===${JSON.stringify(integrationId)});\nif(!integration)throw new Error('grant missing');\nconst r=await fetch(base+integration.endpoint+'echo/'+marker,{method:'POST',body:marker,signal:AbortSignal.timeout(10000)});\nif(!r.ok||(await r.json()).marker!==marker)throw new Error('response mismatch');\nconsole.log('executed:'+marker);\nfs.writeFileSync('/home/exedev/.factorize-job/evidence.txt',marker);\nawait new Promise(r=>setTimeout(r,1500));\nfs.writeFileSync(process.env.FACTORIZE_RESULT_PATH,JSON.stringify({status:'succeeded',outputs:{marker,directBlocked:true}}));\nJS\n`; const jobInput = { name: "Docker code", slug: "docker-code", projectId: project.id, executionType: "code", script, executionConfigId: "docker", triggers: [{ kind: "manual", slug: "trigger-1", config: {} }] }; const enabled = env.TEST_DOCKER_EXECUTION; @@ -111,8 +110,7 @@ it("runs saved code through the real API, encrypted grant, mTLS proxy and schedu const job = await json("/jobs", "POST", jobInput); await json(`/jobs/${job.id}`, "PUT", { ...jobInput, portableIntegrationIds: [integrationId] }); const ungrantedId = randomUUID(); - const ungranted = await encrypt(upstreamSecret, ungrantedId, "bearer", upstreamOrigin, 2); - await json("/integrations/bearer", "POST", { id: ungrantedId, expectedRevision: 1, idempotencyKey: randomUUID(), name: "Ungranted", origin: upstreamOrigin, description: null, encryptedPayload: `${Buffer.from(ungranted.nonce).toString("base64")}.${Buffer.from(ungranted.ciphertext).toString("base64")}` }); + await json("/integrations/bearer", "POST", { id: ungrantedId, expectedRevision: 1, idempotencyKey: randomUUID(), name: "Ungranted", origin: upstreamOrigin, description: null, token: upstreamSecret }); const setup = await json("/credential-proxy/setup", "POST", { operationId: randomUUID() }); expect(setup.proxyIdentity.startsWith(`docker:${namespace}:`)).toBe(true); const lifecycle = async (action: string, body: unknown = {}) => { const c = await json("/credential-proxy/browser-capability", "POST", { action }); return fetch(c.endpoint, { method: "POST", headers: { Authorization: `Bearer ${c.capability}`, Origin: env.APP_ORIGIN, "Content-Type": "application/json" }, body: JSON.stringify(body), signal: AbortSignal.timeout(15_000) }); }; diff --git a/packages/api/test/encrypted-integration-api.postgres.test.ts b/packages/api/test/encrypted-integration-api.postgres.test.ts index 77d4c01e..c420a787 100644 --- a/packages/api/test/encrypted-integration-api.postgres.test.ts +++ b/packages/api/test/encrypted-integration-api.postgres.test.ts @@ -3,6 +3,7 @@ import worker from "../src/worker"; import { protectedApiFetch } from "../src/protected-api"; import { IdentityRepository } from "../src/postgres/identity-repository"; import { RunEnrollmentRepository } from "../src/postgres/run-enrollment-repository"; +import { EncryptedIntegrationRepository } from "../src/postgres/encrypted-integration-repository"; import { signSession } from "../src/session"; import { loadingFixture } from "./helpers/loading-fixture"; @@ -18,7 +19,7 @@ async function userEncrypt(plaintext: string): Promise { return `${encode(iv)}.${encode(new Uint8Array(body))}`; } -describe.skipIf(!databaseUrl)("browser-only encrypted bearer integration API (PostgreSQL)", { timeout: 60_000 }, () => { +describe.skipIf(!databaseUrl)("owner-only managed credential API (PostgreSQL)", { timeout: 60_000 }, () => { it("keeps Docker test selection and proxy setup behind explicit environment and owner boundaries", async () => { const f = await loadingFixture(databaseUrl!); try { @@ -72,7 +73,7 @@ describe.skipIf(!databaseUrl)("browser-only encrypted bearer integration API (Po expect((await request("/unlock-key/verification", "POST", { generationId: oldGeneration, encryptedVerification: verification(oldGeneration) })).status).toBe(200); const encrypted = await userEncrypt("synthetic bearer payload"); const integrationId = crypto.randomUUID(); - expect((await request("/integrations/bearer", "POST", { id: integrationId, expectedRevision: 0, idempotencyKey: crypto.randomUUID(), name: "Synthetic", origin: "https://api.example.test", description: null, encryptedPayload: encrypted })).status).toBe(201); + await new EncryptedIntegrationRepository(f.db, f.tenantId, f.env.CREDENTIAL_ENCRYPTION_KEY).write({ id: integrationId, kind: "bearer", name: "Synthetic", origin: "https://api.example.test", description: null, expectedRevision: 0, idempotencyKey: crypto.randomUUID(), operation: "upsert", encryptedPayload: encrypted }); await f.db.pool.query("INSERT INTO app.connections(tenant_id,kind,encrypted_value) VALUES($1,'fly:connection-fixture','encrypted-fly-fixture')", [f.tenantId]); await f.db.pool.query("UPDATE app.jobs SET execution_config=$3 WHERE tenant_id=$1 AND id=$2", [f.tenantId, f.jobIds[0], { provider: "fly", connectionId: "fly:connection-fixture", region: "ord", vmSize: "shared-cpu-1x" }]); const flyConnectionBefore = (await f.db.pool.query("SELECT kind,encrypted_value FROM app.connections WHERE tenant_id=$1 ORDER BY kind", [f.tenantId])).rows; @@ -106,7 +107,7 @@ describe.skipIf(!databaseUrl)("browser-only encrypted bearer integration API (Po expect((await f.db.pool.query("SELECT consumed_at FROM app.credential_run_enrollments WHERE tenant_id=$1 AND run_id=$2", [f.tenantId, runId])).rows[0].consumed_at).toBeInstanceOf(Date); expect(await enrollmentRepository.consume(issued!.token, binding)).toBeNull(); const rotatedCipher = await userEncrypt("rotated synthetic bearer payload"), rotatedId = crypto.randomUUID(); - expect((await request("/integrations/bearer", "POST", { id: rotatedId, expectedRevision: 2, idempotencyKey: crypto.randomUUID(), name: "Rotated", origin: "https://api.example.test", description: null, encryptedPayload: encrypted })).status).toBe(201); + await new EncryptedIntegrationRepository(f.db, f.tenantId, f.env.CREDENTIAL_ENCRYPTION_KEY).write({ id: rotatedId, kind: "bearer", expectedRevision: 2, idempotencyKey: crypto.randomUUID(), name: "Rotated", origin: "https://api.example.test", description: null, operation: "upsert", encryptedPayload: encrypted }); const rotationSnapshot = await (await request("/unlock-key/rotation-snapshot")).json() as any; const finalGeneration = crypto.randomUUID(); const rotated = await request("/unlock-key/rotation", "POST", { @@ -118,7 +119,7 @@ describe.skipIf(!databaseUrl)("browser-only encrypted bearer integration API (Po expect(rotated.status).toBe(200); expect(await rotated.json()).toEqual({ generationId: finalGeneration, revision: 4, duplicate: false }); expect((await request("/integrations/bearer")).status).toBe(200); - expect((await (await request("/integrations/bearer")).json() as any).integrations[0].encryptedPayload).toBe(rotatedCipher); + expect(JSON.stringify(await (await request("/integrations/bearer")).json())).not.toContain(rotatedCipher); const agent = await request("/unlock-key/rotation-snapshot", "GET", undefined, "untrusted-cookie"); expect(agent.status).toBe(401); } finally { await f.cleanup(); } @@ -130,28 +131,30 @@ describe.skipIf(!databaseUrl)("browser-only encrypted bearer integration API (Po method, headers: { Cookie: cookie, Origin: f.env.APP_ORIGIN, "Content-Type": "application/json" }, ...(body === undefined ? {} : { body: JSON.stringify(body) }), }), f.env, { waitUntil() {} } as any); - const id = crypto.randomUUID(), idempotencyKey = crypto.randomUUID(), cipher = await userEncrypt("synthetic upstream bearer credential"); - const created = await request("/integrations/bearer", "POST", { id, expectedRevision: 0, idempotencyKey, name: "Test service", origin: "https://api.example.test", description: "fixture", encryptedPayload: cipher }); + const id = crypto.randomUUID(), idempotencyKey = crypto.randomUUID(), token = "synthetic upstream bearer credential"; + const created = await request("/integrations/bearer", "POST", { id, expectedRevision: 0, idempotencyKey, name: "Test service", origin: "https://api.example.test", description: "fixture", token }); expect(created.status).toBe(201); expect(await created.json()).toEqual({ revision: 1, duplicate: false }); const listed = await request("/integrations/bearer"); expect(listed.status).toBe(200); const result = await listed.json() as any; - expect(result).toEqual({ revision: 1, integrations: [{ id, kind: "bearer", name: "Test service", origin: "https://api.example.test", description: "fixture", revision: 1, encryptedPayload: cipher }] }); - expect(JSON.stringify(result)).not.toContain("synthetic upstream bearer credential"); + expect(result).toEqual({ revision: 1, integrations: [{ id, kind: "bearer", name: "Test service", origin: "https://api.example.test", description: "fixture", revision: 1 }] }); + expect(JSON.stringify(result)).not.toContain(token); expect(result.integrations[0]).not.toHaveProperty("unlockKey"); expect(result.integrations[0]).not.toHaveProperty("token"); - const updated = await request(`/integrations/bearer/${id}`, "PUT", { expectedRevision: 1, idempotencyKey: crypto.randomUUID(), name: "Renamed service", origin: "https://api.example.test", description: null, encryptedPayload: cipher }); + const updated = await request(`/integrations/bearer/${id}`, "PUT", { expectedRevision: 1, idempotencyKey: crypto.randomUUID(), name: "Renamed service", origin: "https://api.example.test", description: null, token }); expect(updated.status).toBe(200); expect(await updated.json()).toEqual({ revision: 2, duplicate: false }); - const malformed = await request("/integrations/bearer", "POST", { id: crypto.randomUUID(), expectedRevision: 2, idempotencyKey: crypto.randomUUID(), name: "Malformed", origin: "https://api.example.test", description: null, encryptedPayload: "not-ciphertext" }); + const malformed = await request("/integrations/bearer", "POST", { id: crypto.randomUUID(), expectedRevision: 2, idempotencyKey: crypto.randomUUID(), name: "Malformed", origin: "https://api.example.test", description: null, token: "" }); expect(malformed.status).toBe(400); - const plaintext = await request("/integrations/bearer", "POST", { id: crypto.randomUUID(), expectedRevision: 2, idempotencyKey: crypto.randomUUID(), name: "Plaintext", origin: "https://api.example.test", description: null, encryptedPayload: cipher, bearerToken: "must-not-be-accepted" }); - expect(plaintext.status).toBe(400); - const stale = await request(`/integrations/bearer/${id}`, "PUT", { expectedRevision: 1, idempotencyKey: crypto.randomUUID(), name: "Stale", origin: "https://api.example.test", description: null, encryptedPayload: cipher }); + const oldFormat = await request("/integrations/bearer", "POST", { id: crypto.randomUUID(), expectedRevision: 2, idempotencyKey: crypto.randomUUID(), name: "Old format", origin: "https://api.example.test", description: null, encryptedPayload: "cipher" }); + expect(oldFormat.status).toBe(400); + const stored = await f.db.pool.query<{ encrypted_payload: string }>("SELECT encrypted_payload FROM app.integration_records WHERE tenant_id=$1 AND id=$2", [f.tenantId, id]); + expect(stored.rows[0]!.encrypted_payload).not.toContain(token); + const stale = await request(`/integrations/bearer/${id}`, "PUT", { expectedRevision: 1, idempotencyKey: crypto.randomUUID(), name: "Stale", origin: "https://api.example.test", description: null, token }); expect(stale.status).toBe(409); expect((await stale.json() as any).error.code).toBe("stale_revision"); @@ -208,9 +211,11 @@ describe.skipIf(!databaseUrl)("browser-only encrypted bearer integration API (Po const agent = await protectedApiFetch(new Request(path), f.env, { tenantId: f.tenantId, userId: f.userId, sessionVersion: 0, scopes: ["integrations:write"], authMethod: "access_token" } as any, {} as any); expect(agent.status).toBe(403); - const id = crypto.randomUUID(), cipher = await userEncrypt("tenant private credential"); - const created = await worker.fetch(new Request(path, { method: "POST", headers: { Cookie: f.cookie, Origin: f.env.APP_ORIGIN, "Content-Type": "application/json" }, body: JSON.stringify({ id, expectedRevision: 0, idempotencyKey: crypto.randomUUID(), name: "Private", origin: "https://api.example.test", description: null, encryptedPayload: cipher }) }), f.env, { waitUntil() {} } as any); + const id = crypto.randomUUID(), token = "tenant private credential"; + const created = await worker.fetch(new Request(path, { method: "POST", headers: { Cookie: f.cookie, Origin: f.env.APP_ORIGIN, "Content-Type": "application/json" }, body: JSON.stringify({ id, expectedRevision: 0, idempotencyKey: crypto.randomUUID(), name: "Private", origin: "https://api.example.test", description: null, token }) }), f.env, { waitUntil() {} } as any); expect(created.status).toBe(201); + const listed = await worker.fetch(new Request(path, { headers: { Cookie: f.cookie } }), f.env, { waitUntil() {} } as any); + expect(JSON.stringify(await listed.json())).not.toContain(token); const otherUser = crypto.randomUUID(); await new IdentityRepository(f.db, f.otherTenant).upsertOwner(otherUser, "other-owner@example.test"); @@ -219,7 +224,7 @@ describe.skipIf(!databaseUrl)("browser-only encrypted bearer integration API (Po const otherList = await worker.fetch(new Request(path, { headers: { Cookie: otherCookie } }), f.env, { waitUntil() {} } as any); expect(otherList.status).toBe(200); expect(await otherList.json()).toEqual({ revision: 0, integrations: [] }); - const otherUpdate = await worker.fetch(new Request(path + `/${id}`, { method: "PUT", headers: { Cookie: otherCookie, Origin: f.env.APP_ORIGIN, "Content-Type": "application/json" }, body: JSON.stringify({ expectedRevision: 0, idempotencyKey: crypto.randomUUID(), name: "Stolen", origin: "https://api.example.test", description: null, encryptedPayload: cipher }) }), f.env, { waitUntil() {} } as any); + const otherUpdate = await worker.fetch(new Request(path + `/${id}`, { method: "PUT", headers: { Cookie: otherCookie, Origin: f.env.APP_ORIGIN, "Content-Type": "application/json" }, body: JSON.stringify({ expectedRevision: 0, idempotencyKey: crypto.randomUUID(), name: "Stolen", origin: "https://api.example.test", description: null, token }) }), f.env, { waitUntil() {} } as any); expect(otherUpdate.status).toBe(404); } finally { await f.cleanup(); } }); diff --git a/packages/app/src/features/settings/bearer-integrations.tsx b/packages/app/src/features/settings/bearer-integrations.tsx index a8d9ad4d..2d5c0c9a 100644 --- a/packages/app/src/features/settings/bearer-integrations.tsx +++ b/packages/app/src/features/settings/bearer-integrations.tsx @@ -2,23 +2,14 @@ import { useState } from "react"; import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; import { api } from "factorize-api-client"; import { Button, Card, Input, Label } from "../../shared/ui"; -import { encryptRecord, verifyUnlockKey } from "../../lib/unlock-crypto"; -import { getUnlockVerification } from "../../lib/unlock-key"; import { messageOf } from "../auth/session"; -type BearerRecord = { id: string; name: string; origin: string; description: string | null; revision: number; encryptedPayload: string }; +type BearerRecord = { id: string; name: string; origin: string; description: string | null; revision: number }; const recordsQuery = { queryKey: ["settings", "bearer-integrations"], queryFn: async ({ signal }: { signal: AbortSignal }) => { const { data, error } = await api.GET("/api/v1/integrations/bearer", { signal }); if (!data || error) throw new Error(messageOf(error)); return data; } }; -const verificationQuery = { queryKey: ["unlock-key-verification"], queryFn: ({ signal }: { signal: AbortSignal }) => getUnlockVerification(signal), retry: false as const }; -const bytesToBase64 = (bytes: Uint8Array) => { - let value = ""; - for (const byte of bytes) value += String.fromCharCode(byte); - return btoa(value); -}; -const base64UrlToBytes = (value: string) => Uint8Array.from(atob(value.replaceAll("-", "+").replaceAll("_", "/") + "=".repeat((4 - value.length % 4) % 4)), char => char.charCodeAt(0)); function validOrigin(value: string): boolean { try { @@ -38,27 +29,18 @@ function validOrigin(value: string): boolean { } export function BearerIntegrations() { - const cache = useQueryClient(), records = useQuery(recordsQuery), verification = useQuery(verificationQuery); - const [editing, setEditing] = useState(null), [name, setName] = useState(""), [origin, setOrigin] = useState(""), [description, setDescription] = useState(""), [token, setToken] = useState(""), [key, setKey] = useState(""); + const cache = useQueryClient(), records = useQuery(recordsQuery); + const [editing, setEditing] = useState(null), [name, setName] = useState(""), [origin, setOrigin] = useState(""), [description, setDescription] = useState(""), [token, setToken] = useState(""); const [notice, setNotice] = useState(""); - const clearFields = () => { setToken(""); setKey(""); }; + const clearFields = () => { setToken(""); }; const save = useMutation({ retry: false, mutationFn: async () => { const cleanName = name.trim(), cleanOrigin = origin.trim(), cleanDescription = description.trim(); if (!cleanName || cleanName.length > 120) throw new Error("Enter a name up to 120 characters."); if (!validOrigin(cleanOrigin)) throw new Error("Enter a public HTTPS origin without a path, query, fragment, or credentials."); if (cleanDescription.length > 500) throw new Error("Description must be at most 500 characters."); if (!token) throw new Error("Enter a bearer token to create or replace this credential."); - const setup = verification.data?.verification; - if (!setup || !verification.data) throw new Error("Set up an unlock key before managing bearer integrations."); - try { await verifyUnlockKey(key, verification.data.ownerId, setup.generationId, JSON.parse(setup.encryptedVerification)); } - catch (error) { - if (error instanceof TypeError && error.message === "Malformed unlock key") throw error; - throw new Error("Unlock key could not be verified for this account and generation."); - } const id = editing ?? crypto.randomUUID(), expectedRevision = records.data?.revision ?? 0; - const encrypted = await encryptRecord(new TextEncoder().encode(token), key, { ownerId: verification.data.ownerId, recordId: id, recordType: "bearer", destination: cleanOrigin, revision: expectedRevision + 1 }); - const encryptedPayload = `${bytesToBase64(base64UrlToBytes(encrypted.nonce))}.${bytesToBase64(base64UrlToBytes(encrypted.ciphertext))}`; - const body = { expectedRevision, idempotencyKey: crypto.randomUUID(), name: cleanName, origin: cleanOrigin, description: cleanDescription || null, encryptedPayload }; + const body = { expectedRevision, idempotencyKey: crypto.randomUUID(), name: cleanName, origin: cleanOrigin, description: cleanDescription || null, token }; if (editing) { const { data, error } = await api.PUT("/api/v1/integrations/bearer/{integrationId}", { params: { path: { integrationId: editing } }, body }); if (!data || error) throw new Error(messageOf(error)); @@ -67,7 +49,7 @@ export function BearerIntegrations() { const { data, error } = await api.POST("/api/v1/integrations/bearer", { body: { ...body, id } }); if (!data || error) throw new Error(messageOf(error)); return data; - }, onSuccess: async () => { clearFields(); setNotice("Saved encrypted integration. Changes remain pending until the proxy is unlocked."); setEditing(null); setName(""); setOrigin(""); setDescription(""); await cache.invalidateQueries({ queryKey: recordsQuery.queryKey }); }, onError: async error => { clearFields(); setNotice(error.message); if (error.message.includes("changed") || error.message.includes("revision")) await cache.invalidateQueries({ queryKey: recordsQuery.queryKey }); } }); + }, onSuccess: async () => { clearFields(); setNotice("Saved integration in Factorize managed encrypted storage."); setEditing(null); setName(""); setOrigin(""); setDescription(""); await cache.invalidateQueries({ queryKey: recordsQuery.queryKey }); }, onError: async error => { clearFields(); setNotice(error.message); if (error.message.includes("changed") || error.message.includes("revision")) await cache.invalidateQueries({ queryKey: recordsQuery.queryKey }); } }); const remove = useMutation({ retry: false, mutationFn: async (record: BearerRecord) => { const { data, error } = await api.DELETE("/api/v1/integrations/bearer/{integrationId}", { params: { path: { integrationId: record.id } }, body: { expectedRevision: records.data?.revision ?? 0, idempotencyKey: crypto.randomUUID() } }); if (!data || error) throw new Error(messageOf(error)); @@ -76,18 +58,16 @@ export function BearerIntegrations() { const beginEdit = (record: BearerRecord) => { clearFields(); setNotice(""); setEditing(record.id); setName(record.name); setOrigin(record.origin); setDescription(record.description ?? ""); }; const reset = () => { clearFields(); setEditing(null); setName(""); setOrigin(""); setDescription(""); setNotice(""); }; return
-

Bearer integrations

Credentials are encrypted in this browser. Stored tokens cannot be viewed; edit to replace one.

+

Bearer integrations

Factorize encrypts credentials before storing them. Stored tokens cannot be viewed; edit to replace one.

{records.isPending &&

Loading bearer integrations…

}{records.error &&

{records.error.message}

} {records.data?.integrations.map(record =>

{record.name}

{record.origin}

{record.description &&

{record.description}

}

Bearer token stored encrypted

)}

{editing ? "Edit bearer integration" : "Add bearer integration"}

- {!verification.data?.verification && verification.data &&

Set up your unlock key above before adding bearer integrations.

}
{ event.preventDefault(); setNotice(""); save.mutate(); }}> - -
{editing && }
+
{editing && }
{notice &&

{notice}

} diff --git a/packages/app/test/settings.browser.test.mjs b/packages/app/test/settings.browser.test.mjs index 622a9d04..1f7a9fc6 100644 --- a/packages/app/test/settings.browser.test.mjs +++ b/packages/app/test/settings.browser.test.mjs @@ -51,49 +51,34 @@ test("model account settings issue short-lived capabilities and display the boun assert.deepEqual(proxyCalls.map(call => call.body), ["{}", "{}"]); await context.close(); }); -test("owner browser creates a bearer integration with encrypted input and clears both secret fields", async () => { +test("owner browser stores bearer integration in Factorize managed storage without an unlock key", async () => { const { context, page } = await setup(); await page.route("**/api/v1/providers/github/installations", route => route.fulfill({ json: [] })); await page.route("**/api/v1/integrations", route => route.fulfill({ json: { linear: null, clickup: null, exe: null, exeConnections: [], ampConnections: [], cloudflareTail: { count: 0, installations: [] } } })); - let verification = null, saved = [], createBody; - await page.route("**/api/v1/unlock-key/verification", async route => { - if (route.request().method() === "GET") return route.fulfill({ json: { ownerId: "owner", verification } }); - const body = route.request().postDataJSON(); - assert.deepEqual(Object.keys(body).sort(), ["encryptedVerification", "generationId"]); - verification = { generationId: body.generationId, encryptedVerification: body.encryptedVerification }; - return route.fulfill({ json: { generationId: body.generationId } }); - }); + let saved = [], createBody; await page.route("**/api/v1/integrations/bearer", async route => { if (route.request().method() === "GET") return route.fulfill({ json: { revision: saved.length, integrations: saved } }); createBody = route.request().postDataJSON(); - saved = [{ id: createBody.id, name: createBody.name, origin: createBody.origin, description: createBody.description, revision: 1, encryptedPayload: createBody.encryptedPayload }]; + saved = [{ id: createBody.id, name: createBody.name, origin: createBody.origin, description: createBody.description, revision: 1 }]; return route.fulfill({ status: 201, json: { revision: 1, duplicate: false } }); }); await page.goto(origin + "/settings/integrations"); - await page.getByRole("button", { name: "Generate unlock key" }).click(); - const unlockKey = await page.getByLabel("New unlock key").inputValue(); - await page.getByRole("checkbox", { name: "I saved this key somewhere safe." }).check(); - await page.getByRole("button", { name: "I saved my key" }).click(); - await page.getByText("Unlock key verification is set up.", { exact: false }).waitFor(); - const integrations = page.getByRole("region", { name: "Bearer integrations" }); await integrations.getByLabel("Name").fill("Example service"); await integrations.getByLabel("HTTPS origin").fill("https://api.example.test"); await integrations.getByLabel("Description or help (optional)").fill("Fixture API"); await integrations.getByLabel("Bearer token").fill("synthetic-upstream-secret"); - await integrations.getByLabel("Unlock key").fill(unlockKey); await integrations.getByRole("button", { name: "Add integration" }).click(); - await integrations.getByText("Saved encrypted integration.", { exact: false }).waitFor(); + await integrations.getByText("Saved integration in Factorize managed encrypted storage.", { exact: true }).waitFor(); assert.equal(createBody.name, "Example service"); assert.equal(createBody.origin, "https://api.example.test"); assert.equal(createBody.description, "Fixture API"); - assert.equal(JSON.stringify(createBody).includes("synthetic-upstream-secret"), false); - assert.equal(JSON.stringify(createBody).includes(unlockKey), false); - assert.match(createBody.encryptedPayload, /^[A-Za-z0-9+/]+=*\.[A-Za-z0-9+/]+=*$/u); + assert.equal(createBody.token, "synthetic-upstream-secret"); + assert.equal(createBody.unlockKey, undefined); assert.equal(await integrations.getByLabel("Bearer token").inputValue(), ""); - assert.equal(await integrations.getByLabel("Unlock key").inputValue(), ""); + assert.equal(await integrations.getByText("synthetic-upstream-secret", { exact: true }).count(), 0); assert.equal(await page.evaluate(() => JSON.stringify(localStorage).includes("synthetic-upstream-secret")), false); await context.close(); }); @@ -259,22 +244,16 @@ test("owner can rotate the unlock key or reset lost-key integrations without sen assert.equal(JSON.stringify(rotationBody).includes(nextKey), false); await context.close(); }); -test("bearer integrations encrypt in the browser, clear secrets, handle conflicts and delete conditionally", async () => { +test("bearer integrations send secrets to managed storage, clear fields, handle conflicts and delete conditionally", async () => { const { context, page } = await setup(); await page.route("**/api/v1/providers/github/installations", route => route.fulfill({ json: [] })); await page.route("**/api/v1/integrations", route => route.fulfill({ json: { linear: null, clickup: null, exe: null, exeConnections: [], ampConnections: [], cloudflareTail: { count: 0, installations: [] } } })); - let verification = null, revision = 0, writeBody = null, updateBody = null, deleteBody = null, conflict = true, deleted = false; - await page.route("**/api/v1/unlock-key/verification", async route => { - if (route.request().method() === "GET") return route.fulfill({ json: { ownerId: "owner", verification } }); - const body = route.request().postDataJSON(); verification = { generationId: body.generationId, encryptedVerification: body.encryptedVerification }; - return route.fulfill({ json: { generationId: body.generationId } }); - }); + let revision = 0, writeBody = null, updateBody = null, deleteBody = null, conflict = true, deleted = false; await page.route("**/api/v1/integrations/bearer", async route => { - if (route.request().method() === "GET") return route.fulfill({ json: { revision, integrations: deleted ? [] : writeBody ? [{ id: writeBody.id, name: writeBody.name, origin: writeBody.origin, description: writeBody.description, revision, encryptedPayload: writeBody.encryptedPayload }] : [] } }); + if (route.request().method() === "GET") return route.fulfill({ json: { revision, integrations: deleted ? [] : writeBody ? [{ id: writeBody.id, name: writeBody.name, origin: writeBody.origin, description: writeBody.description, revision }] : [] } }); writeBody = route.request().postDataJSON(); - assert.deepEqual(Object.keys(writeBody).sort(), ["description", "encryptedPayload", "expectedRevision", "id", "idempotencyKey", "name", "origin"]); - assert.equal(writeBody.encryptedPayload.includes("plain-bearer-value"), false); - assert.match(writeBody.encryptedPayload, /^[A-Za-z0-9+/]+=*\.[A-Za-z0-9+/]+=*$/u); + assert.deepEqual(Object.keys(writeBody).sort(), ["description", "expectedRevision", "id", "idempotencyKey", "name", "origin", "token"]); + assert.equal(writeBody.token, "plain-bearer-value"); if (conflict) { conflict = false; revision = 1; return route.fulfill({ status: 409, json: { error: { code: "stale_revision", message: "The integration collection changed. Current revision is 1." } } }); } revision++; return route.fulfill({ status: 201, json: { revision, duplicate: false } }); @@ -282,8 +261,8 @@ test("bearer integrations encrypt in the browser, clear secrets, handle conflict await page.route("**/api/v1/integrations/bearer/*", async route => { if (route.request().method() === "PUT") { updateBody = route.request().postDataJSON(); - assert.deepEqual(Object.keys(updateBody).sort(), ["description", "encryptedPayload", "expectedRevision", "idempotencyKey", "name", "origin"]); - assert.equal(updateBody.encryptedPayload.includes("replacement-bearer-value"), false); + assert.deepEqual(Object.keys(updateBody).sort(), ["description", "expectedRevision", "idempotencyKey", "name", "origin", "token"]); + assert.equal(updateBody.token, "replacement-bearer-value"); revision++; writeBody = { ...writeBody, ...updateBody }; return route.fulfill({ json: { revision, duplicate: false } }); } @@ -293,73 +272,43 @@ test("bearer integrations encrypt in the browser, clear secrets, handle conflict return route.fulfill({ json: { id: writeBody.id, deleted: true, revision, duplicate: false } }); }); await page.goto(origin + "/settings/integrations"); - await page.getByRole("button", { name: "Generate unlock key" }).click(); - const key = await page.getByLabel("New unlock key").inputValue(); - await page.getByRole("checkbox", { name: "I saved this key somewhere safe." }).check(); - await page.getByRole("button", { name: "I saved my key" }).click(); - await page.getByText("Unlock key verification is set up.", { exact: false }).waitFor(); const bearer = page.getByRole("region", { name: "Bearer integrations" }); await bearer.getByLabel("Name").fill("Test bearer"); await bearer.getByLabel("HTTPS origin").fill("https://api.example.test"); await bearer.getByLabel("Description or help (optional)").fill("fixture help"); await bearer.getByLabel("Bearer token").fill("plain-bearer-value"); - await bearer.getByLabel("Unlock key").fill("malformed-key"); - await bearer.getByRole("button", { name: "Add integration" }).click(); - await bearer.getByRole("alert").filter({ hasText: "Malformed unlock key" }).waitFor(); - assert.equal(writeBody, null); - assert.equal(await bearer.getByLabel("Bearer token").inputValue(), ""); - assert.equal(await bearer.getByLabel("Unlock key").inputValue(), ""); - - const wrongKey = `${key.slice(0, -1)}${key.endsWith("A") ? "B" : "A"}`; - await bearer.getByLabel("HTTPS origin").fill("https://api.example.test"); - await bearer.getByLabel("Bearer token").fill("plain-bearer-value"); - await bearer.getByLabel("Unlock key").fill(wrongKey); - await bearer.getByRole("button", { name: "Add integration" }).click(); - await bearer.getByRole("alert").waitFor(); - assert.equal((await bearer.getByRole("alert").innerText()).includes("plain-bearer-value"), false); - assert.equal(writeBody, null); - assert.equal(await bearer.getByLabel("Bearer token").inputValue(), ""); - assert.equal(await bearer.getByLabel("Unlock key").inputValue(), ""); - await bearer.getByLabel("HTTPS origin").fill("https://127.0.0.1"); - await bearer.getByLabel("Bearer token").fill("plain-bearer-value"); - await bearer.getByLabel("Unlock key").fill(key); await bearer.getByRole("button", { name: "Add integration" }).click(); await bearer.getByRole("alert").filter({ hasText: "public HTTPS origin" }).waitFor(); assert.equal(writeBody, null, "private origins are rejected before any request"); await bearer.getByLabel("HTTPS origin").fill("https://api.example.test"); await bearer.getByLabel("Bearer token").fill("plain-bearer-value"); - await bearer.getByLabel("Unlock key").fill(key); await bearer.getByRole("button", { name: "Add integration" }).click(); await bearer.getByRole("alert").filter({ hasText: "collection changed" }).waitFor(); assert.equal(await bearer.getByLabel("Bearer token").inputValue(), ""); - assert.equal(await bearer.getByLabel("Unlock key").inputValue(), ""); await bearer.getByLabel("Bearer token").fill("plain-bearer-value"); - await bearer.getByLabel("Unlock key").fill(key); await bearer.getByRole("button", { name: "Add integration" }).click(); - await bearer.getByRole("status").filter({ hasText: "pending until the proxy is unlocked" }).waitFor(); - assert.equal(writeBody.encryptedPayload.includes("plain-bearer-value"), false); + await bearer.getByRole("status").filter({ hasText: "Factorize managed encrypted storage" }).waitFor(); assert.equal(await page.evaluate(() => JSON.stringify(localStorage) + JSON.stringify(sessionStorage)), "{}{}"); assert.equal(page.url().includes("plain-bearer-value"), false); assert.equal(await bearer.getByText("plain-bearer-value", { exact: true }).count(), 0); assert.equal(await bearer.getByLabel("Bearer token").inputValue(), ""); - assert.equal(await bearer.getByLabel("Unlock key").inputValue(), ""); await bearer.getByRole("button", { name: "Replace or edit" }).click(); await bearer.getByLabel("Replacement bearer token").fill("replacement-bearer-value"); - await bearer.getByLabel("Unlock key").fill(key); await bearer.getByRole("button", { name: "Save replacement" }).click(); - await bearer.getByRole("status").filter({ hasText: "pending until the proxy is unlocked" }).waitFor(); + await bearer.getByRole("status").filter({ hasText: "Factorize managed encrypted storage" }).waitFor(); assert.equal(updateBody.expectedRevision, 2); assert.equal(await bearer.getByLabel("Bearer token").inputValue(), ""); - assert.equal(await bearer.getByLabel("Unlock key").inputValue(), ""); page.once("dialog", dialog => dialog.accept()); await bearer.getByRole("button", { name: "Delete" }).click(); await bearer.getByText("Integration deleted.", { exact: true }).waitFor(); - assert.equal(deleteBody.expectedRevision, revision - 1); + assert.equal(deleteBody.expectedRevision, 3); + assert.deepEqual(deleteBody.idempotencyKey.match(/-/gu)?.length, 4); + assert.equal(await bearer.getByText("Test bearer", { exact: true }).count(), 0); await context.close(); }); test("integration settings tolerates legacy exe connections without tags", async () => { diff --git a/packages/credential-proxy/src/decrypted-grants.mjs b/packages/credential-proxy/src/decrypted-grants.mjs index 520eaaa6..fba31583 100644 --- a/packages/credential-proxy/src/decrypted-grants.mjs +++ b/packages/credential-proxy/src/decrypted-grants.mjs @@ -8,6 +8,7 @@ const SALT = new TextEncoder().encode("factorize.unlock-key.v1"); const INFO = new TextEncoder().encode("factorize.record.aes-256-gcm.v1"); const encoder = new TextEncoder(); const decoder = new TextDecoder("utf-8", { fatal: true }); +const MANAGED_BEARER_PREFIX = "factorize-managed-bearer-v1:"; function decodeBase64Url(value, label) { if (typeof value !== "string" || !/^[A-Za-z0-9_-]+$/.test(value)) throw new TypeError(`malformed ${label}`); @@ -61,7 +62,7 @@ function validateOrigin(origin) { * layer; this helper never sends the user's unlock key or plaintext upstream. */ export function createDecryptedGrantResolver({ readSnapshot, getUnlockKey, resolveIntegrationIds } = {}) { - if (typeof readSnapshot !== "function" || typeof getUnlockKey !== "function" + if (typeof readSnapshot !== "function" || (getUnlockKey !== undefined && typeof getUnlockKey !== "function") || (resolveIntegrationIds !== undefined && typeof resolveIntegrationIds !== "function")) throw new TypeError("grant resolver requires snapshot and unlock-key readers"); return async function resolveGrants(binding) { if (!binding || typeof binding.tenantId !== "string" || !binding.tenantId @@ -70,8 +71,6 @@ export function createDecryptedGrantResolver({ readSnapshot, getUnlockKey, resol if (requestedIds !== undefined && (!Array.isArray(requestedIds) || requestedIds.some(id => typeof id !== "string" || !id) || new Set(requestedIds).size !== requestedIds.length)) throw new TypeError("invalid run integration selection"); if (requestedIds?.length === 0) return []; - const unlockKey = await getUnlockKey(); - if (typeof unlockKey !== "string" || !unlockKey) throw new Error("proxy is locked"); const snapshot = await readSnapshot(binding); if (!snapshot || !Array.isArray(snapshot.records) || typeof snapshot.ownerId !== "string" || !snapshot.ownerId) throw new Error("integration snapshot is unavailable"); // Production snapshots are already filtered by the control plane using the @@ -88,7 +87,11 @@ export function createDecryptedGrantResolver({ readSnapshot, getUnlockKey, resol const selectedRecords = snapshot.records.filter(record => selected.has(record?.id) && record.kind === "bearer"); const selectionWasNarrowedLocally = binding.integrationIds !== undefined || resolveIntegrationIds !== undefined; if (selectedRecords.length !== selected.size || (!selectionWasNarrowedLocally && snapshot.records.length !== selectedRecords.length)) throw new Error("selected integration is unavailable"); - const aesKey = await deriveKey(unlockKey); + const needsLegacyKey = selectedRecords.some(record => record.deletedAt == null + && typeof record.encryptedPayload === "string" && !record.encryptedPayload.startsWith(MANAGED_BEARER_PREFIX)); + const unlockKey = needsLegacyKey ? await getUnlockKey?.() : null; + if (needsLegacyKey && (typeof unlockKey !== "string" || !unlockKey)) throw new Error("proxy is locked"); + const aesKey = unlockKey ? await deriveKey(unlockKey) : null; const grants = []; for (const record of selectedRecords) { if (record.deletedAt != null) { @@ -97,9 +100,14 @@ export function createDecryptedGrantResolver({ readSnapshot, getUnlockKey, resol } if (typeof record.encryptedPayload !== "string") throw new Error("selected integration is unavailable"); const origin = validateOrigin(record.origin); - const { nonce, ciphertext } = decodeStoredCiphertext(record.encryptedPayload); - const plaintext = new Uint8Array(await webcrypto.subtle.decrypt({ name: "AES-GCM", iv: nonce, - additionalData: recordAad(snapshot.ownerId, record), tagLength: 128 }, aesKey, ciphertext)); + let nonce, ciphertext, plaintext; + if (record.encryptedPayload.startsWith(MANAGED_BEARER_PREFIX)) { + plaintext = encoder.encode(record.encryptedPayload.slice(MANAGED_BEARER_PREFIX.length)); + } else { + ({ nonce, ciphertext } = decodeStoredCiphertext(record.encryptedPayload)); + plaintext = new Uint8Array(await webcrypto.subtle.decrypt({ name: "AES-GCM", iv: nonce, + additionalData: recordAad(snapshot.ownerId, record), tagLength: 128 }, aesKey, ciphertext)); + } try { const credential = decoder.decode(plaintext); if (!credential || credential.length > 16_384 || /[\u0000-\u001f\u007f]/.test(credential)) throw new TypeError("invalid bearer credential"); @@ -112,8 +120,8 @@ export function createDecryptedGrantResolver({ readSnapshot, getUnlockKey, resol })); } finally { plaintext.fill(0); - nonce.fill(0); - ciphertext.fill(0); + nonce?.fill(0); + ciphertext?.fill(0); } } return grants; diff --git a/packages/credential-proxy/test/decrypted-grants.test.mjs b/packages/credential-proxy/test/decrypted-grants.test.mjs index 10163ee3..4ac3fac5 100644 --- a/packages/credential-proxy/test/decrypted-grants.test.mjs +++ b/packages/credential-proxy/test/decrypted-grants.test.mjs @@ -47,6 +47,21 @@ test("resolver decrypts only selected active bearer records using the shared rec ]); }); +test("resolver uses Factorize-managed bearer secrets without an inner unlock key", async () => { + const token = "server-managed-synthetic-token"; + const record = { id: webcrypto.randomUUID(), kind: "bearer", name: "managed", origin: "https://api.example.test", description: null, revision: 1, + encryptedPayload: `factorize-managed-bearer-v1:${token}`, deletedAt: null }; + let unlockCalls = 0; + const resolver = createDecryptedGrantResolver({ + readSnapshot: async () => ({ ownerId: "owner", records: [record] }), + getUnlockKey: async () => { unlockCalls++; return undefined; }, + }); + assert.deepEqual(await resolver({ tenantId: "tenant", integrationIds: [record.id] }), [ + { id: record.id, name: "managed", description: null, origin: record.origin, credential: token }, + ]); + assert.equal(unlockCalls, 0); +}); + test("resolver rejects missing, ambiguous, malformed, and misbound grants and omits deleted selections", async () => { const record = { id: "integration-a", kind: "bearer", origin: "https://api.example.test", revision: 3, deletedAt: null }; const encryptedPayload = await encryptCredential({ ...record, credential: "synthetic-token" }); @@ -87,14 +102,12 @@ test("production grant resolver reads the run-bound snapshot and only decrypts w }); const binding = { tenantId: ownerId, runId: "22222222-2222-4222-8222-222222222222", grantRevision: 7 }; await assert.rejects(resolve(binding), /locked/); + assert.equal(requests.length, 1, "legacy ciphertext may be fetched into the proxy but is not decrypted while locked"); runtime.unlock(unlockKey); assert.deepEqual(await resolve(binding), [{ id: record.id, name: record.id, description: null, origin: record.origin, credential: "snapshot-token" }]); - assert.deepEqual(requests, [{ - url: "https://factorize.example/internal/credential-proxy/integration-snapshot", - authorization: `Bearer fzc_${"c".repeat(43)}`, - body: { runId: binding.runId, grantRevision: binding.grantRevision }, - }]); + assert.equal(requests.length, 2); await runtime.lock(); await assert.rejects(resolve(binding), /locked/); + assert.equal(requests.length, 3); await runtime.shutdown(); }); diff --git a/packages/credential-proxy/test/fly-guest-helper.e2e.test.mjs b/packages/credential-proxy/test/fly-guest-helper.e2e.test.mjs index 914f2838..b42ecc3a 100644 --- a/packages/credential-proxy/test/fly-guest-helper.e2e.test.mjs +++ b/packages/credential-proxy/test/fly-guest-helper.e2e.test.mjs @@ -292,7 +292,7 @@ test("locked scoped run reconnects with its current grant while another VM stays const waitingWhileLocked = fetch(`http://127.0.0.1:${helperPort}/integrations/${integrationId}/echo`); await new Promise(resolve => setTimeout(resolve, 80)); assert.equal(runtime.state, "locked"); - assert.equal(snapshotReads, 0, "locked proxy denies selected Factorize grants before decrypting a snapshot"); + assert.ok(snapshotReads > 0, "locked proxy may fetch server-encrypted snapshots but does not decrypt or forward legacy grants"); assert.deepEqual(observedAuthorizations, [], "locked proxy does not forward to the upstream"); runtime.unlock(unlockKey); diff --git a/packages/docs/openapi.yaml b/packages/docs/openapi.yaml index 40a76a6d..72868636 100644 --- a/packages/docs/openapi.yaml +++ b/packages/docs/openapi.yaml @@ -2784,16 +2784,16 @@ paths: additionalProperties: false /api/v1/integrations/bearer: get: - summary: List encrypted bearer integrations + summary: List bearer integration metadata description: |- - Requires an interactive owner browser session. Returns safe metadata and user-encrypted ciphertext; credentials are never decrypted or revealed. + Requires an interactive owner browser session. Returns secret-safe metadata only; stored bearer credentials are never returned. Requires the integrations:read scope. An interactive owner session is required; bearer tokens cannot call this operation. responses: "200": - description: Encrypted bearer integration records + description: Bearer integration metadata content: application/json: schema: @@ -2824,15 +2824,12 @@ paths: type: integer minimum: 0 maximum: 9007199254740991 - encryptedPayload: - type: string required: - id - name - origin - description - revision - - encryptedPayload additionalProperties: false required: - revision @@ -2863,9 +2860,9 @@ paths: x-required-scope: integrations:read x-owner-session-required: true post: - summary: Create an encrypted bearer integration + summary: Create a bearer integration description: |- - Requires an interactive owner browser session. Accepts only user-encrypted ciphertext, never an unlock key or plaintext credential. + Requires an interactive owner browser session. Accepts the secret over the authenticated connection and encrypts it with Factorize-managed storage before persistence. The secret is never returned. Requires the integrations:write scope. @@ -2946,10 +2943,10 @@ paths: - type: string maxLength: 500 - type: "null" - encryptedPayload: + token: type: string minLength: 1 - maxLength: 65536 + maxLength: 32768 required: - id - expectedRevision @@ -2957,13 +2954,13 @@ paths: - name - origin - description - - encryptedPayload + - token additionalProperties: false /api/v1/integrations/bearer/{integrationId}: put: - summary: Update an encrypted bearer integration + summary: Update a bearer integration description: |- - Requires an interactive owner browser session and the current collection revision. Accepts only user-encrypted ciphertext. + Requires an interactive owner browser session and the current collection revision. Accepts a replacement secret and encrypts it with Factorize-managed storage before persistence. The secret is never returned. Requires the integrations:write scope. @@ -3047,17 +3044,17 @@ paths: - type: string maxLength: 500 - type: "null" - encryptedPayload: + token: type: string minLength: 1 - maxLength: 65536 + maxLength: 32768 required: - expectedRevision - idempotencyKey - name - origin - description - - encryptedPayload + - token additionalProperties: false delete: summary: Delete an encrypted bearer integration From 713a4cc4849a585067954b1b371b3ff04ec236a5 Mon Sep 17 00:00:00 2001 From: "exe.dev user" Date: Mon, 16 Nov 2026 20:47:47 +0000 Subject: [PATCH 08/28] Store model account caches with server encryption --- packages/api-client/src/schema.d.ts | 7 +- packages/api/src/api-contract.ts | 6 +- packages/api/src/flow-service.ts | 16 +++- .../encrypted-integration-repository.ts | 35 +++++--- packages/api/src/proxy-control.ts | 18 ++-- packages/api/test/api-contract.test.ts | 4 +- ...ed-integration-repository.postgres.test.ts | 26 ++---- packages/api/test/proxy-control.test.ts | 8 +- .../src/features/settings/model-accounts.tsx | 31 ++----- packages/app/test/settings.browser.test.mjs | 22 +---- .../credential-proxy/src/browser-control.mjs | 1 - .../credential-proxy/src/control-client.mjs | 24 ++--- packages/credential-proxy/src/main.mjs | 15 +--- .../src/model-account-lifecycle.mjs | 87 +++++++++---------- .../test/control-client.test.mjs | 29 ++++--- .../test/model-account-lifecycle.test.mjs | 76 +++++++--------- .../test/runtime-revocation.test.mjs | 6 +- packages/docs/openapi.yaml | 11 ++- 18 files changed, 188 insertions(+), 234 deletions(-) diff --git a/packages/api-client/src/schema.d.ts b/packages/api-client/src/schema.d.ts index 00b27998..196ef62b 100644 --- a/packages/api-client/src/schema.d.ts +++ b/packages/api-client/src/schema.d.ts @@ -19,7 +19,7 @@ export interface paths { put?: never; /** * Create a model account - * @description Requires an interactive owner browser session and the current collection revision. Accepts only user-encrypted initial account state; credentials are established directly with the credential proxy. + * @description Requires an interactive owner browser session and the current collection revision. Creates metadata with an empty initial state; the credential proxy establishes credentials and Factorize encrypts cache updates with its server key. * * Requires the integrations:write scope. * @@ -44,7 +44,7 @@ export interface paths { post?: never; /** * Delete a model account - * @description Requires an interactive owner browser session and the current collection revision. Deletion is recorded as a tombstone so future snapshots and unlock reconciliation cannot restore the account. + * @description Requires an interactive owner browser session and the current collection revision. Deletion is recorded as a tombstone so future run snapshots reject the disconnected account. * * Requires the integrations:write scope. * @@ -2937,7 +2937,8 @@ export interface operations { idempotencyKey: string; name: string; description: string | null; - encryptedPayload: string; + /** @constant */ + initialState: "{}"; }; }; }; diff --git a/packages/api/src/api-contract.ts b/packages/api/src/api-contract.ts index f429b7be..029d685d 100644 --- a/packages/api/src/api-contract.ts +++ b/packages/api/src/api-contract.ts @@ -135,7 +135,7 @@ const modelAccountMetadata = z.object({ id: z.uuid(), name: z.string(), descript const modelAccountCreate = z.object({ id: z.uuid(), expectedRevision: z.number().int().nonnegative(), idempotencyKey: z.uuid(), name: z.string().trim().min(1).max(120), description: z.string().max(500).nullable(), - encryptedPayload: z.string().min(1).max(65_536), + initialState: z.literal("{}"), }).strict(); const modelAccountDelete = z.object({ expectedRevision: z.number().int().nonnegative(), idempotencyKey: z.uuid() }).strict(); const modelAccountList = z.object({ revision: z.number().int().nonnegative(), accounts: z.array(modelAccountMetadata) }); @@ -233,12 +233,12 @@ export const API_ROUTES: RouteContract[] = [ }, service => service.listModelAccounts(), { ownerSession: true }), route("POST", "/api/v1/model-accounts", "integrations:write", { summary: "Create a model account", - description: "Requires an interactive owner browser session and the current collection revision. Accepts only user-encrypted initial account state; credentials are established directly with the credential proxy.", + description: "Requires an interactive owner browser session and the current collection revision. Creates metadata with an empty initial state; the credential proxy establishes credentials and Factorize encrypts cache updates with its server key.", responses: { "201": { description: "Created model account", content: { "application/json": { schema: jsonSchema(bearerIntegrationWriteResult, "output") } } } }, }, (service, { body }) => service.createModelAccount(body), { body: modelAccountCreate, maxBodyBytes: 70_000, ownerSession: true }), route("DELETE", "/api/v1/model-accounts/{accountId}", "integrations:write", { summary: "Delete a model account", - description: "Requires an interactive owner browser session and the current collection revision. Deletion is recorded as a tombstone so future snapshots and unlock reconciliation cannot restore the account.", + description: "Requires an interactive owner browser session and the current collection revision. Deletion is recorded as a tombstone so future run snapshots reject the disconnected account.", responses: { "200": { description: "Deleted model account", content: { "application/json": { schema: jsonSchema(bearerIntegrationDeleteResult, "output") } } } }, }, (service, { params, body }) => service.deleteModelAccount(params.accountId, body), { body: modelAccountDelete, maxBodyBytes: 4096, ownerSession: true, parameters: z.object({ accountId: z.uuid() }) }), route("POST", "/api/v1/credential-proxy/setup", "integrations:write", { diff --git a/packages/api/src/flow-service.ts b/packages/api/src/flow-service.ts index 92785696..ae5e9446 100644 --- a/packages/api/src/flow-service.ts +++ b/packages/api/src/flow-service.ts @@ -594,6 +594,9 @@ export class ApiService { async getUnlockKeyRotationSnapshot() { await this.authorizeOwnerSession("integrations:read"); const repository = this.encryptedIntegrations(); + if ((await repository.records("model")).some(record => record.encryptedPayload.startsWith("factorize-managed-model-cache-v1:"))) { + throw new ServiceError(409, "conflict", "Model account caches use Factorize-managed encryption and cannot be included in unlock-key rotation."); + } const [snapshot, verification] = await Promise.all([ repository.rotationSnapshot(), databaseFor(this.env).pool.query<{ generation_id: string }>("SELECT generation_id FROM app.unlock_key_verifications WHERE tenant_id=$1", [this.auth.tenantId]), @@ -682,11 +685,12 @@ export class ApiService { throw error; } } - async createModelAccount(input: { id: string; expectedRevision: number; idempotencyKey: string; name: string; description: string | null; encryptedPayload: string }) { + async createModelAccount(input: { id: string; expectedRevision: number; idempotencyKey: string; name: string; description: string | null; initialState: string }) { await this.authorizeOwnerSession("integrations:write"); const repository = this.encryptedIntegrations(); + const managed = { ...input, initialState: undefined, managedModelPayload: input.initialState, kind: "model" as const, origin: null, operation: "upsert" as const }; try { - const replay = await repository.replay({ ...input, kind: "model", origin: null, operation: "upsert" }); + const replay = await repository.replay(managed); if (replay) return replay; } catch (error) { if (error instanceof IntegrationIdempotencyConflictError) throw new ServiceError(409, "conflict", "The idempotency key was already used for a different model account change."); @@ -694,7 +698,13 @@ export class ApiService { throw error; } if ((await repository.records()).some(record => record.id === input.id)) throw new ServiceError(409, "conflict", "An integration with this id already exists."); - return this.modelAccountWrite({ ...input, operation: "upsert" }); + try { return await repository.write(managed); } + catch (error) { + if (error instanceof StaleIntegrationRevisionError) throw new ServiceError(409, "stale_revision", `The model account collection changed. Current revision is ${error.currentRevision}.`); + if (error instanceof IntegrationIdempotencyConflictError) throw new ServiceError(409, "conflict", "The idempotency key was already used for a different model account change."); + if (error instanceof IntegrationValidationError) throw new ServiceError(400, "invalid_request", error.message); + throw error; + } } async deleteModelAccount(id: string, input: { expectedRevision: number; idempotencyKey: string }) { await this.authorizeOwnerSession("integrations:write"); diff --git a/packages/api/src/postgres/encrypted-integration-repository.ts b/packages/api/src/postgres/encrypted-integration-repository.ts index fd916f20..a846f911 100644 --- a/packages/api/src/postgres/encrypted-integration-repository.ts +++ b/packages/api/src/postgres/encrypted-integration-repository.ts @@ -11,6 +11,8 @@ export type IntegrationWrite = IntegrationMetadata & { encryptedPayload?: string; /** Plaintext bearer value accepted only by the owner-session credential API. */ managedSecret?: string; + /** Initial model cache accepted only by the owner-session model-account API. */ + managedModelPayload?: string; }; export type IntegrationChange = IntegrationMetadata & { revision: number; @@ -22,6 +24,7 @@ export type GenerationRecord = IntegrationMetadata & { revision: number; encrypt export type GenerationChange = IntegrationMetadata & { revision: number; idempotencyKey: string; operation: "upsert" | "delete"; encryptedPayload: string | null }; const MANAGED_BEARER_PREFIX = "factorize-managed-bearer-v1:"; +const MANAGED_MODEL_PREFIX = "factorize-managed-model-cache-v1:"; export class StaleIntegrationRevisionError extends Error { constructor(readonly currentRevision: number, readonly resyncRequired = false) { super(resyncRequired ? "Integration change history expired; fetch the current collection before continuing" : "Integration collection revision is stale"); this.name = "StaleIntegrationRevisionError"; } @@ -68,8 +71,10 @@ function validate(change: IntegrationWrite): void { if (change.kind === "bearer" && (!change.origin || change.origin.length > 2048)) throw new IntegrationValidationError("bearer integrations require an origin of at most 2048 characters"); if (change.kind === "model" && change.origin !== null) throw new IntegrationValidationError("model accounts do not have an origin"); if (change.operation === "upsert" && !(typeof change.managedSecret === "string" && change.managedSecret.length > 0 && change.managedSecret.length <= 32_768) + && !(typeof change.managedModelPayload === "string" && change.managedModelPayload.length > 0 && change.managedModelPayload.length <= 65_536 && (() => { try { const value = JSON.parse(change.managedModelPayload); return Boolean(value && typeof value === "object" && !Array.isArray(value)); } catch { return false; } })()) && !(typeof change.encryptedPayload === "string" && isUserCiphertext(change.encryptedPayload))) throw new IntegrationValidationError("upserts require a credential value"); if (change.kind !== "bearer" && change.managedSecret !== undefined) throw new IntegrationValidationError("managed secrets are only supported for bearer integrations"); + if (change.kind !== "model" && change.managedModelPayload !== undefined) throw new IntegrationValidationError("managed model payloads are only supported for model accounts"); if (change.operation === "delete" && change.encryptedPayload !== undefined) throw new IntegrationValidationError("deletions cannot contain ciphertext"); } @@ -89,7 +94,8 @@ export class EncryptedIntegrationRepository { const { rows } = await this.database.pool.query("SELECT revision,operation,record_id,kind,name,origin,description,encrypted_payload FROM app.integration_changes WHERE tenant_id=$1 AND idempotency_key=$2", [this.tenantId, input.idempotencyKey]); const row = rows[0]; if (!row) return null; - const suppliedPayload = input.managedSecret === undefined ? input.encryptedPayload : `${MANAGED_BEARER_PREFIX}${input.managedSecret}`; + const suppliedPayload = input.managedSecret !== undefined ? `${MANAGED_BEARER_PREFIX}${input.managedSecret}` + : input.managedModelPayload !== undefined ? `${MANAGED_MODEL_PREFIX}${input.managedModelPayload}` : input.encryptedPayload; const sameCiphertext = row.encrypted_payload === null ? input.operation === "delete" && input.encryptedPayload === undefined : input.operation === "upsert" && typeof suppliedPayload === "string" && await decrypt(row.encrypted_payload, this.serverEncryptionKey) === suppliedPayload; @@ -113,7 +119,8 @@ export class EncryptedIntegrationRepository { async write(input: IntegrationWrite): Promise<{ revision: number; duplicate: boolean }> { validate(input); - const suppliedPayload = input.managedSecret === undefined ? input.encryptedPayload : `${MANAGED_BEARER_PREFIX}${input.managedSecret}`; + const suppliedPayload = input.managedSecret !== undefined ? `${MANAGED_BEARER_PREFIX}${input.managedSecret}` + : input.managedModelPayload !== undefined ? `${MANAGED_MODEL_PREFIX}${input.managedModelPayload}` : input.encryptedPayload; const encryptedPayload = input.operation === "upsert" ? await encrypt(suppliedPayload!, this.serverEncryptionKey) : null; const metadata = [input.id, input.kind, input.name, input.origin, input.description, input.operation, encryptedPayload]; return this.database.transaction(async client => { @@ -190,22 +197,22 @@ export class EncryptedIntegrationRepository { }; } - /** - * Replace only a model account's user-encrypted Codex cache. The account - * revision is independent of the collection revision, so unrelated bearer - * edits do not invalidate the cache's authenticated-encryption binding. - */ - async saveModelCache(input: { id: string; expectedRevision: number; keyGeneration: string; encryptedPayload: string; idempotencyKey: string }): Promise<{ revision: number; collectionRevision: number; duplicate: boolean }> { + /** Store a model auth cache under Factorize-managed encryption. The proxy is + * trusted to handle the live token, while the database only receives the + * server-encrypted cache. */ + async saveModelCache(input: { id: string; expectedRevision: number; encryptedPayload: string; idempotencyKey: string }): Promise<{ revision: number; collectionRevision: number; duplicate: boolean }> { const uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; - if (!uuid.test(input.id) || !uuid.test(input.idempotencyKey) || !uuid.test(input.keyGeneration) || !Number.isSafeInteger(input.expectedRevision) || input.expectedRevision < 0 - || !isUserCiphertext(input.encryptedPayload)) throw new IntegrationValidationError("model cache binding is invalid"); - const encryptedPayload = await encrypt(input.encryptedPayload, this.serverEncryptionKey); + if (!uuid.test(input.id) || !uuid.test(input.idempotencyKey) || !Number.isSafeInteger(input.expectedRevision) || input.expectedRevision < 0 + || typeof input.encryptedPayload !== "string" || input.encryptedPayload.length === 0 || input.encryptedPayload.length > 65_536) throw new IntegrationValidationError("model cache binding is invalid"); + let parsed: unknown; + try { parsed = JSON.parse(input.encryptedPayload); } catch { throw new IntegrationValidationError("model cache is invalid"); } + if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) throw new IntegrationValidationError("model cache is invalid"); + const managedPayload = `${MANAGED_MODEL_PREFIX}${input.encryptedPayload}`; + const encryptedPayload = await encrypt(managedPayload, this.serverEncryptionKey); return this.database.transaction(async client => { await client.query("INSERT INTO app.integration_collections(tenant_id) VALUES ($1) ON CONFLICT DO NOTHING", [this.tenantId]); const collection = (await client.query<{ revision: string | number }>("SELECT revision FROM app.integration_collections WHERE tenant_id=$1 FOR UPDATE", [this.tenantId])).rows[0]!; const currentCollectionRevision = safeRevision(collection.revision); - const keyState = (await client.query<{ generation_id: string }>("SELECT generation_id FROM app.unlock_key_verifications WHERE tenant_id=$1 FOR UPDATE", [this.tenantId])).rows[0]; - if (!keyState || keyState.generation_id !== input.keyGeneration) throw new StaleIntegrationRevisionError(currentCollectionRevision); const current = (await client.query<{ kind: EncryptedIntegrationKind; name: string; origin: string | null; description: string | null; revision: string | number; encrypted_payload: string | null; deleted_at: Date | null }>( "SELECT kind,name,origin,description,revision,encrypted_payload,deleted_at FROM app.integration_records WHERE tenant_id=$1 AND id=$2 FOR UPDATE", [this.tenantId, input.id])).rows[0]; if (!current || current.kind !== "model" || current.deleted_at || current.revision === null) throw new IntegrationValidationError("model account is unavailable"); @@ -214,7 +221,7 @@ export class EncryptedIntegrationRepository { "SELECT revision,record_id,operation,encrypted_payload FROM app.integration_changes WHERE tenant_id=$1 AND idempotency_key=$2", [this.tenantId,input.idempotencyKey])).rows[0]; if (previousChange) { const same = previousChange.record_id === input.id && previousChange.operation === "upsert" && previousChange.encrypted_payload !== null - && await decrypt(previousChange.encrypted_payload, this.serverEncryptionKey) === input.encryptedPayload; + && await decrypt(previousChange.encrypted_payload, this.serverEncryptionKey) === managedPayload; if (!same) throw new IntegrationIdempotencyConflictError(); return { revision: Math.max(0, input.expectedRevision + 1), collectionRevision: safeRevision(previousChange.revision), duplicate: true }; } diff --git a/packages/api/src/proxy-control.ts b/packages/api/src/proxy-control.ts index 036cfd78..c2c8920c 100644 --- a/packages/api/src/proxy-control.ts +++ b/packages/api/src/proxy-control.ts @@ -71,7 +71,8 @@ export async function proxyControlFetch(request: Request, env: Parameters("SELECT unlocked FROM app.credential_proxy_states WHERE tenant_id=$1 AND proxy_identity=$2 AND boot_epoch=$3", [proxy.tenantId, proxy.proxyIdentity, proxy.bootEpoch]); - return json({ revokedRunIds: revoked.rows.map(row => row.run_id), lockProxy: !state.rows[0]?.unlocked }); + const activeModelAccounts = await databaseFor(env).pool.query<{ id: string }>("SELECT id FROM app.integration_records WHERE tenant_id=$1 AND kind='model' AND deleted_at IS NULL", [proxy.tenantId]); + return json({ revokedRunIds: revoked.rows.map(row => row.run_id), activeModelAccountIds: activeModelAccounts.rows.map(row => row.id), lockProxy: !state.rows[0]?.unlocked }); } if (url.pathname === "/internal/credential-proxy/model-account-cache") { if (!body || typeof body !== "object" || Array.isArray(body)) return json({ error: "invalid_request" }, 400); @@ -79,9 +80,7 @@ export async function proxyControlFetch(request: Request, env: Parameters("SELECT generation_id FROM app.unlock_key_verifications WHERE tenant_id=$1", [proxy.tenantId]); - if (!keyState.rows[0]) return json({ error: "model_account_unavailable" }, 404); - return json({ ownerId: await recordOwner(env, proxy.tenantId), keyGeneration: keyState.rows[0].generation_id, + return json({ ownerId: await recordOwner(env, proxy.tenantId), accounts: accounts.map(({ id, revision }) => ({ id, revision, kind: "model", origin: null })) }); } if (input.operation === "read" && Object.keys(input).sort().join(",") === "accountId,operation" @@ -89,19 +88,16 @@ export async function proxyControlFetch(request: Request, env: Parameters record.id === input.accountId); if (!account) return json({ error: "model_account_unavailable" }, 404); - const keyState = await databaseFor(env).pool.query<{ generation_id: string }>("SELECT generation_id FROM app.unlock_key_verifications WHERE tenant_id=$1", [proxy.tenantId]); - if (!keyState.rows[0]) return json({ error: "model_account_unavailable" }, 404); - return json({ ownerId: await recordOwner(env, proxy.tenantId), account: { ...account, keyGeneration: keyState.rows[0].generation_id } }); + return json({ ownerId: await recordOwner(env, proxy.tenantId), account }); } - if (input.operation !== "save" || Object.keys(input).sort().join(",") !== "accountId,encryptedPayload,expectedRevision,idempotencyKey,keyGeneration,operation" + if (input.operation !== "save" || Object.keys(input).sort().join(",") !== "accountId,encryptedPayload,expectedRevision,idempotencyKey,operation" || typeof input.accountId !== "string" || !uuid.test(input.accountId) - || typeof input.keyGeneration !== "string" || !uuid.test(input.keyGeneration) || typeof input.idempotencyKey !== "string" || !uuid.test(input.idempotencyKey) || !Number.isSafeInteger(input.expectedRevision) || (input.expectedRevision as number) < 0 - || typeof input.encryptedPayload !== "string") return json({ error: "invalid_request" }, 400); + || typeof input.encryptedPayload !== "string" || input.encryptedPayload.length > 65_536) return json({ error: "invalid_request" }, 400); try { const saved = await new EncryptedIntegrationRepository(databaseFor(env), proxy.tenantId, env.CREDENTIAL_ENCRYPTION_KEY).saveModelCache({ - id: input.accountId, expectedRevision: input.expectedRevision as number, keyGeneration: input.keyGeneration, + id: input.accountId, expectedRevision: input.expectedRevision as number, idempotencyKey: input.idempotencyKey, encryptedPayload: input.encryptedPayload, }); return json({ ...saved, accountId: input.accountId }); diff --git a/packages/api/test/api-contract.test.ts b/packages/api/test/api-contract.test.ts index bd3a686b..943e374d 100644 --- a/packages/api/test/api-contract.test.ts +++ b/packages/api/test/api-contract.test.ts @@ -81,8 +81,8 @@ describe("versioned API contract", () => { expect(route?.ownerSession).toBe(true); expect(route?.documentation.responses["200"].content["application/json"].schema.properties.accounts.items.properties.encryptedPayload).toBeUndefined(); expect(create?.scope).toBe("integrations:write"); expect(create?.ownerSession).toBe(true); - expect(create?.body?.safeParse({ id: "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa", expectedRevision: 0, idempotencyKey: "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb", name: "Account", description: null, encryptedPayload: "cipher" }).success).toBe(true); - expect(create?.body?.safeParse({ id: "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa", expectedRevision: 0, idempotencyKey: "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb", name: "Account", description: null, encryptedPayload: "cipher", unlockKey: "must-not-be-accepted" }).success).toBe(false); + expect(create?.body?.safeParse({ id: "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa", expectedRevision: 0, idempotencyKey: "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb", name: "Account", description: null, initialState: "{}" }).success).toBe(true); + expect(create?.body?.safeParse({ id: "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa", expectedRevision: 0, idempotencyKey: "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb", name: "Account", description: null, initialState: "{}", unlockKey: "must-not-be-accepted" }).success).toBe(false); expect(remove?.scope).toBe("integrations:write"); expect(remove?.ownerSession).toBe(true); expect(remove?.parameters.shape.accountId).toBeDefined(); expect(openapi.paths["/api/v1/model-accounts"].post).toBeDefined(); diff --git a/packages/api/test/encrypted-integration-repository.postgres.test.ts b/packages/api/test/encrypted-integration-repository.postgres.test.ts index c2a5e7ce..550195fc 100644 --- a/packages/api/test/encrypted-integration-repository.postgres.test.ts +++ b/packages/api/test/encrypted-integration-repository.postgres.test.ts @@ -85,26 +85,18 @@ describe.skipIf(!url)("encrypted integration persistence (PostgreSQL)", () => { expect(results.filter(result => result.status === "rejected" && result.reason instanceof StaleIntegrationRevisionError)).toHaveLength(1); }); - it("rejects a model cache save encrypted under a replaced key generation even when its account revision is unchanged", async () => { + it("stores model refresh caches with server encryption and no unlock-key generation", async () => { const { tenantId, repository } = await freshRepository(); - const generation = crypto.randomUUID(); - const replacementGeneration = crypto.randomUUID(); - await db.pool.query("INSERT INTO app.unlock_key_verifications(tenant_id,generation_id,encrypted_verification) VALUES ($1,$2,'verification')", [tenantId, generation]); const id = crypto.randomUUID(); - const created = await repository.write({ id, idempotencyKey: crypto.randomUUID(), expectedRevision: 0, operation: "upsert", kind: "model", name: "Codex", origin: null, description: null, encryptedPayload: await userEncrypt("initial cache") }); - const oldKeyCache = await userEncrypt("old generation cache"); - const saved = await repository.saveModelCache({ id, expectedRevision: created.revision, keyGeneration: generation, idempotencyKey: crypto.randomUUID(), encryptedPayload: oldKeyCache }); + const created = await repository.write({ id, idempotencyKey: crypto.randomUUID(), expectedRevision: 0, operation: "upsert", kind: "model", name: "Codex", origin: null, description: null, managedModelPayload: "{}" }); + const payload = JSON.stringify({ tokens: { access_token: "synthetic-access", refresh_token: "synthetic-refresh" } }); + const saved = await repository.saveModelCache({ id, expectedRevision: created.revision, idempotencyKey: crypto.randomUUID(), encryptedPayload: payload }); expect(saved.revision).toBe(created.revision + 1); - - await db.pool.query("UPDATE app.unlock_key_verifications SET generation_id=$2 WHERE tenant_id=$1", [tenantId, replacementGeneration]); - const staleKeyCache = await userEncrypt("late old generation refresh"); - await expect(repository.saveModelCache({ id, expectedRevision: saved.revision, keyGeneration: generation, idempotencyKey: crypto.randomUUID(), encryptedPayload: staleKeyCache })) - .rejects.toMatchObject({ name: "StaleIntegrationRevisionError" }); - expect((await repository.records("model"))[0]?.encryptedPayload).toBe(oldKeyCache); - - const currentKeyCache = await userEncrypt("replacement generation cache"); - await expect(repository.saveModelCache({ id, expectedRevision: saved.revision, keyGeneration: replacementGeneration, idempotencyKey: crypto.randomUUID(), encryptedPayload: currentKeyCache })) - .resolves.toMatchObject({ revision: saved.revision + 1, duplicate: false }); + const stored = (await db.pool.query("SELECT encrypted_payload FROM app.integration_records WHERE tenant_id=$1 AND id=$2", [tenantId, id])).rows[0].encrypted_payload as string; + expect(stored).not.toContain("synthetic-access"); + expect(await decrypt(stored, serverKey)).toBe(`factorize-managed-model-cache-v1:${payload}`); + await expect(repository.saveModelCache({ id, expectedRevision: saved.revision, idempotencyKey: crypto.randomUUID(), encryptedPayload: "not-json" })) + .rejects.toMatchObject({ name: "IntegrationValidationError" }); }); it("returns edits and deletion tombstones in revision order and deduplicates retries", async () => { diff --git a/packages/api/test/proxy-control.test.ts b/packages/api/test/proxy-control.test.ts index bcf1546b..819ac68f 100644 --- a/packages/api/test/proxy-control.test.ts +++ b/packages/api/test/proxy-control.test.ts @@ -58,7 +58,7 @@ describe("dedicated proxy boot registration endpoint", () => { const env = envFor(); env.query.mockImplementation(async (sql: string) => sql.includes("proxy_token_digest") ? { rows: [{ tenant_id: "11111111-1111-4111-8111-111111111111", proxy_identity: "proxy-fixture", boot_epoch: bootEpoch }], rowCount: 1 } - : sql.includes("FROM app.credential_run_grants") + : sql.includes("FROM app.credential_run_grants") ? { rows: [{ run_id: runId }], rowCount: 1 } : { rows: [], rowCount: 0 }); const response = await proxyControlFetch(request({ @@ -67,7 +67,7 @@ describe("dedicated proxy boot registration endpoint", () => { body: { bootEpoch }, }), env); expect(response.status).toBe(200); - expect(await response.json()).toEqual({ revokedRunIds: [runId], lockProxy: true }); + expect(await response.json()).toEqual({ revokedRunIds: [runId], activeModelAccountIds: [], lockProxy: true }); const revocationsQuery = env.query.mock.calls.find((call: any[]) => call[0].includes("FROM app.credential_run_grants"))?.[0] as string; expect(revocationsQuery).toContain("JOIN app.job_runs"); expect(revocationsQuery).toContain("r.state IN ('succeeded','failed','stopped')"); @@ -192,14 +192,14 @@ describe("dedicated proxy boot registration endpoint", () => { const env = envFor(); env.query.mockImplementation(async (sql: string) => sql.includes("proxy_token_digest") ? { rows: [{ tenant_id: "11111111-1111-4111-8111-111111111111", proxy_identity: "proxy-fixture", boot_epoch: bootEpoch }], rowCount: 1 } - : { rows: [{ run_id: runId }], rowCount: 1 }); + : sql.includes("integration_records") ? { rows: [], rowCount: 0 } : { rows: [{ run_id: runId }], rowCount: 1 }); const response = await proxyControlFetch(request({ authorization: `Bearer ${token}`, path: "/internal/credential-proxy/revocations", body: { bootEpoch }, }), env); expect(response.status).toBe(200); - expect(await response.json()).toEqual({ revokedRunIds: [runId], lockProxy: true }); + expect(await response.json()).toEqual({ revokedRunIds: [runId], activeModelAccountIds: [], lockProxy: true }); expect(env.query.mock.calls[1][0]).toContain("revoked_at IS NOT NULL"); expect(env.query.mock.calls[1][1]).toEqual(["11111111-1111-4111-8111-111111111111", "proxy-fixture", bootEpoch]); const stale = await proxyControlFetch(request({ diff --git a/packages/app/src/features/settings/model-accounts.tsx b/packages/app/src/features/settings/model-accounts.tsx index 3283878f..2a8df382 100644 --- a/packages/app/src/features/settings/model-accounts.tsx +++ b/packages/app/src/features/settings/model-accounts.tsx @@ -2,8 +2,6 @@ import { useEffect, useState } from "react"; import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; import { api } from "factorize-api-client"; import { Button, Card, Input, Label } from "../../shared/ui"; -import { encryptModelAccountCacheRecord, verifyUnlockKey } from "../../lib/unlock-crypto"; -import { getUnlockVerification } from "../../lib/unlock-key"; import { messageOf } from "../auth/session"; type DeviceState = { state: string; verificationUrl?: string; userCode?: string }; @@ -13,7 +11,6 @@ const accountsQuery = { queryKey: ["settings", "model-accounts"], queryFn: async if (!data || error) throw new Error(messageOf(error)); return data; } }; -const verificationQuery = { queryKey: ["unlock-key-verification"], queryFn: ({ signal }: { signal: AbortSignal }) => getUnlockVerification(signal), retry: false as const }; async function proxyAction(accountId: string, action: "authorize" | "status" | "cancel"): Promise { const capability = await api.POST("/api/v1/model-accounts/{accountId}/browser-capability", { @@ -29,44 +26,36 @@ async function proxyAction(accountId: string, action: "authorize" | "status" | " try { result = await response.json() as DeviceState; } catch { throw new Error("The credential proxy returned an invalid response."); } if (!response.ok) { - const messages: Record = { 423: "Unlock the credential proxy before connecting a model account.", 503: "The credential proxy is unavailable. Try again shortly." }; + const messages: Record = { 503: "The credential proxy is unavailable. Try again shortly." }; throw new Error(messages[response.status] ?? "The credential proxy could not complete this request."); } return result; } export function ModelAccounts() { - const cache = useQueryClient(), accounts = useQuery(accountsQuery), verification = useQuery(verificationQuery); + const cache = useQueryClient(), accounts = useQuery(accountsQuery); const [active, setActive] = useState(null); const [states, setStates] = useState>({}); const [error, setError] = useState(""); - const [name, setName] = useState(""), [description, setDescription] = useState(""), [key, setKey] = useState(""); + const [name, setName] = useState(""), [description, setDescription] = useState(""); const create = useMutation({ retry: false, mutationFn: async () => { const cleanName = name.trim(), cleanDescription = description.trim(); if (!cleanName || cleanName.length > 120) throw new Error("Enter a name up to 120 characters."); if (cleanDescription.length > 500) throw new Error("Description must be at most 500 characters."); - const setup = verification.data?.verification; - if (!setup || !verification.data) throw new Error("Set up an unlock key before adding a model account."); if (!accounts.data) throw new Error("Model accounts are still loading. Try again shortly."); - try { await verifyUnlockKey(key, verification.data.ownerId, setup.generationId, JSON.parse(setup.encryptedVerification)); } - catch { throw new Error("Unlock key could not be verified for this account and generation."); } const id = crypto.randomUUID(), expectedRevision = accounts.data.revision; - const encryptedPayload = await encryptModelAccountCacheRecord(new TextEncoder().encode("{}"), key, { - ownerId: verification.data.ownerId, recordId: id, recordType: "model", destination: "factorize", - keyGeneration: setup.generationId, revision: expectedRevision + 1, - }); const { data, error } = await api.POST("/api/v1/model-accounts", { body: { id, expectedRevision, idempotencyKey: crypto.randomUUID(), name: cleanName, - description: cleanDescription || null, encryptedPayload, + description: cleanDescription || null, initialState: "{}", } }); if (!data || error) throw new Error(messageOf(error)); return data; }, onSuccess: async () => { - setName(""); setDescription(""); setKey(""); setError(""); + setName(""); setDescription(""); setError(""); await cache.invalidateQueries({ queryKey: accountsQuery.queryKey }); }, onError: async reason => { - setKey(""); setError(reason.message); + setError(reason.message); if (reason.message.includes("changed") || reason.message.includes("revision")) await cache.invalidateQueries({ queryKey: accountsQuery.queryKey }); } }); @@ -113,7 +102,7 @@ export function ModelAccounts() { }; return
-

ChatGPT model accounts

Connect each account through Codex device authorization. Credentials stay in the credential proxy.

+

ChatGPT model accounts

Connect each account through Codex device authorization. Factorize encrypts credentials on the server.

{accounts.isPending &&

Loading model accounts…

} {accounts.error &&

{accounts.error.message}

} {error &&

{error}

} @@ -130,16 +119,14 @@ export function ModelAccounts() { {state.state === "canceled" &&

Device authorization canceled.

} {state.state === "pending" ? : } - + ; })}

Add a model account

- {!verification.data?.verification && verification.data &&

Set up your unlock key above before adding a model account.

}
{ event.preventDefault(); setError(""); create.mutate(); }}> - - +
; diff --git a/packages/app/test/settings.browser.test.mjs b/packages/app/test/settings.browser.test.mjs index 1f7a9fc6..066f6072 100644 --- a/packages/app/test/settings.browser.test.mjs +++ b/packages/app/test/settings.browser.test.mjs @@ -82,25 +82,18 @@ test("owner browser stores bearer integration in Factorize managed storage witho assert.equal(await page.evaluate(() => JSON.stringify(localStorage).includes("synthetic-upstream-secret")), false); await context.close(); }); -test("model account create/delete encrypts initial state and uses the current collection revision", async () => { +test("model account create/delete uses server-managed state without an unlock key", async () => { const { context, page } = await setup(); await page.route("**/api/v1/providers/github/installations", route => route.fulfill({ json: [] })); await page.route("**/api/v1/integrations", route => route.fulfill({ json: { linear: null, clickup: null, exe: null, exeConnections: [], ampConnections: [], cloudflareTail: { count: 0, installations: [] } } })); - let verification = null, revision = 0, account = null, createBody = null, deleteBodies = [], staleOnce = true; - await page.route("**/api/v1/unlock-key/verification", async route => { - if (route.request().method() === "GET") return route.fulfill({ json: { ownerId: "owner", verification } }); - const body = route.request().postDataJSON(); verification = { generationId: body.generationId, encryptedVerification: body.encryptedVerification }; - return route.fulfill({ json: { generationId: body.generationId } }); - }); + let revision = 0, account = null, createBody = null, deleteBodies = [], staleOnce = true; await page.route("**/api/v1/model-accounts", async route => { if (route.request().method() === "GET") return route.fulfill({ json: { revision, accounts: account ? [account] : [] } }); createBody = route.request().postDataJSON(); - assert.deepEqual(Object.keys(createBody).sort(), ["description", "encryptedPayload", "expectedRevision", "id", "idempotencyKey", "name"]); + assert.deepEqual(Object.keys(createBody).sort(), ["description", "expectedRevision", "id", "idempotencyKey", "initialState", "name"]); assert.equal(createBody.expectedRevision, revision); assert.equal(createBody.name, "Work account"); - assert.equal(createBody.encryptedPayload.includes("{}"), false); - assert.equal(createBody.encryptedPayload.includes("fzk1."), false); - assert.match(createBody.encryptedPayload, /^[A-Za-z0-9+/]+=*\.[A-Za-z0-9+/]+=*$/u); + assert.equal(createBody.initialState, "{}"); revision++; account = { id: createBody.id, name: createBody.name, description: createBody.description, revision }; return route.fulfill({ status: 201, json: { revision, duplicate: false } }); }); @@ -118,16 +111,9 @@ test("model account create/delete encrypts initial state and uses the current co }); await page.goto(origin + "/settings/integrations"); - await page.getByRole("button", { name: "Generate unlock key" }).click(); - const unlockKey = await page.getByLabel("New unlock key").inputValue(); - await page.getByRole("checkbox", { name: "I saved this key somewhere safe." }).check(); - await page.getByRole("button", { name: "I saved my key" }).click(); - await page.getByText("Unlock key verification is set up.", { exact: false }).waitFor(); - const models = page.getByRole("region", { name: "ChatGPT model accounts" }); await models.getByLabel("Name").fill("Work account"); await models.getByLabel("Description (optional)").fill("Personal account"); - await models.getByLabel("Unlock key").fill(unlockKey); await models.getByRole("button", { name: "Add model account" }).click(); await models.getByText("Work account", { exact: true }).waitFor(); assert.equal(createBody.expectedRevision, 0); diff --git a/packages/credential-proxy/src/browser-control.mjs b/packages/credential-proxy/src/browser-control.mjs index 7d40d65d..3a23a4f4 100644 --- a/packages/credential-proxy/src/browser-control.mjs +++ b/packages/credential-proxy/src/browser-control.mjs @@ -154,7 +154,6 @@ export async function startBrowserControl({ return json(response, 400, { error: "invalid_request" }, appOrigin); } if (operation === "authorize") { - if (runtime.state !== "unlocked") return json(response, 423, { error: "proxy_locked" }, appOrigin); const login = await lifecycle.deviceLogin(accountId); const state = { state: "pending", challenge: login.challenge }; authorizations.set(accountId, state); diff --git a/packages/credential-proxy/src/control-client.mjs b/packages/credential-proxy/src/control-client.mjs index b958e30d..a888e084 100644 --- a/packages/credential-proxy/src/control-client.mjs +++ b/packages/credential-proxy/src/control-client.mjs @@ -121,7 +121,7 @@ export function createModelAccountPersistenceAdapter({ controlOrigin, controlCre const account = result?.account; if (result?.ownerId !== ownerId || !account || account.id !== accountId || account.kind !== "model" || account.origin !== null || typeof account.encryptedPayload !== "string" - || !Number.isSafeInteger(account.revision) || !uuidPattern.test(account.keyGeneration ?? "")) { + || !Number.isSafeInteger(account.revision)) { throw new Error("invalid model account persistence response"); } return { ...account, ownerId }; @@ -130,23 +130,24 @@ export function createModelAccountPersistenceAdapter({ controlOrigin, controlCre async listAccounts() { const result = await proxyControlRequest({ controlOrigin, token: controlCredential, path: "/internal/credential-proxy/model-account-cache", body: { operation: "list" }, fetchImpl }); if (result?.ownerId !== ownerId || !Array.isArray(result.accounts) - || !uuidPattern.test(result.keyGeneration ?? "") || result.accounts.some(account => !account || !uuidPattern.test(account.id ?? "") || account.kind !== "model" || account.origin !== null || !Number.isSafeInteger(account.revision))) { throw new Error("invalid model account list response"); } - return result.accounts.map(account => ({ ...account, ownerId, keyGeneration: result.keyGeneration })); + return result.accounts.map(account => ({ ...account, ownerId })); }, getAccount: read, async getEncryptedCache(accountId) { const account = await read(accountId); - return { accountId, ownerId, keyGeneration: account.keyGeneration, revision: account.revision, encryptedPayload: account.encryptedPayload }; + const prefix = "factorize-managed-model-cache-v1:"; + if (!account.encryptedPayload.startsWith(prefix)) return null; + return { accountId, ownerId, revision: account.revision, payload: account.encryptedPayload.slice(prefix.length) }; }, - async persistEncrypted({ id, expectedRevision, keyGeneration, encryptedPayload, idempotencyKey }) { + async persistEncrypted({ id, expectedRevision, encryptedPayload, idempotencyKey }) { if (!uuidPattern.test(id ?? "") || !uuidPattern.test(idempotencyKey ?? "") || !Number.isSafeInteger(expectedRevision) - || !uuidPattern.test(keyGeneration ?? "") || typeof encryptedPayload !== "string" || encryptedPayload.length > 65_536) throw new TypeError("invalid encrypted model account update"); + || typeof encryptedPayload !== "string" || encryptedPayload.length > 65_536) throw new TypeError("invalid model account update"); const result = await proxyControlRequest({ controlOrigin, token: controlCredential, path: "/internal/credential-proxy/model-account-cache", - body: { operation: "save", accountId: id, expectedRevision, keyGeneration, encryptedPayload, idempotencyKey }, fetchImpl }); + body: { operation: "save", accountId: id, expectedRevision, encryptedPayload, idempotencyKey }, fetchImpl }); if (result?.accountId !== id || result.revision !== expectedRevision + 1 || typeof result.duplicate !== "boolean") { throw new Error("invalid model account persistence response"); } @@ -171,16 +172,18 @@ export async function readProxyControlState({ controlOrigin, token, bootEpoch, f body: { bootEpoch }, fetchImpl, }); - if (!Array.isArray(result?.revokedRunIds) || result.revokedRunIds.some(id => !uuidPattern.test(id))) { + if (!Array.isArray(result?.revokedRunIds) || result.revokedRunIds.some(id => !uuidPattern.test(id)) + || !Array.isArray(result?.activeModelAccountIds) || result.activeModelAccountIds.some(id => !uuidPattern.test(id)) + || new Set(result.activeModelAccountIds).size !== result.activeModelAccountIds.length) { throw new Error("invalid proxy revocation response"); } - return { revokedRunIds: result.revokedRunIds, lockProxy: result.lockProxy === true }; + return { revokedRunIds: result.revokedRunIds, activeModelAccountIds: result.activeModelAccountIds, lockProxy: result.lockProxy === true }; } /** Poll durable control-plane state. A failed request leaves established * connections running and the next bounded poll retries when communication * recovers; it does not add an authorization lease or expiry. */ -export function startProxyRunRevocationMonitor({ controlOrigin, controlCredential, bootEpoch, runtime, onRevoked = () => {}, intervalMs = 5_000, fetchImpl = fetch } = {}) { +export function startProxyRunRevocationMonitor({ controlOrigin, controlCredential, bootEpoch, runtime, onRevoked = () => {}, onModelAccountsChanged = () => {}, intervalMs = 5_000, fetchImpl = fetch } = {}) { if (!runtime || typeof runtime.revokeRun !== "function" || !Number.isInteger(intervalMs) || intervalMs < 100 || intervalMs > 60_000) { throw new TypeError("invalid proxy revocation monitor configuration"); } @@ -198,6 +201,7 @@ export function startProxyRunRevocationMonitor({ controlOrigin, controlCredentia const state = await readProxyControlState({ controlOrigin, token: controlCredential, bootEpoch, fetchImpl }); if (stopped || suspensionDepth || revision !== transitionRevision) return; for (const runId of state.revokedRunIds) { await runtime.revokeRun(runId); await onRevoked(runId); } + await onModelAccountsChanged(state.activeModelAccountIds); if (!suspensionDepth && revision === transitionRevision && state.lockProxy && runtime.state !== "locked") await runtime.lock(); } catch { // Keep existing connections alive during an outage and retry on schedule. diff --git a/packages/credential-proxy/src/main.mjs b/packages/credential-proxy/src/main.mjs index 72551cba..a086f908 100644 --- a/packages/credential-proxy/src/main.mjs +++ b/packages/credential-proxy/src/main.mjs @@ -2,8 +2,7 @@ import { readFile } from "node:fs/promises"; import { createAuthenticatedProxyListener } from "./proxy-listener.mjs"; import { createBearerForwarder } from "./bearer-forwarder.mjs"; import { createTestOriginConnector } from "./destination-policy.mjs"; -import { readProxyUnlockVerification, reportProxyRuntimeStatus } from "./control-client.mjs"; -import { verifyProxyUnlockKey } from "./decrypted-grants.mjs"; +import { reportProxyRuntimeStatus } from "./control-client.mjs"; import { createInterface } from "node:readline"; import { randomUUID } from "node:crypto"; import { createProxyRuntime } from "./runtime.mjs"; @@ -15,7 +14,6 @@ import { createProxyTlsAuthority } from "./tls-identity.mjs"; import { createCodexAuthHelper } from "./codex-auth-helper.mjs"; import { createModelAccountLifecycle } from "./model-account-lifecycle.mjs"; import { createModelAccountPersistenceAdapter } from "./control-client.mjs"; -import { decryptModelAccountCache, encryptModelAccountCache } from "./model-account-crypto.mjs"; import { startBrowserControl } from "./browser-control.mjs"; import { createProxyRunCredentialStore } from "./run-credential-store.mjs"; @@ -56,13 +54,11 @@ async function activateRegistration(registration, origin, browserOrigin) { modelAccounts = persistence; modelAccountLifecycle = createModelAccountLifecycle({ authHelper: createCodexAuthHelper(), - getUnlockKey: () => runtime.getUnlockKey(), getAccount: persistence.getAccount, getEncryptedCache: persistence.getEncryptedCache, persistEncrypted: persistence.persistEncrypted, - encryptCache: encryptModelAccountCache, - decryptCache: decryptModelAccountCache, }); + await modelAccountLifecycle.reconcileAll(await persistence.listAccounts()); if (!process.env.FACTORIZE_PROXY_BROWSER_CAPABILITY_PUBLIC_KEY) throw new Error("proxy browser capability verification key is unavailable"); browserControl = await startBrowserControl({ runtime, @@ -76,11 +72,7 @@ async function activateRegistration(registration, origin, browserOrigin) { const resume = revocationMonitor?.suspend(); try { return await work(); } finally { resume?.(); } }, - prepareUnlock: async key => { - const verification = await readProxyUnlockVerification({ controlOrigin: origin, token: registration.controlCredential }); - await verifyProxyUnlockKey(key, verification); - await modelAccountLifecycle.reconcileAll(await persistence.listAccounts()); - }, + prepareUnlock: async () => modelAccountLifecycle.reconcileAll(await persistence.listAccounts()), reportStatus: () => reportProxyRuntimeStatus({ controlOrigin: origin, token: registration.controlCredential, bootEpoch: runtime.bootEpoch, unlocked: runtime.state === "unlocked" }), applyChanges: async () => { await modelAccountLifecycle.reconcileAll(await persistence.listAccounts()); }, appOrigin: process.env.FACTORIZE_APP_ORIGIN ?? "https://app.factorize.sh", @@ -105,6 +97,7 @@ async function activateRegistration(registration, origin, browserOrigin) { bootEpoch: runtime.bootEpoch, runtime, onRevoked: runId => runCredentials.revoke(runId), + onModelAccountsChanged: accountIds => modelAccountLifecycle.revokeUnavailable(accountIds), }); statusReporter = startProxyRuntimeStatusReporter({ controlOrigin: origin, diff --git a/packages/credential-proxy/src/model-account-lifecycle.mjs b/packages/credential-proxy/src/model-account-lifecycle.mjs index 565abde8..0692ed3e 100644 --- a/packages/credential-proxy/src/model-account-lifecycle.mjs +++ b/packages/credential-proxy/src/model-account-lifecycle.mjs @@ -12,16 +12,14 @@ function cachePath(root, accountId) { } /** - * Keep Codex token refresh and encrypted persistence inside the proxy. The - * persistence callback receives only user-encrypted auth-cache bytes; token - * JSON and the unlock key never leave this process in plaintext. + * Keep Codex token refresh inside the proxy. Persistence sends the cache over + * the authenticated proxy control channel; the API encrypts it with the + * Factorize server key before writing it to storage. */ export function createModelAccountLifecycle({ authHelper, accountHomeRoot = "/var/lib/factorize/codex-accounts", - getUnlockKey, getAccount, - encryptCache, persistEncrypted, onUnsaved = () => {}, retryDelaysMs = [100, 500, 2_000], @@ -34,18 +32,15 @@ export function createModelAccountLifecycle({ readDirectory = readdir, replaceFile = rename, getEncryptedCache, - decryptCache, } = {}) { - if (!authHelper || typeof authHelper.invoke !== "function" || typeof getUnlockKey !== "function" - || typeof getAccount !== "function" || typeof encryptCache !== "function" || typeof persistEncrypted !== "function" + if (!authHelper || typeof authHelper.invoke !== "function" + || typeof getAccount !== "function" || typeof persistEncrypted !== "function" || !Array.isArray(retryDelaysMs) || retryDelaysMs.length > 5 || retryDelaysMs.some(ms => !Number.isSafeInteger(ms) || ms < 0 || ms > 30_000) || !Number.isSafeInteger(staleRevisionRetries) || staleRevisionRetries < 0 || staleRevisionRetries > 5) { throw new TypeError("model account lifecycle configuration is invalid"); } - if ((getEncryptedCache === undefined) !== (decryptCache === undefined) - || (getEncryptedCache !== undefined && typeof getEncryptedCache !== "function") - || (decryptCache !== undefined && typeof decryptCache !== "function")) { + if (getEncryptedCache !== undefined && typeof getEncryptedCache !== "function") { throw new TypeError("model account cache restoration configuration is invalid"); } @@ -64,32 +59,20 @@ export function createModelAccountLifecycle({ async function persist(id, generation) { let account = await getAccount(id); if (!account || account.id !== id || account.kind !== "model" || !Number.isSafeInteger(account.revision) - || typeof account.ownerId !== "string" || !account.ownerId || typeof account.keyGeneration !== "string" || !account.keyGeneration) { + || typeof account.ownerId !== "string" || !account.ownerId) { throw new Error("model account persistence binding is unavailable"); } - const unlockKey = await getUnlockKey(); - if (typeof unlockKey !== "string" || !unlockKey) throw new Error("proxy is locked"); const plain = await readCache(cachePath(accountHomeRoot, id)); if (!Buffer.isBuffer(plain) || plain.byteLength === 0 || plain.byteLength > 65_536) throw new Error("Codex token cache is missing or exceeds its limit"); + const payload = plain.toString("utf8"); + try { if (!JSON.parse(payload) || typeof JSON.parse(payload) !== "object") throw new Error(); } + catch { plain.fill(0); throw new Error("Codex token cache is invalid"); } let staleRetries = 0; let attempts = 0; try { for (;;) { - let encrypted; - try { - encrypted = await encryptCache(new Uint8Array(plain), unlockKey, { - ownerId: account.ownerId, - recordId: id, - recordType: "model", - destination: "factorize", - revision: account.revision + 1, - keyGeneration: account.keyGeneration, - }); - } catch (error) { - throw error; - } if (currentGeneration(id) !== generation) throw new Error("model account changed before token persistence"); - const request = { id, expectedRevision: account.revision, keyGeneration: account.keyGeneration, encryptedPayload: encrypted, idempotencyKey: randomUUID() }; + const request = { id, expectedRevision: account.revision, encryptedPayload: payload, idempotencyKey: randomUUID() }; let retryWithLatestRevision = false; for (let attempt = 0; ; attempt++) { if (currentGeneration(id) !== generation) throw new Error("model account changed before token persistence"); @@ -107,7 +90,7 @@ export function createModelAccountLifecycle({ catch { throw new Error("model account changed before token persistence"); } if (!latest || latest.id !== id || latest.kind !== "model" || !Number.isSafeInteger(latest.revision) || latest.revision <= account.revision || latest.ownerId !== account.ownerId - || latest.keyGeneration !== account.keyGeneration) { + ) { throw new Error("model account changed before token persistence"); } account = latest; @@ -126,7 +109,7 @@ export function createModelAccountLifecycle({ try { latest = await getAccount(id); } catch { throw new Error("model account changed before token persistence"); } if (!latest || latest.id !== id || latest.kind !== "model" || latest.ownerId !== account.ownerId - || latest.keyGeneration !== account.keyGeneration) { + ) { throw new Error("model account changed before token persistence"); } } @@ -185,33 +168,23 @@ export function createModelAccountLifecycle({ } async function restore(id) { - if (!getEncryptedCache || !decryptCache) throw new Error("model account cache restoration is unavailable"); + if (!getEncryptedCache) throw new Error("model account cache restoration is unavailable"); const account = await getAccount(id); if (!account || account.id !== id || account.kind !== "model" || !Number.isSafeInteger(account.revision) - || typeof account.ownerId !== "string" || !account.ownerId || typeof account.keyGeneration !== "string" || !account.keyGeneration) { + || typeof account.ownerId !== "string" || !account.ownerId) { await removeCache(resolve(accountHomeRoot, id), { recursive: true, force: true }); return { state: "reauthentication-required" }; } - const encrypted = await getEncryptedCache(id); - if (!encrypted || encrypted.accountId !== id || encrypted.ownerId !== account.ownerId - || encrypted.keyGeneration !== account.keyGeneration || !Number.isSafeInteger(encrypted.revision) - || typeof encrypted.encryptedPayload !== "string") { + const saved = await getEncryptedCache(id); + if (!saved || saved.accountId !== id || saved.ownerId !== account.ownerId + || !Number.isSafeInteger(saved.revision) || typeof saved.payload !== "string") { await removeCache(resolve(accountHomeRoot, id), { recursive: true, force: true }); return { state: "reauthentication-required" }; } - const unlockKey = await getUnlockKey(); - if (typeof unlockKey !== "string" || !unlockKey) throw new Error("proxy is locked"); let plain; try { - plain = await decryptCache(encrypted.encryptedPayload, unlockKey, { - ownerId: account.ownerId, - recordId: id, - recordType: "model", - destination: "factorize", - revision: encrypted.revision, - keyGeneration: account.keyGeneration, - }); - if (!(plain instanceof Uint8Array) || plain.byteLength === 0 || plain.byteLength > 65_536) { + plain = new TextEncoder().encode(saved.payload); + if (plain.byteLength === 0 || plain.byteLength > 65_536 || !JSON.parse(saved.payload) || typeof JSON.parse(saved.payload) !== "object") { throw new Error("restored Codex token cache is invalid"); } const destination = cachePath(accountHomeRoot, id); @@ -226,7 +199,7 @@ export function createModelAccountLifecycle({ } finally { plain?.fill(0); } - return { state: "restored", revision: encrypted.revision }; + return { state: "restored", revision: saved.revision }; } async function reconcile(id) { @@ -253,6 +226,24 @@ export function createModelAccountLifecycle({ restore, reconcile, isUnsaved: id => unsaved.has(id), + /** Remove local auth homes as soon as a server-side disconnect is observed. */ + revokeUnavailable: async accounts => { + if (!Array.isArray(accounts) || accounts.some(accountId => !UUID.test(accountId ?? "")) || new Set(accounts).size !== accounts.length) { + throw new TypeError("active model account snapshot is invalid"); + } + const activeIds = new Set(accounts); + const entries = await readDirectory(accountHomeRoot, { withFileTypes: true }).catch(error => { + if (error?.code === "ENOENT") return []; + throw error; + }); + const removed = []; + for (const entry of entries) { + if (!UUID.test(entry.name) || activeIds.has(entry.name)) continue; + await deleteAccount(entry.name); + removed.push(entry.name); + } + return removed; + }, /** Reconcile a complete server snapshot after unlock. A reset removes every * prior model account from that snapshot, so stale local Codex homes must * be logged out and removed before any current account is admitted. */ diff --git a/packages/credential-proxy/test/control-client.test.mjs b/packages/credential-proxy/test/control-client.test.mjs index 81f86d7f..4c95cb85 100644 --- a/packages/credential-proxy/test/control-client.test.mjs +++ b/packages/credential-proxy/test/control-client.test.mjs @@ -62,50 +62,53 @@ test("proxy snapshot reader requests only the bound run revision and validates e await assert.rejects(readProxyIntegrationSnapshot({ controlOrigin: "https://factorize.example", token, binding: { runId, grantRevision: 7 }, fetchImpl: async () => Response.json({ ...snapshot, modelAccount: { ...snapshot.modelAccount, kind: "bearer" } }) }), /invalid proxy integration snapshot response/); }); -test("model account persistence adapter lists owner-bound account revisions over proxy authentication", async () => { +test("model account persistence adapter uses server-managed cache without an unlock generation", async () => { const ownerId = "11111111-1111-4111-8111-111111111111"; let request; - const keyGeneration = "22222222-2222-4222-8222-222222222222"; const accountId = "33333333-3333-4333-8333-333333333333"; const adapter = createModelAccountPersistenceAdapter({ controlOrigin: "https://factorize.example", controlCredential: token, ownerId, fetchImpl: async (url, init) => { request = { url: String(url), init, body: JSON.parse(init.body) }; if (request.body.operation === "save") return Response.json({ accountId, revision: 5, collectionRevision: 9, duplicate: false }); - if (request.body.operation === "read") return Response.json({ ownerId, account: { id: accountId, kind: "model", origin: null, revision: 4, encryptedPayload: "ciphertext", keyGeneration } }); - return Response.json({ ownerId, keyGeneration, accounts: [{ id: accountId, kind: "model", origin: null, revision: 4 }] }); + if (request.body.operation === "read") return Response.json({ ownerId, account: { id: accountId, kind: "model", origin: null, revision: 4, encryptedPayload: 'factorize-managed-model-cache-v1:{"tokens":{}}' } }); + return Response.json({ ownerId, accounts: [{ id: accountId, kind: "model", origin: null, revision: 4 }] }); }, }); - assert.deepEqual(await adapter.listAccounts(), [{ id: accountId, kind: "model", origin: null, revision: 4, ownerId, keyGeneration }]); + assert.deepEqual(await adapter.listAccounts(), [{ id: accountId, kind: "model", origin: null, revision: 4, ownerId }]); assert.equal(request.url, "https://factorize.example/internal/credential-proxy/model-account-cache"); assert.deepEqual(request.body, { operation: "list" }); assert.equal(request.init.headers.Authorization, `Bearer ${token}`); - await adapter.persistEncrypted({ id: accountId, expectedRevision: 4, keyGeneration, encryptedPayload: "ciphertext", idempotencyKey: "44444444-4444-4444-8444-444444444444" }); - assert.deepEqual(request.body, { operation: "save", accountId, expectedRevision: 4, keyGeneration, encryptedPayload: "ciphertext", idempotencyKey: "44444444-4444-4444-8444-444444444444" }); - await assert.rejects(adapter.persistEncrypted({ id: accountId, expectedRevision: 4, encryptedPayload: "ciphertext", idempotencyKey: "44444444-4444-4444-8444-444444444444" }), /invalid encrypted model account update/); + assert.deepEqual(await adapter.getEncryptedCache(accountId), { accountId, ownerId, revision: 4, payload: '{"tokens":{}}' }); + await adapter.persistEncrypted({ id: accountId, expectedRevision: 4, encryptedPayload: '{"tokens":{}}', idempotencyKey: "44444444-4444-4444-8444-444444444444" }); + assert.deepEqual(request.body, { operation: "save", accountId, expectedRevision: 4, encryptedPayload: '{"tokens":{}}', idempotencyKey: "44444444-4444-4444-8444-444444444444" }); + await assert.rejects(adapter.persistEncrypted({ id: accountId, expectedRevision: 4, encryptedPayload: "x".repeat(65_537), idempotencyKey: "44444444-4444-4444-8444-444444444444" }), /invalid model account update/); await assert.rejects(adapter.listAccounts && createModelAccountPersistenceAdapter({ controlOrigin: "https://factorize.example", controlCredential: token, ownerId, - fetchImpl: async () => Response.json({ ownerId: "22222222-2222-4222-8222-222222222222", keyGeneration: "22222222-2222-4222-8222-222222222222", accounts: [] }), + fetchImpl: async () => Response.json({ ownerId: "22222222-2222-4222-8222-222222222222", accounts: [] }), }).listAccounts(), /invalid model account list response/); }); test("proxy revocation monitor applies durable run revocations and tolerates an outage", async () => { const requests = []; const revoked = []; + const accountSnapshots = []; let failFirst = true; const fetchImpl = async (url, init) => { requests.push({ url: String(url), init, body: JSON.parse(init.body) }); if (failFirst) { failFirst = false; throw new Error("offline fixture"); } - return Response.json({ revokedRunIds: [runId] }); + return Response.json({ revokedRunIds: [runId], activeModelAccountIds: ["33333333-3333-4333-8333-333333333333"] }); }; const runtime = { revokeRun: async id => { revoked.push(id); } }; const monitor = startProxyRunRevocationMonitor({ - controlOrigin: "https://factorize.example", controlCredential: token, bootEpoch, runtime, intervalMs: 100, fetchImpl, + controlOrigin: "https://factorize.example", controlCredential: token, bootEpoch, runtime, + onModelAccountsChanged: ids => accountSnapshots.push(ids), intervalMs: 100, fetchImpl, }); try { const deadline = Date.now() + 1_000; while (!revoked.length && Date.now() < deadline) await new Promise(resolve => setTimeout(resolve, 10)); assert.deepEqual(revoked, [runId]); + assert.deepEqual(accountSnapshots, [["33333333-3333-4333-8333-333333333333"]]); assert.equal(requests.length, 2, "a failed poll leaves the proxy live and retries through the control plane"); assert.ok(requests.every(request => request.url === "https://factorize.example/internal/credential-proxy/revocations")); assert.ok(requests.every(request => request.init.headers.Authorization === `Bearer ${token}`)); @@ -113,7 +116,7 @@ test("proxy revocation monitor applies durable run revocations and tolerates an } finally { await monitor.close(); } - await assert.rejects(readProxyRunRevocations({ controlOrigin: "https://factorize.example", token, bootEpoch, fetchImpl: async () => Response.json({ revokedRunIds: ["invalid"] }) }), /invalid proxy revocation response/); + await assert.rejects(readProxyRunRevocations({ controlOrigin: "https://factorize.example", token, bootEpoch, fetchImpl: async () => Response.json({ revokedRunIds: ["invalid"], activeModelAccountIds: [] }) }), /invalid proxy revocation response/); }); test("boot registration rejects unsafe origins, invalid credentials and mismatched response bindings", async () => { @@ -208,7 +211,7 @@ test("local lifecycle transition discards a stale lock snapshot and resumes dura let polls = 0, locks = 0; const monitor = startProxyRunRevocationMonitor({ controlOrigin: 'https://factorize.example', controlCredential: token, bootEpoch, intervalMs: 100, runtime: { state: 'unlocked', revokeRun: async () => {}, lock: async () => { locks++; } }, - fetchImpl: async () => { polls++; if (polls === 1) await first; return Response.json({ revokedRunIds: [], lockProxy: true }); } }); + fetchImpl: async () => { polls++; if (polls === 1) await first; return Response.json({ revokedRunIds: [], activeModelAccountIds: [], lockProxy: true }); } }); try { const resume = monitor.suspend(); completeFirst(); diff --git a/packages/credential-proxy/test/model-account-lifecycle.test.mjs b/packages/credential-proxy/test/model-account-lifecycle.test.mjs index 310b4dfb..764b4b87 100644 --- a/packages/credential-proxy/test/model-account-lifecycle.test.mjs +++ b/packages/credential-proxy/test/model-account-lifecycle.test.mjs @@ -7,7 +7,7 @@ import { createModelAccountLifecycle } from "../src/model-account-lifecycle.mjs" const accountId = "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"; const resetAccountId = "cccccccc-cccc-4ccc-8ccc-cccccccccccc"; -const account = { id: accountId, kind: "model", ownerId: "owner", keyGeneration: "generation", revision: 4 }; +const account = { id: accountId, kind: "model", ownerId: "owner", revision: 4 }; async function fixture(t, overrides = {}) { const root = await mkdtemp(join(tmpdir(), "factorize-model-account-")); @@ -27,13 +27,7 @@ async function fixture(t, overrides = {}) { const lifecycle = createModelAccountLifecycle({ authHelper: helper, accountHomeRoot: root, - getUnlockKey: async () => "synthetic-unlock-key", getAccount: async () => overrides.getAccount ? overrides.getAccount() : account, - encryptCache: async (plain, key, binding) => { - assert.equal(key, "synthetic-unlock-key"); - events.push({ type: "encrypt", binding, plaintext: new TextDecoder().decode(plain) }); - return `encrypted.${Buffer.from(plain).toString("base64")}`; - }, persistEncrypted: async request => { saves++; events.push({ type: "persist", request }); @@ -47,17 +41,14 @@ async function fixture(t, overrides = {}) { return { root, home, lifecycle, events, methods, calls, get saves() { return saves; } }; } -test("device authorization persists only encrypted, account-bound cache after success", async t => { +test("device authorization persists the refreshed cache for server-side encryption", async t => { const f = await fixture(t); const login = await f.lifecycle.deviceLogin(accountId); assert.equal(login.state, "pending"); assert.deepEqual(await login.completion, { state: "saved" }); - const [encrypted, saved] = f.events.filter(event => event.type === "encrypt" || event.type === "persist"); - assert.equal(encrypted.binding.ownerId, "owner"); - assert.equal(encrypted.binding.recordType, "model"); - assert.equal(encrypted.binding.revision, 5); + const [saved] = f.events.filter(event => event.type === "persist"); assert.equal(saved.request.expectedRevision, 4); - assert.match(saved.request.encryptedPayload, /^encrypted\./); + assert.equal(JSON.parse(saved.request.encryptedPayload).tokens.access_token, "synthetic-access"); assert.equal("unlockKey" in saved.request, false); }); @@ -100,7 +91,7 @@ test("refresh requests for one account serialize and use the latest revision", a assert.equal(f.saves, 2); }); -test("refresh re-encrypts against a newer account revision after a concurrent edit", async t => { +test("refresh retries against a newer server cache revision after a concurrent edit", async t => { let revision = 4; const f = await fixture(t, { getAccount: () => ({ ...account, revision }), @@ -118,39 +109,38 @@ test("refresh re-encrypts against a newer account revision after a concurrent ed const writes = f.events.filter(event => event.type === "persist").map(event => event.request); assert.deepEqual(writes.map(request => request.expectedRevision), [4, 5]); assert.notEqual(writes[0].idempotencyKey, writes[1].idempotencyKey); - const encryptions = f.events.filter(event => event.type === "encrypt"); - assert.deepEqual(encryptions.map(event => event.binding.revision), [5, 6]); + assert.equal(JSON.parse(writes[0].encryptedPayload).tokens.refresh_token, "synthetic-refresh"); + assert.equal(JSON.parse(writes[1].encryptedPayload).tokens.refresh_token, "synthetic-refresh"); }); -test("refresh does not retry a stale cache write after the unlock-key generation rotates", async t => { - let generation = "generation"; +test("refresh retries a stale cache revision without an inner key generation", async t => { + let revision = 4; const f = await fixture(t, { - getAccount: () => ({ ...account, keyGeneration: generation }), + getAccount: () => ({ ...account, revision }), persistEncrypted: async () => { - generation = "rotated-generation"; + if (f.saves > 1) return; + revision++; const error = new Error("stale model account revision"); error.code = "stale_revision"; throw error; }, }); - await assert.rejects(f.lifecycle.refresh(accountId), /changed before token persistence/); - assert.equal(f.saves, 1); - assert.deepEqual(f.events.filter(event => event.type === "encrypt").map(event => event.binding.keyGeneration), ["generation"]); + assert.deepEqual(await f.lifecycle.refresh(accountId), { state: "saved" }); + assert.equal(f.saves, 2); }); -test("refresh does not retry a transient cache write after the key generation rotates during backoff", async t => { - let generation = "generation"; +test("refresh does not retry after model account disconnect during backoff", async t => { + let disconnected = false; const f = await fixture(t, { retryDelaysMs: [1], - getAccount: () => ({ ...account, keyGeneration: generation }), - options: { sleep: async () => { generation = "rotated-generation"; } }, + getAccount: () => disconnected ? null : ({ ...account }), + options: { sleep: async () => { disconnected = true; } }, persistEncrypted: async () => { throw new Error("temporary persistence failure"); }, }); await assert.rejects(f.lifecycle.refresh(accountId), /changed before token persistence/); assert.equal(f.saves, 1); - assert.deepEqual(f.events.filter(event => event.type === "encrypt").map(event => event.binding.keyGeneration), ["generation"]); }); test("deletion invalidates a retry and removes the account cache", async t => { @@ -268,22 +258,12 @@ test("deletion racing pending device login prevents a late authorization from re assert.equal(f.saves, 0); }); -test("unlock reconciliation restores the encrypted Codex cache before checking account status", async t => { +test("reconciliation restores the server-managed Codex cache before checking account status", async t => { const persisted = new TextEncoder().encode(JSON.stringify({ tokens: { access_token: "restored-access", refresh_token: "restored-refresh" } })); - const encryptedPayload = `cache.${Buffer.from(persisted).toString("base64")}`; const f = await fixture(t, { options: { getEncryptedCache: async id => ({ - accountId: id, ownerId: "owner", keyGeneration: "generation", revision: 8, encryptedPayload, + accountId: id, ownerId: "owner", revision: 8, payload: new TextDecoder().decode(persisted), }), - decryptCache: async (payload, key, binding) => { - assert.equal(payload, encryptedPayload); - assert.equal(key, "synthetic-unlock-key"); - assert.deepEqual(binding, { - ownerId: "owner", recordId: accountId, recordType: "model", destination: "factorize", - revision: 8, keyGeneration: "generation", - }); - return new Uint8Array(persisted); - }, } }); assert.deepEqual(await f.lifecycle.reconcile(accountId), { state: "saved" }); @@ -294,12 +274,11 @@ test("unlock reconciliation restores the encrypted Codex cache before checking a assert.equal(f.events.find(event => event.type === "persist").request.expectedRevision, 4); }); -test("unlock reconciliation removes stale cache when the account key generation changed", async t => { +test("reconciliation removes legacy user-encrypted cache and requires reconnect", async t => { const f = await fixture(t, { options: { getEncryptedCache: async id => ({ - accountId: id, ownerId: "owner", keyGeneration: "old-generation", revision: 8, encryptedPayload: "cache.payload", + accountId: id, ownerId: "owner", revision: 8, }), - decryptCache: async () => { throw new Error("must not decrypt stale cache"); }, } }); assert.deepEqual(await f.lifecycle.reconcile(accountId), { state: "reauthentication-required" }); @@ -307,7 +286,7 @@ test("unlock reconciliation removes stale cache when the account key generation assert.equal(f.methods.includes("account-status"), false); }); -test("unlock snapshot reconciliation logs out and removes cached accounts deleted by reset", async t => { +test("snapshot reconciliation logs out and removes cached accounts deleted by reset", async t => { const f = await fixture(t); const staleHome = join(f.root, resetAccountId); await mkdir(staleHome, { recursive: true }); @@ -322,7 +301,14 @@ test("unlock snapshot reconciliation logs out and removes cached accounts delete assert.equal(f.saves, 1); }); -test("unlock snapshot rejects duplicate account identities before touching local state", async t => { +test("server disconnect revocation removes the local model-account cache and logs out", async t => { + const f = await fixture(t); + assert.deepEqual(await f.lifecycle.revokeUnavailable([]), [accountId]); + await assert.rejects(readFile(join(f.home, "auth.json")), { code: "ENOENT" }); + assert.ok(f.methods.includes("logout")); +}); + +test("snapshot reconciliation rejects duplicate account identities before touching local state", async t => { const f = await fixture(t); await assert.rejects(f.lifecycle.reconcileAll([account, account]), /snapshot is invalid/); assert.deepEqual(JSON.parse(await readFile(join(f.home, "auth.json"), "utf8")), { diff --git a/packages/credential-proxy/test/runtime-revocation.test.mjs b/packages/credential-proxy/test/runtime-revocation.test.mjs index b6fb3765..4d5b15bd 100644 --- a/packages/credential-proxy/test/runtime-revocation.test.mjs +++ b/packages/credential-proxy/test/runtime-revocation.test.mjs @@ -86,7 +86,7 @@ test("key-generation replacement locks proxy memory and closes every connection" await runtime.acceptAuthenticatedConnection(connection("run-old-key", "connection-old-key")); const monitor = startProxyRunRevocationMonitor({ controlOrigin: "https://factorize.example", controlCredential: `fzc_${"A".repeat(43)}`, bootEpoch, runtime, intervalMs: 100, - fetchImpl: async () => Response.json({ revokedRunIds: [], lockProxy: true }), + fetchImpl: async () => Response.json({ revokedRunIds: [], activeModelAccountIds: [], lockProxy: true }), }); try { const deadline = Date.now() + 1_000; @@ -155,11 +155,11 @@ test("an established run stays available during a control outage and closes when try { await secondPoll; assert.equal(closed, false, "a failed control-plane poll does not impose a connection lease"); - releaseRevocation(Response.json({ revokedRunIds: [revokedRunId] })); + releaseRevocation(Response.json({ revokedRunIds: [revokedRunId], activeModelAccountIds: [] })); await didClose; assert.equal(closed, true, "durable revocation closes the established connection when delivered"); } finally { - releaseRevocation(Response.json({ revokedRunIds: [] })); + releaseRevocation(Response.json({ revokedRunIds: [], activeModelAccountIds: [] })); await monitor.close(); await runtime.shutdown(); } diff --git a/packages/docs/openapi.yaml b/packages/docs/openapi.yaml index 72868636..f0eeaa49 100644 --- a/packages/docs/openapi.yaml +++ b/packages/docs/openapi.yaml @@ -1883,7 +1883,7 @@ paths: post: summary: Create a model account description: |- - Requires an interactive owner browser session and the current collection revision. Accepts only user-encrypted initial account state; credentials are established directly with the credential proxy. + Requires an interactive owner browser session and the current collection revision. Creates metadata with an empty initial state; the credential proxy establishes credentials and Factorize encrypts cache updates with its server key. Requires the integrations:write scope. @@ -1960,23 +1960,22 @@ paths: - type: string maxLength: 500 - type: "null" - encryptedPayload: + initialState: type: string - minLength: 1 - maxLength: 65536 + const: "{}" required: - id - expectedRevision - idempotencyKey - name - description - - encryptedPayload + - initialState additionalProperties: false /api/v1/model-accounts/{accountId}: delete: summary: Delete a model account description: |- - Requires an interactive owner browser session and the current collection revision. Deletion is recorded as a tombstone so future snapshots and unlock reconciliation cannot restore the account. + Requires an interactive owner browser session and the current collection revision. Deletion is recorded as a tombstone so future run snapshots reject the disconnected account. Requires the integrations:write scope. From 00328322e26441aa1daac49c39bb2a002d4c6dff Mon Sep 17 00:00:00 2001 From: "exe.dev user" Date: Mon, 16 Nov 2026 20:51:17 +0000 Subject: [PATCH 09/28] Update model account API fixture --- packages/api/test/encrypted-integration-api.postgres.test.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/api/test/encrypted-integration-api.postgres.test.ts b/packages/api/test/encrypted-integration-api.postgres.test.ts index c420a787..19aa43b9 100644 --- a/packages/api/test/encrypted-integration-api.postgres.test.ts +++ b/packages/api/test/encrypted-integration-api.postgres.test.ts @@ -173,9 +173,9 @@ describe.skipIf(!databaseUrl)("owner-only managed credential API (PostgreSQL)", method, headers: { Cookie: cookie, Origin: f.env.APP_ORIGIN, "Content-Type": "application/json" }, ...(body === undefined ? {} : { body: JSON.stringify(body) }), }), f.env, { waitUntil() {} } as any); - const ciphertext = await userEncrypt("{}"), createBody = { + const createBody = { id, expectedRevision: 0, idempotencyKey: crypto.randomUUID(), name: "Work account", - description: "Personal subscription", encryptedPayload: ciphertext, + description: "Personal subscription", initialState: "{}", }; const created = await request(path, "POST", createBody); expect(created.status).toBe(201); From 83269951839e5e1095494d2848eabe555c90a36a Mon Sep 17 00:00:00 2001 From: "exe.dev user" Date: Mon, 16 Nov 2026 21:13:21 +0000 Subject: [PATCH 10/28] Select tenant provider connections for jobs --- packages/api-client/src/schema.d.ts | 15 ++++ packages/api/src/api-contract.ts | 2 +- packages/api/src/flow-schemas.ts | 2 + packages/api/src/flow-service.ts | 32 ++++++-- packages/api/src/job-contracts.ts | 1 + packages/api/src/job-domain.ts | 4 + packages/api/src/postgres/job-repository.ts | 2 +- packages/api/src/proxy-control.ts | 14 +++- ...encrypted-integration-api.postgres.test.ts | 14 +++- packages/api/test/loading.postgres.test.ts | 32 ++++++++ packages/api/test/proxy-control.test.ts | 4 +- .../app/src/features/jobs/editor-queries.ts | 6 ++ .../app/src/features/jobs/editor-state.ts | 2 +- packages/app/src/features/jobs/editor.tsx | 9 ++- packages/app/src/lib/unlock-key.ts | 2 +- packages/docs/openapi.yaml | 81 +++++++++++++++++++ 16 files changed, 202 insertions(+), 20 deletions(-) diff --git a/packages/api-client/src/schema.d.ts b/packages/api-client/src/schema.d.ts index 196ef62b..38b96713 100644 --- a/packages/api-client/src/schema.d.ts +++ b/packages/api-client/src/schema.d.ts @@ -2761,6 +2761,8 @@ export interface components { modelAccess?: "native" | "portable"; /** Format: uuid */ modelAccountId?: string; + githubInstallationIds?: number[]; + linearConnectionId?: "linear" | null; }; ManualInvocation: { /** @default */ @@ -3286,6 +3288,7 @@ export interface operations { generationId: string; expectedRevision: number; encryptedVerification: string; + preserveManagedModelCaches?: boolean; records: { /** Format: uuid */ id: string; @@ -6451,6 +6454,8 @@ export interface operations { modelAccess?: "native" | "portable"; /** Format: uuid */ modelAccountId?: string; + githubInstallationIds?: number[]; + linearConnectionId?: "linear" | null; executionConfigId: string; agentKind: string; concurrencyLimit: number; @@ -6748,6 +6753,8 @@ export interface operations { modelAccess?: "native" | "portable"; /** Format: uuid */ modelAccountId?: string; + githubInstallationIds?: number[]; + linearConnectionId?: "linear" | null; executionConfigId: string; agentKind: string; concurrencyLimit: number; @@ -6957,6 +6964,8 @@ export interface operations { modelAccess?: "native" | "portable"; /** Format: uuid */ modelAccountId?: string; + githubInstallationIds?: number[]; + linearConnectionId?: "linear" | null; executionConfigId: string; agentKind: string; concurrencyLimit: number; @@ -7448,6 +7457,8 @@ export interface operations { modelAccess?: "native" | "portable"; /** Format: uuid */ modelAccountId?: string; + githubInstallationIds?: number[]; + linearConnectionId?: "linear" | null; executionConfigId: string; agentKind: string; concurrencyLimit: number; @@ -7738,6 +7749,8 @@ export interface operations { modelAccess?: "native" | "portable"; /** Format: uuid */ modelAccountId?: string; + githubInstallationIds?: number[]; + linearConnectionId?: "linear" | null; /** Format: date-time */ expectedUpdatedAt?: string; }; @@ -7785,6 +7798,8 @@ export interface operations { modelAccess?: "native" | "portable"; /** Format: uuid */ modelAccountId?: string; + githubInstallationIds?: number[]; + linearConnectionId?: "linear" | null; executionConfigId: string; agentKind: string; concurrencyLimit: number; diff --git a/packages/api/src/api-contract.ts b/packages/api/src/api-contract.ts index 029d685d..c244f539 100644 --- a/packages/api/src/api-contract.ts +++ b/packages/api/src/api-contract.ts @@ -146,7 +146,7 @@ const unlockKeyVerificationInput = z.object({ generationId: z.uuid(), encryptedV const rotationRecord = z.object({ id: z.uuid(), kind: z.enum(["bearer", "model"]), name: z.string().min(1).max(120), origin: z.string().nullable(), description: z.string().max(500).nullable(), revision: z.number().int().nonnegative(), encryptedPayload: z.string().max(65_536).nullable(), deletedAt: z.string().datetime({ offset: true }).nullable() }).strict(); const rotationChange = z.object({ id: z.uuid(), kind: z.enum(["bearer", "model"]), name: z.string().min(1).max(120), origin: z.string().nullable(), description: z.string().max(500).nullable(), revision: z.number().int().positive(), idempotencyKey: z.uuid(), operation: z.enum(["upsert", "delete"]), encryptedPayload: z.string().max(65_536).nullable(), recordRevision: z.number().int().positive().nullable().optional() }).strict(); const unlockKeyRotationSnapshot = z.object({ ownerId: z.string(), generationId: z.uuid(), revision: z.number().int().nonnegative(), records: z.array(rotationRecord).max(5000), changes: z.array(rotationChange).max(10000) }).strict(); -const unlockKeyGenerationReplacement = z.object({ expectedGenerationId: z.uuid(), generationId: z.uuid(), expectedRevision: z.number().int().nonnegative(), encryptedVerification: z.string().min(1).max(4096), records: z.array(rotationRecord).max(5000), changes: z.array(rotationChange).max(10000) }).strict(); +const unlockKeyGenerationReplacement = z.object({ expectedGenerationId: z.uuid(), generationId: z.uuid(), expectedRevision: z.number().int().nonnegative(), encryptedVerification: z.string().min(1).max(4096), preserveManagedModelCaches: z.boolean().optional(), records: z.array(rotationRecord).max(5000), changes: z.array(rotationChange).max(10000) }).strict(); const modelAccountBrowserCapabilityInput = z.object({ action: z.enum(["authorize", "status", "cancel"]) }).strict(); function route( diff --git a/packages/api/src/flow-schemas.ts b/packages/api/src/flow-schemas.ts index 7618fb1b..89000687 100644 --- a/packages/api/src/flow-schemas.ts +++ b/packages/api/src/flow-schemas.ts @@ -79,6 +79,8 @@ export const jobInputSchema = z.object({ portableIntegrationIds: z.array(z.guid()).max(100).refine(ids => new Set(ids).size === ids.length, "Portable integrations must be unique").optional(), modelAccess: z.enum(["native", "portable"]).optional(), modelAccountId: z.guid().optional(), + githubInstallationIds: z.array(z.number().int().positive()).max(100).refine(ids => new Set(ids).size === ids.length, "GitHub installations must be unique").optional(), + linearConnectionId: z.literal("linear").nullable().optional(), }).strict().superRefine((value, context) => { if (value.executionType !== "code" && !value.promptTemplate?.trim()) context.addIssue({ code: "custom", path: ["promptTemplate"], message: "Agent jobs require a prompt template." }); if (value.executionType === "code" && !value.script?.trim()) context.addIssue({ code: "custom", path: ["script"], message: "Code jobs require a script." }); diff --git a/packages/api/src/flow-service.ts b/packages/api/src/flow-service.ts index ae5e9446..73a769fe 100644 --- a/packages/api/src/flow-service.ts +++ b/packages/api/src/flow-service.ts @@ -99,6 +99,8 @@ export class ApiService { private async portableSelections(config: Awaited>, executionType: "agent" | "code", input: JobInput, current?: Job) { if (config.executionProvider === "docker" && executionType !== "code") throw new ServiceError(400, "invalid_request", "Docker test execution supports code jobs only."); const portableIntegrationIds = input.portableIntegrationIds ?? current?.portableIntegrationIds ?? current?.executionConfig.portableIntegrationIds ?? []; + const githubInstallationIds = input.githubInstallationIds ?? current?.githubInstallationIds ?? current?.executionConfig.githubInstallationIds ?? []; + const linearConnectionId = input.linearConnectionId !== undefined ? input.linearConnectionId : current?.linearConnectionId ?? current?.executionConfig.linearConnectionId; if (executionType === "code" && input.modelAccess === "portable") throw new ServiceError(400, "invalid_request", "Code jobs cannot select model access."); const modelAccess = executionType === "code" ? "native" : input.modelAccess ?? current?.modelAccess ?? current?.executionConfig.modelAccess ?? (config.executionProvider === "fly" ? "portable" : "native"); if (modelAccess === "native" && input.modelAccountId) throw new ServiceError(400, "invalid_request", "Native model access cannot select a portable model account."); @@ -108,9 +110,13 @@ export class ApiService { const records = await new EncryptedIntegrationRepository(databaseFor(this.env), this.auth.tenantId, this.env.CREDENTIAL_ENCRYPTION_KEY).records(); const byId = new Map(records.map(record => [record.id, record])); if (new Set(portableIntegrationIds).size !== portableIntegrationIds.length || portableIntegrationIds.some(id => byId.get(id)?.kind !== "bearer")) throw new ServiceError(400, "invalid_request", "One or more selected portable integrations are unavailable."); + const installations = await new GitHubRepository(databaseFor(this.env), this.auth.tenantId).installations(); + const activeInstallationIds = new Set(installations.filter(item => item.state === "active").map(item => Number(item.installationId))); + if (new Set(githubInstallationIds).size !== githubInstallationIds.length || githubInstallationIds.some(id => !activeInstallationIds.has(id))) throw new ServiceError(400, "invalid_request", "One or more selected GitHub installations are unavailable."); + if (linearConnectionId && (!await this.connections().get("linear"))) throw new ServiceError(400, "invalid_request", "The selected Linear connection is unavailable."); if (modelAccountId && byId.get(modelAccountId)?.kind !== "model") throw new ServiceError(400, "invalid_request", "The selected model account is unavailable."); if (modelAccess === "portable" && executionType !== "code" && !modelAccountId) throw new ServiceError(400, "invalid_request", "Portable model access requires a model account."); - return { portableIntegrationIds, modelAccess, ...(modelAccountId ? { modelAccountId } : {}) }; + return { portableIntegrationIds, githubInstallationIds, ...(linearConnectionId ? { linearConnectionId } : {}), modelAccess, ...(modelAccountId ? { modelAccountId } : {}) }; } private async validateExecutionOptions(id: string, model: string, effort: string, tags: string[]) { @@ -594,9 +600,6 @@ export class ApiService { async getUnlockKeyRotationSnapshot() { await this.authorizeOwnerSession("integrations:read"); const repository = this.encryptedIntegrations(); - if ((await repository.records("model")).some(record => record.encryptedPayload.startsWith("factorize-managed-model-cache-v1:"))) { - throw new ServiceError(409, "conflict", "Model account caches use Factorize-managed encryption and cannot be included in unlock-key rotation."); - } const [snapshot, verification] = await Promise.all([ repository.rotationSnapshot(), databaseFor(this.env).pool.query<{ generation_id: string }>("SELECT generation_id FROM app.unlock_key_verifications WHERE tenant_id=$1", [this.auth.tenantId]), @@ -613,18 +616,31 @@ export class ApiService { } return { ...change, recordRevision }; }); - return { ownerId: this.auth.userId, generationId, ...snapshot, changes }; + // Factorize-managed model caches are not encrypted with the unlock key. + // Omit them from the browser payload and preserve them server-side below. + const managed = (value: string | null) => value?.startsWith("factorize-managed-model-cache-v1:") ?? false; + const records = snapshot.records.filter(record => !(record.kind === "model" && managed(record.encryptedPayload))); + const retainedChanges = changes.filter(change => !(change.kind === "model" && managed(change.encryptedPayload))); + return { ownerId: this.auth.userId, generationId, revision: snapshot.revision, records, changes: retainedChanges }; } async replaceUnlockKeyGeneration(input: { - expectedGenerationId: string; generationId: string; expectedRevision: number; encryptedVerification: string; + expectedGenerationId: string; generationId: string; expectedRevision: number; encryptedVerification: string; preserveManagedModelCaches?: boolean; records: Array<{ id: string; kind: "bearer" | "model"; name: string; origin: string | null; description: string | null; revision: number; encryptedPayload: string | null; deletedAt: string | null }>; changes: Array<{ id: string; kind: "bearer" | "model"; name: string; origin: string | null; description: string | null; revision: number; idempotencyKey: string; operation: "upsert" | "delete"; encryptedPayload: string | null; recordRevision?: number | null }>; }) { await this.authorizeOwnerSession("integrations:write"); if (input.expectedGenerationId === input.generationId) throw new ServiceError(400, "invalid_request", "A replacement key generation must be new."); const repository = this.encryptedIntegrations(); - const records = input.records.map(record => ({ ...record, deletedAt: record.deletedAt === null ? null : new Date(record.deletedAt) })); - const changes = input.changes.map(({ recordRevision: _recordRevision, ...change }) => change); + let suppliedRecords = input.records; + let suppliedChanges = input.changes; + if (input.preserveManagedModelCaches) { + const current = await repository.rotationSnapshot(); + const managed = (value: string | null) => value?.startsWith("factorize-managed-model-cache-v1:") ?? false; + suppliedRecords = [...suppliedRecords, ...current.records.filter(record => record.kind === "model" && managed(record.encryptedPayload))]; + suppliedChanges = [...suppliedChanges, ...current.changes.filter(change => change.kind === "model" && managed(change.encryptedPayload))]; + } + const records = suppliedRecords.map(record => ({ ...record, deletedAt: record.deletedAt === null ? null : new Date(record.deletedAt) })); + const changes = suppliedChanges.map(({ recordRevision: _recordRevision, ...change }) => change); try { await repository.stageGeneration({ generationId: input.generationId, expectedRevision: input.expectedRevision, records, changes }); const committed = await repository.commitGeneration(input.generationId, input.expectedRevision, { diff --git a/packages/api/src/job-contracts.ts b/packages/api/src/job-contracts.ts index 6c3e139a..27d47ca6 100644 --- a/packages/api/src/job-contracts.ts +++ b/packages/api/src/job-contracts.ts @@ -46,6 +46,7 @@ export const jobResponse = z.object({ executionConfig: z.object({ connectionId: z.string(), workspace: z.string().optional(), cwd: z.string().optional(), agentKind: z.string(), image: z.string().optional(), region: z.string().optional(), size: z.string().optional(), executionType: z.enum(["agent", "code"]).optional(), script: z.string().optional() }), runScopes: z.array(scopeSchema), portableIntegrationIds: z.array(z.guid()).optional(), modelAccess: z.enum(["native", "portable"]).optional(), modelAccountId: z.guid().optional(), + githubInstallationIds: z.array(z.number().int().positive()).optional(), linearConnectionId: z.literal("linear").nullable().optional(), executionConfigId: z.string(), agentKind: z.string(), concurrencyLimit: z.number().int(), runningCount: z.number().int(), currentRuns: z.number().int(), maxConcurrency: z.number().int(), lastRunState: z.enum(["queued", "reserved", "starting", "running", "blocked", "stopping", "succeeded", "failed", "stopped", "done", "ignored"]).nullable(), triggers: z.array(triggerResponse), diff --git a/packages/api/src/job-domain.ts b/packages/api/src/job-domain.ts index 6f136001..0e5ec5fb 100644 --- a/packages/api/src/job-domain.ts +++ b/packages/api/src/job-domain.ts @@ -18,6 +18,8 @@ export interface ExecutionConfig { portableIntegrationIds?: string[]; modelAccess?: "native" | "portable"; modelAccountId?: string; + githubInstallationIds?: number[]; + linearConnectionId?: "linear" | null; executionProvider?: "exe" | "fly" | "docker"; region?: string; size?: string; @@ -58,6 +60,8 @@ export interface Job { portableIntegrationIds?: string[]; modelAccess?: "native" | "portable"; modelAccountId?: string; + githubInstallationIds?: number[]; + linearConnectionId?: "linear" | null; } export interface InvocationRequest { diff --git a/packages/api/src/postgres/job-repository.ts b/packages/api/src/postgres/job-repository.ts index d0b11cbb..b6625812 100644 --- a/packages/api/src/postgres/job-repository.ts +++ b/packages/api/src/postgres/job-repository.ts @@ -34,7 +34,7 @@ export class PostgresJobRepository implements JobRepository { triggerRows = loadedTriggers ?? await db.select().from(triggers).where(and(eq(triggers.tenantId, this.tenantId), eq(triggers.jobId, row.id), isNull(triggers.removedAt))).orderBy(triggers.position, triggers.createdAt, triggers.id); skillRows = loadedSkills?.filter(skill => skill.job_id === row.id) ?? (await db.execute(sql`SELECT s.id,s.key,s.revision,s.encrypted_body,js.position FROM app.job_skills js JOIN app.skills s ON s.tenant_id=js.tenant_id AND s.id=js.skill_id WHERE js.tenant_id=${this.tenantId}::uuid AND js.job_id=${row.id}::uuid ORDER BY js.position`)).rows; } - return { id: row.id, runScopes: row.runScopes ?? [...DEFAULT_RUN_SCOPES], projectId: row.projectId, name: row.name, description: row.description ?? "", slug: row.slug, promptTemplate: await this.decrypt(row.encryptedPromptTemplate), executionType: row.executionConfig.executionType ?? "agent", script: row.executionConfig.script, runNameTemplate: row.encryptedRunNameTemplate ? await this.decrypt(row.encryptedRunNameTemplate) : "", tags: row.tags ?? [], model: row.model, ...(row.effort ? { effort: row.effort } : {}), executionConfig: row.executionConfig, portableIntegrationIds: row.executionConfig.portableIntegrationIds ?? [], modelAccess: row.executionConfig.modelAccess ?? "native", modelAccountId: row.executionConfig.modelAccountId, concurrencyLimit: row.concurrencyLimit, enabled: row.enabled, triggers: triggerRows.map(value => this.trigger(value)), selectedSkills: await Promise.all(skillRows.map(async (skill: any) => ({ id: skill.id, key: skill.key, revision: skill.revision, body: await this.decrypt(skill.encrypted_body), position: skill.position }))), createdAt: row.createdAt.toISOString(), updatedAt: row.updatedAt.toISOString() }; + return { id: row.id, runScopes: row.runScopes ?? [...DEFAULT_RUN_SCOPES], projectId: row.projectId, name: row.name, description: row.description ?? "", slug: row.slug, promptTemplate: await this.decrypt(row.encryptedPromptTemplate), executionType: row.executionConfig.executionType ?? "agent", script: row.executionConfig.script, runNameTemplate: row.encryptedRunNameTemplate ? await this.decrypt(row.encryptedRunNameTemplate) : "", tags: row.tags ?? [], model: row.model, ...(row.effort ? { effort: row.effort } : {}), executionConfig: row.executionConfig, portableIntegrationIds: row.executionConfig.portableIntegrationIds ?? [], modelAccess: row.executionConfig.modelAccess ?? "native", modelAccountId: row.executionConfig.modelAccountId, githubInstallationIds: row.executionConfig.githubInstallationIds ?? [], linearConnectionId: row.executionConfig.linearConnectionId, concurrencyLimit: row.concurrencyLimit, enabled: row.enabled, triggers: triggerRows.map(value => this.trigger(value)), selectedSkills: await Promise.all(skillRows.map(async (skill: any) => ({ id: skill.id, key: skill.key, revision: skill.revision, body: await this.decrypt(skill.encrypted_body), position: skill.position }))), createdAt: row.createdAt.toISOString(), updatedAt: row.updatedAt.toISOString() }; } async getJob(id: string): Promise { diff --git a/packages/api/src/proxy-control.ts b/packages/api/src/proxy-control.ts index c2c8920c..81e0639c 100644 --- a/packages/api/src/proxy-control.ts +++ b/packages/api/src/proxy-control.ts @@ -3,6 +3,7 @@ import { ProxyControlRepository } from "./postgres/proxy-control-repository"; import { RunEnrollmentRepository } from "./postgres/run-enrollment-repository"; import { EncryptedIntegrationRepository } from "./postgres/encrypted-integration-repository"; import { authenticateRunCredential } from "./run-credentials"; +import { GitHubRepository } from "./postgres/github-repository"; async function recordOwner(env: Parameters[0], tenantId: string): Promise { const result = await databaseFor(env).pool.query<{ user_id: string }>("SELECT user_id FROM app.members WHERE tenant_id=$1 AND role='owner' ORDER BY created_at,user_id LIMIT 1", [tenantId]); @@ -143,9 +144,20 @@ export async function proxyControlFetch(request: Request, env: Parameters !Number.isSafeInteger(id) || id <= 0) || new Set(selectedGitHub).size !== selectedGitHub.length) return json({ error: "integration_snapshot_unavailable" }, 403); + const installations = await new GitHubRepository(database, proxy.tenantId).installations(); + const byInstallation = new Map(installations.map(item => [Number(item.installationId), item])); + const githubInstallations = selectedGitHub.map((installationId: number) => ({ installationId, available: byInstallation.get(installationId)?.state === "active" })); + const selectedLinear = run.execution_config?.linearConnectionId; + if (selectedLinear !== undefined && selectedLinear !== "linear") return json({ error: "integration_snapshot_unavailable" }, 403); + const linearPresent = selectedLinear === "linear" + ? Boolean((await database.pool.query("SELECT 1 FROM app.connections WHERE tenant_id=$1 AND kind='linear'", [proxy.tenantId])).rowCount) + : false; + const linearConnection = selectedLinear === "linear" ? { connectionId: "linear", available: linearPresent } : null; // Only the selected model account's user-encrypted payload crosses the // control plane. It remains encrypted until the proxy is unlocked. - return json({ ownerId: await recordOwner(env, proxy.tenantId), records, modelAccount }); + return json({ ownerId: await recordOwner(env, proxy.tenantId), records, modelAccount, providerCredentials: { githubInstallations, linearConnection } }); } const enrollments = new RunEnrollmentRepository(databaseFor(env)); if (url.pathname === "/internal/credential-proxy/enroll") { diff --git a/packages/api/test/encrypted-integration-api.postgres.test.ts b/packages/api/test/encrypted-integration-api.postgres.test.ts index 19aa43b9..2a8b1a89 100644 --- a/packages/api/test/encrypted-integration-api.postgres.test.ts +++ b/packages/api/test/encrypted-integration-api.postgres.test.ts @@ -107,17 +107,23 @@ describe.skipIf(!databaseUrl)("owner-only managed credential API (PostgreSQL)", expect((await f.db.pool.query("SELECT consumed_at FROM app.credential_run_enrollments WHERE tenant_id=$1 AND run_id=$2", [f.tenantId, runId])).rows[0].consumed_at).toBeInstanceOf(Date); expect(await enrollmentRepository.consume(issued!.token, binding)).toBeNull(); const rotatedCipher = await userEncrypt("rotated synthetic bearer payload"), rotatedId = crypto.randomUUID(); - await new EncryptedIntegrationRepository(f.db, f.tenantId, f.env.CREDENTIAL_ENCRYPTION_KEY).write({ id: rotatedId, kind: "bearer", expectedRevision: 2, idempotencyKey: crypto.randomUUID(), name: "Rotated", origin: "https://api.example.test", description: null, operation: "upsert", encryptedPayload: encrypted }); + const integrationRepository = new EncryptedIntegrationRepository(f.db, f.tenantId, f.env.CREDENTIAL_ENCRYPTION_KEY); + await integrationRepository.write({ id: rotatedId, kind: "bearer", expectedRevision: 2, idempotencyKey: crypto.randomUUID(), name: "Rotated", origin: "https://api.example.test", description: null, operation: "upsert", encryptedPayload: encrypted }); + const modelId = crypto.randomUUID(); + await integrationRepository.write({ id: modelId, kind: "model", expectedRevision: 0, idempotencyKey: crypto.randomUUID(), name: "Managed model", origin: null, description: null, operation: "upsert", managedModelPayload: JSON.stringify({ accessToken: "server-managed-fixture" }) }); const rotationSnapshot = await (await request("/unlock-key/rotation-snapshot")).json() as any; + expect(rotationSnapshot.records.some((record: any) => record.id === modelId)).toBe(false); + expect(JSON.stringify(rotationSnapshot)).not.toContain("server-managed-fixture"); const finalGeneration = crypto.randomUUID(); const rotated = await request("/unlock-key/rotation", "POST", { - expectedGenerationId: newGeneration, generationId: finalGeneration, expectedRevision: 3, - encryptedVerification: verification(finalGeneration), + expectedGenerationId: newGeneration, generationId: finalGeneration, expectedRevision: 4, + encryptedVerification: verification(finalGeneration), preserveManagedModelCaches: true, records: rotationSnapshot.records.map((record: any) => ({ ...record, encryptedPayload: record.id === rotatedId ? rotatedCipher : record.encryptedPayload })), changes: rotationSnapshot.changes.map((change: any) => ({ ...change, encryptedPayload: change.id === rotatedId && change.operation === "upsert" ? rotatedCipher : change.encryptedPayload })), }); expect(rotated.status).toBe(200); - expect(await rotated.json()).toEqual({ generationId: finalGeneration, revision: 4, duplicate: false }); + expect(await rotated.json()).toEqual({ generationId: finalGeneration, revision: 5, duplicate: false }); + expect(await integrationRepository.records("model")).toMatchObject([{ id: modelId, name: "Managed model", encryptedPayload: expect.stringContaining("factorize-managed-model-cache-v1:") }]); expect((await request("/integrations/bearer")).status).toBe(200); expect(JSON.stringify(await (await request("/integrations/bearer")).json())).not.toContain(rotatedCipher); const agent = await request("/unlock-key/rotation-snapshot", "GET", undefined, "untrusted-cookie"); diff --git a/packages/api/test/loading.postgres.test.ts b/packages/api/test/loading.postgres.test.ts index f05c1657..d02634aa 100644 --- a/packages/api/test/loading.postgres.test.ts +++ b/packages/api/test/loading.postgres.test.ts @@ -8,6 +8,7 @@ import { ConnectionRepository } from "../src/postgres/connection-repository"; import { EncryptedIntegrationRepository } from "../src/postgres/encrypted-integration-repository"; import { FlyConnectionRepository } from "../src/postgres/fly-connection-repository"; import { FlyExecutionConfigurationRepository } from "../src/postgres/fly-execution-configuration-repository"; +import { GitHubRepository } from "../src/postgres/github-repository"; import { encrypt } from "../src/crypto"; import { ApiService } from "../src/flow-service"; import worker from "../src/worker"; @@ -151,6 +152,37 @@ describe.skipIf(!url)("request loading with PostgreSQL", () => { await new FlyConnectionRepository(db, tenantId, env.CREDENTIAL_ENCRYPTION_KEY).remove(); } }); + it("snapshots selected tenant GitHub and Linear connections and rejects disconnected or foreign selections", async () => { + const service = new ApiService(env, auth), github = new GitHubRepository(db, tenantId), otherGithub = new GitHubRepository(db, otherTenant); + const installationId = Number(`8${Date.now().toString().slice(-8)}`), foreignInstallationId = installationId + 1; + const connections = new ConnectionRepository(db, tenantId, env.CREDENTIAL_ENCRYPTION_KEY), priorLinear = await connections.get("linear"); + const slug = `provider-${crypto.randomUUID().slice(0, 8)}`; + const base = { name: "Provider selections", slug, promptTemplate: "Do work", executionConfigId: "local", concurrencyLimit: 1, triggers: [{ kind: "manual" as const, enabled: true, config: {} }] }; + try { + await github.save({ installationId, accountLogin: "tenant-install", accountType: "Organization", state: "active" }); + await otherGithub.save({ installationId: foreignInstallationId, accountLogin: "foreign-install", accountType: "Organization", state: "active" }); + await connections.put("linear", { organizationName: "Tenant Linear", accessToken: "first" }); + await expect(service.createJob({ ...base, githubInstallationIds: [foreignInstallationId] })).rejects.toMatchObject({ status: 400 }); + const job = await service.createJob({ ...base, githubInstallationIds: [installationId], linearConnectionId: "linear" }); + expect(job).toMatchObject({ githubInstallationIds: [installationId], linearConnectionId: "linear" }); + const invoked = await service.invokeJob(job.id, { prompt: "run", data: {} }); + const readSnapshot = async () => (await db.pool.query("SELECT execution_config FROM app.runs WHERE tenant_id=$1 AND id=$2", [tenantId, invoked.runId])).rows[0].execution_config; + const snapshot = await readSnapshot(); + expect(snapshot).toMatchObject({ githubInstallationIds: [installationId], linearConnectionId: "linear" }); + await connections.put("linear", { organizationName: "Tenant Linear", accessToken: "rotated" }); + await expect(service.updateJob(job.id, { ...base, githubInstallationIds: [installationId], linearConnectionId: "linear" })).resolves.toMatchObject({ githubInstallationIds: [installationId], linearConnectionId: "linear" }); + expect(await readSnapshot()).toEqual(snapshot); + await github.updateState(installationId, "suspended"); + await expect(service.updateJob(job.id, { ...base, githubInstallationIds: [installationId], linearConnectionId: "linear" })).rejects.toMatchObject({ status: 400 }); + await connections.delete("linear"); + await expect(service.createJob({ ...base, slug: `${slug}-disconnected`, linearConnectionId: "linear" })).rejects.toMatchObject({ status: 400 }); + } finally { + await db.pool.query("DELETE FROM app.jobs WHERE tenant_id=$1 AND slug LIKE $2", [tenantId, `${slug}%`]); + await db.pool.query("DELETE FROM app.github_installations WHERE tenant_id=$1 AND installation_id=ANY($2::bigint[])", [tenantId, [installationId]]); + await db.pool.query("DELETE FROM app.github_installations WHERE tenant_id=$1 AND installation_id=$2", [otherTenant, foreignInstallationId]); + if (priorLinear) await connections.put("linear", priorLinear); else await connections.delete("linear"); + } + }); it("enforces tenant and scope boundaries, email verification, cookie expiry and session revocation", async () => { await expect(new ApiService(env, { ...auth, tenantId: otherTenant }).listJobs()).rejects.toMatchObject({ status: 401 }); await expect(new ApiService(env, { ...auth, scopes: ["runs:read"] }).listJobs()).rejects.toMatchObject({ status: 403 }); diff --git a/packages/api/test/proxy-control.test.ts b/packages/api/test/proxy-control.test.ts index 819ac68f..356a1e0c 100644 --- a/packages/api/test/proxy-control.test.ts +++ b/packages/api/test/proxy-control.test.ts @@ -164,7 +164,7 @@ describe("dedicated proxy boot registration endpoint", () => { env.query.mockImplementation(async (sql: string, values: unknown[] = []) => { if (sql.includes("SELECT user_id FROM app.members")) return { rows: [{ user_id: "11111111-1111-4111-8111-111111111111" }], rowCount: 1 }; if (sql.includes("proxy_token_digest")) return { rows: [{ tenant_id: "11111111-1111-4111-8111-111111111111", proxy_identity: "proxy-fixture", boot_epoch: bootEpoch }], rowCount: 1 }; - if (sql.includes("FROM app.runs r")) return { rows: [{ execution_config: { portableIntegrationIds: [integrationId, "99999999-9999-4999-8999-999999999999"], modelAccess: "portable", modelAccountId }, grant_revision: 3 }], rowCount: 1 }; + if (sql.includes("FROM app.runs r")) return { rows: [{ execution_config: { portableIntegrationIds: [integrationId, "99999999-9999-4999-8999-999999999999"], modelAccess: "portable", modelAccountId, githubInstallationIds: [123], linearConnectionId: "linear" }, grant_revision: 3 }], rowCount: 1 }; if (sql.includes("FROM app.integration_records")) return values[1] === "bearer" ? { rows: [ { id: integrationId, kind: "bearer", name: "selected", origin: "https://api.example", description: null, revision: 4, encrypted_payload: await encrypt("user-ciphertext", key), deleted_at: null }, { id: "99999999-9999-4999-8999-999999999999", kind: "bearer", name: "deleted", origin: "https://deleted.example", description: null, revision: 8, encrypted_payload: null, deleted_at: new Date("2026-01-01T00:00:00Z") }, @@ -184,7 +184,7 @@ describe("dedicated proxy boot registration endpoint", () => { expect(await response.json()).toEqual({ ownerId: "11111111-1111-4111-8111-111111111111", records: [ { id: integrationId, kind: "bearer", name: "selected", origin: "https://api.example", description: null, revision: 4, encryptedPayload: "user-ciphertext", deletedAt: null }, { id: "99999999-9999-4999-8999-999999999999", kind: "bearer", name: "deleted", origin: "https://deleted.example", description: null, revision: 8, encryptedPayload: null, deletedAt: "2026-01-01T00:00:00.000Z" }, - ], modelAccount: { id: modelAccountId, kind: "model", name: "selected-model", origin: null, description: "fixture account", revision: 6, encryptedPayload: "model-user-ciphertext" } }); + ], modelAccount: { id: modelAccountId, kind: "model", name: "selected-model", origin: null, description: "fixture account", revision: 6, encryptedPayload: "model-user-ciphertext" }, providerCredentials: { githubInstallations: [{ installationId: 123, available: false }], linearConnection: { connectionId: "linear", available: false } } }); expect(env.query.mock.calls.map((call: any[]) => call[0])).toEqual(expect.arrayContaining([expect.stringContaining("grant_revision=$5"), expect.stringContaining("FROM app.integration_records")])); }); diff --git a/packages/app/src/features/jobs/editor-queries.ts b/packages/app/src/features/jobs/editor-queries.ts index d1e97e91..368f8533 100644 --- a/packages/app/src/features/jobs/editor-queries.ts +++ b/packages/app/src/features/jobs/editor-queries.ts @@ -1,6 +1,12 @@ import { queryOptions } from "@tanstack/react-query"; import { api } from "factorize-api-client"; import { messageOf } from "../auth/session"; +export const providerConnectionsQuery = queryOptions({ queryKey: ["editor", "provider-connections"], queryFn: async ({ signal }) => { + const [github, integrations] = await Promise.all([api.GET("/api/v1/github-installations", { signal }), api.GET("/api/v1/integrations", { signal })]); + if (!github.data || github.error) throw new Error(messageOf(github.error)); + if (!integrations.data || integrations.error) throw new Error(messageOf(integrations.error)); + return { githubInstallations: github.data, linear: integrations.data.linear }; +}, staleTime: 60_000 }); export const targetsQuery = queryOptions({ queryKey: ["editor", "integrations"], queryFn: async ({ signal }) => { const { data, error } = await api.GET("/api/v1/integrations", { signal }); if (!data || error) throw new Error(messageOf(error)); diff --git a/packages/app/src/features/jobs/editor-state.ts b/packages/app/src/features/jobs/editor-state.ts index ad6f2d0d..c192e8ad 100644 --- a/packages/app/src/features/jobs/editor-state.ts +++ b/packages/app/src/features/jobs/editor-state.ts @@ -10,7 +10,7 @@ export function canonicalizeVmImage(value: string): string { return `${name.toLowerCase()}${tag}${digest}`; } export function editableJob(job: Job): JobInput { - return { modelAccountId: job.modelAccountId, modelAccess: job.modelAccess, portableIntegrationIds: job.portableIntegrationIds, runScopes: job.runScopes ?? [...defaultRunScopes], executionType: job.executionType ?? "agent", projectId: job.projectId, name: job.name, description: job.description ?? "", slug: job.slug, promptTemplate: job.promptTemplate, script: job.script ?? "", runNameTemplate: job.runNameTemplate, executionConfigId: job.executionConfigId, concurrencyLimit: job.concurrencyLimit, tags: job.tags ?? [], vmImage: job.executionConfig?.image ?? "", model: job.model, effort: job.effort ?? "", skillIds: job.skills?.map(skill => skill.id) ?? [], triggers: job.triggers.map(trigger => { + return { modelAccountId: job.modelAccountId, modelAccess: job.modelAccess, portableIntegrationIds: job.portableIntegrationIds, githubInstallationIds: job.githubInstallationIds, linearConnectionId: job.linearConnectionId, runScopes: job.runScopes ?? [...defaultRunScopes], executionType: job.executionType ?? "agent", projectId: job.projectId, name: job.name, description: job.description ?? "", slug: job.slug, promptTemplate: job.promptTemplate, script: job.script ?? "", runNameTemplate: job.runNameTemplate, executionConfigId: job.executionConfigId, concurrencyLimit: job.concurrencyLimit, tags: job.tags ?? [], vmImage: job.executionConfig?.image ?? "", model: job.model, effort: job.effort ?? "", skillIds: job.skills?.map(skill => skill.id) ?? [], triggers: job.triggers.map(trigger => { const { id, slug, kind, enabled } = trigger; const config = trigger.kind === "webhook" ? Object.fromEntries(Object.entries(trigger.config).filter(([key]) => !["destination", "secretConfigured"].includes(key))) : trigger.config; return { id, slug, kind, enabled, config } as Trigger; diff --git a/packages/app/src/features/jobs/editor.tsx b/packages/app/src/features/jobs/editor.tsx index 8e9e19d7..ecd96f74 100644 --- a/packages/app/src/features/jobs/editor.tsx +++ b/packages/app/src/features/jobs/editor.tsx @@ -8,7 +8,7 @@ import { Link, useLocation, useNavigate, useParams, useBlocker } from "@tanstack import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; import { api } from "factorize-api-client"; import { jobQuery } from "./queries"; -import { metadataQuery, targetsQuery } from "./editor-queries"; +import { metadataQuery, providerConnectionsQuery, targetsQuery } from "./editor-queries"; import { canonicalizeVmImage, applySavedJob, editableJob, emptyJob, reconcile, validateJobInput, writeInput, type Job, type JobInput } from "./editor-state"; import { TemplateField } from "./template-field"; import { TriggerEditor } from "./trigger-editor"; @@ -39,6 +39,7 @@ function EditorForm({ initial, section }: { initial?: Job; section?: string }) { useBlocker({ shouldBlockFn: ({ next }) => dirty && !(initial && next.pathname.startsWith(`/jobs/${initial.id}/settings/`)) && !savingNavigation.current && !window.confirm("Discard unsaved job changes?"), enableBeforeUnload: dirty }); useEffect(() => { const handler = (event: BeforeUnloadEvent) => { if (dirty) { event.preventDefault(); event.returnValue = ""; } }; window.addEventListener("beforeunload", handler); return () => window.removeEventListener("beforeunload", handler); }, [dirty]); const targets = useQuery(targetsQuery), metadata = useQuery(metadataQuery), skills = useQuery(skillsQuery()); + const providerConnections = useQuery(providerConnectionsQuery); const projects = useQuery({ ...projectsQuery, enabled: !initial }); const flyConnection = useQuery(flyConnectionQuery), flyConfigurations = useQuery(flyConfigurationsQuery); const flyConfiguration = flyConfigurations.data?.find(item => item.id === draft.executionConfigId); @@ -115,6 +116,12 @@ function EditorForm({ initial, section }: { initial?: Job; section?: string }) { {isFly && <> setFlySettingsDirty(true)} onSaved={id => { setFlySettingsDirty(false); update("executionConfigId", id); update("vmImage", ""); }} />{(draft.executionType ?? "agent") === "agent" && }} {flyConnection.error &&

Fly.io: {flyConnection.error.message}

}{flyConfigurations.error &&

Fly.io: {flyConfigurations.error.message}

} {!isFly && } +
Provider credentials for runs

Choose only the tenant connections this job may use. Each run keeps this selection; disconnecting a connection revokes it.

+ {providerConnections.isPending &&

Loading provider connections…

}{providerConnections.error &&

{providerConnections.error.message}

} + {providerConnections.data?.githubInstallations.filter(item => item.state === "active").map(item => { const id = Number(item.installationId); return ; })} + {!providerConnections.isPending && providerConnections.data?.githubInstallations.filter(item => item.state === "active").length === 0 &&

No active GitHub installations are connected.

} + {providerConnections.data?.linear ? :

No Linear connection is connected.

} +
{target?.kind !== "amp" && !isFly &&
{draft.vmImage &&

{verification.data?.status === "succeeded" && activeVerificationId ? `Verified: ${verification.data?.phase}` : verification.data?.status === "failed" && activeVerificationId ? `${verification.data?.errorKind}: ${verification.data?.error}` : verification.data?.status === "cleanup_failed" && activeVerificationId ? `Cleanup unresolved: ${verification.data?.error}` : activeVerificationId ? `Verification ${verification.data?.status}: ${verification.data?.phase}` : "Not verified"}

}{draft.vmImage && }{verifyImage.error &&

{verifyImage.error.message}

}
} {(draft.executionType ?? "agent") === "agent" && <> diff --git a/packages/app/src/lib/unlock-key.ts b/packages/app/src/lib/unlock-key.ts index 384cfdef..4856ad2c 100644 --- a/packages/app/src/lib/unlock-key.ts +++ b/packages/app/src/lib/unlock-key.ts @@ -69,7 +69,7 @@ export async function replaceUnlockKeyGeneration(oldKey: string | null, newKey: })); const { data, error } = await api.POST("/api/v1/unlock-key/rotation", { body: { expectedGenerationId: snapshot.generationId, generationId, expectedRevision: snapshot.revision, - encryptedVerification, records, changes, + encryptedVerification, preserveManagedModelCaches: mode === "rotate", records, changes, } }); if (!data || error) throw new Error(messageOf(error)); return data; diff --git a/packages/docs/openapi.yaml b/packages/docs/openapi.yaml index f0eeaa49..370c74bb 100644 --- a/packages/docs/openapi.yaml +++ b/packages/docs/openapi.yaml @@ -1689,6 +1689,18 @@ components: type: string format: uuid pattern: ^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$ + githubInstallationIds: + maxItems: 100 + type: array + items: + type: integer + exclusiveMinimum: 0 + maximum: 9007199254740991 + linearConnectionId: + anyOf: + - type: string + const: linear + - type: "null" required: - name - slug @@ -2657,6 +2669,8 @@ paths: type: string minLength: 1 maxLength: 4096 + preserveManagedModelCaches: + type: boolean records: maxItems: 5000 type: array @@ -8660,6 +8674,17 @@ paths: type: string format: uuid pattern: ^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$ + githubInstallationIds: + type: array + items: + type: integer + exclusiveMinimum: 0 + maximum: 9007199254740991 + linearConnectionId: + anyOf: + - type: string + const: linear + - type: "null" executionConfigId: type: string agentKind: @@ -9486,6 +9511,17 @@ paths: type: string format: uuid pattern: ^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$ + githubInstallationIds: + type: array + items: + type: integer + exclusiveMinimum: 0 + maximum: 9007199254740991 + linearConnectionId: + anyOf: + - type: string + const: linear + - type: "null" executionConfigId: type: string agentKind: @@ -10079,6 +10115,17 @@ paths: type: string format: uuid pattern: ^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$ + githubInstallationIds: + type: array + items: + type: integer + exclusiveMinimum: 0 + maximum: 9007199254740991 + linearConnectionId: + anyOf: + - type: string + const: linear + - type: "null" executionConfigId: type: string agentKind: @@ -11165,6 +11212,17 @@ paths: type: string format: uuid pattern: ^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$ + githubInstallationIds: + type: array + items: + type: integer + exclusiveMinimum: 0 + maximum: 9007199254740991 + linearConnectionId: + anyOf: + - type: string + const: linear + - type: "null" executionConfigId: type: string agentKind: @@ -11771,6 +11829,17 @@ paths: type: string format: uuid pattern: ^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$ + githubInstallationIds: + type: array + items: + type: integer + exclusiveMinimum: 0 + maximum: 9007199254740991 + linearConnectionId: + anyOf: + - type: string + const: linear + - type: "null" executionConfigId: type: string agentKind: @@ -12659,6 +12728,18 @@ paths: type: string format: uuid pattern: ^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$ + githubInstallationIds: + maxItems: 100 + type: array + items: + type: integer + exclusiveMinimum: 0 + maximum: 9007199254740991 + linearConnectionId: + anyOf: + - type: string + const: linear + - type: "null" expectedUpdatedAt: type: string format: date-time From 276edfa4583689e4321a6d268e48a80e6be13dd3 Mon Sep 17 00:00:00 2001 From: "exe.dev user" Date: Mon, 16 Nov 2026 21:16:12 +0000 Subject: [PATCH 11/28] Preserve managed caches during unlock rotation --- packages/api/src/flow-service.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/api/src/flow-service.ts b/packages/api/src/flow-service.ts index 73a769fe..a4d81f40 100644 --- a/packages/api/src/flow-service.ts +++ b/packages/api/src/flow-service.ts @@ -636,7 +636,7 @@ export class ApiService { if (input.preserveManagedModelCaches) { const current = await repository.rotationSnapshot(); const managed = (value: string | null) => value?.startsWith("factorize-managed-model-cache-v1:") ?? false; - suppliedRecords = [...suppliedRecords, ...current.records.filter(record => record.kind === "model" && managed(record.encryptedPayload))]; + suppliedRecords = [...suppliedRecords, ...current.records.filter(record => record.kind === "model" && managed(record.encryptedPayload)).map(record => ({ ...record, deletedAt: record.deletedAt?.toISOString() ?? null }))]; suppliedChanges = [...suppliedChanges, ...current.changes.filter(change => change.kind === "model" && managed(change.encryptedPayload))]; } const records = suppliedRecords.map(record => ({ ...record, deletedAt: record.deletedAt === null ? null : new Date(record.deletedAt) })); From 6ca4076c9e407208ffc82647ce4fb3ac361959e6 Mon Sep 17 00:00:00 2001 From: "exe.dev user" Date: Mon, 16 Nov 2026 21:19:41 +0000 Subject: [PATCH 12/28] Fix managed cache rotation fixture revision --- packages/api/test/encrypted-integration-api.postgres.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/api/test/encrypted-integration-api.postgres.test.ts b/packages/api/test/encrypted-integration-api.postgres.test.ts index 2a8b1a89..f5138cbe 100644 --- a/packages/api/test/encrypted-integration-api.postgres.test.ts +++ b/packages/api/test/encrypted-integration-api.postgres.test.ts @@ -110,7 +110,7 @@ describe.skipIf(!databaseUrl)("owner-only managed credential API (PostgreSQL)", const integrationRepository = new EncryptedIntegrationRepository(f.db, f.tenantId, f.env.CREDENTIAL_ENCRYPTION_KEY); await integrationRepository.write({ id: rotatedId, kind: "bearer", expectedRevision: 2, idempotencyKey: crypto.randomUUID(), name: "Rotated", origin: "https://api.example.test", description: null, operation: "upsert", encryptedPayload: encrypted }); const modelId = crypto.randomUUID(); - await integrationRepository.write({ id: modelId, kind: "model", expectedRevision: 0, idempotencyKey: crypto.randomUUID(), name: "Managed model", origin: null, description: null, operation: "upsert", managedModelPayload: JSON.stringify({ accessToken: "server-managed-fixture" }) }); + await integrationRepository.write({ id: modelId, kind: "model", expectedRevision: 3, idempotencyKey: crypto.randomUUID(), name: "Managed model", origin: null, description: null, operation: "upsert", managedModelPayload: JSON.stringify({ accessToken: "server-managed-fixture" }) }); const rotationSnapshot = await (await request("/unlock-key/rotation-snapshot")).json() as any; expect(rotationSnapshot.records.some((record: any) => record.id === modelId)).toBe(false); expect(JSON.stringify(rotationSnapshot)).not.toContain("server-managed-fixture"); From 9a2fdc936c6d53c77f6acba4ec31053aad21fd25 Mon Sep 17 00:00:00 2001 From: "exe.dev user" Date: Mon, 16 Nov 2026 21:25:30 +0000 Subject: [PATCH 13/28] Allow server-preserved caches in key rotation --- packages/api/src/flow-service.ts | 5 ++++- .../api/src/postgres/encrypted-integration-repository.ts | 8 +++++--- 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/packages/api/src/flow-service.ts b/packages/api/src/flow-service.ts index a4d81f40..d21cc047 100644 --- a/packages/api/src/flow-service.ts +++ b/packages/api/src/flow-service.ts @@ -630,6 +630,9 @@ export class ApiService { }) { await this.authorizeOwnerSession("integrations:write"); if (input.expectedGenerationId === input.generationId) throw new ServiceError(400, "invalid_request", "A replacement key generation must be new."); + if (input.preserveManagedModelCaches && [...input.records.map(record => record.encryptedPayload), ...input.changes.map(change => change.encryptedPayload)].some(value => value?.startsWith("factorize-managed-model-cache-v1:"))) { + throw new ServiceError(400, "invalid_request", "Managed model cache payloads are preserved by the server and cannot be supplied by the browser."); + } const repository = this.encryptedIntegrations(); let suppliedRecords = input.records; let suppliedChanges = input.changes; @@ -642,7 +645,7 @@ export class ApiService { const records = suppliedRecords.map(record => ({ ...record, deletedAt: record.deletedAt === null ? null : new Date(record.deletedAt) })); const changes = suppliedChanges.map(({ recordRevision: _recordRevision, ...change }) => change); try { - await repository.stageGeneration({ generationId: input.generationId, expectedRevision: input.expectedRevision, records, changes }); + await repository.stageGeneration({ generationId: input.generationId, expectedRevision: input.expectedRevision, records, changes, preserveManagedModelCaches: input.preserveManagedModelCaches }); const committed = await repository.commitGeneration(input.generationId, input.expectedRevision, { expectedVerificationGenerationId: input.expectedGenerationId, verificationGenerationId: input.generationId, diff --git a/packages/api/src/postgres/encrypted-integration-repository.ts b/packages/api/src/postgres/encrypted-integration-repository.ts index a846f911..7e14b101 100644 --- a/packages/api/src/postgres/encrypted-integration-repository.ts +++ b/packages/api/src/postgres/encrypted-integration-repository.ts @@ -248,15 +248,17 @@ export class EncryptedIntegrationRepository { } /** Store one complete replacement generation. Payloads must already be user-encrypted. */ - async stageGeneration(input: { generationId: string; expectedRevision: number; records: GenerationRecord[]; changes: GenerationChange[] }): Promise<{ duplicate: boolean }> { + async stageGeneration(input: { generationId: string; expectedRevision: number; records: GenerationRecord[]; changes: GenerationChange[]; preserveManagedModelCaches?: boolean }): Promise<{ duplicate: boolean }> { const uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; if (!uuid.test(input.generationId) || !Number.isSafeInteger(input.expectedRevision) || input.expectedRevision < 0) throw new IntegrationValidationError("generationId and expectedRevision are invalid"); if (input.records.length > 5000 || input.changes.length > 10000) throw new IntegrationValidationError("generation exceeds staging limits"); for (const record of input.records) { - if (!uuid.test(record.id) || (record.encryptedPayload !== null && !isUserCiphertext(record.encryptedPayload)) || (record.deletedAt === null) !== (record.encryptedPayload !== null)) throw new IntegrationValidationError("generation records must contain ciphertext or a tombstone"); + const managedModel = input.preserveManagedModelCaches && record.kind === "model" && record.encryptedPayload?.startsWith(MANAGED_MODEL_PREFIX); + if (!uuid.test(record.id) || (record.encryptedPayload !== null && !isUserCiphertext(record.encryptedPayload) && !managedModel) || (record.deletedAt === null) !== (record.encryptedPayload !== null)) throw new IntegrationValidationError("generation records must contain ciphertext or a tombstone"); } for (const change of input.changes) { - if (!uuid.test(change.id) || !uuid.test(change.idempotencyKey) || !Number.isSafeInteger(change.revision) || change.revision < 1 || (change.encryptedPayload !== null && !isUserCiphertext(change.encryptedPayload)) || (change.operation === "upsert") !== (change.encryptedPayload !== null)) throw new IntegrationValidationError("generation changes must contain ordered ciphertext or tombstones"); + const managedModel = input.preserveManagedModelCaches && change.kind === "model" && change.encryptedPayload?.startsWith(MANAGED_MODEL_PREFIX); + if (!uuid.test(change.id) || !uuid.test(change.idempotencyKey) || !Number.isSafeInteger(change.revision) || change.revision < 1 || (change.encryptedPayload !== null && !isUserCiphertext(change.encryptedPayload) && !managedModel) || (change.operation === "upsert") !== (change.encryptedPayload !== null)) throw new IntegrationValidationError("generation changes must contain ordered ciphertext or tombstones"); } const canonical = JSON.stringify({ records: [...input.records].sort((a,b) => a.id.localeCompare(b.id)).map(row => ({ ...row, deletedAt: row.deletedAt?.toISOString() ?? null })), From bdd2c876e03371ebfa9f9d687dd541d84f36c55a Mon Sep 17 00:00:00 2001 From: "exe.dev user" Date: Mon, 16 Nov 2026 21:51:43 +0000 Subject: [PATCH 14/28] GEN-2922 resolve and revoke run provider credentials --- packages/api/src/index.ts | 4 +- packages/api/src/linear.ts | 6 +- .../api/src/postgres/connection-repository.ts | 16 ++++ packages/api/src/postgres/provider-catalog.ts | 10 ++- packages/api/src/provider-credentials.ts | 73 +++++++++++++++++++ packages/api/src/proxy-control.ts | 16 ++-- .../api/test/provider-credentials.test.ts | 58 +++++++++++++++ .../credential-proxy/src/control-client.mjs | 26 +++++-- .../credential-proxy/src/decrypted-grants.mjs | 9 +++ packages/credential-proxy/src/main.mjs | 4 +- .../credential-proxy/src/proxy-listener.mjs | 11 +++ packages/credential-proxy/src/runtime.mjs | 18 +++++ .../credential-proxy/src/tunnel-transport.mjs | 4 +- .../test/control-client.test.mjs | 3 +- .../test/decrypted-grants.test.mjs | 2 +- .../test/fly-guest-helper.e2e.test.mjs | 4 +- .../test/proxy-listener.e2e.test.mjs | 1 + .../test/runtime-revocation.test.mjs | 35 +++++++++ 18 files changed, 272 insertions(+), 28 deletions(-) create mode 100644 packages/api/src/provider-credentials.ts create mode 100644 packages/api/test/provider-credentials.test.ts diff --git a/packages/api/src/index.ts b/packages/api/src/index.ts index a4370e1a..9aa26437 100644 --- a/packages/api/src/index.ts +++ b/packages/api/src/index.ts @@ -75,14 +75,14 @@ app.get("/auth/linear/callback", async (c) => { if (!session || !code || !state || rawState !== getCookie(c, "linear_oauth_state") || state.tenantId !== session.tenantId || state.userId !== session.userId) return c.text("Invalid OAuth state", 400); deleteCookie(c, "linear_oauth_state", { path: "/auth/linear" }); const tokenResponse = await fetch("https://api.linear.app/oauth/token", { method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded" }, body: new URLSearchParams({ code, redirect_uri: `${c.env.APP_ORIGIN}/auth/linear/callback`, client_id: c.env.LINEAR_CLIENT_ID, client_secret: c.env.LINEAR_CLIENT_SECRET, grant_type: "authorization_code" }) }); - const tokens = await tokenResponse.json() as { access_token?: string; refresh_token?: string }; + const tokens = await tokenResponse.json() as { access_token?: string; refresh_token?: string; expires_in?: number }; if (!tokenResponse.ok || !tokens.access_token || !tokens.refresh_token) return c.text("Linear token exchange failed", 502); const meResponse = await fetch("https://api.linear.app/graphql", { method: "POST", headers: { Authorization: `Bearer ${tokens.access_token}`, "Content-Type": "application/json" }, body: JSON.stringify({ query: "query { viewer { id email } organization { id name } }" }) }); const me = await meResponse.json() as any; const organization = me.data?.organization; const viewer = me.data?.viewer; if (!organization?.id || !viewer?.id) return c.text("Could not identify Linear workspace", 502); - const connected = await new ConnectionRepository(databaseFor(c.env), session.tenantId, c.env.CREDENTIAL_ENCRYPTION_KEY).putLinear(organization.id, { accessToken: tokens.access_token, refreshToken: tokens.refresh_token, organizationId: organization.id, organizationName: organization.name, viewerId: viewer.id, viewerEmail: viewer.email }); + const connected = await new ConnectionRepository(databaseFor(c.env), session.tenantId, c.env.CREDENTIAL_ENCRYPTION_KEY).putLinear(organization.id, { accessToken: tokens.access_token, refreshToken: tokens.refresh_token, accessTokenExpiresAt: Number.isFinite(tokens.expires_in) ? new Date(Date.now() + tokens.expires_in! * 1000).toISOString() : null, organizationId: organization.id, organizationName: organization.name, viewerId: viewer.id, viewerEmail: viewer.email }); if (!connected) return c.text("This Linear workspace is already connected to another Factorize workspace. Sign in to that Factorize account to manage it.", 409); return c.redirect("/settings/integrations"); }); diff --git a/packages/api/src/linear.ts b/packages/api/src/linear.ts index c1e0f8e2..90455b4b 100644 --- a/packages/api/src/linear.ts +++ b/packages/api/src/linear.ts @@ -21,13 +21,13 @@ export const isLinearAuthenticationError = (status: number, errors: LinearError[ })); }; -export const refreshLinearToken = async (refreshToken: string, clientId: string, clientSecret: string): Promise<{ access_token: string; refresh_token?: string }> => { +export const refreshLinearToken = async (refreshToken: string, clientId: string, clientSecret: string): Promise<{ access_token: string; refresh_token?: string; expires_in?: number }> => { const response = await fetch("https://api.linear.app/oauth/token", { method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded" }, body: new URLSearchParams({ grant_type: "refresh_token", refresh_token: refreshToken, client_id: clientId, client_secret: clientSecret }), }); - const tokens = await response.json() as { access_token?: string; refresh_token?: string }; + const tokens = await response.json() as { access_token?: string; refresh_token?: string; expires_in?: number }; if (!response.ok || !tokens.access_token) throw new Error("Your Linear connection expired. Reconnect Linear to continue."); - return { access_token: tokens.access_token, refresh_token: tokens.refresh_token }; + return { access_token: tokens.access_token, refresh_token: tokens.refresh_token, expires_in: tokens.expires_in }; }; diff --git a/packages/api/src/postgres/connection-repository.ts b/packages/api/src/postgres/connection-repository.ts index 40d89319..c97ebf3d 100644 --- a/packages/api/src/postgres/connection-repository.ts +++ b/packages/api/src/postgres/connection-repository.ts @@ -35,6 +35,22 @@ export class ConnectionRepository { throw error; } } + /** Persist a rotated Linear token only while the connection still has the + * refresh token used for the exchange. This prevents a late refresh from + * replacing a reconnect or a newer token rotation. */ + async rotateLinearTokens(expectedRefreshToken: string, value: Record): Promise | null> { + return this.database.transaction(async client => { + const current = await client.query<{ encrypted_value: string }>( + "SELECT encrypted_value FROM app.connections WHERE tenant_id=$1 AND kind='linear' FOR UPDATE", [this.tenantId]); + if (!current.rows[0]) return null; + const connection = JSON.parse(await decrypt(current.rows[0].encrypted_value, this.encryptionKey)); + if (connection.refreshToken !== expectedRefreshToken) return connection; + const encryptedValue = await encrypt(JSON.stringify({ ...connection, ...value }), this.encryptionKey); + await client.query("UPDATE app.connections SET encrypted_value=$3,updated_at=now() WHERE tenant_id=$1 AND kind='linear' AND encrypted_value=$2", + [this.tenantId, current.rows[0].encrypted_value, encryptedValue]); + return { ...connection, ...value }; + }); + } async delete(kind: string): Promise { return Boolean((await this.database.orm.delete(connections).where(and(eq(connections.tenantId, this.tenantId), eq(connections.kind, kind))).returning({ kind: connections.kind })).length); } async kinds(prefix?: string): Promise { const rows = await this.database.orm.select({ kind: connections.kind }).from(connections).where(and(eq(connections.tenantId, this.tenantId), ...(prefix ? [like(connections.kind, `${prefix}%`)] : []))).orderBy(connections.kind); diff --git a/packages/api/src/postgres/provider-catalog.ts b/packages/api/src/postgres/provider-catalog.ts index 18334b86..c9b0d316 100644 --- a/packages/api/src/postgres/provider-catalog.ts +++ b/packages/api/src/postgres/provider-catalog.ts @@ -23,8 +23,14 @@ export class ProviderCatalog { let result = await request(connection.accessToken); if (isLinearAuthenticationError(result.response.status, result.payload.errors)) { const tokens = await refreshLinearToken(connection.refreshToken, this.env.LINEAR_CLIENT_ID, this.env.LINEAR_CLIENT_SECRET); - await this.connections.put("linear", { ...connection, accessToken: tokens.access_token, refreshToken: tokens.refresh_token ?? connection.refreshToken }); - result = await request(tokens.access_token); + const updated = await this.connections.rotateLinearTokens(connection.refreshToken, { + accessToken: tokens.access_token, + refreshToken: tokens.refresh_token ?? connection.refreshToken, + accessTokenExpiresAt: new Date(Date.now() + (Number.isFinite(tokens.expires_in) ? tokens.expires_in! * 1000 : 50 * 60_000)).toISOString(), + }); + const accessToken = updated?.accessToken; + if (!accessToken) throw new Error("Your Linear connection expired. Reconnect Linear to continue."); + result = await request(accessToken); } if (!result.response.ok || result.payload.errors?.length) throw new Error(result.payload.errors?.[0]?.message ?? `Linear request failed (${result.response.status})`); return result.payload.data; diff --git a/packages/api/src/provider-credentials.ts b/packages/api/src/provider-credentials.ts new file mode 100644 index 00000000..0c58d6e3 --- /dev/null +++ b/packages/api/src/provider-credentials.ts @@ -0,0 +1,73 @@ +import type { Env } from "./types"; +import type { Database } from "./postgres/database"; +import { installationToken } from "./github"; +import { refreshLinearToken } from "./linear"; +import { ConnectionRepository } from "./postgres/connection-repository"; +import { GitHubRepository } from "./postgres/github-repository"; + +type CachedInstallationToken = { token: string; expiresAt: number }; +const installationTokens = new Map(); +const LINEAR_REFRESH_MARGIN_MS = 5 * 60_000; +const GITHUB_TOKEN_TTL_MS = 50 * 60_000; +const LINEAR_TOKEN_TTL_MS = 50 * 60_000; + +function validExpiry(value: unknown): number | null { + if (typeof value !== "string") return null; + const parsed = Date.parse(value); + return Number.isFinite(parsed) ? parsed : null; +} + +/** Resolve provider credentials for one already-authorized run snapshot. The + * caller supplies only the immutable selection read from that active run. */ +export async function resolveRunProviderCredentials(input: { + database: Database; + env: Env; + tenantId: string; + githubInstallationIds: number[]; + linearSelected: boolean; +}): Promise<{ githubInstallations: Array<{ installationId: number; available: boolean; accessToken?: string }>; + linearConnection: null | { connectionId: "linear"; available: boolean; accessToken?: string } }> { + const { database, env, tenantId } = input; + const github = await Promise.all(input.githubInstallationIds.map(async installationId => { + const cacheKey = `${tenantId}:${installationId}`; + const installation = await new GitHubRepository(database, tenantId).installation(installationId); + if (installation?.state !== "active") { installationTokens.delete(cacheKey); return { installationId, available: false }; } + let cached = installationTokens.get(cacheKey); + if (!cached || cached.expiresAt <= Date.now()) { + const token = await installationToken(env, installationId); + cached = { token, expiresAt: Date.now() + GITHUB_TOKEN_TTL_MS }; + installationTokens.set(cacheKey, cached); + } + // Recheck availability after the remote token request to close a + // suspension/disconnect race before returning a usable credential. + const current = await new GitHubRepository(database, tenantId).installation(installationId); + if (current?.state !== "active") { + installationTokens.delete(cacheKey); + return { installationId, available: false }; + } + return { installationId, available: true, accessToken: cached.token }; + })); + + if (!input.linearSelected) return { githubInstallations: github, linearConnection: null }; + const connected = await database.pool.query("SELECT 1 FROM app.connections WHERE tenant_id=$1 AND kind='linear'", [tenantId]); + if (!connected.rowCount) return { githubInstallations: github, linearConnection: { connectionId: "linear", available: false } }; + const connections = new ConnectionRepository(database, tenantId, env.CREDENTIAL_ENCRYPTION_KEY); + let linear = await connections.get>("linear"); + if (!linear) return { githubInstallations: github, linearConnection: { connectionId: "linear", available: false } }; + let expiry = validExpiry(linear.accessTokenExpiresAt); + if (!expiry || expiry <= Date.now() + LINEAR_REFRESH_MARGIN_MS) { + const refreshed = await refreshLinearToken(linear.refreshToken, env.LINEAR_CLIENT_ID, env.LINEAR_CLIENT_SECRET); + const updated = await connections.rotateLinearTokens(linear.refreshToken, { + accessToken: refreshed.access_token, + refreshToken: refreshed.refresh_token ?? linear.refreshToken, + accessTokenExpiresAt: new Date(Date.now() + (Number.isFinite(refreshed.expires_in) + ? Math.max(0, refreshed.expires_in!) * 1000 : LINEAR_TOKEN_TTL_MS)).toISOString(), + }); + if (!updated) return { githubInstallations: github, linearConnection: { connectionId: "linear", available: false } }; + linear = updated; + expiry = validExpiry(linear.accessTokenExpiresAt); + // A refresh response without an expiry cannot be safely cached as current. + if (!expiry || expiry <= Date.now()) return { githubInstallations: github, linearConnection: { connectionId: "linear", available: false } }; + } + return { githubInstallations: github, linearConnection: { connectionId: "linear", available: true, accessToken: linear.accessToken } }; +} diff --git a/packages/api/src/proxy-control.ts b/packages/api/src/proxy-control.ts index 81e0639c..31a33ccd 100644 --- a/packages/api/src/proxy-control.ts +++ b/packages/api/src/proxy-control.ts @@ -3,7 +3,7 @@ import { ProxyControlRepository } from "./postgres/proxy-control-repository"; import { RunEnrollmentRepository } from "./postgres/run-enrollment-repository"; import { EncryptedIntegrationRepository } from "./postgres/encrypted-integration-repository"; import { authenticateRunCredential } from "./run-credentials"; -import { GitHubRepository } from "./postgres/github-repository"; +import { resolveRunProviderCredentials } from "./provider-credentials"; async function recordOwner(env: Parameters[0], tenantId: string): Promise { const result = await databaseFor(env).pool.query<{ user_id: string }>("SELECT user_id FROM app.members WHERE tenant_id=$1 AND role='owner' ORDER BY created_at,user_id LIMIT 1", [tenantId]); @@ -146,18 +146,14 @@ export async function proxyControlFetch(request: Request, env: Parameters !Number.isSafeInteger(id) || id <= 0) || new Set(selectedGitHub).size !== selectedGitHub.length) return json({ error: "integration_snapshot_unavailable" }, 403); - const installations = await new GitHubRepository(database, proxy.tenantId).installations(); - const byInstallation = new Map(installations.map(item => [Number(item.installationId), item])); - const githubInstallations = selectedGitHub.map((installationId: number) => ({ installationId, available: byInstallation.get(installationId)?.state === "active" })); const selectedLinear = run.execution_config?.linearConnectionId; if (selectedLinear !== undefined && selectedLinear !== "linear") return json({ error: "integration_snapshot_unavailable" }, 403); - const linearPresent = selectedLinear === "linear" - ? Boolean((await database.pool.query("SELECT 1 FROM app.connections WHERE tenant_id=$1 AND kind='linear'", [proxy.tenantId])).rowCount) - : false; - const linearConnection = selectedLinear === "linear" ? { connectionId: "linear", available: linearPresent } : null; + const providerCredentials = await resolveRunProviderCredentials({ database, env, tenantId: proxy.tenantId, + githubInstallationIds: selectedGitHub, linearSelected: selectedLinear === "linear" }); // Only the selected model account's user-encrypted payload crosses the - // control plane. It remains encrypted until the proxy is unlocked. - return json({ ownerId: await recordOwner(env, proxy.tenantId), records, modelAccount, providerCredentials: { githubInstallations, linearConnection } }); + // control plane. It remains encrypted until the proxy is unlocked. Provider + // credentials cross only this authenticated proxy control channel. + return json({ ownerId: await recordOwner(env, proxy.tenantId), records, modelAccount, providerCredentials }); } const enrollments = new RunEnrollmentRepository(databaseFor(env)); if (url.pathname === "/internal/credential-proxy/enroll") { diff --git a/packages/api/test/provider-credentials.test.ts b/packages/api/test/provider-credentials.test.ts new file mode 100644 index 00000000..a934b07d --- /dev/null +++ b/packages/api/test/provider-credentials.test.ts @@ -0,0 +1,58 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; +import * as github from "../src/github"; +import { resolveRunProviderCredentials } from "../src/provider-credentials"; +import { ConnectionRepository } from "../src/postgres/connection-repository"; +import { GitHubRepository } from "../src/postgres/github-repository"; +import type { Env } from "../src/types"; + +const tenantId = "11111111-1111-4111-8111-111111111111"; +const otherTenant = "22222222-2222-4222-8222-222222222222"; +const database: any = { pool: { query: vi.fn(async () => ({ rows: [], rowCount: 0 })) } }; +const env = { CREDENTIAL_ENCRYPTION_KEY: "test", LINEAR_CLIENT_ID: "linear-client", LINEAR_CLIENT_SECRET: "linear-secret", GITHUB_APP_ID: "github-app", GITHUB_APP_PRIVATE_KEY: "private" } as Env; + +afterEach(() => { vi.restoreAllMocks(); vi.unstubAllGlobals(); }); + +describe("run provider credential lifecycle", () => { + it("resolves only the active tenant's selected GitHub installations and denies suspended selections", async () => { + const installation = vi.spyOn(GitHubRepository.prototype, "installation").mockImplementation(function(this: any, id: number) { + if (this.tenantId !== tenantId) return Promise.resolve(null); + return Promise.resolve(id === 17 ? { state: "active" } : id === 18 ? { state: "suspended" } : null); + }); + const mint = vi.spyOn(github, "installationToken").mockResolvedValue("rotated-installation-token"); + const result = await resolveRunProviderCredentials({ database, env, tenantId, githubInstallationIds: [17, 18], linearSelected: false }); + expect(result).toEqual({ githubInstallations: [ + { installationId: 17, available: true, accessToken: "rotated-installation-token" }, + { installationId: 18, available: false }, + ], linearConnection: null }); + expect(installation.mock.calls.map(([id]) => id)).toEqual([17, 18, 17]); + expect(mint).toHaveBeenCalledTimes(1); + await resolveRunProviderCredentials({ database, env, tenantId: otherTenant, githubInstallationIds: [17], linearSelected: false }); + expect(mint).toHaveBeenCalledTimes(1); + }); + + it("refreshes and persists a rotated Linear token only when that connection is selected", async () => { + database.pool.query.mockResolvedValue({ rows: [{ connected: 1 }], rowCount: 1 }); + const old = { accessToken: "expired-access", refreshToken: "old-refresh", accessTokenExpiresAt: "2020-01-01T00:00:00.000Z" }; + const current = { ...old, accessToken: "new-access", refreshToken: "new-refresh", accessTokenExpiresAt: new Date(Date.now() + 3_600_000).toISOString() }; + const get = vi.spyOn(ConnectionRepository.prototype, "get").mockResolvedValue(old); + const rotate = vi.spyOn(ConnectionRepository.prototype, "rotateLinearTokens").mockResolvedValue(current); + vi.stubGlobal("fetch", vi.fn(async () => Response.json({ access_token: "new-access", refresh_token: "new-refresh", expires_in: 3600 }))); + const result = await resolveRunProviderCredentials({ database, env, tenantId, githubInstallationIds: [], linearSelected: true }); + expect(result).toEqual({ githubInstallations: [], linearConnection: { connectionId: "linear", available: true, accessToken: "new-access" } }); + expect(get).toHaveBeenCalledTimes(1); + expect(rotate).toHaveBeenCalledWith("old-refresh", expect.objectContaining({ accessToken: "new-access", refreshToken: "new-refresh" })); + + get.mockClear(); + const unselected = await resolveRunProviderCredentials({ database, env, tenantId, githubInstallationIds: [], linearSelected: false }); + expect(unselected.linearConnection).toBeNull(); + expect(get).not.toHaveBeenCalled(); + }); + + it("returns no credential after Linear disconnect and never refreshes an unselected connection", async () => { + database.pool.query.mockResolvedValue({ rows: [], rowCount: 0 }); + const get = vi.spyOn(ConnectionRepository.prototype, "get"); + const result = await resolveRunProviderCredentials({ database, env, tenantId, githubInstallationIds: [], linearSelected: true }); + expect(result.linearConnection).toEqual({ connectionId: "linear", available: false }); + expect(get).not.toHaveBeenCalled(); + }); +}); diff --git a/packages/credential-proxy/src/control-client.mjs b/packages/credential-proxy/src/control-client.mjs index a888e084..61092f2e 100644 --- a/packages/credential-proxy/src/control-client.mjs +++ b/packages/credential-proxy/src/control-client.mjs @@ -104,12 +104,24 @@ export async function readProxyIntegrationSnapshot({ controlOrigin, token, bindi || !(record.deletedAt != null && record.encryptedPayload === null || typeof record.origin === "string" && typeof record.encryptedPayload === "string") || !Number.isSafeInteger(record.revision)) || !(modelAccount === null || (modelAccount && typeof modelAccount.id === "string" && modelAccount.kind === "model" - && modelAccount.origin === null && typeof modelAccount.encryptedPayload === "string" && Number.isSafeInteger(modelAccount.revision)))) { + && modelAccount.origin === null && typeof modelAccount.encryptedPayload === "string" && Number.isSafeInteger(modelAccount.revision))) + || !validProviderCredentials(result.providerCredentials)) { throw new Error("invalid proxy integration snapshot response"); } return result; } +function validProviderCredentials(value) { + if (!value || !Array.isArray(value.githubInstallations) + || value.githubInstallations.some(item => !item || !Number.isSafeInteger(item.installationId) || item.installationId <= 0 + || typeof item.available !== "boolean" || (item.available ? typeof item.accessToken !== "string" || !item.accessToken : item.accessToken !== undefined)) + || !(value.linearConnection === null || (value.linearConnection && value.linearConnection.connectionId === "linear" + && typeof value.linearConnection.available === "boolean" + && (value.linearConnection.available ? typeof value.linearConnection.accessToken === "string" && Boolean(value.linearConnection.accessToken) + : value.linearConnection.accessToken === undefined)))) return false; + return new Set(value.githubInstallations.map(item => item.installationId)).size === value.githubInstallations.length; +} + /** Concrete proxy-side adapters for revision-bound encrypted model caches. */ export function createModelAccountPersistenceAdapter({ controlOrigin, controlCredential, ownerId, fetchImpl = fetch } = {}) { if (typeof ownerId !== "string" || !ownerId || !/^fzc_[A-Za-z0-9_-]{43}$/.test(controlCredential ?? "")) { @@ -233,13 +245,13 @@ const uuidPattern = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{1 * Create the proxy-side half of enrollment. The job VM supplies only its run * ID over the already authenticated TLS connection; the proxy derives VM and * boot identity locally, then issues and consumes a fresh one-use enrollment - * using its private control credential. Integration secrets stay in the - * proxy's local grant resolver and never cross this control API. + * using its private control credential. Provider credentials are returned + * only to this process over the control channel and are never sent to the VM. */ -export function createProxyEnrollmentAuthenticator({ controlOrigin, controlCredential, bootEpoch, resolveGrants, resolveRunCredential, fetchImpl = fetch } = {}) { +export function createProxyEnrollmentAuthenticator({ controlOrigin, controlCredential, bootEpoch, resolveGrants, resolveProviderCredentials, resolveRunCredential, fetchImpl = fetch } = {}) { if (!/^fzc_[A-Za-z0-9_-]{43}$/.test(controlCredential ?? "")) throw new TypeError("invalid proxy control credential"); if (!bootEpochPattern.test(bootEpoch ?? "")) throw new TypeError("invalid proxy boot epoch"); - if (typeof resolveGrants !== "function" || typeof resolveRunCredential !== "function") throw new TypeError("proxy enrollment requires local grant and run credential resolvers"); + if (typeof resolveGrants !== "function" || typeof resolveProviderCredentials !== "function" || typeof resolveRunCredential !== "function") throw new TypeError("proxy enrollment requires local credential resolvers"); validateOrigin(controlOrigin); let credential = controlCredential; return async function authenticateRun({ runId, vmIdentity, bootEpoch: requestedBootEpoch }) { @@ -258,6 +270,8 @@ export function createProxyEnrollmentAuthenticator({ controlOrigin, controlCrede } const grants = await resolveGrants(binding); if (!Array.isArray(grants)) throw new Error("proxy grants are unavailable"); + const providerCredentials = await resolveProviderCredentials(binding); + if (!providerCredentials || !Array.isArray(providerCredentials.githubInstallations)) throw new Error("provider credentials are unavailable"); return { authenticated: true, enrollmentConsumed: true, @@ -271,6 +285,8 @@ export function createProxyEnrollmentAuthenticator({ controlOrigin, controlCrede grantRevision: binding.grantRevision, grants, refreshGrants: () => resolveGrants(binding), + providerCredentials, + refreshProviderCredentials: () => resolveProviderCredentials(binding), }; }; } diff --git a/packages/credential-proxy/src/decrypted-grants.mjs b/packages/credential-proxy/src/decrypted-grants.mjs index fba31583..5a3fb668 100644 --- a/packages/credential-proxy/src/decrypted-grants.mjs +++ b/packages/credential-proxy/src/decrypted-grants.mjs @@ -139,6 +139,15 @@ export function createProxyIntegrationGrantResolver({ runtime, controlOrigin, co }); } +/** Resolve tenant-selected GitHub/Linear credentials through the same active + * run and grant-revision checked snapshot used for bearer grants. */ +export function createProxyProviderCredentialResolver({ controlOrigin, controlCredential, fetchImpl = fetch } = {}) { + if (typeof controlOrigin !== "string" || !/^fzc_[A-Za-z0-9_-]{43}$/.test(controlCredential ?? "")) { + throw new TypeError("provider credential resolver requires the registered proxy identity"); + } + return async binding => (await readProxyIntegrationSnapshot({ controlOrigin, token: controlCredential, binding, fetchImpl })).providerCredentials; +} + /** Verify the current user-encrypted generation before opening access. */ export async function verifyProxyUnlockKey(key, record) { const envelope = JSON.parse(record.encryptedVerification); diff --git a/packages/credential-proxy/src/main.mjs b/packages/credential-proxy/src/main.mjs index a086f908..e12706b6 100644 --- a/packages/credential-proxy/src/main.mjs +++ b/packages/credential-proxy/src/main.mjs @@ -8,7 +8,7 @@ import { randomUUID } from "node:crypto"; import { createProxyRuntime } from "./runtime.mjs"; import { registerProxyBoot, startProxyRunRevocationMonitor, startProxyRuntimeStatusReporter } from "./control-client.mjs"; import { startProxyBootstrapControl } from "./bootstrap-control.mjs"; -import { createProxyIntegrationGrantResolver } from "./decrypted-grants.mjs"; +import { createProxyIntegrationGrantResolver, createProxyProviderCredentialResolver } from "./decrypted-grants.mjs"; import { startAuthenticatedProxyTunnel } from "./tunnel-transport.mjs"; import { createProxyTlsAuthority } from "./tls-identity.mjs"; import { createCodexAuthHelper } from "./codex-auth-helper.mjs"; @@ -78,12 +78,14 @@ async function activateRegistration(registration, origin, browserOrigin) { appOrigin: process.env.FACTORIZE_APP_ORIGIN ?? "https://app.factorize.sh", }); const resolveGrants = createProxyIntegrationGrantResolver({ runtime, controlOrigin: origin, controlCredential: registration.controlCredential }); + const resolveProviderCredentials = createProxyProviderCredentialResolver({ controlOrigin: origin, controlCredential: registration.controlCredential }); const started = await startAuthenticatedProxyTunnel({ tls: tlsAuthority.tls, runtime, controlOrigin: origin, controlCredential: registration.controlCredential, resolveGrants, + resolveProviderCredentials, resolveRunCredential: (runId, vmIdentity) => runCredentials.resolve(runId, vmIdentity), host: process.env.FACTORIZE_PROXY_TUNNEL_HOST ?? "0.0.0.0", port: tunnelPort, diff --git a/packages/credential-proxy/src/proxy-listener.mjs b/packages/credential-proxy/src/proxy-listener.mjs index b1ce1861..009b65db 100644 --- a/packages/credential-proxy/src/proxy-listener.mjs +++ b/packages/credential-proxy/src/proxy-listener.mjs @@ -49,6 +49,7 @@ export async function createAuthenticatedProxyListener({ connection, forwarder = throw new TypeError("proxy listener requires an authenticated consumed connection"); } let grants = grantTable(connection.grants); + let providerCredentials = connection.providerCredentials ?? { githubInstallations: [], linearConnection: null }; let unlocked = true; let lockedMetadata = []; const controllers = new Set(); @@ -149,18 +150,28 @@ export async function createAuthenticatedProxyListener({ connection, forwarder = unlocked = false; lockedMetadata = [...grants.values()].map(({ id, name, description }) => ({ id, name, description })); grants = new Map(); + providerCredentials = { githubInstallations: [], linearConnection: null }; for (const controller of controllers) controller.abort(new Error("proxy locked")); }, + getProviderCredentials() { + return structuredClone(providerCredentials); + }, replaceGrants(nextGrants) { if (closed) return; grants = grantTable(nextGrants); unlocked = true; lockedMetadata = []; }, + replaceProviderCredentials(nextCredentials) { + if (closed) return; + providerCredentials = nextCredentials && typeof nextCredentials === "object" + ? nextCredentials : { githubInstallations: [], linearConnection: null }; + }, close: () => { if (closed) return Promise.resolve(); closed = true; grants = new Map(); + providerCredentials = { githubInstallations: [], linearConnection: null }; for (const controller of controllers) controller.abort(new Error("authenticated tunnel disconnected")); return new Promise((resolve, reject) => server.close(error => error ? reject(error) : resolve())); }, diff --git a/packages/credential-proxy/src/runtime.mjs b/packages/credential-proxy/src/runtime.mjs index 07dae38d..4529a04d 100644 --- a/packages/credential-proxy/src/runtime.mjs +++ b/packages/credential-proxy/src/runtime.mjs @@ -57,6 +57,17 @@ export function createProxyRuntime({ listenerFactory = createAuthenticatedProxyL })); } + async function refreshActiveProviderCredentials() { + const epoch = grantEpoch; + const current = [...listeners]; + await Promise.allSettled(current.map(async listener => { + const connection = listenerConnections.get(listener); + if (!connection || typeof connection.refreshProviderCredentials !== "function" || typeof listener.replaceProviderCredentials !== "function") return; + const credentials = await connection.refreshProviderCredentials(); + if (epoch === grantEpoch && state === "unlocked" && !shutdown && !revokedRuns.has(connection.runId) && listeners.has(listener)) listener.replaceProviderCredentials(credentials); + })); + } + return Object.freeze({ // A fresh process identity invalidates enrollments from every prior boot. bootEpoch, @@ -72,6 +83,7 @@ export function createProxyRuntime({ listenerFactory = createAuthenticatedProxyL grantEpoch++; state = "unlocked"; void refreshActiveGrants(); + void refreshActiveProviderCredentials(); }, /** Keep access locked until the caller has reconciled the current encrypted * snapshot. The preparation callback can read the transient key, but no @@ -91,6 +103,7 @@ export function createProxyRuntime({ listenerFactory = createAuthenticatedProxyL if (shutdown || locking || state !== "preparing") throw new Error("proxy unlock was interrupted"); state = "unlocked"; await refreshActiveGrants(); + await refreshActiveProviderCredentials(); } catch (error) { unlockMaterial?.fill(0); unlockMaterial = undefined; @@ -148,6 +161,10 @@ export function createProxyRuntime({ listenerFactory = createAuthenticatedProxyL try { const next = await connection.refreshGrants(); if (epoch === grantEpoch && state === "unlocked" && !shutdown && !revokedRuns.has(connection.runId)) listener.replaceGrants(next); + if (typeof connection.refreshProviderCredentials === "function" && typeof listener.replaceProviderCredentials === "function") { + const providers = await connection.refreshProviderCredentials(); + if (epoch === grantEpoch && state === "unlocked" && !shutdown && !revokedRuns.has(connection.runId)) listener.replaceProviderCredentials(providers); + } } catch { // A control-plane outage does not expire established grants. Retry // on the next interval; durable revocation has its own monitor. @@ -157,6 +174,7 @@ export function createProxyRuntime({ listenerFactory = createAuthenticatedProxyL const timer = setInterval(refresh, grantRefreshIntervalMs); timer.unref?.(); grantRefreshTimers.set(listener, timer); + void refreshActiveProviderCredentials(); } return listener; }, diff --git a/packages/credential-proxy/src/tunnel-transport.mjs b/packages/credential-proxy/src/tunnel-transport.mjs index 367014c6..cf2b5962 100644 --- a/packages/credential-proxy/src/tunnel-transport.mjs +++ b/packages/credential-proxy/src/tunnel-transport.mjs @@ -118,10 +118,10 @@ export function createAuthenticatedTunnelServer({ tls, runtime, authenticateEnro /** Start the proxy's production-shaped mTLS listener using its boot-registered * control credential and process-local decrypted integration grants. */ export async function startAuthenticatedProxyTunnel({ - tls, runtime, controlOrigin, controlCredential, resolveGrants, resolveRunCredential, fetchImpl = fetch, host = "127.0.0.1", port = 0, + tls, runtime, controlOrigin, controlCredential, resolveGrants, resolveProviderCredentials, resolveRunCredential, fetchImpl = fetch, host = "127.0.0.1", port = 0, } = {}) { const authenticateRun = createProxyEnrollmentAuthenticator({ - controlOrigin, controlCredential, bootEpoch: runtime?.bootEpoch, resolveGrants, resolveRunCredential, fetchImpl, + controlOrigin, controlCredential, bootEpoch: runtime?.bootEpoch, resolveGrants, resolveProviderCredentials, resolveRunCredential, fetchImpl, }); const tunnel = createAuthenticatedTunnelServer({ tls, runtime, authenticateRun, host, port }); try { diff --git a/packages/credential-proxy/test/control-client.test.mjs b/packages/credential-proxy/test/control-client.test.mjs index 4c95cb85..55dcb356 100644 --- a/packages/credential-proxy/test/control-client.test.mjs +++ b/packages/credential-proxy/test/control-client.test.mjs @@ -49,7 +49,7 @@ test("boot registration uses a one-call control credential, HTTPS, exact path an test("proxy snapshot reader requests only the bound run revision and validates encrypted records", async () => { let request; - const snapshot = { ownerId: "owner-1", records: [{ id: "integration-1", kind: "bearer", origin: "https://api.example", revision: 4, encryptedPayload: "ciphertext" }], modelAccount: { id: "model-1", kind: "model", origin: null, revision: 5, encryptedPayload: "model-ciphertext" } }; + const snapshot = { ownerId: "owner-1", records: [{ id: "integration-1", kind: "bearer", origin: "https://api.example", revision: 4, encryptedPayload: "ciphertext" }], modelAccount: { id: "model-1", kind: "model", origin: null, revision: 5, encryptedPayload: "model-ciphertext" }, providerCredentials: { githubInstallations: [], linearConnection: null } }; const result = await readProxyIntegrationSnapshot({ controlOrigin: "https://factorize.example", token, binding: { runId, grantRevision: 7 }, fetchImpl: async (url, init) => { request = { url: String(url), init, body: JSON.parse(init.body) }; return Response.json(snapshot); @@ -174,6 +174,7 @@ test("proxy enrollment authenticator binds issued and consumed state to the mTLS assert.equal(binding.runId, "33333333-3333-4333-8333-333333333333"); return grants; }, + resolveProviderCredentials: async () => ({ githubInstallations: [], linearConnection: null }), }); const connection = await authenticateRun({ runId, diff --git a/packages/credential-proxy/test/decrypted-grants.test.mjs b/packages/credential-proxy/test/decrypted-grants.test.mjs index 4ac3fac5..5d8dbefd 100644 --- a/packages/credential-proxy/test/decrypted-grants.test.mjs +++ b/packages/credential-proxy/test/decrypted-grants.test.mjs @@ -97,7 +97,7 @@ test("production grant resolver reads the run-bound snapshot and only decrypts w controlCredential: `fzc_${"c".repeat(43)}`, fetchImpl: async (url, init) => { requests.push({ url: String(url), authorization: new Headers(init.headers).get("authorization"), body: JSON.parse(init.body) }); - return Response.json({ ownerId, records: [{ ...record, encryptedPayload }], modelAccount: null }); + return Response.json({ ownerId, records: [{ ...record, encryptedPayload }], modelAccount: null, providerCredentials: { githubInstallations: [], linearConnection: null } }); }, }); const binding = { tenantId: ownerId, runId: "22222222-2222-4222-8222-222222222222", grantRevision: 7 }; diff --git a/packages/credential-proxy/test/fly-guest-helper.e2e.test.mjs b/packages/credential-proxy/test/fly-guest-helper.e2e.test.mjs index b42ecc3a..a02883c1 100644 --- a/packages/credential-proxy/test/fly-guest-helper.e2e.test.mjs +++ b/packages/credential-proxy/test/fly-guest-helper.e2e.test.mjs @@ -97,6 +97,7 @@ test("generated Fly guest helper forwards through identity-bound mTLS and reject runtime, controlOrigin: "https://factorize.example", controlCredential: `fzc_${"c".repeat(43)}`, + resolveProviderCredentials: async () => ({ githubInstallations: [], linearConnection: null }), resolveRunCredential: (id, vmIdentity) => { if (id === crossVmRunId && vmIdentity === "api.example.test") rejectedRunBinding = true; return credentials.resolve(id, vmIdentity); @@ -259,7 +260,7 @@ test("locked scoped run reconnects with its current grant while another VM stays assert.equal(activeRun.vmIdentity, vmIdentity); assert.deepEqual(activeRun.integrationIds, [integrationId]); snapshotReads++; - return Response.json({ ownerId, records: activeRun.integrationIds.includes(record.id) ? [record] : [], modelAccount: null }); + return Response.json({ ownerId, records: activeRun.integrationIds.includes(record.id) ? [record] : [], modelAccount: null, providerCredentials: { githubInstallations: [], linearConnection: null } }); } return Response.json({ error: "not found" }, { status: 404 }); }; @@ -269,6 +270,7 @@ test("locked scoped run reconnects with its current grant while another VM stays tls: { key, cert: proxyCert, ca: cert }, runtime, controlOrigin: "https://factorize.example", controlCredential, resolveGrants, + resolveProviderCredentials: async () => ({ githubInstallations: [], linearConnection: null }), resolveRunCredential: (id, identity) => credentials.resolve(id, identity), fetchImpl: fetchControl, }); diff --git a/packages/credential-proxy/test/proxy-listener.e2e.test.mjs b/packages/credential-proxy/test/proxy-listener.e2e.test.mjs index 2fcc3c0d..fae34d4c 100644 --- a/packages/credential-proxy/test/proxy-listener.e2e.test.mjs +++ b/packages/credential-proxy/test/proxy-listener.e2e.test.mjs @@ -370,6 +370,7 @@ test("VM helper authenticates the active run while the proxy performs authentica runtime, controlOrigin: "https://factorize.example", controlCredential: `fzc_${"c".repeat(43)}`, + resolveProviderCredentials: async () => ({ githubInstallations: [], linearConnection: null }), resolveRunCredential: (id, vmIdentity) => runCredentials.resolve(id, vmIdentity), fetchImpl: async (url, init) => { const body = JSON.parse(init.body); diff --git a/packages/credential-proxy/test/runtime-revocation.test.mjs b/packages/credential-proxy/test/runtime-revocation.test.mjs index 4d5b15bd..a3b171c2 100644 --- a/packages/credential-proxy/test/runtime-revocation.test.mjs +++ b/packages/credential-proxy/test/runtime-revocation.test.mjs @@ -199,6 +199,41 @@ test("connection grant refresh swaps current integrations and tolerates failed p } }); +test("provider credential refresh removes disconnected credentials from an established tunnel", async () => { + let available = true; + const updates = []; + let revoked; + const revokedPromise = new Promise(resolve => { revoked = resolve; }); + const runtime = createProxyRuntime({ + bootEpoch, + grantRefreshIntervalMs: 100, + listenerFactory: async ({ connection: value }) => ({ + connectionId: value.connectionId, + replaceGrants: () => {}, + replaceProviderCredentials: next => { + updates.push(next); + if (next.linearConnection?.available === false) revoked(); + }, + close: async () => {}, + }), + }); + runtime.unlock("synthetic-unlock-key"); + try { + await runtime.acceptAuthenticatedConnection({ + ...connection("run-provider-refresh", "connection-provider-refresh"), + providerCredentials: { githubInstallations: [], linearConnection: { connectionId: "linear", available: true, accessToken: "initial" } }, + refreshGrants: async () => [], + refreshProviderCredentials: async () => ({ githubInstallations: [], linearConnection: { connectionId: "linear", available, ...(available ? { accessToken: "current" } : {}) } }), + }); + available = false; + await revokedPromise; + assert.ok(updates.some(value => value.linearConnection?.accessToken === "current")); + assert.deepEqual(updates.at(-1), { githubInstallations: [], linearConnection: { connectionId: "linear", available: false } }); + } finally { + await runtime.shutdown(); + } +}); + test("a delayed grant refresh cannot restore access after run revocation", async () => { let resolveRefresh; let refreshStarted; From 2efd2d8babcfe68b94407a3c7488d0d74f025674 Mon Sep 17 00:00:00 2001 From: "exe.dev user" Date: Mon, 16 Nov 2026 22:16:06 +0000 Subject: [PATCH 15/28] Route selected run GitHub and Linear requests --- packages/api/test/run-credentials.test.ts | 20 ++++- .../credential-proxy/src/bearer-forwarder.mjs | 8 +- .../credential-proxy/src/proxy-listener.mjs | 83 +++++++++++++++---- .../test/proxy-listener.e2e.test.mjs | 60 +++++++++++++- 4 files changed, 148 insertions(+), 23 deletions(-) diff --git a/packages/api/test/run-credentials.test.ts b/packages/api/test/run-credentials.test.ts index 4068d3f7..e5862085 100644 --- a/packages/api/test/run-credentials.test.ts +++ b/packages/api/test/run-credentials.test.ts @@ -3,11 +3,11 @@ import { authenticateRunCredential, issueRunCredential, RUN_SCOPES } from "../sr describe("run-scoped execution credentials", () => { it("binds a short-lived bearer credential to its active tenant, job, and run", async () => { - let storedDigest = "", active = true; + let storedDigest = "", storedScopes: string[] = [], active = true; const database = { pool: { query: async (sql: string, values: unknown[] = []) => { if (sql.includes("SELECT user_id,session_version")) return { rows: [{ user_id: "owner-1", session_version: 7 }], rowCount: 1 }; - if (sql.includes("INSERT INTO app.run_credentials")) { storedDigest = String(values[2]); return { rows: [], rowCount: 1 }; } - if (sql.includes("FROM app.run_credentials c")) return active && values[1] === storedDigest ? { rows: [{ tenant_id: "tenant-1", user_id: "owner-1", session_version: 7, job_id: "job-1", scopes: RUN_SCOPES }], rowCount: 1 } : { rows: [], rowCount: 0 }; + if (sql.includes("INSERT INTO app.run_credentials")) { storedDigest = String(values[2]); storedScopes = JSON.parse(String(values[6])); return { rows: [], rowCount: 1 }; } + if (sql.includes("FROM app.run_credentials c")) return active && values[1] === storedDigest ? { rows: [{ tenant_id: "tenant-1", user_id: "owner-1", session_version: 7, job_id: "job-1", scopes: storedScopes }], rowCount: 1 } : { rows: [], rowCount: 0 }; throw new Error(`Unexpected SQL: ${sql}`); } } } as any; const env = { DATABASE: database } as any; @@ -22,4 +22,18 @@ describe("run-scoped execution credentials", () => { active = false; expect(await authenticateRunCredential(request(token), env)).toBeNull(); }); + + it("persists the run's configured scope snapshot, including an empty scope set", async () => { + let storedDigest = "", storedScopes: string[] = []; + const database = { pool: { query: async (sql: string, values: unknown[] = []) => { + if (sql.includes("SELECT user_id,session_version")) return { rows: [{ user_id: "owner-1", session_version: 7 }] }; + if (sql.includes("INSERT INTO app.run_credentials")) { storedDigest = String(values[2]); storedScopes = JSON.parse(String(values[6])); return { rows: [] }; } + if (sql.includes("FROM app.run_credentials c")) return values[1] === storedDigest ? { rows: [{ tenant_id: "tenant-1", user_id: "owner-1", session_version: 7, job_id: "job-1", scopes: storedScopes }] } : { rows: [] }; + throw new Error(`Unexpected SQL: ${sql}`); + } } } as any; + const env = { DATABASE: database } as any; + const token = await issueRunCredential(env, "tenant-1", "00000000-0000-4000-8000-000000000002", []); + const request = new Request("https://example.test/api/v1", { headers: { Authorization: `Bearer ${token}` } }); + expect((await authenticateRunCredential(request, env))?.scopes).toEqual([]); + }); }); diff --git a/packages/credential-proxy/src/bearer-forwarder.mjs b/packages/credential-proxy/src/bearer-forwarder.mjs index 37ea1854..52f6715e 100644 --- a/packages/credential-proxy/src/bearer-forwarder.mjs +++ b/packages/credential-proxy/src/bearer-forwarder.mjs @@ -19,7 +19,7 @@ const HOP_BY_HOP = new Set([ "content-length", "expect", ]); -function safeHeaders(input, credential, maxBytes) { +function safeHeaders(input, credential, maxBytes, authorization = "bearer") { const source = input instanceof Headers ? [...input.entries()] : Object.entries(input ?? {}); const connectionTokens = new Set(); for (const [name, value] of source) { @@ -37,7 +37,9 @@ function safeHeaders(input, credential, maxBytes) { if (size > maxBytes) throw new RangeError("request headers exceed configured limit"); headers[lower] = text; } - headers.authorization = `Bearer ${credential}`; + headers.authorization = authorization === "github-git-basic" + ? `Basic ${Buffer.from(`x-access-token:${credential}`).toString("base64")}` + : `Bearer ${credential}`; return headers; } @@ -160,7 +162,7 @@ export function createBearerForwarder({ connectorFactory = createOriginConnector } const method = String(input.method ?? "GET").toUpperCase(); if (!/^[A-Z!#$%&'*+.^_`|~-]+$/.test(method)) throw new TypeError("invalid HTTP method"); - const headers = safeHeaders(input.headers, integration.credential, limits.headerBytes); + const headers = safeHeaders(input.headers, integration.credential, limits.headerBytes, integration.authorization); const result = await request({ socket, url, method, headers, body: input.body, limits, signal: controller.signal }); if (result?.body && typeof result.body.once === "function") { result.body.once("end", release); diff --git a/packages/credential-proxy/src/proxy-listener.mjs b/packages/credential-proxy/src/proxy-listener.mjs index 009b65db..6c714241 100644 --- a/packages/credential-proxy/src/proxy-listener.mjs +++ b/packages/credential-proxy/src/proxy-listener.mjs @@ -38,6 +38,39 @@ function requestTarget(origin, suffix, search) { return `${base.origin}${path}${search}`; } +function githubCredential(credentials, installationId) { + if (!/^\d{1,20}$/.test(installationId)) return null; + const selected = credentials.githubInstallations.find(item => String(item.installationId) === installationId); + return selected?.available && typeof selected.accessToken === "string" && selected.accessToken + ? { origin: "https://api.github.com", credential: selected.accessToken, authorization: "bearer" } + : null; +} + +function isGitSmartHttp(path, search) { + return (path.endsWith("/info/refs") && /(?:^|[?&])service=git-(?:upload|receive)-pack(?:&|$)/.test(search)) + || /\.git\/git-(?:upload|receive)-pack$/.test(path); +} + +function providerRoute(pathname, search, credentials) { + const github = /^\/providers\/github\/([^/]+)(\/.*)?$/.exec(pathname); + if (github) { + let installationId; + try { installationId = decodeURIComponent(github[1]); } catch { return { error: 400 }; } + const selected = githubCredential(credentials, installationId); + if (!selected) return { error: 403 }; + const suffix = github[2] ?? "/"; + const git = isGitSmartHttp(suffix, search); + return { ...selected, origin: git ? "https://github.com" : selected.origin, + path: suffix, authorization: git ? "github-git-basic" : "bearer" }; + } + if (/^\/providers\/linear(?:\/|$)/.test(pathname)) { + const selected = credentials.linearConnection; + if (!selected?.available || typeof selected.accessToken !== "string" || !selected.accessToken) return { error: 403 }; + return { origin: "https://api.linear.app", credential: selected.accessToken, authorization: "bearer", path: pathname.slice("/providers/linear".length) || "/" }; + } + return null; +} + /** * Start one loopback HTTP endpoint for a single already-authenticated tunnel * connection. The connection's consumed grants are held in this closure and @@ -82,34 +115,52 @@ export async function createAuthenticatedProxyListener({ connection, forwarder = availability: unlocked ? "available" : "locked", }; }); + const providers = unlocked ? { + githubInstallations: providerCredentials.githubInstallations.filter(item => item.available).map(item => ({ installationId: item.installationId, endpoint: `/providers/github/${item.installationId}/` })), + linear: providerCredentials.linearConnection?.available ? { endpoint: "/providers/linear/" } : null, + } : { githubInstallations: [], linear: null }; response.writeHead(200, { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" }); - response.end(JSON.stringify({ state: unlocked ? "unlocked" : "locked", integrations })); + response.end(JSON.stringify({ state: unlocked ? "unlocked" : "locked", integrations, providers })); return; } if (!unlocked) { response.writeHead(423, { "cache-control": "no-store" }).end(); return; } - const match = /^\/integrations\/([^/]+)(\/.*)?$/.exec(parsed.pathname); - if (!match) { - response.writeHead(404).end(); - return; - } - let integrationId; - try { integrationId = decodeURIComponent(match[1]); } catch { - response.writeHead(400).end(); - return; - } - if (!integrationId || integrationId.includes("/") || integrationId.includes("\\")) { - response.writeHead(400).end(); - return; + const provider = providerRoute(parsed.pathname, parsed.search, providerCredentials); + let integration; + let suffix; + if (provider) { + if (provider.error) { response.writeHead(provider.error).end(); return; } + integration = provider; + suffix = provider.path; + } else { + const match = /^\/integrations\/([^/]+)(\/.*)?$/.exec(parsed.pathname); + if (!match) { + response.writeHead(404).end(); + return; + } + let integrationId; + try { integrationId = decodeURIComponent(match[1]); } catch { + response.writeHead(400).end(); + return; + } + if (!integrationId || integrationId.includes("/") || integrationId.includes("\\")) { + response.writeHead(400).end(); + return; + } + integration = grants.get(integrationId); + suffix = match[2] ?? "/"; } - const integration = grants.get(integrationId); if (!integration) { response.writeHead(403).end(); return; } - const target = requestTarget(integration.origin, match[2] ?? "/", parsed.search); + if (!unlocked) { + response.writeHead(404).end(); + return; + } + const target = requestTarget(integration.origin, suffix, parsed.search); const result = await forwarder.forward(integration, { url: target, method: request.method, diff --git a/packages/credential-proxy/test/proxy-listener.e2e.test.mjs b/packages/credential-proxy/test/proxy-listener.e2e.test.mjs index fae34d4c..f59f0110 100644 --- a/packages/credential-proxy/test/proxy-listener.e2e.test.mjs +++ b/packages/credential-proxy/test/proxy-listener.e2e.test.mjs @@ -1,5 +1,6 @@ import assert from "node:assert/strict"; import { readFile } from "node:fs/promises"; +import { Readable } from "node:stream"; import { createServer as createHttpsServer } from "node:https"; import { once } from "node:events"; import { connect as tlsConnect } from "node:tls"; @@ -129,6 +130,63 @@ test("authenticated tunnel listener streams over TLS, confines grants and cancel } }); +test("provider routes use only selected run credentials and choose Git smart HTTP auth while streaming", { timeout: 5_000 }, async () => { + const seen = []; + const forwarder = createBearerForwarder({ + connectorFactory: () => async requestUrl => ({ socket: { destroy() {} }, url: new URL(requestUrl) }), + request: async ({ socket, url, headers, body }) => { + const chunks = []; + for await (const chunk of body ?? []) chunks.push(Buffer.from(chunk)); + seen.push({ origin: url.origin, authorization: headers.authorization, path: url.pathname, search: url.search, body: Buffer.concat(chunks).toString() }); + return { status: 200, headers: { "content-type": "text/plain" }, body: Readable.from(["first", "second"]) }; + }, + }); + const runtime = createProxyRuntime({ listenerFactory: ({ connection }) => createAuthenticatedProxyListener({ connection, forwarder }) }); + let listener; + try { + runtime.unlock("synthetic-unlock-key"); + listener = await runtime.acceptAuthenticatedConnection({ + authenticated: true, enrollmentConsumed: true, bootEpoch: runtime.bootEpoch, + connectionId: "provider-route-connection", runId: "provider-route-run", vmId: "provider-route-vm", + grants: [], + providerCredentials: { githubInstallations: [ + { installationId: 42, available: true, accessToken: "github-selected-token" }, + { installationId: 43, available: false }, + ], linearConnection: { connectionId: "linear", available: true, accessToken: "linear-selected-token" } }, + }); + const base = `http://127.0.0.1:${listener.address.port}`; + const inventory = await (await fetch(`${base}/integrations`)).json(); + assert.deepEqual(inventory.providers, { + githubInstallations: [{ installationId: 42, endpoint: "/providers/github/42/" }], + linear: { endpoint: "/providers/linear/" }, + }); + const git = await fetch(`${base}/providers/github/42/owner/repo.git/info/refs?service=git-upload-pack`, { + headers: { authorization: "Bearer guest-controlled", "git-protocol": "version=2" }, + }); + assert.equal(await git.text(), "firstsecond"); + const githubApi = await fetch(`${base}/providers/github/42/user`, { headers: { authorization: "Bearer guest-controlled" } }); + assert.equal(await githubApi.text(), "firstsecond"); + const linear = await fetch(`${base}/providers/linear/graphql?operation=Query`, { + method: "POST", headers: { authorization: "Bearer guest-controlled" }, body: "{ viewer { id } }", + }); + assert.equal(await linear.text(), "firstsecond"); + assert.equal((await fetch(`${base}/providers/github/43/user`)).status, 403); + assert.deepEqual(seen.map(item => [item.origin, item.authorization, item.path, item.search]), [ + ["https://github.com", "Basic eC1hY2Nlc3MtdG9rZW46Z2l0aHViLXNlbGVjdGVkLXRva2Vu", "/owner/repo.git/info/refs", "?service=git-upload-pack"], + ["https://api.github.com", "Bearer github-selected-token", "/user", ""], + ["https://api.linear.app", "Bearer linear-selected-token", "/graphql", "?operation=Query"], + ]); + assert.equal(seen[0].body, ""); + listener.replaceProviderCredentials({ githubInstallations: [{ installationId: 42, available: false }], linearConnection: { connectionId: "linear", available: false } }); + assert.equal((await fetch(`${base}/providers/github/42/user`)).status, 403); + assert.equal((await fetch(`${base}/providers/linear/graphql`)).status, 403); + assert.equal(seen.length, 3, "revoked credentials never reach an upstream request"); + } finally { + if (listener) await runtime.disconnect("provider-route-connection"); + await runtime.shutdown(); + } +}); + test("reflection exposes safe metadata for only the authenticated VM connection and tracks live grant changes", { timeout: 5_000 }, async () => { const runtime = createProxyRuntime(); const connections = []; @@ -182,7 +240,7 @@ test("reflection exposes safe metadata for only the authenticated VM connection await runtime.lock(); const locked = await reflect(first); - assert.deepEqual(locked, { state: "locked", integrations: [ + assert.deepEqual(locked, { state: "locked", providers: { githubInstallations: [], linear: null }, integrations: [ { id: "selected-2", source: "portable", name: "Metrics API", description: "current help", endpoint: "/integrations/selected-2/", example: 'curl "$FACTORIZE_PROXY_URL/integrations/selected-2/"', availability: "locked" }, ] }); assert.equal((await fetch(`http://127.0.0.1:${first.address.port}/integrations/selected-2/`)).status, 423); From 0a49490d05d5949d19c5c4965a054e2b57d7d140 Mon Sep 17 00:00:00 2001 From: "exe.dev user" Date: Mon, 16 Nov 2026 22:33:07 +0000 Subject: [PATCH 16/28] Route selected model requests through active run proxy --- packages/api/src/agent-driver.ts | 15 +++++- packages/api/src/postgres/run-scheduler.ts | 8 ++- packages/api/src/proxy-control.ts | 4 +- packages/api/src/run-credentials.ts | 9 +++- packages/api/test/agent-driver.test.ts | 10 ++++ packages/api/test/proxy-control.test.ts | 14 +++++ .../credential-proxy/src/control-client.mjs | 5 +- .../credential-proxy/src/decrypted-grants.mjs | 19 +++++++ packages/credential-proxy/src/main.mjs | 4 +- .../src/model-account-lifecycle.mjs | 27 ++++++++++ .../credential-proxy/src/proxy-listener.mjs | 21 ++++++-- packages/credential-proxy/src/runtime.mjs | 4 ++ .../credential-proxy/src/tunnel-transport.mjs | 4 +- .../test/model-account-lifecycle.test.mjs | 15 ++++++ .../test/proxy-listener.e2e.test.mjs | 30 ++++++++--- .../test/runtime-revocation.test.mjs | 51 +++++++++++++++++++ 16 files changed, 219 insertions(+), 21 deletions(-) diff --git a/packages/api/src/agent-driver.ts b/packages/api/src/agent-driver.ts index 1e0fe6c2..adf4255f 100644 --- a/packages/api/src/agent-driver.ts +++ b/packages/api/src/agent-driver.ts @@ -4,7 +4,7 @@ import type { TraceSources } from "./trace-source"; import { JOB_RESULT_PATH } from "./job-result"; export type AgentKind = "codex" | "claude" | "pi"; -export interface AgentConfiguration { model?: string; effort?: string; codexModel?: { baseUrl: string; providerName?: string }; } +export interface AgentConfiguration { model?: string; effort?: string; codexModel?: { baseUrl: string; providerName?: string }; providerEndpoints?: { githubInstallationIds?: number[]; linear?: boolean; model?: boolean }; } export interface ArtifactLocator { /** Paths are interpreted inside the guest; the compute backend only transports files. */ roots: string[]; @@ -73,9 +73,20 @@ class PiDriver implements AgentDriver { } const drivers: Record = { codex: new CodexDriver(), claude: new ClaudeDriver(), pi: new PiDriver() }; +function providerEndpointEnv(config: AgentConfiguration): Record { + const proxy = "http://127.0.0.1:18180"; + const installations = [...new Set(config.providerEndpoints?.githubInstallationIds ?? [])] + .filter(id => Number.isSafeInteger(id) && id > 0) + .map(installationId => ({ installationId, apiUrl: `${proxy}/providers/github/${installationId}/`, gitUrl: `${proxy}/providers/github/${installationId}/` })); + return { + ...(installations.length ? { FACTORIZE_GITHUB_INSTALLATIONS: JSON.stringify(installations) } : {}), + ...(config.providerEndpoints?.linear ? { FACTORIZE_LINEAR_API_URL: `${proxy}/providers/linear/` } : {}), + ...(config.providerEndpoints?.model ? { FACTORIZE_MODEL_API_URL: `${proxy}/providers/model/v1` } : {}), + }; +} export function agentDriver(kind: AgentKind): AgentDriver { const driver = drivers[kind]; - return { kind, launch(runId, config) { const spec = driver.launch(runId, config); return { ...spec, env: { ...spec.env, FACTORIZE_RESULT_PATH: JOB_RESULT_PATH }, traceSources: driverTraceSources(kind, spec) }; } }; + return { kind, launch(runId, config) { const spec = driver.launch(runId, config); return { ...spec, env: { ...spec.env, ...providerEndpointEnv(config), FACTORIZE_RESULT_PATH: JOB_RESULT_PATH }, traceSources: driverTraceSources(kind, spec) }; } }; } /** Compatibility for drivers and historical runs that only declare native sessions. */ diff --git a/packages/api/src/postgres/run-scheduler.ts b/packages/api/src/postgres/run-scheduler.ts index f94e7d9c..51a0874e 100644 --- a/packages/api/src/postgres/run-scheduler.ts +++ b/packages/api/src/postgres/run-scheduler.ts @@ -197,14 +197,18 @@ export class RunScheduler { return; } if (run.executionConfig.agentKind === "Amp") throw new Error("Amp execution is unavailable for new runs because it cannot deliver the required structured result file. Choose an exe.dev agent integration."); - const backend = await this.backend(run), driver = agentDriver(run.executionConfig.agentKind as AgentKind), harness = driver.launch(run.id, { model: run.executionConfig.model, effort: run.executionConfig.effort, ...(driver.kind === "codex" ? { codexModel: { baseUrl: this.env.CODEX_MODEL_BASE_URL ?? "https://llm.int.exe.xyz/v1" } } : {}) }); + const backend = await this.backend(run), driver = agentDriver(run.executionConfig.agentKind as AgentKind), harness = driver.launch(run.id, { + model: run.executionConfig.model, effort: run.executionConfig.effort, + providerEndpoints: { githubInstallationIds: run.executionConfig.githubInstallationIds ?? [], linear: run.executionConfig.linearConnectionId === "linear", model: run.executionConfig.modelAccess === "portable" && Boolean(run.executionConfig.modelAccountId) }, + ...(driver.kind === "codex" ? { codexModel: { baseUrl: run.executionConfig.modelAccess === "portable" && run.executionConfig.modelAccountId ? "http://127.0.0.1:18180/providers/model/v1" : this.env.CODEX_MODEL_BASE_URL ?? "https://llm.int.exe.xyz/v1" } } : {}), + }); const sources = rolloutTraceSources(driverTraceSources(driver.kind, harness), run.tenantId, this.env); validateTraceSources(sources); const runToken = await issueRunCredential(this.env, run.tenantId, run.id, run.executionConfig.runScopes); const prompt = await decrypt(run.encryptedPrompt, this.env.CREDENTIAL_ENCRYPTION_KEY); const reservation = backend.reserve?.(run.id) ?? null; if (reservation) await this.runs.recordLaunchHandle(run, reservation); - const launched = await backend.launch({ runId: run.id, reservation: reservation ?? undefined, prompt: `${prompt}${JOB_RESULT_INSTRUCTIONS}${runProxyInstructions(run.id)}`, runProxy: { targetOrigin: this.env.APP_ORIGIN, credential: runToken }, traceSources: sources, harness: { executable: harness.executable, args: harness.args, env: harness.env }, verifyVendorIdentity: this.vendorIdentityVerifier(run) }); + const launched = await backend.launch({ runId: run.id, reservation: reservation ?? undefined, prompt: `${prompt}${JOB_RESULT_INSTRUCTIONS}${runProxyInstructions(run.id, { githubInstallationIds: run.executionConfig.githubInstallationIds ?? [], linear: run.executionConfig.linearConnectionId === "linear", model: run.executionConfig.modelAccess === "portable" && Boolean(run.executionConfig.modelAccountId) })}`, runProxy: { targetOrigin: this.env.APP_ORIGIN, credential: runToken }, traceSources: sources, harness: { executable: harness.executable, args: harness.args, env: harness.env }, verifyVendorIdentity: this.vendorIdentityVerifier(run) }); await this.runs.markLaunched(run, launched.handle, launched.destinationUrl, launched.capabilities, sources); if (launched.observation.state === "failed") await this.runs.recordObservation(run, launched.observation); } diff --git a/packages/api/src/proxy-control.ts b/packages/api/src/proxy-control.ts index 31a33ccd..b55128aa 100644 --- a/packages/api/src/proxy-control.ts +++ b/packages/api/src/proxy-control.ts @@ -140,7 +140,9 @@ export async function proxyControlFetch(request: Request, env: Parameters record.id === modelAccountId) ?? null; - if (!modelAccount) return json({ error: "integration_snapshot_unavailable" }, 403); + // A deleted selected account is a revocation signal for an already-open + // run tunnel. Preserve the active run snapshot with a null account so the + // proxy replaces its model credential with an unavailable state. } else if (modelAccess !== "native" || modelAccountId !== undefined) { return json({ error: "integration_snapshot_unavailable" }, 403); } diff --git a/packages/api/src/run-credentials.ts b/packages/api/src/run-credentials.ts index 1a7c7b06..a809d5b4 100644 --- a/packages/api/src/run-credentials.ts +++ b/packages/api/src/run-credentials.ts @@ -12,8 +12,13 @@ export function runProxyName(runId: string): string { return `fz-run-${runId.toLowerCase()}`; } -export function runProxyInstructions(runId: string): string { - return `\n\n## Factorize access\nThis run's complete Factorize proxy origin is https://${runProxyName(runId)}.int.exe.xyz. Preserve the entire hostname, including .int.exe.xyz. Discover the ${runProxyName(runId)} integration in https://reflection.int.exe.xyz/integrations and use the proxy URL in its help text for all Factorize /api/v1 requests, replacing any shared Factorize hostname mentioned in the task or job template. exe.dev injects this run's credential outside the VM; do not supply Authorization headers or look for tokens in the environment. GET /api/v1/runtime-context through this proxy to verify your identity and discover your effective scopes. Only perform operations permitted by those scopes. Job-to-job invocation also requires explicit destination authorization. A granted jobs:write permits editing jobs and their run scopes for future runs; never assume a write is unavailable merely because this is a run proxy. If an optional bookkeeping operation is unavailable, continue implementation and report that limitation. Use FACTORIZE_RESULT_PATH to report the final outcome.\n`; +export function runProxyInstructions(runId: string, providers: { githubInstallationIds?: number[]; linear?: boolean; model?: boolean } = {}): string { + const github = [...new Set(providers.githubInstallationIds ?? [])].filter(id => Number.isSafeInteger(id) && id > 0) + .map(id => `${id}: http://127.0.0.1:18180/providers/github/${id}/`).join(", "); + const selectedProviders = [github ? `selected GitHub installation endpoints: ${github} (REST/GraphQL and Git smart HTTP)` : "", + providers.linear ? "selected Linear endpoint: http://127.0.0.1:18180/providers/linear/ (GraphQL)" : "", + providers.model ? "selected model endpoint: http://127.0.0.1:18180/providers/model/v1 (Codex Responses; already configured for Codex)" : ""].filter(Boolean).join("\n"); + return `\n\n## Factorize access\nThis run's complete Factorize proxy origin is https://${runProxyName(runId)}.int.exe.xyz. Preserve the entire hostname, including .int.exe.xyz. Discover the ${runProxyName(runId)} integration in https://reflection.int.exe.xyz/integrations and use the proxy URL in its help text for all Factorize /api/v1 requests, replacing any shared Factorize hostname mentioned in the task or job template. exe.dev injects this run's credential outside the VM; do not supply Authorization headers or look for tokens in the environment. GET /api/v1/runtime-context through this proxy to verify your identity and discover your effective scopes. Only perform operations permitted by those scopes. Job-to-job invocation also requires explicit destination authorization. A granted jobs:write permits editing job configuration and future run scopes; never assume a write is unavailable merely because this is a run proxy. If an optional bookkeeping operation is unavailable, continue implementation and report that limitation. Use FACTORIZE_PROXY_URL for authenticated outbound integration requests and the endpoint variables supplied to your agent for selected providers. Never access provider APIs directly when a selected endpoint is available. Use FACTORIZE_RESULT_PATH to report the final outcome.${selectedProviders ? `\n\n## Selected provider clients\n${selectedProviders}\nThe run proxy injects credentials server-side. Clients must not supply or cache provider credentials. Use only these listed endpoints for the selected connections.` : ""}\n`; } const encode = (value: string) => btoa(String.fromCharCode(...new TextEncoder().encode(value))).replaceAll("+", "-").replaceAll("/", "_").replaceAll("=", ""); diff --git a/packages/api/test/agent-driver.test.ts b/packages/api/test/agent-driver.test.ts index b6e34a5b..ec59930f 100644 --- a/packages/api/test/agent-driver.test.ts +++ b/packages/api/test/agent-driver.test.ts @@ -10,4 +10,14 @@ describe("agent drivers", () => { it("keeps transport details out of every driver", () => { for (const kind of ["codex", "claude", "pi"] as const) expect(JSON.stringify(agentDriver(kind).launch("run-1", {}))).not.toContain("ssh"); }); + it("passes only selected listener endpoints to provider clients", () => { + const launch = agentDriver("codex").launch("run-1", { providerEndpoints: { githubInstallationIds: [42, 43, 42], linear: true, model: true } }); + expect(JSON.parse(launch.env.FACTORIZE_GITHUB_INSTALLATIONS!)).toEqual([ + { installationId: 42, apiUrl: "http://127.0.0.1:18180/providers/github/42/", gitUrl: "http://127.0.0.1:18180/providers/github/42/" }, + { installationId: 43, apiUrl: "http://127.0.0.1:18180/providers/github/43/", gitUrl: "http://127.0.0.1:18180/providers/github/43/" }, + ]); + expect(launch.env.FACTORIZE_LINEAR_API_URL).toBe("http://127.0.0.1:18180/providers/linear/"); + expect(launch.env.FACTORIZE_MODEL_API_URL).toBe("http://127.0.0.1:18180/providers/model/v1"); + expect(JSON.stringify(launch.env)).not.toMatch(/token|secret|credential/i); + }); }); diff --git a/packages/api/test/proxy-control.test.ts b/packages/api/test/proxy-control.test.ts index 356a1e0c..a146545a 100644 --- a/packages/api/test/proxy-control.test.ts +++ b/packages/api/test/proxy-control.test.ts @@ -188,6 +188,20 @@ describe("dedicated proxy boot registration endpoint", () => { expect(env.query.mock.calls.map((call: any[]) => call[0])).toEqual(expect.arrayContaining([expect.stringContaining("grant_revision=$5"), expect.stringContaining("FROM app.integration_records")])); }); + it("returns a null model selection when the active run's selected account was disconnected", async () => { + const env = envFor(); + env.query.mockImplementation(async (sql: string) => { + if (sql.includes("SELECT user_id FROM app.members")) return { rows: [{ user_id: "11111111-1111-4111-8111-111111111111" }], rowCount: 1 }; + if (sql.includes("proxy_token_digest")) return { rows: [{ tenant_id: "11111111-1111-4111-8111-111111111111", proxy_identity: "proxy-fixture", boot_epoch: bootEpoch }], rowCount: 1 }; + if (sql.includes("FROM app.runs r")) return { rows: [{ execution_config: { portableIntegrationIds: [], modelAccess: "portable", modelAccountId: "77777777-7777-4777-8777-777777777777", githubInstallationIds: [] }, grant_revision: 3 }], rowCount: 1 }; + if (sql.includes("FROM app.integration_records")) return { rows: [], rowCount: 0 }; + return { rows: [], rowCount: 0 }; + }); + const response = await proxyControlFetch(request({ authorization: `Bearer ${token}`, path: "/internal/credential-proxy/integration-snapshot", body: { runId, grantRevision: 3 } }), env); + expect(response.status).toBe(200); + expect(await response.json()).toMatchObject({ modelAccount: null, providerCredentials: { githubInstallations: [], linearConnection: null } }); + }); + it("returns durable revoked runs only for the authenticated current proxy boot", async () => { const env = envFor(); env.query.mockImplementation(async (sql: string) => sql.includes("proxy_token_digest") diff --git a/packages/credential-proxy/src/control-client.mjs b/packages/credential-proxy/src/control-client.mjs index 61092f2e..1c3922ab 100644 --- a/packages/credential-proxy/src/control-client.mjs +++ b/packages/credential-proxy/src/control-client.mjs @@ -248,7 +248,7 @@ const uuidPattern = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{1 * using its private control credential. Provider credentials are returned * only to this process over the control channel and are never sent to the VM. */ -export function createProxyEnrollmentAuthenticator({ controlOrigin, controlCredential, bootEpoch, resolveGrants, resolveProviderCredentials, resolveRunCredential, fetchImpl = fetch } = {}) { +export function createProxyEnrollmentAuthenticator({ controlOrigin, controlCredential, bootEpoch, resolveGrants, resolveProviderCredentials, resolveModelCredentials, resolveRunCredential, fetchImpl = fetch } = {}) { if (!/^fzc_[A-Za-z0-9_-]{43}$/.test(controlCredential ?? "")) throw new TypeError("invalid proxy control credential"); if (!bootEpochPattern.test(bootEpoch ?? "")) throw new TypeError("invalid proxy boot epoch"); if (typeof resolveGrants !== "function" || typeof resolveProviderCredentials !== "function" || typeof resolveRunCredential !== "function") throw new TypeError("proxy enrollment requires local credential resolvers"); @@ -272,6 +272,7 @@ export function createProxyEnrollmentAuthenticator({ controlOrigin, controlCrede if (!Array.isArray(grants)) throw new Error("proxy grants are unavailable"); const providerCredentials = await resolveProviderCredentials(binding); if (!providerCredentials || !Array.isArray(providerCredentials.githubInstallations)) throw new Error("provider credentials are unavailable"); + const modelCredentials = resolveModelCredentials ? await resolveModelCredentials(binding) : { available: false }; return { authenticated: true, enrollmentConsumed: true, @@ -287,6 +288,8 @@ export function createProxyEnrollmentAuthenticator({ controlOrigin, controlCrede refreshGrants: () => resolveGrants(binding), providerCredentials, refreshProviderCredentials: () => resolveProviderCredentials(binding), + modelCredentials, + ...(resolveModelCredentials ? { refreshModelCredentials: () => resolveModelCredentials(binding) } : {}), }; }; } diff --git a/packages/credential-proxy/src/decrypted-grants.mjs b/packages/credential-proxy/src/decrypted-grants.mjs index 5a3fb668..f3e80138 100644 --- a/packages/credential-proxy/src/decrypted-grants.mjs +++ b/packages/credential-proxy/src/decrypted-grants.mjs @@ -148,6 +148,25 @@ export function createProxyProviderCredentialResolver({ controlOrigin, controlCr return async binding => (await readProxyIntegrationSnapshot({ controlOrigin, token: controlCredential, binding, fetchImpl })).providerCredentials; } +/** Resolve the one model account selected by this still-active run. The token + * is read only from the proxy's private Codex auth home; encrypted account + * data and credentials never cross into the guest VM. */ +export function createProxyModelCredentialResolver({ controlOrigin, controlCredential, getAccessCredential, fetchImpl = fetch } = {}) { + if (typeof controlOrigin !== "string" || !/^fzc_[A-Za-z0-9_-]{43}$/.test(controlCredential ?? "") + || typeof getAccessCredential !== "function") throw new TypeError("model credential resolver requires the registered proxy identity"); + return async binding => { + const snapshot = await readProxyIntegrationSnapshot({ controlOrigin, token: controlCredential, binding, fetchImpl }); + const account = snapshot.modelAccount; + if (!account) return { available: false }; + if (account.kind !== "model" || typeof account.id !== "string" || typeof account.encryptedPayload !== "string" + || !account.encryptedPayload.startsWith("factorize-managed-model-cache-v1:")) return { available: false }; + const credential = await getAccessCredential(account.id); + return credential?.available === true && typeof credential.accessToken === "string" && credential.accessToken + ? { available: true, accountId: credential.accountId, accessToken: credential.accessToken } + : { available: false }; + }; +} + /** Verify the current user-encrypted generation before opening access. */ export async function verifyProxyUnlockKey(key, record) { const envelope = JSON.parse(record.encryptedVerification); diff --git a/packages/credential-proxy/src/main.mjs b/packages/credential-proxy/src/main.mjs index e12706b6..8716b936 100644 --- a/packages/credential-proxy/src/main.mjs +++ b/packages/credential-proxy/src/main.mjs @@ -8,7 +8,7 @@ import { randomUUID } from "node:crypto"; import { createProxyRuntime } from "./runtime.mjs"; import { registerProxyBoot, startProxyRunRevocationMonitor, startProxyRuntimeStatusReporter } from "./control-client.mjs"; import { startProxyBootstrapControl } from "./bootstrap-control.mjs"; -import { createProxyIntegrationGrantResolver, createProxyProviderCredentialResolver } from "./decrypted-grants.mjs"; +import { createProxyIntegrationGrantResolver, createProxyProviderCredentialResolver, createProxyModelCredentialResolver } from "./decrypted-grants.mjs"; import { startAuthenticatedProxyTunnel } from "./tunnel-transport.mjs"; import { createProxyTlsAuthority } from "./tls-identity.mjs"; import { createCodexAuthHelper } from "./codex-auth-helper.mjs"; @@ -79,6 +79,7 @@ async function activateRegistration(registration, origin, browserOrigin) { }); const resolveGrants = createProxyIntegrationGrantResolver({ runtime, controlOrigin: origin, controlCredential: registration.controlCredential }); const resolveProviderCredentials = createProxyProviderCredentialResolver({ controlOrigin: origin, controlCredential: registration.controlCredential }); + const resolveModelCredentials = createProxyModelCredentialResolver({ controlOrigin: origin, controlCredential: registration.controlCredential, getAccessCredential: modelAccountLifecycle.getAccessCredential }); const started = await startAuthenticatedProxyTunnel({ tls: tlsAuthority.tls, runtime, @@ -86,6 +87,7 @@ async function activateRegistration(registration, origin, browserOrigin) { controlCredential: registration.controlCredential, resolveGrants, resolveProviderCredentials, + resolveModelCredentials, resolveRunCredential: (runId, vmIdentity) => runCredentials.resolve(runId, vmIdentity), host: process.env.FACTORIZE_PROXY_TUNNEL_HOST ?? "0.0.0.0", port: tunnelPort, diff --git a/packages/credential-proxy/src/model-account-lifecycle.mjs b/packages/credential-proxy/src/model-account-lifecycle.mjs index 0692ed3e..04a35867 100644 --- a/packages/credential-proxy/src/model-account-lifecycle.mjs +++ b/packages/credential-proxy/src/model-account-lifecycle.mjs @@ -47,6 +47,7 @@ export function createModelAccountLifecycle({ const generations = new Map(); const queues = new Map(); const unsaved = new Set(); + const lastCredentialRefresh = new Map(); const currentGeneration = id => generations.get(id) ?? 0; function serialize(id, operation) { @@ -162,6 +163,7 @@ export function createModelAccountLifecycle({ await authHelper.invoke({ method: "logout", accountId: id }).catch(() => {}); await removeCache(resolve(accountHomeRoot, id), { recursive: true, force: true }); unsaved.delete(id); + lastCredentialRefresh.delete(id); onUnsaved({ accountId: id, unsaved: false }); return { state: "deleted" }; }); @@ -202,11 +204,35 @@ export function createModelAccountLifecycle({ return { state: "restored", revision: saved.revision }; } + async function getAccessCredential(id) { + const account = await getAccount(id); + if (!account || account.id !== id || account.kind !== "model") return { available: false }; + let plain; + try { + const refreshedAt = lastCredentialRefresh.get(id) ?? 0; + if (Date.now() - refreshedAt >= 60_000) { + lastCredentialRefresh.set(id, Date.now()); + let refreshed; + try { refreshed = await refresh(id); } catch { return { available: false }; } + if (refreshed.state === "reauthentication-required" || refreshed.state === "deleted") return { available: false }; + } + plain = await readCache(cachePath(accountHomeRoot, id)); + if (!Buffer.isBuffer(plain) || plain.byteLength === 0 || plain.byteLength > 65_536) return { available: false }; + const auth = JSON.parse(plain.toString("utf8")); + const accessToken = auth?.tokens?.access_token; + if (typeof accessToken !== "string" || !accessToken || accessToken.length > 16_384) return { available: false }; + const accountId = auth?.tokens?.account_id ?? auth?.tokens?.chatgpt_account_id; + return { available: true, accessToken, ...(typeof accountId === "string" && accountId.length <= 512 ? { accountId } : {}) }; + } catch { return { available: false }; } + finally { plain?.fill(0); } + } + async function reconcile(id) { return serialize(id, async () => { if (!await getAccount(id)) { await removeCache(resolve(accountHomeRoot, id), { recursive: true, force: true }); unsaved.delete(id); + lastCredentialRefresh.delete(id); return { state: "deleted" }; } if (getEncryptedCache) { @@ -224,6 +250,7 @@ export function createModelAccountLifecycle({ refresh, deleteAccount, restore, + getAccessCredential, reconcile, isUnsaved: id => unsaved.has(id), /** Remove local auth homes as soon as a server-side disconnect is observed. */ diff --git a/packages/credential-proxy/src/proxy-listener.mjs b/packages/credential-proxy/src/proxy-listener.mjs index 6c714241..bb768480 100644 --- a/packages/credential-proxy/src/proxy-listener.mjs +++ b/packages/credential-proxy/src/proxy-listener.mjs @@ -52,6 +52,14 @@ function isGitSmartHttp(path, search) { } function providerRoute(pathname, search, credentials) { + const model = /^\/providers\/model\/v1(?:\/(.*))?$/.exec(pathname); + if (model) { + const selected = credentials.modelAccount; + if (!selected?.available || typeof selected.accessToken !== "string" || !selected.accessToken) return { error: 403 }; + const accountId = typeof selected.accountId === "string" ? selected.accountId : null; + return { origin: "https://chatgpt.com", credential: selected.accessToken, authorization: "bearer", + path: `/backend-api/codex/${model[1] ?? ""}`, ...(accountId ? { extraHeaders: { "chatgpt-account-id": accountId } } : {}) }; + } const github = /^\/providers\/github\/([^/]+)(\/.*)?$/.exec(pathname); if (github) { let installationId; @@ -83,6 +91,7 @@ export async function createAuthenticatedProxyListener({ connection, forwarder = } let grants = grantTable(connection.grants); let providerCredentials = connection.providerCredentials ?? { githubInstallations: [], linearConnection: null }; + let modelCredentials = connection.modelCredentials ?? { available: false }; let unlocked = true; let lockedMetadata = []; const controllers = new Set(); @@ -118,7 +127,8 @@ export async function createAuthenticatedProxyListener({ connection, forwarder = const providers = unlocked ? { githubInstallations: providerCredentials.githubInstallations.filter(item => item.available).map(item => ({ installationId: item.installationId, endpoint: `/providers/github/${item.installationId}/` })), linear: providerCredentials.linearConnection?.available ? { endpoint: "/providers/linear/" } : null, - } : { githubInstallations: [], linear: null }; + model: modelCredentials.available ? { endpoint: "/providers/model/v1/" } : null, + } : { githubInstallations: [], linear: null, model: null }; response.writeHead(200, { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" }); response.end(JSON.stringify({ state: unlocked ? "unlocked" : "locked", integrations, providers })); return; @@ -127,7 +137,7 @@ export async function createAuthenticatedProxyListener({ connection, forwarder = response.writeHead(423, { "cache-control": "no-store" }).end(); return; } - const provider = providerRoute(parsed.pathname, parsed.search, providerCredentials); + const provider = providerRoute(parsed.pathname, parsed.search, { ...providerCredentials, modelAccount: modelCredentials }); let integration; let suffix; if (provider) { @@ -164,7 +174,7 @@ export async function createAuthenticatedProxyListener({ connection, forwarder = const result = await forwarder.forward(integration, { url: target, method: request.method, - headers: request.headers, + headers: { ...request.headers, ...(integration.extraHeaders ?? {}) }, body: request, }, { signal: controller.signal }); const headers = Object.create(null); @@ -202,6 +212,7 @@ export async function createAuthenticatedProxyListener({ connection, forwarder = lockedMetadata = [...grants.values()].map(({ id, name, description }) => ({ id, name, description })); grants = new Map(); providerCredentials = { githubInstallations: [], linearConnection: null }; + modelCredentials = { available: false }; for (const controller of controllers) controller.abort(new Error("proxy locked")); }, getProviderCredentials() { @@ -218,6 +229,10 @@ export async function createAuthenticatedProxyListener({ connection, forwarder = providerCredentials = nextCredentials && typeof nextCredentials === "object" ? nextCredentials : { githubInstallations: [], linearConnection: null }; }, + replaceModelCredentials(nextCredentials) { + if (closed) return; + modelCredentials = nextCredentials && typeof nextCredentials === "object" ? nextCredentials : { available: false }; + }, close: () => { if (closed) return Promise.resolve(); closed = true; diff --git a/packages/credential-proxy/src/runtime.mjs b/packages/credential-proxy/src/runtime.mjs index 4529a04d..d57359c3 100644 --- a/packages/credential-proxy/src/runtime.mjs +++ b/packages/credential-proxy/src/runtime.mjs @@ -165,6 +165,10 @@ export function createProxyRuntime({ listenerFactory = createAuthenticatedProxyL const providers = await connection.refreshProviderCredentials(); if (epoch === grantEpoch && state === "unlocked" && !shutdown && !revokedRuns.has(connection.runId)) listener.replaceProviderCredentials(providers); } + if (typeof connection.refreshModelCredentials === "function" && typeof listener.replaceModelCredentials === "function") { + const model = await connection.refreshModelCredentials(); + if (epoch === grantEpoch && state === "unlocked" && !shutdown && !revokedRuns.has(connection.runId)) listener.replaceModelCredentials(model); + } } catch { // A control-plane outage does not expire established grants. Retry // on the next interval; durable revocation has its own monitor. diff --git a/packages/credential-proxy/src/tunnel-transport.mjs b/packages/credential-proxy/src/tunnel-transport.mjs index cf2b5962..0d7610a5 100644 --- a/packages/credential-proxy/src/tunnel-transport.mjs +++ b/packages/credential-proxy/src/tunnel-transport.mjs @@ -118,10 +118,10 @@ export function createAuthenticatedTunnelServer({ tls, runtime, authenticateEnro /** Start the proxy's production-shaped mTLS listener using its boot-registered * control credential and process-local decrypted integration grants. */ export async function startAuthenticatedProxyTunnel({ - tls, runtime, controlOrigin, controlCredential, resolveGrants, resolveProviderCredentials, resolveRunCredential, fetchImpl = fetch, host = "127.0.0.1", port = 0, + tls, runtime, controlOrigin, controlCredential, resolveGrants, resolveProviderCredentials, resolveModelCredentials, resolveRunCredential, fetchImpl = fetch, host = "127.0.0.1", port = 0, } = {}) { const authenticateRun = createProxyEnrollmentAuthenticator({ - controlOrigin, controlCredential, bootEpoch: runtime?.bootEpoch, resolveGrants, resolveProviderCredentials, resolveRunCredential, fetchImpl, + controlOrigin, controlCredential, bootEpoch: runtime?.bootEpoch, resolveGrants, resolveProviderCredentials, resolveModelCredentials, resolveRunCredential, fetchImpl, }); const tunnel = createAuthenticatedTunnelServer({ tls, runtime, authenticateRun, host, port }); try { diff --git a/packages/credential-proxy/test/model-account-lifecycle.test.mjs b/packages/credential-proxy/test/model-account-lifecycle.test.mjs index 764b4b87..fb1d386b 100644 --- a/packages/credential-proxy/test/model-account-lifecycle.test.mjs +++ b/packages/credential-proxy/test/model-account-lifecycle.test.mjs @@ -52,6 +52,21 @@ test("device authorization persists the refreshed cache for server-side encrypti assert.equal("unlockKey" in saved.request, false); }); +test("outbound model credential reads only the current account cache and observes refreshed tokens", async t => { + const f = await fixture(t); + assert.deepEqual(await f.lifecycle.getAccessCredential(accountId), { available: true, accessToken: "synthetic-access" }); + await writeFile(join(f.home, "auth.json"), JSON.stringify({ tokens: { access_token: "synthetic-refreshed", account_id: "fixture-account" } })); + assert.deepEqual(await f.lifecycle.getAccessCredential(accountId), { available: true, accessToken: "synthetic-refreshed", accountId: "fixture-account" }); + const deleted = createModelAccountLifecycle({ authHelper: { invoke: async () => ({ state: "idle" }) }, accountHomeRoot: f.root, + getAccount: async () => null, persistEncrypted: async () => {}, readCache: readFile }); + assert.deepEqual(await deleted.getAccessCredential(accountId), { available: false }); +}); + +test("outbound model credentials fail closed when refresh requires reconnect", async t => { + const f = await fixture(t, { refreshResult: { state: "reauthentication-required" } }); + assert.deepEqual(await f.lifecycle.getAccessCredential(accountId), { available: false }); +}); + test("denied or expired device authorization does not persist token state", async t => { const f = await fixture(t, { completion: Promise.resolve({ state: "reauthentication-required" }) }); const login = await f.lifecycle.deviceLogin(accountId); diff --git a/packages/credential-proxy/test/proxy-listener.e2e.test.mjs b/packages/credential-proxy/test/proxy-listener.e2e.test.mjs index f59f0110..b42d9c39 100644 --- a/packages/credential-proxy/test/proxy-listener.e2e.test.mjs +++ b/packages/credential-proxy/test/proxy-listener.e2e.test.mjs @@ -137,7 +137,7 @@ test("provider routes use only selected run credentials and choose Git smart HTT request: async ({ socket, url, headers, body }) => { const chunks = []; for await (const chunk of body ?? []) chunks.push(Buffer.from(chunk)); - seen.push({ origin: url.origin, authorization: headers.authorization, path: url.pathname, search: url.search, body: Buffer.concat(chunks).toString() }); + seen.push({ origin: url.origin, authorization: headers.authorization, path: url.pathname, search: url.search, accountId: headers["chatgpt-account-id"], body: Buffer.concat(chunks).toString() }); return { status: 200, headers: { "content-type": "text/plain" }, body: Readable.from(["first", "second"]) }; }, }); @@ -153,12 +153,14 @@ test("provider routes use only selected run credentials and choose Git smart HTT { installationId: 42, available: true, accessToken: "github-selected-token" }, { installationId: 43, available: false }, ], linearConnection: { connectionId: "linear", available: true, accessToken: "linear-selected-token" } }, + modelCredentials: { available: true, accessToken: "model-selected-token", accountId: "chatgpt-account-1" }, }); const base = `http://127.0.0.1:${listener.address.port}`; const inventory = await (await fetch(`${base}/integrations`)).json(); assert.deepEqual(inventory.providers, { githubInstallations: [{ installationId: 42, endpoint: "/providers/github/42/" }], linear: { endpoint: "/providers/linear/" }, + model: { endpoint: "/providers/model/v1/" }, }); const git = await fetch(`${base}/providers/github/42/owner/repo.git/info/refs?service=git-upload-pack`, { headers: { authorization: "Bearer guest-controlled", "git-protocol": "version=2" }, @@ -170,17 +172,31 @@ test("provider routes use only selected run credentials and choose Git smart HTT method: "POST", headers: { authorization: "Bearer guest-controlled" }, body: "{ viewer { id } }", }); assert.equal(await linear.text(), "firstsecond"); + const model = await fetch(`${base}/providers/model/v1/responses`, { + method: "POST", headers: { authorization: "Bearer guest-controlled", "content-type": "application/json" }, body: '{"model":"fixture"}', + }); + const modelBody = await model.text(); + assert.equal(model.status, 200, modelBody); + assert.equal(modelBody, "firstsecond"); assert.equal((await fetch(`${base}/providers/github/43/user`)).status, 403); - assert.deepEqual(seen.map(item => [item.origin, item.authorization, item.path, item.search]), [ - ["https://github.com", "Basic eC1hY2Nlc3MtdG9rZW46Z2l0aHViLXNlbGVjdGVkLXRva2Vu", "/owner/repo.git/info/refs", "?service=git-upload-pack"], - ["https://api.github.com", "Bearer github-selected-token", "/user", ""], - ["https://api.linear.app", "Bearer linear-selected-token", "/graphql", "?operation=Query"], + assert.deepEqual(seen.map(item => [item.origin, item.authorization, item.path, item.search, item.accountId]), [ + ["https://github.com", "Basic eC1hY2Nlc3MtdG9rZW46Z2l0aHViLXNlbGVjdGVkLXRva2Vu", "/owner/repo.git/info/refs", "?service=git-upload-pack", undefined], + ["https://api.github.com", "Bearer github-selected-token", "/user", "", undefined], + ["https://api.linear.app", "Bearer linear-selected-token", "/graphql", "?operation=Query", undefined], + ["https://chatgpt.com", "Bearer model-selected-token", "/backend-api/codex/responses", "", "chatgpt-account-1"], ]); assert.equal(seen[0].body, ""); + assert.equal(seen[3].body, '{"model":"fixture"}'); listener.replaceProviderCredentials({ githubInstallations: [{ installationId: 42, available: false }], linearConnection: { connectionId: "linear", available: false } }); + listener.replaceModelCredentials({ available: true, accessToken: "model-refreshed-token", accountId: "chatgpt-account-1" }); + const refreshedModel = await fetch(`${base}/providers/model/v1/responses`, { method: "POST", body: '{"model":"fixture"}' }); + assert.equal(await refreshedModel.text(), "firstsecond"); + assert.equal(seen.at(-1).authorization, "Bearer model-refreshed-token"); + listener.replaceModelCredentials({ available: false }); + assert.equal((await fetch(`${base}/providers/model/v1/responses`, { method: "POST", body: '{}' })).status, 403); assert.equal((await fetch(`${base}/providers/github/42/user`)).status, 403); assert.equal((await fetch(`${base}/providers/linear/graphql`)).status, 403); - assert.equal(seen.length, 3, "revoked credentials never reach an upstream request"); + assert.equal(seen.length, 5, "revoked credentials never reach an upstream request"); } finally { if (listener) await runtime.disconnect("provider-route-connection"); await runtime.shutdown(); @@ -240,7 +256,7 @@ test("reflection exposes safe metadata for only the authenticated VM connection await runtime.lock(); const locked = await reflect(first); - assert.deepEqual(locked, { state: "locked", providers: { githubInstallations: [], linear: null }, integrations: [ + assert.deepEqual(locked, { state: "locked", providers: { githubInstallations: [], linear: null, model: null }, integrations: [ { id: "selected-2", source: "portable", name: "Metrics API", description: "current help", endpoint: "/integrations/selected-2/", example: 'curl "$FACTORIZE_PROXY_URL/integrations/selected-2/"', availability: "locked" }, ] }); assert.equal((await fetch(`http://127.0.0.1:${first.address.port}/integrations/selected-2/`)).status, 423); diff --git a/packages/credential-proxy/test/runtime-revocation.test.mjs b/packages/credential-proxy/test/runtime-revocation.test.mjs index a3b171c2..fe2a63cb 100644 --- a/packages/credential-proxy/test/runtime-revocation.test.mjs +++ b/packages/credential-proxy/test/runtime-revocation.test.mjs @@ -2,6 +2,8 @@ import assert from "node:assert/strict"; import { test } from "node:test"; import { createProxyRuntime } from "../src/runtime.mjs"; import { startProxyRunRevocationMonitor } from "../src/control-client.mjs"; +import { createBearerForwarder } from "../src/bearer-forwarder.mjs"; +import { createAuthenticatedProxyListener } from "../src/proxy-listener.mjs"; const bootEpoch = "11111111-1111-4111-8111-111111111111"; @@ -234,6 +236,55 @@ test("provider credential refresh removes disconnected credentials from an estab } }); +test("selected model refresh and disconnect affect actual outbound requests on an established run listener", { timeout: 5_000 }, async () => { + const observed = []; + const forwarder = createBearerForwarder({ + connectorFactory: () => async requestUrl => ({ socket: { destroy() {} }, url: new URL(requestUrl) }), + request: async ({ url, headers }) => { + observed.push({ path: url.pathname, authorization: headers.authorization }); + return { status: 200, headers: {}, body: (await import("node:stream")).Readable.from(["ok"]) }; + }, + }); + let selected = { available: true, accessToken: "model-token-v1" }; + const runtime = createProxyRuntime({ bootEpoch, grantRefreshIntervalMs: 100, + listenerFactory: ({ connection: value }) => createAuthenticatedProxyListener({ connection: value, forwarder }) }); + runtime.unlock("synthetic-unlock-key"); + let listener; + try { + listener = await runtime.acceptAuthenticatedConnection({ + ...connection("run-model-refresh", "connection-model-refresh"), vmId: "vm-model-refresh", grants: [], + providerCredentials: { githubInstallations: [], linearConnection: null }, modelCredentials: selected, + refreshGrants: async () => [], refreshProviderCredentials: async () => ({ githubInstallations: [], linearConnection: null }), + refreshModelCredentials: async () => selected, + }); + const endpoint = `http://127.0.0.1:${listener.address.port}/providers/model/v1/responses`; + const request = async () => fetch(endpoint, { method: "POST", body: "{}" }); + assert.equal((await request()).status, 200); + selected = { available: true, accessToken: "model-token-v2" }; + const refreshedBy = Date.now() + 1_500; + while (Date.now() < refreshedBy && !observed.some(value => value.authorization === "Bearer model-token-v2")) { + const response = await request(); + await response.arrayBuffer(); + await new Promise(resolve => setTimeout(resolve, 25)); + } + assert.ok(observed.some(value => value.authorization === "Bearer model-token-v2"), "refreshed selected token reached the outbound model request"); + selected = { available: false }; + const revokedBy = Date.now() + 1_500; + while (Date.now() < revokedBy) { + const response = await request(); + if (response.status === 403) break; + await response.arrayBuffer(); + await new Promise(resolve => setTimeout(resolve, 25)); + } + assert.equal((await request()).status, 403, "disconnected model account is denied before outbound forwarding"); + assert.ok(observed.every(value => value.path === "/backend-api/codex/responses")); + assert.ok(observed.some(value => value.authorization === "Bearer model-token-v1")); + } finally { + if (listener) await runtime.disconnect(listener.connectionId); + await runtime.shutdown(); + } +}); + test("a delayed grant refresh cannot restore access after run revocation", async () => { let resolveRefresh; let refreshStarted; From 5d0a09b7014fa2322b5e578b271f45f7b47928e9 Mon Sep 17 00:00:00 2001 From: "exe.dev user" Date: Mon, 16 Nov 2026 22:53:50 +0000 Subject: [PATCH 17/28] Document GEN-2922 credential proxy cutover --- packages/docs/docs.json | 1 + packages/docs/llms-full.txt | 151 +++++++++++++----- packages/docs/llms.txt | 3 +- packages/docs/scripts/content.mjs | 4 + .../docs/self-hosting/credential-cutover.mdx | 96 +++++++++++ .../credential-proxy-security.mdx | 56 ++----- packages/docs/self-hosting/operations.mdx | 2 +- 7 files changed, 231 insertions(+), 82 deletions(-) create mode 100644 packages/docs/self-hosting/credential-cutover.mdx diff --git a/packages/docs/docs.json b/packages/docs/docs.json index 9868afe2..4b710abf 100644 --- a/packages/docs/docs.json +++ b/packages/docs/docs.json @@ -73,6 +73,7 @@ "self-hosting/deployment", "self-hosting/configuration", "self-hosting/operations", + "self-hosting/credential-cutover", "self-hosting/credential-proxy-security" ] } diff --git a/packages/docs/llms-full.txt b/packages/docs/llms-full.txt index 266e6c3d..f97fbacd 100644 --- a/packages/docs/llms-full.txt +++ b/packages/docs/llms-full.txt @@ -856,7 +856,7 @@ Source: https://docs.factorize.sh/self-hosting/operations Use the [deployment runbook](https://github.com/GenerationSoftware/factorize/blob/main/docs/package-migration.md) and [trace rollout runbook](https://github.com/GenerationSoftware/factorize/blob/main/docs/trace-rollout-runbook.md) for retention, canary gates and rollback. `npm run check` checks package boundaries, generated contracts, runtime tests and builds. The PostgreSQL auth suite uses an isolated database; see configuration for migration verification. -For the credential proxy's security boundaries, lifecycle decisions, key-loss handling, and independent Fly shutdown, see the [credential proxy security and operator runbook](credential-proxy-security). +For the breaking migration and job repair procedure, see [Credential proxy cutover and recovery](credential-cutover). The older [credential proxy security runbook](credential-proxy-security) describes the retired standalone proxy and unlock architecture. `get_run_diagnostics` exposes declared trace sources, projection evidence, artifacts and fallback use. A trace may be partial when collection fails. A `matched` reconciliation result verifies the live prefix against the terminal artifact; missing evidence does not prove completeness. @@ -876,47 +876,118 @@ Migration `0027_run_proxy_delivery.sql` distinguishes proxy-issued credentials f Cleanup checks the integration's run ownership marker before removal and retries failures. The scheduler persists its execution handle before external provisioning, so interrupted and partial launches retain cleanup ownership when their launch lease is recovered. Inspect failed cleanup before removing a marked integration manually; never delete an unrelated name collision. VM attachments and credentials expire after at most 24 hours even when external cleanup is unavailable. -## Credential proxy security and operator runbook +## Credential proxy cutover and recovery +Source: https://docs.factorize.sh/self-hosting/credential-cutover + +# Credential proxy cutover and recovery + +This procedure describes the required breaking cutover; it is not evidence +that the cutover has shipped. In the current repository checkpoint, the old +proxy provisioning, pairing, and unlock paths are still wired into the API, +settings UI, and scheduler. Do not execute this procedure until those paths +have been removed and the new backend release is verified. + +This is a breaking migration. The previous per-owner Fly credential proxy, +browser pairing, and user-held unlock key are not compatible with the Factorize +backend run proxy. Do not run the cutover until the backend release containing +vendor-verified VM identity and tenant-selected run credentials is deployed and +the acceptance checks for both execution providers pass. + +## Before the cutover + +1. Announce a maintenance window and pause schedules, webhook triggers, and + other dispatch sources for affected jobs. Prevent new runs from starting + while the inventory is being prepared. +2. Inventory each tenant's jobs, selected portable integration IDs, model + account IDs, and the owner of each credential. Keep this inventory private; + it must contain identifiers and owners, never secret values. +3. Let active runs finish. For runs that cannot finish, stop them through the + Factorize run controls and verify that each is terminal before proceeding. + Do not stop a shared execution app or VM to drain one tenant's runs. +4. Confirm the new backend is healthy and that a canary run can use only its + selected credentials. Check both exe.dev and Fly runs, including a run with + no portable credentials and one with explicit selections. + +If any run is still active or cannot be confirmed terminal, pause the cutover. +Do not revoke its old proxy access while it is running. + +## Retire the old proxy + +1. In the owner settings, disable the old credential proxy and revoke its run + enrollment before removing any resource. Verify that it no longer accepts + new runs. Disabling the proxy does not stop agent VMs; the drain step above + is required. +2. Identify the proxy Machine from the owner's saved Factorize proxy record. + Confirm the recorded Fly app and Machine ID in the Fly dashboard before + stopping it. Stop the proxy Machine and verify its stopped state. Do not + stop execution Machines as a substitute. +3. After the stop is verified and no old run depends on it, destroy the proxy + Machine and retire the proxy-only Fly app, deployment secret, browser + pairing, and control credential. Keep the owner's Fly connection and all + execution configurations. Remove obsolete proxy-specific deployment + settings from the backend only after the new backend release is serving + traffic. +4. Do not copy the old proxy's unlock key or decrypt old ciphertext into the + new service. The old user-encrypted secrets cannot be migrated by Factorize. + +Use the Fly dashboard or documented Fly CLI commands for resource retirement. +Record the app and Machine identifiers that were removed, but never record +credentials, unlock keys, or decrypted secret values. + +## Reconnect credentials and repair jobs + +1. Each owner reconnects GitHub and Linear using the existing Factorize + connection flow, reconnects model accounts, and re-enters custom bearer + credentials. Re-enter the same intended account where possible; a new + connection ID is expected. +2. Compare the new connection metadata with the private inventory. Update each + affected job to select the corresponding new credential ID. The cutover + must not select every tenant credential automatically. A job that cannot + be mapped confidently stays disabled until its owner repairs it. +3. Verify each saved selection belongs to that job's tenant and that the + selected account is connected. Run one canary per repaired job and confirm + its outbound requests use only those selections. Confirm Factorize API + scopes match the job's configured scopes. +4. Keep jobs with no portable selections unchanged. Do not add a credential to + a job merely because it was available to the retired proxy. +5. Resume dispatch only after the affected job inventory is reconciled. If a + credential cannot be reconnected, leave that selection unavailable and the + job disabled; do not substitute another credential silently. + +## Recovery + +If the new backend canary fails, keep affected jobs paused and repair the new +backend or the specific credential selection. The old unlock architecture is +not a rollback path. Re-enable an old proxy only if the deployment has not +retired it, its identity is still verified, and an operator has confirmed that +doing so will not reintroduce access for unrelated tenants or runs. Never +restore old credentials or ciphertext from a database backup as part of +rollback. Re-enter or reconnect credentials after service is restored. + +## Completion record + +Record the maintenance window, terminal-run count, retired proxy app/Machine +identifiers, repaired job count, jobs left disabled for owner repair, and +canary results. Keep secret values, bearer tokens, unlock keys, and decrypted +credential material out of the record. + +## Credential proxy architecture migration Source: https://docs.factorize.sh/self-hosting/credential-proxy-security -This guide records the agreed design in [GEN-2824](https://linear.app/generation/issue/GEN-2824/add-provider-independent-integrations-with-a-user-unlocked-credential) and the intended operator response. It is not evidence of a production deployment. As of this revision, key rotation/lost-key browser flows (GEN-2873), recovery status and lifecycle audit metadata (GEN-2866), and bounded live portability checks (GEN-2875) are unfinished. Do not assume those controls or evidence exist in a deployed service until their work is complete and the release has been verified. +# Credential proxy architecture being retired -## Trust and data boundaries +The per-owner Fly credential proxy, browser pairing, and user-held unlock key +are the legacy architecture targeted by the breaking backend-proxy cutover. +Those paths are still present in the current repository checkpoint, so this +page no longer describes supported setup or recovery for the target design. +Do not interpret this migration checkpoint as proof that the runtime cutover +has shipped. -- One Factorize user has one private credential collection, one credential proxy, and one user-owned Fly account/organization connection. That connection can own many execution configurations. Fly and exe.dev are the initial execution providers; the proxy design is provider-independent. -- The user holds a generated, high-entropy unlock key. There is no password substitute or recovery backdoor. Integration bearer credentials and ChatGPT model tokens are encrypted under this key before Factorize receives them, then protected by Factorize's independent server encryption. The key and plaintext upstream credentials must not appear in Factorize storage, launch configuration, logs, or backups. -- The browser is trusted at secret entry: the key is entered into Factorize's browser UI and trusted frontend code can read it. The browser sends it directly to the proxy over authenticated HTTPS for unlock; Factorize receives status only. The proxy's public Fly hostname terminates TLS at Fly's edge and forwards over Fly's private network. This trusts Fly's edge and private-network boundary; TLS does not continue to the guest. -- Factorize is trusted to provision and pair the proxy, administer cloud machines, and authorize run enrollment. Initial pairing is trusted provisioning, not independent user verification. The paired identity includes proxy, Fly app/Machine, HTTPS origin, SSH host fingerprint, and generation. Unexpected identity changes must fail closed and require an authenticated owner's explicit approval. -- A named bearer integration is bound to one public HTTPS origin. A granted job can use HTTP methods, paths, queries, and bodies on that origin. Redirects are rejected and destinations must be public. Agent compromise can exercise all authority in that job's grant. Already-sent requests cannot be recalled; upstream effects can persist independently, including tokens returned by an upstream service. -- Factorize run API credentials are separate, per-run scoped/revocable credentials. They are not encrypted with the user's key and are delivered to proxy memory over a separate control path; they must never be placed in a Fly agent VM. Keep grants explicit and minimal. Native exe.dev integrations remain available alongside portable integrations in a separate namespace; adding a portable integration must not change native behavior or implicitly grant it to a job. -- Portable integration reflection is served at `GET $FACTORIZE_PROXY_URL/integrations` only through that VM's authenticated tunnel. It lists the connection's selected integration names, descriptions, local paths, examples, and availability; it omits upstream origins and all credentials. Locking clears decrypted grants and aborts in-flight forwarding while preserving safe metadata as `locked` for that established connection. A later unlock refreshes grants from the current run snapshot before restoring access. Each VM connection has an independent listener and reflection view. -- Database or server-encryption-key theft alone does not reveal the inner user-encrypted records. A compromised Factorize control plane can authorize malicious workloads and administer provisioned cloud machines. A compromised proxy host can access secrets while unlocked. This design does not promise physical erasure of host memory, prevent a key holder from decrypting their ciphertext, or prevent upstream services from retaining access they have granted. +Use the [credential proxy cutover and recovery procedure](credential-cutover) +to drain existing runs, retire old proxy resources, reconnect credentials, +and repair affected jobs. Old user-encrypted secrets cannot be transferred; +owners must reconnect provider accounts or re-enter custom credentials. -## Lifecycle and recovery runbook - -Use the browser lifecycle controls when available. The state distinctions matter: stopped has no running proxy; running/locked may serve separately authorized Factorize API access but not user integrations; unlocked can serve its authorized grants; disabled additionally blocks automatic startup and new enrollment. Stop and disable do not stop agent VMs. Re-enable does not unlock. No idle lock or automatic unlock after a crash is promised. - -1. **Routine start or unlock:** authenticate as the owner in Factorize. Start leaves the proxy locked. Enter the unlock key through the browser's direct HTTPS flow. Apply pending encrypted edits before new agent connections. If unavailable or locked, dependent launches should report blocked and wait for an explicit retry; they must not silently launch with stale grants. -2. **Edit or update:** stage encrypted credential changes in Factorize; they can be made while stopped. A deliberate pinned-image update restarts the proxy locked. Re-enter the key before using user integrations. A changed proxy identity/origin/fingerprint requires explicit owner review and pairing-generation replacement; never trust a DNS change, restart, or new certificate alone. -3. **Stop or disable:** stop closes proxy connections and stops the Machine, preserving the Machine for a later start. Disable also revokes enrollment and prevents automatic starts and new enrollment until an owner explicitly enables it. Check agent runs separately: these controls do not stop their VMs, and in-flight upstream requests may complete. -4. **Rotation or lost key:** rotation requires the current key and should atomically re-encrypt all current and pending records under a newly generated key, then require unlock with that key. If the key is lost, do not claim to recover it. The reset flow must stop the proxy, revoke grants/enrollments, delete encrypted integration/model-account records and pending changes, and create an empty generation. Preserve the Fly connection and execution configurations; repair jobs that reference deleted items. These browser flows are not yet complete (GEN-2873), so if needed now use the independent Fly shutdown below and wait for the shipped reset flow rather than improvising database edits. -5. **Restart/recovery:** a cold or crash restart starts locked and does not restore unlock material. A surviving authorized run may reconnect only after a fresh enrollment is issued. A run that exited is never revived. Factorize may re-issue separate run credentials after restart without unlocking user integrations. A revoked upstream refresh token may require reconnecting that account; do not promise guaranteed refresh recovery. -6. **Image rollback:** roll back only to a previously reviewed, digest-pinned proxy image through the normal deployment mechanism. Restart it locked and verify its identity and health before unlocking. Do not restore old secrets, ciphertext generations, pending changes, grants, or enrollments from an image backup. Reconcile any schema/data incompatibility explicitly; stop and reset through the supported owner flow if safe reconciliation is unavailable. - -### Independent Fly shutdown - -If Factorize is unavailable or the proxy must be isolated, stop its Fly Machine from the Fly dashboard: open the owning organization, select the proxy app and its Machine, then choose **Stop** and verify the Machine is stopped. Identify the proxy Machine carefully; stopping it does not stop execution Machines. - -With the documented [Fly CLI](https://fly.io/docs/flyctl/machine-stop/) installed and authenticated to the owning organization, the equivalent command is: - -```sh -fly machine stop -a -``` - -Use the app and Machine identity recorded during provisioning. Verify the result in the Fly dashboard or with `fly machine status -a ` ([status command reference](https://fly.io/docs/flyctl/machine-status/)). These are Fly CLI commands, not Factorize scripts. This independent stop halts the proxy Machine but does not by itself revoke enrollment or upstream credentials; perform owner-side disable/recovery when Factorize is available. - -## Verification evidence and release gate - -Repository fixtures provide narrow evidence only: `packages/app/test/https-pairing.browser.test.mjs` exercises local HTTPS origin and pairing decisions; `packages/app/test/unlock-crypto.test.mjs` covers browser key parsing/cryptography; `packages/credential-proxy/test/runtime-process.test.mjs` checks the small locked/unlocked process runtime; `packages/api/test/fly-machines-client.test.ts` uses a local fake Fly API. None establishes live Fly behavior, production HTTPS termination, full browser lifecycle controls, actual upstream portability, or physical host-memory erasure. GEN-2875's bounded opt-in live checks remain the place for explicitly authorized live evidence; fixture success must not be presented as live verification. - -Before enabling this design for operators, finish the dependent lifecycle/reset/recovery/live-check issues, run their deterministic local tests and the repository's full validation, and record separately any bounded live evidence and its prerequisites. For current repository validation, use the instructions in [operations](operations) and the repository root `AGENTS.md`; tests must use local fixtures and isolated databases. Do not use production deployment as a verification step for this guide. +The former design is retained in the repository's historical decisions and +Linear work for audit context. Fixture results from that implementation are +not live exe.dev or Fly identity evidence. diff --git a/packages/docs/llms.txt b/packages/docs/llms.txt index 9825e74e..59f3c036 100644 --- a/packages/docs/llms.txt +++ b/packages/docs/llms.txt @@ -54,7 +54,8 @@ Current MCP does not return execution output; inspect browser traces or REST tra - [Optional self-hosting](https://docs.factorize.sh/self-hosting/deployment): Deploy your own Factorize instance. - [Operator configuration](https://docs.factorize.sh/self-hosting/configuration): Email, OAuth applications, webhooks, and Worker secrets. - [Operations and advanced trace recovery](https://docs.factorize.sh/self-hosting/operations): Operator checks, retained artifacts, and rollout evidence. -- [Credential proxy security and operator runbook](https://docs.factorize.sh/self-hosting/credential-proxy-security): Security boundaries, recovery decisions, and independent shutdown for the user credential proxy. +- [Credential proxy cutover and recovery](https://docs.factorize.sh/self-hosting/credential-cutover): Operator and user procedure for retiring the separate credential proxy and reconnecting credentials for the per-run backend proxy. +- [Credential proxy architecture migration](https://docs.factorize.sh/self-hosting/credential-proxy-security): Status of the retired standalone proxy and link to the current migration procedure. ## Machine-readable REST reference diff --git a/packages/docs/scripts/content.mjs b/packages/docs/scripts/content.mjs index 5f8c5461..fb07922e 100644 --- a/packages/docs/scripts/content.mjs +++ b/packages/docs/scripts/content.mjs @@ -30,6 +30,10 @@ export async function checkContent() { for (const phrase of ["list_execution_configs", "create_job", "invoke_job", "get_run", "idempotencyKey", "browser", "output"]) if (!guides.get("quickstart").includes(phrase)) throw new Error(`Incomplete first-job guide: ${phrase}`); if (/Worker secrets|POSTMARK_SERVER_TOKEN|LINEAR_CLIENT_SECRET|Cloudflare account/.test(main)) throw new Error("Operator prerequisite in main onboarding"); for (const body of guides.values()) if (/username\/password|username, email|Job create object|mirrors REST/.test(body)) throw new Error("Stale auth or capability claim"); + const cutover = guides.get("self-hosting/credential-cutover"); + for (const phrase of ["verify that each is terminal", "Stop the proxy Machine and verify its stopped state", "reconnects model accounts", "re-enters custom bearer", "must not select every tenant credential automatically", "do not substitute another credential silently"]) { + if (!cutover.includes(phrase)) throw new Error(`Incomplete credential cutover and repair procedure: ${phrase}`); + } const reference = guides.get("mcp/tools"); checkInventory(await readFile(resolve(root, "../api/src/protected-api.ts"), "utf8"), reference); for (const term of ["expectedUpdatedAt", "replaces configuration", "duplicate", "manual:", "edited", "Current", "not full REST parity"]) if (!reference.includes(term)) throw new Error(`Missing contract detail: ${term}`); diff --git a/packages/docs/self-hosting/credential-cutover.mdx b/packages/docs/self-hosting/credential-cutover.mdx new file mode 100644 index 00000000..37ff8f2f --- /dev/null +++ b/packages/docs/self-hosting/credential-cutover.mdx @@ -0,0 +1,96 @@ +--- +title: Credential proxy cutover and recovery +description: Operator and user procedure for retiring the separate credential proxy and reconnecting credentials for the per-run backend proxy. +--- + +# Credential proxy cutover and recovery + +This procedure describes the required breaking cutover; it is not evidence +that the cutover has shipped. In the current repository checkpoint, the old +proxy provisioning, pairing, and unlock paths are still wired into the API, +settings UI, and scheduler. Do not execute this procedure until those paths +have been removed and the new backend release is verified. + +This is a breaking migration. The previous per-owner Fly credential proxy, +browser pairing, and user-held unlock key are not compatible with the Factorize +backend run proxy. Do not run the cutover until the backend release containing +vendor-verified VM identity and tenant-selected run credentials is deployed and +the acceptance checks for both execution providers pass. + +## Before the cutover + +1. Announce a maintenance window and pause schedules, webhook triggers, and + other dispatch sources for affected jobs. Prevent new runs from starting + while the inventory is being prepared. +2. Inventory each tenant's jobs, selected portable integration IDs, model + account IDs, and the owner of each credential. Keep this inventory private; + it must contain identifiers and owners, never secret values. +3. Let active runs finish. For runs that cannot finish, stop them through the + Factorize run controls and verify that each is terminal before proceeding. + Do not stop a shared execution app or VM to drain one tenant's runs. +4. Confirm the new backend is healthy and that a canary run can use only its + selected credentials. Check both exe.dev and Fly runs, including a run with + no portable credentials and one with explicit selections. + +If any run is still active or cannot be confirmed terminal, pause the cutover. +Do not revoke its old proxy access while it is running. + +## Retire the old proxy + +1. In the owner settings, disable the old credential proxy and revoke its run + enrollment before removing any resource. Verify that it no longer accepts + new runs. Disabling the proxy does not stop agent VMs; the drain step above + is required. +2. Identify the proxy Machine from the owner's saved Factorize proxy record. + Confirm the recorded Fly app and Machine ID in the Fly dashboard before + stopping it. Stop the proxy Machine and verify its stopped state. Do not + stop execution Machines as a substitute. +3. After the stop is verified and no old run depends on it, destroy the proxy + Machine and retire the proxy-only Fly app, deployment secret, browser + pairing, and control credential. Keep the owner's Fly connection and all + execution configurations. Remove obsolete proxy-specific deployment + settings from the backend only after the new backend release is serving + traffic. +4. Do not copy the old proxy's unlock key or decrypt old ciphertext into the + new service. The old user-encrypted secrets cannot be migrated by Factorize. + +Use the Fly dashboard or documented Fly CLI commands for resource retirement. +Record the app and Machine identifiers that were removed, but never record +credentials, unlock keys, or decrypted secret values. + +## Reconnect credentials and repair jobs + +1. Each owner reconnects GitHub and Linear using the existing Factorize + connection flow, reconnects model accounts, and re-enters custom bearer + credentials. Re-enter the same intended account where possible; a new + connection ID is expected. +2. Compare the new connection metadata with the private inventory. Update each + affected job to select the corresponding new credential ID. The cutover + must not select every tenant credential automatically. A job that cannot + be mapped confidently stays disabled until its owner repairs it. +3. Verify each saved selection belongs to that job's tenant and that the + selected account is connected. Run one canary per repaired job and confirm + its outbound requests use only those selections. Confirm Factorize API + scopes match the job's configured scopes. +4. Keep jobs with no portable selections unchanged. Do not add a credential to + a job merely because it was available to the retired proxy. +5. Resume dispatch only after the affected job inventory is reconciled. If a + credential cannot be reconnected, leave that selection unavailable and the + job disabled; do not substitute another credential silently. + +## Recovery + +If the new backend canary fails, keep affected jobs paused and repair the new +backend or the specific credential selection. The old unlock architecture is +not a rollback path. Re-enable an old proxy only if the deployment has not +retired it, its identity is still verified, and an operator has confirmed that +doing so will not reintroduce access for unrelated tenants or runs. Never +restore old credentials or ciphertext from a database backup as part of +rollback. Re-enter or reconnect credentials after service is restored. + +## Completion record + +Record the maintenance window, terminal-run count, retired proxy app/Machine +identifiers, repaired job count, jobs left disabled for owner repair, and +canary results. Keep secret values, bearer tokens, unlock keys, and decrypted +credential material out of the record. diff --git a/packages/docs/self-hosting/credential-proxy-security.mdx b/packages/docs/self-hosting/credential-proxy-security.mdx index 5eadf520..65ae6aff 100644 --- a/packages/docs/self-hosting/credential-proxy-security.mdx +++ b/packages/docs/self-hosting/credential-proxy-security.mdx @@ -1,46 +1,22 @@ --- -title: Credential proxy security and operator runbook -description: Security boundaries, recovery decisions, and independent shutdown for the user credential proxy. +title: Credential proxy architecture migration +description: Status of the retired standalone proxy and link to the current migration procedure. --- -This guide records the agreed design in [GEN-2824](https://linear.app/generation/issue/GEN-2824/add-provider-independent-integrations-with-a-user-unlocked-credential) and the intended operator response. It is not evidence of a production deployment. As of this revision, key rotation/lost-key browser flows (GEN-2873), recovery status and lifecycle audit metadata (GEN-2866), and bounded live portability checks (GEN-2875) are unfinished. Do not assume those controls or evidence exist in a deployed service until their work is complete and the release has been verified. +# Credential proxy architecture being retired -## Trust and data boundaries +The per-owner Fly credential proxy, browser pairing, and user-held unlock key +are the legacy architecture targeted by the breaking backend-proxy cutover. +Those paths are still present in the current repository checkpoint, so this +page no longer describes supported setup or recovery for the target design. +Do not interpret this migration checkpoint as proof that the runtime cutover +has shipped. -- One Factorize user has one private credential collection, one credential proxy, and one user-owned Fly account/organization connection. That connection can own many execution configurations. Fly and exe.dev are the initial execution providers; the proxy design is provider-independent. -- The user holds a generated, high-entropy unlock key. There is no password substitute or recovery backdoor. Integration bearer credentials and ChatGPT model tokens are encrypted under this key before Factorize receives them, then protected by Factorize's independent server encryption. The key and plaintext upstream credentials must not appear in Factorize storage, launch configuration, logs, or backups. -- The browser is trusted at secret entry: the key is entered into Factorize's browser UI and trusted frontend code can read it. The browser sends it directly to the proxy over authenticated HTTPS for unlock; Factorize receives status only. The proxy's public Fly hostname terminates TLS at Fly's edge and forwards over Fly's private network. This trusts Fly's edge and private-network boundary; TLS does not continue to the guest. -- Factorize is trusted to provision and pair the proxy, administer cloud machines, and authorize run enrollment. Initial pairing is trusted provisioning, not independent user verification. The paired identity includes proxy, Fly app/Machine, HTTPS origin, SSH host fingerprint, and generation. Unexpected identity changes must fail closed and require an authenticated owner's explicit approval. -- A named bearer integration is bound to one public HTTPS origin. A granted job can use HTTP methods, paths, queries, and bodies on that origin. Redirects are rejected and destinations must be public. Agent compromise can exercise all authority in that job's grant. Already-sent requests cannot be recalled; upstream effects can persist independently, including tokens returned by an upstream service. -- Factorize run API credentials are separate, per-run scoped/revocable credentials. They are not encrypted with the user's key and are delivered to proxy memory over a separate control path; they must never be placed in a Fly agent VM. Keep grants explicit and minimal. Native exe.dev integrations remain available alongside portable integrations in a separate namespace; adding a portable integration must not change native behavior or implicitly grant it to a job. -- Portable integration reflection is served at `GET $FACTORIZE_PROXY_URL/integrations` only through that VM's authenticated tunnel. It lists the connection's selected integration names, descriptions, local paths, examples, and availability; it omits upstream origins and all credentials. Locking clears decrypted grants and aborts in-flight forwarding while preserving safe metadata as `locked` for that established connection. A later unlock refreshes grants from the current run snapshot before restoring access. Each VM connection has an independent listener and reflection view. -- Database or server-encryption-key theft alone does not reveal the inner user-encrypted records. A compromised Factorize control plane can authorize malicious workloads and administer provisioned cloud machines. A compromised proxy host can access secrets while unlocked. This design does not promise physical erasure of host memory, prevent a key holder from decrypting their ciphertext, or prevent upstream services from retaining access they have granted. +Use the [credential proxy cutover and recovery procedure](credential-cutover) +to drain existing runs, retire old proxy resources, reconnect credentials, +and repair affected jobs. Old user-encrypted secrets cannot be transferred; +owners must reconnect provider accounts or re-enter custom credentials. -## Lifecycle and recovery runbook - -Use the browser lifecycle controls when available. The state distinctions matter: stopped has no running proxy; running/locked may serve separately authorized Factorize API access but not user integrations; unlocked can serve its authorized grants; disabled additionally blocks automatic startup and new enrollment. Stop and disable do not stop agent VMs. Re-enable does not unlock. No idle lock or automatic unlock after a crash is promised. - -1. **Routine start or unlock:** authenticate as the owner in Factorize. Start leaves the proxy locked. Enter the unlock key through the browser's direct HTTPS flow. Apply pending encrypted edits before new agent connections. If unavailable or locked, dependent launches should report blocked and wait for an explicit retry; they must not silently launch with stale grants. -2. **Edit or update:** stage encrypted credential changes in Factorize; they can be made while stopped. A deliberate pinned-image update restarts the proxy locked. Re-enter the key before using user integrations. A changed proxy identity/origin/fingerprint requires explicit owner review and pairing-generation replacement; never trust a DNS change, restart, or new certificate alone. -3. **Stop or disable:** stop closes proxy connections and stops the Machine, preserving the Machine for a later start. Disable also revokes enrollment and prevents automatic starts and new enrollment until an owner explicitly enables it. Check agent runs separately: these controls do not stop their VMs, and in-flight upstream requests may complete. -4. **Rotation or lost key:** rotation requires the current key and should atomically re-encrypt all current and pending records under a newly generated key, then require unlock with that key. If the key is lost, do not claim to recover it. The reset flow must stop the proxy, revoke grants/enrollments, delete encrypted integration/model-account records and pending changes, and create an empty generation. Preserve the Fly connection and execution configurations; repair jobs that reference deleted items. These browser flows are not yet complete (GEN-2873), so if needed now use the independent Fly shutdown below and wait for the shipped reset flow rather than improvising database edits. -5. **Restart/recovery:** a cold or crash restart starts locked and does not restore unlock material. A surviving authorized run may reconnect only after a fresh enrollment is issued. A run that exited is never revived. Factorize may re-issue separate run credentials after restart without unlocking user integrations. A revoked upstream refresh token may require reconnecting that account; do not promise guaranteed refresh recovery. -6. **Image rollback:** roll back only to a previously reviewed, digest-pinned proxy image through the normal deployment mechanism. Restart it locked and verify its identity and health before unlocking. Do not restore old secrets, ciphertext generations, pending changes, grants, or enrollments from an image backup. Reconcile any schema/data incompatibility explicitly; stop and reset through the supported owner flow if safe reconciliation is unavailable. - -### Independent Fly shutdown - -If Factorize is unavailable or the proxy must be isolated, stop its Fly Machine from the Fly dashboard: open the owning organization, select the proxy app and its Machine, then choose **Stop** and verify the Machine is stopped. Identify the proxy Machine carefully; stopping it does not stop execution Machines. - -With the documented [Fly CLI](https://fly.io/docs/flyctl/machine-stop/) installed and authenticated to the owning organization, the equivalent command is: - -```sh -fly machine stop -a -``` - -Use the app and Machine identity recorded during provisioning. Verify the result in the Fly dashboard or with `fly machine status -a ` ([status command reference](https://fly.io/docs/flyctl/machine-status/)). These are Fly CLI commands, not Factorize scripts. This independent stop halts the proxy Machine but does not by itself revoke enrollment or upstream credentials; perform owner-side disable/recovery when Factorize is available. - -## Verification evidence and release gate - -Repository fixtures provide narrow evidence only: `packages/app/test/https-pairing.browser.test.mjs` exercises local HTTPS origin and pairing decisions; `packages/app/test/unlock-crypto.test.mjs` covers browser key parsing/cryptography; `packages/credential-proxy/test/runtime-process.test.mjs` checks the small locked/unlocked process runtime; `packages/api/test/fly-machines-client.test.ts` uses a local fake Fly API. None establishes live Fly behavior, production HTTPS termination, full browser lifecycle controls, actual upstream portability, or physical host-memory erasure. GEN-2875's bounded opt-in live checks remain the place for explicitly authorized live evidence; fixture success must not be presented as live verification. - -Before enabling this design for operators, finish the dependent lifecycle/reset/recovery/live-check issues, run their deterministic local tests and the repository's full validation, and record separately any bounded live evidence and its prerequisites. For current repository validation, use the instructions in [operations](operations) and the repository root `AGENTS.md`; tests must use local fixtures and isolated databases. Do not use production deployment as a verification step for this guide. +The former design is retained in the repository's historical decisions and +Linear work for audit context. Fixture results from that implementation are +not live exe.dev or Fly identity evidence. diff --git a/packages/docs/self-hosting/operations.mdx b/packages/docs/self-hosting/operations.mdx index e3541d1a..0dec2561 100644 --- a/packages/docs/self-hosting/operations.mdx +++ b/packages/docs/self-hosting/operations.mdx @@ -5,7 +5,7 @@ description: Operator checks, retained artifacts, and rollout evidence. Use the [deployment runbook](https://github.com/GenerationSoftware/factorize/blob/main/docs/package-migration.md) and [trace rollout runbook](https://github.com/GenerationSoftware/factorize/blob/main/docs/trace-rollout-runbook.md) for retention, canary gates and rollback. `npm run check` checks package boundaries, generated contracts, runtime tests and builds. The PostgreSQL auth suite uses an isolated database; see configuration for migration verification. -For the credential proxy's security boundaries, lifecycle decisions, key-loss handling, and independent Fly shutdown, see the [credential proxy security and operator runbook](credential-proxy-security). +For the breaking migration and job repair procedure, see [Credential proxy cutover and recovery](credential-cutover). The older [credential proxy security runbook](credential-proxy-security) describes the retired standalone proxy and unlock architecture. `get_run_diagnostics` exposes declared trace sources, projection evidence, artifacts and fallback use. A trace may be partial when collection fails. A `matched` reconciliation result verifies the live prefix against the terminal artifact; missing evidence does not prove completeness. From 47ccf62453a6f3ab0b640c266824a6ed6ec019eb Mon Sep 17 00:00:00 2001 From: "exe.dev user" Date: Tue, 17 Nov 2026 14:44:12 +0000 Subject: [PATCH 18/28] Pin Fly run identities to organization slugs and verify live vendors --- docs/gen-2922-progress.md | 68 +++++++++++++++++++ docs/vendor-run-identity.md | 17 +++-- packages/api/src/fly-job-execution-backend.ts | 5 +- .../api/src/machine-job-execution-backend.ts | 5 +- packages/api/src/postgres/run-scheduler.ts | 4 +- packages/api/src/vendor-run-identity.ts | 4 +- .../test/fly-job-execution-backend.test.ts | 22 +++++- packages/api/test/vendor-run-identity.test.ts | 8 ++- 8 files changed, 116 insertions(+), 17 deletions(-) create mode 100644 docs/gen-2922-progress.md diff --git a/docs/gen-2922-progress.md b/docs/gen-2922-progress.md new file mode 100644 index 00000000..0609f424 --- /dev/null +++ b/docs/gen-2922-progress.md @@ -0,0 +1,68 @@ +# GEN-2922 completion ledger + +Continue on PR #404 (`codex/gen-2922-vendor-identity`). Do not mark the issue +complete or release the breaking change until every remaining gate passes. + +## Current implementation + +- [x] Vendor JWT signature, issuer, audience, lifetime, VM and run binding primitives; + immutable PostgreSQL bindings and renewal/revocation fixtures. +- [x] Managed bearer/model storage, selected existing GitHub/Linear connections, + provider/model forwarding and scope snapshot fixtures in the preceding PR commits. +- [x] Correct Fly issuer and subject configuration to use the connected organization + **slug**, independently of the app name and organization display name. Apply the + same pinned issuer/subject on launch and renewal. +- [x] Reject redirects and bound discovery/JWKS fetches to ten seconds. +- [x] Live vendor signature verification described below. +- [ ] Vendor identity authentication on each backend API/proxy request. Current run + bearer credentials and standalone proxy admission still exist. +- [ ] Move outbound forwarding and model authentication/refresh into the backend. +- [ ] Replace runtime provisioning, guest discovery/client setup and scheduler gates. +- [ ] Remove standalone proxy/pairing/unlock API, UI, configuration and dependencies. +- [ ] Implement and test the documented breaking migration and job repair behavior. +- [ ] Reconcile operator/user docs, superseded work, and deployment/release gates. +- [ ] End-to-end live vendor/run/proxy evidence and final complete root validation. + +## Live vendor evidence — 2026-11-17 + +These checks used real vendor-signed tokens and vendor discovery/JWKS with the +repository verifier. They used an explicit local test run binding, so they do +not prove production run eligibility, persistence, forwarding, disconnection or +cancellation. JWTs and credentials are intentionally absent from this record. + +Fly isolated app `factorize-gen2922-identity-20261117`, Machine `811112ea04e618` +(`vendor-identity-check`), organization slug `brendan-asselstine`: + +- Token obtained through the documented `/.fly/api` Unix socket and + `POST /v1/tokens/oidc`, for the explicit test run audience. +- Live issuer was `https://oidc.fly.io/brendan-asselstine`; subject was + `brendan-asselstine:factorize-gen2922-identity-20261117:vendor-identity-check`. + This exposed and corrected the previous app-issuer/display-name assumptions. +- RS256 signature verified using live discovery and JWKS. A second token renewed + the same VM binding. Wrong issuer, audience, subject, Machine and inactive run + were rejected against the real token. +- Test app and Machine deleted; subsequent org inventory contained zero apps. + +exe.dev unique WIF integration `fz-gen2922-live-check`, directly attached only +to `expressway-by-scraper` with a one-hour grant: + +- Live inventory showed a single VM attachment, generated issuer + `https://exe.dev/issuer/kilo-extra-sun`, and an integration-scoped subject. +- Token obtained from the documented integration `/token` endpoint; RS256 + signature verified against live discovery/JWKS. Wrong issuer, audience, + subject, VM and inactive run were rejected. +- The unattached VM `factorize-gen2922-validation` received HTTP 403 from that + endpoint. No assumption was made that the WIF subject itself identifies a VM. +- Temporary WIF integration cleanup and validation VM cleanup are pending. + +Signing-key rotation, database revocation, terminal/canceled runs, cross-tenant +isolation and provider requests remain deterministic fixture evidence until the +backend cutover permits an end-to-end live test. + +## Validation + +Node 24.12.0 / npm 11.19.0; clean `npm ci` passed. Focused vendor identity and +Fly backend suites: 32 tests passed. Root local validation on the development VM +stopped before tests because its PostgreSQL password does not match the runner +configuration. No host repair was attempted. A new isolated exe.dev VM is booted +from the documented immutable validation-runner image for the required suite. diff --git a/docs/vendor-run-identity.md b/docs/vendor-run-identity.md index f8b159d5..6d3a3738 100644 --- a/docs/vendor-run-identity.md +++ b/docs/vendor-run-identity.md @@ -33,8 +33,9 @@ token expires. tag-attached integration does not establish an exclusive VM binding. * Fly.io's [OIDC workload identity guide](https://fly.io/blog/oidc-cloud-roles/) documents signed machine tokens, a machine-specific `machine_id`, an - app-scoped issuer, short-lived tokens, and key publication. Factorize must - pin the app issuer/audience and compare the signed machine ID to the + organization-scoped issuer, short-lived tokens, and key publication. Factorize must + pin the connected organization slug as issuer, the run audience, and the + `org-slug:app-name:machine-name` subject and compare the signed machine ID to the provisioned machine. `packages/api/src/vendor-run-token-sources.ts` implements the documented guest @@ -52,6 +53,12 @@ removes the per-run exe.dev integration after verifying its VM attachment. Focused backend tests use deterministic token and provider response fixtures, and the PostgreSQL repository tests cover immutable renewal, revocation, expiry, duplicate bindings, and inactive runs. They do not establish live -vendor behavior. No live exe.dev or Fly token was observed in development or -validation. The existing proxy admission and proxy identity remain outside this -milestone; vendor verification does not add a shared-secret fallback. +vendor behavior. On 2026-11-17 the verifier accepted real exe.dev and Fly signed tokens using +live vendor discovery and JWKS, and rejected wrong VM, subject, issuer, audience, +and inactive-run bindings. Fly renewal was verified with a second live token. +exe.dev's WIF integration was attached only to `expressway-by-scraper`; an +unattached validation VM received HTTP 403 from its token endpoint. The local +run binding in these checks was explicit test input, not a production run or an +end-to-end backend proxy session. See [the completion ledger](gen-2922-progress.md) +for the remaining runtime and cutover gates. The existing proxy admission and +proxy identity remain outside this verification evidence. diff --git a/packages/api/src/fly-job-execution-backend.ts b/packages/api/src/fly-job-execution-backend.ts index 5cfa879c..cdc0142f 100644 --- a/packages/api/src/fly-job-execution-backend.ts +++ b/packages/api/src/fly-job-execution-backend.ts @@ -7,7 +7,7 @@ type SharedOptions = ConstructorParameters[0] /** Preserves persisted Fly handles while sharing the complete guest lifecycle. */ export class FlyJobExecutionBackend extends MachineJobExecutionBackend { - constructor(options: Omit & { region: string; size: string; organizationName?: string }) { + constructor(options: Omit & { region: string; size: string; organizationSlug?: string }) { super({ ...options, kind: "fly", @@ -17,8 +17,9 @@ export class FlyJobExecutionBackend extends MachineJobExecutionBackend { }), vmIdentity: machine => `fly:${options.app}:${machine.id}`, proxyAddress: { host: `${options.app}.internal`, port: 9090 }, + ...(options.organizationSlug ? { vendorIdentityIssuer: `https://oidc.fly.io/${options.organizationSlug}` } : {}), vendorIdentityAudience: options.vendorIdentityAudience ?? (runId => `factorize://runs/${runId}`), - ...(options.organizationName ? { vendorIdentitySubject: machine => machine.name ? `${options.organizationName}:${options.app}:${machine.name}` : "" } : {}), + ...(options.organizationSlug ? { vendorIdentitySubject: machine => machine.name ? `${options.organizationSlug}:${options.app}:${machine.name}` : "" } : {}), }); } } diff --git a/packages/api/src/machine-job-execution-backend.ts b/packages/api/src/machine-job-execution-backend.ts index 00877abf..5e5e71cf 100644 --- a/packages/api/src/machine-job-execution-backend.ts +++ b/packages/api/src/machine-job-execution-backend.ts @@ -54,6 +54,7 @@ export class MachineJobExecutionBackend implements ExecutionBackend, JobResultRe destinationUrl?: (machine: JobMachine) => string; vendorIdentityAudience?: (runId: string) => string; vendorIdentitySubject?: (machine: JobMachine) => string; + vendorIdentityIssuer?: string; verifyVendorIdentity?: (input: { provider: "exe.dev" | "fly.io"; vmId: string; token: string; integrationName?: string; expectedIssuer?: string; expectedSubject?: string }) => Promise; }, ) {} @@ -104,7 +105,7 @@ export class MachineJobExecutionBackend implements ExecutionBackend, JobResultRe const token = await acquireFlyMachineOidcToken({ guest, audience }); const expectedSubject = this.options.vendorIdentitySubject?.(machine); if (this.options.vendorIdentitySubject && !expectedSubject) throw new Error("Fly vendor identity subject is unavailable"); - await verifyVendorIdentity({ provider: "fly.io", vmId: machine.id, token, ...(expectedSubject ? { expectedSubject } : {}) }); + await verifyVendorIdentity({ provider: "fly.io", vmId: machine.id, token, ...(this.options.vendorIdentityIssuer ? { expectedIssuer: this.options.vendorIdentityIssuer } : {}), ...(expectedSubject ? { expectedSubject } : {}) }); } const tunnelPrerequisites = request.runProxy ? " && command -v node >/dev/null && command -v openssl >/dev/null" : ""; const installed = await guest.run(["/bin/sh", "-c", `command -v python3 >/dev/null && command -v runuser >/dev/null${tunnelPrerequisites} && id exedev >/dev/null && mkdir -p /usr/local/bin && install -d -o exedev -g exedev -m 0700 /home/exedev/.factorize-job && cat > /usr/local/bin/factorize-job && chmod 0755 /usr/local/bin/factorize-job`], FACTORIZE_JOB_LAUNCHER); @@ -179,7 +180,7 @@ export class MachineJobExecutionBackend implements ExecutionBackend, JobResultRe const token = await acquireFlyMachineOidcToken({ guest: this.options.guest({ id }), audience }); const expectedSubject = this.options.vendorIdentitySubject?.(machine); if (this.options.vendorIdentitySubject && !expectedSubject) throw new Error("Fly vendor identity subject is unavailable"); - await this.options.verifyVendorIdentity({ provider: "fly.io", vmId: id, token, ...(expectedSubject ? { expectedSubject } : {}) }); + await this.options.verifyVendorIdentity({ provider: "fly.io", vmId: id, token, ...(this.options.vendorIdentityIssuer ? { expectedIssuer: this.options.vendorIdentityIssuer } : {}), ...(expectedSubject ? { expectedSubject } : {}) }); } catch { return { state: "failed", detail: "Fly Machine vendor identity renewal failed", failure: { source: "system", code: "vendor_identity_renewal_failed", reason: "Fly Machine vendor identity renewal failed" } }; } diff --git a/packages/api/src/postgres/run-scheduler.ts b/packages/api/src/postgres/run-scheduler.ts index 51a0874e..89fd7ada 100644 --- a/packages/api/src/postgres/run-scheduler.ts +++ b/packages/api/src/postgres/run-scheduler.ts @@ -158,13 +158,13 @@ export class RunScheduler { const app = proxy[1]!; const machines = createFlyMachinesClient({ token: connection }); return new FlyJobExecutionBackend({ - app, organizationName: connectionDetails.organizationName, image: configuration.image, region: configuration.region, size: configuration.size, + app, organizationSlug: connectionDetails.organizationSlug, image: configuration.image, region: configuration.region, size: configuration.size, machines, guest: machine => flyJobGuest({ app, machine: machine.id, token: connection }), proxyIdentity: rows[0]!.proxy_identity, proxyBootEpoch: rows[0]!.boot_epoch, proxyGuest: createFlyCredentialProxyGuest({ app, machine: proxy[2]!, token: connection }), vendorIdentityAudience: runId => `factorize://runs/${runId}`, - verifyVendorIdentity: this.vendorIdentityVerifier(run, `https://oidc.fly.io/${app}`), + verifyVendorIdentity: this.vendorIdentityVerifier(run, `https://oidc.fly.io/${connectionDetails.organizationSlug}`), }); } const kind = run.executionConfig.backendKind ?? (run.executionConfig.agentKind === "Amp" ? "amp" : "exe-vm"); diff --git a/packages/api/src/vendor-run-identity.ts b/packages/api/src/vendor-run-identity.ts index 69e14992..375a7612 100644 --- a/packages/api/src/vendor-run-identity.ts +++ b/packages/api/src/vendor-run-identity.ts @@ -118,7 +118,7 @@ export function createJwksResolver(options: { jwksUri: string; fetcher?: typeof let keys = new Map(), expiresAt = 0; const load = async (force: boolean) => { if (!force && keys.size && now() < expiresAt) return; - const response = await fetcher(options.jwksUri, { headers: { accept: "application/json" } }); + const response = await fetcher(options.jwksUri, { headers: { accept: "application/json" }, redirect: "error", signal: AbortSignal.timeout(10_000) }); if (!response.ok) throw new Error(`Vendor signing keys unavailable (${response.status})`); const body = await response.json() as { keys?: unknown }; if (!Array.isArray(body.keys)) throw new Error("Vendor signing keys response is invalid"); @@ -154,7 +154,7 @@ export async function discoverVendorIssuerTrust(options: { if (options.provider === "fly.io" && !/^\/[A-Za-z0-9-]+\/?$/.test(issuerUrl.pathname)) throw new Error("Fly.io issuer path is invalid"); const issuer = options.issuer.replace(/\/$/, ""); const discoveryUrl = `${issuer}/.well-known/openid-configuration`; - const response = await (options.fetcher ?? fetch)(discoveryUrl, { headers: { accept: "application/json" } }); + const response = await (options.fetcher ?? fetch)(discoveryUrl, { headers: { accept: "application/json" }, redirect: "error", signal: AbortSignal.timeout(10_000) }); if (!response.ok) throw new Error(`Vendor issuer metadata unavailable (${response.status})`); const metadata = await response.json() as { issuer?: unknown; jwks_uri?: unknown }; if (metadata.issuer !== issuer || typeof metadata.jwks_uri !== "string") throw new Error("Vendor issuer metadata does not match the configured issuer"); diff --git a/packages/api/test/fly-job-execution-backend.test.ts b/packages/api/test/fly-job-execution-backend.test.ts index 4fb05940..9053d66d 100644 --- a/packages/api/test/fly-job-execution-backend.test.ts +++ b/packages/api/test/fly-job-execution-backend.test.ts @@ -55,14 +55,32 @@ describe("Fly job execution backend", () => { f.guest.run.mockResolvedValueOnce({ ok: true, exitCode: 0, stdout: token, stderr: "" }); const verify = vi.fn(async () => undefined); const runId = "11111111-1111-4111-8111-111111111111"; - const backend = new FlyJobExecutionBackend({ app: "factorize-test", organizationName: "factorize-org", image: "ghcr.io/acme/code:v1", region: "iad", size: "shared-cpu-1x", machines: f.machines, guest: () => f.guest, verifyVendorIdentity: verify }); + const backend = new FlyJobExecutionBackend({ app: "factorize-test", organizationSlug: "factorize-org", image: "ghcr.io/acme/code:v1", region: "iad", size: "shared-cpu-1x", machines: f.machines, guest: () => f.guest, verifyVendorIdentity: verify }); const receipt = await backend.launch({ runId, prompt: "work" }); expect(receipt.observation.state).toBe("running"); expect(f.guest.run.mock.calls[0]?.[0]).toContain("http://localhost/v1/tokens/oidc"); - expect(verify).toHaveBeenCalledWith({ provider: "fly.io", vmId: "machine-1", token, expectedSubject: "factorize-org:factorize-test:machine-name" }); + expect(verify).toHaveBeenCalledWith({ provider: "fly.io", vmId: "machine-1", token, expectedIssuer: "https://oidc.fly.io/factorize-org", expectedSubject: "factorize-org:factorize-test:machine-name" }); expect(verify.mock.invocationCallOrder[0]).toBeLessThan(f.guest.run.mock.invocationCallOrder.at(-1)!); }); + it("pins the organization slug issuer and subject again during renewal", async () => { + const f = fixture(); + const token = "eyJhbGciOiJSUzI1NiJ9.eyJzdWIiOiJmaXh0dXJlIn0.c2ln"; + f.machines.inspectMachine.mockResolvedValue({ ...machine, state: "started" }); + f.guest.run.mockResolvedValueOnce({ ok: true, exitCode: 0, stdout: token, stderr: "" }); + f.guest.run.mockResolvedValueOnce({ ok: true, exitCode: 0, stdout: '{"state":"running"}', stderr: "" }); + const verify = vi.fn(async () => undefined); + const backend = new FlyJobExecutionBackend({ app: "factorize-test", organizationSlug: "factorize-org", image: "image", region: "iad", size: "shared-cpu-1x", machines: f.machines, guest: () => f.guest, verifyVendorIdentity: verify }); + await backend.inspect({ backendKind: "fly", id: "factorize-test/machine-1", operationId: "11111111-1111-4111-8111-111111111111" }); + expect(verify).toHaveBeenCalledWith({ provider: "fly.io", vmId: machine.id, token, + expectedIssuer: "https://oidc.fly.io/factorize-org", expectedSubject: "factorize-org:factorize-test:machine-name" }); + verify.mockRejectedValueOnce(new Error("issuer mismatch")); + f.guest.run.mockResolvedValueOnce({ ok: true, exitCode: 0, stdout: token, stderr: "" }); + await expect(backend.inspect({ backendKind: "fly", id: "factorize-test/machine-1", operationId: "11111111-1111-4111-8111-111111111111" })).resolves.toMatchObject({ + state: "failed", failure: { code: "vendor_identity_renewal_failed" }, + }); + }); + it("reports a nonzero Fly guest process exit as a failed run", async () => { const f = fixture(); f.machines.inspectMachine.mockResolvedValue({ ...machine, state: "started" }); diff --git a/packages/api/test/vendor-run-identity.test.ts b/packages/api/test/vendor-run-identity.test.ts index 0b2e4371..23b15d43 100644 --- a/packages/api/test/vendor-run-identity.test.ts +++ b/packages/api/test/vendor-run-identity.test.ts @@ -12,7 +12,7 @@ async function token(claims: Record, kid = "key-1", key = priva return `${input}.${btoa(String.fromCharCode(...signature)).replaceAll("+", "-").replaceAll("/", "_").replace(/=+$/, "")}`; } -const flyBinding: VendorRunBinding = { provider: "fly.io", runId: "run-1", activeRunId: "run-1", vmId: "machine-1", issuer: "https://oidc.fly.io/factorize-app", audience: "factorize-run", subject: "org:factorize-app:run-machine", maxTokenAgeSeconds: 600 }; +const flyBinding: VendorRunBinding = { provider: "fly.io", runId: "run-1", activeRunId: "run-1", vmId: "machine-1", issuer: "https://oidc.fly.io/org", audience: "factorize-run", subject: "org:factorize-app:run-machine", maxTokenAgeSeconds: 600 }; const claims = { iss: flyBinding.issuer, sub: flyBinding.subject, aud: flyBinding.audience, iat: now - 10, exp: now + 100, machine_id: flyBinding.vmId }; beforeAll(async () => { @@ -63,6 +63,8 @@ describe("vendor run identity", () => { rotated.kid = "key-2"; const fetches: string[] = []; const resolver = createJwksResolver({ jwksUri: "https://issuer.example/keys", now: () => now * 1000, fetcher: async (_url, init) => { + expect(init?.redirect).toBe("error"); + expect(init?.signal).toBeInstanceOf(AbortSignal); fetches.push(String(init?.headers ? "requested" : "missing-accept")); return Response.json({ keys: fetches.length === 1 ? [publicJwk] : [rotated] }); } }); @@ -78,7 +80,9 @@ describe("vendor run identity", () => { it("loads issuer keys only from matching HTTPS metadata on the vendor origin", async () => { const calls: string[] = []; - const trust = await discoverVendorIssuerTrust({ provider: "fly.io", issuer: flyBinding.issuer, fetcher: async input => { + const trust = await discoverVendorIssuerTrust({ provider: "fly.io", issuer: flyBinding.issuer, fetcher: async (input, init) => { + expect(init?.redirect).toBe("error"); + expect(init?.signal).toBeInstanceOf(AbortSignal); calls.push(String(input)); return Response.json({ issuer: flyBinding.issuer, jwks_uri: "https://oidc.fly.io/keys" }); } }); From bcfe788b4ae1737cbce887b9e77459ceec1a334d Mon Sep 17 00:00:00 2001 From: "exe.dev user" Date: Tue, 17 Nov 2026 14:52:49 +0000 Subject: [PATCH 19/28] Authenticate backend API requests with provisioned vendor run identities --- docs/gen-2922-progress.md | 24 +- docs/vendor-run-identity.md | 24 ++ packages/api-client/src/schema.d.ts | 142 ++++---- packages/api/src/api-contract.ts | 6 +- packages/api/src/exe-vm-backend.ts | 6 + packages/api/src/flow-service.ts | 23 +- packages/api/src/types.ts | 3 +- packages/api/src/vendor-run-auth.ts | 71 ++++ packages/api/src/worker.ts | 6 + .../api/test/vendor-run-auth.postgres.test.ts | 135 ++++++++ packages/docs/openapi.yaml | 324 ++++++++++++------ 11 files changed, 577 insertions(+), 187 deletions(-) create mode 100644 packages/api/src/vendor-run-auth.ts create mode 100644 packages/api/test/vendor-run-auth.postgres.test.ts diff --git a/docs/gen-2922-progress.md b/docs/gen-2922-progress.md index 0609f424..1edeac1a 100644 --- a/docs/gen-2922-progress.md +++ b/docs/gen-2922-progress.md @@ -14,8 +14,11 @@ complete or release the breaking change until every remaining gate passes. same pinned issuer/subject on launch and renewal. - [x] Reject redirects and bound discovery/JWKS fetches to ten seconds. - [x] Live vendor signature verification described below. -- [ ] Vendor identity authentication on each backend API/proxy request. Current run - bearer credentials and standalone proxy admission still exist. +- [x] Vendor identity authentication at the existing backend API/MCP boundary, + with fixture coverage for scope snapshots, eligibility/revocation, invocation + permissions, invalid tokens and fresh exe.dev attachment checks. +- [ ] Adopt vendor authentication in guest/runtime setup and outbound forwarding. + Current run bearer credentials and standalone proxy admission still exist. - [ ] Move outbound forwarding and model authentication/refresh into the backend. - [ ] Replace runtime provisioning, guest discovery/client setup and scheduler gates. - [ ] Remove standalone proxy/pairing/unlock API, UI, configuration and dependencies. @@ -53,7 +56,8 @@ to `expressway-by-scraper` with a one-hour grant: subject, VM and inactive run were rejected. - The unattached VM `factorize-gen2922-validation` received HTTP 403 from that endpoint. No assumption was made that the WIF subject itself identifies a VM. -- Temporary WIF integration cleanup and validation VM cleanup are pending. +- Temporary WIF integration removed after the test. The isolated validation VM + is retained while implementation and required local validation continue. Signing-key rotation, database revocation, terminal/canceled runs, cross-tenant isolation and provider requests remain deterministic fixture evidence until the @@ -66,3 +70,17 @@ Fly backend suites: 32 tests passed. Root local validation on the development VM stopped before tests because its PostgreSQL password does not match the runner configuration. No host repair was attempted. A new isolated exe.dev VM is booted from the documented immutable validation-runner image for the required suite. + + +The complete root suite at `47ccf62` passed on a fresh exe.dev VM using the +pinned validation image: backend, static slice, functional/browser unit, proxy, +and Docker E2E lanes all passed. SSH does not inherit the OCI browser-path +environment; the image's existing login profile supplies it. The image smoke +was run through a root login shell (and itself launches a non-login `exedev` +Chromium process), and validation through an `exedev` login shell. This is not +evidence that non-login Factorize job processes inherit OCI environment on +exe.dev; that separate runner-image gate remains unchanged. + +The request-admission fixture suite adds five PostgreSQL/Worker tests and +passed in the isolated validation VM. Complete validation of that follow-up +commit is pending. diff --git a/docs/vendor-run-identity.md b/docs/vendor-run-identity.md index 6d3a3738..b4817ccf 100644 --- a/docs/vendor-run-identity.md +++ b/docs/vendor-run-identity.md @@ -62,3 +62,27 @@ run binding in these checks was explicit test input, not a production run or an end-to-end backend proxy session. See [the completion ledger](gen-2922-progress.md) for the remaining runtime and cutover gates. The existing proxy admission and proxy identity remain outside this verification evidence. + + +## Backend request authentication + +A VM can call the existing `/api/v1` and `/mcp` boundaries with a fresh vendor +JWT in `Authorization: Bearer ...` and its provisioned UUID in +`X-Factorize-Run-Id`. The UUID is only a lookup hint: Factorize reads the tenant, +owner/session binding, immutable vendor/VM binding and scope snapshot from its +database. It verifies the signature and exact stored issuer, subject, audience +and VM for every request. A vendor token alone grants no access. An invalid +run-identity request cannot fall back to another authentication method. + +Admission requires both execution records to remain starting/running/blocked, +an unrevoked binding, a matching persisted execution handle, and a connected +execution provider. exe.dev additionally rechecks its exclusive WIF attachment +through provider inventory on every admission. Fly pins the connected +organization slug and app/Machine association. Job edits cannot broaden the +active run's API scopes; an empty scope snapshot remains empty. A run with +`jobs:write` cannot grant itself new invocation destinations. + +This request path is implemented alongside the old launch/runtime path while +GEN-2922 remains in progress. Guest setup still needs to adopt it, and old run +bearer authentication must be removed during the breaking cutover. It is not +completion or release evidence for that cutover. diff --git a/packages/api-client/src/schema.d.ts b/packages/api-client/src/schema.d.ts index 38b96713..3736d1a2 100644 --- a/packages/api-client/src/schema.d.ts +++ b/packages/api-client/src/schema.d.ts @@ -571,7 +571,7 @@ export interface paths { * Get template autocomplete metadata * @description Requires the jobs:read scope. * - * Accepts a scoped bearer token or interactive owner session. + * Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. */ get: operations["get_api_v1_trigger_contexts"]; put?: never; @@ -593,7 +593,7 @@ export interface paths { * List exe connections * @description Requires the integrations:read scope. * - * Accepts a scoped bearer token or interactive owner session. + * Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. */ get: operations["get_api_v1_exe_connections"]; put?: never; @@ -615,7 +615,7 @@ export interface paths { * List GitHub installations * @description Requires the integrations:read scope. * - * Accepts a scoped bearer token or interactive owner session. + * Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. */ get: operations["get_api_v1_github_installations"]; put?: never; @@ -637,7 +637,7 @@ export interface paths { * List available trigger kinds * @description Requires the jobs:read scope. * - * Accepts a scoped bearer token or interactive owner session. + * Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. */ get: operations["get_api_v1_job_trigger_availability"]; put?: never; @@ -661,7 +661,7 @@ export interface paths { * Preview schedule * @description Requires the jobs:read scope. * - * Accepts a scoped bearer token or interactive owner session. + * Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. */ post: operations["post_api_v1_schedules_preview"]; delete?: never; @@ -681,7 +681,7 @@ export interface paths { * List Tail integrations * @description Requires the integrations:read scope. * - * Accepts a scoped bearer token or interactive owner session. + * Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. */ get: operations["get_api_v1_integrations_cloudflare_tail"]; put?: never; @@ -689,7 +689,7 @@ export interface paths { * Create a Tail integration * @description Requires the integrations:write scope. * - * Accepts a scoped bearer token or interactive owner session. + * Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. */ post: operations["post_api_v1_integrations_cloudflare_tail"]; delete?: never; @@ -709,7 +709,7 @@ export interface paths { * List installed integrations * @description Requires the integrations:read scope. * - * Accepts a scoped bearer token or interactive owner session. + * Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. */ get: operations["get_api_v1_integrations"]; put?: never; @@ -862,7 +862,7 @@ export interface paths { * Create an exe.dev integration * @description Requires the integrations:write scope. * - * Accepts a scoped bearer token or interactive owner session. + * Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. */ put: operations["put_api_v1_integrations_exe"]; post?: never; @@ -885,7 +885,7 @@ export interface paths { * Test exe.dev credentials * @description Requires the integrations:write scope. * - * Accepts a scoped bearer token or interactive owner session. + * Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. */ post: operations["post_api_v1_integrations_exe_test"]; delete?: never; @@ -906,7 +906,7 @@ export interface paths { * Create an Amp integration * @description Requires the integrations:write scope. * - * Accepts a scoped bearer token or interactive owner session. + * Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. */ put: operations["put_api_v1_integrations_amp"]; post?: never; @@ -929,7 +929,7 @@ export interface paths { * Test Amp credentials * @description Requires the integrations:write scope. * - * Accepts a scoped bearer token or interactive owner session. + * Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. */ post: operations["post_api_v1_integrations_amp_test"]; delete?: never; @@ -949,7 +949,7 @@ export interface paths { * List Linear projects * @description Requires the integrations:read scope. * - * Accepts a scoped bearer token or interactive owner session. + * Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. */ get: operations["get_api_v1_providers_linear_projects"]; put?: never; @@ -971,7 +971,7 @@ export interface paths { * List Linear trigger options * @description Requires the integrations:read scope. * - * Accepts a scoped bearer token or interactive owner session. + * Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. */ get: operations["get_api_v1_providers_linear_options"]; put?: never; @@ -993,7 +993,7 @@ export interface paths { * List ClickUp lists * @description Requires the integrations:read scope. * - * Accepts a scoped bearer token or interactive owner session. + * Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. */ get: operations["get_api_v1_providers_clickup_lists"]; put?: never; @@ -1015,7 +1015,7 @@ export interface paths { * List ClickUp trigger options * @description Requires the integrations:read scope. * - * Accepts a scoped bearer token or interactive owner session. + * Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. */ get: operations["get_api_v1_providers_clickup_options"]; put?: never; @@ -1037,7 +1037,7 @@ export interface paths { * List GitHub installations for provider setup * @description Requires the integrations:read scope. * - * Accepts a scoped bearer token or interactive owner session. + * Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. */ get: operations["get_api_v1_providers_github_installations"]; put?: never; @@ -1156,7 +1156,7 @@ export interface paths { * Remove an exe.dev integration * @description Requires the integrations:write scope. * - * Accepts a scoped bearer token or interactive owner session. + * Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. */ delete: operations["delete_api_v1_integrations_exe_connectionId"]; options?: never; @@ -1178,7 +1178,7 @@ export interface paths { * Remove an Amp integration * @description Requires the integrations:write scope. * - * Accepts a scoped bearer token or interactive owner session. + * Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. */ delete: operations["delete_api_v1_integrations_amp_connectionId"]; options?: never; @@ -1198,7 +1198,7 @@ export interface paths { * Update a Tail integration * @description Requires the integrations:write scope. * - * Accepts a scoped bearer token or interactive owner session. + * Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. */ put: operations["put_api_v1_integrations_cloudflare_tail_integrationId"]; post?: never; @@ -1206,7 +1206,7 @@ export interface paths { * Remove a Tail integration * @description Requires the integrations:write scope. * - * Accepts a scoped bearer token or interactive owner session. + * Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. */ delete: operations["delete_api_v1_integrations_cloudflare_tail_integrationId"]; options?: never; @@ -1227,7 +1227,7 @@ export interface paths { * Test a Tail integration * @description Requires the integrations:write scope. * - * Accepts a scoped bearer token or interactive owner session. + * Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. */ post: operations["post_api_v1_integrations_cloudflare_tail_integrationId_test"]; delete?: never; @@ -1247,7 +1247,7 @@ export interface paths { * List installation repositories * @description Requires the integrations:read scope. * - * Accepts a scoped bearer token or interactive owner session. + * Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. */ get: operations["get_api_v1_providers_github_installations_installationId_repositories"]; put?: never; @@ -1269,7 +1269,7 @@ export interface paths { * List GitHub issue trigger options * @description Requires the integrations:read scope. * - * Accepts a scoped bearer token or interactive owner session. + * Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. */ get: operations["get_api_v1_providers_github_installations_installationId_repositories_repositoryId_issue_options"]; put?: never; @@ -1294,7 +1294,7 @@ export interface paths { * Disconnect a GitHub installation * @description Requires the integrations:write scope. * - * Accepts a scoped bearer token or interactive owner session. + * Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. */ delete: operations["delete_api_v1_providers_github_installations_installationId"]; options?: never; @@ -1315,7 +1315,7 @@ export interface paths { * Probe exe.dev permissions and a disposable VM's agent/model integration * @description Requires the integrations:write scope. * - * Accepts a scoped bearer token or interactive owner session. + * Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. */ post: operations["post_api_v1_integrations_exe_connectionId_diagnostics"]; delete?: never; @@ -1337,7 +1337,7 @@ export interface paths { * * Requires the jobs:read scope. * - * Accepts a scoped bearer token or interactive owner session. + * Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. */ get: operations["get_api_v1_job_summaries"]; put?: never; @@ -1359,7 +1359,7 @@ export interface paths { * Search bounded lifecycle job options * @description Requires the jobs:read scope. * - * Accepts a scoped bearer token or interactive owner session. + * Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. */ get: operations["get_api_v1_job_selector"]; put?: never; @@ -1381,7 +1381,7 @@ export interface paths { * List projects * @description Requires the projects:read scope. * - * Accepts a scoped bearer token or interactive owner session. + * Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. */ get: operations["get_api_v1_projects"]; put?: never; @@ -1389,7 +1389,7 @@ export interface paths { * Create project * @description Requires the projects:write scope. * - * Accepts a scoped bearer token or interactive owner session. + * Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. */ post: operations["post_api_v1_projects"]; delete?: never; @@ -1409,14 +1409,14 @@ export interface paths { * Get project * @description Requires the projects:read scope. * - * Accepts a scoped bearer token or interactive owner session. + * Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. */ get: operations["get_api_v1_projects_projectId"]; /** * Update project * @description Requires the projects:write scope. * - * Accepts a scoped bearer token or interactive owner session. + * Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. */ put: operations["put_api_v1_projects_projectId"]; post?: never; @@ -1424,7 +1424,7 @@ export interface paths { * Delete empty project * @description Requires the projects:write scope. * - * Accepts a scoped bearer token or interactive owner session. + * Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. */ delete: operations["delete_api_v1_projects_projectId"]; options?: never; @@ -1445,7 +1445,7 @@ export interface paths { * * Requires the projects:read scope. * - * Accepts a scoped bearer token or interactive owner session. + * Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. */ get: operations["get_api_v1_projects_projectId_graph"]; put?: never; @@ -1467,7 +1467,7 @@ export interface paths { * Search global skills * @description Requires the skills:read scope. * - * Accepts a scoped bearer token or interactive owner session. + * Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. */ get: operations["get_api_v1_skills"]; put?: never; @@ -1475,7 +1475,7 @@ export interface paths { * Create a global skill * @description Requires the skills:write scope. * - * Accepts a scoped bearer token or interactive owner session. + * Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. */ post: operations["post_api_v1_skills"]; delete?: never; @@ -1497,7 +1497,7 @@ export interface paths { * Preview a composed job prompt * @description Requires the skills:read scope. * - * Accepts a scoped bearer token or interactive owner session. + * Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. */ post: operations["post_api_v1_skills_preview"]; delete?: never; @@ -1517,14 +1517,14 @@ export interface paths { * Get a global skill * @description Requires the skills:read scope. * - * Accepts a scoped bearer token or interactive owner session. + * Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. */ get: operations["get_api_v1_skills_skillId"]; /** * Update a global skill * @description Requires the skills:write scope. * - * Accepts a scoped bearer token or interactive owner session. + * Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. */ put: operations["put_api_v1_skills_skillId"]; post?: never; @@ -1532,7 +1532,7 @@ export interface paths { * Delete an unused global skill * @description Requires the skills:write scope. * - * Accepts a scoped bearer token or interactive owner session. + * Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. */ delete: operations["delete_api_v1_skills_skillId"]; options?: never; @@ -1551,7 +1551,7 @@ export interface paths { * List jobs using a skill * @description Requires the skills:read scope. * - * Accepts a scoped bearer token or interactive owner session. + * Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. */ get: operations["get_api_v1_skills_skillId_jobs"]; put?: never; @@ -1575,7 +1575,7 @@ export interface paths { * Move a job to a project * @description Requires the projects:write scope. * - * Accepts a scoped bearer token or interactive owner session. + * Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. */ post: operations["post_api_v1_jobs_jobId_project"]; delete?: never; @@ -1599,7 +1599,7 @@ export interface paths { * * Requires the jobs:write scope. * - * Accepts a scoped bearer token or interactive owner session. + * Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. */ post: operations["post_api_v1_vm_image_verifications"]; delete?: never; @@ -1619,7 +1619,7 @@ export interface paths { * Get VM image verification progress * @description Requires the jobs:read scope. * - * Accepts a scoped bearer token or interactive owner session. + * Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. */ get: operations["get_api_v1_vm_image_verifications_verificationId"]; put?: never; @@ -1641,7 +1641,7 @@ export interface paths { * List jobs * @description Requires the jobs:read scope. * - * Accepts a scoped bearer token or interactive owner session. + * Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. */ get: operations["get_api_v1_jobs"]; put?: never; @@ -1649,7 +1649,7 @@ export interface paths { * Create job * @description Requires the jobs:write scope. * - * Accepts a scoped bearer token or interactive owner session. + * Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. */ post: operations["post_api_v1_jobs"]; delete?: never; @@ -1673,7 +1673,7 @@ export interface paths { * * Requires the jobs:write scope. * - * Accepts a scoped bearer token or interactive owner session. + * Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. */ post: operations["post_api_v1_job_conditions_test"]; delete?: never; @@ -1695,7 +1695,7 @@ export interface paths { * Invoke job * @description Requires the runs:invoke scope. * - * Accepts a scoped bearer token or interactive owner session. + * Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. */ post: operations["post_api_v1_jobs_jobId_invocations"]; delete?: never; @@ -1715,7 +1715,7 @@ export interface paths { * Inspect the current runtime identity and scopes * @description Returns the verified calling identity and effective scopes without credentials. Requires a verified active identity but no application-resource scope; callers with zero scopes can inspect only their own identity. Execution provisioning uses this operation to verify the dedicated run proxy. Execution VMs must not have additional shared Factorize proxy attachments. * - * Accepts a scoped bearer token or interactive owner session. + * Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. */ get: operations["get_api_v1_runtime_context"]; put?: never; @@ -1737,7 +1737,7 @@ export interface paths { * List a source job's manual invocation destinations * @description Requires the jobs:read scope. * - * Accepts a scoped bearer token or interactive owner session. + * Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. */ get: operations["get_api_v1_jobs_jobId_invocation_permissions"]; /** @@ -1746,7 +1746,7 @@ export interface paths { * * Requires the jobs:write scope. * - * Accepts a scoped bearer token or interactive owner session. + * Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. */ put: operations["put_api_v1_jobs_jobId_invocation_permissions"]; post?: never; @@ -1767,7 +1767,7 @@ export interface paths { * List webhook activity * @description Requires the runs:read scope. * - * Accepts a scoped bearer token or interactive owner session. + * Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. */ get: operations["get_api_v1_jobs_jobId_events"]; put?: never; @@ -1791,7 +1791,7 @@ export interface paths { * Enable job * @description Requires the jobs:write scope. * - * Accepts a scoped bearer token or interactive owner session. + * Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. */ post: operations["post_api_v1_jobs_jobId_enable"]; delete?: never; @@ -1813,7 +1813,7 @@ export interface paths { * Disable job * @description Requires the jobs:write scope. * - * Accepts a scoped bearer token or interactive owner session. + * Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. */ post: operations["post_api_v1_jobs_jobId_disable"]; delete?: never; @@ -1833,7 +1833,7 @@ export interface paths { * Get job * @description Requires the jobs:read scope. * - * Accepts a scoped bearer token or interactive owner session. + * Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. */ get: operations["get_api_v1_jobs_jobId"]; /** @@ -1842,7 +1842,7 @@ export interface paths { * * Requires the jobs:write scope. * - * Accepts a scoped bearer token or interactive owner session. + * Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. */ put: operations["put_api_v1_jobs_jobId"]; post?: never; @@ -1850,7 +1850,7 @@ export interface paths { * Delete job * @description Requires the jobs:write scope. * - * Accepts a scoped bearer token or interactive owner session. + * Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. */ delete: operations["delete_api_v1_jobs_jobId"]; options?: never; @@ -1871,7 +1871,7 @@ export interface paths { * * Requires the runs:read scope. * - * Accepts a scoped bearer token or interactive owner session. + * Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. */ get: operations["get_api_v1_runs"]; put?: never; @@ -1895,7 +1895,7 @@ export interface paths { * * Requires the jobs:read and runs:read scopes. * - * Accepts a scoped bearer token or interactive owner session. + * Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. */ get: operations["get_api_v1_search"]; put?: never; @@ -1917,7 +1917,7 @@ export interface paths { * Search webhook deliveries * @description Requires the runs:read scope. * - * Accepts a scoped bearer token or interactive owner session. + * Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. */ get: operations["get_api_v1_webhooks_deliveries"]; put?: never; @@ -1939,7 +1939,7 @@ export interface paths { * Get webhook delivery detail and processing timeline * @description Requires the runs:read scope. * - * Accepts a scoped bearer token or interactive owner session. + * Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. */ get: operations["get_api_v1_webhooks_deliveries_deliveryId"]; put?: never; @@ -1963,7 +1963,7 @@ export interface paths { * * Requires the runs:read scope. * - * Accepts a scoped bearer token or interactive owner session. + * Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. */ get: operations["get_api_v1_runs_runId_status"]; put?: never; @@ -1985,7 +1985,7 @@ export interface paths { * Download a retained run artifact * @description Requires the runs:read scope. * - * Accepts a scoped bearer token or interactive owner session. + * Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. */ get: operations["get_api_v1_runs_runId_artifacts_artifactId"]; put?: never; @@ -2009,7 +2009,7 @@ export interface paths { * * Requires the runs:read scope. * - * Accepts a scoped bearer token or interactive owner session. + * Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. */ get: operations["get_api_v1_runs_runId_trace_pages"]; put?: never; @@ -2031,7 +2031,7 @@ export interface paths { * Get run * @description Requires the runs:read scope. * - * Accepts a scoped bearer token or interactive owner session. + * Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. */ get: operations["get_api_v1_runs_runId"]; put?: never; @@ -2045,7 +2045,7 @@ export interface paths { * * Requires the runs:write scope. * - * Accepts a scoped bearer token or interactive owner session. + * Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. */ patch: operations["patch_api_v1_runs_runId"]; trace?: never; @@ -2065,7 +2065,7 @@ export interface paths { * * Requires the runs:write scope. * - * Accepts a scoped bearer token or interactive owner session. + * Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. */ post: operations["post_api_v1_runs_runId_report_error"]; delete?: never; @@ -2085,7 +2085,7 @@ export interface paths { * Get paginated run trace events * @description Requires the runs:read scope. * - * Accepts a scoped bearer token or interactive owner session. + * Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. */ get: operations["get_api_v1_runs_runId_trace"]; put?: never; @@ -2131,7 +2131,7 @@ export interface paths { * Get credential-safe run lifecycle diagnostics * @description Requires the runs:read scope. * - * Accepts a scoped bearer token or interactive owner session. + * Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. */ get: operations["get_api_v1_runs_runId_diagnostics"]; put?: never; @@ -2155,7 +2155,7 @@ export interface paths { * Stop run * @description Requires the runs:cancel scope. * - * Accepts a scoped bearer token or interactive owner session. + * Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. */ post: operations["post_api_v1_runs_runId_stop"]; delete?: never; @@ -2201,7 +2201,7 @@ export interface paths { * Kill run and immediately release its concurrency slot * @description Requires the runs:cancel scope. * - * Accepts a scoped bearer token or interactive owner session. + * Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. */ post: operations["post_api_v1_runs_runId_kill"]; delete?: never; diff --git a/packages/api/src/api-contract.ts b/packages/api/src/api-contract.ts index c244f539..e295e1a9 100644 --- a/packages/api/src/api-contract.ts +++ b/packages/api/src/api-contract.ts @@ -1305,13 +1305,13 @@ export function generateOpenApi() { route.authOperation || (Array.isArray(route.scope) && route.scope.length === 0) ? undefined : `Requires the ${Array.isArray(route.scope) ? route.scope.join(" and ") : route.scope.replaceAll("+", " and ")} scope${Array.isArray(route.scope) || route.scope.includes("+") ? "s" : ""}.`, route.authOperation ? undefined : route.ownerSession ? "An interactive owner session is required; bearer tokens cannot call this operation." - : "Accepts a scoped bearer token or interactive owner session.", + : "Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session.", ] .filter(Boolean) .join("\n\n"), operationId: `${route.method.toLowerCase()}_${route.path.replace(/[^a-zA-Z0-9]+/g, "_").replace(/^_|_$/g, "")}`, tags: [route.path.split("/")[3]], - security: route.authOperation ? (route.ownerSession ? [{ cookieAuth: [] }] : []) : [{ bearerAuth: [] }, { cookieAuth: [] }], + security: route.authOperation ? (route.ownerSession ? [{ cookieAuth: [] }] : []) : route.ownerSession ? [{ cookieAuth: [] }] : [{ bearerAuth: [] }, { vendorRunIdentity: [], runIdentityHeader: [] }, { cookieAuth: [] }], ...(route.authOperation ? { "x-browser-auth-operation": route.authOperation } : { "x-required-scope": route.scope }), "x-owner-session-required": route.ownerSession, ...(parameters.length ? { parameters } : {}), @@ -1330,7 +1330,7 @@ export function generateOpenApi() { } return { ...document, - components: { ...document.components, securitySchemes: { ...document.components.securitySchemes, cookieAuth: { type: "apiKey", in: "cookie", name: "factorize_session" } }, schemas, responses: errorResponses }, + components: { ...document.components, securitySchemes: { ...document.components.securitySchemes, cookieAuth: { type: "apiKey", in: "cookie", name: "factorize_session" }, vendorRunIdentity: { type: "http", scheme: "bearer", bearerFormat: "JWT", description: "Fresh vendor-signed exe.dev WIF or Fly Machine OIDC token matching the provisioned active run. Must be combined with X-Factorize-Run-Id; a vendor token alone grants no access." }, runIdentityHeader: { type: "apiKey", in: "header", name: "X-Factorize-Run-Id", description: "Provisioned run UUID. Used only to locate the immutable vendor/VM binding; this header is not a credential. Scopes and tenant come from the server-side run snapshot." } }, schemas, responses: errorResponses }, paths, }; } diff --git a/packages/api/src/exe-vm-backend.ts b/packages/api/src/exe-vm-backend.ts index a55e5d7e..bbb5484b 100644 --- a/packages/api/src/exe-vm-backend.ts +++ b/packages/api/src/exe-vm-backend.ts @@ -91,6 +91,12 @@ export class ExeVmBackend implements ExecutionBackend { } catch { throw new Error("exe.dev WIF integration metadata is invalid"); } } + /** Read-only provider check used on every backend request admission. */ + async verifyIdentityAttachment(vm: string, runId: string): Promise { + if (vm !== vmNameFor(runId)) throw new Error("exe.dev VM/run mismatch"); + return this.ensureExeWif(vm, runId, false); + } + private async removeExeWif(vm: string, runId: string, name: string): Promise { if (name !== exeWifIntegrationNameFor(runId)) throw new Error("Refusing to remove an unrelated exe.dev WIF integration"); const listed = await this.api("integrations list --json"); diff --git a/packages/api/src/flow-service.ts b/packages/api/src/flow-service.ts index d21cc047..6d3abd75 100644 --- a/packages/api/src/flow-service.ts +++ b/packages/api/src/flow-service.ts @@ -250,7 +250,7 @@ export class ApiService { await this.authorize("runs:write"); const parsed = reportRunErrorSchema.parse(input), reason = safeDiagnosticText(parsed.reason, 1000); if (!reason.trim()) throw new ServiceError(400, "invalid_request", "Reason must contain safe text."); - const reporterKind = this.auth.authMethod === "oauth" ? "oauth" : this.auth.authMethod === "access_token" ? "api_key" : this.auth.authMethod === "run_token" ? "run_token" : "session"; + const reporterKind = this.auth.authMethod === "oauth" ? "oauth" : this.auth.authMethod === "access_token" ? "api_key" : (this.auth.authMethod === "run_token" || this.auth.authMethod === "vendor_identity") ? "run_token" : "session"; const reporterId = reporterKind === "oauth" ? this.auth.oauthGrantId && this.auth.oauthClientId ? `${this.auth.oauthClientId}:${this.auth.oauthGrantId}` : undefined : reporterKind === "api_key" ? this.auth.accessTokenId : reporterKind === "run_token" ? this.auth.runId : this.auth.userId; if (!reporterId) throw new ServiceError(403, "invalid_token", "Authenticated reporter identity is unavailable."); const result = await new RunRepository(databaseFor(this.env)).reportAgentError({ tenantId: this.auth.tenantId, runId, reason, userId: this.auth.userId, reporterKind, reporterId }); @@ -475,9 +475,17 @@ export class ApiService { async setJobEnabled(jobId: string, enabled: boolean) { await this.authorize("jobs:write"); const repository = this.jobs(); if (!await repository.setEnabled(jobId, enabled, new Date().toISOString())) throw new ServiceError(404, "not_found", "Job not found"); await this.wakeScheduler(); return { id: jobId, enabled }; } async invokeJob(jobId: string, input: ManualInvocationInput) { await this.authorize("runs:invoke"); const repository = this.jobs(), job = await repository.getJob(jobId); if (!job) throw new ServiceError(404, "not_found", "Job not found"); - if (this.auth.authMethod === "run_token") { + if (this.auth.authMethod === "run_token" || this.auth.authMethod === "vendor_identity") { if (!this.auth.runId || !this.auth.runJobId) throw new ServiceError(401, "invalid_token", "A verified run identity is required."); - const permission = await databaseFor(this.env).pool.query(`SELECT 1 FROM app.run_credentials c + const permission = this.auth.authMethod === "vendor_identity" + ? await databaseFor(this.env).pool.query(`SELECT 1 FROM app.vendor_run_identity_bindings b + JOIN app.job_runs r ON r.tenant_id=b.tenant_id AND r.id=b.run_id + JOIN app.jobs source ON source.tenant_id=r.tenant_id AND source.id=r.job_id + JOIN app.jobs destination ON destination.tenant_id=source.tenant_id AND destination.id=$3 AND destination.project_id=source.project_id + JOIN app.manual_invocation_permissions p ON p.tenant_id=b.tenant_id AND p.source_job_id=r.job_id AND p.destination_job_id=$3 + WHERE b.tenant_id=$1 AND b.run_id=$2 AND b.provider=$4 AND b.revoked_at IS NULL + AND r.state IN ('starting','running','blocked')`, [this.auth.tenantId, this.auth.runId, jobId, this.auth.runIdentityProvider]) + : await databaseFor(this.env).pool.query(`SELECT 1 FROM app.run_credentials c JOIN app.job_runs r ON r.tenant_id=c.tenant_id AND r.id=c.run_id JOIN app.jobs source ON source.tenant_id=r.tenant_id AND source.id=r.job_id JOIN app.jobs destination ON destination.tenant_id=source.tenant_id AND destination.id=$3 AND destination.project_id=source.project_id @@ -487,8 +495,8 @@ export class ApiService { } const trigger = job.triggers.find(value => value.kind === "manual" && value.enabled); if (!trigger) throw new ServiceError(409, "operation_failed", "The manual trigger is disabled"); const service = new InvocationService(repository, value => encrypt(value, this.env.CREDENTIAL_ENCRYPTION_KEY)); - const claimKey = input.idempotencyKey ? `manual:${this.auth.authMethod === "run_token" ? `run:${this.auth.runId}:` : ""}${input.idempotencyKey}` : `manual:${crypto.randomUUID()}`; - const result = await service.invoke(jobId, { source: "manual", name: input.name, triggerId: trigger.id, claimKey, ...(this.auth.authMethod === "run_token" ? { sourceJobId: this.auth.runJobId, sourceRunId: this.auth.runId } : {}), context: { [trigger.slug]: { prompt: input.prompt, data: input.data ?? {} } } }); + const claimKey = input.idempotencyKey ? `manual:${(this.auth.authMethod === "run_token" || this.auth.authMethod === "vendor_identity") ? `run:${this.auth.runId}:` : ""}${input.idempotencyKey}` : `manual:${crypto.randomUUID()}`; + const result = await service.invoke(jobId, { source: "manual", name: input.name, triggerId: trigger.id, claimKey, ...((this.auth.authMethod === "run_token" || this.auth.authMethod === "vendor_identity") ? { sourceJobId: this.auth.runJobId, sourceRunId: this.auth.runId } : {}), context: { [trigger.slug]: { prompt: input.prompt, data: input.data ?? {} } } }); if (this.env.SCHEDULER) await this.env.SCHEDULER.get(this.env.SCHEDULER.idFromName("global")).fetch("https://scheduler/wake", { method: "POST" }); return { invocationId: result.invocation.id, runId: result.run.id, state: result.run.state, duplicate: result.duplicate }; } @@ -503,9 +511,8 @@ export class ApiService { } async setInvocationPermissions(sourceJobId: string, destinationJobIds: string[]) { await this.authorize("jobs:write"); - // Run credentials intentionally have a read/invoke-only scope set. Keep this - // service guard as defense in depth if a future run credential gains scopes. - if (this.auth.authMethod === "run_token") throw new ServiceError(403, "insufficient_scope", "Run credentials cannot change invocation permissions."); + // A run with jobs:write still cannot expand its invocation destinations. + if (this.auth.authMethod === "run_token" || this.auth.authMethod === "vendor_identity") throw new ServiceError(403, "insufficient_scope", "Run credentials cannot change invocation permissions."); const unique = [...new Set(destinationJobIds)]; if (unique.length !== destinationJobIds.length) throw new ServiceError(400, "invalid_request", "Destination jobs must be unique."); const db = databaseFor(this.env); diff --git a/packages/api/src/types.ts b/packages/api/src/types.ts index c98daa28..f72cc575 100644 --- a/packages/api/src/types.ts +++ b/packages/api/src/types.ts @@ -55,10 +55,11 @@ export type OAuthProps = { runId?: string; runJobId?: string; runCredentialDigest?: string; + runIdentityProvider?: "exe.dev" | "fly.io"; /** Stable identifier for the OAuth authorization grant; never a bearer token. */ oauthGrantId?: string; oauthClientId?: string; - authMethod?: "session" | "oauth" | "access_token" | "run_token"; + authMethod?: "session" | "oauth" | "access_token" | "run_token" | "vendor_identity"; }; export interface WorkItem { diff --git a/packages/api/src/vendor-run-auth.ts b/packages/api/src/vendor-run-auth.ts new file mode 100644 index 00000000..ead41dd5 --- /dev/null +++ b/packages/api/src/vendor-run-auth.ts @@ -0,0 +1,71 @@ +import type { Env, OAuthProps } from "./types"; +import { databaseFor } from "./postgres/database"; +import { ConnectionRepository } from "./postgres/connection-repository"; +import { FlyConnectionRepository } from "./postgres/fly-connection-repository"; +import { ExeVmBackend, vmNameFor } from "./exe-vm-backend"; +import type { ExeRunConnection } from "./exe"; +import { normalizeScopes } from "./access-tokens"; +import { discoverVendorIssuerTrust, verifyVendorRunIdentity, type VendorIdentityProvider } from "./vendor-run-identity"; + +export const RUN_IDENTITY_HEADER = "X-Factorize-Run-Id"; +const uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; + +type RunAuthorization = { + tenant_id: string; run_id: string; job_id: string; user_id: string; session_version: number; + scopes: string[]; provider: VendorIdentityProvider; vm_id: string; issuer: string; + subject: string; audience: string; execution_config: Record; + execution_handle: { id?: string; vendorIdentityIntegrationName?: string } | null; +}; + +/** A run ID is a lookup hint, never authority. Only a fresh vendor signature + * matching the immutable provisioned binding can authorize this request. */ +export async function authenticateVendorRunRequest(request: Request, env: Env): Promise { + const runId = request.headers.get(RUN_IDENTITY_HEADER); + const token = request.headers.get("Authorization")?.match(/^Bearer ([A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+)$/)?.[1]; + if (!runId || !uuid.test(runId) || !token || token.length > 16_384) return null; + const database = databaseFor(env); + const result = await database.pool.query(`SELECT b.tenant_id,b.run_id,b.provider,b.vm_id,b.issuer,b.subject,b.audience, + c.user_id,c.session_version,c.scopes,j.job_id,r.execution_config,r.execution_handle + FROM app.vendor_run_identity_bindings b + JOIN app.job_runs j ON j.tenant_id=b.tenant_id AND j.id=b.run_id + JOIN app.runs r ON r.tenant_id=j.tenant_id AND r.id=j.id + JOIN app.run_credentials c ON c.tenant_id=j.tenant_id AND c.run_id=j.id + JOIN app.members m ON m.tenant_id=c.tenant_id AND m.user_id=c.user_id AND m.role='owner' AND m.session_version=c.session_version + WHERE b.run_id=$1 AND b.revoked_at IS NULL AND j.state IN ('starting','running','blocked') + AND r.state IN ('starting','running','blocked')`, [runId]); + // Fail closed on ambiguous cross-tenant/run/provider lookup as well as absence. + if (result.rows.length !== 1) return null; + const row = result.rows[0]!; + try { + let exeAttachment: { integrationName: string; attachedVmId: string; mode: "vm" } | undefined; + if (row.provider === "exe.dev") { + if (row.vm_id !== vmNameFor(runId) || row.execution_handle?.id !== row.vm_id) return null; + const connectionId = row.execution_config.connectionId; + if (typeof connectionId !== "string") return null; + const connection = await new ConnectionRepository(database, row.tenant_id, env.CREDENTIAL_ENCRYPTION_KEY).get(`exe:${connectionId}`); + if (!connection) return null; + // Re-read provider inventory on every admission. A valid integration JWT + // alone is insufficient if someone broadened or moved its attachment. + const attachment = await new ExeVmBackend(connection).verifyIdentityAttachment(row.vm_id, runId); + if (attachment.issuer !== row.issuer || attachment.subject !== row.subject || attachment.audience !== row.audience) return null; + exeAttachment = { integrationName: attachment.integrationName, attachedVmId: row.vm_id, mode: "vm" }; + } else if (row.provider === "fly.io") { + const connection = await new FlyConnectionRepository(database, row.tenant_id, env.CREDENTIAL_ENCRYPTION_KEY).get(); + const parts = row.execution_handle?.id?.split("/"); + if (!connection || !parts || parts.length !== 2 || parts[1] !== row.vm_id + || row.issuer !== `https://oidc.fly.io/${connection.organizationSlug}` + || !row.subject.startsWith(`${connection.organizationSlug}:${parts[0]}:`)) return null; + } else return null; + const trust = await discoverVendorIssuerTrust({ provider: row.provider, issuer: row.issuer }); + await verifyVendorRunIdentity({ token, resolveKey: trust.resolveKey, binding: { + provider: row.provider, runId, activeRunId: row.run_id, vmId: row.vm_id, + issuer: row.issuer, subject: row.subject, audience: row.audience, exeAttachment, + } }); + return { tenantId: row.tenant_id, userId: row.user_id, sessionVersion: row.session_version, + scopes: normalizeScopes(row.scopes), authMethod: "vendor_identity", runId, runJobId: row.job_id, + runIdentityProvider: row.provider }; + } catch { + // Never surface provider response text, JWTs, or decrypted credentials. + return null; + } +} diff --git a/packages/api/src/worker.ts b/packages/api/src/worker.ts index e32c339b..c5d4406e 100644 --- a/packages/api/src/worker.ts +++ b/packages/api/src/worker.ts @@ -9,6 +9,7 @@ import { consentDecision } from "./consent-api"; import { addDeviceMetadata, DEVICE_GRANT, deviceAuthorization, deviceClientRegistration, deviceToken, deviceVerification } from "./device-oauth"; import type { Env, OAuthProps } from "./types"; import { ACCESS_SCOPES, authenticateAccessToken } from "./access-tokens"; +import { authenticateVendorRunRequest, RUN_IDENTITY_HEADER } from "./vendor-run-auth"; import { authenticateRunCredential } from "./run-credentials"; import { artifactUpload } from "./artifact-upload"; import { traceChunkUpload } from "./trace-chunk-upload"; @@ -96,6 +97,11 @@ const backend = { async fetch(request: Request, env: Env, ctx: ExecutionContext) if (traceChunkMatch) return traceChunkUpload(request, env, decodeURIComponent(traceChunkMatch[1]!)); const artifactMatch = url.pathname.match(/^\/internal\/run-artifacts\/([^/]+)$/); if (artifactMatch) return artifactUpload(request, env, decodeURIComponent(artifactMatch[1]!)); + if ((url.pathname === "/mcp" || url.pathname.startsWith("/api/v1")) && request.headers.has(RUN_IDENTITY_HEADER)) { + const auth = await authenticateVendorRunRequest(request, env); + if (!auth) return Response.json({ error: { code: "invalid_token", message: "The vendor identity is invalid or the run is no longer authorized." } }, { status: 401, headers: { "WWW-Authenticate": 'Bearer error="invalid_token"' } }); + return protectedApiFetch(request, apiEnv, auth, ctx); + } if (isBrowserAuthOperation(request.method, url.pathname)) return protectedApiFetch(request, apiEnv, null, ctx); if (url.pathname.startsWith("/api/v1") && !request.headers.has("Authorization")) { // Signature and expiry here; the service performs the authoritative owner, diff --git a/packages/api/test/vendor-run-auth.postgres.test.ts b/packages/api/test/vendor-run-auth.postgres.test.ts new file mode 100644 index 00000000..9e50a294 --- /dev/null +++ b/packages/api/test/vendor-run-auth.postgres.test.ts @@ -0,0 +1,135 @@ +import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest"; +import { loadingFixture } from "./helpers/loading-fixture"; +import { VendorRunIdentityRepository } from "../src/postgres/vendor-run-identity-repository"; +import { FlyConnectionRepository } from "../src/postgres/fly-connection-repository"; +import { issueRunCredential } from "../src/run-credentials"; +import { authenticateVendorRunRequest } from "../src/vendor-run-auth"; +import { exeWifIntegrationNameFor, vmNameFor } from "../src/exe-vm-backend"; +import worker from "../src/worker"; + +vi.mock("cloudflare:workers", () => ({ WorkerEntrypoint: class {}, DurableObject: class {} })); +vi.mock("@cloudflare/workers-oauth-provider", () => ({ OAuthProvider: class {}, AuthorizationError: class extends Error {}, getOAuthApi: vi.fn() })); + +const url = process.env.AUTH_TEST_DATABASE_URL; +describe.skipIf(!url)("vendor identity request admission (PostgreSQL and Worker boundary)", () => { + let f: Awaited>; + let privateKey: CryptoKey, jwk: JsonWebKey, jwt: string; + const issuer = "https://oidc.fly.io/connected-org", subject = "connected-org:run-app:machine-name", machineId = "fixture-machine"; + const encode = (v: unknown) => Buffer.from(JSON.stringify(v)).toString("base64url"); + async function sign(overrides: Record = {}) { + const now = Math.floor(Date.now() / 1000); + const input = `${encode({alg: "RS256", kid: "test-key"})}.${encode({ iss: issuer, sub: subject, aud: `factorize://runs/${f.runId}`, machine_id: machineId, iat: now - 5, exp: now + 600, ...overrides })}`; + return `${input}.${Buffer.from(await crypto.subtle.sign("RSASSA-PKCS1-v1_5", privateKey, new TextEncoder().encode(input))).toString("base64url")}`; + } + function request(token = jwt, runId = f.runId, path = "/api/v1/runtime-context", extra: Record = {}) { + return new Request(`${f.env.APP_ORIGIN}${path}`, { headers: { Authorization: `Bearer ${token}`, "X-Factorize-Run-Id": runId, ...extra } }); + } + beforeAll(async () => { + f = await loadingFixture(url!); + const pair = await crypto.subtle.generateKey({ name: "RSASSA-PKCS1-v1_5", modulusLength: 2048, publicExponent: new Uint8Array([1, 0, 1]), hash: "SHA-256" }, true, ["sign", "verify"]); + privateKey = pair.privateKey; + jwk = await crypto.subtle.exportKey("jwk", pair.publicKey); + }); + afterAll(async () => { await f?.cleanup(); }); + beforeEach(async () => { + const now = Math.floor(Date.now() / 1000); + await f.db.pool.query("UPDATE app.job_runs SET state='running' WHERE tenant_id=$1 AND id=$2", [f.tenantId, f.runId]); + await f.db.pool.query("UPDATE app.runs SET state='running',execution_handle=$3,execution_config=$4 WHERE tenant_id=$1 AND id=$2", [f.tenantId, f.runId, {backendKind: "fly", id: `run-app/${machineId}`}, {executionProvider: "fly", connectionId: "config", runScopes: ["runs:read"]}]); + await new FlyConnectionRepository(f.db, f.tenantId, f.env.CREDENTIAL_ENCRYPTION_KEY).save({organizationSlug: "connected-org", organizationName: "A different display name"}, "fixture-token"); + await f.db.pool.query("DELETE FROM app.vendor_run_identity_bindings WHERE tenant_id=$1 AND run_id=$2", [f.tenantId, f.runId]); + await new VendorRunIdentityRepository(f.db).persistVerified({tenantId: f.tenantId, issuedAt: now - 5, identity: {provider: "fly.io", issuer, subject, audience: `factorize://runs/${f.runId}`, runId: f.runId, vmId: machineId, issuedAt: now - 5, expiresAt: now + 600, keyId: "test-key"}}); + await issueRunCredential(f.env, f.tenantId, f.runId, ["runs:read"]); + jwt = await sign(); + vi.stubGlobal("fetch", vi.fn(async (input: RequestInfo | URL) => { + if (String(input) === `${issuer}/.well-known/openid-configuration`) return Response.json({issuer, jwks_uri: `${issuer}/.well-known/jwks`}); + if (String(input) === `${issuer}/.well-known/jwks`) return Response.json({keys: [{...jwk, kid: "test-key"}]}); + throw new Error("Unexpected outbound request"); + })); + }); + afterEach(() => { vi.unstubAllGlobals(); }); + + it("authenticates at the Worker boundary with only snapshotted scopes and server tenant", async () => { + const auth = await authenticateVendorRunRequest(request(jwt, f.runId, undefined, {"X-Factorize-Tenant-Id": f.otherTenant}), f.env); + expect(auth).toMatchObject({tenantId: f.tenantId, runId: f.runId, runJobId: f.jobIds[0], authMethod: "vendor_identity", scopes: ["runs:read"]}); + expect(auth).not.toHaveProperty("runCredentialDigest"); + const response = await worker.fetch(request(), f.env, {waitUntil() {}} as any); + expect(response.status).toBe(200); + expect(await response.json()).toMatchObject({authMethod: "vendor_identity", scopes: ["runs:read"], runId: f.runId}); + expect((await worker.fetch(request(jwt, f.runId, "/api/v1/jobs"), f.env, {waitUntil() {}} as any)).status).toBe(403); + await f.db.pool.query("UPDATE app.jobs SET run_scopes='[\"jobs:write\",\"jobs:read\"]' WHERE tenant_id=$1 AND id=$2", [f.tenantId, f.jobIds[0]]); + expect((await authenticateVendorRunRequest(request(), f.env))?.scopes).toEqual(["runs:read"]); + await f.db.pool.query("UPDATE app.run_credentials SET scopes='[]' WHERE tenant_id=$1 AND run_id=$2", [f.tenantId, f.runId]); + expect((await authenticateVendorRunRequest(request(), f.env))?.scopes).toEqual([]); + }); + + it("requires both the exact provisioned run and a valid vendor signature", async () => { + for (const claims of [{iss: "https://oidc.fly.io/foreign-org"}, {aud: "other"}, {sub: "other"}, {machine_id: "other"}, {exp: Math.floor(Date.now()/1000)-1}]) { + expect(await authenticateVendorRunRequest(request(await sign(claims)), f.env)).toBeNull(); + } + expect(await authenticateVendorRunRequest(request(jwt, crypto.randomUUID()), f.env)).toBeNull(); + expect(await authenticateVendorRunRequest(new Request(f.env.APP_ORIGIN, {headers: {Authorization: `Bearer ${jwt}`}}), f.env)).toBeNull(); + const forged = jwt.split("."); forged[1] = encode({iss: issuer, sub: subject}); + expect(await authenticateVendorRunRequest(request(forged.join(".")), f.env)).toBeNull(); + // A malformed run-auth request cannot fall back to an otherwise valid session. + expect((await worker.fetch(request("invalid", f.runId, undefined, {Cookie: f.cookie}), f.env, {waitUntil() {}} as any)).status).toBe(401); + }); + + it("requires explicit destination permission and prevents a run from granting itself permission", async () => { + await f.db.pool.query("UPDATE app.run_credentials SET scopes='[\"runs:invoke\",\"jobs:write\"]' WHERE tenant_id=$1 AND run_id=$2", [f.tenantId, f.runId]); + const invoke = () => worker.fetch(new Request(request(jwt, f.runId, `/api/v1/jobs/${f.jobIds[1]}/invocations`), { + method: "POST", headers: {Authorization: `Bearer ${jwt}`, "X-Factorize-Run-Id": f.runId, "Content-Type": "application/json"}, body: JSON.stringify({prompt: "selected destination", idempotencyKey: "vendor-run-test"}), + }), f.env, {waitUntil() {}} as any); + expect((await invoke()).status).toBe(403); + const escalate = await worker.fetch(new Request(request(jwt, f.runId, `/api/v1/jobs/${f.jobIds[0]}/invocation-permissions`), { + method: "PUT", headers: {Authorization: `Bearer ${jwt}`, "X-Factorize-Run-Id": f.runId, "Content-Type": "application/json"}, body: JSON.stringify({destinationJobIds: [f.jobIds[1]]}), + }), f.env, {waitUntil() {}} as any); + expect(escalate.status).toBe(403); + await f.db.pool.query("INSERT INTO app.manual_invocation_permissions(tenant_id,source_job_id,destination_job_id) VALUES($1,$2,$3)", [f.tenantId, f.jobIds[0], f.jobIds[1]]); + const accepted = await invoke(); + expect(accepted.status).toBe(202); + const first = await accepted.json() as Record; + expect(await (await invoke()).json()).toMatchObject({...first, duplicate: true}); + }); + + it("revalidates the exclusive exe.dev attachment on each request", async () => { + const vm = vmNameFor(f.runId), integrationName = exeWifIntegrationNameFor(f.runId); + const exeIssuer = "https://exe.dev/issuer/test-run", exeSubject = "sub-run-integration"; + await f.db.pool.query("DELETE FROM app.vendor_run_identity_bindings WHERE tenant_id=$1 AND run_id=$2", [f.tenantId, f.runId]); + const now = Math.floor(Date.now()/1000); + await new VendorRunIdentityRepository(f.db).persistVerified({tenantId: f.tenantId, issuedAt: now-5, identity: {provider: "exe.dev", issuer: exeIssuer, subject: exeSubject, audience: `factorize://runs/${f.runId}`, runId: f.runId, vmId: vm, issuedAt: now-5, expiresAt: now+600, keyId: "test-key"}}); + await f.db.pool.query("UPDATE app.runs SET execution_handle=$3,execution_config=$4 WHERE tenant_id=$1 AND id=$2", [f.tenantId, f.runId, {id: vm}, {connectionId: "local", executionProvider: "exe"}]); + const token = await sign({iss: exeIssuer, sub: exeSubject}); + let attachments = [`vm:${vm}`]; + vi.stubGlobal("fetch", vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => { + if (String(input) === "https://exe.dev/exec") { + expect(init?.body).toBe("integrations list --json"); + expect((init?.headers as Record).Authorization).toBe("Bearer private-exe-token"); + return Response.json([{name: integrationName, type: "wif", config: {issuer_id: "test-run", subject: exeSubject, audience: `factorize://runs/${f.runId}`}, attachments}]); + } + if (String(input) === `${exeIssuer}/.well-known/openid-configuration`) return Response.json({issuer: exeIssuer, jwks_uri: `${exeIssuer}/keys`}); + if (String(input) === `${exeIssuer}/keys`) return Response.json({keys: [{...jwk, kid: "test-key"}]}); + throw new Error("Unexpected request"); + })); + expect(await authenticateVendorRunRequest(request(token), f.env)).toMatchObject({tenantId: f.tenantId, authMethod: "vendor_identity"}); + for (const changed of [[`vm:${vm}`, "tag:all-runs"], ["vm:another-vm"], ["auto:all"], []]) { + attachments = changed; + expect(await authenticateVendorRunRequest(request(token), f.env)).toBeNull(); + } + }); + + it("rechecks current run lifecycle, revocation, handle and execution connection", async () => { + for (const state of ["queued", "reserved", "stopping", "stopped", "succeeded", "failed"]) { + await f.db.pool.query("UPDATE app.job_runs SET state=$3 WHERE tenant_id=$1 AND id=$2", [f.tenantId, f.runId, state]); + expect(await authenticateVendorRunRequest(request(), f.env), state).toBeNull(); + } + await f.db.pool.query("UPDATE app.job_runs SET state='running' WHERE tenant_id=$1 AND id=$2", [f.tenantId, f.runId]); + await f.db.pool.query("UPDATE app.vendor_run_identity_bindings SET revoked_at=now() WHERE tenant_id=$1 AND run_id=$2", [f.tenantId, f.runId]); + expect(await authenticateVendorRunRequest(request(), f.env)).toBeNull(); + await f.db.pool.query("UPDATE app.vendor_run_identity_bindings SET revoked_at=NULL WHERE tenant_id=$1 AND run_id=$2", [f.tenantId, f.runId]); + await f.db.pool.query("UPDATE app.runs SET execution_handle=$3 WHERE tenant_id=$1 AND id=$2", [f.tenantId, f.runId, {id: "run-app/other-machine"}]); + expect(await authenticateVendorRunRequest(request(), f.env)).toBeNull(); + await f.db.pool.query("UPDATE app.runs SET execution_handle=$3 WHERE tenant_id=$1 AND id=$2", [f.tenantId, f.runId, {id: `run-app/${machineId}`}]); + await new FlyConnectionRepository(f.db, f.tenantId, f.env.CREDENTIAL_ENCRYPTION_KEY).remove(); + expect(await authenticateVendorRunRequest(request(), f.env)).toBeNull(); + }); +}); diff --git a/packages/docs/openapi.yaml b/packages/docs/openapi.yaml index 370c74bb..5a94fbbc 100644 --- a/packages/docs/openapi.yaml +++ b/packages/docs/openapi.yaml @@ -19,6 +19,16 @@ components: type: apiKey in: cookie name: factorize_session + vendorRunIdentity: + type: http + scheme: bearer + bearerFormat: JWT + description: Fresh vendor-signed exe.dev WIF or Fly Machine OIDC token matching the provisioned active run. Must be combined with X-Factorize-Run-Id; a vendor token alone grants no access. + runIdentityHeader: + type: apiKey + in: header + name: X-Factorize-Run-Id + description: Provisioned run UUID. Used only to locate the immutable vendor/VM binding; this header is not a credential. Scopes and tenant come from the server-side run snapshot. schemas: Error: type: object @@ -1888,7 +1898,6 @@ paths: tags: - model-accounts security: - - bearerAuth: [] - cookieAuth: [] x-required-scope: integrations:read x-owner-session-required: true @@ -1940,7 +1949,6 @@ paths: tags: - model-accounts security: - - bearerAuth: [] - cookieAuth: [] x-required-scope: integrations:write x-owner-session-required: true @@ -2041,7 +2049,6 @@ paths: tags: - model-accounts security: - - bearerAuth: [] - cookieAuth: [] x-required-scope: integrations:write x-owner-session-required: true @@ -2121,7 +2128,6 @@ paths: tags: - credential-proxy security: - - bearerAuth: [] - cookieAuth: [] x-required-scope: integrations:write x-owner-session-required: true @@ -2187,7 +2193,6 @@ paths: tags: - credential-proxy security: - - bearerAuth: [] - cookieAuth: [] x-required-scope: integrations:write x-owner-session-required: true @@ -2256,7 +2261,6 @@ paths: tags: - model-accounts security: - - bearerAuth: [] - cookieAuth: [] x-required-scope: integrations:write x-owner-session-required: true @@ -2342,7 +2346,6 @@ paths: tags: - unlock-key security: - - bearerAuth: [] - cookieAuth: [] x-required-scope: integrations:read x-owner-session-required: true @@ -2391,7 +2394,6 @@ paths: tags: - unlock-key security: - - bearerAuth: [] - cookieAuth: [] x-required-scope: integrations:write x-owner-session-required: true @@ -2584,7 +2586,6 @@ paths: tags: - unlock-key security: - - bearerAuth: [] - cookieAuth: [] x-required-scope: integrations:read x-owner-session-required: true @@ -2642,7 +2643,6 @@ paths: tags: - unlock-key security: - - bearerAuth: [] - cookieAuth: [] x-required-scope: integrations:write x-owner-session-required: true @@ -2868,7 +2868,6 @@ paths: tags: - integrations security: - - bearerAuth: [] - cookieAuth: [] x-required-scope: integrations:read x-owner-session-required: true @@ -2920,7 +2919,6 @@ paths: tags: - integrations security: - - bearerAuth: [] - cookieAuth: [] x-required-scope: integrations:write x-owner-session-required: true @@ -3018,7 +3016,6 @@ paths: tags: - integrations security: - - bearerAuth: [] - cookieAuth: [] x-required-scope: integrations:write x-owner-session-required: true @@ -3126,7 +3123,6 @@ paths: tags: - integrations security: - - bearerAuth: [] - cookieAuth: [] x-required-scope: integrations:write x-owner-session-required: true @@ -4361,12 +4357,14 @@ paths: description: |- Requires the jobs:read scope. - Accepts a scoped bearer token or interactive owner session. + Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. operationId: get_api_v1_trigger_contexts tags: - trigger-contexts security: - bearerAuth: [] + - vendorRunIdentity: [] + runIdentityHeader: [] - cookieAuth: [] x-required-scope: jobs:read x-owner-session-required: false @@ -4435,12 +4433,14 @@ paths: description: |- Requires the integrations:read scope. - Accepts a scoped bearer token or interactive owner session. + Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. operationId: get_api_v1_exe_connections tags: - exe-connections security: - bearerAuth: [] + - vendorRunIdentity: [] + runIdentityHeader: [] - cookieAuth: [] x-required-scope: integrations:read x-owner-session-required: false @@ -4498,12 +4498,14 @@ paths: description: |- Requires the integrations:read scope. - Accepts a scoped bearer token or interactive owner session. + Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. operationId: get_api_v1_github_installations tags: - github-installations security: - bearerAuth: [] + - vendorRunIdentity: [] + runIdentityHeader: [] - cookieAuth: [] x-required-scope: integrations:read x-owner-session-required: false @@ -4563,12 +4565,14 @@ paths: description: |- Requires the jobs:read scope. - Accepts a scoped bearer token or interactive owner session. + Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. operationId: get_api_v1_job_trigger_availability tags: - job-trigger-availability security: - bearerAuth: [] + - vendorRunIdentity: [] + runIdentityHeader: [] - cookieAuth: [] x-required-scope: jobs:read x-owner-session-required: false @@ -4609,12 +4613,14 @@ paths: description: |- Requires the jobs:read scope. - Accepts a scoped bearer token or interactive owner session. + Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. operationId: post_api_v1_schedules_preview tags: - schedules security: - bearerAuth: [] + - vendorRunIdentity: [] + runIdentityHeader: [] - cookieAuth: [] x-required-scope: jobs:read x-owner-session-required: false @@ -4692,12 +4698,14 @@ paths: description: |- Requires the integrations:read scope. - Accepts a scoped bearer token or interactive owner session. + Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. operationId: get_api_v1_integrations_cloudflare_tail tags: - integrations security: - bearerAuth: [] + - vendorRunIdentity: [] + runIdentityHeader: [] - cookieAuth: [] x-required-scope: integrations:read x-owner-session-required: false @@ -4750,12 +4758,14 @@ paths: description: |- Requires the integrations:write scope. - Accepts a scoped bearer token or interactive owner session. + Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. operationId: post_api_v1_integrations_cloudflare_tail tags: - integrations security: - bearerAuth: [] + - vendorRunIdentity: [] + runIdentityHeader: [] - cookieAuth: [] x-required-scope: integrations:write x-owner-session-required: false @@ -4983,12 +4993,14 @@ paths: description: |- Requires the integrations:read scope. - Accepts a scoped bearer token or interactive owner session. + Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. operationId: get_api_v1_integrations tags: - integrations security: - bearerAuth: [] + - vendorRunIdentity: [] + runIdentityHeader: [] - cookieAuth: [] x-required-scope: integrations:read x-owner-session-required: false @@ -5045,7 +5057,6 @@ paths: tags: - fly security: - - bearerAuth: [] - cookieAuth: [] x-required-scope: integrations:read x-owner-session-required: true @@ -5101,7 +5112,6 @@ paths: tags: - fly security: - - bearerAuth: [] - cookieAuth: [] x-required-scope: integrations:write x-owner-session-required: true @@ -5167,7 +5177,6 @@ paths: tags: - fly security: - - bearerAuth: [] - cookieAuth: [] x-required-scope: integrations:write x-owner-session-required: true @@ -5228,7 +5237,6 @@ paths: tags: - fly security: - - bearerAuth: [] - cookieAuth: [] x-required-scope: integrations:write x-owner-session-required: true @@ -5323,7 +5331,6 @@ paths: tags: - fly security: - - bearerAuth: [] - cookieAuth: [] x-required-scope: integrations:read x-owner-session-required: true @@ -5396,7 +5403,6 @@ paths: tags: - fly security: - - bearerAuth: [] - cookieAuth: [] x-required-scope: integrations:write x-owner-session-required: true @@ -5494,7 +5500,6 @@ paths: tags: - fly security: - - bearerAuth: [] - cookieAuth: [] x-required-scope: integrations:read x-owner-session-required: true @@ -5573,7 +5578,6 @@ paths: tags: - fly security: - - bearerAuth: [] - cookieAuth: [] x-required-scope: integrations:write x-owner-session-required: true @@ -5656,7 +5660,6 @@ paths: tags: - fly security: - - bearerAuth: [] - cookieAuth: [] x-required-scope: integrations:write x-owner-session-required: true @@ -5712,12 +5715,14 @@ paths: description: |- Requires the integrations:write scope. - Accepts a scoped bearer token or interactive owner session. + Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. operationId: put_api_v1_integrations_exe tags: - integrations security: - bearerAuth: [] + - vendorRunIdentity: [] + runIdentityHeader: [] - cookieAuth: [] x-required-scope: integrations:write x-owner-session-required: false @@ -5819,12 +5824,14 @@ paths: description: |- Requires the integrations:write scope. - Accepts a scoped bearer token or interactive owner session. + Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. operationId: post_api_v1_integrations_exe_test tags: - integrations security: - bearerAuth: [] + - vendorRunIdentity: [] + runIdentityHeader: [] - cookieAuth: [] x-required-scope: integrations:write x-owner-session-required: false @@ -5894,12 +5901,14 @@ paths: description: |- Requires the integrations:write scope. - Accepts a scoped bearer token or interactive owner session. + Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. operationId: put_api_v1_integrations_amp tags: - integrations security: - bearerAuth: [] + - vendorRunIdentity: [] + runIdentityHeader: [] - cookieAuth: [] x-required-scope: integrations:write x-owner-session-required: false @@ -5960,12 +5969,14 @@ paths: description: |- Requires the integrations:write scope. - Accepts a scoped bearer token or interactive owner session. + Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. operationId: post_api_v1_integrations_amp_test tags: - integrations security: - bearerAuth: [] + - vendorRunIdentity: [] + runIdentityHeader: [] - cookieAuth: [] x-required-scope: integrations:write x-owner-session-required: false @@ -6029,12 +6040,14 @@ paths: description: |- Requires the integrations:read scope. - Accepts a scoped bearer token or interactive owner session. + Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. operationId: get_api_v1_providers_linear_projects tags: - providers security: - bearerAuth: [] + - vendorRunIdentity: [] + runIdentityHeader: [] - cookieAuth: [] x-required-scope: integrations:read x-owner-session-required: false @@ -6112,12 +6125,14 @@ paths: description: |- Requires the integrations:read scope. - Accepts a scoped bearer token or interactive owner session. + Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. operationId: get_api_v1_providers_linear_options tags: - providers security: - bearerAuth: [] + - vendorRunIdentity: [] + runIdentityHeader: [] - cookieAuth: [] x-required-scope: integrations:read x-owner-session-required: false @@ -6161,12 +6176,14 @@ paths: description: |- Requires the integrations:read scope. - Accepts a scoped bearer token or interactive owner session. + Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. operationId: get_api_v1_providers_clickup_lists tags: - providers security: - bearerAuth: [] + - vendorRunIdentity: [] + runIdentityHeader: [] - cookieAuth: [] x-required-scope: integrations:read x-owner-session-required: false @@ -6244,12 +6261,14 @@ paths: description: |- Requires the integrations:read scope. - Accepts a scoped bearer token or interactive owner session. + Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. operationId: get_api_v1_providers_clickup_options tags: - providers security: - bearerAuth: [] + - vendorRunIdentity: [] + runIdentityHeader: [] - cookieAuth: [] x-required-scope: integrations:read x-owner-session-required: false @@ -6314,12 +6333,14 @@ paths: description: |- Requires the integrations:read scope. - Accepts a scoped bearer token or interactive owner session. + Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. operationId: get_api_v1_providers_github_installations tags: - providers security: - bearerAuth: [] + - vendorRunIdentity: [] + runIdentityHeader: [] - cookieAuth: [] x-required-scope: integrations:read x-owner-session-required: false @@ -6389,7 +6410,6 @@ paths: tags: - access security: - - bearerAuth: [] - cookieAuth: [] x-required-scope: jobs:read x-owner-session-required: true @@ -6470,7 +6490,6 @@ paths: tags: - access-tokens security: - - bearerAuth: [] - cookieAuth: [] x-required-scope: jobs:read x-owner-session-required: true @@ -6553,7 +6572,6 @@ paths: tags: - access-tokens security: - - bearerAuth: [] - cookieAuth: [] x-required-scope: jobs:write x-owner-session-required: true @@ -6637,7 +6655,6 @@ paths: tags: - access-tokens security: - - bearerAuth: [] - cookieAuth: [] x-required-scope: jobs:write x-owner-session-required: true @@ -6682,7 +6699,6 @@ paths: tags: - access security: - - bearerAuth: [] - cookieAuth: [] x-required-scope: jobs:write x-owner-session-required: true @@ -6722,12 +6738,14 @@ paths: description: |- Requires the integrations:write scope. - Accepts a scoped bearer token or interactive owner session. + Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. operationId: delete_api_v1_integrations_exe_connectionId tags: - integrations security: - bearerAuth: [] + - vendorRunIdentity: [] + runIdentityHeader: [] - cookieAuth: [] x-required-scope: integrations:write x-owner-session-required: false @@ -6767,12 +6785,14 @@ paths: description: |- Requires the integrations:write scope. - Accepts a scoped bearer token or interactive owner session. + Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. operationId: delete_api_v1_integrations_amp_connectionId tags: - integrations security: - bearerAuth: [] + - vendorRunIdentity: [] + runIdentityHeader: [] - cookieAuth: [] x-required-scope: integrations:write x-owner-session-required: false @@ -6833,12 +6853,14 @@ paths: description: |- Requires the integrations:write scope. - Accepts a scoped bearer token or interactive owner session. + Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. operationId: put_api_v1_integrations_cloudflare_tail_integrationId tags: - integrations security: - bearerAuth: [] + - vendorRunIdentity: [] + runIdentityHeader: [] - cookieAuth: [] x-required-scope: integrations:write x-owner-session-required: false @@ -6902,12 +6924,14 @@ paths: description: |- Requires the integrations:write scope. - Accepts a scoped bearer token or interactive owner session. + Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. operationId: delete_api_v1_integrations_cloudflare_tail_integrationId tags: - integrations security: - bearerAuth: [] + - vendorRunIdentity: [] + runIdentityHeader: [] - cookieAuth: [] x-required-scope: integrations:write x-owner-session-required: false @@ -6953,12 +6977,14 @@ paths: description: |- Requires the integrations:write scope. - Accepts a scoped bearer token or interactive owner session. + Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. operationId: post_api_v1_integrations_cloudflare_tail_integrationId_test tags: - integrations security: - bearerAuth: [] + - vendorRunIdentity: [] + runIdentityHeader: [] - cookieAuth: [] x-required-scope: integrations:write x-owner-session-required: false @@ -7023,12 +7049,14 @@ paths: description: |- Requires the integrations:read scope. - Accepts a scoped bearer token or interactive owner session. + Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. operationId: get_api_v1_providers_github_installations_installationId_repositories tags: - providers security: - bearerAuth: [] + - vendorRunIdentity: [] + runIdentityHeader: [] - cookieAuth: [] x-required-scope: integrations:read x-owner-session-required: false @@ -7113,12 +7141,14 @@ paths: description: |- Requires the integrations:read scope. - Accepts a scoped bearer token or interactive owner session. + Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. operationId: get_api_v1_providers_github_installations_installationId_repositories_repositoryId_issue_options tags: - providers security: - bearerAuth: [] + - vendorRunIdentity: [] + runIdentityHeader: [] - cookieAuth: [] x-required-scope: integrations:read x-owner-session-required: false @@ -7164,12 +7194,14 @@ paths: description: |- Requires the integrations:write scope. - Accepts a scoped bearer token or interactive owner session. + Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. operationId: delete_api_v1_providers_github_installations_installationId tags: - providers security: - bearerAuth: [] + - vendorRunIdentity: [] + runIdentityHeader: [] - cookieAuth: [] x-required-scope: integrations:write x-owner-session-required: false @@ -7209,12 +7241,14 @@ paths: description: |- Requires the integrations:write scope. - Accepts a scoped bearer token or interactive owner session. + Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. operationId: post_api_v1_integrations_exe_connectionId_diagnostics tags: - integrations security: - bearerAuth: [] + - vendorRunIdentity: [] + runIdentityHeader: [] - cookieAuth: [] x-required-scope: integrations:write x-owner-session-required: false @@ -7233,7 +7267,7 @@ paths: Requires the jobs:read scope. - Accepts a scoped bearer token or interactive owner session. + Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. responses: "200": description: Summary page @@ -7345,6 +7379,8 @@ paths: - job-summaries security: - bearerAuth: [] + - vendorRunIdentity: [] + runIdentityHeader: [] - cookieAuth: [] x-required-scope: jobs:read x-owner-session-required: false @@ -7463,12 +7499,14 @@ paths: description: |- Requires the jobs:read scope. - Accepts a scoped bearer token or interactive owner session. + Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. operationId: get_api_v1_job_selector tags: - job-selector security: - bearerAuth: [] + - vendorRunIdentity: [] + runIdentityHeader: [] - cookieAuth: [] x-required-scope: jobs:read x-owner-session-required: false @@ -7583,12 +7621,14 @@ paths: description: |- Requires the projects:read scope. - Accepts a scoped bearer token or interactive owner session. + Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. operationId: get_api_v1_projects tags: - projects security: - bearerAuth: [] + - vendorRunIdentity: [] + runIdentityHeader: [] - cookieAuth: [] x-required-scope: projects:read x-owner-session-required: false @@ -7664,12 +7704,14 @@ paths: description: |- Requires the projects:write scope. - Accepts a scoped bearer token or interactive owner session. + Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. operationId: post_api_v1_projects tags: - projects security: - bearerAuth: [] + - vendorRunIdentity: [] + runIdentityHeader: [] - cookieAuth: [] x-required-scope: projects:write x-owner-session-required: false @@ -7743,12 +7785,14 @@ paths: description: |- Requires the projects:read scope. - Accepts a scoped bearer token or interactive owner session. + Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. operationId: get_api_v1_projects_projectId tags: - projects security: - bearerAuth: [] + - vendorRunIdentity: [] + runIdentityHeader: [] - cookieAuth: [] x-required-scope: projects:read x-owner-session-required: false @@ -7813,12 +7857,14 @@ paths: description: |- Requires the projects:write scope. - Accepts a scoped bearer token or interactive owner session. + Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. operationId: put_api_v1_projects_projectId tags: - projects security: - bearerAuth: [] + - vendorRunIdentity: [] + runIdentityHeader: [] - cookieAuth: [] x-required-scope: projects:write x-owner-session-required: false @@ -7874,12 +7920,14 @@ paths: description: |- Requires the projects:write scope. - Accepts a scoped bearer token or interactive owner session. + Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. operationId: delete_api_v1_projects_projectId tags: - projects security: - bearerAuth: [] + - vendorRunIdentity: [] + runIdentityHeader: [] - cookieAuth: [] x-required-scope: projects:write x-owner-session-required: false @@ -7898,7 +7946,7 @@ paths: Requires the projects:read scope. - Accepts a scoped bearer token or interactive owner session. + Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. responses: "200": description: Complete project graph @@ -8002,6 +8050,8 @@ paths: - projects security: - bearerAuth: [] + - vendorRunIdentity: [] + runIdentityHeader: [] - cookieAuth: [] x-required-scope: projects:read x-owner-session-required: false @@ -8083,12 +8133,14 @@ paths: description: |- Requires the skills:read scope. - Accepts a scoped bearer token or interactive owner session. + Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. operationId: get_api_v1_skills tags: - skills security: - bearerAuth: [] + - vendorRunIdentity: [] + runIdentityHeader: [] - cookieAuth: [] x-required-scope: skills:read x-owner-session-required: false @@ -8174,12 +8226,14 @@ paths: description: |- Requires the skills:write scope. - Accepts a scoped bearer token or interactive owner session. + Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. operationId: post_api_v1_skills tags: - skills security: - bearerAuth: [] + - vendorRunIdentity: [] + runIdentityHeader: [] - cookieAuth: [] x-required-scope: skills:write x-owner-session-required: false @@ -8231,12 +8285,14 @@ paths: description: |- Requires the skills:read scope. - Accepts a scoped bearer token or interactive owner session. + Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. operationId: post_api_v1_skills_preview tags: - skills security: - bearerAuth: [] + - vendorRunIdentity: [] + runIdentityHeader: [] - cookieAuth: [] x-required-scope: skills:read x-owner-session-required: false @@ -8325,12 +8381,14 @@ paths: description: |- Requires the skills:read scope. - Accepts a scoped bearer token or interactive owner session. + Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. operationId: get_api_v1_skills_skillId tags: - skills security: - bearerAuth: [] + - vendorRunIdentity: [] + runIdentityHeader: [] - cookieAuth: [] x-required-scope: skills:read x-owner-session-required: false @@ -8401,12 +8459,14 @@ paths: description: |- Requires the skills:write scope. - Accepts a scoped bearer token or interactive owner session. + Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. operationId: put_api_v1_skills_skillId tags: - skills security: - bearerAuth: [] + - vendorRunIdentity: [] + runIdentityHeader: [] - cookieAuth: [] x-required-scope: skills:write x-owner-session-required: false @@ -8465,12 +8525,14 @@ paths: description: |- Requires the skills:write scope. - Accepts a scoped bearer token or interactive owner session. + Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. operationId: delete_api_v1_skills_skillId tags: - skills security: - bearerAuth: [] + - vendorRunIdentity: [] + runIdentityHeader: [] - cookieAuth: [] x-required-scope: skills:write x-owner-session-required: false @@ -8552,12 +8614,14 @@ paths: description: |- Requires the skills:read scope. - Accepts a scoped bearer token or interactive owner session. + Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. operationId: get_api_v1_skills_skillId_jobs tags: - skills security: - bearerAuth: [] + - vendorRunIdentity: [] + runIdentityHeader: [] - cookieAuth: [] x-required-scope: skills:read x-owner-session-required: false @@ -9166,12 +9230,14 @@ paths: description: |- Requires the projects:write scope. - Accepts a scoped bearer token or interactive owner session. + Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. operationId: post_api_v1_jobs_jobId_project tags: - jobs security: - bearerAuth: [] + - vendorRunIdentity: [] + runIdentityHeader: [] - cookieAuth: [] x-required-scope: projects:write x-owner-session-required: false @@ -9207,7 +9273,7 @@ paths: Requires the jobs:write scope. - Accepts a scoped bearer token or interactive owner session. + Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. responses: "200": description: Verification operation @@ -9277,6 +9343,8 @@ paths: - vm-image-verifications security: - bearerAuth: [] + - vendorRunIdentity: [] + runIdentityHeader: [] - cookieAuth: [] x-required-scope: jobs:write x-owner-session-required: false @@ -9387,12 +9455,14 @@ paths: description: |- Requires the jobs:read scope. - Accepts a scoped bearer token or interactive owner session. + Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. operationId: get_api_v1_vm_image_verifications_verificationId tags: - vm-image-verifications security: - bearerAuth: [] + - vendorRunIdentity: [] + runIdentityHeader: [] - cookieAuth: [] x-required-scope: jobs:read x-owner-session-required: false @@ -10001,12 +10071,14 @@ paths: description: |- Requires the jobs:read scope. - Accepts a scoped bearer token or interactive owner session. + Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. operationId: get_api_v1_jobs tags: - jobs security: - bearerAuth: [] + - vendorRunIdentity: [] + runIdentityHeader: [] - cookieAuth: [] x-required-scope: jobs:read x-owner-session-required: false @@ -10607,12 +10679,14 @@ paths: description: |- Requires the jobs:write scope. - Accepts a scoped bearer token or interactive owner session. + Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. operationId: post_api_v1_jobs tags: - jobs security: - bearerAuth: [] + - vendorRunIdentity: [] + runIdentityHeader: [] - cookieAuth: [] x-required-scope: jobs:write x-owner-session-required: false @@ -10630,7 +10704,7 @@ paths: Requires the jobs:write scope. - Accepts a scoped bearer token or interactive owner session. + Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. responses: "200": description: Decision @@ -10681,6 +10755,8 @@ paths: - job-conditions security: - bearerAuth: [] + - vendorRunIdentity: [] + runIdentityHeader: [] - cookieAuth: [] x-required-scope: jobs:write x-owner-session-required: false @@ -10736,12 +10812,14 @@ paths: description: |- Requires the runs:invoke scope. - Accepts a scoped bearer token or interactive owner session. + Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. operationId: post_api_v1_jobs_jobId_invocations tags: - jobs security: - bearerAuth: [] + - vendorRunIdentity: [] + runIdentityHeader: [] - cookieAuth: [] x-required-scope: runs:invoke x-owner-session-required: false @@ -10764,7 +10842,7 @@ paths: description: |- Returns the verified calling identity and effective scopes without credentials. Requires a verified active identity but no application-resource scope; callers with zero scopes can inspect only their own identity. Execution provisioning uses this operation to verify the dedicated run proxy. Execution VMs must not have additional shared Factorize proxy attachments. - Accepts a scoped bearer token or interactive owner session. + Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. responses: "200": description: Verified runtime identity @@ -10818,6 +10896,8 @@ paths: - runtime-context security: - bearerAuth: [] + - vendorRunIdentity: [] + runIdentityHeader: [] - cookieAuth: [] x-required-scope: [] x-owner-session-required: false @@ -10865,12 +10945,14 @@ paths: description: |- Requires the jobs:read scope. - Accepts a scoped bearer token or interactive owner session. + Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. operationId: get_api_v1_jobs_jobId_invocation_permissions tags: - jobs security: - bearerAuth: [] + - vendorRunIdentity: [] + runIdentityHeader: [] - cookieAuth: [] x-required-scope: jobs:read x-owner-session-required: false @@ -10888,7 +10970,7 @@ paths: Requires the jobs:write scope. - Accepts a scoped bearer token or interactive owner session. + Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. responses: "200": description: Saved manual invocation permissions @@ -10934,6 +11016,8 @@ paths: - jobs security: - bearerAuth: [] + - vendorRunIdentity: [] + runIdentityHeader: [] - cookieAuth: [] x-required-scope: jobs:write x-owner-session-required: false @@ -10992,12 +11076,14 @@ paths: description: |- Requires the runs:read scope. - Accepts a scoped bearer token or interactive owner session. + Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. operationId: get_api_v1_jobs_jobId_events tags: - jobs security: - bearerAuth: [] + - vendorRunIdentity: [] + runIdentityHeader: [] - cookieAuth: [] x-required-scope: runs:read x-owner-session-required: false @@ -11045,12 +11131,14 @@ paths: description: |- Requires the jobs:write scope. - Accepts a scoped bearer token or interactive owner session. + Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. operationId: post_api_v1_jobs_jobId_enable tags: - jobs security: - bearerAuth: [] + - vendorRunIdentity: [] + runIdentityHeader: [] - cookieAuth: [] x-required-scope: jobs:write x-owner-session-required: false @@ -11090,12 +11178,14 @@ paths: description: |- Requires the jobs:write scope. - Accepts a scoped bearer token or interactive owner session. + Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. operationId: post_api_v1_jobs_jobId_disable tags: - jobs security: - bearerAuth: [] + - vendorRunIdentity: [] + runIdentityHeader: [] - cookieAuth: [] x-required-scope: jobs:write x-owner-session-required: false @@ -11702,12 +11792,14 @@ paths: description: |- Requires the jobs:read scope. - Accepts a scoped bearer token or interactive owner session. + Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. operationId: get_api_v1_jobs_jobId tags: - jobs security: - bearerAuth: [] + - vendorRunIdentity: [] + runIdentityHeader: [] - cookieAuth: [] x-required-scope: jobs:read x-owner-session-required: false @@ -11725,7 +11817,7 @@ paths: Requires the jobs:write scope. - Accepts a scoped bearer token or interactive owner session. + Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. responses: "200": description: Updated @@ -12324,6 +12416,8 @@ paths: - jobs security: - bearerAuth: [] + - vendorRunIdentity: [] + runIdentityHeader: [] - cookieAuth: [] x-required-scope: jobs:write x-owner-session-required: false @@ -12777,12 +12871,14 @@ paths: description: |- Requires the jobs:write scope. - Accepts a scoped bearer token or interactive owner session. + Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. operationId: delete_api_v1_jobs_jobId tags: - jobs security: - bearerAuth: [] + - vendorRunIdentity: [] + runIdentityHeader: [] - cookieAuth: [] x-required-scope: jobs:write x-owner-session-required: false @@ -12801,7 +12897,7 @@ paths: Requires the runs:read scope. - Accepts a scoped bearer token or interactive owner session. + Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. responses: "200": description: Paginated runs @@ -12830,6 +12926,8 @@ paths: - runs security: - bearerAuth: [] + - vendorRunIdentity: [] + runIdentityHeader: [] - cookieAuth: [] x-required-scope: runs:read x-owner-session-required: false @@ -12947,7 +13045,7 @@ paths: Requires the jobs:read and runs:read scopes. - Accepts a scoped bearer token or interactive owner session. + Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. responses: "200": description: Search results @@ -13052,6 +13150,8 @@ paths: - search security: - bearerAuth: [] + - vendorRunIdentity: [] + runIdentityHeader: [] - cookieAuth: [] x-required-scope: jobs:read+runs:read x-owner-session-required: false @@ -13091,12 +13191,14 @@ paths: description: |- Requires the runs:read scope. - Accepts a scoped bearer token or interactive owner session. + Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. operationId: get_api_v1_webhooks_deliveries tags: - webhooks security: - bearerAuth: [] + - vendorRunIdentity: [] + runIdentityHeader: [] - cookieAuth: [] x-required-scope: runs:read x-owner-session-required: false @@ -13178,12 +13280,14 @@ paths: description: |- Requires the runs:read scope. - Accepts a scoped bearer token or interactive owner session. + Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. operationId: get_api_v1_webhooks_deliveries_deliveryId tags: - webhooks security: - bearerAuth: [] + - vendorRunIdentity: [] + runIdentityHeader: [] - cookieAuth: [] x-required-scope: runs:read x-owner-session-required: false @@ -13202,7 +13306,7 @@ paths: Requires the runs:read scope. - Accepts a scoped bearer token or interactive owner session. + Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. responses: "200": description: Status @@ -13362,6 +13466,8 @@ paths: - runs security: - bearerAuth: [] + - vendorRunIdentity: [] + runIdentityHeader: [] - cookieAuth: [] x-required-scope: runs:read x-owner-session-required: false @@ -13403,12 +13509,14 @@ paths: description: |- Requires the runs:read scope. - Accepts a scoped bearer token or interactive owner session. + Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. operationId: get_api_v1_runs_runId_artifacts_artifactId tags: - runs security: - bearerAuth: [] + - vendorRunIdentity: [] + runIdentityHeader: [] - cookieAuth: [] x-required-scope: runs:read x-owner-session-required: false @@ -13435,7 +13543,7 @@ paths: Requires the runs:read scope. - Accepts a scoped bearer token or interactive owner session. + Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. responses: "200": description: Revision-bound page @@ -13537,6 +13645,8 @@ paths: - runs security: - bearerAuth: [] + - vendorRunIdentity: [] + runIdentityHeader: [] - cookieAuth: [] x-required-scope: runs:read x-owner-session-required: false @@ -13612,12 +13722,14 @@ paths: description: |- Requires the runs:read scope. - Accepts a scoped bearer token or interactive owner session. + Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. operationId: get_api_v1_runs_runId tags: - runs security: - bearerAuth: [] + - vendorRunIdentity: [] + runIdentityHeader: [] - cookieAuth: [] x-required-scope: runs:read x-owner-session-required: false @@ -13635,7 +13747,7 @@ paths: Requires the runs:write scope. - Accepts a scoped bearer token or interactive owner session. + Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. responses: "200": description: Saved run display name @@ -13674,6 +13786,8 @@ paths: - runs security: - bearerAuth: [] + - vendorRunIdentity: [] + runIdentityHeader: [] - cookieAuth: [] x-required-scope: runs:write x-owner-session-required: false @@ -13710,7 +13824,7 @@ paths: Requires the runs:write scope. - Accepts a scoped bearer token or interactive owner session. + Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. responses: "200": description: Report saved or identical retry acknowledged @@ -13758,6 +13872,8 @@ paths: - runs security: - bearerAuth: [] + - vendorRunIdentity: [] + runIdentityHeader: [] - cookieAuth: [] x-required-scope: runs:write x-owner-session-required: false @@ -13824,12 +13940,14 @@ paths: description: |- Requires the runs:read scope. - Accepts a scoped bearer token or interactive owner session. + Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. operationId: get_api_v1_runs_runId_trace tags: - runs security: - bearerAuth: [] + - vendorRunIdentity: [] + runIdentityHeader: [] - cookieAuth: [] x-required-scope: runs:read x-owner-session-required: false @@ -13901,7 +14019,6 @@ paths: tags: - runs security: - - bearerAuth: [] - cookieAuth: [] x-required-scope: runs:cancel x-owner-session-required: true @@ -13948,12 +14065,14 @@ paths: description: |- Requires the runs:read scope. - Accepts a scoped bearer token or interactive owner session. + Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. operationId: get_api_v1_runs_runId_diagnostics tags: - runs security: - bearerAuth: [] + - vendorRunIdentity: [] + runIdentityHeader: [] - cookieAuth: [] x-required-scope: runs:read x-owner-session-required: false @@ -13993,12 +14112,14 @@ paths: description: |- Requires the runs:cancel scope. - Accepts a scoped bearer token or interactive owner session. + Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. operationId: post_api_v1_runs_runId_stop tags: - runs security: - bearerAuth: [] + - vendorRunIdentity: [] + runIdentityHeader: [] - cookieAuth: [] x-required-scope: runs:cancel x-owner-session-required: false @@ -14058,7 +14179,6 @@ paths: tags: - runs security: - - bearerAuth: [] - cookieAuth: [] x-required-scope: runs:cancel x-owner-session-required: true @@ -14099,12 +14219,14 @@ paths: description: |- Requires the runs:cancel scope. - Accepts a scoped bearer token or interactive owner session. + Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. operationId: post_api_v1_runs_runId_kill tags: - runs security: - bearerAuth: [] + - vendorRunIdentity: [] + runIdentityHeader: [] - cookieAuth: [] x-required-scope: runs:cancel x-owner-session-required: false From 01d63cd5ef39cde7581ba65984ed62b6cc6fce0b Mon Sep 17 00:00:00 2001 From: "exe.dev user" Date: Tue, 17 Nov 2026 15:05:59 +0000 Subject: [PATCH 20/28] Forward selected run credentials inside the backend and persist disconnect revocations --- docs/gen-2922-progress.md | 17 ++- docs/vendor-run-identity.md | 34 +++++ .../0049_run_credential_revocations.sql | 78 +++++++++++ packages/api/src/managed-model-credentials.ts | 68 ++++++++++ .../encrypted-integration-repository.ts | 39 ++++++ packages/api/src/public-address.ts | 61 +++++++++ packages/api/src/run-outbound-forwarder.ts | 66 ++++++++++ packages/api/src/run-outbound-proxy.ts | 82 ++++++++++++ packages/api/src/worker.ts | 2 + .../api/test/run-outbound-forwarder.test.ts | 59 +++++++++ .../api/test/vendor-run-auth.postgres.test.ts | 123 +++++++++++++++++- 11 files changed, 625 insertions(+), 4 deletions(-) create mode 100644 packages/api/migrations/0049_run_credential_revocations.sql create mode 100644 packages/api/src/managed-model-credentials.ts create mode 100644 packages/api/src/public-address.ts create mode 100644 packages/api/src/run-outbound-forwarder.ts create mode 100644 packages/api/src/run-outbound-proxy.ts create mode 100644 packages/api/test/run-outbound-forwarder.test.ts diff --git a/docs/gen-2922-progress.md b/docs/gen-2922-progress.md index 1edeac1a..ff441094 100644 --- a/docs/gen-2922-progress.md +++ b/docs/gen-2922-progress.md @@ -19,7 +19,11 @@ complete or release the breaking change until every remaining gate passes. permissions, invalid tokens and fresh exe.dev attachment checks. - [ ] Adopt vendor authentication in guest/runtime setup and outbound forwarding. Current run bearer credentials and standalone proxy admission still exist. -- [ ] Move outbound forwarding and model authentication/refresh into the backend. +- [x] Backend streaming outbound protocol for selected managed bearers, existing + GitHub API/Git/raw/archive and Linear connections, and managed model accounts. + Model refresh is serialized/persisted server-side; disconnection persists + per-run revocation and reconnect cannot restore the old selection. +- [ ] Adopt the backend protocol in guest/runtime setup and retire old forwarding. - [ ] Replace runtime provisioning, guest discovery/client setup and scheduler gates. - [ ] Remove standalone proxy/pairing/unlock API, UI, configuration and dependencies. - [ ] Implement and test the documented breaking migration and job repair behavior. @@ -82,5 +86,12 @@ evidence that non-login Factorize job processes inherit OCI environment on exe.dev; that separate runner-image gate remains unchanged. The request-admission fixture suite adds five PostgreSQL/Worker tests and -passed in the isolated validation VM. Complete validation of that follow-up -commit is pending. +passed in the isolated validation VM. The complete root suite at `bcfe788` also passed on the same isolated VM. + + +Backend outbound fixtures currently pass 21 tests across the PostgreSQL/Worker +boundary and streaming primitive suites. They cover selected/unselected and +cross-tenant denial, API/Git/Linear forwarding, model streaming and concurrent +refresh, cache restoration, failed refresh denial, cancellation/disconnection, +and permanent revocation after reconnect. This remains fixture evidence; +end-to-end guest adoption and final validation of this follow-up are pending. diff --git a/docs/vendor-run-identity.md b/docs/vendor-run-identity.md index b4817ccf..69ac478e 100644 --- a/docs/vendor-run-identity.md +++ b/docs/vendor-run-identity.md @@ -86,3 +86,37 @@ This request path is implemented alongside the old launch/runtime path while GEN-2922 remains in progress. Guest setup still needs to adopt it, and old run bearer authentication must be removed during the breaking cutover. It is not completion or release evidence for that cutover. + +## Backend outbound protocol + +`/internal/run-proxy//integrations//...` +and `/internal/run-proxy//providers/{github/,linear,model/v1}/...` +are raw outbound protocol routes authenticated by the same fresh vendor JWT and +run header. They do not expose a credential-delivery JSON API. The Worker looks +up only that run's selected credential and current tenant-owned connection. +Custom bearer origins remain fixed to a public HTTPS origin; redirects are +rejected. The deployment retains Cloudflare's documented +[`global_fetch_strictly_public`](https://developers.cloudflare.com/workers/configuration/compatibility-flags/#global-fetch-strictly-public) +flag, so outbound fetches cannot use private zone-origin routing. Request and +response body limits and a total deadline bound streaming forwarding. + +GitHub uses the existing selected App installation: REST/GraphQL uses Bearer; +Git smart HTTP uses Basic `x-access-token` and preserves `Git-Protocol` and pack +bodies. Explicit `/raw/` and `/archive/` suffixes route to the corresponding fixed +GitHub content hosts. The implementation follows the protocol distinctions in +[Clawflare's GitHub handler](https://github.com/asselstine/clawflare/blob/main/packages/github/src/index.ts). +Linear uses the existing selected connection and its existing token refresh. + +Selected model accounts are resolved from managed encrypted storage. ChatGPT +refresh follows [Codex's published OAuth refresh implementation](https://github.com/openai/codex/blob/main/codex-rs/login/src/auth/manager.rs), +restricted to its trusted authority/client. Refresh is serialized and persisted +under database locks across backend instances; failed refresh cannot use an +expired token. API key model accounts use OpenAI's API origin. Upstream tokens, +refresh tokens and model caches never cross the guest boundary. + +Disconnect/suspension records a durable revocation for existing selected runs. +Reconnecting a provider slot or reusing a deleted credential UUID cannot restore +an old grant. Execution-connection disconnection also revokes its VM identity +bindings. Newly created runs can use explicitly selected reconnected credentials. +These guarantees currently apply to the new backend request path; the legacy +runtime and its bypasses still need removal before release. diff --git a/packages/api/migrations/0049_run_credential_revocations.sql b/packages/api/migrations/0049_run_credential_revocations.sql new file mode 100644 index 00000000..82183019 --- /dev/null +++ b/packages/api/migrations/0049_run_credential_revocations.sql @@ -0,0 +1,78 @@ +-- Disconnect/suspension is permanent for existing run selections. Reconnecting +-- a provider slot or reusing an integration UUID must not restore old grants. +CREATE TABLE app.run_credential_revocations ( + tenant_id uuid NOT NULL, + run_id uuid NOT NULL, + kind text NOT NULL CHECK (kind IN ('bearer','model','github','linear')), + credential_id text NOT NULL, + revoked_at timestamptz NOT NULL DEFAULT now(), + PRIMARY KEY (tenant_id,run_id,kind,credential_id), + FOREIGN KEY (tenant_id,run_id) REFERENCES app.job_runs(tenant_id,id) ON DELETE CASCADE +); + +CREATE FUNCTION app.revoke_selected_run_credential(owner_tenant uuid, credential_kind text, selected_id text) RETURNS void LANGUAGE sql AS $$ + INSERT INTO app.run_credential_revocations(tenant_id,run_id,kind,credential_id) + SELECT r.tenant_id,r.id,credential_kind,selected_id + FROM app.runs r JOIN app.job_runs j ON j.tenant_id=r.tenant_id AND j.id=r.id + JOIN app.jobs job ON job.tenant_id=j.tenant_id AND job.id=j.job_id + JOIN app.tenants t ON t.id=r.tenant_id + WHERE r.tenant_id=owner_tenant AND j.state IN ('queued','reserved','starting','running','blocked','stopping') + AND CASE credential_kind + WHEN 'bearer' THEN coalesce(r.execution_config->'portableIntegrationIds','[]'::jsonb) @> jsonb_build_array(selected_id) + WHEN 'model' THEN r.execution_config->>'modelAccess'='portable' AND r.execution_config->>'modelAccountId'=selected_id + WHEN 'github' THEN coalesce(r.execution_config->'githubInstallationIds','[]'::jsonb) @> jsonb_build_array(selected_id::bigint) + WHEN 'linear' THEN r.execution_config->>'linearConnectionId'='linear' + ELSE false END + ON CONFLICT DO NOTHING; +$$; + +CREATE FUNCTION app.revoke_disconnected_integration() RETURNS trigger LANGUAGE plpgsql AS $$ +BEGIN + IF TG_OP='DELETE' OR (OLD.deleted_at IS NULL AND NEW.deleted_at IS NOT NULL) THEN + PERFORM app.revoke_selected_run_credential(OLD.tenant_id,OLD.kind,OLD.id::text); + END IF; + RETURN NULL; +END; +$$; +CREATE TRIGGER integration_run_revocation AFTER DELETE OR UPDATE OF deleted_at ON app.integration_records + FOR EACH ROW EXECUTE FUNCTION app.revoke_disconnected_integration(); + +CREATE FUNCTION app.revoke_disconnected_github() RETURNS trigger LANGUAGE plpgsql AS $$ +BEGIN + IF TG_OP='DELETE' OR (OLD.state='active' AND NEW.state<>'active') THEN + PERFORM app.revoke_selected_run_credential(OLD.tenant_id,'github',OLD.installation_id::text); + END IF; + RETURN NULL; +END; +$$; +CREATE TRIGGER github_run_revocation AFTER DELETE OR UPDATE OF state ON app.github_installations + FOR EACH ROW EXECUTE FUNCTION app.revoke_disconnected_github(); + +CREATE FUNCTION app.revoke_disconnected_connection() RETURNS trigger LANGUAGE plpgsql AS $$ +BEGIN + IF OLD.kind='linear' THEN + PERFORM app.revoke_selected_run_credential(OLD.tenant_id,'linear','linear'); + ELSIF OLD.kind LIKE 'exe:%' THEN + UPDATE app.vendor_run_identity_bindings b SET revoked_at=coalesce(b.revoked_at,now()),updated_at=now() + FROM app.runs r WHERE b.tenant_id=OLD.tenant_id AND b.provider='exe.dev' + AND r.tenant_id=b.tenant_id AND r.id=b.run_id AND r.execution_config->>'connectionId'=substring(OLD.kind FROM 5); + END IF; + RETURN NULL; +END; +$$; +CREATE TRIGGER connection_run_revocation AFTER DELETE ON app.connections + FOR EACH ROW EXECUTE FUNCTION app.revoke_disconnected_connection(); + +CREATE FUNCTION app.revoke_disconnected_fly() RETURNS trigger LANGUAGE plpgsql AS $$ +BEGIN + IF TG_OP='DELETE' OR OLD.organization_slug IS DISTINCT FROM NEW.organization_slug THEN + UPDATE app.vendor_run_identity_bindings SET revoked_at=coalesce(revoked_at,now()),updated_at=now() + WHERE tenant_id=OLD.tenant_id AND provider='fly.io'; + END IF; + RETURN NULL; +END; +$$; +CREATE TRIGGER fly_run_revocation AFTER DELETE OR UPDATE OF organization_slug ON app.fly_connections + FOR EACH ROW EXECUTE FUNCTION app.revoke_disconnected_fly(); + +INSERT INTO app.schema_migrations(version) VALUES ('0049_run_credential_revocations') ON CONFLICT DO NOTHING; diff --git a/packages/api/src/managed-model-credentials.ts b/packages/api/src/managed-model-credentials.ts new file mode 100644 index 00000000..c1ab23eb --- /dev/null +++ b/packages/api/src/managed-model-credentials.ts @@ -0,0 +1,68 @@ +import type { Database } from "./postgres/database"; +import type { Env } from "./types"; +import { EncryptedIntegrationRepository } from "./postgres/encrypted-integration-repository"; + +const CLIENT_ID = "app_EMoamEEZ73f0CkXaXp7hrann"; +const REFRESH_ORIGIN = "https://auth.openai.com"; +type Cache = { OPENAI_API_KEY?: unknown; tokens?: { access_token?: unknown; refresh_token?: unknown; id_token?: unknown; account_id?: unknown; chatgpt_account_id?: unknown; oauth_provenance?: { issuer?: unknown; client_id?: unknown } }; last_refresh?: unknown }; +function cache(payload: string): Cache { + const result = JSON.parse(payload); + if (!result || typeof result !== "object" || Array.isArray(result)) throw new Error("Model account requires reconnection"); + return result; +} +function nonempty(value: unknown): value is string { return typeof value === "string" && value.length > 0 && value.length <= 16_384 && !/[\r\n]/.test(value); } +function needsRefresh(auth: Cache): boolean { + if (nonempty(auth.OPENAI_API_KEY)) return false; + if (!nonempty(auth.tokens?.access_token)) return true; + try { + const claims = JSON.parse(atob(auth.tokens.access_token.split(".")[1]!.replaceAll("-", "+").replaceAll("_", "/"))); + // This is only an expiry hint for an owner-supplied upstream credential, + // never an identity verification or local authorization decision. + if (typeof claims.exp === "number") return claims.exp * 1000 <= Date.now() + 60_000; + } catch { /* Opaque tokens follow Codex's scheduled refresh interval. */ } + const refreshed = typeof auth.last_refresh === "string" ? Date.parse(auth.last_refresh) : NaN; + return !Number.isFinite(refreshed) || refreshed <= Date.now() - 8 * 24 * 60 * 60_000; +} + +/** Codex's published OAuth refresh protocol, restricted to its trusted issuer. + * No guest-supplied endpoint or client can receive the refresh credential. */ +export async function resolveManagedModelCredential(input: { database: Database; env: Env; tenantId: string; accountId: string }): Promise<{ origin: string; prefix: string; accessToken: string; accountId?: string } | null> { + const repository = new EncryptedIntegrationRepository(input.database, input.tenantId, input.env.CREDENTIAL_ENCRYPTION_KEY); + const current = await repository.managedCredential(input.accountId, "model"); + if (!current) return null; + let payload: string | null = current.payload; + if (needsRefresh(cache(payload))) { + payload = await repository.refreshManagedModel(input.accountId, async value => { + const auth = cache(value); + if (!needsRefresh(auth)) return value; + const tokens = auth.tokens; + if (!tokens || !nonempty(tokens.refresh_token)) throw new Error("Model account requires reconnection"); + const provenance = tokens.oauth_provenance; + if (provenance && (provenance.issuer !== REFRESH_ORIGIN || provenance.client_id !== CLIENT_ID)) throw new Error("Unsupported model OAuth authority"); + const response = await fetch(`${REFRESH_ORIGIN}/oauth/token`, { + method: "POST", headers: {"Content-Type": "application/json", Accept: "application/json"}, + body: JSON.stringify({client_id: CLIENT_ID, grant_type: "refresh_token", refresh_token: tokens.refresh_token}), + redirect: "error", signal: AbortSignal.timeout(10_000), + }); + if (!response.ok) { await response.body?.cancel(); throw new Error("Model account requires reconnection"); } + const refreshed = await response.json() as Record; + if (!nonempty(refreshed.access_token) || (refreshed.refresh_token !== undefined && !nonempty(refreshed.refresh_token)) || (refreshed.id_token !== undefined && !nonempty(refreshed.id_token))) throw new Error("Invalid model refresh response"); + tokens.access_token = refreshed.access_token; + if (refreshed.refresh_token !== undefined) tokens.refresh_token = refreshed.refresh_token; + if (refreshed.id_token !== undefined) tokens.id_token = refreshed.id_token; + auth.last_refresh = new Date().toISOString(); + return JSON.stringify(auth); + }); + } + if (payload === null) return null; + // Disconnect may have waited for a refresh lock; check live availability + // again before authorizing an outbound request. + const latest = await repository.managedCredential(input.accountId, "model"); + if (!latest) return null; + const auth = cache(latest.payload); + if (nonempty(auth.OPENAI_API_KEY)) return {origin: "https://api.openai.com", prefix: "/v1", accessToken: auth.OPENAI_API_KEY}; + if (!nonempty(auth.tokens?.access_token) || needsRefresh(auth)) return null; + const accountId = auth.tokens.account_id ?? auth.tokens.chatgpt_account_id; + if (accountId !== undefined && (!nonempty(accountId) || accountId.length > 512)) return null; + return {origin: "https://chatgpt.com", prefix: "/backend-api/codex", accessToken: auth.tokens.access_token, ...(typeof accountId === "string" ? {accountId} : {})}; +} diff --git a/packages/api/src/postgres/encrypted-integration-repository.ts b/packages/api/src/postgres/encrypted-integration-repository.ts index 7e14b101..2212ba8f 100644 --- a/packages/api/src/postgres/encrypted-integration-repository.ts +++ b/packages/api/src/postgres/encrypted-integration-repository.ts @@ -162,6 +162,45 @@ export class EncryptedIntegrationRepository { }); } + /** Resolve exactly one selected live credential. Legacy user ciphertext is + * deliberately unavailable to the managed backend and requires re-entry. */ + async managedCredential(id: string, kind: EncryptedIntegrationKind): Promise<(IntegrationMetadata & { revision: number; payload: string }) | null> { + const row = (await this.database.pool.query<{ id: string; kind: EncryptedIntegrationKind; name: string; origin: string | null; description: string | null; revision: string | number; encrypted_payload: string }>( + "SELECT id,kind,name,origin,description,revision,encrypted_payload FROM app.integration_records WHERE tenant_id=$1 AND id=$2 AND kind=$3 AND deleted_at IS NULL", [this.tenantId, id, kind])).rows[0]; + if (!row) return null; + const plain = await decrypt(row.encrypted_payload, this.serverEncryptionKey); + const prefix = kind === "bearer" ? MANAGED_BEARER_PREFIX : MANAGED_MODEL_PREFIX; + if (!plain.startsWith(prefix)) return null; + return { id: row.id, kind: row.kind, name: row.name, origin: row.origin, description: row.description, + revision: safeRevision(row.revision), payload: plain.slice(prefix.length) }; + } + + /** Serialize refresh across backend instances. Lock order matches writes: + * collection first, then the selected credential. A disconnect/reconnect + * cannot be overwritten by a delayed refresh. */ + async refreshManagedModel(id: string, refresh: (payload: string) => Promise): Promise { + return this.database.transaction(async client => { + const collection = (await client.query<{ revision: string | number }>("SELECT revision FROM app.integration_collections WHERE tenant_id=$1 FOR UPDATE", [this.tenantId])).rows[0]; + if (!collection) return null; + const row = (await client.query<{ revision: string | number; encrypted_payload: string; name: string; description: string | null }>( + "SELECT revision,encrypted_payload,name,description FROM app.integration_records WHERE tenant_id=$1 AND id=$2 AND kind='model' AND deleted_at IS NULL FOR UPDATE", [this.tenantId, id])).rows[0]; + if (!row) return null; + const plain = await decrypt(row.encrypted_payload, this.serverEncryptionKey); + if (!plain.startsWith(MANAGED_MODEL_PREFIX)) return null; + const payload = plain.slice(MANAGED_MODEL_PREFIX.length); + const updated = await refresh(payload); + if (updated === payload) return payload; + if (updated.length > 65_536) throw new IntegrationValidationError("Model cache exceeds its limit"); + const encrypted = await encrypt(`${MANAGED_MODEL_PREFIX}${updated}`, this.serverEncryptionKey); + const revision = safeRevision(collection.revision) + 1; + await client.query("UPDATE app.integration_collections SET revision=$2,updated_at=now() WHERE tenant_id=$1", [this.tenantId, revision]); + await client.query("UPDATE app.integration_records SET revision=revision+1,encrypted_payload=$3,updated_at=now() WHERE tenant_id=$1 AND id=$2", [this.tenantId, id, encrypted]); + await client.query(`INSERT INTO app.integration_changes(tenant_id,revision,id,idempotency_key,operation,record_id,kind,name,origin,description,encrypted_payload) + VALUES($1,$2,$3,$4,'upsert',$5,'model',$6,NULL,$7,$8)`, [this.tenantId, revision, crypto.randomUUID(), crypto.randomUUID(), id, row.name, row.description, encrypted]); + return updated; + }); + } + async records(kind?: EncryptedIntegrationKind): Promise> { const { rows } = await this.database.pool.query<{ id: string; kind: EncryptedIntegrationKind; name: string; origin: string | null; description: string | null; revision: string | number; encrypted_payload: string }>( `SELECT id,kind,name,origin,description,revision,encrypted_payload FROM app.integration_records WHERE tenant_id=$1 AND deleted_at IS NULL${kind ? " AND kind=$2" : ""} ORDER BY revision,id`, kind ? [this.tenantId, kind] : [this.tenantId]); diff --git a/packages/api/src/public-address.ts b/packages/api/src/public-address.ts new file mode 100644 index 00000000..2cd00db7 --- /dev/null +++ b/packages/api/src/public-address.ts @@ -0,0 +1,61 @@ +import { isIP } from "node:net"; + +function ipv4Number(address: string) { + return address.split(".").reduce((value, part) => (value * 256) + Number(part), 0) >>> 0; +} + +function ipv6Number(address: string) { + let source = address.toLowerCase(); + if (source.includes(".")) { + const lastColon = source.lastIndexOf(":"); + const v4 = ipv4Number(source.slice(lastColon + 1)); + source = `${source.slice(0, lastColon)}:${(v4 >>> 16).toString(16)}:${(v4 & 0xffff).toString(16)}`; + } + const halves = source.split("::"); + const left = halves[0] ? halves[0]!.split(":") : []; + const right = halves[1] ? halves[1]!.split(":") : []; + const groups = halves.length === 1 ? left : [...left, ...Array(8 - left.length - right.length).fill("0"), ...right]; + return groups.reduce((value, group) => (value << 16n) | BigInt(`0x${group || "0"}`), 0n); +} + +function inV4Range(address: string, network: string, prefix: number) { + const shift = 32 - prefix; + return (ipv4Number(address) >>> shift) === (ipv4Number(network) >>> shift); +} + +function inV6Range(value: bigint, network: string, prefix: number) { + const shift = 128n - BigInt(prefix); + return (value >> shift) === (ipv6Number(network) >> shift); +} + +const NON_PUBLIC_V4: Array<[string, number]> = [ + ["0.0.0.0", 8], ["10.0.0.0", 8], ["100.64.0.0", 10], ["127.0.0.0", 8], + ["169.254.0.0", 16], ["172.16.0.0", 12], ["192.0.0.0", 24], ["192.0.2.0", 24], + ["192.88.99.0", 24], ["192.168.0.0", 16], ["198.18.0.0", 15], ["198.51.100.0", 24], + ["203.0.113.0", 24], ["224.0.0.0", 4], ["240.0.0.0", 4], +]; + +const NON_PUBLIC_V6: Array<[string, number]> = [ + ["::", 128], ["::1", 128], ["::", 96], ["64:ff9b::", 96], ["64:ff9b:1::", 48], + ["100::", 64], ["2001::", 23], ["2001:db8::", 32], ["2002::", 16], + ["fc00::", 7], ["fe80::", 10], ["ff00::", 8], +]; + +/** Return true only for globally routable IP literals. */ +export function isPublicAddress(address: string) { + if (typeof address !== "string") return false; + const unzoned = address.split("%")[0]!; + const family = isIP(unzoned); + if (family === 4) return !NON_PUBLIC_V4.some(([network, prefix]) => inV4Range(unzoned, network, prefix)); + if (family !== 6) return false; + + const value = ipv6Number(unzoned); + // IPv4-mapped IPv6 addresses inherit the embedded IPv4 address policy. + if (value >> 32n === 0xffffn) { + const embedded = Number(value & 0xffffffffn); + return isPublicAddress([24, 16, 8, 0].map((shift) => (embedded >>> shift) & 255).join(".")); + } + // Global unicast is the only IPv6 range eligible for outbound connections. + if ((value >> 125n) !== 1n) return false; // 2000::/3 + return !NON_PUBLIC_V6.some(([network, prefix]) => inV6Range(value, network, prefix)); +} diff --git a/packages/api/src/run-outbound-forwarder.ts b/packages/api/src/run-outbound-forwarder.ts new file mode 100644 index 00000000..655c042b --- /dev/null +++ b/packages/api/src/run-outbound-forwarder.ts @@ -0,0 +1,66 @@ +/** Streaming HTTP egress for the backend Worker. The deployment must retain + * global_fetch_strictly_public: fetch never uses private zone-origin routing. + * Destinations and credentials are resolved server-side before this function. */ +export type OutboundCredential = { + origin: string; path: string; credential: string; + authorization?: "bearer" | "github-git-basic"; + headers?: Record; +}; +const hop = new Set(["connection", "keep-alive", "proxy-authenticate", "proxy-authorization", "te", "trailer", "transfer-encoding", "upgrade"]); +const privateHeaders = new Set(["host", "authorization", "cookie", "content-length", "expect", "forwarded", "x-factorize-run-id"]); + +function filteredHeaders(input: Headers, request: boolean): Headers { + const result = new Headers(); + const connectionTokens = new Set((input.get("connection") ?? "").toLowerCase().split(",").map(s => s.trim())); + input.forEach((value, key) => { + const name = key.toLowerCase(); + if (hop.has(name) || connectionTokens.has(name) || (request && (privateHeaders.has(name) || name.startsWith("x-forwarded-") || name.startsWith("sec-") || name.startsWith("cf-") || name === "origin" || name === "referer")) || (!request && name === "set-cookie")) return; + result.set(key, value); + }); + return result; +} + +function bounded(body: ReadableStream | null, bytes: number, abort: AbortController): ReadableStream | null { + if (!body) return null; + let read = 0; + return body.pipeThrough(new TransformStream({ transform(chunk, controller) { + read += chunk.byteLength; + if (read > bytes) { abort.abort(); throw new Error("Proxy stream limit exceeded"); } + controller.enqueue(chunk); + } })); +} + +/** A single-origin protocol request. No redirects, body buffering, guest + * credentials, or upstream Set-Cookie propagation. Git-Protocol is preserved. */ +export async function forwardRunOutbound(request: Request, selected: OutboundCredential, options: { + fetcher?: typeof fetch; requestBytes?: number; responseBytes?: number; timeoutMs?: number; +} = {}): Promise { + const configured = new URL(selected.origin); + if (configured.protocol !== "https:" || configured.origin !== selected.origin || configured.username || configured.password + || !selected.path.startsWith("/") || selected.path.includes("\\") || /[\r\n\0]/.test(selected.path) + || !selected.credential || /[\r\n]/.test(selected.credential)) throw new Error("Invalid outbound credential binding"); + const target = new URL(selected.origin); + const separator = selected.path.indexOf("?"); + target.pathname = separator < 0 ? selected.path : selected.path.slice(0, separator); + target.search = separator < 0 ? "" : selected.path.slice(separator); + const headers = filteredHeaders(request.headers, true); + headers.set("Authorization", selected.authorization === "github-git-basic" ? `Basic ${btoa(`x-access-token:${selected.credential}`)}` : `Bearer ${selected.credential}`); + headers.set("Accept-Encoding", "identity"); + headers.set("User-Agent", "Factorize-Run-Proxy"); + for (const [name, value] of Object.entries(selected.headers ?? {})) headers.set(name, value); + const abort = new AbortController(); + const signal = AbortSignal.any([request.signal, abort.signal, AbortSignal.timeout(options.timeoutMs ?? 15 * 60_000)]); + const response = await (options.fetcher ?? fetch)(target, { + method: request.method, headers, signal, redirect: "manual", cache: "no-store", + body: request.method === "GET" || request.method === "HEAD" ? undefined : bounded(request.body, options.requestBytes ?? 32 * 1024 * 1024, abort), + ...({duplex: "half"} as RequestInit), + }); + if (response.status >= 300 && response.status < 400) { + await response.body?.cancel(); + throw new Error("Upstream redirects are not permitted"); + } + const output = filteredHeaders(response.headers, false); + output.delete("Content-Length"); + output.set("Cache-Control", "no-store"); + return new Response(bounded(response.body, options.responseBytes ?? 64 * 1024 * 1024, abort), { status: response.status, statusText: response.statusText, headers: output }); +} diff --git a/packages/api/src/run-outbound-proxy.ts b/packages/api/src/run-outbound-proxy.ts new file mode 100644 index 00000000..b217086e --- /dev/null +++ b/packages/api/src/run-outbound-proxy.ts @@ -0,0 +1,82 @@ +import { isIP } from "node:net"; +import type { Env } from "./types"; +import { databaseFor } from "./postgres/database"; +import { EncryptedIntegrationRepository } from "./postgres/encrypted-integration-repository"; +import { resolveRunProviderCredentials } from "./provider-credentials"; +import { authenticateVendorRunRequest, RUN_IDENTITY_HEADER } from "./vendor-run-auth"; +import { forwardRunOutbound, type OutboundCredential } from "./run-outbound-forwarder"; +import { resolveManagedModelCredential } from "./managed-model-credentials"; +import { isPublicAddress } from "./public-address"; + +const unavailable = () => new Response("Run credential unavailable", {status: 403, headers: {"Cache-Control": "no-store"}}); + +function publicOrigin(value: string, backendOrigin: string): boolean { + try { + const url = new URL(value), host = url.hostname.replace(/^\[|\]$/g, ""); + return url.protocol === "https:" && url.origin === value && !url.username && !url.password && value !== backendOrigin + && (isIP(host) ? isPublicAddress(host) : host.includes(".") && !/(?:^|\.)(?:localhost|internal|local|test|invalid|example)$/.test(host)); + } catch { return false; } +} + +/** Raw outbound protocol boundary. The guest supplies a path, never an origin, + * upstream token, tenant, or credential outside its immutable run selection. */ +export async function runOutboundProxyFetch(request: Request, env: Env): Promise { + const url = new URL(request.url); + const route = /^\/internal\/run-proxy\/([0-9a-f-]{36})(\/.*)$/.exec(url.pathname); + if (!route || route[1] !== request.headers.get(RUN_IDENTITY_HEADER)) return unavailable(); + const auth = await authenticateVendorRunRequest(request, env); + if (!auth?.runId || auth.authMethod !== "vendor_identity") return unavailable(); + const database = databaseFor(env); + const active = async () => (await database.pool.query<{ execution_config: Record }>(`SELECT r.execution_config FROM app.runs r JOIN app.job_runs j ON j.tenant_id=r.tenant_id AND j.id=r.id + JOIN app.vendor_run_identity_bindings b ON b.tenant_id=j.tenant_id AND b.run_id=j.id + WHERE r.tenant_id=$1 AND r.id=$2 AND b.provider=$3 AND b.revoked_at IS NULL + AND r.state IN ('starting','running','blocked') AND j.state IN ('starting','running','blocked')`, [auth.tenantId, auth.runId, auth.runIdentityProvider])).rows[0]; + const revoked = async (kind: string, id: string) => Boolean((await database.pool.query( + "SELECT 1 FROM app.run_credential_revocations WHERE tenant_id=$1 AND run_id=$2 AND kind=$3 AND credential_id=$4", [auth.tenantId, auth.runId, kind, id])).rowCount); + const run = await active(); + if (!run) return unavailable(); + const config = run.execution_config, path = route[2]!; + let selected: OutboundCredential | null = null; + try { + const bearer = /^\/integrations\/([0-9a-f-]{36})(\/.*)?$/.exec(path); + const github = /^\/providers\/github\/([1-9][0-9]*)(\/.*)?$/.exec(path); + const linear = /^\/providers\/linear(\/.*)?$/.exec(path); + const model = /^\/providers\/model\/v1(\/.*)?$/.exec(path); + if (bearer) { + if (!Array.isArray(config.portableIntegrationIds) || !config.portableIntegrationIds.includes(bearer[1]) || await revoked("bearer", bearer[1]!)) return unavailable(); + const credential = await new EncryptedIntegrationRepository(database, auth.tenantId, env.CREDENTIAL_ENCRYPTION_KEY).managedCredential(bearer[1]!, "bearer"); + if (!credential?.origin || !publicOrigin(credential.origin, env.APP_ORIGIN)) return unavailable(); + selected = {origin: credential.origin, path: `${bearer[2] ?? "/"}${url.search}`, credential: credential.payload}; + } else if (github) { + const installationId = Number(github[1]); + if (!Number.isSafeInteger(installationId) || !Array.isArray(config.githubInstallationIds) || !config.githubInstallationIds.includes(installationId) || await revoked("github", github[1]!)) return unavailable(); + const resolved = await resolveRunProviderCredentials({database, env, tenantId: auth.tenantId, githubInstallationIds: [installationId], linearSelected: false}); + const credential = resolved.githubInstallations[0]; + if (!credential?.available || !credential.accessToken) return unavailable(); + let suffix = github[2] ?? "/", origin = "https://api.github.com"; + const smart = /\/(?:info\/refs|git-upload-pack|git-receive-pack)$/.test(suffix); + if (smart) origin = "https://github.com"; + else if (suffix.startsWith("/raw/")) { origin = "https://raw.githubusercontent.com"; suffix = suffix.slice(4); } + else if (suffix.startsWith("/archive/")) { origin = "https://codeload.github.com"; suffix = suffix.slice(8); } + selected = {origin, path: `${suffix}${url.search}`, credential: credential.accessToken, authorization: smart ? "github-git-basic" : "bearer"}; + } else if (linear) { + if (config.linearConnectionId !== "linear" || await revoked("linear", "linear")) return unavailable(); + const resolved = await resolveRunProviderCredentials({database, env, tenantId: auth.tenantId, githubInstallationIds: [], linearSelected: true}); + if (!resolved.linearConnection?.available || !resolved.linearConnection.accessToken) return unavailable(); + selected = {origin: "https://api.linear.app", path: `${linear[1] ?? "/graphql"}${url.search}`, credential: resolved.linearConnection.accessToken}; + } else if (model) { + if (config.modelAccess !== "portable" || typeof config.modelAccountId !== "string" || await revoked("model", config.modelAccountId)) return unavailable(); + const credential = await resolveManagedModelCredential({database, env, tenantId: auth.tenantId, accountId: config.modelAccountId}); + if (!credential) return unavailable(); + const suffix = model[1] ?? "/"; + const target = new URL(`${credential.origin}${credential.prefix}${suffix}`); + if (!target.pathname.startsWith(`${credential.prefix}/`)) return unavailable(); + selected = {origin: credential.origin, path: `${target.pathname}${url.search}`, credential: credential.accessToken, + ...(credential.accountId ? {headers: {"chatgpt-account-id": credential.accountId}} : {})}; + } + if (!selected || !await active()) return unavailable(); + return await forwardRunOutbound(request, selected); + } catch { + return new Response("Run outbound request unavailable", {status: 502, headers: {"Cache-Control": "no-store"}}); + } +} diff --git a/packages/api/src/worker.ts b/packages/api/src/worker.ts index c5d4406e..c627548a 100644 --- a/packages/api/src/worker.ts +++ b/packages/api/src/worker.ts @@ -15,6 +15,7 @@ import { artifactUpload } from "./artifact-upload"; import { traceChunkUpload } from "./trace-chunk-upload"; import { databaseFor } from "./postgres/database"; import { IdentityRepository } from "./postgres/identity-repository"; +import { runOutboundProxyFetch } from "./run-outbound-proxy"; import { proxyControlFetch } from "./proxy-control"; const scopes = [...ACCESS_SCOPES]; @@ -87,6 +88,7 @@ function provider(env: Env) { return new OAuthProvider(providerOptions(env) export { AlarmCoordinator } from "./alarm-coordinator"; const backend = { async fetch(request: Request, env: Env, ctx: ExecutionContext) { + if (new URL(request.url).pathname.startsWith("/internal/run-proxy/")) return runOutboundProxyFetch(request, env); if (new URL(request.url).pathname.startsWith("/internal/credential-proxy/")) return proxyControlFetch(request, env); const staticResponse = !["/authorize", "/device"].includes(new URL(request.url).pathname) ? await staticApp(request, env) : null; if (staticResponse) return staticResponse; diff --git a/packages/api/test/run-outbound-forwarder.test.ts b/packages/api/test/run-outbound-forwarder.test.ts new file mode 100644 index 00000000..93893120 --- /dev/null +++ b/packages/api/test/run-outbound-forwarder.test.ts @@ -0,0 +1,59 @@ +import { describe, expect, it } from "vitest"; +import { forwardRunOutbound } from "../src/run-outbound-forwarder"; +import { isPublicAddress } from "../src/public-address"; + +describe("backend streaming outbound protocol", () => { + it("injects Git Basic auth, preserves protocol headers and removes VM/session authority", async () => { + const request = new Request("https://factorize.test/internal/run-proxy/run/providers/github/17/owner/repo.git/git-upload-pack", { + method: "POST", headers: {Authorization: "Bearer vendor-token", Cookie: "factorize_session=private", "X-Factorize-Run-Id": "run", "Git-Protocol": "version=2", "Content-Type": "application/x-git-upload-pack-request", Connection: "x-hidden", "X-Hidden": "private", "X-Forwarded-Host": "private"}, body: "pack-request", + }); + const result = await forwardRunOutbound(request, {origin: "https://github.com", path: "/owner/repo.git/git-upload-pack", credential: "installation-token", authorization: "github-git-basic"}, { + fetcher: async (input, init) => { + expect(String(input)).toBe("https://github.com/owner/repo.git/git-upload-pack"); + const headers = init!.headers as Headers; + expect(headers.get("Authorization")).toBe(`Basic ${btoa("x-access-token:installation-token")}`); + expect(headers.get("Git-Protocol")).toBe("version=2"); + for (const name of ["Cookie", "X-Factorize-Run-Id", "X-Hidden", "X-Forwarded-Host", "Connection"]) expect(headers.has(name)).toBe(false); + expect(await new Response(init!.body).text()).toBe("pack-request"); + expect(init!.redirect).toBe("manual"); + return new Response("pack-response", {headers: {"Content-Type": "application/x-git-upload-pack-result", "Set-Cookie": "upstream-session=private", Connection: "x-upstream", "X-Upstream": "hidden"}}); + }, + }); + expect(result.headers.get("Content-Type")).toBe("application/x-git-upload-pack-result"); + expect(result.headers.has("Set-Cookie")).toBe(false); + expect(result.headers.has("X-Upstream")).toBe(false); + expect(await result.text()).toBe("pack-response"); + }); + + it("exposes streamed response chunks before the upstream finishes", async () => { + let release!: () => void; + const gate = new Promise(resolve => { release = resolve; }); + const body = new ReadableStream({async start(controller) { + controller.enqueue(new TextEncoder().encode("data: first\n\n")); + await gate; + controller.enqueue(new TextEncoder().encode("data: last\n\n")); controller.close(); + }}); + const response = await forwardRunOutbound(new Request("https://factorize.test/"), {origin: "https://api.example.com", path: "/v1/responses", credential: "selected-model"}, {fetcher: async () => new Response(body, {headers: {"Content-Type": "text/event-stream"}})}); + const reader = response.body!.getReader(); + expect(new TextDecoder().decode((await reader.read()).value)).toBe("data: first\n\n"); + release(); + expect(new TextDecoder().decode((await reader.read()).value)).toBe("data: last\n\n"); + expect((await reader.read()).done).toBe(true); + }); + + it("rejects redirects, invalid bindings and oversized streams without exposing a secret", async () => { + const credential = {origin: "https://api.example.com", path: "/", credential: "secret"}; + await expect(forwardRunOutbound(new Request("https://factorize.test/"), credential, {fetcher: async () => new Response(null, {status: 302, headers: {Location: "https://other.example/"}})})).rejects.toThrow("redirects"); + for (const invalid of [{origin: "http://api.example.com"}, {origin: "https://api.example.com/path"}, {path: "https://other.example/path"}, {path: "/\\other.example"}]) { + await expect(forwardRunOutbound(new Request("https://factorize.test/"), {...credential, ...invalid})).rejects.toThrow("binding"); + } + const response = await forwardRunOutbound(new Request("https://factorize.test/"), credential, {responseBytes: 2, fetcher: async () => new Response("oversized")}); + await expect(response.text()).rejects.toThrow("limit"); + await expect(forwardRunOutbound(new Request("https://factorize.test/", {method: "POST", body: "oversized"}), credential, {requestBytes: 2, fetcher: async (_input, init) => new Response(await new Response(init!.body).text())})).rejects.toThrow("limit"); + }); + + it.each(["127.0.0.1", "10.1.2.3", "169.254.169.254", "192.168.0.1", "100.64.0.1", "::1", "::ffff:127.0.0.1", "fc00::1", "2001:db8::1"])("rejects non-public address %s", address => { + expect(isPublicAddress(address)).toBe(false); + }); + it("accepts globally routable address literals", () => { expect(isPublicAddress("1.1.1.1")).toBe(true); expect(isPublicAddress("2606:4700:4700::1111")).toBe(true); }); +}); diff --git a/packages/api/test/vendor-run-auth.postgres.test.ts b/packages/api/test/vendor-run-auth.postgres.test.ts index 9e50a294..1cf014e8 100644 --- a/packages/api/test/vendor-run-auth.postgres.test.ts +++ b/packages/api/test/vendor-run-auth.postgres.test.ts @@ -5,6 +5,9 @@ import { FlyConnectionRepository } from "../src/postgres/fly-connection-reposito import { issueRunCredential } from "../src/run-credentials"; import { authenticateVendorRunRequest } from "../src/vendor-run-auth"; import { exeWifIntegrationNameFor, vmNameFor } from "../src/exe-vm-backend"; +import { EncryptedIntegrationRepository } from "../src/postgres/encrypted-integration-repository"; +import { GitHubRepository } from "../src/postgres/github-repository"; +import { ConnectionRepository } from "../src/postgres/connection-repository"; import worker from "../src/worker"; vi.mock("cloudflare:workers", () => ({ WorkerEntrypoint: class {}, DurableObject: class {} })); @@ -117,6 +120,121 @@ describe.skipIf(!url)("vendor identity request admission (PostgreSQL and Worker } }); + it("forwards only the run's selected managed bearer and stops after disconnect or cancellation", async () => { + const records = new EncryptedIntegrationRepository(f.db, f.tenantId, f.env.CREDENTIAL_ENCRYPTION_KEY); + const id = crypto.randomUUID(), otherId = crypto.randomUUID(); + await records.write({id, kind: "bearer", name: "selected", origin: "https://selected.example.com", description: null, expectedRevision: await records.revision(), idempotencyKey: crypto.randomUUID(), operation: "upsert", managedSecret: "selected-secret"}); + await new EncryptedIntegrationRepository(f.db, f.otherTenant, f.env.CREDENTIAL_ENCRYPTION_KEY).write({id: otherId, kind: "bearer", name: "other", origin: "https://other.example.com", description: null, expectedRevision: 0, idempotencyKey: crypto.randomUUID(), operation: "upsert", managedSecret: "other-tenant-secret"}); + await f.db.pool.query("UPDATE app.runs SET execution_config=execution_config || $3::jsonb WHERE tenant_id=$1 AND id=$2", [f.tenantId, f.runId, JSON.stringify({portableIntegrationIds: [id]})]); + const vendorFetch = globalThis.fetch; + const outbound: string[] = []; + vi.stubGlobal("fetch", vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => { + if (String(input).startsWith(issuer)) return vendorFetch(input, init); + expect(String(input)).toBe("https://selected.example.com/resource?limit=1"); + expect((init!.headers as Headers).get("Authorization")).toBe("Bearer selected-secret"); + expect((init!.headers as Headers).has("X-Factorize-Run-Id")).toBe(false); + outbound.push(String(input)); return new Response("selected response"); + })); + const call = (credentialId = id) => worker.fetch(request(jwt, f.runId, `/internal/run-proxy/${f.runId}/integrations/${credentialId}/resource?limit=1`), f.env, {waitUntil() {}} as any); + expect(await (await call()).text()).toBe("selected response"); + expect((await call(otherId)).status).toBe(403); + // Even a corrupt/foreign selection cannot escape the authenticated tenant. + await f.db.pool.query("UPDATE app.runs SET execution_config=execution_config || $3::jsonb WHERE tenant_id=$1 AND id=$2", [f.tenantId, f.runId, JSON.stringify({portableIntegrationIds: [id, otherId]})]); + expect((await call(otherId)).status).toBe(403); + await records.write({id, kind: "bearer", name: "selected", origin: "https://selected.example.com", description: null, expectedRevision: await records.revision(), idempotencyKey: crypto.randomUUID(), operation: "delete"}); + expect((await call()).status).toBe(403); + await records.write({id, kind: "bearer", name: "selected", origin: "https://selected.example.com", description: null, expectedRevision: await records.revision(), idempotencyKey: crypto.randomUUID(), operation: "upsert", managedSecret: "selected-secret"}); + expect((await call()).status).toBe(403); // Reusing the ID cannot revive a disconnected grant. + await f.db.pool.query("UPDATE app.job_runs SET state='stopping' WHERE tenant_id=$1 AND id=$2", [f.tenantId, f.runId]); + expect((await call()).status).toBe(403); + expect(outbound).toHaveLength(1); + }); + + it("reuses selected GitHub and Linear connections for API and Git protocol requests", async () => { + const installationId = 424242; + const github = new GitHubRepository(f.db, f.tenantId); + await github.save({installationId, accountLogin: "selected-org", accountType: "Organization", state: "active"}); + const connections = new ConnectionRepository(f.db, f.tenantId, f.env.CREDENTIAL_ENCRYPTION_KEY); + await connections.put("linear", {accessToken: "selected-linear", refreshToken: "linear-refresh", accessTokenExpiresAt: new Date(Date.now()+3_600_000).toISOString()}); + f.env.GITHUB_APP_ID = "fixture-app"; + const der = Buffer.from(await crypto.subtle.exportKey("pkcs8", privateKey)).toString("base64"); + f.env.GITHUB_APP_PRIVATE_KEY = `-----BEGIN PRIVATE KEY-----\n${der}\n-----END PRIVATE KEY-----`; + await f.db.pool.query("UPDATE app.runs SET execution_config=execution_config || $3::jsonb WHERE tenant_id=$1 AND id=$2", [f.tenantId, f.runId, JSON.stringify({githubInstallationIds: [installationId], linearConnectionId: "linear"})]); + const vendorFetch = globalThis.fetch; + const sent: Array<{url: string; auth: string | null; body: string; protocol: string | null}> = []; + vi.stubGlobal("fetch", vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => { + const address = String(input); + if (address.startsWith(issuer)) return vendorFetch(input, init); + if (address === `https://api.github.com/app/installations/${installationId}/access_tokens`) return Response.json({token: "selected-installation-token"}); + const headers = init!.headers as Headers; + sent.push({url: address, auth: headers.get("Authorization"), body: await new Response(init!.body).text(), protocol: headers.get("Git-Protocol")}); + return new Response("protocol response"); + })); + const call = (path: string, method = "GET", body?: string) => worker.fetch(new Request(request(jwt, f.runId, `/internal/run-proxy/${f.runId}${path}`), {method, body, headers: {Authorization: `Bearer ${jwt}`, "X-Factorize-Run-Id": f.runId, "Git-Protocol": "version=2"}}), f.env, {waitUntil() {}} as any); + expect((await call(`/providers/github/${installationId}/graphql`, "POST", "graphql")).status).toBe(200); + expect((await call(`/providers/github/${installationId}/owner/repo.git/info/refs?service=git-upload-pack`)).status).toBe(200); + expect((await call(`/providers/github/${installationId}/owner/repo.git/git-upload-pack`, "POST", "fetch-pack")).status).toBe(200); + expect((await call(`/providers/github/${installationId}/owner/repo.git/git-receive-pack`, "POST", "push-pack")).status).toBe(200); + expect((await call("/providers/linear/graphql", "POST", "linear-query")).status).toBe(200); + expect((await call(`/providers/github/${installationId}/raw/owner/repo/main/file`)).status).toBe(200); + expect((await call(`/providers/github/${installationId}/archive/owner/repo/zip/refs/heads/main`)).status).toBe(200); + expect(sent.map(value => value.auth)).toEqual(["Bearer selected-installation-token", ...Array(3).fill(`Basic ${btoa("x-access-token:selected-installation-token")}`), "Bearer selected-linear", "Bearer selected-installation-token", "Bearer selected-installation-token"]); + expect(sent[5]?.url).toBe("https://raw.githubusercontent.com/owner/repo/main/file"); + expect(sent[6]?.url).toBe("https://codeload.github.com/owner/repo/zip/refs/heads/main"); + expect(sent[2]).toMatchObject({url: "https://github.com/owner/repo.git/git-upload-pack", body: "fetch-pack", protocol: "version=2"}); + expect(sent[3]?.body).toBe("push-pack"); + expect((await call("/providers/github/99999/graphql", "POST", "unselected")).status).toBe(403); + await github.delete(installationId); + await connections.delete("linear"); + expect((await call(`/providers/github/${installationId}/graphql`, "POST", "disconnected")).status).toBe(403); + expect((await call("/providers/linear/graphql", "POST", "disconnected")).status).toBe(403); + await github.save({installationId, accountLogin: "selected-org", accountType: "Organization", state: "active"}); + await connections.put("linear", {accessToken: "reconnected-linear", refreshToken: "new-refresh", accessTokenExpiresAt: new Date(Date.now()+3_600_000).toISOString()}); + expect((await call(`/providers/github/${installationId}/graphql`, "POST", "reconnected")).status).toBe(403); + expect((await call("/providers/linear/graphql", "POST", "reconnected")).status).toBe(403); + expect(sent).toHaveLength(7); + }); + + it("refreshes the selected model server-side, streams it, restores after restart, and revokes on disconnect", async () => { + const records = new EncryptedIntegrationRepository(f.db, f.tenantId, f.env.CREDENTIAL_ENCRYPTION_KEY); + const id = crypto.randomUUID(); + const access = (exp: number) => `${encode({alg: "none"})}.${encode({exp})}.upstream-fixture`; + const old = access(Math.floor(Date.now()/1000)-5), renewed = access(Math.floor(Date.now()/1000)+3600); + await records.write({id, kind: "model", name: "selected-model", origin: null, description: null, expectedRevision: await records.revision(), idempotencyKey: crypto.randomUUID(), operation: "upsert", managedModelPayload: JSON.stringify({tokens: {access_token: old, refresh_token: "old-refresh", account_id: "selected-account"}})}); + await f.db.pool.query("UPDATE app.runs SET execution_config=execution_config || $3::jsonb WHERE tenant_id=$1 AND id=$2", [f.tenantId, f.runId, JSON.stringify({modelAccess: "portable", modelAccountId: id})]); + const vendorFetch = globalThis.fetch; + let refreshes = 0, requests = 0, failRefresh = false; + vi.stubGlobal("fetch", vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => { + if (String(input).startsWith(issuer)) return vendorFetch(input, init); + if (String(input) === "https://auth.openai.com/oauth/token") { + refreshes++; + expect(JSON.parse(String(init!.body))).toMatchObject({grant_type: "refresh_token", refresh_token: "old-refresh"}); + if (failRefresh) return Response.json({error: "invalid_grant"}, {status: 400}); + return Response.json({access_token: renewed, refresh_token: "rotated-refresh"}); + } + expect(String(input)).toBe("https://chatgpt.com/backend-api/codex/responses"); + expect((init!.headers as Headers).get("Authorization")).toBe(`Bearer ${renewed}`); + expect((init!.headers as Headers).get("chatgpt-account-id")).toBe("selected-account"); + requests++; + return new Response("data: model-stream\n\n", {headers: {"Content-Type": "text/event-stream"}}); + })); + const call = () => worker.fetch(new Request(request(jwt, f.runId, `/internal/run-proxy/${f.runId}/providers/model/v1/responses`), {method: "POST", body: "model-input"}), f.env, {waitUntil() {}} as any); + const concurrent = await Promise.all([call(), call()]); + for (const response of concurrent) expect(await response.text()).toBe("data: model-stream\n\n"); + const restored = await new EncryptedIntegrationRepository(f.db, f.tenantId, f.env.CREDENTIAL_ENCRYPTION_KEY).managedCredential(id, "model"); + expect(JSON.parse(restored!.payload).tokens.refresh_token).toBe("rotated-refresh"); + expect((await call()).status).toBe(200); + expect(refreshes).toBe(1); + failRefresh = true; + await records.write({id, kind: "model", name: "selected-model", origin: null, description: null, expectedRevision: await records.revision(), idempotencyKey: crypto.randomUUID(), operation: "upsert", managedModelPayload: JSON.stringify({tokens: {access_token: old, refresh_token: "old-refresh", account_id: "selected-account"}})}); + expect((await call()).status).toBe(502); // Failed refresh never uses the expired credential. + await records.write({id, kind: "model", name: "selected-model", origin: null, description: null, expectedRevision: await records.revision(), idempotencyKey: crypto.randomUUID(), operation: "delete"}); + expect((await call()).status).toBe(403); + await records.write({id, kind: "model", name: "selected-model", origin: null, description: null, expectedRevision: await records.revision(), idempotencyKey: crypto.randomUUID(), operation: "upsert", managedModelPayload: JSON.stringify({tokens: {access_token: renewed, refresh_token: "new-refresh", account_id: "selected-account"}})}); + expect((await call()).status).toBe(403); + expect(requests).toBe(3); + }); + it("rechecks current run lifecycle, revocation, handle and execution connection", async () => { for (const state of ["queued", "reserved", "stopping", "stopped", "succeeded", "failed"]) { await f.db.pool.query("UPDATE app.job_runs SET state=$3 WHERE tenant_id=$1 AND id=$2", [f.tenantId, f.runId, state]); @@ -129,7 +247,10 @@ describe.skipIf(!url)("vendor identity request admission (PostgreSQL and Worker await f.db.pool.query("UPDATE app.runs SET execution_handle=$3 WHERE tenant_id=$1 AND id=$2", [f.tenantId, f.runId, {id: "run-app/other-machine"}]); expect(await authenticateVendorRunRequest(request(), f.env)).toBeNull(); await f.db.pool.query("UPDATE app.runs SET execution_handle=$3 WHERE tenant_id=$1 AND id=$2", [f.tenantId, f.runId, {id: `run-app/${machineId}`}]); - await new FlyConnectionRepository(f.db, f.tenantId, f.env.CREDENTIAL_ENCRYPTION_KEY).remove(); + const fly = new FlyConnectionRepository(f.db, f.tenantId, f.env.CREDENTIAL_ENCRYPTION_KEY); + await fly.remove(); + expect(await authenticateVendorRunRequest(request(), f.env)).toBeNull(); + await fly.save({organizationSlug: "connected-org", organizationName: "Reconnected"}, "new-fixture-token"); expect(await authenticateVendorRunRequest(request(), f.env)).toBeNull(); }); }); From 940b85d9e18bda059e92c4e9262a5422cf4ae2ef Mon Sep 17 00:00:00 2001 From: "exe.dev user" Date: Tue, 17 Nov 2026 15:13:17 +0000 Subject: [PATCH 21/28] Add vendor identity guest helper and selected run integration discovery --- docs/gen-2922-progress.md | 6 + packages/api-client/src/schema.d.ts | 75 +++++++++++ packages/api/src/api-contract.ts | 5 +- packages/api/src/flow-service.ts | 31 ++++- packages/api/src/run-identity-guest-helper.ts | 92 +++++++++++++ packages/api/src/run-read-contracts.ts | 10 ++ .../test/run-identity-guest-helper.test.ts | 65 +++++++++ .../api/test/vendor-run-auth.postgres.test.ts | 9 ++ packages/docs/openapi.yaml | 125 ++++++++++++++++++ 9 files changed, 415 insertions(+), 3 deletions(-) create mode 100644 packages/api/src/run-identity-guest-helper.ts create mode 100644 packages/api/test/run-identity-guest-helper.test.ts diff --git a/docs/gen-2922-progress.md b/docs/gen-2922-progress.md index ff441094..2cc9bbe9 100644 --- a/docs/gen-2922-progress.md +++ b/docs/gen-2922-progress.md @@ -95,3 +95,9 @@ cross-tenant denial, API/Git/Linear forwarding, model streaming and concurrent refresh, cache restoration, failed refresh denial, cancellation/disconnection, and permanent revocation after reconnect. This remains fixture evidence; end-to-end guest adoption and final validation of this follow-up are pending. + +The complete root suite at `01d63cd` passed on the isolated validation VM. +The guest identity helper and selected-integration discovery API are now +implemented and pass 23 focused helper/API-contract/PostgreSQL boundary tests; +launch adoption remains pending. Discovery omits credential origins and tokens +and reports persistent revocations as unavailable, even after reconnection. diff --git a/packages/api-client/src/schema.d.ts b/packages/api-client/src/schema.d.ts index 3736d1a2..a38df30c 100644 --- a/packages/api-client/src/schema.d.ts +++ b/packages/api-client/src/schema.d.ts @@ -1726,6 +1726,28 @@ export interface paths { patch?: never; trace?: never; }; + "/api/v1/runtime-integrations": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * Discover this run's selected integration endpoints + * @description Requires vendor-verified run identity. Returns only snapshotted selections and current availability, without origins or credentials. Selection authorization is independent of the run's Factorize API scopes. + * + * Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. + */ + get: operations["get_api_v1_runtime_integrations"]; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; "/api/v1/jobs/{jobId}/invocation-permissions": { parameters: { query?: never; @@ -7238,6 +7260,59 @@ export interface operations { 503: components["responses"]["Error503"]; }; }; + get_api_v1_runtime_integrations: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description Selected run integrations */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + /** @constant */ + kind: "factorize-run-integrations-v1"; + integrations: { + id: string; + name: string; + description: string | null; + path: string; + available: boolean; + }[]; + providers: { + githubInstallations: { + installationId: number; + path: string; + available: boolean; + }[]; + linear: { + path: string; + available: boolean; + } | null; + model: { + path: string; + available: boolean; + } | null; + }; + }; + }; + }; + 400: components["responses"]["Error400"]; + 401: components["responses"]["Error401"]; + 403: components["responses"]["Error403"]; + 404: components["responses"]["Error404"]; + 409: components["responses"]["Error409"]; + 429: components["responses"]["Error429"]; + 500: components["responses"]["Error500"]; + 503: components["responses"]["Error503"]; + }; + }; get_api_v1_jobs_jobId_invocation_permissions: { parameters: { query?: never; diff --git a/packages/api/src/api-contract.ts b/packages/api/src/api-contract.ts index e295e1a9..4e57b3b6 100644 --- a/packages/api/src/api-contract.ts +++ b/packages/api/src/api-contract.ts @@ -3,7 +3,7 @@ import { searchResponse } from "./search-contracts"; import { consentPreviewInput, consentPreviewResponse, consentDecisionInput, consentDecisionResponse } from "./consent-api"; import { exeConnection, integrationStatus, authorizedClient, accessToken, createdAccessToken, savedExe, testedExe, savedAmp, savedTail, okResult } from "./settings-contracts"; import { triggerAvailabilityResponse, namedOption, providerOptions, githubInstallation, githubRepository, tailIntegration } from "./editor-contracts"; -import { runSummaryResponse, runPageResponse, runStatusResponse, fullRunResponse, revisionTracePage, revisionTraceQuery, runtimeContextResponse } from "./run-read-contracts"; +import { runSummaryResponse, runPageResponse, runStatusResponse, fullRunResponse, revisionTracePage, revisionTraceQuery, runtimeContextResponse, runtimeIntegrationsResponse } from "./run-read-contracts"; import { jobPageQuery, jobSummaryPage, jobSelectorPage, jobResponse, jobUpdateInput } from "./job-contracts"; import { projectInput, projectListQuery, projectResponse } from "./project-contracts"; import { projectGraphResponse } from "./project-graph-contracts"; @@ -191,7 +191,7 @@ function route( // Legacy route labels are translated by resource and effect; they are never // accepted as newly issued scopes. function scopeForRoute(path: string, legacy: string): string | string[] { - if (path === "/api/v1/runtime-context") return []; + if (path === "/api/v1/runtime-context" || path === "/api/v1/runtime-integrations") return []; if (legacy === "runs:write" && path.endsWith("/report-error")) return "runs:write"; if (legacy === "runs:write" && path === "/api/v1/runs/{runId}" ) return "runs:write"; if (legacy === "runs:read" && path === "/api/v1/search") return "jobs:read+runs:read"; @@ -876,6 +876,7 @@ export const API_ROUTES: RouteContract[] = [ description: "Returns the verified calling identity and effective scopes without credentials. Requires a verified active identity but no application-resource scope; callers with zero scopes can inspect only their own identity. Execution provisioning uses this operation to verify the dedicated run proxy. Execution VMs must not have additional shared Factorize proxy attachments.", responses: { "200": { description: "Verified runtime identity", content: { "application/json": { schema: jsonSchema(runtimeContextResponse, "output") } } } } }, service => service.getRuntimeContext()), + route("GET", "/api/v1/runtime-integrations", "integrations:read", { summary: "Discover this run's selected integration endpoints", description: "Requires vendor-verified run identity. Returns only snapshotted selections and current availability, without origins or credentials. Selection authorization is independent of the run's Factorize API scopes.", responses: { "200": { description: "Selected run integrations", content: { "application/json": { schema: jsonSchema(runtimeIntegrationsResponse, "output") } } } } }, service => service.getRuntimeIntegrations()), route("GET", "/api/v1/jobs/{jobId}/invocation-permissions", "jobs:read", { summary: "List a source job's manual invocation destinations", responses: { "200": { description: "Configured destination jobs in the same project", content: { "application/json": { schema: jsonSchema(invocationPermissionsResponse, "output") } } } } }, (service, { params }) => service.getInvocationPermissions(params.jobId)), route("PUT", "/api/v1/jobs/{jobId}/invocation-permissions", "jobs:write", { summary: "Replace a source job's manual invocation destinations", description: "Requires an owner session, scoped API key, or authorized OAuth client with jobs:write. Destinations must belong to the source job's project; self-invocation is allowed. A run token may invoke a configured destination only while both jobs remain in the same project. Lifecycle subscriptions do not create permissions.", responses: { "200": { description: "Saved manual invocation permissions", content: { "application/json": { schema: jsonSchema(invocationPermissionsResponse, "output") } } } } }, (service, { params, body }) => service.setInvocationPermissions(params.jobId, body.destinationJobIds), { body: invocationPermissionsInput }), route( diff --git a/packages/api/src/flow-service.ts b/packages/api/src/flow-service.ts index 6d3abd75..814609e6 100644 --- a/packages/api/src/flow-service.ts +++ b/packages/api/src/flow-service.ts @@ -3,7 +3,7 @@ import { searchResponse } from "./search-contracts"; import { integrationStatus, exeConnection, accessToken, createdAccessToken, authorizedClient } from "./settings-contracts"; import { namedOption, providerOptions, githubRepository, githubInstallation, tailIntegration } from "./editor-contracts"; import { z } from "zod"; -import { runPageResponse, fullRunResponse, runtimeContextResponse } from "./run-read-contracts"; +import { runPageResponse, fullRunResponse, runtimeContextResponse, runtimeIntegrationsResponse } from "./run-read-contracts"; import { triggerContextCatalog } from "./trigger-context"; import type { Env, OAuthProps } from "./types"; import { canonicalizeVmImage, renameRunSchema, reportRunErrorSchema, vmImageVerificationInput, type JobInput, type ManualInvocationInput } from "./flow-schemas"; @@ -202,6 +202,35 @@ export class ApiService { } private async authorizeOwnerSession(scope: Scope): Promise { await this.authorize(scope); if (this.auth.authMethod !== "session") throw new ServiceError(403, "session_required", "An interactive owner session is required."); } + async getRuntimeIntegrations() { + await this.authorizeIdentity(); + if (this.auth.authMethod !== "vendor_identity" || !this.auth.runId) throw new ServiceError(403, "forbidden", "A vendor-verified run identity is required."); + const db = databaseFor(this.env), tenantId = this.auth.tenantId, runId = this.auth.runId; + const active = (await db.pool.query<{execution_config: Record}>(`SELECT r.execution_config FROM app.runs r JOIN app.job_runs j ON j.tenant_id=r.tenant_id AND j.id=r.id + WHERE r.tenant_id=$1 AND r.id=$2 AND r.state IN ('starting','running','blocked') AND j.state IN ('starting','running','blocked')`, [tenantId, runId])).rows[0]; + if (!active) throw new ServiceError(403, "forbidden", "The run is no longer active."); + const config = active.execution_config; + const ids = Array.isArray(config.portableIntegrationIds) ? config.portableIntegrationIds : []; + const githubIds = Array.isArray(config.githubInstallationIds) ? config.githubInstallationIds : []; + const [records, installations, revoked, linear, model] = await Promise.all([ + db.pool.query<{id: string; name: string; description: string | null}>("SELECT id,name,description FROM app.integration_records WHERE tenant_id=$1 AND id=ANY($2::uuid[]) AND kind='bearer' AND deleted_at IS NULL", [tenantId, ids]), + db.pool.query<{installation_id: number; state: string}>("SELECT installation_id,state FROM app.github_installations WHERE tenant_id=$1 AND installation_id=ANY($2::bigint[])", [tenantId, githubIds]), + db.pool.query<{kind: string; credential_id: string}>("SELECT kind,credential_id FROM app.run_credential_revocations WHERE tenant_id=$1 AND run_id=$2", [tenantId, runId]), + config.linearConnectionId === "linear" ? db.pool.query("SELECT 1 FROM app.connections WHERE tenant_id=$1 AND kind='linear'", [tenantId]) : null, + config.modelAccess === "portable" && typeof config.modelAccountId === "string" ? db.pool.query("SELECT 1 FROM app.integration_records WHERE tenant_id=$1 AND id=$2 AND kind='model' AND deleted_at IS NULL", [tenantId, config.modelAccountId]) : null, + ]); + const denied = new Set(revoked.rows.map(row => `${row.kind}:${row.credential_id}`)); + return publicValue(runtimeIntegrationsResponse, { + kind: "factorize-run-integrations-v1", + integrations: ids.map((id: string) => { const record = records.rows.find(row => row.id === id); return {id, name: record?.name ?? "Unavailable integration", description: record?.description ?? null, path: `/integrations/${id}/`, available: Boolean(record) && !denied.has(`bearer:${id}`)}; }), + providers: { + githubInstallations: githubIds.map((installationId: number) => ({installationId, path: `/providers/github/${installationId}/`, available: installations.rows.some(row => Number(row.installation_id) === installationId && row.state === "active") && !denied.has(`github:${installationId}`)})), + linear: config.linearConnectionId === "linear" ? {path: "/providers/linear/", available: Boolean(linear?.rowCount) && !denied.has("linear:linear")} : null, + model: config.modelAccess === "portable" && typeof config.modelAccountId === "string" ? {path: "/providers/model/v1", available: Boolean(model?.rowCount) && !denied.has(`model:${config.modelAccountId}`)} : null, + }, + }); + } + async getRuntimeContext() { await this.authorizeIdentity(); return publicValue(runtimeContextResponse, { kind: "factorize-runtime-context-v1", authMethod: this.auth.authMethod ?? "oauth", runId: this.auth.runId ?? null, jobId: this.auth.runJobId ?? null, scopes: normalizeScopes(this.auth.scopes) }); diff --git a/packages/api/src/run-identity-guest-helper.ts b/packages/api/src/run-identity-guest-helper.ts new file mode 100644 index 00000000..e040bac2 --- /dev/null +++ b/packages/api/src/run-identity-guest-helper.ts @@ -0,0 +1,92 @@ +/** Installed inside run-owned VMs. It handles only vendor identity and streams + * to Factorize; upstream credentials never enter this process or its config. */ +export const RUN_IDENTITY_GUEST_HELPER = String.raw`import { readFile } from "node:fs/promises"; +import { request as httpRequest, createServer } from "node:http"; +import { Readable } from "node:stream"; +import { pipeline } from "node:stream/promises"; +import { pathToFileURL } from "node:url"; + +function validate(config) { + if (!config || !/^[0-9a-f-]{36}$/.test(config.runId)) throw new Error("Invalid run identity configuration"); + const origin = new URL(config.backendOrigin); + if (origin.protocol !== "https:" || origin.origin !== config.backendOrigin || origin.username || origin.password) throw new Error("Invalid backend origin"); + if (config.provider !== "exe.dev" && config.provider !== "fly.io") throw new Error("Unsupported VM identity provider"); + if (config.provider === "exe.dev" && !/^[A-Za-z0-9][A-Za-z0-9-]{0,62}$/.test(config.integrationName ?? "")) throw new Error("Invalid WIF integration"); +} +function requireToken(value) { + if (typeof value !== "string" || value.length > 16384 || !/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/.test(value.trim())) throw new Error("Vendor identity unavailable"); + return value.trim(); +} +export async function vendorToken(config, fetcher = fetch) { + validate(config); + if (config.provider === "exe.dev") { + const response = await fetcher("https://" + config.integrationName + ".int.exe.xyz/token", {redirect: "error", signal: AbortSignal.timeout(10000)}); + if (!response.ok) throw new Error("Vendor identity unavailable"); + const result = await response.json(); + return requireToken(result.token); + } + const body = JSON.stringify({aud: "factorize://runs/" + config.runId}); + const token = await new Promise((resolve, reject) => { + const request = httpRequest({socketPath: "/.fly/api", path: "/v1/tokens/oidc", method: "POST", headers: {"Content-Type": "application/json", "Content-Length": Buffer.byteLength(body)}, timeout: 10000}, response => { + let value = ""; + response.setEncoding("utf8"); + response.on("data", chunk => { value += chunk; if (value.length > 16384) request.destroy(new Error("Vendor identity unavailable")); }); + response.on("end", () => response.statusCode === 200 ? resolve(value) : reject(new Error("Vendor identity unavailable"))); + response.on("error", reject); + }); + request.on("timeout", () => request.destroy(new Error("Vendor identity unavailable"))); + request.on("error", reject); + request.end(body); + }); + return requireToken(token); +} + +export function createRunIdentityProxy(config, {getToken = () => vendorToken(config), fetcher = fetch} = {}) { + validate(config); + return createServer(async (incoming, outgoing) => { + if (incoming.url === "/_factorize/ready") { outgoing.writeHead(200, {"Content-Type": "text/plain"}).end("ready"); return; } + const abort = new AbortController(); + outgoing.on("close", () => { if (!outgoing.writableFinished) abort.abort(); }); + try { + if (!incoming.url?.startsWith("/") || incoming.url.startsWith("//") || incoming.url.includes("\\")) throw new Error("Invalid local request"); + const url = new URL(incoming.url, "http://127.0.0.1"); + let path; + if (url.pathname === "/api/v1" || url.pathname.startsWith("/api/v1/") || url.pathname === "/mcp") path = url.pathname; + else if (url.pathname === "/integrations") path = "/api/v1/runtime-integrations"; + else if (url.pathname.startsWith("/integrations/") || url.pathname.startsWith("/providers/")) path = "/internal/run-proxy/" + config.runId + url.pathname; + else { outgoing.writeHead(404).end(); return; } + const token = requireToken(await getToken()); + const headers = new Headers(); + const blocked = new Set(["host", "authorization", "cookie", "connection", "keep-alive", "proxy-authorization", "proxy-authenticate", "te", "trailer", "transfer-encoding", "upgrade", "content-length", "expect", "x-factorize-run-id"]); + const connectionTokens = new Set(String(incoming.headers.connection ?? "").toLowerCase().split(",").map(value => value.trim())); + for (const [name, value] of Object.entries(incoming.headers)) { + if (value !== undefined && !blocked.has(name) && !connectionTokens.has(name) && !name.startsWith("x-forwarded-") && name !== "forwarded") headers.set(name, Array.isArray(value) ? value.join(", ") : value); + } + headers.set("Authorization", "Bearer " + token); + headers.set("X-Factorize-Run-Id", config.runId); + const method = incoming.method ?? "GET"; + const response = await fetcher(config.backendOrigin + path + url.search, { + method, headers, body: method === "GET" || method === "HEAD" ? undefined : Readable.toWeb(incoming), duplex: "half", + redirect: "manual", signal: AbortSignal.any([abort.signal, AbortSignal.timeout(15 * 60 * 1000)]), + }); + const output = {}; + const privateResponseHeaders = new Set(["connection", "keep-alive", "proxy-authenticate", "proxy-authorization", "te", "trailer", "transfer-encoding", "upgrade", "set-cookie", "content-length", "content-encoding"]); + const responseConnectionTokens = new Set((response.headers.get("connection") ?? "").toLowerCase().split(",").map(value => value.trim())); + response.headers.forEach((value, name) => { if (!privateResponseHeaders.has(name) && !responseConnectionTokens.has(name)) output[name] = value; }); + outgoing.writeHead(response.status, output); + if (!response.body) outgoing.end(); + else await pipeline(Readable.fromWeb(response.body), outgoing); + } catch { + abort.abort(); + if (!outgoing.headersSent) outgoing.writeHead(502, {"Content-Type": "text/plain", "Cache-Control": "no-store"}).end("Factorize run access unavailable"); + else outgoing.destroy(); + } + }); +} + +if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { + const config = JSON.parse(await readFile(process.argv[2] ?? "/run/factorize-identity/config.json", "utf8")); + const server = createRunIdentityProxy(config); + server.listen(config.localPort ?? 18180, "127.0.0.1"); +} +`; diff --git a/packages/api/src/run-read-contracts.ts b/packages/api/src/run-read-contracts.ts index 62e19940..923ac443 100644 --- a/packages/api/src/run-read-contracts.ts +++ b/packages/api/src/run-read-contracts.ts @@ -3,6 +3,16 @@ export const runtimeContextResponse = z.object({ kind: z.literal("factorize-runtime-context-v1"), authMethod: z.string(), runId: z.string().nullable(), jobId: z.string().nullable(), scopes: z.array(z.string()), }); +const runIntegration = z.object({ id: z.string(), name: z.string(), description: z.string().nullable(), path: z.string(), available: z.boolean() }); +export const runtimeIntegrationsResponse = z.object({ + kind: z.literal("factorize-run-integrations-v1"), + integrations: z.array(runIntegration), + providers: z.object({ + githubInstallations: z.array(z.object({installationId: z.number().int(), path: z.string(), available: z.boolean()})), + linear: z.object({path: z.string(), available: z.boolean()}).nullable(), + model: z.object({path: z.string(), available: z.boolean()}).nullable(), + }), +}); export const executionState = z.enum(["queued", "reserved", "starting", "running", "blocked", "stopping", "succeeded", "failed", "stopped"]); export const agentErrorResponse = z.object({ reason: z.string(), reported_at: z.string(), reporter: z.object({ user_id: z.string(), kind: z.enum(["api_key", "oauth", "session", "run_token"]), id: z.string() }) }); export const runFailureResponse = z.object({ source: z.enum(["run", "system"]), code: z.string(), reason: z.string() }); diff --git a/packages/api/test/run-identity-guest-helper.test.ts b/packages/api/test/run-identity-guest-helper.test.ts new file mode 100644 index 00000000..345978fb --- /dev/null +++ b/packages/api/test/run-identity-guest-helper.test.ts @@ -0,0 +1,65 @@ +import { afterAll, beforeAll, describe, expect, it } from "vitest"; +import { RUN_IDENTITY_GUEST_HELPER } from "../src/run-identity-guest-helper"; +import type { Server } from "node:http"; + +const runId = "11111111-1111-4111-8111-111111111111"; +const config = {runId, backendOrigin: "https://factorize.example.com", provider: "exe.dev", integrationName: "fz-run-test"}; +let helper: any; +beforeAll(async () => { helper = await import(/* @vite-ignore */ `data:text/javascript;base64,${Buffer.from(RUN_IDENTITY_GUEST_HELPER).toString("base64")}`); }); +const servers: Server[] = []; +afterAll(async () => { await Promise.all(servers.map(server => new Promise(resolve => {server.closeAllConnections(); server.close(() => resolve());}))); }); +async function listen(server: Server): Promise { + servers.push(server); + await new Promise(resolve => server.listen(0, "127.0.0.1", resolve)); + return `http://127.0.0.1:${(server.address() as {port: number}).port}`; +} + +describe("run-owned vendor identity guest helper", () => { + it("renews vendor identity per request and streams only to the configured backend", async () => { + let tokens = 0; + const forwarded: Array<{url: string; token: string; body: string; protocol: string | null}> = []; + const server = helper.createRunIdentityProxy(config, { + getToken: async () => `header.claims.signature${++tokens}`, + fetcher: async (input: string, init: RequestInit) => { + const headers = init.headers as Headers; + expect(headers.get("X-Factorize-Run-Id")).toBe(runId); + expect(headers.has("Cookie")).toBe(false); + forwarded.push({url: input, token: headers.get("Authorization")!, body: await new Response(init.body).text(), protocol: headers.get("Git-Protocol")}); + return new Response("data: streamed\n\n", {headers: {"Content-Type": "text/event-stream", "Set-Cookie": "private=value"}}); + }, + }); + const origin = await listen(server); + const response = await fetch(`${origin}/providers/github/17/owner/repo.git/git-upload-pack`, {method: "POST", body: "pack-request", headers: {Authorization: "Bearer guest-supplied", Cookie: "factorize_session=private", "X-Factorize-Run-Id": "other-run", "Git-Protocol": "version=2"}}); + expect(await response.text()).toBe("data: streamed\n\n"); + expect(response.headers.has("Set-Cookie")).toBe(false); + await (await fetch(`${origin}/api/v1/runtime-context`)).body?.cancel(); + await (await fetch(`${origin}/integrations`)).body?.cancel(); + expect(forwarded).toMatchObject([ + {url: `https://factorize.example.com/internal/run-proxy/${runId}/providers/github/17/owner/repo.git/git-upload-pack`, token: "Bearer header.claims.signature1", body: "pack-request", protocol: "version=2"}, + {url: "https://factorize.example.com/api/v1/runtime-context", token: "Bearer header.claims.signature2"}, + {url: "https://factorize.example.com/api/v1/runtime-integrations", token: "Bearer header.claims.signature3"}, + ]); + }); + + it("fails closed when vendor identity is unavailable and rejects unsupported providers", async () => { + let calls = 0; + const origin = await listen(helper.createRunIdentityProxy(config, {getToken: async () => {throw new Error("private provider response");}, fetcher: async () => {calls++; return new Response("unexpected");}})); + const response = await fetch(`${origin}/api/v1/runtime-context`); + expect(response.status).toBe(502); + expect(await response.text()).toBe("Factorize run access unavailable"); + expect(calls).toBe(0); + expect(() => helper.createRunIdentityProxy({...config, provider: "shared-secret", token: "fallback"})).toThrow("Unsupported"); + expect(() => helper.createRunIdentityProxy({...config, backendOrigin: "http://factorize.example.com"})).toThrow("origin"); + }); + + it("acquires exe.dev tokens only from the documented exact integration host", async () => { + const calls: string[] = []; + const token = await helper.vendorToken(config, async (url: string, init: RequestInit) => { + calls.push(url); expect(init.redirect).toBe("error"); + return Response.json({token: "header.claims.signature"}); + }); + expect(token).toBe("header.claims.signature"); + expect(calls).toEqual(["https://fz-run-test.int.exe.xyz/token"]); + await expect(helper.vendorToken(config, async () => new Response("private", {status: 403}))).rejects.toThrow("Vendor identity unavailable"); + }); +}); diff --git a/packages/api/test/vendor-run-auth.postgres.test.ts b/packages/api/test/vendor-run-auth.postgres.test.ts index 1cf014e8..3851c4ac 100644 --- a/packages/api/test/vendor-run-auth.postgres.test.ts +++ b/packages/api/test/vendor-run-auth.postgres.test.ts @@ -137,6 +137,12 @@ describe.skipIf(!url)("vendor identity request admission (PostgreSQL and Worker })); const call = (credentialId = id) => worker.fetch(request(jwt, f.runId, `/internal/run-proxy/${f.runId}/integrations/${credentialId}/resource?limit=1`), f.env, {waitUntil() {}} as any); expect(await (await call()).text()).toBe("selected response"); + const reflected = await worker.fetch(request(jwt, f.runId, "/api/v1/runtime-integrations"), f.env, {waitUntil() {}} as any); + expect(reflected.status).toBe(200); + const metadata = await reflected.json() as any; + expect(metadata.integrations).toEqual([{id, name: "selected", description: null, path: `/integrations/${id}/`, available: true}]); + expect(JSON.stringify(metadata)).not.toMatch(/selected-secret|other-tenant-secret|selected\.example\.com|other\.example\.com/); + expect((await call(otherId)).status).toBe(403); // Even a corrupt/foreign selection cannot escape the authenticated tenant. await f.db.pool.query("UPDATE app.runs SET execution_config=execution_config || $3::jsonb WHERE tenant_id=$1 AND id=$2", [f.tenantId, f.runId, JSON.stringify({portableIntegrationIds: [id, otherId]})]); @@ -145,6 +151,9 @@ describe.skipIf(!url)("vendor identity request admission (PostgreSQL and Worker expect((await call()).status).toBe(403); await records.write({id, kind: "bearer", name: "selected", origin: "https://selected.example.com", description: null, expectedRevision: await records.revision(), idempotencyKey: crypto.randomUUID(), operation: "upsert", managedSecret: "selected-secret"}); expect((await call()).status).toBe(403); // Reusing the ID cannot revive a disconnected grant. + const disconnected = await worker.fetch(request(jwt, f.runId, "/api/v1/runtime-integrations"), f.env, {waitUntil() {}} as any); + expect((await disconnected.json() as any).integrations[0].available).toBe(false); + await f.db.pool.query("UPDATE app.job_runs SET state='stopping' WHERE tenant_id=$1 AND id=$2", [f.tenantId, f.runId]); expect((await call()).status).toBe(403); expect(outbound).toHaveLength(1); diff --git a/packages/docs/openapi.yaml b/packages/docs/openapi.yaml index 5a94fbbc..a4cfdb3d 100644 --- a/packages/docs/openapi.yaml +++ b/packages/docs/openapi.yaml @@ -10901,6 +10901,131 @@ paths: - cookieAuth: [] x-required-scope: [] x-owner-session-required: false + /api/v1/runtime-integrations: + get: + summary: Discover this run's selected integration endpoints + description: |- + Requires vendor-verified run identity. Returns only snapshotted selections and current availability, without origins or credentials. Selection authorization is independent of the run's Factorize API scopes. + + Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. + responses: + "200": + description: Selected run integrations + content: + application/json: + schema: + type: object + properties: + kind: + type: string + const: factorize-run-integrations-v1 + integrations: + type: array + items: + type: object + properties: + id: + type: string + name: + type: string + description: + type: + - string + - "null" + path: + type: string + available: + type: boolean + required: + - id + - name + - description + - path + - available + additionalProperties: false + providers: + type: object + properties: + githubInstallations: + type: array + items: + type: object + properties: + installationId: + type: integer + minimum: -9007199254740991 + maximum: 9007199254740991 + path: + type: string + available: + type: boolean + required: + - installationId + - path + - available + additionalProperties: false + linear: + anyOf: + - type: object + properties: + path: + type: string + available: + type: boolean + required: + - path + - available + additionalProperties: false + - type: "null" + model: + anyOf: + - type: object + properties: + path: + type: string + available: + type: boolean + required: + - path + - available + additionalProperties: false + - type: "null" + required: + - githubInstallations + - linear + - model + additionalProperties: false + required: + - kind + - integrations + - providers + additionalProperties: false + "400": + $ref: "#/components/responses/Error400" + "401": + $ref: "#/components/responses/Error401" + "403": + $ref: "#/components/responses/Error403" + "404": + $ref: "#/components/responses/Error404" + "409": + $ref: "#/components/responses/Error409" + "429": + $ref: "#/components/responses/Error429" + "500": + $ref: "#/components/responses/Error500" + "503": + $ref: "#/components/responses/Error503" + operationId: get_api_v1_runtime_integrations + tags: + - runtime-integrations + security: + - bearerAuth: [] + - vendorRunIdentity: [] + runIdentityHeader: [] + - cookieAuth: [] + x-required-scope: [] + x-owner-session-required: false /api/v1/jobs/{jobId}/invocation-permissions: get: summary: List a source job's manual invocation destinations From f1aaa50f2b4faa1e798c0247de30326d3b1cbd0c Mon Sep 17 00:00:00 2001 From: "exe.dev user" Date: Tue, 17 Nov 2026 15:19:28 +0000 Subject: [PATCH 22/28] Use token-free run snapshots and Worker-compatible Fly guest execution --- docs/gen-2922-progress.md | 5 ++ .../migrations/0050_run_authorizations.sql | 15 +++++ packages/api/src/fly-http-guest-transport.ts | 65 +++++++++++++++++++ packages/api/src/fly-job-execution-backend.ts | 4 +- packages/api/src/postgres/run-scheduler.ts | 3 + packages/api/src/postgres/schema.ts | 3 +- packages/api/src/run-authorizations.ts | 11 ++++ packages/api/src/vendor-run-auth.ts | 2 +- .../api/test/fly-http-guest-transport.test.ts | 43 ++++++++++++ .../api/test/vendor-run-auth.postgres.test.ts | 10 +-- 10 files changed, 153 insertions(+), 8 deletions(-) create mode 100644 packages/api/migrations/0050_run_authorizations.sql create mode 100644 packages/api/src/fly-http-guest-transport.ts create mode 100644 packages/api/src/run-authorizations.ts create mode 100644 packages/api/test/fly-http-guest-transport.test.ts diff --git a/docs/gen-2922-progress.md b/docs/gen-2922-progress.md index 2cc9bbe9..d3809fb0 100644 --- a/docs/gen-2922-progress.md +++ b/docs/gen-2922-progress.md @@ -101,3 +101,8 @@ The guest identity helper and selected-integration discovery API are now implemented and pass 23 focused helper/API-contract/PostgreSQL boundary tests; launch adoption remains pending. Discovery omits credential origins and tokens and reports persistent revocations as unavailable, even after reconnection. + +Runtime foundations now include token-free immutable run authorization +snapshots (independent of legacy bearer rows) and a Worker-compatible Fly guest +transport using the documented Machines HTTP exec API with argv/stdin. +Focused transport, Fly backend and vendor-request boundary suites pass 29 tests. diff --git a/packages/api/migrations/0050_run_authorizations.sql b/packages/api/migrations/0050_run_authorizations.sql new file mode 100644 index 00000000..b4a6c2f8 --- /dev/null +++ b/packages/api/migrations/0050_run_authorizations.sql @@ -0,0 +1,15 @@ +-- Immutable, token-free owner/scope snapshots for vendor-authenticated runs. +-- Kept independently of browser sessions and legacy run bearer credentials. +CREATE TABLE app.run_authorizations ( + tenant_id uuid NOT NULL, + run_id uuid NOT NULL, + user_id uuid NOT NULL, + session_version integer NOT NULL, + scopes jsonb NOT NULL CHECK (jsonb_typeof(scopes)='array'), + 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 +); +-- Deliberately retain the original user/session binding if membership is +-- deleted: a replacement owner cannot recreate authority for an old run. +INSERT INTO app.schema_migrations(version) VALUES ('0050_run_authorizations') ON CONFLICT DO NOTHING; diff --git a/packages/api/src/fly-http-guest-transport.ts b/packages/api/src/fly-http-guest-transport.ts new file mode 100644 index 00000000..a51877a6 --- /dev/null +++ b/packages/api/src/fly-http-guest-transport.ts @@ -0,0 +1,65 @@ +import { Buffer } from "node:buffer"; +import type { JobGuest } from "./machine-job-execution-backend"; + +type Options = {app: string; machine: string; token: string; apiOrigin?: string; fetcher?: typeof fetch; timeoutMs?: number; outputLimitBytes?: number; fileLimitBytes?: number}; +function path(value: string): string { + if (!value.startsWith("/") || /[\r\n\0]/.test(value) || value.split("/").some(part => part === "." || part === "..")) throw new TypeError("Invalid guest file path"); + return value; +} +function failure(): Error { return new Error("Fly guest HTTP transport unavailable"); } + +/** Worker-compatible guest transport using the documented Machines exec API, + * including stdin. No host CLI, subprocess, filesystem or credential-bearing + * argv is required in the Factorize backend. */ +export function createFlyHttpGuestTransport(options: Options): Required { + if (!/^[a-z0-9-]+$/.test(options.app) || !/^[A-Za-z0-9-]+$/.test(options.machine) || !options.token) throw new TypeError("Invalid Fly guest identity"); + const origin = options.apiOrigin ?? "https://api.machines.dev"; + const timeoutMs = options.timeoutMs ?? 30_000, outputLimit = options.outputLimitBytes ?? 64 * 1024, fileLimit = options.fileLimitBytes ?? 16 * 1024 * 1024; + if (new URL(origin).origin !== origin || !Number.isSafeInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 600_000 + || !Number.isSafeInteger(outputLimit) || outputLimit < 1 || outputLimit > 16 * 1024 * 1024 + || !Number.isSafeInteger(fileLimit) || fileLimit < 1 || fileLimit > 64 * 1024 * 1024) throw new TypeError("Invalid Fly guest transport limits"); + async function execute(command: readonly string[], input: string | Uint8Array | undefined, limit: number) { + if (!command.length || command.some(arg => typeof arg !== "string" || arg.includes("\0"))) throw new TypeError("Invalid Fly guest command"); + const stdin = typeof input === "string" || input === undefined ? input : new TextDecoder("utf8", {fatal: true}).decode(input); + try { + const response = await (options.fetcher ?? fetch)(`${origin}/v1/apps/${encodeURIComponent(options.app)}/machines/${encodeURIComponent(options.machine)}/exec`, { + method: "POST", headers: {Authorization: `Bearer ${options.token}`, "Content-Type": "application/json", Accept: "application/json"}, + body: JSON.stringify({command, ...(stdin !== undefined ? {stdin} : {}), timeout: Math.max(1, Math.ceil(timeoutMs/1000))}), + redirect: "error", signal: AbortSignal.timeout(timeoutMs), + }); + if (!response.ok || !response.body) { await response.body?.cancel(); throw failure(); } + const reader = response.body.getReader(); + const chunks: Uint8Array[] = []; let size = 0; + for (;;) { + const {value, done} = await reader.read(); if (done) break; + size += value.byteLength; + // JSON can escape each output byte as six characters. + if (size > limit * 6 + 65_536) { await reader.cancel(); throw failure(); } + chunks.push(value); + } + const data = new Uint8Array(size); let offset = 0; + for (const chunk of chunks) {data.set(chunk, offset); offset += chunk.byteLength;} + const result = JSON.parse(new TextDecoder().decode(data)); + if (typeof result.stdout !== "string" || typeof result.stderr !== "string" || !Number.isInteger(result.exit_code) + || new TextEncoder().encode(result.stdout).byteLength + new TextEncoder().encode(result.stderr).byteLength > limit) throw failure(); + return {ok: result.exit_code === 0, exitCode: result.exit_code as number, stdout: result.stdout as string, stderr: result.stderr as string}; + } catch { throw failure(); } + } + return { + run: (command, input) => execute(command, input, outputLimit), + async upload(remotePath, bytes) { + remotePath = path(remotePath); + if (bytes.byteLength > fileLimit) throw new Error("Fly guest upload exceeds its limit"); + const result = await execute(["/bin/sh", "-c", 'umask 077; base64 -d > "$1"', "factorize-upload", remotePath], Buffer.from(bytes).toString("base64"), outputLimit); + if (!result.ok) throw failure(); + }, + async download(remotePath) { + remotePath = path(remotePath); + const result = await execute(["python3", "-c", "import base64,sys; data=open(sys.argv[1],'rb').read(int(sys.argv[2])+1); sys.exit(3) if len(data)>int(sys.argv[2]) else sys.stdout.write(base64.b64encode(data).decode('ascii'))", remotePath, String(fileLimit)], undefined, Math.ceil(fileLimit*4/3)+1024); + if (!result.ok || !/^[A-Za-z0-9+/]*={0,2}$/.test(result.stdout)) throw failure(); + const bytes = Uint8Array.from(atob(result.stdout), c => c.charCodeAt(0)); + if (bytes.byteLength > fileLimit) throw failure(); + return bytes; + }, + }; +} diff --git a/packages/api/src/fly-job-execution-backend.ts b/packages/api/src/fly-job-execution-backend.ts index cdc0142f..8af85f9a 100644 --- a/packages/api/src/fly-job-execution-backend.ts +++ b/packages/api/src/fly-job-execution-backend.ts @@ -1,5 +1,5 @@ import { MachineJobExecutionBackend } from "./machine-job-execution-backend"; -import { createFlyGuestTransport } from "./fly-guest-transport"; +import { createFlyHttpGuestTransport } from "./fly-http-guest-transport"; import { flyJobMachineConfig } from "./fly-job-machine"; export type { JobMachines as FlyJobMachines, JobGuest as FlyJobGuest, ProxyGuest as FlyProxyGuest } from "./machine-job-execution-backend"; @@ -26,5 +26,5 @@ export class FlyJobExecutionBackend extends MachineJobExecutionBackend { /** CLI credentials stay in the scheduler process. */ export function flyJobGuest(options: { app: string; machine: string; token: string }) { - return createFlyGuestTransport({ ...options, timeoutMs: 30_000, outputLimitBytes: 64 * 1024 }); + return createFlyHttpGuestTransport({ ...options, timeoutMs: 30_000, outputLimitBytes: 64 * 1024 }); } diff --git a/packages/api/src/postgres/run-scheduler.ts b/packages/api/src/postgres/run-scheduler.ts index 89fd7ada..0bb46c04 100644 --- a/packages/api/src/postgres/run-scheduler.ts +++ b/packages/api/src/postgres/run-scheduler.ts @@ -21,6 +21,8 @@ import { rolloutTraceSources } from "../trace-source"; import { TraceProjectionRepository, TRACE_PARSER_VERSION } from "./trace-projection-repository"; import { LiveTraceRepository } from "./live-trace-repository"; import { JOB_RESULT_INSTRUCTIONS, parseJobResult } from "../job-result"; +import { snapshotRunAuthorization } from "../run-authorizations"; +import { DEFAULT_RUN_SCOPES } from "../run-scopes"; import { issueRunCredential, runProxyInstructions } from "../run-credentials"; import { ProxyLaunchBlockedError, proxyLaunchDecision, requireProxyLaunch } from "../proxy-launch-policy"; import { FlyConnectionRepository } from "./fly-connection-repository"; @@ -176,6 +178,7 @@ export class RunScheduler { private async launch(run: PersistedRun) { const config = run.executionConfig; + await snapshotRunAuthorization(this.database, {tenantId: run.tenantId, runId: run.id, scopes: config.runScopes ?? DEFAULT_RUN_SCOPES}); const decision = proxyLaunchDecision({ executionProvider: config.executionProvider === "fly" || config.executionProvider === "docker" ? "fly" : "exe", executionType: config.executionType === "code" ? "code" : "agent", diff --git a/packages/api/src/postgres/schema.ts b/packages/api/src/postgres/schema.ts index 880433c4..636416b6 100644 --- a/packages/api/src/postgres/schema.ts +++ b/packages/api/src/postgres/schema.ts @@ -114,6 +114,7 @@ export const runTraceEvents = app.table("run_trace_events", { }, t => [primaryKey({ columns: [t.tenantId, t.runId, t.sequence] }), foreignKey({ columns: [t.tenantId, t.runId], foreignColumns: [runs.tenantId, runs.id] }).onDelete("cascade"), index("run_trace_events_search").using("gin", t.searchVector), index("run_trace_events_by_type").on(t.tenantId, t.runId, t.eventType, t.sequence)]); export const runActivity = app.table("run_activity", { tenantId: uuid("tenant_id").notNull(), id: uuid("id").notNull(), runId: uuid("run_id").notNull(), action: text("action").notNull(), detail: text("detail").notNull(), createdAt: createdAt() }, t => [primaryKey({ columns: [t.tenantId, t.id] }), foreignKey({ columns: [t.tenantId, t.runId], foreignColumns: [runs.tenantId, runs.id] }).onDelete("cascade")]); export const activeClaims = app.table("active_claims", { tenantId: uuid("tenant_id").notNull(), jobId: uuid("job_id").notNull(), claimKey: text("claim_key").notNull(), runId: uuid("run_id").notNull(), expiresAt: timestamp("expires_at", { withTimezone: true }) }, t => [primaryKey({ columns: [t.tenantId, t.jobId, t.claimKey] }), foreignKey({ columns: [t.tenantId, t.jobId], foreignColumns: [jobs.tenantId, jobs.id] }).onDelete("cascade"), foreignKey({ columns: [t.tenantId, t.runId], foreignColumns: [runs.tenantId, runs.id] }).onDelete("cascade")]); +export const runAuthorizations = app.table("run_authorizations", { tenantId: uuid("tenant_id").notNull(), runId: uuid("run_id").notNull(), userId: uuid("user_id").notNull(), sessionVersion: integer("session_version").notNull(), scopes: jsonb("scopes").$type().notNull(), createdAt: createdAt() }, t => [primaryKey({ columns: [t.tenantId, t.runId] }), foreignKey({ columns: [t.tenantId, t.runId], foreignColumns: [jobRuns.tenantId, jobRuns.id] }).onDelete("cascade")]); export const runCredentials = app.table("run_credentials", { tenantId: uuid("tenant_id").notNull(), runId: uuid("run_id").notNull(), digest: text("digest").notNull(), proxyName: text("proxy_name"), scopes: jsonb("scopes").$type().notNull().default(DEFAULT_RUN_SCOPES), userId: uuid("user_id").notNull(), sessionVersion: integer("session_version").notNull(), expiresAt: timestamp("expires_at", { withTimezone: true }).notNull() }, t => [primaryKey({ columns: [t.tenantId, t.runId] }), foreignKey({ columns: [t.tenantId, t.runId], foreignColumns: [jobRuns.tenantId, jobRuns.id] }).onDelete("cascade"), foreignKey({ columns: [t.tenantId, t.userId], foreignColumns: [members.tenantId, members.userId] }).onDelete("cascade"), index("run_credentials_digest").on(t.digest)]); export const scheduleState = app.table("schedule_state", { tenantId: uuid("tenant_id").notNull(), triggerId: uuid("trigger_id").notNull(), jobId: uuid("job_id").notNull(), nextRunAt: timestamp("next_run_at", { withTimezone: true }), lastTriggeredAt: timestamp("last_triggered_at", { withTimezone: true }) }, t => [primaryKey({ columns: [t.tenantId, t.triggerId] }), foreignKey({ columns: [t.tenantId, t.triggerId], foreignColumns: [triggers.tenantId, triggers.id] }).onDelete("cascade"), foreignKey({ columns: [t.tenantId, t.jobId], foreignColumns: [jobs.tenantId, jobs.id] }).onDelete("cascade"), index("schedules_due").on(t.nextRunAt).where(sql`${t.nextRunAt} is not null`)]); @@ -168,7 +169,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, credentialProxyStates, credentialProxyControlCredentials, credentialRunGrants, credentialRunEnrollments, linearWorkspaces, githubInstallations, githubSetupStates, projects, jobs, vmImageVerifications, skills, jobSkills, triggers, webhookConditionsCutover, invocations, manualInvocationPermissions, jobRuns, runCredentials, runs, runArtifacts, runRetentionCleanup, + connections, integrationCollections, integrationRecords, integrationChanges, credentialProxyStates, credentialProxyControlCredentials, credentialRunGrants, credentialRunEnrollments, linearWorkspaces, githubInstallations, githubSetupStates, projects, jobs, vmImageVerifications, skills, jobSkills, triggers, webhookConditionsCutover, invocations, manualInvocationPermissions, jobRuns, runAuthorizations, runCredentials, runs, runArtifacts, runRetentionCleanup, 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-authorizations.ts b/packages/api/src/run-authorizations.ts new file mode 100644 index 00000000..7b320b04 --- /dev/null +++ b/packages/api/src/run-authorizations.ts @@ -0,0 +1,11 @@ +import type { Database } from "./postgres/database"; +import { normalizeScopes } from "./access-tokens"; + +/** Capture once, before provisioning. Retries/restarts cannot broaden scopes + * or replace a revoked owner/session binding. There is no guest credential. */ +export async function snapshotRunAuthorization(database: Database, input: {tenantId: string; runId: string; scopes: readonly string[]}): Promise { + const owner = (await database.pool.query<{user_id: string; session_version: number}>("SELECT user_id,session_version FROM app.members WHERE tenant_id=$1 AND role='owner' ORDER BY user_id LIMIT 1", [input.tenantId])).rows[0]; + if (!owner) throw new Error("Run owner is unavailable"); + await database.pool.query(`INSERT INTO app.run_authorizations(tenant_id,run_id,user_id,session_version,scopes) + VALUES($1,$2,$3,$4,$5::jsonb) ON CONFLICT(tenant_id,run_id) DO NOTHING`, [input.tenantId, input.runId, owner.user_id, owner.session_version, JSON.stringify(normalizeScopes(input.scopes))]); +} diff --git a/packages/api/src/vendor-run-auth.ts b/packages/api/src/vendor-run-auth.ts index ead41dd5..4af07eae 100644 --- a/packages/api/src/vendor-run-auth.ts +++ b/packages/api/src/vendor-run-auth.ts @@ -29,7 +29,7 @@ export async function authenticateVendorRunRequest(request: Request, env: Env): FROM app.vendor_run_identity_bindings b JOIN app.job_runs j ON j.tenant_id=b.tenant_id AND j.id=b.run_id JOIN app.runs r ON r.tenant_id=j.tenant_id AND r.id=j.id - JOIN app.run_credentials c ON c.tenant_id=j.tenant_id AND c.run_id=j.id + JOIN app.run_authorizations c ON c.tenant_id=j.tenant_id AND c.run_id=j.id JOIN app.members m ON m.tenant_id=c.tenant_id AND m.user_id=c.user_id AND m.role='owner' AND m.session_version=c.session_version WHERE b.run_id=$1 AND b.revoked_at IS NULL AND j.state IN ('starting','running','blocked') AND r.state IN ('starting','running','blocked')`, [runId]); diff --git a/packages/api/test/fly-http-guest-transport.test.ts b/packages/api/test/fly-http-guest-transport.test.ts new file mode 100644 index 00000000..41bace82 --- /dev/null +++ b/packages/api/test/fly-http-guest-transport.test.ts @@ -0,0 +1,43 @@ +import { describe, expect, it } from "vitest"; +import { createFlyHttpGuestTransport } from "../src/fly-http-guest-transport"; + +const options = {app: "selected-app", machine: "machine-1", token: "server-held-token"}; +describe("Worker-compatible Fly guest exec transport", () => { + it("uses argv and stdin through the documented HTTP API without a CLI", async () => { + const command = ["printf", "%s", "$(do-not-run) ' literal"]; + const guest = createFlyHttpGuestTransport({...options, fetcher: async (input, init) => { + expect(String(input)).toBe("https://api.machines.dev/v1/apps/selected-app/machines/machine-1/exec"); + expect(init?.headers).toMatchObject({Authorization: "Bearer server-held-token"}); + expect(JSON.parse(String(init?.body))).toEqual({command, stdin: "job input", timeout: 30}); + expect(init?.redirect).toBe("error"); + return Response.json({stdout: "output", stderr: "failure", exit_code: 7}); + }}); + expect(await guest.run(command, "job input")).toEqual({ok: false, exitCode: 7, stdout: "output", stderr: "failure"}); + }); + + it("transports file bytes without interpolating a guest filename into shell text", async () => { + const bytes = new Uint8Array([0, 128, 255, 42]); + let commands = 0; + const guest = createFlyHttpGuestTransport({...options, fetcher: async (_input, init) => { + const request = JSON.parse(String(init?.body)); + if (++commands === 1) { + expect(request.command).toEqual(["/bin/sh", "-c", 'umask 077; base64 -d > "$1"', "factorize-upload", "/tmp/literal ' $(file)"]); + expect(request.stdin).toBe(Buffer.from(bytes).toString("base64")); + return Response.json({stdout: "", stderr: "", exit_code: 0}); + } + expect(request.command[0]).toBe("python3"); + expect(request.command[3]).toBe("/tmp/file"); + return Response.json({stdout: Buffer.from(bytes).toString("base64"), stderr: "", exit_code: 0}); + }}); + await guest.upload("/tmp/literal ' $(file)", bytes); + expect(await guest.download("/tmp/file")).toEqual(bytes); + await expect(guest.upload("/tmp/../escape", bytes)).rejects.toThrow("path"); + }); + + it("bounds output and sanitizes provider failures", async () => { + for (const response of [Response.json({stdout: "too-large", stderr: "", exit_code: 0}), Response.json({error: "server-held-token"}, {status: 403}), Response.json({stdout: "", stderr: ""})]) { + const guest = createFlyHttpGuestTransport({...options, outputLimitBytes: 2, fetcher: async () => response}); + await expect(guest.run(["echo", "not-logged"])).rejects.toThrow("Fly guest HTTP transport unavailable"); + } + }); +}); diff --git a/packages/api/test/vendor-run-auth.postgres.test.ts b/packages/api/test/vendor-run-auth.postgres.test.ts index 3851c4ac..5abc056b 100644 --- a/packages/api/test/vendor-run-auth.postgres.test.ts +++ b/packages/api/test/vendor-run-auth.postgres.test.ts @@ -2,7 +2,7 @@ import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } import { loadingFixture } from "./helpers/loading-fixture"; import { VendorRunIdentityRepository } from "../src/postgres/vendor-run-identity-repository"; import { FlyConnectionRepository } from "../src/postgres/fly-connection-repository"; -import { issueRunCredential } from "../src/run-credentials"; +import { snapshotRunAuthorization } from "../src/run-authorizations"; import { authenticateVendorRunRequest } from "../src/vendor-run-auth"; import { exeWifIntegrationNameFor, vmNameFor } from "../src/exe-vm-backend"; import { EncryptedIntegrationRepository } from "../src/postgres/encrypted-integration-repository"; @@ -41,7 +41,8 @@ describe.skipIf(!url)("vendor identity request admission (PostgreSQL and Worker await new FlyConnectionRepository(f.db, f.tenantId, f.env.CREDENTIAL_ENCRYPTION_KEY).save({organizationSlug: "connected-org", organizationName: "A different display name"}, "fixture-token"); await f.db.pool.query("DELETE FROM app.vendor_run_identity_bindings WHERE tenant_id=$1 AND run_id=$2", [f.tenantId, f.runId]); await new VendorRunIdentityRepository(f.db).persistVerified({tenantId: f.tenantId, issuedAt: now - 5, identity: {provider: "fly.io", issuer, subject, audience: `factorize://runs/${f.runId}`, runId: f.runId, vmId: machineId, issuedAt: now - 5, expiresAt: now + 600, keyId: "test-key"}}); - await issueRunCredential(f.env, f.tenantId, f.runId, ["runs:read"]); + await f.db.pool.query("DELETE FROM app.run_authorizations WHERE tenant_id=$1 AND run_id=$2", [f.tenantId, f.runId]); + await snapshotRunAuthorization(f.db, {tenantId: f.tenantId, runId: f.runId, scopes: ["runs:read"]}); jwt = await sign(); vi.stubGlobal("fetch", vi.fn(async (input: RequestInfo | URL) => { if (String(input) === `${issuer}/.well-known/openid-configuration`) return Response.json({issuer, jwks_uri: `${issuer}/.well-known/jwks`}); @@ -60,8 +61,9 @@ describe.skipIf(!url)("vendor identity request admission (PostgreSQL and Worker expect(await response.json()).toMatchObject({authMethod: "vendor_identity", scopes: ["runs:read"], runId: f.runId}); expect((await worker.fetch(request(jwt, f.runId, "/api/v1/jobs"), f.env, {waitUntil() {}} as any)).status).toBe(403); await f.db.pool.query("UPDATE app.jobs SET run_scopes='[\"jobs:write\",\"jobs:read\"]' WHERE tenant_id=$1 AND id=$2", [f.tenantId, f.jobIds[0]]); + await snapshotRunAuthorization(f.db, {tenantId: f.tenantId, runId: f.runId, scopes: ["jobs:read", "jobs:write"]}); expect((await authenticateVendorRunRequest(request(), f.env))?.scopes).toEqual(["runs:read"]); - await f.db.pool.query("UPDATE app.run_credentials SET scopes='[]' WHERE tenant_id=$1 AND run_id=$2", [f.tenantId, f.runId]); + await f.db.pool.query("UPDATE app.run_authorizations SET scopes='[]' WHERE tenant_id=$1 AND run_id=$2", [f.tenantId, f.runId]); expect((await authenticateVendorRunRequest(request(), f.env))?.scopes).toEqual([]); }); @@ -78,7 +80,7 @@ describe.skipIf(!url)("vendor identity request admission (PostgreSQL and Worker }); it("requires explicit destination permission and prevents a run from granting itself permission", async () => { - await f.db.pool.query("UPDATE app.run_credentials SET scopes='[\"runs:invoke\",\"jobs:write\"]' WHERE tenant_id=$1 AND run_id=$2", [f.tenantId, f.runId]); + await f.db.pool.query("UPDATE app.run_authorizations SET scopes='[\"runs:invoke\",\"jobs:write\"]' WHERE tenant_id=$1 AND run_id=$2", [f.tenantId, f.runId]); const invoke = () => worker.fetch(new Request(request(jwt, f.runId, `/api/v1/jobs/${f.jobIds[1]}/invocations`), { method: "POST", headers: {Authorization: `Bearer ${jwt}`, "X-Factorize-Run-Id": f.runId, "Content-Type": "application/json"}, body: JSON.stringify({prompt: "selected destination", idempotencyKey: "vendor-run-test"}), }), f.env, {waitUntil() {}} as any); From 78b6da4bd48fd2422dee84c3de2f745317b35d02 Mon Sep 17 00:00:00 2001 From: "exe.dev user" Date: Tue, 17 Nov 2026 15:42:26 +0000 Subject: [PATCH 23/28] Launch run identity helpers and retire legacy HTTP admission paths --- docs/gen-2922-progress.md | 20 +++++ packages/api-client/src/schema.d.ts | 2 +- packages/api/src/access-tokens.ts | 5 +- packages/api/src/api-contract.ts | 2 +- packages/api/src/exe-vm-backend.ts | 29 +++++-- packages/api/src/exe-vm-isolation.ts | 27 +++++++ packages/api/src/execution.ts | 4 +- packages/api/src/fly-machines-client.ts | 35 ++++++-- packages/api/src/guest-artifact-commands.ts | 8 ++ .../api/src/machine-job-execution-backend.ts | 48 +++++++---- .../api/src/postgres/run-query-repository.ts | 8 +- packages/api/src/postgres/run-repository.ts | 4 +- packages/api/src/postgres/run-scheduler.ts | 51 ++++-------- packages/api/src/public-address.ts | 9 +++ packages/api/src/run-artifact-target.ts | 8 ++ packages/api/src/run-credential-launch.ts | 35 ++++++++ packages/api/src/run-identity-guest-helper.ts | 2 + packages/api/src/run-instructions.ts | 8 ++ packages/api/src/run-outbound-proxy.ts | 13 +-- packages/api/src/vendor-run-auth.ts | 9 ++- packages/api/src/worker.ts | 23 +++--- packages/api/test/execution-backend.test.ts | 20 +++-- .../test/fly-job-execution-backend.test.ts | 25 +++++- packages/api/test/fly-machines-client.test.ts | 5 +- .../run-credential-repair.postgres.test.ts | 48 +++++++++++ .../test/run-proxy-launch.postgres.test.ts | 79 ------------------- ...unch.test.ts => run-vendor-launch.test.ts} | 42 +++++----- .../api/test/vendor-run-auth.postgres.test.ts | 25 ++++++ packages/docs/openapi.yaml | 2 +- 29 files changed, 390 insertions(+), 206 deletions(-) create mode 100644 packages/api/src/exe-vm-isolation.ts create mode 100644 packages/api/src/guest-artifact-commands.ts create mode 100644 packages/api/src/run-artifact-target.ts create mode 100644 packages/api/src/run-credential-launch.ts create mode 100644 packages/api/src/run-instructions.ts create mode 100644 packages/api/test/run-credential-repair.postgres.test.ts delete mode 100644 packages/api/test/run-proxy-launch.postgres.test.ts rename packages/api/test/{run-proxy-launch.test.ts => run-vendor-launch.test.ts} (56%) diff --git a/docs/gen-2922-progress.md b/docs/gen-2922-progress.md index d3809fb0..30c61904 100644 --- a/docs/gen-2922-progress.md +++ b/docs/gen-2922-progress.md @@ -106,3 +106,23 @@ Runtime foundations now include token-free immutable run authorization snapshots (independent of legacy bearer rows) and a Worker-compatible Fly guest transport using the documented Machines HTTP exec API with argv/stdin. Focused transport, Fly backend and vendor-request boundary suites pass 29 tests. + +Runtime adoption now uses vendor identity helpers for exe.dev and Fly launches, +with no standalone proxy prerequisite or newly issued run bearer. Fly run +Machines use a tenant run app (no proxy Machine), HTTP guest exec, top-level +region and `skip_launch`. The backend records the verified Machine handle +before guest requests begin. Native exe.dev shared Factorize integrations are +rejected at launch and rechecked during identity renewal. + +Artifact/trace HTTP ingress now requires both vendor identity and a matching +signed upload grant. Stopping runs can finish only that separately authorized +finalization protocol; normal API and outbound access stop immediately. Terminal +runs cannot upload. Guest uploads go through the identity helper, including +streamed Fly artifact/trace collection. + +Focused runtime, protocol, API boundary and repairability suites pass 83 tests. +The previous full-suite run at `f1aaa50` failed five obsolete launch-unit mocks +that expected the old proxy gate/token schema; those tests are now replaced by +vendor launch assertions. Final complete validation is pending old architecture +removal and E2E adaptation. Old implementation files/API/UI still require removal; +the old Worker run-bearer and proxy-control HTTP admission paths are disabled. diff --git a/packages/api-client/src/schema.d.ts b/packages/api-client/src/schema.d.ts index a38df30c..b3c582d7 100644 --- a/packages/api-client/src/schema.d.ts +++ b/packages/api-client/src/schema.d.ts @@ -2197,7 +2197,7 @@ export interface paths { put?: never; /** * Manually retry a blocked launch - * @description Retries only a pre-launch proxy-gated run after its prerequisites have been resolved. The run remains blocked until an interactive owner explicitly retries it; unlock or status changes do not automatically launch it. + * @description Retries a blocked launch with its original immutable credential and API scope snapshot. Job edits affect future runs; revoked/deleted selections require job repair and a new run. An interactive owner must request this retry. * * Requires the runs:cancel scope. * diff --git a/packages/api/src/access-tokens.ts b/packages/api/src/access-tokens.ts index 6dfe2c12..ca549c7d 100644 --- a/packages/api/src/access-tokens.ts +++ b/packages/api/src/access-tokens.ts @@ -37,7 +37,10 @@ export function issueAccessToken(tenantId: string): string { export function accessTokenTenant(token: string): string | null { const match = token.match(/^fzt_([A-Za-z0-9_-]+)_[A-Za-z0-9_-]{43}$/); if (!match) return null; - try { return decode(match[1]); } catch { return null; } + try { + const tenantId = decode(match[1]); + return /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(tenantId) ? tenantId : null; + } catch { return null; } } export async function authenticateAccessToken(request: Request, env: Env): Promise { diff --git a/packages/api/src/api-contract.ts b/packages/api/src/api-contract.ts index 4e57b3b6..a1f82245 100644 --- a/packages/api/src/api-contract.ts +++ b/packages/api/src/api-contract.ts @@ -1148,7 +1148,7 @@ export const API_ROUTES: RouteContract[] = [ ), route("POST", "/api/v1/runs/{runId}/retry-launch", "runs:cancel", { summary: "Manually retry a blocked launch", - description: "Retries only a pre-launch proxy-gated run after its prerequisites have been resolved. The run remains blocked until an interactive owner explicitly retries it; unlock or status changes do not automatically launch it.", + description: "Retries a blocked launch with its original immutable credential and API scope snapshot. Job edits affect future runs; revoked/deleted selections require job repair and a new run. An interactive owner must request this retry.", responses: { "200": { description: "Manual retry queued", content: { "application/json": { schema: { type: "object", required: ["runId", "retryRequested"], properties: { runId: { type: "string", format: "uuid" }, retryRequested: { type: "boolean", const: true } }, additionalProperties: false } } } }, "403": { description: "Interactive owner session required" }, diff --git a/packages/api/src/exe-vm-backend.ts b/packages/api/src/exe-vm-backend.ts index bbb5484b..5af2efab 100644 --- a/packages/api/src/exe-vm-backend.ts +++ b/packages/api/src/exe-vm-backend.ts @@ -5,6 +5,10 @@ import { base64 } from "./crypto"; import { shellAtom, type ExeConnection, type ExeRunConnection } from "./exe"; import { HARNESS_LOG_LIMIT, safeDiagnosticText } from "./harness-diagnostics"; +import { traceChunkCommand } from "./guest-artifact-commands"; +import { runArtifactTarget } from "./run-artifact-target"; +import { assertExeVmIsolation } from "./exe-vm-isolation"; +import { RUN_IDENTITY_GUEST_HELPER } from "./run-identity-guest-helper"; import { ExeRunProxy } from "./exe-run-proxy"; import { runProxyName } from "./run-credentials"; import { FACTORIZE_JOB_LAUNCHER } from "./factorize-job-launcher"; @@ -216,6 +220,12 @@ export class ExeVmBackend implements ExecutionBackend { handle.vendorIdentityIntegrationName ??= exeWifIntegrationNameFor(request.runId); } const vm = this.vm(handle); + if (request.runIdentity) { + if (!(request.verifyVendorIdentity ?? this.vendorIdentityVerifier)) throw new Error("Vendor identity verification is required for run access"); + handle.identityProxyOrigin = request.runIdentity.backendOrigin; + delete handle.runProxyName; + await assertExeVmIsolation({execute: command => this.api(command), vm, backendOrigin: request.runIdentity.backendOrigin, tags: this.connection.tags ?? []}); + } let proxy: ExeRunProxy | undefined, plan: Awaited> | undefined; if (request.runProxy) { try { @@ -264,15 +274,24 @@ export class ExeVmBackend implements ExecutionBackend { const code = request.code, output = request.traceSources?.primary.formatVersion === "codex-exec-jsonl" ? request.traceSources.primary.path : "/tmp/factorize.log", unit = vm; const launchPayload = JSON.stringify({ version: 1, runId: request.runId, ...(code ? { code } : { prompt: request.prompt, harness: request.harness }), ...(request.traceSources ? { traceSources: request.traceSources } : {}) }); const launchPayloadPath = "/home/exedev/.factorize-job/launch.json"; + const identitySetup = request.runIdentity ? [ + "command -v node >/dev/null && command -v curl >/dev/null", + "sudo install -d -m 0700 /run/factorize-identity", + `printf '%s' ${shellAtom(base64(RUN_IDENTITY_GUEST_HELPER))} | sudo sh -c 'base64 -d > /run/factorize-identity/proxy.mjs'`, + `printf '%s' ${shellAtom(base64(JSON.stringify({runId: request.runId, backendOrigin: request.runIdentity.backendOrigin, provider: "exe.dev", integrationName: exeWifIntegrationNameFor(request.runId), localPort: 18180})))} | sudo sh -c 'base64 -d > /run/factorize-identity/config.json'`, + `if [ "$(sudo systemctl show ${shellAtom(`factorize-identity-${request.runId}`)} --property=LoadState --value 2>/dev/null || true)" != loaded ]; then sudo systemd-run --quiet --unit=${shellAtom(`factorize-identity-${request.runId}`)} --property=Type=exec --property=Restart=on-failure node /run/factorize-identity/proxy.mjs; else sudo systemctl start ${shellAtom(`factorize-identity-${request.runId}`)}; fi`, + "n=0; until curl --fail --silent http://127.0.0.1:18180/_factorize/ready >/dev/null; do n=$((n+1)); test $n -lt 50 || exit 1; sleep 0.1; done", + ] : []; const work = [ "set -eu", "mkdir -p /home/exedev/workspace", "cd /home/exedev/workspace", + ...identitySetup, ...(request.traceSources?.primary.kind === "execution_stream" ? [`mkdir -p -- ${shellAtom(request.traceSources.primary.path.slice(0, request.traceSources.primary.path.lastIndexOf("/")) || "/")}`, `touch -- ${shellAtom(request.traceSources.primary.path)}`] : []), "sudo install -d -o exedev -g exedev -m 0700 /home/exedev/.factorize-job", `printf '%s' ${shellAtom(base64(FACTORIZE_JOB_LAUNCHER))} | sudo sh -c ${shellAtom("base64 -d > /usr/local/bin/factorize-job && chmod 0755 /usr/local/bin/factorize-job")}`, `printf '%s' ${shellAtom(base64(launchPayload))} | base64 -d > ${shellAtom(launchPayloadPath)} && sudo chown exedev:exedev ${shellAtom(launchPayloadPath)}`, - `if [ "$(sudo systemctl show ${shellAtom(unit)} --property=LoadState --value 2>/dev/null || true)" != loaded ]; then sudo systemd-run --quiet --uid=exedev --gid=exedev --unit=${shellAtom(unit)} --property=Type=exec --property=RemainAfterExit=yes --property=WorkingDirectory=/home/exedev/workspace --property=StandardInput=null --property=StandardOutput=${output === "/tmp/factorize.log" ? `append:${output}` : shellAtom(`append:${output}`)} --property=StandardError=append:/tmp/factorize.stderr /bin/sh -c ${shellAtom(`exec /usr/local/bin/factorize-job launch --foreground < ${launchPayloadPath}`)}; fi`, + `if [ "$(sudo systemctl show ${shellAtom(unit)} --property=LoadState --value 2>/dev/null || true)" != loaded ]; then sudo systemd-run --quiet --uid=exedev --gid=exedev --unit=${shellAtom(unit)} --property=Type=exec --property=RemainAfterExit=yes --property=WorkingDirectory=/home/exedev/workspace --property=StandardInput=null --property=StandardOutput=${output === "/tmp/factorize.log" ? `append:${output}` : shellAtom(`append:${output}`)} --property=StandardError=append:/tmp/factorize.stderr /bin/sh -c ${shellAtom(`exec ${request.runIdentity ? "/usr/bin/env FACTORIZE_PROXY_URL=http://127.0.0.1:18180 " : ""}/usr/local/bin/factorize-job launch --foreground < ${launchPayloadPath}`)}; fi`, "echo started", ].join("; "); if (request.traceSources?.primary.formatVersion === "codex-exec-jsonl") { @@ -293,6 +312,7 @@ export class ExeVmBackend implements ExecutionBackend { const vm = this.vm(handle); if (handle.operationId && handle.vendorIdentityIntegrationName && this.vendorIdentityVerifier) { try { + if (handle.identityProxyOrigin) await assertExeVmIsolation({execute: command => this.api(command), vm, backendOrigin: handle.identityProxyOrigin, tags: this.connection.tags ?? []}); const integration = await this.ensureExeWif(vm, handle.operationId, false); if (integration.integrationName !== handle.vendorIdentityIntegrationName) throw new Error("WIF integration changed"); const token = await this.exeWifToken(vm, handle.vendorIdentityIntegrationName); @@ -378,20 +398,19 @@ export class ExeVmBackend implements ExecutionBackend { async collectJobFile(handle: RunHandle, request: JobFileCollectionRequest) { const file = `/home/exedev/.factorize-job/${request.path}`; - const remote = `set -eu; file=${shellAtom(file)}; test -f "$file"; test ! -L "$file"; real=$(realpath -- "$file"); case "$real" in /home/exedev/.factorize-job/*) ;; *) exit 41;; esac; size=$(wc -c < "$file" | tr -d ' '); test "$size" -le 10485760; sha=$(sha256sum "$file" | cut -d' ' -f1); curl --fail --silent --show-error -X PUT -H 'Content-Type: application/octet-stream' -H "Content-Length: $size" -H "X-Artifact-SHA256: $sha" --data-binary @"$file" ${shellAtom(request.uploadUrl)}`; + const remote = `set -eu; file=${shellAtom(file)}; test -f "$file"; test ! -L "$file"; real=$(realpath -- "$file"); case "$real" in /home/exedev/.factorize-job/*) ;; *) exit 41;; esac; size=$(wc -c < "$file" | tr -d ' '); test "$size" -le 10485760; sha=$(sha256sum "$file" | cut -d' ' -f1); curl --fail --silent --show-error -X PUT -H 'Content-Type: application/octet-stream' -H "Content-Length: $size" -H "X-Artifact-SHA256: $sha" --data-binary @"$file" ${shellAtom(runArtifactTarget(handle, request.uploadUrl))}`; const result = await this.api(`ssh ${shellAtom(this.vm(handle))} ${shellAtom(remote)}`); return { ok: result.ok, detail: result.ok ? undefined : `Job file upload failed (${result.status})`, command: result }; } async collectArtifact(handle: RunHandle, request: ArtifactCollectionRequest) { - const remote = `set -eu; file=$(${request.source ? sourceCommand(request.source) : request.discoverCommand}); test -n "$file"; test -f "$file"; snapshot=$(mktemp); trap 'rm -f "$snapshot"' EXIT; cp "$file" "$snapshot"; size=$(wc -c < "$snapshot" | tr -d ' '); sha=$(sha256sum "$snapshot" | cut -d' ' -f1); curl --fail --silent --show-error -X PUT -H ${shellAtom(`Content-Type: ${request.contentType}`)} -H "Content-Length: $size" -H "X-Artifact-SHA256: $sha" --data-binary @"$snapshot" ${shellAtom(request.uploadUrl)}`; + const remote = `set -eu; file=$(${request.source ? sourceCommand(request.source) : request.discoverCommand}); test -n "$file"; test -f "$file"; snapshot=$(mktemp); trap 'rm -f "$snapshot"' EXIT; cp "$file" "$snapshot"; size=$(wc -c < "$snapshot" | tr -d ' '); sha=$(sha256sum "$snapshot" | cut -d' ' -f1); curl --fail --silent --show-error -X PUT -H ${shellAtom(`Content-Type: ${request.contentType}`)} -H "Content-Length: $size" -H "X-Artifact-SHA256: $sha" --data-binary @"$snapshot" ${shellAtom(runArtifactTarget(handle, request.uploadUrl))}`; const result = await this.api(`ssh ${shellAtom(this.vm(handle))} ${shellAtom(remote)}`); return { ok: result.ok, detail: result.ok ? undefined : `Artifact upload failed (${result.status}): ${result.body.slice(0, 300)}`, command: result }; } async collectTraceChunk(handle: RunHandle, request: TraceChunkCollectionRequest) { - const expectedGeneration = request.generation ?? "", zeroHash = "0".repeat(64); - const remote = `set -eu; file=$(${request.source ? sourceCommand(request.source) : request.discoverCommand}); test -n "$file"; test -f "$file"; exec 3<"$file"; file=/proc/$$/fd/3; identity=$(stat -Lc '%d:%i:%W' "$file"); generation="$identity"; case ${shellAtom(expectedGeneration)} in "$identity":*) generation=${shellAtom(expectedGeneration)};; esac; start=${request.offset}; previous=${shellAtom(request.previousHash)}; if [ -n ${shellAtom(expectedGeneration)} ] && [ "$generation" != ${shellAtom(expectedGeneration)} ]; then start=0; previous=${shellAtom(zeroHash)}; fi; total=$(wc -c < "$file" | tr -d ' '); if [ "$total" -lt "$start" ]; then generation="$identity:$(date +%s%N)"; start=0; previous=${shellAtom(zeroHash)}; fi; if [ "$total" -le "$start" ]; then printf 'no-change'; exit 0; fi; count=$((total-start)); if [ "$count" -gt 4194304 ]; then count=4194304; fi; chunk=$(mktemp); trap 'rm -f "$chunk"' EXIT; dd if="$file" of="$chunk" iflag=skip_bytes,count_bytes skip="$start" count="$count" status=none; size=$(wc -c < "$chunk" | tr -d ' '); sha=$(sha256sum "$chunk" | cut -d' ' -f1); curl --fail --silent --show-error -X PUT -H "Content-Length: $size" -H "X-Trace-Generation: $generation" -H ${shellAtom(`X-Trace-Expected-Generation: ${expectedGeneration}`)} -H "X-Trace-Start: $start" -H "X-Trace-SHA256: $sha" -H "X-Trace-Previous-Hash: $previous" --data-binary @"$chunk" ${shellAtom(request.uploadUrl)}`; + const remote = traceChunkCommand(request, runArtifactTarget(handle, request.uploadUrl)); const result = await this.api(`ssh ${shellAtom(this.vm(handle))} ${shellAtom(remote)}`); return { ok: result.ok, detail: result.ok ? undefined : `Live trace upload failed (${result.status}): ${result.body.slice(0, 300)}`, command: result }; } diff --git a/packages/api/src/exe-vm-isolation.ts b/packages/api/src/exe-vm-isolation.ts new file mode 100644 index 00000000..6c9f89b8 --- /dev/null +++ b/packages/api/src/exe-vm-isolation.ts @@ -0,0 +1,27 @@ +import type { BackendCommandResult } from "./execution"; + +type Integration = {name?: string; type?: string; target?: string; attachments?: unknown[]}; +/** Reject any native Factorize bearer proxy available at boot. Only the + * vendor-authenticated local helper may grant a run Factorize API access. */ +export async function assertExeVmIsolation(input: {execute: (command: string) => Promise; vm: string; backendOrigin: string; tags: string[]}): Promise { + const response = await input.execute("integrations list --json"); + if (!response.ok) throw new Error("exe.dev integration isolation inventory unavailable"); + let inventory: unknown; + try { inventory = JSON.parse(response.body); } catch { throw new Error("exe.dev integration isolation inventory invalid"); } + const integrations: Integration[] = Array.isArray(inventory) ? inventory : (inventory as {integrations: Integration[]})?.integrations; + if (!Array.isArray(integrations)) throw new Error("exe.dev integration isolation inventory invalid"); + for (const integration of integrations) { + if (integration.type !== "http-proxy") continue; + let target: URL; + try { target = new URL(integration.target ?? ""); } catch { throw new Error("exe.dev integration target unavailable for isolation check"); } + if (target.origin !== input.backendOrigin) continue; + if (!Array.isArray(integration.attachments)) throw new Error("exe.dev Factorize attachment inventory unavailable"); + for (const entry of integration.attachments) { + if (typeof entry !== "string") throw new Error("exe.dev Factorize attachment inventory invalid"); + const match = /^(.*?)(?:@(.+))?$/.exec(entry)!; + const spec = match[1]!; + if (match[2]) { const expiry = Date.parse(match[2]); if (!Number.isFinite(expiry)) throw new Error("exe.dev attachment expiry invalid"); if (expiry <= Date.now()) continue; } + if (spec === "auto:all" || spec === `vm:${input.vm}` || input.tags.some(tag => spec === `tag:${tag}`)) throw new Error("A shared Factorize integration is attached to this execution VM. Restrict its attachments before retrying."); + } + } +} diff --git a/packages/api/src/execution.ts b/packages/api/src/execution.ts index 954f3b15..53175de3 100644 --- a/packages/api/src/execution.ts +++ b/packages/api/src/execution.ts @@ -18,6 +18,8 @@ export interface LaunchRequest { prompt: string; /** Control-plane only: provisioned into an exe.dev proxy, never the guest. */ runProxy?: { targetOrigin: string; credential: string }; + /** Public backend configuration only; requests must use fresh vendor identity. */ + runIdentity?: { backendOrigin: string }; traceSources?: TraceSources; harness?: { executable: string; args: string[]; env: Record }; code?: { script: string; context: Record }; @@ -26,7 +28,7 @@ export interface LaunchRequest { } /** Opaque to orchestration. Only the backend that created it may interpret id. */ -export interface RunHandle { backendKind: string; id: string; runProxyName?: string; /** Stable provider operation key retained across a scheduler restart. */ operationId?: string; vendorIdentityIntegrationName?: string; } +export interface RunHandle { identityProxyOrigin?: string; backendKind: string; id: string; runProxyName?: string; /** Stable provider operation key retained across a scheduler restart. */ operationId?: string; vendorIdentityIntegrationName?: string; } export interface ExecutionObservation { systemd?: import("./harness-diagnostics").ExecutionDiagnostics["systemd"]; diff --git a/packages/api/src/fly-machines-client.ts b/packages/api/src/fly-machines-client.ts index 58fe5687..60e22db9 100644 --- a/packages/api/src/fly-machines-client.ts +++ b/packages/api/src/fly-machines-client.ts @@ -123,12 +123,33 @@ export function createFlyMachinesClient(options: FlyMachinesClientOptions) { const machinePath = (app: string, machine: string) => `${appPath(app)}/machines/${segment(machine, "machine id")}`; async function findByOperationId(app: string, operationId: string): Promise { - const machines = await request(`${appPath(app)}/machines`, { method: "GET" }, true); + let machines: FlyMachine[]; + try { machines = await request(`${appPath(app)}/machines`, { method: "GET" }, true); } + catch (error) { if (error instanceof FlyClientError && error.status === 404) return undefined; throw error; } if (!Array.isArray(machines)) throw new FlyClientError("Fly returned an invalid Machine list", "invalid_response"); - return machines.find((machine) => machine.config?.metadata?.[OPERATION_METADATA_KEY] === operationId); + const matches = machines.filter(machine => machine.config?.metadata?.[OPERATION_METADATA_KEY] === operationId); + if (matches.length > 1) throw new FlyClientError("Fly operation matches multiple Machines", "invalid_response"); + return matches[0]; } return { + /** Run apps contain execution Machines only, with a distinct private network. + * Never infer ownership from a globally unique app name alone. */ + async ensureRunApp(app: string, organizationSlug: string): Promise { + if (!/^[a-z0-9-]{1,63}$/.test(app) || !/^[a-z0-9-]{1,63}$/.test(organizationSlug)) throw new TypeError("Invalid Fly run app identity"); + const read = () => request<{name?: string; organization?: {slug?: string}}>(appPath(app), {method: "GET"}, true); + let current; + try { current = await read(); } + catch (error) { + if (!(error instanceof FlyClientError) || error.status !== 404) throw error; + try { await request("/apps", {method: "POST", headers: {"content-type": "application/json"}, body: JSON.stringify({app_name: app, org_slug: organizationSlug, network: app})}, false); } + catch (createError) { + if (!(createError instanceof FlyClientError) || !(["network", "timeout", "server"].includes(createError.kind) || createError.status === 409)) throw createError; + } + current = await read(); + } + if (current.name !== app || current.organization?.slug !== organizationSlug) throw new FlyClientError("Fly run app organization does not match", "invalid_response"); + }, /** Resolve a previously persisted provisional run handle after a scheduler restart. */ findMachineByOperationId(app: string, operationId: string): Promise { if (!operationId || operationId.length > 200) throw new TypeError("operationId must contain 1 to 200 characters"); @@ -138,9 +159,12 @@ export function createFlyMachinesClient(options: FlyMachinesClientOptions) { if (!operationId || operationId.length > 200) throw new TypeError("operationId must contain 1 to 200 characters"); const existing = await findByOperationId(app, operationId); if (existing) return existing; + const {region, ...machineConfig} = config; const body = { + ...(typeof region === "string" ? {region} : {}), + skip_launch: true, config: { - ...config, + ...machineConfig, // Job Machines are supervised by Factorize. A provider restart can // replay a script after an ambiguous guest exit, duplicating side // effects, so execution guests must stop with their process. @@ -171,8 +195,9 @@ export function createFlyMachinesClient(options: FlyMachinesClientOptions) { throw new FlyClientError("Fly Machine creation outcome is ambiguous; retry with the same operationId", "ambiguous_create", undefined, { cause }); } }, - inspectMachine(app: string, machine: string): Promise { - return request(machinePath(app, machine), { method: "GET" }, true); + async inspectMachine(app: string, machine: string): Promise { + try { return await request(machinePath(app, machine), { method: "GET" }, true); } + catch (error) { if (error instanceof FlyClientError && error.status === 404) return {id: machine, state: "destroyed"}; throw error; } }, startMachine(app: string, machine: string): Promise { return request(`${machinePath(app, machine)}/start`, { method: "POST" }, false); diff --git a/packages/api/src/guest-artifact-commands.ts b/packages/api/src/guest-artifact-commands.ts new file mode 100644 index 00000000..5deb421a --- /dev/null +++ b/packages/api/src/guest-artifact-commands.ts @@ -0,0 +1,8 @@ +import { shellAtom } from "./exe"; +import { sourceCommand } from "./trace-source"; +import type { TraceChunkCollectionRequest } from "./execution"; + +export function traceChunkCommand(request: TraceChunkCollectionRequest, uploadTarget: string): string { + const expectedGeneration = request.generation ?? "", zeroHash = "0".repeat(64); + return `set -eu; file=$(${request.source ? sourceCommand(request.source) : request.discoverCommand}); test -n "$file"; test -f "$file"; exec 3<"$file"; file=/proc/$$/fd/3; identity=$(stat -Lc '%d:%i:%W' "$file"); generation="$identity"; case ${shellAtom(expectedGeneration)} in "$identity":*) generation=${shellAtom(expectedGeneration)};; esac; start=${request.offset}; previous=${shellAtom(request.previousHash)}; if [ -n ${shellAtom(expectedGeneration)} ] && [ "$generation" != ${shellAtom(expectedGeneration)} ]; then start=0; previous=${shellAtom(zeroHash)}; fi; total=$(wc -c < "$file" | tr -d ' '); if [ "$total" -lt "$start" ]; then generation="$identity:$(date +%s%N)"; start=0; previous=${shellAtom(zeroHash)}; fi; if [ "$total" -le "$start" ]; then printf 'no-change'; exit 0; fi; count=$((total-start)); if [ "$count" -gt 4194304 ]; then count=4194304; fi; chunk=$(mktemp); trap 'rm -f "$chunk"' EXIT; dd if="$file" of="$chunk" iflag=skip_bytes,count_bytes skip="$start" count="$count" status=none; size=$(wc -c < "$chunk" | tr -d ' '); sha=$(sha256sum "$chunk" | cut -d' ' -f1); curl --fail --silent --show-error -X PUT -H "Content-Length: $size" -H "X-Trace-Generation: $generation" -H ${shellAtom(`X-Trace-Expected-Generation: ${expectedGeneration}`)} -H "X-Trace-Start: $start" -H "X-Trace-SHA256: $sha" -H "X-Trace-Previous-Hash: $previous" --data-binary @"$chunk" ${shellAtom(uploadTarget)}`; +} diff --git a/packages/api/src/machine-job-execution-backend.ts b/packages/api/src/machine-job-execution-backend.ts index 5e5e71cf..d35bfdb4 100644 --- a/packages/api/src/machine-job-execution-backend.ts +++ b/packages/api/src/machine-job-execution-backend.ts @@ -1,12 +1,15 @@ import type { ExecutionBackend, ExecutionObservation, LaunchReceipt, LaunchRequest, RunHandle } from "./execution"; export type JobMachine = { id: string; name?: string; state?: string; config?: { metadata?: Record } }; export type JobMachineConfig = Record & { metadata?: Record }; -import { createHash } from "node:crypto"; import { safeDiagnosticText } from "./harness-diagnostics"; -import type { ArtifactCollectionRequest, ArtifactCollector, ExecutionTerminator, HarnessLogReader, JobFileCollectionRequest, JobFileCollector, JobResultReader } from "./execution"; +import type { TraceChunkCollectionRequest, ArtifactCollectionRequest, ArtifactCollector, ExecutionTerminator, HarnessLogReader, JobFileCollectionRequest, JobFileCollector, JobResultReader } from "./execution"; import { sourceCommand } from "./trace-source"; import { FACTORIZE_JOB_LAUNCHER } from "./factorize-job-launcher"; import { FACTORIZE_FLY_TUNNEL_HELPER } from "./fly-job-tunnel-helper"; +import { traceChunkCommand } from "./guest-artifact-commands"; +import { runArtifactTarget } from "./run-artifact-target"; +import { shellAtom } from "./exe"; +import { RUN_IDENTITY_GUEST_HELPER } from "./run-identity-guest-helper"; import { acquireFlyMachineOidcToken } from "./vendor-run-token-sources"; const SUPPORTED_CODEX_CLI_VERSION = "codex-cli 0.167.1"; @@ -41,6 +44,7 @@ export class MachineJobExecutionBackend implements ExecutionBackend, JobResultRe constructor( private readonly options: { kind: "fly" | "docker"; + prepare?: () => Promise; machineConfig: (request: LaunchRequest) => JobMachineConfig; vmIdentity: (machine: JobMachine) => string; proxyAddress: { host: string; port: number; serverName?: string }; @@ -84,9 +88,11 @@ export class MachineJobExecutionBackend implements ExecutionBackend, JobResultRe const handle = request.reservation ?? this.reserve(request.runId); this.handleParts(handle); const config = this.options.machineConfig(request); + if (request.runIdentity && (this.kind !== "fly" || !(request.verifyVendorIdentity ?? this.options.verifyVendorIdentity))) throw new Error("Vendor identity is required for run access"); + await this.options.prepare?.(); const machine = await this.options.machines.createMachine(this.options.app, config, operationId); if (!machine.id) throw new Error("Fly returned a Machine without an id"); - const actualHandle = { backendKind: this.kind, id: `${this.options.app}/${machine.id}`, operationId }; + const actualHandle = { backendKind: this.kind, id: `${this.options.app}/${machine.id}`, operationId, ...(request.runIdentity ? {identityProxyOrigin: request.runIdentity.backendOrigin} : {}) }; try { if (request.runProxy) { if (!this.options.proxyIdentity || !this.options.proxyBootEpoch || !this.options.proxyGuest?.issueVmCertificate) throw new Error("Fly credential proxy delivery is unavailable"); @@ -107,7 +113,7 @@ export class MachineJobExecutionBackend implements ExecutionBackend, JobResultRe if (this.options.vendorIdentitySubject && !expectedSubject) throw new Error("Fly vendor identity subject is unavailable"); await verifyVendorIdentity({ provider: "fly.io", vmId: machine.id, token, ...(this.options.vendorIdentityIssuer ? { expectedIssuer: this.options.vendorIdentityIssuer } : {}), ...(expectedSubject ? { expectedSubject } : {}) }); } - const tunnelPrerequisites = request.runProxy ? " && command -v node >/dev/null && command -v openssl >/dev/null" : ""; + const tunnelPrerequisites = request.runProxy ? " && command -v node >/dev/null && command -v openssl >/dev/null" : request.runIdentity ? " && command -v node >/dev/null && command -v curl >/dev/null" : ""; const installed = await guest.run(["/bin/sh", "-c", `command -v python3 >/dev/null && command -v runuser >/dev/null${tunnelPrerequisites} && id exedev >/dev/null && mkdir -p /usr/local/bin && install -d -o exedev -g exedev -m 0700 /home/exedev/.factorize-job && cat > /usr/local/bin/factorize-job && chmod 0755 /usr/local/bin/factorize-job`], FACTORIZE_JOB_LAUNCHER); if (!installed.ok) throw new Error(request.runProxy ? "Fly guest is missing python3, runuser, Node.js, OpenSSL, or the exedev user, or could not install the shared Factorize job launcher" @@ -143,8 +149,18 @@ export class MachineJobExecutionBackend implements ExecutionBackend, JobResultRe const startTunnel = await guest.run(["/bin/sh", "-c", `chown exedev:exedev ${directory}/config.json ${directory}/tunnel.mjs && chmod 0600 ${directory}/config.json ${directory}/tunnel.mjs && (nohup /usr/sbin/runuser -u exedev -- /usr/bin/env PATH=/usr/local/bin:/usr/bin:/bin node ${directory}/tunnel.mjs >/tmp/factorize-proxy-tunnel.log 2>&1 /tmp/factorize-proxy-tunnel.pid) && sleep 1 && kill -0 "$(cat /tmp/factorize-proxy-tunnel.pid)"`]); if (!startTunnel.ok) throw new Error("Fly guest could not start its credential proxy tunnel"); } + if (request.runIdentity) { + if (!guest.upload) throw new Error("Fly guest cannot install the vendor identity helper"); + const directory = "/run/factorize-identity"; + const prepared = await guest.run(["/usr/bin/install", "-d", "-m", "0700", directory]); + if (!prepared.ok) throw new Error("Fly guest could not prepare run identity access"); + await guest.upload(`${directory}/proxy.mjs`, new TextEncoder().encode(RUN_IDENTITY_GUEST_HELPER)); + await guest.upload(`${directory}/config.json`, new TextEncoder().encode(JSON.stringify({runId: request.runId, backendOrigin: request.runIdentity.backendOrigin, provider: "fly.io", localPort: 18180}))); + const started = await guest.run(["/bin/sh", "-c", "nohup node /run/factorize-identity/proxy.mjs >/tmp/factorize-identity-proxy.log 2>&1 /run/factorize-identity/pid; n=0; until curl --fail --silent http://127.0.0.1:18180/_factorize/ready >/dev/null; do n=$((n+1)); test $n -lt 50 || exit 1; sleep 0.1; done"]); + if (!started.ok) throw new Error("Fly guest vendor identity helper did not become ready"); + } const payload = JSON.stringify({ version: 1, runId: request.runId, ...(request.code ? { code: request.code } : { prompt: request.prompt, harness: request.harness }), ...(request.traceSources ? { traceSources: request.traceSources } : {}) }); - const launchCommand = request.runProxy + const launchCommand = request.runProxy || request.runIdentity ? ["/usr/sbin/runuser", "-u", "exedev", "--", "/usr/bin/env", "FACTORIZE_PROXY_URL=http://127.0.0.1:18180", "/usr/local/bin/factorize-job", "launch"] : ["/usr/sbin/runuser", "-u", "exedev", "--", "/usr/local/bin/factorize-job", "launch"]; const started = await guest.run(launchCommand, `${payload}\n`); @@ -248,25 +264,23 @@ export class MachineJobExecutionBackend implements ExecutionBackend, JobResultRe } async collectJobFile(handle: RunHandle, request: JobFileCollectionRequest) { - if (request.path.split("/").some(part => !part || part === "." || part === "..") || /[\\\r\n\0]/.test(request.path)) throw new TypeError("Unsafe Fly job output path"); - const bytes = await this.download(handle, `/home/exedev/.factorize-job/${request.path}`); - if (bytes.byteLength > 10 * 1024 * 1024) throw new Error("Fly job output file exceeds the 10 MiB limit"); - return this.upload(request.uploadUrl, bytes, "application/octet-stream"); + const file = `/home/exedev/.factorize-job/${request.path}`; + const command = `set -eu; file=${shellAtom(file)}; test -f "$file"; test ! -L "$file"; real=$(realpath -- "$file"); case "$real" in /home/exedev/.factorize-job/*) ;; *) exit 41;; esac; size=$(wc -c < "$file" | tr -d ' '); test "$size" -le 10485760; sha=$(sha256sum "$file" | cut -d' ' -f1); curl --fail --silent --show-error -X PUT -H 'Content-Type: application/octet-stream' -H "Content-Length: $size" -H "X-Artifact-SHA256: $sha" --data-binary @"$file" ${shellAtom(runArtifactTarget(handle, request.uploadUrl))}`; + const result = await (await this.guestFor(handle)).run(["/bin/sh", "-c", command]); + return {ok: result.ok, detail: result.ok ? undefined : "Fly job file upload failed"}; } async collectArtifact(handle: RunHandle, request: ArtifactCollectionRequest) { - const guest = await this.guestFor(handle); const discover = request.source ? sourceCommand(request.source) : request.discoverCommand; if (!discover) throw new Error("Fly artifact source is unavailable"); - const found = await guest.run(["/bin/sh", "-c", discover]); - if (!found.ok || !found.stdout.trim().startsWith("/")) throw new Error("Fly artifact source could not be resolved"); - return this.upload(request.uploadUrl, await this.download(handle, found.stdout.trim()), request.contentType); + const command = `set -eu; file=$(${discover}); test -n "$file"; test -f "$file"; snapshot=$(mktemp); trap 'rm -f "$snapshot"' EXIT; cp "$file" "$snapshot"; size=$(wc -c < "$snapshot" | tr -d ' '); sha=$(sha256sum "$snapshot" | cut -d' ' -f1); curl --fail --silent --show-error -X PUT -H ${shellAtom(`Content-Type: ${request.contentType}`)} -H "Content-Length: $size" -H "X-Artifact-SHA256: $sha" --data-binary @"$snapshot" ${shellAtom(runArtifactTarget(handle, request.uploadUrl))}`; + const result = await (await this.guestFor(handle)).run(["/bin/sh", "-c", command]); + return {ok: result.ok, detail: result.ok ? undefined : "Fly artifact upload failed"}; } - private async upload(uploadUrl: string, bytes: Uint8Array, contentType: string) { - const sha256 = createHash("sha256").update(bytes).digest("hex"); - const response = await fetch(uploadUrl, { method: "PUT", headers: { "Content-Type": contentType, "Content-Length": String(bytes.byteLength), "X-Artifact-SHA256": sha256 }, body: Buffer.from(bytes) }); - return { ok: response.ok, detail: response.ok ? undefined : `Fly artifact upload failed (${response.status})` }; + async collectTraceChunk(handle: RunHandle, request: TraceChunkCollectionRequest) { + const result = await (await this.guestFor(handle)).run(["/bin/sh", "-c", traceChunkCommand(request, runArtifactTarget(handle, request.uploadUrl))]); + return {ok: result.ok, detail: result.ok ? undefined : "Fly trace chunk upload failed"}; } async stop(handle: RunHandle): Promise { diff --git a/packages/api/src/postgres/run-query-repository.ts b/packages/api/src/postgres/run-query-repository.ts index db31518f..69012032 100644 --- a/packages/api/src/postgres/run-query-repository.ts +++ b/packages/api/src/postgres/run-query-repository.ts @@ -113,9 +113,13 @@ export class RunQueryRepository { async stop(runId: string) { return this.database.transaction(async client => { await client.query("SELECT pg_advisory_xact_lock(hashtextextended($1::text, 0))", [this.tenantId]); - const result = await client.query("UPDATE app.job_runs SET state=CASE WHEN state='reserved' THEN 'stopped' ELSE 'stopping' END,next_poll_at=CASE WHEN state='reserved' THEN NULL ELSE now() END,updated_at=now() WHERE tenant_id=$1 AND id=$2 AND state IN ('reserved','starting','running','blocked','stopping') RETURNING id,state", [this.tenantId, runId]); + const result = await client.query(`UPDATE app.job_runs jr SET state=CASE WHEN jr.state IN ('queued','reserved') OR (jr.state='blocked' AND EXISTS (SELECT 1 FROM app.runs x WHERE x.tenant_id=jr.tenant_id AND x.id=jr.id AND x.execution_handle IS NULL)) THEN 'stopped' ELSE 'stopping' END,next_poll_at=now(),updated_at=now() WHERE jr.tenant_id=$1 AND jr.id=$2 AND jr.state IN ('queued','reserved','starting','running','blocked','stopping') RETURNING id,state`, [this.tenantId, runId]); const row = result.rows[0]; - if (row?.state === "stopped") await client.query("UPDATE app.runs SET state='stopped',claim_released=true,vm_cleanup_complete=true,updated_at=now() WHERE tenant_id=$1 AND id=$2", [this.tenantId, runId]); + if (row?.state === "stopped") { + await client.query("UPDATE app.job_runs SET next_poll_at=NULL WHERE tenant_id=$1 AND id=$2", [this.tenantId, runId]); + await client.query("UPDATE app.runs SET state='stopped',claim_released=true,vm_cleanup_complete=true,updated_at=now() WHERE tenant_id=$1 AND id=$2", [this.tenantId, runId]); + await client.query("DELETE FROM app.active_claims WHERE tenant_id=$1 AND run_id=$2", [this.tenantId, runId]); + } if (row?.state === "stopping") { await client.query("UPDATE app.runs SET state='stopping',updated_at=now() WHERE tenant_id=$1 AND id=$2 AND state IN ('starting','running','blocked','stopping')", [this.tenantId, runId]); await client.query("INSERT INTO app.run_activity(tenant_id,id,run_id,action,detail) SELECT $1,$2,$3,'stop_requested','Stop request accepted' WHERE NOT EXISTS (SELECT 1 FROM app.run_activity WHERE tenant_id=$1 AND run_id=$3 AND action='stop_requested')", [this.tenantId, crypto.randomUUID(), runId]); diff --git a/packages/api/src/postgres/run-repository.ts b/packages/api/src/postgres/run-repository.ts index a1c28cda..541b0922 100644 --- a/packages/api/src/postgres/run-repository.ts +++ b/packages/api/src/postgres/run-repository.ts @@ -62,7 +62,7 @@ export class RunRepository { const changed = await client.query(`UPDATE app.job_runs SET state='blocked',launch_lease_expires_at=NULL,next_poll_at=NULL,updated_at=now() WHERE tenant_id=$1 AND id=$2 AND state='starting' RETURNING id`, [run.tenantId, run.id]); if (!changed.rowCount) return; - await client.query(`UPDATE app.runs SET state='blocked',failure_code='proxy_launch_blocked',failure_reason=$3,updated_at=now() + await client.query(`UPDATE app.runs SET state='blocked',failure_code='credential_repair_required',failure_reason=$3,updated_at=now() WHERE tenant_id=$1 AND id=$2 AND execution_handle IS NULL`, [run.tenantId, run.id, safeReason]); await client.query("INSERT INTO app.run_activity(tenant_id,id,run_id,action,detail) VALUES ($1,$2,$3,'launch_blocked',$4)", [run.tenantId, crypto.randomUUID(), run.id, safeReason]); }); @@ -73,7 +73,7 @@ export class RunRepository { return this.database.transaction(async client => { const changed = await client.query(`UPDATE app.job_runs r SET state='reserved',launch_lease_expires_at=NULL,next_poll_at=NULL,updated_at=now() FROM app.runs x WHERE r.tenant_id=$1 AND r.id=$2 AND r.tenant_id=x.tenant_id AND r.id=x.id - AND r.state='blocked' AND x.execution_handle IS NULL AND x.failure_code='proxy_launch_blocked' RETURNING r.id`, [tenantId, runId]); + AND r.state='blocked' AND x.execution_handle IS NULL AND x.failure_code='credential_repair_required' RETURNING r.id`, [tenantId, runId]); if (!changed.rowCount) return false; await client.query("UPDATE app.runs SET state='reserved',failure_source=NULL,failure_code=NULL,failure_reason=NULL,updated_at=now() WHERE tenant_id=$1 AND id=$2", [tenantId, runId]); await client.query("INSERT INTO app.run_activity(tenant_id,id,run_id,action,detail) VALUES ($1,$2,$3,'launch_retry_requested','Owner requested a manual retry')", [tenantId, crypto.randomUUID(), runId]); diff --git a/packages/api/src/postgres/run-scheduler.ts b/packages/api/src/postgres/run-scheduler.ts index 0bb46c04..e1f90d3f 100644 --- a/packages/api/src/postgres/run-scheduler.ts +++ b/packages/api/src/postgres/run-scheduler.ts @@ -23,13 +23,12 @@ import { LiveTraceRepository } from "./live-trace-repository"; import { JOB_RESULT_INSTRUCTIONS, parseJobResult } from "../job-result"; import { snapshotRunAuthorization } from "../run-authorizations"; import { DEFAULT_RUN_SCOPES } from "../run-scopes"; -import { issueRunCredential, runProxyInstructions } from "../run-credentials"; -import { ProxyLaunchBlockedError, proxyLaunchDecision, requireProxyLaunch } from "../proxy-launch-policy"; +import { runAccessInstructions } from "../run-instructions"; +import { RunCredentialRepairRequired, requireRunCredentials } from "../run-credential-launch"; import { FlyConnectionRepository } from "./fly-connection-repository"; import { FlyExecutionConfigurationRepository } from "./fly-execution-configuration-repository"; import { createFlyMachinesClient } from "../fly-machines-client"; import { FlyJobExecutionBackend, flyJobGuest } from "../fly-job-execution-backend"; -import { createFlyCredentialProxyGuest } from "../fly-credential-proxy-provisioner"; import { verifyAndPersistVendorRunIdentity } from "../vendor-run-identity-provisioning"; /** Host runners may supply infrastructure without patching scheduler internals. */ @@ -45,8 +44,8 @@ export class RunScheduler { for (const run of await this.runs.dueForPoll()) await this.poll(run).catch(error => this.fail(run, error, "poll")); for (let count = 0; count < 20; count++) { const run = await this.runs.claimNext(); if (!run) break; - await this.launch(run).catch(error => error instanceof ProxyLaunchBlockedError - ? this.runs.blockLaunch(run, `Credential proxy ${error.reason}; resolve the prerequisite and manually retry this run.`) + await this.launch(run).catch(error => error instanceof RunCredentialRepairRequired + ? this.runs.blockLaunch(run, error.message) : this.fail(run, error, "launch")); } const retention = new RunRetentionRepository(this.database); @@ -127,11 +126,16 @@ export class RunScheduler { private vendorIdentityVerifier(run: PersistedRun, expectedIssuer?: string) { return async (input: { provider: "exe.dev" | "fly.io"; vmId: string; token: string; integrationName?: string; expectedIssuer?: string; expectedSubject?: string }) => { - await verifyAndPersistVendorRunIdentity({ + const binding = await verifyAndPersistVendorRunIdentity({ database: this.database, tenantId: run.tenantId, runId: run.id, provider: input.provider, vmId: input.vmId, token: input.token, audience: `factorize://runs/${run.id}`, integrationName: input.integrationName, expectedIssuer: input.expectedIssuer ?? expectedIssuer, expectedSubject: input.expectedSubject, }); + if (run.state === "starting") { + const id = input.provider === "exe.dev" ? input.vmId : `${binding.subject.split(":")[1]}/${input.vmId}`; + await this.runs.recordLaunchHandle(run, {backendKind: input.provider === "exe.dev" ? "exe-vm" : "fly", id, operationId: run.id, identityProxyOrigin: this.env.APP_ORIGIN, + ...(input.provider === "exe.dev" ? {vendorIdentityIntegrationName: input.integrationName} : {})}); + } }; } @@ -151,20 +155,12 @@ export class RunScheduler { if (!connection) throw new Error("Fly connection is unavailable"); if (!connectionDetails) throw new Error("Fly connection is unavailable"); if (!configuration) throw new Error("Fly execution configuration is unavailable"); - const { rows } = await this.database.pool.query<{ proxy_identity: string; boot_epoch: string }>( - "SELECT proxy_identity, boot_epoch FROM app.credential_proxy_states WHERE tenant_id=$1 AND disabled_at IS NULL AND revoked_at IS NULL", - [run.tenantId], - ); - const proxy = /^fly:([a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])):([^:]+)$/.exec(rows[0]?.proxy_identity ?? ""); - if (!proxy) throw new Error("A registered Fly credential proxy is unavailable for this tenant"); - const app = proxy[1]!; + const app = `factorize-run-${run.tenantId.replaceAll("-", "")}`; const machines = createFlyMachinesClient({ token: connection }); return new FlyJobExecutionBackend({ app, organizationSlug: connectionDetails.organizationSlug, image: configuration.image, region: configuration.region, size: configuration.size, machines, guest: machine => flyJobGuest({ app, machine: machine.id, token: connection }), - proxyIdentity: rows[0]!.proxy_identity, - proxyBootEpoch: rows[0]!.boot_epoch, - proxyGuest: createFlyCredentialProxyGuest({ app, machine: proxy[2]!, token: connection }), + prepare: () => machines.ensureRunApp(app, connectionDetails.organizationSlug), vendorIdentityAudience: runId => `factorize://runs/${runId}`, verifyVendorIdentity: this.vendorIdentityVerifier(run, `https://oidc.fly.io/${connectionDetails.organizationSlug}`), }); @@ -179,22 +175,14 @@ export class RunScheduler { private async launch(run: PersistedRun) { const config = run.executionConfig; await snapshotRunAuthorization(this.database, {tenantId: run.tenantId, runId: run.id, scopes: config.runScopes ?? DEFAULT_RUN_SCOPES}); - const decision = proxyLaunchDecision({ - executionProvider: config.executionProvider === "fly" || config.executionProvider === "docker" ? "fly" : "exe", - executionType: config.executionType === "code" ? "code" : "agent", - portableIntegrationIds: config.portableIntegrationIds, - modelAccess: config.modelAccess, - modelAccountId: config.modelAccountId, - }, await this.proxyLaunchState(run.tenantId)); - requireProxyLaunch(decision); + await requireRunCredentials({database: this.database, env: this.env, tenantId: run.tenantId, runId: run.id, config}); if (run.executionConfig.executionType === "code") { if (typeof run.executionConfig.script !== "string" || !run.executionConfig.script.trim()) throw new Error("The code job has no saved script"); const backend = await this.backend(run), context = run.executionConfig.inputContext; if (!context || typeof context !== "object" || Array.isArray(context)) throw new Error("The code job input context snapshot is missing"); - const runToken = await issueRunCredential(this.env, run.tenantId, run.id, run.executionConfig.runScopes); const reservation = backend.reserve?.(run.id) ?? null; if (reservation) await this.runs.recordLaunchHandle(run, reservation); - const launched = await backend.launch({ runId: run.id, reservation: reservation ?? undefined, prompt: "", runProxy: { targetOrigin: this.env.APP_ORIGIN, credential: runToken }, code: { script: run.executionConfig.script, context }, verifyVendorIdentity: this.vendorIdentityVerifier(run) }); + const launched = await backend.launch({ runId: run.id, reservation: reservation ?? undefined, prompt: "", runIdentity: { backendOrigin: this.env.APP_ORIGIN }, code: { script: run.executionConfig.script, context }, verifyVendorIdentity: this.vendorIdentityVerifier(run) }); await this.runs.markLaunched(run, launched.handle, launched.destinationUrl, launched.capabilities); if (launched.observation.state === "failed") await this.runs.recordObservation(run, launched.observation); return; @@ -207,23 +195,14 @@ export class RunScheduler { }); const sources = rolloutTraceSources(driverTraceSources(driver.kind, harness), run.tenantId, this.env); validateTraceSources(sources); - const runToken = await issueRunCredential(this.env, run.tenantId, run.id, run.executionConfig.runScopes); const prompt = await decrypt(run.encryptedPrompt, this.env.CREDENTIAL_ENCRYPTION_KEY); const reservation = backend.reserve?.(run.id) ?? null; if (reservation) await this.runs.recordLaunchHandle(run, reservation); - const launched = await backend.launch({ runId: run.id, reservation: reservation ?? undefined, prompt: `${prompt}${JOB_RESULT_INSTRUCTIONS}${runProxyInstructions(run.id, { githubInstallationIds: run.executionConfig.githubInstallationIds ?? [], linear: run.executionConfig.linearConnectionId === "linear", model: run.executionConfig.modelAccess === "portable" && Boolean(run.executionConfig.modelAccountId) })}`, runProxy: { targetOrigin: this.env.APP_ORIGIN, credential: runToken }, traceSources: sources, harness: { executable: harness.executable, args: harness.args, env: harness.env }, verifyVendorIdentity: this.vendorIdentityVerifier(run) }); + const launched = await backend.launch({ runId: run.id, reservation: reservation ?? undefined, prompt: `${prompt}${JOB_RESULT_INSTRUCTIONS}${runAccessInstructions({ githubInstallationIds: run.executionConfig.githubInstallationIds ?? [], linear: run.executionConfig.linearConnectionId === "linear", model: run.executionConfig.modelAccess === "portable" && Boolean(run.executionConfig.modelAccountId) })}`, runIdentity: { backendOrigin: this.env.APP_ORIGIN }, traceSources: sources, harness: { executable: harness.executable, args: harness.args, env: harness.env }, verifyVendorIdentity: this.vendorIdentityVerifier(run) }); await this.runs.markLaunched(run, launched.handle, launched.destinationUrl, launched.capabilities, sources); if (launched.observation.state === "failed") await this.runs.recordObservation(run, launched.observation); } - private async proxyLaunchState(tenantId: string) { - const result = await this.database.pool.query<{ enabled: boolean; unlocked: boolean }>(`SELECT disabled_at IS NULL AND revoked_at IS NULL AS enabled, - unlocked AND updated_at > now() - interval '30 seconds' AS unlocked - FROM app.credential_proxy_states WHERE tenant_id=$1`, [tenantId]); - const state = result.rows[0]; - return { enabled: Boolean(state?.enabled), running: Boolean(state), unlocked: Boolean(state?.unlocked), pendingChanges: false }; - } - private async poll(run: PersistedRun) { if (!run.executionHandle && run.state === "stopping") return this.runs.schedulePoll(run, "stopping"); const backend = await this.backend(run); if (!run.executionHandle) throw new Error("Execution handle is missing"); diff --git a/packages/api/src/public-address.ts b/packages/api/src/public-address.ts index 2cd00db7..5aafa654 100644 --- a/packages/api/src/public-address.ts +++ b/packages/api/src/public-address.ts @@ -59,3 +59,12 @@ export function isPublicAddress(address: string) { if ((value >> 125n) !== 1n) return false; // 2000::/3 return !NON_PUBLIC_V6.some(([network, prefix]) => inV6Range(value, network, prefix)); } + + +export function isPublicHttpsOrigin(value: string, backendOrigin = ""): boolean { + try { + const url = new URL(value), host = url.hostname.replace(/^\[|\]$/g, ""); + return url.protocol === "https:" && url.origin === value && !url.username && !url.password && value !== backendOrigin + && (isIP(host) ? isPublicAddress(host) : host.includes(".") && !/(?:^|\.)(?:localhost|internal|local|test|invalid|example)$/.test(host)); + } catch { return false; } +} diff --git a/packages/api/src/run-artifact-target.ts b/packages/api/src/run-artifact-target.ts new file mode 100644 index 00000000..98e66210 --- /dev/null +++ b/packages/api/src/run-artifact-target.ts @@ -0,0 +1,8 @@ +import type { RunHandle } from "./execution"; +/** Signed grants authorize one upload, but never replace vendor authentication. + * The guest's local helper supplies vendor proof to the same backend origin. */ +export function runArtifactTarget(handle: RunHandle, uploadUrl: string): string { + const url = new URL(uploadUrl); + if (!handle.identityProxyOrigin || url.origin !== handle.identityProxyOrigin || !/^\/internal\/run-(?:artifacts|trace-chunks)\/[^/]+$/.test(url.pathname)) throw new Error("Vendor-authenticated artifact target unavailable"); + return `http://127.0.0.1:18180${url.pathname}${url.search}`; +} diff --git a/packages/api/src/run-credential-launch.ts b/packages/api/src/run-credential-launch.ts new file mode 100644 index 00000000..8d9ae948 --- /dev/null +++ b/packages/api/src/run-credential-launch.ts @@ -0,0 +1,35 @@ +import type { Database } from "./postgres/database"; +import type { Env } from "./types"; +import { EncryptedIntegrationRepository } from "./postgres/encrypted-integration-repository"; +import { GitHubRepository } from "./postgres/github-repository"; +import { isPublicHttpsOrigin } from "./public-address"; +import { resolveManagedModelCredential } from "./managed-model-credentials"; + +export class RunCredentialRepairRequired extends Error { + constructor() { super("A selected credential is unavailable or requires reconnection. Repair the job's selections and start a new run; this run's selection snapshot is unchanged."); } +} +/** Fail closed before provisioning, preserving all unavailable selections for + * explicit repair. No unlock/proxy service is a launch prerequisite. */ +export async function requireRunCredentials(input: {database: Database; env: Env; tenantId: string; runId: string; config: Record}): Promise { + const {database, env, tenantId, runId, config} = input; + const repository = new EncryptedIntegrationRepository(database, tenantId, env.CREDENTIAL_ENCRYPTION_KEY); + const revoked = (await database.pool.query("SELECT 1 FROM app.run_credential_revocations WHERE tenant_id=$1 AND run_id=$2 LIMIT 1", [tenantId, runId])).rowCount; + if (revoked) throw new RunCredentialRepairRequired(); + const ids = config.portableIntegrationIds ?? [], githubIds = config.githubInstallationIds ?? []; + if (!Array.isArray(ids) || !Array.isArray(githubIds) || new Set(ids).size !== ids.length || new Set(githubIds).size !== githubIds.length + || ![undefined, "native", "portable"].includes(config.modelAccess) + || (config.modelAccess !== "portable" && config.modelAccountId !== undefined) + || (config.executionType === "code" && (config.modelAccess === "portable" || config.modelAccountId !== undefined))) throw new RunCredentialRepairRequired(); + for (const id of ids) { + if (typeof id !== "string" || !/^[0-9a-f-]{36}$/i.test(id)) throw new RunCredentialRepairRequired(); + const credential = await repository.managedCredential(id, "bearer"); + if (!credential?.origin || !isPublicHttpsOrigin(credential.origin, env.APP_ORIGIN)) throw new RunCredentialRepairRequired(); + } + for (const id of githubIds) if (!Number.isSafeInteger(id) || id < 1 || (await new GitHubRepository(database, tenantId).installation(id))?.state !== "active") throw new RunCredentialRepairRequired(); + if (config.linearConnectionId !== undefined && (config.linearConnectionId !== "linear" || !(await database.pool.query("SELECT 1 FROM app.connections WHERE tenant_id=$1 AND kind='linear'", [tenantId])).rowCount)) throw new RunCredentialRepairRequired(); + if (config.modelAccess === "portable") { + if (typeof config.modelAccountId !== "string") throw new RunCredentialRepairRequired(); + try { if (!await resolveManagedModelCredential({database, env, tenantId, accountId: config.modelAccountId})) throw new RunCredentialRepairRequired(); } + catch { throw new RunCredentialRepairRequired(); } + } +} diff --git a/packages/api/src/run-identity-guest-helper.ts b/packages/api/src/run-identity-guest-helper.ts index e040bac2..a416a6af 100644 --- a/packages/api/src/run-identity-guest-helper.ts +++ b/packages/api/src/run-identity-guest-helper.ts @@ -52,6 +52,7 @@ export function createRunIdentityProxy(config, {getToken = () => vendorToken(con const url = new URL(incoming.url, "http://127.0.0.1"); let path; if (url.pathname === "/api/v1" || url.pathname.startsWith("/api/v1/") || url.pathname === "/mcp") path = url.pathname; + else if (/^\/internal\/run-(?:artifacts|trace-chunks)\/[^/]+$/.test(url.pathname)) path = url.pathname; else if (url.pathname === "/integrations") path = "/api/v1/runtime-integrations"; else if (url.pathname.startsWith("/integrations/") || url.pathname.startsWith("/providers/")) path = "/internal/run-proxy/" + config.runId + url.pathname; else { outgoing.writeHead(404).end(); return; } @@ -62,6 +63,7 @@ export function createRunIdentityProxy(config, {getToken = () => vendorToken(con for (const [name, value] of Object.entries(incoming.headers)) { if (value !== undefined && !blocked.has(name) && !connectionTokens.has(name) && !name.startsWith("x-forwarded-") && name !== "forwarded") headers.set(name, Array.isArray(value) ? value.join(", ") : value); } + if (/^\/internal\/run-(?:artifacts|trace-chunks)\//.test(path) && typeof incoming.headers["content-length"] === "string" && /^[0-9]+$/.test(incoming.headers["content-length"])) headers.set("Content-Length", incoming.headers["content-length"]); headers.set("Authorization", "Bearer " + token); headers.set("X-Factorize-Run-Id", config.runId); const method = incoming.method ?? "GET"; diff --git a/packages/api/src/run-instructions.ts b/packages/api/src/run-instructions.ts new file mode 100644 index 00000000..474a4cc3 --- /dev/null +++ b/packages/api/src/run-instructions.ts @@ -0,0 +1,8 @@ +/** Public guest instructions. No run token, upstream token, shared proxy URL, + * pairing, or unlock operation is part of the run access protocol. */ +export function runAccessInstructions(providers: {githubInstallationIds?: number[]; linear?: boolean; model?: boolean} = {}): string { + const selected = (providers.githubInstallationIds ?? []).map(id => `GitHub installation ${id}: http://127.0.0.1:18180/providers/github/${id}/ (REST/GraphQL and Git smart HTTP)`); + if (providers.linear) selected.push("Linear: http://127.0.0.1:18180/providers/linear/graphql"); + if (providers.model) selected.push("Model: http://127.0.0.1:18180/providers/model/v1 (already configured for Codex)"); + return `\n\n## Factorize run access\nUse FACTORIZE_PROXY_URL (http://127.0.0.1:18180) for all Factorize /api/v1 and /mcp requests. The local helper obtains fresh vendor identity and Factorize authorizes only this active run's tenant, selected connections and configured API scopes. Do not supply Authorization headers or look for Factorize/upstream tokens. GET $FACTORIZE_PROXY_URL/api/v1/runtime-context to discover your effective scopes and GET $FACTORIZE_PROXY_URL/integrations for selected integration paths and current availability. Job edits affect future runs. Use only the selected endpoints for upstream requests. Unavailable selections require owner repair; do not substitute another credential. Job-to-job invocation also requires explicit destination authorization. A granted jobs:write permits editing job configuration and future run scopes, but cannot expand this run's scopes or invocation destinations. If optional bookkeeping is outside the scopes, continue the authorized implementation and report that limitation. Use FACTORIZE_RESULT_PATH to report the final outcome.${selected.length ? `\n\n## Selected provider clients\n${selected.join("\n")}` : ""}\n`; +} diff --git a/packages/api/src/run-outbound-proxy.ts b/packages/api/src/run-outbound-proxy.ts index b217086e..9276543a 100644 --- a/packages/api/src/run-outbound-proxy.ts +++ b/packages/api/src/run-outbound-proxy.ts @@ -1,4 +1,3 @@ -import { isIP } from "node:net"; import type { Env } from "./types"; import { databaseFor } from "./postgres/database"; import { EncryptedIntegrationRepository } from "./postgres/encrypted-integration-repository"; @@ -6,18 +5,10 @@ import { resolveRunProviderCredentials } from "./provider-credentials"; import { authenticateVendorRunRequest, RUN_IDENTITY_HEADER } from "./vendor-run-auth"; import { forwardRunOutbound, type OutboundCredential } from "./run-outbound-forwarder"; import { resolveManagedModelCredential } from "./managed-model-credentials"; -import { isPublicAddress } from "./public-address"; +import { isPublicHttpsOrigin } from "./public-address"; const unavailable = () => new Response("Run credential unavailable", {status: 403, headers: {"Cache-Control": "no-store"}}); -function publicOrigin(value: string, backendOrigin: string): boolean { - try { - const url = new URL(value), host = url.hostname.replace(/^\[|\]$/g, ""); - return url.protocol === "https:" && url.origin === value && !url.username && !url.password && value !== backendOrigin - && (isIP(host) ? isPublicAddress(host) : host.includes(".") && !/(?:^|\.)(?:localhost|internal|local|test|invalid|example)$/.test(host)); - } catch { return false; } -} - /** Raw outbound protocol boundary. The guest supplies a path, never an origin, * upstream token, tenant, or credential outside its immutable run selection. */ export async function runOutboundProxyFetch(request: Request, env: Env): Promise { @@ -45,7 +36,7 @@ export async function runOutboundProxyFetch(request: Request, env: Env): Promise if (bearer) { if (!Array.isArray(config.portableIntegrationIds) || !config.portableIntegrationIds.includes(bearer[1]) || await revoked("bearer", bearer[1]!)) return unavailable(); const credential = await new EncryptedIntegrationRepository(database, auth.tenantId, env.CREDENTIAL_ENCRYPTION_KEY).managedCredential(bearer[1]!, "bearer"); - if (!credential?.origin || !publicOrigin(credential.origin, env.APP_ORIGIN)) return unavailable(); + if (!credential?.origin || !isPublicHttpsOrigin(credential.origin, env.APP_ORIGIN)) return unavailable(); selected = {origin: credential.origin, path: `${bearer[2] ?? "/"}${url.search}`, credential: credential.payload}; } else if (github) { const installationId = Number(github[1]); diff --git a/packages/api/src/vendor-run-auth.ts b/packages/api/src/vendor-run-auth.ts index 4af07eae..0d8ee734 100644 --- a/packages/api/src/vendor-run-auth.ts +++ b/packages/api/src/vendor-run-auth.ts @@ -19,11 +19,14 @@ type RunAuthorization = { /** A run ID is a lookup hint, never authority. Only a fresh vendor signature * matching the immutable provisioned binding can authorize this request. */ -export async function authenticateVendorRunRequest(request: Request, env: Env): Promise { +export async function authenticateVendorRunRequest(request: Request, env: Env, options: {artifactFinalization?: boolean} = {}): Promise { const runId = request.headers.get(RUN_IDENTITY_HEADER); const token = request.headers.get("Authorization")?.match(/^Bearer ([A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+)$/)?.[1]; if (!runId || !uuid.test(runId) || !token || token.length > 16_384) return null; const database = databaseFor(env); + // Stopping guests may finish a separately signed artifact upload only. + // Application/proxy callers never enable this control-protocol mode. + const states = options.artifactFinalization ? "('starting','running','blocked','stopping')" : "('starting','running','blocked')"; const result = await database.pool.query(`SELECT b.tenant_id,b.run_id,b.provider,b.vm_id,b.issuer,b.subject,b.audience, c.user_id,c.session_version,c.scopes,j.job_id,r.execution_config,r.execution_handle FROM app.vendor_run_identity_bindings b @@ -31,8 +34,8 @@ export async function authenticateVendorRunRequest(request: Request, env: Env): JOIN app.runs r ON r.tenant_id=j.tenant_id AND r.id=j.id JOIN app.run_authorizations c ON c.tenant_id=j.tenant_id AND c.run_id=j.id JOIN app.members m ON m.tenant_id=c.tenant_id AND m.user_id=c.user_id AND m.role='owner' AND m.session_version=c.session_version - WHERE b.run_id=$1 AND b.revoked_at IS NULL AND j.state IN ('starting','running','blocked') - AND r.state IN ('starting','running','blocked')`, [runId]); + WHERE b.run_id=$1 AND b.revoked_at IS NULL AND j.state IN ${states} + AND r.state IN ${states}`, [runId]); // Fail closed on ambiguous cross-tenant/run/provider lookup as well as absence. if (result.rows.length !== 1) return null; const row = result.rows[0]!; diff --git a/packages/api/src/worker.ts b/packages/api/src/worker.ts index c627548a..62a02aef 100644 --- a/packages/api/src/worker.ts +++ b/packages/api/src/worker.ts @@ -10,13 +10,11 @@ import { addDeviceMetadata, DEVICE_GRANT, deviceAuthorization, deviceClientRegis import type { Env, OAuthProps } from "./types"; import { ACCESS_SCOPES, authenticateAccessToken } from "./access-tokens"; import { authenticateVendorRunRequest, RUN_IDENTITY_HEADER } from "./vendor-run-auth"; -import { authenticateRunCredential } from "./run-credentials"; -import { artifactUpload } from "./artifact-upload"; +import { artifactUpload, readArtifactUploadGrant } from "./artifact-upload"; import { traceChunkUpload } from "./trace-chunk-upload"; import { databaseFor } from "./postgres/database"; import { IdentityRepository } from "./postgres/identity-repository"; import { runOutboundProxyFetch } from "./run-outbound-proxy"; -import { proxyControlFetch } from "./proxy-control"; const scopes = [...ACCESS_SCOPES]; // Keep accepting grants issued by the pre-resource-scope protocol. New @@ -89,16 +87,20 @@ function provider(env: Env) { return new OAuthProvider(providerOptions(env) export { AlarmCoordinator } from "./alarm-coordinator"; const backend = { async fetch(request: Request, env: Env, ctx: ExecutionContext) { if (new URL(request.url).pathname.startsWith("/internal/run-proxy/")) return runOutboundProxyFetch(request, env); - if (new URL(request.url).pathname.startsWith("/internal/credential-proxy/")) return proxyControlFetch(request, env); const staticResponse = !["/authorize", "/device"].includes(new URL(request.url).pathname) ? await staticApp(request, env) : null; if (staticResponse) return staticResponse; const oauth = provider(env); const url = new URL(request.url); const apiEnv = { ...env, OAUTH_PROVIDER: env.OAUTH_PROVIDER ?? getOAuthApi(providerOptions(env), env) }; - const traceChunkMatch = url.pathname.match(/^\/internal\/run-trace-chunks\/([^/]+)$/); - if (traceChunkMatch) return traceChunkUpload(request, env, decodeURIComponent(traceChunkMatch[1]!)); - const artifactMatch = url.pathname.match(/^\/internal\/run-artifacts\/([^/]+)$/); - if (artifactMatch) return artifactUpload(request, env, decodeURIComponent(artifactMatch[1]!)); + const upload = url.pathname.match(/^\/internal\/run-(artifacts|trace-chunks)\/([^/]+)$/); + if (upload) { + let token: string; + try { token = decodeURIComponent(upload[2]!); } catch { return new Response("Invalid upload grant", {status: 401}); } + const [auth, grant] = await Promise.all([authenticateVendorRunRequest(request, env, {artifactFinalization: true}), readArtifactUploadGrant(token, env.SESSION_SIGNING_SECRET)]); + if (!auth || !grant || auth.tenantId !== grant.tenantId || auth.runId !== grant.runId) return new Response("Vendor-verified run identity and a matching upload grant are required", {status: 401}); + return upload[1] === "artifacts" ? artifactUpload(request, env, token) : traceChunkUpload(request, env, token); + } + if (url.pathname.startsWith("/internal/")) return new Response("Not found", {status: 404}); if ((url.pathname === "/mcp" || url.pathname.startsWith("/api/v1")) && request.headers.has(RUN_IDENTITY_HEADER)) { const auth = await authenticateVendorRunRequest(request, env); if (!auth) return Response.json({ error: { code: "invalid_token", message: "The vendor identity is invalid or the run is no longer authorized." } }, { status: 401, headers: { "WWW-Authenticate": 'Bearer error="invalid_token"' } }); @@ -113,11 +115,6 @@ const backend = { async fetch(request: Request, env: Env, ctx: ExecutionContext) return protectedApiFetch(request, apiEnv, { tenantId: session.tenantId, userId: session.userId, sessionVersion: session.sessionVersion, scopes, authMethod: "session" }, ctx); } if ((url.pathname === "/mcp" || url.pathname.startsWith("/api/v1")) && request.headers.get("Authorization")?.startsWith("Bearer fzt_")) { - if (request.headers.get("Authorization")?.startsWith("Bearer fzt_run_")) { - const auth = await authenticateRunCredential(request, env); - if (!auth) return Response.json({ error: { code: "invalid_token", message: "The run credential is invalid, expired, revoked, or no longer active." } }, { status: 401, headers: { "WWW-Authenticate": "Bearer error=\"invalid_token\"" } }); - return protectedApiFetch(request, apiEnv, auth, ctx); - } const auth = await authenticateAccessToken(request, env); if (!auth) return Response.json({ error: { code: "invalid_token", message: "The access token is invalid, expired, or revoked." } }, { status: 401, headers: { "WWW-Authenticate": "Bearer error=\"invalid_token\"" } }); return protectedApiFetch(request, apiEnv, auth, ctx); diff --git a/packages/api/test/execution-backend.test.ts b/packages/api/test/execution-backend.test.ts index d1ff97d7..7dfa0b38 100644 --- a/packages/api/test/execution-backend.test.ts +++ b/packages/api/test/execution-backend.test.ts @@ -122,10 +122,16 @@ describe("ExeVmBackend", () => { })); const verify = vi.fn(async () => undefined); const runId = "00000000-0000-4000-8000-000000000001"; - const launched = await new ExeVmBackend(connection).launch({ runId, prompt: "work", harness: agentDriver("codex").launch(runId, {}), verifyVendorIdentity: verify }); + const launched = await new ExeVmBackend(connection).launch({ runId, prompt: "work", harness: agentDriver("codex").launch(runId, {}), verifyVendorIdentity: verify, runIdentity: {backendOrigin: "https://factorize.example.com"} }); expect(launched.observation.state).toBe("running"); - expect(requests[1]).toContain("integrations add wif"); - expect(requests[1]).toContain("--attach='vm:factorize-00000000-0000-4000-8000-000000000001'"); + expect(requests[0]).toBe("integrations list --json"); + const wif = requests.find(value => value.startsWith("integrations add wif"))!; + expect(wif).toContain("--attach='vm:factorize-00000000-0000-4000-8000-000000000001'"); + expect(requests.some(value => value.startsWith("integrations add http-proxy"))).toBe(false); + const work = requests.find(value => value.includes("sudo systemd-run"))!; + expect(work).toContain("/run/factorize-identity/proxy.mjs"); + expect(work).toContain("FACTORIZE_PROXY_URL=http://127.0.0.1:18180"); + expect(launched.handle).not.toHaveProperty("runProxyName"); expect(verify).toHaveBeenCalledWith({ provider: "exe.dev", vmId: "factorize-00000000-0000-4000-8000-000000000001", token, integrationName: "fzrun-00000000000040008000000000000001", expectedIssuer: "https://exe.dev/issuer/test", expectedSubject: "sub-test" }); expect(requests.indexOf(requests.find(value => value.includes("sudo systemd-run"))!)).toBeGreaterThan(requests.indexOf(requests.find(value => value.includes("/token"))!)); }); @@ -291,8 +297,8 @@ describe("ExeVmBackend", () => { return new Response("uploaded", { headers: { "X-Exe-Exit": "0" } }); })); const result = await new ExeVmBackend(connection).collectArtifact( - { backendKind: "exe-vm", id: "factorize-run-1" }, - { discoverCommand: "find sessions -name '*.jsonl' | head -1", contentType: "application/x-ndjson", uploadUrl: "https://app.example/upload" }, + { backendKind: "exe-vm", id: "factorize-run-1", identityProxyOrigin: "https://app.example" }, + { discoverCommand: "find sessions -name '*.jsonl' | head -1", contentType: "application/x-ndjson", uploadUrl: "https://app.example/internal/run-artifacts/signed-grant" }, ); expect(result.ok).toBe(true); expect(request).toContain("snapshot=$(mktemp)"); @@ -304,8 +310,8 @@ describe("ExeVmBackend", () => { let request = ""; vi.stubGlobal("fetch", vi.fn(async (_url: string, init: RequestInit) => { request = String(init.body); return new Response("uploaded", { headers: { "X-Exe-Exit": "0" } }); })); const result = await new ExeVmBackend(connection).collectTraceChunk( - { backendKind: "exe-vm", id: "factorize-run-1" }, - { discoverCommand: "find sessions -name '*.jsonl' | head -1", generation: "1:2:3", offset: 1234, previousHash: "a".repeat(64), uploadUrl: "https://app.example/chunk" }, + { backendKind: "exe-vm", id: "factorize-run-1", identityProxyOrigin: "https://app.example" }, + { discoverCommand: "find sessions -name '*.jsonl' | head -1", generation: "1:2:3", offset: 1234, previousHash: "a".repeat(64), uploadUrl: "https://app.example/internal/run-trace-chunks/signed-grant" }, ); expect(result.ok).toBe(true); expect(request).toContain("start=1234"); diff --git a/packages/api/test/fly-job-execution-backend.test.ts b/packages/api/test/fly-job-execution-backend.test.ts index 9053d66d..9ba8628d 100644 --- a/packages/api/test/fly-job-execution-backend.test.ts +++ b/packages/api/test/fly-job-execution-backend.test.ts @@ -17,7 +17,7 @@ function fixture() { ok: true, exitCode: 0, stdout: command.at(-1) === "--version" ? "codex-cli 0.167.1\n" : "started\n", stderr: "", })), - upload: vi.fn(async () => undefined), + upload: vi.fn(async (_path: string, _bytes: Uint8Array) => undefined), download: vi.fn(async (path: string) => new TextEncoder().encode(path.endsWith("results.json") ? '{"status":"succeeded"}' : "saved log")), }; const proxyGuest = { @@ -81,6 +81,29 @@ describe("Fly job execution backend", () => { }); }); + it("installs only public vendor identity configuration and never provisions a credential-proxy peer", async () => { + const f = fixture(), verify = vi.fn(async () => undefined), prepare = vi.fn(async () => undefined); + const token = "header.claims.signature"; + f.guest.run.mockResolvedValueOnce({ok: true, exitCode: 0, stdout: token, stderr: ""}); + const backend = new FlyJobExecutionBackend({app: "factorize-test", organizationSlug: "factorize-org", image: "image", region: "iad", size: "shared-cpu-1x", machines: f.machines, guest: () => f.guest, verifyVendorIdentity: verify, prepare}); + const runId = "11111111-1111-4111-8111-111111111111"; + const result = await backend.launch({runId, prompt: "work", runIdentity: {backendOrigin: "https://factorize.example.com"}}); + expect(result.observation.state).toBe("running"); + expect(prepare.mock.invocationCallOrder[0]).toBeLessThan(f.machines.createMachine.mock.invocationCallOrder[0]!); + expect(f.proxyGuest.run).not.toHaveBeenCalled(); + expect(f.guest.upload.mock.calls.map(([name]) => name)).toContain("/run/factorize-identity/proxy.mjs"); + const config = f.guest.upload.mock.calls.find(([name]) => name === "/run/factorize-identity/config.json")!; + expect(JSON.parse(new TextDecoder().decode(config[1]))).toEqual({runId, backendOrigin: "https://factorize.example.com", provider: "fly.io", localPort: 18180}); + expect(f.guest.upload.mock.calls.map(([, bytes]) => new TextDecoder().decode(bytes)).join("\n")).not.toContain(token); + expect(f.guest.run.mock.calls.at(-1)![0]).toContain("FACTORIZE_PROXY_URL=http://127.0.0.1:18180"); + }); + + it("refuses run access before provisioning when no vendor verifier is configured", async () => { + const f = fixture(); + await expect(f.backend.launch({runId: "11111111-1111-4111-8111-111111111111", prompt: "work", runIdentity: {backendOrigin: "https://factorize.example.com"}})).rejects.toThrow("Vendor identity"); + expect(f.machines.createMachine).not.toHaveBeenCalled(); + }); + it("reports a nonzero Fly guest process exit as a failed run", async () => { const f = fixture(); f.machines.inspectMachine.mockResolvedValue({ ...machine, state: "started" }); diff --git a/packages/api/test/fly-machines-client.test.ts b/packages/api/test/fly-machines-client.test.ts index 60ab6d26..7ac9713f 100644 --- a/packages/api/test/fly-machines-client.test.ts +++ b/packages/api/test/fly-machines-client.test.ts @@ -43,6 +43,9 @@ describe("bounded Fly Machines client", () => { const body = JSON.parse(raw); expect(body.config.metadata.factorize_operation_id).toBe("op-1"); expect(body.config.restart).toEqual({ policy: "no" }); + expect(body.skip_launch).toBe(true); + expect(body.region).toBe("ord"); + expect(body.config).not.toHaveProperty("region"); return json(res, 200, machine); } if (req.method === "GET" && req.url === "/v1/apps/app-a/machines/m-1") return json(res, 200, machine); @@ -54,7 +57,7 @@ describe("bounded Fly Machines client", () => { json(res, 404, { error: "not found" }); }); const client = createFlyMachinesClient({ token, apiOrigin: origin, wait: async () => undefined }); - const created = await client.createMachine("app-a", { image: "example/image", restart: { policy: "always" }, metadata: { keep: "yes" } }, "op-1"); + const created = await client.createMachine("app-a", { image: "example/image", region: "ord", restart: { policy: "always" }, metadata: { keep: "yes" } }, "op-1"); expect(created.id).toBe("m-1"); expect((await client.inspectMachine("app-a", "m-1")).id).toBe("m-1"); await client.startMachine("app-a", "m-1"); diff --git a/packages/api/test/run-credential-repair.postgres.test.ts b/packages/api/test/run-credential-repair.postgres.test.ts new file mode 100644 index 00000000..aac4c33e --- /dev/null +++ b/packages/api/test/run-credential-repair.postgres.test.ts @@ -0,0 +1,48 @@ +import {afterAll, beforeAll, describe, expect, it, vi} from "vitest"; +import {loadingFixture} from "./helpers/loading-fixture"; +import {RunScheduler} from "../src/postgres/run-scheduler"; +import {protectedApiFetch} from "../src/protected-api"; +import {EncryptedIntegrationRepository} from "../src/postgres/encrypted-integration-repository"; +import {RunRepository} from "../src/postgres/run-repository"; + +vi.mock("cloudflare:workers", () => ({WorkerEntrypoint: class {}, DurableObject: class {}})); +vi.mock("@cloudflare/workers-oauth-provider", () => ({OAuthProvider: class {}, AuthorizationError: class extends Error {}, getOAuthApi: vi.fn()})); +const url = process.env.AUTH_TEST_DATABASE_URL; +describe.skipIf(!url)("run credential repair and cancellation (PostgreSQL)", () => { + let f: Awaited>; + beforeAll(async () => { f = await loadingFixture(url!); }); + afterAll(async () => { await f?.cleanup(); }); + const call = (path: string, body?: unknown) => protectedApiFetch(new Request(f.env.APP_ORIGIN+path, {method: "POST", headers: {Origin: f.env.APP_ORIGIN, "Content-Type": "application/json"}, ...(body === undefined ? {} : {body: JSON.stringify(body)})}), f.env, {...f.auth, scopes: ["jobs:read", "jobs:write", "runs:invoke", "runs:cancel"]}, {waitUntil() {}} as any); + + it("keeps unavailable selections intact, cancels an unprovisioned block, and launches a repaired future run", async () => { + const missing = crypto.randomUUID(), replacement = crypto.randomUUID(); + const snapshot = {agentKind: "codex", connectionId: "local", portableIntegrationIds: [missing], modelAccess: "native", runScopes: []}; + await f.db.pool.query("UPDATE app.runs SET state='reserved',execution_config=$3 WHERE tenant_id=$1 AND id=$2", [f.tenantId, f.runId, snapshot]); + await f.db.pool.query("UPDATE app.job_runs SET state='reserved' WHERE tenant_id=$1 AND id=$2", [f.tenantId, f.runId]); + const launch = vi.fn(async (request: any) => ({handle: {backendKind: "exe-vm", id: `factorize-${request.runId}`}, observation: {state: "running" as const}, capabilities: [], destinationUrl: "https://vm.example.com"})); + const scheduler = new RunScheduler(f.db, f.env, async () => ({kind: "exe-vm", capabilities: [], launch, inspect: async () => ({state: "running" as const}), stop: async () => ({state: "stopped" as const})})); + await scheduler.process(); + expect(launch).not.toHaveBeenCalled(); + const blocked = (await f.db.pool.query("SELECT state,failure_code,execution_config,execution_handle FROM app.runs WHERE tenant_id=$1 AND id=$2", [f.tenantId, f.runId])).rows[0]; + expect(blocked).toMatchObject({state: "blocked", failure_code: "credential_repair_required", execution_handle: null, execution_config: snapshot}); + const records = new EncryptedIntegrationRepository(f.db, f.tenantId, f.env.CREDENTIAL_ENCRYPTION_KEY); + await records.write({id: replacement, kind: "bearer", name: "Re-entered", origin: "https://selected.example.com", description: null, managedSecret: "replacement-secret", expectedRevision: 0, idempotencyKey: crypto.randomUUID(), operation: "upsert"}); + await f.db.pool.query("UPDATE app.jobs SET execution_config=$3,run_scopes='[]' WHERE tenant_id=$1 AND id=$2", [f.tenantId, f.jobIds[0], {...snapshot, portableIntegrationIds: [replacement]}]); + expect(await new RunRepository(f.db).retryBlockedLaunch(f.tenantId, f.runId)).toBe(true); + await scheduler.process(); + expect(launch).not.toHaveBeenCalled(); // Repair never mutates the old snapshot. + expect((await call(`/api/v1/runs/${f.runId}/stop`)).status).toBe(200); + const stopped = (await f.db.pool.query("SELECT state,claim_released,vm_cleanup_complete FROM app.runs WHERE tenant_id=$1 AND id=$2", [f.tenantId, f.runId])).rows[0]; + expect(stopped).toEqual({state: "stopped", claim_released: true, vm_cleanup_complete: true}); + const invoked = await call(`/api/v1/jobs/${f.jobIds[0]}/invocations`, {prompt: "repaired run", idempotencyKey: "repaired-future-run"}); + expect(invoked.status).toBe(202); + const next = await invoked.json() as {runId: string}; + await scheduler.process(); + expect(launch).toHaveBeenCalledTimes(1); + expect(launch.mock.calls[0]![0].runIdentity).toEqual({backendOrigin: f.env.APP_ORIGIN}); + expect(launch.mock.calls[0]![0]).not.toHaveProperty("runProxy"); + const saved = (await f.db.pool.query("SELECT r.execution_config,a.scopes FROM app.runs r JOIN app.run_authorizations a ON a.tenant_id=r.tenant_id AND a.run_id=r.id WHERE r.tenant_id=$1 AND r.id=$2", [f.tenantId, next.runId])).rows[0]; + expect(saved.execution_config.portableIntegrationIds).toEqual([replacement]); + expect(saved.scopes).toEqual([]); + }); +}); diff --git a/packages/api/test/run-proxy-launch.postgres.test.ts b/packages/api/test/run-proxy-launch.postgres.test.ts deleted file mode 100644 index 3bfbf500..00000000 --- a/packages/api/test/run-proxy-launch.postgres.test.ts +++ /dev/null @@ -1,79 +0,0 @@ -import { afterAll, beforeAll, describe, expect, it, vi } from "vitest"; -import { loadingFixture } from "./helpers/loading-fixture"; -import { RunScheduler } from "../src/postgres/run-scheduler"; -import { protectedApiFetch } from "../src/protected-api"; - -vi.mock("cloudflare:workers", () => ({ WorkerEntrypoint: class {}, DurableObject: class {} })); -vi.mock("@cloudflare/workers-oauth-provider", () => ({ OAuthProvider: class {}, AuthorizationError: class extends Error {}, getOAuthApi: vi.fn() })); - -const url = process.env.AUTH_TEST_DATABASE_URL; -describe.skipIf(!url)("proxy-gated scheduler lifecycle (PostgreSQL/API)", () => { - let fixture: Awaited>; - beforeAll(async () => { fixture = await loadingFixture(url!); }); - afterAll(async () => { await fixture?.cleanup(); }); - - it("keeps launches blocked for missing, disabled, revoked, stale, or locked proxy state until the owner retries", async () => { - const { db, env, auth, tenantId, runId } = fixture; - const proxyIdentity = `proxy-${crypto.randomUUID()}`; - await db.pool.query(`UPDATE app.runs SET execution_config=$3 - WHERE tenant_id=$1 AND id=$2`, [tenantId, runId, { - agentKind: "codex", connectionId: "local", executionProvider: "fly", executionType: "agent", - modelAccess: "portable", modelAccountId: crypto.randomUUID(), portableIntegrationIds: [], runScopes: [], - }]); - - const cases = [ - { label: "no registered proxy", state: "missing", reason: "proxy_disabled" }, - { label: "disabled proxy", state: "disabled", reason: "proxy_disabled" }, - { label: "revoked proxy", state: "revoked", reason: "proxy_disabled" }, - { label: "stale unlock heartbeat", state: "stale", reason: "proxy_locked" }, - { label: "locked proxy", state: "locked", reason: "proxy_locked" }, - ] as const; - for (const scenario of cases) { - await db.pool.query("DELETE FROM app.run_activity WHERE tenant_id=$1 AND run_id=$2", [tenantId, runId]); - await db.pool.query(`UPDATE app.job_runs SET state='reserved',launch_lease_expires_at=NULL,next_poll_at=NULL WHERE tenant_id=$1 AND id=$2`, [tenantId, runId]); - await db.pool.query(`UPDATE app.runs SET state='reserved',failure_source=NULL,failure_code=NULL,failure_reason=NULL,execution_handle=NULL WHERE tenant_id=$1 AND id=$2`, [tenantId, runId]); - if (scenario.state === "missing") { - await db.pool.query("DELETE FROM app.credential_proxy_states WHERE tenant_id=$1", [tenantId]); - } else { - const disabled = scenario.state === "disabled" ? "now()" : "NULL"; - const revoked = scenario.state === "revoked" ? "now()" : "NULL"; - const unlocked = scenario.state === "stale" ? "true" : "false"; - const heartbeat = scenario.state === "stale" ? "now()-interval '1 minute'" : "now()"; - await db.pool.query(`INSERT INTO app.credential_proxy_states(tenant_id,proxy_identity,boot_epoch,disabled_at,revoked_at,unlocked,updated_at) - VALUES ($1,$2,$3,${disabled},${revoked},${unlocked},${heartbeat}) - 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,unlocked=excluded.unlocked,updated_at=excluded.updated_at`, - [tenantId, proxyIdentity, crypto.randomUUID()]); - } - - await new RunScheduler(db, env).process(); - const blocked = (await db.pool.query(`SELECT jr.state job_state,r.state run_state,r.failure_code,r.failure_reason, - r.execution_handle,jr.launch_lease_expires_at - FROM app.job_runs jr JOIN app.runs r USING (tenant_id,id) WHERE jr.tenant_id=$1 AND jr.id=$2`, [tenantId, runId])).rows[0]; - expect(blocked, scenario.label).toMatchObject({ job_state: "blocked", run_state: "blocked", failure_code: "proxy_launch_blocked", execution_handle: null, launch_lease_expires_at: null }); - expect(blocked.failure_reason, scenario.label).toContain(scenario.reason); - expect((await db.pool.query("SELECT action FROM app.run_activity WHERE tenant_id=$1 AND run_id=$2 ORDER BY created_at", [tenantId, runId])).rows, scenario.label).toEqual([{ action: "launch_blocked" }]); - } - - await db.pool.query("UPDATE app.credential_proxy_states SET unlocked=true,updated_at=now(),disabled_at=NULL,revoked_at=NULL WHERE tenant_id=$1", [tenantId]); - const request = () => protectedApiFetch(new Request(`${env.APP_ORIGIN}/api/v1/runs/${runId}/retry-launch`, { - method: "POST", headers: { Origin: env.APP_ORIGIN }, - }), env, { ...auth, authMethod: "session", scopes: ["runs:cancel"] }, { waitUntil() {} } as any); - const retried = await request(); - expect(retried.status).toBe(200); - expect(await retried.json()).toEqual({ runId, retryRequested: true }); - expect((await db.pool.query(`SELECT jr.state job_state,r.state run_state,r.failure_code,r.execution_handle - FROM app.job_runs jr JOIN app.runs r USING (tenant_id,id) WHERE jr.tenant_id=$1 AND jr.id=$2`, [tenantId, runId])).rows[0]).toMatchObject({ job_state: "reserved", run_state: "reserved", failure_code: null, execution_handle: null }); - expect((await db.pool.query("SELECT action FROM app.run_activity WHERE tenant_id=$1 AND run_id=$2 ORDER BY created_at", [tenantId, runId])).rows.map((row: any) => row.action)).toEqual(["launch_blocked", "launch_retry_requested"]); - expect((await db.pool.query("SELECT key FROM app.wake_hints WHERE key='global'")).rowCount).toBe(1); - expect((await request()).status).toBe(409); - - // The explicit retry only requeues the run. If proxy state changes before - // the scheduler claims it, the launch gate must block it again. - await db.pool.query("UPDATE app.credential_proxy_states SET unlocked=false,updated_at=now() WHERE tenant_id=$1", [tenantId]); - await new RunScheduler(db, env).process(); - expect((await db.pool.query(`SELECT jr.state job_state,r.state run_state,r.failure_code,r.execution_handle - FROM app.job_runs jr JOIN app.runs r USING (tenant_id,id) WHERE jr.tenant_id=$1 AND jr.id=$2`, [tenantId, runId])).rows[0]).toMatchObject({ job_state: "blocked", run_state: "blocked", failure_code: "proxy_launch_blocked", execution_handle: null }); - expect((await db.pool.query("SELECT action FROM app.run_activity WHERE tenant_id=$1 AND run_id=$2 ORDER BY created_at", [tenantId, runId])).rows.map((row: any) => row.action)).toEqual(["launch_blocked", "launch_retry_requested", "launch_blocked"]); - }, 30_000); -}); diff --git a/packages/api/test/run-proxy-launch.test.ts b/packages/api/test/run-vendor-launch.test.ts similarity index 56% rename from packages/api/test/run-proxy-launch.test.ts rename to packages/api/test/run-vendor-launch.test.ts index 299f3e6e..16ab8393 100644 --- a/packages/api/test/run-proxy-launch.test.ts +++ b/packages/api/test/run-vendor-launch.test.ts @@ -3,33 +3,37 @@ import { RunScheduler } from "../src/postgres/run-scheduler"; import { RunRepository } from "../src/postgres/run-repository"; import { ExeVmBackend } from "../src/exe-vm-backend"; import { encrypt } from "../src/crypto"; -import { runProxyName } from "../src/run-credentials"; -import { ProxyLaunchBlockedError } from "../src/proxy-launch-policy"; + +import { RunCredentialRepairRequired } from "../src/run-credential-launch"; afterEach(() => vi.restoreAllMocks()); -describe("control-plane run credential delivery", () => { - it("persists a pre-launch block when a credential-dependent job has no fresh unlocked proxy status", async () => { - const database = { pool: { query: vi.fn() } }; - const scheduler: any = new RunScheduler(database as any, {} as any); - vi.spyOn(scheduler, "proxyLaunchState").mockResolvedValue({ enabled: true, running: true, unlocked: false, pendingChanges: false }); - await expect(scheduler.launch({ - id: "00000000-0000-4000-8000-000000000001", tenantId: "tenant", - executionConfig: { executionProvider: "fly", executionType: "agent", modelAccess: "portable", modelAccountId: "account" }, - })).rejects.toEqual(new ProxyLaunchBlockedError("proxy_locked")); +describe("vendor-authenticated run launch", () => { + it("requires repair before provisioning when a selected credential is missing", async () => { + const database = {pool: {query: vi.fn(async (sql: string) => { + if (sql.includes("SELECT user_id,session_version")) return {rows: [{user_id: "owner", session_version: 1}]}; + if (sql.includes("INSERT INTO app.run_authorizations")) return {rows: []}; + if (sql.includes("run_credential_revocations")) return {rows: [], rowCount: 0}; + if (sql.includes("FROM app.integration_records")) return {rows: []}; + throw new Error("Unexpected query"); + })}}; + const scheduler: any = new RunScheduler(database as any, {CREDENTIAL_ENCRYPTION_KEY: btoa("a".repeat(32))} as any); + const backend = vi.spyOn(scheduler, "backend"); + await expect(scheduler.launch({id: "00000000-0000-4000-8000-000000000001", tenantId: "tenant", executionConfig: {portableIntegrationIds: ["00000000-0000-4000-8000-000000000002"]}})).rejects.toBeInstanceOf(RunCredentialRepairRequired); + expect(backend).not.toHaveBeenCalled(); }); - it.each(["codex", "claude", "pi", "code"])("keeps %s proxy credentials out of the guest environment and prompt", async agentKind => { + it.each(["codex", "claude", "pi", "code"])("launches %s with public identity configuration and snapshotted scopes", async agentKind => { const runId = "00000000-0000-4000-8000-000000000001", key = btoa("a".repeat(32)); let issuedScopes: unknown; const database = { pool: { query: async (sql: string, values: unknown[] = []) => { if (sql.includes("SELECT user_id,session_version")) return { rows: [{ user_id: "owner", session_version: 1 }] }; - if (sql.includes("INSERT INTO app.run_credentials")) { issuedScopes = JSON.parse(String(values[6])); return { rows: [] }; } + if (sql.includes("INSERT INTO app.run_authorizations")) { issuedScopes = JSON.parse(String(values[4])); return { rows: [] }; } + if (sql.includes("run_credential_revocations")) return {rows: [], rowCount: 0}; throw new Error("Unexpected database operation"); } } }; const env = { DATABASE: database, APP_ORIGIN: "https://app.test", CREDENTIAL_ENCRYPTION_KEY: key } as any; const scheduler: any = new RunScheduler(database as any, env); - vi.spyOn(scheduler, "proxyLaunchState").mockResolvedValue({ enabled: true, running: true, unlocked: true, pendingChanges: false }); const backend = new ExeVmBackend({ apiToken: "control-plane-token", agentKind: (agentKind === "code" ? "codex" : agentKind) as any, tags: [] }); vi.spyOn(scheduler, "backend").mockResolvedValue(backend); const launch = vi.spyOn(backend, "launch").mockResolvedValue({ handle: { backendKind: "exe-vm", id: "factorize-run" }, observation: { state: "running" }, capabilities: [], destinationUrl: "https://vm.test" }); @@ -38,16 +42,16 @@ describe("control-plane run credential delivery", () => { await scheduler.launch({ id: runId, tenantId: "tenant", executionConfig: { agentKind, runScopes: ["jobs:read", "jobs:write"], ...(agentKind === "code" ? { executionType: "code", script: "echo test", inputContext: {} } : {}) }, encryptedPrompt: await encrypt("Complete the task", key) }); const request = launch.mock.calls[0][0]; expect(recordHandle.mock.invocationCallOrder[0]).toBeLessThan(launch.mock.invocationCallOrder[0]); - expect(request.runProxy?.credential).toMatch(/^fzt_run_/); - expect(request.runProxy?.targetOrigin).toBe(env.APP_ORIGIN); + expect(request.runProxy).toBeUndefined(); + expect(request.runIdentity).toEqual({backendOrigin: env.APP_ORIGIN}); + expect(typeof request.verifyVendorIdentity).toBe("function"); expect(issuedScopes).toEqual(["jobs:read", "jobs:write"]); if (agentKind === "code") { expect(request.code?.script).toBe("echo test"); return; } expect(request.harness?.env).toHaveProperty("FACTORIZE_RESULT_PATH"); expect(request.harness?.env).not.toHaveProperty("FACTORIZE_API_URL"); expect(request.harness?.env).not.toHaveProperty("FACTORIZE_RUN_TOKEN"); - expect(request.prompt).toContain(runProxyName(runId)); - expect(request.prompt).toContain("reflection.int.exe.xyz/integrations"); - expect(request.prompt).not.toContain(request.runProxy!.credential); + expect(request.prompt).toContain("http://127.0.0.1:18180"); + expect(request.prompt).not.toContain("fzt_run_"); expect(request.prompt).not.toContain(env.APP_ORIGIN); }); }); diff --git a/packages/api/test/vendor-run-auth.postgres.test.ts b/packages/api/test/vendor-run-auth.postgres.test.ts index 5abc056b..512a1355 100644 --- a/packages/api/test/vendor-run-auth.postgres.test.ts +++ b/packages/api/test/vendor-run-auth.postgres.test.ts @@ -2,6 +2,7 @@ import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } import { loadingFixture } from "./helpers/loading-fixture"; import { VendorRunIdentityRepository } from "../src/postgres/vendor-run-identity-repository"; import { FlyConnectionRepository } from "../src/postgres/fly-connection-repository"; +import { issueArtifactUploadGrant } from "../src/artifact-upload"; import { snapshotRunAuthorization } from "../src/run-authorizations"; import { authenticateVendorRunRequest } from "../src/vendor-run-auth"; import { exeWifIntegrationNameFor, vmNameFor } from "../src/exe-vm-backend"; @@ -246,6 +247,30 @@ describe.skipIf(!url)("vendor identity request admission (PostgreSQL and Worker expect(requests).toBe(3); }); + it("requires vendor identity as well as a matching artifact grant, including finalization", async () => { + const grant = await issueArtifactUploadGrant({tenantId: f.tenantId, runId: f.runId, path: "native/session.jsonl", contentType: "application/x-ndjson", provider: "claude", format: "jsonl", expiresAt: Date.now()+60_000}, f.env.SESSION_SIGNING_SECRET); + const path = `/internal/run-artifacts/${encodeURIComponent(grant)}`; + const put = (value = request(jwt, f.runId, path)) => worker.fetch(new Request(value, {method: "PUT", body: "artifact"}), f.env, {waitUntil() {}} as any); + expect((await put(new Request(f.env.APP_ORIGIN+path))).status).toBe(401); + expect((await put()).status).toBe(503); // Authentication passed; this fixture deliberately has no R2 storage. + const foreign = await issueArtifactUploadGrant({tenantId: f.otherTenant, runId: f.runId, path: "native/session.jsonl", contentType: "application/x-ndjson", provider: "claude", format: "jsonl", expiresAt: Date.now()+60_000}, f.env.SESSION_SIGNING_SECRET); + expect((await put(request(jwt, f.runId, `/internal/run-artifacts/${encodeURIComponent(foreign)}`))).status).toBe(401); + await f.db.pool.query("UPDATE app.job_runs SET state='stopping' WHERE tenant_id=$1 AND id=$2", [f.tenantId, f.runId]); + await f.db.pool.query("UPDATE app.runs SET state='stopping' WHERE tenant_id=$1 AND id=$2", [f.tenantId, f.runId]); + expect((await worker.fetch(request(), f.env, {waitUntil() {}} as any)).status).toBe(401); + expect((await put()).status).toBe(503); // Only the signed, run-bound finalization protocol remains eligible. + await f.db.pool.query("UPDATE app.job_runs SET state='stopped' WHERE tenant_id=$1 AND id=$2", [f.tenantId, f.runId]); + expect((await put()).status).toBe(401); + }); + + it("rejects old run bearer and credential-proxy control authentication paths", async () => { + const obsolete = `fzt_run_${Buffer.from(f.runId).toString("base64url")}_${"A".repeat(43)}`; + const response = await worker.fetch(new Request(f.env.APP_ORIGIN+"/api/v1/runtime-context", {headers: {Authorization: `Bearer ${obsolete}`}}), f.env, {waitUntil() {}} as any); + expect(response.status).toBe(401); + const control = await worker.fetch(new Request(f.env.APP_ORIGIN+"/internal/credential-proxy/enroll", {method: "POST", headers: {Authorization: "Bearer old-proxy-control-secret"}, body: "{}"}), f.env, {waitUntil() {}} as any); + expect(control.status).toBe(404); + }); + it("rechecks current run lifecycle, revocation, handle and execution connection", async () => { for (const state of ["queued", "reserved", "stopping", "stopped", "succeeded", "failed"]) { await f.db.pool.query("UPDATE app.job_runs SET state=$3 WHERE tenant_id=$1 AND id=$2", [f.tenantId, f.runId, state]); diff --git a/packages/docs/openapi.yaml b/packages/docs/openapi.yaml index a4cfdb3d..7a722366 100644 --- a/packages/docs/openapi.yaml +++ b/packages/docs/openapi.yaml @@ -14259,7 +14259,7 @@ paths: post: summary: Manually retry a blocked launch description: |- - Retries only a pre-launch proxy-gated run after its prerequisites have been resolved. The run remains blocked until an interactive owner explicitly retries it; unlock or status changes do not automatically launch it. + Retries a blocked launch with its original immutable credential and API scope snapshot. Job edits affect future runs; revoked/deleted selections require job repair and a new run. An interactive owner must request this retry. Requires the runs:cancel scope. From 066b6d5fe10acc70c3432b6603f5fc33421f3306 Mon Sep 17 00:00:00 2001 From: "exe.dev user" Date: Tue, 17 Nov 2026 16:11:55 +0000 Subject: [PATCH 24/28] Retire standalone proxy and unlock architecture with guarded managed cutover --- .../gen-2826-browser-proxy-https-pairing.md | 2 + docs/docker-execution-development.md | 155 +--- docs/fly-guest-transport.md | 78 +- package-lock.json | 8 - packages/api-client/src/schema.d.ts | 375 ++-------- .../0051_model_device_authorizations.sql | 13 + .../0052_retire_credential_proxy.sql | 34 + .../scripts/prepare-credential-cutover.mjs | 46 ++ packages/api/src/api-contract.ts | 41 +- packages/api/src/docker-execution-host.ts | 65 -- .../api/src/docker-job-execution-backend.ts | 20 - packages/api/src/exe-run-proxy.ts | 126 ---- packages/api/src/exe-vm-backend.ts | 40 +- packages/api/src/execution.ts | 4 +- packages/api/src/flow-service.ts | 180 ++--- .../src/fly-credential-proxy-provisioner.ts | 210 ------ packages/api/src/fly-guest-transport.ts | 126 ---- packages/api/src/fly-job-execution-backend.ts | 8 +- packages/api/src/fly-job-tunnel-helper.ts | 58 -- .../api/src/machine-job-execution-backend.ts | 55 +- packages/api/src/managed-model-credentials.ts | 7 +- packages/api/src/model-device-auth.ts | 88 +++ .../api/src/postgres/credential-repository.ts | 160 ++++ .../encrypted-integration-repository.ts | 399 ---------- .../src/postgres/proxy-control-repository.ts | 93 --- .../src/postgres/run-enrollment-repository.ts | 115 --- .../src/postgres/run-retention-repository.ts | 27 +- packages/api/src/postgres/schema.ts | 21 +- packages/api/src/proxy-browser-capability.ts | 46 -- packages/api/src/proxy-control.ts | 186 ----- packages/api/src/proxy-launch-policy.ts | 61 -- packages/api/src/proxy-provisioner.ts | 40 - packages/api/src/run-credential-launch.ts | 4 +- packages/api/src/run-credentials.ts | 55 -- packages/api/src/run-enrollment-service.ts | 22 - packages/api/src/run-outbound-proxy.ts | 4 +- packages/api/src/types.ts | 8 +- packages/api/test/api-boundary.test.ts | 8 - .../test/credential-cutover.postgres.test.ts | 37 + packages/api/test/docker-code-job.e2e.test.ts | 303 ++++---- .../docker-job-infrastructure.e2e.test.ts | 2 +- ...encrypted-integration-api.postgres.test.ts | 126 +--- ...ed-integration-repository.postgres.test.ts | 272 ++----- packages/api/test/exe-run-proxy.test.ts | 205 ------ packages/api/test/execution-backend.test.ts | 3 +- .../api/test/fixtures/Dockerfile.code-job | 2 +- .../fly-account-connection.postgres.test.ts | 2 +- .../fly-credential-proxy-provisioner.test.ts | 255 ------- packages/api/test/fly-guest-transport.test.ts | 81 --- .../test/fly-job-execution-backend.test.ts | 30 +- .../helpers}/docker-job-infrastructure.ts | 4 +- packages/api/test/loading.postgres.test.ts | 6 +- .../test/model-device-auth.postgres.test.ts | 46 ++ .../api/test/proxy-browser-capability.test.ts | 25 - .../api/test/proxy-control-repository.test.ts | 54 -- packages/api/test/proxy-control.test.ts | 226 ------ packages/api/test/proxy-launch-policy.test.ts | 42 -- .../proxy-management-authorization.test.ts | 55 -- packages/api/test/proxy-provisioner.test.ts | 47 -- .../run-credential-repair.postgres.test.ts | 4 +- packages/api/test/run-credentials.test.ts | 39 - .../api/test/run-enrollment.postgres.test.ts | 99 --- packages/api/test/run-scopes.postgres.test.ts | 17 +- packages/api/test/run-vendor-launch.test.ts | 2 +- packages/api/test/runtime-context.test.ts | 27 +- .../api/test/trace-source.postgres.test.ts | 22 - .../api/test/vendor-run-auth.postgres.test.ts | 10 +- packages/app/src/features/jobs/editor.tsx | 16 +- .../src/features/settings/integrations.tsx | 3 +- .../src/features/settings/model-accounts.tsx | 196 ++--- .../features/settings/unlock-key-setup.tsx | 72 -- packages/app/src/lib/unlock-crypto.ts | 162 ----- packages/app/src/lib/unlock-key.ts | 78 -- .../test/functional/unlock-crypto.spec.mjs | 49 -- packages/app/test/settings.browser.test.mjs | 300 +------- packages/app/test/unlock-crypto.test.mjs | 91 --- packages/credential-proxy/Dockerfile | 35 - .../credential-proxy/image/package-lock.json | 137 ---- packages/credential-proxy/image/package.json | 8 - packages/credential-proxy/package.json | 19 - .../credential-proxy/src/authorize-run.mjs | 52 -- .../credential-proxy/src/bearer-forwarder.mjs | 180 ----- .../src/bootstrap-control.mjs | 110 --- .../credential-proxy/src/browser-control.mjs | 190 ----- .../src/codex-auth-helper.mjs | 163 ----- .../credential-proxy/src/control-client.mjs | 299 -------- .../credential-proxy/src/decrypted-grants.mjs | 181 ----- .../src/destination-policy.mjs | 181 ----- packages/credential-proxy/src/main.mjs | 196 ----- .../src/model-account-crypto.mjs | 61 -- .../src/model-account-lifecycle.mjs | 300 -------- .../credential-proxy/src/proxy-listener.mjs | 245 ------- .../src/run-credential-store.mjs | 32 - packages/credential-proxy/src/runtime.mjs | 205 ------ packages/credential-proxy/src/startup.mjs | 46 -- .../credential-proxy/src/tls-identity.mjs | 87 --- .../credential-proxy/src/tunnel-transport.mjs | 232 ------ .../credential-proxy/src/vm-certificate.mjs | 61 -- .../test/bearer-forwarder.test.mjs | 79 -- .../test/bootstrap-control.test.mjs | 97 --- .../test/browser-control.test.mjs | 104 --- .../test/codex-auth-helper.test.mjs | 87 --- .../test/control-client.test.mjs | 226 ------ .../test/decrypted-grants.test.mjs | 113 --- .../test/destination-policy.test.mjs | 131 ---- .../test/fixtures/proxy-cert.pem | 19 - .../test/fixtures/upstream-cert.pem | 20 - .../test/fixtures/upstream-key.pem | 28 - .../test/fly-guest-helper.e2e.test.mjs | 326 --------- .../test/model-account-crypto.test.mjs | 37 - .../test/model-account-lifecycle.test.mjs | 333 --------- .../test/proxy-listener.e2e.test.mjs | 685 ----------------- .../test/run-credential-store.test.mjs | 34 - .../test/runtime-process.test.mjs | 109 --- .../test/runtime-revocation.test.mjs | 336 --------- .../test/tls-identity.test.mjs | 50 -- packages/docs/openapi.yaml | 687 ++++-------------- .../docs/self-hosting/credential-cutover.mdx | 102 +-- scripts/build-credential-proxy-image.sh | 34 - scripts/docker-execution-e2e.mjs | 6 +- scripts/validation.mjs | 4 +- 121 files changed, 1162 insertions(+), 11503 deletions(-) create mode 100644 packages/api/migrations/0051_model_device_authorizations.sql create mode 100644 packages/api/migrations/0052_retire_credential_proxy.sql create mode 100644 packages/api/scripts/prepare-credential-cutover.mjs delete mode 100644 packages/api/src/docker-execution-host.ts delete mode 100644 packages/api/src/docker-job-execution-backend.ts delete mode 100644 packages/api/src/exe-run-proxy.ts delete mode 100644 packages/api/src/fly-credential-proxy-provisioner.ts delete mode 100644 packages/api/src/fly-guest-transport.ts delete mode 100644 packages/api/src/fly-job-tunnel-helper.ts create mode 100644 packages/api/src/model-device-auth.ts create mode 100644 packages/api/src/postgres/credential-repository.ts delete mode 100644 packages/api/src/postgres/encrypted-integration-repository.ts delete mode 100644 packages/api/src/postgres/proxy-control-repository.ts delete mode 100644 packages/api/src/postgres/run-enrollment-repository.ts delete mode 100644 packages/api/src/proxy-browser-capability.ts delete mode 100644 packages/api/src/proxy-control.ts delete mode 100644 packages/api/src/proxy-launch-policy.ts delete mode 100644 packages/api/src/proxy-provisioner.ts delete mode 100644 packages/api/src/run-credentials.ts delete mode 100644 packages/api/src/run-enrollment-service.ts create mode 100644 packages/api/test/credential-cutover.postgres.test.ts delete mode 100644 packages/api/test/exe-run-proxy.test.ts delete mode 100644 packages/api/test/fly-credential-proxy-provisioner.test.ts delete mode 100644 packages/api/test/fly-guest-transport.test.ts rename packages/api/{src => test/helpers}/docker-job-infrastructure.ts (95%) create mode 100644 packages/api/test/model-device-auth.postgres.test.ts delete mode 100644 packages/api/test/proxy-browser-capability.test.ts delete mode 100644 packages/api/test/proxy-control-repository.test.ts delete mode 100644 packages/api/test/proxy-control.test.ts delete mode 100644 packages/api/test/proxy-launch-policy.test.ts delete mode 100644 packages/api/test/proxy-management-authorization.test.ts delete mode 100644 packages/api/test/proxy-provisioner.test.ts delete mode 100644 packages/api/test/run-credentials.test.ts delete mode 100644 packages/api/test/run-enrollment.postgres.test.ts delete mode 100644 packages/app/src/features/settings/unlock-key-setup.tsx delete mode 100644 packages/app/src/lib/unlock-crypto.ts delete mode 100644 packages/app/src/lib/unlock-key.ts delete mode 100644 packages/app/test/functional/unlock-crypto.spec.mjs delete mode 100644 packages/app/test/unlock-crypto.test.mjs delete mode 100644 packages/credential-proxy/Dockerfile delete mode 100644 packages/credential-proxy/image/package-lock.json delete mode 100644 packages/credential-proxy/image/package.json delete mode 100644 packages/credential-proxy/package.json delete mode 100644 packages/credential-proxy/src/authorize-run.mjs delete mode 100644 packages/credential-proxy/src/bearer-forwarder.mjs delete mode 100644 packages/credential-proxy/src/bootstrap-control.mjs delete mode 100644 packages/credential-proxy/src/browser-control.mjs delete mode 100644 packages/credential-proxy/src/codex-auth-helper.mjs delete mode 100644 packages/credential-proxy/src/control-client.mjs delete mode 100644 packages/credential-proxy/src/decrypted-grants.mjs delete mode 100644 packages/credential-proxy/src/destination-policy.mjs delete mode 100644 packages/credential-proxy/src/main.mjs delete mode 100644 packages/credential-proxy/src/model-account-crypto.mjs delete mode 100644 packages/credential-proxy/src/model-account-lifecycle.mjs delete mode 100644 packages/credential-proxy/src/proxy-listener.mjs delete mode 100644 packages/credential-proxy/src/run-credential-store.mjs delete mode 100644 packages/credential-proxy/src/runtime.mjs delete mode 100644 packages/credential-proxy/src/startup.mjs delete mode 100644 packages/credential-proxy/src/tls-identity.mjs delete mode 100644 packages/credential-proxy/src/tunnel-transport.mjs delete mode 100644 packages/credential-proxy/src/vm-certificate.mjs delete mode 100644 packages/credential-proxy/test/bearer-forwarder.test.mjs delete mode 100644 packages/credential-proxy/test/bootstrap-control.test.mjs delete mode 100644 packages/credential-proxy/test/browser-control.test.mjs delete mode 100644 packages/credential-proxy/test/codex-auth-helper.test.mjs delete mode 100644 packages/credential-proxy/test/control-client.test.mjs delete mode 100644 packages/credential-proxy/test/decrypted-grants.test.mjs delete mode 100644 packages/credential-proxy/test/destination-policy.test.mjs delete mode 100644 packages/credential-proxy/test/fixtures/proxy-cert.pem delete mode 100644 packages/credential-proxy/test/fixtures/upstream-cert.pem delete mode 100644 packages/credential-proxy/test/fixtures/upstream-key.pem delete mode 100644 packages/credential-proxy/test/fly-guest-helper.e2e.test.mjs delete mode 100644 packages/credential-proxy/test/model-account-crypto.test.mjs delete mode 100644 packages/credential-proxy/test/model-account-lifecycle.test.mjs delete mode 100644 packages/credential-proxy/test/proxy-listener.e2e.test.mjs delete mode 100644 packages/credential-proxy/test/run-credential-store.test.mjs delete mode 100644 packages/credential-proxy/test/runtime-process.test.mjs delete mode 100644 packages/credential-proxy/test/runtime-revocation.test.mjs delete mode 100644 packages/credential-proxy/test/tls-identity.test.mjs delete mode 100755 scripts/build-credential-proxy-image.sh diff --git a/docs/decisions/gen-2826-browser-proxy-https-pairing.md b/docs/decisions/gen-2826-browser-proxy-https-pairing.md index 99f4b7d1..f82dab7f 100644 --- a/docs/decisions/gen-2826-browser-proxy-https-pairing.md +++ b/docs/decisions/gen-2826-browser-proxy-https-pairing.md @@ -1,3 +1,5 @@ +> Superseded by GEN-2922. The standalone proxy and browser pairing described below are retired; see the credential cutover runbook. + # GEN-2826: Browser to credential proxy HTTPS and identity pairing ## Decision diff --git a/docs/docker-execution-development.md b/docs/docker-execution-development.md index 7e9edd92..5aba3743 100644 --- a/docs/docker-execution-development.md +++ b/docs/docker-execution-development.md @@ -1,130 +1,25 @@ -# Local Docker execution and credential-proxy E2E - -Docker is a test-only execution infrastructure adapter. Application jobs select -`executionConfigId: "docker"` only when the local API has an explicit -`TEST_DOCKER_EXECUTION` configuration. Deployed Workers do not configure it, -do not list Docker, and reject that selection. Docker supports code jobs only. - -## Prerequisites and commands - -Use Node 24.12.0 and npm 11.19.0, PostgreSQL, Chromium and Docker with Linux -container/bridge-network permissions. For an exe.dev VM use the pinned validation -runner described in [factorize-validation-runner.md](factorize-validation-runner.md). -Docker is an additional host prerequisite: verify `docker info` succeeds. Missing -prerequisites fail validation rather than skipping coverage. - -```sh -npm ci -npm run bootstrap:test -# Export DATABASE_URL, AUTH_TEST_DATABASE_URL and QUEUE_TEST_DATABASE_URL printed above. -npm run test:docker -npm test -``` - -The focused command builds the deployable credential-proxy Dockerfile and a small -code-job fixture image with cached Docker layers. Initial builds require registry -and Debian/npm download access; subsequent runs reuse layers. No image publication, -Fly token, model account or external API credential is needed. The command resolves -locally built images to immutable Docker image IDs and uses those exact IDs for -provisioning. Keep several GiB free for images/build cache. - -For a separate local PostgreSQL container, bind its port to loopback and supply -`VALIDATION_DATABASE_URL` and `VALIDATION_DATABASE_ADMIN_URL` to bootstrap. Include -`?sslmode=disable` for a local server without TLS. Both URLs must use localhost or -127.0.0.1; never use a shared or production database. - -For example, this creates a separate local PostgreSQL instance without changing -an existing VM service: - -```sh -docker run -d --name factorize-validation-postgres \ - -e POSTGRES_PASSWORD=local-validation-only -p 127.0.0.1::5432 postgres:16-alpine -for attempt in $(seq 1 30); do - docker exec factorize-validation-postgres pg_isready -U postgres && break - sleep 1 -done -factorize_pg_port="$(docker inspect --format '{{(index (index .NetworkSettings.Ports "5432/tcp") 0).HostPort}}' factorize-validation-postgres)" -export VALIDATION_DATABASE_URL="postgresql://postgres:local-validation-only@127.0.0.1:${factorize_pg_port}/factorize_validation?sslmode=disable" -export VALIDATION_DATABASE_ADMIN_URL="postgresql://postgres:local-validation-only@127.0.0.1:${factorize_pg_port}/postgres?sslmode=disable" -npm run bootstrap:test -# Export the three variables printed by bootstrap, then run npm test or npm run test:docker. -# When finished with this isolated helper: -# docker rm -f factorize-validation-postgres -``` - -The complete scenario has a 120-second test deadline after image preparation; -the host subprocess also has a deadline. Root validation includes this command -and allows 760 seconds for the complete suite. - -## Shared host boundary - -`MachineJobExecutionBackend` implements reservation/recovery, launch sequencing, -run-credential delivery, guest-generated keys/CSR enrollment, shared launcher and -mTLS tunnel installation, result/log/file collection and shutdown. The Fly wrapper -retains existing Fly handles and identities. Docker implements container lifecycle, -operation labels, private stdin execution and bounded file transfer. Host Docker -access is never mounted into the proxy or job. - -`createLocalExecutionRunner` drives the real PostgreSQL scheduler in Node, with a -public provider factory used consistently for launch, polling and cleanup. -`createLocalArtifactStorage` supplies local artifact persistence. The local HTTPS -server passes requests to the application's real Fetch handler. The E2E provides -only Node replacements for unavailable Cloudflare platform classes; it does not -mock backend or scheduler methods. Production Fly execution-host deployment is -outside this issue's scope. - -The owner-session `/api/v1/credential-proxy/setup` operation calls the configured -execution host and completes real proxy registration. Browser capabilities for -unlock/lock/apply/status are one-use, valid for 60 seconds and bound to owner, -action, application origin and proxy boot. Unlock keys go directly to the proxy, -which verifies the current encrypted generation before admitting access. Factorize -never accepts plaintext unlock keys through these application endpoints. - -## Evidence and limits - -The scenario creates its own migrated database, owner identity, HTTPS CA and -synthetic credentials. Jobs, encrypted integrations, verification records, grants -and runs are created/updated through authenticated application APIs. Provisioning -uses the shared one-use bootstrap and real control/enrollment endpoints. - -The job and fake API occupy separate networks; only the proxy joins both. The fake -API has no published port. Saved code proves direct TCP access fails and proxy -access succeeds, discovers its granted integration, validates a unique response, -and writes a correlated structured result and output. Independent fixture receipts -verify the injected bearer credential, method, path and body. Locked access and a -saved but ungranted integration produce no additional upstream receipt. - -Container inspection, observed guest stdin, installed files, logs and stored -artifacts are checked for upstream/run credential leakage. Results/logs are -persisted and the scheduler destroys the job container before the teardown's -cleanup runs. The built proxy image exercises its actual entry points, OpenSSL, -writable runtime directories and memory-backed TLS storage; it stays healthy -beyond the former two-second startup deadline and shuts down normally. - -The test-only exact-origin transport requires NODE_ENV=test plus an explicit test -configuration. It pins the fixture IP, origin and CA while retaining TLS hostname -and certificate verification. Production destination policy continues to reject -private IPs. This does not validate live Fly authentication, networking or exec/SFTP. - -## Cleanup and recovery - -The command uses unique `fz-*` namespaces, ephemeral ports and isolated -`docker_e2e_*` databases. Both fixture teardown and outer process cleanup cover -failures/signals. After a hard host termination, inspect: - -```sh -docker ps -a --filter label=sh.factorize.test.namespace -docker network ls --filter name=fz- -``` - -Remove only containers/networks whose labels/names match the interrupted run. -Stop its runner before dropping its exact `docker_e2e_*` database. Cached test -images remain deliberately for reuse; remove only the Factorize test image tags -or their known build-cache entries when reclaiming space. - -The narrower infrastructure check remains available: - -```sh -docker pull alpine:3.22 -npm exec --workspace=factorize -- vitest run --config scripts/docker-infrastructure.config.ts -``` +# Local Docker execution validation + +Use the pinned Factorize validation runner documented in +[factorize-validation-runner.md](factorize-validation-runner.md). Run `npm ci`, +then `npm run test:local` for the required complete suite. For focused iteration, +bootstrap the isolated local database and run `npm run test:docker` with the +printed variables. Remote/shared databases are refused. + +The Docker lane builds only the isolated code-job fixture image. It executes a +saved job through the real API, scheduler, Fly lifecycle backend, job launcher, +localhost identity helper, signed JWT verifier, selected backend egress, +artifact persistence and provider cleanup. A test-local Unix-socket issuer +supplies synthetic Fly-shaped JWTs and fixture JWKS. This is deterministic +protocol evidence, not live Fly identity evidence. No production verifier +fallback or fixture key is installed by application code. + +The test also checks an unselected credential, permanent disconnect revocation, +credential-free guest configuration, stored results and cleanup after artifact +collection. Docker resource labels, isolated database names, bounded process +trees and independent fallback cleanup keep failures local to this invocation. +The separate infrastructure test covers idempotent creation and guest transport. + +The standalone proxy image and owner proxy/unlock setup API have been removed. +`TEST_DOCKER_EXECUTION` exposes only an explicitly enabled test execution target; +production execution uses documented exe.dev or Fly identity and provisioning. diff --git a/docs/fly-guest-transport.md b/docs/fly-guest-transport.md index d2910d50..d3f585ad 100644 --- a/docs/fly-guest-transport.md +++ b/docs/fly-guest-transport.md @@ -1,60 +1,18 @@ -# Fly guest command and file transport - -`createFlyGuestTransport` in `packages/api/src/fly-guest-transport.ts` uses the documented `fly machine exec` and `fly sftp put/get` commands. It starts Fly CLI directly with an argument vector; guest command arguments and paths are never interpolated into a shell command. The Fly API token is supplied through the CLI's `FLY_API_TOKEN` environment variable and is not included in arguments, results, or transport errors. - -The execution host must have a supported `fly` CLI installed and access to the selected Fly app and Machine. The token must authorize Machine execution and SFTP access. Machines must be running. The guest image must support Fly's Machine exec and SFTP paths; images do not need exe.dev's SSH tooling or systemd. `run()` accepts a nonempty executable and argv plus optional stdin bytes, returns captured stdout/stderr and the process exit code, and enforces a deadline of at most ten minutes and a combined output cap of at most 16 MiB. File operations enforce a configurable transfer cap of at most 64 MiB and use normalized absolute guest paths. Timed out operations terminate the CLI process group. - -Both execution backends install and invoke the same small `factorize-job` guest launcher as `exedev`. It requires Python 3, the `exedev` account, and a writable `/home/exedev/.factorize-job` directory. It accepts a bounded JSON launch payload over stdin, starts the code script or agent argv without a shell command assembled from the payload, writes structured process state, preserves stdout/stderr and the run result, and exposes `factorize-job status` for Fly scheduler polling. Fly images also need `runuser`, `/bin/sh`, `/usr/local/bin`, Node.js and OpenSSL for portable proxy access, and the provider's documented Machine exec/SFTP support. Codex images must provide the tested `codex-cli 0.167.1`; Fly checks this as the `exedev` user before launch and returns a bounded failure for a missing or unsupported version. Code jobs do not require Codex. Image verification checks Python 3 for exe.dev execution; Fly reports a bounded launch failure when guest prerequisites are absent. The helper and job Machine are not configured to restart and replay a failed process. Custom entrypoints can finish their own setup before the backend invokes the launcher. - -The local protocol fixtures verify process result handling, timeout, output overflow, disconnect, safe argv construction, and file byte transfer. They do not validate live Fly authentication, Fly CLI compatibility, routing to a real Machine, or the guest's exec/SFTP capabilities. A separate opt-in validation requires a Fly account, an authorized app/Machine and token, an installed Fly CLI, and a custom image with Fly exec/SFTP support; no Fly network call is part of the required test suite. - -For portable integrations, the scheduler sends the scoped run credential over Fly's authenticated Machine exec channel directly to the dedicated credential proxy's private Unix socket. The proxy keeps it in process memory, bound to that run and provider VM identity, and removes it when durable revocation arrives. The credential is not part of Machine configuration, launch files, or the job VM payload. During guest launch, the VM generates its own private key and CSR; the proxy signs the CSR for the provider VM identity, and only the certificate and trust bundle return to the scheduler for installation. An internal-only Fly service exposes the proxy tunnel listener on port 9090. The guest starts a loopback CONNECT forwarder and sets HTTP(S)_PROXY for the job process. Each tunnel connection presents only its run ID over mTLS; the proxy retrieves its in-memory credential to perform fresh control-plane enrollment. - -## Credential-proxy package and local evidence - -`packages/credential-proxy` is a private npm workspace of native ES modules and -uses Node.js built-ins at runtime. Its package entry points are declared in -`package.json`; only `src/` is included in the package artifact, excluding the -test suite's synthetic TLS keys and fixtures. The Fly VM tunnel helper is generated from -`packages/api/src/fly-job-tunnel-helper.ts`. After `npm ci`, inspect the local -package contents without publishing with: - -```sh -npm pack --dry-run --workspace=@factorize/credential-proxy --json -npm run test:proxy -``` - -The provisioner accepts only an image pinned by digest and equal to the reviewed -image supplied by deployment configuration. Proxy control credentials enter -through the private bootstrap socket; run credentials enter through Fly's -authenticated Machine exec channel and remain in proxy memory. Neither user -unlock keys nor integration credentials belong in image build arguments, image -configuration, guest environment variables, or launch payloads. - -The minimal credential-proxy OCI recipe is `packages/credential-proxy/Dockerfile`. -It pins the Node 24.12.0 multi-platform manifest digest, installs the -authentication-only Codex CLI 0.167.1 from a checked-in lockfile, copies only -proxy runtime source, and runs as the unprivileged `node` user. Build locally -without publishing using `scripts/build-credential-proxy-image.sh`; Docker -Buildx emits an OCI archive with max-mode provenance and an SBOM under -`~/.factorize-job/credential-proxy-image/`, alongside a compact JSON summary -binding the archive digest to the source commit, base digest, and Codex version. -The OCI archive and generated provenance are inspectable/rebuildable artifacts; -this repository deliberately has no publishing workflow, and this local recipe -does not establish that any production digest has been published or approved. -The provisioner's reviewed-digest configuration must still be updated through -the separate release process after image review. Live Fly networking also -remains unverified. - -Local coverage is split across fixtures to avoid repeating full application -startup: `packages/credential-proxy/test/fly-guest-helper.e2e.test.mjs` executes -the generated guest helper against an mTLS proxy and local HTTPS upstream and -rejects a mismatched VM binding; `proxy-listener.e2e.test.mjs` checks per-VM -reflection, locked access, configured-origin forwarding, redirect rejection, -interrupted writes, and reconnect after lock/unlock. These synthetic fixtures do -not establish live provider or production behavior. The combined -`locked scoped run reconnects with its current grant while another VM stays denied` -fixture exercises the production grant resolver with a synthetic Factorize run -snapshot and local TLS upstream. The repository runbook -`packages/docs/self-hosting/credential-proxy-security.mdx` documents key handling, lifecycle recovery, -accepted provider/control-plane risks, and the independent Fly shutdown steps. +# Fly run guest transport + +The backend uses the documented Machines HTTP exec API with an argv `command` +array and optional stdin. It does not run a Fly CLI or SSH agent in the Worker. +`packages/api/src/fly-http-guest-transport.ts` handles bounded output, deadlines, +file uploads and downloads. `flyJobGuest` supplies the tenant's encrypted Fly +provisioning credential only to the Machines API; it never enters the guest. + +Machines are created with top-level region and `skip_launch: true`, then started +explicitly. Before job launch, Factorize verifies the guest's signed OIDC token +from `/.fly/api`, pins the organization-slug issuer and exact subject/Machine, +and persists the immutable run binding. The root-owned localhost identity +helper requests fresh vendor tokens and forwards API, selected credential and +artifact requests to the backend. Upstream credentials stay in Factorize. + +The former standalone credential-proxy workspace, image, certificate tunnel and +browser capabilities are removed by GEN-2922. See the credential cutover runbook +before deploying this breaking change. diff --git a/package-lock.json b/package-lock.json index b6d2b8fa..dc0bfade 100644 --- a/package-lock.json +++ b/package-lock.json @@ -2285,10 +2285,6 @@ "node": ">=18" } }, - "node_modules/@factorize/credential-proxy": { - "resolved": "packages/credential-proxy", - "link": true - }, "node_modules/@img/colour": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/@img/colour/-/colour-1.1.0.tgz", @@ -9664,10 +9660,6 @@ } } }, - "packages/credential-proxy": { - "name": "@factorize/credential-proxy", - "version": "0.1.0" - }, "packages/docs": { "name": "factorize-docs", "version": "0.1.0" diff --git a/packages/api-client/src/schema.d.ts b/packages/api-client/src/schema.d.ts index b3c582d7..999b7835 100644 --- a/packages/api-client/src/schema.d.ts +++ b/packages/api-client/src/schema.d.ts @@ -19,7 +19,7 @@ export interface paths { put?: never; /** * Create a model account - * @description Requires an interactive owner browser session and the current collection revision. Creates metadata with an empty initial state; the credential proxy establishes credentials and Factorize encrypts cache updates with its server key. + * @description Requires an interactive owner browser session and the current collection revision. Accepts an API key or Codex credential object into Factorize-managed encrypted storage, or an empty initial state for backend device authorization. Credentials are never returned. * * Requires the integrations:write scope. * @@ -40,47 +40,31 @@ export interface paths { cookie?: never; }; get?: never; - put?: never; - post?: never; /** - * Delete a model account - * @description Requires an interactive owner browser session and the current collection revision. Deletion is recorded as a tombstone so future run snapshots reject the disconnected account. + * Replace a model account credential + * @description Owner session required. Replaces the managed credential without changing the selected account ID; active runs use the replacement on their next request. * * Requires the integrations:write scope. * * An interactive owner session is required; bearer tokens cannot call this operation. */ - delete: operations["delete_api_v1_model_accounts_accountId"]; - options?: never; - head?: never; - patch?: never; - trace?: never; - }; - "/api/v1/credential-proxy/setup": { - parameters: { - query?: never; - header?: never; - path?: never; - cookie?: never; - }; - get?: never; - put?: never; + put: operations["put_api_v1_model_accounts_accountId"]; + post?: never; /** - * Provision and register the owner's credential proxy - * @description Interactive owner session required. Calls the configured execution host; bootstrap credentials cross only the private guest transport. Reuse operationId for retries. + * Delete a model account + * @description Requires an interactive owner browser session and the current collection revision. Deletion is recorded as a tombstone so future run snapshots reject the disconnected account. * * Requires the integrations:write scope. * * An interactive owner session is required; bearer tokens cannot call this operation. */ - post: operations["post_api_v1_credential_proxy_setup"]; - delete?: never; + delete: operations["delete_api_v1_model_accounts_accountId"]; options?: never; head?: never; patch?: never; trace?: never; }; - "/api/v1/credential-proxy/browser-capability": { + "/api/v1/model-accounts/{accountId}/authorization/authorize": { parameters: { query?: never; header?: never; @@ -90,21 +74,21 @@ export interface paths { get?: never; put?: never; /** - * Authorize a direct browser-to-proxy lifecycle operation - * @description Owner session only. One-use capability bound to action, owner, application origin and proxy boot, valid for 60 seconds. Unlock keys go directly to the proxy and are never accepted by this API. + * authorize backend ChatGPT device authorization + * @description Interactive owner session required. Device IDs, PKCE exchange codes and tokens remain server-side. Responses contain only a one-time user code, fixed verification URL and status. * * Requires the integrations:write scope. * * An interactive owner session is required; bearer tokens cannot call this operation. */ - post: operations["post_api_v1_credential_proxy_browser_capability"]; + post: operations["post_api_v1_model_accounts_accountId_authorization_authorize"]; delete?: never; options?: never; head?: never; patch?: never; trace?: never; }; - "/api/v1/model-accounts/{accountId}/browser-capability": { + "/api/v1/model-accounts/{accountId}/authorization/status": { parameters: { query?: never; header?: never; @@ -114,77 +98,21 @@ export interface paths { get?: never; put?: never; /** - * Issue a short-lived browser capability for a paired model account - * @description Requires an interactive owner browser session. Returns a single-use, 60-second capability scoped to the account, action, proxy boot and exact application origin. The browser sends it directly to the paired proxy; Factorize never receives model-account tokens. - * - * Requires the integrations:write scope. - * - * An interactive owner session is required; bearer tokens cannot call this operation. - */ - post: operations["post_api_v1_model_accounts_accountId_browser_capability"]; - delete?: never; - options?: never; - head?: never; - patch?: never; - trace?: never; - }; - "/api/v1/unlock-key/verification": { - parameters: { - query?: never; - header?: never; - path?: never; - cookie?: never; - }; - /** - * Get the current encrypted unlock-key verification record - * @description Requires an interactive owner browser session. Returns user-encrypted verification ciphertext and its key generation; the unlock key is never accepted or returned. - * - * Requires the integrations:read scope. - * - * An interactive owner session is required; bearer tokens cannot call this operation. - */ - get: operations["get_api_v1_unlock_key_verification"]; - put?: never; - /** - * Create the encrypted unlock-key verification record - * @description Requires an interactive owner browser session. Stores only browser-encrypted verification ciphertext and permits one setup per account. + * status backend ChatGPT device authorization + * @description Interactive owner session required. Device IDs, PKCE exchange codes and tokens remain server-side. Responses contain only a one-time user code, fixed verification URL and status. * * Requires the integrations:write scope. * * An interactive owner session is required; bearer tokens cannot call this operation. */ - post: operations["post_api_v1_unlock_key_verification"]; + post: operations["post_api_v1_model_accounts_accountId_authorization_status"]; delete?: never; options?: never; head?: never; patch?: never; trace?: never; }; - "/api/v1/unlock-key/rotation-snapshot": { - parameters: { - query?: never; - header?: never; - path?: never; - cookie?: never; - }; - /** - * Get encrypted state for owner key rotation - * @description Owner browser session only. Returns encrypted records, tombstones, and pending change history for local re-encryption; plaintext credentials and unlock keys are never returned. - * - * Requires the integrations:read scope. - * - * An interactive owner session is required; bearer tokens cannot call this operation. - */ - get: operations["get_api_v1_unlock_key_rotation_snapshot"]; - put?: never; - post?: never; - delete?: never; - options?: never; - head?: never; - patch?: never; - trace?: never; - }; - "/api/v1/unlock-key/rotation": { + "/api/v1/model-accounts/{accountId}/authorization/cancel": { parameters: { query?: never; header?: never; @@ -194,14 +122,14 @@ export interface paths { get?: never; put?: never; /** - * Atomically replace the unlock-key generation - * @description Owner browser session only. Commits a revision-checked encrypted generation and verification record, revokes grants, consumes enrollments, and locks the proxy. Fly connection and execution configuration are preserved. + * cancel backend ChatGPT device authorization + * @description Interactive owner session required. Device IDs, PKCE exchange codes and tokens remain server-side. Responses contain only a one-time user code, fixed verification URL and status. * * Requires the integrations:write scope. * * An interactive owner session is required; bearer tokens cannot call this operation. */ - post: operations["post_api_v1_unlock_key_rotation"]; + post: operations["post_api_v1_model_accounts_accountId_authorization_cancel"]; delete?: never; options?: never; head?: never; @@ -2930,6 +2858,7 @@ export interface operations { name: string; description: string | null; revision: number; + credentialConfigured: boolean; }[]; }; }; @@ -2961,8 +2890,7 @@ export interface operations { idempotencyKey: string; name: string; description: string | null; - /** @constant */ - initialState: "{}"; + initialState: string; }; }; }; @@ -2990,7 +2918,7 @@ export interface operations { 503: components["responses"]["Error503"]; }; }; - delete_api_v1_model_accounts_accountId: { + put_api_v1_model_accounts_accountId: { parameters: { query?: never; header?: never; @@ -3005,21 +2933,20 @@ export interface operations { expectedRevision: number; /** Format: uuid */ idempotencyKey: string; + name: string; + description: string | null; + initialState: string; }; }; }; responses: { - /** @description Deleted model account */ + /** @description Model account updated */ 200: { headers: { [name: string]: unknown; }; content: { "application/json": { - /** Format: uuid */ - id: string; - /** @constant */ - deleted: true; revision: number; duplicate: boolean; }; @@ -3036,72 +2963,38 @@ export interface operations { 503: components["responses"]["Error503"]; }; }; - post_api_v1_credential_proxy_setup: { + delete_api_v1_model_accounts_accountId: { parameters: { query?: never; header?: never; - path?: never; + path: { + accountId: string; + }; cookie?: never; }; requestBody: { content: { "application/json": { + expectedRevision: number; /** Format: uuid */ - operationId: string; + idempotencyKey: string; }; }; }; responses: { - /** @description Registered proxy identity */ + /** @description Deleted model account */ 200: { headers: { [name: string]: unknown; }; content: { "application/json": { - proxyIdentity: string; /** Format: uuid */ - bootEpoch: string; - }; - }; - }; - 400: components["responses"]["Error400"]; - 401: components["responses"]["Error401"]; - 403: components["responses"]["Error403"]; - 404: components["responses"]["Error404"]; - 409: components["responses"]["Error409"]; - 415: components["responses"]["Error415"]; - 429: components["responses"]["Error429"]; - 500: components["responses"]["Error500"]; - 503: components["responses"]["Error503"]; - }; - }; - post_api_v1_credential_proxy_browser_capability: { - parameters: { - query?: never; - header?: never; - path?: never; - cookie?: never; - }; - requestBody: { - content: { - "application/json": { - /** @enum {string} */ - action: "unlock" | "lock" | "apply" | "status"; - }; - }; - }; - responses: { - /** @description Proxy endpoint and one-use capability */ - 200: { - headers: { - [name: string]: unknown; - }; - content: { - "application/json": { - /** Format: uri */ - endpoint: string; - capability: string; + id: string; + /** @constant */ + deleted: true; + revision: number; + duplicate: boolean; }; }; }; @@ -3116,7 +3009,7 @@ export interface operations { 503: components["responses"]["Error503"]; }; }; - post_api_v1_model_accounts_accountId_browser_capability: { + post_api_v1_model_accounts_accountId_authorization_authorize: { parameters: { query?: never; header?: never; @@ -3127,23 +3020,23 @@ export interface operations { }; requestBody: { content: { - "application/json": { - /** @enum {string} */ - action: "authorize" | "status" | "cancel"; - }; + "application/json": Record; }; }; responses: { - /** @description Paired proxy endpoint and one-use capability */ + /** @description Device authorization state */ 200: { headers: { [name: string]: unknown; }; content: { "application/json": { - /** Format: uri */ - endpoint: string; - capability: string; + /** @enum {string} */ + state: "pending" | "authorized" | "idle" | "canceled" | "expired" | "failed" | "reauthentication-required"; + /** @constant */ + verificationUrl?: "https://auth.openai.com/codex/device"; + userCode?: string; + pollAfterSeconds?: number; }; }; }; @@ -3158,67 +3051,34 @@ export interface operations { 503: components["responses"]["Error503"]; }; }; - get_api_v1_unlock_key_verification: { + post_api_v1_model_accounts_accountId_authorization_status: { parameters: { query?: never; header?: never; - path?: never; - cookie?: never; - }; - requestBody?: never; - responses: { - /** @description Encrypted verification record or empty setup state */ - 200: { - headers: { - [name: string]: unknown; - }; - content: { - "application/json": { - ownerId: string; - verification: { - /** Format: uuid */ - generationId: string; - encryptedVerification: string; - } | null; - }; - }; + path: { + accountId: string; }; - 400: components["responses"]["Error400"]; - 401: components["responses"]["Error401"]; - 403: components["responses"]["Error403"]; - 404: components["responses"]["Error404"]; - 409: components["responses"]["Error409"]; - 429: components["responses"]["Error429"]; - 500: components["responses"]["Error500"]; - 503: components["responses"]["Error503"]; - }; - }; - post_api_v1_unlock_key_verification: { - parameters: { - query?: never; - header?: never; - path?: never; cookie?: never; }; requestBody: { content: { - "application/json": { - /** Format: uuid */ - generationId: string; - encryptedVerification: string; - }; + "application/json": Record; }; }; responses: { - /** @description Created verification record */ + /** @description Device authorization state */ 200: { headers: { [name: string]: unknown; }; content: { "application/json": { - /** Format: uuid */ - generationId: string; + /** @enum {string} */ + state: "pending" | "authorized" | "idle" | "canceled" | "expired" | "failed" | "reauthentication-required"; + /** @constant */ + verificationUrl?: "https://auth.openai.com/codex/device"; + userCode?: string; + pollAfterSeconds?: number; }; }; }; @@ -3233,127 +3093,34 @@ export interface operations { 503: components["responses"]["Error503"]; }; }; - get_api_v1_unlock_key_rotation_snapshot: { + post_api_v1_model_accounts_accountId_authorization_cancel: { parameters: { query?: never; header?: never; - path?: never; - cookie?: never; - }; - requestBody?: never; - responses: { - /** @description Encrypted rekey snapshot */ - 200: { - headers: { - [name: string]: unknown; - }; - content: { - "application/json": { - ownerId: string; - /** Format: uuid */ - generationId: string; - revision: number; - records: { - /** Format: uuid */ - id: string; - /** @enum {string} */ - kind: "bearer" | "model"; - name: string; - origin: string | null; - description: string | null; - revision: number; - encryptedPayload: string | null; - deletedAt: string | null; - }[]; - changes: { - /** Format: uuid */ - id: string; - /** @enum {string} */ - kind: "bearer" | "model"; - name: string; - origin: string | null; - description: string | null; - revision: number; - /** Format: uuid */ - idempotencyKey: string; - /** @enum {string} */ - operation: "upsert" | "delete"; - encryptedPayload: string | null; - recordRevision?: number | null; - }[]; - }; - }; + path: { + accountId: string; }; - 400: components["responses"]["Error400"]; - 401: components["responses"]["Error401"]; - 403: components["responses"]["Error403"]; - 404: components["responses"]["Error404"]; - 409: components["responses"]["Error409"]; - 429: components["responses"]["Error429"]; - 500: components["responses"]["Error500"]; - 503: components["responses"]["Error503"]; - }; - }; - post_api_v1_unlock_key_rotation: { - parameters: { - query?: never; - header?: never; - path?: never; cookie?: never; }; requestBody: { content: { - "application/json": { - /** Format: uuid */ - expectedGenerationId: string; - /** Format: uuid */ - generationId: string; - expectedRevision: number; - encryptedVerification: string; - preserveManagedModelCaches?: boolean; - records: { - /** Format: uuid */ - id: string; - /** @enum {string} */ - kind: "bearer" | "model"; - name: string; - origin: string | null; - description: string | null; - revision: number; - encryptedPayload: string | null; - deletedAt: string | null; - }[]; - changes: { - /** Format: uuid */ - id: string; - /** @enum {string} */ - kind: "bearer" | "model"; - name: string; - origin: string | null; - description: string | null; - revision: number; - /** Format: uuid */ - idempotencyKey: string; - /** @enum {string} */ - operation: "upsert" | "delete"; - encryptedPayload: string | null; - recordRevision?: number | null; - }[]; - }; + "application/json": Record; }; }; responses: { - /** @description Key generation replaced */ + /** @description Device authorization state */ 200: { headers: { [name: string]: unknown; }; content: { "application/json": { - /** Format: uuid */ - generationId: string; - revision: number; - duplicate: boolean; + /** @enum {string} */ + state: "pending" | "authorized" | "idle" | "canceled" | "expired" | "failed" | "reauthentication-required"; + /** @constant */ + verificationUrl?: "https://auth.openai.com/codex/device"; + userCode?: string; + pollAfterSeconds?: number; }; }; }; @@ -3386,6 +3153,8 @@ export interface operations { "application/json": { revision: number; integrations: { + /** @constant */ + kind?: "bearer"; /** Format: uuid */ id: string; name: string; diff --git a/packages/api/migrations/0051_model_device_authorizations.sql b/packages/api/migrations/0051_model_device_authorizations.sql new file mode 100644 index 00000000..36974e2e --- /dev/null +++ b/packages/api/migrations/0051_model_device_authorizations.sql @@ -0,0 +1,13 @@ +CREATE TABLE app.model_device_authorizations ( + tenant_id uuid NOT NULL, + account_id uuid NOT NULL, + user_id uuid NOT NULL, + session_version integer NOT NULL, + encrypted_payload text NOT NULL, + expires_at timestamptz NOT NULL, + next_poll_at timestamptz NOT NULL, + PRIMARY KEY (tenant_id,account_id), + FOREIGN KEY (tenant_id,account_id) REFERENCES app.integration_records(tenant_id,id) ON DELETE CASCADE +); +CREATE INDEX model_device_authorizations_expiry ON app.model_device_authorizations(expires_at); +INSERT INTO app.schema_migrations(version) VALUES ('0051_model_device_authorizations') ON CONFLICT DO NOTHING; diff --git a/packages/api/migrations/0052_retire_credential_proxy.sql b/packages/api/migrations/0052_retire_credential_proxy.sql new file mode 100644 index 00000000..88a4a623 --- /dev/null +++ b/packages/api/migrations/0052_retire_credential_proxy.sql @@ -0,0 +1,34 @@ +-- Breaking cutover: dispatch must remain paused through preparation/deploy. +-- Fresh installs have no data to prepare. Existing installations must run the +-- reviewed prepare-credential-cutover script after draining ALL old runs. +LOCK TABLE app.job_runs, app.integration_records IN ACCESS EXCLUSIVE MODE; +DO $$ +BEGIN + IF EXISTS (SELECT 1 FROM app.job_runs WHERE state NOT IN ('succeeded','failed','stopped')) THEN + RAISE EXCEPTION 'GEN-2922 cutover requires drained terminal runs'; + END IF; + IF EXISTS (SELECT 1 FROM app.integration_records) AND NOT EXISTS ( + SELECT 1 FROM app.schema_migrations WHERE version='gen_2922_credentials_prepared' + ) THEN + RAISE EXCEPTION 'Run prepare-credential-cutover before the GEN-2922 migration'; + END IF; + IF EXISTS (SELECT 1 FROM app.integration_records r WHERE r.updated_at > ( + SELECT applied_at FROM app.schema_migrations WHERE version='gen_2922_credentials_prepared' + )) THEN + RAISE EXCEPTION 'Credential data changed after preparation; pause writes and prepare again'; + END IF; +END $$; +DROP TABLE app.credential_run_enrollments; +DROP TABLE app.credential_run_grants; +DROP TABLE app.credential_proxy_browser_pairings; +DROP TABLE app.credential_proxy_control_credentials; +DROP TABLE app.credential_proxy_states; +DROP TABLE app.run_credentials; +DROP TABLE app.unlock_key_verifications; +DROP TABLE app.integration_generation_previous_changes; +DROP TABLE app.integration_generation_previous_records; +DROP TABLE app.integration_generation_changes; +DROP TABLE app.integration_generation_records; +DROP TABLE app.integration_generation_journal; +ALTER TABLE app.integration_collections DROP COLUMN changes_pruned_through; +INSERT INTO app.schema_migrations(version) VALUES ('0052_retire_credential_proxy') ON CONFLICT DO NOTHING; diff --git a/packages/api/scripts/prepare-credential-cutover.mjs b/packages/api/scripts/prepare-credential-cutover.mjs new file mode 100644 index 00000000..3e5034cd --- /dev/null +++ b/packages/api/scripts/prepare-credential-cutover.mjs @@ -0,0 +1,46 @@ +import pg from 'pg'; +import {webcrypto} from 'node:crypto'; + +// Run against the pre-cutover schema with dispatch AND credential writes paused. +// Default is a read-only plan. It never prints or recovers inner user secrets. +const apply=process.argv.includes('--apply'); +if(!process.env.DATABASE_URL || !process.env.CREDENTIAL_ENCRYPTION_KEY)throw new Error('DATABASE_URL and CREDENTIAL_ENCRYPTION_KEY are required'); +const client=new pg.Client({connectionString:process.env.DATABASE_URL}); +await client.connect(); +try{ + await client.query('BEGIN'); + await client.query('LOCK TABLE app.job_runs,app.jobs,app.integration_records,app.integration_changes IN ACCESS EXCLUSIVE MODE'); + const active=(await client.query("SELECT count(*)::int AS count FROM app.job_runs WHERE state NOT IN ('succeeded','failed','stopped')")).rows[0].count; + if(active)throw new Error('Drain all runs and pause dispatch before preparation'); + const key=await webcrypto.subtle.importKey('raw',Buffer.from(process.env.CREDENTIAL_ENCRYPTION_KEY,'base64'),'AES-GCM',false,['decrypt']); + const records=(await client.query('SELECT tenant_id,id,kind,encrypted_payload FROM app.integration_records WHERE deleted_at IS NULL')).rows; + const legacy=[]; + for(const record of records){ + // Decrypt only the existing Factorize envelope. Inner user ciphertext is + // classified as unavailable; the old user key is neither accepted nor used. + const [iv,body]=record.encrypted_payload.split('.'); + const plain=new TextDecoder().decode(await webcrypto.subtle.decrypt({name:'AES-GCM',iv:Buffer.from(iv,'base64')},key,Buffer.from(body,'base64'))); + const prefix=record.kind==='bearer'?'factorize-managed-bearer-v1:':'factorize-managed-model-cache-v1:'; + if(!plain.startsWith(prefix))legacy.push({tenantId:record.tenant_id,id:record.id,kind:record.kind}); + } + const proxies=(await client.query('SELECT tenant_id,proxy_identity FROM app.credential_proxy_states ORDER BY tenant_id')).rows; + const jobs=(await client.query('SELECT tenant_id,id,enabled,execution_config FROM app.jobs ORDER BY tenant_id,id')).rows.map(row=>({tenantId:row.tenant_id,id:row.id,enabled:row.enabled,portableIntegrationIds:row.execution_config.portableIntegrationIds??[],modelAccountId:row.execution_config.modelAccountId??null,requiresRepair:legacy.some(c=>c.tenantId===row.tenant_id && ((row.execution_config.portableIntegrationIds??[]).includes(c.id)||row.execution_config.modelAccountId===c.id))})); + if(apply){ + for(const job of jobs.filter(j=>j.requiresRepair))await client.query('UPDATE app.jobs SET enabled=false,updated_at=now() WHERE tenant_id=$1 AND id=$2',[job.tenantId,job.id]); + for(const record of legacy)await client.query('UPDATE app.integration_records SET encrypted_payload=NULL,deleted_at=now(),updated_at=now() WHERE tenant_id=$1 AND id=$2',[record.tenantId,record.id]); + for(const tenantId of new Set(legacy.map(r=>r.tenantId)))await client.query('UPDATE app.integration_collections SET revision=revision+1,updated_at=now() WHERE tenant_id=$1',[tenantId]); + // The removed change-feed protocol is deliberately reset at this breaking + // boundary. Managed active records are preserved, old ciphertext is erased. + await client.query('DELETE FROM app.integration_changes'); + await client.query("UPDATE app.credential_proxy_states SET disabled_at=now(),revoked_at=now()"); + await client.query("UPDATE app.credential_proxy_control_credentials SET revoked_at=now()"); + await client.query("UPDATE app.credential_run_grants SET revoked_at=now()"); + await client.query("UPDATE app.credential_run_enrollments SET consumed_at=now()"); + await client.query("INSERT INTO app.schema_migrations(version,applied_at) VALUES('gen_2922_credentials_prepared',now()) ON CONFLICT(version) DO UPDATE SET applied_at=excluded.applied_at"); + await client.query('COMMIT'); + }else await client.query('ROLLBACK'); + console.log(JSON.stringify({mode:apply?'applied':'plan',activeRuns:active,legacyCredentials:legacy,retireProxies:proxies,jobs},null,2)); +}catch{ + await client.query('ROLLBACK').catch(()=>{}); + throw new Error('Cutover preparation failed; no changes committed. Check paused dispatch, terminal runs, schema and server encryption key.'); +}finally{await client.end();} diff --git a/packages/api/src/api-contract.ts b/packages/api/src/api-contract.ts index a1f82245..328cf09b 100644 --- a/packages/api/src/api-contract.ts +++ b/packages/api/src/api-contract.ts @@ -24,6 +24,7 @@ import { vmImageVerificationResponse, } from "./flow-schemas"; import { traceReplaySchema } from "./trace-replay-schemas"; +import {modelAuthorizationState} from "./model-device-auth"; import document from "./api-document.json"; import { authInputs, authSuccess, continuationSuccess, connectionStartInput, connectionStartSuccess, connectionResumeInput, loginSuccess, sessionResponse, type AuthAction } from "./auth-api"; import { skillInput, skillUpdateInput, skillPage, skillResponse, skillJobsResponse, previewSkillInput } from "./skills"; @@ -120,34 +121,27 @@ const accessTokenBody = z.object({ expiryDays: z.union([z.literal(7), z.literal(30), z.literal(90)]), }); const bearerIntegrationMetadata = z.object({ - id: z.uuid(), name: z.string(), origin: z.string(), description: z.string().nullable(), + kind: z.literal("bearer").optional(), id: z.uuid(), name: z.string(), origin: z.string(), description: z.string().nullable(), revision: z.number().int().nonnegative(), }); const bearerIntegrationCreate = z.object({ id: z.uuid(), expectedRevision: z.number().int().nonnegative(), idempotencyKey: z.uuid(), name: z.string().trim().min(1).max(120), origin: z.string().url().max(2048), - description: z.string().max(500).nullable(), token: z.string().min(1).max(32_768), + description: z.string().max(500).nullable(), token: z.string().min(1).max(32_768).regex(/^[^\r\n]+$/).meta({writeOnly:true}), }).strict(); const bearerIntegrationUpdate = bearerIntegrationCreate.omit({ id: true }); const bearerIntegrationDelete = z.object({ expectedRevision: z.number().int().nonnegative(), idempotencyKey: z.uuid() }).strict(); const bearerIntegrationList = z.object({ revision: z.number().int().nonnegative(), integrations: z.array(bearerIntegrationMetadata) }); -const modelAccountMetadata = z.object({ id: z.uuid(), name: z.string(), description: z.string().nullable(), revision: z.number().int().nonnegative() }); +const modelAccountMetadata = z.object({ id: z.uuid(), name: z.string(), description: z.string().nullable(), revision: z.number().int().nonnegative(), credentialConfigured: z.boolean() }); const modelAccountCreate = z.object({ id: z.uuid(), expectedRevision: z.number().int().nonnegative(), idempotencyKey: z.uuid(), name: z.string().trim().min(1).max(120), description: z.string().max(500).nullable(), - initialState: z.literal("{}"), + initialState: z.string().min(1).max(65_536).refine(value=>{try {const auth=JSON.parse(value); if(!auth || typeof auth!=="object" || Array.isArray(auth)) return false; if(Object.keys(auth).length===0) return true; return typeof auth.OPENAI_API_KEY==="string" && auth.OPENAI_API_KEY.length>0 || typeof auth.tokens?.access_token==="string" && auth.tokens.access_token.length>0;} catch {return false;}}, "Enter an API key, Codex credential object, or an empty account for device authorization").meta({writeOnly:true}), }).strict(); const modelAccountDelete = z.object({ expectedRevision: z.number().int().nonnegative(), idempotencyKey: z.uuid() }).strict(); const modelAccountList = z.object({ revision: z.number().int().nonnegative(), accounts: z.array(modelAccountMetadata) }); const bearerIntegrationWriteResult = z.object({ revision: z.number().int().nonnegative(), duplicate: z.boolean() }); const bearerIntegrationDeleteResult = z.object({ id: z.uuid(), deleted: z.literal(true), revision: z.number().int().nonnegative(), duplicate: z.boolean() }); -const unlockKeyVerification = z.object({ ownerId: z.string(), verification: z.object({ generationId: z.uuid(), encryptedVerification: z.string() }).strict().nullable() }).strict(); -const unlockKeyVerificationInput = z.object({ generationId: z.uuid(), encryptedVerification: z.string().min(1).max(4096) }).strict(); -const rotationRecord = z.object({ id: z.uuid(), kind: z.enum(["bearer", "model"]), name: z.string().min(1).max(120), origin: z.string().nullable(), description: z.string().max(500).nullable(), revision: z.number().int().nonnegative(), encryptedPayload: z.string().max(65_536).nullable(), deletedAt: z.string().datetime({ offset: true }).nullable() }).strict(); -const rotationChange = z.object({ id: z.uuid(), kind: z.enum(["bearer", "model"]), name: z.string().min(1).max(120), origin: z.string().nullable(), description: z.string().max(500).nullable(), revision: z.number().int().positive(), idempotencyKey: z.uuid(), operation: z.enum(["upsert", "delete"]), encryptedPayload: z.string().max(65_536).nullable(), recordRevision: z.number().int().positive().nullable().optional() }).strict(); -const unlockKeyRotationSnapshot = z.object({ ownerId: z.string(), generationId: z.uuid(), revision: z.number().int().nonnegative(), records: z.array(rotationRecord).max(5000), changes: z.array(rotationChange).max(10000) }).strict(); -const unlockKeyGenerationReplacement = z.object({ expectedGenerationId: z.uuid(), generationId: z.uuid(), expectedRevision: z.number().int().nonnegative(), encryptedVerification: z.string().min(1).max(4096), preserveManagedModelCaches: z.boolean().optional(), records: z.array(rotationRecord).max(5000), changes: z.array(rotationChange).max(10000) }).strict(); -const modelAccountBrowserCapabilityInput = z.object({ action: z.enum(["authorize", "status", "cancel"]) }).strict(); function route( method: string, @@ -233,35 +227,16 @@ export const API_ROUTES: RouteContract[] = [ }, service => service.listModelAccounts(), { ownerSession: true }), route("POST", "/api/v1/model-accounts", "integrations:write", { summary: "Create a model account", - description: "Requires an interactive owner browser session and the current collection revision. Creates metadata with an empty initial state; the credential proxy establishes credentials and Factorize encrypts cache updates with its server key.", + description: "Requires an interactive owner browser session and the current collection revision. Accepts an API key or Codex credential object into Factorize-managed encrypted storage, or an empty initial state for backend device authorization. Credentials are never returned.", responses: { "201": { description: "Created model account", content: { "application/json": { schema: jsonSchema(bearerIntegrationWriteResult, "output") } } } }, }, (service, { body }) => service.createModelAccount(body), { body: modelAccountCreate, maxBodyBytes: 70_000, ownerSession: true }), + route("PUT", "/api/v1/model-accounts/{accountId}", "integrations:write", {summary:"Replace a model account credential",description:"Owner session required. Replaces the managed credential without changing the selected account ID; active runs use the replacement on their next request.",responses:{"200":{description:"Model account updated",content:{"application/json":{schema:jsonSchema(bearerIntegrationWriteResult,"output")}}}}},(service,{params,body})=>service.updateModelAccount(params.accountId,body),{body:modelAccountCreate.omit({id:true}),maxBodyBytes:70_000,ownerSession:true,parameters:z.object({accountId:z.uuid()})}), + ...(["authorize","status","cancel"] as const).map(action=>route("POST",`/api/v1/model-accounts/{accountId}/authorization/${action}`,"integrations:write",{summary:`${action} backend ChatGPT device authorization`,description:"Interactive owner session required. Device IDs, PKCE exchange codes and tokens remain server-side. Responses contain only a one-time user code, fixed verification URL and status.",responses:{"200":{description:"Device authorization state",content:{"application/json":{schema:jsonSchema(modelAuthorizationState,"output")}}}}},(service,{params})=>service.modelAuthorization(params.accountId,action),{body:z.object({}).strict(),ownerSession:true,maxBodyBytes:1024,parameters:z.object({accountId:z.uuid()})})), route("DELETE", "/api/v1/model-accounts/{accountId}", "integrations:write", { summary: "Delete a model account", description: "Requires an interactive owner browser session and the current collection revision. Deletion is recorded as a tombstone so future run snapshots reject the disconnected account.", responses: { "200": { description: "Deleted model account", content: { "application/json": { schema: jsonSchema(bearerIntegrationDeleteResult, "output") } } } }, }, (service, { params, body }) => service.deleteModelAccount(params.accountId, body), { body: modelAccountDelete, maxBodyBytes: 4096, ownerSession: true, parameters: z.object({ accountId: z.uuid() }) }), - route("POST", "/api/v1/credential-proxy/setup", "integrations:write", { - summary: "Provision and register the owner's credential proxy", description: "Interactive owner session required. Calls the configured execution host; bootstrap credentials cross only the private guest transport. Reuse operationId for retries.", - responses: { "200": { description: "Registered proxy identity", content: { "application/json": { schema: jsonSchema(z.object({ proxyIdentity: z.string(), bootEpoch: z.uuid() }), "output") } } } }, - }, (service, { body }) => service.setupCredentialProxy(body.operationId), { body: z.object({ operationId: z.uuid() }).strict(), ownerSession: true, maxBodyBytes: 1024 }), - route("POST", "/api/v1/credential-proxy/browser-capability", "integrations:write", { - summary: "Authorize a direct browser-to-proxy lifecycle operation", description: "Owner session only. One-use capability bound to action, owner, application origin and proxy boot, valid for 60 seconds. Unlock keys go directly to the proxy and are never accepted by this API.", - responses: { "200": { description: "Proxy endpoint and one-use capability", content: { "application/json": { schema: jsonSchema(z.object({ endpoint: z.url(), capability: z.string() }), "output") } } } }, - }, (service, { body }) => service.issueCredentialProxyCapability(body.action), { body: z.object({ action: z.enum(["unlock", "lock", "apply", "status"]) }).strict(), ownerSession: true, maxBodyBytes: 1024 }), - route("POST", "/api/v1/model-accounts/{accountId}/browser-capability", "integrations:write", { - summary: "Issue a short-lived browser capability for a paired model account", - description: "Requires an interactive owner browser session. Returns a single-use, 60-second capability scoped to the account, action, proxy boot and exact application origin. The browser sends it directly to the paired proxy; Factorize never receives model-account tokens.", - responses: { "200": { description: "Paired proxy endpoint and one-use capability", content: { "application/json": { schema: jsonSchema(z.object({ endpoint: z.url(), capability: z.string() }), "output") } } } }, - }, (service, { params, body }) => service.issueModelAccountBrowserCapability(params.accountId, body.action), { body: modelAccountBrowserCapabilityInput, maxBodyBytes: 1024, ownerSession: true, parameters: z.object({ accountId: z.uuid() }) }), - route("GET", "/api/v1/unlock-key/verification", "integrations:read", { summary: "Get the current encrypted unlock-key verification record", description: "Requires an interactive owner browser session. Returns user-encrypted verification ciphertext and its key generation; the unlock key is never accepted or returned.", responses: { "200": { description: "Encrypted verification record or empty setup state", content: { "application/json": { schema: jsonSchema(unlockKeyVerification, "output") } } } } }, service => service.getUnlockKeyVerification(), { ownerSession: true }), - route("POST", "/api/v1/unlock-key/verification", "integrations:write", { summary: "Create the encrypted unlock-key verification record", description: "Requires an interactive owner browser session. Stores only browser-encrypted verification ciphertext and permits one setup per account.", responses: { "200": { description: "Created verification record", content: { "application/json": { schema: jsonSchema(z.object({ generationId: z.uuid() }), "output") } } } } }, (service, { body }) => service.createUnlockKeyVerification(body), { body: unlockKeyVerificationInput, maxBodyBytes: 8192, ownerSession: true }), - route("GET", "/api/v1/unlock-key/rotation-snapshot", "integrations:read", { summary: "Get encrypted state for owner key rotation", description: "Owner browser session only. Returns encrypted records, tombstones, and pending change history for local re-encryption; plaintext credentials and unlock keys are never returned.", responses: { "200": { description: "Encrypted rekey snapshot", content: { "application/json": { schema: jsonSchema(unlockKeyRotationSnapshot, "output") } } } } }, service => service.getUnlockKeyRotationSnapshot(), { ownerSession: true }), - route("POST", "/api/v1/unlock-key/rotation", "integrations:write", { - summary: "Atomically replace the unlock-key generation", - description: "Owner browser session only. Commits a revision-checked encrypted generation and verification record, revokes grants, consumes enrollments, and locks the proxy. Fly connection and execution configuration are preserved.", - responses: { "200": { description: "Key generation replaced", content: { "application/json": { schema: jsonSchema(z.object({ generationId: z.uuid(), revision: z.number().int().nonnegative(), duplicate: z.boolean() }), "output") } } } }, - }, (service, { body }) => service.replaceUnlockKeyGeneration(body), { body: unlockKeyGenerationReplacement, maxBodyBytes: 12_000_000, ownerSession: true }), route("GET", "/api/v1/integrations/bearer", "flows:read", { summary: "List bearer integration metadata", description: "Requires an interactive owner browser session. Returns secret-safe metadata only; stored bearer credentials are never returned.", diff --git a/packages/api/src/docker-execution-host.ts b/packages/api/src/docker-execution-host.ts deleted file mode 100644 index e24bc0a1..00000000 --- a/packages/api/src/docker-execution-host.ts +++ /dev/null @@ -1,65 +0,0 @@ -import { createDockerJobInfrastructure } from "./docker-job-infrastructure"; -import { createDockerJobExecutionBackend } from "./docker-job-execution-backend"; -import { createCredentialProxyGuest, createMachineCredentialProxyProvisioner } from "./fly-credential-proxy-provisioner"; -import { ProxyControlRepository } from "./postgres/proxy-control-repository"; -import type { Database } from "./postgres/database"; -import type { Env } from "./types"; -import type { RunBackendFactory } from "./postgres/run-scheduler"; - -/** Test-only host implementation. Image IDs are verified locally, without registry publication. */ -export function createDockerExecutionHost(options: { - observeJobDestruction?: (id: string) => Promise; - observeJobInput?: (command: readonly string[], input?: string | Uint8Array) => void; - testMode: true; database: Database; env: Env; namespace: string; jobNetwork: string; upstreamNetwork: string; - jobImage: string; proxyImage: string; tlsDirectory: string; upstreamOrigin: string; upstreamAddress: string; -}) { - if (options.testMode !== true || options.env.TEST_DOCKER_EXECUTION?.enabled !== true) throw new Error("Docker host requires an explicit test environment"); - for (const image of [options.proxyImage, options.jobImage]) if (!/^sha256:[a-f0-9]{64}$/.test(image)) throw new TypeError("Local images must be immutable Docker image IDs"); - const proxies = createDockerJobInfrastructure({ testMode: true, namespace: options.namespace, network: options.jobNetwork, - additionalNetworks: [options.upstreamNetwork], mounts: [{ source: options.tlsDirectory, target: "/fixture-tls" }], publishBrowserPort: true }); - const control = new ProxyControlRepository(options.database); - const provisioner = createMachineCredentialProxyProvisioner({ - control, machines: proxies.machines, - guest: machine => createCredentialProxyGuest(proxies.guest(machine.id)), reviewedImage: options.proxyImage, - infrastructure: { - kind: "docker", validateImage: image => { if (image !== options.proxyImage) throw new Error("Unreviewed proxy image"); }, - identity: machine => `docker:${options.namespace}:${machine.id}`, - browserOrigin: async machine => `https://localhost:${await proxies.browserPort(machine.id)}`, - serverName: "proxy.local", - environment: { NODE_ENV: "test", NODE_EXTRA_CA_CERTS: "/fixture-tls/ca.crt", FACTORIZE_APP_ORIGIN: options.env.APP_ORIGIN, - FACTORIZE_PROXY_TEST_MODE: "true", FACTORIZE_PROXY_BROWSER_TLS_CERT: "/fixture-tls/server.crt", FACTORIZE_PROXY_BROWSER_TLS_KEY: "/fixture-tls/server.key", - FACTORIZE_PROXY_TEST_TRANSPORT: JSON.stringify({ origin: options.upstreamOrigin, address: options.upstreamAddress, caFile: "/fixture-tls/ca.crt" }), - }, - }, - }); - const pending = new Map>(); - async function setup(tenantId: string, operationId: string) { - const existing = await control.browserPairing(tenantId); - if (existing) { - const id = existing.proxyIdentity.split(":").at(-1)!; - if ((await proxies.machines.inspectMachine(options.namespace, id)).state === "started") return { proxyIdentity: existing.proxyIdentity, bootEpoch: existing.bootEpoch }; - } - const key = tenantId; - if (!pending.has(key)) { - const started = provisioner.start({ tenantId, operationId, app: options.namespace, image: options.proxyImage, region: "iad", size: "shared-cpu-1x", - browserCapabilityPublicKey: options.env.MODEL_ACCOUNT_CAPABILITY_PUBLIC_KEY!, controlOrigin: options.env.APP_ORIGIN }).then(({ proxyIdentity, bootEpoch }) => ({ proxyIdentity, bootEpoch })); - pending.set(key, started); - void started.finally(() => pending.delete(key)).catch(() => {}); - } - return pending.get(key)!; - } - const backendFactory: RunBackendFactory = async run => { - if (run.executionConfig.executionProvider !== "docker" && run.backendKind !== "docker") return undefined; - if (run.executionConfig.executionType !== "code") throw new Error("Docker supports code jobs only"); - const pairing = await control.browserPairing(run.tenantId); - if (!pairing || !pairing.proxyIdentity.startsWith(`docker:${options.namespace}:`)) throw new Error("Docker credential proxy is not registered"); - const id = pairing.proxyIdentity.split(":").at(-1)!; - const proxy = await proxies.machines.inspectMachine(options.namespace, id); - if (proxy.state !== "started") throw new Error("Docker credential proxy is unavailable"); - // Container IP is reachable only within the job's isolated network; certificate uses proxy.local. - return createDockerJobExecutionBackend({ testMode: true, namespace: `${options.namespace}-jobs`, network: options.jobNetwork, image: options.jobImage, - beforeDestroy: options.observeJobDestruction, observeGuestInput: options.observeJobInput, proxyHost: await proxies.address(id, options.jobNetwork), proxyPort: 9090, proxyServerName: "proxy.local", proxyIdentity: pairing.proxyIdentity, proxyBootEpoch: pairing.bootEpoch, - proxyGuest: createCredentialProxyGuest(proxies.guest(id)) }); - }; - return { setup, backendFactory }; -} diff --git a/packages/api/src/docker-job-execution-backend.ts b/packages/api/src/docker-job-execution-backend.ts deleted file mode 100644 index 74b00f0d..00000000 --- a/packages/api/src/docker-job-execution-backend.ts +++ /dev/null @@ -1,20 +0,0 @@ -import { MachineJobExecutionBackend, type ProxyGuest } from "./machine-job-execution-backend"; -import { createDockerJobInfrastructure } from "./docker-job-infrastructure"; - -/** Explicit host-runner construction; Docker is never selected by production API configuration. */ -export function createDockerJobExecutionBackend(options: { - beforeDestroy?: (id: string) => Promise; - observeGuestInput?: (command: readonly string[], input?: string | Uint8Array) => void; - testMode: true; namespace: string; network: string; image: string; - proxyHost: string; proxyServerName?: string; proxyPort: number; proxyIdentity: string; proxyBootEpoch: string; proxyGuest: ProxyGuest; -}) { - const infrastructure = createDockerJobInfrastructure(options); - return new MachineJobExecutionBackend({ - kind: "docker", app: options.namespace, image: options.image, - machines: infrastructure.machines, guest: machine => infrastructure.guest(machine.id), - machineConfig: request => ({ image: options.image, metadata: { factorize_operation_id: request.runId } }), - vmIdentity: machine => `docker:${machine.id.slice(0, 32)}`, - proxyAddress: { host: options.proxyHost, port: options.proxyPort, serverName: options.proxyServerName }, - proxyIdentity: options.proxyIdentity, proxyBootEpoch: options.proxyBootEpoch, proxyGuest: options.proxyGuest, - }); -} diff --git a/packages/api/src/exe-run-proxy.ts b/packages/api/src/exe-run-proxy.ts deleted file mode 100644 index 60cb7130..00000000 --- a/packages/api/src/exe-run-proxy.ts +++ /dev/null @@ -1,126 +0,0 @@ -import type { BackendCommandResult } from "./execution"; -import { shellAtom } from "./exe"; -import { runProxyName } from "./run-credentials"; - -interface Integration { name: string; type: string; comment?: string; help?: string; target?: string; attachments?: unknown[]; } -interface ProxyPlan { name: string; runId: string; exists: boolean; } - -// The public CLI serializes time-boxed attachments as spec@RFC3339. -function attachment(value: unknown): { spec: string; expiresAt?: number } { - if (typeof value !== "string") throw new Error("Unsupported integration attachment"); - const parts = value.split("@"), spec = parts[0]; - if ((spec !== "auto:all" && !/^(?:vm|tag):[A-Za-z0-9._:-]+$/.test(spec)) || parts.length > 2) throw new Error("Unsupported integration attachment"); - if (parts.length === 1) return { spec }; - if (!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/.test(parts[1])) throw new Error("Unsupported integration attachment expiry"); - const expiresAt = Date.parse(parts[1]); - if (!Number.isFinite(expiresAt)) throw new Error("Unsupported integration attachment expiry"); - return { spec, expiresAt }; -} - -/** All credential-bearing commands go to the exe.dev control plane, never SSH. */ -export class ExeRunProxy { - constructor(private execute: (command: string) => Promise) {} - - private async inventory(): Promise { - const result = await this.execute("integrations list --json"); - if (!result.ok) throw new Error("Run proxy inventory is unavailable; check the exe.dev integrations list permission"); - let parsed: any; - try { parsed = JSON.parse(result.body); } catch { throw new Error("Run proxy inventory is invalid"); } - const items = Array.isArray(parsed) ? parsed : parsed.integrations; - if (!Array.isArray(items) || items.some(item => !item || typeof item.name !== "string" || typeof item.type !== "string")) throw new Error("Run proxy inventory is invalid"); - return items; - } - - private owned(integration: Integration, runId: string) { - return integration.name === runProxyName(runId) && integration.type === "http-proxy" && integration.comment === `Factorize run ${runId}`; - } - - async prepare(runId: string): Promise { - const name = runProxyName(runId), existing = (await this.inventory()).find(item => item.name === name); - if (existing && !this.owned(existing, runId)) throw new Error("Run proxy name is already owned by another integration; refusing to change it"); - return { name, runId, exists: Boolean(existing) }; - } - - async provision(plan: ProxyPlan, vm: string, targetOrigin: string, credential: string): Promise { - const target = new URL(targetOrigin); - if (target.protocol !== "https:" || target.origin !== targetOrigin) throw new Error("Run proxy target must be an HTTPS origin"); - // Retry by replacing only our marked integration. Recheck ownership before - // deletion; the inventory may have changed since prepare. This uses the - // add/remove permissions exposed by exe.dev's token picker. - if (plan.exists) await this.remove(plan.name, plan.runId); - const command = `integrations add http-proxy --name=${shellAtom(plan.name)} --target=${shellAtom(targetOrigin)} --bearer=${shellAtom(credential)} --comment=${shellAtom(`Factorize run ${plan.runId}`)}`; - // Never include provider responses, exception messages, or command text in - // errors: an upstream error can echo the bearer credential being installed. - let installed: BackendCommandResult; - try { installed = await this.execute(command); } - catch { throw new Error("Run proxy provisioning was interrupted; reconciliation and cleanup are required"); } - if (!installed.ok) throw new Error(`Run proxy provisioning failed (HTTP ${installed.status}); check exe.dev integrations add permission`); - const attached = await this.execute(`integrations attach ${shellAtom(plan.name)} ${shellAtom(`vm:${vm}`)} --for=24h`); - if (!attached.ok) throw new Error("Run proxy attachment failed; check the exe.dev integrations attach permission"); - } - - private async guestJson(vm: string, url: string): Promise { - const result = await this.execute(`ssh ${shellAtom(vm)} ${shellAtom(`curl --silent --show-error --max-time 10 --max-filesize 65536 ${shellAtom(url)}`)}`); - if (!result.ok) throw new Error("Run proxy preflight could not contact an attached integration"); - try { return JSON.parse(result.body); } catch { return null; } - } - - private async checkIsolation(vm: string, runId: string, targetOrigin: string, tags: string[], requireOwn: boolean): Promise { - const integrations = (await this.inventory()).filter(item => { - if (item.type !== "http-proxy" || !item.target) return false; - try { return new URL(item.target).origin === targetOrigin; } catch { return false; } - }); - const name = runProxyName(runId), own = integrations.find(item => item.name === name); - if (own) { - if (!this.owned(own, runId) || !Array.isArray(own.attachments)) throw new Error("The run proxy ownership and attachments could not be verified"); - for (const value of own.attachments) { - const grant = attachment(value); - if ((grant.expiresAt === undefined || grant.expiresAt > Date.now()) && grant.spec !== `vm:${vm}`) throw new Error("The run proxy must be attached only to its execution VM"); - } - } - if (requireOwn) { - if (!own || !this.owned(own, runId) || !Array.isArray(own.attachments) || own.attachments.length !== 1) throw new Error("The run proxy must be attached only to its execution VM"); - const grant = attachment(own.attachments[0]); - if (grant.spec !== `vm:${vm}` || !grant.expiresAt || grant.expiresAt <= Date.now() || grant.expiresAt > Date.now() + 24 * 60 * 60_000 + 60_000) throw new Error("The run proxy requires a live VM-specific attachment of at most 24 hours"); - } - // Enforce isolation from control-plane attachments, not guest-reported - // metadata or a model's choice to include an optional identity header. - for (const integration of integrations.filter(item => item.name !== name)) { - if (!Array.isArray(integration.attachments)) throw new Error(`Cannot verify attachments for Factorize integration ${integration.name}`); - const attached = integration.attachments.some(value => { - const grant = attachment(value); - if (grant.expiresAt !== undefined && grant.expiresAt <= Date.now()) return false; - return grant.spec === "auto:all" || grant.spec === `vm:${vm}` || tags.some(tag => grant.spec === `tag:${tag}`); - }); - if (attached) throw new Error(`Unsafe shared Factorize integration ${integration.name} is attached to this execution VM. Restrict it to operator-only VM attachments before retrying`); - } - } - - async assertIsolated(vm: string, runId: string, targetOrigin: string, tags: string[] = []): Promise { - await this.checkIsolation(vm, runId, targetOrigin, tags, false); - } - - async verify(vm: string, runId: string, targetOrigin: string, tags: string[] = []): Promise { - await this.checkIsolation(vm, runId, targetOrigin, tags, true); - const name = runProxyName(runId); - const reflection = await this.guestJson(vm, "https://reflection.int.exe.xyz/integrations"); - if (!Array.isArray(reflection?.integrations)) throw new Error("Reflection integrations are unavailable during run proxy preflight"); - const proxy: Integration | undefined = reflection.integrations.find((item: Integration) => item.name === name && item.type === "http-proxy"); - if (!proxy) throw new Error("The run-specific Factorize proxy is missing from Reflection"); - const address = proxy.help?.match(/https:\/\/[^\s'"<>]+/)?.[0]; - if (!address) throw new Error("Reflection must publish the run proxy URL"); - const url = new URL(address); - if (url.protocol !== "https:" || url.hostname !== `${name}.int.exe.xyz`) throw new Error("Reflection returned an unexpected run proxy URL"); - const context = await this.guestJson(vm, `${url.origin}/api/v1/runtime-context`); - if (context?.kind !== "factorize-runtime-context-v1" || context.authMethod !== "run_token" || context.runId !== runId || !Array.isArray(context.scopes)) throw new Error("The run proxy identity could not be verified"); - } - - async remove(name: string, runId: string): Promise { - if (name !== runProxyName(runId)) throw new Error("Refusing to remove an unrelated run proxy"); - const existing = (await this.inventory()).find(item => item.name === name); - if (!existing) return; - if (!this.owned(existing, runId)) throw new Error("Run proxy ownership marker does not match; refusing deletion"); - const result = await this.execute(`integrations remove ${shellAtom(name)}`); - if (!result.ok && result.status !== 404) throw new Error("Run proxy cleanup failed; check the exe.dev integrations remove permission"); - } -} diff --git a/packages/api/src/exe-vm-backend.ts b/packages/api/src/exe-vm-backend.ts index 5af2efab..edd3d2de 100644 --- a/packages/api/src/exe-vm-backend.ts +++ b/packages/api/src/exe-vm-backend.ts @@ -9,8 +9,6 @@ import { traceChunkCommand } from "./guest-artifact-commands"; import { runArtifactTarget } from "./run-artifact-target"; import { assertExeVmIsolation } from "./exe-vm-isolation"; import { RUN_IDENTITY_GUEST_HELPER } from "./run-identity-guest-helper"; -import { ExeRunProxy } from "./exe-run-proxy"; -import { runProxyName } from "./run-credentials"; import { FACTORIZE_JOB_LAUNCHER } from "./factorize-job-launcher"; const API = "https://exe.dev/exec"; @@ -67,7 +65,7 @@ export class ExeVmBackend implements ExecutionBackend { private readonly vendorIdentityVerifier?: (input: { provider: "exe.dev" | "fly.io"; vmId: string; token: string; integrationName?: string; expectedIssuer?: string; expectedSubject?: string }) => Promise, ) {} - reserve(runId: string): RunHandle { return { backendKind: this.kind, id: vmNameFor(runId), runProxyName: runProxyName(runId), operationId: runId, vendorIdentityIntegrationName: exeWifIntegrationNameFor(runId) }; } + reserve(runId: string): RunHandle { return { backendKind: this.kind, id: vmNameFor(runId), operationId: runId, vendorIdentityIntegrationName: exeWifIntegrationNameFor(runId) }; } private async exeWifToken(vm: string, integrationName: string): Promise { const command = `curl --fail --silent --show-error https://${integrationName}.int.exe.xyz/token | python3 -c 'import json,sys;v=json.load(sys.stdin);t=v.get("token");sys.stdout.write(t if isinstance(t,str) else "")'`; @@ -223,22 +221,8 @@ export class ExeVmBackend implements ExecutionBackend { if (request.runIdentity) { if (!(request.verifyVendorIdentity ?? this.vendorIdentityVerifier)) throw new Error("Vendor identity verification is required for run access"); handle.identityProxyOrigin = request.runIdentity.backendOrigin; - delete handle.runProxyName; await assertExeVmIsolation({execute: command => this.api(command), vm, backendOrigin: request.runIdentity.backendOrigin, tags: this.connection.tags ?? []}); } - let proxy: ExeRunProxy | undefined, plan: Awaited> | undefined; - if (request.runProxy) { - try { - proxy = new ExeRunProxy(command => this.api(command)); - plan = await proxy.prepare(request.runId); - if (plan.exists) handle.runProxyName = plan.name; - // Check before VM creation: even image boot processes must not inherit - // a shared Factorize credential while provisioning is in progress. - await proxy.assertIsolated(vm, request.runId, request.runProxy.targetOrigin, this.connection.tags); - } catch (error) { - return { handle, destinationUrl: `https://${vm}.exe.xyz/`, capabilities, observation: { state: "failed", detail: error instanceof Error ? error.message : "Run proxy preflight failed" } }; - } - } const tags = [...new Set(this.connection.tags)].map(tag => `--tag=${shellAtom(tag)}`).join(" "); const image = connection.image; const created = await this.api(`new --name=${shellAtom(vm)} --no-email --comment=${shellAtom(`Factorize VM ${vm}`)} ${tags}${image ? ` --image=${shellAtom(image)}` : ""}`.trim()); @@ -247,18 +231,6 @@ export class ExeVmBackend implements ExecutionBackend { throw new Error(`exe.dev VM creation failed (${created.status}): ${created.body.slice(0, 500)}`); } - if (request.runProxy && proxy && plan) { - try { - handle.runProxyName = plan.name; - await proxy.provision(plan, vm, request.runProxy.targetOrigin, request.runProxy.credential); - await proxy.verify(vm, request.runId, request.runProxy.targetOrigin, this.connection.tags); - } catch (error) { - // Retain the handle even on a partial provision, so polling can retry - // ownership-safe proxy/VM cleanup before releasing the active slot. - return { handle, destinationUrl: `https://${vm}.exe.xyz/`, capabilities, observation: { state: "failed", detail: error instanceof Error ? error.message : "Run proxy provisioning failed" } }; - } - } - const verifyVendorIdentity = request.verifyVendorIdentity ?? this.vendorIdentityVerifier; if (verifyVendorIdentity) { try { @@ -417,19 +389,15 @@ export class ExeVmBackend implements ExecutionBackend { async stop(handle: RunHandle): Promise { const vm = this.vm(handle); - let proxyError: string | undefined; - if (handle.runProxyName) { - try { await new ExeRunProxy(command => this.api(command)).remove(handle.runProxyName, vm.slice("factorize-".length)); } - catch { proxyError = "Run proxy cleanup failed; retry required"; } - } + let cleanupError: string | undefined; if (handle.vendorIdentityIntegrationName) { try { if (!handle.operationId) throw new Error("WIF run identity is unavailable"); await this.removeExeWif(vm, handle.operationId, handle.vendorIdentityIntegrationName); - } catch { proxyError ??= "exe.dev WIF integration cleanup failed; retry required"; } + } catch { cleanupError ??= "exe.dev WIF integration cleanup failed; retry required"; } } const result = await this.deleteVm(vm); - return { state: result.ok && !proxyError ? "stopped" : "failed", detail: proxyError ?? (result.ok ? undefined : `VM deletion failed (${result.status}): ${result.body.slice(0, 300)}`), command: result }; + return { state: result.ok && !cleanupError ? "stopped" : "failed", detail: cleanupError ?? (result.ok ? undefined : `VM deletion failed (${result.status}): ${result.body.slice(0, 300)}`), command: result }; } private async deleteVm(vm: string): Promise { diff --git a/packages/api/src/execution.ts b/packages/api/src/execution.ts index 53175de3..f721e810 100644 --- a/packages/api/src/execution.ts +++ b/packages/api/src/execution.ts @@ -16,8 +16,6 @@ export interface LaunchRequest { /** Backend-owned provisional handle, persisted before provisioning when supported. */ reservation?: RunHandle; prompt: string; - /** Control-plane only: provisioned into an exe.dev proxy, never the guest. */ - runProxy?: { targetOrigin: string; credential: string }; /** Public backend configuration only; requests must use fresh vendor identity. */ runIdentity?: { backendOrigin: string }; traceSources?: TraceSources; @@ -28,7 +26,7 @@ export interface LaunchRequest { } /** Opaque to orchestration. Only the backend that created it may interpret id. */ -export interface RunHandle { identityProxyOrigin?: string; backendKind: string; id: string; runProxyName?: string; /** Stable provider operation key retained across a scheduler restart. */ operationId?: string; vendorIdentityIntegrationName?: string; } +export interface RunHandle { identityProxyOrigin?: string; backendKind: string; id: string; /** Stable provider operation key retained across a scheduler restart. */ operationId?: string; vendorIdentityIntegrationName?: string; } export interface ExecutionObservation { systemd?: import("./harness-diagnostics").ExecutionDiagnostics["systemd"]; diff --git a/packages/api/src/flow-service.ts b/packages/api/src/flow-service.ts index 814609e6..526246fd 100644 --- a/packages/api/src/flow-service.ts +++ b/packages/api/src/flow-service.ts @@ -16,9 +16,7 @@ import { jobResponse } from "./job-contracts"; import type { JobPageQuery } from "./job-contracts"; import { PostgresJobRepository, StaleJobEdit } from "./postgres/job-repository"; import { ConnectionRepository } from "./postgres/connection-repository"; -import { EncryptedIntegrationRepository, IntegrationIdempotencyConflictError, IntegrationValidationError, StaleIntegrationRevisionError } from "./postgres/encrypted-integration-repository"; -import { ProxyControlRepository } from "./postgres/proxy-control-repository"; -import { issueModelAccountCapability, issueProxyCapability } from "./proxy-browser-capability"; +import { CredentialRepository, IntegrationIdempotencyConflictError, IntegrationValidationError, StaleIntegrationRevisionError } from "./postgres/credential-repository"; import { decrypt, encrypt } from "./crypto"; import { InvocationService, type Job, type Trigger } from "./job-domain"; import { RunQueryRepository } from "./postgres/run-query-repository"; @@ -47,6 +45,8 @@ import { FlyConnectionRepository } from "./postgres/fly-connection-repository"; import { FlyExecutionConfigurationRepository } from "./postgres/fly-execution-configuration-repository"; import { flyExecutionConfigurationInput, getFlyExecutionMetadata, type FlyExecutionMetadataLoader } from "./fly-execution-configurations"; +import {modelDeviceAuthorization, modelCredentialConfigured, ModelAccountUnavailable} from "./model-device-auth"; + const PROJECT_GRAPH_LABEL_MAX_CHARS = 24; export class ServiceError extends Error { @@ -103,11 +103,12 @@ export class ApiService { const linearConnectionId = input.linearConnectionId !== undefined ? input.linearConnectionId : current?.linearConnectionId ?? current?.executionConfig.linearConnectionId; if (executionType === "code" && input.modelAccess === "portable") throw new ServiceError(400, "invalid_request", "Code jobs cannot select model access."); const modelAccess = executionType === "code" ? "native" : input.modelAccess ?? current?.modelAccess ?? current?.executionConfig.modelAccess ?? (config.executionProvider === "fly" ? "portable" : "native"); + if (modelAccess === "portable" && config.agentKind !== "codex") throw new ServiceError(400,"invalid_request","Managed model accounts support Codex jobs."); if (modelAccess === "native" && input.modelAccountId) throw new ServiceError(400, "invalid_request", "Native model access cannot select a portable model account."); const modelAccountId = modelAccess === "portable" ? input.modelAccountId ?? current?.modelAccountId ?? current?.executionConfig.modelAccountId : undefined; if (executionType === "code" && modelAccountId) throw new ServiceError(400, "invalid_request", "Code jobs cannot select a model account."); if (config.executionProvider === "fly" && executionType === "agent" && config.agentKind === "codex" && (!modelAccountId || modelAccess !== "portable")) throw new ServiceError(400, "invalid_request", "Fly Codex jobs require a portable model account."); - const records = await new EncryptedIntegrationRepository(databaseFor(this.env), this.auth.tenantId, this.env.CREDENTIAL_ENCRYPTION_KEY).records(); + const records = await new CredentialRepository(databaseFor(this.env), this.auth.tenantId, this.env.CREDENTIAL_ENCRYPTION_KEY).metadata(); const byId = new Map(records.map(record => [record.id, record])); if (new Set(portableIntegrationIds).size !== portableIntegrationIds.length || portableIntegrationIds.some(id => byId.get(id)?.kind !== "bearer")) throw new ServiceError(400, "invalid_request", "One or more selected portable integrations are unavailable."); const installations = await new GitHubRepository(databaseFor(this.env), this.auth.tenantId).installations(); @@ -115,6 +116,8 @@ export class ApiService { if (new Set(githubInstallationIds).size !== githubInstallationIds.length || githubInstallationIds.some(id => !activeInstallationIds.has(id))) throw new ServiceError(400, "invalid_request", "One or more selected GitHub installations are unavailable."); if (linearConnectionId && (!await this.connections().get("linear"))) throw new ServiceError(400, "invalid_request", "The selected Linear connection is unavailable."); if (modelAccountId && byId.get(modelAccountId)?.kind !== "model") throw new ServiceError(400, "invalid_request", "The selected model account is unavailable."); + if (modelAccountId && !modelCredentialConfigured((await this.credentials().managedCredential(modelAccountId,"model"))?.payload??"")) throw new ServiceError(400,"invalid_request","Connect the selected model account before using it in a job."); + for (const id of portableIntegrationIds) if (!await this.credentials().managedCredential(id,"bearer")) throw new ServiceError(400,"invalid_request","Re-enter the selected bearer credential before using it in a job."); if (modelAccess === "portable" && executionType !== "code" && !modelAccountId) throw new ServiceError(400, "invalid_request", "Portable model access requires a model account."); return { portableIntegrationIds, githubInstallationIds, ...(linearConnectionId ? { linearConnectionId } : {}), modelAccess, ...(modelAccountId ? { modelAccountId } : {}) }; } @@ -279,7 +282,7 @@ export class ApiService { await this.authorize("runs:write"); const parsed = reportRunErrorSchema.parse(input), reason = safeDiagnosticText(parsed.reason, 1000); if (!reason.trim()) throw new ServiceError(400, "invalid_request", "Reason must contain safe text."); - const reporterKind = this.auth.authMethod === "oauth" ? "oauth" : this.auth.authMethod === "access_token" ? "api_key" : (this.auth.authMethod === "run_token" || this.auth.authMethod === "vendor_identity") ? "run_token" : "session"; + const reporterKind = this.auth.authMethod === "oauth" ? "oauth" : this.auth.authMethod === "access_token" ? "api_key" : this.auth.authMethod === "vendor_identity" ? "run_token" : "session"; const reporterId = reporterKind === "oauth" ? this.auth.oauthGrantId && this.auth.oauthClientId ? `${this.auth.oauthClientId}:${this.auth.oauthGrantId}` : undefined : reporterKind === "api_key" ? this.auth.accessTokenId : reporterKind === "run_token" ? this.auth.runId : this.auth.userId; if (!reporterId) throw new ServiceError(403, "invalid_token", "Authenticated reporter identity is unavailable."); const result = await new RunRepository(databaseFor(this.env)).reportAgentError({ tenantId: this.auth.tenantId, runId, reason, userId: this.auth.userId, reporterKind, reporterId }); @@ -504,28 +507,21 @@ export class ApiService { async setJobEnabled(jobId: string, enabled: boolean) { await this.authorize("jobs:write"); const repository = this.jobs(); if (!await repository.setEnabled(jobId, enabled, new Date().toISOString())) throw new ServiceError(404, "not_found", "Job not found"); await this.wakeScheduler(); return { id: jobId, enabled }; } async invokeJob(jobId: string, input: ManualInvocationInput) { await this.authorize("runs:invoke"); const repository = this.jobs(), job = await repository.getJob(jobId); if (!job) throw new ServiceError(404, "not_found", "Job not found"); - if (this.auth.authMethod === "run_token" || this.auth.authMethod === "vendor_identity") { + if (this.auth.authMethod === "vendor_identity") { if (!this.auth.runId || !this.auth.runJobId) throw new ServiceError(401, "invalid_token", "A verified run identity is required."); - const permission = this.auth.authMethod === "vendor_identity" - ? await databaseFor(this.env).pool.query(`SELECT 1 FROM app.vendor_run_identity_bindings b + const permission = await databaseFor(this.env).pool.query(`SELECT 1 FROM app.vendor_run_identity_bindings b JOIN app.job_runs r ON r.tenant_id=b.tenant_id AND r.id=b.run_id JOIN app.jobs source ON source.tenant_id=r.tenant_id AND source.id=r.job_id JOIN app.jobs destination ON destination.tenant_id=source.tenant_id AND destination.id=$3 AND destination.project_id=source.project_id JOIN app.manual_invocation_permissions p ON p.tenant_id=b.tenant_id AND p.source_job_id=r.job_id AND p.destination_job_id=$3 WHERE b.tenant_id=$1 AND b.run_id=$2 AND b.provider=$4 AND b.revoked_at IS NULL - AND r.state IN ('starting','running','blocked')`, [this.auth.tenantId, this.auth.runId, jobId, this.auth.runIdentityProvider]) - : await databaseFor(this.env).pool.query(`SELECT 1 FROM app.run_credentials c - JOIN app.job_runs r ON r.tenant_id=c.tenant_id AND r.id=c.run_id - JOIN app.jobs source ON source.tenant_id=r.tenant_id AND source.id=r.job_id - JOIN app.jobs destination ON destination.tenant_id=source.tenant_id AND destination.id=$3 AND destination.project_id=source.project_id - JOIN app.manual_invocation_permissions p ON p.tenant_id=c.tenant_id AND p.source_job_id=r.job_id AND p.destination_job_id=$3 - WHERE c.tenant_id=$1 AND c.run_id=$2 AND c.digest=$4 AND c.expires_at>now() AND r.state IN ('reserved','starting','running','blocked','stopping')`, [this.auth.tenantId, this.auth.runId, jobId, this.auth.runCredentialDigest]); + AND r.state IN ('starting','running','blocked')`, [this.auth.tenantId, this.auth.runId, jobId, this.auth.runIdentityProvider]); if (!permission.rowCount) throw new ServiceError(403, "forbidden", "This run is no longer active or its source job is not authorized to invoke the destination."); } const trigger = job.triggers.find(value => value.kind === "manual" && value.enabled); if (!trigger) throw new ServiceError(409, "operation_failed", "The manual trigger is disabled"); const service = new InvocationService(repository, value => encrypt(value, this.env.CREDENTIAL_ENCRYPTION_KEY)); - const claimKey = input.idempotencyKey ? `manual:${(this.auth.authMethod === "run_token" || this.auth.authMethod === "vendor_identity") ? `run:${this.auth.runId}:` : ""}${input.idempotencyKey}` : `manual:${crypto.randomUUID()}`; - const result = await service.invoke(jobId, { source: "manual", name: input.name, triggerId: trigger.id, claimKey, ...((this.auth.authMethod === "run_token" || this.auth.authMethod === "vendor_identity") ? { sourceJobId: this.auth.runJobId, sourceRunId: this.auth.runId } : {}), context: { [trigger.slug]: { prompt: input.prompt, data: input.data ?? {} } } }); + const claimKey = input.idempotencyKey ? `manual:${this.auth.authMethod === "vendor_identity" ? `run:${this.auth.runId}:` : ""}${input.idempotencyKey}` : `manual:${crypto.randomUUID()}`; + const result = await service.invoke(jobId, { source: "manual", name: input.name, triggerId: trigger.id, claimKey, ...(this.auth.authMethod === "vendor_identity" ? { sourceJobId: this.auth.runJobId, sourceRunId: this.auth.runId } : {}), context: { [trigger.slug]: { prompt: input.prompt, data: input.data ?? {} } } }); if (this.env.SCHEDULER) await this.env.SCHEDULER.get(this.env.SCHEDULER.idFromName("global")).fetch("https://scheduler/wake", { method: "POST" }); return { invocationId: result.invocation.id, runId: result.run.id, state: result.run.state, duplicate: result.duplicate }; } @@ -541,7 +537,7 @@ export class ApiService { async setInvocationPermissions(sourceJobId: string, destinationJobIds: string[]) { await this.authorize("jobs:write"); // A run with jobs:write still cannot expand its invocation destinations. - if (this.auth.authMethod === "run_token" || this.auth.authMethod === "vendor_identity") throw new ServiceError(403, "insufficient_scope", "Run credentials cannot change invocation permissions."); + if (this.auth.authMethod === "vendor_identity") throw new ServiceError(403, "insufficient_scope", "Run credentials cannot change invocation permissions."); const unique = [...new Set(destinationJobIds)]; if (unique.length !== destinationJobIds.length) throw new ServiceError(400, "invalid_request", "Destination jobs must be unique."); const db = databaseFor(this.env); @@ -580,11 +576,11 @@ export class ApiService { async testAmpIntegration(input: any) { await this.authorize("integrations:write"); return this.integrations().testAmp(input); } async saveTailIntegration(input: any) { await this.authorize("integrations:write"); return this.integrations().saveTail(input); } async testTailIntegration(id: string) { await this.authorize("integrations:write"); const result = await this.integrations().testTail(id); if (!result) throw new ServiceError(404, "not_found", "Integration not found"); return result; } - private encryptedIntegrations() { return new EncryptedIntegrationRepository(databaseFor(this.env), this.auth.tenantId, this.env.CREDENTIAL_ENCRYPTION_KEY); } + private credentials() { return new CredentialRepository(databaseFor(this.env), this.auth.tenantId, this.env.CREDENTIAL_ENCRYPTION_KEY); } private async bearerWrite(input: { id: string; expectedRevision: number; idempotencyKey: string; name: string; origin: string; description: string | null; token?: string; operation: "upsert" | "delete" }) { - try { return await this.encryptedIntegrations().write({ ...input, managedSecret: input.token, kind: "bearer" }); } + try { return await this.credentials().write({ ...input, managedSecret: input.token, kind: "bearer" }); } catch (error) { - if (error instanceof StaleIntegrationRevisionError) throw new ServiceError(409, "stale_revision", `${error.resyncRequired ? "Integration change history expired; fetch the current collection to resynchronize. " : "The integration collection changed. "}Current revision is ${error.currentRevision}.`); + if (error instanceof StaleIntegrationRevisionError) throw new ServiceError(409, "stale_revision", `The integration collection changed. Current revision is ${error.currentRevision}.`); if (error instanceof IntegrationIdempotencyConflictError) throw new ServiceError(409, "conflict", "The idempotency key was already used for a different integration change."); if (error instanceof IntegrationValidationError) throw new ServiceError(400, "invalid_request", error.message); throw error; @@ -597,142 +593,41 @@ export class ApiService { } async listBearerIntegrations() { await this.authorizeOwnerSession("integrations:read"); - const [revision, records] = await Promise.all([this.encryptedIntegrations().revision(), this.encryptedIntegrations().records("bearer")]); + const [revision, records] = await Promise.all([this.credentials().revision(), this.credentials().metadata("bearer")]); // Secret values are only read by the server-side credential control path. - return { revision, integrations: records.map(({ encryptedPayload: _secret, ...record }) => record) }; + return { revision, integrations: records }; } async createBearerIntegration(input: { id: string; expectedRevision: number; idempotencyKey: string; name: string; origin: string; description: string | null; token: string }) { await this.authorizeOwnerSession("integrations:write"); this.validateBearerOrigin(input.origin); - if ((await this.encryptedIntegrations().records("bearer")).some(record => record.id === input.id)) throw new ServiceError(409, "conflict", "Integration already exists."); + if ((await this.credentials().metadata("bearer")).some(record => record.id === input.id)) throw new ServiceError(409, "conflict", "Integration already exists."); return this.bearerWrite({ ...input, operation: "upsert" }); } async updateBearerIntegration(id: string, input: { expectedRevision: number; idempotencyKey: string; name: string; origin: string; description: string | null; token: string }) { await this.authorizeOwnerSession("integrations:write"); this.validateBearerOrigin(input.origin); - const existing = (await this.encryptedIntegrations().records("bearer")).find(record => record.id === id); + const existing = (await this.credentials().metadata("bearer")).find(record => record.id === id); if (!existing) throw new ServiceError(404, "not_found", "Integration not found."); return this.bearerWrite({ ...input, id, operation: "upsert" }); } async deleteBearerIntegration(id: string, input: { expectedRevision: number; idempotencyKey: string }) { await this.authorizeOwnerSession("integrations:write"); - const existing = (await this.encryptedIntegrations().records("bearer")).find(record => record.id === id && record.origin !== null); + const existing = (await this.credentials().metadata("bearer")).find(record => record.id === id && record.origin !== null); if (!existing) throw new ServiceError(404, "not_found", "Integration not found."); const result = await this.bearerWrite({ id, name: existing.name, origin: existing.origin!, description: existing.description, ...input, operation: "delete" }); return { id, deleted: true as const, ...result }; } - async getUnlockKeyVerification() { - await this.authorizeOwnerSession("integrations:read"); - const { rows } = await databaseFor(this.env).pool.query<{ generation_id: string; encrypted_verification: string }>("SELECT generation_id,encrypted_verification FROM app.unlock_key_verifications WHERE tenant_id=$1", [this.auth.tenantId]); - return { ownerId: this.auth.userId, verification: rows[0] ? { generationId: rows[0].generation_id, encryptedVerification: rows[0].encrypted_verification } : null }; - } - async createUnlockKeyVerification(input: { generationId: string; encryptedVerification: string }) { - await this.authorizeOwnerSession("integrations:write"); - let envelope: any; - try { envelope = JSON.parse(input.encryptedVerification); } catch { throw new ServiceError(400, "invalid_request", "Verification ciphertext is malformed."); } - if (!envelope || typeof envelope !== "object" || Array.isArray(envelope) || envelope.version !== 1 || envelope.algorithm !== "A256GCM" || Object.keys(envelope).sort().join(",") !== "algorithm,ciphertext,nonce,version" || typeof envelope.nonce !== "string" || !/^[A-Za-z0-9_-]{16}$/u.test(envelope.nonce) || typeof envelope.ciphertext !== "string" || !/^[A-Za-z0-9_-]{22,}$/u.test(envelope.ciphertext)) throw new ServiceError(400, "invalid_request", "Verification ciphertext is malformed."); - const { rows } = await databaseFor(this.env).pool.query("INSERT INTO app.unlock_key_verifications(tenant_id,generation_id,encrypted_verification) VALUES ($1,$2,$3) ON CONFLICT (tenant_id) DO NOTHING RETURNING generation_id", [this.auth.tenantId, input.generationId, input.encryptedVerification]); - if (!rows.length) throw new ServiceError(409, "conflict", "An unlock key is already set up for this account."); - return { generationId: input.generationId }; - } - async getUnlockKeyRotationSnapshot() { - await this.authorizeOwnerSession("integrations:read"); - const repository = this.encryptedIntegrations(); - const [snapshot, verification] = await Promise.all([ - repository.rotationSnapshot(), - databaseFor(this.env).pool.query<{ generation_id: string }>("SELECT generation_id FROM app.unlock_key_verifications WHERE tenant_id=$1", [this.auth.tenantId]), - ]); - const generationId = verification.rows[0]?.generation_id; - if (!generationId) throw new ServiceError(409, "conflict", "Set up an unlock key before rotating or resetting integrations."); - const modelRevisions = new Map(); - const changes = snapshot.changes.map(change => { - let recordRevision: number | null = null; - if (change.kind === "model" && change.operation === "delete") modelRevisions.delete(change.id); - if (change.kind === "model" && change.operation === "upsert" && change.encryptedPayload !== null) { - recordRevision = modelRevisions.has(change.id) ? modelRevisions.get(change.id)! + 1 : change.revision; - modelRevisions.set(change.id, recordRevision); - } - return { ...change, recordRevision }; - }); - // Factorize-managed model caches are not encrypted with the unlock key. - // Omit them from the browser payload and preserve them server-side below. - const managed = (value: string | null) => value?.startsWith("factorize-managed-model-cache-v1:") ?? false; - const records = snapshot.records.filter(record => !(record.kind === "model" && managed(record.encryptedPayload))); - const retainedChanges = changes.filter(change => !(change.kind === "model" && managed(change.encryptedPayload))); - return { ownerId: this.auth.userId, generationId, revision: snapshot.revision, records, changes: retainedChanges }; - } - async replaceUnlockKeyGeneration(input: { - expectedGenerationId: string; generationId: string; expectedRevision: number; encryptedVerification: string; preserveManagedModelCaches?: boolean; - records: Array<{ id: string; kind: "bearer" | "model"; name: string; origin: string | null; description: string | null; revision: number; encryptedPayload: string | null; deletedAt: string | null }>; - changes: Array<{ id: string; kind: "bearer" | "model"; name: string; origin: string | null; description: string | null; revision: number; idempotencyKey: string; operation: "upsert" | "delete"; encryptedPayload: string | null; recordRevision?: number | null }>; - }) { - await this.authorizeOwnerSession("integrations:write"); - if (input.expectedGenerationId === input.generationId) throw new ServiceError(400, "invalid_request", "A replacement key generation must be new."); - if (input.preserveManagedModelCaches && [...input.records.map(record => record.encryptedPayload), ...input.changes.map(change => change.encryptedPayload)].some(value => value?.startsWith("factorize-managed-model-cache-v1:"))) { - throw new ServiceError(400, "invalid_request", "Managed model cache payloads are preserved by the server and cannot be supplied by the browser."); - } - const repository = this.encryptedIntegrations(); - let suppliedRecords = input.records; - let suppliedChanges = input.changes; - if (input.preserveManagedModelCaches) { - const current = await repository.rotationSnapshot(); - const managed = (value: string | null) => value?.startsWith("factorize-managed-model-cache-v1:") ?? false; - suppliedRecords = [...suppliedRecords, ...current.records.filter(record => record.kind === "model" && managed(record.encryptedPayload)).map(record => ({ ...record, deletedAt: record.deletedAt?.toISOString() ?? null }))]; - suppliedChanges = [...suppliedChanges, ...current.changes.filter(change => change.kind === "model" && managed(change.encryptedPayload))]; - } - const records = suppliedRecords.map(record => ({ ...record, deletedAt: record.deletedAt === null ? null : new Date(record.deletedAt) })); - const changes = suppliedChanges.map(({ recordRevision: _recordRevision, ...change }) => change); - try { - await repository.stageGeneration({ generationId: input.generationId, expectedRevision: input.expectedRevision, records, changes, preserveManagedModelCaches: input.preserveManagedModelCaches }); - const committed = await repository.commitGeneration(input.generationId, input.expectedRevision, { - expectedVerificationGenerationId: input.expectedGenerationId, - verificationGenerationId: input.generationId, - encryptedVerification: input.encryptedVerification, - }); - return { generationId: input.generationId, ...committed }; - } catch (error) { - if (error instanceof StaleIntegrationRevisionError || (error as Error)?.name === "StaleIntegrationGenerationError") throw new ServiceError(409, "stale_revision", "Integration records changed during key replacement. Reload and retry with the current unlock key."); - if (error instanceof IntegrationIdempotencyConflictError) throw new ServiceError(409, "conflict", "This key replacement ID was already used for different encrypted data."); - if (error instanceof IntegrationValidationError) throw new ServiceError(400, "invalid_request", error.message); - throw error; - } - } - async setupCredentialProxy(operationId: string) { - await this.authorizeOwnerSession("integrations:write"); - if (!this.env.CREDENTIAL_PROXY_HOST) throw new ServiceError(503, "operation_failed", "Credential proxy execution host is unavailable."); - return this.env.CREDENTIAL_PROXY_HOST.setup(this.auth.tenantId, operationId); - } - async issueCredentialProxyCapability(action: "unlock" | "lock" | "apply" | "status") { - await this.authorizeOwnerSession("integrations:write"); - const pairing = await new ProxyControlRepository(databaseFor(this.env)).browserPairing(this.auth.tenantId); - if (!pairing || !this.env.MODEL_ACCOUNT_CAPABILITY_PRIVATE_KEY) throw new ServiceError(503, "operation_failed", "Credential proxy is not paired."); - const capability = await issueProxyCapability({ privateKeyPem: this.env.MODEL_ACCOUNT_CAPABILITY_PRIVATE_KEY, - proxyIdentity: pairing.proxyIdentity, ownerId: this.auth.tenantId, action, - appOrigin: this.env.APP_ORIGIN, generation: pairing.bootEpoch }); - return { endpoint: `${pairing.browserOrigin}/proxy/${action}`, capability }; - } - async issueModelAccountBrowserCapability(accountId: string, action: "authorize" | "status" | "cancel") { + async modelAuthorization(accountId: string, action: "authorize" | "status" | "cancel") { await this.authorizeOwnerSession("integrations:write"); - if (!this.env.MODEL_ACCOUNT_CAPABILITY_PRIVATE_KEY) throw new ServiceError(503, "operation_failed", "Model-account browser authorization is unavailable."); - const [pairing, accounts] = await Promise.all([ - new ProxyControlRepository(databaseFor(this.env)).browserPairing(this.auth.tenantId), - this.encryptedIntegrations().records("model"), - ]); - if (!pairing) throw new ServiceError(503, "operation_failed", "The credential proxy is not paired for browser authorization."); - if (!accounts.some(account => account.id === accountId)) throw new ServiceError(404, "not_found", "Model account not found."); - const capability = await issueModelAccountCapability({ - privateKeyPem: this.env.MODEL_ACCOUNT_CAPABILITY_PRIVATE_KEY, - proxyIdentity: pairing.proxyIdentity, ownerId: this.auth.tenantId, accountId, action, - appOrigin: this.env.APP_ORIGIN, generation: pairing.bootEpoch, - }); - return { endpoint: `${pairing.browserOrigin}/model-accounts/${accountId}/${action}`, capability }; + try {return await modelDeviceAuthorization(this.env,this.auth,accountId,action);} + catch (error) {if (error instanceof ModelAccountUnavailable) throw new ServiceError(404,"not_found","Model account not found."); throw new ServiceError(503,"model_authorization_unavailable","Model account authorization is unavailable. Try connecting again.");} } async listModelAccounts() { await this.authorizeOwnerSession("integrations:read"); - const repository = this.encryptedIntegrations(); - const [revision, accounts] = await Promise.all([repository.revision(), repository.records("model")]); - return { revision, accounts: accounts.map(({ id, name, description, revision }) => ({ id, name, description, revision })) }; + const repository = this.credentials(); + const [revision, accounts] = await Promise.all([repository.revision(), repository.metadata("model")]); + return {revision, accounts: await Promise.all(accounts.map(async ({id,name,description,revision}) => ({id,name,description,revision, credentialConfigured: modelCredentialConfigured((await repository.managedCredential(id,"model"))?.payload ?? "")})))}; } - private async modelAccountWrite(input: { id: string; expectedRevision: number; idempotencyKey: string; name: string; description: string | null; encryptedPayload?: string; operation: "upsert" | "delete" }) { - try { return await this.encryptedIntegrations().write({ ...input, kind: "model", origin: null }); } + private async modelAccountWrite(input: { id: string; expectedRevision: number; idempotencyKey: string; name: string; description: string | null; operation: "upsert" | "delete" }) { + try { return await this.credentials().write({ ...input, kind: "model", origin: null }); } catch (error) { if (error instanceof StaleIntegrationRevisionError) throw new ServiceError(409, "stale_revision", `The model account collection changed. Current revision is ${error.currentRevision}.`); if (error instanceof IntegrationIdempotencyConflictError) throw new ServiceError(409, "conflict", "The idempotency key was already used for a different model account change."); @@ -742,7 +637,7 @@ export class ApiService { } async createModelAccount(input: { id: string; expectedRevision: number; idempotencyKey: string; name: string; description: string | null; initialState: string }) { await this.authorizeOwnerSession("integrations:write"); - const repository = this.encryptedIntegrations(); + const repository = this.credentials(); const managed = { ...input, initialState: undefined, managedModelPayload: input.initialState, kind: "model" as const, origin: null, operation: "upsert" as const }; try { const replay = await repository.replay(managed); @@ -752,7 +647,7 @@ export class ApiService { if (error instanceof IntegrationValidationError) throw new ServiceError(400, "invalid_request", error.message); throw error; } - if ((await repository.records()).some(record => record.id === input.id)) throw new ServiceError(409, "conflict", "An integration with this id already exists."); + if ((await repository.metadata()).some(record => record.id === input.id)) throw new ServiceError(409, "conflict", "An integration with this id already exists."); try { return await repository.write(managed); } catch (error) { if (error instanceof StaleIntegrationRevisionError) throw new ServiceError(409, "stale_revision", `The model account collection changed. Current revision is ${error.currentRevision}.`); @@ -761,10 +656,17 @@ export class ApiService { throw error; } } + async updateModelAccount(id: string, input: {expectedRevision: number; idempotencyKey: string; name: string; description: string | null; initialState: string}) { + await this.authorizeOwnerSession("integrations:write"); + const repository=this.credentials(); + if (!(await repository.metadata("model")).some(record=>record.id===id)) throw new ServiceError(404,"not_found","Model account not found."); + try {return await repository.write({...input,id,kind:"model",origin:null,operation:"upsert",managedModelPayload:input.initialState});} + catch (error) {if(error instanceof StaleIntegrationRevisionError) throw new ServiceError(409,"stale_revision","The model account collection changed. Reload and retry."); if(error instanceof IntegrationIdempotencyConflictError) throw new ServiceError(409,"conflict",error.message); if(error instanceof IntegrationValidationError) throw new ServiceError(400,"invalid_request",error.message); throw error;} + } async deleteModelAccount(id: string, input: { expectedRevision: number; idempotencyKey: string }) { await this.authorizeOwnerSession("integrations:write"); - const repository = this.encryptedIntegrations(); - const existing = (await repository.records("model")).find(record => record.id === id); + const repository = this.credentials(); + const existing = (await repository.metadata("model")).find(record => record.id === id); if (!existing) { try { const replay = await repository.replayDelete(id, "model", input.idempotencyKey); diff --git a/packages/api/src/fly-credential-proxy-provisioner.ts b/packages/api/src/fly-credential-proxy-provisioner.ts deleted file mode 100644 index ca2f0553..00000000 --- a/packages/api/src/fly-credential-proxy-provisioner.ts +++ /dev/null @@ -1,210 +0,0 @@ -import { provisionCredentialProxy, type ProxyBootstrapProvisioning } from "./proxy-provisioner"; -import type { ProxyControlRepository } from "./postgres/proxy-control-repository"; -import type { FlyMachine, FlyMachineConfig } from "./fly-machines-client"; -import { createFlyGuestTransport } from "./fly-guest-transport"; - -const IMAGE_DIGEST = /@sha256:[a-f0-9]{64}$/i; -const UUID_V4 = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i; - -export type FlyCredentialProxyConfig = { - tenantId: string; - app: string; - /** Only reviewed credential-proxy images pinned by digest are accepted. */ - image: string; - region: string; - size: string; - browserCapabilityPublicKey: string; - memoryMb?: number; - controlOrigin: string; - /** Stable across retries of one provisioning operation. */ - operationId: string; -}; - -export type FlyCredentialProxyMachineClient = { - createMachine(app: string, config: FlyMachineConfig, operationId: string): Promise; - startMachine(app: string, machine: string): Promise; - destroyMachine(app: string, machine: string): Promise; -}; - -export type FlyCredentialProxyGuest = { - run(command: readonly string[], input?: string | Uint8Array): Promise<{ ok: boolean; exitCode: number; stdout: string; stderr: string }>; - /** The reviewed image startup command consumes this payload from stdin only. */ - startProxy(input: ProxyBootstrapProvisioning & { credential: string }): Promise; - /** Signs a VM-generated CSR over the provider's private guest channel. Only - * the public certificate and CA trust bundle return to the caller. */ - issueVmCertificate(input: { bootEpoch: string; vmIdentity: string; csr: string }): Promise<{ certificate: string; trustBundle: string }>; -}; - -/** Provider exec adapter: the bootstrap record is the command's stdin payload. */ -export function createFlyCredentialProxyGuest(options: { - app: string; - machine: string; - token: string; - cliPath?: string; - spawnProcess?: typeof import("node:child_process").spawn; -}): FlyCredentialProxyGuest { - const transport = createFlyGuestTransport({ ...options, timeoutMs: 30_000, outputLimitBytes: 16 * 1024 }); - return createCredentialProxyGuest(transport); -} - -/** Shared provisioner protocol over a private infrastructure guest transport. */ -export function createCredentialProxyGuest(transport: Pick): FlyCredentialProxyGuest { - return { - run: (command, input) => transport.run(command, input), - async startProxy(input) { - const ready = await transport.run(["/bin/sh", "-c", "n=0; until test -S /run/factorize-proxy/bootstrap.sock; do n=$((n+1)); test $n -lt 100 || exit 1; sleep 0.1; done"]); - if (!ready.ok) throw new Error("Credential proxy bootstrap socket did not become ready"); - const result = await transport.run(["/usr/local/bin/factorize-proxy-startup"], `${JSON.stringify({ - type: "register-boot", - controlOrigin: input.controlOrigin, - browserOrigin: input.browserOrigin, - bootEpoch: input.bootEpoch, - credential: input.credential, - })}\n`); - if (!result.ok) throw new Error("Credential proxy startup command failed"); - if (result.stdout.trim() !== "Credential proxy started") throw new Error("Credential proxy startup was not confirmed"); - }, - async issueVmCertificate(input) { - if (!input || !UUID_V4.test(input.bootEpoch) || !/^[A-Za-z0-9:._-]{1,255}$/.test(input.vmIdentity) - || typeof input.csr !== "string" || input.csr.length < 100 || input.csr.length > 16_384) throw new TypeError("Invalid VM certificate provisioning request"); - const result = await transport.run(["/usr/local/bin/factorize-proxy-certify-vm"], `${JSON.stringify(input)}\n`); - if (!result.ok) throw new Error("Credential proxy VM certificate provisioning failed"); - let response: unknown; - try { response = JSON.parse(result.stdout); } catch { throw new Error("Credential proxy returned an invalid VM certificate response"); } - if (!response || typeof response !== "object" || Array.isArray(response) - || Object.keys(response).sort().join(",") !== "bootEpoch,certificate,trustBundle,vmIdentity" - || (response as any).bootEpoch !== input.bootEpoch || (response as any).vmIdentity !== input.vmIdentity - || typeof (response as any).certificate !== "string" || !(response as any).certificate.startsWith("-----BEGIN CERTIFICATE-----") - || typeof (response as any).trustBundle !== "string" || !(response as any).trustBundle.startsWith("-----BEGIN CERTIFICATE-----")) { - throw new Error("Credential proxy returned an invalid VM certificate response"); - } - return { certificate: (response as any).certificate, trustBundle: (response as any).trustBundle }; - }, - }; -} - -export type FlyCredentialProxyProvisionerOptions = { - control: Pick; - machines: FlyCredentialProxyMachineClient; - guest: (machine: FlyMachine) => FlyCredentialProxyGuest; - /** Exact reviewed proxy artifact selected by deployment configuration. */ - reviewedImage: string; - /** Injectable to keep boot identity deterministic in boundary tests. */ - newBootEpoch?: () => string; - infrastructure?: { - kind: "docker"; - validateImage(image: string): void; - identity(machine: FlyMachine): string; - browserOrigin(machine: FlyMachine): Promise; - serverName: string; - environment: Record; - }; -}; - -function validate(input: FlyCredentialProxyConfig, reviewedImage: string): void { - if (!input.tenantId || !input.app || !input.operationId || input.operationId.length > 200) throw new TypeError("Invalid credential proxy provisioning identity"); - if (!/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/.test(input.app)) throw new TypeError("Invalid credential proxy Fly app name"); - if (!IMAGE_DIGEST.test(input.image)) throw new TypeError("Credential proxy image must be pinned by sha256 digest"); - if (!IMAGE_DIGEST.test(reviewedImage) || input.image !== reviewedImage) throw new TypeError("Credential proxy image must match the configured reviewed image"); - if (!/^[a-z0-9]{3}$/.test(input.region)) throw new TypeError("Invalid credential proxy region"); - if (!/^(shared-cpu|performance)-(1|2|4)x$/.test(input.size)) throw new TypeError("Invalid credential proxy size"); - if (!input.browserCapabilityPublicKey.startsWith("-----BEGIN PUBLIC KEY-----")) throw new TypeError("Proxy browser capability public key is required"); - if (input.memoryMb !== undefined && (!Number.isInteger(input.memoryMb) || input.memoryMb < 256 || input.memoryMb > 8192)) throw new TypeError("Credential proxy memory must be between 256 and 8192 MiB"); -} - -/** - * Provisions one dedicated Fly Machine for the credential proxy and wires its - * startup through the one-use bootstrap boundary. The bootstrap credential is - * never part of the Machine config; the guest adapter must deliver it over its - * private stdin startup channel. - */ -export function createFlyCredentialProxyProvisioner(options: Omit) { - return createMachineCredentialProxyProvisioner(options); -} - -export function createMachineCredentialProxyProvisioner(options: FlyCredentialProxyProvisionerOptions) { - return { - async start(input: FlyCredentialProxyConfig): Promise<{ proxyIdentity: string; bootEpoch: string; machine: FlyMachine }> { - if (options.infrastructure) { - if (input.image !== options.reviewedImage) throw new TypeError("Proxy image does not match reviewed local image identity"); - options.infrastructure.validateImage(input.image); - } else validate(input, options.reviewedImage); - const origin = new URL(input.controlOrigin); - if (origin.protocol !== "https:" || origin.username || origin.password || origin.pathname !== "/" || origin.search || origin.hash) { - throw new TypeError("controlOrigin must be an HTTPS origin"); - } - const candidateBootEpoch = (options.newBootEpoch ?? (() => crypto.randomUUID()))(); - if (!UUID_V4.test(candidateBootEpoch)) throw new TypeError("boot epoch must be a UUID v4"); - const size = input.size.match(/^(shared-cpu|performance)-(1|2|4)x$/)!; - const config: FlyMachineConfig = { - image: input.image, - region: input.region, - cmd: ["/usr/local/bin/factorize-credential-proxy", "--boot-epoch", candidateBootEpoch], - guest: { cpu_kind: size[1] === "shared-cpu" ? "shared" : "performance", cpus: Number(size[2]), memory_mb: input.memoryMb ?? 512 }, - env: { - FACTORIZE_PROXY_TUNNEL_SERVER_NAME: options.infrastructure?.serverName ?? `${input.app}.internal`, - ...options.infrastructure?.environment, - FACTORIZE_PROXY_TUNNEL_PORT: "9090", - FACTORIZE_PROXY_BROWSER_CAPABILITY_PUBLIC_KEY: input.browserCapabilityPublicKey, - }, - services: [ - { protocol: "tcp", internal_port: 8080, ports: [{ port: 443, handlers: ["tls", "http"] }], force_instance_key: true }, - // Private 6PN service for job VMs. Tunnel TLS terminates in the - // credential proxy, where the per-VM client certificate is checked. - { protocol: "tcp", internal_port: 9090, ports: [] }, - ], - metadata: { - factorize_role: "credential-proxy", - factorize_tenant_id: input.tenantId, - factorize_operation_id: input.operationId, - factorize_boot_epoch: candidateBootEpoch, - }, - // The proxy must be explicitly started and must not be restarted after - // process failure with a stale one-use bootstrap credential. - auto_start: false, - auto_stop: false, - restart: { policy: "no" }, - }; - const machine = await options.machines.createMachine(input.app, config, input.operationId); - if (!machine.id) throw new Error("Fly returned a credential proxy Machine without an id"); - try { - const metadata = machine.config?.metadata; - const bootEpoch = metadata?.factorize_boot_epoch; - // The create response is the identity boundary for this Machine. Do not - // infer missing identity from the request: Fly may have reconciled an - // older or foreign Machine for the same operation key, and bootstrap - // authority must only be issued after all returned bindings match. - if (!metadata || !UUID_V4.test(bootEpoch ?? "") || bootEpoch !== candidateBootEpoch - || metadata.factorize_role !== "credential-proxy" - || metadata.factorize_tenant_id !== input.tenantId - || metadata.factorize_operation_id !== input.operationId) { - throw new Error("Fly returned a credential proxy Machine with mismatched provisioning identity"); - } - const proxyIdentity = options.infrastructure?.identity(machine) ?? `fly:${input.app}:${machine.id}`; - if (options.infrastructure) await options.machines.startMachine(input.app, machine.id); - const bootstrap = { - tenantId: input.tenantId, - proxyIdentity, - bootEpoch, - controlOrigin: origin.origin, - browserOrigin: options.infrastructure ? await options.infrastructure.browserOrigin(machine) : `https://${input.app}.fly.dev`, - }; - await provisionCredentialProxy(bootstrap, { - control: options.control, - startProxy: async (request) => { - // Fly Machine startup is explicit. Machine config and metadata only - // hold public identity/configuration; the token crosses stdin. - if (!options.infrastructure) await options.machines.startMachine(input.app, machine.id); - await options.guest(machine).startProxy(request); - }, - }); - return { proxyIdentity, bootEpoch, machine }; - } catch (error) { - // Preserve the sanitized original provisioning failure while making a - // best-effort cleanup of a machine that never completed startup. - await options.machines.destroyMachine(input.app, machine.id).catch(() => undefined); - throw error; - } - }, - }; -} diff --git a/packages/api/src/fly-guest-transport.ts b/packages/api/src/fly-guest-transport.ts deleted file mode 100644 index c17ff2aa..00000000 --- a/packages/api/src/fly-guest-transport.ts +++ /dev/null @@ -1,126 +0,0 @@ -import { mkdtemp, readFile, rm, stat, writeFile } from "node:fs/promises"; -import { tmpdir } from "node:os"; -import { join } from "node:path"; -import { spawn } from "node:child_process"; - -export type FlyGuestErrorKind = "timeout" | "output_limit" | "disconnect" | "transport" | "file_limit"; - -/** Sanitized transport errors never include CLI output, command arguments, or credentials. */ -export class FlyGuestError extends Error { - constructor(readonly kind: FlyGuestErrorKind) { - super(`Fly guest transport ${kind.replace("_", " ")}`); - this.name = "FlyGuestError"; - } -} - -export type FlyGuestCommandResult = { ok: boolean; exitCode: number; stdout: string; stderr: string }; -export type FlyGuestTransportOptions = { - app: string; - machine: string; - token: string; - cliPath?: string; - timeoutMs?: number; - outputLimitBytes?: number; - fileLimitBytes?: number; - /** Subprocess injection is used by deterministic local protocol fixtures. */ - spawnProcess?: typeof spawn; -}; - -function pathSegment(value: string, name: string): string { - if (!value || value === "." || value === ".." || /[\0/\r\n]/.test(value)) throw new TypeError(`${name} must be a path segment`); - return value; -} - -function guestPath(value: string): string { - if (!value.startsWith("/") || value.includes("\0") || value.includes("\r") || value.includes("\n") || value.split("/").some(part => part === "." || part === "..")) { - throw new TypeError("Guest file path must be absolute and normalized"); - } - return value; -} - -export function createFlyGuestTransport(options: FlyGuestTransportOptions) { - pathSegment(options.app, "app"); - pathSegment(options.machine, "machine"); - if (!options.token) throw new TypeError("Fly token is required"); - const timeoutMs = options.timeoutMs ?? 30_000; - const outputLimitBytes = options.outputLimitBytes ?? 1024 * 1024; - const fileLimitBytes = options.fileLimitBytes ?? 16 * 1024 * 1024; - if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 10 * 60_000) throw new TypeError("timeoutMs must be between 1ms and 10 minutes"); - if (!Number.isSafeInteger(outputLimitBytes) || outputLimitBytes < 1 || outputLimitBytes > 16 * 1024 * 1024 || !Number.isSafeInteger(fileLimitBytes) || fileLimitBytes < 1 || fileLimitBytes > 64 * 1024 * 1024) throw new TypeError("transport limits exceed the supported bounds"); - const spawnProcess = options.spawnProcess ?? spawn; - const base = ["--app", options.app, "--machine", options.machine]; - - async function invoke(args: string[], limit = outputLimitBytes, input?: string | Uint8Array): Promise { - return new Promise((resolve, reject) => { - let stdout = Buffer.alloc(0), stderr = Buffer.alloc(0), settled = false, exceeded = false; - const child = spawnProcess(options.cliPath ?? "fly", args, { env: { ...process.env, FLY_API_TOKEN: options.token }, stdio: ["pipe", "pipe", "pipe"], windowsHide: true, detached: process.platform !== "win32" }); - const killTree = () => { - try { - if (child.pid && process.platform !== "win32") process.kill(-child.pid, "SIGKILL"); - else child.kill("SIGKILL"); - } catch { child.kill("SIGKILL"); } - }; - const finishError = (error: FlyGuestError) => { - if (settled) return; - settled = true; - clearTimeout(deadline); - killTree(); - reject(error); - }; - const collect = (current: Buffer, chunk: Buffer): Buffer => { - const remaining = limit - stdout.byteLength - stderr.byteLength; - if (chunk.byteLength > remaining) { - exceeded = true; - return Buffer.concat([current, chunk.subarray(0, Math.max(0, remaining))]); - } - return Buffer.concat([current, chunk]); - }; - child.stdout.on("data", (chunk: Buffer) => { stdout = collect(stdout, chunk); if (exceeded) finishError(new FlyGuestError("output_limit")); }); - child.stderr.on("data", (chunk: Buffer) => { stderr = collect(stderr, chunk); if (exceeded) finishError(new FlyGuestError("output_limit")); }); - child.on("error", () => finishError(new FlyGuestError("transport"))); - const deadline = setTimeout(() => finishError(new FlyGuestError("timeout")), timeoutMs); - child.stdin.end(input); - child.on("close", (code: number | null) => { - if (settled) return; - settled = true; - clearTimeout(deadline); - if (code === null) return reject(new FlyGuestError("disconnect")); - resolve({ ok: code === 0, exitCode: code, stdout: stdout.toString("utf8"), stderr: stderr.toString("utf8") }); - }); - }); - } - - return { - /** Arguments are passed as an argv vector after `--`; no shell parses guest input. */ - run(command: readonly string[], input?: string | Uint8Array): Promise { - if (!command.length || command.some(arg => typeof arg !== "string" || arg.includes("\0"))) throw new TypeError("Guest command must contain valid arguments"); - return invoke(["machine", "exec", options.machine, "--app", options.app, "--no-container", "--timeout", String(Math.max(1, Math.ceil(timeoutMs / 1000))), "--", ...command], outputLimitBytes, input); - }, - async upload(remotePath: string, bytes: Uint8Array): Promise { - remotePath = guestPath(remotePath); - if (bytes.byteLength > fileLimitBytes) throw new FlyGuestError("file_limit"); - const directory = await mkdtemp(join(tmpdir(), "factorize-fly-upload-")); - const localPath = join(directory, "payload"); - try { - await writeFile(localPath, bytes, { mode: 0o600 }); - const result = await invoke(["sftp", "put", localPath, remotePath, ...base, "--no-container", "--user", "root"], 64 * 1024); - if (!result.ok) throw new FlyGuestError("transport"); - } finally { await rm(directory, { recursive: true, force: true }); } - }, - async download(remotePath: string): Promise { - remotePath = guestPath(remotePath); - const directory = await mkdtemp(join(tmpdir(), "factorize-fly-download-")); - const localPath = join(directory, "payload"); - try { - const result = await invoke(["sftp", "get", remotePath, localPath, ...base, "--no-container", "--user", "root"], 64 * 1024); - if (!result.ok) throw new FlyGuestError("transport"); - const size = (await stat(localPath)).size; - if (size > fileLimitBytes) throw new FlyGuestError("file_limit"); - return new Uint8Array(await readFile(localPath)); - } catch (error) { - if (error instanceof FlyGuestError) throw error; - throw new FlyGuestError("transport"); - } finally { await rm(directory, { recursive: true, force: true }); } - }, - }; -} diff --git a/packages/api/src/fly-job-execution-backend.ts b/packages/api/src/fly-job-execution-backend.ts index 8af85f9a..4dca2245 100644 --- a/packages/api/src/fly-job-execution-backend.ts +++ b/packages/api/src/fly-job-execution-backend.ts @@ -1,13 +1,13 @@ import { MachineJobExecutionBackend } from "./machine-job-execution-backend"; import { createFlyHttpGuestTransport } from "./fly-http-guest-transport"; import { flyJobMachineConfig } from "./fly-job-machine"; -export type { JobMachines as FlyJobMachines, JobGuest as FlyJobGuest, ProxyGuest as FlyProxyGuest } from "./machine-job-execution-backend"; +export type { JobMachines as FlyJobMachines, JobGuest as FlyJobGuest } from "./machine-job-execution-backend"; type SharedOptions = ConstructorParameters[0]; /** Preserves persisted Fly handles while sharing the complete guest lifecycle. */ export class FlyJobExecutionBackend extends MachineJobExecutionBackend { - constructor(options: Omit & { region: string; size: string; organizationSlug?: string }) { + constructor(options: Omit & { region: string; size: string; organizationSlug?: string }) { super({ ...options, kind: "fly", @@ -15,8 +15,6 @@ export class FlyJobExecutionBackend extends MachineJobExecutionBackend { runId: request.runId, operationId: request.runId, image: options.image, region: options.region, size: options.size, }), - vmIdentity: machine => `fly:${options.app}:${machine.id}`, - proxyAddress: { host: `${options.app}.internal`, port: 9090 }, ...(options.organizationSlug ? { vendorIdentityIssuer: `https://oidc.fly.io/${options.organizationSlug}` } : {}), vendorIdentityAudience: options.vendorIdentityAudience ?? (runId => `factorize://runs/${runId}`), ...(options.organizationSlug ? { vendorIdentitySubject: machine => machine.name ? `${options.organizationSlug}:${options.app}:${machine.name}` : "" } : {}), @@ -24,7 +22,7 @@ export class FlyJobExecutionBackend extends MachineJobExecutionBackend { } } -/** CLI credentials stay in the scheduler process. */ +/** Fly control credentials stay in the backend and never enter the guest. */ export function flyJobGuest(options: { app: string; machine: string; token: string }) { return createFlyHttpGuestTransport({ ...options, timeoutMs: 30_000, outputLimitBytes: 64 * 1024 }); } diff --git a/packages/api/src/fly-job-tunnel-helper.ts b/packages/api/src/fly-job-tunnel-helper.ts deleted file mode 100644 index 7be0556f..00000000 --- a/packages/api/src/fly-job-tunnel-helper.ts +++ /dev/null @@ -1,58 +0,0 @@ -/** Standalone guest helper for the authenticated Fly-to-proxy TCP tunnel. */ -export const FACTORIZE_FLY_TUNNEL_HELPER = String.raw`import { readFile } from "node:fs/promises"; -import { connect as connectTls } from "node:tls"; -import { createServer } from "node:net"; - -const root = "/home/exedev/.factorize-job/proxy"; -const config = JSON.parse(await readFile(root + "/config.json", "utf8")); -const [key, cert, ca] = await Promise.all(["client.key", "client.crt", "ca.crt"].map(name => readFile(root + "/" + name))); -const tls = { key, cert, ca, rejectUnauthorized: true, servername: config.proxyServerName ?? config.proxyHost }; -const server = createServer(local => { - local.pause(); - let closed = false; - local.once("close", () => { closed = true; }); - void (async () => { - let attempt = 0; - while (!closed && !local.destroyed) { - let remote; - try { - remote = connectTls({ ...tls, host: config.proxyHost, port: config.proxyPort }); - await new Promise((resolve, reject) => { - const timeout = setTimeout(() => remote.destroy(new Error("connect timeout")), 10000); - remote.once("secureConnect", () => { clearTimeout(timeout); resolve(); }); - remote.once("error", error => { clearTimeout(timeout); reject(error); }); - }); - remote.write("FACTORIZE-TUNNEL/3 " + config.runId + "\n"); - await new Promise((resolve, reject) => { - let response = ""; - const timeout = setTimeout(() => reject(new Error("tunnel timeout")), 10000); - const onData = chunk => { - response += chunk.toString("utf8"); - if (response.length > 128) { cleanup(); reject(new Error("invalid tunnel response")); } - else if (response.includes("\n")) { - cleanup(); - response === "FACTORIZE-TUNNEL/1 ACCEPTED\n" ? resolve() : reject(new Error("tunnel rejected")); - } - }; - const cleanup = () => { clearTimeout(timeout); remote.removeListener("data", onData); remote.removeListener("error", onError); }; - const onError = error => { cleanup(); reject(error); }; - remote.on("data", onData); - remote.once("error", onError); - }); - local.pipe(remote); - remote.pipe(local); - local.resume(); - remote.once("close", () => local.destroy()); - local.once("close", () => remote.destroy()); - return; - } catch { - remote?.destroy(); - if (closed || local.destroyed) return; - const delay = Math.min(30000, 1000 * (2 ** Math.min(attempt++, 5))); - await new Promise(resolve => setTimeout(resolve, delay)); - } - } - })(); -}); -server.listen(config.localPort, "127.0.0.1"); -`; diff --git a/packages/api/src/machine-job-execution-backend.ts b/packages/api/src/machine-job-execution-backend.ts index d35bfdb4..36798c0f 100644 --- a/packages/api/src/machine-job-execution-backend.ts +++ b/packages/api/src/machine-job-execution-backend.ts @@ -5,7 +5,6 @@ import { safeDiagnosticText } from "./harness-diagnostics"; import type { TraceChunkCollectionRequest, ArtifactCollectionRequest, ArtifactCollector, ExecutionTerminator, HarnessLogReader, JobFileCollectionRequest, JobFileCollector, JobResultReader } from "./execution"; import { sourceCommand } from "./trace-source"; import { FACTORIZE_JOB_LAUNCHER } from "./factorize-job-launcher"; -import { FACTORIZE_FLY_TUNNEL_HELPER } from "./fly-job-tunnel-helper"; import { traceChunkCommand } from "./guest-artifact-commands"; import { runArtifactTarget } from "./run-artifact-target"; import { shellAtom } from "./exe"; @@ -29,10 +28,6 @@ export type JobGuest = { download?(path: string): Promise; }; -export type ProxyGuest = Pick & { - issueVmCertificate?(input: { bootEpoch: string; vmIdentity: string; csr: string }): Promise<{ certificate: string; trustBundle: string }>; -}; - const capabilities = ["stop", "recovery"] as const; /** Shared Machine lifecycle orchestration. Machine creation is idempotent by run ID; @@ -43,18 +38,13 @@ export class MachineJobExecutionBackend implements ExecutionBackend, JobResultRe constructor( private readonly options: { - kind: "fly" | "docker"; + kind: "fly"; prepare?: () => Promise; machineConfig: (request: LaunchRequest) => JobMachineConfig; - vmIdentity: (machine: JobMachine) => string; - proxyAddress: { host: string; port: number; serverName?: string }; app: string; image: string; machines: JobMachines; guest: (machine: JobMachine) => JobGuest; - proxyIdentity?: string; - proxyBootEpoch?: string; - proxyGuest?: ProxyGuest; destinationUrl?: (machine: JobMachine) => string; vendorIdentityAudience?: (runId: string) => string; vendorIdentitySubject?: (machine: JobMachine) => string; @@ -94,14 +84,6 @@ export class MachineJobExecutionBackend implements ExecutionBackend, JobResultRe if (!machine.id) throw new Error("Fly returned a Machine without an id"); const actualHandle = { backendKind: this.kind, id: `${this.options.app}/${machine.id}`, operationId, ...(request.runIdentity ? {identityProxyOrigin: request.runIdentity.backendOrigin} : {}) }; try { - if (request.runProxy) { - if (!this.options.proxyIdentity || !this.options.proxyBootEpoch || !this.options.proxyGuest?.issueVmCertificate) throw new Error("Fly credential proxy delivery is unavailable"); - const vmIdentity = this.options.vmIdentity(machine); - const delivered = await this.options.proxyGuest.run(["/usr/local/bin/factorize-proxy-authorize-run"], `${JSON.stringify({ - runId: request.runId, vmIdentity, credential: request.runProxy.credential, - })}\n`); - if (!delivered.ok || delivered.stdout.trim() !== "Run credential delivered to proxy memory") throw new Error("Fly credential proxy did not confirm run credential delivery"); - } await this.options.machines.startMachine(this.options.app, machine.id); const guest = this.options.guest(machine); const verifyVendorIdentity = request.verifyVendorIdentity ?? this.options.verifyVendorIdentity; @@ -113,42 +95,15 @@ export class MachineJobExecutionBackend implements ExecutionBackend, JobResultRe if (this.options.vendorIdentitySubject && !expectedSubject) throw new Error("Fly vendor identity subject is unavailable"); await verifyVendorIdentity({ provider: "fly.io", vmId: machine.id, token, ...(this.options.vendorIdentityIssuer ? { expectedIssuer: this.options.vendorIdentityIssuer } : {}), ...(expectedSubject ? { expectedSubject } : {}) }); } - const tunnelPrerequisites = request.runProxy ? " && command -v node >/dev/null && command -v openssl >/dev/null" : request.runIdentity ? " && command -v node >/dev/null && command -v curl >/dev/null" : ""; + const tunnelPrerequisites = request.runIdentity ? " && command -v node >/dev/null && command -v curl >/dev/null" : ""; const installed = await guest.run(["/bin/sh", "-c", `command -v python3 >/dev/null && command -v runuser >/dev/null${tunnelPrerequisites} && id exedev >/dev/null && mkdir -p /usr/local/bin && install -d -o exedev -g exedev -m 0700 /home/exedev/.factorize-job && cat > /usr/local/bin/factorize-job && chmod 0755 /usr/local/bin/factorize-job`], FACTORIZE_JOB_LAUNCHER); - if (!installed.ok) throw new Error(request.runProxy - ? "Fly guest is missing python3, runuser, Node.js, OpenSSL, or the exedev user, or could not install the shared Factorize job launcher" - : "Fly guest is missing python3, runuser, or the exedev user, or could not install the shared Factorize job launcher"); + if (!installed.ok) throw new Error("Fly guest is missing the shared launcher or vendor identity helper prerequisites"); if (request.harness?.executable === "codex") { const version = await guest.run(["/usr/sbin/runuser", "-u", "exedev", "--", "codex", "--version"]); if (!version.ok || version.stdout.trim() !== SUPPORTED_CODEX_CLI_VERSION) { throw new Error(`Fly guest requires ${SUPPORTED_CODEX_CLI_VERSION} for Codex jobs`); } } - if (request.runProxy) { - if (!guest.upload) throw new Error("Fly guest transport cannot install the credential proxy tunnel helper"); - const vmIdentity = this.options.vmIdentity(machine); - const proxyHost = this.options.proxyAddress.host; - const proxyPort = this.options.proxyAddress.port; - const localPort = 18180; - const directory = "/home/exedev/.factorize-job/proxy"; - const directoryReady = await guest.run(["/usr/bin/install", "-d", "-o", "exedev", "-g", "exedev", "-m", "0700", directory]); - if (!directoryReady.ok) throw new Error("Fly guest could not prepare its proxy tunnel directory"); - const prepared = await guest.run(["/usr/bin/openssl", "req", "-new", "-newkey", "ec", "-pkeyopt", "ec_paramgen_curve:P-256", "-nodes", "-keyout", `${directory}/client.key`, "-out", `${directory}/client.csr`, "-subj", `/CN=${vmIdentity}`]); - if (!prepared.ok) throw new Error("Fly guest could not create its proxy tunnel identity"); - const csr = await guest.run(["/bin/cat", `${directory}/client.csr`]); - if (!csr.ok) throw new Error("Fly guest did not return its proxy tunnel certificate request"); - const issued = await this.options.proxyGuest!.issueVmCertificate!({ bootEpoch: this.options.proxyBootEpoch!, vmIdentity, csr: csr.stdout.trim() }); - const configured = await guest.run(["/bin/sh", "-c", `install -d -o exedev -g exedev -m 0700 ${directory} && chown exedev:exedev ${directory}/client.key && chmod 0600 ${directory}/client.key && cat > ${directory}/certificates.json`], JSON.stringify({ certificate: issued.certificate, trustBundle: issued.trustBundle })); - if (!configured.ok) throw new Error("Fly guest could not install its proxy tunnel certificate"); - const extracted = await guest.run(["node", "-e", `const fs=require('node:fs');const p=${JSON.stringify(directory)};const v=JSON.parse(fs.readFileSync(p+'/certificates.json','utf8'));if(typeof v.certificate!=='string'||typeof v.trustBundle!=='string')process.exit(2);fs.writeFileSync(p+'/client.crt',v.certificate,{mode:0o600});fs.writeFileSync(p+'/ca.crt',v.trustBundle,{mode:0o600});fs.unlinkSync(p+'/certificates.json');`]); - if (!extracted.ok || !guest.upload) throw new Error("Fly guest could not prepare its proxy tunnel certificate files"); - const config = { runId: request.runId, proxyHost, proxyPort, localPort, proxyServerName: this.options.proxyAddress.serverName ?? proxyHost }; - const tunnelConfig = await guest.run(["/bin/sh", "-c", `chown exedev:exedev ${directory}/client.crt ${directory}/ca.crt && cat > ${directory}/config.json`], JSON.stringify(config)); - if (!tunnelConfig.ok) throw new Error("Fly guest could not configure its proxy tunnel"); - await guest.upload(`${directory}/tunnel.mjs`, new TextEncoder().encode(FACTORIZE_FLY_TUNNEL_HELPER)); - const startTunnel = await guest.run(["/bin/sh", "-c", `chown exedev:exedev ${directory}/config.json ${directory}/tunnel.mjs && chmod 0600 ${directory}/config.json ${directory}/tunnel.mjs && (nohup /usr/sbin/runuser -u exedev -- /usr/bin/env PATH=/usr/local/bin:/usr/bin:/bin node ${directory}/tunnel.mjs >/tmp/factorize-proxy-tunnel.log 2>&1 /tmp/factorize-proxy-tunnel.pid) && sleep 1 && kill -0 "$(cat /tmp/factorize-proxy-tunnel.pid)"`]); - if (!startTunnel.ok) throw new Error("Fly guest could not start its credential proxy tunnel"); - } if (request.runIdentity) { if (!guest.upload) throw new Error("Fly guest cannot install the vendor identity helper"); const directory = "/run/factorize-identity"; @@ -160,7 +115,7 @@ export class MachineJobExecutionBackend implements ExecutionBackend, JobResultRe if (!started.ok) throw new Error("Fly guest vendor identity helper did not become ready"); } const payload = JSON.stringify({ version: 1, runId: request.runId, ...(request.code ? { code: request.code } : { prompt: request.prompt, harness: request.harness }), ...(request.traceSources ? { traceSources: request.traceSources } : {}) }); - const launchCommand = request.runProxy || request.runIdentity + const launchCommand = request.runIdentity ? ["/usr/sbin/runuser", "-u", "exedev", "--", "/usr/bin/env", "FACTORIZE_PROXY_URL=http://127.0.0.1:18180", "/usr/local/bin/factorize-job", "launch"] : ["/usr/sbin/runuser", "-u", "exedev", "--", "/usr/local/bin/factorize-job", "launch"]; const started = await guest.run(launchCommand, `${payload}\n`); @@ -248,7 +203,7 @@ export class MachineJobExecutionBackend implements ExecutionBackend, JobResultRe } async listJobFiles(handle: RunHandle): Promise { - const result = await (await this.guestFor(handle)).run(["/bin/sh", "-c", "find /home/exedev/.factorize-job -mindepth 1 -path /home/exedev/.factorize-job/proxy -prune -o -type f ! -name results.json -printf '%P\\t%s\\n'"]); + const result = await (await this.guestFor(handle)).run(["/bin/sh", "-c", "find /home/exedev/.factorize-job -mindepth 1 -type f ! -name results.json -printf '%P\\t%s\\n'"]); if (!result.ok) throw new Error("Fly job output directory collection failed"); const paths: string[] = []; let total = 0; for (const line of result.stdout.split("\n").filter(Boolean)) { diff --git a/packages/api/src/managed-model-credentials.ts b/packages/api/src/managed-model-credentials.ts index c1ab23eb..0748d445 100644 --- a/packages/api/src/managed-model-credentials.ts +++ b/packages/api/src/managed-model-credentials.ts @@ -1,9 +1,8 @@ import type { Database } from "./postgres/database"; import type { Env } from "./types"; -import { EncryptedIntegrationRepository } from "./postgres/encrypted-integration-repository"; +import { CredentialRepository } from "./postgres/credential-repository"; -const CLIENT_ID = "app_EMoamEEZ73f0CkXaXp7hrann"; -const REFRESH_ORIGIN = "https://auth.openai.com"; +import {CODEX_CLIENT_ID as CLIENT_ID, CODEX_AUTH_ORIGIN as REFRESH_ORIGIN} from "./model-device-auth"; type Cache = { OPENAI_API_KEY?: unknown; tokens?: { access_token?: unknown; refresh_token?: unknown; id_token?: unknown; account_id?: unknown; chatgpt_account_id?: unknown; oauth_provenance?: { issuer?: unknown; client_id?: unknown } }; last_refresh?: unknown }; function cache(payload: string): Cache { const result = JSON.parse(payload); @@ -27,7 +26,7 @@ function needsRefresh(auth: Cache): boolean { /** Codex's published OAuth refresh protocol, restricted to its trusted issuer. * No guest-supplied endpoint or client can receive the refresh credential. */ export async function resolveManagedModelCredential(input: { database: Database; env: Env; tenantId: string; accountId: string }): Promise<{ origin: string; prefix: string; accessToken: string; accountId?: string } | null> { - const repository = new EncryptedIntegrationRepository(input.database, input.tenantId, input.env.CREDENTIAL_ENCRYPTION_KEY); + const repository = new CredentialRepository(input.database, input.tenantId, input.env.CREDENTIAL_ENCRYPTION_KEY); const current = await repository.managedCredential(input.accountId, "model"); if (!current) return null; let payload: string | null = current.payload; diff --git a/packages/api/src/model-device-auth.ts b/packages/api/src/model-device-auth.ts new file mode 100644 index 00000000..61a246f5 --- /dev/null +++ b/packages/api/src/model-device-auth.ts @@ -0,0 +1,88 @@ +import {z} from "zod"; +import {decrypt, encrypt} from "./crypto"; +import type {Env, OAuthProps} from "./types"; +import {databaseFor} from "./postgres/database"; +import {CredentialRepository} from "./postgres/credential-repository"; + +export const CODEX_AUTH_ORIGIN = "https://auth.openai.com"; +export const CODEX_CLIENT_ID = "app_EMoamEEZ73f0CkXaXp7hrann"; +export const modelAuthorizationState = z.object({ + state: z.enum(["pending", "authorized", "idle", "canceled", "expired", "failed", "reauthentication-required"]), + verificationUrl: z.literal("https://auth.openai.com/codex/device").optional(), userCode: z.string().optional(), pollAfterSeconds: z.number().int().min(1).max(30).optional(), +}); +type State = z.infer; +type Pending = {deviceAuthId: string; userCode: string; interval: number}; +export class ModelAuthorizationUnavailable extends Error { constructor() {super("Model account authorization is unavailable. Try connecting again.");} } +export class ModelAccountUnavailable extends Error { constructor() {super("Model account not found.");} } +const value = (v: unknown, max=16_384): v is string => typeof v==="string" && v.length>0 && v.length<=max && !/[\r\n]/.test(v); +export function modelCredentialConfigured(payload: string): boolean { + try {const auth=JSON.parse(payload); return value(auth.OPENAI_API_KEY) || value(auth.tokens?.access_token);} + catch {return false;} +} +async function post(path: string, body: unknown, form=false): Promise { + return fetch(`${CODEX_AUTH_ORIGIN}${path}`, {method: "POST", headers: {"Content-Type": form ? "application/x-www-form-urlencoded" : "application/json", Accept: "application/json"}, body: form ? String(body) : JSON.stringify(body), redirect: "error", signal: AbortSignal.timeout(10_000)}); +} +const challenge = (pending: Pending): State => ({state: "pending", verificationUrl: "https://auth.openai.com/codex/device", userCode: pending.userCode, pollAfterSeconds: pending.interval}); + +/** Owner-only device login. All device IDs, PKCE/code exchanges and tokens stay + * server-side; only a one-time user code and fixed verification URL are public. + * Collection/account locks serialize login, refresh, rotation and disconnection. */ +export async function modelDeviceAuthorization(env: Env, owner: OAuthProps, accountId: string, action: "authorize" | "status" | "cancel"): Promise { + const database=databaseFor(env), repository=new CredentialRepository(database, owner.tenantId, env.CREDENTIAL_ENCRYPTION_KEY); + let result: State={state: "idle"}; + try { + const saved=await repository.refreshManagedModel(accountId, async (payload, client) => { + const row=(await client.query<{user_id: string; session_version: number; encrypted_payload: string; expires_at: Date; next_poll_at: Date}>("SELECT user_id,session_version,encrypted_payload,expires_at,next_poll_at FROM app.model_device_authorizations WHERE tenant_id=$1 AND account_id=$2 FOR UPDATE", [owner.tenantId,accountId])).rows[0]; + const clear=()=>client.query("DELETE FROM app.model_device_authorizations WHERE tenant_id=$1 AND account_id=$2", [owner.tenantId,accountId]); + if (action==="cancel") {await clear(); result={state:"canceled"}; return payload;} + const live=row && row.expires_at.getTime()>Date.now() && row.user_id===owner.userId && row.session_version===owner.sessionVersion; + let pending: Pending | undefined; + if (live) pending=JSON.parse(await decrypt(row.encrypted_payload,env.CREDENTIAL_ENCRYPTION_KEY)); + if (action==="authorize") { + if (pending) {result=challenge(pending); return payload;} + const response=await post("/api/accounts/deviceauth/usercode", {client_id:CODEX_CLIENT_ID}); + if (!response.ok) {await response.body?.cancel(); throw new ModelAuthorizationUnavailable();} + const data=await response.json() as Record; + const userCode=data.user_code ?? data.usercode, interval=Math.max(1,Math.min(30,Number(data.interval) || 5)); + if (!value(data.device_auth_id,4096) || !value(userCode,128) || !Number.isInteger(interval)) throw new ModelAuthorizationUnavailable(); + pending={deviceAuthId:data.device_auth_id,userCode,interval}; + const encrypted=await encrypt(JSON.stringify(pending),env.CREDENTIAL_ENCRYPTION_KEY); + await client.query(`INSERT INTO app.model_device_authorizations(tenant_id,account_id,user_id,session_version,encrypted_payload,expires_at,next_poll_at) + VALUES($1,$2,$3,$4,$5,now()+interval '15 minutes',now()+($6::int*interval '1 second')) + ON CONFLICT(tenant_id,account_id) DO UPDATE SET user_id=excluded.user_id,session_version=excluded.session_version,encrypted_payload=excluded.encrypted_payload,expires_at=excluded.expires_at,next_poll_at=excluded.next_poll_at`, [owner.tenantId,accountId,owner.userId,owner.sessionVersion,encrypted,interval]); + result=challenge(pending); return payload; + } + if (!pending) {if(row) await clear(); result={state:row ? "expired" : modelCredentialConfigured(payload) ? "authorized" : "idle"}; return payload;} + if (row!.next_poll_at.getTime()>Date.now()) {result=challenge(pending); return payload;} + const response=await post("/api/accounts/deviceauth/token", {device_auth_id:pending.deviceAuthId,user_code:pending.userCode}); + if (response.status===403 || response.status===404) { + await response.body?.cancel(); + await client.query("UPDATE app.model_device_authorizations SET next_poll_at=now()+($3::int*interval '1 second') WHERE tenant_id=$1 AND account_id=$2",[owner.tenantId,accountId,pending.interval]); + result=challenge(pending); return payload; + } + if (!response.ok) {await response.body?.cancel(); await clear(); result={state:"failed"}; return payload;} + const code=await response.json() as Record; + if (!value(code.authorization_code,4096) || !value(code.code_verifier,4096) || !value(code.code_challenge,4096)) {await clear(); result={state:"failed"}; return payload;} + const digest=Buffer.from(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(code.code_verifier))).toString("base64url"); + if (digest!==code.code_challenge) {await clear(); result={state:"failed"}; return payload;} + // A code may have been consumed even on a failed response. Do not retry + // this token exchange or overwrite an existing credential on ambiguity. + let tokens: Record; + try { + const exchanged=await post("/oauth/token",new URLSearchParams({grant_type:"authorization_code",client_id:CODEX_CLIENT_ID,code:code.authorization_code,code_verifier:code.code_verifier,redirect_uri:`${CODEX_AUTH_ORIGIN}/deviceauth/callback`}),true); + if (!exchanged.ok) {await exchanged.body?.cancel(); throw new Error();} + tokens=await exchanged.json() as Record; + if (!value(tokens.access_token) || !value(tokens.refresh_token) || !value(tokens.id_token)) throw new Error(); + } catch {await clear(); result={state:"reauthentication-required"}; return payload;} + let account: unknown; + try {account=JSON.parse(Buffer.from(String(tokens.id_token).split(".")[1]!,"base64url").toString("utf8"))["https://api.openai.com/auth"]?.chatgpt_account_id;} catch { /* The upstream access token can select its default account. */ } + await clear(); result={state:"authorized"}; + return JSON.stringify({auth_mode:"chatgpt",OPENAI_API_KEY:null,tokens:{...tokens,...(value(account,512) ? {account_id:account} : {}),oauth_provenance:{issuer:CODEX_AUTH_ORIGIN,client_id:CODEX_CLIENT_ID}},last_refresh:new Date().toISOString()}); + }); + if (saved===null) throw new ModelAccountUnavailable(); + return result; + } catch (error) { + if (error instanceof ModelAccountUnavailable) throw error; + throw new ModelAuthorizationUnavailable(); + } +} diff --git a/packages/api/src/postgres/credential-repository.ts b/packages/api/src/postgres/credential-repository.ts new file mode 100644 index 00000000..aa16d7e4 --- /dev/null +++ b/packages/api/src/postgres/credential-repository.ts @@ -0,0 +1,160 @@ +import {decrypt, encrypt} from "../crypto"; +import type {Database, DatabaseClient} from "./database"; + +export type IntegrationKind = "bearer" | "model"; +export type IntegrationMetadata = {id: string; kind: IntegrationKind; name: string; origin: string | null; description: string | null}; +export type IntegrationWrite = IntegrationMetadata & {expectedRevision: number; idempotencyKey: string; operation: "upsert" | "delete"; managedSecret?: string; managedModelPayload?: string}; +export const MANAGED_BEARER_PREFIX = "factorize-managed-bearer-v1:"; +export const MANAGED_MODEL_PREFIX = "factorize-managed-model-cache-v1:"; +export class StaleIntegrationRevisionError extends Error { constructor(readonly currentRevision: number) {super("Integration collection revision is stale"); this.name="StaleIntegrationRevisionError";} } +export class IntegrationIdempotencyConflictError extends Error { constructor() {super("Integration idempotency key was already used for a different change"); this.name="IntegrationIdempotencyConflictError";} } +export class IntegrationValidationError extends Error { constructor(message: string) {super(message); this.name="IntegrationValidationError";} } +type StoredChange = {revision: string | number; operation: "upsert" | "delete"; record_id: string; kind: IntegrationKind; name: string; origin: string | null; description: string | null; encrypted_payload: string | null}; +function safeRevision(value: string | number): number { const revision=Number(value); if (!Number.isSafeInteger(revision) || revision<0) throw new Error("Stored integration revision exceeds supported range"); return revision; } +function validate(change: IntegrationWrite): void { + if (!Number.isSafeInteger(change.expectedRevision) || change.expectedRevision<0) throw new IntegrationValidationError("expectedRevision must be a non-negative safe integer"); + const uuid=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; + if (!uuid.test(change.id) || !uuid.test(change.idempotencyKey)) throw new IntegrationValidationError("id and idempotencyKey must be UUIDs"); + if (change.kind!=="bearer" && change.kind!=="model") throw new IntegrationValidationError("Unsupported integration kind"); + if (!change.name.trim() || change.name.length>120 || (change.description!==null && change.description.length>500)) throw new IntegrationValidationError("Invalid integration metadata"); + if (change.kind==="bearer" && (!change.origin || change.origin.length>2048)) throw new IntegrationValidationError("Bearer integrations require an origin"); + if (change.kind==="model" && change.origin!==null) throw new IntegrationValidationError("Model accounts do not have an origin"); + if (change.kind!=="bearer" && change.managedSecret!==undefined || change.kind!=="model" && change.managedModelPayload!==undefined) throw new IntegrationValidationError("Credential kind does not match its payload"); + if (change.operation==="delete") { if (change.managedSecret!==undefined || change.managedModelPayload!==undefined) throw new IntegrationValidationError("Deletions cannot contain a credential"); return; } + if (change.operation!=="upsert") throw new IntegrationValidationError("Invalid credential operation"); + if (change.kind==="bearer" && (typeof change.managedSecret!=="string" || !change.managedSecret || change.managedSecret.length>32768 || /[\r\n]/.test(change.managedSecret))) throw new IntegrationValidationError("A bearer credential value is required"); + if (change.kind==="model") { + try { const value=JSON.parse(change.managedModelPayload ?? ""); if (!value || typeof value!=="object" || Array.isArray(value) || change.managedModelPayload!.length>65536) throw new Error(); } + catch { throw new IntegrationValidationError("A model credential object is required"); } + } +} + +/** All credentials are encrypted by Factorize. Public reads expose metadata + * only; exactly selected credentials are resolved through managedCredential. */ +export class CredentialRepository { + constructor(private database: Database, private tenantId: string, private serverEncryptionKey: string) {if (!tenantId) throw new Error("tenantId is required");} + async revision(): Promise { + const { rows } = await this.database.pool.query<{ revision: string | number }>("SELECT revision FROM app.integration_collections WHERE tenant_id=$1", [this.tenantId]); + return rows.length ? safeRevision(rows[0]!.revision) : 0; + } + + /** Recognize an exact retry before collection-level create checks run. */ + async replay(input: IntegrationWrite): Promise<{ revision: number; duplicate: true } | null> { + validate(input); + const { rows } = await this.database.pool.query("SELECT revision,operation,record_id,kind,name,origin,description,encrypted_payload FROM app.integration_changes WHERE tenant_id=$1 AND idempotency_key=$2", [this.tenantId, input.idempotencyKey]); + const row = rows[0]; + if (!row) return null; + const suppliedPayload = input.managedSecret !== undefined ? `${MANAGED_BEARER_PREFIX}${input.managedSecret}` + : input.managedModelPayload !== undefined ? `${MANAGED_MODEL_PREFIX}${input.managedModelPayload}` : undefined; + const sameCiphertext = row.encrypted_payload === null + ? input.operation === "delete" + : input.operation === "upsert" && typeof suppliedPayload === "string" && await decrypt(row.encrypted_payload, this.serverEncryptionKey) === suppliedPayload; + if (row.record_id !== input.id || row.kind !== input.kind || row.name !== input.name || row.origin !== input.origin + || row.description !== input.description || row.operation !== input.operation || !sameCiphertext) { + throw new IntegrationIdempotencyConflictError(); + } + return { revision: safeRevision(row.revision), duplicate: true }; + } + + /** Recognize a delete retry after its active record has already become a tombstone. */ + async replayDelete(id: string, kind: IntegrationKind, idempotencyKey: string): Promise<{ revision: number; duplicate: true } | null> { + const uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; + if (!uuid.test(id) || !uuid.test(idempotencyKey)) throw new IntegrationValidationError("id and idempotencyKey must be UUIDs"); + const { rows } = await this.database.pool.query("SELECT revision,operation,record_id,kind,name,origin,description,encrypted_payload FROM app.integration_changes WHERE tenant_id=$1 AND idempotency_key=$2", [this.tenantId, idempotencyKey]); + const row = rows[0]; + if (!row) return null; + if (row.record_id !== id || row.kind !== kind || row.operation !== "delete" || row.encrypted_payload !== null) throw new IntegrationIdempotencyConflictError(); + return { revision: safeRevision(row.revision), duplicate: true }; + } + + async write(input: IntegrationWrite): Promise<{ revision: number; duplicate: boolean }> { + validate(input); + const suppliedPayload = input.managedSecret !== undefined ? `${MANAGED_BEARER_PREFIX}${input.managedSecret}` + : input.managedModelPayload !== undefined ? `${MANAGED_MODEL_PREFIX}${input.managedModelPayload}` : undefined; + const encryptedPayload = input.operation === "upsert" ? await encrypt(suppliedPayload!, this.serverEncryptionKey) : null; + const metadata = [input.id, input.kind, input.name, input.origin, input.description, input.operation, encryptedPayload]; + return this.database.transaction(async client => { + const existing = async () => (await client.query("SELECT revision,operation,record_id,kind,name,origin,description,encrypted_payload FROM app.integration_changes WHERE tenant_id=$1 AND idempotency_key=$2", [this.tenantId, input.idempotencyKey])).rows[0]; + const isSame = async (row: StoredChange) => row.record_id === metadata[0] && row.kind === metadata[1] && row.name === metadata[2] && row.origin === metadata[3] && row.description === metadata[4] && row.operation === metadata[5] && (row.encrypted_payload === null ? encryptedPayload === null : encryptedPayload !== null && await decrypt(row.encrypted_payload, this.serverEncryptionKey) === suppliedPayload); + const duplicate = await existing(); + if (duplicate) { + if (!await isSame(duplicate)) throw new IntegrationIdempotencyConflictError(); + return { revision: safeRevision(duplicate.revision), duplicate: true }; + } + + await client.query("INSERT INTO app.integration_collections(tenant_id) VALUES ($1) ON CONFLICT DO NOTHING", [this.tenantId]); + const bumped = await client.query<{ revision: string | number }>("UPDATE app.integration_collections SET revision=revision+1,updated_at=now() WHERE tenant_id=$1 AND revision=$2 RETURNING revision", [this.tenantId, input.expectedRevision]); + if (!bumped.rows.length) { + const racedDuplicate = await existing(); + if (racedDuplicate) { + if (!await isSame(racedDuplicate)) throw new IntegrationIdempotencyConflictError(); + return { revision: safeRevision(racedDuplicate.revision), duplicate: true }; + } + const current = await client.query<{ revision: string | number }>("SELECT revision FROM app.integration_collections WHERE tenant_id=$1", [this.tenantId]); + throw new StaleIntegrationRevisionError(safeRevision(current.rows[0]!.revision)); + } + const revision = safeRevision(bumped.rows[0]!.revision); + + if (input.operation === "upsert") { + await client.query(`INSERT INTO app.integration_records(tenant_id,id,kind,name,origin,description,revision,encrypted_payload,deleted_at) + VALUES ($1,$2,$3,$4,$5,$6,$7,$8,NULL) + ON CONFLICT (tenant_id,id) DO UPDATE SET kind=excluded.kind,name=excluded.name,origin=excluded.origin,description=excluded.description,revision=excluded.revision,encrypted_payload=excluded.encrypted_payload,deleted_at=NULL,updated_at=now()`, + [this.tenantId, input.id, input.kind, input.name, input.origin, input.description, revision, encryptedPayload]); + } else { + await client.query(`INSERT INTO app.integration_records(tenant_id,id,kind,name,origin,description,revision,encrypted_payload,deleted_at) + VALUES ($1,$2,$3,$4,$5,$6,$7,NULL,now()) + ON CONFLICT (tenant_id,id) DO UPDATE SET kind=excluded.kind,name=excluded.name,origin=excluded.origin,description=excluded.description,revision=excluded.revision,encrypted_payload=NULL,deleted_at=now(),updated_at=now()`, + [this.tenantId, input.id, input.kind, input.name, input.origin, input.description, revision]); + } + if (input.kind === "model") await client.query("DELETE FROM app.model_device_authorizations WHERE tenant_id=$1 AND account_id=$2", [this.tenantId, input.id]); + await client.query(`INSERT INTO app.integration_changes(tenant_id,revision,id,idempotency_key,operation,record_id,kind,name,origin,description,encrypted_payload) + VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11)`, [this.tenantId, revision, crypto.randomUUID(), input.idempotencyKey, input.operation, input.id, input.kind, input.name, input.origin, input.description, encryptedPayload]); + return { revision, duplicate: false }; + }); + } + + /** Resolve exactly one selected live credential. Legacy user ciphertext is + * deliberately unavailable to the managed backend and requires re-entry. */ + async managedCredential(id: string, kind: IntegrationKind): Promise<(IntegrationMetadata & { revision: number; payload: string }) | null> { + const row = (await this.database.pool.query<{ id: string; kind: IntegrationKind; name: string; origin: string | null; description: string | null; revision: string | number; encrypted_payload: string }>( + "SELECT id,kind,name,origin,description,revision,encrypted_payload FROM app.integration_records WHERE tenant_id=$1 AND id=$2 AND kind=$3 AND deleted_at IS NULL", [this.tenantId, id, kind])).rows[0]; + if (!row) return null; + const plain = await decrypt(row.encrypted_payload, this.serverEncryptionKey); + const prefix = kind === "bearer" ? MANAGED_BEARER_PREFIX : MANAGED_MODEL_PREFIX; + if (!plain.startsWith(prefix)) return null; + return { id: row.id, kind: row.kind, name: row.name, origin: row.origin, description: row.description, + revision: safeRevision(row.revision), payload: plain.slice(prefix.length) }; + } + + /** Serialize refresh across backend instances. Lock order matches writes: + * collection first, then the selected credential. A disconnect/reconnect + * cannot be overwritten by a delayed refresh. */ + async refreshManagedModel(id: string, refresh: (payload: string, client: DatabaseClient) => Promise): Promise { + return this.database.transaction(async client => { + const collection = (await client.query<{ revision: string | number }>("SELECT revision FROM app.integration_collections WHERE tenant_id=$1 FOR UPDATE", [this.tenantId])).rows[0]; + if (!collection) return null; + const row = (await client.query<{ revision: string | number; encrypted_payload: string; name: string; description: string | null }>( + "SELECT revision,encrypted_payload,name,description FROM app.integration_records WHERE tenant_id=$1 AND id=$2 AND kind='model' AND deleted_at IS NULL FOR UPDATE", [this.tenantId, id])).rows[0]; + if (!row) return null; + const plain = await decrypt(row.encrypted_payload, this.serverEncryptionKey); + if (!plain.startsWith(MANAGED_MODEL_PREFIX)) return null; + const payload = plain.slice(MANAGED_MODEL_PREFIX.length); + const updated = await refresh(payload, client); + if (updated === payload) return payload; + if (updated.length > 65_536) throw new IntegrationValidationError("Model cache exceeds its limit"); + const encrypted = await encrypt(`${MANAGED_MODEL_PREFIX}${updated}`, this.serverEncryptionKey); + const revision = safeRevision(collection.revision) + 1; + await client.query("UPDATE app.integration_collections SET revision=$2,updated_at=now() WHERE tenant_id=$1", [this.tenantId, revision]); + await client.query("UPDATE app.integration_records SET revision=revision+1,encrypted_payload=$3,updated_at=now() WHERE tenant_id=$1 AND id=$2", [this.tenantId, id, encrypted]); + await client.query(`INSERT INTO app.integration_changes(tenant_id,revision,id,idempotency_key,operation,record_id,kind,name,origin,description,encrypted_payload) + VALUES($1,$2,$3,$4,'upsert',$5,'model',$6,NULL,$7,$8)`, [this.tenantId, revision, crypto.randomUUID(), crypto.randomUUID(), id, row.name, row.description, encrypted]); + return updated; + }); + } + + async metadata(kind?: IntegrationKind): Promise> { + const {rows}=await this.database.pool.query<{id: string; kind: IntegrationKind; name: string; origin: string | null; description: string | null; revision: string | number}>( + `SELECT id,kind,name,origin,description,revision FROM app.integration_records WHERE tenant_id=$1 AND deleted_at IS NULL${kind ? " AND kind=$2" : ""} ORDER BY revision,id`, kind ? [this.tenantId,kind] : [this.tenantId]); + return rows.map(row=>({...row,revision:safeRevision(row.revision)})); + } +} diff --git a/packages/api/src/postgres/encrypted-integration-repository.ts b/packages/api/src/postgres/encrypted-integration-repository.ts deleted file mode 100644 index 2212ba8f..00000000 --- a/packages/api/src/postgres/encrypted-integration-repository.ts +++ /dev/null @@ -1,399 +0,0 @@ -import { decrypt, encrypt } from "../crypto"; -import type { Database } from "./database"; - -export type EncryptedIntegrationKind = "bearer" | "model"; -export type IntegrationMetadata = { id: string; kind: EncryptedIntegrationKind; name: string; origin: string | null; description: string | null }; -export type IntegrationWrite = IntegrationMetadata & { - expectedRevision: number; - idempotencyKey: string; - operation: "upsert" | "delete"; - /** Ciphertext produced with the user's unlock key. This repository never interprets it. */ - encryptedPayload?: string; - /** Plaintext bearer value accepted only by the owner-session credential API. */ - managedSecret?: string; - /** Initial model cache accepted only by the owner-session model-account API. */ - managedModelPayload?: string; -}; -export type IntegrationChange = IntegrationMetadata & { - revision: number; - operation: "upsert" | "delete"; - encryptedPayload: string | null; -}; - -export type GenerationRecord = IntegrationMetadata & { revision: number; encryptedPayload: string | null; deletedAt: Date | null }; -export type GenerationChange = IntegrationMetadata & { revision: number; idempotencyKey: string; operation: "upsert" | "delete"; encryptedPayload: string | null }; - -const MANAGED_BEARER_PREFIX = "factorize-managed-bearer-v1:"; -const MANAGED_MODEL_PREFIX = "factorize-managed-model-cache-v1:"; - -export class StaleIntegrationRevisionError extends Error { - constructor(readonly currentRevision: number, readonly resyncRequired = false) { super(resyncRequired ? "Integration change history expired; fetch the current collection before continuing" : "Integration collection revision is stale"); this.name = "StaleIntegrationRevisionError"; } -} -export class IntegrationIdempotencyConflictError extends Error { - constructor() { super("Integration idempotency key was already used for a different change"); this.name = "IntegrationIdempotencyConflictError"; } -} -export class StaleIntegrationGenerationError extends Error { - constructor(readonly currentRevision: number) { super("Integration generation changed while rotation was staged"); this.name = "StaleIntegrationGenerationError"; } -} -export class IntegrationValidationError extends Error { - constructor(message: string) { super(message); this.name = "IntegrationValidationError"; } -} - -type StoredChange = { - revision: string | number; operation: "upsert" | "delete"; record_id: string; kind: EncryptedIntegrationKind; - name: string; origin: string | null; description: string | null; encrypted_payload: string | null; -}; - -function safeRevision(value: string | number): number { - const number = Number(value); - if (!Number.isSafeInteger(number) || number < 0) throw new Error("Stored integration revision exceeds supported range"); - return number; -} - -function isUserCiphertext(value: string): boolean { - if (value.length > 65_536) return false; - const [encodedIv, encodedBody, extra] = value.split("."); - if (!encodedIv || !encodedBody || extra !== undefined) return false; - try { - const iv = atob(encodedIv), body = atob(encodedBody); - return iv.length === 12 && body.length >= 16 - && btoa(iv) === encodedIv && btoa(body) === encodedBody; - } catch { return false; } -} - -function validate(change: IntegrationWrite): void { - if (!Number.isSafeInteger(change.expectedRevision) || change.expectedRevision < 0) throw new IntegrationValidationError("expectedRevision must be a non-negative safe integer"); - const uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; - if (!uuid.test(change.id) || !uuid.test(change.idempotencyKey)) throw new IntegrationValidationError("id and idempotencyKey must be UUIDs"); - if (change.kind !== "bearer" && change.kind !== "model") throw new IntegrationValidationError("Unsupported integration kind"); - if (!change.name.trim() || change.name.length > 120) throw new IntegrationValidationError("name must contain 1 to 120 characters"); - if (change.description !== null && change.description.length > 500) throw new IntegrationValidationError("description must be at most 500 characters"); - if (change.kind === "bearer" && (!change.origin || change.origin.length > 2048)) throw new IntegrationValidationError("bearer integrations require an origin of at most 2048 characters"); - if (change.kind === "model" && change.origin !== null) throw new IntegrationValidationError("model accounts do not have an origin"); - if (change.operation === "upsert" && !(typeof change.managedSecret === "string" && change.managedSecret.length > 0 && change.managedSecret.length <= 32_768) - && !(typeof change.managedModelPayload === "string" && change.managedModelPayload.length > 0 && change.managedModelPayload.length <= 65_536 && (() => { try { const value = JSON.parse(change.managedModelPayload); return Boolean(value && typeof value === "object" && !Array.isArray(value)); } catch { return false; } })()) - && !(typeof change.encryptedPayload === "string" && isUserCiphertext(change.encryptedPayload))) throw new IntegrationValidationError("upserts require a credential value"); - if (change.kind !== "bearer" && change.managedSecret !== undefined) throw new IntegrationValidationError("managed secrets are only supported for bearer integrations"); - if (change.kind !== "model" && change.managedModelPayload !== undefined) throw new IntegrationValidationError("managed model payloads are only supported for model accounts"); - if (change.operation === "delete" && change.encryptedPayload !== undefined) throw new IntegrationValidationError("deletions cannot contain ciphertext"); -} - -export class EncryptedIntegrationRepository { - constructor(private database: Database, private tenantId: string, private serverEncryptionKey: string) { - if (!tenantId) throw new Error("tenantId is required"); - } - - async revision(): Promise { - const { rows } = await this.database.pool.query<{ revision: string | number }>("SELECT revision FROM app.integration_collections WHERE tenant_id=$1", [this.tenantId]); - return rows.length ? safeRevision(rows[0]!.revision) : 0; - } - - /** Recognize an exact retry before collection-level create checks run. */ - async replay(input: IntegrationWrite): Promise<{ revision: number; duplicate: true } | null> { - validate(input); - const { rows } = await this.database.pool.query("SELECT revision,operation,record_id,kind,name,origin,description,encrypted_payload FROM app.integration_changes WHERE tenant_id=$1 AND idempotency_key=$2", [this.tenantId, input.idempotencyKey]); - const row = rows[0]; - if (!row) return null; - const suppliedPayload = input.managedSecret !== undefined ? `${MANAGED_BEARER_PREFIX}${input.managedSecret}` - : input.managedModelPayload !== undefined ? `${MANAGED_MODEL_PREFIX}${input.managedModelPayload}` : input.encryptedPayload; - const sameCiphertext = row.encrypted_payload === null - ? input.operation === "delete" && input.encryptedPayload === undefined - : input.operation === "upsert" && typeof suppliedPayload === "string" && await decrypt(row.encrypted_payload, this.serverEncryptionKey) === suppliedPayload; - if (row.record_id !== input.id || row.kind !== input.kind || row.name !== input.name || row.origin !== input.origin - || row.description !== input.description || row.operation !== input.operation || !sameCiphertext) { - throw new IntegrationIdempotencyConflictError(); - } - return { revision: safeRevision(row.revision), duplicate: true }; - } - - /** Recognize a delete retry after its active record has already become a tombstone. */ - async replayDelete(id: string, kind: EncryptedIntegrationKind, idempotencyKey: string): Promise<{ revision: number; duplicate: true } | null> { - const uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; - if (!uuid.test(id) || !uuid.test(idempotencyKey)) throw new IntegrationValidationError("id and idempotencyKey must be UUIDs"); - const { rows } = await this.database.pool.query("SELECT revision,operation,record_id,kind,name,origin,description,encrypted_payload FROM app.integration_changes WHERE tenant_id=$1 AND idempotency_key=$2", [this.tenantId, idempotencyKey]); - const row = rows[0]; - if (!row) return null; - if (row.record_id !== id || row.kind !== kind || row.operation !== "delete" || row.encrypted_payload !== null) throw new IntegrationIdempotencyConflictError(); - return { revision: safeRevision(row.revision), duplicate: true }; - } - - async write(input: IntegrationWrite): Promise<{ revision: number; duplicate: boolean }> { - validate(input); - const suppliedPayload = input.managedSecret !== undefined ? `${MANAGED_BEARER_PREFIX}${input.managedSecret}` - : input.managedModelPayload !== undefined ? `${MANAGED_MODEL_PREFIX}${input.managedModelPayload}` : input.encryptedPayload; - const encryptedPayload = input.operation === "upsert" ? await encrypt(suppliedPayload!, this.serverEncryptionKey) : null; - const metadata = [input.id, input.kind, input.name, input.origin, input.description, input.operation, encryptedPayload]; - return this.database.transaction(async client => { - const existing = async () => (await client.query("SELECT revision,operation,record_id,kind,name,origin,description,encrypted_payload FROM app.integration_changes WHERE tenant_id=$1 AND idempotency_key=$2", [this.tenantId, input.idempotencyKey])).rows[0]; - const isSame = async (row: StoredChange) => row.record_id === metadata[0] && row.kind === metadata[1] && row.name === metadata[2] && row.origin === metadata[3] && row.description === metadata[4] && row.operation === metadata[5] && (row.encrypted_payload === null ? encryptedPayload === null : encryptedPayload !== null && await decrypt(row.encrypted_payload, this.serverEncryptionKey) === suppliedPayload); - const duplicate = await existing(); - if (duplicate) { - if (!await isSame(duplicate)) throw new IntegrationIdempotencyConflictError(); - return { revision: safeRevision(duplicate.revision), duplicate: true }; - } - - await client.query("INSERT INTO app.integration_collections(tenant_id) VALUES ($1) ON CONFLICT DO NOTHING", [this.tenantId]); - const bumped = await client.query<{ revision: string | number }>("UPDATE app.integration_collections SET revision=revision+1,updated_at=now() WHERE tenant_id=$1 AND revision=$2 RETURNING revision", [this.tenantId, input.expectedRevision]); - if (!bumped.rows.length) { - const racedDuplicate = await existing(); - if (racedDuplicate) { - if (!await isSame(racedDuplicate)) throw new IntegrationIdempotencyConflictError(); - return { revision: safeRevision(racedDuplicate.revision), duplicate: true }; - } - const current = await client.query<{ revision: string | number }>("SELECT revision FROM app.integration_collections WHERE tenant_id=$1", [this.tenantId]); - throw new StaleIntegrationRevisionError(safeRevision(current.rows[0]!.revision)); - } - const revision = safeRevision(bumped.rows[0]!.revision); - - if (input.operation === "upsert") { - await client.query(`INSERT INTO app.integration_records(tenant_id,id,kind,name,origin,description,revision,encrypted_payload,deleted_at) - VALUES ($1,$2,$3,$4,$5,$6,$7,$8,NULL) - ON CONFLICT (tenant_id,id) DO UPDATE SET kind=excluded.kind,name=excluded.name,origin=excluded.origin,description=excluded.description,revision=excluded.revision,encrypted_payload=excluded.encrypted_payload,deleted_at=NULL,updated_at=now()`, - [this.tenantId, input.id, input.kind, input.name, input.origin, input.description, revision, encryptedPayload]); - } else { - await client.query(`INSERT INTO app.integration_records(tenant_id,id,kind,name,origin,description,revision,encrypted_payload,deleted_at) - VALUES ($1,$2,$3,$4,$5,$6,$7,NULL,now()) - ON CONFLICT (tenant_id,id) DO UPDATE SET kind=excluded.kind,name=excluded.name,origin=excluded.origin,description=excluded.description,revision=excluded.revision,encrypted_payload=NULL,deleted_at=now(),updated_at=now()`, - [this.tenantId, input.id, input.kind, input.name, input.origin, input.description, revision]); - } - await client.query(`INSERT INTO app.integration_changes(tenant_id,revision,id,idempotency_key,operation,record_id,kind,name,origin,description,encrypted_payload) - VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11)`, [this.tenantId, revision, crypto.randomUUID(), input.idempotencyKey, input.operation, input.id, input.kind, input.name, input.origin, input.description, encryptedPayload]); - return { revision, duplicate: false }; - }); - } - - /** Resolve exactly one selected live credential. Legacy user ciphertext is - * deliberately unavailable to the managed backend and requires re-entry. */ - async managedCredential(id: string, kind: EncryptedIntegrationKind): Promise<(IntegrationMetadata & { revision: number; payload: string }) | null> { - const row = (await this.database.pool.query<{ id: string; kind: EncryptedIntegrationKind; name: string; origin: string | null; description: string | null; revision: string | number; encrypted_payload: string }>( - "SELECT id,kind,name,origin,description,revision,encrypted_payload FROM app.integration_records WHERE tenant_id=$1 AND id=$2 AND kind=$3 AND deleted_at IS NULL", [this.tenantId, id, kind])).rows[0]; - if (!row) return null; - const plain = await decrypt(row.encrypted_payload, this.serverEncryptionKey); - const prefix = kind === "bearer" ? MANAGED_BEARER_PREFIX : MANAGED_MODEL_PREFIX; - if (!plain.startsWith(prefix)) return null; - return { id: row.id, kind: row.kind, name: row.name, origin: row.origin, description: row.description, - revision: safeRevision(row.revision), payload: plain.slice(prefix.length) }; - } - - /** Serialize refresh across backend instances. Lock order matches writes: - * collection first, then the selected credential. A disconnect/reconnect - * cannot be overwritten by a delayed refresh. */ - async refreshManagedModel(id: string, refresh: (payload: string) => Promise): Promise { - return this.database.transaction(async client => { - const collection = (await client.query<{ revision: string | number }>("SELECT revision FROM app.integration_collections WHERE tenant_id=$1 FOR UPDATE", [this.tenantId])).rows[0]; - if (!collection) return null; - const row = (await client.query<{ revision: string | number; encrypted_payload: string; name: string; description: string | null }>( - "SELECT revision,encrypted_payload,name,description FROM app.integration_records WHERE tenant_id=$1 AND id=$2 AND kind='model' AND deleted_at IS NULL FOR UPDATE", [this.tenantId, id])).rows[0]; - if (!row) return null; - const plain = await decrypt(row.encrypted_payload, this.serverEncryptionKey); - if (!plain.startsWith(MANAGED_MODEL_PREFIX)) return null; - const payload = plain.slice(MANAGED_MODEL_PREFIX.length); - const updated = await refresh(payload); - if (updated === payload) return payload; - if (updated.length > 65_536) throw new IntegrationValidationError("Model cache exceeds its limit"); - const encrypted = await encrypt(`${MANAGED_MODEL_PREFIX}${updated}`, this.serverEncryptionKey); - const revision = safeRevision(collection.revision) + 1; - await client.query("UPDATE app.integration_collections SET revision=$2,updated_at=now() WHERE tenant_id=$1", [this.tenantId, revision]); - await client.query("UPDATE app.integration_records SET revision=revision+1,encrypted_payload=$3,updated_at=now() WHERE tenant_id=$1 AND id=$2", [this.tenantId, id, encrypted]); - await client.query(`INSERT INTO app.integration_changes(tenant_id,revision,id,idempotency_key,operation,record_id,kind,name,origin,description,encrypted_payload) - VALUES($1,$2,$3,$4,'upsert',$5,'model',$6,NULL,$7,$8)`, [this.tenantId, revision, crypto.randomUUID(), crypto.randomUUID(), id, row.name, row.description, encrypted]); - return updated; - }); - } - - async records(kind?: EncryptedIntegrationKind): Promise> { - const { rows } = await this.database.pool.query<{ id: string; kind: EncryptedIntegrationKind; name: string; origin: string | null; description: string | null; revision: string | number; encrypted_payload: string }>( - `SELECT id,kind,name,origin,description,revision,encrypted_payload FROM app.integration_records WHERE tenant_id=$1 AND deleted_at IS NULL${kind ? " AND kind=$2" : ""} ORDER BY revision,id`, kind ? [this.tenantId, kind] : [this.tenantId]); - return Promise.all(rows.map(async row => ({ id: row.id, kind: row.kind, name: row.name, origin: row.origin, description: row.description, revision: safeRevision(row.revision), encryptedPayload: await decrypt(row.encrypted_payload, this.serverEncryptionKey) }))); - } - - /** Return selected records including tombstones so an authenticated proxy can - * remove a deleted credential from already-established grants. Tombstones - * never include ciphertext. */ - async recordsIncludingDeleted(kind: EncryptedIntegrationKind): Promise> { - const { rows } = await this.database.pool.query<{ id: string; kind: EncryptedIntegrationKind; name: string; origin: string | null; description: string | null; revision: string | number; encrypted_payload: string | null; deleted_at: Date | null }>( - "SELECT id,kind,name,origin,description,revision,encrypted_payload,deleted_at FROM app.integration_records WHERE tenant_id=$1 AND kind=$2 ORDER BY revision,id", [this.tenantId, kind]); - return Promise.all(rows.map(async row => ({ id: row.id, kind: row.kind, name: row.name, origin: row.origin, description: row.description, - revision: safeRevision(row.revision), encryptedPayload: row.deleted_at || row.encrypted_payload === null ? null : await decrypt(row.encrypted_payload, this.serverEncryptionKey), deletedAt: row.deleted_at }))); - } - - /** Owner-only rekey input. Includes tombstones and the retained change feed so - * a browser rotation can preserve pending edits without exposing plaintext to - * the API process. */ - async rotationSnapshot(): Promise<{ revision: number; records: GenerationRecord[]; changes: GenerationChange[] }> { - const revision = await this.revision(); - const records = await this.database.pool.query<{ id: string; kind: EncryptedIntegrationKind; name: string; origin: string | null; description: string | null; revision: string | number; encrypted_payload: string | null; deleted_at: Date | null }>( - "SELECT id,kind,name,origin,description,revision,encrypted_payload,deleted_at FROM app.integration_records WHERE tenant_id=$1 ORDER BY id", [this.tenantId]); - const changes = await this.database.pool.query( - "SELECT revision,idempotency_key,operation,record_id,kind,name,origin,description,encrypted_payload FROM app.integration_changes WHERE tenant_id=$1 ORDER BY revision", [this.tenantId]); - return { - revision, - records: await Promise.all(records.rows.map(async row => ({ id: row.id, kind: row.kind, name: row.name, origin: row.origin, description: row.description, - revision: safeRevision(row.revision), encryptedPayload: row.deleted_at || row.encrypted_payload === null ? null : await decrypt(row.encrypted_payload, this.serverEncryptionKey), deletedAt: row.deleted_at }))), - changes: await Promise.all(changes.rows.map(async row => ({ id: row.record_id, kind: row.kind, name: row.name, origin: row.origin, description: row.description, - revision: safeRevision(row.revision), idempotencyKey: row.idempotency_key, operation: row.operation, - encryptedPayload: row.encrypted_payload === null ? null : await decrypt(row.encrypted_payload, this.serverEncryptionKey) }))), - }; - } - - /** Store a model auth cache under Factorize-managed encryption. The proxy is - * trusted to handle the live token, while the database only receives the - * server-encrypted cache. */ - async saveModelCache(input: { id: string; expectedRevision: number; encryptedPayload: string; idempotencyKey: string }): Promise<{ revision: number; collectionRevision: number; duplicate: boolean }> { - const uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; - if (!uuid.test(input.id) || !uuid.test(input.idempotencyKey) || !Number.isSafeInteger(input.expectedRevision) || input.expectedRevision < 0 - || typeof input.encryptedPayload !== "string" || input.encryptedPayload.length === 0 || input.encryptedPayload.length > 65_536) throw new IntegrationValidationError("model cache binding is invalid"); - let parsed: unknown; - try { parsed = JSON.parse(input.encryptedPayload); } catch { throw new IntegrationValidationError("model cache is invalid"); } - if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) throw new IntegrationValidationError("model cache is invalid"); - const managedPayload = `${MANAGED_MODEL_PREFIX}${input.encryptedPayload}`; - const encryptedPayload = await encrypt(managedPayload, this.serverEncryptionKey); - return this.database.transaction(async client => { - await client.query("INSERT INTO app.integration_collections(tenant_id) VALUES ($1) ON CONFLICT DO NOTHING", [this.tenantId]); - const collection = (await client.query<{ revision: string | number }>("SELECT revision FROM app.integration_collections WHERE tenant_id=$1 FOR UPDATE", [this.tenantId])).rows[0]!; - const currentCollectionRevision = safeRevision(collection.revision); - const current = (await client.query<{ kind: EncryptedIntegrationKind; name: string; origin: string | null; description: string | null; revision: string | number; encrypted_payload: string | null; deleted_at: Date | null }>( - "SELECT kind,name,origin,description,revision,encrypted_payload,deleted_at FROM app.integration_records WHERE tenant_id=$1 AND id=$2 FOR UPDATE", [this.tenantId, input.id])).rows[0]; - if (!current || current.kind !== "model" || current.deleted_at || current.revision === null) throw new IntegrationValidationError("model account is unavailable"); - const currentRevision = safeRevision(current.revision); - const previousChange = (await client.query<{ revision: string | number; record_id: string; operation: string; encrypted_payload: string | null }>( - "SELECT revision,record_id,operation,encrypted_payload FROM app.integration_changes WHERE tenant_id=$1 AND idempotency_key=$2", [this.tenantId,input.idempotencyKey])).rows[0]; - if (previousChange) { - const same = previousChange.record_id === input.id && previousChange.operation === "upsert" && previousChange.encrypted_payload !== null - && await decrypt(previousChange.encrypted_payload, this.serverEncryptionKey) === managedPayload; - if (!same) throw new IntegrationIdempotencyConflictError(); - return { revision: Math.max(0, input.expectedRevision + 1), collectionRevision: safeRevision(previousChange.revision), duplicate: true }; - } - if (currentRevision !== input.expectedRevision) throw new StaleIntegrationRevisionError(currentRevision); - const collectionRevision = currentCollectionRevision + 1; - const revision = currentRevision + 1; - await client.query("UPDATE app.integration_collections SET revision=$2,updated_at=now() WHERE tenant_id=$1", [this.tenantId, collectionRevision]); - await client.query("UPDATE app.integration_records SET revision=$3,encrypted_payload=$4,updated_at=now() WHERE tenant_id=$1 AND id=$2", [this.tenantId,input.id,revision,encryptedPayload]); - await client.query(`INSERT INTO app.integration_changes(tenant_id,revision,id,idempotency_key,operation,record_id,kind,name,origin,description,encrypted_payload) - VALUES ($1,$2,$3,$4,'upsert',$5,'model',$6,NULL,$7,$8)`, [this.tenantId,collectionRevision,crypto.randomUUID(),input.idempotencyKey,input.id,current.name,current.description,encryptedPayload]); - return { revision, collectionRevision, duplicate: false }; - }); - } - - async changesSince(revision: number, limit = 100): Promise { - if (!Number.isSafeInteger(revision) || revision < 0) throw new IntegrationValidationError("revision must be a non-negative safe integer"); - if (!Number.isSafeInteger(limit) || limit < 1 || limit > 500) throw new IntegrationValidationError("limit must be between 1 and 500"); - const rows = await this.database.transaction(async client => { - const collection = (await client.query<{ revision: string | number; changes_pruned_through: string | number }>("SELECT revision,changes_pruned_through FROM app.integration_collections WHERE tenant_id=$1 FOR SHARE", [this.tenantId])).rows[0]; - if (collection && revision < safeRevision(collection.changes_pruned_through)) throw new StaleIntegrationRevisionError(safeRevision(collection.revision), true); - return (await client.query("SELECT revision,operation,record_id,kind,name,origin,description,encrypted_payload FROM app.integration_changes WHERE tenant_id=$1 AND revision>$2 ORDER BY revision LIMIT $3", [this.tenantId, revision, limit])).rows; - }); - return Promise.all(rows.map(async row => ({ id: row.record_id, kind: row.kind, name: row.name, origin: row.origin, description: row.description, revision: safeRevision(row.revision), operation: row.operation, encryptedPayload: row.encrypted_payload === null ? null : await decrypt(row.encrypted_payload, this.serverEncryptionKey) }))); - } - - /** Store one complete replacement generation. Payloads must already be user-encrypted. */ - async stageGeneration(input: { generationId: string; expectedRevision: number; records: GenerationRecord[]; changes: GenerationChange[]; preserveManagedModelCaches?: boolean }): Promise<{ duplicate: boolean }> { - const uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; - if (!uuid.test(input.generationId) || !Number.isSafeInteger(input.expectedRevision) || input.expectedRevision < 0) throw new IntegrationValidationError("generationId and expectedRevision are invalid"); - if (input.records.length > 5000 || input.changes.length > 10000) throw new IntegrationValidationError("generation exceeds staging limits"); - for (const record of input.records) { - const managedModel = input.preserveManagedModelCaches && record.kind === "model" && record.encryptedPayload?.startsWith(MANAGED_MODEL_PREFIX); - if (!uuid.test(record.id) || (record.encryptedPayload !== null && !isUserCiphertext(record.encryptedPayload) && !managedModel) || (record.deletedAt === null) !== (record.encryptedPayload !== null)) throw new IntegrationValidationError("generation records must contain ciphertext or a tombstone"); - } - for (const change of input.changes) { - const managedModel = input.preserveManagedModelCaches && change.kind === "model" && change.encryptedPayload?.startsWith(MANAGED_MODEL_PREFIX); - if (!uuid.test(change.id) || !uuid.test(change.idempotencyKey) || !Number.isSafeInteger(change.revision) || change.revision < 1 || (change.encryptedPayload !== null && !isUserCiphertext(change.encryptedPayload) && !managedModel) || (change.operation === "upsert") !== (change.encryptedPayload !== null)) throw new IntegrationValidationError("generation changes must contain ordered ciphertext or tombstones"); - } - const canonical = JSON.stringify({ - records: [...input.records].sort((a,b) => a.id.localeCompare(b.id)).map(row => ({ ...row, deletedAt: row.deletedAt?.toISOString() ?? null })), - changes: [...input.changes].sort((a,b) => a.revision - b.revision).map(row => ({ ...row })), - }); - const hashBytes = new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(canonical))); - const contentHash = Array.from(hashBytes, byte => byte.toString(16).padStart(2,"0")).join(""); - return this.database.transaction(async client => { - const prior = (await client.query<{ expected_revision: string | number; state: string; content_hash: string }>("SELECT expected_revision,state,content_hash FROM app.integration_generation_journal WHERE tenant_id=$1 AND generation_id=$2 FOR UPDATE", [this.tenantId, input.generationId])).rows[0]; - if (prior) { - if (safeRevision(prior.expected_revision) !== input.expectedRevision || prior.content_hash !== contentHash || prior.state === "expired" || prior.state === "rolled_back") throw new IntegrationIdempotencyConflictError(); - return { duplicate: true }; - } - await client.query("INSERT INTO app.integration_generation_journal(tenant_id,generation_id,expected_revision,content_hash,state) VALUES($1,$2,$3,$4,'staged')", [this.tenantId, input.generationId, input.expectedRevision,contentHash]); - for (const row of input.records) await client.query(`INSERT INTO app.integration_generation_records(tenant_id,generation_id,id,kind,name,origin,description,revision,encrypted_payload,deleted_at) VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10)`, [this.tenantId,input.generationId,row.id,row.kind,row.name,row.origin,row.description,row.revision,row.encryptedPayload,row.deletedAt]); - for (const row of input.changes) await client.query(`INSERT INTO app.integration_generation_changes(tenant_id,generation_id,revision,id,idempotency_key,operation,record_id,kind,name,origin,description,encrypted_payload) VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12)`, [this.tenantId,input.generationId,row.revision,row.id,row.idempotencyKey,row.operation,row.id,row.kind,row.name,row.origin,row.description,row.encryptedPayload]); - return { duplicate: false }; - }); - } - - /** Atomically archive and replace records, tombstones, changes and the collection revision. */ - async commitGeneration(generationId: string, expectedRevision: number, keyReplacement?: { expectedVerificationGenerationId: string; verificationGenerationId: string; encryptedVerification: string }): Promise<{ revision: number; duplicate: boolean }> { - return this.database.transaction(async client => { - await client.query("INSERT INTO app.integration_collections(tenant_id) VALUES($1) ON CONFLICT DO NOTHING", [this.tenantId]); - const collection = (await client.query<{ revision: string | number }>("SELECT revision FROM app.integration_collections WHERE tenant_id=$1 FOR UPDATE", [this.tenantId])).rows[0]!; - const current = safeRevision(collection.revision); - const journal = (await client.query<{ expected_revision: string | number; state: string; committed_revision: string | number | null }>("SELECT expected_revision,state,committed_revision FROM app.integration_generation_journal WHERE tenant_id=$1 AND generation_id=$2 FOR UPDATE", [this.tenantId,generationId])).rows[0]; - if (!journal || safeRevision(journal.expected_revision) !== expectedRevision) throw new IntegrationValidationError("staged generation was not found for this revision"); - if (journal.state === "committed") return { revision: safeRevision(journal.committed_revision!), duplicate: true }; - if (journal.state !== "staged") throw new IntegrationValidationError("staged generation is no longer available"); - if (current !== expectedRevision) throw new StaleIntegrationGenerationError(current); - if (keyReplacement) { - const currentKey = (await client.query<{ generation_id: string }>("SELECT generation_id FROM app.unlock_key_verifications WHERE tenant_id=$1 FOR UPDATE", [this.tenantId])).rows[0]; - if (!currentKey || currentKey.generation_id !== keyReplacement.expectedVerificationGenerationId) throw new StaleIntegrationGenerationError(current); - if (!/^[0-9a-f-]{36}$/i.test(keyReplacement.verificationGenerationId) || keyReplacement.verificationGenerationId === currentKey.generation_id - || keyReplacement.encryptedVerification.length > 4096) throw new IntegrationValidationError("replacement key verification is invalid"); - let envelope: any; - try { envelope = JSON.parse(keyReplacement.encryptedVerification); } catch { throw new IntegrationValidationError("replacement key verification is malformed"); } - if (!envelope || typeof envelope !== "object" || Array.isArray(envelope) || envelope.version !== 1 || envelope.algorithm !== "A256GCM" - || Object.keys(envelope).sort().join(",") !== "algorithm,ciphertext,nonce,version" || typeof envelope.nonce !== "string" - || !/^[A-Za-z0-9_-]{16}$/u.test(envelope.nonce) || typeof envelope.ciphertext !== "string" || !/^[A-Za-z0-9_-]{22,}$/u.test(envelope.ciphertext)) { - throw new IntegrationValidationError("replacement key verification is malformed"); - } - } - await client.query("DELETE FROM app.integration_generation_previous_records WHERE tenant_id=$1", [this.tenantId]); - await client.query("DELETE FROM app.integration_generation_previous_changes WHERE tenant_id=$1", [this.tenantId]); - await client.query(`INSERT INTO app.integration_generation_previous_records(tenant_id,id,kind,name,origin,description,revision,encrypted_payload,deleted_at,created_at,updated_at,generation_id) SELECT tenant_id,id,kind,name,origin,description,revision,encrypted_payload,deleted_at,created_at,updated_at,$2 FROM app.integration_records WHERE tenant_id=$1`, [this.tenantId,generationId]); - await client.query(`INSERT INTO app.integration_generation_previous_changes(tenant_id,revision,id,idempotency_key,operation,record_id,kind,name,origin,description,encrypted_payload,created_at,generation_id) SELECT tenant_id,revision,id,idempotency_key,operation,record_id,kind,name,origin,description,encrypted_payload,created_at,$2 FROM app.integration_changes WHERE tenant_id=$1`, [this.tenantId,generationId]); - await client.query("DELETE FROM app.integration_records WHERE tenant_id=$1", [this.tenantId]); - const records = (await client.query<{ id: string; kind: EncryptedIntegrationKind; name: string; origin: string | null; description: string | null; revision: string | number; encrypted_payload: string | null; deleted_at: Date | null }>("SELECT id,kind,name,origin,description,revision,encrypted_payload,deleted_at FROM app.integration_generation_records WHERE tenant_id=$1 AND generation_id=$2", [this.tenantId,generationId])).rows; - for (const row of records) await client.query(`INSERT INTO app.integration_records(tenant_id,id,kind,name,origin,description,revision,encrypted_payload,deleted_at) VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9)`, [this.tenantId,row.id,row.kind,row.name,row.origin,row.description,row.revision,row.encrypted_payload === null ? null : await encrypt(row.encrypted_payload,this.serverEncryptionKey),row.deleted_at]); - await client.query("DELETE FROM app.integration_changes WHERE tenant_id=$1", [this.tenantId]); - const changes = (await client.query<{ revision: string | number; id: string; idempotency_key: string; operation: "upsert" | "delete"; record_id: string; kind: EncryptedIntegrationKind; name: string; origin: string | null; description: string | null; encrypted_payload: string | null }>("SELECT revision,id,idempotency_key,operation,record_id,kind,name,origin,description,encrypted_payload FROM app.integration_generation_changes WHERE tenant_id=$1 AND generation_id=$2 ORDER BY revision", [this.tenantId,generationId])).rows; - for (const row of changes) await client.query(`INSERT INTO app.integration_changes(tenant_id,revision,id,idempotency_key,operation,record_id,kind,name,origin,description,encrypted_payload) VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11)`, [this.tenantId,row.revision,row.id,row.idempotency_key,row.operation,row.record_id,row.kind,row.name,row.origin,row.description,row.encrypted_payload === null ? null : await encrypt(row.encrypted_payload,this.serverEncryptionKey)]); - const revision = current + 1; - await client.query("UPDATE app.integration_collections SET revision=$2,updated_at=now() WHERE tenant_id=$1", [this.tenantId,revision]); - await client.query("UPDATE app.integration_generation_journal SET state='committed',committed_revision=$3,committed_at=now() WHERE tenant_id=$1 AND generation_id=$2", [this.tenantId,generationId,revision]); - if (keyReplacement) { - await client.query("UPDATE app.unlock_key_verifications SET generation_id=$2,encrypted_verification=$3,created_at=now() WHERE tenant_id=$1", [this.tenantId,keyReplacement.verificationGenerationId,keyReplacement.encryptedVerification]); - await client.query("UPDATE app.credential_run_grants SET revoked_at=now() WHERE tenant_id=$1 AND revoked_at IS NULL", [this.tenantId]); - await client.query("UPDATE app.credential_run_enrollments SET consumed_at=now() WHERE tenant_id=$1 AND consumed_at IS NULL", [this.tenantId]); - await client.query("UPDATE app.credential_proxy_states SET unlocked=false,updated_at=now() WHERE tenant_id=$1", [this.tenantId]); - } - return { revision, duplicate: false }; - }); - } - - /** Restore the previous generation only while this commit is still the active revision. */ - async rollbackGeneration(generationId: string): Promise { - return this.database.transaction(async client => { - const collection = (await client.query<{ revision: string | number }>("SELECT revision FROM app.integration_collections WHERE tenant_id=$1 FOR UPDATE", [this.tenantId])).rows[0]; - const journal = (await client.query<{ state: string; committed_revision: string | number | null }>("SELECT state,committed_revision FROM app.integration_generation_journal WHERE tenant_id=$1 AND generation_id=$2 FOR UPDATE", [this.tenantId,generationId])).rows[0]; - if (!collection || !journal || journal.state !== "committed") throw new IntegrationValidationError("committed generation is not available for rollback"); - const current = safeRevision(collection.revision); - if (current !== safeRevision(journal.committed_revision!)) throw new StaleIntegrationGenerationError(current); - await client.query("DELETE FROM app.integration_records WHERE tenant_id=$1", [this.tenantId]); - await client.query(`INSERT INTO app.integration_records(tenant_id,id,kind,name,origin,description,revision,encrypted_payload,deleted_at,created_at,updated_at) SELECT tenant_id,id,kind,name,origin,description,revision,encrypted_payload,deleted_at,created_at,updated_at FROM app.integration_generation_previous_records WHERE tenant_id=$1 AND generation_id=$2`, [this.tenantId,generationId]); - await client.query("DELETE FROM app.integration_changes WHERE tenant_id=$1", [this.tenantId]); - await client.query(`INSERT INTO app.integration_changes(tenant_id,revision,id,idempotency_key,operation,record_id,kind,name,origin,description,encrypted_payload,created_at) SELECT tenant_id,revision,id,idempotency_key,operation,record_id,kind,name,origin,description,encrypted_payload,created_at FROM app.integration_generation_previous_changes WHERE tenant_id=$1 AND generation_id=$2`, [this.tenantId,generationId]); - const revision = current + 1; - await client.query("UPDATE app.integration_collections SET revision=$2,updated_at=now() WHERE tenant_id=$1", [this.tenantId,revision]); - await client.query("UPDATE app.integration_generation_journal SET state='rolled_back' WHERE tenant_id=$1 AND generation_id=$2", [this.tenantId,generationId]); - return revision; - }); - } - - /** Delete at most `limit` expired journals; committed archives are retained for at most maxAgeMs. */ - async cleanupGenerations(maxAgeMs: number, limit = 100): Promise { - if (!Number.isSafeInteger(maxAgeMs) || maxAgeMs < 0 || !Number.isSafeInteger(limit) || limit < 1 || limit > 500) throw new IntegrationValidationError("cleanup bounds are invalid"); - return this.database.transaction(async client => { - const expired = (await client.query<{ generation_id: string }>(`SELECT generation_id FROM app.integration_generation_journal WHERE tenant_id=$1 AND created_at < now() - ($2::bigint * interval '1 millisecond') ORDER BY created_at LIMIT $3 FOR UPDATE`, [this.tenantId,maxAgeMs,limit])).rows.map(row => row.generation_id); - if (!expired.length) return 0; - await client.query("DELETE FROM app.integration_generation_previous_records WHERE tenant_id=$1 AND generation_id=ANY($2::uuid[])", [this.tenantId,expired]); - await client.query("DELETE FROM app.integration_generation_previous_changes WHERE tenant_id=$1 AND generation_id=ANY($2::uuid[])", [this.tenantId,expired]); - await client.query("DELETE FROM app.integration_generation_journal WHERE tenant_id=$1 AND generation_id=ANY($2::uuid[])", [this.tenantId,expired]); - return expired.length; - }); - } -} diff --git a/packages/api/src/postgres/proxy-control-repository.ts b/packages/api/src/postgres/proxy-control-repository.ts deleted file mode 100644 index 84a7be38..00000000 --- a/packages/api/src/postgres/proxy-control-repository.ts +++ /dev/null @@ -1,93 +0,0 @@ -import type { Database } from "./database"; - -export type RegisteredProxy = { tenantId: string; proxyIdentity: string; bootEpoch: string; controlCredential: string }; -const uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; -const digest = async (token: string) => new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(token))); - -/** Credentials for the Factorize-to-proxy control plane. These are never job run credentials. */ -export class ProxyControlRepository { - constructor(private database: Database) {} - - /** Called only from the authenticated infrastructure provisioning path; the token is returned once. */ - async provisionCredential(tenantId: string, proxyIdentity: string, bootEpoch: string): Promise { - if (!uuid.test(tenantId) || !proxyIdentity.trim() || proxyIdentity.length > 255 || !uuid.test(bootEpoch)) throw new TypeError("Invalid proxy identity or boot epoch"); - const token = `fzc_${Buffer.from(crypto.getRandomValues(new Uint8Array(32))).toString("base64url")}`; - await this.database.pool.query(`INSERT INTO app.credential_proxy_control_credentials(tenant_id,proxy_identity,boot_epoch,token_digest,revoked_at,consumed_at) - VALUES ($1,$2,$3,$4,NULL,NULL) ON CONFLICT (tenant_id,proxy_identity) DO UPDATE SET boot_epoch=excluded.boot_epoch,token_digest=excluded.token_digest,proxy_token_digest=NULL,revoked_at=NULL,consumed_at=NULL,created_at=now()`, - [tenantId, proxyIdentity, bootEpoch, Buffer.from(await digest(token))]); - return token; - } - - async authenticate(token: string): Promise | null> { - if (typeof token !== "string" || !/^fzc_[A-Za-z0-9_-]{43}$/.test(token)) return null; - const result = await this.database.pool.query<{ tenant_id: string; proxy_identity: string }>(`SELECT tenant_id,proxy_identity - FROM app.credential_proxy_control_credentials WHERE token_digest=$1 AND revoked_at IS NULL`, [Buffer.from(await digest(token))]); - const row = result.rows[0]; - return row ? { tenantId: row.tenant_id, proxyIdentity: row.proxy_identity } : null; - } - - async registerBoot(token: string, bootEpoch: string, browserOrigin: string): Promise { - if (!uuid.test(bootEpoch)) throw new TypeError("bootEpoch must be a UUID"); - const parsedOrigin = new URL(browserOrigin); - if (parsedOrigin.protocol !== "https:" || parsedOrigin.origin !== browserOrigin || parsedOrigin.username || parsedOrigin.password) throw new TypeError("browser origin must be canonical HTTPS"); - const tokenDigest = Buffer.from(await digest(token)); - return this.database.transaction(async client => { - const credential = await client.query<{ tenant_id: string; proxy_identity: string }>(`SELECT tenant_id,proxy_identity - FROM app.credential_proxy_control_credentials WHERE token_digest=$1 AND boot_epoch=$2 AND revoked_at IS NULL AND consumed_at IS NULL FOR UPDATE`, [tokenDigest, bootEpoch]); - const identity = credential.rows[0]; - if (!identity) return null; - const saved = await client.query(`INSERT INTO app.credential_proxy_states(tenant_id,proxy_identity,boot_epoch) - VALUES ($1,$2,$3) ON CONFLICT (tenant_id) DO UPDATE SET proxy_identity=excluded.proxy_identity,boot_epoch=excluded.boot_epoch,unlocked=false,updated_at=now() - WHERE app.credential_proxy_states.proxy_identity=excluded.proxy_identity - AND app.credential_proxy_states.disabled_at IS NULL AND app.credential_proxy_states.revoked_at IS NULL RETURNING tenant_id`, - [identity.tenant_id, identity.proxy_identity, bootEpoch]); - if (!saved.rowCount) return null; - const proxyToken = `fzc_${Buffer.from(crypto.getRandomValues(new Uint8Array(32))).toString("base64url")}`; - await client.query(`UPDATE app.credential_proxy_control_credentials SET consumed_at=now(),proxy_token_digest=$3 - WHERE token_digest=$1 AND boot_epoch=$2 AND consumed_at IS NULL`, [tokenDigest, bootEpoch, Buffer.from(await digest(proxyToken))]); - await client.query(`UPDATE app.credential_run_grants SET revoked_at=now() - WHERE tenant_id=$1 AND proxy_identity=$2 AND boot_epoch<>$3 AND revoked_at IS NULL`, [identity.tenant_id, identity.proxy_identity, bootEpoch]); - await client.query(`INSERT INTO app.credential_proxy_browser_pairings(tenant_id,proxy_identity,boot_epoch,browser_origin) - VALUES ($1,$2,$3,$4) ON CONFLICT (tenant_id) DO UPDATE SET proxy_identity=excluded.proxy_identity, - boot_epoch=excluded.boot_epoch,browser_origin=excluded.browser_origin,updated_at=now()`, - [identity.tenant_id, identity.proxy_identity, bootEpoch, browserOrigin]); - return { tenantId: identity.tenant_id, proxyIdentity: identity.proxy_identity, bootEpoch, controlCredential: proxyToken }; - }); - } - - async browserPairing(tenantId: string): Promise<{ proxyIdentity: string; bootEpoch: string; browserOrigin: string } | null> { - const result = await this.database.pool.query<{ proxy_identity: string; boot_epoch: string; browser_origin: string }>( - `SELECT b.proxy_identity,b.boot_epoch,b.browser_origin FROM app.credential_proxy_browser_pairings b - JOIN app.credential_proxy_states p ON p.tenant_id=b.tenant_id AND p.proxy_identity=b.proxy_identity AND p.boot_epoch=b.boot_epoch - WHERE b.tenant_id=$1 AND p.disabled_at IS NULL AND p.revoked_at IS NULL`, [tenantId]); - const row = result.rows[0]; - return row ? { proxyIdentity: row.proxy_identity, bootEpoch: row.boot_epoch, browserOrigin: row.browser_origin } : null; - } - - /** Authenticates the proxy's memory-held control credential against its current registered boot. */ - async authenticateProxy(token: string): Promise | null> { - if (typeof token !== "string" || !/^fzc_[A-Za-z0-9_-]{43}$/.test(token)) return null; - const result = await this.database.pool.query<{ tenant_id: string; proxy_identity: string; boot_epoch: string }>(`SELECT c.tenant_id,c.proxy_identity,c.boot_epoch - FROM app.credential_proxy_control_credentials c JOIN app.credential_proxy_states p - ON p.tenant_id=c.tenant_id AND p.proxy_identity=c.proxy_identity AND p.boot_epoch=c.boot_epoch - WHERE c.proxy_token_digest=$1 AND c.revoked_at IS NULL AND p.disabled_at IS NULL AND p.revoked_at IS NULL`, [Buffer.from(await digest(token))]); - const row = result.rows[0]; - return row ? { tenantId: row.tenant_id, proxyIdentity: row.proxy_identity, bootEpoch: row.boot_epoch } : null; - } - - async reportRuntimeStatus(token: string, bootEpoch: string, unlocked: boolean): Promise { - if (!uuid.test(bootEpoch) || typeof unlocked !== "boolean") throw new TypeError("Invalid proxy runtime status"); - const identity = await this.authenticateProxy(token); - if (!identity || identity.bootEpoch !== bootEpoch) return false; - const result = await this.database.pool.query(`UPDATE app.credential_proxy_states SET unlocked=$3,updated_at=now() - WHERE tenant_id=$1 AND proxy_identity=$2 AND boot_epoch=$4 AND disabled_at IS NULL AND revoked_at IS NULL`, - [identity.tenantId, identity.proxyIdentity, unlocked, bootEpoch]); - return Boolean(result.rowCount); - } - - async revokeCredential(tenantId: string, proxyIdentity: string): Promise { - const result = await this.database.pool.query(`UPDATE app.credential_proxy_control_credentials SET revoked_at=now() - WHERE tenant_id=$1 AND proxy_identity=$2 AND revoked_at IS NULL`, [tenantId, proxyIdentity]); - return Boolean(result.rowCount); - } -} diff --git a/packages/api/src/postgres/run-enrollment-repository.ts b/packages/api/src/postgres/run-enrollment-repository.ts deleted file mode 100644 index 3bc00bd0..00000000 --- a/packages/api/src/postgres/run-enrollment-repository.ts +++ /dev/null @@ -1,115 +0,0 @@ -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,unlocked=false,updated_at=now()`, - [input.tenantId, input.proxyIdentity, input.bootEpoch, input.disabled ?? false, input.revoked ?? false]); - } - - /** - * Authorize an active run for the current provider binding. The revision is - * stable for repeated reconnects on the same VM/proxy boot, and advances - * when the run is rebound to a new VM or proxy boot. A revoked grant cannot - * be restored on the same binding. Locking the run and proxy state - * serializes first enrollment and reconnect races. - */ - async authorizeRun(binding: RunEnrollmentBinding): Promise { - validateBinding(binding); - 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 - FOR UPDATE OF r,p`, - [binding.tenantId, binding.runId, binding.proxyIdentity, binding.bootEpoch]); - if (!valid.rowCount) return null; - const current = await client.query<{ vm_identity: string; proxy_identity: string; boot_epoch: string; grant_revision: string | number; revoked_at: Date | null }>( - `SELECT vm_identity,proxy_identity,boot_epoch,grant_revision,revoked_at FROM app.credential_run_grants - WHERE tenant_id=$1 AND run_id=$2 FOR UPDATE`, [binding.tenantId, binding.runId]); - const row = current.rows[0]; - if (row && row.vm_identity === binding.vmIdentity && row.proxy_identity === binding.proxyIdentity - && row.boot_epoch === binding.bootEpoch) return row.revoked_at === null ? Number(row.grant_revision) : null; - const grantRevision = row ? Number(row.grant_revision) + 1 : 1; - const saved = await client.query<{ grant_revision: string | number }>(`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 - RETURNING grant_revision`, - [binding.tenantId, binding.runId, binding.vmIdentity, binding.proxyIdentity, binding.bootEpoch, grantRevision]); - return saved.rows[0] ? Number(saved.rows[0].grant_revision) : null; - }); - } - - 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/run-retention-repository.ts b/packages/api/src/postgres/run-retention-repository.ts index f0c086f1..c4de6c62 100644 --- a/packages/api/src/postgres/run-retention-repository.ts +++ b/packages/api/src/postgres/run-retention-repository.ts @@ -79,10 +79,8 @@ export class RunRetentionRepository { SELECT 'integration_changes'::text,count(*)::int,floor(extract(epoch FROM now()-min(created_at)))::int FROM app.integration_changes WHERE created_at < now()-interval '14 days' UNION ALL - SELECT 'integration_generations'::text,count(*)::int,floor(extract(epoch FROM now()-min(created_at)))::int - FROM app.integration_generation_journal WHERE (state='staged' AND created_at < now()-interval '1 day') - OR (state='committed' AND committed_at < now()-interval '7 days') - OR (state IN ('rolled_back','expired') AND created_at < now()-interval '1 day') + SELECT 'model_device_authorizations'::text,count(*)::int,floor(extract(epoch FROM now()-min(expires_at)))::int + FROM app.model_device_authorizations WHERE expires_at tenants.id, { onDelete: "cascade" }), kind: text("kind").notNull(), encryptedValue: text("encrypted_value").notNull(), updatedAt: updatedAt() }, t => [primaryKey({ columns: [t.tenantId, t.kind] })]); export const integrationCollections = app.table("integration_collections", { - tenantId: uuid("tenant_id").primaryKey().references(() => tenants.id, { onDelete: "cascade" }), revision: bigint("revision", { mode: "number" }).notNull().default(0), changesPrunedThrough: bigint("changes_pruned_through", { mode: "number" }).notNull().default(0), createdAt: createdAt(), updatedAt: updatedAt(), + tenantId: uuid("tenant_id").primaryKey().references(() => tenants.id, { onDelete: "cascade" }), revision: bigint("revision", { mode: "number" }).notNull().default(0), createdAt: createdAt(), updatedAt: updatedAt(), }); export const integrationRecords = app.table("integration_records", { tenantId: uuid("tenant_id").notNull().references(() => integrationCollections.tenantId, { onDelete: "cascade" }), id: uuid("id").notNull(), kind: text("kind").$type<"bearer" | "model">().notNull(), name: text("name").notNull(), origin: text("origin"), description: text("description"), revision: bigint("revision", { mode: "number" }).notNull(), encryptedPayload: text("encrypted_payload"), deletedAt: timestamp("deleted_at", { withTimezone: true, mode: "date" }), createdAt: createdAt(), updatedAt: updatedAt(), @@ -50,21 +50,7 @@ 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 }), unlocked: boolean("unlocked").notNull().default(false), updatedAt: updatedAt(), -}); -export const credentialProxyBrowserPairings = app.table("credential_proxy_browser_pairings", { - tenantId: uuid("tenant_id").primaryKey().references(() => tenants.id, { onDelete: "cascade" }), - proxyIdentity: text("proxy_identity").notNull(), bootEpoch: uuid("boot_epoch").notNull(), - browserOrigin: text("browser_origin").notNull(), updatedAt: updatedAt(), -}); -export const credentialProxyControlCredentials = app.table("credential_proxy_control_credentials", { tenantId: uuid("tenant_id").notNull().references(() => tenants.id, { onDelete: "cascade" }), proxyIdentity: text("proxy_identity").notNull(), bootEpoch: uuid("boot_epoch").notNull(), tokenDigest: bytea("token_digest").notNull().unique(), proxyTokenDigest: bytea("proxy_token_digest").unique(), revokedAt: timestamp("revoked_at", { withTimezone: true }), consumedAt: timestamp("consumed_at", { withTimezone: true }), createdAt: createdAt() }, t => [primaryKey({ columns: [t.tenantId, t.proxyIdentity] })]); -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 modelDeviceAuthorizations = app.table("model_device_authorizations", {tenantId:uuid("tenant_id").notNull(),accountId:uuid("account_id").notNull(),userId:uuid("user_id").notNull(),sessionVersion:integer("session_version").notNull(),encryptedPayload:text("encrypted_payload").notNull(),expiresAt:timestamp("expires_at",{withTimezone:true}).notNull(),nextPollAt:timestamp("next_poll_at",{withTimezone:true}).notNull()},t=>[primaryKey({columns:[t.tenantId,t.accountId]}),foreignKey({columns:[t.tenantId,t.accountId],foreignColumns:[integrationRecords.tenantId,integrationRecords.id]}).onDelete("cascade"),index("model_device_authorizations_expiry").on(t.expiresAt)]); 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] }), index("github_setup_states_expiration").on(t.expiresAt,t.tenantId,t.nonce)]); @@ -115,7 +101,6 @@ export const runTraceEvents = app.table("run_trace_events", { export const runActivity = app.table("run_activity", { tenantId: uuid("tenant_id").notNull(), id: uuid("id").notNull(), runId: uuid("run_id").notNull(), action: text("action").notNull(), detail: text("detail").notNull(), createdAt: createdAt() }, t => [primaryKey({ columns: [t.tenantId, t.id] }), foreignKey({ columns: [t.tenantId, t.runId], foreignColumns: [runs.tenantId, runs.id] }).onDelete("cascade")]); export const activeClaims = app.table("active_claims", { tenantId: uuid("tenant_id").notNull(), jobId: uuid("job_id").notNull(), claimKey: text("claim_key").notNull(), runId: uuid("run_id").notNull(), expiresAt: timestamp("expires_at", { withTimezone: true }) }, t => [primaryKey({ columns: [t.tenantId, t.jobId, t.claimKey] }), foreignKey({ columns: [t.tenantId, t.jobId], foreignColumns: [jobs.tenantId, jobs.id] }).onDelete("cascade"), foreignKey({ columns: [t.tenantId, t.runId], foreignColumns: [runs.tenantId, runs.id] }).onDelete("cascade")]); export const runAuthorizations = app.table("run_authorizations", { tenantId: uuid("tenant_id").notNull(), runId: uuid("run_id").notNull(), userId: uuid("user_id").notNull(), sessionVersion: integer("session_version").notNull(), scopes: jsonb("scopes").$type().notNull(), createdAt: createdAt() }, t => [primaryKey({ columns: [t.tenantId, t.runId] }), foreignKey({ columns: [t.tenantId, t.runId], foreignColumns: [jobRuns.tenantId, jobRuns.id] }).onDelete("cascade")]); -export const runCredentials = app.table("run_credentials", { tenantId: uuid("tenant_id").notNull(), runId: uuid("run_id").notNull(), digest: text("digest").notNull(), proxyName: text("proxy_name"), scopes: jsonb("scopes").$type().notNull().default(DEFAULT_RUN_SCOPES), userId: uuid("user_id").notNull(), sessionVersion: integer("session_version").notNull(), expiresAt: timestamp("expires_at", { withTimezone: true }).notNull() }, t => [primaryKey({ columns: [t.tenantId, t.runId] }), foreignKey({ columns: [t.tenantId, t.runId], foreignColumns: [jobRuns.tenantId, jobRuns.id] }).onDelete("cascade"), foreignKey({ columns: [t.tenantId, t.userId], foreignColumns: [members.tenantId, members.userId] }).onDelete("cascade"), index("run_credentials_digest").on(t.digest)]); export const scheduleState = app.table("schedule_state", { tenantId: uuid("tenant_id").notNull(), triggerId: uuid("trigger_id").notNull(), jobId: uuid("job_id").notNull(), nextRunAt: timestamp("next_run_at", { withTimezone: true }), lastTriggeredAt: timestamp("last_triggered_at", { withTimezone: true }) }, t => [primaryKey({ columns: [t.tenantId, t.triggerId] }), foreignKey({ columns: [t.tenantId, t.triggerId], foreignColumns: [triggers.tenantId, triggers.id] }).onDelete("cascade"), foreignKey({ columns: [t.tenantId, t.jobId], foreignColumns: [jobs.tenantId, jobs.id] }).onDelete("cascade"), index("schedules_due").on(t.nextRunAt).where(sql`${t.nextRunAt} is not null`)]); export const automaticWakes = app.table("automatic_wakes", { tenantId: uuid("tenant_id").notNull(), jobId: uuid("job_id").notNull(), trailingPending: boolean("trailing_pending").notNull().default(false), summary: jsonb("summary").$type>().notNull().default({}), updatedAt: updatedAt() }, t => [primaryKey({ columns: [t.tenantId, t.jobId] }), foreignKey({ columns: [t.tenantId, t.jobId], foreignColumns: [jobs.tenantId, jobs.id] }).onDelete("cascade")]); @@ -169,7 +154,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, credentialProxyStates, credentialProxyControlCredentials, credentialRunGrants, credentialRunEnrollments, linearWorkspaces, githubInstallations, githubSetupStates, projects, jobs, vmImageVerifications, skills, jobSkills, triggers, webhookConditionsCutover, invocations, manualInvocationPermissions, jobRuns, runAuthorizations, runCredentials, runs, runArtifacts, runRetentionCleanup, + connections, integrationCollections, integrationRecords, integrationChanges, modelDeviceAuthorizations, linearWorkspaces, githubInstallations, githubSetupStates, projects, jobs, vmImageVerifications, skills, jobSkills, triggers, webhookConditionsCutover, invocations, manualInvocationPermissions, jobRuns, runAuthorizations, runs, runArtifacts, runRetentionCleanup, 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/proxy-browser-capability.ts b/packages/api/src/proxy-browser-capability.ts deleted file mode 100644 index e2777c4c..00000000 --- a/packages/api/src/proxy-browser-capability.ts +++ /dev/null @@ -1,46 +0,0 @@ -const encoder = new TextEncoder(); -const base64url = (bytes: Uint8Array) => btoa(String.fromCharCode(...bytes)).replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_"); - -function decodePem(pem: string): Uint8Array { - const body = pem.replace(/-----BEGIN PRIVATE KEY-----|-----END PRIVATE KEY-----|\s/g, ""); - if (!/^[A-Za-z0-9+/]+={0,2}$/.test(body)) throw new TypeError("invalid browser capability signing key"); - const binary = atob(body); - return Uint8Array.from(binary, character => character.charCodeAt(0)); -} - -/** Issue a one-use capability accepted only by the paired proxy listener. */ -async function issueCapability(input: { - privateKeyPem: string; - proxyIdentity: string; - ownerId: string; - accountId?: string; - action: string; - family: "model-account" | "proxy"; - appOrigin: string; - generation: number | string; - now?: number; - jti?: string; -}): Promise { - const now = input.now ?? Math.floor(Date.now() / 1000); - const header = base64url(encoder.encode(JSON.stringify({ alg: "EdDSA", typ: "JWT" }))); - const claims = base64url(encoder.encode(JSON.stringify({ - iss: "factorize", aud: input.proxyIdentity, sub: input.ownerId, - action: `${input.family}:${input.action}`, accountId: input.accountId, - origin: input.appOrigin, generation: input.generation, exp: now + 60, - jti: input.jti ?? base64url(crypto.getRandomValues(new Uint8Array(24))), - }))); - const payload = `${header}.${claims}`; - const rawKey = decodePem(input.privateKeyPem); - const keyData = new ArrayBuffer(rawKey.byteLength); - new Uint8Array(keyData).set(rawKey); - const key = await crypto.subtle.importKey("pkcs8", keyData, { name: "Ed25519" }, false, ["sign"]); - const signature = await crypto.subtle.sign("Ed25519", key, encoder.encode(payload)); - return `${payload}.${base64url(new Uint8Array(signature))}`; -} - -export function issueModelAccountCapability(input: Omit[0], "family"> & { accountId: string; action: "authorize" | "status" | "cancel" }) { - return issueCapability({ ...input, family: "model-account" }); -} -export function issueProxyCapability(input: Omit[0], "family" | "accountId"> & { action: "unlock" | "lock" | "apply" | "status" }) { - return issueCapability({ ...input, family: "proxy" }); -} diff --git a/packages/api/src/proxy-control.ts b/packages/api/src/proxy-control.ts deleted file mode 100644 index b55128aa..00000000 --- a/packages/api/src/proxy-control.ts +++ /dev/null @@ -1,186 +0,0 @@ -import { databaseFor } from "./postgres/database"; -import { ProxyControlRepository } from "./postgres/proxy-control-repository"; -import { RunEnrollmentRepository } from "./postgres/run-enrollment-repository"; -import { EncryptedIntegrationRepository } from "./postgres/encrypted-integration-repository"; -import { authenticateRunCredential } from "./run-credentials"; -import { resolveRunProviderCredentials } from "./provider-credentials"; - -async function recordOwner(env: Parameters[0], tenantId: string): Promise { - const result = await databaseFor(env).pool.query<{ user_id: string }>("SELECT user_id FROM app.members WHERE tenant_id=$1 AND role='owner' ORDER BY created_at,user_id LIMIT 1", [tenantId]); - if (!result.rows[0]) throw new Error("Proxy record owner is unavailable"); - return result.rows[0].user_id; -} - -const json = (body: unknown, status = 200) => Response.json(body, { status, headers: { "Cache-Control": "no-store" } }); - -/** Dedicated service-to-service endpoint. The run API credential is intentionally not accepted here. */ -export async function proxyControlFetch(request: Request, env: Parameters[0]): Promise { - const url = new URL(request.url); - if (!["/internal/credential-proxy/register-boot", "/internal/credential-proxy/status", "/internal/credential-proxy/unlock-verification", "/internal/credential-proxy/enroll", "/internal/credential-proxy/consume-enrollment", "/internal/credential-proxy/integration-snapshot", "/internal/credential-proxy/model-account-cache", "/internal/credential-proxy/revocations"].includes(url.pathname)) return json({ error: "not_found" }, 404); - if (request.method !== "POST") return json({ error: "method_not_allowed" }, 405); - if (request.headers.get("content-type")?.split(";", 1)[0]?.trim().toLowerCase() !== "application/json") return json({ error: "unsupported_media_type" }, 415); - const authorization = request.headers.get("authorization") ?? ""; - const token = authorization.startsWith("Bearer ") ? authorization.slice(7) : ""; - if (!/^fzc_[A-Za-z0-9_-]{43}$/.test(token)) return json({ error: "unauthorized" }, 401); - const declaredLength = Number(request.headers.get("content-length") ?? "0"); - const maxBodyBytes = url.pathname === "/internal/credential-proxy/model-account-cache" ? 70_000 : 1024; - if (declaredLength > maxBodyBytes) return json({ error: "invalid_request" }, 413); - let body: unknown; - try { - const reader = request.body?.getReader(); - const chunks: Uint8Array[] = []; let length = 0; - if (reader) for (;;) { - const { done, value } = await reader.read(); if (done) break; - length += value.byteLength; - if (length > maxBodyBytes) { await reader.cancel(); return json({ error: "invalid_request" }, 413); } - chunks.push(value); - } - const bytes = new Uint8Array(length); let offset = 0; - for (const chunk of chunks) { bytes.set(chunk, offset); offset += chunk.byteLength; } - body = JSON.parse(new TextDecoder().decode(bytes)); - } catch { return json({ error: "invalid_request" }, 400); } - const repository = new ProxyControlRepository(databaseFor(env)); - if (url.pathname === "/internal/credential-proxy/register-boot") { - if (!body || typeof body !== "object" || Array.isArray(body) || Object.keys(body).sort().join(",") !== "bootEpoch,browserOrigin" || typeof (body as any).bootEpoch !== "string" || typeof (body as any).browserOrigin !== "string") return json({ error: "invalid_request" }, 400); - const registration = await repository.registerBoot(token, (body as any).bootEpoch, (body as any).browserOrigin); - if (!registration) return json({ error: "proxy_registration_unavailable" }, 403); - return json({ registered: true, tenantId: registration.tenantId, proxyIdentity: registration.proxyIdentity, bootEpoch: registration.bootEpoch, controlCredential: registration.controlCredential, recordOwnerId: await recordOwner(env, registration.tenantId) }); - } - - if (url.pathname === "/internal/credential-proxy/status") { - if (!body || typeof body !== "object" || Array.isArray(body) || Object.keys(body).sort().join(",") !== "bootEpoch,unlocked" - || typeof (body as any).bootEpoch !== "string" || typeof (body as any).unlocked !== "boolean") return json({ error: "invalid_request" }, 400); - const updated = await repository.reportRuntimeStatus(token, (body as any).bootEpoch, (body as any).unlocked); - return updated ? json({ updated: true }) : json({ error: "proxy_status_unavailable" }, 403); - } - - const proxy = await repository.authenticateProxy(token); - if (!proxy) return json({ error: "unauthorized" }, 401); - if (url.pathname === "/internal/credential-proxy/unlock-verification") { - if (!body || typeof body !== "object" || Array.isArray(body) || Object.keys(body).length) return json({ error: "invalid_request" }, 400); - const value = await databaseFor(env).pool.query("SELECT generation_id,encrypted_verification FROM app.unlock_key_verifications WHERE tenant_id=$1", [proxy.tenantId]); - if (!value.rows[0]) return json({ error: "not_found" }, 404); - return json({ ownerId: await recordOwner(env, proxy.tenantId), generationId: value.rows[0].generation_id, encryptedVerification: value.rows[0].encrypted_verification }); - } - if (url.pathname === "/internal/credential-proxy/revocations") { - if (!body || typeof body !== "object" || Array.isArray(body) || Object.keys(body).some(key => key !== "bootEpoch") - || typeof (body as any).bootEpoch !== "string" || (body as any).bootEpoch !== proxy.bootEpoch) return json({ error: "invalid_request" }, 400); - const revoked = await databaseFor(env).pool.query<{ run_id: string }>(`SELECT run_id FROM app.credential_run_grants - WHERE tenant_id=$1 AND proxy_identity=$2 AND boot_epoch=$3 AND revoked_at IS NOT NULL - UNION - SELECT c.run_id FROM app.run_credentials c JOIN app.job_runs r ON r.tenant_id=c.tenant_id AND r.id=c.run_id - WHERE c.tenant_id=$1 AND r.state IN ('succeeded','failed','stopped') ORDER BY run_id`, - [proxy.tenantId, proxy.proxyIdentity, proxy.bootEpoch]); - const state = await databaseFor(env).pool.query<{ unlocked: boolean }>("SELECT unlocked FROM app.credential_proxy_states WHERE tenant_id=$1 AND proxy_identity=$2 AND boot_epoch=$3", [proxy.tenantId, proxy.proxyIdentity, proxy.bootEpoch]); - const activeModelAccounts = await databaseFor(env).pool.query<{ id: string }>("SELECT id FROM app.integration_records WHERE tenant_id=$1 AND kind='model' AND deleted_at IS NULL", [proxy.tenantId]); - return json({ revokedRunIds: revoked.rows.map(row => row.run_id), activeModelAccountIds: activeModelAccounts.rows.map(row => row.id), lockProxy: !state.rows[0]?.unlocked }); - } - if (url.pathname === "/internal/credential-proxy/model-account-cache") { - if (!body || typeof body !== "object" || Array.isArray(body)) return json({ error: "invalid_request" }, 400); - const input = body as Record; - const uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; - if (input.operation === "list" && Object.keys(input).length === 1) { - const accounts = await new EncryptedIntegrationRepository(databaseFor(env), proxy.tenantId, env.CREDENTIAL_ENCRYPTION_KEY).records("model"); - return json({ ownerId: await recordOwner(env, proxy.tenantId), - accounts: accounts.map(({ id, revision }) => ({ id, revision, kind: "model", origin: null })) }); - } - if (input.operation === "read" && Object.keys(input).sort().join(",") === "accountId,operation" - && typeof input.accountId === "string" && uuid.test(input.accountId)) { - const account = (await new EncryptedIntegrationRepository(databaseFor(env), proxy.tenantId, env.CREDENTIAL_ENCRYPTION_KEY).records("model")) - .find(record => record.id === input.accountId); - if (!account) return json({ error: "model_account_unavailable" }, 404); - return json({ ownerId: await recordOwner(env, proxy.tenantId), account }); - } - if (input.operation !== "save" || Object.keys(input).sort().join(",") !== "accountId,encryptedPayload,expectedRevision,idempotencyKey,operation" - || typeof input.accountId !== "string" || !uuid.test(input.accountId) - || typeof input.idempotencyKey !== "string" || !uuid.test(input.idempotencyKey) - || !Number.isSafeInteger(input.expectedRevision) || (input.expectedRevision as number) < 0 - || typeof input.encryptedPayload !== "string" || input.encryptedPayload.length > 65_536) return json({ error: "invalid_request" }, 400); - try { - const saved = await new EncryptedIntegrationRepository(databaseFor(env), proxy.tenantId, env.CREDENTIAL_ENCRYPTION_KEY).saveModelCache({ - id: input.accountId, expectedRevision: input.expectedRevision as number, - idempotencyKey: input.idempotencyKey, encryptedPayload: input.encryptedPayload, - }); - return json({ ...saved, accountId: input.accountId }); - } catch (error) { - if (error instanceof Error && error.name === "StaleIntegrationRevisionError") return json({ error: "stale_revision" }, 409); - if (error instanceof Error && error.name === "IntegrationIdempotencyConflictError") return json({ error: "idempotency_conflict" }, 409); - if (error instanceof Error && error.name === "IntegrationValidationError") return json({ error: "model_account_unavailable" }, 404); - throw error; - } - } - if (url.pathname === "/internal/credential-proxy/integration-snapshot") { - if (!body || typeof body !== "object" || Array.isArray(body) || Object.keys(body).some(key => !["runId", "grantRevision"].includes(key)) - || typeof (body as any).runId !== "string" || !Number.isSafeInteger((body as any).grantRevision) || (body as any).grantRevision < 0) return json({ error: "invalid_request" }, 400); - const database = databaseFor(env); - const active = await database.pool.query<{ execution_config: Record; grant_revision: string | number }>(`SELECT r.execution_config,g.grant_revision - FROM app.runs r JOIN app.credential_run_grants g ON g.tenant_id=r.tenant_id AND g.run_id=r.id - JOIN app.credential_proxy_states p ON p.tenant_id=g.tenant_id AND p.proxy_identity=g.proxy_identity AND p.boot_epoch=g.boot_epoch - WHERE r.tenant_id=$1 AND r.id=$2 AND r.state IN ('starting','running','blocked') - AND g.proxy_identity=$3 AND g.boot_epoch=$4 AND g.grant_revision=$5 AND g.revoked_at IS NULL - AND p.disabled_at IS NULL AND p.revoked_at IS NULL`, [proxy.tenantId, (body as any).runId, proxy.proxyIdentity, proxy.bootEpoch, (body as any).grantRevision]); - const run = active.rows[0]; - if (!run) return json({ error: "integration_snapshot_unavailable" }, 403); - const selected = run.execution_config?.portableIntegrationIds; - if (!Array.isArray(selected) || selected.some(id => typeof id !== "string") || new Set(selected).size !== selected.length) return json({ error: "integration_snapshot_unavailable" }, 403); - const currentRecords = selected.length - ? await new EncryptedIntegrationRepository(database, proxy.tenantId, env.CREDENTIAL_ENCRYPTION_KEY).recordsIncludingDeleted("bearer") - : []; - const byId = new Map(currentRecords.map(record => [record.id, record])); - // A generation reset may remove a row rather than leave its CRUD tombstone. - // Represent a missing selected record as a ciphertext-free tombstone so - // established proxy connections can remove that grant on refresh. - const records = selected.map(id => byId.get(id) ?? { id, kind: "bearer" as const, name: "", origin: null, - description: null, revision: 0, encryptedPayload: null, deletedAt: new Date(0) }); - if (records.length !== selected.length) return json({ error: "integration_snapshot_unavailable" }, 403); - const modelAccess = run.execution_config?.modelAccess ?? "native"; - const modelAccountId = run.execution_config?.modelAccountId; - let modelAccount = null; - if (modelAccess === "portable") { - if (typeof modelAccountId !== "string") return json({ error: "integration_snapshot_unavailable" }, 403); - modelAccount = (await new EncryptedIntegrationRepository(database, proxy.tenantId, env.CREDENTIAL_ENCRYPTION_KEY).records("model")) - .find(record => record.id === modelAccountId) ?? null; - // A deleted selected account is a revocation signal for an already-open - // run tunnel. Preserve the active run snapshot with a null account so the - // proxy replaces its model credential with an unavailable state. - } else if (modelAccess !== "native" || modelAccountId !== undefined) { - return json({ error: "integration_snapshot_unavailable" }, 403); - } - const selectedGitHub = run.execution_config?.githubInstallationIds ?? []; - if (!Array.isArray(selectedGitHub) || selectedGitHub.some(id => !Number.isSafeInteger(id) || id <= 0) || new Set(selectedGitHub).size !== selectedGitHub.length) return json({ error: "integration_snapshot_unavailable" }, 403); - const selectedLinear = run.execution_config?.linearConnectionId; - if (selectedLinear !== undefined && selectedLinear !== "linear") return json({ error: "integration_snapshot_unavailable" }, 403); - const providerCredentials = await resolveRunProviderCredentials({ database, env, tenantId: proxy.tenantId, - githubInstallationIds: selectedGitHub, linearSelected: selectedLinear === "linear" }); - // Only the selected model account's user-encrypted payload crosses the - // control plane. It remains encrypted until the proxy is unlocked. Provider - // credentials cross only this authenticated proxy control channel. - return json({ ownerId: await recordOwner(env, proxy.tenantId), records, modelAccount, providerCredentials }); - } - const enrollments = new RunEnrollmentRepository(databaseFor(env)); - if (url.pathname === "/internal/credential-proxy/enroll") { - if (!body || typeof body !== "object" || Array.isArray(body) || Object.keys(body).some(key => !["runId", "vmIdentity", "runCredential"].includes(key)) - || typeof (body as any).runId !== "string" || typeof (body as any).vmIdentity !== "string" || typeof (body as any).runCredential !== "string" - || (body as any).vmIdentity.length === 0 || (body as any).vmIdentity.length > 255) return json({ error: "invalid_request" }, 400); - // A proxy-authenticated request alone must not let a peer that can reach - // the proxy claim another active run. The VM's distinct run credential is - // validated against the current run and tenant before issuing enrollment. - const runAuth = await authenticateRunCredential(new Request(request.url, { - headers: { Authorization: `Bearer ${(body as any).runCredential}` }, - }), env); - if (!runAuth || !runAuth.runId || runAuth.runId !== (body as any).runId || runAuth.tenantId !== proxy.tenantId - || !runAuth.scopes.includes("integrations:read")) return json({ error: "enrollment_unavailable" }, 403); - const binding = { tenantId: proxy.tenantId, runId: runAuth.runId, vmIdentity: (body as any).vmIdentity, proxyIdentity: proxy.proxyIdentity, bootEpoch: proxy.bootEpoch }; - // This is the production grant-creation path. Authenticate the active run - // before binding it to its provider VM, and make reconnect authorization - // idempotent for the same VM and proxy boot while advancing stale bindings. - if (await enrollments.authorizeRun(binding) === null) return json({ error: "enrollment_unavailable" }, 403); - const enrollment = await enrollments.issue(binding, new Date(Date.now() + 30_000)); - return enrollment ? json(enrollment) : json({ error: "enrollment_unavailable" }, 403); - } - if (!body || typeof body !== "object" || Array.isArray(body) || Object.keys(body).some(key => !["runId", "vmIdentity", "enrollmentToken"].includes(key)) - || typeof (body as any).runId !== "string" || typeof (body as any).vmIdentity !== "string" || typeof (body as any).enrollmentToken !== "string") return json({ error: "invalid_request" }, 400); - const binding = { tenantId: proxy.tenantId, runId: (body as any).runId, vmIdentity: (body as any).vmIdentity, proxyIdentity: proxy.proxyIdentity, bootEpoch: proxy.bootEpoch }; - const consumed = await enrollments.consume((body as any).enrollmentToken, binding); - return consumed ? json({ consumed: true, binding: consumed }) : json({ error: "enrollment_unavailable" }, 403); -} diff --git a/packages/api/src/proxy-launch-policy.ts b/packages/api/src/proxy-launch-policy.ts deleted file mode 100644 index da8cb5ab..00000000 --- a/packages/api/src/proxy-launch-policy.ts +++ /dev/null @@ -1,61 +0,0 @@ -/** Inputs required to decide whether a queued execution may create a guest VM. */ -export type ProxyLaunchState = { - enabled: boolean; - running: boolean; - unlocked: boolean; - pendingChanges: boolean; -}; - -export type ProxyLaunchJob = { - executionProvider: "exe" | "fly"; - executionType: "agent" | "code"; - portableIntegrationIds?: readonly string[]; - modelAccess?: "native" | "portable"; - modelAccountId?: string; -}; - -export type ProxyLaunchDecision = - | { kind: "allow" } - | { kind: "start_locked" } - | { kind: "blocked"; reason: "proxy_disabled" | "proxy_unavailable" | "proxy_locked" | "pending_changes"; retry: "manual" }; - -export class ProxyLaunchBlockedError extends Error { - constructor(readonly reason: Extract["reason"]) { - super(`Job launch is blocked until proxy prerequisite is resolved: ${reason}`); - this.name = "ProxyLaunchBlockedError"; - } -} - -export function requireProxyLaunch(decision: ProxyLaunchDecision): void { - if (decision.kind === "blocked") throw new ProxyLaunchBlockedError(decision.reason); -} - -/** - * Encodes the GEN-2824 launch gate. This function is deliberately side-effect - * free: the scheduler must persist a blocked decision and wait for an explicit - * retry instead of treating a later unlock as a queued launch signal. - */ -export function proxyLaunchDecision(job: ProxyLaunchJob, proxy: ProxyLaunchState): ProxyLaunchDecision { - const needsUserCredentials = Boolean(job.portableIntegrationIds?.length) - || job.modelAccess === "portable" - || Boolean(job.modelAccountId); - - // exe.dev-native integrations keep their existing launch behavior. - if (job.executionProvider === "exe" && !needsUserCredentials) return { kind: "allow" }; - - if (!proxy.enabled) return { kind: "blocked", reason: "proxy_disabled", retry: "manual" }; - - // Only code jobs with Factorize access may automatically boot a stopped - // proxy, and that boot is always locked. - if (!needsUserCredentials && job.executionType === "code") { - if (!proxy.running) return { kind: "start_locked" }; - return { kind: "allow" }; - } - - // User credential grants require an already-running proxy with edits - // applied and a user unlock. Unlocking alone does not resume this run. - if (!proxy.running) return { kind: "blocked", reason: "proxy_unavailable", retry: "manual" }; - if (proxy.pendingChanges) return { kind: "blocked", reason: "pending_changes", retry: "manual" }; - if (!proxy.unlocked) return { kind: "blocked", reason: "proxy_locked", retry: "manual" }; - return { kind: "allow" }; -} diff --git a/packages/api/src/proxy-provisioner.ts b/packages/api/src/proxy-provisioner.ts deleted file mode 100644 index c32e7e5d..00000000 --- a/packages/api/src/proxy-provisioner.ts +++ /dev/null @@ -1,40 +0,0 @@ -import type { ProxyControlRepository } from "./postgres/proxy-control-repository"; - -export type ProxyBootstrapProvisioning = { - tenantId: string; - proxyIdentity: string; - /** A new UUID for every process boot. */ - bootEpoch: string; - controlOrigin: string; - browserOrigin: string; -}; - -/** - * Connects one-use bootstrap credential issuance to the infrastructure - * provisioner's private control channel. Implementations must deliver the - * credential directly to proxy stdin (or an equally short-lived memory-only - * channel), never through Machine config, environment, metadata, disk, or logs. - */ -export async function provisionCredentialProxy( - input: ProxyBootstrapProvisioning, - dependencies: { - control: Pick; - startProxy: (request: ProxyBootstrapProvisioning & { credential: string }) => Promise; - }, -): Promise<{ proxyIdentity: string; bootEpoch: string }> { - const origin = new URL(input.controlOrigin); - if (origin.protocol !== "https:" || origin.username || origin.password || origin.pathname !== "/" || origin.search || origin.hash) { - throw new TypeError("controlOrigin must be an HTTPS origin"); - } - const browserOrigin = new URL(input.browserOrigin); - if (browserOrigin.protocol !== "https:" || browserOrigin.origin !== input.browserOrigin || browserOrigin.username || browserOrigin.password) throw new TypeError("browserOrigin must be an HTTPS origin"); - const credential = await dependencies.control.provisionCredential(input.tenantId, input.proxyIdentity, input.bootEpoch); - try { - await dependencies.startProxy({ ...input, controlOrigin: origin.origin, browserOrigin: browserOrigin.origin, credential }); - } catch (error) { - // A failed/ambiguous start must not leave a valid bootstrap credential. - await dependencies.control.revokeCredential(input.tenantId, input.proxyIdentity).catch(() => false); - throw error; - } - return { proxyIdentity: input.proxyIdentity, bootEpoch: input.bootEpoch }; -} diff --git a/packages/api/src/run-credential-launch.ts b/packages/api/src/run-credential-launch.ts index 8d9ae948..16961857 100644 --- a/packages/api/src/run-credential-launch.ts +++ b/packages/api/src/run-credential-launch.ts @@ -1,6 +1,6 @@ import type { Database } from "./postgres/database"; import type { Env } from "./types"; -import { EncryptedIntegrationRepository } from "./postgres/encrypted-integration-repository"; +import { CredentialRepository } from "./postgres/credential-repository"; import { GitHubRepository } from "./postgres/github-repository"; import { isPublicHttpsOrigin } from "./public-address"; import { resolveManagedModelCredential } from "./managed-model-credentials"; @@ -12,7 +12,7 @@ export class RunCredentialRepairRequired extends Error { * explicit repair. No unlock/proxy service is a launch prerequisite. */ export async function requireRunCredentials(input: {database: Database; env: Env; tenantId: string; runId: string; config: Record}): Promise { const {database, env, tenantId, runId, config} = input; - const repository = new EncryptedIntegrationRepository(database, tenantId, env.CREDENTIAL_ENCRYPTION_KEY); + const repository = new CredentialRepository(database, tenantId, env.CREDENTIAL_ENCRYPTION_KEY); const revoked = (await database.pool.query("SELECT 1 FROM app.run_credential_revocations WHERE tenant_id=$1 AND run_id=$2 LIMIT 1", [tenantId, runId])).rowCount; if (revoked) throw new RunCredentialRepairRequired(); const ids = config.portableIntegrationIds ?? [], githubIds = config.githubInstallationIds ?? []; diff --git a/packages/api/src/run-credentials.ts b/packages/api/src/run-credentials.ts deleted file mode 100644 index a809d5b4..00000000 --- a/packages/api/src/run-credentials.ts +++ /dev/null @@ -1,55 +0,0 @@ -import type { Env, OAuthProps } from "./types"; -import { databaseFor } from "./postgres/database"; -import { DEFAULT_RUN_SCOPES } from "./run-scopes"; -import { normalizeScopes, accessTokenDigest } from "./access-tokens"; - -// Compatibility export for existing integrations and tests. -export const RUN_SCOPES = DEFAULT_RUN_SCOPES; -const RUN_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; - -export function runProxyName(runId: string): string { - if (!RUN_ID.test(runId)) throw new Error("A UUID run identity is required for a run proxy"); - return `fz-run-${runId.toLowerCase()}`; -} - -export function runProxyInstructions(runId: string, providers: { githubInstallationIds?: number[]; linear?: boolean; model?: boolean } = {}): string { - const github = [...new Set(providers.githubInstallationIds ?? [])].filter(id => Number.isSafeInteger(id) && id > 0) - .map(id => `${id}: http://127.0.0.1:18180/providers/github/${id}/`).join(", "); - const selectedProviders = [github ? `selected GitHub installation endpoints: ${github} (REST/GraphQL and Git smart HTTP)` : "", - providers.linear ? "selected Linear endpoint: http://127.0.0.1:18180/providers/linear/ (GraphQL)" : "", - providers.model ? "selected model endpoint: http://127.0.0.1:18180/providers/model/v1 (Codex Responses; already configured for Codex)" : ""].filter(Boolean).join("\n"); - return `\n\n## Factorize access\nThis run's complete Factorize proxy origin is https://${runProxyName(runId)}.int.exe.xyz. Preserve the entire hostname, including .int.exe.xyz. Discover the ${runProxyName(runId)} integration in https://reflection.int.exe.xyz/integrations and use the proxy URL in its help text for all Factorize /api/v1 requests, replacing any shared Factorize hostname mentioned in the task or job template. exe.dev injects this run's credential outside the VM; do not supply Authorization headers or look for tokens in the environment. GET /api/v1/runtime-context through this proxy to verify your identity and discover your effective scopes. Only perform operations permitted by those scopes. Job-to-job invocation also requires explicit destination authorization. A granted jobs:write permits editing job configuration and future run scopes; never assume a write is unavailable merely because this is a run proxy. If an optional bookkeeping operation is unavailable, continue implementation and report that limitation. Use FACTORIZE_PROXY_URL for authenticated outbound integration requests and the endpoint variables supplied to your agent for selected providers. Never access provider APIs directly when a selected endpoint is available. Use FACTORIZE_RESULT_PATH to report the final outcome.${selectedProviders ? `\n\n## Selected provider clients\n${selectedProviders}\nThe run proxy injects credentials server-side. Clients must not supply or cache provider credentials. Use only these listed endpoints for the selected connections.` : ""}\n`; -} - -const encode = (value: string) => btoa(String.fromCharCode(...new TextEncoder().encode(value))).replaceAll("+", "-").replaceAll("/", "_").replaceAll("=", ""); -const encodeBytes = (value: Uint8Array) => btoa(String.fromCharCode(...value)).replaceAll("+", "-").replaceAll("/", "_").replaceAll("=", ""); -const decode = (value: string) => new TextDecoder().decode(Uint8Array.from(atob(value.replaceAll("-", "+").replaceAll("_", "/") + "===".slice((value.length + 3) % 4)), c => c.charCodeAt(0))); - -/** Rotate on each launch attempt; only a digest is persisted. */ -export async function issueRunCredential(env: Env, tenantId: string, runId: string, scopes: readonly string[] = RUN_SCOPES): Promise { - const secret = crypto.getRandomValues(new Uint8Array(32)); - const token = `fzt_run_${encode(runId)}_${encodeBytes(secret)}`; - const db = databaseFor(env); - const owner = (await db.pool.query<{ user_id: string; session_version: number }>("SELECT user_id,session_version FROM app.members WHERE tenant_id=$1 AND role='owner' ORDER BY user_id LIMIT 1", [tenantId])).rows[0]; - if (!owner) throw new Error("Run owner is unavailable"); - await db.pool.query(`INSERT INTO app.run_credentials(tenant_id,run_id,digest,user_id,session_version,expires_at,proxy_name,scopes) - VALUES ($1,$2,$3,$4,$5,now()+interval '24 hours',$6,$7::jsonb) ON CONFLICT (tenant_id,run_id) DO UPDATE SET digest=excluded.digest,user_id=excluded.user_id,session_version=excluded.session_version,expires_at=excluded.expires_at,proxy_name=excluded.proxy_name`, [tenantId, runId, await accessTokenDigest(token), owner.user_id, owner.session_version, runProxyName(runId), JSON.stringify(normalizeScopes(scopes))]); - return token; -} - -export async function authenticateRunCredential(request: Request, env: Env): Promise { - const value = request.headers.get("Authorization")?.match(/^Bearer (fzt_run_[A-Za-z0-9_-]+_[A-Za-z0-9_-]{43})$/)?.[1]; - if (!value) return null; - const match = value.match(/^fzt_run_([A-Za-z0-9_-]+)_([A-Za-z0-9_-]{43})$/); - if (!match) return null; - let runId: string; - try { runId = decode(match[1]!); } catch { return null; } - if (!RUN_ID.test(runId)) return null; - const digest = await accessTokenDigest(value); - const result = await databaseFor(env).pool.query<{ tenant_id: string; user_id: string; session_version: number; job_id: string; scopes: string[] }>(`SELECT c.tenant_id,c.user_id,c.session_version,r.job_id,c.scopes - FROM app.run_credentials c JOIN app.job_runs r ON r.tenant_id=c.tenant_id AND r.id=c.run_id - JOIN app.members m ON m.tenant_id=c.tenant_id AND m.user_id=c.user_id AND m.role='owner' AND m.session_version=c.session_version - WHERE c.run_id=$1 AND c.digest=$2 AND c.proxy_name=$3 AND c.expires_at>now() AND r.state IN ('reserved','starting','running','blocked','stopping')`, [runId, digest, runProxyName(runId)]); - const row = result.rows[0]; - return row ? { tenantId: row.tenant_id, userId: row.user_id, sessionVersion: row.session_version, scopes: normalizeScopes(row.scopes), authMethod: "run_token", runId, runJobId: row.job_id, runCredentialDigest: digest } : null; -} diff --git a/packages/api/src/run-enrollment-service.ts b/packages/api/src/run-enrollment-service.ts deleted file mode 100644 index f35dba67..00000000 --- a/packages/api/src/run-enrollment-service.ts +++ /dev/null @@ -1,22 +0,0 @@ -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/src/run-outbound-proxy.ts b/packages/api/src/run-outbound-proxy.ts index 9276543a..532839dd 100644 --- a/packages/api/src/run-outbound-proxy.ts +++ b/packages/api/src/run-outbound-proxy.ts @@ -1,6 +1,6 @@ import type { Env } from "./types"; import { databaseFor } from "./postgres/database"; -import { EncryptedIntegrationRepository } from "./postgres/encrypted-integration-repository"; +import { CredentialRepository } from "./postgres/credential-repository"; import { resolveRunProviderCredentials } from "./provider-credentials"; import { authenticateVendorRunRequest, RUN_IDENTITY_HEADER } from "./vendor-run-auth"; import { forwardRunOutbound, type OutboundCredential } from "./run-outbound-forwarder"; @@ -35,7 +35,7 @@ export async function runOutboundProxyFetch(request: Request, env: Env): Promise const model = /^\/providers\/model\/v1(\/.*)?$/.exec(path); if (bearer) { if (!Array.isArray(config.portableIntegrationIds) || !config.portableIntegrationIds.includes(bearer[1]) || await revoked("bearer", bearer[1]!)) return unavailable(); - const credential = await new EncryptedIntegrationRepository(database, auth.tenantId, env.CREDENTIAL_ENCRYPTION_KEY).managedCredential(bearer[1]!, "bearer"); + const credential = await new CredentialRepository(database, auth.tenantId, env.CREDENTIAL_ENCRYPTION_KEY).managedCredential(bearer[1]!, "bearer"); if (!credential?.origin || !isPublicHttpsOrigin(credential.origin, env.APP_ORIGIN)) return unavailable(); selected = {origin: credential.origin, path: `${bearer[2] ?? "/"}${url.search}`, credential: credential.payload}; } else if (github) { diff --git a/packages/api/src/types.ts b/packages/api/src/types.ts index f72cc575..2bec0dd7 100644 --- a/packages/api/src/types.ts +++ b/packages/api/src/types.ts @@ -5,8 +5,6 @@ export type RunState = "queued" | "reserved" | "starting" | "running" | "done" | export interface Env { /** Explicit local test environment; never configured on deployed Workers. */ TEST_DOCKER_EXECUTION?: { enabled: true; image: string }; - /** Infrastructure host boundary. Host process credentials stay outside Workers. */ - CREDENTIAL_PROXY_HOST?: { setup(tenantId: string, operationId: string): Promise<{ proxyIdentity: string; bootEpoch: string }> }; SCHEDULER?: DurableObjectNamespace; ASSETS: Fetcher; APP_ORIGIN: string; @@ -19,9 +17,6 @@ export interface Env { CLICKUP_CLIENT_SECRET?: string; CREDENTIAL_ENCRYPTION_KEY: string; SESSION_SIGNING_SECRET: string; - /** PKCS#8 Ed25519 key used only for short-lived proxy browser capabilities. */ - MODEL_ACCOUNT_CAPABILITY_PRIVATE_KEY?: string; - MODEL_ACCOUNT_CAPABILITY_PUBLIC_KEY?: string; GITHUB_APP_ID?: string; GITHUB_APP_SLUG?: string; GITHUB_APP_PRIVATE_KEY?: string; @@ -54,12 +49,11 @@ export type OAuthProps = { /** Set only by a verified, active execution credential. */ runId?: string; runJobId?: string; - runCredentialDigest?: string; runIdentityProvider?: "exe.dev" | "fly.io"; /** Stable identifier for the OAuth authorization grant; never a bearer token. */ oauthGrantId?: string; oauthClientId?: string; - authMethod?: "session" | "oauth" | "access_token" | "run_token" | "vendor_identity"; + authMethod?: "session" | "oauth" | "access_token" | "vendor_identity"; }; export interface WorkItem { diff --git a/packages/api/test/api-boundary.test.ts b/packages/api/test/api-boundary.test.ts index 5a9f32a2..be466e0e 100644 --- a/packages/api/test/api-boundary.test.ts +++ b/packages/api/test/api-boundary.test.ts @@ -94,14 +94,6 @@ const jobInput = { }; describe("Worker OpenAPI request/response boundaries", () => { - it("accepts only browser-encrypted unlock verification and rejects plaintext key fields", async () => { - const payload = { generationId: "00000000-0000-4000-8000-000000000001", encryptedVerification: JSON.stringify({ version: 1, algorithm: "A256GCM", nonce: "AAAAAAAAAAAAAAAA", ciphertext: "AAAAAAAAAAAAAAAAAAAAAA" }) }; - const create = vi.spyOn(ApiService.prototype, "createUnlockKeyVerification").mockResolvedValue({ generationId: payload.generationId }); - await assertResponse(await request("POST", "/api/v1/unlock-key/verification", payload), "POST", "/api/v1/unlock-key/verification", 200); - expect(create).toHaveBeenCalledWith(payload); - await assertResponse(await request("POST", "/api/v1/unlock-key/verification", { ...payload, key: "fzk1.never-send-me" }), "POST", "/api/v1/unlock-key/verification", 400); - expect(create).toHaveBeenCalledTimes(1); - }); it("returns a documented JSON array for a read", async () => { vi.spyOn(ApiService.prototype, "listJobs").mockResolvedValue([]); expect( diff --git a/packages/api/test/credential-cutover.postgres.test.ts b/packages/api/test/credential-cutover.postgres.test.ts new file mode 100644 index 00000000..a46d8ba5 --- /dev/null +++ b/packages/api/test/credential-cutover.postgres.test.ts @@ -0,0 +1,37 @@ +import {describe,it,expect} from "vitest"; +import {readFile,readdir} from "node:fs/promises"; +import {execFile} from "node:child_process"; +import {promisify} from "node:util"; +import {Database} from "../src/postgres/database"; +import {encrypt,decrypt} from "../src/crypto"; +const url=process.env.AUTH_TEST_DATABASE_URL,exec=promisify(execFile); +describe.skipIf(!url)("breaking credential cutover",{timeout:60_000},()=>{ + it("gates existing data, plans without mutation, preserves managed records and disables jobs without changing selections",async()=>{ + const name="cutover_"+crypto.randomUUID().replaceAll("-",""),admin=new Database({connectionString:url}),address=new URL(url!);address.pathname="/"+name; + await admin.pool.query(`CREATE DATABASE ${name}`);const db=new Database({connectionString:address.href}); + try{ + const directory=new URL("../migrations/",import.meta.url),files=(await readdir(directory)).filter(f=>f.endsWith(".sql")).sort(); + for(const file of files.filter(f=>f<"0052"))await db.pool.query(await readFile(new URL(file,directory),"utf8")); + const tenant=crypto.randomUUID(),legacy=crypto.randomUUID(),managed=crypto.randomUUID(),job=crypto.randomUUID(),project=crypto.randomUUID(),key=btoa("a".repeat(32)); + await db.pool.query("INSERT INTO app.tenants(id) VALUES($1)",[tenant]);await db.pool.query("INSERT INTO app.integration_collections(tenant_id) VALUES($1)",[tenant]); + for(const [id,payload] of [[legacy,"unreadable-inner-user-ciphertext"],[managed,"factorize-managed-bearer-v1:managed-secret"]])await db.pool.query("INSERT INTO app.integration_records(tenant_id,id,kind,name,origin,revision,encrypted_payload) VALUES($1,$2,'bearer','Fixture','https://api.example.com',1,$3)",[tenant,id,await encrypt(payload,key)]); + await db.pool.query("INSERT INTO app.projects(tenant_id,id,name) VALUES($1,$2,'Fixture')",[tenant,project]); + const config={connectionId:"existing-exe",portableIntegrationIds:[legacy,managed],modelAccess:"native"}; + 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,$3,'Fixture','fixture','encrypted',$4,1)",[tenant,job,project,config]); + await db.pool.query("INSERT INTO app.connections(tenant_id,kind,encrypted_value) VALUES($1,'exe:existing-exe','unchanged')",[tenant]); + await db.pool.query("INSERT INTO app.credential_proxy_states(tenant_id,proxy_identity,boot_epoch) VALUES($1,'fly:old-proxy:machine',$2)",[tenant,crypto.randomUUID()]); + const migration=await readFile(new URL("0052_retire_credential_proxy.sql",directory),"utf8"); + await db.pool.query("BEGIN");await expect(db.pool.query(migration)).rejects.toThrow(/prepare-credential-cutover/);await db.pool.query("ROLLBACK"); + const run=async(apply=false)=>JSON.parse((await exec(process.execPath,[new URL("../scripts/prepare-credential-cutover.mjs",import.meta.url).pathname,...(apply?["--apply"]:[])],{env:{...process.env,DATABASE_URL:address.href,CREDENTIAL_ENCRYPTION_KEY:key}})).stdout); + const plan=await run();expect(plan.mode).toBe("plan");expect(plan.jobs[0]).toMatchObject({id:job,requiresRepair:true,enabled:true,portableIntegrationIds:[legacy,managed]});expect(JSON.stringify(plan)).not.toContain("managed-secret"); + expect((await db.pool.query("SELECT enabled FROM app.jobs WHERE tenant_id=$1 AND id=$2",[tenant,job])).rows[0].enabled).toBe(true); + const applied=await run(true);expect(applied.legacyCredentials).toEqual([{tenantId:tenant,id:legacy,kind:"bearer"}]); + expect((await db.pool.query("SELECT enabled,execution_config FROM app.jobs WHERE tenant_id=$1 AND id=$2",[tenant,job])).rows[0]).toEqual({enabled:false,execution_config:config}); + expect((await db.pool.query("SELECT encrypted_value FROM app.connections WHERE tenant_id=$1",[tenant])).rows[0].encrypted_value).toBe("unchanged"); + expect((await db.pool.query("SELECT encrypted_payload,deleted_at FROM app.integration_records WHERE tenant_id=$1 AND id=$2",[tenant,legacy])).rows[0]).toEqual({encrypted_payload:null,deleted_at:expect.any(Date)}); + const ciphertext=(await db.pool.query("SELECT encrypted_payload FROM app.integration_records WHERE tenant_id=$1 AND id=$2",[tenant,managed])).rows[0].encrypted_payload;expect(await decrypt(ciphertext,key)).toBe("factorize-managed-bearer-v1:managed-secret"); + await db.pool.query("BEGIN");await db.pool.query(migration);await db.pool.query("COMMIT"); + const retired=(await db.pool.query("SELECT to_regclass('app.run_credentials') AS tokens,to_regclass('app.credential_proxy_states') AS proxy,to_regclass('app.unlock_key_verifications') AS unlock")).rows[0];expect(retired).toEqual({tokens:null,proxy:null,unlock:null}); + }finally{await db.close();await admin.pool.query(`DROP DATABASE ${name} WITH (FORCE)`);await admin.close();} + }); +}); diff --git a/packages/api/test/docker-code-job.e2e.test.ts b/packages/api/test/docker-code-job.e2e.test.ts index 377f7028..4955c709 100644 --- a/packages/api/test/docker-code-job.e2e.test.ts +++ b/packages/api/test/docker-code-job.e2e.test.ts @@ -1,180 +1,131 @@ -import { expect, it, vi } from "vitest"; -import { execFileSync } from "node:child_process"; -import { generateKeyPairSync, randomUUID } from "node:crypto"; -import { readFile, readdir, mkdtemp, rm } from "node:fs/promises"; -import { tmpdir } from "node:os"; -import { join, resolve } from "node:path"; +import {expect,it,vi} from "vitest"; +import {execFileSync} from "node:child_process"; +import {generateKeyPairSync,randomUUID} from "node:crypto"; +import {readFile,readdir,mkdtemp,rm} from "node:fs/promises"; +import {tmpdir} from "node:os"; +import {join} from "node:path"; import worker from "../src/worker"; -import { Database } from "../src/postgres/database"; -import { IdentityRepository } from "../src/postgres/identity-repository"; -import { signSession } from "../src/session"; -import { createDockerExecutionHost } from "../src/docker-execution-host"; -import { createLocalExecutionRunner } from "../src/local-execution-runner"; -import { createLocalArtifactStorage } from "../src/local-execution-storage"; -import { startLocalApiServer } from "../src/local-api-server"; -import { createDockerJobInfrastructure } from "../src/docker-job-infrastructure"; -import type { Env } from "../src/types"; +import {Database} from "../src/postgres/database"; +import {IdentityRepository} from "../src/postgres/identity-repository"; +import {FlyConnectionRepository} from "../src/postgres/fly-connection-repository"; +import {signSession} from "../src/session"; +import {FlyJobExecutionBackend} from "../src/fly-job-execution-backend"; +import {createLocalExecutionRunner} from "../src/local-execution-runner"; +import {createLocalArtifactStorage} from "../src/local-execution-storage"; +import {startLocalApiServer} from "../src/local-api-server"; +import {createDockerJobInfrastructure} from "./helpers/docker-job-infrastructure"; +import type {Env} from "../src/types"; +vi.mock("cloudflare:workers",()=>({WorkerEntrypoint:class{},DurableObject:class{}})); +vi.mock("@cloudflare/workers-oauth-provider",()=>({OAuthProvider:class{},AuthorizationError:class{},getOAuthApi:()=>({})})); +const docker=(...args:string[])=>execFileSync("docker",args,{encoding:"utf8",timeout:30_000,maxBuffer:1024*1024}).trim(); +const wait=(ms:number)=>new Promise(r=>setTimeout(r,ms)); -// Node has no Cloudflare platform classes. No application/backend/scheduler method is mocked. -vi.mock("cloudflare:workers", () => ({ WorkerEntrypoint: class {}, DurableObject: class {} })); -vi.mock("@cloudflare/workers-oauth-provider", () => ({ OAuthProvider: class {}, AuthorizationError: class {}, getOAuthApi: () => ({}) })); - -const docker = (...args: string[]) => { - try { return execFileSync("docker", args, { timeout: 30_000, maxBuffer: 1024 * 1024, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }).trim(); } - catch { throw new Error(`Docker fixture ${args[0]} failed; command arguments and output withheld`); } -}; -const wait = (ms: number) => new Promise(resolve => setTimeout(resolve, ms)); -async function until(read: () => Promise, ready: (value: T) => boolean, label: string, ms = 15_000) { - const end = Date.now() + ms; - while (Date.now() < end) { const value = await read(); if (ready(value)) return value; await wait(100); } - throw new Error(`Deadline exceeded: ${label}`); -} - -it("runs saved code through the real API, encrypted grant, mTLS proxy and scheduler cleanup", async () => { - if (!process.env.AUTH_TEST_DATABASE_URL || !process.env.FACTORIZE_E2E_TLS_DIR) throw new Error("Run npm run test:docker after npm run bootstrap:test"); - const tlsDirectory = process.env.FACTORIZE_E2E_TLS_DIR; - const namespace = process.env.FACTORIZE_E2E_NAMESPACE ?? `fz-${randomUUID()}`; - const jobNetwork = `${namespace}-jobs`, upstreamNetwork = `${namespace}-api`; - const databaseName = process.env.FACTORIZE_E2E_DATABASE ?? `docker_e2e_${randomUUID().replaceAll("-", "")}`; - if (!/^docker_e2e_[a-f0-9]{32}$/.test(databaseName)) throw new Error("Invalid isolated E2E database name"); - const admin = new Database({ connectionString: process.env.AUTH_TEST_DATABASE_URL }); - const address = new URL(process.env.AUTH_TEST_DATABASE_URL); address.pathname = `/${databaseName}`; - const db = new Database({ connectionString: address.href }); - const storageDirectory = await mkdtemp(join(tmpdir(), "factorize-artifacts-")); - const ownerId = randomUUID(), userId = randomUUID(), marker = randomUUID(); - const upstreamSecret = `synthetic-${randomUUID()}`; - const jobImage = process.env.FACTORIZE_E2E_JOB_IMAGE!, proxyImage = process.env.FACTORIZE_E2E_PROXY_IMAGE!; - const keypair = generateKeyPairSync("ed25519"); - let api: Awaited> | undefined; - let runner: ReturnType | undefined; - let fakeId: string | undefined; - let createdDatabase = false; - try { - await admin.pool.query(`CREATE DATABASE ${databaseName}`); createdDatabase = true; - const migrations = new URL("../migrations/", import.meta.url); - for (const file of (await readdir(migrations)).filter(file => file.endsWith(".sql")).sort()) await db.pool.query(await readFile(new URL(file, migrations), "utf8")); - await new IdentityRepository(db, ownerId).upsertOwner(userId, "docker-owner@example.test"); - docker("network", "create", jobNetwork); - docker("network", "create", "--internal", upstreamNetwork); - fakeId = docker("run", "-d", "--network", upstreamNetwork, "--name", `${namespace}-fake`, - "--label", `sh.factorize.test.namespace=${namespace}`, - "--mount", `type=bind,source=${tlsDirectory},target=/fixture-tls,readonly`, - "--mount", `type=bind,source=${resolve("test/fixtures/docker-fake-api.mjs")},target=/fake-api.mjs,readonly`, - "-e", `EXPECTED_BEARER=${upstreamSecret}`, "-e", `MARKER=${marker}`, jobImage, "node", "/fake-api.mjs"); - const fakeInfo = JSON.parse(docker("inspect", fakeId))[0]; - const fakeAddress = fakeInfo.NetworkSettings.Networks[upstreamNetwork].IPAddress; - const readReceipts = () => JSON.parse(docker("exec", "-e", "NODE_EXTRA_CA_CERTS=/fixture-tls/ca.crt", fakeId!, "node", "-e", "fetch('https://localhost:8443/receipt',{signal:AbortSignal.timeout(3000)}).then(r=>r.text()).then(console.log)")); - const upstreamOrigin = "https://fake-api.local:8443"; - await until(async () => { try { return readReceipts(); } catch { return null; } }, v => v !== null, "fake API readiness"); - const env = { DATABASE: db, APP_ORIGIN: "", CREDENTIAL_ENCRYPTION_KEY: btoa("a".repeat(32)), SESSION_SIGNING_SECRET: `session-${randomUUID()}`, - MODEL_ACCOUNT_CAPABILITY_PRIVATE_KEY: keypair.privateKey.export({ type: "pkcs8", format: "pem" }).toString(), - MODEL_ACCOUNT_CAPABILITY_PUBLIC_KEY: keypair.publicKey.export({ type: "spki", format: "pem" }).toString(), - TEST_DOCKER_EXECUTION: { enabled: true, image: jobImage }, RUN_ARTIFACTS: createLocalArtifactStorage(storageDirectory), - } as unknown as Env; - api = await startLocalApiServer({ key: await readFile(join(tlsDirectory, "server.key")), cert: await readFile(join(tlsDirectory, "server.crt")), - fetch: request => worker.fetch(request, env, { waitUntil() {} } as any) }); - env.APP_ORIGIN = `https://${process.env.FACTORIZE_E2E_HOST_IP ?? "172.17.0.1"}:${api.port}`; - const jobInputs: string[] = []; - let destructionEvidence: { marker: string; storedLog: boolean } | undefined; - const host = createDockerExecutionHost({ observeJobDestruction: async id => { - const result = await db.pool.query(`SELECT r.job_result, EXISTS(SELECT 1 FROM app.run_artifacts a WHERE a.tenant_id=r.tenant_id AND a.run_id=r.id AND a.kind='terminal_log' AND a.state='stored') AS stored_log - FROM app.runs r WHERE tenant_id=$1 AND execution_handle->>'id'=$2`, [ownerId, `${namespace}-jobs/${id}`]); - destructionEvidence = { marker: result.rows[0]?.job_result?.outputs?.marker, storedLog: result.rows[0]?.stored_log }; - }, observeJobInput: (_command, input) => { if (input) jobInputs.push(typeof input === "string" ? input : new TextDecoder().decode(input)); }, testMode: true, database: db, env, namespace, jobNetwork, upstreamNetwork, jobImage, proxyImage, tlsDirectory, upstreamOrigin, upstreamAddress: fakeAddress }); - env.CREDENTIAL_PROXY_HOST = host; - const member = await new IdentityRepository(db, ownerId).member(userId); - const cookie = `factorize_session=${await signSession({ tenantId: ownerId, userId, email: "docker-owner@example.test", sessionVersion: member!.sessionVersion, exp: Math.floor(Date.now()/1000)+600 }, env.SESSION_SIGNING_SECRET)}`; - const request = (path: string, method = "GET", body?: unknown) => fetch(env.APP_ORIGIN + "/api/v1" + path, { method, headers: { Cookie: cookie, Origin: env.APP_ORIGIN, "Content-Type": "application/json" }, ...(body === undefined ? {} : { body: JSON.stringify(body) }), signal: AbortSignal.timeout(20_000) }); - const json = async (path: string, method = "GET", body?: unknown) => { const response = await request(path, method, body); const value = await response.json(); if (!response.ok) throw new Error(`API ${method} ${path}: ${response.status} ${JSON.stringify(value)}`); return value as any; }; - const project = await json("/projects", "POST", { name: "Docker test" }); - const integrationId = randomUUID(), generationId = randomUUID(); - const keyBytes = crypto.getRandomValues(new Uint8Array(32)), unlockKey = `fzk1.${Buffer.from(keyBytes).toString("base64url")}`; - const material = await crypto.subtle.importKey("raw", keyBytes, "HKDF", false, ["deriveKey"]); - const aes = await crypto.subtle.deriveKey({ name: "HKDF", hash: "SHA-256", salt: new TextEncoder().encode("factorize.unlock-key.v1"), info: new TextEncoder().encode("factorize.record.aes-256-gcm.v1") }, material, { name: "AES-GCM", length: 256 }, false, ["encrypt"]); - async function encrypt(plain: string, id: string, kind: string, destination: string, revision: number) { - const nonce = crypto.getRandomValues(new Uint8Array(12)); - const ciphertext = new Uint8Array(await crypto.subtle.encrypt({ name: "AES-GCM", iv: nonce, additionalData: new TextEncoder().encode(JSON.stringify(["factorize-record-v1", userId, id, kind, destination, revision])) }, aes, new TextEncoder().encode(plain))); - return { nonce, ciphertext }; - } - const verification = await encrypt("factorize-unlock-key-verification-v1", generationId, "unlock-verification", "factorize", 0); - await json("/unlock-key/verification", "POST", { generationId, encryptedVerification: JSON.stringify({ version: 1, algorithm: "A256GCM", nonce: Buffer.from(verification.nonce).toString("base64url"), ciphertext: Buffer.from(verification.ciphertext).toString("base64url") }) }); - expect((await json("/unlock-key/verification")).verification.generationId).toBe(generationId); - await json("/integrations/bearer", "POST", { id: integrationId, expectedRevision: 0, idempotencyKey: randomUUID(), name: "Fake API", origin: upstreamOrigin, description: null, token: upstreamSecret }); - const script = `#!/bin/bash\nset -eu\nnode --input-type=module <<'JS'\nimport fs from 'node:fs';\nimport net from 'node:net';\nconst marker=${JSON.stringify(marker)};\nconst direct=await new Promise(resolve=>{const s=net.connect({host:${JSON.stringify(fakeAddress)},port:8443}); s.setTimeout(1000,()=>{s.destroy();resolve(false)});s.once('connect',()=>{s.destroy();resolve(true)});s.once('error',()=>resolve(false))});\nif(direct)throw new Error('network isolation failed');\nconst base=process.env.FACTORIZE_PROXY_URL;\nconst list=await (await fetch(base+'/integrations',{signal:AbortSignal.timeout(10000)})).json();\nconst integration=list.integrations.find(x=>x.id===${JSON.stringify(integrationId)});\nif(!integration)throw new Error('grant missing');\nconst r=await fetch(base+integration.endpoint+'echo/'+marker,{method:'POST',body:marker,signal:AbortSignal.timeout(10000)});\nif(!r.ok||(await r.json()).marker!==marker)throw new Error('response mismatch');\nconsole.log('executed:'+marker);\nfs.writeFileSync('/home/exedev/.factorize-job/evidence.txt',marker);\nawait new Promise(r=>setTimeout(r,1500));\nfs.writeFileSync(process.env.FACTORIZE_RESULT_PATH,JSON.stringify({status:'succeeded',outputs:{marker,directBlocked:true}}));\nJS\n`; - const jobInput = { name: "Docker code", slug: "docker-code", projectId: project.id, executionType: "code", script, executionConfigId: "docker", triggers: [{ kind: "manual", slug: "trigger-1", config: {} }] }; - const enabled = env.TEST_DOCKER_EXECUTION; - delete env.TEST_DOCKER_EXECUTION; - expect((await request("/jobs", "POST", jobInput)).status).toBe(400); - env.TEST_DOCKER_EXECUTION = enabled; - expect((await request("/credential-proxy/browser-capability", "POST", { action: "unlock", key: unlockKey })).status).toBe(400); - const job = await json("/jobs", "POST", jobInput); - await json(`/jobs/${job.id}`, "PUT", { ...jobInput, portableIntegrationIds: [integrationId] }); - const ungrantedId = randomUUID(); - await json("/integrations/bearer", "POST", { id: ungrantedId, expectedRevision: 1, idempotencyKey: randomUUID(), name: "Ungranted", origin: upstreamOrigin, description: null, token: upstreamSecret }); - const setup = await json("/credential-proxy/setup", "POST", { operationId: randomUUID() }); - expect(setup.proxyIdentity.startsWith(`docker:${namespace}:`)).toBe(true); - const lifecycle = async (action: string, body: unknown = {}) => { const c = await json("/credential-proxy/browser-capability", "POST", { action }); return fetch(c.endpoint, { method: "POST", headers: { Authorization: `Bearer ${c.capability}`, Origin: env.APP_ORIGIN, "Content-Type": "application/json" }, body: JSON.stringify(body), signal: AbortSignal.timeout(15_000) }); }; - expect((await lifecycle("status")).status).toBe(200); - expect((await lifecycle("unlock", { key: unlockKey })).status).toBe(200); - expect((await lifecycle("apply")).status).toBe(200); - const invoked = await json(`/jobs/${job.id}/invocations`, "POST", {}); - const runId = invoked.run?.id ?? invoked.runId ?? invoked.id; - expect(typeof runId).toBe("string"); - runner = createLocalExecutionRunner(db, env, host.backendFactory); +// Signed provider fixtures exercise the production verifier, helper, backend and +// scheduler. They are test-local, and do not constitute live Fly verification. +it("runs saved code through vendor identity, selected backend egress, artifacts and cleanup",async()=>{ + const url=process.env.AUTH_TEST_DATABASE_URL!,tls=process.env.FACTORIZE_E2E_TLS_DIR!,namespace=process.env.FACTORIZE_E2E_NAMESPACE!; + if(!url||!tls||!namespace)throw new Error("Use npm run test:docker"); + const databaseName=process.env.FACTORIZE_E2E_DATABASE!; + if(!/^docker_e2e_[a-f0-9]{32}$/.test(databaseName))throw new Error("Invalid isolated database"); + const admin=new Database({connectionString:url}),address=new URL(url);address.pathname="/"+databaseName; + const db=new Database({connectionString:address.href}),storage=await mkdtemp(join(tmpdir(),"factorize-artifacts-")); + const tenantId=randomUUID(),userId=randomUUID(),marker=randomUUID(),secret="synthetic-"+randomUUID(),integrationId=randomUUID(),unselectedId=randomUUID(); + const app=namespace+"-jobs",org="factorize-fixture",issuer="https://oidc.fly.io/"+org,network=namespace+"-jobs"; + const pair=generateKeyPairSync("rsa",{modulusLength:2048}),jwk={...pair.publicKey.export({format:"jwk"}),kid:"docker-fixture",alg:"RS256",use:"sig"}; + const originalFetch=globalThis.fetch,receipts:unknown[]=[]; + let created=false,api:Awaited>|undefined,runner:ReturnType|undefined; + let destructionEvidence:unknown; + try{ + await admin.pool.query(`CREATE DATABASE ${databaseName}`);created=true; + const migrations=new URL("../migrations/",import.meta.url); + for(const file of(await readdir(migrations)).filter(f=>f.endsWith(".sql")).sort())await db.pool.query(await readFile(new URL(file,migrations),"utf8")); + await new IdentityRepository(db,tenantId).upsertOwner(userId,"docker-owner@example.test"); + docker("network","create",network); + const env={DATABASE:db,APP_ORIGIN:"",CREDENTIAL_ENCRYPTION_KEY:btoa("a".repeat(32)),SESSION_SIGNING_SECRET:randomUUID(),TEST_DOCKER_EXECUTION:{enabled:true,image:process.env.FACTORIZE_E2E_JOB_IMAGE!},RUN_ARTIFACTS:createLocalArtifactStorage(storage)} as Env; + await new FlyConnectionRepository(db,tenantId,env.CREDENTIAL_ENCRYPTION_KEY).save({organizationSlug:org,organizationName:"Fixture"},"fixture-control-token"); + vi.stubGlobal("fetch",async(input:RequestInfo|URL,init?:RequestInit)=>{ + const target=String(input instanceof Request?input.url:input); + if(target===issuer+"/.well-known/openid-configuration")return Response.json({issuer,jwks_uri:issuer+"/jwks"}); + if(target===issuer+"/jwks")return Response.json({keys:[jwk]}); + if(target.startsWith("https://fixture-upstream.example.com/")){ + const headers=new Headers(init?.headers); + expect(headers.get("Authorization")).toBe("Bearer "+secret); + expect(headers.has("X-Factorize-Run-Id")).toBe(false); + const body=await new Response(init?.body).text();receipts.push({path:new URL(target).pathname,body}); + return Response.json({marker}); + } + return originalFetch(input,init); + }); + api=await startLocalApiServer({key:await readFile(join(tls,"server.key")),cert:await readFile(join(tls,"server.crt")),fetch:request=>worker.fetch(request,env,{waitUntil(){}} as any)}); + env.APP_ORIGIN=`https://${process.env.FACTORIZE_E2E_HOST_IP}:${api.port}`; + const member=await new IdentityRepository(db,tenantId).member(userId); + const cookie="factorize_session="+await signSession({tenantId,userId,email:"docker-owner@example.test",sessionVersion:member!.sessionVersion,exp:Math.floor(Date.now()/1000)+600},env.SESSION_SIGNING_SECRET); + const request=(path:string,method="GET",body?:unknown)=>originalFetch(env.APP_ORIGIN+"/api/v1"+path,{method,headers:{Cookie:cookie,Origin:env.APP_ORIGIN,"Content-Type":"application/json"},...(body===undefined?{}:{body:JSON.stringify(body)})}); + const json=async(path:string,method="GET",body?:unknown)=>{const r=await request(path,method,body),v=await r.json() as any;if(!r.ok)throw new Error(`${method} ${path}: ${r.status} ${JSON.stringify(v)}`);return v;}; + const project=await json("/projects","POST",{name:"Docker vendor test"}); + for(const [index,id] of[integrationId,unselectedId].entries())await json("/integrations/bearer","POST",{id,expectedRevision:index,idempotencyKey:randomUUID(),name:"Fixture "+index,origin:"https://fixture-upstream.example.com",description:null,token:secret}); + const script=`#!/bin/bash +set -eu +node --input-type=module <<'JS' +import fs from 'node:fs'; +const base=process.env.FACTORIZE_PROXY_URL; +const list=await(await fetch(base+'/integrations')).json(); +if(list.integrations.length!==1||list.integrations[0].id!==${JSON.stringify(integrationId)})throw new Error('selection mismatch'); +const r=await fetch(base+'/integrations/${integrationId}/echo/${marker}',{method:'POST',body:${JSON.stringify(marker)}}); +if(!r.ok||(await r.json()).marker!==${JSON.stringify(marker)})throw new Error('egress failed'); +console.log('executed:${marker}'); +while(!fs.existsSync('/tmp/finish-test'))await new Promise(r=>setTimeout(r,100)); +fs.writeFileSync(process.env.FACTORIZE_RESULT_PATH,JSON.stringify({status:'succeeded',outputs:{marker:${JSON.stringify(marker)}}})); +JS +`; + const job=await json("/jobs","POST",{name:"Docker code",slug:"docker-code",projectId:project.id,executionType:"code",script,executionConfigId:"docker",portableIntegrationIds:[integrationId],triggers:[{kind:"manual",slug:"trigger-1",config:{}}]}); + const invoked=await json(`/jobs/${job.id}/invocations`,"POST",{}),runId=invoked.runId; + const infrastructure=createDockerJobInfrastructure({testMode:true,namespace:app,network,beforeDestroy:async id=>{ + const r=(await db.pool.query("SELECT job_result,artifact_state FROM app.runs WHERE tenant_id=$1 AND id=$2",[tenantId,runId])).rows[0];destructionEvidence={marker:r.job_result?.outputs?.marker,artifactState:r.artifact_state}; + }}); + const guests=new Map>(); + const guest=(id:string)=>{ + let saved=guests.get(id);if(saved)return saved; + const raw=infrastructure.guest(id);let initialized:Promise|undefined; + const prepare=()=>initialized??=(async()=>{ + await raw.upload!("/tmp/fixture-ca.crt",new Uint8Array(await readFile(join(tls,"ca.crt")))); + // This signing key exists only inside this isolated fixture. Production + // trusts Fly's JWKS; it cannot accept this test issuer key. + const source=`const http=require('node:http'),crypto=require('node:crypto');const key=${JSON.stringify(pair.privateKey.export({type:"pkcs8",format:"pem"}).toString())};require('node:fs').mkdirSync('/.fly',{recursive:true});http.createServer((req,res)=>{let body='';req.on('data',c=>body+=c);req.on('end',()=>{const now=Math.floor(Date.now()/1000),h=Buffer.from(JSON.stringify({alg:'RS256',kid:'docker-fixture'})).toString('base64url'),p=Buffer.from(JSON.stringify({iss:${JSON.stringify(issuer)},sub:${JSON.stringify(org+":"+app+":"+app+"-"+runId)},aud:JSON.parse(body).aud,machine_id:${JSON.stringify(id)},iat:now,exp:now+120})).toString('base64url'),data=h+'.'+p;res.end(data+'.'+crypto.sign('RSA-SHA256',Buffer.from(data),key).toString('base64url'));});}).listen('/.fly/api');`; + await raw.upload!("/tmp/vendor-fixture.cjs",new TextEncoder().encode(source)); + const started=await raw.run(["sh","-c","nohup node /tmp/vendor-fixture.cjs >/tmp/vendor-fixture.log 2>&1 {await prepare();return raw.run(["env","NODE_EXTRA_CA_CERTS=/tmp/fixture-ca.crt",...command],input);}};guests.set(id,saved);return saved; + }; + const backend=new FlyJobExecutionBackend({app,organizationSlug:org,image:process.env.FACTORIZE_E2E_JOB_IMAGE!,region:"iad",size:"shared-cpu-1x",machines:infrastructure.machines,guest:machine=>guest(machine.id)}); + runner=createLocalExecutionRunner(db,env,async()=>backend); await runner.tick(); - const row = (await db.pool.query("SELECT execution_handle,execution_diagnostics FROM app.runs WHERE tenant_id=$1 AND id=$2", [ownerId, runId])).rows[0]; - if (row.execution_diagnostics?.state === "failed") throw new Error(row.execution_diagnostics.detail); - expect(row.execution_handle.backendKind).toBe("docker"); - const containerId = row.execution_handle.id.split("/")[1]; - const containerConfig = docker("inspect", containerId); - const inspected = JSON.parse(containerConfig)[0]; - expect(inspected.Config.Image).toBe(jobImage); - expect(inspected.Mounts).toEqual([]); - expect(inspected.HostConfig.Privileged).toBe(false); - expect(inspected.Config.Labels["sh.factorize.test.operation"]).toBe(runId); - expect(containerConfig.includes(upstreamSecret)).toBe(false); - expect(/fzt_run_|fzc_/.test(containerConfig)).toBe(false); - const guest = createDockerJobInfrastructure({ testMode: true, namespace: `${namespace}-jobs`, network: jobNetwork }).guest(containerId); - const surfaces = await guest.run(["sh", "-c", "find /home/exedev/.factorize-job -type f -exec cat {} \\; ; cat /tmp/factorize.log /tmp/factorize.stderr 2>/dev/null || true; for environment in /proc/[0-9]*/environ; do cat \"$environment\" 2>/dev/null || true; done"]); - expect(surfaces.stdout.includes(upstreamSecret)).toBe(false); - expect(/fzt_run_|fzc_/.test(surfaces.stdout)).toBe(false); - expect(jobInputs.some(input => input.includes('"code"'))).toBe(true); - for (const input of jobInputs) { expect(input.includes(upstreamSecret)).toBe(false); expect(/fzt_run_|fzc_/.test(input)).toBe(false); } - await until(async () => (await guest.run(["test", "-s", "/home/exedev/.factorize-job/results.json"])).ok, - ready => ready, "saved code finishes its correlated request", 20_000); - // The same real run/tunnel must deny access to a saved but ungranted integration. - const denied = await guest.run(["runuser", "-u", "exedev", "--", "node", "-e", `fetch('http://127.0.0.1:18180/integrations/${ungrantedId}/echo/${marker}',{method:'POST',body:'${marker}',signal:AbortSignal.timeout(3000)}).then(r=>console.log(r.status))`]); - expect(denied.stdout.trim()).toBe("403"); - const beforeLock = readReceipts().length; - expect((await lifecycle("lock")).status).toBe(200); - const locked = await guest.run(["runuser", "-u", "exedev", "--", "node", "-e", `fetch('http://127.0.0.1:18180/integrations/${integrationId}/echo/${marker}',{method:'POST',body:'${marker}',signal:AbortSignal.timeout(1200)}).then(r=>console.log(r.status)).catch(()=>console.log('denied'))`]); - expect(["423", "denied"]).toContain(locked.stdout.trim()); - expect(readReceipts().length).toBe(beforeLock); - expect((await lifecycle("unlock", { key: unlockKey })).status).toBe(200); - await until(async () => { await runner!.tick(); return (await db.pool.query("SELECT state,artifact_state,failure_code,failure_reason FROM app.runs WHERE tenant_id=$1 AND id=$2", [ownerId, runId])).rows[0]; }, row => ["succeeded", "failed", "stopped"].includes(row.state), "normal scheduler finalization", 60_000).then(row => { if (row.state !== "succeeded" || row.artifact_state !== "stored") throw new Error(`Finalization: ${JSON.stringify(row)}`); }); - expect(destructionEvidence).toEqual({ marker, storedLog: true }); - expect(docker("ps", "-aq", "--filter", `id=${containerId}`)).toBe(""); - const receipt = readReceipts(); - expect(receipt).toEqual([{ credentialMatched: true, method: "POST", path: `/echo/${marker}`, body: marker }]); - const artifacts = (await db.pool.query("SELECT kind,object_key FROM app.run_artifacts WHERE tenant_id=$1 AND run_id=$2", [ownerId, runId])).rows; - expect(artifacts.some(row => row.kind === "terminal_log")).toBe(true); - const log = await env.RUN_ARTIFACTS!.get(artifacts.find(row => row.kind === "terminal_log").object_key); - expect((await log!.text()).includes(`executed:${marker}`)).toBe(true); - const persistedResult = (await db.pool.query("SELECT job_result FROM app.runs WHERE tenant_id=$1 AND id=$2", [ownerId, runId])).rows[0]; - expect(persistedResult.job_result).toMatchObject({ status: "succeeded", outputs: { marker, directBlocked: true } }); - for (const artifact of artifacts) { - const stored = await env.RUN_ARTIFACTS!.get(artifact.object_key); - const text = await stored!.text(); - expect(text.includes(upstreamSecret)).toBe(false); - expect(/fzt_run_|fzc_/.test(text)).toBe(false); - } - } finally { - await runner?.close(); await api?.close(); - const containers = docker("ps", "-aq", "--filter", `label=sh.factorize.test.namespace=${namespace}`).split("\n").filter(Boolean); - const jobs = docker("ps", "-aq", "--filter", `label=sh.factorize.test.namespace=${namespace}-jobs`).split("\n").filter(Boolean); - for (const id of [...containers, ...jobs]) docker("rm", "-f", id); - for (const network of [jobNetwork, upstreamNetwork]) { try { docker("network", "rm", network); } catch {} } - await db.close(); if (createdDatabase) await admin.pool.query(`DROP DATABASE ${databaseName} WITH (FORCE)`); await admin.close(); - await rm(storageDirectory, { recursive: true, force: true }); + const row=(await db.pool.query("SELECT execution_handle,execution_diagnostics FROM app.runs WHERE tenant_id=$1 AND id=$2",[tenantId,runId])).rows[0]; + expect(row.execution_diagnostics?.state,JSON.stringify(row.execution_diagnostics)).not.toBe("failed"); + expect(row.execution_handle.backendKind).toBe("fly"); + const id=row.execution_handle.id.split("/")[1],raw=infrastructure.guest(id); + const deadline=Date.now()+15_000;while(receipts.length===0&&Date.now()(await raw.run(["runuser","-u","exedev","--","node","-e",`fetch('http://127.0.0.1:18180${path}').then(r=>console.log(r.status))`])).stdout.trim(); + expect(await probe(`/integrations/${unselectedId}/echo/no`)).toBe("403"); + expect(await probe("/api/v1/jobs")).toBe("200"); + await json(`/integrations/bearer/${integrationId}`,"DELETE",{expectedRevision:2,idempotencyKey:randomUUID()}); + expect(await probe(`/integrations/${integrationId}/echo/no`)).toBe("403"); + expect(receipts).toHaveLength(1); + const surfaces=await raw.run(["sh","-c","cat /run/factorize-identity/config.json; cat /home/exedev/.factorize-job/launch.json 2>/dev/null || true"]); + expect(surfaces.stdout).not.toContain(secret);expect(surfaces.stdout).not.toMatch(/fzt_run_|fzc_/); + await raw.run(["touch","/tmp/finish-test"]); + let terminal:any; + const end=Date.now()+60_000;while(Date.now() { const namespace = process.env.FACTORIZE_E2E_NAMESPACE ? `${process.env.FACTORIZE_E2E_NAMESPACE}-infra` : `factorize-test-${randomUUID()}`; diff --git a/packages/api/test/encrypted-integration-api.postgres.test.ts b/packages/api/test/encrypted-integration-api.postgres.test.ts index f5138cbe..da86455c 100644 --- a/packages/api/test/encrypted-integration-api.postgres.test.ts +++ b/packages/api/test/encrypted-integration-api.postgres.test.ts @@ -2,8 +2,7 @@ import { describe, expect, it, vi } from "vitest"; import worker from "../src/worker"; import { protectedApiFetch } from "../src/protected-api"; import { IdentityRepository } from "../src/postgres/identity-repository"; -import { RunEnrollmentRepository } from "../src/postgres/run-enrollment-repository"; -import { EncryptedIntegrationRepository } from "../src/postgres/encrypted-integration-repository"; +import { CredentialRepository } from "../src/postgres/credential-repository"; import { signSession } from "../src/session"; import { loadingFixture } from "./helpers/loading-fixture"; @@ -11,124 +10,15 @@ vi.mock("cloudflare:workers", () => ({ WorkerEntrypoint: class {}, DurableObject vi.mock("@cloudflare/workers-oauth-provider", () => ({ OAuthProvider: class {}, AuthorizationError: class extends Error {}, getOAuthApi: vi.fn() })); const databaseUrl = process.env.AUTH_TEST_DATABASE_URL; -async function userEncrypt(plaintext: string): Promise { - const iv = crypto.getRandomValues(new Uint8Array(12)); - const key = await crypto.subtle.importKey("raw", Uint8Array.from(atob(btoa("u".repeat(32))), c => c.charCodeAt(0)), "AES-GCM", false, ["encrypt"]); - const body = await crypto.subtle.encrypt({ name: "AES-GCM", iv }, key, new TextEncoder().encode(plaintext)); - const encode = (bytes: Uint8Array) => btoa(Array.from(bytes, byte => String.fromCharCode(byte)).join("")); - return `${encode(iv)}.${encode(new Uint8Array(body))}`; -} - describe.skipIf(!databaseUrl)("owner-only managed credential API (PostgreSQL)", { timeout: 60_000 }, () => { - it("keeps Docker test selection and proxy setup behind explicit environment and owner boundaries", async () => { - const f = await loadingFixture(databaseUrl!); - try { - const request = (path: string, body: unknown, cookie = f.cookie) => worker.fetch(new Request(f.env.APP_ORIGIN + "/api/v1" + path, { - method: "POST", headers: { Cookie: cookie, Origin: f.env.APP_ORIGIN, "Content-Type": "application/json" }, body: JSON.stringify(body), - }), f.env, { waitUntil() {} } as any); - const body = { name: "Docker", slug: "docker-test", executionType: "code", script: "echo test", executionConfigId: "docker", triggers: [] }; - expect((await request("/jobs", body)).status).toBe(400); - f.env.TEST_DOCKER_EXECUTION = { enabled: true, image: "sha256:" + "a".repeat(64) }; - expect((await request("/jobs", body)).status).toBe(201); - expect((await request("/jobs", { ...body, slug: "agent-test", executionType: "agent", promptTemplate: "test" })).status).toBe(400); - const setup = vi.fn(async () => ({ proxyIdentity: "fixture", bootEpoch: crypto.randomUUID() })); - f.env.CREDENTIAL_PROXY_HOST = { setup }; - expect((await request("/credential-proxy/setup", { operationId: crypto.randomUUID() }, "invalid")).status).toBe(401); - expect(setup).not.toHaveBeenCalled(); - const agent = await protectedApiFetch(new Request(f.env.APP_ORIGIN + "/api/v1/credential-proxy/setup", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ operationId: crypto.randomUUID() }) }), f.env, { ...f.auth, scopes: ["integrations:write"], authMethod: "access_token" }, {} as any); - expect(agent.status).toBe(403); expect(setup).not.toHaveBeenCalled(); - const operationId = crypto.randomUUID(); - expect((await request("/credential-proxy/setup", { operationId })).status).toBe(200); - expect(setup).toHaveBeenCalledWith(f.tenantId, operationId); - expect((await request("/credential-proxy/browser-capability", { action: "unlock", key: "must-not-be-accepted" })).status).toBe(400); - } finally { await f.cleanup(); } - }); - it("stores one ciphertext-only unlock verification per owner and never accepts a plaintext key", async () => { + it("does not expose retired proxy or unlock operations", async () => { const f = await loadingFixture(databaseUrl!); try { - const request = (method = "GET", body?: unknown, cookie = f.cookie) => worker.fetch(new Request(f.env.APP_ORIGIN + "/api/v1/unlock-key/verification", { - method, headers: { Cookie: cookie, Origin: f.env.APP_ORIGIN, "Content-Type": "application/json" }, ...(body === undefined ? {} : { body: JSON.stringify(body) }), - }), f.env, { waitUntil() {} } as any); - expect(await (await request()).json()).toEqual({ ownerId: f.userId, verification: null }); - const generationId = crypto.randomUUID(); - const encryptedVerification = JSON.stringify({ version: 1, algorithm: "A256GCM", nonce: "AAAAAAAAAAAAAAAA", ciphertext: "AAAAAAAAAAAAAAAAAAAAAA" }); - const body = { generationId, encryptedVerification }; - expect((await request("POST", body)).status).toBe(200); - expect(await (await request()).json()).toEqual({ ownerId: f.userId, verification: body }); - const stored = await f.db.pool.query("SELECT generation_id,encrypted_verification FROM app.unlock_key_verifications WHERE tenant_id=$1", [f.tenantId]); - expect(stored.rows).toEqual([{ generation_id: generationId, encrypted_verification: encryptedVerification }]); - expect(JSON.stringify(stored.rows)).not.toContain("fzk1."); - expect((await request("POST", body)).status).toBe(409); - expect((await request("POST", { ...body, unlockKey: "fzk1.must-not-be-accepted" })).status).toBe(400); - } finally { await f.cleanup(); } - }); - it("owner-only key replacement atomically resets encrypted records, changes verification, and locks the proxy", async () => { - const f = await loadingFixture(databaseUrl!); - try { - const request = (path: string, method = "GET", body?: unknown, cookie = f.cookie) => worker.fetch(new Request(f.env.APP_ORIGIN + "/api/v1" + path, { - method, headers: { Cookie: cookie, Origin: f.env.APP_ORIGIN, "Content-Type": "application/json" }, ...(body === undefined ? {} : { body: JSON.stringify(body) }), - }), f.env, { waitUntil() {} } as any); - const oldGeneration = crypto.randomUUID(), newGeneration = crypto.randomUUID(); - const verification = (generationId: string) => JSON.stringify({ version: 1, algorithm: "A256GCM", nonce: "AAAAAAAAAAAAAAAA", ciphertext: "AAAAAAAAAAAAAAAAAAAAAA" }); - expect((await request("/unlock-key/verification", "POST", { generationId: oldGeneration, encryptedVerification: verification(oldGeneration) })).status).toBe(200); - const encrypted = await userEncrypt("synthetic bearer payload"); - const integrationId = crypto.randomUUID(); - await new EncryptedIntegrationRepository(f.db, f.tenantId, f.env.CREDENTIAL_ENCRYPTION_KEY).write({ id: integrationId, kind: "bearer", name: "Synthetic", origin: "https://api.example.test", description: null, expectedRevision: 0, idempotencyKey: crypto.randomUUID(), operation: "upsert", encryptedPayload: encrypted }); - await f.db.pool.query("INSERT INTO app.connections(tenant_id,kind,encrypted_value) VALUES($1,'fly:connection-fixture','encrypted-fly-fixture')", [f.tenantId]); - await f.db.pool.query("UPDATE app.jobs SET execution_config=$3 WHERE tenant_id=$1 AND id=$2", [f.tenantId, f.jobIds[0], { provider: "fly", connectionId: "fly:connection-fixture", region: "ord", vmSize: "shared-cpu-1x" }]); - const flyConnectionBefore = (await f.db.pool.query("SELECT kind,encrypted_value FROM app.connections WHERE tenant_id=$1 ORDER BY kind", [f.tenantId])).rows; - const executionConfigBefore = (await f.db.pool.query("SELECT id,execution_config FROM app.jobs WHERE tenant_id=$1 ORDER BY id", [f.tenantId])).rows; - await f.db.pool.query("INSERT INTO app.credential_proxy_states(tenant_id,proxy_identity,boot_epoch,unlocked) VALUES($1,'proxy-test',$2,true)", [f.tenantId, crypto.randomUUID()]); - const runId = crypto.randomUUID(), jobId = f.jobIds[0], invocationId = crypto.randomUUID(); - const triggerId = (await f.db.pool.query("SELECT id FROM app.triggers WHERE tenant_id=$1 AND job_id=$2 AND kind='manual' LIMIT 1", [f.tenantId, jobId])).rows[0].id; - await f.db.pool.query("INSERT INTO app.invocations(tenant_id,id,job_id,source,claim_key,trigger_id,context) VALUES ($1,$2,$3,'manual','rotation-test',$4,'{}')", [f.tenantId, invocationId, jobId, triggerId]); - await f.db.pool.query("INSERT INTO app.job_runs(tenant_id,id,job_id,invocation_id,state,encrypted_prompt) VALUES ($1,$2,$3,$4,'running','test')", [f.tenantId, runId, jobId, invocationId]); - const enrollmentRepository = new RunEnrollmentRepository(f.db); - const binding = { tenantId: f.tenantId, runId, vmIdentity: "vm-rotation", proxyIdentity: "proxy-test", bootEpoch: (await f.db.pool.query("SELECT boot_epoch FROM app.credential_proxy_states WHERE tenant_id=$1", [f.tenantId])).rows[0].boot_epoch }; - expect(await enrollmentRepository.authorizeRun(binding)).toBe(1); - const issued = await enrollmentRepository.issue(binding, new Date(Date.now() + 60_000)); - expect(issued).not.toBeNull(); - - const snapshot = await request("/unlock-key/rotation-snapshot"); - expect(snapshot.status).toBe(200); - expect(await snapshot.json()).toMatchObject({ ownerId: f.userId, generationId: oldGeneration, revision: 1, records: [{ id: integrationId, kind: "bearer", encryptedPayload: encrypted }] }); - const replacement = await request("/unlock-key/rotation", "POST", { - expectedGenerationId: oldGeneration, generationId: newGeneration, expectedRevision: 1, - encryptedVerification: verification(newGeneration), records: [], changes: [], - }); - expect(replacement.status).toBe(200); - expect(await replacement.json()).toEqual({ generationId: newGeneration, revision: 2, duplicate: false }); - expect((await f.db.pool.query("SELECT generation_id FROM app.unlock_key_verifications WHERE tenant_id=$1", [f.tenantId])).rows[0].generation_id).toBe(newGeneration); - expect((await f.db.pool.query("SELECT id FROM app.integration_records WHERE tenant_id=$1", [f.tenantId])).rows).toEqual([]); - expect((await f.db.pool.query("SELECT unlocked FROM app.credential_proxy_states WHERE tenant_id=$1", [f.tenantId])).rows[0].unlocked).toBe(false); - expect((await f.db.pool.query("SELECT kind,encrypted_value FROM app.connections WHERE tenant_id=$1 ORDER BY kind", [f.tenantId])).rows).toEqual(flyConnectionBefore); - expect((await f.db.pool.query("SELECT id,execution_config FROM app.jobs WHERE tenant_id=$1 ORDER BY id", [f.tenantId])).rows).toEqual(executionConfigBefore); - expect((await f.db.pool.query("SELECT revoked_at FROM app.credential_run_grants WHERE tenant_id=$1 AND run_id=$2", [f.tenantId, runId])).rows[0].revoked_at).toBeInstanceOf(Date); - expect((await f.db.pool.query("SELECT consumed_at FROM app.credential_run_enrollments WHERE tenant_id=$1 AND run_id=$2", [f.tenantId, runId])).rows[0].consumed_at).toBeInstanceOf(Date); - expect(await enrollmentRepository.consume(issued!.token, binding)).toBeNull(); - const rotatedCipher = await userEncrypt("rotated synthetic bearer payload"), rotatedId = crypto.randomUUID(); - const integrationRepository = new EncryptedIntegrationRepository(f.db, f.tenantId, f.env.CREDENTIAL_ENCRYPTION_KEY); - await integrationRepository.write({ id: rotatedId, kind: "bearer", expectedRevision: 2, idempotencyKey: crypto.randomUUID(), name: "Rotated", origin: "https://api.example.test", description: null, operation: "upsert", encryptedPayload: encrypted }); - const modelId = crypto.randomUUID(); - await integrationRepository.write({ id: modelId, kind: "model", expectedRevision: 3, idempotencyKey: crypto.randomUUID(), name: "Managed model", origin: null, description: null, operation: "upsert", managedModelPayload: JSON.stringify({ accessToken: "server-managed-fixture" }) }); - const rotationSnapshot = await (await request("/unlock-key/rotation-snapshot")).json() as any; - expect(rotationSnapshot.records.some((record: any) => record.id === modelId)).toBe(false); - expect(JSON.stringify(rotationSnapshot)).not.toContain("server-managed-fixture"); - const finalGeneration = crypto.randomUUID(); - const rotated = await request("/unlock-key/rotation", "POST", { - expectedGenerationId: newGeneration, generationId: finalGeneration, expectedRevision: 4, - encryptedVerification: verification(finalGeneration), preserveManagedModelCaches: true, - records: rotationSnapshot.records.map((record: any) => ({ ...record, encryptedPayload: record.id === rotatedId ? rotatedCipher : record.encryptedPayload })), - changes: rotationSnapshot.changes.map((change: any) => ({ ...change, encryptedPayload: change.id === rotatedId && change.operation === "upsert" ? rotatedCipher : change.encryptedPayload })), - }); - expect(rotated.status).toBe(200); - expect(await rotated.json()).toEqual({ generationId: finalGeneration, revision: 5, duplicate: false }); - expect(await integrationRepository.records("model")).toMatchObject([{ id: modelId, name: "Managed model", encryptedPayload: expect.stringContaining("factorize-managed-model-cache-v1:") }]); - expect((await request("/integrations/bearer")).status).toBe(200); - expect(JSON.stringify(await (await request("/integrations/bearer")).json())).not.toContain(rotatedCipher); - const agent = await request("/unlock-key/rotation-snapshot", "GET", undefined, "untrusted-cookie"); - expect(agent.status).toBe(401); - } finally { await f.cleanup(); } + for (const path of ["/credential-proxy/setup", "/credential-proxy/browser-capability", "/unlock-key/verification", "/unlock-key/rotation"]) { + const response = await worker.fetch(new Request(f.env.APP_ORIGIN + "/api/v1" + path, {method:"POST", headers:{Cookie:f.cookie, Origin:f.env.APP_ORIGIN,"Content-Type":"application/json"},body:"{}"}),f.env,{waitUntil(){}} as any); + expect(response.status).toBe(404); + } + } finally {await f.cleanup();} }); it("supports safe create, list, update, delete and rejects malformed and stale writes", async () => { const f = await loadingFixture(databaseUrl!); @@ -190,7 +80,7 @@ describe.skipIf(!databaseUrl)("owner-only managed credential API (PostgreSQL)", const listed = await request(path); expect(listed.status).toBe(200); - expect(await listed.json()).toEqual({ revision: 1, accounts: [{ id, name: "Work account", description: "Personal subscription", revision: 1 }] }); + expect(await listed.json()).toEqual({ revision: 1, accounts: [{ id, name: "Work account", description: "Personal subscription", revision: 1, credentialConfigured: false }] }); const stale = await request(path + `/${id}`, "DELETE", { expectedRevision: 0, idempotencyKey: crypto.randomUUID() }); expect(stale.status).toBe(409); diff --git a/packages/api/test/encrypted-integration-repository.postgres.test.ts b/packages/api/test/encrypted-integration-repository.postgres.test.ts index 550195fc..0631b2f4 100644 --- a/packages/api/test/encrypted-integration-repository.postgres.test.ts +++ b/packages/api/test/encrypted-integration-repository.postgres.test.ts @@ -1,232 +1,46 @@ -import { afterAll, beforeAll, describe, expect, it } from "vitest"; -import { readdir, readFile } from "node:fs/promises"; -import pg from "pg"; -import { decrypt } from "../src/crypto"; -import { Database } from "../src/postgres/database"; -import { RunRetentionRepository } from "../src/postgres/run-retention-repository"; -import { EncryptedIntegrationRepository, IntegrationIdempotencyConflictError, StaleIntegrationGenerationError, StaleIntegrationRevisionError } from "../src/postgres/encrypted-integration-repository"; - -const url = process.env.AUTH_TEST_DATABASE_URL; -const serverKey = btoa("s".repeat(32)); -const userKey = btoa("u".repeat(32)); - -async function userEncrypt(plaintext: string): Promise { - const iv = crypto.getRandomValues(new Uint8Array(12)); - const key = await crypto.subtle.importKey("raw", Uint8Array.from(atob(userKey), c => c.charCodeAt(0)), "AES-GCM", false, ["encrypt"]); - const body = await crypto.subtle.encrypt({ name: "AES-GCM", iv }, key, new TextEncoder().encode(plaintext)); - const encode = (bytes: Uint8Array) => btoa(Array.from(bytes, byte => String.fromCharCode(byte)).join("")); - return `${encode(iv)}.${encode(new Uint8Array(body))}`; -} - -describe.skipIf(!url)("encrypted integration persistence (PostgreSQL)", () => { - let db: Database; - let admin: pg.Client; - let databaseName: string; - let tearingDown = false; - let unexpectedPoolError: Error | undefined; - beforeAll(async () => { - admin = new pg.Client({ connectionString: url }); - await admin.connect(); - databaseName = `encrypted_integration_${crypto.randomUUID().replaceAll("-", "")}`; - await admin.query(`CREATE DATABASE ${databaseName}`); - const databaseUrl = new URL(url!); databaseUrl.pathname = `/${databaseName}`; - db = new Database({ connectionString: databaseUrl.toString() }); - db.pool.on("error", error => { - if (tearingDown && (error as NodeJS.ErrnoException).code === "57P01") return; - unexpectedPoolError = error; - }); - const migrations = new URL("../migrations/", import.meta.url); - for (const file of (await readdir(migrations)).filter(file => /^\d+.*\.sql$/.test(file)).sort()) await db.pool.query(await readFile(new URL(file, migrations), "utf8")); - const migration = await db.pool.query("SELECT to_regclass('app.integration_collections') AS collection, to_regclass('app.integration_changes') AS changes"); - expect(migration.rows[0]).toEqual({ collection: "app.integration_collections", changes: "app.integration_changes" }); - }, 30_000); - afterAll(async () => { - await db?.close(); - tearingDown = true; - await admin?.query(`DROP DATABASE IF EXISTS ${databaseName} WITH (FORCE)`); - await admin?.end(); - if (unexpectedPoolError) throw unexpectedPoolError; - }); - - async function freshRepository() { - const tenantId = crypto.randomUUID(); - await db.pool.query("INSERT INTO app.tenants(id) VALUES ($1)", [tenantId]); - return { tenantId, repository: new EncryptedIntegrationRepository(db, tenantId, serverKey) }; - } - - it("encrypts user ciphertext again and server-key access cannot recover synthetic plaintext", async () => { - const plaintext = "synthetic bearer secret that must remain user-encrypted"; - const innerCiphertext = await userEncrypt(plaintext); - const id = crypto.randomUUID(), idempotencyKey = crypto.randomUUID(); - const { tenantId, repository } = await freshRepository(); - await repository.write({ id, idempotencyKey, expectedRevision: 0, operation: "upsert", kind: "bearer", name: "Source", origin: "https://api.example.test", description: "fixture", encryptedPayload: innerCiphertext }); - const stored = (await db.pool.query("SELECT encrypted_payload FROM app.integration_records WHERE tenant_id=$1 AND id=$2", [tenantId, id])).rows[0].encrypted_payload as string; - expect(stored).not.toBe(innerCiphertext); - expect(stored).not.toContain(plaintext); - const returned = (await repository.records())[0]!; - expect(returned.encryptedPayload).toBe(innerCiphertext); - await expect(decrypt(returned.encryptedPayload, serverKey)).rejects.toThrow(); - expect(returned.encryptedPayload).not.toContain(plaintext); - }); - - it("isolates tenants, rejects stale writes, and serializes concurrent conditional edits", async () => { - const { tenantId, repository } = await freshRepository(); - const otherTenant = crypto.randomUUID(); - await db.pool.query("INSERT INTO app.tenants(id) VALUES ($1)", [otherTenant]); - const other = new EncryptedIntegrationRepository(db, otherTenant, serverKey); - const first = { id: crypto.randomUUID(), idempotencyKey: crypto.randomUUID(), expectedRevision: 0, operation: "upsert" as const, kind: "model" as const, name: "Primary", origin: null, description: null, encryptedPayload: await userEncrypt("first") }; - await repository.write(first); - expect(await other.revision()).toBe(0); - expect(await other.records()).toEqual([]); - await expect(repository.write({ ...first, id: crypto.randomUUID(), idempotencyKey: crypto.randomUUID() })).rejects.toMatchObject({ name: "StaleIntegrationRevisionError", currentRevision: 1 }); - const base = await userEncrypt("parallel"); - const results = await Promise.allSettled([0, 1].map(() => repository.write({ id: crypto.randomUUID(), idempotencyKey: crypto.randomUUID(), expectedRevision: 1, operation: "upsert", kind: "model", name: `Concurrent-${crypto.randomUUID()}`, origin: null, description: null, encryptedPayload: base }))); - expect(results.filter(result => result.status === "fulfilled")).toHaveLength(1); - expect(results.filter(result => result.status === "rejected" && result.reason instanceof StaleIntegrationRevisionError)).toHaveLength(1); - }); - - it("stores model refresh caches with server encryption and no unlock-key generation", async () => { - const { tenantId, repository } = await freshRepository(); - const id = crypto.randomUUID(); - const created = await repository.write({ id, idempotencyKey: crypto.randomUUID(), expectedRevision: 0, operation: "upsert", kind: "model", name: "Codex", origin: null, description: null, managedModelPayload: "{}" }); - const payload = JSON.stringify({ tokens: { access_token: "synthetic-access", refresh_token: "synthetic-refresh" } }); - const saved = await repository.saveModelCache({ id, expectedRevision: created.revision, idempotencyKey: crypto.randomUUID(), encryptedPayload: payload }); - expect(saved.revision).toBe(created.revision + 1); - const stored = (await db.pool.query("SELECT encrypted_payload FROM app.integration_records WHERE tenant_id=$1 AND id=$2", [tenantId, id])).rows[0].encrypted_payload as string; - expect(stored).not.toContain("synthetic-access"); - expect(await decrypt(stored, serverKey)).toBe(`factorize-managed-model-cache-v1:${payload}`); - await expect(repository.saveModelCache({ id, expectedRevision: saved.revision, idempotencyKey: crypto.randomUUID(), encryptedPayload: "not-json" })) - .rejects.toMatchObject({ name: "IntegrationValidationError" }); - }); - - it("returns edits and deletion tombstones in revision order and deduplicates retries", async () => { - const { repository, tenantId } = await freshRepository(); - const id = crypto.randomUUID(), idempotencyKey = crypto.randomUUID(); - const one = await userEncrypt("account version one"); - const first = { id, idempotencyKey, expectedRevision: await repository.revision(), operation: "upsert" as const, kind: "bearer" as const, name: "Ordered", origin: "https://one.example.test", description: null, encryptedPayload: one }; - const firstResult = await repository.write(first); - expect(firstResult.duplicate).toBe(false); - expect(await repository.write(first)).toEqual({ ...firstResult, duplicate: true }); - const two = await userEncrypt("account version two"); - const edit = { ...first, idempotencyKey: crypto.randomUUID(), expectedRevision: firstResult.revision, origin: "https://two.example.test", encryptedPayload: two }; - const editResult = await repository.write(edit); - const deletion = { id, idempotencyKey: crypto.randomUUID(), expectedRevision: editResult.revision, operation: "delete" as const, kind: "bearer" as const, name: "Ordered", origin: "https://two.example.test", description: null }; - const deleteResult = await repository.write(deletion); - const changes = await repository.changesSince(firstResult.revision - 1); - expect(changes.map(({ revision, operation }) => [revision, operation])).toEqual([[firstResult.revision, "upsert"], [editResult.revision, "upsert"], [deleteResult.revision, "delete"]]); - expect(changes.map(change => change.encryptedPayload)).toEqual([one, two, null]); - expect(await repository.records()).not.toContainEqual(expect.objectContaining({ id })); - const tombstone = await db.pool.query("SELECT deleted_at,encrypted_payload,revision FROM app.integration_records WHERE tenant_id=$1 AND id=$2", [tenantId, id]); - expect(tombstone.rows[0]).toMatchObject({ encrypted_payload: null, revision: String(deleteResult.revision) }); - expect(tombstone.rows[0].deleted_at).toBeInstanceOf(Date); - await expect(repository.write({ ...first, name: "Different operation with same key" })).rejects.toBeInstanceOf(IntegrationIdempotencyConflictError); - }); - - it("prunes bounded old change history and tells stale consumers to reload the full collection", async () => { - const { tenantId, repository } = await freshRepository(); - const encryptedPayload = await userEncrypt("retained synthetic integration"); - await repository.write({ id: crypto.randomUUID(), idempotencyKey: crypto.randomUUID(), expectedRevision: 0, operation: "upsert", kind: "model", name: "Retained", origin: null, description: null, encryptedPayload }); - await db.pool.query("UPDATE app.integration_changes SET created_at=now()-interval '15 days' WHERE tenant_id=$1", [tenantId]); - - const result = await new RunRetentionRepository(db).cleanupIndependentHistory(); - expect(result.find(row => row.queue === "integration_changes")?.deleted).toBe(1); - await expect(repository.changesSince(0)).rejects.toMatchObject({ name: "StaleIntegrationRevisionError", currentRevision: 1, resyncRequired: true }); - expect(await repository.changesSince(1)).toEqual([]); - expect((await repository.records()).map(record => record.name)).toEqual(["Retained"]); - }); - - it("stages ciphertext only, atomically replaces the whole generation, and makes a lost commit reply retryable", async () => { - const { repository, tenantId } = await freshRepository(); - const id = crypto.randomUUID(), original = await userEncrypt("old credential fixture"), rotated = await userEncrypt("rotated credential fixture"); - const tombstoneId = crypto.randomUUID(), tombstoneCipher = await userEncrypt("deleted credential fixture"); - const write = { id, idempotencyKey: crypto.randomUUID(), expectedRevision: 0, operation: "upsert" as const, kind: "bearer" as const, name: "Rotation", origin: "https://rotation.example.test", description: null, encryptedPayload: original }; - await repository.write(write); - const tombstoneWrite = { id: tombstoneId, idempotencyKey: crypto.randomUUID(), expectedRevision: 1, operation: "upsert" as const, kind: "model" as const, name: "Retired", origin: null, description: null, encryptedPayload: tombstoneCipher }; - await repository.write(tombstoneWrite); - const tombstoneRevision = (await repository.write({ ...tombstoneWrite, expectedRevision: 2, idempotencyKey: crypto.randomUUID(), operation: "delete", encryptedPayload: undefined })).revision; - const baseRevision = tombstoneRevision; - const generationId = crypto.randomUUID(); - const snapshot = { records: [ - { id, kind: "bearer" as const, name: "Rotation", origin: write.origin, description: null, revision: 1, encryptedPayload: rotated, deletedAt: null }, - { id: tombstoneId, kind: "model" as const, name: "Retired", origin: null, description: null, revision: tombstoneRevision, encryptedPayload: null, deletedAt: new Date() }, - ], changes: [ - { id, idempotencyKey: crypto.randomUUID(), kind: "bearer" as const, name: "Rotation", origin: write.origin, description: null, revision: 1, operation: "upsert" as const, encryptedPayload: rotated }, - { id: tombstoneId, idempotencyKey: crypto.randomUUID(), kind: "model" as const, name: "Retired", origin: null, description: null, revision: 2, operation: "upsert" as const, encryptedPayload: tombstoneCipher }, - { id: tombstoneId, idempotencyKey: crypto.randomUUID(), kind: "model" as const, name: "Retired", origin: null, description: null, revision: tombstoneRevision, operation: "delete" as const, encryptedPayload: null }, - ] }; - expect(await repository.stageGeneration({ generationId, expectedRevision: baseRevision, ...snapshot })).toEqual({ duplicate: false }); - expect(await repository.stageGeneration({ generationId, expectedRevision: baseRevision, ...snapshot })).toEqual({ duplicate: true }); - await expect(repository.stageGeneration({ generationId, expectedRevision: baseRevision, ...snapshot, records: snapshot.records.map(record => record.id === id ? { ...record, encryptedPayload: original } : record) })).rejects.toBeInstanceOf(IntegrationIdempotencyConflictError); - const staged = await db.pool.query("SELECT encrypted_payload FROM app.integration_generation_records WHERE tenant_id=$1 AND generation_id=$2 AND encrypted_payload IS NOT NULL", [tenantId,generationId]); - expect(staged.rows[0].encrypted_payload).toBe(rotated); - expect(JSON.stringify(staged.rows)).not.toContain("rotated credential fixture"); - - await db.pool.query(`CREATE FUNCTION app.reject_rotation_delete() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN RAISE EXCEPTION 'injected pre-commit failure'; END $$`); - await db.pool.query("CREATE TRIGGER reject_rotation_delete BEFORE DELETE ON app.integration_records FOR EACH ROW EXECUTE FUNCTION app.reject_rotation_delete()"); - await expect(repository.commitGeneration(generationId, baseRevision)).rejects.toThrow("injected pre-commit failure"); - expect((await repository.records()).find(record => record.id === id)!.encryptedPayload).toBe(original); - await db.pool.query("DROP TRIGGER reject_rotation_delete ON app.integration_records"); - await db.pool.query("DROP FUNCTION app.reject_rotation_delete()"); - - const lockA = 17391, lockB = 2871; - const gate = await db.pool.connect(); - await db.pool.query(`CREATE FUNCTION app.hold_rotation_insert() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN PERFORM pg_advisory_xact_lock(${lockA},${lockB}); RETURN NEW; END $$`); - await db.pool.query("CREATE TRIGGER hold_rotation_insert BEFORE INSERT ON app.integration_records FOR EACH ROW EXECUTE FUNCTION app.hold_rotation_insert()"); - await gate.query("SELECT pg_advisory_lock($1,$2)", [lockA,lockB]); +import {describe, expect, it, vi} from "vitest"; +import {loadingFixture} from "./helpers/loading-fixture"; +import {CredentialRepository, IntegrationIdempotencyConflictError, StaleIntegrationRevisionError, MANAGED_BEARER_PREFIX} from "../src/postgres/credential-repository"; +import {decrypt, encrypt} from "../src/crypto"; + +vi.mock("cloudflare:workers",()=>({WorkerEntrypoint:class{},DurableObject:class{}})); +vi.mock("@cloudflare/workers-oauth-provider",()=>({OAuthProvider:class{},AuthorizationError:class{},getOAuthApi:vi.fn()})); +const url=process.env.AUTH_TEST_DATABASE_URL; +describe.skipIf(!url)("managed credential persistence", {timeout:60_000}, () => { + it("encrypts credentials, exposes metadata only, isolates tenants and preserves CAS/idempotency", async () => { + const f=await loadingFixture(url!); try { - const pendingCommit = repository.commitGeneration(generationId, baseRevision); - const deadline = Date.now() + 5_000; - let reachedInsert = false; - while (Date.now() < deadline) { - const waiting = await gate.query("SELECT 1 FROM pg_stat_activity WHERE wait_event_type='Lock' AND datname=current_database() AND pid<>pg_backend_pid() LIMIT 1"); - if (waiting.rowCount) { reachedInsert = true; break; } - await new Promise(resolve => setImmediate(resolve)); - } - expect(reachedInsert, JSON.stringify((await gate.query("SELECT pid,state,wait_event_type,wait_event,query FROM pg_stat_activity WHERE datname=current_database() AND pid<>pg_backend_pid()")).rows)).toBe(true); - expect((await repository.records()).find(record => record.id === id)!.encryptedPayload).toBe(original); - await gate.query("SELECT pg_advisory_unlock($1,$2)", [lockA,lockB]); - await pendingCommit; - } finally { - await gate.query("SELECT pg_advisory_unlock($1,$2)", [lockA,lockB]); - await db.pool.query("DROP TRIGGER hold_rotation_insert ON app.integration_records"); - await db.pool.query("DROP FUNCTION app.hold_rotation_insert()"); - gate.release(); - } - const committed = await repository.commitGeneration(generationId, baseRevision); - expect(committed).toEqual({ revision: baseRevision + 1, duplicate: true }); - // Simulate the caller losing the response after the transaction committed. - expect(await repository.commitGeneration(generationId, baseRevision)).toEqual({ ...committed, duplicate: true }); - await expect(repository.write({ id: crypto.randomUUID(), idempotencyKey: crypto.randomUUID(), expectedRevision: baseRevision, operation: "upsert", kind: "model", name: "Stale generation write", origin: null, description: null, encryptedPayload: await userEncrypt("stale write") })).rejects.toMatchObject({ name: "StaleIntegrationRevisionError", currentRevision: committed.revision }); - expect((await repository.records()).find(record => record.id === id)!.encryptedPayload).toBe(rotated); - const activeTombstone = await db.pool.query("SELECT deleted_at,encrypted_payload FROM app.integration_records WHERE tenant_id=$1 AND id=$2", [tenantId,tombstoneId]); - expect(activeTombstone.rows[0].encrypted_payload).toBeNull(); - expect(activeTombstone.rows[0].deleted_at).toBeInstanceOf(Date); - expect((await repository.changesSince(0)).map(change => change.encryptedPayload)).toEqual([rotated, tombstoneCipher, null]); - }); - - it("rejects a staged generation after concurrent writes and bounds rollback to the active commit", async () => { - const { repository, tenantId } = await freshRepository(); - const originalId = crypto.randomUUID(), original = await userEncrypt("preserved credential"); - const first = await repository.write({ id: originalId, idempotencyKey: crypto.randomUUID(), expectedRevision: 0, operation: "upsert", kind: "model", name: "Preserved", origin: null, description: null, encryptedPayload: original }); - const replacementId = crypto.randomUUID(), replacement = await userEncrypt("replacement credential"); - const staged = { generationId: crypto.randomUUID(), expectedRevision: first.revision, records: [{ id: replacementId, kind: "model" as const, name: "Replacement", origin: null, description: null, revision: first.revision, encryptedPayload: replacement, deletedAt: null }], changes: [{ id: replacementId, idempotencyKey: crypto.randomUUID(), kind: "model" as const, name: "Replacement", origin: null, description: null, revision: first.revision, operation: "upsert" as const, encryptedPayload: replacement }] }; - await repository.stageGeneration(staged); - await repository.write({ id: crypto.randomUUID(), idempotencyKey: crypto.randomUUID(), expectedRevision: first.revision, operation: "upsert", kind: "model", name: "Concurrent", origin: null, description: null, encryptedPayload: await userEncrypt("concurrent edit") }); - await expect(repository.commitGeneration(staged.generationId, first.revision)).rejects.toMatchObject({ name: "StaleIntegrationGenerationError", currentRevision: first.revision + 1 }); - expect((await repository.records()).map(record => record.name)).toEqual(["Preserved", "Concurrent"]); - - const baseRevision = await repository.revision(), rotated = await userEncrypt("rotated preserved credential"), generationId = crypto.randomUUID(); - const activeRecords = await repository.records(); - const currentChanges = await repository.changesSince(0, 500); - await repository.stageGeneration({ generationId, expectedRevision: baseRevision, - records: activeRecords.map(record => ({ ...record, encryptedPayload: record.id === originalId ? rotated : record.encryptedPayload, deletedAt: null })), - changes: currentChanges.map(change => ({ ...change, idempotencyKey: crypto.randomUUID(), encryptedPayload: change.operation === "upsert" && change.id === originalId ? rotated : change.encryptedPayload })) }); - const committed = await repository.commitGeneration(generationId, baseRevision); - expect((await repository.records()).find(record => record.id === originalId)!.encryptedPayload).toBe(rotated); - expect(await repository.rollbackGeneration(generationId)).toBe(committed.revision + 1); - expect((await repository.records()).find(record => record.id === originalId)!.encryptedPayload).toBe(original); - await expect(repository.rollbackGeneration(generationId)).rejects.toThrow("not available for rollback"); - expect(await repository.cleanupGenerations(0, 500)).toBeGreaterThanOrEqual(1); - expect((await db.pool.query("SELECT 1 FROM app.integration_generation_journal WHERE tenant_id=$1 AND generation_id=$2", [tenantId,generationId])).rowCount).toBe(0); + const repo=new CredentialRepository(f.db,f.tenantId,f.env.CREDENTIAL_ENCRYPTION_KEY); + const input={id:crypto.randomUUID(),idempotencyKey:crypto.randomUUID(),expectedRevision:0,operation:"upsert" as const,kind:"bearer" as const,name:"Service",origin:"https://api.example.com",description:null,managedSecret:"fixture-private-secret"}; + expect(await repo.write(input)).toEqual({revision:1,duplicate:false}); + expect(await repo.write(input)).toEqual({revision:1,duplicate:true}); + await expect(repo.write({...input,managedSecret:"different"})).rejects.toBeInstanceOf(IntegrationIdempotencyConflictError); + await expect(repo.write({...input,idempotencyKey:crypto.randomUUID()})).rejects.toBeInstanceOf(StaleIntegrationRevisionError); + const stored=(await f.db.pool.query("SELECT encrypted_payload FROM app.integration_records WHERE tenant_id=$1 AND id=$2",[f.tenantId,input.id])).rows[0].encrypted_payload; + expect(stored).not.toContain(input.managedSecret); + expect(await decrypt(stored,f.env.CREDENTIAL_ENCRYPTION_KEY)).toBe(MANAGED_BEARER_PREFIX+input.managedSecret); + expect(JSON.stringify(await repo.metadata())).not.toContain(input.managedSecret); + expect(await new CredentialRepository(f.db,f.otherTenant,f.env.CREDENTIAL_ENCRYPTION_KEY).managedCredential(input.id,"bearer")).toBeNull(); + expect((await repo.managedCredential(input.id,"bearer"))?.payload).toBe(input.managedSecret); + await repo.write({...input,expectedRevision:1,idempotencyKey:crypto.randomUUID(),managedSecret:"rotated"}); + expect((await repo.managedCredential(input.id,"bearer"))?.payload).toBe("rotated"); + const {managedSecret,...metadata}=input; + await repo.write({...metadata,expectedRevision:2,idempotencyKey:crypto.randomUUID(),operation:"delete"}); + expect(await repo.managedCredential(input.id,"bearer")).toBeNull(); + } finally {await f.cleanup();} + }); + it("refuses legacy user ciphertext and serializes model refresh without exposing caches", async () => { + const f=await loadingFixture(url!); + try { + const repo=new CredentialRepository(f.db,f.tenantId,f.env.CREDENTIAL_ENCRYPTION_KEY), id=crypto.randomUUID(); + await repo.write({id,idempotencyKey:crypto.randomUUID(),expectedRevision:0,operation:"upsert",kind:"model",name:"Model",origin:null,description:null,managedModelPayload:'{"OPENAI_API_KEY":"old"}'}); + await Promise.all([repo.refreshManagedModel(id, async p=>JSON.stringify({...JSON.parse(p),refreshes:(JSON.parse(p).refreshes??0)+1})),repo.refreshManagedModel(id,async p=>JSON.stringify({...JSON.parse(p),refreshes:(JSON.parse(p).refreshes??0)+1}))]); + expect(JSON.parse((await repo.managedCredential(id,"model"))!.payload).refreshes).toBe(2); + expect(JSON.stringify(await repo.metadata())).not.toContain("OPENAI_API_KEY"); + await f.db.pool.query("UPDATE app.integration_records SET encrypted_payload=$3 WHERE tenant_id=$1 AND id=$2",[f.tenantId,id,await encrypt("old-user-encrypted-payload",f.env.CREDENTIAL_ENCRYPTION_KEY)]); + expect(await repo.managedCredential(id,"model")).toBeNull(); + const refresh=()=>{throw new Error("must not read old ciphertext");}; + expect(await repo.refreshManagedModel(id,refresh)).toBeNull(); + } finally {await f.cleanup();} }); }); diff --git a/packages/api/test/exe-run-proxy.test.ts b/packages/api/test/exe-run-proxy.test.ts deleted file mode 100644 index 8192776e..00000000 --- a/packages/api/test/exe-run-proxy.test.ts +++ /dev/null @@ -1,205 +0,0 @@ -import { afterEach, describe, expect, it, vi } from "vitest"; -import { ExeRunProxy } from "../src/exe-run-proxy"; -import { ExeVmBackend, vmNameFor } from "../src/exe-vm-backend"; -import { agentDriver } from "../src/agent-driver"; -import { runProxyName } from "../src/run-credentials"; -import type { BackendCommandResult } from "../src/execution"; - -afterEach(() => vi.unstubAllGlobals()); -const runId = "00000000-0000-4000-8000-000000000001", vm = vmNameFor(runId), name = runProxyName(runId); -const target = "https://app.factorize.test"; -const until = new Date(Date.now() + 23 * 60 * 60_000).toISOString(); -const owned = { name, type: "http-proxy", target, attachments: [`vm:${vm}@${until}`], comment: `Factorize run ${runId}`, help: `curl https://${name}.int.exe.xyz/` }; -const context = { kind: "factorize-runtime-context-v1", authMethod: "run_token", runId, jobId: "source-job", scopes: ["runs:read", "runs:invoke"] }; -const result = (body: unknown = [], ok = true): BackendCommandResult => ({ ok, body: typeof body === "string" ? body : JSON.stringify(body), status: ok ? 200 : 503, exitCode: ok ? 0 : 1, requestBody: "not retained" }); - -describe("exe.dev run proxy lifecycle", () => { - it("installs the credential in the control plane and time-boxes a VM-specific attachment", async () => { - const commands: string[] = []; - const proxy = new ExeRunProxy(async command => { commands.push(command); return result(); }); - await proxy.provision(await proxy.prepare(runId), vm, "https://app.factorize.test", "private-run-token"); - expect(commands).toHaveLength(3); - expect(commands[1]).toContain("integrations add http-proxy"); - expect(commands[1]).toContain("--bearer='private-run-token'"); - expect(commands[1]).toContain(`--comment='Factorize run ${runId}'`); - expect(commands[2]).toBe(`integrations attach '${name}' 'vm:${vm}' --for=24h`); - expect(commands.some(command => command.startsWith("ssh "))).toBe(false); - }); - - it("rotates an owned integration on retry and removes it idempotently", async () => { - let installed = true; - const commands: string[] = []; - const proxy = new ExeRunProxy(async command => { - commands.push(command); - if (command === "integrations list --json") return result(installed ? [owned] : []); - if (command.startsWith("integrations remove")) installed = false; - if (command.startsWith("integrations add")) installed = true; - return result(); - }); - await proxy.provision(await proxy.prepare(runId), vm, "https://app.factorize.test", "replacement-token"); - expect(commands.slice(1, 3)).toEqual(["integrations list --json", `integrations remove '${name}'`]); - expect(commands[3]).toContain("integrations add http-proxy"); - expect(commands[3]).toContain("--bearer='replacement-token'"); - expect(commands.some(command => command.startsWith("integrations edit"))).toBe(false); - await proxy.remove(name, runId); - await proxy.remove(name, runId); - expect(commands.filter(command => command.startsWith("integrations remove"))).toHaveLength(2); - }); - - it("refuses to replace or remove a colliding integration without its ownership marker", async () => { - const commands: string[] = []; - const proxy = new ExeRunProxy(async command => { commands.push(command); return result([{ ...owned, comment: "unrelated" }]); }); - await expect(proxy.prepare(runId)).rejects.toThrow("another integration"); - await expect(proxy.remove(name, runId)).rejects.toThrow("ownership marker"); - await expect(proxy.remove("production", runId)).rejects.toThrow("unrelated"); - expect(commands.every(command => command === "integrations list --json")).toBe(true); - }); - - it("rechecks ownership before replacing an existing proxy on retry", async () => { - const commands: string[] = []; - const proxy = new ExeRunProxy(async command => { - commands.push(command); - return result([{ ...owned, comment: commands.length === 1 ? owned.comment : "unrelated" }]); - }); - const plan = await proxy.prepare(runId); - await expect(proxy.provision(plan, vm, target, "replacement-token")).rejects.toThrow("ownership marker"); - expect(commands).toEqual(["integrations list --json", "integrations list --json"]); - }); - - it("does not install a replacement credential when removal fails", async () => { - const commands: string[] = []; - const proxy = new ExeRunProxy(async command => { - commands.push(command); - return command === "integrations list --json" ? result([owned]) : result("unavailable", false); - }); - await expect(proxy.provision(await proxy.prepare(runId), vm, target, "replacement-token")).rejects.toThrow("cleanup failed"); - expect(commands).toEqual(["integrations list --json", "integrations list --json", `integrations remove '${name}'`]); - }); - - it.each([false, true])("never exposes a credential echoed by provisioning failure (throws=%s)", async throws => { - const secret = "private-run-token"; - const proxy = new ExeRunProxy(async command => { - if (command === "integrations list --json") return result(); - if (throws) throw new Error(`provider echoed ${secret}`); - return result(`provider echoed ${secret}`, false); - }); - const plan = await proxy.prepare(runId); - try { await proxy.provision(plan, vm, "https://app.factorize.test", secret); throw new Error("Unexpected provision success"); } - catch (error) { expect(String(error)).not.toContain(secret); expect(String(error)).toContain("Run proxy provisioning"); } - }); - - it.each(["auto:all", `vm:${vm}`, "tag:factorize", `tag:factorize@${until}`])("blocks shared attachment %s independently of the guest", async spec => { - const other = { name: "shared-factorize", type: "http-proxy", target, attachments: [spec] }; - const commands: string[] = []; - const proxy = new ExeRunProxy(async command => { - commands.push(command); - if (command === "integrations list --json") return result([owned, other]); - // A guest claiming it only sees its own proxy cannot hide the grant. - if (command.includes("reflection.int.exe.xyz")) return result({ integrations: [owned] }); - return result(context); - }); - await expect(proxy.verify(vm, runId, target, ["factorize"])).rejects.toThrow("Unsafe shared Factorize integration shared-factorize"); - expect(commands).toEqual(["integrations list --json"]); - }); - - it("allows operator-only integrations without exposing them to the guest", async () => { - const other = { name: "factorize", type: "http-proxy", target, attachments: ["tag:human"] }; - const proxy = new ExeRunProxy(async command => command === "integrations list --json" ? result([owned, other]) - : command.includes("reflection.int.exe.xyz") ? result({ integrations: [owned] }) : result(context)); - await expect(proxy.verify(vm, runId, target, ["factorize"])).resolves.toBeUndefined(); - }); - - it.each([{ scopes: [] }, { scopes: ["jobs:write"] }])("verifies a dedicated proxy without requiring read or invoke scopes ($scopes)", async ({ scopes }) => { - const proxy = new ExeRunProxy(async command => command === "integrations list --json" ? result([owned]) - : command.includes("reflection.int.exe.xyz") ? result({ integrations: [owned] }) : result({ ...context, scopes })); - await expect(proxy.verify(vm, runId, target)).resolves.toBeUndefined(); - }); - - it("rejects a run proxy with attachments to other VMs", async () => { - const proxy = new ExeRunProxy(async () => result([{ ...owned, attachments: [`vm:${vm}`, "auto:all"] }])); - await expect(proxy.verify(vm, runId, target)).rejects.toThrow("attached only to its execution VM"); - }); - - it.each([`vm:${vm}`, `vm:${vm}@2000-01-01T00:00:00Z`, `vm:${vm}@${new Date(Date.now() + 48 * 60 * 60_000).toISOString()}`])("rejects an unbounded, expired, or excessive proxy lease: %s", async grant => { - const proxy = new ExeRunProxy(async () => result([{ ...owned, attachments: [grant] }])); - await expect(proxy.verify(vm, runId, target)).rejects.toThrow("at most 24 hours"); - }); - - it("rejects shared authority before even creating the execution VM", async () => { - const commands: string[] = []; - vi.stubGlobal("fetch", vi.fn(async (_url: string, init: RequestInit) => { - commands.push(String(init.body)); - return Response.json([{ name: "factorize", type: "http-proxy", target, attachments: ["auto:all"] }]); - })); - const launched = await new ExeVmBackend({ apiToken: "control-plane-token", agentKind: "codex", tags: [] }).launch({ runId, prompt: "work", harness: agentDriver("codex").launch(runId, {}), runProxy: { targetOrigin: target, credential: "private-run-token" } }); - expect(launched.observation.state).toBe("failed"); - expect(launched.observation.detail).toContain("Unsafe shared Factorize integration"); - expect(commands).toEqual(["integrations list --json", "integrations list --json"]); - }); - - it("fails closed when a Factorize proxy's authority cannot be inspected", async () => { - const proxy = new ExeRunProxy(async command => command === "integrations list --json" ? result([owned]) - : command.includes("reflection.int.exe.xyz") ? result({ integrations: [owned] }) : result({ error: { code: "internal_error" } })); - await expect(proxy.verify(vm, runId, target)).rejects.toThrow("identity could not be verified"); - }); - - it("rejects a run proxy that authenticates as a different run", async () => { - const proxy = new ExeRunProxy(async command => command === "integrations list --json" ? result([owned]) : command.includes("reflection.int.exe.xyz") ? result({ integrations: [owned] }) : result({ ...context, runId: "another-run" })); - await expect(proxy.verify(vm, runId, target)).rejects.toThrow("run proxy identity could not be verified"); - }); - - it("retains cleanup on proxy deletion failure rather than claiming success", async () => { - const proxy = new ExeRunProxy(async command => command === "integrations list --json" ? result([owned]) : result("unavailable", false)); - await expect(proxy.remove(name, runId)).rejects.toThrow("cleanup failed"); - }); - - it("launches without placing the credential in guest commands, prompts, or receipts", async () => { - const commands: string[] = []; - const secret = "private-run-token"; - let installed = false; - vi.stubGlobal("fetch", vi.fn(async (_url: string, init: RequestInit) => { - const command = String(init.body); commands.push(command); - if (command === "integrations list --json") return Response.json(installed ? [owned] : []); - if (command.startsWith("integrations add")) installed = true; - if (command.includes("reflection.int.exe.xyz")) return Response.json({ integrations: [owned] }); - if (command.includes("/api/v1/runtime-context")) return Response.json(context); - return new Response(command.startsWith("ssh ") ? "started" : "{}", { headers: { "X-Exe-Exit": "0" } }); - })); - const launched = await new ExeVmBackend({ apiToken: "control-plane-token", agentKind: "codex", tags: [] }).launch({ - runId, prompt: "work", harness: agentDriver("codex").launch(runId, {}), runProxy: { targetOrigin: "https://app.factorize.test", credential: secret }, - }); - expect(launched.observation.state).toBe("running"); - expect(launched.handle.runProxyName).toBe(name); - expect(commands.filter(command => command.includes(secret))).toHaveLength(1); - expect(commands.filter(command => command.startsWith("ssh ")).join("\n")).not.toContain(secret); - expect(commands.filter(command => command.startsWith("ssh ")).join("\n")).not.toContain("https://app.factorize.test"); - expect(JSON.stringify(launched)).not.toContain(secret); - }); - - it("does not start the agent after a partial provision and retries proxy cleanup", async () => { - const commands: string[] = []; - let installed = false, removalFails = true; - vi.stubGlobal("fetch", vi.fn(async (_url: string, init: RequestInit) => { - const command = String(init.body); commands.push(command); - if (command === "integrations list --json") return Response.json(installed ? [owned] : []); - if (command.startsWith("integrations add")) { installed = true; throw new Error("provider echoed private-run-token"); } - if (command.startsWith("integrations remove")) { - if (removalFails) return new Response("unavailable", { status: 503 }); - installed = false; - } - if (command === "ls --json") return Response.json({ vms: [{ name: vm, comment: `Factorize VM ${vm}` }] }); - return new Response("{}", { headers: { "X-Exe-Exit": "0" } }); - })); - const backend = new ExeVmBackend({ apiToken: "control-plane-token", agentKind: "codex", tags: [] }); - const launched = await backend.launch({ runId, prompt: "work", harness: agentDriver("codex").launch(runId, {}), runProxy: { targetOrigin: target, credential: "private-run-token" } }); - expect(launched.observation.state).toBe("failed"); - expect(launched.handle.runProxyName).toBe(name); - expect(commands.some(command => command.includes("systemd-run"))).toBe(false); - expect(JSON.stringify(launched)).not.toContain("private-run-token"); - expect((await backend.stop(launched.handle)).state).toBe("failed"); - expect(commands).toContain(`rm '${vm}'`); - removalFails = false; - expect((await backend.stop(launched.handle)).state).toBe("stopped"); - expect(commands.filter(command => command.startsWith("integrations remove"))).toHaveLength(2); - }); -}); diff --git a/packages/api/test/execution-backend.test.ts b/packages/api/test/execution-backend.test.ts index 7dfa0b38..17c67b9f 100644 --- a/packages/api/test/execution-backend.test.ts +++ b/packages/api/test/execution-backend.test.ts @@ -7,7 +7,6 @@ import { ExeImageVerificationError, ExeVmBackend, isOwnedVmName, tagsFromInvento import type { ExecutionBackend, ExecutionObservation, LaunchRequest, RunHandle } from "../src/execution"; import { effortOptions, selectableExeTags, type ExeRunConnection } from "../src/exe"; import { agentDriver } from "../src/agent-driver"; -import { runProxyName } from "../src/run-credentials"; afterEach(() => vi.unstubAllGlobals()); @@ -25,7 +24,7 @@ function launchPayload(command: string): any { describe("ExeVmBackend", () => { it("reserves its legacy VM and proxy handle for scheduler recovery", () => { const runId = "00000000-0000-4000-8000-000000000001"; - expect(new ExeVmBackend(connection).reserve(runId)).toEqual({ backendKind: "exe-vm", id: vmNameFor(runId), runProxyName: runProxyName(runId), operationId: runId, vendorIdentityIntegrationName: "fzrun-00000000000040008000000000000001" }); + expect(new ExeVmBackend(connection).reserve(runId)).toEqual({ backendKind: "exe-vm", id: vmNameFor(runId), operationId: runId, vendorIdentityIntegrationName: "fzrun-00000000000040008000000000000001" }); }); it("defines the supported effort choices by agent", () => { expect(effortOptions.codex).toEqual(["minimal", "low", "medium", "high", "xhigh"]); diff --git a/packages/api/test/fixtures/Dockerfile.code-job b/packages/api/test/fixtures/Dockerfile.code-job index e2f0bd96..725cbe4d 100644 --- a/packages/api/test/fixtures/Dockerfile.code-job +++ b/packages/api/test/fixtures/Dockerfile.code-job @@ -1,4 +1,4 @@ FROM node:24.12.0-bookworm-slim@sha256:7326fb2dbdce998edd72140946851be64ef4a643e8715e138ca467e8e9d92c99 -RUN apt-get update && apt-get install -y --no-install-recommends python3 openssl util-linux bash ca-certificates && rm -rf /var/lib/apt/lists/* \ +RUN apt-get update && apt-get install -y --no-install-recommends python3 curl openssl util-linux bash ca-certificates && rm -rf /var/lib/apt/lists/* \ && useradd -m -s /bin/bash exedev CMD ["sleep", "infinity"] diff --git a/packages/api/test/fly-account-connection.postgres.test.ts b/packages/api/test/fly-account-connection.postgres.test.ts index b8b4dfbc..0ce74a30 100644 --- a/packages/api/test/fly-account-connection.postgres.test.ts +++ b/packages/api/test/fly-account-connection.postgres.test.ts @@ -60,7 +60,7 @@ describe.skipIf(!url)("Fly account connection (PostgreSQL/API)", () => { }); it("denies agent credentials even when integrations:write is granted", async () => { - const agent = { ...fixture.auth, authMethod: "run_token", scopes: ["integrations:write"] } as OAuthProps; + const agent = { ...fixture.auth, authMethod: "vendor_identity", scopes: ["integrations:write"] } as OAuthProps; const response = await request("PUT", agent, { token: "secret", organizationSlug: "alpha" }); expect(response.status).toBe(403); expect(await response.json()).toMatchObject({ error: { code: "session_required" } }); diff --git a/packages/api/test/fly-credential-proxy-provisioner.test.ts b/packages/api/test/fly-credential-proxy-provisioner.test.ts deleted file mode 100644 index 9a4dd2e1..00000000 --- a/packages/api/test/fly-credential-proxy-provisioner.test.ts +++ /dev/null @@ -1,255 +0,0 @@ -import { describe, expect, it, vi } from "vitest"; -import { createFlyCredentialProxyProvisioner, createFlyCredentialProxyGuest } from "../src/fly-credential-proxy-provisioner"; - -const epoch = "11111111-1111-4111-8111-111111111111"; -const machine = { - id: "machine-1", - state: "created", - config: { metadata: { - factorize_role: "credential-proxy", - factorize_tenant_id: "11111111-1111-4111-8111-111111111112", - factorize_operation_id: "tenant-proxy-start-1", - factorize_boot_epoch: "11111111-1111-4111-8111-111111111111", - } }, -}; -const input = { - tenantId: "11111111-1111-4111-8111-111111111112", - app: "factorize-proxies", - image: `ghcr.io/generationsoftware/credential-proxy@sha256:${"a".repeat(64)}`, - region: "iad", - size: "shared-cpu-1x", - browserCapabilityPublicKey: "-----BEGIN PUBLIC KEY-----\nfixture\n-----END PUBLIC KEY-----", - controlOrigin: "https://factorize.example", - operationId: "tenant-proxy-start-1", -}; - -function fixture() { - const control = { - provisionCredential: vi.fn(async () => `fzc_${"b".repeat(43)}`), - revokeCredential: vi.fn(async () => true), - }; - const machines = { - createMachine: vi.fn(async (_app: string, _config: any, _operationId: string) => machine), - startMachine: vi.fn(async () => undefined), - destroyMachine: vi.fn(async () => undefined), - }; - const guest = vi.fn(() => ({ run: vi.fn(async () => ({ ok: true, exitCode: 0, stdout: "", stderr: "" })), startProxy: vi.fn(async () => undefined), issueVmCertificate: vi.fn(async () => ({ certificate: "", trustBundle: "" })) })); - const provisioner = createFlyCredentialProxyProvisioner({ control, machines, guest, reviewedImage: input.image, newBootEpoch: () => epoch }); - return { control, machines, guest, provisioner }; -} - -describe("Fly credential proxy startup", () => { - it("creates a digest-pinned dedicated Machine and delivers bootstrap only through startup", async () => { - const { control, machines, guest, provisioner } = fixture(); - const started = await provisioner.start(input); - expect(started).toMatchObject({ proxyIdentity: "fly:factorize-proxies:machine-1", bootEpoch: epoch, machine }); - expect(machines.createMachine).toHaveBeenCalledWith(input.app, expect.objectContaining({ - image: input.image, - region: input.region, - cmd: ["/usr/local/bin/factorize-credential-proxy", "--boot-epoch", epoch], - guest: { cpu_kind: "shared", cpus: 1, memory_mb: 512 }, - env: { FACTORIZE_PROXY_TUNNEL_SERVER_NAME: "factorize-proxies.internal", FACTORIZE_PROXY_TUNNEL_PORT: "9090", FACTORIZE_PROXY_BROWSER_CAPABILITY_PUBLIC_KEY: input.browserCapabilityPublicKey }, - services: [ - { protocol: "tcp", internal_port: 8080, ports: [{ port: 443, handlers: ["tls", "http"] }], force_instance_key: true }, - { protocol: "tcp", internal_port: 9090, ports: [] }, - ], - restart: { policy: "no" }, - auto_start: false, - auto_stop: false, - metadata: expect.objectContaining({ factorize_role: "credential-proxy", factorize_tenant_id: input.tenantId }), - }), input.operationId); - expect(JSON.stringify(machines.createMachine.mock.calls[0])).not.toContain("fzc_"); - expect(machines.startMachine).toHaveBeenCalledWith(input.app, machine.id); - expect(control.provisionCredential).toHaveBeenCalledWith(input.tenantId, "fly:factorize-proxies:machine-1", epoch); - expect(guest).toHaveBeenCalledWith(machine); - const guestAdapter = guest.mock.results[0]!.value; - expect(guestAdapter.startProxy).toHaveBeenCalledWith(expect.objectContaining({ - tenantId: input.tenantId, - proxyIdentity: "fly:factorize-proxies:machine-1", - bootEpoch: epoch, - controlOrigin: input.controlOrigin, - browserOrigin: `https://${input.app}.fly.dev`, - credential: `fzc_${"b".repeat(43)}`, - })); - }); - - it.each([ - ["shared-cpu-1x", "shared", 1], - ["shared-cpu-2x", "shared", 2], - ["shared-cpu-4x", "shared", 4], - ["performance-1x", "performance", 1], - ["performance-2x", "performance", 2], - ["performance-4x", "performance", 4], - ] as const)("uses the requested region, %s size and memory without enabling suspension", async (size, cpuKind, cpus) => { - const { machines, provisioner } = fixture(); - await provisioner.start({ ...input, region: "ord", size, memoryMb: 2048 }); - - const [, config, operationId] = machines.createMachine.mock.calls[0]!; - expect(config).toMatchObject({ - image: input.image, - region: "ord", - guest: { cpu_kind: cpuKind, cpus, memory_mb: 2048 }, - auto_start: false, - auto_stop: false, - restart: { policy: "no" }, - }); - expect(operationId).toBe(input.operationId); - expect(config).not.toHaveProperty("suspend"); - expect(config).not.toHaveProperty("auto_suspend"); - }); - - it("revokes bootstrap authority and removes a Machine when startup fails", async () => { - const { control, machines, guest } = fixture(); - guest.mockReturnValue({ run: vi.fn(), startProxy: vi.fn().mockRejectedValue(new Error("private startup channel failed")), issueVmCertificate: vi.fn() }); - const provisioner = createFlyCredentialProxyProvisioner({ control, machines, guest, reviewedImage: input.image, newBootEpoch: () => epoch }); - await expect(provisioner.start(input)).rejects.toThrow("private startup channel failed"); - expect(control.revokeCredential).toHaveBeenCalledWith(input.tenantId, "fly:factorize-proxies:machine-1"); - expect(machines.destroyMachine).toHaveBeenCalledWith(input.app, machine.id); - }); - - it("removes a created Machine when Fly returns an invalid boot epoch", async () => { - const f = fixture(); - f.machines.createMachine.mockResolvedValue({ - ...machine, - config: { metadata: { ...machine.config.metadata, factorize_boot_epoch: "not-a-uuid" } }, - } as any); - - await expect(f.provisioner.start(input)).rejects.toThrow("mismatched provisioning identity"); - - expect(f.machines.destroyMachine).toHaveBeenCalledWith(input.app, machine.id); - expect(f.control.provisionCredential).not.toHaveBeenCalled(); - expect(f.guest).not.toHaveBeenCalled(); - }); - - it("rejects a valid but different returned boot epoch before granting bootstrap authority", async () => { - const f = fixture(); - f.machines.createMachine.mockResolvedValue({ - ...machine, - config: { metadata: { ...machine.config.metadata, factorize_boot_epoch: "22222222-2222-4222-8222-222222222222" } }, - } as any); - - await expect(f.provisioner.start(input)).rejects.toThrow("mismatched provisioning identity"); - - expect(f.control.provisionCredential).not.toHaveBeenCalled(); - expect(f.guest).not.toHaveBeenCalled(); - expect(f.machines.destroyMachine).toHaveBeenCalledWith(input.app, machine.id); - }); - - it("rejects returned tenant or operation metadata that belongs to another provisioning request", async () => { - for (const metadata of [ - { ...machine.config.metadata, factorize_tenant_id: "another-tenant" }, - { ...machine.config.metadata, factorize_operation_id: "another-operation" }, - { ...machine.config.metadata, factorize_role: "job" }, - ]) { - const f = fixture(); - f.machines.createMachine.mockResolvedValue({ ...machine, config: { metadata } } as any); - - await expect(f.provisioner.start(input)).rejects.toThrow("mismatched provisioning identity"); - - expect(f.control.provisionCredential).not.toHaveBeenCalled(); - expect(f.guest).not.toHaveBeenCalled(); - expect(f.machines.destroyMachine).toHaveBeenCalledWith(input.app, machine.id); - } - }); - - it("fails closed when Fly omits any returned provisioning identity metadata", async () => { - for (const key of ["factorize_boot_epoch", "factorize_role", "factorize_tenant_id", "factorize_operation_id"]) { - const f = fixture(); - const metadata = { ...machine.config.metadata }; - delete (metadata as Record)[key]; - f.machines.createMachine.mockResolvedValue({ ...machine, config: { metadata } } as any); - - await expect(f.provisioner.start(input)).rejects.toThrow("mismatched provisioning identity"); - - expect(f.control.provisionCredential).not.toHaveBeenCalled(); - expect(f.guest).not.toHaveBeenCalled(); - expect(f.machines.destroyMachine).toHaveBeenCalledWith(input.app, machine.id); - } - }); - - it("revokes bootstrap authority and attempts Machine cleanup when explicit start fails", async () => { - const f = fixture(); - const startupFailure = new Error("local Fly fixture start failed"); - f.machines.startMachine.mockRejectedValue(startupFailure); - // Cleanup failure must not replace the original provisioning diagnosis. - f.machines.destroyMachine.mockRejectedValue(new Error("local Fly fixture cleanup failed")); - - await expect(f.provisioner.start(input)).rejects.toBe(startupFailure); - - expect(f.control.provisionCredential).toHaveBeenCalledOnce(); - expect(f.control.revokeCredential).toHaveBeenCalledWith(input.tenantId, "fly:factorize-proxies:machine-1"); - expect(f.control.revokeCredential.mock.invocationCallOrder[0]).toBeLessThan(f.machines.destroyMachine.mock.invocationCallOrder[0]!); - expect(f.machines.destroyMachine).toHaveBeenCalledWith(input.app, machine.id); - expect(f.guest).not.toHaveBeenCalled(); - }); - - it("rejects mutable images and unsafe control origins before provisioning", async () => { - const { machines, provisioner } = fixture(); - await expect(provisioner.start({ ...input, image: "ghcr.io/example/proxy:latest" })).rejects.toThrow("pinned by sha256 digest"); - await expect(provisioner.start({ ...input, controlOrigin: "http://factorize.example" })).rejects.toThrow("HTTPS origin"); - await expect(provisioner.start({ ...input, app: "invalid/app" })).rejects.toThrow("Fly app name"); - expect(machines.createMachine).not.toHaveBeenCalled(); - }); - - it("rejects unsupported Fly sizes before provisioning", async () => { - const { machines, provisioner } = fixture(); - await expect(provisioner.start({ ...input, size: "custom-3x" })).rejects.toThrow("Invalid credential proxy size"); - expect(machines.createMachine).not.toHaveBeenCalled(); - }); - - it.each([255, 8193, 512.5])("rejects unsupported proxy memory %s MiB before provisioning", async memoryMb => { - const { machines, provisioner } = fixture(); - await expect(provisioner.start({ ...input, memoryMb })).rejects.toThrow("between 256 and 8192 MiB"); - expect(machines.createMachine).not.toHaveBeenCalled(); - }); - - it("rejects a different digest-pinned image instead of treating any immutable image as reviewed", async () => { - const { machines, provisioner } = fixture(); - await expect(provisioner.start({ ...input, image: `ghcr.io/generationsoftware/credential-proxy@sha256:${"c".repeat(64)}` })) - .rejects.toThrow("configured reviewed image"); - expect(machines.createMachine).not.toHaveBeenCalled(); - }); -}); - -describe("Fly credential proxy guest adapter", () => { - it("sends the bootstrap credential as stdin to the reviewed startup command", async () => { - const calls: unknown[][] = []; - const spawnProcess = ((command: string, args: string[], options: { stdio: string[] }) => { - calls.push([command, args, options]); - const stdoutHandlers: Array<(chunk: Buffer) => void> = []; - const child: any = { pid: undefined, stdin: { end: (value: string) => { calls.push(["stdin", value]); } }, - stdout: { on: (_event: string, callback: (chunk: Buffer) => void) => stdoutHandlers.push(callback) }, - stderr: { on: () => undefined }, on: (event: string, callback: (code: number) => void) => { - if (event === "close") queueMicrotask(() => { stdoutHandlers.forEach(handler => handler(Buffer.from("Credential proxy started\n"))); callback(0); }); - }, kill: () => undefined }; - return child; - }) as any; - const guest = createFlyCredentialProxyGuest({ app: input.app, machine: machine.id, token: "server-token-fixture", spawnProcess }); - await guest.startProxy({ tenantId: input.tenantId, proxyIdentity: "fly:factorize-proxies:machine-1", bootEpoch: epoch, controlOrigin: input.controlOrigin, browserOrigin: `https://${input.app}.fly.dev`, credential: `fzc_${"c".repeat(43)}` }); - expect(calls[2]?.[1]).toContain("/usr/local/bin/factorize-proxy-startup"); - expect(String(calls[3]?.[1])).toContain(`"type":"register-boot"`); - expect(String(calls[3]?.[1])).toContain(`"credential":"fzc_${"c".repeat(43)}"`); - }); - - it("requests a VM CSR signature through the private guest channel and verifies both bindings", async () => { - const calls: unknown[][] = []; - const spawnProcess = ((command: string, args: string[], options: { stdio: string[] }) => { - calls.push([command, args, options]); - const stdoutHandlers: Array<(chunk: Buffer) => void> = []; - const child: any = { pid: undefined, stdin: { end: (value: string) => { calls.push(["stdin", value]); } }, - stdout: { on: (_event: string, callback: (chunk: Buffer) => void) => stdoutHandlers.push(callback) }, - stderr: { on: () => undefined }, on: (event: string, callback: (code: number) => void) => { - if (event === "close") queueMicrotask(() => { stdoutHandlers.forEach(handler => handler(Buffer.from(JSON.stringify({ - bootEpoch: epoch, vmIdentity: "fly:job-1", certificate: "-----BEGIN CERTIFICATE-----cert", trustBundle: "-----BEGIN CERTIFICATE-----ca", - }) + "\n"))); callback(0); }); - }, kill: () => undefined }; - return child; - }) as any; - const guest = createFlyCredentialProxyGuest({ app: input.app, machine: machine.id, token: "server-token-fixture", spawnProcess }); - await expect(guest.issueVmCertificate({ bootEpoch: epoch, vmIdentity: "fly:job-1", csr: `-----BEGIN CERTIFICATE REQUEST-----\n${"A".repeat(120)}\n-----END CERTIFICATE REQUEST-----` })) - .resolves.toEqual({ certificate: "-----BEGIN CERTIFICATE-----cert", trustBundle: "-----BEGIN CERTIFICATE-----ca" }); - expect(calls[0]?.[1]).toContain("/usr/local/bin/factorize-proxy-certify-vm"); - expect(String(calls[1]?.[1])).toContain("\"vmIdentity\":\"fly:job-1\""); - await expect(guest.issueVmCertificate({ bootEpoch: epoch, vmIdentity: "fly:job-1", csr: "bad" })).rejects.toThrow("Invalid VM certificate provisioning request"); - }); -}); diff --git a/packages/api/test/fly-guest-transport.test.ts b/packages/api/test/fly-guest-transport.test.ts deleted file mode 100644 index 3b7fff7e..00000000 --- a/packages/api/test/fly-guest-transport.test.ts +++ /dev/null @@ -1,81 +0,0 @@ -import { EventEmitter } from "node:events"; -import { PassThrough } from "node:stream"; -import { readFile, writeFile } from "node:fs/promises"; -import { describe, expect, it } from "vitest"; -import { createFlyGuestTransport, FlyGuestError } from "../src/fly-guest-transport.js"; - -function fixture(handler: (args: string[]) => Promise<{ code: number | null; stdout?: string; stderr?: string }>) { - const calls: { executable: string; args: string[]; env: NodeJS.ProcessEnv; stdin: Buffer }[] = []; - const spawnProcess = ((executable: string, args: string[], options: any) => { - const call = { executable, args: [...args], env: options.env, stdin: Buffer.alloc(0) }; - calls.push(call); - const child = new EventEmitter() as any; - child.stdout = new PassThrough(); child.stderr = new PassThrough(); child.stdin = new PassThrough(); - child.stdin.on("data", (chunk: Buffer) => { call.stdin = Buffer.concat([call.stdin, chunk]); }); - child.kill = () => { queueMicrotask(() => child.emit("close", null)); return true; }; - void handler(args).then(result => { - if (result.stdout) child.stdout.write(result.stdout); - if (result.stderr) child.stderr.write(result.stderr); - queueMicrotask(() => child.emit("close", result.code)); - }); - return child; - }) as any; - return { calls, spawnProcess }; -} - -const base = { app: "fixture-app", machine: "machine-1", token: "redacted-test-token", timeoutMs: 1000, outputLimitBytes: 128, fileLimitBytes: 1024 }; - -describe("Fly guest command and file transport", () => { - it("passes arguments literally and returns a nonzero process exit", async () => { - const f = fixture(async () => ({ code: 17, stdout: "guest output", stderr: "guest error" })); - const transport = createFlyGuestTransport({ ...base, spawnProcess: f.spawnProcess }); - const result = await transport.run(["printf", "%s", "$(touch /tmp/not-run); ' quote"], "prompt bytes"); - expect(result).toEqual({ ok: false, exitCode: 17, stdout: "guest output", stderr: "guest error" }); - expect(f.calls[0].args).toEqual(["machine", "exec", "machine-1", "--app", "fixture-app", "--no-container", "--timeout", "1", "--", "printf", "%s", "$(touch /tmp/not-run); ' quote"]); - expect(f.calls[0].env.FLY_API_TOKEN).toBe(base.token); - expect(f.calls[0].stdin.toString()).toBe("prompt bytes"); - }); - - it("bounds the operation deadline and captured output", async () => { - const hanging = fixture(() => new Promise(() => undefined)); - const transport = createFlyGuestTransport({ ...base, timeoutMs: 15, spawnProcess: hanging.spawnProcess }); - await expect(transport.run(["sleep", "forever"])).rejects.toMatchObject({ kind: "timeout" }); - - const noisy = fixture(async () => ({ code: 0, stdout: "x".repeat(129) })); - await expect(createFlyGuestTransport({ ...base, spawnProcess: noisy.spawnProcess }).run(["emit"])).rejects.toMatchObject({ kind: "output_limit" }); - }); - - it("reports a disconnected guest transport distinctly", async () => { - const f = fixture(async () => ({ code: null })); - await expect(createFlyGuestTransport({ ...base, spawnProcess: f.spawnProcess }).run(["true"])).rejects.toMatchObject({ kind: "disconnect" }); - }); - - it("uploads and downloads bytes through SFTP argv without shell interpolation", async () => { - let uploaded = new Uint8Array(); - const downloaded = Buffer.from([0, 1, 2, 255]); - const f = fixture(async args => { - const mode = args[1]; - if (mode === "put") uploaded = new Uint8Array(await readFile(args[2])); - if (mode === "get") await writeFile(args[3], downloaded); - return { code: 0 }; - }); - const transport = createFlyGuestTransport({ ...base, spawnProcess: f.spawnProcess }); - await transport.upload("/tmp/file;$(id)", new Uint8Array([3, 4, 5])); - expect([...uploaded]).toEqual([3, 4, 5]); - expect(f.calls[0].args.slice(0, 2)).toEqual(["sftp", "put"]); - expect(f.calls[0].args[3]).toBe("/tmp/file;$(id)"); - expect([...await transport.download("/tmp/result")]).toEqual([0, 1, 2, 255]); - expect(f.calls[1].args.slice(0, 3)).toEqual(["sftp", "get", "/tmp/result"]); - }); - - it("rejects unsafe guest paths and oversized transfers", async () => { - const f = fixture(async () => ({ code: 0 })); - const transport = createFlyGuestTransport({ ...base, spawnProcess: f.spawnProcess }); - await expect(transport.download("/tmp/../secret")).rejects.toThrow(); - await expect(transport.upload("relative", new Uint8Array())).rejects.toThrow(); - await expect(transport.upload("/tmp/large", new Uint8Array(1025))).rejects.toMatchObject({ kind: "file_limit" } satisfies Partial); - expect(f.calls).toHaveLength(0); - expect(() => createFlyGuestTransport({ ...base, timeoutMs: 10 * 60_000 + 1 })).toThrow(/10 minutes/); - expect(() => createFlyGuestTransport({ ...base, outputLimitBytes: 16 * 1024 * 1024 + 1 })).toThrow(/supported bounds/); - }); -}); diff --git a/packages/api/test/fly-job-execution-backend.test.ts b/packages/api/test/fly-job-execution-backend.test.ts index 9ba8628d..660d2b43 100644 --- a/packages/api/test/fly-job-execution-backend.test.ts +++ b/packages/api/test/fly-job-execution-backend.test.ts @@ -20,13 +20,8 @@ function fixture() { upload: vi.fn(async (_path: string, _bytes: Uint8Array) => undefined), download: vi.fn(async (path: string) => new TextEncoder().encode(path.endsWith("results.json") ? '{"status":"succeeded"}' : "saved log")), }; - const proxyGuest = { - run: vi.fn(async () => ({ ok: true, exitCode: 0, stdout: "Run credential delivered to proxy memory\n", stderr: "" })), - issueVmCertificate: vi.fn(async () => ({ certificate: "-----BEGIN CERTIFICATE-----\npublic\n-----END CERTIFICATE-----", trustBundle: "-----BEGIN CERTIFICATE-----\nroot\n-----END CERTIFICATE-----" })), - }; - const backend = new FlyJobExecutionBackend({ app: "factorize-test", image: "ghcr.io/acme/code:v1", region: "iad", size: "shared-cpu-1x", machines, guest: () => guest, - proxyIdentity: "fly:factorize-test:proxy-1", proxyBootEpoch: "22222222-2222-4222-8222-222222222222", proxyGuest }); - return { backend, machines, guest, proxyGuest }; + const backend = new FlyJobExecutionBackend({ app: "factorize-test", image: "ghcr.io/acme/code:v1", region: "iad", size: "shared-cpu-1x", machines, guest: () => guest }); + return { backend, machines, guest }; } describe("Fly job execution backend", () => { @@ -90,7 +85,6 @@ describe("Fly job execution backend", () => { const result = await backend.launch({runId, prompt: "work", runIdentity: {backendOrigin: "https://factorize.example.com"}}); expect(result.observation.state).toBe("running"); expect(prepare.mock.invocationCallOrder[0]).toBeLessThan(f.machines.createMachine.mock.invocationCallOrder[0]!); - expect(f.proxyGuest.run).not.toHaveBeenCalled(); expect(f.guest.upload.mock.calls.map(([name]) => name)).toContain("/run/factorize-identity/proxy.mjs"); const config = f.guest.upload.mock.calls.find(([name]) => name === "/run/factorize-identity/config.json")!; expect(JSON.parse(new TextDecoder().decode(config[1]))).toEqual({runId, backendOrigin: "https://factorize.example.com", provider: "fly.io", localPort: 18180}); @@ -234,7 +228,7 @@ describe("Fly job execution backend", () => { expect(receipt.handle).toMatchObject({ backendKind: "fly", id: "factorize-test/machine-1" }); expect(receipt.observation).toMatchObject({ state: "failed", - detail: "Fly guest is missing python3, runuser, or the exedev user, or could not install the shared Factorize job launcher", + detail: "Fly guest is missing the shared launcher or vendor identity helper prerequisites", failure: { code: "launch_failed", reason: "Fly guest launch failed" }, }); expect(f.guest.run).toHaveBeenCalledOnce(); @@ -283,24 +277,6 @@ describe("Fly job execution backend", () => { expect(f.machines.destroyMachine).toHaveBeenCalledWith("factorize-test", "machine-1"); }); - it("delivers the scoped run credential to proxy memory before starting the VM and omits it from guest payload", async () => { - const f = fixture(); - const runId = "11111111-1111-4111-8111-111111111111"; - const credential = `fzt_run_${Buffer.from(runId).toString("base64url")}_${"R".repeat(43)}`; - await f.backend.launch({ runId, prompt: "task", runProxy: { targetOrigin: "https://factorize.example", credential } }); - expect(f.proxyGuest.run).toHaveBeenCalledOnce(); - expect(f.proxyGuest.run).toHaveBeenCalledWith(["/usr/local/bin/factorize-proxy-authorize-run"], expect.stringContaining(`"credential":"${credential}"`)); - expect(f.proxyGuest.run.mock.invocationCallOrder[0]).toBeLessThan(f.machines.startMachine.mock.invocationCallOrder[0]); - expect(f.proxyGuest.issueVmCertificate).toHaveBeenCalledWith(expect.objectContaining({ - bootEpoch: "22222222-2222-4222-8222-222222222222", vmIdentity: "fly:factorize-test:machine-1", - })); - expect(f.guest.upload).toHaveBeenCalledWith("/home/exedev/.factorize-job/proxy/tunnel.mjs", expect.any(Uint8Array)); - expect(f.guest.run.mock.calls.some(([command]) => command.includes("FACTORIZE_PROXY_URL=http://127.0.0.1:18180"))).toBe(true); - const payload = String(f.guest.run.mock.calls.at(-1)?.[1] ?? ""); - expect(payload).not.toContain(credential); - expect(payload).toContain(runId); - }); - it("destroys a stopped Machine after confirming provider state", async () => { const f = fixture(); f.machines.inspectMachine.mockResolvedValue({ ...machine, state: "stopped" }); diff --git a/packages/api/src/docker-job-infrastructure.ts b/packages/api/test/helpers/docker-job-infrastructure.ts similarity index 95% rename from packages/api/src/docker-job-infrastructure.ts rename to packages/api/test/helpers/docker-job-infrastructure.ts index 72313d33..d9af6b00 100644 --- a/packages/api/src/docker-job-infrastructure.ts +++ b/packages/api/test/helpers/docker-job-infrastructure.ts @@ -1,5 +1,5 @@ import { spawn } from "node:child_process"; -import type { JobMachines, JobGuest } from "./machine-job-execution-backend"; +import type { JobMachines, JobGuest } from "../../src/machine-job-execution-backend"; /** Host-only test infrastructure. Never import this module into a Worker runner. */ export function createDockerJobInfrastructure(options: { testMode: true; network: string; namespace: string; additionalNetworks?: string[]; mounts?: { source: string; target: string }[]; publishBrowserPort?: boolean; beforeDestroy?: (id: string) => Promise; observeGuestInput?: (command: readonly string[], input?: string | Uint8Array) => void }) { @@ -58,7 +58,7 @@ export function createDockerJobInfrastructure(options: { testMode: true; network } const data = JSON.parse(observed.stdout)[0]; if (data.Config.Labels[label] !== options.namespace) throw new Error("Container belongs to another namespace"); - return { id, config: { metadata: Object.fromEntries(Object.entries(data.Config.Labels).filter(([key]) => key.startsWith("factorize_"))) as Record }, state: data.State.Running ? "started" : data.State.Status === "created" ? "created" : "stopped" }; + return { id, name: data.Name.replace(/^\//, ""), config: { metadata: Object.fromEntries(Object.entries(data.Config.Labels).filter(([key]) => key.startsWith("factorize_"))) as Record }, state: data.State.Running ? "started" : data.State.Status === "created" ? "created" : "stopped" }; } const machines: JobMachines = { async findMachineByOperationId(_app, operationId) { diff --git a/packages/api/test/loading.postgres.test.ts b/packages/api/test/loading.postgres.test.ts index d02634aa..42b68040 100644 --- a/packages/api/test/loading.postgres.test.ts +++ b/packages/api/test/loading.postgres.test.ts @@ -5,7 +5,7 @@ import { IdentityRepository } from "../src/postgres/identity-repository"; import { PostgresJobRepository } from "../src/postgres/job-repository"; import { JobSummaryRepository } from "../src/postgres/job-summary-repository"; import { ConnectionRepository } from "../src/postgres/connection-repository"; -import { EncryptedIntegrationRepository } from "../src/postgres/encrypted-integration-repository"; +import { CredentialRepository } from "../src/postgres/credential-repository"; import { FlyConnectionRepository } from "../src/postgres/fly-connection-repository"; import { FlyExecutionConfigurationRepository } from "../src/postgres/fly-execution-configuration-repository"; import { GitHubRepository } from "../src/postgres/github-repository"; @@ -120,8 +120,8 @@ describe.skipIf(!url)("request loading with PostgreSQL", () => { it("persists explicit integration and model selections and snapshots them at invocation", async () => { const service = new ApiService(env, auth); const write = async (kind: "bearer" | "model", name: string, owner = tenantId) => { - const repository = new EncryptedIntegrationRepository(db, owner, env.CREDENTIAL_ENCRYPTION_KEY), id = crypto.randomUUID(); - await repository.write({ id, idempotencyKey: crypto.randomUUID(), expectedRevision: await repository.revision(), operation: "upsert", kind, name, origin: kind === "bearer" ? "https://api.example.test" : null, description: null, encryptedPayload: await encrypt("fixture", env.CREDENTIAL_ENCRYPTION_KEY) }); + const repository = new CredentialRepository(db, owner, env.CREDENTIAL_ENCRYPTION_KEY), id = crypto.randomUUID(); + await repository.write({ id, idempotencyKey: crypto.randomUUID(), expectedRevision: await repository.revision(), operation: "upsert", kind, name, origin: kind === "bearer" ? "https://api.example.test" : null, description: null, ...(kind === "bearer" ? {managedSecret: "fixture"} : {managedModelPayload: JSON.stringify({OPENAI_API_KEY:"fixture-model-key"})}) }); return id; }; const bearerA = await write("bearer", "Tools A"), bearerB = await write("bearer", "Tools B"); diff --git a/packages/api/test/model-device-auth.postgres.test.ts b/packages/api/test/model-device-auth.postgres.test.ts new file mode 100644 index 00000000..23e10f74 --- /dev/null +++ b/packages/api/test/model-device-auth.postgres.test.ts @@ -0,0 +1,46 @@ +import {describe,expect,it,vi,afterEach} from "vitest"; +import {loadingFixture} from "./helpers/loading-fixture"; +import {CredentialRepository} from "../src/postgres/credential-repository"; +import {modelDeviceAuthorization,ModelAccountUnavailable} from "../src/model-device-auth"; +vi.mock("cloudflare:workers",()=>({WorkerEntrypoint:class{},DurableObject:class{}})); +vi.mock("@cloudflare/workers-oauth-provider",()=>({OAuthProvider:class{},AuthorizationError:class{},getOAuthApi:vi.fn()})); +const url=process.env.AUTH_TEST_DATABASE_URL; +afterEach(()=>vi.unstubAllGlobals()); +describe.skipIf(!url)("server managed model device authorization",{timeout:60_000},()=>{ + async function fixture(){const f=await loadingFixture(url!),id=crypto.randomUUID(),repo=new CredentialRepository(f.db,f.tenantId,f.env.CREDENTIAL_ENCRYPTION_KEY);await repo.write({id,kind:"model",name:"ChatGPT",origin:null,description:null,expectedRevision:0,idempotencyKey:crypto.randomUUID(),operation:"upsert",managedModelPayload:"{}"});return{...f,id,repo,call:(action:"authorize"|"status"|"cancel")=>modelDeviceAuthorization(f.env,f.auth,id,action),due:()=>f.db.pool.query("UPDATE app.model_device_authorizations SET next_poll_at=now()-interval '1 second' WHERE tenant_id=$1",[f.tenantId])};} + it("keeps private challenges encrypted, throttles polling, verifies PKCE and stores tokens without returning them",async()=>{ + const f=await fixture();try{ + const verifier="fixture-verifier",digest=Buffer.from(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(verifier))).toString("base64url"); + const fetcher=vi.fn(async(input:RequestInfo|URL,init?:RequestInit)=>{ + expect(init?.redirect).toBe("error"); + if(String(input).endsWith("/usercode"))return Response.json({device_auth_id:"private-device-id",user_code:"PUBLIC-CODE",interval:1}); + if(String(input).endsWith("/deviceauth/token"))return Response.json({authorization_code:"private-code",code_verifier:verifier,code_challenge:digest}); + expect(String(input)).toBe("https://auth.openai.com/oauth/token"); + expect(new URLSearchParams(String(init?.body)).get("code_verifier")).toBe(verifier); + return Response.json({access_token:"private-access",refresh_token:"private-refresh",id_token:"private-id"}); + });vi.stubGlobal("fetch",fetcher); + const pending=await f.call("authorize");expect(pending).toMatchObject({state:"pending",userCode:"PUBLIC-CODE",verificationUrl:"https://auth.openai.com/codex/device"}); + expect(await f.call("authorize")).toEqual(pending);expect(await f.call("status")).toEqual(pending);expect(fetcher).toHaveBeenCalledTimes(1); + const stored=(await f.db.pool.query("SELECT encrypted_payload FROM app.model_device_authorizations WHERE tenant_id=$1",[f.tenantId])).rows[0].encrypted_payload;expect(stored).not.toContain("private-device-id"); + await f.due();expect(await f.call("status")).toEqual({state:"authorized"}); + const credential=JSON.parse((await f.repo.managedCredential(f.id,"model"))!.payload);expect(credential.tokens).toMatchObject({access_token:"private-access",refresh_token:"private-refresh"}); + expect(JSON.stringify(await f.repo.metadata())).not.toContain("private-access");expect((await f.db.pool.query("SELECT 1 FROM app.model_device_authorizations WHERE tenant_id=$1",[f.tenantId])).rowCount).toBe(0); + await expect(modelDeviceAuthorization(f.env,{...f.auth,tenantId:f.otherTenant},f.id,"status")).rejects.toBeInstanceOf(ModelAccountUnavailable); + }finally{await f.cleanup();} + }); + it("handles pending, bad PKCE, cancel, expiry, rotation and disconnect without overwriting a credential",async()=>{ + const f=await fixture();try{ + let mode="pending"; + const fetcher=vi.fn(async(input:RequestInfo|URL)=>String(input).endsWith("/usercode")?Response.json({device_auth_id:"private",user_code:"CODE",interval:1}):mode==="pending"?new Response(null,{status:403}):Response.json({authorization_code:"code",code_verifier:"wrong",code_challenge:"mismatch"}));vi.stubGlobal("fetch",fetcher); + await f.call("authorize");await f.due();expect((await f.call("status")).state).toBe("pending"); + mode="bad";await f.due();expect(await f.call("status")).toEqual({state:"failed"});expect((await f.repo.managedCredential(f.id,"model"))!.payload).toBe("{}"); + await f.call("authorize");expect(await f.call("cancel")).toEqual({state:"canceled"});expect(await f.call("status")).toEqual({state:"idle"}); + await f.call("authorize");await f.db.pool.query("UPDATE app.model_device_authorizations SET expires_at=now()-interval '1 second'");expect(await f.call("status")).toEqual({state:"expired"}); + await f.call("authorize");await f.repo.write({id:f.id,kind:"model",name:"ChatGPT",origin:null,description:null,expectedRevision:await f.repo.revision(),idempotencyKey:crypto.randomUUID(),operation:"upsert",managedModelPayload:'{"OPENAI_API_KEY":"replacement"}'}); + expect(await f.call("status")).toEqual({state:"authorized"}); + await f.repo.write({id:f.id,kind:"model",name:"ChatGPT",origin:null,description:null,expectedRevision:await f.repo.revision(),idempotencyKey:crypto.randomUUID(),operation:"delete"}); + await expect(f.call("status")).rejects.toBeInstanceOf(ModelAccountUnavailable); + expect(fetcher.mock.calls.every(([url])=>String(url).startsWith("https://auth.openai.com/"))).toBe(true); + }finally{await f.cleanup();} + }); +}); diff --git a/packages/api/test/proxy-browser-capability.test.ts b/packages/api/test/proxy-browser-capability.test.ts deleted file mode 100644 index 3729c98a..00000000 --- a/packages/api/test/proxy-browser-capability.test.ts +++ /dev/null @@ -1,25 +0,0 @@ -import { describe, expect, it } from "vitest"; -import { generateKeyPairSync, verify } from "node:crypto"; -import { issueModelAccountCapability } from "../src/proxy-browser-capability"; - -describe("proxy browser capabilities", () => { - it("signs an account/action/origin/boot-bound one-minute EdDSA token", async () => { - const { privateKey, publicKey } = generateKeyPairSync("ed25519"); - const token = await issueModelAccountCapability({ - privateKeyPem: privateKey.export({ type: "pkcs8", format: "pem" }).toString(), - proxyIdentity: "fly:proxy:machine-1", ownerId: "11111111-1111-4111-8111-111111111111", - accountId: "22222222-2222-4222-8222-222222222222", action: "authorize", - appOrigin: "https://factorize.example", generation: "33333333-3333-4333-8333-333333333333", - now: 1_900_000_000, jti: "one-use-fixture-nonce-123456", - }); - const [header, claims, signature] = token.split("."); - expect(JSON.parse(Buffer.from(header!, "base64url").toString())).toEqual({ alg: "EdDSA", typ: "JWT" }); - expect(JSON.parse(Buffer.from(claims!, "base64url").toString())).toMatchObject({ - iss: "factorize", aud: "fly:proxy:machine-1", sub: "11111111-1111-4111-8111-111111111111", - action: "model-account:authorize", accountId: "22222222-2222-4222-8222-222222222222", - origin: "https://factorize.example", generation: "33333333-3333-4333-8333-333333333333", - exp: 1_900_000_060, jti: "one-use-fixture-nonce-123456", - }); - expect(verify(null, Buffer.from(`${header}.${claims}`), publicKey, Buffer.from(signature!, "base64url"))).toBe(true); - }); -}); diff --git a/packages/api/test/proxy-control-repository.test.ts b/packages/api/test/proxy-control-repository.test.ts deleted file mode 100644 index b622e0df..00000000 --- a/packages/api/test/proxy-control-repository.test.ts +++ /dev/null @@ -1,54 +0,0 @@ -import { describe, expect, it, vi } from "vitest"; -import { ProxyControlRepository } from "../src/postgres/proxy-control-repository"; - -function database(query: ReturnType, transactionQuery = query) { - return { pool: { query }, transaction: (work: (client: any) => Promise) => work({ query: transactionQuery }) } as any; -} - -describe("dedicated credential proxy control identity", () => { - it("issues a scoped one-time secret and stores only its digest", async () => { - const query = vi.fn().mockResolvedValue({ rows: [], rowCount: 1 }); - const repository = new ProxyControlRepository(database(query)); - const token = await repository.provisionCredential("11111111-1111-4111-8111-111111111111", "proxy-a", "22222222-2222-4222-8222-222222222222"); - expect(token).toMatch(/^fzc_[A-Za-z0-9_-]{43}$/); - const stored = query.mock.calls[0][1][3] as Buffer; - expect(stored).toBeInstanceOf(Buffer); - expect(stored.toString()).not.toContain(token); - expect(stored.byteLength).toBe(32); - }); - - it("authenticates only a live credential and never accepts a guest run token", async () => { - const query = vi.fn().mockResolvedValue({ rows: [{ tenant_id: "tenant-a", proxy_identity: "proxy-a" }], rowCount: 1 }); - const repository = new ProxyControlRepository(database(query)); - expect(await repository.authenticate("fzt_run_" + "a".repeat(43))).toBeNull(); - expect(query).not.toHaveBeenCalled(); - expect(await repository.authenticate("fzc_" + "a".repeat(43))).toEqual({ tenantId: "tenant-a", proxyIdentity: "proxy-a" }); - }); - - it("registers a fresh boot for its credential identity and rejects revoked, disabled, or mismatched identities", async () => { - const identity = { tenant_id: "tenant-a", proxy_identity: "proxy-a" }; - const credentialQuery = vi.fn().mockResolvedValue({ rows: [identity], rowCount: 1 }); - const stateQuery = vi.fn().mockResolvedValue({ rows: [{ tenant_id: identity.tenant_id }], rowCount: 1 }); - const repository = new ProxyControlRepository(database(vi.fn(), vi.fn())); - const tx = { query: vi.fn().mockImplementation((sql: string) => sql.includes("credential_proxy_control_credentials") ? credentialQuery() : sql.includes("INSERT INTO app.credential_proxy_states") ? stateQuery() : Promise.resolve({ rows: [], rowCount: 1 })) }; - (repository as any).database = { transaction: (work: (client: any) => Promise) => work(tx) }; - const epoch = "22222222-2222-4222-8222-222222222222"; - const registration = await repository.registerBoot("fzc_" + "a".repeat(43), epoch, "https://proxy.example"); - expect(registration).toMatchObject({ tenantId: identity.tenant_id, proxyIdentity: identity.proxy_identity, bootEpoch: epoch }); - expect(registration?.controlCredential).toMatch(/^fzc_[A-Za-z0-9_-]{43}$/); - expect(tx.query.mock.calls.map(call => call[0])).toHaveLength(5); - expect(tx.query.mock.calls[0][0]).toContain("boot_epoch=$2 AND revoked_at IS NULL AND consumed_at IS NULL"); - expect(tx.query.mock.calls[2][0]).toContain("consumed_at=now()"); - expect(tx.query.mock.calls[3][0]).toContain("boot_epoch<>$3"); - expect(tx.query.mock.calls[4][0]).toContain("credential_proxy_browser_pairings"); - credentialQuery.mockResolvedValueOnce({ rows: [], rowCount: 0 }); - expect(await repository.registerBoot("fzc_" + "a".repeat(43), epoch, "https://proxy.example")).toBeNull(); - }); - - it("rejects malformed boot epochs before opening a transaction", async () => { - const transaction = vi.fn(); - const repository = new ProxyControlRepository({ transaction, pool: { query: vi.fn() } } as any); - await expect(repository.registerBoot("fzc_" + "a".repeat(43), "old-boot", "https://proxy.example")).rejects.toThrow("bootEpoch must be a UUID"); - expect(transaction).not.toHaveBeenCalled(); - }); -}); diff --git a/packages/api/test/proxy-control.test.ts b/packages/api/test/proxy-control.test.ts deleted file mode 100644 index a146545a..00000000 --- a/packages/api/test/proxy-control.test.ts +++ /dev/null @@ -1,226 +0,0 @@ -import { describe, expect, it, vi } from "vitest"; -import { proxyControlFetch } from "../src/proxy-control"; -import { encrypt } from "../src/crypto"; - -const token = `fzc_${"A".repeat(43)}`; -const bootEpoch = "22222222-2222-4222-8222-222222222222"; -const runId = "33333333-3333-4333-8333-333333333333"; -const runCredential = `fzt_run_${Buffer.from(runId).toString("base64url")}_${"R".repeat(43)}`; - -function envFor({ credentialFound = true, stateSaved = true } = {}) { - const transactionQuery = vi.fn(async (sql: string) => { - if (sql.includes("credential_proxy_control_credentials")) return { rows: credentialFound ? [{ tenant_id: "11111111-1111-4111-8111-111111111111", proxy_identity: "proxy-fixture" }] : [], rowCount: credentialFound ? 1 : 0 }; - if (sql.includes("INSERT INTO app.credential_proxy_states")) return { rows: stateSaved ? [{ tenant_id: "11111111-1111-4111-8111-111111111111" }] : [], rowCount: stateSaved ? 1 : 0 }; - return { rows: [], rowCount: 1 }; - }); - const query = vi.fn(async (sql: string) => sql.includes("SELECT user_id FROM app.members") ? { rows: [{ user_id: "11111111-1111-4111-8111-111111111111" }], rowCount: 1 } : sql.includes("proxy_token_digest") - ? { rows: credentialFound ? [{ tenant_id: "11111111-1111-4111-8111-111111111111", proxy_identity: "proxy-fixture", boot_epoch: bootEpoch }] : [], rowCount: credentialFound ? 1 : 0 } - : sql.includes("SET unlocked=$3") ? { rows: [], rowCount: credentialFound ? 1 : 0 } - : sql.includes("FROM app.run_credentials") - ? { rows: credentialFound ? [{ tenant_id: "11111111-1111-4111-8111-111111111111", user_id: "owner-fixture", session_version: 1, job_id: "job-fixture", scopes: ["integrations:read"] }] : [], rowCount: credentialFound ? 1 : 0 } - : { rows: [], rowCount: 0 }); - return { DATABASE: { pool: { query }, transaction: (work: (client: any) => Promise) => work({ query: transactionQuery }) }, transactionQuery, query } as any; -} - -function request({ authorization, body = { bootEpoch, browserOrigin: "https://proxy.example" }, method = "POST", path = "/internal/credential-proxy/register-boot" }: { authorization?: string; body?: unknown; method?: string; path?: string } = {}) { - return new Request(`https://factorize.example${path}`, { method, headers: { "Content-Type": "application/json", ...(authorization ? { Authorization: authorization } : {}) }, body: method === "POST" ? JSON.stringify(body) : undefined }); -} - -describe("dedicated proxy boot registration endpoint", () => { - it("binds registration to the proxy identity owned by its distinct control credential", async () => { - const env = envFor(); - const response = await proxyControlFetch(request({ authorization: `Bearer ${token}` }), env); - expect(response.status).toBe(200); - expect(await response.json()).toMatchObject({ registered: true, tenantId: "11111111-1111-4111-8111-111111111111", proxyIdentity: "proxy-fixture", bootEpoch, controlCredential: expect.stringMatching(/^fzc_[A-Za-z0-9_-]{43}$/) }); - expect(env.transactionQuery.mock.calls.map((call: any[]) => call[0])).toHaveLength(5); - expect(env.transactionQuery.mock.calls[0][0]).toContain("boot_epoch=$2 AND revoked_at IS NULL AND consumed_at IS NULL"); - expect(env.transactionQuery.mock.calls[2][0]).toContain("consumed_at=now()"); - expect(env.transactionQuery.mock.calls[4][0]).toContain("credential_proxy_browser_pairings"); - }); - - it("rejects guest job tokens before database access", async () => { - const env = envFor(); - const response = await proxyControlFetch(request({ authorization: `Bearer fzt_run_${"B".repeat(32)}` }), env); - expect(response.status).toBe(401); - expect(env.transactionQuery).not.toHaveBeenCalled(); - }); - - it("accepts runtime status only from the current registered proxy credential", async () => { - const env = envFor(); - const response = await proxyControlFetch(request({ authorization: `Bearer ${token}`, path: "/internal/credential-proxy/status", body: { bootEpoch, unlocked: true } }), env); - expect(response.status).toBe(200); - expect(await response.json()).toEqual({ updated: true }); - expect(env.query.mock.calls.some((call: any[]) => call[0].includes("SET unlocked=$3") && call[0].includes("boot_epoch=$4"))).toBe(true); - expect((await proxyControlFetch(request({ authorization: `Bearer ${token}`, path: "/internal/credential-proxy/status", body: { bootEpoch, unlocked: "yes" } }), env)).status).toBe(400); - }); - - it("revokes delivered proxy-memory credentials for runs that ended before first tunnel enrollment", async () => { - const env = envFor(); - env.query.mockImplementation(async (sql: string) => sql.includes("proxy_token_digest") - ? { rows: [{ tenant_id: "11111111-1111-4111-8111-111111111111", proxy_identity: "proxy-fixture", boot_epoch: bootEpoch }], rowCount: 1 } - : sql.includes("FROM app.credential_run_grants") - ? { rows: [{ run_id: runId }], rowCount: 1 } - : { rows: [], rowCount: 0 }); - const response = await proxyControlFetch(request({ - authorization: `Bearer ${token}`, - path: "/internal/credential-proxy/revocations", - body: { bootEpoch }, - }), env); - expect(response.status).toBe(200); - expect(await response.json()).toEqual({ revokedRunIds: [runId], activeModelAccountIds: [], lockProxy: true }); - const revocationsQuery = env.query.mock.calls.find((call: any[]) => call[0].includes("FROM app.credential_run_grants"))?.[0] as string; - expect(revocationsQuery).toContain("JOIN app.job_runs"); - expect(revocationsQuery).toContain("r.state IN ('succeeded','failed','stopped')"); - }); - - it("rejects revoked credentials, disabled proxy identities and tenant or proxy substitution", async () => { - for (const env of [envFor({ credentialFound: false }), envFor({ stateSaved: false })]) { - const response = await proxyControlFetch(request({ authorization: `Bearer ${token}` }), env); - expect(response.status).toBe(403); - } - }); - - it("validates the endpoint, method and exact boot payload", async () => { - const env = envFor(); - expect((await proxyControlFetch(new Request("https://factorize.example/internal/credential-proxy/register-boot", { method: "GET" }), env)).status).toBe(405); - expect((await proxyControlFetch(request({ authorization: `Bearer ${token}`, body: { bootEpoch, tenantId: "attacker-tenant" } }), env)).status).toBe(400); - expect(env.transactionQuery).not.toHaveBeenCalled(); - }); - - it("bounds registration payloads before parsing", async () => { - const env = envFor(); - const response = await proxyControlFetch(request({ authorization: `Bearer ${token}`, body: { bootEpoch, padding: "x".repeat(2_000) } }), env); - expect(response.status).toBe(413); - expect(env.transactionQuery).not.toHaveBeenCalled(); - }); - - it("issues a short-lived enrollment only through the registered proxy identity", async () => { - const env = envFor(); - env.transactionQuery.mockImplementation(async (sql: string) => sql.includes("SELECT g.grant_revision") - ? { rows: [{ grant_revision: 3 }], rowCount: 1 } - : sql.includes("INSERT INTO app.credential_run_grants") - ? { rows: [{ grant_revision: 3 }], rowCount: 1 } - : { rows: [], rowCount: 1 }); - const response = await proxyControlFetch(request({ - authorization: `Bearer ${token}`, - path: "/internal/credential-proxy/enroll", - body: { runId, vmIdentity: "fly:vm-123", runCredential }, - }), env); - expect(response.status).toBe(200); - expect(await response.json()).toMatchObject({ grantRevision: 3, enrollmentId: expect.any(String), token: expect.any(String) }); - expect(env.query).toHaveBeenCalled(); - expect(env.query.mock.calls.some((call: any[]) => call[0].includes("FROM app.run_credentials"))).toBe(true); - expect(env.transactionQuery.mock.calls.some((call: any[]) => call[0].includes("INSERT INTO app.credential_run_grants"))).toBe(true); - expect(env.transactionQuery.mock.calls[0][0]).toContain("JOIN app.credential_proxy_states"); - }); - - it("refuses enrollment when the run credential is absent, invalid, cross-tenant, mismatched, or lacks integration scope", async () => { - for (const [body, expectedStatus] of [ - [{ runId, vmIdentity: "fly:vm-123" }, 400], - [{ runId, vmIdentity: "fly:vm-123", runCredential: "fzt_run_invalid" }, 403], - [{ runId: "44444444-4444-4444-8444-444444444444", vmIdentity: "fly:vm-123", runCredential }, 403], - ] as const) { - const env = envFor(); - expect((await proxyControlFetch(request({ authorization: `Bearer ${token}`, path: "/internal/credential-proxy/enroll", body }), env)).status).toBe(expectedStatus); - expect(env.transactionQuery).not.toHaveBeenCalled(); - } - const crossTenant = envFor(); - crossTenant.query.mockImplementation(async (sql: string) => sql.includes("proxy_token_digest") - ? { rows: [{ tenant_id: "other-tenant", proxy_identity: "proxy-fixture", boot_epoch: bootEpoch }], rowCount: 1 } - : { rows: [], rowCount: 0 }); - expect((await proxyControlFetch(request({ authorization: `Bearer ${token}`, path: "/internal/credential-proxy/enroll", body: { runId, vmIdentity: "fly:vm-123", runCredential } }), crossTenant)).status).toBe(403); - const noScope = envFor(); - noScope.query.mockImplementation(async (sql: string) => sql.includes("proxy_token_digest") - ? { rows: [{ tenant_id: "11111111-1111-4111-8111-111111111111", proxy_identity: "proxy-fixture", boot_epoch: bootEpoch }], rowCount: 1 } - : sql.includes("FROM app.run_credentials") - ? { rows: [{ tenant_id: "11111111-1111-4111-8111-111111111111", user_id: "owner-fixture", session_version: 1, job_id: "job-fixture", scopes: ["runs:read"] }], rowCount: 1 } - : { rows: [], rowCount: 0 }); - expect((await proxyControlFetch(request({ authorization: `Bearer ${token}`, path: "/internal/credential-proxy/enroll", body: { runId, vmIdentity: "fly:vm-123", runCredential } }), noScope)).status).toBe(403); - expect(noScope.transactionQuery).not.toHaveBeenCalled(); - }); - - it("consumes enrollment against the authenticated proxy boot and rejects untrusted extra bindings", async () => { - const env = envFor(); - env.transactionQuery.mockImplementation(async (sql: string) => sql.includes("UPDATE app.credential_run_enrollments") - ? { rows: [{ id: "44444444-4444-4444-8444-444444444444", grant_revision: 3 }], rowCount: 1 } - : { rows: [], rowCount: 1 }); - const accepted = await proxyControlFetch(request({ - authorization: `Bearer ${token}`, - path: "/internal/credential-proxy/consume-enrollment", - body: { runId: "33333333-3333-4333-8333-333333333333", vmIdentity: "fly:vm-123", enrollmentToken: "e".repeat(43) }, - }), env); - expect(accepted.status).toBe(200); - expect(await accepted.json()).toMatchObject({ consumed: true, binding: { bootEpoch, proxyIdentity: "proxy-fixture", vmIdentity: "fly:vm-123" } }); - const rejected = await proxyControlFetch(request({ authorization: `Bearer ${token}`, path: "/internal/credential-proxy/enroll", body: { runId: "33333333-3333-4333-8333-333333333333", vmIdentity: "fly:vm-123", tenantId: "other" } }), env); - expect(rejected.status).toBe(400); - }); - - it("returns only the current run's selected user-encrypted bearer and model records to its registered proxy", async () => { - const integrationId = "55555555-5555-4555-8555-555555555555"; - const modelAccountId = "77777777-7777-4777-8777-777777777777"; - const key = Buffer.alloc(32, 7).toString("base64"); - const env = envFor(); - env.CREDENTIAL_ENCRYPTION_KEY = key; - env.query.mockImplementation(async (sql: string, values: unknown[] = []) => { - if (sql.includes("SELECT user_id FROM app.members")) return { rows: [{ user_id: "11111111-1111-4111-8111-111111111111" }], rowCount: 1 }; - if (sql.includes("proxy_token_digest")) return { rows: [{ tenant_id: "11111111-1111-4111-8111-111111111111", proxy_identity: "proxy-fixture", boot_epoch: bootEpoch }], rowCount: 1 }; - if (sql.includes("FROM app.runs r")) return { rows: [{ execution_config: { portableIntegrationIds: [integrationId, "99999999-9999-4999-8999-999999999999"], modelAccess: "portable", modelAccountId, githubInstallationIds: [123], linearConnectionId: "linear" }, grant_revision: 3 }], rowCount: 1 }; - if (sql.includes("FROM app.integration_records")) return values[1] === "bearer" ? { rows: [ - { id: integrationId, kind: "bearer", name: "selected", origin: "https://api.example", description: null, revision: 4, encrypted_payload: await encrypt("user-ciphertext", key), deleted_at: null }, - { id: "99999999-9999-4999-8999-999999999999", kind: "bearer", name: "deleted", origin: "https://deleted.example", description: null, revision: 8, encrypted_payload: null, deleted_at: new Date("2026-01-01T00:00:00Z") }, - { id: "66666666-6666-4666-8666-666666666666", kind: "bearer", name: "not-selected", origin: "https://other.example", description: null, revision: 5, encrypted_payload: await encrypt("other-ciphertext", key) }, - ], rowCount: 2 } : { rows: [ - { id: modelAccountId, kind: "model", name: "selected-model", origin: null, description: "fixture account", revision: 6, encrypted_payload: await encrypt("model-user-ciphertext", key) }, - { id: "88888888-8888-4888-8888-888888888888", kind: "model", name: "other-model", origin: null, description: null, revision: 7, encrypted_payload: await encrypt("other-model-ciphertext", key) }, - ], rowCount: 2 }; - return { rows: [], rowCount: 0 }; - }); - const response = await proxyControlFetch(request({ - authorization: `Bearer ${token}`, - path: "/internal/credential-proxy/integration-snapshot", - body: { runId, grantRevision: 3 }, - }), env); - expect(response.status).toBe(200); - expect(await response.json()).toEqual({ ownerId: "11111111-1111-4111-8111-111111111111", records: [ - { id: integrationId, kind: "bearer", name: "selected", origin: "https://api.example", description: null, revision: 4, encryptedPayload: "user-ciphertext", deletedAt: null }, - { id: "99999999-9999-4999-8999-999999999999", kind: "bearer", name: "deleted", origin: "https://deleted.example", description: null, revision: 8, encryptedPayload: null, deletedAt: "2026-01-01T00:00:00.000Z" }, - ], modelAccount: { id: modelAccountId, kind: "model", name: "selected-model", origin: null, description: "fixture account", revision: 6, encryptedPayload: "model-user-ciphertext" }, providerCredentials: { githubInstallations: [{ installationId: 123, available: false }], linearConnection: { connectionId: "linear", available: false } } }); - expect(env.query.mock.calls.map((call: any[]) => call[0])).toEqual(expect.arrayContaining([expect.stringContaining("grant_revision=$5"), expect.stringContaining("FROM app.integration_records")])); - }); - - it("returns a null model selection when the active run's selected account was disconnected", async () => { - const env = envFor(); - env.query.mockImplementation(async (sql: string) => { - if (sql.includes("SELECT user_id FROM app.members")) return { rows: [{ user_id: "11111111-1111-4111-8111-111111111111" }], rowCount: 1 }; - if (sql.includes("proxy_token_digest")) return { rows: [{ tenant_id: "11111111-1111-4111-8111-111111111111", proxy_identity: "proxy-fixture", boot_epoch: bootEpoch }], rowCount: 1 }; - if (sql.includes("FROM app.runs r")) return { rows: [{ execution_config: { portableIntegrationIds: [], modelAccess: "portable", modelAccountId: "77777777-7777-4777-8777-777777777777", githubInstallationIds: [] }, grant_revision: 3 }], rowCount: 1 }; - if (sql.includes("FROM app.integration_records")) return { rows: [], rowCount: 0 }; - return { rows: [], rowCount: 0 }; - }); - const response = await proxyControlFetch(request({ authorization: `Bearer ${token}`, path: "/internal/credential-proxy/integration-snapshot", body: { runId, grantRevision: 3 } }), env); - expect(response.status).toBe(200); - expect(await response.json()).toMatchObject({ modelAccount: null, providerCredentials: { githubInstallations: [], linearConnection: null } }); - }); - - it("returns durable revoked runs only for the authenticated current proxy boot", async () => { - const env = envFor(); - env.query.mockImplementation(async (sql: string) => sql.includes("proxy_token_digest") - ? { rows: [{ tenant_id: "11111111-1111-4111-8111-111111111111", proxy_identity: "proxy-fixture", boot_epoch: bootEpoch }], rowCount: 1 } - : sql.includes("integration_records") ? { rows: [], rowCount: 0 } : { rows: [{ run_id: runId }], rowCount: 1 }); - const response = await proxyControlFetch(request({ - authorization: `Bearer ${token}`, - path: "/internal/credential-proxy/revocations", - body: { bootEpoch }, - }), env); - expect(response.status).toBe(200); - expect(await response.json()).toEqual({ revokedRunIds: [runId], activeModelAccountIds: [], lockProxy: true }); - expect(env.query.mock.calls[1][0]).toContain("revoked_at IS NOT NULL"); - expect(env.query.mock.calls[1][1]).toEqual(["11111111-1111-4111-8111-111111111111", "proxy-fixture", bootEpoch]); - const stale = await proxyControlFetch(request({ - authorization: `Bearer ${token}`, - path: "/internal/credential-proxy/revocations", - body: { bootEpoch: "44444444-4444-4444-8444-444444444444" }, - }), env); - expect(stale.status).toBe(400); - }); -}); diff --git a/packages/api/test/proxy-launch-policy.test.ts b/packages/api/test/proxy-launch-policy.test.ts deleted file mode 100644 index 48952ca5..00000000 --- a/packages/api/test/proxy-launch-policy.test.ts +++ /dev/null @@ -1,42 +0,0 @@ -import { describe, expect, it } from "vitest"; -import { proxyLaunchDecision, ProxyLaunchBlockedError, requireProxyLaunch, type ProxyLaunchJob, type ProxyLaunchState } from "../src/proxy-launch-policy"; - -const stopped: ProxyLaunchState = { enabled: true, running: false, unlocked: false, pendingChanges: false }; -const locked: ProxyLaunchState = { enabled: true, running: true, unlocked: false, pendingChanges: false }; -const unlocked: ProxyLaunchState = { enabled: true, running: true, unlocked: true, pendingChanges: false }; -const flyCode: ProxyLaunchJob = { executionProvider: "fly", executionType: "code" }; - -describe("GEN-2824 proxy launch policy", () => { - it("starts an enabled proxy locked for Fly code jobs with no user credential grants", () => { - expect(proxyLaunchDecision(flyCode, stopped)).toEqual({ kind: "start_locked" }); - }); - - it("allows code-only Factorize access while the proxy is running and locked", () => { - expect(proxyLaunchDecision(flyCode, locked)).toEqual({ kind: "allow" }); - }); - - it.each([ - { label: "portable tools", job: { ...flyCode, portableIntegrationIds: ["integration"] } }, - { label: "portable model account", job: { ...flyCode, executionType: "agent" as const, modelAccess: "portable" as const, modelAccountId: "model" } }, - ])("requires an unlocked proxy with applied updates for $label", ({ job }) => { - expect(proxyLaunchDecision(job, stopped)).toEqual({ kind: "blocked", reason: "proxy_unavailable", retry: "manual" }); - expect(proxyLaunchDecision(job, locked)).toEqual({ kind: "blocked", reason: "proxy_locked", retry: "manual" }); - expect(proxyLaunchDecision(job, { ...unlocked, pendingChanges: true })).toEqual({ kind: "blocked", reason: "pending_changes", retry: "manual" }); - expect(proxyLaunchDecision(job, unlocked)).toEqual({ kind: "allow" }); - }); - - it("never auto-starts a disabled proxy and preserves native exe.dev behavior", () => { - expect(proxyLaunchDecision(flyCode, { ...stopped, enabled: false })).toEqual({ kind: "blocked", reason: "proxy_disabled", retry: "manual" }); - expect(proxyLaunchDecision({ executionProvider: "exe", executionType: "agent" }, { ...stopped, enabled: false })).toEqual({ kind: "allow" }); - }); - - it("does not auto-start a stopped proxy for credential-dependent jobs", () => { - expect(proxyLaunchDecision({ ...flyCode, portableIntegrationIds: ["integration"] }, stopped)).toMatchObject({ kind: "blocked", retry: "manual" }); - }); - - it("turns a blocked decision into a scheduler-recognized launch outcome", () => { - expect(() => requireProxyLaunch(proxyLaunchDecision({ ...flyCode, portableIntegrationIds: ["integration"] }, locked))) - .toThrow(new ProxyLaunchBlockedError("proxy_locked")); - expect(() => requireProxyLaunch(proxyLaunchDecision(flyCode, locked))).not.toThrow(); - }); -}); diff --git a/packages/api/test/proxy-management-authorization.test.ts b/packages/api/test/proxy-management-authorization.test.ts deleted file mode 100644 index 1fedfe43..00000000 --- a/packages/api/test/proxy-management-authorization.test.ts +++ /dev/null @@ -1,55 +0,0 @@ -import { describe, expect, it, vi } from "vitest"; -import { protectedApiFetch } from "../src/protected-api"; - -vi.mock("cloudflare:workers", () => ({ WorkerEntrypoint: class {} })); -vi.mock("@cloudflare/workers-oauth-provider", () => ({ OAuthProvider: class {}, AuthorizationError: class extends Error {}, getOAuthApi: vi.fn() })); - -const ownerOnlyOperations = [ - ["GET", "/api/v1/integrations/bearer"], - ["POST", "/api/v1/integrations/bearer"], - ["GET", "/api/v1/model-accounts"], - ["POST", "/api/v1/model-accounts"], - ["POST", "/api/v1/model-accounts/aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa/browser-capability"], - ["GET", "/api/v1/unlock-key/verification"], - ["POST", "/api/v1/unlock-key/verification"], - ["GET", "/api/v1/unlock-key/rotation-snapshot"], - ["POST", "/api/v1/unlock-key/rotation"], -] as const; - -describe("credential and model-account management authorization", () => { - it.each(["access_token", "oauth"] as const)("rejects %s credentials even when granted integration write", async authMethod => { - const auth = { - tenantId: "tenant-fixture", - userId: "owner-fixture", - sessionVersion: 1, - authMethod, - scopes: ["integrations:read", "integrations:write", "jobs:write"], - } as any; - for (const [method, path] of ownerOnlyOperations) { - const response = await protectedApiFetch(new Request(`https://app.example${path}`, { - method, - headers: { - Origin: "https://app.example", - "Content-Type": "application/json", - ...(method === "POST" ? {} : {}), - }, - ...(method === "POST" ? { body: "{}" } : {}), - }), { APP_ORIGIN: "https://app.example" } as any, auth, {} as any); - expect(response.status, `${method} ${path}`).toBe(403); - expect(await response.json(), `${method} ${path}`).toMatchObject({ error: { code: "session_required" } }); - } - }); - - it("rejects a cross-origin interactive mutation before service access", async () => { - const response = await protectedApiFetch(new Request("https://app.example/api/v1/integrations/bearer", { - method: "POST", - headers: { Origin: "https://attacker.example", "Content-Type": "application/json" }, - body: "{}", - }), { APP_ORIGIN: "https://app.example" } as any, { - tenantId: "tenant-fixture", userId: "owner-fixture", sessionVersion: 1, - authMethod: "session", scopes: ["integrations:write"], - } as any, {} as any); - expect(response.status).toBe(403); - expect(await response.json()).toMatchObject({ error: { code: "invalid_origin" } }); - }); -}); diff --git a/packages/api/test/proxy-provisioner.test.ts b/packages/api/test/proxy-provisioner.test.ts deleted file mode 100644 index bc6e9eca..00000000 --- a/packages/api/test/proxy-provisioner.test.ts +++ /dev/null @@ -1,47 +0,0 @@ -import { describe, expect, it, vi } from "vitest"; -import { provisionCredentialProxy } from "../src/proxy-provisioner"; - -const input = { - tenantId: "11111111-1111-4111-8111-111111111111", - proxyIdentity: "fly-app/proxy-machine", - bootEpoch: "22222222-2222-4222-8222-222222222222", - controlOrigin: "https://factorize.example/", - browserOrigin: "https://proxy.example", -}; - -describe("credential proxy bootstrap provisioning", () => { - it("issues an epoch-bound credential only to the provisioner's private start channel", async () => { - const control = { - provisionCredential: vi.fn().mockResolvedValue("fzc_one-use-secret"), - revokeCredential: vi.fn().mockResolvedValue(true), - }; - const startProxy = vi.fn().mockResolvedValue(undefined); - - await expect(provisionCredentialProxy(input, { control, startProxy })).resolves.toEqual({ - proxyIdentity: input.proxyIdentity, - bootEpoch: input.bootEpoch, - }); - - expect(control.provisionCredential).toHaveBeenCalledWith(input.tenantId, input.proxyIdentity, input.bootEpoch); - expect(startProxy).toHaveBeenCalledWith({ ...input, controlOrigin: "https://factorize.example", credential: "fzc_one-use-secret" }); - expect(control.revokeCredential).not.toHaveBeenCalled(); - }); - - it("revokes the one-use credential if proxy startup fails", async () => { - const control = { - provisionCredential: vi.fn().mockResolvedValue("fzc_one-use-secret"), - revokeCredential: vi.fn().mockResolvedValue(true), - }; - const failure = new Error("startup failed"); - await expect(provisionCredentialProxy(input, { control, startProxy: vi.fn().mockRejectedValue(failure) })).rejects.toBe(failure); - expect(control.revokeCredential).toHaveBeenCalledWith(input.tenantId, input.proxyIdentity); - }); - - it("rejects non-HTTPS or non-origin control URLs before issuing a credential", async () => { - const control = { provisionCredential: vi.fn(), revokeCredential: vi.fn() }; - await expect(provisionCredentialProxy({ ...input, controlOrigin: "http://factorize.example" }, { control, startProxy: vi.fn() })).rejects.toThrow("HTTPS origin"); - await expect(provisionCredentialProxy({ ...input, controlOrigin: "https://factorize.example/path" }, { control, startProxy: vi.fn() })).rejects.toThrow("HTTPS origin"); - await expect(provisionCredentialProxy({ ...input, browserOrigin: "http://proxy.example" }, { control, startProxy: vi.fn() })).rejects.toThrow("HTTPS origin"); - expect(control.provisionCredential).not.toHaveBeenCalled(); - }); -}); diff --git a/packages/api/test/run-credential-repair.postgres.test.ts b/packages/api/test/run-credential-repair.postgres.test.ts index aac4c33e..91535b2c 100644 --- a/packages/api/test/run-credential-repair.postgres.test.ts +++ b/packages/api/test/run-credential-repair.postgres.test.ts @@ -2,7 +2,7 @@ import {afterAll, beforeAll, describe, expect, it, vi} from "vitest"; import {loadingFixture} from "./helpers/loading-fixture"; import {RunScheduler} from "../src/postgres/run-scheduler"; import {protectedApiFetch} from "../src/protected-api"; -import {EncryptedIntegrationRepository} from "../src/postgres/encrypted-integration-repository"; +import {CredentialRepository} from "../src/postgres/credential-repository"; import {RunRepository} from "../src/postgres/run-repository"; vi.mock("cloudflare:workers", () => ({WorkerEntrypoint: class {}, DurableObject: class {}})); @@ -25,7 +25,7 @@ describe.skipIf(!url)("run credential repair and cancellation (PostgreSQL)", () expect(launch).not.toHaveBeenCalled(); const blocked = (await f.db.pool.query("SELECT state,failure_code,execution_config,execution_handle FROM app.runs WHERE tenant_id=$1 AND id=$2", [f.tenantId, f.runId])).rows[0]; expect(blocked).toMatchObject({state: "blocked", failure_code: "credential_repair_required", execution_handle: null, execution_config: snapshot}); - const records = new EncryptedIntegrationRepository(f.db, f.tenantId, f.env.CREDENTIAL_ENCRYPTION_KEY); + const records = new CredentialRepository(f.db, f.tenantId, f.env.CREDENTIAL_ENCRYPTION_KEY); await records.write({id: replacement, kind: "bearer", name: "Re-entered", origin: "https://selected.example.com", description: null, managedSecret: "replacement-secret", expectedRevision: 0, idempotencyKey: crypto.randomUUID(), operation: "upsert"}); await f.db.pool.query("UPDATE app.jobs SET execution_config=$3,run_scopes='[]' WHERE tenant_id=$1 AND id=$2", [f.tenantId, f.jobIds[0], {...snapshot, portableIntegrationIds: [replacement]}]); expect(await new RunRepository(f.db).retryBlockedLaunch(f.tenantId, f.runId)).toBe(true); diff --git a/packages/api/test/run-credentials.test.ts b/packages/api/test/run-credentials.test.ts deleted file mode 100644 index e5862085..00000000 --- a/packages/api/test/run-credentials.test.ts +++ /dev/null @@ -1,39 +0,0 @@ -import { describe, expect, it } from "vitest"; -import { authenticateRunCredential, issueRunCredential, RUN_SCOPES } from "../src/run-credentials"; - -describe("run-scoped execution credentials", () => { - it("binds a short-lived bearer credential to its active tenant, job, and run", async () => { - let storedDigest = "", storedScopes: string[] = [], active = true; - const database = { pool: { query: async (sql: string, values: unknown[] = []) => { - if (sql.includes("SELECT user_id,session_version")) return { rows: [{ user_id: "owner-1", session_version: 7 }], rowCount: 1 }; - if (sql.includes("INSERT INTO app.run_credentials")) { storedDigest = String(values[2]); storedScopes = JSON.parse(String(values[6])); return { rows: [], rowCount: 1 }; } - if (sql.includes("FROM app.run_credentials c")) return active && values[1] === storedDigest ? { rows: [{ tenant_id: "tenant-1", user_id: "owner-1", session_version: 7, job_id: "job-1", scopes: storedScopes }], rowCount: 1 } : { rows: [], rowCount: 0 }; - throw new Error(`Unexpected SQL: ${sql}`); - } } } as any; - const env = { DATABASE: database } as any; - const token = await issueRunCredential(env, "tenant-1", "00000000-0000-4000-8000-000000000001"); - const request = (credential: string) => new Request("https://example.test/api/v1", { headers: { Authorization: `Bearer ${credential}` } }); - const auth = await authenticateRunCredential(request(token), env); - expect(auth).toMatchObject({ tenantId: "tenant-1", userId: "owner-1", scopes: RUN_SCOPES, authMethod: "run_token", runJobId: "job-1", runId: "00000000-0000-4000-8000-000000000001" }); - expect(auth?.scopes).toContain("runs:read"); - expect(auth?.scopes.some(scope => scope.endsWith(":write") || scope === "runs:cancel")).toBe(false); - expect(auth?.runCredentialDigest).toBe(storedDigest); - expect(await authenticateRunCredential(request(token + "forged"), env)).toBeNull(); - active = false; - expect(await authenticateRunCredential(request(token), env)).toBeNull(); - }); - - it("persists the run's configured scope snapshot, including an empty scope set", async () => { - let storedDigest = "", storedScopes: string[] = []; - const database = { pool: { query: async (sql: string, values: unknown[] = []) => { - if (sql.includes("SELECT user_id,session_version")) return { rows: [{ user_id: "owner-1", session_version: 7 }] }; - if (sql.includes("INSERT INTO app.run_credentials")) { storedDigest = String(values[2]); storedScopes = JSON.parse(String(values[6])); return { rows: [] }; } - if (sql.includes("FROM app.run_credentials c")) return values[1] === storedDigest ? { rows: [{ tenant_id: "tenant-1", user_id: "owner-1", session_version: 7, job_id: "job-1", scopes: storedScopes }] } : { rows: [] }; - throw new Error(`Unexpected SQL: ${sql}`); - } } } as any; - const env = { DATABASE: database } as any; - const token = await issueRunCredential(env, "tenant-1", "00000000-0000-4000-8000-000000000002", []); - const request = new Request("https://example.test/api/v1", { headers: { Authorization: `Bearer ${token}` } }); - expect((await authenticateRunCredential(request, env))?.scopes).toEqual([]); - }); -}); diff --git a/packages/api/test/run-enrollment.postgres.test.ts b/packages/api/test/run-enrollment.postgres.test.ts deleted file mode 100644 index add65893..00000000 --- a/packages/api/test/run-enrollment.postgres.test.ts +++ /dev/null @@ -1,99 +0,0 @@ -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)).toBe(1); - 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("1"); - }, 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: 1 }); - 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, vmIdentity: `${revised.binding.vmIdentity}-replacement` })).toBe(2); - await expect(revised.service.authenticate(priorRevision.token, revised.binding, priorRevision.now)).rejects.toThrow(); - - const restarted = await fixture(), oldEpoch = await enrollment(restarted); - const newEpoch = crypto.randomUUID(); - await restarted.repository.setProxyState({ tenantId: restarted.tenantId, proxyIdentity: restarted.proxyIdentity, bootEpoch: newEpoch }); - await expect(restarted.service.authenticate(oldEpoch.token, restarted.binding, oldEpoch.now)).rejects.toThrow(); - const restartedBinding = { ...restarted.binding, bootEpoch: newEpoch }; - expect(await restarted.repository.authorizeRun(restartedBinding)).toBe(2); - expect(await restarted.repository.authorizeRun(restartedBinding)).toBe(2); - const fresh = await restarted.service.enroll(restartedBinding, new Date(now.getTime() + 60_000), now); - await expect(restarted.service.authenticate(fresh.token, restartedBinding, now)).resolves.toMatchObject({ bootEpoch: newEpoch, grantRevision: 2 }); - - 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(); - expect(await revoked.repository.authorizeRun(revoked.binding)).toBeNull(); - - 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); -}); diff --git a/packages/api/test/run-scopes.postgres.test.ts b/packages/api/test/run-scopes.postgres.test.ts index 90fba054..ea586fad 100644 --- a/packages/api/test/run-scopes.postgres.test.ts +++ b/packages/api/test/run-scopes.postgres.test.ts @@ -1,7 +1,8 @@ import { afterAll, beforeAll, describe, expect, it, vi } from "vitest"; import { loadingFixture } from "./helpers/loading-fixture"; import { protectedApiFetch } from "../src/protected-api"; -import { authenticateRunCredential, issueRunCredential, RUN_SCOPES } from "../src/run-credentials"; +import { DEFAULT_RUN_SCOPES as RUN_SCOPES } from "../src/run-scopes"; +import {snapshotRunAuthorization} from "../src/run-authorizations"; import { normalizeScopes } from "../src/access-tokens"; import type { OAuthProps } from "../src/types"; @@ -53,9 +54,8 @@ describe.skipIf(!url)("configurable run scopes with PostgreSQL", () => { it("allows an orchestration run to change job scopes without upgrading its own active credential", async () => { const { tenantId, runId, env, db } = fixture; await db.pool.query("UPDATE app.job_runs SET state='running' WHERE tenant_id=$1 AND id=$2", [tenantId, runId]); - const bearer = (token: string) => new Request(env.APP_ORIGIN, { headers: { Authorization: `Bearer ${token}` } }); - const token = await issueRunCredential(env, tenantId, runId, ["jobs:write"]); - const auth = (await authenticateRunCredential(bearer(token), env))!; + await snapshotRunAuthorization(db,{tenantId,runId,scopes:["jobs:write"]}); + const auth: OAuthProps = {...fixture.auth,authMethod:"vendor_identity",runId,runJobId:fixture.jobIds[0],runIdentityProvider:"fly.io",scopes:["jobs:write"]}; expect(auth.scopes).toEqual(["jobs:write"]); const id = fixture.jobIds[0]; const updated = await request(`/api/v1/jobs/${id}`, auth, { ...await updateBody(id), runScopes: ["jobs:write", "integrations:write"] }); @@ -63,10 +63,8 @@ describe.skipIf(!url)("configurable run scopes with PostgreSQL", () => { expect(await updated.json()).toMatchObject({ runScopes: ["jobs:write", "integrations:write"] }); const foreignJob = await db.pool.query("SELECT run_scopes FROM app.jobs WHERE tenant_id=$1 AND id=$2", [fixture.otherTenant, id]); expect(foreignJob.rows[0].run_scopes).toEqual(RUN_SCOPES); - expect((await authenticateRunCredential(bearer(token), env))?.scopes).toEqual(["jobs:write"]); - const rotated = await issueRunCredential(env, tenantId, runId, ["jobs:write", "integrations:write"]); - expect(await authenticateRunCredential(bearer(token), env)).toBeNull(); - expect((await authenticateRunCredential(bearer(rotated), env))?.scopes).toEqual(["jobs:write"]); + await snapshotRunAuthorization(db,{tenantId,runId,scopes:["jobs:write","integrations:write"]}); + expect((await db.pool.query("SELECT scopes FROM app.run_authorizations WHERE tenant_id=$1 AND run_id=$2",[tenantId,runId])).rows[0].scopes).toEqual(["jobs:write"]); const foreign = crypto.randomUUID(); expect((await request(`/api/v1/jobs/${foreign}`, auth, { ...await updateBody(id), runScopes: [] })).status).toBe(404); }); @@ -74,8 +72,7 @@ describe.skipIf(!url)("configurable run scopes with PostgreSQL", () => { it("attributes an explicitly granted run error report to the execution credential", async () => { const { tenantId, env, db } = fixture; const source = (await db.pool.query("SELECT id FROM app.job_runs WHERE tenant_id=$1 AND state='running' AND id<>$2 LIMIT 1", [tenantId, fixture.runId])).rows[0].id; - const token = await issueRunCredential(env, tenantId, source, ["runs:write"]); - const auth = (await authenticateRunCredential(new Request(env.APP_ORIGIN, { headers: { Authorization: `Bearer ${token}` } }), env))!; + const auth: OAuthProps = {...fixture.auth,authMethod:"vendor_identity",runId:source,runIdentityProvider:"fly.io",scopes:["runs:write"]}; const result = await protectedApiFetch(new Request(env.APP_ORIGIN + `/api/v1/runs/${source}/report-error`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ reason: "Orchestrator detected a problem" }), }), env, auth, {} as any); diff --git a/packages/api/test/run-vendor-launch.test.ts b/packages/api/test/run-vendor-launch.test.ts index 16ab8393..ec60def6 100644 --- a/packages/api/test/run-vendor-launch.test.ts +++ b/packages/api/test/run-vendor-launch.test.ts @@ -42,7 +42,7 @@ describe("vendor-authenticated run launch", () => { await scheduler.launch({ id: runId, tenantId: "tenant", executionConfig: { agentKind, runScopes: ["jobs:read", "jobs:write"], ...(agentKind === "code" ? { executionType: "code", script: "echo test", inputContext: {} } : {}) }, encryptedPrompt: await encrypt("Complete the task", key) }); const request = launch.mock.calls[0][0]; expect(recordHandle.mock.invocationCallOrder[0]).toBeLessThan(launch.mock.invocationCallOrder[0]); - expect(request.runProxy).toBeUndefined(); + expect(request).not.toHaveProperty("runProxy"); expect(request.runIdentity).toEqual({backendOrigin: env.APP_ORIGIN}); expect(typeof request.verifyVendorIdentity).toBe("function"); expect(issuedScopes).toEqual(["jobs:read", "jobs:write"]); diff --git a/packages/api/test/runtime-context.test.ts b/packages/api/test/runtime-context.test.ts index 0a128e32..2bcb06cf 100644 --- a/packages/api/test/runtime-context.test.ts +++ b/packages/api/test/runtime-context.test.ts @@ -1,7 +1,7 @@ import { afterEach, describe, expect, it, vi } from "vitest"; import worker from "../src/worker"; import { protectedApiFetch } from "../src/protected-api"; -import { issueRunCredential, RUN_SCOPES } from "../src/run-credentials"; +import { DEFAULT_RUN_SCOPES as RUN_SCOPES } from "../src/run-scopes"; import { IdentityRepository } from "../src/postgres/identity-repository"; vi.mock("cloudflare:workers", () => ({ WorkerEntrypoint: class {}, DurableObject: class {} })); @@ -12,27 +12,12 @@ vi.mock("@cloudflare/workers-oauth-provider", () => ({ afterEach(() => vi.restoreAllMocks()); describe("run proxy identity boundary", () => { - it("authenticates an injected bearer, exposes its own identity, and rejects it when inactive", async () => { - let digest = "", active = true; - const runId = "00000000-0000-4000-8000-000000000001"; - const database = { pool: { query: async (sql: string, values: unknown[] = []) => { - if (sql.includes("SELECT user_id,session_version")) return { rows: [{ user_id: "owner", session_version: 1 }] }; - if (sql.includes("INSERT INTO app.run_credentials")) { digest = String(values[2]); return { rows: [] }; } - if (sql.includes("FROM app.run_credentials c")) return { rows: active && values[1] === digest ? [{ tenant_id: "tenant", user_id: "owner", session_version: 1, job_id: "source", scopes: RUN_SCOPES }] : [] }; - throw new Error("Unexpected database operation"); - } } }; - const env = { DATABASE: database, APP_ORIGIN: "https://app.test" } as any; - vi.spyOn(IdentityRepository.prototype, "member").mockResolvedValue({ role: "owner", sessionVersion: 1 } as any); - const token = await issueRunCredential(env, "tenant", runId); - const request = (path: string, method = "GET") => worker.fetch(new Request(env.APP_ORIGIN + path, { method, headers: { Authorization: `Bearer ${token}` } }), env, {} as ExecutionContext); - const response = await request("/api/v1/runtime-context"); + it("reports a verified run with an empty scope snapshot", async () => { + vi.spyOn(IdentityRepository.prototype, "member").mockResolvedValue({role:"owner",sessionVersion:1} as any); + const response=await protectedApiFetch(new Request("https://app.test/api/v1/runtime-context"), {DATABASE:{}} as any, + {tenantId:"tenant",userId:"owner",sessionVersion:1,authMethod:"vendor_identity",runId:"run",runJobId:"source",runIdentityProvider:"fly.io",scopes:[]},{} as any); expect(response.status).toBe(200); - expect(await response.json()).toEqual({ kind: "factorize-runtime-context-v1", authMethod: "run_token", runId, jobId: "source", scopes: RUN_SCOPES }); - const write = await request("/api/v1/jobs/source", "DELETE"); - expect(write.status).toBe(403); - expect(await write.json()).toMatchObject({ error: { code: "insufficient_scope" } }); - active = false; - expect((await request("/api/v1/runtime-context")).status).toBe(401); + expect(await response.json()).toMatchObject({authMethod:"vendor_identity",runId:"run",jobId:"source",scopes:[]}); }); it("can verify that an integration is read-only", async () => { diff --git a/packages/api/test/trace-source.postgres.test.ts b/packages/api/test/trace-source.postgres.test.ts index 42b16b56..8ca4e337 100644 --- a/packages/api/test/trace-source.postgres.test.ts +++ b/packages/api/test/trace-source.postgres.test.ts @@ -13,7 +13,6 @@ import { RunScheduler } from "../src/postgres/run-scheduler"; import { ExeVmBackend } from "../src/exe-vm-backend"; import { agentDriver } from "../src/agent-driver"; import { IdentityRepository } from "../src/postgres/identity-repository"; -import { authenticateRunCredential, issueRunCredential } from "../src/run-credentials"; import { RunRetentionRepository } from "../src/postgres/run-retention-repository"; const url = process.env.TRACE_TEST_DATABASE_URL ?? process.env.AUTH_TEST_DATABASE_URL; @@ -56,27 +55,6 @@ describe.skipIf(!url)("trace sources with PostgreSQL", () => { return { tenantId, env, runId, upload, blobs, live: new LiveTraceRepository(database, tenantId), trace: new TraceRepository(database, tenantId), artifacts: new ArtifactRepository(database, tenantId) }; } - it("rejects legacy guest credentials, expired credentials, and terminal-run proxy credentials", async () => { - const f = await fixture(); - const userId = crypto.randomUUID(); - await new IdentityRepository(database, f.tenantId).upsertOwner(userId, `${userId}@example.test`); - const { job_id: jobId, invocation_id: invocationId } = (await database.pool.query("SELECT job_id,invocation_id FROM app.runs WHERE tenant_id=$1 AND id=$2", [f.tenantId, f.runId])).rows[0]; - await database.pool.query("INSERT INTO app.job_runs(tenant_id,id,job_id,invocation_id,state,encrypted_prompt) VALUES ($1,$2,$3,$4,'running','test')", [f.tenantId, f.runId, jobId, invocationId]); - const request = (token: string) => new Request("https://app.test/api/v1/runtime-context", { headers: { Authorization: `Bearer ${token}` } }); - const token = await issueRunCredential(f.env, f.tenantId, f.runId); - expect(await authenticateRunCredential(request(token), f.env)).toMatchObject({ runId: f.runId, runJobId: jobId }); - await database.pool.query("UPDATE app.run_credentials SET proxy_name=NULL WHERE tenant_id=$1 AND run_id=$2", [f.tenantId, f.runId]); - expect(await authenticateRunCredential(request(token), f.env)).toBeNull(); - const replacement = await issueRunCredential(f.env, f.tenantId, f.runId); - expect(await authenticateRunCredential(request(token), f.env)).toBeNull(); - expect(await authenticateRunCredential(request(replacement), f.env)).not.toBeNull(); - await database.pool.query("UPDATE app.run_credentials SET expires_at=now()-interval '1 second' WHERE tenant_id=$1 AND run_id=$2", [f.tenantId, f.runId]); - expect(await authenticateRunCredential(request(replacement), f.env)).toBeNull(); - const final = await issueRunCredential(f.env, f.tenantId, f.runId); - await new RunRepository(database).terminal({ tenantId: f.tenantId, id: f.runId } as any, "failed", "failed"); - expect(await authenticateRunCredential(request(final), f.env)).toBeNull(); - }); - it("retains pre-provision cleanup ownership across an interrupted launch lease", async () => { const f = await fixture(); const { job_id: jobId, invocation_id: invocationId } = (await database.pool.query("SELECT job_id,invocation_id FROM app.runs WHERE tenant_id=$1 AND id=$2", [f.tenantId, f.runId])).rows[0]; diff --git a/packages/api/test/vendor-run-auth.postgres.test.ts b/packages/api/test/vendor-run-auth.postgres.test.ts index 512a1355..995307cb 100644 --- a/packages/api/test/vendor-run-auth.postgres.test.ts +++ b/packages/api/test/vendor-run-auth.postgres.test.ts @@ -6,7 +6,7 @@ import { issueArtifactUploadGrant } from "../src/artifact-upload"; import { snapshotRunAuthorization } from "../src/run-authorizations"; import { authenticateVendorRunRequest } from "../src/vendor-run-auth"; import { exeWifIntegrationNameFor, vmNameFor } from "../src/exe-vm-backend"; -import { EncryptedIntegrationRepository } from "../src/postgres/encrypted-integration-repository"; +import { CredentialRepository } from "../src/postgres/credential-repository"; import { GitHubRepository } from "../src/postgres/github-repository"; import { ConnectionRepository } from "../src/postgres/connection-repository"; import worker from "../src/worker"; @@ -124,10 +124,10 @@ describe.skipIf(!url)("vendor identity request admission (PostgreSQL and Worker }); it("forwards only the run's selected managed bearer and stops after disconnect or cancellation", async () => { - const records = new EncryptedIntegrationRepository(f.db, f.tenantId, f.env.CREDENTIAL_ENCRYPTION_KEY); + const records = new CredentialRepository(f.db, f.tenantId, f.env.CREDENTIAL_ENCRYPTION_KEY); const id = crypto.randomUUID(), otherId = crypto.randomUUID(); await records.write({id, kind: "bearer", name: "selected", origin: "https://selected.example.com", description: null, expectedRevision: await records.revision(), idempotencyKey: crypto.randomUUID(), operation: "upsert", managedSecret: "selected-secret"}); - await new EncryptedIntegrationRepository(f.db, f.otherTenant, f.env.CREDENTIAL_ENCRYPTION_KEY).write({id: otherId, kind: "bearer", name: "other", origin: "https://other.example.com", description: null, expectedRevision: 0, idempotencyKey: crypto.randomUUID(), operation: "upsert", managedSecret: "other-tenant-secret"}); + await new CredentialRepository(f.db, f.otherTenant, f.env.CREDENTIAL_ENCRYPTION_KEY).write({id: otherId, kind: "bearer", name: "other", origin: "https://other.example.com", description: null, expectedRevision: 0, idempotencyKey: crypto.randomUUID(), operation: "upsert", managedSecret: "other-tenant-secret"}); await f.db.pool.query("UPDATE app.runs SET execution_config=execution_config || $3::jsonb WHERE tenant_id=$1 AND id=$2", [f.tenantId, f.runId, JSON.stringify({portableIntegrationIds: [id]})]); const vendorFetch = globalThis.fetch; const outbound: string[] = []; @@ -208,7 +208,7 @@ describe.skipIf(!url)("vendor identity request admission (PostgreSQL and Worker }); it("refreshes the selected model server-side, streams it, restores after restart, and revokes on disconnect", async () => { - const records = new EncryptedIntegrationRepository(f.db, f.tenantId, f.env.CREDENTIAL_ENCRYPTION_KEY); + const records = new CredentialRepository(f.db, f.tenantId, f.env.CREDENTIAL_ENCRYPTION_KEY); const id = crypto.randomUUID(); const access = (exp: number) => `${encode({alg: "none"})}.${encode({exp})}.upstream-fixture`; const old = access(Math.floor(Date.now()/1000)-5), renewed = access(Math.floor(Date.now()/1000)+3600); @@ -233,7 +233,7 @@ describe.skipIf(!url)("vendor identity request admission (PostgreSQL and Worker const call = () => worker.fetch(new Request(request(jwt, f.runId, `/internal/run-proxy/${f.runId}/providers/model/v1/responses`), {method: "POST", body: "model-input"}), f.env, {waitUntil() {}} as any); const concurrent = await Promise.all([call(), call()]); for (const response of concurrent) expect(await response.text()).toBe("data: model-stream\n\n"); - const restored = await new EncryptedIntegrationRepository(f.db, f.tenantId, f.env.CREDENTIAL_ENCRYPTION_KEY).managedCredential(id, "model"); + const restored = await new CredentialRepository(f.db, f.tenantId, f.env.CREDENTIAL_ENCRYPTION_KEY).managedCredential(id, "model"); expect(JSON.parse(restored!.payload).tokens.refresh_token).toBe("rotated-refresh"); expect((await call()).status).toBe(200); expect(refreshes).toBe(1); diff --git a/packages/app/src/features/jobs/editor.tsx b/packages/app/src/features/jobs/editor.tsx index ecd96f74..e01cadf6 100644 --- a/packages/app/src/features/jobs/editor.tsx +++ b/packages/app/src/features/jobs/editor.tsx @@ -44,7 +44,8 @@ function EditorForm({ initial, section }: { initial?: Job; section?: string }) { const flyConnection = useQuery(flyConnectionQuery), flyConfigurations = useQuery(flyConfigurationsQuery); const flyConfiguration = flyConfigurations.data?.find(item => item.id === draft.executionConfigId); const isFly = draft.executionConfigId === "fly-new" || Boolean(flyConfiguration); - const accounts = useQuery({ enabled: isFly && (draft.executionType ?? "agent") === "agent", queryKey: ["settings", "model-accounts"], queryFn: async ({ signal }) => { const { data, error } = await api.GET("/api/v1/model-accounts", { signal }); if (!data || error) throw new Error(messageOf(error)); return data.accounts; } }); + const bearers=useQuery({queryKey:["settings","bearer-integrations"],queryFn:async({signal})=>{const {data,error}=await api.GET("/api/v1/integrations/bearer",{signal});if(!data||error)throw new Error(messageOf(error));return data.integrations;}}); + const accounts = useQuery({ enabled: (draft.executionType ?? "agent") === "agent", queryKey: ["settings", "model-accounts"], queryFn: async ({ signal }) => { const { data, error } = await api.GET("/api/v1/model-accounts", { signal }); if (!data || error) throw new Error(messageOf(error)); return data.accounts; } }); const target = targets.data?.find(t => t.id === draft.executionConfigId); const verificationFingerprint = JSON.stringify([draft.executionConfigId, canonicalizeVmImage(draft.vmImage ?? ""), draft.tags ?? [], target?.agentKind ?? ""]); const verificationKey = `factorize-vm-image-verification:${initial?.id ?? "new"}`; @@ -111,16 +112,25 @@ function EditorForm({ initial, section }: { initial?: Job; section?: string }) {
{show("general") &&

General

Set the job name, description, and stable identifier.

{!initial &&
{projects.isPending &&

Loading projects…

}{projects.error &&

{projects.error.message}

}
}