Compare commits

..
13 changed files with 271 additions and 337 deletions

No files matched your search

@@ -5,6 +5,8 @@ import { expect, it, vi } from "vitest";
import { ArtifactResourceScope } from "../../artifacts/ArtifactResourceScope.js";
import { apiContractSchema } from "../../domain/apiContract/apiContract.js";
import { AnalysisResourceConstraintError } from "../../domain/analysisErrorCore.js";
import { parseEvidence } from "../../domain/evidence.js";
import { projectAnalysisView } from "../../domain/analysisView/analysisView.js";
import { createTestTempDirectory } from "../../../tests/fixtures/temporaryDirectory.js";
import { inspectApiContractEvidence } from "./ApiContractService.js";
import * as readOwner from "./ApiContractRead.js";
@@ -317,3 +319,89 @@ it("cancels a cooperative document traversal after the actual verified file read
await resources.close();
}
});
it.each(["between-paths", "after-projection"] as const)(
"preserves authenticated OpenAPI facts on cancellation %s",
async (stage) => {
const bytes = JSON.stringify({
openapi: "3.1.2",
info: { title: "Cancellation", version: "1" },
paths: { "/first": { get: {} }, "/second": { post: {} } },
});
const { path } = await inputFile(bytes);
const resources = new ArtifactResourceScope();
const controller = new AbortController();
const realParse = parser.parseApiContractSteps;
try {
const baseline = await inspectApiContractEvidence({ path }, resources);
if (!baseline.ok) throw baseline.error;
const complete = apiContractSchema.parse(
baseline.value.normalized_result,
);
const scheduled = vi
.spyOn(parser, "parseApiContractSteps")
.mockImplementationOnce(function* (...args) {
const steps = realParse(...args);
if (stage === "between-paths") {
expect(steps.next().done).toBe(false);
expect(steps.next().done).toBe(false);
setImmediate(() => controller.abort(stage));
return yield* steps;
}
const result = yield* steps;
setImmediate(() => controller.abort(stage));
return result;
});
try {
const result = await inspectApiContractEvidence({ path }, resources, {
signal: controller.signal,
});
if (result.ok) throw new Error("Expected cancellation");
expect(result.error._tag).toBe("AnalysisCancelledError");
expect(result.error.cause).toBe(stage);
const evidence = parseEvidence(result.error.partialObservation);
const retained = apiContractSchema.parse(evidence.normalized_result);
expect(evidence.subject).toEqual(baseline.value.subject);
expect(evidence.parameters).toEqual(baseline.value.parameters);
expect(retained.artifact).toEqual(complete.artifact);
expect(retained.contract_id).toBe(complete.contract_id);
if (stage === "between-paths") {
expect(retained.operations).toEqual(complete.operations.slice(0, 1));
expect(retained.source_coverage.status).toBe("partial");
expect(evidence.evidence_id).not.toBe(baseline.value.evidence_id);
const page = projectAnalysisView(
{
evidenceId: evidence.evidence_id,
operation: evidence.operation,
predicateType: evidence.predicate_type,
normalizedResult: evidence.normalized_result,
limitations: evidence.limitations,
},
{
kind: "api-contract",
collection: "operations",
offset: 0,
limit: 1,
},
);
expect(page).toMatchObject({
ok: true,
value: {
parent_evidence_id: evidence.evidence_id,
items: [{ path: "/first", state: "declared" }],
coverage: { exhausted: true },
source_coverage: { status: "partial" },
},
});
} else {
expect(retained).toEqual(complete);
expect(evidence.evidence_id).toBe(baseline.value.evidence_id);
}
} finally {
scheduled.mockRestore();
}
} finally {
await resources.close();
}
},
);
@@ -11,6 +11,8 @@ import { err, ok, type Result } from "../../domain/result.js";
import {
API_CONTRACT_OPERATION as operation,
API_CONTRACT_PROVIDER,
apiContractSchema,
type ApiContract,
type ApiContractArtifact,
} from "../../domain/apiContract/apiContract.js";
import {
@@ -70,8 +72,32 @@ function* documentSteps(document: unknown, artifact: ApiContractArtifact) {
return yield* parseApiContractSteps(document, artifact);
}
type OpenApiInput = Extract<
InspectApiContractInput,
{ format: "openapi-json" }
>;
const documentEvidence = (input: OpenApiInput, result: ApiContract): Evidence =>
createEvidence(
{ path: input.path, format: "file", sha256: result.artifact.sha256 },
API_CONTRACT_PROVIDER,
{
operation,
predicateType: "rea.api-contract-inventory",
parameters: {
path: input.path,
format: input.format,
max_file_bytes: input.max_file_bytes,
},
result,
confidence: "observed",
limitations: result.limitations,
locations: [{ kind: "artifact-path", path: input.path }],
},
);
const importDocument = async (
input: Extract<InspectApiContractInput, { format: "openapi-json" }>,
input: OpenApiInput,
bytes: Buffer,
sha256: string,
signal?: AbortSignal,
@@ -86,26 +112,16 @@ const importDocument = async (
}),
signal,
);
if (!parsed.ok) return parsed;
const result = parsed.value;
if (!parsed.ok) {
const partial = apiContractSchema.safeParse(
parsed.error.partialObservation,
);
if (partial.success)
parsed.error.partialObservation = documentEvidence(input, partial.data);
return parsed;
}
return completeProviderEvidence(
createEvidence(
{ path: input.path, format: "file", sha256 },
API_CONTRACT_PROVIDER,
{
operation,
predicateType: "rea.api-contract-inventory",
parameters: {
path: input.path,
format: input.format,
max_file_bytes: input.max_file_bytes,
},
result,
confidence: "observed",
limitations: result.limitations,
locations: [{ kind: "artifact-path", path: input.path }],
},
),
documentEvidence(input, parsed.value),
signal,
);
};
+2
View File
@@ -1,6 +1,7 @@
import type { PartialTaskMeasurement } from "./desktop/taskDifficulty.js";
import type { AppleIpsPartialObservation } from "./native/appleIps.js";
import type { PlaywrightTrace } from "./playwrightTrace/playwrightTrace.js";
import type { ApiContract } from "./apiContract/apiContract.js";
import type { GraphqlContract } from "./apiContract/graphqlContract.js";
import type { SavedAnalysisSnapshotPartialObservation } from "./savedAnalysisSnapshot.js";
import type { AnalysisSettingLimit } from "./analysisSettings.js";
@@ -498,6 +499,7 @@ export type AnalysisPartialObservation =
}
| { readonly kind: "unretained-evidence"; readonly evidence: Evidence }
| { readonly kind: "retained-evidence"; readonly evidence_id: string }
| ApiContract
| GraphqlContract
| PlaywrightTrace
| SavedAnalysisSnapshotPartialObservation
+1 -1
View File
@@ -185,7 +185,7 @@ export const projectApiContractView = (
unknowns:
context.source_coverage.status === "partial"
? [
"Unresolved or malformed declarations limit this inventory; query path-item-references and diagnostics for exact source pointers.",
"This inventory is partial. Inspect limitations for coverage and query path-item-references and diagnostics for any retained source pointers.",
]
: [],
};
@@ -3,6 +3,7 @@ import { readFileSync } from "node:fs";
import { expect, it } from "vitest";
import { apiContractSchema, type ApiContractArtifact } from "./apiContract.js";
import { parseApiContractSteps } from "./parseApiContract.js";
import { AnalysisCancelledError } from "../analysisErrorCore.js";
const artifact: ApiContractArtifact = {
path: "/contract.json",
@@ -305,9 +306,39 @@ it("handles 3.2 QUERY and case-sensitive additional methods, diagnosing invalid
it("bounds expanded identities and source pointers before building a giant row", () => {
const result = parse(
document({ [`/${"a".repeat(1_100_000)}`]: { get: {} } }),
document({
"/retained": { get: {} },
[`/${"a".repeat(1_100_000)}`]: { get: {} },
}),
);
expect(result.ok).toBe(false);
if (!result.ok)
expect(result.error._tag).toBe("AnalysisResourceConstraintError");
if (result.ok) throw new Error("Expected a retained-facts refusal");
expect(result.error._tag).toBe("AnalysisResourceConstraintError");
const partial = apiContractSchema.parse(result.error.partialObservation);
expect(partial.operations.map((row) => row.path)).toEqual(["/retained"]);
expect(partial.source_coverage.status).toBe("partial");
});
it("retains an interpreted path when cancellation interrupts traversal", () => {
const input = document({
"/first": { get: { operationId: "first" } },
"/second": { get: { operationId: "second" } },
});
const steps = parseApiContractSteps(input, artifact);
for (let checkpoint = 0; checkpoint < 3; checkpoint++)
expect(steps.next().done).toBe(false);
const cancellation = new AnalysisCancelledError("inspect_api_contract");
const stopped = steps.throw(cancellation);
if (!stopped.done || stopped.value.ok)
throw new Error("Expected cancellation");
expect(stopped.value.error).toBe(cancellation);
const partial = apiContractSchema.parse(cancellation.partialObservation);
const complete = report(input);
expect(partial.operations).toEqual(complete.operations.slice(0, 1));
expect(partial.summary.operation_slots).toBe(1);
expect(partial.source_coverage).toMatchObject({
status: "partial",
path_entries_examined: 1,
});
expect(complete.source_coverage.status).toBe("complete-within-scope");
});
+72 -39
View File
@@ -1,4 +1,5 @@
import {
AnalysisCancelledError,
AnalysisInputError,
AnalysisResourceConstraintError,
AnalysisUnsupportedTargetError,
@@ -316,14 +317,17 @@ function* pathItem(
return ok(undefined);
}
const completedInventory = (
interface ContractReportContext {
readonly openapi: string;
readonly info: ApiContract["info"];
readonly pathsState: ApiContract["source_coverage"]["paths_state"];
examined: number;
}
const contractReport = (
inventory: ContractInventory,
context: {
openapi: string;
info: ApiContract["info"];
pathsState: ApiContract["source_coverage"]["paths_state"];
examined: number;
},
context: ContractReportContext,
incomplete = false,
): ApiContract => {
const artifact = inventory.artifact;
let declared = 0;
@@ -348,7 +352,9 @@ const completedInventory = (
source_coverage: {
scope: "inline-path-operations",
status:
inventory.references.length > 0 || inventory.diagnostics.length > 0
incomplete ||
inventory.references.length > 0 ||
inventory.diagnostics.length > 0
? "partial"
: "complete-within-scope",
paths_state: context.pathsState,
@@ -358,6 +364,11 @@ const completedInventory = (
duplicate_json_members: "last-value-wins",
},
limitations: [
...(incomplete
? [
"Traversal stopped before the inventory was complete. Counts describe the retained rows.",
]
: []),
"Operations are document declarations, not evidence of runtime implementation, reachability or authorization.",
"Only inline operations under paths are inventoried; callbacks, webhooks, components, servers, parameters, schemas, request/response contracts and security are not analyzed.",
"No reference is resolved, including local fragments. A Path Item reference makes its effective operations unknown; adjacent inline slots are preserved without merging referenced definitions.",
@@ -368,6 +379,32 @@ const completedInventory = (
};
};
function* collectPaths(
sourcePaths: Record<string, unknown>,
inventory: ContractInventory,
context: ContractReportContext,
modern: boolean,
): Generator<void, Result<void, AnalysisError>> {
for (const path in sourcePaths) {
if (!Object.hasOwn(sourcePaths, path) || path.startsWith("x-")) continue;
yield;
context.examined++;
// Reserve expanded pointer/path strings before escaping or building a row.
const admitted = inventory.reserve(512 + path.length * 16);
if (!admitted.ok) return admitted;
const pointer = `/paths/${pointerPart(path)}`;
const read = path.startsWith("/")
? yield* pathItem(sourcePaths[path], { inventory, path, pointer, modern })
: inventory.diagnostic(
"invalid-path-key",
pointer,
"A Paths entry must start with /; it was not interpreted as an endpoint.",
);
if (!read.ok) return read;
}
return ok(undefined);
}
/** Enumerate declarations only; never resolve references, servers, callbacks or runtime expressions. */
export function* parseApiContractSteps(
value: unknown,
@@ -417,36 +454,32 @@ export function* parseApiContractSteps(
);
if (!diagnosed.ok) return diagnosed;
}
let examined = 0;
const sourcePaths = paths ?? {};
for (const path in sourcePaths) {
if (!Object.hasOwn(sourcePaths, path) || path.startsWith("x-")) continue;
yield;
examined++;
// Reserve expanded pointer/path strings before escaping or building a row.
const admitted = inventory.reserve(512 + path.length * 16);
if (!admitted.ok) return admitted;
const pointer = `/paths/${pointerPart(path)}`;
const read = path.startsWith("/")
? yield* pathItem(sourcePaths[path], {
inventory,
path,
pointer,
modern: version[1] === "2",
})
: inventory.diagnostic(
"invalid-path-key",
pointer,
"A Paths entry must start with /; it was not interpreted as an endpoint.",
);
if (!read.ok) return read;
const context: ContractReportContext = {
openapi: root.openapi,
info: info.value,
pathsState,
examined: 0,
};
const interrupted = (error: AnalysisError) => {
const retainedRows =
inventory.operations.length +
inventory.references.length +
inventory.diagnostics.length;
if (retainedRows > 0)
error.retainPartialObservation(contractReport(inventory, context, true));
return err(error);
};
try {
const read = yield* collectPaths(
paths ?? {},
inventory,
context,
version[1] === "2",
);
if (!read.ok) return interrupted(read.error);
} catch (cause: unknown) {
if (cause instanceof AnalysisCancelledError) return interrupted(cause);
throw cause;
}
return ok(
completedInventory(inventory, {
openapi: root.openapi,
info: info.value,
pathsState,
examined,
}),
);
return ok(contractReport(inventory, context));
}
@@ -202,9 +202,8 @@ describe("v1 signature block (PKCS#7 SignedData)", () => {
let nested: Uint8Array = Uint8Array.from([0x05, 0x00]);
for (let i = 0; i < 64; i += 1) nested = indefinite(0x30, nested);
expect(errorOf(nested)).toEqual({
kind: "budget-exceeded",
resource: "asn1-depth",
limit: 32,
kind: "malformed-pkcs7",
detail: "ASN.1 nesting exceeds 32 levels.",
});
});
});
@@ -412,42 +411,3 @@ it.each([0, 1])(
});
},
);
it("keeps a valid constructed CMS content depth refusal distinct from malformed input", () => {
let content = tlv(0x04, Uint8Array.of(1));
const block = () =>
signedDataBlock({
certificates: [LEAF_CERTIFICATE],
signerInfos: [signerInfo({ names: LEAF_CERTIFICATE })],
encapsulatedContent: content,
});
expect(decodeV1SignatureBlock(block()).ok).toBe(true);
for (let depth = 0; depth < 40; depth += 1)
content = indefinite(0x24, content);
expect(errorOf(block())).toEqual({
kind: "budget-exceeded",
resource: "asn1-depth",
limit: 32,
});
});
it("preserves the canonical OID byte allowance for a valid unknown digest algorithm", () => {
const algorithm = tlv(
0x06,
Uint8Array.from([0x2a, ...Array<number>(64).fill(0)]),
);
expect(
errorOf(
signedDataBlock({
certificates: [LEAF_CERTIFICATE],
signerInfos: [
signerInfo({
names: LEAF_CERTIFICATE,
digestAlgorithmOid: algorithm,
}),
],
digestAlgorithmOid: algorithm,
}),
),
).toEqual({ kind: "budget-exceeded", resource: "oid-bytes", limit: 64 });
});
+8 -26
View File
@@ -27,10 +27,7 @@ export type ApkV1BlockError =
readonly resource:
| "v1-block-certificates"
| "v1-signer-infos"
| "asn1-elements"
| "asn1-depth"
| "oid-bytes"
| "oid-arc-bytes";
| "asn1-elements";
readonly limit: number;
};
@@ -101,14 +98,11 @@ class ApkBerReader {
return this.#reader.read(at, limit, depth);
} catch (cause: unknown) {
if (!(cause instanceof Asn1BerFailure)) throw cause;
if (cause.constraint !== null)
if (cause.kind === "budget-exceeded")
throw new BlockFailure({
kind: "budget-exceeded",
resource:
cause.constraint.resource === "nodes"
? "asn1-elements"
: "asn1-depth",
limit: cause.constraint.limit,
resource: "asn1-elements",
limit: MAX_ASN1_ELEMENTS,
});
throw malformed(cause.message);
}
@@ -161,13 +155,6 @@ const expectOctetString = (
const oidText = (content: Uint8Array): string => {
const decoded = decodeAsn1Oid(content, { bytes: 64, arcBytes: 64 });
if (decoded.ok) return decoded.value;
if (decoded.error.kind === "byte-limit" || decoded.error.kind === "arc-limit")
throw new BlockFailure({
kind: "budget-exceeded",
resource:
decoded.error.kind === "byte-limit" ? "oid-bytes" : "oid-arc-bytes",
limit: decoded.error.limit,
});
if (decoded.error.kind === "truncated")
throw malformed("object identifier is truncated");
throw malformed(`object identifier of ${String(content.length)} bytes`);
@@ -201,13 +188,6 @@ const integerIdentityContents = (bytes: Uint8Array): Uint8Array => {
return start === 0 ? bytes : bytes.subarray(start);
};
/** Optional identity interpretation may remain unknown while raw certificate identity survives. */
const unavailableIdentityInterpretation = (cause: unknown): boolean =>
cause instanceof BlockFailure &&
(cause.error.kind === "malformed-pkcs7" ||
cause.error.resource === "oid-bytes" ||
cause.error.resource === "oid-arc-bytes");
/**
* RFC 5280 §7.1: RDN order matters; attributes in one SET do not. This
* comparison profile admits ASCII PrintableString/UTF8String for common
@@ -257,7 +237,8 @@ const directoryNameKey = (name: Asn1BerNode): string | null => {
}
return JSON.stringify(rdns);
} catch (cause) {
if (unavailableIdentityInterpretation(cause)) return null;
if (cause instanceof BlockFailure && cause.error.kind === "malformed-pkcs7")
return null;
throw cause;
}
};
@@ -317,7 +298,8 @@ const certificateIdentity = (
subjectKeyIdentifier,
};
} catch (cause: unknown) {
if (unavailableIdentityInterpretation(cause)) return null;
if (cause instanceof BlockFailure && cause.error.kind === "malformed-pkcs7")
return null;
throw cause;
}
};
+8 -14
View File
@@ -11,16 +11,11 @@ export interface Asn1BerNode {
readonly children: readonly Asn1BerNode[];
}
/** The fixed parser allowance that prevented examining more BER structure. */
export interface Asn1BerConstraint {
readonly resource: "nodes" | "depth";
readonly limit: number;
}
export class Asn1BerFailure extends Error {
constructor(
message: string,
readonly constraint: Asn1BerConstraint | null = null,
readonly kind: "malformed" | "budget-exceeded" = "malformed",
readonly limit: number | null = null,
) {
super(message);
this.name = "Asn1BerFailure";
@@ -33,9 +28,10 @@ interface Budget {
const fail = (
message: string,
constraint: Asn1BerConstraint | null = null,
kind: Asn1BerFailure["kind"] = "malformed",
limit: number | null = null,
): never => {
throw new Asn1BerFailure(message, constraint);
throw new Asn1BerFailure(message, kind, limit);
};
/**
@@ -55,14 +51,12 @@ export class Asn1BerReader {
read(offset = 0, end = this.bytes.length, depth = 0): Asn1BerNode {
if (depth > this.maxDepth)
return fail(`ASN.1 nesting exceeds ${String(this.maxDepth)} levels.`, {
resource: "depth",
limit: this.maxDepth,
});
return fail(`ASN.1 nesting exceeds ${String(this.maxDepth)} levels.`);
if (this.#budget.remaining <= 0)
return fail(
`ASN.1 value count exceeds the ${String(this.maxNodes)}-node budget.`,
{ resource: "nodes", limit: this.maxNodes },
"budget-exceeded",
this.maxNodes,
);
this.#budget.remaining -= 1;
if (offset >= end || offset + 2 > end)
+6 -19
View File
@@ -28,12 +28,7 @@ const OID_NAMES: Readonly<Record<string, string>> = {
/** A fixed per-payload decoder allowance and its limit. */
export interface PeCertificateDecodeAllowance {
readonly allowance:
| "asn1-nodes"
| "asn1-depth"
| "decoded-text"
| "oid-bytes"
| "oid-arc-bytes";
readonly allowance: "asn1-nodes" | "decoded-text";
readonly limit: number;
}
@@ -67,15 +62,9 @@ export const readAsn1 = (bytes: Buffer): Asn1BerNode => {
if (cause instanceof Asn1BerFailure)
throw new PeCertificateAsn1Failure(
cause.message,
cause.constraint === null
? null
: {
allowance:
cause.constraint.resource === "nodes"
? "asn1-nodes"
: "asn1-depth",
limit: cause.constraint.limit,
},
cause.kind === "budget-exceeded"
? { allowance: "asn1-nodes", limit: cause.limit ?? ASN1_NODE_BUDGET }
: null,
);
throw cause;
}
@@ -123,14 +112,12 @@ export const decodeOid = (content: Buffer): string => {
case "empty":
return fail("Empty OBJECT IDENTIFIER.");
case "byte-limit":
throw new PeCertificateAsn1Failure(
return fail(
`OBJECT IDENTIFIER exceeds ${String(decoded.error.limit)} bytes.`,
{ allowance: "oid-bytes", limit: decoded.error.limit },
);
case "arc-limit":
throw new PeCertificateAsn1Failure(
return fail(
`OBJECT IDENTIFIER arc exceeds ${String(decoded.error.limit)} bytes.`,
{ allowance: "oid-arc-bytes", limit: decoded.error.limit },
);
case "non-minimal":
return fail("Non-minimal OBJECT IDENTIFIER component.");
@@ -1,132 +0,0 @@
import { writeFile } from "node:fs/promises";
import { join } from "node:path";
import { expect, it } from "vitest";
import { createTestTempDirectory } from "../../../tests/fixtures/temporaryDirectory.js";
import { repeatedCertificateSignedData } from "../../../tests/fixtures/peCertificateAllowance.js";
import {
indefinite,
tlv,
signedDataBlock,
signerInfo,
LEAF_CERTIFICATE,
} from "../../../tests/fixtures/apkSignature/v1SignatureBlock.js";
import { inspectPeCertificatesInputSchema } from "../../domain/native/peCertificates.js";
import {
AnalysisInputError,
AnalysisResourceConstraintError,
} from "../../domain/analysisErrorCore.js";
import { peCertificateFixture } from "./PeCertificates.fixture.js";
import { PeCertificatesProvider } from "./PeCertificatesProvider.js";
const encapsulated = (depth: number): Buffer => {
let content = tlv(0x04, Uint8Array.of(1));
for (let level = 0; level < depth; level += 1)
content = indefinite(0x24, content);
return Buffer.from(
signedDataBlock({
certificates: [LEAF_CERTIFICATE],
signerInfos: [signerInfo({ names: LEAF_CERTIFICATE })],
encapsulatedContent: content,
}),
);
};
const inspect = async (payload: Buffer) => {
const path = join(
await createTestTempDirectory("rea-pe-decoder-allowance-"),
"inert.exe",
);
await writeFile(path, peCertificateFixture(false, payload));
const provider = new PeCertificatesProvider();
try {
return await provider.inspect(
inspectPeCertificatesInputSchema.parse({ path }),
);
} finally {
await provider.close();
}
};
it.each([
{
name: "depth",
payload: () => encapsulated(40),
limits: { max_asn1_depth: 32 },
description: "32 nesting levels",
},
{
name: "nodes",
payload: () => repeatedCertificateSignedData(600),
limits: { max_asn1_values: 16_384 },
description: "16384 values",
},
{
name: "text",
payload: () => repeatedCertificateSignedData(350),
limits: { max_decoded_text_bytes: 65_536 },
description: "65536 bytes",
},
])(
"reports the fixed $name allowance with its own resource and recovery",
async ({ payload, limits, description }) => {
const result = await inspect(payload());
expect(result.ok).toBe(false);
if (result.ok) throw new Error("Expected decoder refusal");
expect(result.error).toBeInstanceOf(AnalysisResourceConstraintError);
if (!(result.error instanceof AnalysisResourceConstraintError))
throw result.error;
expect(result.error.reportedLimits).toEqual(limits);
expect(result.error.retryable).toBe(false);
expect(result.error.fixedAllowance?.name).toContain(description);
expect(result.error.fixedAllowance?.name).toContain("no runtime override");
},
);
it("accepts shallower valid BER and keeps malformed BER an input failure", async () => {
expect((await inspect(encapsulated(1))).ok).toBe(true);
const malformed = await inspect(Buffer.from([0x30, 0x03, 0x05]));
expect(malformed.ok).toBe(false);
if (malformed.ok) throw new Error("Expected malformed input refusal");
expect(malformed.error).toBeInstanceOf(AnalysisInputError);
});
it.each([
{
name: "bytes",
content: Buffer.from([0x2a, ...Array<number>(256).fill(0)]),
limits: { max_oid_bytes: 256 },
},
{
name: "arc bytes",
content: Buffer.from([0x2a, 0x81, ...Array<number>(31).fill(0x80), 0]),
limits: { max_oid_arc_bytes: 32 },
},
])(
"preserves the canonical OID $name allowance in a valid CMS algorithm",
async ({ content, limits }) => {
const algorithm = tlv(0x06, content);
const result = await inspect(
Buffer.from(
signedDataBlock({
certificates: [LEAF_CERTIFICATE],
signerInfos: [
signerInfo({
names: LEAF_CERTIFICATE,
digestAlgorithmOid: algorithm,
}),
],
digestAlgorithmOid: algorithm,
}),
),
);
expect(result.ok).toBe(false);
if (result.ok) throw new Error("Expected OID allowance refusal");
expect(result.error).toBeInstanceOf(AnalysisResourceConstraintError);
if (!(result.error instanceof AnalysisResourceConstraintError))
throw result.error;
expect(result.error.reportedLimits).toEqual(limits);
expect(result.error.retryable).toBe(false);
expect(result.error.fixedAllowance?.name).toContain("OBJECT IDENTIFIER");
expect(result.error.fixedAllowance?.name).toContain("no runtime override");
},
);
+11 -27
View File
@@ -105,40 +105,24 @@ const inputBudgetRemediation = (
const decoderAllowanceFailure = (
cause: PeCertificateAsn1Failure,
{ allowance, limit }: PeCertificateDecodeAllowance,
) => {
const selected = {
"asn1-nodes": {
limits: { max_asn1_values: limit },
description: `The PE certificate ASN.1 allowance of ${String(limit)} values per PKCS#7 payload (this release has no runtime override)`,
},
"asn1-depth": {
limits: { max_asn1_depth: limit },
description: `The PE certificate ASN.1 allowance of ${String(limit)} nesting levels per PKCS#7 payload (this release has no runtime override)`,
},
"decoded-text": {
limits: { max_decoded_text_bytes: limit },
description: `The PE certificate decoded-text allowance of ${String(limit)} bytes per PKCS#7 payload (this release has no runtime override)`,
},
"oid-bytes": {
limits: { max_oid_bytes: limit },
description: `The PE certificate OBJECT IDENTIFIER allowance of ${String(limit)} bytes per OID (this release has no runtime override)`,
},
"oid-arc-bytes": {
limits: { max_oid_arc_bytes: limit },
description: `The PE certificate OBJECT IDENTIFIER allowance of ${String(limit)} bytes per base-128 arc (this release has no runtime override)`,
},
}[allowance];
return new AnalysisResourceConstraintError(
) =>
new AnalysisResourceConstraintError(
OPERATION,
"memory",
`PKCS#7 signedData exceeds a fixed decoder allowance: ${cause.message}`,
selected.limits,
allowance === "asn1-nodes"
? { max_asn1_values: limit }
: { max_decoded_text_bytes: limit },
{
cause,
...fixedAllowanceOptions(selected.description, "parser"),
...fixedAllowanceOptions(
allowance === "asn1-nodes"
? `The PE certificate ASN.1 allowance of ${String(limit)} values per PKCS#7 payload (this release has no runtime override)`
: `The PE certificate decoded-text allowance of ${String(limit)} bytes per PKCS#7 payload (this release has no runtime override)`,
"parser",
),
},
);
};
const peCertificatesFailurePrimary = (
facts: ArtifactFilePrimaryFacts,
+3 -14
View File
@@ -230,15 +230,12 @@ export interface SignerInfoSpec {
* from the certificate named by `names`.
*/
readonly serial?: Uint8Array;
/** Complete digest algorithm OID TLV, including bounded-parser fixtures. */
readonly digestAlgorithmOid?: Uint8Array;
}
export const signerInfo = ({
names,
signature,
serial,
digestAlgorithmOid,
}: SignerInfoSpec): Uint8Array =>
tlv(
0x30,
@@ -247,7 +244,7 @@ export const signerInfo = ({
names,
serial === undefined ? undefined : tlv(0x02, serial),
),
tlv(0x30, digestAlgorithmOid ?? oid(OID_SHA256)),
algorithm(OID_SHA256),
algorithm(OID_ECDSA_SHA256),
signature ?? tlv(0x04, Uint8Array.from([1, 2, 3])),
);
@@ -257,8 +254,6 @@ export const signedDataBlock = (options: {
readonly certificates: readonly Uint8Array[];
readonly signerInfos: readonly Uint8Array[];
readonly contentType?: string;
readonly encapsulatedContent?: Uint8Array;
readonly digestAlgorithmOid?: Uint8Array;
}): Uint8Array =>
tlv(
0x30,
@@ -268,14 +263,8 @@ export const signedDataBlock = (options: {
tlv(
0x30,
integer(1),
tlv(0x31, tlv(0x30, options.digestAlgorithmOid ?? oid(OID_SHA256))),
tlv(
0x30,
oid("1.2.840.113549.1.7.1"),
...(options.encapsulatedContent === undefined
? []
: [tlv(0xa0, options.encapsulatedContent)]),
),
tlv(0x31, algorithm(OID_SHA256)),
tlv(0x30, oid("1.2.840.113549.1.7.1")),
tlv(0xa0, ...options.certificates),
tlv(0x31, ...options.signerInfos),
),