diff --git a/.github/workflows/token-vault-validation.yml b/.github/workflows/token-vault-validation.yml index 67ca2a8..e700570 100644 --- a/.github/workflows/token-vault-validation.yml +++ b/.github/workflows/token-vault-validation.yml @@ -24,5 +24,15 @@ jobs: node-version: 22 - name: Validate Worker and password utility run: node security/token-vault/scripts/check-source.mjs - - name: Run Worker smoke tests + - name: Validate D1 schema + run: | + node --input-type=module <<'NODE' + import { DatabaseSync } from 'node:sqlite'; + import { readFileSync } from 'node:fs'; + const db = new DatabaseSync(':memory:'); + db.exec(readFileSync('security/token-vault/schema.sql', 'utf8')); + db.close(); + console.log('D1-compatible schema syntax passed.'); + NODE + - name: Run Worker smoke and integration tests run: node --test security/token-vault/tests/*.test.mjs diff --git a/security/token-vault/README.md b/security/token-vault/README.md index 9bdc727..3ed17d4 100644 --- a/security/token-vault/README.md +++ b/security/token-vault/README.md @@ -4,49 +4,79 @@ A private credential-management service for OCode.js projects. This source packa ## Current implementation -- Bootstrap identity is fixed to `TOKEN`; the sign-in screen asks for a password only. -- Password verification uses PBKDF2-SHA-256 with 310,000 iterations. The verifier is configured as Worker secret `BOOTSTRAP_PASSWORD_HASH`. +- Bootstrap identity is fixed to TOKEN; the sign-in screen asks for a password only. +- Password verification uses PBKDF2-SHA-256 with 310,000 iterations. The verifier is configured as Worker secret BOOTSTRAP_PASSWORD_HASH. - Token values are encrypted server-side with AES-256-GCM and a fresh 96-bit IV before D1 storage. +- Each token is assigned a project ID (default: ocodejs-core). - Session cookies are Secure, HttpOnly, SameSite=Strict, signed with a separate key, and expire after four hours. Server-side revocation is supported. -- State-changing browser requests require an exact same-origin `Origin` and reject cross-site Fetch Metadata. +- State-changing browser requests require an exact same-origin Origin and reject cross-site Fetch Metadata. - Login and reveal operations have IP-based D1 rate limits. Authentication responses do not reveal whether an identity exists. -- The Worker sends no-store and browser security headers. Session role is read from the current identity row, not copied from an old session snapshot. -- The Worker currently serves its password-only login and credential inventory UI at `/` and `/vault`. -- Token reveal is explicit, audited, and restricted to `owner` and `security_admin`. The dashboard clears a revealed value after 15 seconds. +- The Worker sends no-store and browser security headers. Session role is read from the current identity row on every request. +- The Worker serves its password-only login and credential inventory UI at / and /vault. +- Token reveal is explicit, audited, and restricted to owner and security_admin. The dashboard clears a revealed value after 15 seconds. + +## AI Agent access + +Owners can issue a unique machine credential for each agent. The raw API key is shown only once; D1 stores only its SHA-256 hash. Keys expire after 1–365 days (90 days by default) and can be revoked. + +Each agent receives explicit per-project grants: + +- metadata: list credential metadata for that project. +- reveal: list metadata and reveal token values for that project. + +An agent cannot enumerate other projects, use the human session cookie, or call the browser login. Agent endpoints reject requests carrying an Origin header and require a bearer key. Every successful agent reveal is audited. Never grant an agent a human owner or security_admin role. + +Example machine API: + + GET /api/agent/tokens?project_id=ocodejs-core + Authorization: Bearer oca_ + +For an approved reveal grant: + + POST /api/agent/tokens//reveal + Authorization: Bearer oca_ ## Required Cloudflare resources - Cloudflare Worker runtime. -- D1 database created from `schema.sql`. -- D1 binding named `DB`. -- Worker secrets: `BOOTSTRAP_PASSWORD_HASH`, `SESSION_SIGNING_KEY`, `TOKEN_ENCRYPTION_KEY`. +- D1 database created from schema.sql. +- D1 binding named DB. +- Worker secrets: BOOTSTRAP_PASSWORD_HASH, SESSION_SIGNING_KEY, TOKEN_ENCRYPTION_KEY. -Generate a new unique password locally with the hidden-input utility in `scripts/hash-password.mjs`. Store only its output as `BOOTSTRAP_PASSWORD_HASH`. Generate independent random 32-byte signing and encryption keys; store them as Worker secrets. The password previously supplied in chat is exposed and must never be used. +Generate a new unique password locally with the hidden-input utility in scripts/hash-password.mjs. Store only its output as BOOTSTRAP_PASSWORD_HASH. Generate independent random 32-byte signing and encryption keys; store them as Worker secrets. The password previously supplied in chat is exposed and must never be used. The encryption key is expected as Base64 or Base64URL encoding of exactly 32 random bytes. The signing key must be at least 32 characters. Do not reuse key material across purposes. ## Roles and current limitations -| Role | Browse metadata | Create / reveal / delete | -|---|---:|---:| -| owner | Yes | Yes | -| security_admin | Yes | Yes | -| developer | Yes | No | -| ai_agent | Yes | No | -| auditor | Yes | No | +| Role | Browse metadata | Create / reveal / delete | Manage AI agents | +|---|---:|---:|---:| +| owner | Yes | Yes | Yes | +| security_admin | Yes | Yes | No | +| developer | Yes | No | No | +| ai_agent | Project-scoped | Project-granted reveal only | No | +| auditor | Yes | No | No | -The current API only bootstraps the `TOKEN` owner identity. It does **not yet** provision staff identities, issue scoped AI-agent grants, or provide a safe token-broker/proxy for agents. Do not grant an agent a human administrator role. The next security milestone is individual identity provisioning plus project-scoped capabilities and audited approval. Until then, AI-agent and staff access is not enabled. +The bootstrap TOKEN identity is currently the only human login. Individual staff SSO/identity provisioning is not implemented in this milestone. AI Agent credentials are independent, project-scoped machine identities; do not share the bootstrap password with agents or staff. ## API -- `POST /api/login` — password-only bootstrap login. -- `POST /api/logout` — revoke the current session. -- `GET /api/me` — current identity and role. -- `GET /api/tokens` — credential metadata only. -- `POST /api/tokens` — encrypt and store a credential. -- `POST /api/tokens/:id/reveal` — privileged reveal with audit event. -- `DELETE /api/tokens/:id` — privileged deletion with audit event. +- POST /api/login — password-only bootstrap login. +- POST /api/logout — revoke the current session. +- GET /api/me — current identity and role. +- GET /api/tokens — credential metadata. +- POST /api/tokens — encrypt and store a project-scoped credential. +- POST /api/tokens/:id/reveal — privileged human reveal with audit event. +- DELETE /api/tokens/:id — privileged deletion with audit event. +- GET /api/agents, POST /api/agents — owner-only agent inventory and one-time key issuance. +- GET/POST /api/agents/:subject/grants — owner-only project grants. +- DELETE /api/agents/:subject — revoke an agent. +- GET /api/agent/tokens?project_id=... — agent metadata within granted project. +- POST /api/agent/tokens/:id/reveal — agent reveal only with an explicit reveal grant. ## Validation and deployment -Run `node security/token-vault/scripts/check-source.mjs` for source validation and `node --test security/token-vault/tests/*.test.mjs` for Worker smoke tests. This repository change is not a deployment. No Worker, D1 database, Access policy, secrets, or live tokens have been created or configured. Keep the service behind Cloudflare Access before any staging exposure. +Run node security/token-vault/scripts/check-source.mjs for source validation and node --test security/token-vault/tests/*.test.mjs for Worker smoke tests. This repository change is not a deployment. No Worker, D1 database, Access policy, secrets, or live tokens have been created or configured. Keep the service behind Cloudflare Access before any staging exposure. + + +Schema validation is executed against an in-memory SQLite database in CI before the Worker integration suite. diff --git a/security/token-vault/schema.sql b/security/token-vault/schema.sql index 18c0f3b..2639a97 100644 --- a/security/token-vault/schema.sql +++ b/security/token-vault/schema.sql @@ -12,6 +12,7 @@ CREATE TABLE IF NOT EXISTS vault_tokens ( id TEXT PRIMARY KEY, label TEXT NOT NULL, provider TEXT NOT NULL, + project_id TEXT NOT NULL DEFAULT 'ocodejs-core', ciphertext TEXT NOT NULL, iv TEXT NOT NULL, created_by TEXT NOT NULL, @@ -45,3 +46,31 @@ CREATE TABLE IF NOT EXISTS audit_events ( INSERT OR IGNORE INTO identities (id, subject, role) VALUES ('bootstrap-token-admin', 'TOKEN', 'owner'); + +CREATE TABLE IF NOT EXISTS agent_credentials ( + id TEXT PRIMARY KEY, + subject TEXT NOT NULL UNIQUE, + key_hash TEXT NOT NULL UNIQUE, + active INTEGER NOT NULL DEFAULT 1, + expires_at INTEGER, + last_used_at TEXT, + created_by TEXT NOT NULL, + created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')), + FOREIGN KEY(subject) REFERENCES identities(subject), + FOREIGN KEY(created_by) REFERENCES identities(subject) +); + +CREATE TABLE IF NOT EXISTS agent_project_grants ( + agent_id TEXT NOT NULL, + project_id TEXT NOT NULL, + permission TEXT NOT NULL CHECK (permission IN ('metadata','reveal')), + created_by TEXT NOT NULL, + created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')), + PRIMARY KEY(agent_id, project_id), + FOREIGN KEY(agent_id) REFERENCES agent_credentials(id) ON DELETE CASCADE, + FOREIGN KEY(created_by) REFERENCES identities(subject) +); + +CREATE INDEX IF NOT EXISTS idx_vault_tokens_project ON vault_tokens(project_id); +CREATE INDEX IF NOT EXISTS idx_agent_credentials_key_hash ON agent_credentials(key_hash); +CREATE INDEX IF NOT EXISTS idx_agent_grants_project ON agent_project_grants(project_id, permission); diff --git a/security/token-vault/scripts/check-source.mjs b/security/token-vault/scripts/check-source.mjs index ee6c792..468b5b8 100644 --- a/security/token-vault/scripts/check-source.mjs +++ b/security/token-vault/scripts/check-source.mjs @@ -24,6 +24,10 @@ for (const marker of [ 'rateLimit(req, env, "login")', 'rateLimit(req, env, "reveal")', 'path === "/vault"', + "authenticateAgent", + "agent_project_grants", + "agent.token.reveal", + "validProject(projectId)", '"cache-control": "no-store, max-age=0"' ]) assert.ok(worker.includes(marker), "Missing security invariant: " + marker); assert.ok(!worker.includes("!origin ||"), "Missing Origin must not be accepted"); @@ -33,3 +37,7 @@ assert.ok(passwordScript.includes("code === 13 || code === 10"), "Password utili assert.ok(passwordScript.includes("password.length < 16"), "Bootstrap password must be at least 16 chars"); assert.ok(!/sk-[A-Za-z0-9]{20,}/.test(worker + passwordScript), "Possible hard-coded provider token"); console.log("Token Vault source validation passed."); + +assert.ok(schema.includes("CREATE TABLE IF NOT EXISTS agent_credentials")); +assert.ok(schema.includes("CREATE TABLE IF NOT EXISTS agent_project_grants")); +assert.ok(schema.includes("project_id TEXT NOT NULL DEFAULT 'ocodejs-core'")); diff --git a/security/token-vault/src/worker.js b/security/token-vault/src/worker.js index ce35bee..5d1a849 100644 --- a/security/token-vault/src/worker.js +++ b/security/token-vault/src/worker.js @@ -99,15 +99,36 @@ async function rateLimit(req, env, action) { } return { ok: true, bucket }; } -const LOGIN_HTML = 'OCode.js · Token Vault
OCODE.JS / SECURITY

Token Vault

Protected credential workspace

'; -const VAULT_HTML = 'OCode.js · Vault
OCode.js / TOKEN VAULT
Checking session…

Credential workspace

Encrypted storage · Explicit reveal · Audited access

Register credential
Security

Secrets are encrypted before storage. Reveal is restricted to privileged roles. Revealed values are cleared after 15 seconds.

Stored credentials
Loading…
'; + +async function authenticateAgent(req, env) { + if (req.headers.has("origin")) return null; + const header = req.headers.get("authorization") || ""; + const match = header.match(/^Bearer (oca_[A-Za-z0-9_-]{40,64})$/); + if (!match) return null; + const row = await env.DB.prepare( + "SELECT c.id,c.subject,c.expires_at,i.active FROM agent_credentials c JOIN identities i ON i.subject=c.subject WHERE c.key_hash=? AND c.active=1" + ).bind(await hash(match[1])).first(); + const now = Math.floor(Date.now() / 1000); + if (!row || !row.active || (row.expires_at && row.expires_at <= now)) return null; + await env.DB.prepare("UPDATE agent_credentials SET last_used_at=strftime('%Y-%m-%dT%H:%M:%fZ','now') WHERE id=?").bind(row.id).run(); + return { id: row.id, subject: row.subject }; +} +async function agentGrant(env, agentId, projectId) { + return env.DB.prepare("SELECT permission FROM agent_project_grants WHERE agent_id=? AND project_id=?") + .bind(agentId, projectId).first(); +} +function validProject(value) { + return typeof value === "string" && /^[a-z0-9][a-z0-9._-]{1,63}$/.test(value); +} +const LOGIN_HTML = 'OCode.js · Token Vault
OCODE.JS / SECURITY

Token Vault

Protected credential workspace

'; +const VAULT_HTML = 'OCode.js · Vault
OCode.js / TOKEN VAULT
Checking session…

Credential workspace

Encrypted storage · Explicit reveal · Audited access

Register credential
Security

Secrets are encrypted before storage. Reveal is restricted to privileged roles. Revealed values are cleared after 15 seconds.

Stored credentials
Loading…
'; async function login(req, env) { if (!sameOrigin(req)) return json({ error: "Forbidden" }, 403); const limit = await rateLimit(req, env, "login"); if (!limit.ok) return json({ error: "Too many attempts" }, 429); let body; try { body = await req.json(); } catch { return json({ error: "Invalid request" }, 400); } const password = typeof body.password === "string" ? body.password : ""; - if (password.length < 12 || password.length > 1024 || !await verifyPassword(password, env.BOOTSTRAP_PASSWORD_HASH)) { + if (password.length < 16 || password.length > 1024 || !await verifyPassword(password, env.BOOTSTRAP_PASSWORD_HASH)) { await audit(env, "TOKEN", "login", null, "denied"); return json({ error: "Unauthorized" }, 401); } @@ -123,7 +144,9 @@ async function login(req, env) { async function route(req, env) { const path = new URL(req.url).pathname; if (req.method === "GET" && (path === "/" || path === "/login")) return page(LOGIN_HTML); - if ((req.method === "POST" || req.method === "DELETE") && !sameOrigin(req)) return json({ error: "Forbidden" }, 403); + if (path.startsWith("/api/agent/")) { + if (req.headers.has("origin")) return json({ error: "Forbidden" }, 403); + } else if ((req.method === "POST" || req.method === "DELETE") && !sameOrigin(req)) return json({ error: "Forbidden" }, 403); if (req.method === "GET" && path === "/vault") { configured(env); return await currentUser(req, env) ? page(VAULT_HTML) : Response.redirect(new URL("/", req.url), 303); @@ -136,23 +159,131 @@ async function route(req, env) { if (user) await audit(env, user.subject, "logout", null); return json({ ok: true }, 200, { "set-cookie": cookie("", 0) }); } + + if (path.startsWith("/api/agent/")) { + const agent = await authenticateAgent(req, env); + if (!agent) return json({ error: "Unauthorized" }, 401); + if (req.method === "GET" && path === "/api/agent/tokens") { + const projectId = new URL(req.url).searchParams.get("project_id") || ""; + if (!validProject(projectId)) return json({ error: "Invalid project_id" }, 400); + const grant = await agentGrant(env, agent.id, projectId); + if (!grant) return json({ error: "Forbidden" }, 403); + const rows = await env.DB.prepare( + "SELECT id,label,provider,project_id,created_at FROM vault_tokens WHERE project_id=? ORDER BY created_at DESC LIMIT 200" + ).bind(projectId).all(); + return json({ tokens: rows.results, permission: grant.permission }); + } + const agentReveal = path.match(/^\/api\/agent\/tokens\/([0-9a-f-]+)\/reveal$/i); + if (req.method === "POST" && agentReveal) { + const row = await env.DB.prepare("SELECT id,project_id,ciphertext,iv FROM vault_tokens WHERE id=?") + .bind(agentReveal[1]).first(); + if (!row) return json({ error: "Not found" }, 404); + const grant = await agentGrant(env, agent.id, row.project_id); + if (!grant || grant.permission !== "reveal") return json({ error: "Forbidden" }, 403); + const agentRevealLimit = await rateLimit(req, env, "reveal"); + if (!agentRevealLimit.ok) return json({ error: "Too many reveal attempts" }, 429); + try { + const clear = await crypto.subtle.decrypt( + { name: "AES-GCM", iv: unb64(row.iv) }, await key(env), unb64(row.ciphertext) + ); + await audit(env, agent.subject, "agent.token.reveal", row.id); + return json({ value: new TextDecoder().decode(clear) }); + } catch { + await audit(env, agent.subject, "agent.token.reveal", row.id, "decrypt_failed"); + return json({ error: "Unable to reveal credential" }, 500); + } + } + return json({ error: "Not found" }, 404); + } const user = await currentUser(req, env); if (!user) return json({ error: "Unauthorized" }, 401); if (req.method === "GET" && path === "/api/me") return json({ subject: user.subject, role: user.role }); + + if (req.method === "GET" && path === "/api/agents") { + if (user.role !== "owner") return json({ error: "Forbidden" }, 403); + const rows = await env.DB.prepare( + "SELECT c.id,c.subject,c.active,c.expires_at,c.last_used_at,c.created_at FROM agent_credentials c ORDER BY c.created_at DESC" + ).all(); + return json({ agents: rows.results }); + } + if (req.method === "POST" && path === "/api/agents") { + if (user.role !== "owner") return json({ error: "Forbidden" }, 403); + let body; try { body = await req.json(); } catch { return json({ error: "Invalid request" }, 400); } + const subject = typeof body.subject === "string" ? body.subject.trim() : ""; + const days = Number.isInteger(body.expires_in_days) ? body.expires_in_days : 90; + if (!/^[a-zA-Z0-9][a-zA-Z0-9._-]{2,63}$/.test(subject) || subject === "TOKEN" || days < 1 || days > 365) { + return json({ error: "Invalid agent subject or expiry" }, 400); + } + const agentId = crypto.randomUUID(); + const apiKey = "oca_" + b64(crypto.getRandomValues(new Uint8Array(32))); + const expiresAt = Math.floor(Date.now() / 1000) + days * 86400; + try { + await env.DB.batch([ + env.DB.prepare("INSERT INTO identities(id,subject,role,active) VALUES(?,?, 'ai_agent',1)") + .bind(crypto.randomUUID(), subject), + env.DB.prepare("INSERT INTO agent_credentials(id,subject,key_hash,expires_at,created_by) VALUES(?,?,?,?,?)") + .bind(agentId, subject, await hash(apiKey), expiresAt, user.subject) + ]); + } catch { + return json({ error: "Agent identity already exists or could not be created" }, 409); + } + await audit(env, user.subject, "agent.create", agentId); + return json({ subject, api_key: apiKey, expires_at: expiresAt }, 201); + } + const agentGrantPath = path.match(/^\/api\/agents\/([a-zA-Z0-9._-]{3,64})\/grants$/); + if (agentGrantPath && req.method === "GET") { + if (user.role !== "owner") return json({ error: "Forbidden" }, 403); + const subject = agentGrantPath[1]; + const rows = await env.DB.prepare( + "SELECT g.project_id,g.permission,g.created_at FROM agent_project_grants g JOIN agent_credentials c ON c.id=g.agent_id WHERE c.subject=? ORDER BY g.project_id" + ).bind(subject).all(); + return json({ grants: rows.results }); + } + if (agentGrantPath && req.method === "POST") { + if (user.role !== "owner") return json({ error: "Forbidden" }, 403); + let body; try { body = await req.json(); } catch { return json({ error: "Invalid request" }, 400); } + if (!validProject(body.project_id) || !["metadata", "reveal"].includes(body.permission)) { + return json({ error: "Invalid project grant" }, 400); + } + const agent = await env.DB.prepare("SELECT id FROM agent_credentials WHERE subject=? AND active=1") + .bind(agentGrantPath[1]).first(); + if (!agent) return json({ error: "Agent not found" }, 404); + await env.DB.prepare( + "INSERT INTO agent_project_grants(agent_id,project_id,permission,created_by) VALUES(?,?,?,?) ON CONFLICT(agent_id,project_id) DO UPDATE SET permission=excluded.permission,created_by=excluded.created_by,created_at=strftime('%Y-%m-%dT%H:%M:%fZ','now')" + ).bind(agent.id, body.project_id, body.permission, user.subject).run(); + await audit(env, user.subject, "agent.grant", agent.id + ":" + body.project_id); + return json({ ok: true }); + } + const agentPath = path.match(/^\/api\/agents\/([a-zA-Z0-9._-]{3,64})$/); + if (agentPath && req.method === "DELETE") { + if (user.role !== "owner") return json({ error: "Forbidden" }, 403); + const subject = agentPath[1]; + const agent = await env.DB.prepare("SELECT id FROM agent_credentials WHERE subject=?") + .bind(subject).first(); + if (!agent) return json({ error: "Agent not found" }, 404); + await env.DB.batch([ + env.DB.prepare("UPDATE identities SET active=0 WHERE subject=?").bind(subject), + env.DB.prepare("UPDATE agent_credentials SET active=0 WHERE subject=?").bind(subject) + ]); + await audit(env, user.subject, "agent.revoke", agent.id); + return json({ ok: true }); + } + if (req.method === "GET" && path === "/api/tokens") { - const rows = await env.DB.prepare("SELECT id,label,provider,created_at,rotated_at FROM vault_tokens ORDER BY created_at DESC LIMIT 200").all(); + const rows = await env.DB.prepare("SELECT id,label,provider,project_id,created_at,rotated_at FROM vault_tokens ORDER BY created_at DESC LIMIT 200").all(); return json({ tokens: rows.results }); } if (req.method === "POST" && path === "/api/tokens") { if (!PRIVILEGED.has(user.role)) return json({ error: "Forbidden" }, 403); let body; try { body = await req.json(); } catch { return json({ error: "Invalid request" }, 400); } + const projectId = body.project_id || "ocodejs-core"; if (typeof body.label !== "string" || !body.label.trim() || typeof body.provider !== "string" || !body.provider.trim() || - typeof body.value !== "string" || body.value.length < 8 || body.value.length > 8192) return json({ error: "Invalid token record" }, 400); + !validProject(projectId) || typeof body.value !== "string" || body.value.length < 8 || body.value.length > 8192) return json({ error: "Invalid token record" }, 400); const iv = crypto.getRandomValues(new Uint8Array(12)); const ciphertext = await crypto.subtle.encrypt({ name: "AES-GCM", iv }, await key(env), enc.encode(body.value)); const id = crypto.randomUUID(); - await env.DB.prepare("INSERT INTO vault_tokens(id,label,provider,ciphertext,iv,created_by) VALUES(?,?,?,?,?,?)") - .bind(id, body.label.trim().slice(0, 100), body.provider.trim().slice(0, 80), b64(ciphertext), b64(iv), user.subject).run(); + await env.DB.prepare("INSERT INTO vault_tokens(id,label,provider,project_id,ciphertext,iv,created_by) VALUES(?,?,?,?,?,?,?)") + .bind(id, body.label.trim().slice(0, 100), body.provider.trim().slice(0, 80), projectId, b64(ciphertext), b64(iv), user.subject).run(); await audit(env, user.subject, "token.create", id); return json({ id }, 201); } diff --git a/security/token-vault/tests/agent-scope.test.mjs b/security/token-vault/tests/agent-scope.test.mjs new file mode 100644 index 0000000..1d3dd40 --- /dev/null +++ b/security/token-vault/tests/agent-scope.test.mjs @@ -0,0 +1,130 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; +import { DatabaseSync } from "node:sqlite"; +import { pbkdf2Sync, randomBytes } from "node:crypto"; +import worker from "../src/worker.js"; + +class D1Statement { + constructor(db, sql) { this.db = db; this.sql = sql; this.args = []; } + bind(...args) { this.args = args; return this; } + first() { return this.db.sqlite.prepare(this.sql).get(...this.args) ?? null; } + all() { return { results: this.db.sqlite.prepare(this.sql).all(...this.args) }; } + run() { + const result = this.db.sqlite.prepare(this.sql).run(...this.args); + return { meta: { changes: Number(result.changes) } }; + } +} +class D1Mock { + constructor() { + this.sqlite = new DatabaseSync(":memory:"); + this.sqlite.exec(readFileSync(new URL("../schema.sql", import.meta.url), "utf8")); + } + prepare(sql) { return new D1Statement(this, sql); } + batch(statements) { + this.sqlite.exec("BEGIN"); + try { + for (const statement of statements) this.sqlite.prepare(statement.sql).run(...statement.args); + this.sqlite.exec("COMMIT"); + } catch (error) { + this.sqlite.exec("ROLLBACK"); + throw error; + } + } +} +function makeEnv() { + const password = "vault-test-password-2026"; + const salt = randomBytes(16); + const verifier = salt.toString("base64") + ":" + pbkdf2Sync(password, salt, 310000, 32, "sha256").toString("base64"); + return { + password, + env: { + DB: new D1Mock(), + BOOTSTRAP_PASSWORD_HASH: verifier, + SESSION_SIGNING_KEY: randomBytes(32).toString("base64"), + TOKEN_ENCRYPTION_KEY: randomBytes(32).toString("base64") + } + }; +} +function browserHeaders(cookie) { + return { + origin: "https://vault.example", + "sec-fetch-site": "same-origin", + "content-type": "application/json", + ...(cookie ? { cookie } : {}) + }; +} +async function call(path, env, { method = "GET", body, headers = {} } = {}) { + return worker.fetch(new Request("https://vault.example" + path, { + method, + headers, + ...(body === undefined ? {} : { body: JSON.stringify(body) }) + }), env); +} + +test("AI agent grants isolate projects and reveal permission, and revocation works", async () => { + const { env, password } = makeEnv(); + const login = await call("/api/login", env, { + method: "POST", + headers: browserHeaders(), + body: { password } + }); + assert.equal(login.status, 200); + const cookie = login.headers.get("set-cookie").split(";")[0]; + + const createToken = async (label, project_id, value) => { + const response = await call("/api/tokens", env, { + method: "POST", + headers: browserHeaders(cookie), + body: { label, provider: "test-provider", project_id, value } + }); + assert.equal(response.status, 201); + return (await response.json()).id; + }; + const alphaToken = await createToken("alpha-secret", "project-alpha", "alpha-secret-value"); + const betaToken = await createToken("beta-secret", "project-beta", "beta-secret-value"); + + const createAgent = await call("/api/agents", env, { + method: "POST", + headers: browserHeaders(cookie), + body: { subject: "agent-integration-test", expires_in_days: 7 } + }); + assert.equal(createAgent.status, 201); + const { api_key: apiKey } = await createAgent.json(); + assert.match(apiKey, /^oca_[A-Za-z0-9_-]{40,64}$/); + + const grant = async (project_id, permission) => call("/api/agents/agent-integration-test/grants", env, { + method: "POST", + headers: browserHeaders(cookie), + body: { project_id, permission } + }); + assert.equal((await grant("project-alpha", "reveal")).status, 200); + assert.equal((await grant("project-beta", "metadata")).status, 200); + + const bearer = { authorization: "Bearer " + apiKey, "cf-connecting-ip": "203.0.113.8" }; + const alphaList = await call("/api/agent/tokens?project_id=project-alpha", env, { headers: bearer }); + assert.equal(alphaList.status, 200); + assert.deepEqual((await alphaList.json()).tokens.map(t => t.id), [alphaToken]); + + const crossProject = await call("/api/agent/tokens?project_id=project-gamma", env, { headers: bearer }); + assert.equal(crossProject.status, 403); + + const revealAlpha = await call("/api/agent/tokens/" + alphaToken + "/reveal", env, { + method: "POST", headers: bearer, body: {} + }); + assert.equal(revealAlpha.status, 200); + assert.equal((await revealAlpha.json()).value, "alpha-secret-value"); + + const revealBeta = await call("/api/agent/tokens/" + betaToken + "/reveal", env, { + method: "POST", headers: bearer, body: {} + }); + assert.equal(revealBeta.status, 403); + + const revoke = await call("/api/agents/agent-integration-test", env, { + method: "DELETE", headers: browserHeaders(cookie) + }); + assert.equal(revoke.status, 200); + + const afterRevoke = await call("/api/agent/tokens?project_id=project-alpha", env, { headers: bearer }); + assert.equal(afterRevoke.status, 401); +}); diff --git a/security/token-vault/tests/worker.test.mjs b/security/token-vault/tests/worker.test.mjs index 588eea3..750d3d7 100644 --- a/security/token-vault/tests/worker.test.mjs +++ b/security/token-vault/tests/worker.test.mjs @@ -51,3 +51,21 @@ test("same-origin login fails closed when secrets are not configured", async () }), {}); assert.equal(response.status, 503); }); + +test("agent API rejects requests that carry a browser Origin header", async () => { + const response = await worker.fetch(new Request("https://vault.example/api/agent/tokens?project_id=ocodejs-core", { + headers: { origin: "https://vault.example" } + }), {}); + assert.equal(response.status, 403); +}); + +test("agent API requires an independent bearer credential", async () => { + const env = { + DB: { prepare() { throw new Error("DB must not be queried without a bearer key"); } }, + BOOTSTRAP_PASSWORD_HASH: "configured", + SESSION_SIGNING_KEY: "s".repeat(32), + TOKEN_ENCRYPTION_KEY: Buffer.alloc(32).toString("base64") + }; + const response = await worker.fetch(new Request("https://vault.example/api/agent/tokens?project_id=ocodejs-core"), env); + assert.equal(response.status, 401); +});