Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
57 changes: 57 additions & 0 deletions src/doctor.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 () => {
Expand Down Expand Up @@ -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/);
});
});
48 changes: 48 additions & 0 deletions src/doctor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);

Expand Down Expand Up @@ -335,6 +336,52 @@ async function checkBrokerRuntime(cwd: string): Promise<DoctorCheck> {
};
}

/**
* 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<DoctorCheck> {
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":
Expand Down Expand Up @@ -420,6 +467,7 @@ export async function runDoctor(config: kitConfig, cwd: string): Promise<DoctorR

allChecks.push(await checkBrokerScope(cwd));
allChecks.push(await checkBrokerRuntime(cwd));
allChecks.push(await checkKeyless(cwd));
allChecks.push(checkControlPlane(cwd));

const passed = allChecks.filter((c) => c.status === "pass").length;
Expand Down
21 changes: 21 additions & 0 deletions src/exec-broker/profile-policy.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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, []);
});
});
31 changes: 30 additions & 1 deletion src/exec-broker/profile-policy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,13 +35,26 @@ 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;
}

interface ScopeShape {
egress?: string[];
fs?: string[];
secrets?: string[];
sign?: string[];
enforce_runtime?: boolean;
}

Expand All @@ -64,7 +77,14 @@ export async function profileBrokerPolicy(cwd = process.cwd()): Promise<ProfileP
try {
const profile = await loadProfile(cwd);
if (!profile) {
return { regime: "none", policy: null, enforceRuntime: false, detail: "no profile declared" };
return {
regime: "none",
policy: null,
enforceRuntime: false,
signHostsDeclared: [],
signHosts: [],
detail: "no profile declared",
};
}
scope = profile.scope;
} catch (err) {
Expand All @@ -75,6 +95,8 @@ export async function profileBrokerPolicy(cwd = process.cwd()): Promise<ProfileP
regime: "active",
policy: null,
enforceRuntime: false,
signHostsDeclared: [],
signHosts: [],
detail: `profile unreadable — ${err instanceof Error ? err.message : String(err)} (default-deny)`,
};
}
Expand All @@ -83,24 +105,31 @@ export async function profileBrokerPolicy(cwd = process.cwd()): Promise<ProfileP
regime: "none",
policy: null,
enforceRuntime: false,
signHostsDeclared: [],
signHosts: [],
detail: "profile declares no [scope]/RoE",
};
}

const enforceRuntime = scope.enforce_runtime === true;
const signHostsDeclared = scope.sign ? [...scope.sign] : [];
const v = await verifyProfileSignature(cwd);
if (v.status === "valid") {
return {
regime: "active",
policy: scopeToPolicy(scope, cwd),
enforceRuntime,
signHostsDeclared,
signHosts: signHostsDeclared,
detail: `scope verified (${v.detail})`,
};
}
return {
regime: "active",
policy: null,
enforceRuntime,
signHostsDeclared,
signHosts: [],
detail: `scope declared but ${v.status} — ${v.detail}; grants nothing (fail-closed)`,
};
}
116 changes: 116 additions & 0 deletions src/keyless/sign-request.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
import { describe, it, beforeEach, afterEach } from "node:test";
import assert from "node:assert/strict";
import { mkdtempSync, writeFileSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { loadOrCreateIdentity, recordRevocation } from "../identity.js";
import { PROFILE_FILE } from "../profile/schema.js";
import { signProfile } from "../profile/sign.js";
import { signOutbound, verifyInbound, hostRequiresSigning } from "./sign-request.js";
import type { SignableRequest } from "./http-sig.js";

let idDir: string;
let proj: string;
let savedIdEnv: string | undefined;

const REQ: SignableRequest = {
method: "POST",
url: "https://api.acme.com/v1/charge",
headers: { "content-type": "application/json" },
};

const withSign = `version = 1\n[scope]\negress = ["api.acme.com"]\nsign = ["api.acme.com"]\n`;

beforeEach(() => {
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);
});
});
Loading
Loading