diff --git a/security/token-vault/README.md b/security/token-vault/README.md index 3ed17d4..2a5f6b5 100644 --- a/security/token-vault/README.md +++ b/security/token-vault/README.md @@ -42,6 +42,8 @@ For an approved reveal grant: - D1 database created from schema.sql. - D1 binding named DB. - Worker secrets: BOOTSTRAP_PASSWORD_HASH, SESSION_SIGNING_KEY, TOKEN_ENCRYPTION_KEY. +- Worker variable: ACCESS_REQUIRED=true before staging/production exposure. +- Cloudflare Access Self-hosted application for the Worker hostname, with Allow policies restricted to approved staff identity emails or groups. Do not add a public bypass policy. 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. @@ -57,7 +59,7 @@ The encryption key is expected as Base64 or Base64URL encoding of exactly 32 ran | ai_agent | Project-scoped | Project-granted reveal only | No | | auditor | Yes | No | No | -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. +Staff use Cloudflare Access SSO. An owner provisions each staff email and assigns security_admin, developer, or auditor; the email from ctx.access.getIdentity() must match an active D1 identity. Set ACCESS_REQUIRED=true on the Worker before exposure. This also blocks direct workers.dev access for browser/human routes; the independent bearer-key agent API remains protected by its own project-scoped credentials. The TOKEN password remains the bootstrap owner login and is never shared with staff or agents. ## API @@ -68,6 +70,9 @@ The bootstrap TOKEN identity is currently the only human login. Individual staff - 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/members, POST /api/members — owner-only personnel inventory and Access email provisioning. +- PATCH /api/members/:email — update staff role. +- DELETE /api/members/:email — disable staff identity and revoke sessions. - 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. @@ -80,3 +85,7 @@ Run node security/token-vault/scripts/check-source.mjs for source validation and Schema validation is executed against an in-memory SQLite database in CI before the Worker integration suite. + +Cloudflare Workers exposes authenticated Access identity through ctx.access; the Worker uses the verified email claim and then checks the matching active D1 identity before assigning application permissions. See the official Cloudflare Workers Access integration guide: https://developers.cloudflare.com/workers/configuration/cloudflare-access/. + +Staff Access identity is checked against the active D1 identity record on every authenticated request. diff --git a/security/token-vault/scripts/check-source.mjs b/security/token-vault/scripts/check-source.mjs index 468b5b8..54c4b1d 100644 --- a/security/token-vault/scripts/check-source.mjs +++ b/security/token-vault/scripts/check-source.mjs @@ -28,6 +28,9 @@ for (const marker of [ "agent_project_grants", "agent.token.reveal", "validProject(projectId)", + "ctx.access.getIdentity", + "ACCESS_REQUIRED", + "/api/members", '"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"); diff --git a/security/token-vault/src/worker.js b/security/token-vault/src/worker.js index 5d1a849..14053d2 100644 --- a/security/token-vault/src/worker.js +++ b/security/token-vault/src/worker.js @@ -76,13 +76,21 @@ async function audit(env, actor, action, resource, outcome = "success") { await env.DB.prepare("INSERT INTO audit_events(id,actor,action,resource_id,outcome) VALUES(?,?,?,?,?)") .bind(crypto.randomUUID(), actor, action, resource || null, outcome).run(); } -async function currentUser(req, env) { +async function currentUser(req, env, ctx) { const id = await verify(cookieValue(req), env.SESSION_SIGNING_KEY); - if (!id) return null; - const row = await env.DB.prepare("SELECT s.subject,i.role,s.expires_at,i.active FROM sessions s JOIN identities i ON i.subject=s.subject WHERE s.id_hash=? AND s.revoked=0") - .bind(await hash(id)).first(); - if (!row || !row.active || row.expires_at <= Math.floor(Date.now() / 1000)) return null; - return { subject: row.subject, role: row.role }; + if (id) { + const row = await env.DB.prepare("SELECT s.subject,i.role,s.expires_at,i.active FROM sessions s JOIN identities i ON i.subject=s.subject WHERE s.id_hash=? AND s.revoked=0") + .bind(await hash(id)).first(); + if (row && row.active && row.expires_at > Math.floor(Date.now() / 1000)) return { subject: row.subject, role: row.role, auth: "session" }; + } + if (ctx?.access && typeof ctx.access.getIdentity === "function") { + const identity = await ctx.access.getIdentity(); + const email = typeof identity?.email === "string" ? identity.email.trim().toLowerCase() : ""; + if (!email || email.length > 254) return null; + const member = await env.DB.prepare("SELECT subject,role,active FROM identities WHERE subject=?").bind(email).first(); + if (member?.active) return { subject: member.subject, role: member.role, auth: "cloudflare-access" }; + } + return null; } async function key(env) { return crypto.subtle.importKey("raw", unb64(env.TOKEN_ENCRYPTION_KEY), "AES-GCM", false, ["encrypt", "decrypt"]); @@ -121,7 +129,7 @@ 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…
'; +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"); @@ -141,20 +149,28 @@ async function login(req, env) { await audit(env, "TOKEN", "login", null); return json({ ok: true }, 200, { "set-cookie": cookie(await sign(id, env.SESSION_SIGNING_KEY), SESSION_TTL) }); } -async function route(req, env) { +async function route(req, env, ctx) { const path = new URL(req.url).pathname; - if (req.method === "GET" && (path === "/" || path === "/login")) return page(LOGIN_HTML); - if (path.startsWith("/api/agent/")) { + const isAgentApi = path.startsWith("/api/agent/"); + if (env.ACCESS_REQUIRED === "true" && !isAgentApi && !ctx?.access) return json({ error: "Cloudflare Access authentication required" }, 403); + if (req.method === "GET" && (path === "/" || path === "/login")) { + if (ctx?.access) { + configured(env); + if (await currentUser(req, env, ctx)) return Response.redirect(new URL("/vault", req.url), 303); + } + return page(LOGIN_HTML); + } + if (isAgentApi) { 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); + } else if (["POST", "PATCH", "DELETE"].includes(req.method) && !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); + return await currentUser(req, env, ctx) ? page(VAULT_HTML) : Response.redirect(new URL("/", req.url), 303); } configured(env); if (req.method === "POST" && path === "/api/login") return login(req, env); if (req.method === "POST" && path === "/api/logout") { - const user = await currentUser(req, env), id = await verify(cookieValue(req), env.SESSION_SIGNING_KEY); + const user = await currentUser(req, env, ctx), id = await verify(cookieValue(req), env.SESSION_SIGNING_KEY); if (id) await env.DB.prepare("UPDATE sessions SET revoked=1 WHERE id_hash=?").bind(await hash(id)).run(); if (user) await audit(env, user.subject, "logout", null); return json({ ok: true }, 200, { "set-cookie": cookie("", 0) }); @@ -195,9 +211,63 @@ async function route(req, env) { } return json({ error: "Not found" }, 404); } - const user = await currentUser(req, env); + const user = await currentUser(req, env, ctx); 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/me") return json({ subject: user.subject, role: user.role, auth: user.auth || "session" }); + + if (req.method === "GET" && path === "/api/members") { + if (user.role !== "owner") return json({ error: "Forbidden" }, 403); + const rows = await env.DB.prepare( + "SELECT subject,role,active FROM identities WHERE subject<>'TOKEN' AND role<>'ai_agent' ORDER BY subject" + ).all(); + return json({ members: rows.results }); + } + if (req.method === "POST" && path === "/api/members") { + if (user.role !== "owner") return json({ error: "Forbidden" }, 403); + let body; try { body = await req.json(); } catch { return json({ error: "Invalid request" }, 400); } + const email = typeof body.email === "string" ? body.email.trim().toLowerCase() : ""; + const role = body.role; + if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email) || email.length > 254 || + !["security_admin", "developer", "auditor"].includes(role)) { + return json({ error: "Invalid member email or role" }, 400); + } + try { + await env.DB.prepare("INSERT INTO identities(id,subject,role,active) VALUES(?,?,?,1)") + .bind(crypto.randomUUID(), email, role).run(); + } catch { + return json({ error: "Member already exists or could not be created" }, 409); + } + await audit(env, user.subject, "member.create", email); + return json({ ok: true, email, role }, 201); + } + const memberPath = path.match(/^\/api\/members\/(.+)$/); + if (memberPath && req.method === "PATCH") { + if (user.role !== "owner") return json({ error: "Forbidden" }, 403); + const email = decodeURIComponent(memberPath[1]).trim().toLowerCase(); + let body; try { body = await req.json(); } catch { return json({ error: "Invalid request" }, 400); } + if (email === "TOKEN" || !["security_admin", "developer", "auditor"].includes(body.role)) { + return json({ error: "Invalid member role" }, 400); + } + const result = await env.DB.prepare("UPDATE identities SET role=? WHERE subject=? AND role<>'ai_agent'") + .bind(body.role, email).run(); + if (!result.meta?.changes) return json({ error: "Member not found" }, 404); + await audit(env, user.subject, "member.role.update", email); + return json({ ok: true }); + } + if (memberPath && req.method === "DELETE") { + if (user.role !== "owner") return json({ error: "Forbidden" }, 403); + const email = decodeURIComponent(memberPath[1]).trim().toLowerCase(); + if (email === "TOKEN") return json({ error: "Cannot revoke bootstrap owner" }, 400); + const check = await env.DB.prepare("SELECT active,role FROM identities WHERE subject=?").bind(email).first(); + if (!check || check.role === "ai_agent") return json({ error: "Member not found" }, 404); + await env.DB.batch([ + env.DB.prepare("UPDATE identities SET active=0 WHERE subject=?").bind(email), + env.DB.prepare("UPDATE sessions SET revoked=1 WHERE subject=?").bind(email) + ]); + await audit(env, user.subject, "member.revoke", email); + return json({ ok: true, active: false }); + } + if (req.method === "GET" && path === "/api/agents") { if (user.role !== "owner") return json({ error: "Forbidden" }, 403); @@ -313,8 +383,8 @@ async function route(req, env) { return json({ error: "Not found" }, 404); } export default { - async fetch(req, env) { - try { return await route(req, env); } + async fetch(req, env, ctx) { + try { return await route(req, env, ctx); } catch { return json({ error: "Vault temporarily unavailable" }, 503); } } }; diff --git a/security/token-vault/tests/agent-scope.test.mjs b/security/token-vault/tests/agent-scope.test.mjs index 1d3dd40..1b8cff8 100644 --- a/security/token-vault/tests/agent-scope.test.mjs +++ b/security/token-vault/tests/agent-scope.test.mjs @@ -128,3 +128,43 @@ test("AI agent grants isolate projects and reveal permission, and revocation wor const afterRevoke = await call("/api/agent/tokens?project_id=project-alpha", env, { headers: bearer }); assert.equal(afterRevoke.status, 401); }); + + +test("owner provisions personnel and Cloudflare Access enforces the assigned role", async () => { + const { env, password } = makeEnv(); + env.ACCESS_REQUIRED = "true"; + const accessContext = { access: { getIdentity: async () => ({ email: "owner-operator@example.com" }) } }; + const login = await worker.fetch(new Request("https://vault.example/api/login", { + method: "POST", + headers: browserHeaders(), + body: JSON.stringify({ password }) + }), env, accessContext); + assert.equal(login.status, 200); + const cookie = login.headers.get("set-cookie").split(";")[0]; + + const createMember = await worker.fetch(new Request("https://vault.example/api/members", { + method: "POST", + headers: browserHeaders(cookie), + body: JSON.stringify({ email: "developer@example.com", role: "developer" }) + }), env, accessContext); + assert.equal(createMember.status, 201); + + const staffContext = { access: { getIdentity: async () => ({ email: "DEVELOPER@example.com" }) } }; + const me = await worker.fetch(new Request("https://vault.example/api/me"), env, staffContext); + assert.equal(me.status, 200); + assert.deepEqual(await me.json(), { + subject: "developer@example.com", + role: "developer", + auth: "cloudflare-access" + }); + + const forbidden = await worker.fetch(new Request("https://vault.example/api/tokens", { + method: "POST", + headers: browserHeaders(), + body: JSON.stringify({ label: "forbidden", provider: "test", project_id: "project-a", value: "not-a-real-secret" }) + }), env, staffContext); + assert.equal(forbidden.status, 403); + + const noAccess = await worker.fetch(new Request("https://vault.example/"), env); + assert.equal(noAccess.status, 403); +});