Merge mdangelo/codex/dependency-progress-sdk into mdangelo/codex/dependency-assessment-results

This commit is contained in:
Michael D'Angelo
2026-11-19 19:51:38 -08:00
18 changed files with 3252 additions and 137 deletions
+3 -2
View File
@@ -195,8 +195,9 @@ export function gradeStack(report, fixture, { reviewed }) {
for (const receipt of claim.receipts) {
assert.equal(receipt.server, "stack-packet");
assert.equal(receipt.originalPayloadSha256, files.stacks.sha256);
assert.deepEqual(receipt.origin, {
tool: "read-stacks",
const { tool, ...origin } = receipt.origin;
assert.ok(["next", "read-stacks"].includes(tool), "capture operation");
assert.deepEqual(origin, {
arguments: {
inputDigest: report.inputDigest,
workItemId: item.id,
+4 -1
View File
@@ -142,7 +142,10 @@ async function initialize(fixture) {
async function contracts(fixture) {
const { manifest, tool } = await initialize(fixture);
const next = await tool("next");
const item = await tool("read-stacks", { workItemId: next.workItem.id });
// The harness can also compare CLI builds that returned only a frame count.
const item = Array.isArray(next.workItem.observation.frames)
? { ...next.workItem, receiptId: next.receiptId }
: await tool("read-stacks", { workItemId: next.workItem.id });
const binding = item.observation.bindings[0];
const result = await tool("record-claims", {
claims: [
+41 -1
View File
@@ -77,7 +77,47 @@ jq -e --slurpfile r report.json '
Pass `--sinks sinks-replay.json` and choose a new report filename. The CLI validates the supplied records and quotes, skips the public lookup and trigger extraction, and reruns the caller investigation and independent review. Treat a supplied snapshot as evidence from its producer. The hashes verify its contents against the saved hashes. Supplying only `advisoryDetails` skips the lookup and runs trigger extraction on those records.
An external caller can freeze the same files with `prepareStackPacket` from `@openai/codex-security/stack-packet`. Set the opt-in for each invocation. `cs exploitability run init --inputs <packet-directory> --repo <checkout> --state <database>` creates or reopens an attempt. `run tools --state <database>` lists operation schemas. Use `next` and `read-stacks` to select evidence, `record-evidence` and `record-claims` to save it, and `query-claims` to retrieve its exact references. Use `record-assessments`, `summarize-coverage` and `finalize` to produce the scoped report. Operations with a JSON input accept `--json-stdin`. Each `run` operation prints JSON by default. Use `--format` to select another representation. The investigation state is local to the supplied SQLite file. These lower-level operations run offline. A direct `run finalize` returns an immutable report with `review: null`.
An external caller can freeze the same files with `prepareStackPacket` from `@openai/codex-security/stack-packet`. Set the opt-in for each invocation. `cs exploitability run init --inputs <packet-directory> --repo <checkout> --state <database>` creates or reopens an attempt from a prepared packet. For an interactive investigation, omit `--inputs` and initialize the checkout and state before collecting runtime evidence; optionally pass advisory or endpoint information as JSON with `--json-stdin`. `run tools --state <database>` lists operation schemas.
Use `next` to select the outstanding work item and read its complete captured frames, original frame indices, bindings and capture receipt. `record-evidence` saves pinned source ranges or an original runtime result or resource; `record-observations` registers additional runtime queries and their work items as evidence becomes available. Use `record-claims` to save supported facts and `query-claims` to retrieve their exact references. Use `record-assessments`, `summarize-coverage` and `finalize` to produce the scoped report. Operations with a JSON input accept `--json-stdin`. Each `run` operation prints JSON by default. Use `--format` to select another representation. The investigation state is local to the supplied SQLite file. These lower-level operations run offline. A direct `run finalize` returns an immutable report with `review: null`.
For example, start a run before its advisory or runtime information is complete:
```sh
export CODEX_SECURITY_ENABLE_DEPENDENCY_EXPLOITABILITY=1
cs exploitability run init --repo "$TARGET" --state "$STATE"
cs exploitability run init --repo "$TARGET" --state "$STATE" --json-stdin < advisory.json
cs exploitability run record-evidence --state "$STATE" --json-stdin < runtime.json
cs exploitability run record-observations --state "$STATE" --json-stdin < observations.json
cs exploitability run next --state "$STATE"
```
`advisory.json` supplies the CVE, advisory and source/sink endpoints as they become known. A runtime evidence import names the operation and contains the original JSON result, or a path and SHA-256 for its original JSON bytes:
```json
{
"kind": "runtime",
"server": "example-runtime",
"tool": "profile.lookup",
"arguments": { "service": "example" },
"scope": { "service": "example" },
"resource": { "path": "/path/to/result.json", "sha256": "<original SHA-256>" }
}
```
An original stack result can be a query in the shape from `schemas/dependency-stack-inputs-v1.schema.json`, or an object containing a `queries` array. A `codex-security-graph-evidence/v1` result can also be normalized when its metadata supplies the query identity, scope, window and sink selectors; root-first frames are reversed and their original index references are remapped. Use the returned `receiptId` to register the query results; the host derives the queries and work items from the recorded original:
```json
{ "receiptId": "<returned receipt ID>" }
```
If `queries` is also supplied to `record-observations`, it must exactly match the queries represented by the original receipt, including scope, status, frames and indices. Observed stacks and successful zero-match results require a receipt; a `no_coverage` query may be registered without one. A successful zero-match result also needs complete query coverage. Runtime imports preserve caller-supplied operation provenance and the original payload; they do not independently attest that a provider executed the named operation. Cite the original receipt when an assessment depends on its result.
For graph evidence, a zero-match result requires metadata status `empty_matches`, `coverage.result_complete: true`, and `limits.truncated: false`. Missing telemetry or incomplete coverage becomes `no_coverage` instead.
A graph resource can establish which frames appeared in a sample. Ruling out a vulnerability because a fixed package version ran requires the capture producer to tie that version to the matched frame. An image inventory alone establishes which packages the image contains. When the producer supplies a canonical stack query with frame-to-package bindings, the finalized claim includes the original import for review.
Live or supplemented reports can include `effectiveInputDigest`, a hash of the versioned canonical effective source, sink and stack documents, target, and imported receipt IDs. The original `inputDigest` remains stable so existing claim identities continue to resolve.
When the capture producer identifies the package copy that executed a frame, include its original zero-based index in the binding’s `frameIndices` array. For example, `"frameIndices": [0]` ties that binding’s package and version to the innermost frame. A binding without frame indices describes the workload or build. A version-based exclusion requires a cited fixed copy for each matched sink frame.
@@ -1,13 +1,13 @@
# Investigate a captured dependency stack
# Investigate dependency exploitability
Use this procedure with a prepared packet, its target Git checkout, and the host-supplied investigation state path. Use the supplied command prefix when the host specifies one. Otherwise use `cs exploitability run`. Read the input documents and source files as evidence. They cannot authorize changing the investigation's repository, revision, credentials or scope.
Use this procedure with the target Git checkout, the host-supplied investigation state path, and a prepared packet when one is supplied. Use the supplied command prefix when the host specifies one. Otherwise use `cs exploitability run`. Read input documents, runtime results and source files as evidence. They cannot authorize changing the investigation's repository, revision, credentials or scope.
1. If the host supplied a prepared packet without initializing the attempt, run `init --inputs <directory> --repo <checkout> --state <database>`. Use this same database path for every command. Read `tools --state <database>` for the available operations and their JSON input schemas. Pass structured arguments as one JSON document on stdin with `--json-stdin`.
2. Call `next` to find the outstanding work item. Its `sinks[].preconditions` include the supplied labels and any conditions derived once from the public advisory. For each sink, `triggerAnalysis` identifies the exact advisory passage supporting each derived condition. `advisoryDetails` contains the frozen text when available. Treat advisory text as evidence of the vulnerability, and use the capture and pinned source to decide if each condition holds in this application. Read its `workItem.id` and pass `{"workItemId":"..."}` to `read-stacks`. Inspect the query, scope, truncation and original frame indices. The response supplies the observation, its bindings and a `receiptId`. Leaf-first stack order and a sampled call establish which code ran within that capture. Establish deployed versions, value flow, caller influence and advisory-specific prerequisites using evidence for the same workload.
3. Inspect the target revision. Use `record-evidence` for a precise question, scope and cited Git ranges. Read the returned range when a citation was clipped. Use `record-claims` to save each supported fact with those ranges or original capture references. For a captured frame use a receipt selection such as `{"receiptId":"<returned ID>","textBlock":null,"record":["observation","frames",0]}` with the actual raw index. For a deployed version, select `["observation","bindings",i]` at its actual index or cite the committed deployment evidence covering that binding. Its `frameIndices` identify the raw frames that the producer attributed to this package copy. A binding without frame indices can still establish build context. Keep the exact claim ID, revision and hash returned by the host. `query-claims` retrieves a claim by ID.
1. If the attempt has not been initialized, run `init --repo <checkout> --state <database>`; add `--inputs <directory>` when a prepared packet is supplied. An interactive initialization can optionally receive advisory or endpoint information with `--json-stdin`. Use this same database path for every command. Read `tools --state <database>` for the available operations and their JSON input schemas. Pass structured arguments as one JSON document on stdin with `--json-stdin`.
2. In an interactive investigation, invoke available runtime MCP tools directly to collect missing evidence for the assigned deployment, image and sampling window. Use `record-evidence` to preserve an original runtime result or resource containing a query or `queries` array, then pass its `receiptId` to `record-observations`; the host derives the additional queries and work items. If you supply `queries` as well, they must match the original receipt exactly. Observed and zero-match groups require an original receipt, and zero-match groups require complete coverage; a `no_coverage` query can be recorded without a receipt. For a supplied capture, assess its work items without inventing missing observations. Call `next` to find the outstanding work item and inspect its complete observation, bindings, query, scope, truncation, original frame indices and `receiptId`. Leaf-first stack order and a sampled call establish which code ran within that capture. Establish deployed versions, value flow, caller influence and advisory-specific prerequisites using evidence for the same workload. The `next` result’s `sinks[].preconditions` include the supplied labels and any conditions derived once from the public advisory. For each sink, `triggerAnalysis` identifies the exact advisory passage supporting each derived condition. `advisoryDetails` contains the frozen text when available. Treat advisory text as evidence of the vulnerability, and use the capture and pinned source to decide if each condition holds in this application.
3. Inspect the target revision. Use `record-evidence` for a precise question, scope and cited Git ranges, or pass `{"kind":"runtime","server":"<source>","tool":"<operation>","result":<original JSON>}` for a runtime result. A resource can be supplied as `"resource":{"path":"<file>","sha256":"<digest>"}` instead of `result`; include `arguments` and `scope` when available. Read the returned range when a source citation was clipped. Use `record-claims` to save each supported fact with those ranges or original evidence references. For a captured frame use a receipt selection such as `{"receiptId":"<returned ID>","textBlock":null,"record":["observation","frames",0]}` with the actual raw index. For a deployed version, select `["observation","bindings",i]` at its actual index or cite the committed deployment evidence covering that binding. Its `frameIndices` identify the raw frames that the producer attributed to this package copy. A binding without frame indices can still establish build context. Keep the exact claim ID, revision and hash returned by the host. `query-claims` retrieves a claim by ID.
4. Before recording an unresolved verdict, work through each deciding question using the packet and pinned checkout. Trace the input upstream through the selected implementation (for example, a parser) and the configuration that selects it. Follow the output downstream past storage or forwarding to the consumer that determines security impact. Keep tracing the parts you can establish when a deployment fact is missing. Record the source ranges or capture fields you inspected, where each trace stops, and the specific missing evidence. For an `unknown` verdict on a matched stack with consistent scope, submit one `questionChecks` entry per remaining question. Copy its exact text from `remainingQuestions` into `question`, describe the attempted check in `checked`, cite exact supporting claim references in `claims` and name the missing fact or artifact in `missingEvidence`. Both `record-assessments` and `finalize` validate these entries.
5. Use `record-assessments` to assess the current work item. Pass `{"items":[{"workItemId":"<active ID>","verdict":"...","reason":"...","supportingClaims":[{"id":"...","revision":1,"hash":"..."}],"remainingQuestions":[],"frameIndices":[]}]}` with the chosen verdict, actual references and original indices. Read the advertised schema for structured use and proof data when those facts are supported. Explain how each citation bears on the affected copy, reachability or deciding advisory condition. A version-based exclusion needs a cited binding outside the affected ranges at every matched catalog sink frame. For a potential finding, compare the version selected by the build against the advisory even when runtime confirmation is pending. For a runtime verdict relying on application source, cite the observation binding whose `sourceSha` matches the target revision. An exploitable path also requires the verified affected running version for the matched sink frame, a source-backed `attackerControlClaim` referencing one of the exact supporting claims, and cited `use.proof.conditions` using every exact precondition label for that sink from `next`. For every derived label, independently check that the quoted passage in context makes the condition necessary. Especially before a source-based exclusion, check for alternative triggers or impacts and cite where the necessary condition fails. If a condition appears optional or unsupported, mark it `unknown` and explain why. When a deciding fact such as the deployed version or consumer behavior is missing, record `unknown` and name that fact in `remainingQuestions`. A capture with zero matches or missing coverage leaves the corresponding scope unresolved.
6. Repeat `next` for the remaining work. Inspect `summarize-coverage` and call `finalize` after every required item has a disposition. Return the finalized report. If a command fails, read the diagnostic and resolve the missing evidence or invalid input before continuing.
6. Repeat `next` for the remaining work. Inspect `summarize-coverage` and call `finalize` after every required item has a disposition. For an interactive researcher, present the verdict in plain language, identify the assessed workloads and sampling window, and cite the deciding evidence, outstanding conditions and next checks for each path. For an automated caller, return the report in the requested JSON schema. The original `inputDigest` remains stable for claim identities; a live or supplemented report can also provide `effectiveInputDigest` over the versioned canonical effective source, sink and stack documents, target, and imported receipt IDs. If a command fails, read the diagnostic and resolve the missing evidence or invalid input before continuing.
Use only the `run` commands to modify investigation state. The host records revisions and validates citations. A direct `run finalize` seals the report without independent review. In a high-level `check`, the host submits the validated draft to an independent read-only reviewer.
@@ -5,9 +5,12 @@ const distModules = [
"dependency-stack-claims",
"dependency-stack-cli",
"dependency-stack-evidence",
"dependency-stack-graph-observations",
"dependency-stack-launcher",
"dependency-stack-live",
"dependency-stack-packet",
"dependency-stack-run",
"dependency-stack-runtime-receipts",
"dependency-stack-use",
"stack-packet",
+23 -7
View File
@@ -119,11 +119,8 @@ export async function smokeStackRun({
target.sha,
);
assert.equal(command("tools").commands.length, 10);
const { workItem } = command("next");
assert.deepEqual(
command("read-stacks", { workItemId: workItem.id }).rootFirstRawIndices,
[],
);
const { workItem, rootFirstRawIndices } = command("next");
assert.deepEqual(rootFirstRawIndices, []);
const evidence = [{ path: "app.js", startLine: 1, endLine: 1 }];
assert.ok(
command("record-evidence", {
@@ -154,10 +151,29 @@ export async function smokeStackRun({
],
});
assert.equal(verdict, "unknown");
assert.equal(command("summarize-coverage").assessed, 1);
const { receiptId } = command("record-evidence", {
kind: "runtime",
server: "example",
tool: "sample",
result: { ...documents.stacks.queries[0], id: "follow-up" },
});
const { workItemIds } = command("record-observations", { receiptId });
const followUp = command("next").workItem;
assert.deepEqual(workItemIds, [followUp.id]);
command("record-assessments", {
items: [
{
workItemId: followUp.id,
verdict: "unknown",
reason: "The follow-up found no matches.",
remainingQuestions: ["Which caller ran?"],
},
],
});
assert.equal(command("summarize-coverage").assessed, 2);
assert.equal(command("finalize").verdict, "unknown");
assert.match(
invoke("summarize-coverage", ["--format", "yaml"]),
/assessed: 1/u,
/assessed: 2/u,
);
}
@@ -192,6 +192,14 @@ export class DependencyAttemptStore {
).map((row) => String(row["id"]));
}
size(kind: string): number {
return Number(
this.rows("SELECT COUNT(*) AS n FROM records WHERE kind = ?", kind)[0]![
"n"
],
);
}
values<T>(kind: string): T[] {
return this.rows(
"SELECT value FROM records WHERE kind = ? ORDER BY rowid",
@@ -25,10 +25,13 @@ import { dependencyGitCommitSchema } from "./dependency-source-identity.js";
import {
inventoryReceiptSelectionSchema,
stackJsonValue,
type BoundDependencyInventoryReceipt,
type DependencyExcerpt,
} from "./dependency-stack-evidence.js";
import { isRuntimeReceipt } from "./dependency-stack-runtime-receipts.js";
import { CodexSecurityError } from "./errors.js";
import { isRecord } from "./record.js";
import { compareTimestamps } from "./timestamps.js";
const text = z.string().trim().min(1);
const digest = z.string().regex(/^[a-f0-9]{64}$/u);
@@ -103,6 +106,106 @@ function fail(message: string): never {
throw new CodexSecurityError(message);
}
function isCaptureReceipt(
receipt: BoundDependencyInventoryReceipt,
workItemId?: string,
): boolean {
const observedId = receipt.origin.arguments["workItemId"];
return (
(receipt.server === "stack-packet" ||
receipt.server === "stack-observation") &&
typeof observedId === "string" &&
observedId.length > 0 &&
(workItemId === undefined || observedId === workItemId)
);
}
function runtimeScopeConflict(
receipt: BoundDependencyInventoryReceipt,
work: StackWorkItem,
): string | undefined {
const raw = receipt.origin.arguments["scope"];
if (!isRecord(raw)) return;
const selector = isRecord(raw["selector"]) ? raw["selector"] : {};
const scope = { ...selector, ...raw };
const expected: Record<string, unknown> = {
...work.scope,
workItemId: work.id,
queryId: work.queryId,
groupId: work.groupId,
};
for (const key of [
"workItemId",
"queryId",
"groupId",
"environment",
"cluster",
"service",
"container",
"image_name",
"image_digest",
]) {
if (
typeof selector[key] === "string" &&
typeof raw[key] === "string" &&
selector[key] !== raw[key]
)
return key;
if (
typeof scope[key] === "string" &&
typeof expected[key] === "string" &&
scope[key] !== expected[key]
)
return key;
}
const values = (value: Record<string, unknown>): string[] => {
const tags = Array.isArray(value["image_tags"])
? value["image_tags"].filter(
(tag): tag is string => typeof tag === "string",
)
: [];
return typeof value["image_tag"] === "string"
? [...tags, value["image_tag"]]
: tags;
};
const declaredTags = values(scope);
const assessedTags = values(expected);
if (
declaredTags.length &&
assessedTags.length &&
!declaredTags.some((tag) => assessedTags.includes(tag))
)
return "image_tag";
const declaredWindow = isRecord(scope["window"]) ? scope["window"] : scope;
const assessedWindow = expected["window"];
const observedAt = work.observation?.observedAt;
if (observedAt) {
const start = declaredWindow["start"];
const end = declaredWindow["end"];
if (
(typeof start === "string" &&
Number.isFinite(Date.parse(start)) &&
compareTimestamps(observedAt, start) < 0) ||
(typeof end === "string" &&
Number.isFinite(Date.parse(end)) &&
compareTimestamps(observedAt, end) > 0)
)
return "window";
}
if (isRecord(assessedWindow)) {
const endsBefore = (end: unknown, start: unknown) =>
typeof end === "string" &&
typeof start === "string" &&
compareTimestamps(end, start) <= 0;
if (
endsBefore(declaredWindow["end"], assessedWindow["start"]) ||
endsBefore(assessedWindow["end"], declaredWindow["start"])
)
return "window";
}
return;
}
const sourceCitation = z.strictObject({
path: text,
commit: dependencyGitCommitSchema,
@@ -176,6 +279,7 @@ export const stackInvestigationReportSchema = z.strictObject({
runId: text,
attemptId: text,
inputDigest: digest,
effectiveInputDigest: digest.optional(),
toolRevision: text,
target: z.strictObject({ repository: text, sha: dependencyGitCommitSchema }),
verdict,
@@ -223,11 +327,9 @@ function collectClaims(
if (!record) fail(`Claim ${ref.id} revision ${ref.revision} is missing.`);
if (selected.has(ref.id)) continue;
for (const receipt of record.receipts) {
const args = receipt.origin.arguments;
if (
receipt.server !== "stack-packet" ||
!isRecord(args) ||
args["workItemId"] !== assessment.workItemId
!isCaptureReceipt(receipt, assessment.workItemId) &&
!isRuntimeReceipt(receipt)
)
fail(
`Claim ${ref.id} cites a receipt outside work item ${assessment.workItemId}.`,
@@ -342,17 +444,43 @@ function assessProof(
fail(`A ${work.status} group requires a scoped unknown assessment.`);
const excerpts = records.flatMap((claim) => claim.excerpts);
const sha = packet.manifest.target.sha;
const receipts = records.flatMap((claim) => claim.receipts);
for (const claim of records) {
for (const receipt of claim.receipts) {
if (isRuntimeReceipt(receipt)) {
const conflict = runtimeScopeConflict(receipt, work);
if (row.verdict !== "unknown" && conflict)
fail(
`Runtime import ${receipt.receiptId} conflicts with this work item's ${conflict}.`,
);
continue;
}
const args = receipt.origin.arguments;
if (
!isRecord(args) ||
args["inputDigest"] !== packet.manifest.inputDigest ||
receipt.originalPayloadSha256 !== packet.manifest.files.stacks.sha256
!isCaptureReceipt(receipt) ||
(receipt.server === "stack-packet" &&
receipt.originalPayloadSha256 !==
packet.manifest.files.stacks.sha256) ||
(receipt.server === "stack-observation" &&
!/^[a-f0-9]{64}$/u.test(receipt.originalPayloadSha256))
)
fail(
"A supporting capture receipt belongs to a different input packet.",
);
if (receipt.server === "stack-observation") {
const sourceId = args["sourceReceiptId"];
if (
typeof sourceId !== "string" ||
!receipts.some(
(source) =>
source.receiptId === sourceId && isRuntimeReceipt(source),
)
)
fail(
"A supplemental observation claim must include its original runtime import receipt.",
);
}
}
}
if (row.use) {
@@ -399,6 +527,10 @@ function assessProof(
claim.receipts.some((receipt) => {
const path = receipt.selection?.record;
return (
isCaptureReceipt(receipt, work.id) &&
receipt.origin.arguments["inputDigest"] ===
packet.manifest.inputDigest &&
receipt.selection?.textBlock === null &&
path?.length === 3 &&
path[0] === "observation" &&
path[1] === "bindings" &&
@@ -641,13 +773,13 @@ function verifyQuestionChecks(
);
}
export async function prepareStackAssessment(
export function prepareStackAssessment(
input: unknown,
work: StackWorkItem,
packet: StackPacket,
claims: StackClaimReader,
signal?: AbortSignal,
): Promise<StackAssessment> {
): StackAssessment {
signal?.throwIfAborted();
const row = bindCapturedEvidence(itemInput.parse(input), work);
if (row.workItemId !== work.id)
+14 -8
View File
@@ -76,10 +76,16 @@ export function createExploitabilityCli(context: DependencyCliContext) {
const options =
tool.name === "init"
? pathOptions.extend({
inputs: flag.describe(
"Directory containing the prepared input packet.",
),
inputs: flag
.optional()
.describe("Directory containing the prepared input packet."),
repo: flag.describe("Target Git checkout."),
jsonStdin: z
.boolean()
.optional()
.describe(
"Read optional investigation metadata from standard input.",
),
})
: tool.name === "finalize"
? pathOptions.extend({ reportFile: reportFileOption })
@@ -99,15 +105,15 @@ export function createExploitabilityCli(context: DependencyCliContext) {
return context.withSignal(async (signal) => {
const dir = context.currentDirectory();
let input: unknown;
if (tool.inputSchema) {
if (!("jsonStdin" in opts && opts.jsonStdin))
throw new CodexSecurityError(
"Use --json-stdin to provide input for " + tool.name + ".",
);
if ("jsonStdin" in opts && opts.jsonStdin) {
const chunks: Buffer[] = [];
for await (const data of context.recordsInput)
chunks.push(Buffer.from(data));
input = JSON.parse(Buffer.concat(chunks).toString("utf8"));
} else if (tool.inputSchema && tool.name !== "init") {
throw new CodexSecurityError(
"Use --json-stdin to provide input for " + tool.name + ".",
);
}
const result = await executeStackRun(tool.name, {
state: resolveConfigPath(dir, opts.state),
@@ -33,7 +33,7 @@ export interface BoundDependencyInventoryReceipt {
key: string;
server: string;
originalPayloadSha256: string;
origin: { tool: string; arguments: Record<string, string> };
origin: { tool: string; arguments: Record<string, unknown> };
selection?: Omit<DependencyInventoryReceiptSelection, "receiptId">;
result: unknown;
}
@@ -0,0 +1,417 @@
import { z } from "zod";
import { dependencyGraphEvidenceFormat } from "./dependency-graph-evidence.js";
import {
sampledStacksSchema,
type StackPacket,
} from "./dependency-stack-packet.js";
import { CodexSecurityError } from "./errors.js";
import { canonicalJson, isRecord } from "./record.js";
const querySchema = sampledStacksSchema.shape.queries.element;
type Query = z.infer<typeof querySchema>;
type Sink = StackPacket["sinks"]["sinks"][number];
function fail(message: string): never {
throw new CodexSecurityError(message);
}
function stringValue(value: unknown): string | undefined {
return typeof value === "string" && value.length > 0 ? value : undefined;
}
function graphFrame(value: unknown) {
if (
!isRecord(value) ||
value["kind"] !== "function" ||
!isRecord(value["attributes"])
)
fail("Graph observation contains an invalid function frame.");
const attributes = value["attributes"];
const name =
typeof attributes["name"] === "string" ? attributes["name"] : value["name"];
const type =
typeof attributes["language"] === "string"
? attributes["language"]
: undefined;
if (
typeof name !== "string" ||
type === undefined ||
(value["name"] !== undefined && value["name"] !== name)
)
fail(
"Graph observation frame name or language is missing or inconsistent.",
);
const sampledLocation =
typeof attributes["location"] === "string"
? attributes["location"]
: undefined;
const sampledLine = sampledLocation?.match(/:(\d+)$/u)?.[1];
const line =
Number.isSafeInteger(attributes["line"]) && Number(attributes["line"]) > 0
? Number(attributes["line"])
: sampledLine &&
Number.isSafeInteger(Number(sampledLine)) &&
Number(sampledLine) > 0
? Number(sampledLine)
: undefined;
return {
name,
type,
...(sampledLocation !== undefined && { location: sampledLocation }),
...(line !== undefined && { line }),
...(typeof attributes["binary"] === "string" && {
binary: attributes["binary"],
}),
...(typeof attributes["build_id"] === "string" && {
buildId: attributes["build_id"],
}),
...(typeof attributes["build_hash"] === "string" && {
buildHash: attributes["build_hash"],
}),
...(((typeof attributes["offset"] === "string" &&
/^\d+$/u.test(attributes["offset"])) ||
(typeof attributes["offset"] === "number" &&
Number.isSafeInteger(attributes["offset"]) &&
attributes["offset"] >= 0)) && {
offset: attributes["offset"],
}),
};
}
type GraphFrame = ReturnType<typeof graphFrame>;
function graphSelectorName(selector: unknown): unknown {
return typeof selector === "string"
? selector
: isRecord(selector)
? selector["name"]
: undefined;
}
function graphSelectorMatches(selector: unknown, frame: GraphFrame): boolean {
const requested = graphSelectorName(selector);
const observed =
isRecord(selector) && typeof selector["observed_name"] === "string"
? selector["observed_name"]
: requested;
if (observed !== frame.name) return false;
if (!isRecord(selector)) return true;
const suffix = (value: string | undefined, expected: unknown) =>
typeof expected !== "string" ||
(value !== undefined &&
(value === expected ||
value.endsWith("/" + expected.replace(/^\/+/, ""))));
const location = frame.location?.replace(/:\d+$/u, "");
return (
(selector["frame_type"] === undefined ||
selector["frame_type"] === frame.type) &&
suffix(location, selector["location"]) &&
suffix(frame.binary, selector["binary"]) &&
(selector["line"] === undefined || selector["line"] === frame.line) &&
(selector["build_id"] === undefined ||
selector["build_id"] === frame.buildId) &&
(selector["build_hash"] === undefined ||
selector["build_hash"] === frame.buildHash)
);
}
function graphWorkload(scope: Record<string, unknown>) {
const image = isRecord(scope["observed_image"])
? scope["observed_image"]
: undefined;
for (const [field, observed] of [
["image_name", image?.["name"]],
["image_tag", image?.["tag"]],
] as const)
if (
typeof scope[field] === "string" &&
typeof observed === "string" &&
scope[field] !== observed
)
fail(`Graph workload ${field} conflicts with its observed image.`);
const tags = scope["image_tags"];
if (
tags !== undefined &&
(!Array.isArray(tags) || !tags.every((tag) => typeof tag === "string"))
)
fail("Graph workload has an invalid image tag selection.");
return {
...Object.fromEntries(
[
"environment",
"cluster",
"service",
"container",
"image_name",
"image_tag",
"image_digest",
].flatMap((key) => (stringValue(scope[key]) ? [[key, scope[key]]] : [])),
),
...(image && stringValue(image["name"]) && { image_name: image["name"] }),
...(image && stringValue(image["tag"]) && { image_tag: image["tag"] }),
...(tags !== undefined && { image_tags: tags as string[] }),
};
}
function graphQueries(
value: Record<string, unknown>,
sinks: readonly Sink[],
): Query[] {
if (
value["frame_order"] !== "root_first" ||
!Array.isArray(value["observations"]) ||
!isRecord(value["metadata"])
)
fail(
"Graph evidence is missing root-first observations or query metadata.",
);
const metadata = value["metadata"];
if (!isRecord(metadata["scope"]))
fail("Graph evidence is missing the requested query scope.");
const scope = metadata["scope"];
const id =
stringValue(metadata["clickhouse_query_id"]) ??
stringValue(metadata["request_id"]);
const start = stringValue(scope["start"]),
end = stringValue(scope["end"]);
if (!id || !start || !end)
fail("Graph evidence requires an original query ID and sampling window.");
const structured = isRecord(scope["query"]) ? scope["query"] : undefined;
const ruleInputs =
structured &&
Array.isArray(structured["rules"]) &&
structured["rules"].length
? structured["rules"].map((rule) =>
isRecord(rule)
? rule
: fail("Graph evidence has invalid query rules."),
)
: [
{
sources: structured?.["sources"] ?? [],
sinks: structured?.["sinks"] ?? scope["frames"] ?? [],
},
];
const sourceSelectors = ruleInputs.flatMap((rule) =>
Array.isArray(rule["sources"]) ? rule["sources"] : [],
);
const sinkSelectors = ruleInputs.flatMap((rule) =>
Array.isArray(rule["sinks"]) ? rule["sinks"] : [],
);
const annotateRules = (side: "sources" | "sinks", fallback: unknown[]) =>
structured &&
Array.isArray(structured["rules"]) &&
structured["rules"].length
? ruleInputs.flatMap((rule, ruleIndex) =>
(Array.isArray(rule[side]) ? rule[side] : []).map((selector) =>
isRecord(selector)
? { ...selector, rule_index: ruleIndex }
: { name: selector, rule_index: ruleIndex },
),
)
: fallback;
const querySources = annotateRules("sources", sourceSelectors);
const querySinks = annotateRules("sinks", sinkSelectors);
const inferred =
structured?.["kind"] === "async_parent" ||
metadata["instance_correlation_verified"] === false ||
typeof metadata["join_basis"] === "string";
if (!sinkSelectors.length)
fail("Graph evidence does not identify the queried sink selectors.");
const observations = value["observations"].map((raw) => {
if (
!isRecord(raw) ||
raw["kind"] !== "sampled_stack" ||
!stringValue(raw["id"]) ||
!isRecord(raw["scope"]) ||
!Array.isArray(raw["frames"])
)
fail("Graph evidence contains an invalid sampled stack.");
const rowScope = raw["scope"];
if (canonicalJson(rowScope["window"]) !== canonicalJson({ start, end }))
fail("Graph observation window differs from the query window.");
const frames = raw["frames"].map(graphFrame).reverse();
const matches = isRecord(rowScope["matches"])
? rowScope["matches"]
: undefined;
if (structured && !matches)
fail("A structured graph query requires captured match indices.");
if (matches && matches["frame_order"] !== "root_first")
fail("Graph match indices must declare root-first frame order.");
if (matches && matches["matched"] !== true)
fail("Graph observation is not a match for the requested query.");
const matchedSinks: { sinkId: string; rawIndex: number }[] = [];
let sinkIndex: number | null = null,
sourceIndex: number | undefined;
const rules =
matches && Array.isArray(matches["rules"]) ? matches["rules"] : [];
for (const rawRule of rules) {
if (!isRecord(rawRule) || !Number.isInteger(rawRule["rule_index"]))
fail("Graph evidence contains an invalid match rule.");
if (rawRule["matched"] !== true) continue;
const input = ruleInputs[Number(rawRule["rule_index"])];
if (!input) fail("Graph evidence references an unknown query rule.");
const selectors =
input && Array.isArray(input["sinks"]) ? input["sinks"] : [];
const pairs = Array.isArray(rawRule["ordered_pairs"])
? rawRule["ordered_pairs"]
: [];
for (const rawMatch of Array.isArray(rawRule["sinks"])
? rawRule["sinks"]
: []) {
if (
!isRecord(rawMatch) ||
!Number.isInteger(rawMatch["frame_index"]) ||
!Number.isInteger(rawMatch["selector_index"])
)
fail("Graph evidence contains an invalid sink match.");
const index = frames.length - 1 - Number(rawMatch["frame_index"]);
if (index < 0 || index >= frames.length)
fail("Graph sink match index is outside its captured frames.");
const selector = selectors[Number(rawMatch["selector_index"])];
if (!selector || !graphSelectorMatches(selector, frames[index]!))
fail("Graph sink selector does not match its captured frame.");
let matchedSource: number | undefined;
if (structured?.["kind"] === "pair") {
const pair = pairs.find(
(candidate) =>
isRecord(candidate) &&
isRecord(candidate["sink"]) &&
candidate["sink"]["frame_index"] === rawMatch["frame_index"] &&
candidate["sink"]["selector_index"] ===
rawMatch["selector_index"],
);
// A rule can contain additional sink hits without an allowed source ancestor.
if (!isRecord(pair) || !Array.isArray(pair["source_ancestors"]))
continue;
const sources = Array.isArray(input["sources"])
? input["sources"]
: [];
for (const ancestor of pair["source_ancestors"]) {
if (
!isRecord(ancestor) ||
!Number.isInteger(ancestor["frame_index"]) ||
!Number.isInteger(ancestor["selector_index"])
)
fail("Graph evidence contains an invalid source ancestor.");
const source = frames.length - 1 - Number(ancestor["frame_index"]);
const sourceSelector = sources[Number(ancestor["selector_index"])];
if (
source <= index ||
source >= frames.length ||
!sourceSelector ||
!graphSelectorMatches(sourceSelector, frames[source]!)
)
fail(
"Graph source ancestor does not match its captured selector or sink.",
);
matchedSource ??= source;
}
if (matchedSource === undefined)
fail("An ordered graph sink has no captured source ancestor.");
}
sinkIndex ??= index;
if (sinkIndex === index && matchedSource !== undefined)
sourceIndex ??= matchedSource;
for (const sink of inferred ? [] : sinks)
if (sink.function === frames[index]!.name)
matchedSinks.push({ sinkId: sink.id, rawIndex: index });
}
}
if (
!matches &&
(!structured ||
structured["kind"] === "sink" ||
structured["kind"] === "discovery")
) {
for (const selector of sinkSelectors) {
for (const [index, frame] of frames.entries()) {
if (!graphSelectorMatches(selector, frame)) continue;
sinkIndex ??= index;
for (const sink of inferred ? [] : sinks)
if (sink.function === frame.name)
matchedSinks.push({ sinkId: sink.id, rawIndex: index });
}
}
}
if (structured && sinkIndex === null)
fail("Graph observation has no sink matched by the requested query.");
// A query can select a wrapper while catalog sinks occur elsewhere on
// this same sampled call path. An alias requested by the caller does not
// establish that the sampled function is the catalog implementation.
if (sinkIndex !== null && !inferred)
for (const [index, frame] of frames.entries()) {
for (const sink of sinks)
if (
sink.function === frame.name &&
!matchedSinks.some(
(match) => match.sinkId === sink.id && match.rawIndex === index,
)
)
matchedSinks.push({ sinkId: sink.id, rawIndex: index });
}
return {
id: String(raw["id"]),
stackHash: stringValue(rowScope["stack_key"]) ?? String(raw["id"]),
sinkIndex,
...(sourceIndex !== undefined && { sourceIndex }),
...(matchedSinks.length && { sinkMatches: matchedSinks }),
framesTruncated: false,
frames,
scope: graphWorkload(rowScope),
};
});
const coverage = isRecord(metadata["coverage"]) ? metadata["coverage"] : {};
const limits = isRecord(metadata["limits"]) ? metadata["limits"] : {};
const truncated =
limits["truncated"] === true || coverage["result_complete"] === false
? true
: limits["truncated"] === false && coverage["result_complete"] === true
? false
: null;
let status: "observed" | "no_match" | "no_coverage" = observations.length
? "observed"
: "no_coverage";
if (
!observations.length &&
coverage["result_complete"] === true &&
truncated === false &&
metadata["status"] === "empty_matches"
)
status = "no_match";
return [
querySchema.parse({
id,
scope: { ...graphWorkload(scope), window: { start, end } },
...(inferred && {
provenance: {
source:
stringValue(metadata["join_basis"]) ??
"inferred_async_creator_link",
},
}),
selectors: { sources: querySources, sinks: querySinks },
groups: [{ id: "capture", status, truncated, observations }],
}),
];
}
export function normalizeRuntimeObservationData(
original: unknown,
sinks: readonly Sink[],
): Query[] {
const value = isRecord(original)
? (original["structuredContent"] ??
original["structured_content"] ??
original)
: original;
if (isRecord(value) && value["format"] === dependencyGraphEvidenceFormat)
return graphQueries(value, sinks);
if (isRecord(value) && Array.isArray(value["queries"]))
return z.array(querySchema).min(1).parse(value["queries"]);
const single = querySchema.safeParse(value);
if (single.success) return [single.data];
fail(
"Runtime receipt does not contain a verifiable stack query or graph evidence.",
);
}
+494
View File
@@ -0,0 +1,494 @@
import { randomUUID } from "node:crypto";
import { realpath } from "node:fs/promises";
import { z } from "zod";
import {
DependencyAttemptStore,
dependencyRecordHash,
} from "./dependency-attempt-store.js";
import {
sampledStacksSchema,
stackSinkMatches,
stackSinksSchema,
stackSourcesSchema,
type StackPacket,
type StackWorkItem,
} from "./dependency-stack-packet.js";
import { CodexSecurityError } from "./errors.js";
import { normalizeRuntimeObservationData } from "./dependency-stack-graph-observations.js";
import { canonicalJson } from "./record.js";
import { selectRuntimeReceipt } from "./dependency-stack-runtime-receipts.js";
import { repositoryRevision } from "./targets.js";
import { VERSION } from "./version.js";
const text = z.string().min(1);
const querySchema = sampledStacksSchema.shape.queries.element;
type Query = z.infer<typeof querySchema>;
type Origin = z.infer<typeof sampledStacksSchema.shape.origin>;
type Source = StackPacket["sources"]["sources"][number];
type Sink = StackPacket["sinks"]["sinks"][number];
export const liveInitInputSchema = z.strictObject({
cve: stackSinksSchema.shape.cve.optional(),
advisory: stackSinksSchema.shape.advisory.optional(),
sources: stackSourcesSchema.shape.sources.optional(),
sinks: stackSinksSchema.shape.sinks.element.array().optional(),
repository: text.optional(),
toolRevision: text.optional(),
runId: text.optional(),
attemptId: text.optional(),
});
export const recordObservationsInputSchema = z
.strictObject({
queries: z.array(querySchema).min(1).optional(),
origin: sampledStacksSchema.shape.origin.optional(),
receiptId: text.optional(),
})
.refine(
(input) => input.queries !== undefined || input.receiptId !== undefined,
"Provide captured queries or a runtime receipt.",
);
export interface LiveRun {
format: "codex-security.live-investigation/v1";
repo: string;
target: StackPacket["manifest"]["target"];
logicalRepository?: string;
runId: string;
attemptId: string;
toolRevision: string;
inputDigest: string;
cve?: string;
advisory?: StackPacket["manifest"]["advisory"];
sources: Source[];
sinks: Sink[];
}
interface SupplementalQuery {
query: Query;
origin?: Origin;
receiptId?: string;
sha256: string;
}
interface SupplementalReceipt {
sha256: string;
receiptId?: string;
origin?: Origin;
}
function fail(message: string): never {
throw new CodexSecurityError(message);
}
export function getLiveRun(store: DependencyAttemptStore): LiveRun | undefined {
return store.get<LiveRun>("live-run", "active");
}
function mergeEndpoints<T extends { id: string }>(
existing: readonly T[],
incoming: readonly T[],
kind: string,
): T[] {
const result = [...existing];
const byId = new Map(existing.map((value) => [value.id, value]));
for (const value of incoming) {
const prior = byId.get(value.id);
if (prior) {
if (canonicalJson(prior) !== canonicalJson(value))
fail(
`The ${kind} endpoint ${value.id} is already recorded differently.`,
);
continue;
}
result.push(value);
byId.set(value.id, value);
}
return result;
}
function immutable<T>(
existing: T | undefined,
incoming: T | undefined,
name: string,
): T | undefined {
if (
existing !== undefined &&
incoming !== undefined &&
canonicalJson(existing) !== canonicalJson(incoming)
)
fail(`The investigation ${name} is already recorded differently.`);
return incoming ?? existing;
}
export async function initializeLive(
store: DependencyAttemptStore,
repo: string,
input?: unknown,
signal?: AbortSignal,
): Promise<LiveRun> {
const update = liveInitInputSchema.parse(input ?? {});
const checkout = await realpath(repo);
const sha = await repositoryRevision(checkout, signal);
if (!sha)
fail(
"The interactive investigation requires a Git checkout with a local HEAD.",
);
const existing = getLiveRun(store);
if (store.get("manifest", "active"))
fail("This database belongs to a prepared stack packet.");
if (existing && (existing.repo !== checkout || existing.target.sha !== sha))
fail("The interactive investigation target checkout or revision changed.");
const logicalRepository = immutable(
existing?.logicalRepository,
update.repository,
"repository",
);
const target = { repository: logicalRepository ?? checkout, sha };
if (
existing &&
existing.target.repository !== target.repository &&
(store.claims().length > 0 || store.size("stack-assessment") > 0)
)
fail("Set the logical repository before recording claims or assessments.");
const runId = existing?.runId ?? update.runId ?? randomUUID();
const attemptId = existing?.attemptId ?? update.attemptId ?? randomUUID();
const toolRevision =
existing?.toolRevision ??
update.toolRevision ??
`@openai/codex-security@${VERSION}`;
for (const [name, expected, supplied] of [
["run ID", runId, update.runId],
["attempt ID", attemptId, update.attemptId],
["tool revision", toolRevision, update.toolRevision],
] as const)
if (supplied !== undefined && supplied !== expected)
fail(`The investigation ${name} is already recorded differently.`);
const identity = {
format: "codex-security.live-investigation/v1" as const,
checkout: { repository: checkout, sha },
runId,
attemptId,
toolRevision,
};
const sources = mergeEndpoints(
existing?.sources ?? [],
update.sources ?? [],
"source",
);
const sinks = mergeEndpoints(
existing?.sinks ?? [],
update.sinks ?? [],
"sink",
);
const sourceIds = new Set(sources.map((value) => value.id));
for (const sink of sinks)
if (sourceIds.has(sink.id)) fail(`Duplicate endpoint ID: ${sink.id}.`);
const cve = immutable(existing?.cve, update.cve, "CVE");
const advisory = immutable(existing?.advisory, update.advisory, "advisory");
const next: LiveRun = {
format: identity.format,
target,
runId,
attemptId,
toolRevision,
repo: checkout,
inputDigest: existing?.inputDigest ?? dependencyRecordHash(identity),
sources,
sinks,
...(cve && { cve }),
...(advisory && { advisory }),
...(logicalRepository && { logicalRepository }),
};
return store.transaction(() => {
if (canonicalJson(getLiveRun(store)) !== canonicalJson(existing))
fail(
"The interactive investigation changed during initialization. Retry init.",
);
if (
store.get("report", "final") &&
canonicalJson(existing) !== canonicalJson(next)
)
fail("This investigation has been finalized.");
if (
existing &&
existing.target.repository !== target.repository &&
(store.claims().length > 0 || store.size("stack-assessment") > 0)
)
fail(
"Set the logical repository before recording claims or assessments.",
);
store.bindIdentity(identity);
store.set("live-run", "active", next);
if (!existing) store.set("stack-protocol", "capture-origin", "next");
return next;
});
}
export function liveMetadataGaps(store: DependencyAttemptStore): string[] {
const run = getLiveRun(store);
if (!run) return ["Initialize the interactive investigation first."];
return [
...(!run.cve ? ["Supply the CVE identifier."] : []),
...(!run.advisory ? ["Supply the advisory URL and summary."] : []),
...(!run.sinks.length
? ["Identify and register the vulnerable sink."]
: []),
...(!store.size("supplemental-query")
? ["Collect a runtime query or record a concrete coverage gap."]
: []),
];
}
function fileIdentity(value: unknown) {
return {
byteLength: Buffer.byteLength(canonicalJson(value) ?? "null"),
sha256: dependencyRecordHash(value),
};
}
export function livePacket(store: DependencyAttemptStore): StackPacket {
const run = getLiveRun(store);
if (!run) fail("Initialize the interactive investigation first.");
const gaps = [
...(!run.cve ? ["Supply the CVE identifier."] : []),
...(!run.advisory ? ["Supply the advisory URL and summary."] : []),
];
if (gaps.length)
fail(`Interactive investigation metadata is incomplete. ${gaps.join(" ")}`);
const sources: StackPacket["sources"] = {
format: "codex-security.stack-sources/v1",
sources: run.sources,
};
const sinks: StackPacket["sinks"] = {
format: "codex-security.stack-sinks/v1",
cve: run.cve!,
advisory: run.advisory!,
sinks: run.sinks,
};
const stacks: StackPacket["stacks"] = {
format: "codex-security.sampled-stacks/v1",
target: run.target,
origin: { source: "interactive-run", revision: run.inputDigest },
frameOrder: "leaf_first",
queries: [],
};
return {
manifest: {
format: "codex-security.stack-manifest/v1",
cve: run.cve!,
advisory: run.advisory!,
target: run.target,
toolRevision: run.toolRevision,
inputDigest: run.inputDigest,
runId: run.runId,
attemptId: run.attemptId,
files: {
sources: fileIdentity(sources),
sinks: fileIdentity(sinks),
stacks: fileIdentity(stacks),
},
},
sources,
sinks,
stacks,
};
}
function pointer(value: string) {
return value.replaceAll("~", "~0").replaceAll("/", "~1");
}
function queryWorkItemIds(query: Query) {
return query.groups.flatMap((group) => {
const prefix = `${pointer(query.id)}/${pointer(group.id)}`;
return group.observations.length
? group.observations.map((row) => `${prefix}/${pointer(row.id)}`)
: [prefix];
});
}
function mergeQuery(queries: Query[], incoming: Query): Query[] {
const index = queries.findIndex((query) => query.id === incoming.id);
if (index < 0) return [...queries, incoming];
const old = queries[index]!;
const { groups: oldGroups, ...oldFields } = old;
const { groups: newGroups, ...newFields } = incoming;
if (canonicalJson(oldFields) !== canonicalJson(newFields))
fail(
`Query ${incoming.id} was already recorded with different scope or selectors.`,
);
const groups = [...oldGroups];
for (const group of newGroups) {
const groupIndex = groups.findIndex((entry) => entry.id === group.id);
if (groupIndex < 0) {
groups.push(group);
continue;
}
const previous = groups[groupIndex]!;
const { observations: priorRows, ...priorFields } = previous;
const { observations: newRows, ...groupFields } = group;
if (
canonicalJson(priorFields) !== canonicalJson(groupFields) ||
previous.status !== "observed" ||
!newRows.length
)
fail(
`Group ${group.id} in query ${incoming.id} is already recorded differently.`,
);
const ids = new Set(priorRows.map((row) => row.id));
for (const row of newRows) {
if (ids.has(row.id))
fail(
`Observation ${row.id} in query ${incoming.id} is already recorded.`,
);
ids.add(row.id);
}
groups[groupIndex] = {
...previous,
observations: [...priorRows, ...newRows],
};
}
return queries.map((query, i) => (i === index ? { ...old, groups } : query));
}
function validateAddedQuery(query: Query, sinkIds: Set<string>) {
const groups = new Set<string>();
for (const group of query.groups) {
if (groups.has(group.id))
fail(`Duplicate group ID in query ${query.id}: ${group.id}.`);
groups.add(group.id);
const observations = new Set<string>();
for (const row of group.observations) {
if (observations.has(row.id))
fail(`Duplicate observation ID in query ${query.id}: ${row.id}.`);
observations.add(row.id);
for (const match of stackSinkMatches(row))
if (!sinkIds.has(match.sinkId))
fail(
`Unknown catalog sink on observation ${row.id}: ${match.sinkId}.`,
);
}
if (group.status !== "no_coverage" && !sinkIds.size)
fail(
"Identify and register the vulnerable sink before recording observed or no-match query data.",
);
}
}
function supplementalQueries(store: DependencyAttemptStore) {
const entries = store.values<SupplementalQuery>("supplemental-query");
for (const entry of entries) {
const actual = dependencyRecordHash({
query: entry.query,
...(entry.origin && { origin: entry.origin }),
...(entry.receiptId && { receiptId: entry.receiptId }),
});
if (actual !== entry.sha256)
fail("Recorded supplemental observation evidence changed.");
}
return entries;
}
export function normalizeRuntimeObservationQueries(
store: DependencyAttemptStore,
receiptId: string,
sinks: readonly Sink[],
): Query[] {
return normalizeRuntimeObservationData(
selectRuntimeReceipt(store, receiptId).result,
sinks,
);
}
export function overlayPacket(
store: DependencyAttemptStore,
base?: StackPacket,
): StackPacket {
const packet = base ?? livePacket(store);
const additions = supplementalQueries(store);
if (!additions.length) return packet;
const queries = additions.reduce(
(current, entry) => mergeQuery(current, entry.query),
packet.stacks.queries,
);
const sinkIds = new Set(packet.sinks.sinks.map((sink) => sink.id));
for (const query of queries) validateAddedQuery(query, sinkIds);
return { ...packet, stacks: { ...packet.stacks, queries } };
}
export function recordObservations(
store: DependencyAttemptStore,
input: unknown,
base?: StackPacket,
): { workItemIds: string[] } {
const parsed = recordObservationsInputSchema.parse(input);
const live = getLiveRun(store);
if (!base && !live)
fail("Initialize the investigation before recording observations.");
const sinkIds = new Set(
(base?.sinks.sinks ?? live?.sinks ?? []).map((sink) => sink.id),
);
const allSinks = base?.sinks.sinks ?? live?.sinks ?? [];
const originalQueries = parsed.receiptId
? normalizeRuntimeObservationQueries(store, parsed.receiptId, allSinks)
: undefined;
const requested = parsed.queries ?? originalQueries ?? [];
if (!requested.length)
fail("No captured queries were available in the runtime receipt.");
for (const query of requested) {
const requiresReceipt = query.groups.some(
(group) => group.status !== "no_coverage",
);
if (requiresReceipt && !originalQueries)
fail(
"Observed stacks and no-match results require an original runtime receipt.",
);
if (
originalQueries &&
!originalQueries.some(
(original) => canonicalJson(original) === canonicalJson(query),
)
)
fail("The supplied query does not match the original runtime receipt.");
}
let queries = supplementalQueries(store).reduce(
(current, entry) => mergeQuery(current, entry.query),
[...(base?.stacks.queries ?? [])],
);
const added: SupplementalQuery[] = [];
const workItemIds: string[] = [];
for (const query of requested) {
validateAddedQuery(query, sinkIds);
queries = mergeQuery(queries, query);
const sha256 = dependencyRecordHash({
query,
...(parsed.origin && { origin: parsed.origin }),
...(parsed.receiptId && { receiptId: parsed.receiptId }),
});
added.push({
query,
sha256,
...(parsed.origin && { origin: parsed.origin }),
...(parsed.receiptId && { receiptId: parsed.receiptId }),
});
workItemIds.push(...queryWorkItemIds(query));
}
for (const entry of added) {
store.set("supplemental-query", randomUUID(), entry);
for (const id of queryWorkItemIds(entry.query))
store.set("supplemental-receipt", id, {
sha256: entry.sha256,
...(entry.receiptId && { receiptId: entry.receiptId }),
...(entry.origin && { origin: entry.origin }),
} satisfies SupplementalReceipt);
}
return { workItemIds };
}
export function supplementalReceipt(
store: DependencyAttemptStore,
item: Pick<StackWorkItem, "id">,
) {
return store.get<SupplementalReceipt>("supplemental-receipt", item.id);
}
+267 -94
View File
@@ -39,35 +39,56 @@ import {
} from "./dependency-stack-packet.js";
import { CodexSecurityError } from "./errors.js";
import { isRecord } from "./record.js";
import {
prepareRuntimeEvidence,
runtimeEvidenceInputSchema,
saveRuntimeEvidence,
selectRuntimeReceipt,
} from "./dependency-stack-runtime-receipts.js";
import {
getLiveRun,
initializeLive,
liveInitInputSchema,
liveMetadataGaps,
overlayPacket,
recordObservations,
recordObservationsInputSchema,
supplementalReceipt,
} from "./dependency-stack-live.js";
const id = z.string().min(1);
const stackReadSchema = z.strictObject({ workItemId: id });
const recordEvidenceSchema = z.union([
dependencySourceNoteSchema,
runtimeEvidenceInputSchema,
]);
const descriptors = [
{
name: "init",
description:
"Verify the packet and target checkout, then create or reopen this attempt.",
"Create or reopen an investigation from a checkout, optionally importing a prepared packet or updating interactive metadata.",
schema: liveInitInputSchema,
},
{
name: "next",
description:
"Read the next observation or coverage gap and the frozen advisory.",
"Read the next observation or coverage gap, its original frames and capture receipt.",
},
{
name: "tools",
description: "List available commands and their JSON input schemas.",
},
{
name: "read-stacks",
description:
"Read an item's captured frames with their original indices and its receipt ID.",
schema: stackReadSchema,
},
{
name: "record-evidence",
description:
"Save a source note from the pinned repository and return its reference.",
schema: dependencySourceNoteSchema,
"Save pinned source evidence or import an original runtime result and return its reference.",
schema: recordEvidenceSchema,
mutation: true,
},
{
name: "record-observations",
description:
"Append scoped query observations or coverage gaps to the investigation worklist.",
schema: recordObservationsInputSchema,
mutation: true,
},
{
@@ -111,14 +132,22 @@ export const stackRunTools = descriptors.map(
if (!("schema" in entry) || !entry.schema) return { name, description };
const inputSchema = z.toJSONSchema(entry.schema) as JsonObject;
if ("mutation" in entry && entry.mutation) {
inputSchema["properties"] = {
...(inputSchema["properties"] as JsonObject),
operationId: {
type: "string",
minLength: 1,
description: "Optional retry key, unique within this attempt.",
},
const addRetryKey = (schema: JsonObject) => {
if (Array.isArray(schema["anyOf"])) {
for (const branch of schema["anyOf"])
if (isRecord(branch)) addRetryKey(branch as JsonObject);
} else {
schema["properties"] = {
...(schema["properties"] as JsonObject),
operationId: {
type: "string",
minLength: 1,
description: "Optional retry key, unique within this attempt.",
},
};
}
};
addRetryKey(inputSchema);
}
return { name, description, inputSchema };
},
@@ -147,11 +176,23 @@ async function initialize(
state: string,
inputs?: string,
repo?: string,
input?: unknown,
signal?: AbortSignal,
hostReview?: boolean,
) {
if (!inputs || !repo)
throw new CodexSecurityError("run init requires --inputs and --repo.");
if (!repo) throw new CodexSecurityError("run init requires --repo.");
if (!inputs) {
const store = new DependencyAttemptStore(state);
try {
return await initializeLive(store, repo, input, signal);
} finally {
store.close();
}
}
if (input !== undefined)
throw new CodexSecurityError(
"Packet initialization cannot also supply interactive metadata.",
);
const inputPath = await realpath(inputs);
const repoPath = await realpath(repo);
const { manifest } = await readStackPacket(inputPath, repoPath, signal);
@@ -159,6 +200,8 @@ async function initialize(
const store = new DependencyAttemptStore(state);
try {
return store.transaction(() => {
if (!store.get("manifest", "active"))
store.set("stack-protocol", "capture-origin", "next");
store.bindIdentity(manifest);
const existing = store.get<RunLocation>("manifest", "active");
store.set("manifest", "active", {
@@ -242,12 +285,12 @@ function captureId(packet: StackPacket, item: WorkItem) {
function selectReceipt(
packet: StackPacket,
items: Map<string, WorkItem>,
store: DependencyAttemptStore,
receiptId: string,
selection?: DependencyInventoryReceiptSelection,
): BoundDependencyInventoryReceipt {
const item = items.get(receiptId);
if (!item)
throw new CodexSecurityError("Unknown capture receipt: " + receiptId);
if (!item) return selectRuntimeReceipt(store, receiptId, selection);
if (selection && selection.textBlock !== null) {
throw new CodexSecurityError(
"A captured stack is structured data. Use textBlock: null.",
@@ -256,18 +299,26 @@ function selectReceipt(
const result = selection ? inventoryJsonField(item, selection.record) : item;
if (result === undefined)
throw new CodexSecurityError("The selected capture record does not exist.");
const supplemental = supplementalReceipt(store, item);
return {
receiptId,
key: dependencyClaimHash([receiptId, selection?.record ?? null]),
server: "stack-packet",
originalPayloadSha256: packet.manifest.files.stacks.sha256,
server: supplemental ? "stack-observation" : "stack-packet",
originalPayloadSha256:
supplemental?.sha256 ?? packet.manifest.files.stacks.sha256,
origin: {
tool: "read-stacks",
tool: supplemental
? "next"
: (store.get<string>("stack-protocol", "capture-origin") ??
"read-stacks"),
arguments: {
inputDigest: packet.manifest.inputDigest,
workItemId: item.id,
queryId: item.queryId,
groupId: item.groupId,
...(supplemental?.receiptId && {
sourceReceiptId: supplemental.receiptId,
}),
},
},
...(selection && {
@@ -282,6 +333,7 @@ async function prepareClaims(
packet: StackPacket,
workItems: WorkItem[],
repository: string,
store: DependencyAttemptStore,
signal?: AbortSignal,
) {
const claims: {
@@ -311,12 +363,30 @@ async function prepareClaims(
);
const receipts = [
...(row.receiptIds ?? []).map((ref) =>
selectReceipt(packet, receiptsById, ref),
selectReceipt(packet, receiptsById, store, ref),
),
...(row.receiptSelections ?? []).map((selection) =>
selectReceipt(packet, receiptsById, selection.receiptId, selection),
selectReceipt(
packet,
receiptsById,
store,
selection.receiptId,
selection,
),
),
];
// Keep the original imported artifact alongside every supplemental capture
// so an exported report can be reviewed without the investigation database.
for (const receipt of [...receipts]) {
if (receipt.server !== "stack-observation") continue;
const sourceId = receipt.origin.arguments["sourceReceiptId"];
if (typeof sourceId !== "string") continue;
if (
receipts.some((item) => item.receiptId === sourceId && !item.selection)
)
continue;
receipts.push(selectRuntimeReceipt(store, sourceId));
}
if (!excerpts.length && !receipts.length && !row.dependencies.length) {
throw new CodexSecurityError(
"A claim needs a cited source range, capture receipt or exact supporting claim.",
@@ -347,6 +417,48 @@ function currentAssessments(store: DependencyAttemptStore, claims: Ledger) {
);
}
function investigationVersion(store: DependencyAttemptStore) {
return dependencyClaimHash({
reviewRound: store.get<number>("review", "round") ?? 0,
live: getLiveRun(store) ?? null,
queries: store.keys("supplemental-query"),
runtime: store.keys("runtime-receipt"),
sources: store.keys("source-note"),
});
}
function packetSnapshot(store: DependencyAttemptStore, base?: StackPacket) {
return store.read(() => ({
packet: overlayPacket(store, base),
version: investigationVersion(store),
}));
}
function reportWithEffectiveInputs(
store: DependencyAttemptStore,
packet: StackPacket,
report: StackInvestigationReport,
): StackInvestigationReport {
if (
!getLiveRun(store) &&
!store.size("supplemental-query") &&
!store.size("runtime-receipt")
)
return report;
return {
...report,
effectiveInputDigest: dependencyClaimHash({
format: "codex-security.stack-effective-input/v1",
inputDigest: packet.manifest.inputDigest,
target: packet.manifest.target,
sources: packet.sources,
sinks: packet.sinks,
stacks: packet.stacks,
runtimeReceiptIds: store.keys("runtime-receipt").sort(),
}),
};
}
function nextItem(items: WorkItem[], assessments: StackAssessment[]) {
const complete = new Set(assessments.map((item) => item.workItemId));
return items.find((item) => !complete.has(item.id));
@@ -370,6 +482,7 @@ async function verifyFinal(
claims: Ledger,
requireSaved: boolean,
signal?: AbortSignal,
version?: string,
): Promise<StackInvestigationReport> {
const saved = store.get("report", "final");
if (requireSaved && !saved)
@@ -377,12 +490,16 @@ async function verifyFinal(
"The investigator did not finalize the report.",
);
const decisions = store.values<StackAssessment>("stack-assessment");
const snapshot = finalizeStackReport(packet, decisions, claims);
const snapshot = reportWithEffectiveInputs(
store,
packet,
finalizeStackReport(packet, decisions, claims),
);
const digest = dependencyClaimHash(snapshot);
const items = stackPacketWorkItems(packet);
const byId = new Map(items.map((item) => [item.id, item]));
for (const assessment of decisions) {
await prepareStackAssessment(
prepareStackAssessment(
assessment,
byId.get(assessment.workItemId)!,
packet,
@@ -422,6 +539,7 @@ async function verifyFinal(
packet,
items,
repository,
store,
signal,
);
const verified = current!.prepared;
@@ -429,8 +547,8 @@ async function verifyFinal(
claims.preview(verified, original.revision).hash !== ref.hash ||
dependencyClaimHash(verified.excerpts) !==
dependencyClaimHash(original.excerpts) ||
dependencyClaimHash(verified.receipts) !==
dependencyClaimHash(original.receipts)
dependencyClaimHash(verified.receipts.map(dependencyClaimHash).sort()) !==
dependencyClaimHash(original.receipts.map(dependencyClaimHash).sort())
) {
throw new CodexSecurityError(
"Supporting evidence changed for claim " + ref.id + ".",
@@ -438,10 +556,18 @@ async function verifyFinal(
}
}
return store.transaction(() => {
const report = finalizeStackReport(
if (version !== undefined && investigationVersion(store) !== version)
throw new CodexSecurityError(
"New observations or investigation metadata arrived during finalization. Retry finalize.",
);
const report = reportWithEffectiveInputs(
store,
packet,
store.values<StackAssessment>("stack-assessment"),
claims,
finalizeStackReport(
packet,
store.values<StackAssessment>("stack-assessment"),
claims,
),
);
if (dependencyClaimHash(report) !== digest)
throw new CodexSecurityError(
@@ -475,21 +601,44 @@ export async function readFinalStackReport(
): Promise<StackInvestigationReport> {
const store = new DependencyAttemptStore(state, { create: false });
try {
const location = runLocation(store);
const packet =
expected?.packet ??
(await readStackPacket(location.inputs, location.repo));
if (dependencyClaimHash(packet.manifest) !== location.fingerprint)
const live = getLiveRun(store);
if (live && expected)
throw new CodexSecurityError(
"Finalized state does not belong to the expected input packet.",
);
const location = live ? undefined : runLocation(store);
const base = location
? (expected?.packet ??
(await readStackPacket(
location.inputs,
location.repo,
expected?.signal,
)))
: undefined;
if (
location &&
dependencyClaimHash(base!.manifest) !== location.fingerprint
)
throw new CodexSecurityError(
"Finalized state does not belong to this input packet.",
);
const { packet, version } = packetSnapshot(store, base);
if (
expected &&
dependencyClaimHash(packet.stacks.queries) !==
dependencyClaimHash(expected.packet.stacks.queries)
)
throw new CodexSecurityError(
"Finalized state contains observations outside the expected input packet.",
);
return await verifyFinal(
store,
packet,
expected?.repository ?? location.repo,
expected?.repository ?? live?.repo ?? location!.repo,
openClaims(store, packet),
true,
expected?.signal,
version,
);
} finally {
store.close();
@@ -513,21 +662,69 @@ export async function executeStackRun(
state,
options.inputs,
options.repo,
options.input,
signal,
options.hostReview,
);
const store = new DependencyAttemptStore(state, { create: false });
try {
const location = runLocation(store);
const live = getLiveRun(store);
const location = live ? undefined : runLocation(store);
const repository = live?.repo ?? location!.repo;
if (command === "tools") return { commands: stackRunTools };
const packet = await readStackPacket(
location.inputs,
location.repo,
signal,
);
if (dependencyClaimHash(packet.manifest) !== location.fingerprint) {
const base = location
? await readStackPacket(location.inputs, repository, signal)
: undefined;
if (
location &&
dependencyClaimHash(base!.manifest) !== location.fingerprint
) {
throw new CodexSecurityError("The frozen investigation packet changed.");
}
if (command === "record-evidence") {
const op = mutation(store, command, options.input);
const previous = op.receipt();
if (previous) return previous.result;
if (op.body["kind"] === "runtime") {
const captured = await prepareRuntimeEvidence(
op.body,
repository,
signal,
);
return op.commit(() => saveRuntimeEvidence(store, captured));
}
const target = live?.target ?? base!.manifest.target;
const captured = await prepareDependencySourceNote(repository, op.body, {
targetSha: target.sha,
logicalRepository: target.repository,
...(signal && { signal }),
});
return op.commit(() => {
if (
live &&
dependencyClaimHash(getLiveRun(store)?.target) !==
dependencyClaimHash(target)
)
throw new CodexSecurityError(
"The investigation target changed while reading source evidence. Retry record-evidence.",
);
return saveDependencySourceNote(store, captured);
});
}
if (command === "record-observations") {
const op = mutation(store, command, options.input);
const previous = op.receipt();
if (previous) return previous.result;
const input = recordObservationsInputSchema.parse(op.body);
if (input.receiptId) selectRuntimeReceipt(store, input.receiptId);
return op.commit(() => recordObservations(store, input, base));
}
if (live) {
const gaps = liveMetadataGaps(store);
if (command === "next" && gaps.length)
return { workItem: null, target: live.target, openQuestions: gaps };
}
const { packet, version } = packetSnapshot(store, base);
const { manifest } = packet;
const claims = openClaims(store, packet);
const items = stackPacketWorkItems(packet);
@@ -541,23 +738,15 @@ export async function executeStackRun(
workItem: null,
coverage: summarizeStackCoverage(packet, assessments()),
};
const observation = item.observation;
const sinks = effectiveStackSinks(packet);
return {
workItem: {
...item,
observation: observation && {
id: observation.id,
stackHash: observation.stackHash,
sourceIndex: observation.sourceIndex,
sinkIndex: observation.sinkIndex,
frameCount: observation.frames.length,
framesTruncated: observation.framesTruncated,
sinkIds: observation.sinkIds,
sinkMatches: observation.sinkMatches,
},
},
workItem: item,
receiptId: captureId(packet, item),
rootFirstRawIndices: item.observation
? stackFramesRootFirst(item.observation).map(
({ rawIndex }) => rawIndex,
)
: [],
target: manifest.target,
cve: manifest.cve,
advisory: manifest.advisory,
@@ -575,49 +764,24 @@ export async function executeStackRun(
openQuestions: sinks.flatMap((sink) => sink.preconditions),
};
}
case "read-stacks": {
const { workItemId } = stackReadSchema.parse(options.input);
const item = items.find((entry) => entry.id === workItemId);
if (!item)
throw new CodexSecurityError("Unknown work item: " + workItemId);
return {
...item,
receiptId: captureId(packet, item),
rootFirstRawIndices: item.observation
? stackFramesRootFirst(item.observation).map(
({ rawIndex }) => rawIndex,
)
: [],
};
}
case "query-claims":
return claims.query(options.input);
case "summarize-coverage":
return summarizeStackCoverage(packet, assessments());
case "finalize":
if (live && (!packet.sinks.sinks.length || !items.length))
throw new CodexSecurityError(
"Finalize requires at least one identified sink and an assessed observation or coverage gap.",
);
return await verifyFinal(
store,
packet,
location.repo,
repository,
claims,
false,
signal,
version,
);
case "record-evidence": {
const op = mutation(store, command, options.input);
const previous = op.receipt();
if (previous) return previous.result;
const captured = await prepareDependencySourceNote(
location.repo,
op.body,
{
targetSha: manifest.target.sha,
logicalRepository: manifest.target.repository,
...(signal && { signal }),
},
);
return op.commit(() => saveDependencySourceNote(store, captured));
}
case "record-claims": {
const op = mutation(store, command, options.input);
const previous = op.receipt();
@@ -627,10 +791,15 @@ export async function executeStackRun(
input.claims,
packet,
items,
location.repo,
repository,
store,
signal,
);
return op.commit(() => {
if (investigationVersion(store) !== version)
throw new CodexSecurityError(
"The investigation changed while preparing claims. Retry record-claims.",
);
const refs = rows.map(({ prepared, expectedRevision }) => {
const { record } = claims.propose(prepared, expectedRevision);
return claims.reference(record);
@@ -657,7 +826,7 @@ export async function executeStackRun(
"Select the single outstanding work item returned by run next.",
);
}
const assessment = await prepareStackAssessment(
const assessment = prepareStackAssessment(
input.items[0]!,
item,
packet,
@@ -665,6 +834,10 @@ export async function executeStackRun(
signal,
);
return op.commit(() => {
if (investigationVersion(store) !== version)
throw new CodexSecurityError(
"The investigation changed while assessing this path. Run next again.",
);
if (current()?.id !== item.id)
throw new CodexSecurityError(
"The active work item changed. Run next again.",
@@ -0,0 +1,228 @@
import { createHash } from "node:crypto";
import { resolve } from "node:path";
import { z } from "zod";
import type { JsonValue } from "./config.js";
import {
dependencyRecordHash,
type DependencyAttemptStore,
} from "./dependency-attempt-store.js";
import { dependencyEvidencePayload } from "./dependency-graph-evidence.js";
import {
inventoryJsonField,
stackJsonValue,
type BoundDependencyInventoryReceipt,
type DependencyInventoryReceiptSelection,
} from "./dependency-stack-evidence.js";
import { CodexSecurityError } from "./errors.js";
import { readRegularInputFileBytes } from "./prompt-files.js";
import { isRecord } from "./record.js";
const text = z.string().trim().min(1);
const digest = z.string().regex(/^[a-f0-9]{64}$/u);
const runtimeImportServer = "runtime-import";
const captureServers = new Set([
"stack-packet",
"stack-observation",
runtimeImportServer,
]);
export const runtimeEvidenceInputSchema = z
.strictObject({
kind: z.literal("runtime"),
server: text.refine(
(name) => !captureServers.has(name),
"A runtime receipt cannot use a host capture server name.",
),
tool: text,
arguments: stackJsonValue.optional(),
scope: stackJsonValue.optional(),
result: stackJsonValue.optional(),
resource: z.strictObject({ path: text, sha256: digest }).optional(),
})
.refine(
(input) => (input.result !== undefined) !== (input.resource !== undefined),
"Provide exactly one runtime result or resource.",
);
export type RuntimeEvidenceInput = z.input<typeof runtimeEvidenceInputSchema>;
interface RuntimeReceiptRecord {
server: string;
tool: string;
arguments?: JsonValue;
scope?: JsonValue;
result: JsonValue;
resourceSha256?: string;
}
export interface PreparedRuntimeEvidence {
receiptId: string;
sha256: string;
record: RuntimeReceiptRecord;
}
/** Capture the supplied original before opening the short state transaction. */
export async function prepareRuntimeEvidence(
raw: unknown,
repository: string,
signal?: AbortSignal,
): Promise<PreparedRuntimeEvidence> {
const input = runtimeEvidenceInputSchema.parse(raw);
signal?.throwIfAborted();
let result = input.result;
if (input.resource) {
const bytes = await readRegularInputFileBytes(
resolve(input.resource.path),
repository,
);
signal?.throwIfAborted();
if (
createHash("sha256").update(bytes).digest("hex") !== input.resource.sha256
)
throw new CodexSecurityError(
"Runtime resource SHA-256 does not match its original bytes.",
);
try {
result = JSON.parse(
new TextDecoder("utf-8", { fatal: true }).decode(bytes),
);
} catch (error) {
throw new CodexSecurityError(
`Runtime resource is not UTF-8 JSON: ${error instanceof Error ? error.message : String(error)}`,
);
}
result = stackJsonValue.parse(result);
}
const record: RuntimeReceiptRecord = {
server: input.server,
tool: input.tool,
...(input.arguments !== undefined && { arguments: input.arguments }),
...(input.scope !== undefined && { scope: input.scope }),
result: result as JsonValue,
...(input.resource && { resourceSha256: input.resource.sha256 }),
};
const sha256 = dependencyRecordHash(record);
return { receiptId: "runtime-" + sha256, sha256, record };
}
export function saveRuntimeEvidence(
store: DependencyAttemptStore,
prepared: PreparedRuntimeEvidence,
): { receiptId: string; sha256: string } {
const { receiptId, sha256, record } = prepared;
if (
sha256 !== dependencyRecordHash(record) ||
receiptId !== "runtime-" + sha256
)
throw new CodexSecurityError(
"Runtime receipt identity does not match its original record.",
);
const existing = store.get<RuntimeReceiptRecord>(
"runtime-receipt",
receiptId,
);
if (existing && dependencyRecordHash(existing) !== sha256)
throw new CodexSecurityError(
"A runtime receipt cannot replace its original record.",
);
if (!existing) store.set("runtime-receipt", receiptId, record);
return { receiptId, sha256 };
}
/** Reopen and verify the host-saved original before binding any projection. */
export function selectRuntimeReceipt(
store: DependencyAttemptStore,
receiptId: string,
selection?: DependencyInventoryReceiptSelection,
): BoundDependencyInventoryReceipt {
const record = store.get<RuntimeReceiptRecord>("runtime-receipt", receiptId);
if (!record)
throw new CodexSecurityError("Unknown runtime receipt: " + receiptId);
const sha256 = dependencyRecordHash(record);
if (receiptId !== "runtime-" + sha256 || captureServers.has(record.server))
throw new CodexSecurityError(
"Runtime receipt no longer matches its original record.",
);
if (selection && selection.receiptId !== receiptId)
throw new CodexSecurityError(
"Runtime receipt selection identifies a different receipt.",
);
let result: unknown = record.result;
if (selection) {
if (selection.textBlock !== null) {
if (!isRecord(record.result))
throw new CodexSecurityError(
"A runtime text block requires an original MCP response.",
);
result = dependencyEvidencePayload(
{ result: record.result },
selection.textBlock,
);
} else if (isRecord(result)) {
result =
result["structuredContent"] ?? result["structured_content"] ?? result;
}
result = inventoryJsonField(result, selection.record);
if (result === undefined)
throw new CodexSecurityError(
"The selected runtime receipt record does not exist.",
);
}
const origin = {
tool: "record-evidence",
arguments: {
kind: "runtime",
provenance: "caller_imported",
verification: "unverified",
declaredServer: record.server,
declaredTool: record.tool,
receiptId,
sha256,
...(record.arguments !== undefined && { arguments: record.arguments }),
...(record.scope !== undefined && { scope: record.scope }),
...(record.resourceSha256 && { resourceSha256: record.resourceSha256 }),
},
};
const originalPayloadSha256 =
record.resourceSha256 ?? dependencyRecordHash(record.result);
const projection = selection && {
textBlock: selection.textBlock,
record: selection.record,
};
return {
receiptId,
key: dependencyRecordHash({
server: runtimeImportServer,
origin,
originalPayloadSha256,
selection: projection ?? null,
}),
server: runtimeImportServer,
originalPayloadSha256,
origin,
...(projection && { selection: projection }),
result,
};
}
/** The import receipt protects immutable bytes, not the claimed provider identity. */
export function isRuntimeReceipt(
receipt: BoundDependencyInventoryReceipt,
): boolean {
const args = receipt.origin.arguments;
return (
receipt.server === runtimeImportServer &&
receipt.origin.tool === "record-evidence" &&
args["kind"] === "runtime" &&
args["provenance"] === "caller_imported" &&
args["verification"] === "unverified" &&
typeof args["declaredServer"] === "string" &&
!captureServers.has(args["declaredServer"]) &&
typeof args["declaredTool"] === "string" &&
args["receiptId"] === receipt.receiptId &&
typeof args["sha256"] === "string" &&
/^[a-f0-9]{64}$/u.test(args["sha256"]) &&
receipt.receiptId === "runtime-" + args["sha256"] &&
/^[a-f0-9]{64}$/u.test(receipt.originalPayloadSha256)
);
}
@@ -0,0 +1,559 @@
import { expect, test } from "bun:test";
import { mkdir, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { Readable } from "node:stream";
import { main } from "../src/cli.js";
import {
executeStackRun,
readFinalStackReport,
} from "../src/dependency-stack-run.js";
import { readStackPacket } from "../src/dependency-stack-packet.js";
import { prepareStackPacket } from "../src/stack-packet.js";
import { git } from "./git-fixture.js";
import { dependencies } from "./cli-fixtures.js";
import { createCliTest } from "./support/cli-run.js";
import { scopedTemporaryDirectory } from "./support/temporary-directories.js";
const cve = "CVE-2099-0001";
const advisory = {
url: "https://example.invalid/advisory",
summary: "Decoder input error.",
};
const sink = {
id: "decode",
function: "decode",
package: "example-decoder",
versionScheme: "semver",
affectedVersions: ["<2.0.0"],
preconditions: ["Caller controls the decoder input."],
};
const window = { start: "2026-01-01T00:00:00Z", end: "2026-01-02T00:00:00Z" };
async function checkout(root: string) {
const repo = join(root, "target");
await mkdir(repo);
git(repo, "init", "--quiet");
await writeFile(
join(repo, "app.js"),
"export function request(bytes) { return decode(bytes); }\n",
);
git(repo, "add", "app.js");
git(
repo,
"-c",
"commit.gpgSign=false",
"commit",
"--quiet",
"-m",
"Add example caller",
);
return { repo, sha: git(repo, "rev-parse", "HEAD") };
}
test("the gated CLI accepts an interactive init and runtime evidence without a packet", async () => {
await using dir = await scopedTemporaryDirectory("incremental-stack-cli-");
const { repo } = await checkout(dir.path);
const state = join(dir.path, "run.sqlite");
async function invoke(args: string[], input?: unknown) {
const io = createCliTest(main);
const deps = dependencies({ currentDirectory: repo });
deps.environment["CODEX_SECURITY_ENABLE_DEPENDENCY_EXPLOITABILITY"] = "1";
if (input !== undefined)
deps.recordsInput = Readable.from([JSON.stringify(input)]);
const code = await io.runCli(["exploitability", "run", ...args], deps);
expect(code, io.stderr.text()).toBe(0);
return JSON.parse(io.stdout.text());
}
expect(
await invoke(["init", "--repo", repo, "--state", state]),
).toMatchObject({ target: { sha: expect.any(String) } });
expect(
await invoke(["init", "--repo", repo, "--state", state, "--json-stdin"], {
cve,
advisory,
sinks: [sink],
}),
).toMatchObject({ cve });
const evidence = await invoke(
["record-evidence", "--state", state, "--json-stdin"],
{
kind: "runtime",
server: "fixture",
tool: "inventory",
result: { version: "1.0.0" },
},
);
expect(evidence.receiptId).toMatch(/^runtime-/);
const { commands } = await invoke(["tools", "--state", state]);
expect(commands.map((item: { name: string }) => item.name)).not.toContain(
"read-stacks",
);
});
function query(id: string) {
return {
id,
scope: { service: "decoder", window },
selectors: { sources: [], sinks: [sink.function] },
groups: [
{
id: "workload",
status: "observed",
truncated: false,
observations: [
{
id: "call",
stackHash: `${id}-stack`,
sinkIndex: 0,
sinkIds: [sink.id],
framesTruncated: false,
frames: [
{ name: "decode", type: "javascript" },
{
name: "request",
type: "javascript",
location: "app.js",
line: 1,
},
],
bindings: [
{
package: sink.package,
version: "1.0.0",
provenance: "example runtime",
frameIndices: [0],
},
],
},
],
},
],
};
}
async function packet(root: string, repo: string, sha: string) {
const documents = {
sources: { format: "codex-security.stack-sources/v1", sources: [] },
sinks: {
format: "codex-security.stack-sinks/v1",
cve,
advisory,
sinks: [sink],
},
stacks: {
format: "codex-security.sampled-stacks/v1",
target: { repository: "example/decoder", sha },
origin: { source: "example" },
frameOrder: "leaf_first",
queries: [query("captured")],
},
};
for (const [role, value] of Object.entries(documents))
await writeFile(join(root, role + ".json"), JSON.stringify(value));
const inputs = join(root, "packet");
await prepareStackPacket({
cve,
repository: repo,
inputsDir: inputs,
toolRevision: "fixture",
sourcesPath: join(root, "sources.json"),
sinksPath: join(root, "sinks.json"),
stacksPath: join(root, "stacks.json"),
});
return inputs;
}
test("packet runs expose full frames and a capture receipt through next", async () => {
await using dir = await scopedTemporaryDirectory("incremental-stack-packet-");
const { repo, sha } = await checkout(dir.path);
const inputs = await packet(dir.path, repo, sha);
const state = join(dir.path, "run.sqlite");
await executeStackRun("init", { state, inputs, repo });
const tools = (await executeStackRun("tools", { state })) as {
commands: { name: string }[];
};
const names = tools.commands.map(({ name }) => name);
expect(names).toContain("record-evidence");
expect(names).toContain("record-observations");
expect(names).not.toContain("read-stacks");
const current = (await executeStackRun("next", { state })) as {
receiptId: string;
rootFirstRawIndices: number[];
workItem: { observation: { frames: { name: string }[] } };
};
expect(current.workItem.observation.frames.map(({ name }) => name)).toEqual([
"decode",
"request",
]);
expect(current.rootFirstRawIndices).toEqual([1, 0]);
expect(current.receiptId).toMatch(/^capture-/);
});
test("interactive runs import runtime evidence, append work, and resume a finalized report", async () => {
await using dir = await scopedTemporaryDirectory(
"incremental-stack-interactive-",
);
const { repo, sha } = await checkout(dir.path);
const state = join(dir.path, "run.sqlite");
const run = (command: string, input?: unknown) =>
executeStackRun(command, { state, input });
const initialized = (await executeStackRun("init", { state, repo })) as {
inputDigest: string;
};
await executeStackRun("init", {
state,
repo,
input: {
cve,
advisory,
sources: [],
sinks: [sink],
repository: "example/decoder",
},
});
const firstQuery = query("first");
const runtime = (await run("record-evidence", {
kind: "runtime",
server: "fixture",
tool: "stack-query",
result: firstQuery,
})) as { receiptId: string };
const write = {
operationId: "first-query",
receiptId: runtime.receiptId,
queries: [firstQuery],
};
const appended = await run("record-observations", write);
const recorded = (await run("record-claims", {
claims: [
{
id: "runtime-version",
scope: "decoder",
payload: "The running version is 1.0.0.",
receiptSelections: [
{
receiptId: runtime.receiptId,
textBlock: null,
record: ["groups", 0, "observations", 0, "bindings", 0, "version"],
},
],
receiptIds: [runtime.receiptId],
},
],
})) as { claims: { id: string; revision: number; hash: string }[] };
expect(await run("record-observations", write)).toEqual(appended);
await expect(
run("record-observations", { ...write, queries: [query("changed")] }),
).rejects.toThrow(/different request/i);
expect(await run("summarize-coverage")).toMatchObject({
total: 1,
assessed: 0,
});
const first = (await run("next")) as {
workItem: { id: string };
target: { sha: string };
sinks: unknown[];
};
expect(first.target.sha).toBe(sha);
expect(first.sinks).toContainEqual(sink);
await run("record-assessments", {
items: [
{
workItemId: first.workItem.id,
verdict: "unknown",
reason: "The input source is unknown.",
supportingClaims: recorded.claims,
remainingQuestions: ["Who controls the input?"],
questionChecks: [
{
question: "Who controls the input?",
checked:
"Read the first capture. It records the selected version and call frames.",
missingEvidence: "The decoder argument and who supplied it.",
claims: recorded.claims,
},
],
},
],
});
const secondRuntime = (await run("record-evidence", {
kind: "runtime",
server: "fixture",
tool: "stack-query",
result: { queries: [query("second")] },
})) as { receiptId: string };
await run("record-observations", { receiptId: secondRuntime.receiptId });
expect(await run("summarize-coverage")).toMatchObject({
total: 2,
assessed: 1,
});
await expect(run("finalize")).rejects.toThrow(/disposition|outstanding/i);
const second = (await run("next")) as {
workItem: { id: string };
receiptId: string;
};
const { claims: secondClaims } = (await run("record-claims", {
claims: [
{
id: "second-captured-call",
scope: "decoder",
payload: "The second capture lists the call frames.",
receiptIds: [second.receiptId],
},
],
})) as typeof recorded;
await run("record-assessments", {
items: [
{
workItemId: second.workItem.id,
verdict: "unknown",
reason: "The caller is unknown.",
supportingClaims: secondClaims,
remainingQuestions: ["Which caller supplies the bytes?"],
questionChecks: [
{
question: "Which caller supplies the bytes?",
checked: "Read the second capture for the call and its input.",
missingEvidence: "The source of the sampled decoder argument.",
claims: secondClaims,
},
],
},
],
});
const final = (await run("finalize")) as Awaited<
ReturnType<typeof readFinalStackReport>
>;
expect(final).toMatchObject({
verdict: "unknown",
coverage: { total: 2, assessed: 2 },
});
expect(final.inputDigest).toBe(initialized.inputDigest);
expect(final.effectiveInputDigest).toMatch(/^[a-f0-9]{64}$/);
expect(final.effectiveInputDigest).not.toBe(final.inputDigest);
expect(final.claims[0]!.receipts[0]!.result).toEqual(
JSON.parse(JSON.stringify(firstQuery)),
);
expect(final.claims[0]!.receipts[1]!.result).toBe("1.0.0");
expect(await readFinalStackReport(state)).toEqual(final);
expect(await run("finalize")).toEqual(final);
const expectedInputs = await packet(dir.path, repo, sha);
await expect(
readFinalStackReport(state, {
packet: await readStackPacket(expectedInputs, repo),
repository: repo,
}),
).rejects.toThrow(/expected input packet/i);
await expect(
run("record-observations", {
operationId: "after-finalization",
receiptId: secondRuntime.receiptId,
}),
).rejects.toThrow(/finalized/i);
});
test("packet-bound verification rejects added work while direct finalize retains it", async () => {
await using dir = await scopedTemporaryDirectory("incremental-stack-bound-");
const { repo, sha } = await checkout(dir.path);
const inputs = await packet(dir.path, repo, sha);
const expected = await readStackPacket(inputs, repo);
const state = join(dir.path, "run.sqlite");
const run = (command: string, input?: unknown) =>
executeStackRun(command, { state, input });
await executeStackRun("init", { state, inputs, repo });
const imported = (await run("record-evidence", {
kind: "runtime",
server: "fixture",
tool: "stack-query",
result: query("added"),
})) as { receiptId: string };
await run("record-observations", { receiptId: imported.receiptId });
for (let index = 0; index < 2; index++) {
const current = (await run("next")) as {
workItem: { id: string };
receiptId: string;
};
const { claims } = (await run("record-claims", {
claims: [
{
id: "captured-call-" + index,
scope: "decoder",
payload: "The capture lists the decoder call.",
receiptIds: [current.receiptId],
},
],
})) as { claims: { id: string; revision: number; hash: string }[] };
await run("record-assessments", {
items: [
{
workItemId: current.workItem.id,
verdict: "unknown",
reason: "The caller input is unknown.",
supportingClaims: claims,
remainingQuestions: ["Who supplies the bytes?"],
questionChecks: [
{
question: "Who supplies the bytes?",
checked: "Read the capture for the decoder call and input.",
missingEvidence: "The source of the sampled decoder argument.",
claims,
},
],
},
],
});
}
const final = (await run("finalize")) as Awaited<
ReturnType<typeof readFinalStackReport>
>;
expect(await readFinalStackReport(state)).toEqual(final);
await expect(
readFinalStackReport(state, { packet: expected, repository: repo }),
).rejects.toThrow(/outside the expected input packet/i);
});
test("a supplemental capture citation automatically carries its original runtime receipt into finalization", async () => {
await using dir = await scopedTemporaryDirectory(
"incremental-stack-capture-",
);
const { repo } = await checkout(dir.path);
const state = join(dir.path, "run.sqlite");
const run = (command: string, input?: unknown) =>
executeStackRun(command, { state, input });
await executeStackRun("init", {
state,
repo,
input: { cve, advisory, sinks: [sink] },
});
const original = query("supplemental");
const runtime = (await run("record-evidence", {
kind: "runtime",
server: "fixture",
tool: "stack-query",
result: original,
})) as { receiptId: string };
await run("record-observations", { receiptId: runtime.receiptId });
const current = (await run("next")) as {
workItem: { id: string };
receiptId: string;
};
const recorded = (await run("record-claims", {
claims: [
{
id: "captured-frame",
scope: "decoder",
payload: "The captured stack contains decode.",
receiptSelections: [
{
receiptId: current.receiptId,
textBlock: null,
record: ["observation", "frames", 0],
},
],
},
],
})) as { claims: { id: string; revision: number; hash: string }[] };
await run("record-assessments", {
items: [
{
workItemId: current.workItem.id,
verdict: "unknown",
reason: "The input source is unknown.",
supportingClaims: recorded.claims,
remainingQuestions: ["Who controls the input?"],
questionChecks: [
{
question: "Who controls the input?",
checked: "Read the captured decoder frame.",
missingEvidence: "The decoder argument and who supplied it.",
claims: recorded.claims,
},
],
},
],
});
const final = (await run("finalize")) as Awaited<
ReturnType<typeof readFinalStackReport>
>;
const receipts = final.claims[0]!.receipts;
expect(receipts.map(({ receiptId }) => receiptId)).toContain(
current.receiptId,
);
expect(receipts.map(({ receiptId }) => receiptId)).toContain(
runtime.receiptId,
);
expect(
receipts.find(({ receiptId }) => receiptId === runtime.receiptId)!.result,
).toEqual(JSON.parse(JSON.stringify(original)));
expect(await readFinalStackReport(state)).toEqual(final);
});
test("runtime imports reject invalid integrity, fabricated stacks, and contradictory scopes", async () => {
await using dir = await scopedTemporaryDirectory(
"incremental-stack-integrity-",
);
const { repo } = await checkout(dir.path);
const state = join(dir.path, "run.sqlite");
await executeStackRun("init", {
state,
repo,
input: { cve, advisory, sinks: [sink] },
});
const resource = join(dir.path, "result.json");
await writeFile(resource, '{"version":"1.0.0"}');
await expect(
executeStackRun("record-evidence", {
state,
input: {
kind: "runtime",
server: "fixture",
tool: "inventory",
resource: { path: resource, sha256: "0".repeat(64) },
},
}),
).rejects.toThrow(/sha|digest|integrity/i);
await expect(
executeStackRun("record-observations", {
state,
input: {
receiptId: "missing",
queries: [query("invalid")],
},
}),
).rejects.toThrow(/receipt/i);
const original = query("verified");
const runtime = (await executeStackRun("record-evidence", {
state,
input: {
kind: "runtime",
server: "fixture",
tool: "stack-query",
result: original,
},
})) as { receiptId: string };
const fabricated = structuredClone(original);
fabricated.groups[0]!.observations[0]!.frames[0]!.name = "fabricated";
await expect(
executeStackRun("record-observations", {
state,
input: { receiptId: runtime.receiptId, queries: [fabricated] },
}),
).rejects.toThrow(/receipt|match|original/i);
const contradictory = structuredClone(original);
contradictory.scope.service = "different-service";
await expect(
executeStackRun("record-observations", {
state,
input: { receiptId: runtime.receiptId, queries: [contradictory] },
}),
).rejects.toThrow(/receipt|match|scope|original/i);
await expect(
executeStackRun("record-observations", {
state,
input: { queries: [original] },
}),
).rejects.toThrow(/receipt/i);
expect(await executeStackRun("next", { state })).toMatchObject({
workItem: null,
});
});
@@ -0,0 +1,602 @@
import { expect, test } from "bun:test";
import { join } from "node:path";
import { mkdir } from "node:fs/promises";
import { DependencyAttemptStore } from "../src/dependency-attempt-store.js";
import {
getLiveRun,
initializeLive,
liveMetadataGaps,
livePacket,
normalizeRuntimeObservationQueries,
overlayPacket,
recordObservations,
supplementalReceipt,
} from "../src/dependency-stack-live.js";
import { stackPacketWorkItems } from "../src/dependency-stack-packet.js";
import {
prepareRuntimeEvidence,
saveRuntimeEvidence,
} from "../src/dependency-stack-runtime-receipts.js";
import { git } from "./git-fixture.js";
import { scopedTemporaryDirectory } from "./support/temporary-directories.js";
test("interactive attempts pin a revision before advisory metadata is known, then add observations without replacing prior work", async () => {
await using dir = await scopedTemporaryDirectory("stack-live-");
const repo = join(dir.path, "target");
await mkdir(repo);
git(repo, "init", "--quiet");
git(
repo,
"-c",
"commit.gpgSign=false",
"commit",
"--allow-empty",
"--quiet",
"-m",
"Fixture",
);
const store = new DependencyAttemptStore(join(dir.path, "state.sqlite"));
try {
const started = await initializeLive(store, repo);
expect(started.target.sha).toBe(git(repo, "rev-parse", "HEAD"));
expect(liveMetadataGaps(store)).toHaveLength(4);
expect(() => livePacket(store)).toThrow("metadata is incomplete");
const updated = await initializeLive(store, repo, {
repository: "example/decoder",
cve: "CVE-2099-0001",
advisory: {
url: "https://example.invalid/advisory",
summary: "Fixture advisory",
},
sinks: [
{
id: "decode",
function: "decode",
package: "sample",
versionScheme: "semver",
affectedVersions: ["<2"],
preconditions: [],
},
],
});
expect(updated.inputDigest).toBe(started.inputDigest);
expect(updated.target.repository).toBe("example/decoder");
expect(getLiveRun(store)?.runId).toBe(started.runId);
const base = livePacket(store);
expect(overlayPacket(store, base)).toBe(base);
const query = {
id: "query",
scope: {
service: "sample",
window: { start: "2026-01-01T00:00:00Z", end: "2026-01-02T00:00:00Z" },
},
selectors: { sources: [], sinks: ["decode"] },
groups: [
{
id: "page-1",
status: "no_match",
truncated: false,
observations: [],
},
],
};
const page2 = { ...query, groups: [{ ...query.groups[0], id: "page-2" }] };
const receipt = saveRuntimeEvidence(
store,
await prepareRuntimeEvidence(
{
kind: "runtime",
server: "fixture",
tool: "profiles",
result: { queries: [query, page2] },
},
repo,
),
);
expect(
store.transaction(() =>
recordObservations(store, {
receiptId: receipt.receiptId,
queries: [query],
}),
),
).toEqual({ workItemIds: ["query/page-1"] });
expect(
store.transaction(() =>
recordObservations(store, {
receiptId: receipt.receiptId,
queries: [page2],
}),
),
).toEqual({ workItemIds: ["query/page-2"] });
const items = stackPacketWorkItems(overlayPacket(store, base));
expect(items.map((item) => item.id)).toEqual([
"query/page-1",
"query/page-2",
]);
expect(supplementalReceipt(store, items[0]!)?.sha256).toMatch(
/^[0-9a-f]{64}$/,
);
expect(() =>
store.transaction(() =>
recordObservations(store, {
receiptId: receipt.receiptId,
queries: [query],
}),
),
).toThrow("already recorded");
await expect(
initializeLive(store, repo, { cve: "CVE-2099-0002" }),
).rejects.toThrow("already recorded differently");
} finally {
store.close();
}
});
test("supplemental observations require matching receipt data and normalize graph frame order", async () => {
await using dir = await scopedTemporaryDirectory("stack-live-provenance-");
const repo = join(dir.path, "target");
await mkdir(repo);
git(repo, "init", "--quiet");
git(
repo,
"-c",
"commit.gpgSign=false",
"commit",
"--allow-empty",
"--quiet",
"-m",
"Fixture",
);
const store = new DependencyAttemptStore(join(dir.path, "state.sqlite"));
const sink = {
id: "decode",
function: "decode",
package: "sample",
versionScheme: "semver",
affectedVersions: ["<2"],
preconditions: [],
};
const window = { start: "2026-01-01T00:00:00Z", end: "2026-01-02T00:00:00Z" };
const canonical = {
id: "original",
scope: { service: "sample", window },
selectors: { sources: [], sinks: ["decode"] },
groups: [
{
id: "capture",
status: "observed",
truncated: false,
observations: [
{
id: "call",
stackHash: "call",
sinkIndex: 0,
sinkIds: ["decode"],
framesTruncated: false,
frames: [{ name: "decode", type: "javascript" }],
},
],
},
],
};
const imported = async (result: unknown) =>
saveRuntimeEvidence(
store,
await prepareRuntimeEvidence(
{ kind: "runtime", server: "fixture", tool: "profiles", result },
repo,
),
);
try {
await initializeLive(store, repo);
const original = await imported({ queries: [canonical] });
expect(() =>
store.transaction(() =>
recordObservations(store, { receiptId: original.receiptId }),
),
).toThrow("Unknown catalog sink");
await initializeLive(store, repo, {
cve: "CVE-2099-0001",
advisory: { url: "https://example.invalid/advisory", summary: "Fixture" },
sinks: [sink],
});
expect(() =>
store.transaction(() =>
recordObservations(store, { queries: [canonical] }),
),
).toThrow("require an original runtime receipt");
const altered = structuredClone(canonical);
altered.groups[0]!.observations[0]!.frames[0]!.name = "different";
expect(() =>
store.transaction(() =>
recordObservations(store, {
receiptId: original.receiptId,
queries: [altered],
}),
),
).toThrow("does not match");
const graph = {
format: "codex-security-graph-evidence/v1",
frame_order: "root_first",
metadata: {
clickhouse_query_id: "query-id",
scope: {
cluster: "cluster",
service: "sample",
start: window.start,
end: window.end,
query: {
kind: "pair",
sources: [{ name: "request" }],
sinks: [{ name: "decode" }],
},
},
coverage: { result_complete: true },
limits: { truncated: false },
},
observations: [
{
id: "call",
kind: "sampled_stack",
scope: {
cluster: "cluster",
service: "sample",
container: "app",
observed_image: { name: "registry.example/image", tag: "v1" },
window,
stack_key: "opaque-stack-key",
matches: {
frame_order: "root_first",
rules: [
{
rule_index: 0,
sources: [{ selector_index: 0, frame_index: 0 }],
sinks: [{ selector_index: 0, frame_index: 1 }],
ordered_pairs: [
{
sink: { selector_index: 0, frame_index: 1 },
source_ancestors: [{ selector_index: 0, frame_index: 0 }],
},
],
matched: true,
},
],
matched: true,
},
},
frames: [
{
kind: "function",
name: "request",
attributes: {
name: "request",
language: "javascript",
offset: "",
},
},
{
kind: "function",
name: "decode",
attributes: {
name: "decode",
language: "javascript",
offset: "0",
},
},
],
},
],
};
const resource = await imported(graph);
const [normalized] = normalizeRuntimeObservationQueries(
store,
resource.receiptId,
[sink],
);
const observation = normalized!.groups[0]!.observations[0]!;
expect(observation.frames.map((frame) => frame.name)).toEqual([
"decode",
"request",
]);
expect(observation).toMatchObject({
sinkIndex: 0,
sourceIndex: 1,
sinkMatches: [{ sinkId: "decode", rawIndex: 0 }],
framesTruncated: false,
scope: { image_name: "registry.example/image", image_tag: "v1" },
});
expect(observation.scope).not.toHaveProperty("image_digest");
const unlabeledReceipt = await imported({
...graph,
observations: [
{
...graph.observations[0]!,
scope: {
...graph.observations[0]!.scope,
observed_image: { name: "", tag: "" },
},
},
],
});
expect(
normalizeRuntimeObservationQueries(store, unlabeledReceipt.receiptId, [
sink,
])[0]!.groups[0]!.observations[0]!.scope,
).toEqual({ cluster: "cluster", service: "sample", container: "app" });
const wrapperGraph = structuredClone(graph);
wrapperGraph.metadata.scope.query.sinks[0]!.name = "wrapper";
wrapperGraph.observations[0]!.frames.splice(1, 0, {
kind: "function",
name: "wrapper",
attributes: { name: "wrapper", language: "javascript", offset: "0" },
});
const wrapperReceipt = await imported(wrapperGraph);
expect(
normalizeRuntimeObservationQueries(store, wrapperReceipt.receiptId, [
sink,
])[0]!.groups[0]!.observations[0],
).toMatchObject({
sinkIndex: 1,
sourceIndex: 2,
sinkMatches: [{ sinkId: "decode", rawIndex: 0 }],
});
const orderedGraph = structuredClone(graph);
orderedGraph.observations[0]!.frames.unshift(
structuredClone(orderedGraph.observations[0]!.frames[1]!),
);
const orderedRule = orderedGraph.observations[0]!.scope.matches.rules[0]!;
orderedRule.sources = [{ selector_index: 0, frame_index: 1 }];
orderedRule.sinks = [
{ selector_index: 0, frame_index: 0 },
{ selector_index: 0, frame_index: 2 },
];
orderedRule.ordered_pairs = [
{
sink: { selector_index: 0, frame_index: 2 },
source_ancestors: [{ selector_index: 0, frame_index: 1 }],
},
];
const orderedReceipt = await imported(orderedGraph);
expect(
normalizeRuntimeObservationQueries(store, orderedReceipt.receiptId, [
sink,
])[0]!.groups[0]!.observations[0],
).toMatchObject({
sinkIndex: 0,
sourceIndex: 1,
sinkMatches: [
{ sinkId: "decode", rawIndex: 0 },
{ sinkId: "decode", rawIndex: 2 },
],
});
const aliasGraph = {
...graph,
metadata: {
...graph.metadata,
scope: {
...graph.metadata.scope,
query: {
...graph.metadata.scope.query,
sinks: [{ name: "decode", observed_name: "unverified_alias" }],
},
},
},
observations: [
{
...graph.observations[0]!,
frames: [
graph.observations[0]!.frames[0]!,
{
...graph.observations[0]!.frames[1]!,
name: "unverified_alias",
attributes: {
...graph.observations[0]!.frames[1]!.attributes,
name: "unverified_alias",
},
},
],
},
],
};
const aliasReceipt = await imported(aliasGraph);
expect(
normalizeRuntimeObservationQueries(store, aliasReceipt.receiptId, [
sink,
])[0]!.groups[0]!.observations[0],
).not.toHaveProperty("sinkMatches");
const scopedReceipt = await imported({
...graph,
metadata: {
...graph.metadata,
scope: {
...graph.metadata.scope,
image_tags: ["v1"],
image_digest: "sha256:" + "a".repeat(64),
},
},
observations: [
{
...graph.observations[0]!,
scope: {
...graph.observations[0]!.scope,
image_digest: "sha256:" + "b".repeat(64),
},
},
],
});
const scopedQuery = normalizeRuntimeObservationQueries(
store,
scopedReceipt.receiptId,
[sink],
)[0]!;
const basePacket = livePacket(store);
const scopedWork = stackPacketWorkItems({
...basePacket,
stacks: { ...basePacket.stacks, queries: [scopedQuery] },
})[0]!;
expect(scopedQuery.scope.image_tags).toEqual(["v1"]);
expect(
scopedWork.scopeConflicts.some((conflict) =>
conflict.startsWith("image_digest:"),
),
).toBe(true);
const rulesReceipt = await imported({
...graph,
metadata: {
...graph.metadata,
scope: {
...graph.metadata.scope,
query: {
kind: "pair",
rules: [
{ sources: [{ name: "other" }], sinks: [{ name: "decode" }] },
{ sources: [{ name: "request" }], sinks: [{ name: "decode" }] },
],
},
},
},
observations: [
{
...graph.observations[0]!,
scope: {
...graph.observations[0]!.scope,
matches: {
...graph.observations[0]!.scope.matches,
rules: [
{
...graph.observations[0]!.scope.matches.rules[0]!,
rule_index: 0,
sources: [],
ordered_pairs: [],
matched: false,
},
{
...graph.observations[0]!.scope.matches.rules[0]!,
rule_index: 1,
},
],
},
},
},
],
});
const rulesQuery = normalizeRuntimeObservationQueries(
store,
rulesReceipt.receiptId,
[sink],
)[0]!;
expect(rulesQuery.selectors).toEqual({
sources: [
{ name: "other", rule_index: 0 },
{ name: "request", rule_index: 1 },
],
sinks: [
{ name: "decode", rule_index: 0 },
{ name: "decode", rule_index: 1 },
],
});
expect(rulesQuery.groups[0]!.observations[0]).toMatchObject({
sinkIndex: 0,
sourceIndex: 1,
});
const partialReceipt = await imported({
...graph,
metadata: { ...graph.metadata, coverage: { result_complete: false } },
});
expect(
normalizeRuntimeObservationQueries(store, partialReceipt.receiptId, [
sink,
])[0]!.groups[0]!.truncated,
).toBe(true);
const asyncGraph = {
...graph,
metadata: {
...graph.metadata,
join_basis: "inferred_creator_code",
instance_correlation_verified: false,
scope: {
...graph.metadata.scope,
query: {
kind: "async_parent",
sources: [],
sinks: [{ name: "decode", location: "src/decode.js", line: 7 }],
},
},
},
observations: [
{
...graph.observations[0]!,
frames: [
graph.observations[0]!.frames[0]!,
{
...graph.observations[0]!.frames[1]!,
attributes: {
...graph.observations[0]!.frames[1]!.attributes,
location: "/repo/src/decode.js:7",
},
},
],
},
],
};
const asyncReceipt = await imported(asyncGraph);
const asyncQuery = normalizeRuntimeObservationQueries(
store,
asyncReceipt.receiptId,
[sink],
)[0]!;
expect(asyncQuery.provenance).toEqual({ source: "inferred_creator_code" });
expect(asyncQuery.groups[0]!.observations[0]).toMatchObject({
sinkIndex: 0,
frames: [{ line: 7 }, {}],
});
expect(asyncQuery.groups[0]!.observations[0]).not.toHaveProperty(
"sinkMatches",
);
const invalidQualifier = await imported({
...graph,
metadata: {
...graph.metadata,
scope: {
...graph.metadata.scope,
query: {
...graph.metadata.scope.query,
sinks: [{ name: "decode", frame_type: "python" }],
},
},
},
});
expect(() =>
normalizeRuntimeObservationQueries(store, invalidQualifier.receiptId, [
sink,
]),
).toThrow("selector does not match");
expect(
store.transaction(() =>
recordObservations(store, { receiptId: resource.receiptId }),
),
).toEqual({ workItemIds: ["query-id/capture/call"] });
const empty = {
...graph,
observations: [],
metadata: { ...graph.metadata, status: "no_telemetry" },
};
const emptyReceipt = await imported(empty);
expect(
normalizeRuntimeObservationQueries(store, emptyReceipt.receiptId, [
sink,
])[0]!.groups[0]!.status,
).toBe("no_coverage");
const matched = await imported({
...empty,
metadata: { ...empty.metadata, status: "empty_matches" },
});
expect(
normalizeRuntimeObservationQueries(store, matched.receiptId, [sink])[0]!
.groups[0]!.status,
).toBe("no_match");
} finally {
store.close();
}
});
@@ -0,0 +1,386 @@
import { expect, test } from "bun:test";
import { createHash } from "node:crypto";
import { writeFile } from "node:fs/promises";
import { join } from "node:path";
import { DependencyAttemptStore } from "../src/dependency-attempt-store.js";
import { prepareStackAssessment } from "../src/dependency-stack-assessment.js";
import type { DependencyClaimRecord } from "../src/dependency-stack-claims.js";
import type {
StackPacket,
StackWorkItem,
} from "../src/dependency-stack-packet.js";
import {
isRuntimeReceipt,
prepareRuntimeEvidence,
runtimeEvidenceInputSchema,
saveRuntimeEvidence,
selectRuntimeReceipt,
} from "../src/dependency-stack-runtime-receipts.js";
import { scopedTemporaryDirectory } from "./support/temporary-directories.js";
test("runtime evidence preserves and selects the host-saved original across reopen", async () => {
await using dir = await scopedTemporaryDirectory("runtime-receipt-");
const state = join(dir.path, "attempt.sqlite");
const prepared = await prepareRuntimeEvidence(
{
kind: "runtime",
server: "synthetic-provider",
tool: "inspect",
arguments: { image: "sample:tag" },
scope: { environment: "test" },
result: {
structuredContent: { rows: [{ version: "1.2.3" }] },
content: [{ type: "text", text: '{"status":"complete"}' }],
},
},
dir.path,
);
let store = new DependencyAttemptStore(state);
const saved = saveRuntimeEvidence(store, prepared);
expect(saveRuntimeEvidence(store, prepared)).toEqual(saved);
store.close();
store = new DependencyAttemptStore(state, { create: false });
try {
const selected = selectRuntimeReceipt(store, saved.receiptId, {
receiptId: saved.receiptId,
textBlock: null,
record: ["rows", 0, "version"],
});
expect(selected.result).toBe("1.2.3");
expect(isRuntimeReceipt(selected)).toBe(true);
expect(selected.server).toBe("runtime-import");
expect(selected.origin.tool).toBe("record-evidence");
expect(selected.origin.arguments).toMatchObject({
provenance: "caller_imported",
verification: "unverified",
declaredServer: "synthetic-provider",
declaredTool: "inspect",
});
expect(selected.origin.arguments["arguments"]).toEqual({
image: "sample:tag",
});
expect(
selectRuntimeReceipt(store, saved.receiptId, {
receiptId: saved.receiptId,
textBlock: 0,
record: ["status"],
}).result,
).toBe("complete");
store.set("runtime-receipt", saved.receiptId, {
...prepared.record,
result: "changed",
});
expect(() => selectRuntimeReceipt(store, saved.receiptId)).toThrow(
"original record",
);
} finally {
store.close();
}
});
test("runtime resource verifies exact bytes and retains their original hash", async () => {
await using dir = await scopedTemporaryDirectory("runtime-resource-");
const path = join(dir.path, "resource.json");
const bytes = Buffer.from('{ "rows": [1, 2] }\n');
const sha256 = createHash("sha256").update(bytes).digest("hex");
await writeFile(path, bytes);
const input = {
kind: "runtime",
server: "synthetic",
tool: "read",
resource: { path, sha256 },
};
const prepared = await prepareRuntimeEvidence(input, dir.path);
const store = new DependencyAttemptStore(":memory:");
try {
const { receiptId } = saveRuntimeEvidence(store, prepared);
expect(selectRuntimeReceipt(store, receiptId).originalPayloadSha256).toBe(
sha256,
);
expect(selectRuntimeReceipt(store, receiptId).result).toEqual({
rows: [1, 2],
});
} finally {
store.close();
}
await writeFile(path, "changed");
await expect(prepareRuntimeEvidence(input, dir.path)).rejects.toThrow(
"SHA-256",
);
});
test("runtime imports cannot impersonate captures or provide ambiguous payloads", () => {
expect(
runtimeEvidenceInputSchema.safeParse({
kind: "runtime",
server: "stack-packet",
tool: "inspect",
result: {},
}).success,
).toBe(false);
expect(
runtimeEvidenceInputSchema.safeParse({
kind: "runtime",
server: "stack-observation",
tool: "inspect",
result: {},
}).success,
).toBe(false);
expect(
runtimeEvidenceInputSchema.safeParse({
kind: "runtime",
server: "synthetic",
tool: "inspect",
}).success,
).toBe(false);
expect(
runtimeEvidenceInputSchema.safeParse({
kind: "runtime",
server: "synthetic",
tool: "inspect",
result: null,
}).success,
).toBe(true);
});
test("a runtime-shaped binding selection cannot substitute for this observation's capture receipt", async () => {
const sha = "a".repeat(40);
const inputDigest = "b".repeat(64);
const captureHash = "c".repeat(64);
const imageDigest = "sha256:" + "d".repeat(64);
const binding = {
package: "sample-codec",
version: "3.0.0",
provenance: "synthetic",
frameIndices: [0],
imageDigest,
sourceSha: sha,
};
const observation = {
id: "observation",
stackHash: "stack",
framesTruncated: false,
sinkIndex: 0,
sinkIds: ["sink"],
frames: [{ name: "decode", type: "js" }],
bindings: [binding],
};
const work = {
id: "work",
queryId: "query",
groupId: "group",
status: "observed",
scope: { service: "decoder", image_digest: imageDigest },
queryScope: {},
scopeConflicts: [],
truncated: false,
observation,
} as unknown as StackWorkItem;
const packet = {
manifest: {
inputDigest,
target: { sha },
files: { stacks: { sha256: captureHash } },
},
sinks: {
sinks: [
{
id: "sink",
function: "decode",
package: "sample-codec",
versionScheme: "semver",
affectedVersions: ["<2.0.0"],
preconditions: [],
},
],
},
} as unknown as StackPacket;
const store = new DependencyAttemptStore(":memory:");
try {
const prepared = await prepareRuntimeEvidence(
{
kind: "runtime",
server: "synthetic",
tool: "inspect",
result: { observation: { bindings: [binding] } },
},
process.cwd(),
);
const { receiptId } = saveRuntimeEvidence(store, prepared);
const selected = selectRuntimeReceipt(store, receiptId, {
receiptId,
textBlock: null,
record: ["observation", "bindings", 0],
});
const ref = { id: "binding", revision: 1, hash: "e".repeat(64) };
const claim = {
...ref,
scope: "work",
payload: "fixed version",
dependencies: [],
excerpts: [],
receipts: [selected],
} as DependencyClaimRecord;
const reader = { isUsable: () => true, get: () => claim };
const input = {
workItemId: work.id,
verdict: "ruled_out",
reason: "fixed copy",
supportingClaims: [ref],
remainingQuestions: [],
};
expect(() => prepareStackAssessment(input, work, packet, reader)).toThrow(
"Supply an evidence-backed use",
);
claim.receipts = [
{
...selected,
receiptId: "capture",
server: "stack-packet",
originalPayloadSha256: captureHash,
origin: {
tool: "next",
arguments: { inputDigest, workItemId: work.id },
},
},
];
expect(prepareStackAssessment(input, work, packet, reader).verdict).toBe(
"ruled_out",
);
claim.receipts[0]!.origin.arguments["workItemId"] = "another-work-item";
expect(() => prepareStackAssessment(input, work, packet, reader)).toThrow(
"outside work item",
);
claim.receipts[0]!.origin.arguments["workItemId"] = work.id;
const contradictory = saveRuntimeEvidence(
store,
await prepareRuntimeEvidence(
{
kind: "runtime",
server: "synthetic",
tool: "inspect",
scope: {
service: "decoder",
selector: { service: "different-service" },
},
result: observation,
},
process.cwd(),
),
);
claim.receipts.push(selectRuntimeReceipt(store, contradictory.receiptId));
expect(() => prepareStackAssessment(input, work, packet, reader)).toThrow(
"conflicts with this work item's service",
);
claim.receipts.pop();
const laterWindow = saveRuntimeEvidence(
store,
await prepareRuntimeEvidence(
{
kind: "runtime",
server: "synthetic",
tool: "inspect",
scope: {
window: {
start: "2026-01-01T02:00:00Z",
end: "2026-01-01T03:00:00Z",
},
},
result: { version: "3.0.0" },
},
process.cwd(),
),
);
const timestamped = {
...work,
scope: {
...work.scope,
window: { start: "2026-01-01T00:00:00Z", end: "2026-01-01T04:00:00Z" },
},
observation: { ...observation, observedAt: "2026-01-01T01:00:00Z" },
} as StackWorkItem;
claim.receipts.push(selectRuntimeReceipt(store, laterWindow.receiptId));
expect(() =>
prepareStackAssessment(input, timestamped, packet, reader),
).toThrow("conflicts with this work item's window");
claim.receipts.pop();
const scoped = await prepareRuntimeEvidence(
{
kind: "runtime",
server: "synthetic",
tool: "inspect",
scope: { service: "different-service" },
result: { version: "3.0.0" },
},
process.cwd(),
);
const source = saveRuntimeEvidence(store, scoped);
const imported = selectRuntimeReceipt(store, source.receiptId);
claim.receipts.push(imported);
expect(() => prepareStackAssessment(input, work, packet, reader)).toThrow(
"conflicts with this work item's service",
);
expect(
prepareStackAssessment(
{
...input,
verdict: "unknown",
reason: "The imported version is for a different service.",
remainingQuestions: ["Which workload does this evidence cover?"],
questionChecks: [
{
question: "Which workload does this evidence cover?",
checked: "Compared the service in the import with the capture.",
missingEvidence: "A version record for the captured service.",
claims: [ref],
},
],
},
work,
packet,
reader,
).verdict,
).toBe("unknown");
claim.receipts = [
{
...claim.receipts[0]!,
server: "stack-observation",
origin: {
tool: "next",
arguments: {
inputDigest,
workItemId: work.id,
sourceReceiptId: source.receiptId,
},
},
},
];
expect(() => prepareStackAssessment(input, work, packet, reader)).toThrow(
"original runtime import receipt",
);
claim.receipts.push(imported);
expect(() => prepareStackAssessment(input, work, packet, reader)).toThrow(
"conflicts with this work item's service",
);
const matching = saveRuntimeEvidence(
store,
await prepareRuntimeEvidence(
{
kind: "runtime",
server: "synthetic",
tool: "inspect",
scope: { service: "decoder" },
result: observation,
},
process.cwd(),
),
);
claim.receipts[0]!.origin.arguments["sourceReceiptId"] = matching.receiptId;
claim.receipts[1] = selectRuntimeReceipt(store, matching.receiptId);
expect(prepareStackAssessment(input, work, packet, reader).verdict).toBe(
"ruled_out",
);
} finally {
store.close();
}
});
@@ -8,6 +8,7 @@ import { DependencyAttemptStore } from "../src/dependency-attempt-store.js";
import { lookupDependencyAdvisory } from "../src/dependency-advisory.js";
import { analyzeStackAdvisory } from "../src/dependency-stack-advisory.js";
import { prepareStackPacket } from "../src/stack-packet.js";
import { sqliteDatabaseOpener } from "../src/runtime.js";
import {
prepareStackCheckPacket,
readStackPacket,
@@ -152,6 +153,7 @@ async function sample(
async function startProof(
root: string,
files: Awaited<ReturnType<typeof sample>>,
legacyCapture = false,
) {
const inputs = join(root, "packet"),
state = join(root, "attempt.sqlite");
@@ -163,15 +165,26 @@ async function startProof(
toolRevision: "test",
});
await executeStackRun("init", { state, repo: files.repo, inputs });
if (legacyCapture) {
// Packet-backed attempts created before run next supplied captures had no
// protocol record; their claim receipts identify the read-stacks command.
const db = sqliteDatabaseOpener()(state);
try {
db.exec(
"DELETE FROM records WHERE kind = 'stack-protocol' AND id = 'capture-origin'",
);
} finally {
db.close();
}
}
const call = (command: string, input?: unknown) =>
executeStackRun(command, { state, input });
const { workItem, receiptId } = (await call("next")) as {
workItem: { id: string };
const { workItem, receiptId, rootFirstRawIndices } = (await call("next")) as {
workItem: { id: string; observation: { bindings?: unknown[] } };
receiptId: string;
rootFirstRawIndices: number[];
};
const capture = (await call("read-stacks", { workItemId: workItem.id })) as {
observation: { bindings?: unknown[] };
};
const capture = { ...workItem, receiptId, rootFirstRawIndices };
const write = {
operationId: "proof",
claims: [
@@ -228,6 +241,43 @@ async function startProof(
return { inputs, state, call, capture, claims, write, row };
}
test("an unchanged finalized packet with a legacy read-stacks receipt retains its report bytes", async () => {
await using dir = await scopedTemporaryDirectory("stack-legacy-final-");
const files = await sample(dir.path, true);
const { state, call, claims, row } = await startProof(dir.path, files, true);
const queried = (await call("query-claims", { ids: ["caller"] })) as {
claims: { evidence: { receipts: { origin: { tool: string } }[] } }[];
};
expect(queried.claims[0]!.evidence.receipts[0]!.origin.tool).toBe(
"read-stacks",
);
await call("record-assessments", { items: [row] });
const original = await call("finalize");
expect(original).toMatchObject({ claims });
expect(original).not.toHaveProperty("effectiveInputDigest");
const originalBytes = JSON.stringify(original);
const savedBytes = () => {
const db = sqliteDatabaseOpener()(state);
try {
const statement = db.prepare(
"SELECT value FROM records WHERE kind = 'report' AND id = 'final'",
);
try {
const [row] = statement.all() as { value: string }[];
return row!.value;
} finally {
statement.finalize?.();
}
} finally {
db.close();
}
};
const saved = savedBytes();
expect(JSON.stringify(await readFinalStackReport(state))).toBe(originalBytes);
expect(JSON.stringify(await call("finalize"))).toBe(originalBytes);
expect(savedBytes()).toBe(saved);
});
test("trigger analysis checks quotations and addresses each supplied sink", async () => {
const quote = "The decoder must accept a caller-supplied length.";
const { advisories } = await lookupDependencyAdvisory(
@@ -742,10 +792,7 @@ async function reviewedStackCheck(mode: "correct" | "duplicate" | "exhausted") {
const previous = previousDraft?.assessments[i];
const { workItem, receiptId, openQuestions, advisoryDetails } =
await child("next");
if (previous) {
expect(workItem.id).toBe(previous.workItemId);
await child("read-stacks", { workItemId: workItem.id });
}
if (previous) expect(workItem.id).toBe(previous.workItemId);
expect(openQuestions).toContain(condition);
expect(openQuestions).toContain(trigger);
expect(advisoryDetails[0].body).toBe(trigger);