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
43 changes: 42 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,47 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/).

## [Unreleased]

### Added

- **Living shared decisions — lifecycle (status / supersedes / reverses).**
Shared memory entries are now versioned: a change is a NEW append-only entry
that `--supersedes <id>` or `--reverses <id>` an old one (or carries an explicit
`--status`). `kit memory share` validates the referenced id exists. Surfacing
shows only ACTIVE decisions with their age (e.g. `2y ago`) so an aging decision
is flagged for review, never blind obedience; `kit memory area`/`search` badge
superseded/reversed entries (and show the chain) so "this was tried + reversed"
still surfaces. `active` stays implicit (absent field) so pre-lifecycle entries
are byte-identical. New `effectiveStatus`, `activeShared`, `formatAge`.
- **Shared (curated) memory folded into recall.** `kit memory search` now also
searches the committed `.kit/shared/memory.jsonl` tier and surfaces matching
team decisions/conventions _above_ raw transcript hits (`--json` now returns
`{ messages, shared }`). SessionStart recovery re-injects the project's most
recent durable shared decisions (kinds: decision/convention/security/status),
so a resumed session regains the settled context, not just the last few raw
turns. Both paths are project-local and fail-open (a missing/broken shared
store never breaks recall).
- **Berget AI + Grunden.ai as known providers.** Added `berget` and `grunden`
(EU-sovereign, OpenAI-compatible inference) to the service registry with their
canonical key names (`BERGET_API_KEY`/`BERGET_BASE_URL`,
`GRUNDEN_API_KEY`/`GRUNDEN_BASE_URL`) and where to get them, so `kit secrets`
treats them as known, vault-resolved keys (never plaintext). Catalog-only by
design: both are used via the `openai` SDK with a custom base URL, so there is
no unique package signal to auto-detect on (keying on the `openai` dep would
misattribute every OpenAI user). Agent-backend wiring + a Berget Code gate
adapter are deferred.

- **Identity-signed audit entries.** When a local `kit identity` exists, each
appended `.kit-audit.jsonl` line is signed: kit attaches `kid` (signer id) +
`sig` (Ed25519 signature over the line hash). Best-effort and append-safe — no
identity means entries are written as before, and a signing failure never
blocks the append. `kid`/`sig` sit outside the hashed remainder, so the hash
chain still verifies across mixed signed/unsigned/legacy logs. `kit audit
verify` now reports the signature tally (verified / unknown-key / unsigned)
against the locally-known keys (current + rotated) and FAILS hard on a forged
signature, while fail-opening on absent/unknown trust. This is the asymmetric
ATTRIBUTION layer (who produced an entry, verifiable with only the public key)
orthogonal to the symmetric HMAC INTEGRITY anchor. See `docs/AUDIT_ATTESTATION.md` §2.5.

## [2.2.0] - 2026-06-28

kit 2.2 — agent gate coverage + the first 3.0 primitive. Additive minor: new
Expand All @@ -30,7 +71,7 @@ experimental commands and adapters, no breaking changes to any `stable` surface.
- **`kit ci --init gitlab|bitbucket`** — generate a pipeline snippet that runs
`kit ci` (GitLab job → JUnit; Bitbucket step). Prints to stdout; `--write` writes
the file only when absent. Plus `docs/CI_AND_GIT_HOSTS.md` (the 4-layer gate model
+ per-host enforcement guidance).
- per-host enforcement guidance).
- **`kit gha-audit` extended to GitLab CI + Bitbucket Pipelines** — lints
`.gitlab-ci.yml` / `bitbucket-pipelines.yml` for unpinned `:latest`/untagged
images (CWE-1104), remote `include:` (OWASP-A08), and pipe-to-shell (CWE-494).
Expand Down
39 changes: 39 additions & 0 deletions docs/AUDIT_ATTESTATION.md
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,45 @@ tamper-proof against a same-UID local principal: an attacker running as the same
user can read `~/.kit/audit-anchor.key` AND the anchor record, recompute the tip,
and re-seal a forged log. Do not describe this as tamper-proof.

## 2.5. Identity signatures on audit entries (`kit identity` + `kit audit verify`)

The HMAC anchor is the INTEGRITY layer (was anything edited / rolled back). It is
symmetric, so it answers "was this tampered" but not "who wrote it" — a verifier
holding the anchor key could itself have produced any entry. The identity layer
is the orthogonal ATTRIBUTION layer.

