diff --git a/docs/portable-workloads.md b/docs/portable-workloads.md new file mode 100644 index 00000000..359ec4bb --- /dev/null +++ b/docs/portable-workloads.md @@ -0,0 +1,32 @@ +# Portable workload attachment + +Portable attachment authenticates an enrolled process as a workload. The existing Factorize proxy evaluates workload scopes, integration revocation epochs, provider-specific permissions, and server-selected origins just as it does for Fly. The enrollment binds a server-issued grant ID, tenant, workload UUID and attachment to an ephemeral signing key. The signed body covers the entire proxy request, including the upstream method, relative path, headers and payload. Tailscale and Headscale remain optional and customer-managed. + +## Try it with isolated fixtures + +From the repository root on a validation runner with Node 24.21.0, npm 11.19.0, OpenSSL, and the repository's disposable local PostgreSQL database: + +```sh +npm ci +npm run bootstrap:test +# Export the local AUTH_TEST_DATABASE_URL printed by bootstrap:test. +cd packages/api +../../node_modules/.bin/vitest run test/portable-workloads.postgres.test.ts test/vm-enrollment.postgres.test.ts +``` + +The fixture starts a local TLS listener and passes HTTPS requests to the Worker. Only upstream provider fetches are simulated. It creates fake X and Cloudflare connections and runs separate Node processes with an isolated test CA. The tests require no customer accounts. + +## Operator and client walkthrough + +1. Use an authorized operator credential with `vms:edit`, `proxy:use` and the integration permission to delegate. Read the integration's current required scope from reflection. POST JSON to `/api/v1/workloads/grants`, for example `{"workload":"","permissions":{"scopes":["proxy:use","integration::"]}}`. The same permission snapshot evaluator used by Fly rejects scopes outside the operator's effective access. Record the grantId. A browser owner session alone lacks integration delegation scopes. +2. POST to `/api/v1/workloads/grants//enrollments` with an authenticated workspace owner session and its same-origin Origin header. Deliver the returned JSON directly to the intended process through your trusted channel. It contains a two-minute, single-use secret. Keep it out of shell arguments, command history, environment exports, disk, and logs. +3. On a local computer, VM or VPS with Node 24.21 or later, pipe that JSON from your trusted delivery tool to `node packages/workload-client/example.ts https://factorize.example /2/users/me`. The example prints the upstream status and disconnects. In a long-running process, import `attach` from `factorize-workload-client`, call `await attach(origin, enrollment)`, use `session.request({integration, method, path, body})`, and `await session.close()` during shutdown. +4. DELETE `/api/v1/workloads/grants/` as the owner. The next request under any of its sessions fails. Create a fresh grant if a revoked workload needs access again. + +## Trust, expiry and recovery + +The enrollment recipient can be the first process to redeem it. Whoever controls delivery controls that choice. Enrollment proves possession of the process key. It supplies no evidence of provider ownership or host integrity. A root user controlling a live host can use the process or intercept enrollment. Workload names, IP addresses, hostnames and clock readings supply no identity. Fly OIDC grants stay bound to their enrolled Fly machine. + +Redemption signs the body containing the one-time secret and ephemeral public key. The server compares a stored SHA-256 digest and atomically consumes the secret while binding the key. The client keeps a non-exportable P-256 signing key in memory. Every compact ES256 JWS binds tenant, workload UUID, attachment ID, POST, exact HTTPS URL, SHA-256 of the raw body, issue time and a strictly increasing sequence. PostgreSQL locks the row and accepts a sequence once. Issuance timestamps limit replay lifetime. Session lookup and live authorization use tenant and attachment together. The proxy checks integration availability, revocation epoch, scopes and existing provider rules again before forwarding. + +The client heartbeats every 10 seconds. A session expires 30 seconds after its last accepted heartbeat or redemption. A clean disconnect takes effect at commit. After a crash or network loss an already-sent heartbeat may still arrive within the proof freshness window (15 seconds old, up to 5 seconds of forward clock skew), giving a maximum of 50 seconds after the last signature. An in-flight upstream request can finish. A terminated process loses its key even if its directory is copied. After a lost connection, restart with fresh enrollment. If delivery or the process may have been compromised, revoke the grant before issuing a replacement. Rotate upstream credentials separately if the upstream account itself was compromised. diff --git a/package-lock.json b/package-lock.json index f47872b9..343d7963 100644 --- a/package-lock.json +++ b/package-lock.json @@ -6036,6 +6036,10 @@ "resolved": "packages/tail-relay", "link": true }, + "node_modules/factorize-workload-client": { + "resolved": "packages/workload-client", + "link": true + }, "node_modules/fast-deep-equal": { "version": "3.1.3", "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", @@ -10730,6 +10734,16 @@ "typescript": "^5.9.3", "wrangler": "^4.44.0" } + }, + "packages/workload-client": { + "name": "factorize-workload-client", + "version": "0.1.0", + "dependencies": { + "factorize-api-client": "0.1.0" + }, + "engines": { + "node": ">=24.21.0" + } } } } diff --git a/packages/api-client/src/schema.d.ts b/packages/api-client/src/schema.d.ts index 6cd7f60d..635b63ef 100644 --- a/packages/api-client/src/schema.d.ts +++ b/packages/api-client/src/schema.d.ts @@ -2259,7 +2259,7 @@ export interface paths { put?: never; /** * Make an authorized credential-injected API request - * @description OAuth requires proxy:use. An enrolled VM sends its short-lived provider OIDC bearer token, X-Factorize-VM-Grant, and a fresh signed request proof in X-Factorize-VM-Proof. Only server-selected origins are used. Integration-wide grants are bounded by upstream credential permissions. Missing requestable access returns HTTP 403 with WWW-Authenticate insufficient_scope, scope and resource_metadata. Upstream status is returned in the result, including non-2xx. Text is UTF-8; other bodies are base64. Responses above 32 KiB are retained for 30 minutes and read in chunks. Revocation prevents subsequent calls and reads, but cannot undo upstream side effects. + * @description A portable client may send a signed X-Factorize-Attachment-Proof for its workload; the proxy applies the same workload scopes and provider policy as Fly. OAuth requires proxy:use. An enrolled VM sends its short-lived provider OIDC bearer token, X-Factorize-VM-Grant, and a fresh signed request proof in X-Factorize-VM-Proof. Only server-selected origins are used. Integration-wide grants are bounded by upstream credential permissions. Missing requestable access returns HTTP 403 with WWW-Authenticate insufficient_scope, scope and resource_metadata. Upstream status is returned in the result, including non-2xx. Text is UTF-8; other bodies are base64. Responses above 32 KiB are retained for 30 minutes and read in chunks. Revocation prevents subsequent calls and reads, but cannot undo upstream side effects. * * Accepts a scoped bearer token or interactive owner session. */ @@ -2992,6 +2992,138 @@ export interface paths { patch?: never; trace?: never; }; + "/api/v1/workloads/grants": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Create a portable workload grant from the operator's effective workload permissions + * @description Requires the vms:edit scope. + * + * Accepts a scoped bearer token or interactive owner session. + */ + post: operations["post_api_v1_workloads_grants"]; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/v1/workloads/grants/{grantId}/enrollments": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Issue a two-minute single-use portable enrollment + * @description Requires the vms:edit scope. + * + * An interactive owner session is required; bearer tokens cannot call this operation. + */ + post: operations["post_api_v1_workloads_grants_grantId_enrollments"]; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/v1/workloads/grants/{grantId}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + post?: never; + /** + * Revoke a portable workload grant + * @description Requires the vms:edit scope. + * + * An interactive owner session is required; bearer tokens cannot call this operation. + */ + delete: operations["delete_api_v1_workloads_grants_grantId"]; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/v1/workloads/redeem": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Authenticate portable workload redeem + * @description Requires an ES256 X-Factorize-Attachment-Proof bound to the exact request. See docs/portable-workloads.md. + * + * Accepts a scoped bearer token or interactive owner session. + */ + post: operations["post_api_v1_workloads_redeem"]; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/v1/workloads/heartbeat": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Authenticate portable workload heartbeat + * @description Requires an ES256 X-Factorize-Attachment-Proof bound to the exact request. See docs/portable-workloads.md. + * + * Accepts a scoped bearer token or interactive owner session. + */ + post: operations["post_api_v1_workloads_heartbeat"]; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/v1/workloads/disconnect": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Authenticate portable workload disconnect + * @description Requires an ES256 X-Factorize-Attachment-Proof bound to the exact request. See docs/portable-workloads.md. + * + * Accepts a scoped bearer token or interactive owner session. + */ + post: operations["post_api_v1_workloads_disconnect"]; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; } export type webhooks = Record; export interface components { @@ -10273,4 +10405,231 @@ export interface operations { 503: components["responses"]["Error503"]; }; }; + post_api_v1_workloads_grants: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody: { + content: { + "application/json": { + /** Format: uuid */ + workload: string; + permissions: { + scopes: string[]; + }; + }; + }; + }; + responses: { + /** @description Create a portable workload grant from the operator's effective workload permissions */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + /** Format: uuid */ + grantId: 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_workloads_grants_grantId_enrollments: { + parameters: { + query?: never; + header?: never; + path: { + grantId: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description Issue a two-minute single-use portable enrollment */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + /** Format: uuid */ + tenant: string; + /** Format: uuid */ + workload: string; + /** Format: uuid */ + attachment: string; + secret: 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"]; + }; + }; + delete_api_v1_workloads_grants_grantId: { + parameters: { + query?: never; + header?: never; + path: { + grantId: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description Revoke a portable workload grant */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + revoked: boolean; + }; + }; + }; + 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_workloads_redeem: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody: { + content: { + "application/json": { + secret: string; + key: { + /** @constant */ + kty: "EC"; + /** @constant */ + crv: "P-256"; + x: string; + y: string; + }; + }; + }; + }; + responses: { + /** @description Authenticate portable workload redeem */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + active: boolean; + }; + }; + }; + 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_workloads_heartbeat: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody: { + content: { + "application/json": Record; + }; + }; + responses: { + /** @description Authenticate portable workload heartbeat */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + active: boolean; + }; + }; + }; + 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_workloads_disconnect: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody: { + content: { + "application/json": Record; + }; + }; + responses: { + /** @description Authenticate portable workload disconnect */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + active: boolean; + }; + }; + }; + 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"]; + }; + }; } diff --git a/packages/api/migrations/0122_portable_workloads.sql b/packages/api/migrations/0122_portable_workloads.sql new file mode 100644 index 00000000..820537a5 --- /dev/null +++ b/packages/api/migrations/0122_portable_workloads.sql @@ -0,0 +1,20 @@ +CREATE TABLE app.portable_grants ( + tenant_id uuid NOT NULL REFERENCES app.tenants(id) ON DELETE CASCADE, + id uuid NOT NULL DEFAULT gen_random_uuid(), + workload uuid NOT NULL, + scopes text[] NOT NULL, + revoked_at timestamptz, + PRIMARY KEY (tenant_id,id) +); +CREATE TABLE app.portable_attachments ( + tenant_id uuid NOT NULL, + id uuid NOT NULL DEFAULT gen_random_uuid(), + grant_id uuid NOT NULL, + enrollment_hash text, + expires_at timestamptz NOT NULL, + public_key jsonb, + sequence bigint NOT NULL DEFAULT 0, + PRIMARY KEY (tenant_id,id), + FOREIGN KEY (tenant_id,grant_id) REFERENCES app.portable_grants(tenant_id,id) ON DELETE CASCADE +); +CREATE INDEX portable_attachment_expiry ON app.portable_attachments(expires_at); diff --git a/packages/api/src/api-contract.ts b/packages/api/src/api-contract.ts index 55057036..f8867ba0 100644 --- a/packages/api/src/api-contract.ts +++ b/packages/api/src/api-contract.ts @@ -8,6 +8,7 @@ import { integrationRoutes } from "./integrations/api/rest"; import { authRoutes } from "./auth/api/rest"; import { triggerRoutes } from "./triggers/api/rest"; import { accessRoutes } from "./access-control/api/rest"; +import { portableRoutes } from "./portable/api/rest"; import { vmGrantRoutes } from "./vm-grants/api/rest"; import { subscriptionRoutes } from "./subscriptions/api/rest"; import { eventRoutes } from "./events/api/rest"; @@ -27,6 +28,7 @@ export const API_ROUTES: RouteContract[] = [ ...subscriptionRoutes, ...triggerRoutes, ...vmGrantRoutes, + ...portableRoutes, ]; export const API_OPERATIONS = API_ROUTES.map( @@ -165,7 +167,7 @@ export function generateOpenApi() { .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: [] }] : []) : route.ownerSession ? [{ cookieAuth: [] }] : [{ bearerAuth: [] }, { cookieAuth: [] }], + security: route.documentation.security ?? (route.authOperation ? (route.ownerSession ? [{ cookieAuth: [] }] : []) : route.ownerSession ? [{ cookieAuth: [] }] : [{ bearerAuth: [] }, { cookieAuth: [] }]), ...(route.authOperation ? { "x-browser-auth-operation": route.authOperation } : { "x-required-scope": route.scope }), "x-owner-session-required": route.ownerSession, ...(parameters.length ? { parameters } : {}), @@ -184,7 +186,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, attachmentProof: { type: "apiKey", in: "header", name: "X-Factorize-Attachment-Proof" }, cookieAuth: { type: "apiKey", in: "cookie", name: "factorize_session" } }, schemas, responses: errorResponses }, paths, }; } diff --git a/packages/api/src/api-service.ts b/packages/api/src/api-service.ts index b01f23ce..f277d57b 100644 --- a/packages/api/src/api-service.ts +++ b/packages/api/src/api-service.ts @@ -1,3 +1,4 @@ +import { PortableGrants } from "./portable/application/grants"; import { SshService } from "./ssh/application/ssh-service"; import { HetznerClientKeyService } from "./integrations/application/hetzner-client-key"; import { AwsIntegrationService } from "./integrations/application/aws-service"; @@ -39,6 +40,7 @@ export class ApiService { get subscriptions() { return new SubscriptionsService(this.env, this.auth, scope => this.authorize(scope), scope => this.authorizeOwnerSession(scope)); } + get portableGrants() { return new PortableGrants(this.env,this.auth,()=>this.authorize("vms:edit"),()=>this.authorizeOwnerSession("vms:edit")); } get vmGrants() { return new VmGrantsService(this.env, this.auth, scope => this.authorize(scope)); } diff --git a/packages/api/src/integrations/application/cloudflare-tail.ts b/packages/api/src/integrations/application/cloudflare-tail.ts index 42ff0e50..efb2cfc2 100644 --- a/packages/api/src/integrations/application/cloudflare-tail.ts +++ b/packages/api/src/integrations/application/cloudflare-tail.ts @@ -5,7 +5,7 @@ export const TAIL_HANDLER_SCAFFOLD = `function handler(webhook) { return webhook.outcome === "exception" || webhook.logs.some((log) => log.level === "error"); }`; -const sensitive = /authorization|cookie|token|secret|password|credential|api[-_]?key|prompt|body/i; +const sensitive = /authorization|cookie|token|secret|password|credential|api[-_]?key|prompt|body|^x-factorize-(?:attachment|vm)-proof$/i; const encoder = new TextEncoder(); export function signingPayload(timestamp: string, deliveryId: string, body: string): string { diff --git a/packages/api/src/portable/api/rest.ts b/packages/api/src/portable/api/rest.ts new file mode 100644 index 00000000..cb611e09 --- /dev/null +++ b/packages/api/src/portable/api/rest.ts @@ -0,0 +1,74 @@ +import { z } from "zod"; +import { + route, + jsonSchema, + type RouteContract, +} from "../../transport/rest/route-contract"; +import { redemption } from "../application/session"; +import { grantRef, grantInput } from "../application/grants"; + +const receipt = z.strictObject({ + tenant: z.uuid(), + workload: z.uuid(), + attachment: z.uuid(), + secret: z.string(), +}); +function doc(summary: string, schema: z.ZodType) { + return { + summary, + responses: { + "200": { + description: summary, + content: { + "application/json": { schema: jsonSchema(schema, "output") }, + }, + }, + }, + }; +} +export const portableRoutes = [ + route( + "POST", + "/api/v1/workloads/grants", + "vms:edit", + doc("Create a portable workload grant from the operator's effective workload permissions", grantRef), + (service, { body }) => service.portableGrants.create(body), + { body: grantInput }, + ), + route( + "POST", + "/api/v1/workloads/grants/{grantId}/enrollments", + "vms:edit", + doc("Issue a two-minute single-use portable enrollment", receipt), + (service, { params }) => service.portableGrants.enroll(params.grantId), + { ownerSession: true, parameters: grantRef }, + ), + route( + "DELETE", + "/api/v1/workloads/grants/{grantId}", + "vms:edit", + doc("Revoke a portable workload grant", z.object({ revoked: z.boolean() })), + (service, { params }) => service.portableGrants.revoke(params.grantId), + { ownerSession: true, parameters: grantRef }, + ), + ...["redeem", "heartbeat", "disconnect"].map((action) => + route( + "POST", + "/api/v1/workloads/" + action, + [], + { + ...doc( + "Authenticate portable workload " + action, + z.object({ active: z.boolean() }), + ), + security: [{attachmentProof:[]}], + description: + "Requires an ES256 X-Factorize-Attachment-Proof bound to the exact request. See docs/portable-workloads.md.", + }, + async () => { + throw new Error("Attachment proof required"); + }, + {body:action==="redeem"?redemption:z.strictObject({}),maxBodyBytes:2048}, + ), + ), +] satisfies RouteContract[]; diff --git a/packages/api/src/portable/application/grants.ts b/packages/api/src/portable/application/grants.ts new file mode 100644 index 00000000..86b5b73a --- /dev/null +++ b/packages/api/src/portable/application/grants.ts @@ -0,0 +1,56 @@ +import { randomBytes, createHash } from "node:crypto"; +import { z } from "zod"; +import type { Env, OAuthProps } from "../../types"; +import { databaseFor } from "../../postgres/database"; +import { ServiceError } from "../../service-contract"; +import { vmPermissionSource, writeVmPermissionSnapshot } from "../../vm-grants/application/vm-permissions"; + +export const grantInput = z.strictObject({ + workload: z.uuid(), + permissions: vmPermissionSource, +}); +export const grantRef = z.strictObject({ grantId: z.uuid() }); +export const digest = (value: string | Uint8Array) => + createHash("sha256").update(value).digest("base64url"); +export const denied = () => + new ServiceError(403, "forbidden", "Workload access denied."); + +export class PortableGrants { + constructor( + private env: Env, + private auth: OAuthProps, + private operator: () => Promise, + private owner: () => Promise, + ) {} + async create(input: z.infer) { + await this.operator(); + return writeVmPermissionSnapshot(databaseFor(this.env), this.auth, input.permissions, async (db, snapshot) => { + const { rows } = await db.query<{ id: string }>( + "INSERT INTO app.portable_grants(tenant_id,workload,scopes) VALUES($1,$2,$3) RETURNING id", + [this.auth.tenantId, input.workload, snapshot.scopes], + ); + return { grantId: rows[0]!.id }; + }); + } + async enroll(grantId: string) { + await this.owner(); + const secret = randomBytes(32).toString("base64url"); + const { rows } = await databaseFor(this.env).pool.query<{ id: string; workload:string }>( + `INSERT INTO app.portable_attachments(tenant_id,grant_id,enrollment_hash,expires_at) + SELECT tenant_id,id,$3,clock_timestamp()+interval '2 minutes' FROM app.portable_grants + WHERE tenant_id=$1 AND id=$2 AND revoked_at IS NULL RETURNING id, (SELECT workload FROM app.portable_grants WHERE tenant_id=$1 AND id=$2) AS workload`, + [this.auth.tenantId, grantId, digest(secret)], + ); + if (!rows[0]) throw denied(); + return { tenant: this.auth.tenantId, attachment: rows[0].id, workload: rows[0].workload, secret }; + } + async revoke(grantId: string) { + await this.owner(); + const result = await databaseFor(this.env).pool.query( + "UPDATE app.portable_grants SET revoked_at=COALESCE(revoked_at, now()) WHERE tenant_id=$1 AND id=$2", + [this.auth.tenantId, grantId], + ); + if (!result.rowCount) throw new ServiceError(404, "not_found", "Portable workload grant not found."); + return { revoked: true }; + } +} diff --git a/packages/api/src/portable/application/session.ts b/packages/api/src/portable/application/session.ts new file mode 100644 index 00000000..8ef0ac47 --- /dev/null +++ b/packages/api/src/portable/application/session.ts @@ -0,0 +1,191 @@ +import { proxyRequestLimit } from "../../proxy/api/agent-api-contracts"; +import { Buffer } from "node:buffer"; +import { z } from "zod"; +import { databaseFor, type DatabaseClient } from "../../postgres/database"; +import { currentVmScopes } from "../../vm-grants/application/vm-permissions"; +import type { Env, OAuthProps } from "../../types"; +import { digest, denied } from "./grants"; + +const base = "/api/v1/workloads/"; +export const proxyPath = "/api/v1/agent/requests"; +const paths = [ + base + "redeem", + base + "heartbeat", + base + "disconnect", + proxyPath, + "/api/v1/agent/responses/read", + "/api/v1/agent/responses/query", +]; +const part = z.string().regex(/^[A-Za-z0-9_-]+$/); +const point = z.string().regex(/^[A-Za-z0-9_-]{43}$/); +const publicKey = z.strictObject({ + kty: z.literal("EC"), + crv: z.literal("P-256"), + x: point, + y: point, +}); +const header = z.strictObject({ + typ: z.literal("factorize-attachment+jwt"), + alg: z.literal("ES256"), +}); +const claimsSchema = z.strictObject({ + tenant: z.uuid(), + workload: z.uuid(), + attachment: z.uuid(), + seq: z.number().int().nonnegative().safe(), + iat: z.number().int(), + htu: z.string(), + htm: z.literal("POST"), + body: point, +}); +export const redemption = z.strictObject({ secret: point, key: publicKey }); +type Attachment = { + sequence: string; + grant_id: string; + workload: string; + scopes: string[]; + public_key: JsonWebKey | null; + enrollment_hash: string | null; +}; +async function live( + db: DatabaseClient, + tenant: string, + id: string, + lock = false, +) { + return ( + await db.query( + `SELECT a.sequence,a.public_key,a.enrollment_hash,a.grant_id,g.workload,g.scopes + FROM app.portable_attachments a JOIN app.portable_grants g ON (g.tenant_id,g.id)=(a.tenant_id,a.grant_id) + WHERE a.tenant_id=$1 AND a.id=$2 AND a.expires_at>clock_timestamp() AND g.revoked_at IS NULL + ${lock ? "FOR UPDATE OF a FOR SHARE OF g" : ""}`, + [tenant, id], + ) + ).rows[0]; +} +export async function portableScopes(env: Env, auth: OAuthProps) { + const db = databaseFor(env).pool; + const row = await live(db, auth.tenantId, auth.portableAttachment!); + if (!row?.public_key || row.grant_id !== auth.vmGrantId || row.workload !== auth.userId) return null; + return currentVmScopes(db, auth.tenantId, row.scopes.filter(scope => auth.scopes.includes(scope))); +} +async function boundedBody(request: Request, limit:number) { + const reader = request.body?.getReader(); + if (!reader) throw denied(); + const chunks = []; + let size = 0; + for (;;) { + const { value, done } = await reader.read(); + if (done) break; + size += value.byteLength; + if (size > limit) { + await reader.cancel(); + throw denied(); + } + chunks.push(value); + } + return Buffer.concat(chunks); +} +export async function attachmentRequest( + env: Env, + request: Request, + dispatch: (request: Request, auth: OAuthProps) => Promise, +) { + const url = new URL(request.url); + try { + if ( + url.protocol !== "https:" || + request.method !== "POST" || + url.search || + !paths.includes(url.pathname) + ) + throw denied(); + const proof = request.headers.get("X-Factorize-Attachment-Proof") ?? ""; + if (proof.length > 2048) throw denied(); + const [h, p, s] = z.tuple([part, part, part]).parse(proof.split(".")); + header.parse(JSON.parse(Buffer.from(h, "base64url").toString())); + const claims = claimsSchema.parse( + JSON.parse(Buffer.from(p, "base64url").toString()), + ); + const proxy = url.pathname.startsWith("/api/v1/agent/"); + const now = Date.now() / 1000; + if (claims.htu !== request.url || claims.iat < now - 15 || claims.iat > now + 5) throw denied(); + + const database = databaseFor(env); + const initial = await live(database.pool, claims.tenant, claims.attachment); + if (!initial || initial.workload !== claims.workload) throw denied(); + + // Only redemption carries the verification key in its (2 KiB maximum) body. + const enrolling = url.pathname === base + "redeem"; + if (enrolling ? initial.public_key || claims.seq !== 0 : !initial.public_key || claims.seq <= Number(initial.sequence)) throw denied(); + const enrollmentBytes = enrolling ? await boundedBody(request, 2048) : null; + const redeem = enrollmentBytes ? redemption.parse(JSON.parse(enrollmentBytes.toString())) : null; + if (redeem && initial.enrollment_hash !== digest(redeem.secret)) throw denied(); + const key = redeem?.key ?? initial.public_key; + if (!key) throw denied(); + const imported = await crypto.subtle.importKey( + "jwk", key, { name: "ECDSA", namedCurve: "P-256" }, false, ["verify"], + ); + if (!(await crypto.subtle.verify( + { name: "ECDSA", hash: "SHA-256" }, imported, Uint8Array.from(Buffer.from(s, "base64url")), + new TextEncoder().encode(h + "." + p), + ))) throw denied(); + + const bytes = enrollmentBytes ?? await boundedBody(request, url.pathname === proxyPath ? proxyRequestLimit : 2048); + if (claims.body !== digest(bytes)) throw denied(); + if (!redeem && !proxy) z.strictObject({}).parse(JSON.parse(bytes.toString())); + + // Keys are immutable after redemption. Recheck liveness under lock before consuming the proof. + const auth = await database.transaction(async (db) => { + const row = await live(db, claims.tenant, claims.attachment, true); + if (!row || row.workload !== claims.workload || + (redeem && row.enrollment_hash !== initial.enrollment_hash)) throw denied(); + const changed = await db.query( + `UPDATE app.portable_attachments SET sequence=$3, enrollment_hash=NULL, + public_key=coalesce(public_key,$4::jsonb),expires_at=CASE WHEN $5 THEN clock_timestamp() WHEN $6 THEN clock_timestamp()+interval '30 seconds' ELSE expires_at END + WHERE tenant_id=$1 AND id=$2 AND expires_at>clock_timestamp() + AND ($7 AND public_key IS NULL OR NOT $7 AND public_key IS NOT NULL AND sequence<$3) + AND to_timestamp($8) BETWEEN clock_timestamp()-interval '15 seconds' AND clock_timestamp()+interval '5 seconds'`, + [ + claims.tenant, + claims.attachment, + claims.seq, + redeem ? JSON.stringify(key) : null, + url.pathname === base + "disconnect", + !!redeem || url.pathname === base + "heartbeat", + !!redeem, + claims.iat, + ], + ); + if (changed.rowCount !== 1) throw denied(); + return { + tenantId: claims.tenant, + userId: row.workload, + vmGrantId: row.grant_id, + scopes: row.scopes, + authMethod: "vm" as const, + portableAttachment: claims.attachment, + sessionVersion: 0, + }; + }); + if (proxy) + return dispatch( + new Request(request.url, { + method: "POST", + headers: { "Content-Type": request.headers.get("Content-Type") ?? "" }, + body: Uint8Array.from(bytes), + signal: request.signal, + }), + auth, + ); + return Response.json( + { active: url.pathname !== base + "disconnect" }, + { headers: { "Cache-Control": "no-store" } }, + ); + } catch { + return Response.json( + { error: { code: "invalid_attachment" } }, + { status: 401, headers: { "Cache-Control": "no-store" } }, + ); + } +} diff --git a/packages/api/src/proxy/api/agent-api-contracts.ts b/packages/api/src/proxy/api/agent-api-contracts.ts index 84db98df..51da97c4 100644 --- a/packages/api/src/proxy/api/agent-api-contracts.ts +++ b/packages/api/src/proxy/api/agent-api-contracts.ts @@ -5,6 +5,7 @@ export const apiPolicyInput = z.object({ policy: z.enum(["baseline", "requestabl export const apiPolicy = z.object({ id: integrationRef, credentialId: z.string(), name: z.string(), description: z.string().nullable(), kind: z.enum(["bearer", "github", "linear", "model", "fly", "exe", "amp", "clickup", "x", "cloudflare", "hetzner"]), policy: z.enum(["baseline", "requestable", "disabled"]), available: z.boolean(), revision: z.number().int(), requiredScope: z.string() }); export const apiPolicyList = z.object({ integrations: z.array(apiPolicy) }); export const apiReflection = z.object({ identity: z.object({ id: z.uuid(), kind: z.enum(["oauth", "vm"]) }), scopes: z.array(z.string()), proxy: z.object({ requestUrl: z.url(), readResponseUrl: z.url(), requestTool:z.literal("request_api"), readResponseTool:z.literal("read_api_response"), authentication: z.string() }), integrations: z.array(apiPolicy.extend({ access: z.enum(["granted", "requestable", "unavailable"]), instructions: z.string(), requestExample:z.object({integration:integrationRef,method:z.enum(["GET","POST"]),path:z.string(),headers:z.record(z.string(),z.string()).optional(),body:z.string().optional()}) })) }); +export const proxyRequestLimit = 45_000_000; export const requestApiInput = z.object({ integration: integrationRef, method: z.enum(["GET", "HEAD", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"]), diff --git a/packages/api/src/proxy/api/rest.ts b/packages/api/src/proxy/api/rest.ts index 6d27f06b..41a89f2a 100644 --- a/packages/api/src/proxy/api/rest.ts +++ b/packages/api/src/proxy/api/rest.ts @@ -1,7 +1,7 @@ import { createPayloadInput, payloadReceipt, appendPayloadInput, finalizePayloadInput, attachmentInput } from "../../proxy/application/proxy-payloads"; import { operationRef, operationRead, operationReceipt } from "../../proxy/application/proxy-operations"; import { queryApiResponseInput, queryApiResponseResult } from "../../proxy/api/agent-api-contracts"; -import { apiReflection, apiPolicyList, apiPolicyInput, requestApiInput, requestApiResponse, readApiResponseInput, apiResponseChunk } from "../../proxy/api/agent-api-contracts"; +import { proxyRequestLimit, apiReflection, apiPolicyList, apiPolicyInput, requestApiInput, requestApiResponse, readApiResponseInput, apiResponseChunk } from "../../proxy/api/agent-api-contracts"; import { z } from "zod"; @@ -9,7 +9,7 @@ import { route, jsonSchema, type RouteContract } from "../../transport/rest/rout export const proxyRoutes = [ route("GET", "/api/v1/agent/reflection", [], { summary: "Discover agent identity and granted or requestable integration APIs", description: "OAuth authorization required. Availability reports connection state, without probing credential health. OAuth integration scopes are integration:{stable UUID}:{revocation epoch}; initial login need not request any integration scopes.", responses: { "200": { description: "Agent reflection", content: { "application/json": { schema: jsonSchema(apiReflection, "output") } } } } }, service => service.proxy.getApiReflection(), {scope: []}), - route("POST", "/api/v1/agent/requests", [], { summary: "Make an authorized credential-injected API request", description: "OAuth requires proxy:use. An enrolled VM sends its short-lived provider OIDC bearer token, X-Factorize-VM-Grant, and a fresh signed request proof in X-Factorize-VM-Proof. Only server-selected origins are used. Integration-wide grants are bounded by upstream credential permissions. Missing requestable access returns HTTP 403 with WWW-Authenticate insufficient_scope, scope and resource_metadata. Upstream status is returned in the result, including non-2xx. Text is UTF-8; other bodies are base64. Responses above 32 KiB are retained for 30 minutes and read in chunks. Revocation prevents subsequent calls and reads, but cannot undo upstream side effects.", responses: { "200": { description: "Upstream response or retained response handle", content: { "application/json": { schema: jsonSchema(requestApiResponse, "output") } } } } }, (service,{body,signal}) => service.proxy.requestApi(body,signal), {body: requestApiInput, maxBodyBytes: 45_000_000, scope: []}), + route("POST", "/api/v1/agent/requests", [], { security: [{bearerAuth:[]},{attachmentProof:[]}], summary: "Make an authorized credential-injected API request", description: "A portable client may send a signed X-Factorize-Attachment-Proof for its workload; the proxy applies the same workload scopes and provider policy as Fly. OAuth requires proxy:use. An enrolled VM sends its short-lived provider OIDC bearer token, X-Factorize-VM-Grant, and a fresh signed request proof in X-Factorize-VM-Proof. Only server-selected origins are used. Integration-wide grants are bounded by upstream credential permissions. Missing requestable access returns HTTP 403 with WWW-Authenticate insufficient_scope, scope and resource_metadata. Upstream status is returned in the result, including non-2xx. Text is UTF-8; other bodies are base64. Responses above 32 KiB are retained for 30 minutes and read in chunks. Revocation prevents subsequent calls and reads, but cannot undo upstream side effects.", responses: { "200": { description: "Upstream response or retained response handle", content: { "application/json": { schema: jsonSchema(requestApiResponse, "output") } } } } }, (service,{body,signal}) => service.proxy.requestApi(body,signal), {body: requestApiInput, maxBodyBytes: proxyRequestLimit, scope: []}), route("POST","/api/v1/proxy-payloads",[],{summary:"Reserve a temporary connection-bound request body",responses:{"200":{description:"Upload/staging receipt",content:{"application/json":{schema:jsonSchema(payloadReceipt,"output")}}}}},(service,{body})=>service.proxy.createProxyPayload(body),{body:createPayloadInput}), route("GET","/api/v1/proxy-payloads/{handle}",[],{summary:"Inspect an authorized temporary upload",responses:{"200":{description:"Payload receipt",content:{"application/json":{schema:jsonSchema(payloadReceipt,"output")}}}}},(service,{params})=>service.proxy.getProxyPayload(params.handle),{parameters:z.object({handle:z.uuid()})}), route("PUT","/api/v1/proxy-payloads/{handle}/bytes",[],{summary:"Stream a generic file into an authorized payload",description:"An authenticated owner browser can upload for its originating OAuth connection. Immutable finalized bytes; fixed 32 MiB limit. The originating OAuth connection is required.",requestBody:{required:true,content:{"application/octet-stream":{schema:{type:"string",format:"binary"}}}},responses:{"200":{description:"Finalized payload receipt",content:{"application/json":{schema:jsonSchema(payloadReceipt,"output")}}}}},(service,{params,request})=>service.proxy.uploadProxyPayload(params.handle,request!),{rawBody:true,parameters:z.object({handle:z.uuid()})}), diff --git a/packages/api/src/runtime/scheduled-maintenance.ts b/packages/api/src/runtime/scheduled-maintenance.ts index bf23db3d..08484595 100644 --- a/packages/api/src/runtime/scheduled-maintenance.ts +++ b/packages/api/src/runtime/scheduled-maintenance.ts @@ -26,4 +26,5 @@ export async function runScheduledMaintenance(env: Env) { await pruneTotp(db.pool); await pruneBrowserSessions(db); await pruneVmGrants(db); + await db.pool.query("DELETE FROM app.portable_attachments WHERE expires_at <= now()"); } diff --git a/packages/api/src/types.ts b/packages/api/src/types.ts index f8f4e340..b7ad46cc 100644 --- a/packages/api/src/types.ts +++ b/packages/api/src/types.ts @@ -19,6 +19,7 @@ export type OAuthProps = { explicitIntegrationScopes?: boolean; /** Expiry of the presented, verified OAuth access token. */ oauthExpiresAt?: number; + portableAttachment?: string; vmGrantId?: string; vmTokenExpiresAt?: number; authMethod?: "session" | "oauth" | "access_token" | "vm"; diff --git a/packages/api/src/vm-grants/application/vm-auth.ts b/packages/api/src/vm-grants/application/vm-auth.ts index 37fa1b85..831d7066 100644 --- a/packages/api/src/vm-grants/application/vm-auth.ts +++ b/packages/api/src/vm-grants/application/vm-auth.ts @@ -1,3 +1,4 @@ +import { portableScopes } from "../../portable/application/session"; import { z } from "zod"; import { databaseFor, type DatabaseClient } from "../../postgres/database"; import type { VmGrant } from "../storage/vm-grant-repository"; @@ -56,6 +57,7 @@ async function activeGrant(db: DatabaseClient, id: string, tenantId?: string, lo } export async function activeVmAuthorization(env: Env, auth: OAuthProps): Promise { + if (auth.authMethod === "vm" && auth.portableAttachment) return portableScopes(env,auth); if (auth.authMethod !== "vm" || !auth.vmGrantId || !auth.vmTokenExpiresAt || auth.vmTokenExpiresAt <= Date.now() / 1000) return null; const db = databaseFor(env); const grant = await activeGrant(db.pool, auth.vmGrantId, auth.tenantId); diff --git a/packages/api/src/worker.ts b/packages/api/src/worker.ts index 74450e4b..6866c57d 100644 --- a/packages/api/src/worker.ts +++ b/packages/api/src/worker.ts @@ -1,3 +1,4 @@ +import { attachmentRequest } from "./portable/application/session"; import { awsIssuerResponse } from "./integrations/providers/aws/issuer"; import { dispatchOAuth, provider, proxyOAuthResponse, withOAuthProvider } from "./auth/transport/worker-oauth"; import { runScheduledMaintenance } from "./runtime/scheduled-maintenance"; @@ -44,6 +45,9 @@ const backend = { async fetch(request: Request, env: Env, ctx: ExecutionContext) const oauth = provider(env); const url = new URL(request.url); const apiEnv = withOAuthProvider(env); + if (request.headers.has("X-Factorize-Attachment-Proof") || ["/api/v1/workloads/redeem", "/api/v1/workloads/heartbeat", "/api/v1/workloads/disconnect"].includes(url.pathname)) { + return attachmentRequest(apiEnv, request, (bound, auth) => protectedApiFetch(bound, apiEnv, auth, ctx)); + } if (url.pathname.startsWith("/internal/")) return new Response("Not found", {status: 404}); if ((url.pathname === "/mcp" || url.pathname.startsWith("/api/v1/")) && (request.headers.has(VM_GRANT_HEADER) || request.headers.has(VM_PROOF_HEADER))) { diff --git a/packages/api/test/cloudflare-tail.test.ts b/packages/api/test/cloudflare-tail.test.ts index c02657bb..1c6c8f7c 100644 --- a/packages/api/test/cloudflare-tail.test.ts +++ b/packages/api/test/cloudflare-tail.test.ts @@ -1,4 +1,5 @@ -import { describe, expect, it } from "vitest"; +import relay from "../../tail-relay/src/index"; +import { describe, expect, it, vi } from "vitest"; import { generateTailSecret, sanitizeTailEvent, signTailDelivery, suppressTailEvent, tailFingerprint, verifyTailDelivery } from "../src/integrations/application/cloudflare-tail"; describe("Cloudflare Tail ingestion", () => { @@ -23,6 +24,26 @@ describe("Cloudflare Tail ingestion", () => { expect(event.event.request.headers.accept).toBe("json"); }); + it("redacts both workload proofs before relay delivery and independently on ingestion", async () => { + const headers = { "X-Factorize-Attachment-Proof": "portable-marker", "x-FaCtOrIzE-vM-pRoOf": "fly-marker", accept: "application/json" }; + const event = { event: { request: { headers } } }; + const expected = { "X-Factorize-Attachment-Proof": "[redacted]", "x-FaCtOrIzE-vM-pRoOf": "[redacted]", accept: "application/json" }; + expect(sanitizeTailEvent(event).event.request.headers).toEqual(expected); + let sent = ""; + vi.stubGlobal("fetch", async (_url: string, init: RequestInit) => { + sent = String(init.body); + return new Response(); + }); + try { + const pending: Promise[] = []; + await relay.tail([event as unknown as TraceItem], { + FACTORIZE_TAIL_DESTINATION: "https://fixture.test", FACTORIZE_TAIL_SECRET: "fixture", + }, { waitUntil: (work: Promise) => pending.push(work) } as unknown as ExecutionContext); + await Promise.all(pending); + expect(JSON.parse(sent).event.request.headers).toEqual(expected); + } finally { vi.unstubAllGlobals(); } + }); + it("suppresses relay and ingestion failures and fingerprints repeats", async () => { expect(suppressTailEvent({ scriptName: "factorize-tail-relay" })).toBe(true); expect(suppressTailEvent({ logs: [{ message: "factorize_tail_ingestion failed" }] })).toBe(true); diff --git a/packages/api/test/portable-client-shutdown.test.ts b/packages/api/test/portable-client-shutdown.test.ts new file mode 100644 index 00000000..172f192f --- /dev/null +++ b/packages/api/test/portable-client-shutdown.test.ts @@ -0,0 +1,36 @@ +import { expect, it, vi } from "vitest"; +import { attach } from "../../workload-client/client"; + +it("aborts in-flight work and disconnects once ahead of a queued write and heartbeat", async () => { + vi.useFakeTimers({ toFake: ["setInterval", "clearInterval"] }); + let started!: () => void; + const inFlight = new Promise(resolve => { started = resolve; }); + const paths: string[] = []; + vi.stubGlobal("fetch", async (url: string, init: RequestInit) => { + const path = new URL(url).pathname; + paths.push(path); + if (path.endsWith("/requests")) { + started(); + return new Promise((_, reject) => init.signal!.addEventListener("abort", () => reject(Error("aborted")), {once:true})); + } + return Response.json({ active: true }); + }); + try { + const session = await attach("https://fixture.test", { + tenant: crypto.randomUUID(), workload: crypto.randomUUID(), attachment: crypto.randomUUID(), secret: "fixture", + }); + const request = { integration: crypto.randomUUID(), method: "POST" as const, path: "/fixture" }; + const first = session.request(request); + await inFlight; + const queued = session.request(request); + const outcomes = Promise.allSettled([first, queued]); + vi.advanceTimersByTime(10000); + await Promise.all([session.close(), session.close()]); + expect((await outcomes).map(outcome => outcome.status)).toEqual(["rejected", "rejected"]); + expect(paths).toEqual(["/api/v1/workloads/redeem", "/api/v1/agent/requests", "/api/v1/workloads/disconnect"]); + expect(() => session.request(request)).toThrow("closed"); + } finally { + vi.unstubAllGlobals(); + vi.useRealTimers(); + } +}); diff --git a/packages/api/test/portable-workloads.postgres.test.ts b/packages/api/test/portable-workloads.postgres.test.ts new file mode 100644 index 00000000..6d9368aa --- /dev/null +++ b/packages/api/test/portable-workloads.postgres.test.ts @@ -0,0 +1,364 @@ +import {createHash, generateKeyPairSync, sign} from "node:crypto"; +import { protectedApiFetch } from "../src/protected-api"; +import { expect, it, vi } from "vitest"; +import { execFile } from "node:child_process"; +import { promisify } from "node:util"; +import { cp, mkdtemp, mkdir, readdir, readFile, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { createServer } from "node:https"; +import type { AddressInfo } from "node:net"; +import { fileURLToPath } from "node:url"; +import worker from "../src/worker"; +import { encrypt } from "../src/crypto"; +import { XConnectionRepository } from "../src/credentials/storage/x-connection-repository"; +import { loadingFixture } from "./helpers/loading-fixture"; + +vi.mock("cloudflare:workers", () => ({ + WorkerEntrypoint: class {}, + DurableObject: class {}, + WorkflowEntrypoint: class {}, +})); +vi.mock("@cloudflare/workers-oauth-provider", () => ({ + OAuthProvider: class {}, + AuthorizationError: class extends Error {}, + getOAuthApi: vi.fn(), +})); +const database = process.env.AUTH_TEST_DATABASE_URL; +const clientDir = fileURLToPath( + new URL("../../workload-client/", import.meta.url), +); +const run = promisify(execFile); + +it.skipIf(!database)( + "binds two HTTPS client processes to separate live grants and single-use sessions", + async () => { + const f = await loadingFixture(database!); + const dir = await mkdtemp(join(tmpdir(), "portable-test-")); + const calls: string[] = []; + let heartbeats = 0; + const captured: Request[] = []; + let beforeProxy: (() => Promise) | undefined; + const dispatch = (request: Request) => + worker.fetch(request, f.env, {} as ExecutionContext); + const server = createServer(); + try { + const cert = join(dir, "cert.pem"), + key = join(dir, "key.pem"); + await run("openssl", [ + "req", + "-x509", + "-newkey", + "rsa:2048", + "-nodes", + "-days", + "1", + "-subj", + "/CN=localhost", + "-addext", + "subjectAltName=IP:127.0.0.1", + "-keyout", + key, + "-out", + cert, + ]); + server.setSecureContext({ + cert: await readFile(cert), + key: await readFile(key), + }); + server.on("request", async (req, res) => { + try { + const chunks = []; + for await (const chunk of req) chunks.push(chunk); + const request = new Request(f.env.APP_ORIGIN + req.url, { + method: req.method, + headers: req.headers as Record, + body: Buffer.concat(chunks), + }); + if (request.url.endsWith("/agent/requests")) { + const header = "X-Factorize-Attachment-Proof"; + const proof = request.headers.get(header)!; + const invalid = new Request(request.url, {method:"POST",headers:request.headers,body:"{}"}); + invalid.headers.set(header, proof.slice(0, proof.lastIndexOf(".") + 1) + Buffer.alloc(64).toString("base64url")); + expect((await dispatch(invalid)).status).toBe(401); + expect(invalid.bodyUsed).toBe(false); + captured.push(request.clone() as Request); + const changed = new Request(request.url,{method:"POST",headers:request.headers,body:JSON.stringify({integration:crypto.randomUUID(),method:"GET",path:"/2/users/me"})}); + expect((await dispatch(changed)).status).toBe(401); + const hook = beforeProxy; + beforeProxy = undefined; + await hook?.(); + } + const response = await dispatch(request); + if(request.url.endsWith("/heartbeat") && response.ok) heartbeats++; + response.headers.forEach((value, name) => res.setHeader(name, value)); + res.writeHead(response.status); + res.end(Buffer.from(await response.arrayBuffer())); + } catch { + res.writeHead(500); + res.end(); + } + }); + await new Promise((resolve) => + server.listen(0, "127.0.0.1", resolve), + ); + f.env.APP_ORIGIN = + "https://127.0.0.1:" + (server.address() as AddressInfo).port; + const origin = f.env.APP_ORIGIN; + const upstreams = [ + "https://api.x.com/2/users/me", + "https://api.cloudflare.com/client/v4/zones", + ]; + vi.stubGlobal("fetch", async (target: URL, init: RequestInit) => { + if(init.method === "POST") { + expect(String(target)).toBe("https://api.cloudflare.com/client/v4/zones/fixture/dns_records"); + expect(await new Response(init.body).text()).toBe(JSON.stringify({type:"TXT",content:"fixture"})); + } else expect(upstreams).toContain(String(target)); + expect(new Headers(init.headers).get("Authorization")).toBe( + "Bearer fixture-only", + ); + calls.push(String(target)); + return Response.json({ ok: true }); + }); + const xId = crypto.randomUUID(), + cfId = crypto.randomUUID(); + const repo = new XConnectionRepository( + f.db, + f.tenantId, + f.env.CREDENTIAL_ENCRYPTION_KEY, + ); + await repo.create({ + id: xId, + name: "Fixture", + clientId: "fixture", + clientSecret: "fixture", + scopes: ["users.read"], + }); + await repo.completeOAuth(xId, { + accessToken: "fixture-only", + refreshToken: "fixture", + expiresAt: new Date(Date.now() + 300000).toISOString(), + accountId: "123", + accountHandle: "fixture", + grantedScopes: ["users.read"], + }); + await f.db.pool.query( + "INSERT INTO app.cloudflare_connections(tenant_id,id,account_name,encrypted_credentials) VALUES($1,$2,'Fixture',$3)", + [ + f.tenantId, + cfId, + await encrypt( + JSON.stringify({ + access: "fixture-only", + expiration: Date.now() + 300000, + }), + f.env.CREDENTIAL_ENCRYPTION_KEY, + ), + ], + ); + const cf = ( + await f.db.pool.query( + "INSERT INTO app.agent_integrations(tenant_id,kind,credential_id,name,available) VALUES($1,'cloudflare',$2,'Fixture',true) RETURNING id", + [f.tenantId, cfId], + ) + ).rows[0].id; + const x = ( + await f.db.pool.query( + "SELECT id FROM app.agent_integrations WHERE tenant_id=$1 AND kind='x' AND credential_id=$2", + [f.tenantId, xId], + ) + ).rows[0].id; + const owner = (path: string, method = "POST", body?: unknown) => + dispatch( + new Request(origin + "/api/v1/workloads/grants" + path, { + method, + headers: { + Cookie: f.cookie, + Origin: origin, + "Content-Type": "application/json", + }, + body: body ? JSON.stringify(body) : undefined, + }), + ); + async function grant(integration: string) { + const row=(await f.db.pool.query("SELECT epoch FROM app.agent_integrations WHERE tenant_id=$1 AND id=$2",[f.tenantId,integration])).rows[0]; + const scopes=["proxy:use", "integration:"+integration+":"+row.epoch]; + const body={workload:crypto.randomUUID(),permissions:{scopes}}; + expect((await owner("", "POST", body)).status).toBe(403); + const response = await protectedApiFetch(new Request(origin+"/api/v1/workloads/grants",{ + method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(body) + }), f.env, {...f.auth, authMethod:"oauth", oauthGrantId:"fixture-operator",oauthClientId:"fixture", + oauthExpiresAt:Date.now()/1000+300,scopes:["vms:edit",...scopes]}, {} as ExecutionContext); + expect(response.status).toBe(200); + return (await response.json<{grantId:string}>()).grantId; + } + async function enroll(id: string) { + const response = await owner("/" + id + "/enrollments"); + expect(response.status).toBe(200); + return response.json<{tenant:string;workload:string;attachment:string;secret:string}>(); + } + async function signedSession(grantId: string) { + const {tenant, workload, attachment, secret} = await enroll(grantId); + const {publicKey, privateKey} = generateKeyPairSync("ec", {namedCurve:"P-256"}); + let seq = 0; + async function post(path: string, input: unknown) { + const body = JSON.stringify(input); + const encode = (obj: unknown) => Buffer.from(JSON.stringify(obj)).toString("base64url"); + const claims = {tenant, workload, attachment, seq:seq++, iat:Math.floor(Date.now()/1000), + htu:origin+path, htm:"POST", body:createHash("sha256").update(body).digest("base64url")}; + const message = encode({alg:"ES256", typ:"factorize-attachment+jwt"})+"."+encode(claims); + const signature = sign("sha256", Buffer.from(message), {key:privateKey,dsaEncoding:"ieee-p1363"}).toString("base64url"); + return dispatch(new Request(origin+path,{method:"POST",headers:{"Content-Type":"application/json", + "X-Factorize-Attachment-Proof":message+"."+signature},body})); + } + expect((await post("/api/v1/workloads/redeem",{secret,key:publicKey.export({format:"jwk"})})).status).toBe(200); + return post; + } + const first = await grant(x), + second = await grant(cf); + const a = await enroll(first), + b = await enroll(second); + const cwd = join(dir, "original"), + copy = join(dir, "copy"); + await mkdir(cwd); + await cp(clientDir, cwd, { recursive: true }); + // The process accepts enrollment only on stdin. Tests return status codes only. + const script = `import {attach} from "./client.ts";import {text} from "node:stream/consumers"; + const [origin,integration,path,wrong,wrongPath,mode]=process.argv.slice(1); + try {const s=await attach(origin,JSON.parse(await text(process.stdin))); + for(const [id,p] of [[integration,path],[wrong,wrongPath]]) { + try {console.log((await s.request({integration:id,method:"GET",path:p})).status)} catch {console.log("denied")} + } + if(mode==="heartbeat"){ + console.log((await s.request({integration,method:"POST",path:"/zones/fixture/dns_records",body:JSON.stringify({type:"TXT",content:"fixture"})})).status); + await new Promise(resolve=>setTimeout(resolve,11500)); + } + if(mode==="exit"){ + try {await s.request({integration,method:"POST",path:"/2/tweets",body:"{}"});console.log("unexpected");} catch {console.log("scope denied");} + } + if(mode!=="exit")await s.close(); + }catch{console.log("denied")}`; + function client( + ticket: unknown, + id: string, + path: string, + wrong: string, + wrongPath: string, + folder = cwd, + mode = "close", + ) { + const child = execFile( + process.execPath, + [ + "--input-type=module", + "-e", + script, + origin, + id, + path, + wrong, + wrongPath, + mode, + ], + { cwd: folder, env: { ...process.env, NODE_EXTRA_CA_CERTS: cert } }, + ); + child.stdin!.end(JSON.stringify(ticket)); + return new Promise((resolve, reject) => { + let out = ""; + child.stdout!.on("data", (s) => (out += s)); + child.once("error", reject); + child.once("exit", (code) => + code === 0 + ? resolve(out.trim()) + : reject(Error("Fixture process failed")), + ); + }); + } + const A = (ticket: unknown, folder = cwd, mode = "close") => + client(ticket, x, "/2/users/me", cf, "/zones", folder, mode); + const B = (ticket: unknown) => + client(ticket, cf, "/zones", x, "/2/users/me"); + expect(await A({...a,workload:b.workload})).toBe("denied"); + expect(await A({ ...a, tenant: f.otherTenant })).toBe("denied"); + expect( + ( + await Promise.all([A(a, cwd, "exit"), A(a, cwd, "exit"), client(b,cf,"/zones",x,"/2/users/me",cwd,"heartbeat")]) + ).sort(), + ).toEqual(["200\ndenied\n200", "200\ndenied\nscope denied", "denied"]); + expect(heartbeats).toBeGreaterThan(0); + const disconnected=await f.db.pool.query("SELECT expires_at <= clock_timestamp() AS closed FROM app.portable_attachments WHERE tenant_id=$1 AND id=$2",[f.tenantId,b.attachment]); + expect(disconnected.rows[0].closed).toBe(true); + expect(calls.sort()).toEqual([...upstreams,"https://api.cloudflare.com/client/v4/zones/fixture/dns_records"].sort()); + for (const request of captured) + expect((await dispatch(request.clone() as Request)).status).toBe(401); + await cp(cwd, copy, { recursive: true }); + expect((await readdir(copy)).sort()).toEqual( + (await readdir(clientDir)).sort(), + ); + expect(await A(a, copy)).toBe("denied"); + const pending = await enroll(first); + await f.db.pool.query( + "UPDATE app.portable_attachments SET expires_at=now()-interval '1 second' WHERE tenant_id=$1 AND id=ANY($2::uuid[])", + [f.tenantId, [a.attachment, pending.attachment]], + ); + expect(await A(pending)).toBe("denied"); + const stale = await enroll(second); + beforeProxy = async () => { + await f.db.pool.query( + "UPDATE app.portable_attachments SET expires_at=now() WHERE tenant_id=$1 AND id=$2", + [f.tenantId, stale.attachment], + ); + }; + expect(await B(stale)).toBe("denied\ndenied\ndenied"); + const live = await enroll(first); + beforeProxy = async () => { + expect((await owner("/" + first, "DELETE")).status).toBe(200); + }; + expect(await A(live)).toBe("denied\ndenied\ndenied"); + expect((await owner("/" + first, "DELETE")).status).toBe(200); + const foreign = crypto.randomUUID(); + await f.db.pool.query("INSERT INTO app.portable_grants(tenant_id,id,workload,scopes) VALUES($1,$2,$3,'{}')", + [f.otherTenant, foreign, crypto.randomUUID()]); + // Give two live principals the same integration permissions; the handle belongs to only one. + const originator = await signedSession(second); + const peer = await signedSession(await grant(cf)); + const handle = crypto.randomUUID(); + const content = Buffer.from("fixture"); + await f.db.pool.query(`INSERT INTO app.agent_proxy_responses + (tenant_id,id,identity_id,integration_id,integration_epoch,object_key,size,expires_at) + SELECT tenant_id,$2,$3,id,operation_epoch,'fixture-response',$5,now()+interval '1 minute' + FROM app.agent_integrations WHERE tenant_id=$1 AND id=$4`,[f.tenantId,handle,second,cf,content.length]); + const get = vi.fn(async () => ({arrayBuffer: async () => Uint8Array.from(content).buffer})); + f.env.PROXY_ARTIFACTS = {get} as unknown as R2Bucket; + for (const action of ["read","query"]) { + const path = "/api/v1/agent/responses/"+action; + const input = action === "read" ? {handle,offset:0} : {handle,mode:"bytes"}; + const allowed = await originator(path,input); + expect(allowed.status).toBe(200); + expect(await allowed.text()).toContain(content.toString("base64")); + get.mockClear(); + expect((await peer(path,input)).status).toBe(404); + expect(get).not.toHaveBeenCalled(); + } + expect((await owner("/"+second,"DELETE")).status).toBe(200); + for (const action of ["read","query"]) { + expect((await originator("/api/v1/agent/responses/"+action,{handle,offset:0})).status).toBe(401); + expect(get).not.toHaveBeenCalled(); + } + const missing = await owner("/" + crypto.randomUUID(), "DELETE"); + const hidden = await owner("/" + foreign, "DELETE"); + expect([missing.status,hidden.status]).toEqual([404,404]); + expect(await hidden.json()).toEqual(await missing.json()); + expect((await f.db.pool.query("SELECT revoked_at FROM app.portable_grants WHERE tenant_id=$1 AND id=$2",[f.otherTenant,foreign])).rows[0].revoked_at).toBeNull(); + expect(calls).toHaveLength(3); + expect((await owner("/" + first + "/enrollments")).status).toBe(403); + } finally { + server.closeAllConnections(); + server.close(); + vi.unstubAllGlobals(); + await f.cleanup(); + await rm(dir, { recursive: true, force: true }); + } + }, + 60000, +); diff --git a/packages/api/test/vm-enrollment.postgres.test.ts b/packages/api/test/vm-enrollment.postgres.test.ts index 6138cd11..aba90141 100644 --- a/packages/api/test/vm-enrollment.postgres.test.ts +++ b/packages/api/test/vm-enrollment.postgres.test.ts @@ -149,6 +149,7 @@ describe.skipIf(!url)("Fly permission enrollment", () => { method, headers: { Cookie: f.cookie, Origin: f.env.APP_ORIGIN, "Content-Type": "application/json" }, body: body === undefined ? undefined : JSON.stringify(body), }), env, { waitUntil() {} } as unknown as ExecutionContext); + expect((await sessionRequest("/api/v1/workloads/grants/" + active.id + "/enrollments", "POST")).status).toBe(403); const edit = { target: { kind: "existing", grantId: active.id, expectedRevision: 1 }, permissions: { scopes: ["vms:read"] } }; expect((await sessionRequest("/api/v1/vms/grants", "POST", edit)).status).toBe(200); expect((await sessionRequest("/api/v1/vms/grants", "POST", edit)).status).toBe(409); diff --git a/packages/docs/openapi.yaml b/packages/docs/openapi.yaml index e06c259e..939c2c30 100644 --- a/packages/docs/openapi.yaml +++ b/packages/docs/openapi.yaml @@ -15,6 +15,10 @@ components: type: http scheme: bearer bearerFormat: OAuth2 + attachmentProof: + type: apiKey + in: header + name: X-Factorize-Attachment-Proof cookieAuth: type: apiKey in: cookie @@ -9626,9 +9630,12 @@ paths: x-owner-session-required: false /api/v1/agent/requests: post: + security: + - bearerAuth: [] + - attachmentProof: [] summary: Make an authorized credential-injected API request description: |- - OAuth requires proxy:use. An enrolled VM sends its short-lived provider OIDC bearer token, X-Factorize-VM-Grant, and a fresh signed request proof in X-Factorize-VM-Proof. Only server-selected origins are used. Integration-wide grants are bounded by upstream credential permissions. Missing requestable access returns HTTP 403 with WWW-Authenticate insufficient_scope, scope and resource_metadata. Upstream status is returned in the result, including non-2xx. Text is UTF-8; other bodies are base64. Responses above 32 KiB are retained for 30 minutes and read in chunks. Revocation prevents subsequent calls and reads, but cannot undo upstream side effects. + A portable client may send a signed X-Factorize-Attachment-Proof for its workload; the proxy applies the same workload scopes and provider policy as Fly. OAuth requires proxy:use. An enrolled VM sends its short-lived provider OIDC bearer token, X-Factorize-VM-Grant, and a fresh signed request proof in X-Factorize-VM-Proof. Only server-selected origins are used. Integration-wide grants are bounded by upstream credential permissions. Missing requestable access returns HTTP 403 with WWW-Authenticate insufficient_scope, scope and resource_metadata. Upstream status is returned in the result, including non-2xx. Text is UTF-8; other bodies are base64. Responses above 32 KiB are retained for 30 minutes and read in chunks. Revocation prevents subsequent calls and reads, but cannot undo upstream side effects. Accepts a scoped bearer token or interactive owner session. responses: @@ -9697,9 +9704,6 @@ paths: operationId: post_api_v1_agent_requests tags: - agent - security: - - bearerAuth: [] - - cookieAuth: [] x-required-scope: [] x-owner-session-required: false requestBody: @@ -14451,3 +14455,382 @@ paths: type: string format: uuid pattern: ^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$ + /api/v1/workloads/grants: + post: + summary: Create a portable workload grant from the operator's effective workload permissions + responses: + "200": + description: Create a portable workload grant from the operator's effective workload permissions + content: + application/json: + schema: + type: object + properties: + grantId: + type: string + format: uuid + pattern: ^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$ + required: + - grantId + 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" + "415": + $ref: "#/components/responses/Error415" + "429": + $ref: "#/components/responses/Error429" + "500": + $ref: "#/components/responses/Error500" + "503": + $ref: "#/components/responses/Error503" + description: |- + Requires the vms:edit scope. + + Accepts a scoped bearer token or interactive owner session. + operationId: post_api_v1_workloads_grants + tags: + - workloads + security: + - bearerAuth: [] + - cookieAuth: [] + x-required-scope: vms:edit + x-owner-session-required: false + requestBody: + required: true + content: + application/json: + schema: + type: object + properties: + workload: + type: string + format: uuid + pattern: ^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$ + permissions: + type: object + properties: + scopes: + maxItems: 100 + type: array + items: + type: string + minLength: 1 + maxLength: 200 + required: + - scopes + additionalProperties: false + required: + - workload + - permissions + additionalProperties: false + /api/v1/workloads/grants/{grantId}/enrollments: + post: + summary: Issue a two-minute single-use portable enrollment + responses: + "200": + description: Issue a two-minute single-use portable enrollment + content: + application/json: + schema: + type: object + properties: + tenant: + type: string + format: uuid + pattern: ^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$ + workload: + type: string + format: uuid + pattern: ^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$ + attachment: + type: string + format: uuid + pattern: ^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$ + secret: + type: string + required: + - tenant + - workload + - attachment + - secret + 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" + description: |- + Requires the vms:edit scope. + + An interactive owner session is required; bearer tokens cannot call this operation. + operationId: post_api_v1_workloads_grants_grantId_enrollments + tags: + - workloads + security: + - cookieAuth: [] + x-required-scope: vms:edit + x-owner-session-required: true + parameters: + - name: grantId + in: path + required: true + schema: + type: string + format: uuid + pattern: ^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$ + /api/v1/workloads/grants/{grantId}: + delete: + summary: Revoke a portable workload grant + responses: + "200": + description: Revoke a portable workload grant + content: + application/json: + schema: + type: object + properties: + revoked: + type: boolean + required: + - revoked + 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" + description: |- + Requires the vms:edit scope. + + An interactive owner session is required; bearer tokens cannot call this operation. + operationId: delete_api_v1_workloads_grants_grantId + tags: + - workloads + security: + - cookieAuth: [] + x-required-scope: vms:edit + x-owner-session-required: true + parameters: + - name: grantId + in: path + required: true + schema: + type: string + format: uuid + pattern: ^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$ + /api/v1/workloads/redeem: + post: + summary: Authenticate portable workload redeem + responses: + "200": + description: Authenticate portable workload redeem + content: + application/json: + schema: + type: object + properties: + active: + type: boolean + required: + - active + 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" + "415": + $ref: "#/components/responses/Error415" + "429": + $ref: "#/components/responses/Error429" + "500": + $ref: "#/components/responses/Error500" + "503": + $ref: "#/components/responses/Error503" + security: + - attachmentProof: [] + description: |- + Requires an ES256 X-Factorize-Attachment-Proof bound to the exact request. See docs/portable-workloads.md. + + Accepts a scoped bearer token or interactive owner session. + operationId: post_api_v1_workloads_redeem + tags: + - workloads + x-required-scope: [] + x-owner-session-required: false + requestBody: + required: true + content: + application/json: + schema: + type: object + properties: + secret: + type: string + pattern: ^[A-Za-z0-9_-]{43}$ + key: + type: object + properties: + kty: + type: string + const: EC + crv: + type: string + const: P-256 + x: + type: string + pattern: ^[A-Za-z0-9_-]{43}$ + y: + type: string + pattern: ^[A-Za-z0-9_-]{43}$ + required: + - kty + - crv + - x + - y + additionalProperties: false + required: + - secret + - key + additionalProperties: false + /api/v1/workloads/heartbeat: + post: + summary: Authenticate portable workload heartbeat + responses: + "200": + description: Authenticate portable workload heartbeat + content: + application/json: + schema: + type: object + properties: + active: + type: boolean + required: + - active + 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" + "415": + $ref: "#/components/responses/Error415" + "429": + $ref: "#/components/responses/Error429" + "500": + $ref: "#/components/responses/Error500" + "503": + $ref: "#/components/responses/Error503" + security: + - attachmentProof: [] + description: |- + Requires an ES256 X-Factorize-Attachment-Proof bound to the exact request. See docs/portable-workloads.md. + + Accepts a scoped bearer token or interactive owner session. + operationId: post_api_v1_workloads_heartbeat + tags: + - workloads + x-required-scope: [] + x-owner-session-required: false + requestBody: + required: true + content: + application/json: + schema: + type: object + properties: {} + additionalProperties: false + /api/v1/workloads/disconnect: + post: + summary: Authenticate portable workload disconnect + responses: + "200": + description: Authenticate portable workload disconnect + content: + application/json: + schema: + type: object + properties: + active: + type: boolean + required: + - active + 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" + "415": + $ref: "#/components/responses/Error415" + "429": + $ref: "#/components/responses/Error429" + "500": + $ref: "#/components/responses/Error500" + "503": + $ref: "#/components/responses/Error503" + security: + - attachmentProof: [] + description: |- + Requires an ES256 X-Factorize-Attachment-Proof bound to the exact request. See docs/portable-workloads.md. + + Accepts a scoped bearer token or interactive owner session. + operationId: post_api_v1_workloads_disconnect + tags: + - workloads + x-required-scope: [] + x-owner-session-required: false + requestBody: + required: true + content: + application/json: + schema: + type: object + properties: {} + additionalProperties: false diff --git a/packages/tail-relay/src/index.ts b/packages/tail-relay/src/index.ts index e6951b6a..3b69862e 100644 --- a/packages/tail-relay/src/index.ts +++ b/packages/tail-relay/src/index.ts @@ -1,5 +1,5 @@ interface Env { FACTORIZE_TAIL_DESTINATION: string; FACTORIZE_TAIL_SECRET: string } -const sensitive = /authorization|cookie|token|secret|password|credential|api[-_]?key|prompt|body/i; +const sensitive = /authorization|cookie|token|secret|password|credential|api[-_]?key|prompt|body|^x-factorize-(?:attachment|vm)-proof$/i; const encoder = new TextEncoder(); function sanitize(value: unknown, depth = 0): any { if (depth > 8) return "[truncated]"; diff --git a/packages/workload-client/client.ts b/packages/workload-client/client.ts new file mode 100644 index 00000000..dcd49808 --- /dev/null +++ b/packages/workload-client/client.ts @@ -0,0 +1,102 @@ +import { createHash } from "node:crypto"; +import { Buffer } from "node:buffer"; + +import type { paths } from "factorize-api-client"; +type ProxyInput = paths["/api/v1/agent/requests"]["post"]["requestBody"]["content"]["application/json"]; +type Enrollment = { workload:string; tenant: string; attachment: string; secret: string }; +const encoded = (value: unknown) => + Buffer.from(JSON.stringify(value)).toString("base64url"); +const header = encoded({ alg: "ES256", typ: "factorize-attachment+jwt" }); + +export async function attach( + origin: string, + { tenant, workload, attachment, secret }: Enrollment, +) { + const url = new URL(origin); + if (url.protocol !== "https:" || url.origin !== origin) + throw new Error("An HTTPS origin is required"); + const pair = await crypto.subtle.generateKey( + { name: "ECDSA", namedCurve: "P-256" }, + false, + ["sign", "verify"], + ); + const { kty, crv, x, y } = await crypto.subtle.exportKey( + "jwk", + pair.publicKey, + ); + let seq = 0; + const lifetime = new AbortController(); + let pending = Promise.resolve(); + let disconnect: Promise | undefined; + + async function transmit(path: string, input: unknown, signal: AbortSignal) { + signal.throwIfAborted(); + const htu = origin + path, + body = JSON.stringify(input); + const payload = encoded({ + tenant, + workload, + attachment, + seq: seq++, + iat: Math.floor(Date.now() / 1000), + htu, + htm: "POST", + body: createHash("sha256").update(body).digest("base64url"), + }); + const signed = header + "." + payload; + const signature = await crypto.subtle.sign( + { name: "ECDSA", hash: "SHA-256" }, + pair.privateKey, + new TextEncoder().encode(signed), + ); + signal.throwIfAborted(); + const response = await fetch(htu, { + method: "POST", + redirect: "error", + signal: AbortSignal.any([signal, AbortSignal.timeout(10000)]), + headers: { + "Content-Type": "application/json", + "X-Factorize-Attachment-Proof": + signed + "." + Buffer.from(signature).toString("base64url"), + }, + body, + }); + if (!response.ok) { + await response.body?.cancel(); + throw new Error("Workload request denied (" + response.status + ")"); + } + return response.json(); + } + + function send(path: string, input: unknown) { + const operation = pending.then(() => transmit(path, input, lifetime.signal)); + pending = operation.then( + () => {}, + () => {}, + ); + return operation; + } + await send("/api/v1/workloads/redeem", { key: { kty, crv, x, y }, secret }); + secret = ""; + const timer = setInterval(() => { + if (!lifetime.signal.aborted) + void send("/api/v1/workloads/heartbeat", {}).catch(() => { + lifetime.abort(); + clearInterval(timer); + }); + }, 10000); + timer.unref(); + return { + request(input: ProxyInput) { + if (lifetime.signal.aborted) throw new Error("Workload session closed"); + return send("/api/v1/agent/requests", input); + }, + close() { + clearInterval(timer); + lifetime.abort(); + // Disconnect gets the next sequence immediately and outlives the aborted queue. + disconnect ??= transmit("/api/v1/workloads/disconnect", {}, new AbortController().signal).then(() => {}); + return disconnect; + }, + }; +} diff --git a/packages/workload-client/example.ts b/packages/workload-client/example.ts new file mode 100644 index 00000000..09be6d54 --- /dev/null +++ b/packages/workload-client/example.ts @@ -0,0 +1,16 @@ +import { attach } from "./client.ts"; +import { text } from "node:stream/consumers"; + +const [origin, integration, path] = process.argv.slice(2); +try { + const session = await attach(origin!, JSON.parse(await text(process.stdin))); + try { + const result = await session.request({integration:integration!, method:"GET", path:path!}); + console.log("Upstream status", result.status); + } finally { + await session.close(); + } +} catch { + console.error("Workload example failed"); + process.exitCode = 1; +} diff --git a/packages/workload-client/package.json b/packages/workload-client/package.json new file mode 100644 index 00000000..6aea069c --- /dev/null +++ b/packages/workload-client/package.json @@ -0,0 +1,11 @@ +{ + "name": "factorize-workload-client", + "version": "0.1.0", + "private": true, + "type": "module", + "dependencies": {"factorize-api-client":"0.1.0"}, + "exports": "./client.ts", + "engines": { + "node": ">=24.21.0" + } +}