Skip to content

An open-source, faster Devin alternative

TypeScript

fix(agent-worker): close production boundary review gaps

Igor Zalutski7a284e44dba3
diff --git a/cloudflare-workers/oc-gateway/README.md b/cloudflare-workers/oc-gateway/README.md
index 247f114f..1e89f6e8 100644
--- a/cloudflare-workers/oc-gateway/README.md
+++ b/cloudflare-workers/oc-gateway/README.md
@@ -74,8 +74,8 @@ POST {GATEWAY_ORKEY_URL} Authorization: Bearer {GATEWAY_ORKEY_SECRET} body {
→ 200 {"key": "sk-or-..."} (resolveManagedSecret for the org's active managed credential)
```
-The plaintext is cached per-org in-isolate with a 60 s TTL. `TEST_OR_KEY` is an in-process/local-test
-override only and must be absent from the production Worker.
+The plaintext is cached per-org in-isolate with a 60 s TTL. There is no single-key test or production
+override: missing seam configuration returns no key, and tests exercise the same org-scoped request.
### 7. Prompt-caching safety
@@ -96,18 +96,18 @@ Some models route (via OpenRouter) to a backend that rejects Anthropic `cache_co
| `src/token.ts` | EdDSA per-deploy token mint/verify (Web Crypto, no deps) |
| `src/budget.ts` | `SpendCounter` DO — keyed spend counter + hard gate (µ$ integers); org+agt (hard) + per-session (tracked) |
| `src/deploylease.ts` | `DeployLease` DO — per-(org,agt) lease-epoch floor (rotation/revocation fence) |
-| `src/orgkey.ts` | org OR-key resolution via the dedicated sessions-api seam (`TEST_OR_KEY` is test-only) |
+| `src/orgkey.ts` | fail-closed org OR-key resolution via the dedicated sessions-api seam |
| `src/cost.ts` | per-response cost extraction (JSON + SSE) |
| `src/models.ts` | `cache_control` safety (strip for unsafe models) |
| `scripts/mint.ts` | mint a per-deploy token for live verification |
-| `test/` | `logic` (20) + `integration` (11) — **31 green** |
+| `test/` | `logic` (25) + `integration` (11) — **36 green** |
## Production deployment
The permanent Worker identity is `oc-agent-gateway-prod`, exposed only at its Workers.dev URL. Its
fresh `SpendCounter` and `DeployLease` state is owned by that Worker. Production config fixes
`GATEWAY_ORKEY_URL` to `https://api.opencomputer.dev/internal/gateway/org-key`; it does not configure
-`TEST_OR_KEY` or `AGENT_BUDGET_USD_DEFAULT`.
+`AGENT_BUDGET_USD_DEFAULT`.
Default deploy fails intentionally. Production requires the explicit command:
diff --git a/cloudflare-workers/oc-gateway/src/index.ts b/cloudflare-workers/oc-gateway/src/index.ts
index bdbdd790..24afd01e 100644
--- a/cloudflare-workers/oc-gateway/src/index.ts
+++ b/cloudflare-workers/oc-gateway/src/index.ts
@@ -46,8 +46,6 @@ export interface Env {
// Org OR-key seam (orgkey.ts): dedicated internal sessions-api route + its bearer secret.
GATEWAY_ORKEY_URL?: string;
GATEWAY_ORKEY_SECRET?: string;
- // Acceptance-test single-key override (bypasses the seam). Never set in multi-org prod.
- TEST_OR_KEY?: string;
// Bearer that guards the control-plane admin routes (/admin/*). Unset → admin routes 404.
GATEWAY_ADMIN_SECRET?: string;
// Override OpenRouter base for tests; default = prod.
diff --git a/cloudflare-workers/oc-gateway/src/orgkey.ts b/cloudflare-workers/oc-gateway/src/orgkey.ts
index bfc1e636..58931482 100644
--- a/cloudflare-workers/oc-gateway/src/orgkey.ts
+++ b/cloudflare-workers/oc-gateway/src/orgkey.ts
@@ -13,14 +13,12 @@
// → 404/other on no active managed key.
//
// The plaintext is cached PER ORG in-isolate with a short TTL — it bounds exposure (evaporates with
-// the isolate) and avoids hammering the seam on every model call in a turn. TEST_OR_KEY short-circuits
-// resolution for the acceptance run against a throwaway $1-capped key (no sealed dev credential needed).
+// the isolate) and avoids hammering the seam on every model call in a turn. There is deliberately no
+// single-key override: every environment exercises the org-scoped seam and missing config fails closed.
export interface OrgKeyEnv {
GATEWAY_ORKEY_URL?: string;
GATEWAY_ORKEY_SECRET?: string;
- /** Acceptance-test / single-key override — bypasses the seam. Never set in multi-org prod. */
- TEST_OR_KEY?: string;
}
interface CacheEntry {
@@ -32,8 +30,6 @@ const cache = new Map<string, CacheEntry>();
/** Resolve the org's OpenRouter inference key, or null if unavailable. Never throws. */
export async function resolveOrgKey(env: OrgKeyEnv, orgId: string, nowMs: number): Promise<string | null> {
- if (env.TEST_OR_KEY) return env.TEST_OR_KEY;
-
const hit = cache.get(orgId);
if (hit && hit.exp > nowMs) return hit.key;
diff --git a/cloudflare-workers/oc-gateway/test/integration.test.ts b/cloudflare-workers/oc-gateway/test/integration.test.ts
index 57a7eea3..243b13de 100644
--- a/cloudflare-workers/oc-gateway/test/integration.test.ts
+++ b/cloudflare-workers/oc-gateway/test/integration.test.ts
@@ -11,9 +11,11 @@ import worker, { Env } from "../src/index.js";
import { SpendCounter } from "../src/budget.js";
import { DeployLease } from "../src/deploylease.js";
import { generateKeyPair, mintDeployToken } from "../src/token.js";
+import { _clearOrgKeyCache } from "../src/orgkey.js";
const OR_KEY = "sk-or-v1-FAKE-org-key";
const OR_BASE = "https://mock-openrouter.test/api";
+const OR_KEY_URL = "https://api.opencomputer.dev/internal/gateway/org-key";
const ORG_ID = "11111111-1111-4111-8111-111111111111";
const AGENT_ID = "agt_0123456789abcdef01234567";
@@ -53,6 +55,14 @@ let lastHeadersToOR: Headers | null;
function mockFetch(perCallCost: number) {
return vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
const url = typeof input === "string" ? input : input.toString();
+ if (url === OR_KEY_URL) {
+ expect(new Headers(init?.headers).get("authorization")).toBe("Bearer dedicated-org-key-bearer");
+ expect(JSON.parse(String(init?.body))).toEqual({ org: ORG_ID });
+ return new Response(JSON.stringify({ key: OR_KEY }), {
+ status: 200,
+ headers: { "content-type": "application/json" },
+ });
+ }
lastHeadersToOR = new Headers(init?.headers);
lastAuthToOR = lastHeadersToOR.get("authorization");
lastBodyToOR = init?.body ? JSON.parse(init.body as string) : null;
@@ -70,7 +80,15 @@ function mockFetch(perCallCost: number) {
function mkEnv(extra: Partial<Env> = {}) {
const spend = fakeNamespace(SpendCounter);
const lease = fakeNamespace(DeployLease);
- const env = { GATEWAY_TOKEN_PUBLIC_KEY: PUB, TEST_OR_KEY: OR_KEY, OPENROUTER_BASE: OR_BASE, SPEND_COUNTER: spend.ns, DEPLOY_LEASE: lease.ns, ...extra } as Env;
+ const env = {
+ GATEWAY_TOKEN_PUBLIC_KEY: PUB,
+ GATEWAY_ORKEY_URL: OR_KEY_URL,
+ GATEWAY_ORKEY_SECRET: "dedicated-org-key-bearer",
+ OPENROUTER_BASE: OR_BASE,
+ SPEND_COUNTER: spend.ns,
+ DEPLOY_LEASE: lease.ns,
+ ...extra,
+ } as Env;
return { env, spend, lease };
}
@@ -99,7 +117,12 @@ const stateOf = async (inst: { fetch(r: Request): Promise<Response> }) =>
(await inst.fetch(new Request("https://do/state"))).json() as Promise<{ spent_micro: number }>;
describe("gateway on-path flow (resolved seam)", () => {
- beforeEach(() => { lastAuthToOR = null; lastBodyToOR = null; lastHeadersToOR = null; });
+ beforeEach(() => {
+ _clearOrgKeyCache();
+ lastAuthToOR = null;
+ lastBodyToOR = null;
+ lastHeadersToOR = null;
+ });
afterEach(() => vi.restoreAllMocks());
it("GET /healthz → ok", async () => {
diff --git a/cloudflare-workers/oc-gateway/test/logic.test.ts b/cloudflare-workers/oc-gateway/test/logic.test.ts
index 37d43189..503e1113 100644
--- a/cloudflare-workers/oc-gateway/test/logic.test.ts
+++ b/cloudflare-workers/oc-gateway/test/logic.test.ts
@@ -89,6 +89,12 @@ describe("deploy token (EdDSA, per-deploy {org, agt})", () => {
describe("org-key identity seam", () => {
afterEach(() => { _clearOrgKeyCache(); vi.restoreAllMocks(); });
+ it("fails closed without the dedicated route and bearer", async () => {
+ const fetchMock = vi.spyOn(globalThis, "fetch");
+ expect(await resolveOrgKey({}, ORG_ID, Date.now())).toBeNull();
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+
it("sends the token's bare UUID exactly once to the sessions API", async () => {
let request: { url: string; auth: string | null; body: unknown } | undefined;
vi.stubGlobal("fetch", vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
diff --git a/cloudflare-workers/oc-gateway/wrangler.toml b/cloudflare-workers/oc-gateway/wrangler.toml
index 0d652ce4..0d82b6a4 100644
--- a/cloudflare-workers/oc-gateway/wrangler.toml
+++ b/cloudflare-workers/oc-gateway/wrangler.toml
@@ -42,5 +42,5 @@ GATEWAY_ORKEY_URL = "https://api.opencomputer.dev/internal/gateway/org-key"
# GATEWAY_TOKEN_PUBLIC_KEY — base64url raw 32-byte Ed25519 public key
# GATEWAY_ORKEY_SECRET — bearer for the dedicated org-key route
# GATEWAY_ADMIN_SECRET — bearer for /admin/*
-# TEST_OR_KEY is test-only and MUST be absent from production.
+# No single-key test override exists; production and tests both exercise the org-key seam.
# AGENT_BUDGET_USD_DEFAULT is intentionally absent; managed OpenRouter/Autumn limits are authoritative.
diff --git a/cmd/oc/internal/commands/agent_deploy_flue.go b/cmd/oc/internal/commands/agent_deploy_flue.go
index 581c1f30..c44f0227 100644
--- a/cmd/oc/internal/commands/agent_deploy_flue.go
+++ b/cmd/oc/internal/commands/agent_deploy_flue.go
@@ -225,7 +225,8 @@ func runFlueBuild(ctx context.Context, dir string) error {
// readFlueBundle locates the generated wrangler, extracts the exact Flue descriptor,
// and reads only regular .js/.mjs modules rooted at the wrangler's directory. The raw
-// wrangler resolution dump, .vite state, source maps and non-modules are never archived.
+// wrangler resolution dump, .vite state and source maps are known control artifacts and
+// are never archived; any other non-module fails loudly instead of producing a broken deploy.
func readFlueBundle(distDir string) ([]bundle.File, flueWranglerDescriptor, error) {
wranglerPath, err := findGeneratedWrangler(distDir)
if err != nil {
@@ -362,7 +363,8 @@ func findGeneratedWrangler(distDir string) (string, error) {
}
// readBundleModules walks the output into a module-only fileset with normalized modes
-// and forward-slash, root-relative paths. Symlinks and special files fail closed.
+// and forward-slash, root-relative paths. Symlinks, special files and unexpected regular
+// files fail closed. Only the generated wrangler, source maps and .vite state are ignored.
func readBundleModules(root string) ([]bundle.File, error) {
if info, err := os.Stat(root); err != nil || !info.IsDir() {
return nil, fmt.Errorf("build output %s not found — did `flue build --target cloudflare` run?", root)
@@ -386,19 +388,22 @@ func readBundleModules(root string) ([]bundle.File, error) {
return err
}
rel = filepath.ToSlash(rel)
- if !safeFlueModulePath(rel) {
- return nil // excludes wrangler.json, source maps and every non-.js/.mjs file
- }
- content, err := os.ReadFile(p)
- if err != nil {
- return err
- }
st, err := d.Info()
if err != nil {
return err
}
if !st.Mode().IsRegular() {
- return fmt.Errorf("build output contains non-regular module %s", p)
+ return fmt.Errorf("build output contains non-regular file %s", p)
+ }
+ if rel == "wrangler.json" || strings.HasSuffix(rel, ".map") {
+ return nil
+ }
+ if !safeFlueModulePath(rel) {
+ return fmt.Errorf("build output contains unsupported file %q; expected only .js/.mjs modules", rel)
+ }
+ content, err := os.ReadFile(p)
+ if err != nil {
+ return err
}
files = append(files, bundle.File{
Path: rel,
diff --git a/cmd/oc/internal/commands/agent_deploy_flue_test.go b/cmd/oc/internal/commands/agent_deploy_flue_test.go
index ca897113..14b32cdc 100644
--- a/cmd/oc/internal/commands/agent_deploy_flue_test.go
+++ b/cmd/oc/internal/commands/agent_deploy_flue_test.go
@@ -121,12 +121,11 @@ func TestDeployFlueDoEndToEnd(t *testing.T) {
"cat > dist/e2e_flue/.flue-vite/runtime.mjs <<'JS'\n" + e2eRuntimeBody + "\nJS\n" +
"printf '%s' '{\"version\":3}' > dist/e2e_flue/.vite/manifest.json\n" +
"printf '%s' '{\"version\":3}' > dist/e2e_flue/index.js.map\n" +
- "printf '%s' 'not a module' > dist/e2e_flue/README.txt\n" +
"cat > dist/e2e_flue/wrangler.json <<'JSON'\n" + e2eWranglerBody + "\nJSON\n"
writeFile(t, filepath.Join(dir, "node_modules", ".bin", "flue"), buildScript, 0o755)
- // Only regular modules leave the machine. Raw Wrangler metadata, .vite state,
- // source maps and non-modules are absent; .flue-vite is a legitimate module path.
+ // Only regular modules leave the machine. Raw Wrangler metadata, .vite state and
+ // source maps are absent; .flue-vite is a legitimate module path.
expectedFiles := []bundle.File{
{Path: "index.js", Mode: 0o644, Content: []byte(e2eModuleBody + "\n")},
{Path: "assets/chunk.js", Mode: 0o644, Content: []byte(e2eAssetBody + "\n")},
@@ -317,6 +316,15 @@ func TestReadBundleModulesRejectsSymlink(t *testing.T) {
}
}
+func TestReadBundleModulesRejectsUnexpectedRegularFile(t *testing.T) {
+ root := t.TempDir()
+ writeFile(t, filepath.Join(root, "index.js"), "export {};", 0o644)
+ writeFile(t, filepath.Join(root, "runtime.wasm"), "not really wasm", 0o644)
+ if _, err := readBundleModules(root); err == nil || !strings.Contains(err.Error(), "unsupported file") {
+ t.Fatalf("expected unsupported-file rejection, got %v", err)
+ }
+}
+
func TestSyncManifestVarsReplacesDesiredVars(t *testing.T) {
f := &fakeCP{}
srv := httptest.NewServer(f)