When a local `kit identity` exists (an Ed25519 keypair under `~/.kit`, see
`kit identity`), each appended audit line is additionally signed: kit signs the
line's `hash` and attaches two fields the chain does NOT cover, `kid` (the
signer's identity id) and `sig` (base64 Ed25519 signature over `hash`).

- **Signing is best-effort and append-safe.** No identity → entries are written
exactly as before (no `kid`/`sig`). A signing failure never blocks the append.
- **`kid`/`sig` sit OUTSIDE the hashed remainder.** `verifyAuditChain` strips
them before recomputing the hash, so a log mixes signed and unsigned lines and
the chain still verifies end to end. Existing/legacy logs are unaffected.
- **`kit audit verify` reports the signature tally** after the chain + anchor
checks: `verified / signed` against the locally-known keys (the current
identity plus archived rotated keys), how many were signed by an unknown key
(`unverifiable`), and how many were keyless (`unsigned`).

Verdict rules (`verifyAuditSignatures`):

| Condition | Effect on verify |
| ------------------------------------------ | ------------------------------------------------------- |
| Signature valid for a known `kid` | counted `verified` |
| Signature INVALID (forged / hash tampered) | hard FAIL (`invalid > 0`) |
| `kid` not resolvable to a public key | `unverifiable` — fail-OPEN (absence of trust ≠ forgery) |
| No `kid`/`sig` (legacy/keyless) | `unsigned` — fail-OPEN |

Asymmetric payoff: a remote / CI / teammate verifies WHO produced an entry with
only the PUBLIC key — never a forge-capable secret, unlike the HMAC anchor. Same
same-UID boundary applies for _production_: a same-UID principal can read the
0600 private key and sign as this identity (closed later by non-exportable key
storage — TPM/keychain/HSM, the 3.0 regulated tier). What it buys today is
offline, third-party-verifiable attribution that the symmetric anchor cannot
express.

## 3. Signed check-attestation receipt (`kit check --attest`)

With `--attest` (or `KIT_ATTEST=1`), `kit check` / `kit ci` writes
Expand Down
132 changes: 132 additions & 0 deletions src/audit.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,9 @@
formatAuditLog,
appendAuditEventDirect,
verifyAuditChain,
verifyAuditSignatures,
} from "./audit.js";
import { loadOrCreateIdentity, localPublicKeys } from "./identity.js";
import type { GovernanceConfig } from "./config.js";

describe("logAuditEvent", () => {
Expand Down Expand Up @@ -47,7 +49,7 @@
try {
await readFile(testLogFile, "utf-8");
assert.fail("Log file should not have been created");
} catch (error: any) {

Check warning on line 52 in src/audit.test.ts

View workflow job for this annotation

GitHub Actions / build-and-test

Unexpected any. Specify a different type
assert.equal(error.code, "ENOENT");
}
});
Expand Down Expand Up @@ -416,6 +418,136 @@
});
});

