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..05ff47ea 100644 --- a/docs/fly-guest-transport.md +++ b/docs/fly-guest-transport.md @@ -1,60 +1,21 @@ -# 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 the documented default boot +behavior. Their init process only sleeps; image CMD does not launch a job. The +backend polls startup for at most three minutes, and starts stopped/suspended +Machines once without replaying ambiguous responses. It does not race image +preparation with a start request in the `created` state. 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/docs/gen-2922-progress.md b/docs/gen-2922-progress.md new file mode 100644 index 00000000..22432453 --- /dev/null +++ b/docs/gen-2922-progress.md @@ -0,0 +1,137 @@ +# GEN-2922 completion ledger + +Implementation complete on PR #404 (`codex/gen-2922-vendor-identity`). Final +application code is `cc5ae0e`; the subsequent ledger commit changes documentation +only. Production has not been deployed or migrated. Review and the documented +maintenance/cutover gates remain release responsibilities. + +## Acceptance checklist + +- [x] exe.dev and Fly vendor signature, issuer, audience, lifetime and exact + provisioned VM/run verification; immutable tenant/run bindings, renewal and + signing-key rotation; no Factorize-issued VM bearer fallback. +- [x] Real vendor tokens and live guest/helper/backend checks for both vendors; + actual evidence is separated from fixtures below. +- [x] Token-free owner/session/API-scope snapshot and immutable selected credential + IDs; job edits do not broaden existing runs, including empty-scope runs. +- [x] Backend API/MCP and outbound admission use current vendor identity and run + eligibility. Cancellation/terminal state denies normal access immediately. + Stopping artifact finalization requires an additional signed upload grant. +- [x] Server-encrypted bearer/model storage, write-only secret input, safe metadata, + owner-only ChatGPT device authorization and API-key replacement. Server-side + refresh is serialized, persisted and checked against disconnect/rotation. +- [x] Existing GitHub App and Linear connections reused without new upstream + permission layers. Only explicit tenant/run selections authorize forwarding. +- [x] Streaming backend proxy: GitHub REST/GraphQL Bearer, smart HTTP Basic, + raw/archive routes, Linear, custom HTTPS origins and model streaming. +- [x] Durable per-run disconnect revocation; reconnect cannot revive old grants. +- [x] Runtime provisioning, exclusive exe.dev WIF attachment checks, guest discovery, + localhost helper, Worker-compatible Fly guest exec, cancellation and cleanup. +- [x] Standalone proxy workspace/image, certificate tunnel, pairing/control/enrollment, + guest bearer, unlock API/UI, browser capabilities and obsolete dependencies removed. +- [x] Guarded migration 0052 and operator preparation; drain all runs, retain managed + records and execution connections/configuration, tombstone unreadable inner + ciphertext, disable affected jobs without silently altering selections. +- [x] Job repair UI and DB/browser behavior tests; missing selections remain explicit + until the owner replaces/removes them and starts a newly authorized run. +- [x] OpenAPI/client generation, API namespace and package boundaries, user/operator + documentation, release/rollback gates and superseded work reconciled. +- [x] Complete required root validation after the final application code change. + +## Deterministic evidence + +The complete root suite on `cc5ae0e` passed with Node 24.12.0 and npm 11.19.0 +on the isolated exe.dev validation VM, using the documented immutable runner +image and `npm ci`. `npm run test:local` bootstrapped only its isolated local +PostgreSQL database and ran the root `npm test` suite: + +- Backend: 104 files, 670 tests passed, five intentionally skipped; generated + contract drift, boundaries, docs, app build and Worker dry-run passed. +- Compiled static app/API/PostgreSQL integration: two tests passed. +- Functional Chromium: six tests passed. Browser unit checks: 94 passed, one skipped. +- Process cancellation/deadline checks: four passed. Backend protocol/guest/signature + checks: 30 passed. Docker lifecycle/infrastructure E2E: both tests passed. + +Behavioral fixtures cover cross-tenant/unselected denial, identity errors and +VM/run mismatches, signing-key rotation, immutable scopes, restart/renewal, +termination/cancellation, owner session revocation, provider connection reuse, +permanent disconnect/reconnect denial, Git API/smart-HTTP authentication and +headers, streaming, model refresh concurrency/persistence and repairability. +Device authorization fixtures cover encrypted challenges, polling limits, PKCE, +expiration/cancel and replacement/disconnect without credential disclosure. + +The image smoke ran through the image's existing login profile and launches a +non-login exedev Chromium process. SSH itself does not inherit the OCI browser +path. This does not close GEN-2889's separate requirement that Factorize job +processes inherit the image environment; no unrelated runner-image gate is claimed. + +## Earlier live vendor primitives — 2026-11-17 + +Real Fly RS256 JWTs from `/.fly/api` were verified against live discovery/JWKS: +organization `brendan-asselstine`, isolated app +`factorize-gen2922-identity-20261117`, Machine `811112ea04e618`. The issuer uses +the organization slug, not its display name or app name. A renewed token passed; +wrong issuer, audience, subject, VM and inactive run bindings were rejected. + +Real exe.dev WIF tokens from a uniquely attached test integration were verified +against live discovery/JWKS at `https://exe.dev/issuer/kilo-extra-sun`. An +unattached validation VM received HTTP 403. The integration subject was not +assumed to identify a VM; exclusive vendor attachment supplied that binding. +Wrong issuer/audience/subject/VM and inactive run bindings were rejected. +Temporary primitive-test resources were removed. + +## Live guest/backend verification — completed 2026-11-17 + +These checks provisioned real guests through the production execution backend +classes, persisted verified bindings and token-free scope snapshots in isolated +PostgreSQL databases, and served the actual Worker request handlers through a +temporary exe.dev HTTPS relay. The attached Reflection integrations supplied +control-plane authentication through test-only transport rewriting. No fixture +JWT key, identity verifier bypass or production tenant was used. This is live +VM/helper/backend protocol evidence; the full scheduler/artifact lifecycle is +separately exercised by Docker/DB fixtures, not claimed as a production deployment. + +- exe.dev: run `f80bf764-a2a9-4438-a369-7b560954a4b6`, VM + `factorize-f80bf764-a2a9-4438-a369-7b560954a4b6`. Its exclusively attached + per-run WIF integration was checked against actual vendor inventory, and + signatures against actual issuer discovery/JWKS. The guest saw vendor identity + and an empty scope snapshot, received 403 for jobs API access and an unselected + credential, and used its selected backend egress to an actual public HTTPS + status endpoint. Changing the run to stopping made runtime-context return 401. +- Fly: run `9f6249bc-948a-4125-bbe0-e3aaae36b40a`, Machine `86ed0ece491768`, + isolated app `fz-gen2922-live-9f6249bc`, organization `brendan-asselstine`. + The real guest Unix-socket JWT was verified and durably bound to the exact + Machine/run. The same empty-scope, unselected credential, selected HTTPS + egress and stopping/401 checks passed through the guest helper and backend. +- Egress used a synthetic bearer and `https://httpbin.org/status/200`; the + service returned only status, not echoed credentials. This proves live + routing, not authentication to a real GitHub, Linear or model account. + Credential injection, Git protocols, model streaming/refresh and permanent + disconnect revocation remain explicitly deterministic fixture evidence. +- Both test guests, all temporary Fly apps/Machines and run WIF integrations + were removed and absence verified. The relay was stopped, its VM returned to + private visibility, and the development tunnels removed. The isolated + validation VM is removed after final validation completes. + +Live testing found a Fly startup assumption that fixtures had missed: an +immediate start of a paused/created Machine returned 412. The final backend +uses the documented default base-image boot with a sleeping init process, +bounded three-minute readiness polling and one explicit start only for +stopped/suspended Machines. No job payload is delivered until vendor verification. +Unknown/ambiguous start results are not repeated. Never-started Machines can +be deleted without an invalid stop request. Focused readiness/lifecycle tests +pass, and the live Fly guest passed with this final startup behavior. + +## Superseded work and release + +GEN-2824's user-unlocked separate proxy architecture, GEN-2892's boot/control +enrollment (already canceled), and GEN-2826's browser pairing decision are +superseded. GEN-2921's Docker validation intent is retained through the new +backend/identity lifecycle E2E. No unrelated Linear issues were closed. + +The concrete operator plan/apply script and migration regression tests validate +credential classification, preparation gating, encrypted managed preservation, +unchanged execution connections and unchanged selections on disabled jobs. +See `packages/docs/self-hosting/credential-cutover.mdx` before deployment. +Migration 0052 is breaking; the old release cannot operate against its removed +tables. No production cutover or upstream model consent was performed here. diff --git a/docs/vendor-run-identity.md b/docs/vendor-run-identity.md new file mode 100644 index 00000000..69ac478e --- /dev/null +++ b/docs/vendor-run-identity.md @@ -0,0 +1,122 @@ +# 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. `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 +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 + 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 +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`. 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. + +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. 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. + + +## 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. + +## 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/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 d728a542..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. 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. 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 snapshots and unlock reconciliation cannot restore the 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. + * 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_model_accounts_accountId_browser_capability"]; + post: operations["post_api_v1_model_accounts_accountId_authorization_status"]; 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. - * - * 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"]; - 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; @@ -216,8 +144,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 +154,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 +177,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. * @@ -571,7 +499,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 +521,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 +543,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 +565,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 +589,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 +609,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 +617,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 +637,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 +790,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 +813,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 +834,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 +857,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 +877,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 +899,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 +921,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 +943,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 +965,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 +1084,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 +1106,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 +1126,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 +1134,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 +1155,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 +1175,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 +1197,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 +1222,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 +1243,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 +1265,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 +1287,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 +1309,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 +1317,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 +1337,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 +1352,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 +1373,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 +1395,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 +1403,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 +1425,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 +1445,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 +1460,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 +1479,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 +1503,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 +1527,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 +1547,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 +1569,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 +1577,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 +1601,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 +1623,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 +1643,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; @@ -1726,6 +1654,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; @@ -1737,7 +1687,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 +1696,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 +1717,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 +1741,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 +1763,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 +1783,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 +1792,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 +1800,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 +1821,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 +1845,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 +1867,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 +1889,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 +1913,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 +1935,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 +1959,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 +1981,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 +1995,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 +2015,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 +2035,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 +2081,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 +2105,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; @@ -2175,7 +2125,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. * @@ -2201,7 +2151,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; @@ -2761,6 +2711,8 @@ export interface components { modelAccess?: "native" | "portable"; /** Format: uuid */ modelAccountId?: string; + githubInstallationIds?: number[]; + linearConnectionId?: "linear" | null; }; ManualInvocation: { /** @default */ @@ -2906,6 +2858,7 @@ export interface operations { name: string; description: string | null; revision: number; + credentialConfigured: boolean; }[]; }; }; @@ -2937,7 +2890,7 @@ export interface operations { idempotencyKey: string; name: string; description: string | null; - encryptedPayload: string; + initialState: string; }; }; }; @@ -2965,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; @@ -2980,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; }; @@ -3011,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; }; }; }; @@ -3091,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; @@ -3102,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; }; }; }; @@ -3133,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; }; }; }; @@ -3208,126 +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; - 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; }; }; }; @@ -3351,7 +3144,7 @@ export interface operations { }; requestBody?: never; responses: { - /** @description Encrypted bearer integration records */ + /** @description Bearer integration metadata */ 200: { headers: { [name: string]: unknown; @@ -3360,13 +3153,14 @@ export interface operations { "application/json": { revision: number; integrations: { + /** @constant */ + kind?: "bearer"; /** Format: uuid */ id: string; name: string; origin: string; description: string | null; revision: number; - encryptedPayload: string; }[]; }; }; @@ -3400,7 +3194,7 @@ export interface operations { /** Format: uri */ origin: string; description: string | null; - encryptedPayload: string; + token: string; }; }; }; @@ -3447,7 +3241,7 @@ export interface operations { /** Format: uri */ origin: string; description: string | null; - encryptedPayload: string; + token: string; }; }; }; @@ -6451,6 +6245,8 @@ export interface operations { modelAccess?: "native" | "portable"; /** Format: uuid */ modelAccountId?: string; + githubInstallationIds?: number[]; + linearConnectionId?: "linear" | null; executionConfigId: string; agentKind: string; concurrencyLimit: number; @@ -6748,6 +6544,8 @@ export interface operations { modelAccess?: "native" | "portable"; /** Format: uuid */ modelAccountId?: string; + githubInstallationIds?: number[]; + linearConnectionId?: "linear" | null; executionConfigId: string; agentKind: string; concurrencyLimit: number; @@ -6957,6 +6755,8 @@ export interface operations { modelAccess?: "native" | "portable"; /** Format: uuid */ modelAccountId?: string; + githubInstallationIds?: number[]; + linearConnectionId?: "linear" | null; executionConfigId: string; agentKind: string; concurrencyLimit: number; @@ -7229,6 +7029,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; @@ -7448,6 +7301,8 @@ export interface operations { modelAccess?: "native" | "portable"; /** Format: uuid */ modelAccountId?: string; + githubInstallationIds?: number[]; + linearConnectionId?: "linear" | null; executionConfigId: string; agentKind: string; concurrencyLimit: number; @@ -7738,6 +7593,8 @@ export interface operations { modelAccess?: "native" | "portable"; /** Format: uuid */ modelAccountId?: string; + githubInstallationIds?: number[]; + linearConnectionId?: "linear" | null; /** Format: date-time */ expectedUpdatedAt?: string; }; @@ -7785,6 +7642,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/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/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/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/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/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/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/api-contract.ts b/packages/api/src/api-contract.ts index bf564905..328cf09b 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"; @@ -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(), - revision: z.number().int().nonnegative(), encryptedPayload: z.string(), + 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(), encryptedPayload: z.string().min(1).max(65_536), + 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(), - encryptedPayload: z.string().min(1).max(65_536), + 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), 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, @@ -191,7 +185,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"; @@ -233,48 +227,29 @@ 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. 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 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", { - 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 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", { @@ -876,6 +851,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( @@ -1147,7 +1123,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" }, @@ -1305,13 +1281,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 +1306,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/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 d4ffb8c0..edd3d2de 100644 --- a/packages/api/src/exe-vm-backend.ts +++ b/packages/api/src/exe-vm-backend.ts @@ -5,8 +5,10 @@ import { base64 } from "./crypto"; import { shellAtom, type ExeConnection, type ExeRunConnection } from "./exe"; import { HARNESS_LOG_LIMIT, safeDiagnosticText } from "./harness-diagnostics"; -import { ExeRunProxy } from "./exe-run-proxy"; -import { runProxyName } from "./run-credentials"; +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 { FACTORIZE_JOB_LAUNCHER } from "./factorize-job-launcher"; const API = "https://exe.dev/exec"; @@ -17,6 +19,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 +60,65 @@ 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), 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"); } + } + + /** 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); + } - 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,19 +213,15 @@ 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) { - 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" } }; - } + if (request.runIdentity) { + if (!(request.verifyVendorIdentity ?? this.vendorIdentityVerifier)) throw new Error("Vendor identity verification is required for run access"); + handle.identityProxyOrigin = request.runIdentity.backendOrigin; + await assertExeVmIsolation({execute: command => this.api(command), vm, backendOrigin: request.runIdentity.backendOrigin, tags: this.connection.tags ?? []}); } const tags = [...new Set(this.connection.tags)].map(tag => `--tag=${shellAtom(tag)}`).join(" "); const image = connection.image; @@ -172,30 +231,39 @@ 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) { + const verifyVendorIdentity = request.verifyVendorIdentity ?? this.vendorIdentityVerifier; + if (verifyVendorIdentity) { 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); + 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) { - // 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" } }; + 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"; + 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") { @@ -214,6 +282,17 @@ export class ExeVmBackend implements ExecutionBackend { async inspect(handle: RunHandle): Promise { 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); + 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)}`); } @@ -291,33 +370,34 @@ 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 }; } 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 { 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/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 4e4e5f53..f721e810 100644 --- a/packages/api/src/execution.ts +++ b/packages/api/src/execution.ts @@ -16,15 +16,17 @@ 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; 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 { 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-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 e2693ffd..526246fd 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"; @@ -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 { @@ -99,18 +99,27 @@ 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 === "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(); + 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 (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, modelAccess, ...(modelAccountId ? { modelAccountId } : {}) }; + return { portableIntegrationIds, githubInstallationIds, ...(linearConnectionId ? { linearConnectionId } : {}), modelAccess, ...(modelAccountId ? { modelAccountId } : {}) }; } private async validateExecutionOptions(id: string, model: string, effort: string, tags: string[]) { @@ -196,6 +205,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) }); @@ -244,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" ? "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 }); @@ -469,20 +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") { + 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 = 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]); + 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]); 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" ? `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 === "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 }; } @@ -497,9 +536,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 === "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); @@ -538,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 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 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.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; @@ -555,125 +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 }; } - 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."); + 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; 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); + 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 }; - }); - return { ownerId: this.auth.userId, generationId, ...snapshot, changes }; - } - async replaceUnlockKeyGeneration(input: { - expectedGenerationId: string; generationId: string; expectedRevision: number; encryptedVerification: string; - 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); - try { - await repository.stageGeneration({ generationId: input.generationId, expectedRevision: input.expectedRevision, records, changes }); - 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) { + async modelAuthorization(accountId: string, action: "authorize" | "status" | "cancel") { 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") { - 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."); @@ -681,24 +635,38 @@ 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 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({ ...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."); 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."); - return this.modelAccountWrite({ ...input, operation: "upsert" }); + 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}.`); + 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 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-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 aceda92e..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 { 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"; +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 }) { + constructor(options: Omit & { region: string; size: string; organizationSlug?: string }) { super({ ...options, kind: "fly", @@ -15,13 +15,14 @@ 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}` : "" } : {}), }); } } -/** 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 createFlyGuestTransport({ ...options, timeoutMs: 30_000, outputLimitBytes: 64 * 1024 }); + return createFlyHttpGuestTransport({ ...options, timeoutMs: 30_000, outputLimitBytes: 64 * 1024 }); } diff --git a/packages/api/src/fly-job-machine.ts b/packages/api/src/fly-job-machine.ts index 98ccf2b7..70eceba0 100644 --- a/packages/api/src/fly-job-machine.ts +++ b/packages/api/src/fly-job-machine.ts @@ -28,6 +28,9 @@ export function flyJobMachineConfig(app: string, input: FlyJobMachineInput): Fly return { image: input.image, + // Boot only the base guest. The authenticated launcher starts the job + // after verification; an image CMD must not execute it independently. + init: {exec: ["/bin/sh", "-c", "exec sleep infinity"]}, region: input.region, guest: { cpu_kind: size[1] === "shared-cpu" ? "shared" : "performance", cpus: cpuCount, memory_mb: cpuCount * 1024 }, metadata: { 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/fly-machines-client.ts b/packages/api/src/fly-machines-client.ts index 58fe5687..4e3e2bd6 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: false, 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,11 +195,26 @@ 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); + async startMachine(app: string, machine: string): Promise { + const path = machinePath(app, machine), deadline = Date.now() + 180_000; + let current = await request(path, {method: "GET"}, true); + // New Machines boot their base image during create. Do not race image + // preparation with POST /start: created is not a startable state. + if (["stopped", "suspended"].includes(current.state ?? "")) { + await request(`${path}/start`, {method: "POST"}, false); + current = await request(path, {method: "GET"}, true); + } + for (;;) { + if (current.state === "started") return; + if (!["created", "starting"].includes(current.state ?? "")) throw new FlyClientError("Fly Machine did not start", "invalid_response"); + if (Date.now() >= deadline) throw new FlyClientError("Fly Machine preparation timed out", "timeout"); + await wait(1_000); + current = await request(path, {method: "GET"}, true); + } }, stopMachine(app: string, machine: string): Promise { return request(`${machinePath(app, machine)}/stop`, { 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/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/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/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/machine-job-execution-backend.ts b/packages/api/src/machine-job-execution-backend.ts index 1d29461c..354a80ce 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; 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"; -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"; @@ -25,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; @@ -39,18 +38,18 @@ 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; + vendorIdentityIssuer?: string; + verifyVendorIdentity?: (input: { provider: "exe.dev" | "fly.io"; vmId: string; token: string; integrationName?: string; expectedIssuer?: string; expectedSubject?: string }) => Promise; }, ) {} @@ -79,58 +78,44 @@ 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"); - 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 tunnelPrerequisites = request.runProxy ? " && command -v node >/dev/null && command -v openssl >/dev/null" : ""; + 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 }); + 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, ...(this.options.vendorIdentityIssuer ? { expectedIssuer: this.options.vendorIdentityIssuer } : {}), ...(expectedSubject ? { expectedSubject } : {}) }); + } + 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"; + 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.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`); @@ -159,6 +144,18 @@ 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 }); + 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, ...(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" } }; + } + } try { const result = await this.options.guest(machine).run(["/usr/sbin/runuser", "-u", "exedev", "--", "/usr/local/bin/factorize-job", "status"]); if (result.ok) { @@ -206,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)) { @@ -222,25 +219,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 { @@ -248,6 +243,12 @@ export class MachineJobExecutionBackend implements ExecutionBackend, JobResultRe if (!id) return { state: "stopped" }; const machine = await this.options.machines.inspectMachine(this.options.app, id); if (["destroyed", "destroying"].includes(String(machine.state ?? "").toLowerCase())) return { state: "stopped" }; + if (String(machine.state ?? "").toLowerCase() === "created") { + // A never-started/preparing Machine has no live guest to stop. The + // documented delete is safe; a provider rejection remains retryable. + await this.options.machines.destroyMachine(this.options.app, id); + return {state: "stopped"}; + } if (String(machine.state ?? "").toLowerCase() !== "stopped") { await this.options.machines.stopMachine(this.options.app, id); } @@ -261,7 +262,7 @@ export class MachineJobExecutionBackend implements ExecutionBackend, JobResultRe const id = await this.machineId(handle); if (!id) return { state: "stopped" }; const machine = await this.options.machines.inspectMachine(this.options.app, id); - if (["destroyed", "destroying", "stopped"].includes(String(machine.state ?? "").toLowerCase())) return { state: "stopped" }; + if (["destroyed", "destroying", "stopped", "created"].includes(String(machine.state ?? "").toLowerCase())) return { state: "stopped" }; await this.options.machines.stopMachine(this.options.app, id); const after = await this.options.machines.inspectMachine(this.options.app, id); return ["stopped", "destroyed"].includes(String(after.state ?? "").toLowerCase()) ? { state: "stopped" } : { state: "stopping" }; diff --git a/packages/api/src/managed-model-credentials.ts b/packages/api/src/managed-model-credentials.ts new file mode 100644 index 00000000..0748d445 --- /dev/null +++ b/packages/api/src/managed-model-credentials.ts @@ -0,0 +1,67 @@ +import type { Database } from "./postgres/database"; +import type { Env } from "./types"; +import { CredentialRepository } from "./postgres/credential-repository"; + +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); + 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 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; + 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/model-device-auth.ts b/packages/api/src/model-device-auth.ts new file mode 100644 index 00000000..adb3968c --- /dev/null +++ b/packages/api/src/model-device-auth.ts @@ -0,0 +1,89 @@ +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;} +} +type AuthEndpoint = "https://auth.openai.com/api/accounts/deviceauth/usercode" | "https://auth.openai.com/api/accounts/deviceauth/token" | "https://auth.openai.com/oauth/token"; +async function post(endpoint: AuthEndpoint, body: unknown, form=false): Promise { + return fetch(endpoint, {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("https://auth.openai.com/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("https://auth.openai.com/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("https://auth.openai.com/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/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/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 a83dbdcb..00000000 --- a/packages/api/src/postgres/encrypted-integration-repository.ts +++ /dev/null @@ -1,343 +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; -}; -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 }; - -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.encryptedPayload !== "string" || !isUserCiphertext(change.encryptedPayload))) throw new IntegrationValidationError("upserts require a valid user-encrypted AES-GCM ciphertext envelope"); - 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 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; - 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 encryptedPayload = input.operation === "upsert" ? await encrypt(input.encryptedPayload!, 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 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 }; - }); - } - - 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) }))), - }; - } - - /** - * 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 }> { - 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); - 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"); - 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) === input.encryptedPayload; - 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[] }): 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"); - } - 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 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/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/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/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-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-retention-repository.ts b/packages/api/src/postgres/run-retention-repository.ts index f0c086f1..3b162b87 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 ExecutionBackend | undefined | Promise; @@ -42,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); @@ -122,6 +124,21 @@ 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 }) => { + 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} : {})}); + } + }; + } + private hasCapability(backend: ExecutionBackend, method: keyof T): backend is ExecutionBackend & T { return typeof (backend as unknown as Record)[method] === "function"; } @@ -130,78 +147,62 @@ 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", - [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, 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 }), + prepare: () => machines.ensureRunApp(app, connectionDetails.organizationSlug), + vendorIdentityAudience: runId => `factorize://runs/${runId}`, + verifyVendorIdentity: this.vendorIdentityVerifier(run, `https://oidc.fly.io/${connectionDetails.organizationSlug}`), }); } 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) { const config = run.executionConfig; - 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 snapshotRunAuthorization(this.database, {tenantId: run.tenantId, runId: run.id, scopes: config.runScopes ?? DEFAULT_RUN_SCOPES}); + 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 } }); + 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; } 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 } }); + 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/postgres/schema.ts b/packages/api/src/postgres/schema.ts index 880433c4..62748b2e 100644 --- a/packages/api/src/postgres/schema.ts +++ b/packages/api/src/postgres/schema.ts @@ -42,7 +42,7 @@ export const accessTokens = app.table("access_tokens", { export const connections = app.table("connections", { tenantId: uuid("tenant_id").notNull().references(() => 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)]); @@ -114,7 +100,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 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 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 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")]); @@ -168,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, 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/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/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-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 036cfd78..00000000 --- a/packages/api/src/proxy-control.ts +++ /dev/null @@ -1,180 +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"; - -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]); - return json({ revokedRunIds: revoked.rows.map(row => row.run_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"); - 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), keyGeneration: keyState.rows[0].generation_id, - 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); - 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 } }); - } - if (input.operation !== "save" || Object.keys(input).sort().join(",") !== "accountId,encryptedPayload,expectedRevision,idempotencyKey,keyGeneration,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); - 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, - 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; - if (!modelAccount) return json({ error: "integration_snapshot_unavailable" }, 403); - } else if (modelAccess !== "native" || modelAccountId !== undefined) { - return json({ error: "integration_snapshot_unavailable" }, 403); - } - // 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 }); - } - 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/public-address.ts b/packages/api/src/public-address.ts new file mode 100644 index 00000000..5aafa654 --- /dev/null +++ b/packages/api/src/public-address.ts @@ -0,0 +1,70 @@ +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)); +} + + +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-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/run-credential-launch.ts b/packages/api/src/run-credential-launch.ts new file mode 100644 index 00000000..16961857 --- /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 { CredentialRepository } from "./postgres/credential-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 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 ?? []; + 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-credentials.ts b/packages/api/src/run-credentials.ts deleted file mode 100644 index 1a7c7b06..00000000 --- a/packages/api/src/run-credentials.ts +++ /dev/null @@ -1,50 +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): 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`; -} - -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-identity-guest-helper.ts b/packages/api/src/run-identity-guest-helper.ts new file mode 100644 index 00000000..a416a6af --- /dev/null +++ b/packages/api/src/run-identity-guest-helper.ts @@ -0,0 +1,94 @@ +/** 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 (/^\/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; } + 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); + } + 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"; + 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-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-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..532839dd --- /dev/null +++ b/packages/api/src/run-outbound-proxy.ts @@ -0,0 +1,73 @@ +import type { Env } from "./types"; +import { databaseFor } from "./postgres/database"; +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"; +import { resolveManagedModelCredential } from "./managed-model-credentials"; +import { isPublicHttpsOrigin } from "./public-address"; + +const unavailable = () => new Response("Run credential unavailable", {status: 403, headers: {"Cache-Control": "no-store"}}); + +/** 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 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) { + 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/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/src/types.ts b/packages/api/src/types.ts index c98daa28..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,11 +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"; + authMethod?: "session" | "oauth" | "access_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..0d8ee734 --- /dev/null +++ b/packages/api/src/vendor-run-auth.ts @@ -0,0 +1,74 @@ +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, 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 + 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_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 ${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]!; + 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/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/src/vendor-run-identity.ts b/packages/api/src/vendor-run-identity.ts new file mode 100644 index 00000000..375a7612 --- /dev/null +++ b/packages/api/src/vendor-run-identity.ts @@ -0,0 +1,166 @@ +/** 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; + issuedAt: number; + expiresAt: number; + keyId: string; +}; + +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 }; + +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, issuedAt: claims.iat, 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" }, 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"); + 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); + }; +} + +/** 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" }, 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"); + 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/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/src/worker.ts b/packages/api/src/worker.ts index e32c339b..62a02aef 100644 --- a/packages/api/src/worker.ts +++ b/packages/api/src/worker.ts @@ -9,12 +9,12 @@ 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 { authenticateRunCredential } from "./run-credentials"; -import { artifactUpload } from "./artifact-upload"; +import { authenticateVendorRunRequest, RUN_IDENTITY_HEADER } from "./vendor-run-auth"; +import { artifactUpload, readArtifactUploadGrant } from "./artifact-upload"; import { traceChunkUpload } from "./trace-chunk-upload"; import { databaseFor } from "./postgres/database"; import { IdentityRepository } from "./postgres/identity-repository"; -import { proxyControlFetch } from "./proxy-control"; +import { runOutboundProxyFetch } from "./run-outbound-proxy"; const scopes = [...ACCESS_SCOPES]; // Keep accepting grants issued by the pre-resource-scope protocol. New @@ -86,16 +86,26 @@ 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/credential-proxy/")) return proxyControlFetch(request, env); + if (new URL(request.url).pathname.startsWith("/internal/run-proxy/")) return runOutboundProxyFetch(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"' } }); + 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, @@ -105,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/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/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/api-contract.test.ts b/packages/api/test/api-contract.test.ts index abfbcb01..1364c115 100644 --- a/packages/api/test/api-contract.test.ts +++ b/packages/api/test/api-contract.test.ts @@ -56,22 +56,14 @@ describe("versioned API contract", () => { expect(operation?.parameters.shape.projectId).toBeDefined(); expect(openapi.paths["/api/v1/projects/{projectId}/graph"].get["x-required-scope"]).toBe("projects:read"); }); - it("publishes owner-session unlock verification operations and strict ciphertext-only input", () => { - const get = API_ROUTES.find(route => route.method === "GET" && route.path === "/api/v1/unlock-key/verification"); - const post = API_ROUTES.find(route => route.method === "POST" && route.path === "/api/v1/unlock-key/verification"); - expect(get?.scope).toBe("integrations:read"); expect(get?.ownerSession).toBe(true); - expect(post?.scope).toBe("integrations:write"); expect(post?.ownerSession).toBe(true); - expect(post?.body?.safeParse({ generationId: "00000000-0000-4000-8000-000000000001", encryptedVerification: "ciphertext", key: "plain" }).success).toBe(false); - expect(openapi.paths["/api/v1/unlock-key/verification"].post.requestBody).toBeDefined(); - }); - it("publishes model-account proxy capabilities as owner-only API operations", () => { - const route = API_ROUTES.find(item => item.method === "POST" && item.path === "/api/v1/model-accounts/{accountId}/browser-capability"); - expect(route?.scope).toBe("integrations:write"); - expect(route?.ownerSession).toBe(true); - expect(route?.parameters.shape.accountId).toBeDefined(); - expect(route?.body?.safeParse({ action: "authorize" }).success).toBe(true); - expect(route?.body?.safeParse({ action: "authorize", accountId: "attacker" }).success).toBe(false); - expect(openapi.paths["/api/v1/model-accounts/{accountId}/browser-capability"].post.requestBody).toBeDefined(); + it("retires unlock and browser-capability operations and publishes owner-only model authorization", () => { + expect(API_ROUTES.some(route=>route.path.includes("unlock-key")||route.path.includes("browser-capability")||route.path.includes("credential-proxy"))).toBe(false); + for(const action of ["authorize","status","cancel"]){ + const route=API_ROUTES.find(item=>item.method==="POST"&&item.path===`/api/v1/model-accounts/{accountId}/authorization/${action}`); + expect(route?.scope).toBe("integrations:write");expect(route?.ownerSession).toBe(true); + expect(route?.body?.safeParse({}).success).toBe(true); + expect(route?.body?.safeParse({token:"guest-supplied"}).success).toBe(false); + } }); it("lists only safe model account metadata for the owner browser", () => { const route = API_ROUTES.find(item => item.method === "GET" && item.path === "/api/v1/model-accounts"); @@ -81,14 +73,25 @@ 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(); 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/credential-cutover.postgres.test.ts b/packages/api/test/credential-cutover.postgres.test.ts new file mode 100644 index 00000000..c9aab25a --- /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',$4,'https://api.example.com',1,$3)",[tenant,id,await encrypt(payload,key),id]); + 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 f96a885f..4955c709 100644 --- a/packages/api/test/docker-code-job.e2e.test.ts +++ b/packages/api/test/docker-code-job.e2e.test.ts @@ -1,182 +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); - 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")}` }); - 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(); - 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")}` }); - 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 77d4c01e..da86455c 100644 --- a/packages/api/test/encrypted-integration-api.postgres.test.ts +++ b/packages/api/test/encrypted-integration-api.postgres.test.ts @@ -2,7 +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 { CredentialRepository } from "../src/postgres/credential-repository"; import { signSession } from "../src/session"; import { loadingFixture } from "./helpers/loading-fixture"; @@ -10,118 +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)("browser-only encrypted bearer integration 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 () => { +describe.skipIf(!databaseUrl)("owner-only managed credential API (PostgreSQL)", { timeout: 60_000 }, () => { + 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(); - 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 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(); - 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); - const rotationSnapshot = await (await request("/unlock-key/rotation-snapshot")).json() as any; - const finalGeneration = crypto.randomUUID(); - const rotated = await request("/unlock-key/rotation", "POST", { - expectedGenerationId: newGeneration, generationId: finalGeneration, expectedRevision: 3, - encryptedVerification: verification(finalGeneration), - 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 request("/integrations/bearer")).status).toBe(200); - expect((await (await request("/integrations/bearer")).json() as any).integrations[0].encryptedPayload).toBe(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!); @@ -130,28 +27,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"); @@ -170,9 +69,9 @@ 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 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); @@ -181,7 +80,7 @@ describe.skipIf(!databaseUrl)("browser-only encrypted bearer integration API (Po 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); @@ -208,9 +107,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 +120,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/api/test/encrypted-integration-repository.postgres.test.ts b/packages/api/test/encrypted-integration-repository.postgres.test.ts index c2a5e7ce..0631b2f4 100644 --- a/packages/api/test/encrypted-integration-repository.postgres.test.ts +++ b/packages/api/test/encrypted-integration-repository.postgres.test.ts @@ -1,240 +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("rejects a model cache save encrypted under a replaced key generation even when its account revision is unchanged", 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 }); - 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 }); - }); - - 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 34bf9f51..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) }); + 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"]); @@ -110,6 +109,32 @@ 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, runIdentity: {backendOrigin: "https://factorize.example.com"} }); + expect(launched.observation.state).toBe("running"); + 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"))!)); + }); + it("generates standard I/O settings accepted by systemd", async () => { const requests: string[] = []; vi.stubGlobal("fetch", vi.fn(async (_url: string, init: RequestInit) => { @@ -271,8 +296,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)"); @@ -284,8 +309,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/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-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/fly-job-execution-backend.test.ts b/packages/api/test/fly-job-execution-backend.test.ts index 5305f682..f5666e4a 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), @@ -17,16 +17,11 @@ 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 = { - 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", () => { @@ -49,6 +44,60 @@ 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", 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, 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("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.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" }); @@ -179,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(); @@ -228,22 +277,10 @@ 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("deletes a never-started Machine without issuing an invalid stop", async () => { + const f=fixture(); + expect(await f.backend.stop({backendKind:"fly",id:"factorize-test/machine-1"})).toEqual({state:"stopped"}); + expect(f.machines.stopMachine).not.toHaveBeenCalled();expect(f.machines.destroyMachine).toHaveBeenCalledWith("factorize-test","machine-1"); }); it("destroys a stopped Machine after confirming provider state", async () => { diff --git a/packages/api/test/fly-job-machine.test.ts b/packages/api/test/fly-job-machine.test.ts index 17c5e2ea..4cab888d 100644 --- a/packages/api/test/fly-job-machine.test.ts +++ b/packages/api/test/fly-job-machine.test.ts @@ -13,6 +13,7 @@ describe("Fly job Machine configuration", () => { it("records run ownership, uses the selected size, and disables provider restarts", () => { expect(flyJobMachineConfig("factorize-user", input)).toEqual({ image: input.image, + init: {exec: ["/bin/sh", "-c", "exec sleep infinity"]}, region: "iad", guest: { cpu_kind: "shared", cpus: 2, memory_mb: 2048 }, metadata: { diff --git a/packages/api/test/fly-machines-client.test.ts b/packages/api/test/fly-machines-client.test.ts index 60ab6d26..a7fc68f8 100644 --- a/packages/api/test/fly-machines-client.test.ts +++ b/packages/api/test/fly-machines-client.test.ts @@ -1,6 +1,6 @@ import { createServer, type Server } from "node:http"; import { once } from "node:events"; -import { afterEach, describe, expect, it } from "vitest"; +import { afterEach, describe, expect, it, vi } from "vitest"; import { createFlyMachinesClient, FlyClientError, type FlyMachine } from "../src/fly-machines-client.js"; const token = "test-fly-secret-do-not-leak"; @@ -43,10 +43,14 @@ 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(false); + 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); if (req.method === "POST" && ["/v1/apps/app-a/machines/m-1/start", "/v1/apps/app-a/machines/m-1/stop"].includes(req.url)) { + machine.state=req.url.endsWith("/start") ? "started" : "stopped"; res.writeHead(204); return res.end(); } if (req.method === "POST" && req.url === "/v1/apps/app-a/machines/m-1") return json(res, 200, machine); @@ -54,9 +58,10 @@ 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"); + machine.state = "stopped"; await client.startMachine("app-a", "m-1"); await client.stopMachine("app-a", "m-1"); expect((await client.updateMachineConfig("app-a", "m-1", { image: "example/new" })).id).toBe("m-1"); @@ -64,11 +69,27 @@ describe("bounded Fly Machines client", () => { expect(calls.every((call) => call.auth === `Bearer ${token}`)).toBe(true); expect(calls.map(({ method, path }) => `${method} ${path}`)).toEqual([ "GET /v1/apps/app-a/machines", "POST /v1/apps/app-a/machines", "GET /v1/apps/app-a/machines/m-1", - "POST /v1/apps/app-a/machines/m-1/start", "POST /v1/apps/app-a/machines/m-1/stop", + "GET /v1/apps/app-a/machines/m-1", "POST /v1/apps/app-a/machines/m-1/start", "GET /v1/apps/app-a/machines/m-1", "POST /v1/apps/app-a/machines/m-1/stop", "POST /v1/apps/app-a/machines/m-1", "DELETE /v1/apps/app-a/machines/m-1", ]); }); + it("observes base-image boot without posting start during created/starting or restarting a running Machine", async () => { + const states=["created","starting","started","started"],calls:string[]=[]; + const client=createFlyMachinesClient({token,wait:async()=>{},fetch:async(_url,init)=>{calls.push(init?.method??"GET");return Response.json({id:"machine",state:states.shift()});}}); + await client.startMachine("app","machine");await client.startMachine("app","machine"); + expect(calls).toEqual(["GET","GET","GET","GET"]); + }); + it("bounds boot preparation and never retries an ambiguous explicit start", async () => { + let now=0;const clock=vi.spyOn(Date,"now").mockImplementation(()=>now); + try { + const client=createFlyMachinesClient({token,wait:async()=>{now+=30_000;},fetch:async()=>Response.json({state:"created"})}); + await expect(client.startMachine("app","machine")).rejects.toMatchObject({kind:"timeout"}); + let starts=0;const ambiguous=createFlyMachinesClient({token,fetch:async(_url,init)=>{if(init?.method==="POST"){starts++;throw new Error("lost response");}return Response.json({state:"stopped"});}}); + await expect(ambiguous.startMachine("app","machine")).rejects.toMatchObject({kind:"network"});expect(starts).toBe(1); + } finally {clock.mockRestore();} + }); + it("returns typed auth errors without exposing credentials or provider bodies", async () => { const origin = await fakeFly((_req, res) => json(res, 401, { detail: token })); const client = createFlyMachinesClient({ token, apiOrigin: origin }); diff --git a/packages/api/test/fly-run-scheduler-lifecycle.test.ts b/packages/api/test/fly-run-scheduler-lifecycle.test.ts index f7de4679..cfc28cfe 100644 --- a/packages/api/test/fly-run-scheduler-lifecycle.test.ts +++ b/packages/api/test/fly-run-scheduler-lifecycle.test.ts @@ -78,6 +78,7 @@ function localFlyFixture(options: { ambiguousCreate?: boolean; failFirstInspect? }; const guest = { run: vi.fn(async (command: readonly string[]) => { + if (command.at(-1)?.includes("curl --fail") && command.at(-1)?.includes("report.json")) events.push("upload-job-file"); if (command.at(-1) === "status") return { ok: true, exitCode: 0, stdout: JSON.stringify({ state: "exited", exitCode: 0 }), stderr: "" }; if (command.at(-1)?.startsWith("find ")) return { ok: true, exitCode: 0, stdout: (options.jobFiles ?? []).map(path => `${path}\t4`).join("\n"), stderr: "" }; return { ok: true, exitCode: 0, stdout: "", stderr: "" }; @@ -204,17 +205,14 @@ describe("Fly scheduler lifecycle", () => { it("collects and uploads Fly job files before destroying the Machine", async () => { const fly = localFlyFixture({ jobFiles: ["report.json"] }); const f = schedulerForLocalFly(fly.backend); - vi.stubGlobal("fetch", vi.fn(async () => { - fly.events.push("upload-job-file"); - return new Response(null, { status: 200 }); - })); + f.run.executionHandle.identityProxyOrigin="https://app.example.test"; await f.scheduler.poll(f.run); - expect(fly.events.indexOf("download-job-file")).toBeGreaterThanOrEqual(0); - expect(fly.events.indexOf("download-job-file")).toBeLessThan(fly.events.indexOf("destroy")); + expect(fly.events.indexOf("upload-job-file")).toBeGreaterThanOrEqual(0); expect(fly.events.indexOf("upload-job-file")).toBeLessThan(fly.events.indexOf("destroy")); - expect(fly.guest.download).toHaveBeenCalledWith("/home/exedev/.factorize-job/report.json"); + expect(fly.guest.run.mock.calls.some(([command])=>command.at(-1)?.includes("http://127.0.0.1:18180/internal/run-artifacts/"))).toBe(true); + expect(fly.guest.download).not.toHaveBeenCalledWith("/home/exedev/.factorize-job/report.json"); expect(f.events.at(-1)).toBe("terminal"); }); }); 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 f05c1657..42b68040 100644 --- a/packages/api/test/loading.postgres.test.ts +++ b/packages/api/test/loading.postgres.test.ts @@ -5,9 +5,10 @@ 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"; import { encrypt } from "../src/crypto"; import { ApiService } from "../src/flow-service"; import worker from "../src/worker"; @@ -119,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"); @@ -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/manual-invocation-permissions.test.ts b/packages/api/test/manual-invocation-permissions.test.ts index 10053302..cf60f859 100644 --- a/packages/api/test/manual-invocation-permissions.test.ts +++ b/packages/api/test/manual-invocation-permissions.test.ts @@ -32,7 +32,7 @@ function fixture(options: { member?: boolean; activeToken?: boolean } = {}) { return { env, database, persisted }; } -function auth(authMethod: "session" | "access_token" | "oauth" | "run_token", scopes = ["jobs:write"], accessTokenId?: string) { +function auth(authMethod: "session" | "access_token" | "oauth" | "vendor_identity", scopes = ["jobs:write"], accessTokenId?: string) { return { tenantId, userId: "owner", sessionVersion: 1, scopes, authMethod, accessTokenId } as any; } @@ -86,7 +86,7 @@ describe("manual invocation permission management", () => { await expect(service.setInvocationPermissions(sourceId, [crossProjectId])).rejects.toMatchObject({ status: 400, code: "invalid_request" }); }); - it("rejects missing scopes, missing credentials, invalid or revoked owner credentials, and run tokens", async () => { + it("rejects missing scopes, missing credentials, invalid or revoked owner credentials, and verified run identities", async () => { for (const transport of ["REST", "MCP"] as const) { const noScope = await request(transport, auth("oauth", ["jobs:read"])); if (transport === "REST") { @@ -116,7 +116,7 @@ describe("manual invocation permission management", () => { } const f = fixture(); - await expect(new ApiService(f.env, auth("run_token", ["jobs:write"])).setInvocationPermissions(sourceId, [destinationId])) + await expect(new ApiService(f.env, auth("vendor_identity", ["jobs:write"])).setInvocationPermissions(sourceId, [destinationId])) .rejects.toBeInstanceOf(ServiceError); await expect(new ApiService(f.env, auth("session", ["jobs:write"])).setInvocationPermissions(foreignId, [destinationId])) .rejects.toMatchObject({ status: 404, code: "not_found" }); diff --git a/packages/api/test/manual-invocation.test.ts b/packages/api/test/manual-invocation.test.ts index 19156cfb..155213c0 100644 --- a/packages/api/test/manual-invocation.test.ts +++ b/packages/api/test/manual-invocation.test.ts @@ -31,7 +31,7 @@ describe("manual invocation API and shared service", () => { const response = await protectedApiFetch(new Request("https://example.com" + (transport === "REST" ? "/api/v1/jobs/job-1/invocations" : "/mcp"), { method: "POST", headers: { Origin: env.APP_ORIGIN, Host: "example.com", "Content-Type": "application/json", Accept: "application/json, text/event-stream" }, body: JSON.stringify(transport === "REST" ? body : { jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "invoke_job", arguments: { jobId: "job-1", ...body } } }), - }), env, sourceAuth ? { scopes: ["runs:invoke"], authMethod: "run_token", runId: sourceAuth.runId, runJobId: sourceAuth.runJobId } as any : { scopes: ["runs:write"], authMethod: "session" } as any, {} as any); + }), env, sourceAuth ? { scopes: ["runs:invoke"], authMethod: "vendor_identity", runId: sourceAuth.runId, runJobId: sourceAuth.runJobId } as any : { scopes: ["runs:write"], authMethod: "session" } as any, {} as any); if (transport === "REST") return response; expect(response.status).toBe(200); const text = await response.text(); 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/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/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 bcf1546b..00000000 --- a/packages/api/test/proxy-control.test.ts +++ /dev/null @@ -1,212 +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], 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 }, 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" } }); - 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 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 } - : { 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(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 new file mode 100644 index 00000000..91535b2c --- /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 {CredentialRepository} from "../src/postgres/credential-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 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); + 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-credentials.test.ts b/packages/api/test/run-credentials.test.ts deleted file mode 100644 index 4068d3f7..00000000 --- a/packages/api/test/run-credentials.test.ts +++ /dev/null @@ -1,25 +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 = "", 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 }; - 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(); - }); -}); 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-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/run-launch-block.test.ts b/packages/api/test/run-launch-block.test.ts index 5dc0670e..0c3b7473 100644 --- a/packages/api/test/run-launch-block.test.ts +++ b/packages/api/test/run-launch-block.test.ts @@ -1,23 +1,23 @@ import { describe, expect, it } from "vitest"; import { RunRepository } from "../src/postgres/run-repository"; -describe("durable proxy-gated launch retry", () => { +describe("durable credential repair launch retry", () => { it("persists a blocked pre-launch run without polling it as a live execution", async () => { const statements: string[] = []; const client = { query: async (sql: string) => { statements.push(sql); return { rowCount: 1, rows: [{ id: "run" }] }; } }; const database = { transaction: async (fn: (client: any) => Promise) => fn(client), pool: { query: client.query } }; - await new RunRepository(database as any).blockLaunch({ tenantId: "tenant", id: "run" } as any, "proxy_locked"); + await new RunRepository(database as any).blockLaunch({ tenantId: "tenant", id: "run" } as any, "credential_repair_required"); expect(statements.some(sql => sql.includes("state='blocked'") && sql.includes("launch_lease_expires_at=NULL"))).toBe(true); expect(statements.some(sql => sql.includes("execution_handle IS NULL"))).toBe(true); expect(statements.some(sql => sql.includes("'launch_blocked'"))).toBe(true); }); - it("only manually requeues a proxy-gated run that has no execution handle", async () => { + it("only manually requeues a credential-blocked run that has no execution handle", async () => { const statements: string[] = []; const client = { query: async (sql: string) => { statements.push(sql); return { rowCount: 1, rows: [{ id: "run" }] }; } }; const database = { transaction: async (fn: (client: any) => Promise) => fn(client), pool: { query: client.query } }; expect(await new RunRepository(database as any).retryBlockedLaunch("tenant", "run")).toBe(true); - expect(statements.some(sql => sql.includes("state='blocked'") && sql.includes("failure_code='proxy_launch_blocked'") && sql.includes("execution_handle IS NULL"))).toBe(true); + expect(statements.some(sql => sql.includes("state='blocked'") && sql.includes("failure_code='credential_repair_required'") && sql.includes("execution_handle IS NULL"))).toBe(true); expect(statements.some(sql => sql.includes("state='reserved'"))).toBe(true); expect(statements.some(sql => sql.includes("'launch_retry_requested'"))).toBe(true); expect(statements.some(sql => sql.includes("wake_hints"))).toBe(true); 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/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-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-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..ec60def6 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).not.toHaveProperty("runProxy"); + 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/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/trace-tail-boundary.test.ts b/packages/api/test/trace-tail-boundary.test.ts index 7a59e35f..b5aae7c5 100644 --- a/packages/api/test/trace-tail-boundary.test.ts +++ b/packages/api/test/trace-tail-boundary.test.ts @@ -20,8 +20,8 @@ it("tails the declared stream before exit, resumes by offset, and detects trunca return new Response(result.stdout + result.stderr, { headers: { "X-Exe-Exit": String(result.status) } }); })); const source: TraceSource = { kind: "execution_stream", path, mediaType: "application/x-ndjson", provider: "codex" }; - const backend = new ExeVmBackend({ apiToken: "test", tags: [] }), handle = { backendKind: "exe-vm", id: "factorize-test" }; - const request = { source, uploadUrl: "https://app.example/chunk", generation: null as string | null, offset: 0, previousHash: "0".repeat(64) }; + const backend = new ExeVmBackend({ apiToken: "test", tags: [] }), handle = { backendKind: "exe-vm", id: "factorize-test", identityProxyOrigin: "https://app.example" }; + const request = { source, uploadUrl: "https://app.example/internal/run-trace-chunks/fixture", generation: null as string | null, offset: 0, previousHash: "0".repeat(64) }; expect((await backend.collectTraceChunk(handle, request)).ok).toBe(true); expect(readFileSync(captured, "utf8")).toBe('{"version":1}\n'); request.generation = readFileSync(headers, "utf8").match(/X-Trace-Generation: ([^\n]+)/)![1]; 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..995307cb --- /dev/null +++ b/packages/api/test/vendor-run-auth.postgres.test.ts @@ -0,0 +1,292 @@ +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 { 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 { 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"; + +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 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`}); + 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]]); + 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_authorizations 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_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); + 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("forwards only the run's selected managed bearer and stops after disconnect or cancellation", async () => { + 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 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[] = []; + 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"); + 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]})]); + 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. + 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); + }); + + 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 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); + 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 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); + 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("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]); + 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}`}]); + 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(); + }); +}); 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..ea94c6f3 --- /dev/null +++ b/packages/api/test/vendor-run-identity.postgres.test.ts @@ -0,0 +1,99 @@ +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; + +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: `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) }; + } + + 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); + + 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 = `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, 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: 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)}`; + }; + 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, 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, 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, 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, expectedSubject: subject, now: new Date((now + 90) * 1000) })) + .rejects.toThrow("binding is revoked"); + } finally { vi.unstubAllGlobals(); } + }, 30_000); +}); 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..23b15d43 --- /dev/null +++ b/packages/api/test/vendor-run-identity.test.ts @@ -0,0 +1,95 @@ +import { beforeAll, describe, expect, it } from "vitest"; +import { createJwksResolver, discoverVendorIssuerTrust, 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/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 () => { + 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, issuedAt: now - 10, 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) => { + 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] }); + } }); + 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"); + }); + + 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, 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" }); + } }); + 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"); + }); +}); 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"); + }); +}); 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..e01cadf6 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,11 +39,13 @@ 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); 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"}`; @@ -110,11 +112,26 @@ 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}

}
}