Files
reverse-engineering-anything/src/android/AndroidJniLibraries.ts
T
Adolanium 996ab6e2ae fix(zip): bound the member count of a ZIP inventory (#14997)
* fix(limits): admit a ZIP member count on reader limits

artifact.member_count now resolves artifact_limits.zip.member_count. Recorded Evidence from before this group may omit zip.

* fix(zip): refuse a central directory past the member count

Count every central-directory record before retaining it. The refusal omits required_value because later records stay unread.

* test(zip): cover a central directory past the member count

Three empty members at a count of two refuse through the reader and through the zip format reader.

* docs(limits): name zip.member_count on the member-count setting

The existing REA_ARTIFACT_MEMBER_COUNT seed already supplies that default.

* test(artifacts): select the ZIP member count with the explicit fields

The acceptance case ignores an invalid artifact.member_count seed only when every backed field is selected. zip.member_count is one of those fields.

* fix(schemas): record the ZIP member-count input summaries

extract_artifact and inspect_artifact changed their input compact schema when zip.member_count was advertised.

* fix(zip): keep member count on Flutter, Playwright, and SAZ

Those readers omitted the session count and described the refusal as a byte budget. They now admit artifact.member_count and report the count.

* test(zip): cover member-count refusals outside artifact inventory

A two-member archive at a session count of one stays a count for Flutter, Playwright traces, and SAZ. One member still passes that cap.

* docs(limits): name the ZIP consumers of artifact.member_count

Flutter APK inventory, Playwright trace import, and SAZ decoding use the session count and report it as a count.

* fix(capture): read the fixed-limit boundary from the ceiling

CaptureFormatError keeps that boundary on ceiling. The SAZ reply read cause.boundary, so a fixed-limit reply omitted the field the parent requires.

* fix(limits): recover ZIP member count through the session setting

Flutter, Playwright, and SAZ have no artifact_limits argument. The refusal names artifact.member_count, leaves parameter unset, and tells the caller to raise that setting. sessionSettingConstraint owns the error next to the other resource refusals.

* fix(android): keep a partial JNI report at the ZIP member count

readAndroidJniLibraries already returns a partial inventory when its entry allowance stops the scan. The session member count is that same stop. The reader takes artifact.member_count, and the report names the unexamined remainder instead of aborting the inspection.

* fix(zip): resolve the member count from the selected environment

ZIP admission and its refusal use the launch environment selected for the runtime. Only SAZ sends that count to the capture decoder.

* fix(zip): drop the unused ZipReaderLimits export

Knip reports the type because no caller imports it. ZIP limits stay on the schema.

* fix(playwright): return an invalid member-count seed as a result

The trace catch uses the count captured before the failure. A configuration error stays a Result and keeps the archive hash.

* fix(jni): name the member count on a partial library scan

The partial report keeps the count that stopped the scan and the recovery for artifact.member_count.

* fix(settings): register artifact.member_count for its ZIP consumers

Scoped inspection of the Flutter, Playwright, capture, and JNI operations includes the setting.

* test(artifacts): parse Evidence that omits the audit-log policy

The merged reader-limit schema still accepts a record that omits the Kubernetes audit-log policy.
2026-11-29 13:08:56 -05:00

365 lines
14 KiB
TypeScript

import {
ArtifactReaderFailure,
type ArtifactResourceScope,
streamChunkToBuffer,
yieldArtifactRead,
ZipArtifactReader,
} from "../resources/index.js";
import type {
AndroidJniLibraryObservation,
AndroidJniReport,
AndroidJniSelection,
AndroidJniLibraryCheckpoint,
} from "../domain/android/androidJniBindings.js";
import { compileAndroidJniLibrarySelection } from "../domain/android/androidJniBindings.js";
import { AnalysisError } from "../domain/analysisErrorBase.js";
import { jsonValueByteLength } from "../domain/jsonValueByteLength.js";
import type { JsonValue } from "../domain/jsonValue.js";
import { inspectAndroidJniLibrary } from "../domain/android/androidJniLibrary.js";
import {
JadxInterruption,
throwIfJadxInterrupted,
} from "./JadxInterruption.js";
import { ProviderCleanupError } from "../domain/providerCleanupError.js";
import { analysisErrorWithCleanupFailure } from "../domain/analysisErrorCleanup.js";
import { analysisClientFailureForOperation } from "../providers/AnalysisClientFailure.js";
import { errorMessage } from "../kernel/errorMessage.js";
import { sha256Hex } from "../kernel/sha256Hex.js";
import { invariantViolation } from "../domain/internalInvariant.js";
import type { AnalysisSettingsReader } from "../domain/analysisSettings.js";
import {
operationZipMemberCount,
zipMemberCountReason,
ZIP_MEMBER_COUNT_PARAMETER,
} from "../config/artifactMemberCount.js";
/** Bounds cover the live library buffer, completed scan work and retained JSON separately. */
export const ANDROID_JNI_LIBRARY_LIMITS = Object.freeze({
libraryBytes: 64 * 1024 * 1024,
totalBytes: 256 * 1024 * 1024,
factsBytes: 16 * 1024 * 1024,
entries: 100_000,
libraries: 2048,
});
export interface AndroidJniLibraries {
readonly libraries: readonly AndroidJniLibraryObservation[];
readonly inventory: AndroidJniReport["library_inventory"];
}
/** A library read failure, with the reader check an `integrity` failure names. */
const jniReadFailure = (
cause: unknown,
): NonNullable<AndroidJniLibraryObservation["failure"]> => {
if (cause instanceof AnalysisError) throw cause;
const message = errorMessage(cause);
if (!(cause instanceof ArtifactReaderFailure)) return { kind: "io", message };
// The library report has only a message, so a reader-named ceiling's
// narrowing (such as recompressing a Zstandard member) travels in it.
const narrowing = cause.fixedAllowance?.narrowing;
if (cause.reason !== "integrity")
return {
kind: cause.reason,
message: narrowing === undefined ? message : `${message} ${narrowing}`,
};
if (cause.integrityCheck === undefined)
throw invariantViolation(
"An integrity reader failure reached the JNI inventory without its check.",
{ cause },
);
return {
kind: "integrity",
message,
integrity_check: cause.integrityCheck,
};
};
/** Read each exact ZIP occurrence once from the provider's immutable admitted APK. */
export const readAndroidJniLibraries = async (input: {
readonly snapshot: string;
readonly apkSha256: string;
readonly selection: AndroidJniSelection;
readonly resources: ArtifactResourceScope;
readonly signal: AbortSignal;
readonly interruption: (reason: unknown) => AnalysisError;
readonly onObservation: (checkpoint: AndroidJniLibraryCheckpoint) => void;
readonly environment?: Readonly<Record<string, string | undefined>>;
readonly settings?: AnalysisSettingsReader;
}): Promise<AndroidJniLibraries> =>
input.resources
.run(async () => {
const memberCount = operationZipMemberCount(
input.environment ?? process.env,
input.settings,
);
const reader = new ZipArtifactReader(
input.snapshot,
"apk",
ANDROID_JNI_LIBRARY_LIMITS.factsBytes,
undefined,
undefined,
memberCount.value,
);
const owner = {
kind: "reader" as const,
resource: input.snapshot,
reader,
};
const libraries: AndroidJniLibraryObservation[] = [];
const inventory: AndroidJniReport["library_inventory"] = {
status: "complete",
examined_entries: 0,
selected_libraries: 0,
unknowns: [],
};
let totalBytes = 0;
let factsBytes = 0;
let primary: unknown;
let failed = false;
let inProgress: AndroidJniLibraryObservation | undefined;
const selectLibrary = compileAndroidJniLibrarySelection(input.selection);
try {
for await (const entry of reader.entries(input.signal)) {
throwIfJadxInterrupted(input.signal);
const source_index = inventory.examined_entries++;
if (inventory.examined_entries > ANDROID_JNI_LIBRARY_LIMITS.entries) {
inventory.status = "partial";
inventory.unknowns.push(
"APK entry inventory exceeded the bounded entry allowance; remaining libraries are unknown.",
);
break;
}
const match = /^lib\/([^/]+)\/([^/]+\.so)$/u.exec(entry.path);
if (match === null || entry.kind === "directory") continue;
const abi = match[1]!;
if (!selectLibrary({ abi, path: entry.path })) continue;
if (libraries.length >= ANDROID_JNI_LIBRARY_LIMITS.libraries) {
inventory.status = "partial";
inventory.unknowns.push(
"Selected native-library occurrence inventory exceeded its retained-state allowance.",
);
break;
}
const identity = {
library_id: `jni_library_${sha256Hex(JSON.stringify([input.apkSha256, entry.adapterKey]))}`,
source_index,
source_key: entry.adapterKey,
path: entry.path,
source_path: entry.sourcePath ?? entry.path,
abi,
sha256: null,
size: null,
declared_size: entry.declaredSize,
compressed_size: entry.compressedSize,
};
inProgress = {
...identity,
facts: null,
failure: {
kind: "incomplete",
message: "Native-library inspection did not complete",
},
};
let observation: AndroidJniLibraryObservation;
const limit =
entry.declaredSize === null ||
!Number.isSafeInteger(entry.declaredSize) ||
entry.declaredSize < 0 ||
entry.declaredSize > ANDROID_JNI_LIBRARY_LIMITS.libraryBytes ||
entry.declaredSize >
ANDROID_JNI_LIBRARY_LIMITS.totalBytes - totalBytes;
if (entry.kind !== "file" || entry.encrypted || limit) {
observation = {
...identity,
facts: null,
failure: {
kind: entry.encrypted
? "encrypted"
: entry.kind !== "file"
? "unsupported"
: "capacity",
message: entry.encrypted
? "Selected native library is encrypted."
: entry.kind !== "file"
? "Selected native library is not a regular ZIP member."
: "Selected native library exceeds the bounded library or cumulative scan-byte allowance.",
},
};
} else {
totalBytes += entry.declaredSize!;
try {
const bytes = Buffer.alloc(entry.declaredSize!);
let offset = 0;
const stream = await reader.open(entry, input.signal);
try {
for await (const chunk of stream) {
throwIfJadxInterrupted(input.signal);
const data = streamChunkToBuffer(chunk);
if (data.length > bytes.length - offset)
throw new ArtifactReaderFailure(
"integrity",
"Native library exceeds its declared ZIP size",
{ integrityCheck: "declared-size" },
);
data.copy(bytes, offset);
offset += data.length;
}
} finally {
stream.destroy();
}
if (offset !== bytes.length)
throw new ArtifactReaderFailure(
"integrity",
"Native library is shorter than its declared ZIP size",
{ integrityCheck: "declared-size" },
);
throwIfJadxInterrupted(input.signal);
const sha256 = sha256Hex(bytes);
inProgress = {
...identity,
sha256,
size: bytes.length,
facts: null,
failure: {
kind: "incomplete",
message: "Native-library parsing did not complete",
},
};
const parsed = await inspectAndroidJniLibrary(bytes, {
signal: input.signal,
pause: () => yieldArtifactRead(input.signal),
});
throwIfJadxInterrupted(input.signal);
observation = {
...identity,
sha256,
size: bytes.length,
facts: parsed.ok ? parsed.value : null,
failure: parsed.ok ? null : parsed.error,
};
} catch (cause: unknown) {
if (cause instanceof JadxInterruption) throw cause;
if (
cause instanceof ArtifactReaderFailure &&
cause.reason === "cancelled"
)
throw input.interruption(input.signal.reason);
observation = {
...identity,
facts: null,
failure: jniReadFailure(cause),
};
}
}
factsBytes += jsonValueByteLength(
observation as unknown as JsonValue,
ANDROID_JNI_LIBRARY_LIMITS.factsBytes,
);
if (factsBytes > ANDROID_JNI_LIBRARY_LIMITS.factsBytes) {
inventory.status = "partial";
inventory.unknowns.push(
"Selected native-library facts exceed the retained-facts allowance; remaining occurrences are unknown.",
);
break;
}
libraries.push(observation);
inProgress = undefined;
}
inventory.selected_libraries = libraries.length;
throwIfJadxInterrupted(input.signal);
} catch (cause: unknown) {
// The entry allowance returns a partial inventory. A session member
// count is that same stop, so the report stays reachable.
const readerLimit =
cause instanceof ArtifactReaderFailure && cause.reason === "limit"
? cause.readerLimit
: undefined;
if (readerLimit?.parameter === ZIP_MEMBER_COUNT_PARAMETER) {
inventory.status = "partial";
const stopped =
readerLimit.effective_value === memberCount.value
? memberCount.value
: readerLimit.effective_value;
inventory.unknowns.push(
`${zipMemberCountReason(stopped)} Remaining libraries are unknown.`,
);
} else {
failed = true;
primary =
cause instanceof JadxInterruption
? input.interruption(cause.reason)
: cause instanceof ArtifactReaderFailure &&
cause.reason === "cancelled"
? input.interruption(input.signal.reason)
: cause;
}
}
if (failed) {
inventory.status = "partial";
inventory.unknowns.push(
"Native-library scan did not exhaust APK inventory; unexamined selected occurrences remain unknown.",
);
}
if (inProgress !== undefined) {
// An interrupted member still has an observed carrier identity; retain
// its digest only if those bytes actually completed authentication.
libraries.push(inProgress);
}
inventory.selected_libraries = libraries.length;
const checkpoint: AndroidJniLibraryCheckpoint = {
scan_state:
failed || inventory.status !== "complete"
? "interrupted"
: "completed",
libraries: [...libraries],
inventory: { ...inventory, unknowns: [...inventory.unknowns] },
};
try {
input.onObservation(checkpoint);
} catch (cause: unknown) {
if (!failed) {
failed = true;
primary = cause;
}
}
const released = await input.resources.release(owner);
if (released.kind === "failed") {
const operation = "inspect_android_jni_bindings";
const cleanup = new ProviderCleanupError(
"jadx",
[owner.resource],
{
reason: errorMessage(released.cause),
},
{ operation, cause: released.cause },
);
if (!failed && input.signal.aborted) {
failed = true;
primary = input.interruption(input.signal.reason);
}
const failure = failed
? analysisErrorWithCleanupFailure(
primary instanceof AnalysisError
? primary
: analysisClientFailureForOperation(primary, "jadx", operation),
cleanup,
operation,
)
: cleanup;
released.lease.bindCleanupError(failure);
throw failure;
}
if (failed) throw primary;
throwIfJadxInterrupted(input.signal);
return { libraries, inventory };
})
.catch((cause: unknown) => {
// A prior owned close can reject scope admission before this callback runs.
if (cause instanceof ArtifactReaderFailure && cause.cleanup !== undefined)
throw analysisClientFailureForOperation(
cause,
"jadx",
"inspect_android_jni_bindings",
);
throw cause;
});