mirror of
https://github.com/morluto/rea.git
synced 2026-12-01 11:01:11 +00:00
feat(artifacts): inventory standalone Unix ar archives offline (#15224)
* feat(artifacts): inventory standalone Unix ar archives offline * test(artifacts): align standalone ar assertions and comparison docs * fix(artifacts): preserve ar names, admission and permission uncertainty * chore(contracts): refresh ar admission schema summaries * fix(artifacts): handle GNU thin references and exact name budgets * perf(artifacts): cache ar name-table observations --------- Co-authored-by: Vincent Koc <vincentkoc@ieee.org>
This commit is contained in:
1 parent
4886a406f9
commit
bd6ff678c4
33 files changed
+1410
-133
No files matched your search
@@ -623,6 +623,11 @@ export const documentationSections = [
|
||||
source: "guides/firmware/n64-roms.md",
|
||||
route: "/n64-roms",
|
||||
},
|
||||
{
|
||||
text: "Unix ar archives",
|
||||
source: "guides/artifacts/ar-archives.md",
|
||||
route: "/ar-archives",
|
||||
},
|
||||
{
|
||||
text: "WeChat mini-program wxapkg archives",
|
||||
source: "wxapkg.md",
|
||||
|
||||
@@ -154,6 +154,7 @@ The [REA website](https://rea.tools/) has worked examples and product pages.
|
||||
- [macOS flat installer packages](macos-pkg.md)
|
||||
- [ISO 9660 disc images](guides/firmware/iso9660-images.md)
|
||||
- [tar and gzip-compressed tar archives](tar-archives.md)
|
||||
- [Unix ar archives](guides/artifacts/ar-archives.md)
|
||||
- [Nintendo Switch NSO and NRO executables](guides/firmware/switch-executables.md)
|
||||
- [GPU asset headers: DDS, GLB, KTX and KTX2](gpu-asset-headers.md)
|
||||
- [Media asset headers: Ogg Opus, RIFF/XMA2, Bink 2 and Vulkan pipeline cache](media-asset-headers.md)
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
# Unix ar archives
|
||||
|
||||
Use `rea inspect-artifact libexample.a --json` or MCP `inspect_artifact` to
|
||||
inventory a local Unix ar archive. Recognition uses the archive signature.
|
||||
Debian packages keep their dedicated inspection route.
|
||||
|
||||
The inventory records member names, byte ranges and the mode, owner IDs and
|
||||
modification time recorded in the header. GNU name-table references and BSD
|
||||
inline names are supported. Symbol tables are counted separately. For GNU thin
|
||||
archives, the original path and recorded size appear as declaration metadata.
|
||||
REA does not open referenced files. Flattened GNU thin archives also retain
|
||||
the nested member offset in `nested_member_offset`, without opening the nested
|
||||
archive.
|
||||
|
||||
A malformed or truncated member leaves earlier observations available with
|
||||
unknown coverage. Blank or malformed permissions remain unknown, including
|
||||
whether a member is executable.
|
||||
|
||||
Reader admission uses `artifact_limits.ar`: `header_count` (100,000 by default,
|
||||
including symbol and name-table headers), `name_bytes` (4 KiB per extended name),
|
||||
`name_table_bytes` (4 MiB per GNU table), and `retained_name_bytes` (8 MiB for
|
||||
source names and logical paths, including repeated references). The session
|
||||
setting `artifact.member_count`, changed with `update_analysis_settings`, backs
|
||||
`header_count` unless the call explicitly selects it.
|
||||
|
||||
A limit failure retains earlier observations and names the effective control
|
||||
and required increase. Retry the same complete archive with the named
|
||||
`artifact_limits.ar` field raised; paging does not raise reader admission.
|
||||
|
||||
```sh
|
||||
rea inspect-artifact libexample.a --artifact-limits '{"ar":{"header_count":200000}}' --json
|
||||
```
|
||||
|
||||
GNU thin nested-member references follow the [Binutils archive reader](https://gnu.googlesource.com/binutils-gdb/+/afbe444945daaf102c438da2e513109e6a6a5907/bfd/archive.c).
|
||||
@@ -796,7 +796,7 @@ editable setting or active worker telemetry.
|
||||
## Artifact reader admission
|
||||
|
||||
`inspect_artifact` and `extract_artifact` accept `bun`, `dotnet_bundle`,
|
||||
`node_sea`, `godot`, `iso9660`, `deno`, `wxapkg`, `tar` and
|
||||
`node_sea`, `godot`, `iso9660`, `deno`, `wxapkg`, `ar`, `tar` and
|
||||
`android_sparse_image`, `android_super_image`, `android_vbmeta`,
|
||||
`media_asset`, `android_dtbo` and `kubernetes_audit_log` groups in
|
||||
`artifact_limits`. Their controls apply when
|
||||
@@ -805,7 +805,7 @@ assert the format is present. Unsupported keys are rejected. Each group follows
|
||||
one domain-owned default policy. See [.NET bundles](../dotnet-bundles.md),
|
||||
[Node SEA](../node-sea.md), [Godot PCK](../godot-pck.md),
|
||||
[Bun standalone](../bun-standalone.md), [Deno compile](../deno-standalone.md),
|
||||
[wxapkg](../wxapkg.md), [tar](../tar-archives.md),
|
||||
[wxapkg](../wxapkg.md), [ar](../guides/artifacts/ar-archives.md), [tar](../tar-archives.md),
|
||||
[Android sparse images](../guides/firmware/android-sparse-image.md),
|
||||
[Android vbmeta](../guides/firmware/android-vbmeta.md),
|
||||
[media asset headers](../media-asset-headers.md),
|
||||
@@ -846,7 +846,7 @@ runtime override. See
|
||||
`artifact.member_count` (launch seed `REA_ARTIFACT_MEMBER_COUNT`, default
|
||||
100,000, range 1 to 2,147,483,647) is the session default for the per-call
|
||||
member counts `bun.module_count`, `dotnet_bundle.entry_count`,
|
||||
`node_sea.asset_count`, `deno.vfs_entries`, and `zip.member_count`. An explicit `artifact_limits`
|
||||
`node_sea.asset_count`, `deno.vfs_entries`, `zip.member_count`, and `ar.header_count`. An explicit `artifact_limits`
|
||||
field wins for that call; otherwise the runtime override, then the launch
|
||||
seed, then the default applies (see [precedence](#precedence-and-lifetime)).
|
||||
A refusal at one of those fields also reports `details.limit` as that
|
||||
|
||||
@@ -2160,8 +2160,8 @@ when both are omitted, storage is not compared.
|
||||
(`pyinstaller-entry`), Node SEA members (`node-sea-entry`),
|
||||
UBI volumes (`ubi-volume`), ESP image segments (`esp-image-segment`), DfuSe elements (`dfuse-element`),
|
||||
ESP flash partitions (`esp-flash-partition`), Nintendo DS ROM members
|
||||
(`nds-entry`), FIT images (`fit-image`) and tar
|
||||
members (`tar-entry`)<!-- END:compare-artifacts:compared-format-metadata-kinds -->;
|
||||
(`nds-entry`), FIT images (`fit-image`), Unix ar members (`ar-entry`)
|
||||
and tar members (`tar-entry`)<!-- END:compare-artifacts:compared-format-metadata-kinds -->;
|
||||
each format's guide names the compared fields. A changed declaration is a
|
||||
metadata change, including when content is unavailable. A declaration that
|
||||
only one side records, or that the other side records as another kind, is
|
||||
|
||||
@@ -14,6 +14,7 @@ The table lists what REA returns for each target and which tools or host it requ
|
||||
| IL2CPP metadata | Unity global-metadata.dat assembly images, type and method names and index ranges | Built-in static decoding of versions 24, 27, 29, 31 and 39; no Unity required |
|
||||
| Godot PCK | Archive inventory and extraction, original header/directory facts and selected content identities | Built-in static formats 2, 3 and 4; no Godot required |
|
||||
| tar archives | Member inventory and extraction for stored and gzip tar, including `.unitypackage` | Built-in static ustar, pax and GNU headers; [tar archives](../tar-archives.md) |
|
||||
| Unix ar archives | Member inventory for GNU and BSD archives, including thin archive references | Built-in static reader; [Unix ar archives](../guides/artifacts/ar-archives.md) |
|
||||
| Switch NSO/NRO | Module id, segment layout and hashes, NRO icon/NACP/RomFS ranges; LZ4 segments decompressed | Built-in static header parsing; [Switch executables](../guides/firmware/switch-executables.md) |
|
||||
| GPU asset headers | DDS (incl. DX10), GLB, KTX and KTX2 header facts and declared regions; payloads not decoded | Built-in static header parsing; [GPU asset headers](../gpu-asset-headers.md) |
|
||||
| Media asset headers | Ogg Opus, RIFF/XMA2, Bink 2 and Vulkan pipeline-cache header facts and declared regions; payloads not decoded | Built-in static header parsing; [media asset headers](../media-asset-headers.md) |
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"schemas": {
|
||||
"input compact": "88b731a5247e5d38",
|
||||
"input compact": "dbac54e26f05641b",
|
||||
"output compact": "fc6c5d5a78a47254"
|
||||
},
|
||||
"patterns": {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"schemas": {
|
||||
"input compact": "3f04e4e6b4922b28",
|
||||
"input compact": "391b1003435bab50",
|
||||
"output compact": "fc6c5d5a78a47254"
|
||||
},
|
||||
"patterns": {
|
||||
|
||||
@@ -130,6 +130,7 @@ const TARGETS: TargetFixtures = {
|
||||
unityfs: { ...archive, format: "unityfs" },
|
||||
wxapkg: { ...archive, format: "wxapkg" },
|
||||
tar: { ...archive, format: "tar" },
|
||||
ar: { ...archive, format: "ar" },
|
||||
dds: { ...archive, format: "dds" },
|
||||
glb: { ...archive, format: "glb" },
|
||||
ktx: { ...archive, format: "ktx" },
|
||||
|
||||
@@ -0,0 +1,361 @@
|
||||
import { buffer } from "node:stream/consumers";
|
||||
import { expect, it } from "vitest";
|
||||
import { createTestTempFile } from "../../tests/fixtures/temporaryDirectory.js";
|
||||
import { parseBinaryTarget } from "../application/BinaryTargetResolver.js";
|
||||
import {
|
||||
DEFAULT_AR_READER_LIMITS,
|
||||
type ArReaderLimits,
|
||||
} from "../domain/artifactReaderLimits.js";
|
||||
import { AR_MAGIC } from "../domain/arFormat.js";
|
||||
import type {
|
||||
ArtifactEntry,
|
||||
ArtifactReaderTraversal,
|
||||
} from "../resources/index.js";
|
||||
import { ArArtifactReader } from "./ArArtifactReader.js";
|
||||
|
||||
const member = (
|
||||
name: string,
|
||||
body: string,
|
||||
size = Buffer.byteLength(body),
|
||||
): Buffer => {
|
||||
const header = [
|
||||
name.padEnd(16),
|
||||
"0".padEnd(12),
|
||||
"10".padEnd(6),
|
||||
"20".padEnd(6),
|
||||
"100644".padEnd(8),
|
||||
String(size).padEnd(10),
|
||||
"`\n",
|
||||
].join("");
|
||||
const contents = Buffer.from(body);
|
||||
return Buffer.concat([
|
||||
Buffer.from(header),
|
||||
contents,
|
||||
contents.length % 2 === 0 ? Buffer.alloc(0) : Buffer.from("\n"),
|
||||
]);
|
||||
};
|
||||
|
||||
const inspect = async (bytes: Buffer, limits?: ArReaderLimits) => {
|
||||
const path = await createTestTempFile("rea-ar-", "archive.bin", bytes);
|
||||
const reader = new ArArtifactReader(path, undefined, limits);
|
||||
const entries: ArtifactEntry[] = [];
|
||||
const coverage: ArtifactReaderTraversal[] = [];
|
||||
try {
|
||||
let failure: unknown;
|
||||
try {
|
||||
for await (const entry of reader.entries(undefined, {
|
||||
onCoverage: (value) => coverage.push(value),
|
||||
}))
|
||||
entries.push(entry);
|
||||
} catch (cause) {
|
||||
failure = cause;
|
||||
}
|
||||
const contents = new Map<string, string>();
|
||||
for (const entry of entries) {
|
||||
if (entry.kind === "file")
|
||||
contents.set(
|
||||
entry.path,
|
||||
(await buffer(await reader.open(entry))).toString(),
|
||||
);
|
||||
else
|
||||
await expect(reader.open(entry)).rejects.toThrow(
|
||||
"no physical byte range",
|
||||
);
|
||||
}
|
||||
return {
|
||||
entries,
|
||||
failure,
|
||||
coverage,
|
||||
contents,
|
||||
metadata: reader.formatMetadata(),
|
||||
path,
|
||||
};
|
||||
} finally {
|
||||
await reader.close();
|
||||
}
|
||||
};
|
||||
|
||||
it("reads GNU and BSD long names and aligns stored member ranges", async () => {
|
||||
const result = await inspect(
|
||||
Buffer.concat([
|
||||
AR_MAGIC,
|
||||
member("/", "index"),
|
||||
member("//", "very-long-gnu-name.o/\n"),
|
||||
member("/0", "one"),
|
||||
member("#1/20", "very-long-bsd-name.otwo"),
|
||||
member("last.o/", "three"),
|
||||
]),
|
||||
);
|
||||
expect([...result.contents]).toEqual([
|
||||
["very-long-gnu-name.o", "one"],
|
||||
["very-long-bsd-name.o", "two"],
|
||||
["last.o", "three"],
|
||||
]);
|
||||
expect(result.metadata).toEqual({
|
||||
kind: "ar",
|
||||
archive_kind: "regular",
|
||||
symbol_tables: 1,
|
||||
});
|
||||
expect(result.entries[0]?.formatMetadata).toMatchObject({
|
||||
mode: 0o100644,
|
||||
uid: 10,
|
||||
gid: 20,
|
||||
member_bytes: 3,
|
||||
});
|
||||
expect(result.coverage).toEqual([{ status: "complete", limitations: [] }]);
|
||||
expect(await parseBinaryTarget(result.path)).toMatchObject({
|
||||
ok: true,
|
||||
value: { kind: "archive", format: "ar" },
|
||||
});
|
||||
});
|
||||
|
||||
it("preserves earlier entries when a later member is truncated", async () => {
|
||||
const result = await inspect(
|
||||
Buffer.concat([
|
||||
AR_MAGIC,
|
||||
member("first.o/", "ok"),
|
||||
member("truncated.o/", "x", 30),
|
||||
]),
|
||||
);
|
||||
expect([...result.contents]).toEqual([["first.o", "ok"]]);
|
||||
expect(result.coverage).toMatchObject([
|
||||
{
|
||||
status: "unknown",
|
||||
limitations: [expect.stringContaining("Truncated ar member")],
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("keeps thin external paths as declarations without opening their files", async () => {
|
||||
const result = await inspect(
|
||||
Buffer.concat([
|
||||
Buffer.from("!<thin>\n"),
|
||||
member("//", "../missing/long-object-name.o/\n"),
|
||||
member("/0", "", 11),
|
||||
member("/0", "", 19),
|
||||
]),
|
||||
);
|
||||
expect(result.contents.size).toBe(0);
|
||||
expect(result.metadata?.archive_kind).toBe("thin");
|
||||
expect(result.coverage[0]?.status).toBe("complete");
|
||||
expect(result.entries.map((entry) => entry.formatMetadata)).toMatchObject([
|
||||
{
|
||||
external: true,
|
||||
source_path: "../missing/long-object-name.o",
|
||||
member_bytes: 11,
|
||||
},
|
||||
{
|
||||
external: true,
|
||||
source_path: "../missing/long-object-name.o",
|
||||
member_bytes: 19,
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("preserves Debian package recognition ahead of generic ar", async () => {
|
||||
const path = await createTestTempFile(
|
||||
"rea-ar-",
|
||||
"package.bin",
|
||||
Buffer.concat([AR_MAGIC, member("debian-binary", "2.0\n")]),
|
||||
);
|
||||
expect(await parseBinaryTarget(path)).toMatchObject({
|
||||
ok: true,
|
||||
value: { format: "deb" },
|
||||
});
|
||||
});
|
||||
|
||||
it("preserves filename spaces and treats interior NULs as unreadable", async () => {
|
||||
const result = await inspect(
|
||||
Buffer.concat([
|
||||
AR_MAGIC,
|
||||
member(" leading.o/", "a"),
|
||||
member("space.o /", "b"),
|
||||
member("//", " long-name.o /\n"),
|
||||
member("/0", "c"),
|
||||
member("#1/10", "bsd.o \0\0\0\0d"),
|
||||
member("#1/3", "a\0be"),
|
||||
]),
|
||||
);
|
||||
expect([...result.contents]).toEqual([
|
||||
[" leading.o", "a"],
|
||||
["space.o ", "b"],
|
||||
[" long-name.o ", "c"],
|
||||
["bsd.o ", "d"],
|
||||
]);
|
||||
expect(result.coverage[0]?.status).toBe("unknown");
|
||||
});
|
||||
|
||||
it("does not classify a leading-space debian-binary as Debian", async () => {
|
||||
const result = await inspect(
|
||||
Buffer.concat([AR_MAGIC, member(" debian-binary/", "2.0\n")]),
|
||||
);
|
||||
expect(await parseBinaryTarget(result.path)).toMatchObject({
|
||||
ok: true,
|
||||
value: { format: "ar" },
|
||||
});
|
||||
});
|
||||
|
||||
it.each(["", "garbage"])(
|
||||
"keeps unknown executable permission for mode %s",
|
||||
async (mode) => {
|
||||
const bytes = member("file.o/", "data");
|
||||
bytes.write(mode.padEnd(8), 40, "ascii");
|
||||
const result = await inspect(Buffer.concat([AR_MAGIC, bytes]));
|
||||
expect(result.entries[0]).toMatchObject({
|
||||
executable: null,
|
||||
formatMetadata: { mode: null },
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
it.each([
|
||||
{
|
||||
field: "header_count",
|
||||
exact: 2,
|
||||
prefix: 1,
|
||||
parts: [member("one/", "a"), member("two/", "b")],
|
||||
},
|
||||
{
|
||||
field: "name_bytes",
|
||||
exact: 6,
|
||||
prefix: 1,
|
||||
parts: [member("one/", "a"), member("#1/6", "long.ob")],
|
||||
},
|
||||
{
|
||||
field: "name_bytes",
|
||||
exact: 6,
|
||||
prefix: 0,
|
||||
parts: [member("//", "long.o/\n"), member("/0", "b")],
|
||||
},
|
||||
{
|
||||
field: "name_table_bytes",
|
||||
exact: 8,
|
||||
prefix: 1,
|
||||
parts: [member("one/", "a"), member("//", "long.o/\n"), member("/0", "b")],
|
||||
},
|
||||
{
|
||||
field: "retained_name_bytes",
|
||||
exact: 24,
|
||||
prefix: 1,
|
||||
parts: [member("//", "long.o/\n"), member("/0", "b"), member("/0", "c")],
|
||||
},
|
||||
] as const)(
|
||||
"reports and recovers the exact $field admission",
|
||||
async ({ field, exact, prefix, parts }) => {
|
||||
const bytes = Buffer.concat([AR_MAGIC, ...parts]);
|
||||
for (const allowance of [exact, exact + 1]) {
|
||||
const result = await inspect(bytes, {
|
||||
...DEFAULT_AR_READER_LIMITS,
|
||||
[field]: allowance,
|
||||
});
|
||||
expect(result.failure).toBeUndefined();
|
||||
expect(result.coverage[0]?.status).toBe("complete");
|
||||
}
|
||||
const refused = await inspect(bytes, {
|
||||
...DEFAULT_AR_READER_LIMITS,
|
||||
[field]: exact - 1,
|
||||
});
|
||||
expect(refused.failure).toMatchObject({
|
||||
reason: "limit",
|
||||
readerLimit: {
|
||||
parameter: `artifact_limits.ar.${field}`,
|
||||
effective_value: exact - 1,
|
||||
required_value: exact,
|
||||
},
|
||||
});
|
||||
expect(refused.entries).toHaveLength(prefix);
|
||||
expect(refused.coverage[0]?.status).toBe("unknown");
|
||||
},
|
||||
);
|
||||
|
||||
it("preserves distinct nested thin-archive declarations without opening either archive", async () => {
|
||||
const result = await inspect(
|
||||
Buffer.concat([
|
||||
Buffer.from("!<thin>\n"),
|
||||
member("//", "missing-archive.a/\n"),
|
||||
member("/0:84", "", 123),
|
||||
member("/0:208", "", 456),
|
||||
]),
|
||||
);
|
||||
expect(result.entries.map((entry) => entry.formatMetadata)).toMatchObject([
|
||||
{
|
||||
source_path: "missing-archive.a",
|
||||
nested_member_offset: 84,
|
||||
member_bytes: 123,
|
||||
external: true,
|
||||
},
|
||||
{
|
||||
source_path: "missing-archive.a",
|
||||
nested_member_offset: 208,
|
||||
member_bytes: 456,
|
||||
external: true,
|
||||
},
|
||||
]);
|
||||
expect(result.contents.size).toBe(0);
|
||||
expect(result.coverage[0]?.status).toBe("complete");
|
||||
});
|
||||
|
||||
it.each([false, true])(
|
||||
"keeps a table-referenced reserved filename as a member (thin=%s)",
|
||||
async (thin) => {
|
||||
const result = await inspect(
|
||||
Buffer.concat([
|
||||
thin ? Buffer.from("!<thin>\n") : AR_MAGIC,
|
||||
member("//", "__.SYMDEF/\n"),
|
||||
member("/0", thin ? "" : "data", 4),
|
||||
member("next.o/", thin ? "" : "next", 4),
|
||||
]),
|
||||
);
|
||||
expect(result.entries).toHaveLength(2);
|
||||
expect(result.entries[0]?.formatMetadata).toMatchObject({
|
||||
source_path: "__.SYMDEF",
|
||||
external: thin,
|
||||
});
|
||||
expect(result.metadata?.symbol_tables).toBe(0);
|
||||
expect(result.coverage[0]?.status).toBe("complete");
|
||||
},
|
||||
);
|
||||
|
||||
it("reports the complete GNU name length so one suggested increase recovers", async () => {
|
||||
const name = "long-name".repeat(20);
|
||||
const archive = Buffer.concat([
|
||||
AR_MAGIC,
|
||||
member("//", `${name}/\n`),
|
||||
member("/0", "data"),
|
||||
]);
|
||||
const refused = await inspect(archive, {
|
||||
...DEFAULT_AR_READER_LIMITS,
|
||||
name_bytes: 8,
|
||||
});
|
||||
expect(refused.failure).toMatchObject({
|
||||
readerLimit: { required_value: Buffer.byteLength(name) },
|
||||
});
|
||||
const admitted = await inspect(archive, {
|
||||
...DEFAULT_AR_READER_LIMITS,
|
||||
name_bytes: Buffer.byteLength(name),
|
||||
});
|
||||
expect(admitted.failure).toBeUndefined();
|
||||
expect([...admitted.contents.keys()]).toEqual([name]);
|
||||
});
|
||||
|
||||
it("retains malformed-name coverage and replaces cached table facts with each new table", async () => {
|
||||
const result = await inspect(
|
||||
Buffer.concat([
|
||||
AR_MAGIC,
|
||||
member("//", "unterminated"),
|
||||
...Array.from({ length: 512 }, () => member("/0", "")),
|
||||
member("//", "first-name.o/\n"),
|
||||
member("/0", "one"),
|
||||
member("//", "other-name.o/\n"),
|
||||
member("/0", "two"),
|
||||
]),
|
||||
);
|
||||
expect([...result.contents]).toEqual([
|
||||
["first-name.o", "one"],
|
||||
["other-name.o", "two"],
|
||||
]);
|
||||
expect(result.coverage[0]?.status).toBe("unknown");
|
||||
expect(result.coverage[0]?.limitations).toContain(
|
||||
"512 ar member name(s) could not be decoded or represented as safe paths.",
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,264 @@
|
||||
import {
|
||||
DEFAULT_AR_READER_LIMITS,
|
||||
type ArReaderLimits,
|
||||
} from "../domain/artifactReaderLimits.js";
|
||||
import { Budget } from "../domain/budget.js";
|
||||
import {
|
||||
AR_HEADER_BYTES,
|
||||
AR_MAGIC,
|
||||
arArchiveKind,
|
||||
readArHeader,
|
||||
AR_SYMBOL_NAMES,
|
||||
arInlineName,
|
||||
ArNameTable,
|
||||
type ArMetadata,
|
||||
} from "../domain/arFormat.js";
|
||||
import { decodeUtf8PreservingBomOrNull } from "../domain/strictUtf8.js";
|
||||
import type { StableRegularFileDescriptor } from "../filesystem/RegularFile.js";
|
||||
import {
|
||||
ArtifactReaderFailure,
|
||||
artifactReaderLimitFailure,
|
||||
malformedArtifact,
|
||||
normalizeArtifactPath,
|
||||
withoutCurrentDirectoryPrefix,
|
||||
type ArtifactEntry,
|
||||
} from "../resources/index.js";
|
||||
import {
|
||||
createBoundedArtifactRead,
|
||||
readArtifactFileBytes,
|
||||
} from "./ArtifactFileRange.js";
|
||||
import {
|
||||
PositionalArtifactReader,
|
||||
type PositionalArtifactEntries,
|
||||
} from "./PositionalArtifactReader.js";
|
||||
|
||||
const logicalMemberPath = (name: string): string | null => {
|
||||
try {
|
||||
return normalizeArtifactPath(withoutCurrentDirectoryPrefix(name));
|
||||
} catch (cause: unknown) {
|
||||
if (!(cause instanceof ArtifactReaderFailure) || cause.reason !== "path")
|
||||
throw cause;
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
export class ArArtifactReader extends PositionalArtifactReader<
|
||||
ArMetadata,
|
||||
ArtifactEntry
|
||||
> {
|
||||
override readonly format = "ar" as const;
|
||||
|
||||
constructor(
|
||||
path: string,
|
||||
admitted?: StableRegularFileDescriptor,
|
||||
private readonly limits: ArReaderLimits = DEFAULT_AR_READER_LIMITS,
|
||||
) {
|
||||
super(path, "Unix ar archive", admitted);
|
||||
}
|
||||
|
||||
formatMetadata(): ArMetadata | undefined {
|
||||
const metadata = this.preparedFormatMetadata;
|
||||
return metadata === undefined ? undefined : { ...metadata };
|
||||
}
|
||||
|
||||
protected override async prepareEntries(
|
||||
signal?: AbortSignal,
|
||||
): Promise<PositionalArtifactEntries<ArMetadata, ArtifactEntry>> {
|
||||
const { handle, initial } = await this.verifyCarrier(signal);
|
||||
const readPrefix = createBoundedArtifactRead(
|
||||
this.format,
|
||||
handle,
|
||||
initial.size,
|
||||
signal,
|
||||
);
|
||||
const archiveKind = arArchiveKind(await readPrefix(0, AR_MAGIC.length));
|
||||
if (archiveKind === undefined)
|
||||
throw malformedArtifact(this.format, "Invalid Unix ar signature");
|
||||
|
||||
const read = (offset: number, length: number): Promise<Buffer> =>
|
||||
readArtifactFileBytes(
|
||||
this.format,
|
||||
handle,
|
||||
offset,
|
||||
length,
|
||||
initial.size,
|
||||
signal,
|
||||
);
|
||||
const entries: ArtifactEntry[] = [];
|
||||
const limitations: string[] = [];
|
||||
let offset = AR_MAGIC.length;
|
||||
let headers = 0;
|
||||
let symbolTables = 0;
|
||||
const retainedNames = new Budget(this.limits.retained_name_bytes);
|
||||
let terminalFailure: ArtifactReaderFailure | undefined;
|
||||
const limit = (field: keyof ArReaderLimits, required: number) => {
|
||||
terminalFailure = artifactReaderLimitFailure(
|
||||
`artifact_limits.ar.${field}`,
|
||||
this.limits[field],
|
||||
field === "header_count" ? "count" : "bytes",
|
||||
required,
|
||||
);
|
||||
limitations.push(terminalFailure.message);
|
||||
};
|
||||
let unsafeNames = 0;
|
||||
let nameTable: ArNameTable | undefined;
|
||||
if (archiveKind === "thin")
|
||||
limitations.push(
|
||||
"Thin ar members are external references. Their contents were not opened.",
|
||||
);
|
||||
|
||||
while (offset < initial.size) {
|
||||
this.assertOpen(signal);
|
||||
if (headers === this.limits.header_count) {
|
||||
limit("header_count", headers + 1);
|
||||
break;
|
||||
}
|
||||
const bytes = await readPrefix(offset, AR_HEADER_BYTES);
|
||||
const parsed = readArHeader(bytes, archiveKind);
|
||||
if (!parsed.ok) {
|
||||
limitations.push(
|
||||
`Invalid or truncated ar header at byte ${String(offset)}.`,
|
||||
);
|
||||
break;
|
||||
}
|
||||
headers += 1;
|
||||
|
||||
const header = parsed.value;
|
||||
const { name, size } = header;
|
||||
const isNameTable = name.kind === "gnu-table";
|
||||
let dataOffset = offset + AR_HEADER_BYTES;
|
||||
let memberBytes = size;
|
||||
let sourcePath: string | null;
|
||||
if (name.kind === "bsd-inline") {
|
||||
const nameBytes = name.length;
|
||||
if (
|
||||
archiveKind === "thin" ||
|
||||
nameBytes > Math.min(size, initial.size - dataOffset)
|
||||
) {
|
||||
limitations.push(
|
||||
`Invalid or unsupported BSD ar name at byte ${String(offset)}.`,
|
||||
);
|
||||
break;
|
||||
}
|
||||
if (nameBytes > this.limits.name_bytes) {
|
||||
limit("name_bytes", nameBytes);
|
||||
break;
|
||||
}
|
||||
const raw = arInlineName(await read(dataOffset, nameBytes));
|
||||
sourcePath = raw === null ? null : decodeUtf8PreservingBomOrNull(raw);
|
||||
dataOffset += nameBytes;
|
||||
memberBytes -= nameBytes;
|
||||
} else if (name.kind === "gnu-reference") {
|
||||
const resolved =
|
||||
nameTable === undefined
|
||||
? undefined
|
||||
: nameTable.resolve(name.offset, this.limits.name_bytes);
|
||||
if (
|
||||
resolved !== undefined &&
|
||||
!resolved.ok &&
|
||||
resolved.error.kind === "limit"
|
||||
) {
|
||||
limit("name_bytes", resolved.error.required);
|
||||
break;
|
||||
}
|
||||
sourcePath = resolved?.ok
|
||||
? decodeUtf8PreservingBomOrNull(resolved.value)
|
||||
: null;
|
||||
} else {
|
||||
sourcePath =
|
||||
name.kind === "gnu-table"
|
||||
? "//"
|
||||
: decodeUtf8PreservingBomOrNull(Buffer.from(name.value, "latin1"));
|
||||
}
|
||||
if (sourcePath?.includes("\0")) sourcePath = null;
|
||||
|
||||
const isSymbolTable =
|
||||
name.kind === "symbol-table" ||
|
||||
(name.kind === "bsd-inline" &&
|
||||
sourcePath !== null &&
|
||||
AR_SYMBOL_NAMES.has(sourcePath));
|
||||
const external = archiveKind === "thin" && !isNameTable && !isSymbolTable;
|
||||
const storedBytes = external ? 0 : size;
|
||||
const next = offset + AR_HEADER_BYTES + storedBytes + (storedBytes % 2);
|
||||
if (next > initial.size) {
|
||||
limitations.push(`Truncated ar member at byte ${String(offset)}.`);
|
||||
break;
|
||||
}
|
||||
if (isNameTable) {
|
||||
if (size > this.limits.name_table_bytes) {
|
||||
limit("name_table_bytes", size);
|
||||
break;
|
||||
}
|
||||
nameTable = new ArNameTable(await read(dataOffset, size));
|
||||
} else if (isSymbolTable) {
|
||||
symbolTables += 1;
|
||||
} else {
|
||||
const path =
|
||||
sourcePath === null
|
||||
? null
|
||||
: external
|
||||
? `external/${String(headers)}`
|
||||
: logicalMemberPath(sourcePath);
|
||||
if (sourcePath === null || path === null) {
|
||||
unsafeNames += 1;
|
||||
} else {
|
||||
const nameBytes =
|
||||
Buffer.byteLength(sourcePath) + Buffer.byteLength(path);
|
||||
if (!retainedNames.tryCharge(nameBytes)) {
|
||||
limit("retained_name_bytes", retainedNames.used + nameBytes);
|
||||
break;
|
||||
}
|
||||
entries.push({
|
||||
path,
|
||||
kind: external ? "metadata" : "file",
|
||||
declaredSize: external ? null : memberBytes,
|
||||
compressedSize: null,
|
||||
executable:
|
||||
header.mode === null ? null : (header.mode & 0o111) !== 0,
|
||||
encrypted: false,
|
||||
byteOffset: external ? null : dataOffset,
|
||||
declaredIntegrity: null,
|
||||
unpacked: false,
|
||||
limitations: [],
|
||||
adapterKey: `ar:${String(offset)}`,
|
||||
formatMetadata: {
|
||||
kind: "ar-entry",
|
||||
source_path: sourcePath,
|
||||
header_offset: offset,
|
||||
member_bytes: memberBytes,
|
||||
mode: header.mode,
|
||||
uid: header.uid,
|
||||
gid: header.gid,
|
||||
mtime: header.mtime,
|
||||
external,
|
||||
...(name.kind === "gnu-reference" &&
|
||||
name.nestedOffset !== undefined
|
||||
? { nested_member_offset: name.nestedOffset }
|
||||
: {}),
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
offset = next;
|
||||
}
|
||||
if (unsafeNames > 0)
|
||||
limitations.push(
|
||||
`${String(unsafeNames)} ar member name(s) could not be decoded or represented as safe paths.`,
|
||||
);
|
||||
|
||||
return {
|
||||
entries,
|
||||
...(terminalFailure === undefined ? {} : { terminalFailure }),
|
||||
coverage: {
|
||||
status:
|
||||
offset === initial.size && unsafeNames === 0 ? "complete" : "unknown",
|
||||
limitations,
|
||||
},
|
||||
formatMetadata: {
|
||||
kind: "ar",
|
||||
archive_kind: archiveKind,
|
||||
symbol_tables: symbolTables,
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
import { ArtifactTraversalLimitFailure } from "./ArtifactTraversalObservation.js";
|
||||
import { ArtifactPreparation } from "./ArtifactPreparation.js";
|
||||
import { Readable, Transform } from "node:stream";
|
||||
import { setImmediate } from "node:timers/promises";
|
||||
@@ -65,6 +66,8 @@ export interface PositionalArtifactEntries<
|
||||
readonly coverage: ArtifactReaderTraversal;
|
||||
readonly formatMetadata?: Metadata;
|
||||
readonly containerIntegrity?: ArtifactContainerIntegrityPair;
|
||||
/** Report a stopped traversal after publishing its established prefix. */
|
||||
readonly terminalFailure?: ArtifactReaderFailure;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -88,6 +91,7 @@ export abstract class PositionalArtifactReader<
|
||||
| {
|
||||
readonly entries: ReadonlyMap<string, Entry>;
|
||||
readonly coverage: ArtifactReaderTraversal;
|
||||
readonly terminalFailure: ArtifactReaderFailure | undefined;
|
||||
readonly formatMetadata: Metadata | undefined;
|
||||
readonly containerIntegrity: ArtifactContainerIntegrityPair | undefined;
|
||||
}
|
||||
@@ -177,6 +181,8 @@ export abstract class PositionalArtifactReader<
|
||||
yield copyArtifactEntry(entry);
|
||||
}
|
||||
this.assertOpen(signal);
|
||||
if (prepared.terminalFailure !== undefined)
|
||||
throw new ArtifactTraversalLimitFailure(prepared.terminalFailure);
|
||||
}
|
||||
|
||||
async open(entry: ArtifactEntry, signal?: AbortSignal): Promise<Readable> {
|
||||
@@ -289,6 +295,7 @@ export abstract class PositionalArtifactReader<
|
||||
this.#prepared = {
|
||||
entries,
|
||||
coverage: prepared.coverage,
|
||||
terminalFailure: prepared.terminalFailure,
|
||||
formatMetadata: prepared.formatMetadata,
|
||||
containerIntegrity: prepared.containerIntegrity,
|
||||
};
|
||||
|
||||
@@ -73,6 +73,7 @@ import { BfltArtifactReader } from "./BfltArtifactReader.js";
|
||||
import { SwitchExecutableArtifactReader } from "./SwitchExecutableArtifactReader.js";
|
||||
import { UnityFsArtifactReader } from "./UnityFsArtifactReader.js";
|
||||
import { WxapkgArtifactReader } from "./WxapkgArtifactReader.js";
|
||||
import { ArArtifactReader } from "./ArArtifactReader.js";
|
||||
import { TarArtifactReader } from "./tar/TarArtifactReader.js";
|
||||
import {
|
||||
GpuAssetArtifactReader,
|
||||
@@ -471,6 +472,15 @@ const NON_ZIP_FORMATS = {
|
||||
options.readerLimits?.expanded_bytes,
|
||||
),
|
||||
}),
|
||||
ar: container("ar", {
|
||||
roleContainer: true,
|
||||
retainClassifiedSource: true,
|
||||
absentInventory: "unavailable",
|
||||
readerLimitation:
|
||||
"Unix ar inventory reports stored members and thin archive references. Archive symbol tables are counted and external members are never opened.",
|
||||
createReader: (path, options) =>
|
||||
new ArArtifactReader(path, sourceOf(options), options.readerLimits?.ar),
|
||||
}),
|
||||
tar: container("tar", {
|
||||
roleContainer: true,
|
||||
retainClassifiedSource: true,
|
||||
|
||||
@@ -57,7 +57,7 @@ export interface MutableOccurrence {
|
||||
artifact_format: ArtifactOccurrence["artifact_format"];
|
||||
declared_size: number | null;
|
||||
compressed_size: number | null;
|
||||
executable: boolean;
|
||||
executable: ArtifactOccurrence["executable"];
|
||||
encrypted: boolean;
|
||||
unpacked?: boolean;
|
||||
hash_status: ArtifactOccurrence["hash_status"];
|
||||
|
||||
@@ -1023,12 +1023,8 @@ it("resolves a GNU ar long name at the name limit", async () => {
|
||||
});
|
||||
|
||||
it.for([
|
||||
[
|
||||
"past the end of the string table",
|
||||
"/40",
|
||||
/outside the 18-byte string table/u,
|
||||
],
|
||||
["at an empty string-table entry", "/17", /empty string-table entry/u],
|
||||
["past the end of the string table", "/40", /Invalid GNU ar name reference/u],
|
||||
["at an empty string-table entry", "/17", /Invalid GNU ar name reference/u],
|
||||
] as const)(
|
||||
"refuses a GNU ar long name reference %s with the partial report",
|
||||
async ([, reference, message]) => {
|
||||
@@ -1615,3 +1611,23 @@ it("counts large multi-million-line conffiles and blank-padded md5sums without l
|
||||
missing_from_md5sums: 0,
|
||||
});
|
||||
});
|
||||
|
||||
it("preserves GNU ar filename whitespace and rejects unterminated name tables", async () => {
|
||||
const named = (name: string) =>
|
||||
gnuLongNameReferences(
|
||||
debPackageFixture({
|
||||
extraMembers: [
|
||||
{ name: "//", data: Buffer.from(name) },
|
||||
{ name: "/0", data: Buffer.alloc(0) },
|
||||
],
|
||||
}),
|
||||
);
|
||||
expect(
|
||||
(await parse(named(" leading.o /\n"))).ar.extra_member_names,
|
||||
).toContain(" leading.o ");
|
||||
const error = await expectFailure(
|
||||
() => parse(named("unterminated.o")),
|
||||
DebPackageFormatFailure,
|
||||
);
|
||||
expect(error.message).toContain("Invalid GNU ar name reference");
|
||||
});
|
||||
+69
-56
@@ -1,3 +1,4 @@
|
||||
import { readArHeader, arInlineName, ArNameTable } from "../domain/arFormat.js";
|
||||
import { decodeUtf8PreservingBomOrNull } from "../domain/strictUtf8.js";
|
||||
import { ellipsisExcerpt } from "../domain/excerpt.js";
|
||||
import {
|
||||
@@ -70,30 +71,6 @@ const memberNameTooLong = (length: number): DebPackageAllowanceFailure =>
|
||||
`ar member name of ${String(length)} bytes exceeds the ${String(MAX_AR_MEMBER_NAME_BYTES)}-byte name limit.`,
|
||||
);
|
||||
|
||||
/** Resolves a GNU ar `/<offset>` reference against the `//` string table. */
|
||||
const gnuLongName = (
|
||||
stringTable: string,
|
||||
index: number,
|
||||
): string | DebPackageFormatFailure | DebPackageAllowanceFailure => {
|
||||
if (index >= stringTable.length)
|
||||
return new DebPackageFormatFailure(
|
||||
"malformed",
|
||||
`GNU ar long name offset ${String(index)} is outside the ${String(stringTable.length)}-byte string table.`,
|
||||
);
|
||||
const newline = stringTable.indexOf("\n", index);
|
||||
let end = newline === -1 ? stringTable.length : newline;
|
||||
if (end > index && stringTable[end - 1] === "/") end -= 1;
|
||||
if (end - index > MAX_AR_MEMBER_NAME_BYTES)
|
||||
return memberNameTooLong(end - index);
|
||||
const name = trimField(stringTable.slice(index, end));
|
||||
if (name === "")
|
||||
return new DebPackageFormatFailure(
|
||||
"malformed",
|
||||
`GNU ar long name offset ${String(index)} names an empty string-table entry.`,
|
||||
);
|
||||
return name;
|
||||
};
|
||||
|
||||
const XZ_MAGIC = Buffer.from([0xfd, 0x37, 0x7a, 0x58, 0x5a, 0x00]);
|
||||
const ZSTD_MAGIC = Buffer.from([0x28, 0xb5, 0x2f, 0xfd]);
|
||||
const BZ2_MAGIC = Buffer.from("BZh", "ascii");
|
||||
@@ -278,7 +255,7 @@ const parseArMembers = (bytes: Uint8Array, maxMembers: number): ArParse => {
|
||||
);
|
||||
const members: ParsedArMember[] = [];
|
||||
let offset = AR_MAGIC.length;
|
||||
let stringTable: string | null = null;
|
||||
let stringTable: ArNameTable | undefined;
|
||||
while (offset < bytes.length) {
|
||||
if (offset + AR_HEADER > bytes.length) {
|
||||
if (isZeroBlock(bytes.subarray(offset))) break;
|
||||
@@ -291,30 +268,22 @@ const parseArMembers = (bytes: Uint8Array, maxMembers: number): ArParse => {
|
||||
};
|
||||
}
|
||||
const header = bytes.subarray(offset, offset + AR_HEADER);
|
||||
if (header[58] !== 0x60 || header[59] !== 0x0a)
|
||||
const parsed = readArHeader(header);
|
||||
if (!parsed.ok)
|
||||
return {
|
||||
members,
|
||||
error: new DebPackageFormatFailure(
|
||||
"malformed",
|
||||
"ar member header is missing the `\\n terminator.",
|
||||
),
|
||||
};
|
||||
const rawName = ascii(header.subarray(0, 16));
|
||||
const size = parseDecimal(trimField(ascii(header.subarray(48, 58))));
|
||||
if (size === null)
|
||||
return {
|
||||
members,
|
||||
error: new DebPackageFormatFailure(
|
||||
"malformed",
|
||||
"ar member size is not a decimal integer.",
|
||||
`Invalid ar ${parsed.error}.`,
|
||||
),
|
||||
};
|
||||
const { name: descriptor, size } = parsed.value;
|
||||
let dataStart = offset + AR_HEADER;
|
||||
let name = trimField(rawName);
|
||||
let dataSize = size;
|
||||
if (name.startsWith("#1/")) {
|
||||
const nameLength = Number(name.slice(3));
|
||||
if (!Number.isInteger(nameLength) || nameLength < 0 || nameLength > size)
|
||||
let name: string;
|
||||
if (descriptor.kind === "bsd-inline") {
|
||||
const nameLength = descriptor.length;
|
||||
if (nameLength > size)
|
||||
return {
|
||||
members,
|
||||
error: new DebPackageFormatFailure(
|
||||
@@ -324,7 +293,7 @@ const parseArMembers = (bytes: Uint8Array, maxMembers: number): ArParse => {
|
||||
};
|
||||
if (nameLength > MAX_AR_MEMBER_NAME_BYTES)
|
||||
return { members, error: memberNameTooLong(nameLength) };
|
||||
if (dataStart + nameLength > bytes.length)
|
||||
if (nameLength > bytes.length - dataStart)
|
||||
return {
|
||||
members,
|
||||
error: new DebPackageFormatFailure(
|
||||
@@ -332,13 +301,23 @@ const parseArMembers = (bytes: Uint8Array, maxMembers: number): ArParse => {
|
||||
"BSD ar long name extends past the end of the file.",
|
||||
),
|
||||
};
|
||||
name = trimField(
|
||||
ascii(bytes.subarray(dataStart, dataStart + nameLength)),
|
||||
const raw = arInlineName(
|
||||
Buffer.from(bytes.subarray(dataStart, dataStart + nameLength)),
|
||||
);
|
||||
const decoded = raw === null ? null : decodeUtf8PreservingBomOrNull(raw);
|
||||
if (decoded === null)
|
||||
return {
|
||||
members,
|
||||
error: new DebPackageFormatFailure(
|
||||
"malformed",
|
||||
"BSD ar name is not valid UTF-8 or contains an interior NUL.",
|
||||
),
|
||||
};
|
||||
name = decoded;
|
||||
dataStart += nameLength;
|
||||
dataSize = size - nameLength;
|
||||
} else if (name === "//") {
|
||||
if (dataStart + size > bytes.length)
|
||||
dataSize -= nameLength;
|
||||
} else if (descriptor.kind === "gnu-table") {
|
||||
if (size > bytes.length - dataStart)
|
||||
return {
|
||||
members,
|
||||
error: new DebPackageFormatFailure(
|
||||
@@ -346,11 +325,12 @@ const parseArMembers = (bytes: Uint8Array, maxMembers: number): ArParse => {
|
||||
"GNU ar string table extends past the end of the file.",
|
||||
),
|
||||
};
|
||||
// The string table is a physical member: it is kept in the inventory
|
||||
// and counted against max_ar_members like any other.
|
||||
stringTable = ascii(bytes.subarray(dataStart, dataStart + size));
|
||||
} else if (/^\/\d+$/u.test(name)) {
|
||||
if (stringTable === null)
|
||||
stringTable = new ArNameTable(
|
||||
Buffer.from(bytes.subarray(dataStart, dataStart + size)),
|
||||
);
|
||||
name = "//";
|
||||
} else if (descriptor.kind === "gnu-reference") {
|
||||
if (stringTable === undefined)
|
||||
return {
|
||||
members,
|
||||
error: new DebPackageFormatFailure(
|
||||
@@ -358,11 +338,44 @@ const parseArMembers = (bytes: Uint8Array, maxMembers: number): ArParse => {
|
||||
"GNU ar long name refers to a missing string table.",
|
||||
),
|
||||
};
|
||||
const resolved = gnuLongName(stringTable, Number(name.slice(1)));
|
||||
if (typeof resolved !== "string") return { members, error: resolved };
|
||||
name = resolved;
|
||||
const resolved = stringTable.resolve(
|
||||
descriptor.offset,
|
||||
MAX_AR_MEMBER_NAME_BYTES,
|
||||
);
|
||||
if (!resolved.ok)
|
||||
return {
|
||||
members,
|
||||
error:
|
||||
resolved.error.kind === "limit"
|
||||
? memberNameTooLong(resolved.error.required)
|
||||
: new DebPackageFormatFailure(
|
||||
"malformed",
|
||||
"Invalid GNU ar name reference.",
|
||||
),
|
||||
};
|
||||
const decoded = decodeUtf8PreservingBomOrNull(resolved.value);
|
||||
if (decoded === null || decoded.includes("\0"))
|
||||
return {
|
||||
members,
|
||||
error: new DebPackageFormatFailure(
|
||||
"malformed",
|
||||
"GNU ar name is not valid UTF-8 or contains a NUL.",
|
||||
),
|
||||
};
|
||||
name = decoded;
|
||||
} else {
|
||||
name = name.replace(/\/$/u, "");
|
||||
const decoded = decodeUtf8PreservingBomOrNull(
|
||||
Buffer.from(descriptor.value, "latin1"),
|
||||
);
|
||||
if (decoded === null || decoded.includes("\0"))
|
||||
return {
|
||||
members,
|
||||
error: new DebPackageFormatFailure(
|
||||
"malformed",
|
||||
"ar name is not valid UTF-8 or contains a NUL.",
|
||||
),
|
||||
};
|
||||
name = decoded;
|
||||
}
|
||||
if (dataStart + dataSize > bytes.length)
|
||||
return {
|
||||
|
||||
@@ -399,6 +399,7 @@ export const projectArtifactInventoryView = (
|
||||
inventory.manifest.root_format === "wxapkg" ||
|
||||
inventory.manifest.root_format === "iso9660" ||
|
||||
inventory.manifest.root_format === "tar" ||
|
||||
inventory.manifest.root_format === "ar" ||
|
||||
inventory.manifest.root_format === "nso" ||
|
||||
inventory.manifest.root_format === "nro" ||
|
||||
inventory.manifest.root_format === "pyinstaller" ||
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
import { expect, it } from "vitest";
|
||||
import { readArHeader, arInlineName, ArNameTable } from "./arFormat.js";
|
||||
import { hasDebPackageHeader } from "./deb/debPackage.js";
|
||||
|
||||
const header = (name: string) =>
|
||||
Buffer.from(
|
||||
`${name.padEnd(16)}${"".padEnd(12)}${"".padEnd(6)}${"".padEnd(6)}${"".padEnd(8)}${"4".padEnd(10)}\u0060\n`,
|
||||
);
|
||||
|
||||
it.each([
|
||||
["x.o/", { kind: "short", value: "x.o" }],
|
||||
[" x.o/", { kind: "short", value: " x.o" }],
|
||||
["x.o /", { kind: "short", value: "x.o " }],
|
||||
["/", { kind: "symbol-table", value: "/" }],
|
||||
["/SYM64/", { kind: "symbol-table", value: "/SYM64/" }],
|
||||
["//", { kind: "gnu-table" }],
|
||||
["/12", { kind: "gnu-reference", offset: 12 }],
|
||||
["#1/4", { kind: "bsd-inline", length: 4 }],
|
||||
])(
|
||||
"parses ar name %s without interpreting optional metadata",
|
||||
(name, expected) => {
|
||||
expect(readArHeader(header(name as string))).toEqual({
|
||||
ok: true,
|
||||
value: {
|
||||
name: expected,
|
||||
size: 4,
|
||||
mtime: null,
|
||||
uid: null,
|
||||
gid: null,
|
||||
mode: null,
|
||||
},
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
it.each(["/12junk", "/-1", "#1/+1", "#1/2x"])(
|
||||
"refuses malformed ar name descriptor %s",
|
||||
(name) => {
|
||||
expect(readArHeader(header(name))).toEqual({ ok: false, error: "name" });
|
||||
},
|
||||
);
|
||||
|
||||
it("shares precise Debian recognition for plain and BSD names", () => {
|
||||
const prefix = (name: string, data = "2.0\n") =>
|
||||
Buffer.concat([Buffer.from("!<arch>\n"), header(name), Buffer.from(data)]);
|
||||
expect(hasDebPackageHeader(prefix("debian-binary/"))).toBe(true);
|
||||
expect(hasDebPackageHeader(prefix(" debian-binary/"))).toBe(false);
|
||||
const bsd = prefix("#1/13", "debian-binary\0");
|
||||
bsd.write("13 ", 8 + 48, "ascii");
|
||||
expect(hasDebPackageHeader(bsd)).toBe(true);
|
||||
bsd[8 + 58] = 0;
|
||||
expect(hasDebPackageHeader(bsd)).toBe(false);
|
||||
});
|
||||
|
||||
it("preserves GNU whitespace and rejects missing delimiters and interior BSD NULs", () => {
|
||||
expect(new ArNameTable(Buffer.from(" x.o /\n")).resolve(0, 6)).toEqual({
|
||||
ok: true,
|
||||
value: Buffer.from(" x.o "),
|
||||
});
|
||||
expect(new ArNameTable(Buffer.from("x.o")).resolve(0, 6)).toEqual({
|
||||
ok: false,
|
||||
error: { kind: "reference" },
|
||||
});
|
||||
expect(
|
||||
arInlineName(Buffer.from("x.o \0\0"))?.equals(Buffer.from("x.o ")),
|
||||
).toBe(true);
|
||||
expect(arInlineName(Buffer.from("x\0.o"))).toBeNull();
|
||||
});
|
||||
|
||||
it("accepts nested-member offsets only in thin archive headers", () => {
|
||||
expect(readArHeader(header("/0:123"))).toEqual({ ok: false, error: "name" });
|
||||
expect(readArHeader(header("/0:123"), "thin")).toMatchObject({
|
||||
ok: true,
|
||||
value: { name: { kind: "gnu-reference", offset: 0, nestedOffset: 123 } },
|
||||
});
|
||||
for (const name of ["/0:", "/0:-1", "/0:1:2"])
|
||||
expect(readArHeader(header(name), "thin")).toEqual({
|
||||
ok: false,
|
||||
error: "name",
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps per-call name admission independent of cached table facts", () => {
|
||||
const names = new ArNameTable(Buffer.from("long-name.o/\n"));
|
||||
expect(names.resolve(0, 2)).toEqual({
|
||||
ok: false,
|
||||
error: { kind: "limit", required: 11 },
|
||||
});
|
||||
expect(names.resolve(0, 11).ok).toBe(true);
|
||||
expect(names.resolve(1, 11)).toEqual({
|
||||
ok: false,
|
||||
error: { kind: "reference" },
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,170 @@
|
||||
import { z } from "zod";
|
||||
import { err, ok, type Result } from "./result.js";
|
||||
|
||||
export const AR_MAGIC = Buffer.from("!<arch>\n", "ascii");
|
||||
const THIN_MAGIC = Buffer.from("!<thin>\n", "ascii");
|
||||
export const AR_HEADER_BYTES = 60;
|
||||
|
||||
export const arArchiveKind = (
|
||||
prefix: Uint8Array,
|
||||
): "regular" | "thin" | undefined => {
|
||||
if (prefix.length < AR_MAGIC.length) return undefined;
|
||||
if (AR_MAGIC.every((byte, index) => prefix[index] === byte)) return "regular";
|
||||
if (THIN_MAGIC.every((byte, index) => prefix[index] === byte)) return "thin";
|
||||
return undefined;
|
||||
};
|
||||
|
||||
const numberField = (text: string, radix: 8 | 10): number | null => {
|
||||
const pattern = radix === 8 ? /^[0-7]+$/u : /^\d+$/u;
|
||||
const value = pattern.test(text) ? Number.parseInt(text, radix) : NaN;
|
||||
return Number.isSafeInteger(value) ? value : null;
|
||||
};
|
||||
|
||||
export type ArName =
|
||||
| { readonly kind: "short"; readonly value: string }
|
||||
| { readonly kind: "symbol-table"; readonly value: string }
|
||||
| { readonly kind: "gnu-table" }
|
||||
| {
|
||||
readonly kind: "gnu-reference";
|
||||
readonly offset: number;
|
||||
readonly nestedOffset?: number;
|
||||
}
|
||||
| { readonly kind: "bsd-inline"; readonly length: number };
|
||||
|
||||
export interface ArHeader {
|
||||
readonly name: ArName;
|
||||
readonly size: number;
|
||||
readonly mtime: number | null;
|
||||
readonly uid: number | null;
|
||||
readonly gid: number | null;
|
||||
readonly mode: number | null;
|
||||
}
|
||||
|
||||
export const AR_SYMBOL_NAMES: ReadonlySet<string> = new Set([
|
||||
"/",
|
||||
"/SYM64/",
|
||||
"__.SYMDEF",
|
||||
"__.SYMDEF SORTED",
|
||||
"__.SYMDEF_64",
|
||||
"__.SYMDEF_64 SORTED",
|
||||
]);
|
||||
|
||||
/** Only the fixed header's trailing ASCII spaces are padding. */
|
||||
export const readArHeader = (
|
||||
bytes: Uint8Array,
|
||||
archiveKind: "regular" | "thin" = "regular",
|
||||
): Result<ArHeader, "header" | "size" | "name"> => {
|
||||
const header = Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
||||
if (
|
||||
header.length !== AR_HEADER_BYTES ||
|
||||
header[58] !== 0x60 ||
|
||||
header[59] !== 0x0a
|
||||
)
|
||||
return err("header");
|
||||
const field = (start: number, end: number): string =>
|
||||
header.toString("latin1", start, end).trim();
|
||||
const size = numberField(field(48, 58), 10);
|
||||
if (size === null) return err("size");
|
||||
const rawName = header.toString("latin1", 0, 16).replace(/ +$/u, "");
|
||||
let name: ArName;
|
||||
if (rawName === "//") name = { kind: "gnu-table" };
|
||||
else if (AR_SYMBOL_NAMES.has(rawName))
|
||||
name = { kind: "symbol-table", value: rawName };
|
||||
else if (rawName.startsWith("#1/")) {
|
||||
const length = numberField(rawName.slice(3), 10);
|
||||
if (length === null) return err("name");
|
||||
name = { kind: "bsd-inline", length };
|
||||
} else if (rawName.startsWith("/")) {
|
||||
const parts = rawName.slice(1).split(":");
|
||||
if (parts.length > 2 || (parts.length === 2 && archiveKind !== "thin"))
|
||||
return err("name");
|
||||
const offset = numberField(parts[0] ?? "", 10);
|
||||
if (offset === null) return err("name");
|
||||
const nestedOffset =
|
||||
parts.length === 2 ? numberField(parts[1] ?? "", 10) : undefined;
|
||||
if (nestedOffset === null) return err("name");
|
||||
name = {
|
||||
kind: "gnu-reference",
|
||||
offset,
|
||||
...(nestedOffset === undefined ? {} : { nestedOffset }),
|
||||
};
|
||||
} else
|
||||
name = {
|
||||
kind: "short",
|
||||
value: rawName.replace(/\/$/u, ""),
|
||||
};
|
||||
return ok({
|
||||
name,
|
||||
size,
|
||||
mtime: numberField(field(16, 28), 10),
|
||||
uid: numberField(field(28, 34), 10),
|
||||
gid: numberField(field(34, 40), 10),
|
||||
mode: numberField(field(40, 48), 8),
|
||||
});
|
||||
};
|
||||
|
||||
/** BSD inline names may have trailing NUL padding, but not interior NULs. */
|
||||
export const arInlineName = (bytes: Buffer): Buffer | null => {
|
||||
let end = bytes.length;
|
||||
while (end > 0 && bytes[end - 1] === 0) end -= 1;
|
||||
const name = bytes.subarray(0, end);
|
||||
return name.includes(0) ? null : name;
|
||||
};
|
||||
|
||||
type ArNameLookup = Result<Buffer, { readonly kind: "reference" }>;
|
||||
|
||||
/** Each admitted table owns its parsed entries, including malformed ones. */
|
||||
export class ArNameTable {
|
||||
readonly #entries = new Map<number, ArNameLookup>();
|
||||
|
||||
constructor(private readonly table: Buffer) {}
|
||||
|
||||
resolve(
|
||||
offset: number,
|
||||
maximum: number,
|
||||
): Result<
|
||||
Buffer,
|
||||
| { readonly kind: "reference" }
|
||||
| { readonly kind: "limit"; readonly required: number }
|
||||
> {
|
||||
if (
|
||||
offset >= this.table.length ||
|
||||
(offset > 0 && this.table[offset - 1] !== 0x0a)
|
||||
)
|
||||
return err({ kind: "reference" });
|
||||
let entry = this.#entries.get(offset);
|
||||
if (entry === undefined) {
|
||||
const end = this.table.indexOf(0x0a, offset);
|
||||
entry =
|
||||
end <= offset || this.table[end - 1] !== 0x2f
|
||||
? err({ kind: "reference" })
|
||||
: ok(this.table.subarray(offset, end - 1));
|
||||
this.#entries.set(offset, entry);
|
||||
}
|
||||
if (!entry.ok) return entry;
|
||||
if (entry.value.length > maximum)
|
||||
return err({ kind: "limit", required: entry.value.length });
|
||||
return entry;
|
||||
}
|
||||
}
|
||||
|
||||
export const arMetadataSchema = z.strictObject({
|
||||
kind: z.literal("ar"),
|
||||
archive_kind: z.enum(["regular", "thin"]),
|
||||
symbol_tables: z.int().nonnegative(),
|
||||
});
|
||||
|
||||
export const arEntryMetadataSchema = z.strictObject({
|
||||
kind: z.literal("ar-entry"),
|
||||
source_path: z.string(),
|
||||
header_offset: z.int().nonnegative(),
|
||||
member_bytes: z.int().nonnegative(),
|
||||
mode: z.int().nonnegative().nullable(),
|
||||
uid: z.int().nonnegative().nullable(),
|
||||
gid: z.int().nonnegative().nullable(),
|
||||
mtime: z.int().nonnegative().nullable(),
|
||||
external: z.boolean(),
|
||||
nested_member_offset: z.int().nonnegative().exactOptional(),
|
||||
});
|
||||
|
||||
export type ArMetadata = z.infer<typeof arMetadataSchema>;
|
||||
@@ -576,7 +576,7 @@ const recordObservation = (
|
||||
record: {
|
||||
readonly content?: string;
|
||||
readonly encrypted?: boolean;
|
||||
readonly executable?: boolean;
|
||||
readonly executable?: boolean | null;
|
||||
readonly limitations?: string[];
|
||||
readonly unpacked?: boolean;
|
||||
} = {},
|
||||
@@ -615,7 +615,7 @@ const recordObservation = (
|
||||
artifact_format: "unknown",
|
||||
declared_size: 0,
|
||||
compressed_size: null,
|
||||
executable: record.executable ?? false,
|
||||
executable: record.executable === undefined ? false : record.executable,
|
||||
encrypted,
|
||||
hash_status:
|
||||
sha256 !== undefined
|
||||
@@ -1290,3 +1290,104 @@ it("reads, projects, and compares saved inventories whose effective_limits omit
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it.each([null, false, true])(
|
||||
"does not infer executable changes from unknown permissions versus %s",
|
||||
(executable) => {
|
||||
const result = compareArtifacts(
|
||||
packingObservation(undefined, "verified", false, { executable: null }),
|
||||
packingObservation(undefined, "verified", false, { executable }),
|
||||
);
|
||||
expect(result).toMatchObject({
|
||||
status: "unknown",
|
||||
changes: [{ classification: "unknown", dimensions: ["availability"] }],
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
it("preserves content changes alongside unknown permissions", () => {
|
||||
const result = compareArtifacts(
|
||||
packingObservation(undefined, "verified", false, { executable: null }),
|
||||
packingObservation(undefined, "verified", true, { executable: true }),
|
||||
);
|
||||
expect(result.changes[0]).toMatchObject({
|
||||
classification: "changed",
|
||||
dimensions: expect.arrayContaining(["content", "availability"]),
|
||||
});
|
||||
expect(result.changes[0]?.dimensions).not.toContain("executable");
|
||||
});
|
||||
|
||||
const arDeclaration = (mode: number | null, external: boolean) => ({
|
||||
kind: "ar-entry" as const,
|
||||
source_path: "object.o",
|
||||
header_offset: 8,
|
||||
member_bytes: 4,
|
||||
mode,
|
||||
uid: null,
|
||||
gid: null,
|
||||
mtime: null,
|
||||
external,
|
||||
});
|
||||
it.each([false, true])(
|
||||
"keeps ar permission uncertainty for external=%s",
|
||||
(external) => {
|
||||
for (const mode of [null, 0o644, 0o755]) {
|
||||
const left = arDeclaration(null, external);
|
||||
const right = arDeclaration(mode, external);
|
||||
const result = compareArtifacts(
|
||||
external
|
||||
? recordObservation(left, { executable: null })
|
||||
: declared(left),
|
||||
external
|
||||
? recordObservation(right, {
|
||||
executable: mode === null ? null : (mode & 0o111) !== 0,
|
||||
})
|
||||
: declared(right),
|
||||
);
|
||||
expect(result.changes).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
classification: "unknown",
|
||||
dimensions: ["availability"],
|
||||
}),
|
||||
]),
|
||||
);
|
||||
}
|
||||
const result = compareArtifacts(
|
||||
external
|
||||
? recordObservation(arDeclaration(0o644, external), {
|
||||
executable: false,
|
||||
})
|
||||
: declared(arDeclaration(0o644, external)),
|
||||
external
|
||||
? recordObservation(arDeclaration(0o755, external), {
|
||||
executable: true,
|
||||
})
|
||||
: declared(arDeclaration(0o755, external)),
|
||||
);
|
||||
expect(result.changes).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
classification: "changed",
|
||||
dimensions: expect.arrayContaining(["metadata"]),
|
||||
}),
|
||||
]),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
it("distinguishes nested members of the same external thin archive", () => {
|
||||
const metadata = arDeclaration(0o644, true);
|
||||
const result = compareArtifacts(
|
||||
recordObservation({ ...metadata, nested_member_offset: 84 }),
|
||||
recordObservation({ ...metadata, nested_member_offset: 208 }),
|
||||
);
|
||||
expect(result.changes).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
classification: "changed",
|
||||
dimensions: ["metadata"],
|
||||
}),
|
||||
]),
|
||||
);
|
||||
});
|
||||
@@ -568,6 +568,7 @@ const classifyPath = (input: ClassifyPathInput): ArtifactChange | null => {
|
||||
declarationUnknown(input.metadata) ||
|
||||
occurrence.kindUnknown ||
|
||||
occurrence.formatUnknown ||
|
||||
occurrence.executableUnknown ||
|
||||
input.relations === "unknown" ||
|
||||
differsWithUnknown(input.leftNode?.format, input.rightNode?.format) ||
|
||||
differsWithMissing(
|
||||
@@ -639,6 +640,17 @@ const differsWithMissing = (
|
||||
right: string | null | undefined,
|
||||
): boolean => left !== right && (left == null || right == null);
|
||||
|
||||
/** Missing permission observations cannot establish an executable-bit change. */
|
||||
const compareExecutable = (
|
||||
left: ArtifactOccurrence | undefined,
|
||||
right: ArtifactOccurrence | undefined,
|
||||
): FactComparison =>
|
||||
left?.executable == null || right?.executable == null
|
||||
? "unknown"
|
||||
: left.executable === right.executable
|
||||
? "unchanged"
|
||||
: "changed";
|
||||
|
||||
/** Occurrence facts remain independently comparable when content is unavailable. */
|
||||
const occurrenceDifferences = (input: {
|
||||
readonly metadata: OccurrenceMetadata;
|
||||
@@ -668,7 +680,11 @@ const occurrenceDifferences = (input: {
|
||||
input.rightOccurrence?.artifact_format,
|
||||
),
|
||||
executable:
|
||||
input.leftOccurrence?.executable !== input.rightOccurrence?.executable,
|
||||
compareExecutable(input.leftOccurrence, input.rightOccurrence) ===
|
||||
"changed",
|
||||
executableUnknown:
|
||||
compareExecutable(input.leftOccurrence, input.rightOccurrence) ===
|
||||
"unknown",
|
||||
metadata:
|
||||
declaredFactChanged(input.metadata) ||
|
||||
input.leftOccurrence?.entry_kind !== input.rightOccurrence?.entry_kind,
|
||||
@@ -806,10 +822,15 @@ const classifyDeclarationRecord = (
|
||||
)
|
||||
return { handled: false, change: null };
|
||||
const dimensions: ArtifactChange["dimensions"] = [];
|
||||
if (input.leftOccurrence.executable !== input.rightOccurrence.executable)
|
||||
if (
|
||||
compareExecutable(input.leftOccurrence, input.rightOccurrence) === "changed"
|
||||
)
|
||||
dimensions.push("executable");
|
||||
if (declaredFactChanged(input.metadata)) dimensions.push("metadata");
|
||||
const unknown = declarationUnknown(input.metadata);
|
||||
const unknown =
|
||||
declarationUnknown(input.metadata) ||
|
||||
compareExecutable(input.leftOccurrence, input.rightOccurrence) ===
|
||||
"unknown";
|
||||
if (dimensions.length === 0)
|
||||
return {
|
||||
handled: true,
|
||||
@@ -845,9 +866,13 @@ const classifyLinkTargets = (
|
||||
const dimensions: ArtifactChange["dimensions"] = [];
|
||||
if (left.link_target.hex !== right.link_target.hex)
|
||||
dimensions.push("content");
|
||||
if (left.executable !== right.executable) dimensions.push("executable");
|
||||
if (compareExecutable(left, right) === "changed")
|
||||
dimensions.push("executable");
|
||||
if (declaredFactChanged(input.metadata)) dimensions.push("metadata");
|
||||
const unknown = declarationUnknown(input.metadata);
|
||||
const unknown =
|
||||
declarationUnknown(input.metadata) ||
|
||||
compareExecutable(input.leftOccurrence, input.rightOccurrence) ===
|
||||
"unknown";
|
||||
if (dimensions.length === 0)
|
||||
return {
|
||||
handled: true,
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { z } from "zod";
|
||||
import { arEntryMetadataSchema, arMetadataSchema } from "./arFormat.js";
|
||||
import {
|
||||
androidSuperImageMetadataSchema,
|
||||
androidSuperPartitionMetadataSchema,
|
||||
@@ -99,6 +100,8 @@ export const artifactFormatMetadataSchema = z.discriminatedUnion("kind", [
|
||||
wxapkgEntryMetadataSchema,
|
||||
tarMetadataSchema,
|
||||
tarEntryMetadataSchema,
|
||||
arMetadataSchema,
|
||||
arEntryMetadataSchema,
|
||||
switchExecutableMetadataSchema,
|
||||
switchExecutableEntryMetadataSchema,
|
||||
pyInstallerMetadataSchema,
|
||||
@@ -226,6 +229,26 @@ const declarationsByKind: {
|
||||
notCompared:
|
||||
"index is layout. source_path keeps the declared name, including a producer root prefix the occurrence path strips.",
|
||||
},
|
||||
ar: {
|
||||
notCompared:
|
||||
"The archive kind and symbol table count are properties of the carrier bytes.",
|
||||
},
|
||||
"ar-entry": {
|
||||
unreadable: (metadata) => (metadata.mode === null ? ["mode"] : []),
|
||||
declaration: (metadata) => ({
|
||||
mode: metadata.mode,
|
||||
external: metadata.external,
|
||||
...(metadata.external
|
||||
? {
|
||||
source_path: metadata.source_path,
|
||||
member_bytes: metadata.member_bytes,
|
||||
...(metadata.nested_member_offset === undefined
|
||||
? {}
|
||||
: { nested_member_offset: metadata.nested_member_offset }),
|
||||
}
|
||||
: {}),
|
||||
}),
|
||||
},
|
||||
tar: {
|
||||
notCompared:
|
||||
"Its fields come from the archive's own bytes, which content comparison covers.",
|
||||
|
||||
@@ -705,15 +705,22 @@ it("recognizes a Mega Drive image and an SMD dump, and yields to ELF", () => {
|
||||
expect(recognize(mz)?.format).not.toBe("mega-drive-rom");
|
||||
});
|
||||
|
||||
it("does not recognize a plain ar archive that is not a Debian package", () => {
|
||||
it("recognizes ordinary and thin ar without mistaking late Debian markers for packages", () => {
|
||||
const plainAr = minimalAr([{ name: "hello.o", data: "object" }]);
|
||||
expect(recognize(plainAr)).toBeUndefined();
|
||||
const lateDebianBinary = minimalAr([
|
||||
{ name: "hello.o", data: "object" },
|
||||
{ name: "debian-binary", data: "2.0\n" },
|
||||
]);
|
||||
expect(recognize(lateDebianBinary)).toBeUndefined();
|
||||
expect(recognize(Buffer.from("!<arch>\n", "ascii"))).toBeUndefined();
|
||||
for (const bytes of [
|
||||
plainAr,
|
||||
lateDebianBinary,
|
||||
Buffer.from("!<arch>\n"),
|
||||
Buffer.from("!<thin>\n"),
|
||||
])
|
||||
expect(recognize(bytes)).toMatchObject({
|
||||
state: "recognized",
|
||||
format: "ar",
|
||||
});
|
||||
});
|
||||
|
||||
it("recognizes a standalone ESP-IDF NVS partition and ignores erased or unaligned files", () => {
|
||||
|
||||
@@ -44,6 +44,7 @@ import {
|
||||
readDevicetreeHeader,
|
||||
} from "./firmware/devicetreeHeader.js";
|
||||
import { hasEspNvsHeader } from "./firmware/espNvsParser.js";
|
||||
import { arArchiveKind } from "./arFormat.js";
|
||||
import { hasDebPackageHeader } from "./deb/debPackage.js";
|
||||
import { observePythonBytecodePrefix } from "./python/pythonBytecodeIdentity.js";
|
||||
import { hasEvtxHeader } from "./evtxArchive/evtxArchiveFormat.js";
|
||||
@@ -76,6 +77,7 @@ export type RecognizedArtifactFormat = Extract<
|
||||
| "unityfs"
|
||||
| "wxapkg"
|
||||
| "tar"
|
||||
| "ar"
|
||||
| "dds"
|
||||
| "glb"
|
||||
| "ktx"
|
||||
@@ -362,6 +364,7 @@ export const ARTIFACT_FORMAT_RECOGNIZERS: readonly ArtifactFormatRecognizer[] =
|
||||
when("sqlite", hasSqliteHeader),
|
||||
when("windows-shortcut", hasWindowsShortcutHeader),
|
||||
when("deb", hasDebPackageHeader),
|
||||
when("ar", (prefix) => arArchiveKind(prefix) !== undefined),
|
||||
({ prefix, fileSize }) =>
|
||||
hasEspNvsHeader(prefix, fileSize)
|
||||
? { state: "recognized", format: "esp-nvs" }
|
||||
|
||||
@@ -79,6 +79,7 @@ export const ARTIFACT_FORMAT_IDS = [
|
||||
"unityfs",
|
||||
"wxapkg",
|
||||
"tar",
|
||||
"ar",
|
||||
"dds",
|
||||
"glb",
|
||||
"ktx",
|
||||
@@ -158,6 +159,7 @@ const artifactContentFormatSchema = artifactFormatSchema.extract([
|
||||
"unityfs",
|
||||
"wxapkg",
|
||||
"tar",
|
||||
"ar",
|
||||
"dds",
|
||||
"glb",
|
||||
"ktx",
|
||||
@@ -261,7 +263,7 @@ export const artifactOccurrenceSchema = z.object({
|
||||
artifact_format: artifactFormatSchema,
|
||||
declared_size: z.int().min(0).max(Number.MAX_SAFE_INTEGER).nullable(),
|
||||
compressed_size: z.int().min(0).max(Number.MAX_SAFE_INTEGER).nullable(),
|
||||
executable: z.boolean(),
|
||||
executable: z.boolean().nullable(),
|
||||
encrypted: z.boolean(),
|
||||
/** Reader-observed ASAR storage; omission leaves historical storage unknown. */
|
||||
unpacked: z.boolean().exactOptional(),
|
||||
|
||||
@@ -49,3 +49,17 @@ it("keeps Evidence recorded before Kubernetes audit-log admission", () => {
|
||||
DEFAULT_KUBERNETES_AUDIT_LOG_READER_LIMITS,
|
||||
);
|
||||
});
|
||||
|
||||
it("resolves ar header counts from the shared setting and keeps historical Evidence", () => {
|
||||
expect(resolveArtifactReaderLimits(undefined, 12).ar.header_count).toBe(12);
|
||||
expect(
|
||||
resolveArtifactReaderLimits({ ar: { header_count: 3 } }, 12).ar
|
||||
.header_count,
|
||||
).toBe(3);
|
||||
const { ar: _omitted, ...recorded } = resolveArtifactReaderLimits();
|
||||
expect(artifactReaderLimitsSchema.parse(recorded)).toEqual(recorded);
|
||||
expect(
|
||||
artifactReaderLimitsInputSchema.safeParse({ ar: { name_bytes: 0 } })
|
||||
.success,
|
||||
).toBe(false);
|
||||
});
|
||||
@@ -228,6 +228,20 @@ export const zipReaderLimitsSchema = z.strictObject({
|
||||
member_count: count,
|
||||
});
|
||||
|
||||
export const DEFAULT_AR_READER_LIMITS = {
|
||||
header_count: DEFAULT_ARTIFACT_MEMBER_COUNT,
|
||||
name_bytes: 4096,
|
||||
name_table_bytes: 4 * 1024 * 1024,
|
||||
retained_name_bytes: 8 * 1024 * 1024,
|
||||
};
|
||||
export const arReaderLimitsSchema = z.strictObject({
|
||||
header_count: count,
|
||||
name_bytes: representedBytes,
|
||||
name_table_bytes: representedBytes,
|
||||
retained_name_bytes: bytes,
|
||||
});
|
||||
export type ArReaderLimits = z.output<typeof arReaderLimitsSchema>;
|
||||
|
||||
export const DEFAULT_TAR_READER_LIMITS = {
|
||||
extended_header_bytes: 1024 * 1024,
|
||||
metadata_bytes: 64 * 1024 * 1024,
|
||||
@@ -435,6 +449,19 @@ export const artifactReaderLimitsInputSchema = z.strictObject({
|
||||
.describe(
|
||||
`ZIP admission; omitted fields use ${JSON.stringify(DEFAULT_ZIP_READER_LIMITS)}. Member count bounds central-directory records retained for one archive, including zero-byte members.`,
|
||||
),
|
||||
ar: z
|
||||
.strictObject({
|
||||
header_count: arReaderLimitsSchema.shape.header_count.exactOptional(),
|
||||
name_bytes: arReaderLimitsSchema.shape.name_bytes.exactOptional(),
|
||||
name_table_bytes:
|
||||
arReaderLimitsSchema.shape.name_table_bytes.exactOptional(),
|
||||
retained_name_bytes:
|
||||
arReaderLimitsSchema.shape.retained_name_bytes.exactOptional(),
|
||||
})
|
||||
.exactOptional()
|
||||
.describe(
|
||||
`ar admission; omitted fields use ${JSON.stringify(DEFAULT_AR_READER_LIMITS)}. Header count includes name and symbol tables. Name bytes apply before decoding; retained bytes count source and logical names, including repeated references.`,
|
||||
),
|
||||
tar: z
|
||||
.strictObject({
|
||||
extended_header_bytes:
|
||||
@@ -478,6 +505,7 @@ const readerLimitGroups = {
|
||||
deno: denoReaderLimitsSchema,
|
||||
wxapkg: wxapkgReaderLimitsSchema,
|
||||
zip: zipReaderLimitsSchema,
|
||||
ar: arReaderLimitsSchema,
|
||||
tar: tarReaderLimitsSchema,
|
||||
kubernetes_audit_log: kubernetesAuditLogReaderLimitsSchema,
|
||||
} as const;
|
||||
@@ -498,6 +526,7 @@ export const artifactReaderLimitsSchema =
|
||||
android_super_image: androidSuperImageReaderLimitsSchema.exactOptional(),
|
||||
media_asset: mediaAssetReaderLimitsSchema.exactOptional(),
|
||||
android_dtbo: androidDtboReaderLimitsSchema.exactOptional(),
|
||||
ar: arReaderLimitsSchema.exactOptional(),
|
||||
zip: zipReaderLimitsSchema.exactOptional(),
|
||||
kubernetes_audit_log: kubernetesAuditLogReaderLimitsSchema.exactOptional(),
|
||||
});
|
||||
@@ -512,6 +541,7 @@ export const ARTIFACT_MEMBER_COUNT_PARAMETERS = [
|
||||
"artifact_limits.node_sea.asset_count",
|
||||
"artifact_limits.deno.vfs_entries",
|
||||
"artifact_limits.zip.member_count",
|
||||
"artifact_limits.ar.header_count",
|
||||
] as const satisfies readonly ArtifactReaderLimitParameter[];
|
||||
|
||||
export const resolveArtifactReaderLimits = (
|
||||
@@ -566,6 +596,11 @@ export const resolveArtifactReaderLimits = (
|
||||
member_count: memberCount,
|
||||
...selected?.zip,
|
||||
},
|
||||
ar: {
|
||||
...DEFAULT_AR_READER_LIMITS,
|
||||
header_count: memberCount,
|
||||
...selected?.ar,
|
||||
},
|
||||
tar: { ...DEFAULT_TAR_READER_LIMITS, ...selected?.tar },
|
||||
kubernetes_audit_log: {
|
||||
...DEFAULT_KUBERNETES_AUDIT_LOG_READER_LIMITS,
|
||||
@@ -593,6 +628,8 @@ export const artifactMemberCountSelected = (
|
||||
return selected?.node_sea?.asset_count !== undefined;
|
||||
case "artifact_limits.deno.vfs_entries":
|
||||
return selected?.deno?.vfs_entries !== undefined;
|
||||
case "artifact_limits.ar.header_count":
|
||||
return selected?.ar?.header_count !== undefined;
|
||||
case "artifact_limits.zip.member_count":
|
||||
return selected?.zip?.member_count !== undefined;
|
||||
}
|
||||
|
||||
@@ -1,4 +1,10 @@
|
||||
import { z } from "zod";
|
||||
import {
|
||||
AR_HEADER_BYTES,
|
||||
AR_MAGIC,
|
||||
readArHeader,
|
||||
arInlineName,
|
||||
} from "../arFormat.js";
|
||||
|
||||
import {
|
||||
parameterBudgetLimitFor,
|
||||
@@ -158,56 +164,29 @@ export const DEB_CONTROL_RELATIONSHIP_NAMES: Readonly<
|
||||
};
|
||||
|
||||
/** Global magic that begins every Unix ar archive, including Debian `.deb`. */
|
||||
export const DEB_AR_MAGIC = Buffer.from("!<arch>\n", "ascii");
|
||||
export const DEB_AR_MAGIC = AR_MAGIC;
|
||||
/** Fixed 60-byte header preceding each Unix ar member. */
|
||||
export const DEB_AR_HEADER_BYTES = 60;
|
||||
export const DEB_AR_HEADER_BYTES = AR_HEADER_BYTES;
|
||||
|
||||
const trimArField = (value: string): string => {
|
||||
const nul = value.indexOf("\0");
|
||||
return (nul === -1 ? value : value.slice(0, nul)).trim();
|
||||
};
|
||||
|
||||
/**
|
||||
* Whether leading bytes begin a Debian `.deb` package: Unix ar magic
|
||||
* (`!<arch>\n`) followed by a valid first member header whose name is
|
||||
* `debian-binary` (plain, SysV `debian-binary/`, or BSD `#1/N`).
|
||||
*/
|
||||
/** A Debian package starts with the exact debian-binary ar member. */
|
||||
export const hasDebPackageHeader = (prefix: Uint8Array): boolean => {
|
||||
const headerEnd = DEB_AR_MAGIC.length + DEB_AR_HEADER_BYTES;
|
||||
if (prefix.length < headerEnd) return false;
|
||||
for (let i = 0; i < DEB_AR_MAGIC.length; i++)
|
||||
if (prefix[i] !== DEB_AR_MAGIC[i]) return false;
|
||||
const header = prefix.subarray(DEB_AR_MAGIC.length, headerEnd);
|
||||
if (header[58] !== 0x60 || header[59] !== 0x0a) return false;
|
||||
const sizeText = trimArField(
|
||||
Buffer.from(header.buffer, header.byteOffset + 48, 10).toString("ascii"),
|
||||
const end = AR_MAGIC.length + AR_HEADER_BYTES;
|
||||
if (prefix.length < end || !AR_MAGIC.every((byte, i) => prefix[i] === byte))
|
||||
return false;
|
||||
const parsed = readArHeader(prefix.subarray(AR_MAGIC.length, end));
|
||||
if (!parsed.ok) return false;
|
||||
const { name, size } = parsed.value;
|
||||
if (name.kind === "short") return name.value === "debian-binary";
|
||||
if (
|
||||
name.kind !== "bsd-inline" ||
|
||||
name.length > size ||
|
||||
name.length > prefix.length - end
|
||||
)
|
||||
return false;
|
||||
const value = arInlineName(
|
||||
Buffer.from(prefix.subarray(end, end + name.length)),
|
||||
);
|
||||
if (!/^\d+$/u.test(sizeText)) return false;
|
||||
const size = Number(sizeText);
|
||||
if (!Number.isSafeInteger(size)) return false;
|
||||
const rawName = trimArField(
|
||||
Buffer.from(header.buffer, header.byteOffset, 16).toString("ascii"),
|
||||
);
|
||||
if (rawName.startsWith("#1/")) {
|
||||
const lengthText = rawName.slice(3);
|
||||
if (!/^\d+$/u.test(lengthText)) return false;
|
||||
const nameLength = Number(lengthText);
|
||||
if (
|
||||
!Number.isSafeInteger(nameLength) ||
|
||||
nameLength > size ||
|
||||
headerEnd + nameLength > prefix.length
|
||||
)
|
||||
return false;
|
||||
const extended = trimArField(
|
||||
Buffer.from(
|
||||
prefix.buffer,
|
||||
prefix.byteOffset + headerEnd,
|
||||
nameLength,
|
||||
).toString("ascii"),
|
||||
);
|
||||
return extended === "debian-binary";
|
||||
}
|
||||
return rawName.replace(/\/$/u, "") === "debian-binary";
|
||||
return value !== null && value.equals(Buffer.from("debian-binary"));
|
||||
};
|
||||
|
||||
/** ar member role from its stored name; unknown members stay flagged, not guessed. */
|
||||
|
||||
@@ -101,6 +101,7 @@ export const PE_OVERLAY_LEADING_FORMATS = [
|
||||
"ntfs-mft",
|
||||
"plist",
|
||||
"tar",
|
||||
"ar",
|
||||
"dds",
|
||||
"glb",
|
||||
"ktx",
|
||||
|
||||
@@ -26,6 +26,7 @@ export const BINARY_TARGET_FORMAT_KINDS = {
|
||||
unityfs: "archive",
|
||||
wxapkg: "archive",
|
||||
tar: "archive",
|
||||
ar: "archive",
|
||||
dds: "archive",
|
||||
glb: "archive",
|
||||
ktx: "archive",
|
||||
|
||||
@@ -84,7 +84,8 @@ export interface ArtifactEntry {
|
||||
readonly kind: "file" | "directory" | "symlink" | "slice" | "metadata";
|
||||
readonly declaredSize: number | null;
|
||||
readonly compressedSize: number | null;
|
||||
readonly executable: boolean;
|
||||
/** null means the source did not provide readable permission bits. */
|
||||
readonly executable: boolean | null;
|
||||
readonly encrypted: boolean;
|
||||
readonly byteOffset: number | null;
|
||||
/** Stored source extent; expanded size may differ for compressed members. */
|
||||
@@ -270,6 +271,7 @@ export interface ArtifactReader {
|
||||
| "unityfs"
|
||||
| "wxapkg"
|
||||
| "tar"
|
||||
| "ar"
|
||||
| "dds"
|
||||
| "glb"
|
||||
| "ktx"
|
||||
|
||||
@@ -57,6 +57,25 @@ interface ReaderCase {
|
||||
}
|
||||
|
||||
const readers: readonly ReaderCase[] = [
|
||||
{
|
||||
format: "ar",
|
||||
create: () => {
|
||||
const member = (name: string) =>
|
||||
Buffer.from(
|
||||
`${name.padEnd(16)}${"0".padEnd(12)}${"0".padEnd(6)}${"0".padEnd(6)}${"100644".padEnd(8)}${"0".padEnd(10)}\u0060\n`,
|
||||
);
|
||||
return Buffer.concat([
|
||||
Buffer.from("!<arch>\n"),
|
||||
member("one.o/"),
|
||||
member("two.o/"),
|
||||
]);
|
||||
},
|
||||
lower: { ar: { header_count: 1 } },
|
||||
raised: { ar: { header_count: 2 } },
|
||||
parameter: "artifact_limits.ar.header_count",
|
||||
value: 1,
|
||||
},
|
||||
|
||||
{
|
||||
format: "bun-standalone",
|
||||
create: () =>
|
||||
@@ -477,6 +496,7 @@ test("admits explicit member counts without reading an invalid artifact.member_c
|
||||
node_sea: { asset_count: 2 },
|
||||
deno: { vfs_entries: 2 },
|
||||
zip: { member_count: 2 },
|
||||
ar: { header_count: 2 },
|
||||
}),
|
||||
],
|
||||
environment,
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { sha256 } from "../../../support/sha256.js";
|
||||
import { artifactInventoryResultSchema } from "../../../../src/domain/artifactGraph.js";
|
||||
import { projectCliAnalysisResult } from "../../../../src/cli/projectCliAnalysisResult.js";
|
||||
import { writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
@@ -191,7 +193,7 @@ it("keeps bytes that only resemble a pyc frame unsupported", async () => {
|
||||
).resolves.toMatchObject({ code: "target_unavailable" });
|
||||
});
|
||||
|
||||
it("keeps a plain ar archive that is not a Debian package unsupported", async () => {
|
||||
it("inventories a plain ar archive and its members", async () => {
|
||||
const directory = await createTestTempDirectory("rea-standalone-format-");
|
||||
const path = join(directory, "libhello.a");
|
||||
await writeFile(
|
||||
@@ -199,11 +201,22 @@ it("keeps a plain ar archive that is not a Debian package unsupported", async ()
|
||||
arArchive([{ name: "hello.o", data: Buffer.from("object") }]),
|
||||
);
|
||||
|
||||
await expect(
|
||||
runProviderAnalysis(path, "inspect_artifact", {}).then(
|
||||
const evidence = parseEvidence(
|
||||
await runProviderAnalysis(path, "inspect_artifact", {}).then(
|
||||
projectCliAnalysisResult,
|
||||
),
|
||||
).resolves.toMatchObject({ code: "target_unavailable" });
|
||||
);
|
||||
const inspection = artifactInspectionResultSchema.parse(
|
||||
evidence.normalized_result,
|
||||
);
|
||||
expect(inspection.subject.root_format).toBe("ar");
|
||||
expect(
|
||||
inspection.substeps[0]?.evidence.normalized_result.occurrences,
|
||||
).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({ logical_path: "hello.o" }),
|
||||
]),
|
||||
);
|
||||
});
|
||||
|
||||
it("inventories an Image4 IM4P payload", async () => {
|
||||
@@ -338,3 +351,74 @@ it("routes an ESP flash dump with a populated NVS partition to inspect_esp_nvs",
|
||||
}),
|
||||
]);
|
||||
});
|
||||
|
||||
it("retains the ar prefix and exact reader-limit recovery through public inspection", async () => {
|
||||
const directory = await createTestTempDirectory("rea-ar-admission-");
|
||||
const path = join(directory, "archive.a");
|
||||
await writeFile(
|
||||
path,
|
||||
arArchive([
|
||||
{ name: "first.o", data: Buffer.from("first") },
|
||||
{ name: "second.o", data: Buffer.from("second") },
|
||||
]),
|
||||
);
|
||||
const refused = projectCliAnalysisResult(
|
||||
await runProviderAnalysis(path, "inspect_artifact", {
|
||||
artifact_limits: { ar: { header_count: 1 } },
|
||||
}),
|
||||
);
|
||||
expect(refused).toMatchObject({
|
||||
code: "partial",
|
||||
details: {
|
||||
reader_limit: {
|
||||
parameter: "artifact_limits.ar.header_count",
|
||||
effective_value: 1,
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(refused).toHaveProperty("details.partial_observation");
|
||||
const partial = (refused as { details: { partial_observation: unknown } })
|
||||
.details.partial_observation;
|
||||
const prefix = artifactInventoryResultSchema.parse(
|
||||
parseEvidence(partial).normalized_result,
|
||||
);
|
||||
expect(prefix.coverage.status).toBe("unknown");
|
||||
const first = prefix.occurrences.find(
|
||||
(row) => row.logical_path === "first.o",
|
||||
);
|
||||
expect(first?.hash_status).toBe("verified");
|
||||
expect(
|
||||
prefix.nodes.find((node) => node.artifact_id === first?.artifact_id)
|
||||
?.sha256,
|
||||
).toBe(sha256(Buffer.from("first")));
|
||||
expect(
|
||||
prefix.occurrences.some((row) => row.logical_path === "second.o"),
|
||||
).toBe(false);
|
||||
const evidence = parseEvidence(
|
||||
projectCliAnalysisResult(
|
||||
await runProviderAnalysis(path, "inspect_artifact", {
|
||||
artifact_limits: { ar: { header_count: 2 } },
|
||||
}),
|
||||
),
|
||||
);
|
||||
const inspection = artifactInspectionResultSchema.parse(
|
||||
evidence.normalized_result,
|
||||
);
|
||||
const source = inspection.substeps.find(
|
||||
(step) => step.operation === "inventory_artifact",
|
||||
)?.evidence;
|
||||
const inventory = artifactInventoryResultSchema.parse(
|
||||
source?.normalized_result,
|
||||
);
|
||||
expect(
|
||||
inventory.occurrences.some(
|
||||
(row) => row.logical_path === "first.o" && row.hash_status === "verified",
|
||||
),
|
||||
).toBe(true);
|
||||
expect(
|
||||
inventory.occurrences.some(
|
||||
(row) =>
|
||||
row.logical_path === "second.o" && row.hash_status === "verified",
|
||||
),
|
||||
).toBe(true);
|
||||
});
|
||||
Reference in new issue
Block a user