describe("verifyAuditSignatures (identity attribution)", () => {
async function writeEvents(dir: string, n: number): Promise<void> {
for (let i = 0; i < n; i++) {
const ok = await appendAuditEventDirect(
{ operation: `op-${i}`, environment: "dev", success: true },
{ cwd: dir },
);
assert.equal(ok, true);
}
}

// Run a body with a fresh, isolated identity dir (KIT_IDENTITY_DIR), restoring
// the prior env afterward — so signing happens against a temp keypair.
async function withIdentity(fn: (idDir: string) => Promise<void>): Promise<void> {
const prev = process.env.KIT_IDENTITY_DIR;
const idDir = mkdtempSync(join(tmpdir(), "kit-audit-id-"));
process.env.KIT_IDENTITY_DIR = idDir;
try {
await fn(idDir);
} finally {
if (prev === undefined) delete process.env.KIT_IDENTITY_DIR;
else process.env.KIT_IDENTITY_DIR = prev;
rmSync(idDir, { recursive: true, force: true });
}
}

it("signs appended entries and the chain still verifies (sig/kid excluded from hash)", async () => {
await withIdentity(async () => {
const { identity } = loadOrCreateIdentity();
const dir = mkdtempSync(join(tmpdir(), "kit-audit-s-"));
try {
await writeEvents(dir, 3);
const content = readFileSync(join(dir, ".kit-audit.jsonl"), "utf8");
// Each line carries kid + sig...
for (const line of content.trim().split("\n")) {
const obj = JSON.parse(line);
assert.equal(obj.kid, identity.id);
assert.equal(typeof obj.sig, "string");
}
// ...and the hash chain is still intact despite the extra fields.
const chain = verifyAuditChain(content);
assert.equal(chain.ok, true);
assert.equal(chain.entries, 3);
} finally {
rmSync(dir, { recursive: true, force: true });
}
});
});

it("verifies signatures against the local public key", async () => {
await withIdentity(async () => {
loadOrCreateIdentity();
const dir = mkdtempSync(join(tmpdir(), "kit-audit-sv-"));
try {
await writeEvents(dir, 3);
const content = readFileSync(join(dir, ".kit-audit.jsonl"), "utf8");
const trust = localPublicKeys();
const s = verifyAuditSignatures(content, (kid) => trust.get(kid) ?? null);
assert.equal(s.total, 3);
assert.equal(s.signed, 3);
assert.equal(s.verified, 3);
assert.equal(s.invalid, 0);
assert.equal(s.unsigned, 0);
assert.equal(s.ok, true);
} finally {
rmSync(dir, { recursive: true, force: true });
}
});
});

it("flags a forged signature (invalid > 0 ⇒ not ok)", async () => {
await withIdentity(async () => {
loadOrCreateIdentity();
const dir = mkdtempSync(join(tmpdir(), "kit-audit-f-"));
try {
await writeEvents(dir, 2);
const lines = readFileSync(join(dir, ".kit-audit.jsonl"), "utf8").trim().split("\n");
const obj = JSON.parse(lines[0]);
// Swap the signature for a valid-base64 but wrong signature.
obj.sig = Buffer.from("not-the-real-signature-bytes-xx").toString("base64");
lines[0] = JSON.stringify(obj);
const content = lines.join("\n") + "\n";
const trust = localPublicKeys();
const s = verifyAuditSignatures(content, (kid) => trust.get(kid) ?? null);
assert.equal(s.invalid, 1);
assert.equal(s.verified, 1);
assert.equal(s.ok, false);
} finally {
rmSync(dir, { recursive: true, force: true });
}
});
});

it("reports tampered content under an unknown key as unverifiable (not a forge)", async () => {
await withIdentity(async () => {
loadOrCreateIdentity();
const dir = mkdtempSync(join(tmpdir(), "kit-audit-u-"));
try {
await writeEvents(dir, 2);
const content = readFileSync(join(dir, ".kit-audit.jsonl"), "utf8");
// Resolver that knows no keys → signed entries can't be checked.
const s = verifyAuditSignatures(content, () => null);
assert.equal(s.signed, 2);
assert.equal(s.unverifiable, 2);
assert.equal(s.verified, 0);
assert.equal(s.invalid, 0);
assert.equal(s.ok, true, "unknown key is fail-open, not a forge");
} finally {
rmSync(dir, { recursive: true, force: true });
}
});
});

it("treats a keyless (legacy) log as unsigned, ok", () => {
const legacy =
JSON.stringify({
timestamp: "t",
operation: "x",
environment: "dev",
success: true,
prev: "0".repeat(64),
hash: "abc",
}) + "\n";
const s = verifyAuditSignatures(legacy, () => "irrelevant");
assert.equal(s.signed, 0);
assert.equal(s.unsigned, 1);
assert.equal(s.ok, true);
});
});

