diff --git a/contracts/public-surface.json b/contracts/public-surface.json index d026c9e8..964d5be2 100644 --- a/contracts/public-surface.json +++ b/contracts/public-surface.json @@ -185,6 +185,8 @@ "profile check", "profile freeze", "profile show", + "profile sign", + "profile verify", "review", "run", "sbom", diff --git a/src/cli.ts b/src/cli.ts index d86737b6..b73d6a2b 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -678,7 +678,7 @@ const COMMAND_REGISTRY: Record = { profile: { handler: cmdProfile, stability: "experimental", - help: "Versioned, traveling project profile — declare {skills, mcp, workflows, plugins, vault, gates, scope} and audit declared-vs-discovered drift (show|freeze|check; --json, --gate)", + help: "Versioned, traveling project profile — declare {skills, mcp, workflows, plugins, vault, gates, scope}, audit declared-vs-discovered drift, and sign the scope/RoE (show|freeze|check|sign|verify; --json, --gate, --key)", }, pkg: { handler: cmdPkg, @@ -718,6 +718,10 @@ const SUBCOMMAND_HELP: Record = { "Snapshot the discovered toolchain into .kit-profile.toml (preserves operator-authored workflows/plugins/scope/gates)", "profile check": "Report declared-vs-discovered drift (--gate fails CI on any drift; honest skip when no profile declared)", + "profile sign": + "Sign the profile (scope/RoE) into .kit-profile.sig via your identity/keystore — offline-verifiable", + "profile verify": + "Verify .kit-profile.sig offline (--key pin → local identity → org .kit-policy.signers)", "memory index": "Index ~/.claude transcripts into the SQLite memory store", "memory search": "Full-text search memory (current project; --global for all)", "memory stats": "Show what the local memory store contains", diff --git a/src/commands/profile.ts b/src/commands/profile.ts index cd668531..4d648c93 100644 --- a/src/commands/profile.ts +++ b/src/commands/profile.ts @@ -32,6 +32,8 @@ import { type ProfileDrift, type DriftEntry, } from "../profile/reconcile.js"; +import { signProfile, verifyProfileSignature } from "../profile/sign.js"; +import { flagValue } from "../utils/flags.js"; function noProfileNotice(jsonMode: boolean): boolean { if (jsonMode) { @@ -199,12 +201,74 @@ async function profileFreeze(jsonMode: boolean): Promise { return true; } +async function profileSign(jsonMode: boolean): Promise { + const res = await signProfile(); + if (!res.ok) { + if (jsonMode) { + console.log(JSON.stringify({ signed: false, error: res.error }, null, 2)); + } else { + console.error(`${c.red}✗ ${res.error}${c.reset}`); + } + return false; + } + if (jsonMode) { + console.log( + JSON.stringify({ signed: true, kid: res.kid, fingerprint: res.fingerprint }, null, 2), + ); + return true; + } + const rootedNote = res.rooted ? ` ${c.dim}(hardware-rooted)${c.reset}` : ""; + console.log( + `${c.green}✓${c.reset} signed ${c.bold}${res.fingerprint}${c.reset} as ${c.bold}${res.kid}${c.reset}${rootedNote} ${c.dim}→ ${PROFILE_FILE}.sig${c.reset}`, + ); + console.log( + `${c.dim}commit ${PROFILE_FILE} + ${PROFILE_FILE}.sig; verifiers check it offline against .kit-policy.signers${c.reset}`, + ); + return true; +} + +async function profileVerify(jsonMode: boolean): Promise { + const r = await verifyProfileSignature(process.cwd(), { key: flagValue(process.argv, "--key") }); + if (jsonMode) { + console.log(JSON.stringify(r, null, 2)); + // trust-absence (unverifiable) is not a forge — mirror kit policy verify's fail-open there. + return r.status === "valid" || r.status === "unverifiable"; + } + switch (r.status) { + case "valid": + console.log( + `${c.green}✓ profile signature valid${c.reset} ${c.dim}${r.fingerprint} ${r.detail}${c.reset}`, + ); + return true; + case "unverifiable": + console.warn(`${c.yellow}! ${r.detail}${c.reset}`); + return true; + case "unsigned": + console.error(`${c.red}${r.detail}${c.reset}`); + return false; + case "invalid": + console.error( + `${c.red}✗ profile signature INVALID${c.reset} ${c.dim}(${r.detail})${c.reset}`, + ); + return false; + case "revoked": + console.error( + `${c.red}✗ profile signed by a REVOKED key${c.reset} ${c.dim}(${r.detail})${c.reset}`, + ); + return false; + } +} + export async function cmdProfile(): Promise { const sub = process.argv[3] ?? "show"; const jsonMode = hasFlag(process.argv, "--json"); if (sub === "show") return await profileShow(jsonMode); if (sub === "freeze") return await profileFreeze(jsonMode); if (sub === "check") return await profileCheck(jsonMode, hasFlag(process.argv, "--gate")); - console.error(`${c.red}usage: kit profile [--json] [--gate]${c.reset}`); + if (sub === "sign") return await profileSign(jsonMode); + if (sub === "verify") return await profileVerify(jsonMode); + console.error( + `${c.red}usage: kit profile [--json] [--gate] [--key ]${c.reset}`, + ); return false; } diff --git a/src/profile/sign.test.ts b/src/profile/sign.test.ts new file mode 100644 index 00000000..7cfe347f --- /dev/null +++ b/src/profile/sign.test.ts @@ -0,0 +1,108 @@ +import { describe, it, beforeEach, afterEach } from "node:test"; +import assert from "node:assert/strict"; +import { mkdtempSync, writeFileSync, existsSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { loadOrCreateIdentity } from "../identity.js"; +import { PROFILE_FILE } from "./schema.js"; +import { signProfile, verifyProfileSignature, verifiedScope, getProfileSigPath } from "./sign.js"; + +let idDir: string; +let proj: string; +let savedIdEnv: string | undefined; + +const SCOPED = `version = 1 +name = "acme" +[scope] +egress = ["api.acme.com"] +fs = ["."] +secrets = ["DATABASE_URL"] +`; + +beforeEach(() => { + idDir = mkdtempSync(join(tmpdir(), "kit-id-")); + proj = mkdtempSync(join(tmpdir(), "kit-profsign-")); + savedIdEnv = process.env.KIT_IDENTITY_DIR; + process.env.KIT_IDENTITY_DIR = idDir; + loadOrCreateIdentity(); // mint a file identity under idDir +}); + +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("signProfile / verifyProfileSignature", () => { + it("signs a profile and verifies it via the local identity", async () => { + writeFileSync(join(proj, PROFILE_FILE), SCOPED); + const res = await signProfile(proj); + assert.equal(res.ok, true); + assert.ok(existsSync(getProfileSigPath(proj))); + assert.match(res.fingerprint ?? "", /^sha256:/); + + const v = await verifyProfileSignature(proj); + assert.equal(v.status, "valid"); + assert.equal(v.via, "local"); + }); + + it("refuses to sign when no profile is declared", async () => { + const res = await signProfile(proj); + assert.equal(res.ok, false); + assert.match(res.error ?? "", /no profile/); + }); + + it("reports unsigned when there is no .kit-profile.sig", async () => { + writeFileSync(join(proj, PROFILE_FILE), SCOPED); + const v = await verifyProfileSignature(proj); + assert.equal(v.status, "unsigned"); + }); + + it("detects tampering — a changed profile invalidates the signature", async () => { + writeFileSync(join(proj, PROFILE_FILE), SCOPED); + await signProfile(proj); + // Change a signed field (name is part of the canonical bytes). + writeFileSync(join(proj, PROFILE_FILE), SCOPED.replace("acme", "evil-corp")); + const v = await verifyProfileSignature(proj); + assert.equal(v.status, "invalid"); + }); + + it("re-signing after an edit restores validity (generated is excluded from the signed bytes)", async () => { + writeFileSync(join(proj, PROFILE_FILE), SCOPED); + await signProfile(proj); + writeFileSync(join(proj, PROFILE_FILE), SCOPED.replace("acme", "acme-web")); + assert.equal((await verifyProfileSignature(proj)).status, "invalid"); + await signProfile(proj); + assert.equal((await verifyProfileSignature(proj)).status, "valid"); + }); +}); + +describe("verifiedScope (Pillar 3 hook — fail-closed)", () => { + it("returns the scope only when the signature is valid", async () => { + writeFileSync(join(proj, PROFILE_FILE), SCOPED); + await signProfile(proj); + const scope = await verifiedScope(proj); + assert.deepEqual(scope?.egress, ["api.acme.com"]); + assert.deepEqual(scope?.fs, ["."]); + }); + + it("returns null when the profile is unsigned (unsigned scope grants nothing)", async () => { + writeFileSync(join(proj, PROFILE_FILE), SCOPED); + assert.equal(await verifiedScope(proj), null); + }); + + it("returns null when the profile was tampered after signing", async () => { + writeFileSync(join(proj, PROFILE_FILE), SCOPED); + await signProfile(proj); + writeFileSync(join(proj, PROFILE_FILE), SCOPED.replace("api.acme.com", "evil.example.com")); + assert.equal(await verifiedScope(proj), null); + }); + + it("returns null when a signed profile declares no scope", async () => { + writeFileSync(join(proj, PROFILE_FILE), `version = 1\nname = "no-scope"\n`); + await signProfile(proj); + assert.equal((await verifyProfileSignature(proj)).status, "valid"); + assert.equal(await verifiedScope(proj), null); + }); +}); diff --git a/src/profile/sign.ts b/src/profile/sign.ts new file mode 100644 index 00000000..fd52f395 --- /dev/null +++ b/src/profile/sign.ts @@ -0,0 +1,225 @@ +/** + * kit project profile — signed scope/RoE (Pillar 4 step 5). + * + * Design: `kit-research/docs/research/pillar4-traveling-profile-5.0.md` §4.4. + * + * The profile's `[scope]` section (egress allowlist, fs-scope, secret-scope) is only meaningful + * as a security boundary if it is CRYPTOGRAPHICALLY ATTRIBUTABLE and offline-verifiable — a + * hand-editable file can't gate an autonomous agent. So the profile reuses, verbatim, the + * signing floor kit already ships for `.kit-policy.toml`: + * + * - sign over CANONICAL bytes (`canonicalProfileBytes`, `generated` excluded) through the + * resolved keystore (so a hardware-rooted backend can sign, and a hardware mandate is + * enforceable) — the same path as `kit policy sign`; + * - verify with the SAME trust order as `verifyPolicy`: an explicit `--key` pin → this + * machine's identity → the committed org trust anchor (`.kit-policy.signers`), with the + * same revocation semantics. + * + * `verifiedScope()` is the fail-closed hook for Pillar 3's exec-broker: it returns the scope + * ONLY when the signature verifies. An unsigned or forged scope grants nothing. + * + * Zero new crypto — this is a second consumer of the verified floor. + */ +import { existsSync, readFileSync, writeFileSync } from "node:fs"; +import { resolve } from "node:path"; +import { identityId, localPublicKeys, verifySignature, isRevokedWith } from "../identity.js"; +import { policySignersMap, hasPolicyAnchor } from "../policy-trust.js"; +import { + resolveKeyStore, + assertHardwareIdentity, + isHardwareRooted, + hardwareRequired, +} from "../keystore/index.js"; +import type { PolicySignature } from "../policy-doc.js"; +import { + loadProfile, + canonicalProfileBytes, + profileFingerprint, + type KitProfile, + type ProfileScope, +} from "./schema.js"; + +export const PROFILE_SIG_FILE = ".kit-profile.sig"; + +export function getProfileSigPath(cwd: string): string { + return resolve(cwd, PROFILE_SIG_FILE); +} + +export interface ProfileSignResult { + ok: boolean; + error?: string; + kid?: string; + fingerprint?: string; + rooted?: boolean; +} + +/** + * Sign the profile at `cwd`, writing `.kit-profile.sig`. Signs through the resolved keystore + * (file / command / hardware) exactly like `kit policy sign`, and fails closed when a + * hardware-rooted identity is mandated but the active backend isn't one. + */ +export async function signProfile(cwd = process.cwd()): Promise { + const profile = await loadProfile(cwd); + if (!profile) return { ok: false, error: "no profile declared" }; + + const res = resolveKeyStore(); + const pub = res.store.publicKeyPem(); + if (!pub) { + return { + ok: false, + error: res.availability.ok + ? "no identity to sign with — run kit identity init" + : (res.availability.reason ?? "keystore unavailable"), + }; + } + try { + assertHardwareIdentity(res, hardwareRequired(cwd)); + } catch (e) { + return { ok: false, error: (e as Error).message }; + } + + const kid = identityId(pub); + const bytes = canonicalProfileBytes(profile); + let sigB64: string; + try { + sigB64 = res.store.sign(bytes).toString("base64"); + } catch (e) { + return { ok: false, error: `signing failed: ${(e as Error).message}` }; + } + const record: PolicySignature = { + kid, + sig: sigB64, + ts: new Date().toISOString(), + fingerprint: profileFingerprint(profile), + }; + writeFileSync(getProfileSigPath(cwd), JSON.stringify(record, null, 2) + "\n", "utf-8"); + return { ok: true, kid, fingerprint: record.fingerprint, rooted: isHardwareRooted(res) }; +} + +export type ProfileVerifyStatus = "valid" | "invalid" | "unsigned" | "unverifiable" | "revoked"; + +export interface ProfileVerifyResult { + status: ProfileVerifyStatus; + detail: string; + kid?: string; + fingerprint?: string; + /** Where the verifying key came from. */ + via?: "key" | "local" | "org"; + /** True when a committed org trust anchor (.kit-policy.signers) is present. */ + anchored?: boolean; +} + +/** + * Verify `.kit-profile.sig` against the profile at `cwd`. Same trust order and revocation + * semantics as `verifyPolicy` — fail-closed once an org anchor is present. + */ +export async function verifyProfileSignature( + cwd = process.cwd(), + opts: { key?: string } = {}, +): Promise { + const profile = await loadProfile(cwd); + if (!profile) return { status: "unsigned", detail: "no profile declared" }; + + let record: PolicySignature; + try { + record = JSON.parse(readFileSync(getProfileSigPath(cwd), "utf-8")) as PolicySignature; + } catch { + return { status: "unsigned", detail: `no ${PROFILE_SIG_FILE} (run kit profile sign)` }; + } + + let fingerprint: string; + try { + fingerprint = profileFingerprint(profile); + } catch (e) { + return { + status: "invalid", + detail: e instanceof Error ? e.message : "uncanonicalizable profile", + }; + } + + const anchored = hasPolicyAnchor(cwd); + let pubkey: string | null = null; + let via: ProfileVerifyResult["via"] = undefined; + if (opts.key) { + pubkey = existsSync(opts.key) ? readFileSync(opts.key, "utf-8") : opts.key; + via = "key"; + } else if (localPublicKeys().get(record.kid)) { + pubkey = localPublicKeys().get(record.kid)!; + via = "local"; + } else if (policySignersMap(cwd).get(record.kid)) { + pubkey = policySignersMap(cwd).get(record.kid)!; + via = "org"; + } + if (!pubkey) { + return { + status: "unverifiable", + detail: anchored + ? `signer ${record.kid} is not in the org trust anchor (.kit-policy.signers)` + : `signer ${record.kid} unknown (pin with --key, or add it to .kit-policy.signers)`, + kid: record.kid, + fingerprint, + anchored, + }; + } + + const fpMatches = record.fingerprint === fingerprint; + const sigOk = + fpMatches && + verifySignature(canonicalProfileBytes(profile), Buffer.from(record.sig, "base64"), pubkey); + if (!sigOk) { + return { + status: "invalid", + detail: fpMatches ? "signature mismatch" : "profile changed since signing — re-sign", + kid: record.kid, + fingerprint, + via, + anchored, + }; + } + + // Revocation with the ORG trust context (self-revoke or an org-anchor signer may revoke; + // the local machine root is deliberately not an authority) — identical to verifyPolicy. + const orgSigners = policySignersMap(cwd); + const trustedKeys = new Map([...localPublicKeys(), ...orgSigners]); + const authorities = new Set(orgSigners.keys()); + if (isRevokedWith(record.kid, trustedKeys, authorities)) { + return { + status: "revoked", + detail: `signer ${record.kid} is revoked`, + kid: record.kid, + fingerprint, + via, + anchored, + }; + } + + return { + status: "valid", + detail: `signed by ${record.kid}${via === "org" ? " (org trust anchor)" : ""}`, + kid: record.kid, + fingerprint, + via, + anchored, + }; +} + +/** + * The fail-closed hook for Pillar 3's exec-broker: the profile's `[scope]` — but ONLY when the + * profile carries a VALID signature. An unsigned, changed, forged, or revoked-signer scope + * returns `null` (grants nothing). A profile with no `[scope]` also returns `null`. + */ +export async function verifiedScope( + cwd = process.cwd(), + opts: { key?: string } = {}, +): Promise { + const profile = await loadProfile(cwd); + if (!profile?.scope) return null; + const v = await verifyProfileSignature(cwd, opts); + return v.status === "valid" ? profile.scope : null; +} + +/** Convenience: the declared (UNVERIFIED) scope, for display. */ +export async function declaredScope(cwd = process.cwd()): Promise { + const profile: KitProfile | null = await loadProfile(cwd); + return profile?.scope ?? null; +}