diff --git a/src/doctor.test.ts b/src/doctor.test.ts index c028bb6a..460e5e6a 100644 --- a/src/doctor.test.ts +++ b/src/doctor.test.ts @@ -16,6 +16,8 @@ import { type PolicySignature, } from "./policy-doc.js"; import { addPolicySigner } from "./policy-trust.js"; +import { PROFILE_FILE } from "./profile/schema.js"; +import { signProfile } from "./profile/sign.js"; describe("runDoctor", () => { it("returns skip for Node.js check when no package.json exists", async () => { @@ -272,3 +274,58 @@ describe("runDoctor — control plane (org policy) row (Pillar 2 §4.6)", () => assert.match(row.detail, /RBAC 1 role/); }); }); + +describe("runDoctor — keyless credentials row (Pillar 2 tail)", () => { + let idDir: string; + let proj: string; + let savedId: string | undefined; + + beforeEach(() => { + idDir = mkdtempSync(join(tmpdir(), "kit-id-")); + proj = mkdtempSync(join(tmpdir(), "kit-kl-")); + savedId = process.env.KIT_IDENTITY_DIR; + process.env.KIT_IDENTITY_DIR = idDir; + loadOrCreateIdentity(); + }); + + afterEach(() => { + if (savedId === undefined) delete process.env.KIT_IDENTITY_DIR; + else process.env.KIT_IDENTITY_DIR = savedId; + rmSync(idDir, { recursive: true, force: true }); + rmSync(proj, { recursive: true, force: true }); + }); + + const klRow = async () => + (await runDoctor({}, proj)).checks.find((c) => c.name === "keyless credentials"); + + it("skips when no [scope].sign hosts are declared", async () => { + const row = await klRow(); + assert.ok(row); + assert.equal(row.status, "skip"); + }); + + it("fails when keyless hosts are declared but the scope is unverified (fail-closed)", async () => { + writeFileSync( + join(proj, PROFILE_FILE), + `version = 1\n[scope]\nsign = ["api.acme.com"]\n`, + "utf-8", + ); + const row = await klRow(); + assert.ok(row); + assert.equal(row.status, "fail"); + assert.match(row.detail, /unverified|not trusted/); + }); + + it("passes when keyless hosts are declared, the scope is verified, and an identity can sign", async () => { + writeFileSync( + join(proj, PROFILE_FILE), + `version = 1\n[scope]\nsign = ["api.acme.com"]\n`, + "utf-8", + ); + await signProfile(proj); + const row = await klRow(); + assert.ok(row); + assert.equal(row.status, "pass", row.detail); + assert.match(row.detail, /require signed requests/); + }); +}); diff --git a/src/doctor.ts b/src/doctor.ts index 3f348827..c4e1b385 100644 --- a/src/doctor.ts +++ b/src/doctor.ts @@ -10,6 +10,7 @@ import { profileBrokerPolicy } from "./exec-broker/profile-policy.js"; import { verifyProfileSignature } from "./profile/sign.js"; import { verifyPolicy, loadPolicy, getPolicyPath } from "./policy-doc.js"; import { extractRbac } from "./rbac/policy-schema.js"; +import { tryLoadIdentity, isRevoked } from "./identity.js"; const execFileAsync = promisify(execFile); @@ -335,6 +336,52 @@ async function checkBrokerRuntime(cwd: string): Promise { }; } +/** + * Keyless-credential posture (Pelare 2 tail — "sign, don't store"). Reports whether any hosts are + * declared keyless (`[scope].sign`) and whether kit can actually sign for them — never silent: + * skip no keyless hosts declared + * pass keyless hosts declared, scope VERIFIED, and a usable identity can sign + * fail keyless hosts declared but the scope is unsigned/unverified (list not trusted), OR + * verified but no usable identity to sign with — requests would be fail-closed denied + */ +async function checkKeyless(cwd: string): Promise { + const name = "keyless credentials"; + const category = "security"; + const { signHostsDeclared, signHosts, detail } = await profileBrokerPolicy(cwd); + if (signHostsDeclared.length === 0) { + return { + name, + status: "skip", + detail: + "no keyless hosts declared — add hosts to [scope].sign and re-sign to require signed requests instead of stored tokens", + category, + }; + } + if (signHosts.length === 0) { + return { + name, + status: "fail", + detail: `${signHostsDeclared.length} keyless host(s) declared but the scope is unverified — ${detail}; not trusted (fail-closed)`, + category, + }; + } + const identity = tryLoadIdentity(); + if (!identity || isRevoked(identity.id)) { + return { + name, + status: "fail", + detail: `${signHosts.length} keyless host(s) require signing but ${identity ? `identity ${identity.id} is revoked` : "no usable identity is available"} — requests fail-closed`, + category, + }; + } + return { + name, + status: "pass", + detail: `${signHosts.length} keyless host(s) require signed requests; identity ${identity.id} ready (no stored bearer)`, + category, + }; +} + /** * Control-plane posture (Pelare 2): is a DISTRIBUTED org policy present at this project, and is it * trustworthy? Honest — "distributed" must never silently mean "unverified": @@ -420,6 +467,7 @@ export async function runDoctor(config: kitConfig, cwd: string): Promise c.status === "pass").length; diff --git a/src/exec-broker/profile-policy.test.ts b/src/exec-broker/profile-policy.test.ts index 78fa04ad..8861fe0e 100644 --- a/src/exec-broker/profile-policy.test.ts +++ b/src/exec-broker/profile-policy.test.ts @@ -100,4 +100,25 @@ describe("profileBrokerPolicy", () => { assert.equal(signed.enforceRuntime, true); assert.deepEqual(signed.policy?.egress.allow, ["api.acme.com"]); }); + + it("signHosts is effective only when the scope verifies; declared list is always surfaced", async () => { + const body = `version = 1\n[scope]\negress = ["api.acme.com"]\nsign = ["api.acme.com", ".internal.io"]\n`; + writeFileSync(join(proj, PROFILE_FILE), body); + // Unsigned: declared list is surfaced, but the EFFECTIVE list is empty (fail-closed). + const unsigned = await profileBrokerPolicy(proj); + assert.deepEqual(unsigned.signHostsDeclared, ["api.acme.com", ".internal.io"]); + assert.deepEqual(unsigned.signHosts, []); + // Signed: the declared list becomes effective. + await signProfile(proj); + const signed = await profileBrokerPolicy(proj); + assert.deepEqual(signed.signHosts, ["api.acme.com", ".internal.io"]); + }); + + it("signHosts is empty when no [scope].sign is declared", async () => { + writeFileSync(join(proj, PROFILE_FILE), SCOPED); + await signProfile(proj); + const r = await profileBrokerPolicy(proj); + assert.deepEqual(r.signHostsDeclared, []); + assert.deepEqual(r.signHosts, []); + }); }); diff --git a/src/exec-broker/profile-policy.ts b/src/exec-broker/profile-policy.ts index 47b54aaf..d8ac7c0a 100644 --- a/src/exec-broker/profile-policy.ts +++ b/src/exec-broker/profile-policy.ts @@ -35,6 +35,18 @@ export interface ProfilePolicyResult { * scope is declared or the profile is unreadable. */ enforceRuntime: boolean; + /** + * Keyless "sign, don't store" hosts (Pillar 2 tail) declared in `[scope].sign`, read from the + * DECLARATION regardless of signature status — so `kit doctor` can surface "declared but + * unverified" as a fail-closed posture. Empty when no scope / none declared / unreadable. + */ + signHostsDeclared: string[]; + /** + * EFFECTIVE keyless hosts: the declared list, but ONLY when the scope's signature verified. Empty + * otherwise (fail-closed) — an unverified `[scope].sign` grants no keyless behavior, mirroring how + * an unverified scope yields a null broker policy. + */ + signHosts: string[]; detail: string; } @@ -42,6 +54,7 @@ interface ScopeShape { egress?: string[]; fs?: string[]; secrets?: string[]; + sign?: string[]; enforce_runtime?: boolean; } @@ -64,7 +77,14 @@ export async function profileBrokerPolicy(cwd = process.cwd()): Promise { + idDir = mkdtempSync(join(tmpdir(), "kit-id-")); + proj = mkdtempSync(join(tmpdir(), "kit-keyless-")); + savedIdEnv = process.env.KIT_IDENTITY_DIR; + process.env.KIT_IDENTITY_DIR = idDir; + loadOrCreateIdentity(); +}); + +afterEach(() => { + if (savedIdEnv === undefined) delete process.env.KIT_IDENTITY_DIR; + else process.env.KIT_IDENTITY_DIR = savedIdEnv; + rmSync(idDir, { recursive: true, force: true }); + rmSync(proj, { recursive: true, force: true }); +}); + +describe("keyless hostRequiresSigning", () => { + it("matches exact and suffix hosts, empty list matches nothing", () => { + assert.equal(hostRequiresSigning("https://api.acme.com/x", ["api.acme.com"]), true); + assert.equal(hostRequiresSigning("https://a.internal.io/x", [".internal.io"]), true); + assert.equal(hostRequiresSigning("https://api.acme.com/x", []), false); + assert.equal(hostRequiresSigning("https://other.com/x", ["api.acme.com"]), false); + }); +}); + +describe("keyless signOutbound", () => { + it("not-required when the host is not declared keyless", async () => { + writeFileSync(join(proj, PROFILE_FILE), `version = 1\n[scope]\negress = ["api.acme.com"]\n`); + await signProfile(proj); + const r = await signOutbound(REQ, { root: proj, dir: idDir }); + assert.equal(r.status, "not-required"); + }); + + it("denied (fail-closed) when the host is keyless but the scope is UNVERIFIED", async () => { + writeFileSync(join(proj, PROFILE_FILE), withSign); // written but NOT signed + const r = await signOutbound(REQ, { root: proj, dir: idDir }); + assert.equal(r.status, "denied"); + assert.match(r.detail, /unverified/); + }); + + it("signs a keyless host when the scope is verified, and verifyInbound accepts it", async () => { + writeFileSync(join(proj, PROFILE_FILE), withSign); + await signProfile(proj); + const r = await signOutbound(REQ, { root: proj, dir: idDir, now: new Date(1_000_000_000_000) }); + assert.equal(r.status, "signed", r.detail); + if (r.status !== "signed") return; + assert.match(r.keyid, /^kid_/); + const v = verifyInbound( + REQ, + { signatureInput: r.headers["Signature-Input"], signature: r.headers.Signature }, + { dir: idDir, now: new Date(1_000_000_060_000) }, + ); + assert.equal(v.valid, true, v.detail); + }); + + it("verifyInbound rejects a tampered request", async () => { + writeFileSync(join(proj, PROFILE_FILE), withSign); + await signProfile(proj); + const r = await signOutbound(REQ, { root: proj, dir: idDir, now: new Date(1_000_000_000_000) }); + assert.equal(r.status, "signed"); + if (r.status !== "signed") return; + const v = verifyInbound( + { ...REQ, url: "https://api.acme.com/v1/refund" }, + { signatureInput: r.headers["Signature-Input"], signature: r.headers.Signature }, + { dir: idDir, now: new Date(1_000_000_060_000) }, + ); + assert.equal(v.valid, false); + }); + + it("denied when the signing identity is revoked (fail-closed)", async () => { + writeFileSync(join(proj, PROFILE_FILE), withSign); + await signProfile(proj); + const id = loadOrCreateIdentity().identity; + recordRevocation(id.id, "compromised", idDir); + const r = await signOutbound(REQ, { root: proj, dir: idDir }); + assert.equal(r.status, "denied"); + assert.match(r.detail, /revoked/); + }); + + it("verifyInbound rejects a signature from a revoked signer", async () => { + writeFileSync(join(proj, PROFILE_FILE), withSign); + await signProfile(proj); + const r = await signOutbound(REQ, { root: proj, dir: idDir, now: new Date(1_000_000_000_000) }); + assert.equal(r.status, "signed"); + if (r.status !== "signed") return; + recordRevocation(r.keyid, "compromised", idDir); + const v = verifyInbound( + REQ, + { signatureInput: r.headers["Signature-Input"], signature: r.headers.Signature }, + { dir: idDir, now: new Date(1_000_000_060_000) }, + ); + assert.equal(v.valid, false); + }); +}); diff --git a/src/keyless/sign-request.ts b/src/keyless/sign-request.ts new file mode 100644 index 00000000..06d06f28 --- /dev/null +++ b/src/keyless/sign-request.ts @@ -0,0 +1,148 @@ +/** + * kit keyless credentials (Pillar 2 tail) — the identity bridge for "sign, don't store". + * + * `http-sig.ts` is the pure RFC 9421 core (no I/O, no identity). This module wires it to kit's + * primitives: it decides whether an outbound request's host requires signing (from the SIGNED + * profile `[scope].sign`, verified offline), and mints the `Signature-Input` + `Signature` headers + * from the agent's Ed25519 identity — so no long-lived bearer token is stored for that host. + * + * Fail-CLOSED, never fabricates auth: + * - host not marked keyless → `not-required` (caller uses its normal credential path); + * - host marked keyless but the scope is UNVERIFIED (declared-but-unsigned) → `denied` (the sign + * list is not trusted; we must NOT silently fall back to a stored bearer); + * - host marked keyless + scope verified, but no usable identity (none, or a hardware mandate + * refuses the file key), or the identity is revoked → `denied`. + * Only a host in the VERIFIED sign list with a usable, non-revoked identity yields `signed`. + * + * Deterministic given (request, profile, identity, clock). Offline. Zero LLM. + */ +import { + signWithIdentity, + tryLoadIdentity, + isRevoked, + localPublicKeys, + verifySignature, + isRevokedWith, +} from "../identity.js"; +import { checkEgress } from "../exec-broker/decisions.js"; +import { profileBrokerPolicy } from "../exec-broker/profile-policy.js"; +import { + signRequest, + verifyRequest, + DEFAULT_COMPONENTS, + type SignableRequest, + type SignatureHeaders, + type VerifyResult, +} from "./http-sig.js"; + +/** Default replay window for a minted signature (seconds). */ +const DEFAULT_TTL_SECONDS = 300; + +/** Does `target` (URL or bare host) match the keyless sign list? Same semantics as egress. */ +export function hostRequiresSigning(target: string, signHosts: string[]): boolean { + if (signHosts.length === 0) return false; + return checkEgress(target, { allow: signHosts }).ok; +} + +export type SignOutcome = + | { status: "signed"; headers: SignatureHeaders; keyid: string; detail: string } + | { status: "not-required"; detail: string } + | { status: "denied"; detail: string }; + +export interface SignOutboundOptions { + /** Project root to resolve the profile scope from. Default `process.cwd()`. */ + root?: string; + /** Identity directory override (mainly for tests). */ + dir?: string; + /** Clock for `created`/`expires`. Default now. */ + now?: Date; + /** Signature lifetime in seconds. Default 300. */ + ttlSeconds?: number; + /** Covered components. Default `@method`, `@authority`, `@path`. */ + components?: string[]; +} + +/** + * Decide-and-sign one outbound request. Reads the signed profile scope to learn which hosts are + * keyless, then mints RFC 9421 headers from the identity (never throws — a signing failure becomes a + * `denied` outcome). + */ +export async function signOutbound( + req: SignableRequest, + opts: SignOutboundOptions = {}, +): Promise { + const root = opts.root ?? process.cwd(); + const prof = await profileBrokerPolicy(root); + + // Host not keyless in the VERIFIED scope. Distinguish "declared but unverified" (fail-closed + // deny) from "never declared" (not our concern — caller uses its normal credential path). + if (!hostRequiresSigning(req.url, prof.signHosts)) { + if (hostRequiresSigning(req.url, prof.signHostsDeclared)) { + return { + status: "denied", + detail: `host requires signing but scope is unverified — ${prof.detail}`, + }; + } + return { status: "not-required", detail: "host is not marked keyless in the verified scope" }; + } + + const identity = tryLoadIdentity(opts.dir); + if (!identity) { + return { status: "denied", detail: "host requires signing but no identity is available" }; + } + if (isRevoked(identity.id, opts.dir)) { + return { status: "denied", detail: `identity ${identity.id} is revoked` }; + } + + const now = opts.now ?? new Date(); + const created = Math.floor(now.getTime() / 1000); + const ttl = opts.ttlSeconds ?? DEFAULT_TTL_SECONDS; + try { + const headers = signRequest( + req, + { + keyid: identity.id, + created, + expires: created + ttl, + components: opts.components ?? DEFAULT_COMPONENTS, + }, + (data) => signWithIdentity(data, opts.dir), + ); + return { + status: "signed", + headers, + keyid: identity.id, + detail: `signed by ${identity.id}, expires in ${ttl}s`, + }; + } catch (err) { + // e.g. a hardware mandate refuses the same-UID file key, or a missing covered header. + return { + status: "denied", + detail: `cannot sign: ${err instanceof Error ? err.message : String(err)}`, + }; + } +} + +/** + * Verify an INBOUND signed request against locally-trusted identities (kit-to-kit). Resolves the + * signer's public key from the local identity set and rejects a revoked signer. The general case + * (a third-party server verifying a kit agent) is the server's job with its own trust set; this is + * the symmetric helper for kit peers and for tests. + */ +export function verifyInbound( + req: SignableRequest, + headers: { signatureInput: string; signature: string }, + opts: { dir?: string; now?: Date; required?: string[] } = {}, +): VerifyResult { + const trusted = localPublicKeys(opts.dir); + const authorities = new Set(trusted.keys()); + const resolvePub = (kid: string): string | undefined => { + if (isRevokedWith(kid, trusted, authorities, opts.dir)) return undefined; + return trusted.get(kid); + }; + const now = opts.now ? Math.floor(opts.now.getTime() / 1000) : undefined; + return verifyRequest(req, headers, resolvePub, verifySignature, { + now, + required: opts.required, + }); +} diff --git a/src/profile/schema.ts b/src/profile/schema.ts index 752d8e2b..1c1df2bf 100644 --- a/src/profile/schema.ts +++ b/src/profile/schema.ts @@ -71,6 +71,14 @@ export interface ProfileScope { fs?: string[]; /** Secret-scope: env-var names the operation is allowed to see. */ secrets?: string[]; + /** + * Keyless-credential hosts (Pillar 2 tail — "sign, don't store"). Hosts listed here require a + * signed request (RFC 9421 HTTP Message Signatures minted from the agent's identity) rather than + * a stored bearer token. Same host-matching as `egress` (exact, or a leading-dot suffix match). + * Being inside the signed `[scope]`, this list is covered by the signature — a host cannot be + * marked keyless without re-signing, and it only takes effect once the scope verifies. + */ + sign?: string[]; /** * Explicit opt-in to exec-broker enforcement AT THE MCP RUNTIME (not just the PreToolUse gates / * governance floor). When true and the scope is verified, governed MCP ops that declare their @@ -146,6 +154,7 @@ const kitProfileSchema = z egress: z.array(z.string()).optional(), fs: z.array(z.string()).optional(), secrets: z.array(z.string()).optional(), + sign: z.array(z.string()).optional(), enforce_runtime: z.boolean().optional(), }) .strict()