describe("logAuditEvent return value (fail-closed signal)", () => {
function cfg(logFile: string): any {
return {
Expand Down
117 changes: 115 additions & 2 deletions src/audit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { appendFile, readFile, writeFile, rename } from "node:fs/promises";
import { resolve } from "node:path";
import { createHash } from "node:crypto";
import type { GovernanceConfig } from "./config.js";
import { tryLoadIdentity, signWithIdentity, verifySignature } from "./identity.js";

// ── Tamper-evident hash chain ───────────────────────────────────────────────
// Each appended line carries `prev` (the previous line's hash) and `hash`
Expand Down Expand Up @@ -34,7 +35,34 @@ async function appendChained(logPath: string, event: AuditEvent): Promise<void>
const prev = await lastChainHash(logPath);
const preHash = JSON.stringify({ ...event, prev });
const hash = hashLine(preHash);
await appendFile(logPath, JSON.stringify({ ...event, prev, hash }) + "\n", "utf-8");
// Best-effort identity signing: if a local kit identity exists, sign the
// line hash with it and attach non-hashed `kid` + `sig`. This adds
// ASYMMETRIC, ATTRIBUTABLE provenance on top of the (symmetric) hash chain —
// any verifier with the public key can confirm WHO produced the entry. Both
// fields sit OUTSIDE the hashed remainder (verifyAuditChain strips them), so
// the chain stays valid whether or not an entry is signed; legacy/keyless
// appends are unaffected. Failure to sign never blocks the append.
const signed = signLineHash(hash);
const line = signed
? { ...event, prev, hash, kid: signed.kid, sig: signed.sig }
: { ...event, prev, hash };
await appendFile(logPath, JSON.stringify(line) + "\n", "utf-8");
}

/**
* Sign a line hash with the local kit identity, if one is present. Returns the
* key id + base64 Ed25519 signature, or null when no identity exists / signing
* fails. Pure best-effort: callers never gate on the result.
*/
function signLineHash(hash: string): { kid: string; sig: string } | null {
const identity = tryLoadIdentity();
if (!identity) return null;
try {
const sig = signWithIdentity(hash).toString("base64");
return { kid: identity.id, sig };
} catch {
return null; // record present but key unreadable → unsigned, not a failure
}
}

export interface ChainVerifyResult {
Expand All @@ -60,7 +88,10 @@ export function verifyAuditChain(content: string): ChainVerifyResult {
} catch {
return { ok: false, entries: i, brokenAt: i, reason: "unparseable line" };
}
const { hash, ...rest } = obj;
// `sig`/`kid` are attached AFTER the hash is computed (see appendChained),
// so they must be excluded from the hashed remainder. Lines without them
// (legacy/keyless) leave `rest` unchanged → backward-compatible.
const { hash, sig: _sig, kid: _kid, ...rest } = obj;
if (typeof hash !== "string") {
return { ok: false, entries: i, brokenAt: i, reason: "missing hash (unchained entry)" };
}
Expand All @@ -85,6 +116,88 @@ export function verifyAuditChain(content: string): ChainVerifyResult {
return { ok: true, entries: lines.length };
}

export interface SignatureVerifyResult {
/** Total non-empty lines inspected. */
total: number;
/** Lines carrying both `kid` and `sig`. */
signed: number;
/** Signed lines whose signature verified against the resolved public key. */
verified: number;
/** Signed lines whose signature FAILED to verify (forged/tampered). */
invalid: number;
/** Signed lines whose `kid` could not be resolved to a public key. */
unverifiable: number;
/** Lines with no signature (legacy/keyless appends). */
unsigned: number;
/**
* True when no signed entry FAILED verification. Unsigned and unverifiable
* entries do not flip this to false — absence of a signature is not tamper
* evidence (the hash chain covers that); a *bad* signature is.
*/
ok: boolean;
}

/**
* Verify identity signatures across a `.kit-audit.jsonl` body. Each signed line
* carries `kid` (the signer's identity id) and `sig` (base64 Ed25519 signature
* over the line `hash`). `resolvePubkey` maps a `kid` to its SPKI-PEM public key
* (or null if unknown — e.g. a key not in the trust store / revoked).
*
* This is the ATTRIBUTION layer, orthogonal to verifyAuditChain (the integrity
* layer). The chain proves nothing was edited/reordered; the signatures prove
* WHO produced each entry. Pure — no I/O, fully testable. Fail-closed on a bad
* signature (`invalid` > 0 ⇒ `ok=false`), fail-open on missing/unknown keys.
*/
export function verifyAuditSignatures(
content: string,
resolvePubkey: (kid: string) => string | null | undefined,
): SignatureVerifyResult {
const lines = content.split("\n").filter((l) => l.trim().length > 0);
let signed = 0;
let verified = 0;
let invalid = 0;
let unverifiable = 0;
let unsigned = 0;
for (const line of lines) {
let obj: Record<string, unknown>;
try {
obj = JSON.parse(line) as Record<string, unknown>;
} catch {
// Unparseable lines are the chain verifier's concern; ignore here.
continue;
}
const { hash, kid, sig } = obj as { hash?: unknown; kid?: unknown; sig?: unknown };
if (typeof kid !== "string" || typeof sig !== "string") {
unsigned++;
continue;
}
signed++;
if (typeof hash !== "string") {
invalid++; // signed but no hash to have signed → malformed
continue;
}
const pubkey = resolvePubkey(kid);
if (!pubkey) {
unverifiable++;
continue;
}
if (verifySignature(hash, Buffer.from(sig, "base64"), pubkey)) {
verified++;
} else {
invalid++;
}
}
return {
total: lines.length,
signed,
verified,
invalid,
unverifiable,
unsigned,
ok: invalid === 0,
};
}

const PENDING_QUEUE_FILE = ".kit-audit.pending";
const MAX_PENDING_ENTRIES = 500;
const RETRY_BACKOFF_MS = [250, 1_000, 4_000];
Expand Down
Loading
Loading