refactor(apk): project scheme limits from the parser (#12662)

* refactor(apk): project scheme limits from the parser

* fix(apk): establish scheme record framing before capacity
This commit is contained in:
morluto authored and GitHub committed 2026-11-20 01:38:54 +00:00
1 parent 273f048a55
commit 2a6786168a
7 files changed
+222 -121

No files matched your search

@@ -6,7 +6,7 @@
"src/android/JadxFailure.ts": 2,
"src/android/JadxSession.ts": 2,
"src/apkSignature/ApkSignatureAdmission.ts": 1,
"src/apkSignature/apkSignatureFailures.ts": 6,
"src/apkSignature/apkSignatureFailures.ts": 5,
"src/apktool/ApktoolConfiguration.ts": 1,
"src/application/JsonAuthenticationHeadroom.ts": 2,
"src/application/JsonInputFile.ts": 3,
+6 -6
View File
@@ -165,12 +165,13 @@ interface DecodedScheme {
const lineageOf = (
signer: ApkSigner,
version: Exclude<ApkSchemeVersion, "v2">,
): Result<DecodedSigner["rotation"], ApkSchemeError> => {
const attribute = signer.attributes.find(
(a) => a.id === PROOF_OF_ROTATION_ATTR_ID,
);
if (attribute === undefined) return ok({ present: false });
const nodes = decodeRotationLineage(attribute.value);
const nodes = decodeRotationLineage(attribute.value, version);
if (nodes.ok) return ok({ present: true, nodes: nodes.value });
// A malformed lineage is reported, not dropped; an over-cap lineage is refused.
return nodes.error.kind === "malformed-signer"
@@ -589,10 +590,7 @@ const sourceStampFacts = (
: {
present: true,
certificate: null,
decode_error:
certificate.error.kind === "malformed-signer"
? certificate.error.detail
: `more ${certificate.error.resource} than ${String(certificate.error.limit)}`,
decode_error: certificate.error.detail,
};
};
@@ -610,7 +608,9 @@ const decodeScheme = (
const decoded: DecodedSigner[] = [];
for (const signer of signers.value.signers) {
const rotation =
version === "v2" ? ok({ present: false } as const) : lineageOf(signer);
version === "v2"
? ok({ present: false } as const)
: lineageOf(signer, version);
if (!rotation.ok) return err(mapApkSchemeError(rotation.error, version));
decoded.push({ signer, rotation: rotation.value });
}
@@ -3,7 +3,6 @@ import { projectAnalysisError } from "../domain/analysisErrorProjection.js";
import {
apkOutputBudgetError,
mapApkBlockError,
mapApkSchemeError,
mapCentralDirectoryError,
v1SignerCapacityError,
} from "./apkSignatureFailures.js";
@@ -19,15 +18,6 @@ it.each([
"max_signing_block_pairs",
4096,
],
[
"scheme signers",
mapApkSchemeError(
{ kind: "budget-exceeded", resource: "signers", limit: 32 },
"v2",
),
"max_signers",
32,
],
[
"v1 entries",
mapCentralDirectoryError({
+15 -15
View File
@@ -20,6 +20,7 @@ import {
cancelledBy,
carriedReason,
} from "../domain/analysisErrorCore.js";
import { parseLimitConstraint } from "../domain/parseFailureAnalysisError.js";
import type { ApkSchemeError } from "../domain/apkSignature/apkSignatureSchemes.js";
import type { ApkSigningBlockError } from "../domain/apkSignature/apkSigningBlock.js";
import type { ApkCentralDirectoryError } from "../domain/apkSignature/apkV1Signature.js";
@@ -89,21 +90,20 @@ export const mapApkBlockError = (
export const mapApkSchemeError = (
error: ApkSchemeError,
scheme: string,
): AnalysisError =>
error.kind === "malformed-signer"
? inputError(
`Malformed APK Signature Scheme ${scheme} block: ${error.detail}.`,
)
: new AnalysisResourceConstraintError(
OPERATION,
"capacity",
`APK Signature Scheme ${scheme} holds more ${error.resource} than the ${String(error.limit)} limit.`,
{ [`max_${error.resource.replace(/-/g, "_")}`]: error.limit },
fixedAllowanceOptions(
`The APK Signature Scheme ${scheme} allowance of ${String(error.limit)} ${error.resource} (this release has no runtime override)`,
"count",
),
);
): AnalysisError => {
if (error.kind === "malformed-signer")
return inputError(
`Malformed APK Signature Scheme ${scheme} block: ${error.detail}.`,
);
const { name, maximum } = error.failure.limit;
return parseLimitConstraint(OPERATION, "capacity", error, {
legacyMaximumKey: `max_${name.replace(/-/g, "_")}`,
...fixedAllowanceOptions(
`The APK Signature Scheme ${scheme} allowance of ${String(maximum)} ${name} (this release has no runtime override)`,
"count",
),
});
};
/** A central directory that cannot be walked leaves v1 presence unknown: refuse. */
export const mapCentralDirectoryError = (
@@ -127,7 +127,7 @@ describe("APK scheme signer decoder", () => {
"refuses lineage nodes missing required algorithm/signature framing",
({ node }) => {
expect(
decodeRotationLineage(Uint8Array.from([...u32(1), ...lp(node)])),
decodeRotationLineage(Uint8Array.from([...u32(1), ...lp(node)]), "v3"),
).toMatchObject({ ok: false, error: { kind: "malformed-signer" } });
},
);
@@ -184,7 +184,7 @@ describe("APK scheme signer decoder", () => {
expect(result.error.kind).toBe("malformed-signer");
});
it("names the failing signer and keeps a cap overrun distinct from malformed input", () => {
it("names the failing signer", () => {
const truncated = decodeSigners(
Uint8Array.from(seq([lp([...seq([digestElement]), ...u32(99)])])),
"v3",
@@ -195,63 +195,6 @@ describe("APK scheme signer decoder", () => {
kind: "malformed-signer",
detail: expect.stringContaining("signer 0") as string,
});
const signedData = [
...seq([digestElement]),
...seq([CERT_DER]),
...seq([]),
];
const tooMany = decodeSigners(
Uint8Array.from(
seq(Array.from({ length: MAX_SIGNERS + 1 }, () => lp(signedData))),
),
"v2",
);
expect(tooMany.ok).toBe(false);
if (!tooMany.ok)
expect(tooMany.error).toEqual({
kind: "budget-exceeded",
resource: "signers",
limit: MAX_SIGNERS,
});
});
it("decodes lineage nodes with each node's own retained flags", () => {
const node = (cert: number[], flags: number): number[] =>
lp([
...lp([...lp(cert), ...u32(0x0103)]),
...u32(flags),
...u32(0x0103),
...lp([1]),
]);
const lineage = decodeRotationLineage(
Uint8Array.from([...u32(1), ...node([1, 2], 22), ...node([3, 4], 21)]),
);
expect(lineage.ok).toBe(true);
if (!lineage.ok) return;
expect(lineage.value.map((n) => [[...n.certificate], n.flags])).toEqual([
[[1, 2], 22],
[[3, 4], 21],
]);
});
it("refuses an unknown lineage version and an over-cap lineage", () => {
const badVersion = decodeRotationLineage(Uint8Array.from(u32(2)));
expect(badVersion.ok).toBe(false);
if (!badVersion.ok) expect(badVersion.error.kind).toBe("malformed-signer");
const node = lp([
...lp([...lp([1]), ...u32(0x0103)]),
...u32(0),
...u32(0x0103),
...lp([]),
]);
const tooLong = decodeRotationLineage(
Uint8Array.from([
...u32(1),
...Array.from({ length: MAX_LINEAGE_NODES + 1 }, () => node).flat(),
]),
);
expect(tooLong.ok).toBe(false);
if (!tooLong.ok) expect(tooLong.error.kind).toBe("budget-exceeded");
});
it("maps signature-algorithm ids to content-digest algorithms", () => {
@@ -262,3 +205,94 @@ describe("APK scheme signer decoder", () => {
expect(contentDigestAlgorithm(0x9999)).toBeNull();
});
});
it("distinguishes an extra framed signer from an incomplete frame at capacity", () => {
const signer = schemeValue([
...seq([digestElement]),
...seq([CERT_DER]),
...seq([]),
]).subarray(4);
const prefix = Array.from({ length: MAX_SIGNERS }, () => [...signer]).flat();
expect(decodeSigners(Uint8Array.from(lp(prefix)), "v2").ok).toBe(true);
expect(
decodeSigners(Uint8Array.from(lp([...prefix, ...signer])), "v2"),
).toMatchObject({
ok: false,
error: {
kind: "limit",
failure: { limit: { name: "signers", maximum: MAX_SIGNERS } },
},
});
for (const incomplete of [[1], [...u32(3), 1]]) {
expect(
decodeSigners(Uint8Array.from(lp([...prefix, ...incomplete])), "v2"),
).toMatchObject({
ok: false,
error: { kind: "malformed-signer", detail: "signers element truncated" },
});
}
});
describe("APK proof-of-rotation lineage", () => {
it("decodes lineage nodes with each node's own retained flags", () => {
const node = (cert: number[], flags: number): number[] =>
lp([
...lp([...lp(cert), ...u32(0x0103)]),
...u32(flags),
...u32(0x0103),
...lp([1]),
]);
const lineage = decodeRotationLineage(
Uint8Array.from([...u32(1), ...node([1, 2], 22), ...node([3, 4], 21)]),
"v3",
);
expect(lineage.ok).toBe(true);
if (!lineage.ok) return;
expect(lineage.value.map((n) => [[...n.certificate], n.flags])).toEqual([
[[1, 2], 22],
[[3, 4], 21],
]);
});
it("distinguishes incomplete lineage frames from an extra framed node at capacity", () => {
const badVersion = decodeRotationLineage(Uint8Array.from(u32(2)), "v3");
expect(badVersion.ok).toBe(false);
if (!badVersion.ok) expect(badVersion.error.kind).toBe("malformed-signer");
const node = lp([
...lp([...lp([1]), ...u32(0x0103)]),
...u32(0),
...u32(0x0103),
...lp([]),
]);
const prefix = [
...u32(1),
...Array.from({ length: MAX_LINEAGE_NODES }, () => node).flat(),
];
expect(decodeRotationLineage(Uint8Array.from(prefix), "v3.1").ok).toBe(
true,
);
const tooLong = decodeRotationLineage(
Uint8Array.from([...prefix, ...node]),
"v3.1",
);
expect(tooLong.ok).toBe(false);
if (!tooLong.ok)
expect(tooLong.error).toMatchObject({
kind: "limit",
failure: {
limit: { name: "lineage-nodes", maximum: MAX_LINEAGE_NODES },
},
});
for (const incomplete of [[1], [...u32(3), 1]]) {
expect(
decodeRotationLineage(
Uint8Array.from([...prefix, ...incomplete]),
"v3.1",
),
).toMatchObject({
ok: false,
error: { kind: "malformed-signer", detail: "lineage node truncated" },
});
}
});
});
+41 -30
View File
@@ -9,23 +9,20 @@
* certificate DER, SDK bounds, and additional attributes. Certificate facts and
* digest recomputation are layered on top. Dependency-free and bounded: a short
* or inconsistent length is a `malformed-signer` error, and a count past a
* resource admission cap is a distinct `budget-exceeded` error, never conflated.
* resource admission cap is a distinct typed parse limit.
*/
import { BinaryReader } from "../binaryContainer.js";
import { decodeLimit, type ParseFailureError } from "../parseFailure.js";
import { type Result, err, ok } from "../result.js";
export type ApkSchemeVersion = "v2" | "v3" | "v3.1";
export type ApkSchemeError =
| {
readonly kind: "malformed-signer";
readonly detail: string;
}
| {
readonly kind: "budget-exceeded";
readonly resource: string;
readonly limit: number;
};
interface ApkMalformedSigner {
readonly kind: "malformed-signer";
readonly detail: string;
}
export type ApkSchemeError = ApkMalformedSigner | ParseFailureError<"limit">;
export interface ApkSignerDigest {
/** APK signature-algorithm id (e.g. 0x0103 = RSA-PKCS1 SHA-256). */
@@ -106,23 +103,36 @@ class LeReader {
}
}
const malformed = (detail: string): Result<never, ApkSchemeError> =>
const malformed = (detail: string): Result<never, ApkMalformedSigner> =>
err({ kind: "malformed-signer", detail });
const schemeLimit = (
version: ApkSchemeVersion,
name: string,
maximum: number,
): Result<never, ParseFailureError<"limit">> =>
err(
decodeLimit(
"apk-signature-scheme",
`APK Signature Scheme ${version} holds more ${name} than the ${String(maximum)} limit.`,
{ name, maximum },
),
);
/** Split a length-prefixed sequence into its length-prefixed elements. */
const elements = (
seq: Uint8Array | null,
what: string,
version: ApkSchemeVersion,
limit = MAX_ELEMENTS,
): Result<Uint8Array[], ApkSchemeError> => {
if (seq === null) return malformed(`${what} sequence missing or truncated`);
const reader = new LeReader(seq);
const out: Uint8Array[] = [];
while (reader.remaining > 0) {
if (out.length >= limit)
return err({ kind: "budget-exceeded", resource: what, limit });
const el = reader.lenChunk();
if (el === null) return malformed(`${what} element truncated`);
if (out.length >= limit) return schemeLimit(version, what, limit);
out.push(el);
}
return ok(out);
@@ -131,13 +141,14 @@ const elements = (
const decodeAlgorithmRecords = <T>(
seq: Uint8Array | null,
what: string,
version: ApkSchemeVersion,
record: (
algorithmId: number,
bytes: Uint8Array,
uninterpretedBytes: number,
) => T,
): Result<T[], ApkSchemeError> => {
const items = elements(seq, what);
const items = elements(seq, what, version);
if (!items.ok) return items;
const records: T[] = [];
for (const item of items.value) {
@@ -153,8 +164,9 @@ const decodeAlgorithmRecords = <T>(
const decodeAttributes = (
seq: Uint8Array | null,
version: ApkSchemeVersion,
): Result<ApkSignerAttribute[], ApkSchemeError> => {
const items = elements(seq, "attributes");
const items = elements(seq, "attributes", version);
if (!items.ok) return items;
const attributes: ApkSignerAttribute[] = [];
for (const item of items.value) {
@@ -177,6 +189,7 @@ const decodeSignedData = (
const digests = decodeAlgorithmRecords(
reader.lenChunk(),
"digests",
version,
(algorithmId, digest, uninterpretedBytes) => ({
algorithmId,
digest,
@@ -184,7 +197,7 @@ const decodeSignedData = (
}),
);
if (!digests.ok) return digests;
const certificates = elements(reader.lenChunk(), "certificates");
const certificates = elements(reader.lenChunk(), "certificates", version);
if (!certificates.ok) return certificates;
let minSdk: number | null = null;
let maxSdk: number | null = null;
@@ -194,7 +207,7 @@ const decodeSignedData = (
if (minSdk === null || maxSdk === null)
return malformed("min/max SDK truncated");
}
const attributes = decodeAttributes(reader.lenChunk());
const attributes = decodeAttributes(reader.lenChunk(), version);
if (!attributes.ok) return attributes;
return ok({
certificates: certificates.value,
@@ -227,6 +240,7 @@ const decodeSigner = (
const signatures = decodeAlgorithmRecords(
reader.lenChunk(),
"signatures",
version,
(algorithmId, signature, uninterpretedBytes) => ({
algorithmId,
signature,
@@ -255,7 +269,7 @@ export const decodeSigners = (
version: ApkSchemeVersion,
): Result<ApkDecodedScheme, ApkSchemeError> => {
const reader = new LeReader(value);
const chunks = elements(reader.lenChunk(), "signers", MAX_SIGNERS);
const chunks = elements(reader.lenChunk(), "signers", version, MAX_SIGNERS);
if (!chunks.ok) return chunks;
const signers: ApkSigner[] = [];
for (const [index, chunk] of chunks.value.entries()) {
@@ -290,22 +304,19 @@ export interface ApkLineageNode {
*/
export const decodeRotationLineage = (
value: Uint8Array,
version: Exclude<ApkSchemeVersion, "v2">,
): Result<ApkLineageNode[], ApkSchemeError> => {
const reader = new LeReader(value);
const version = reader.u32();
if (version === null) return malformed("lineage version missing");
if (version !== LINEAGE_VERSION)
return malformed(`unsupported lineage version ${String(version)}`);
const lineageVersion = reader.u32();
if (lineageVersion === null) return malformed("lineage version missing");
if (lineageVersion !== LINEAGE_VERSION)
return malformed(`unsupported lineage version ${String(lineageVersion)}`);
const nodes: ApkLineageNode[] = [];
while (reader.remaining > 0) {
if (nodes.length >= MAX_LINEAGE_NODES)
return err({
kind: "budget-exceeded",
resource: "lineage-nodes",
limit: MAX_LINEAGE_NODES,
});
const node = reader.lenChunk();
if (node === null) return malformed("lineage node truncated");
if (nodes.length >= MAX_LINEAGE_NODES)
return schemeLimit(version, "lineage-nodes", MAX_LINEAGE_NODES);
const nodeReader = new LeReader(node);
const signedData = nodeReader.lenChunk();
const flags = nodeReader.u32();
@@ -331,7 +342,7 @@ export const decodeRotationLineage = (
*/
export const decodeSourceStampCertificate = (
value: Uint8Array,
): Result<Uint8Array, ApkSchemeError> => {
): Result<Uint8Array, ApkMalformedSigner> => {
const stampData = new LeReader(value).lenChunk();
if (stampData === null) return malformed("source stamp data truncated");
const certificate = new LeReader(stampData).lenChunk();
@@ -10,6 +10,11 @@ import { parseMcpToolError } from "../fixtures/mcpToolError.js";
import { connectLocalToolsMcp } from "../fixtures/localToolsMcp.js";
import { createTestTempDirectory } from "../fixtures/temporaryDirectory.js";
import {
APK_SIGNATURE_V2_ID,
APK_SIGNATURE_V3_ID,
LEAF_CERTIFICATE,
v2SchemeValue,
v3SchemeValue,
withSigningBlock,
zipWith,
} from "../fixtures/apkSignature/v1SignatureBlock.js";
@@ -80,3 +85,64 @@ cliTest(
}
},
);
cliTest(
"preserves the fixed signer and lineage refusals through CLI and MCP",
async ({ cli }) => {
const root = await createTestTempDirectory("rea-apk-scheme-limit-");
const archive = await zipWith([
{ name: "AndroidManifest.xml", data: Uint8Array.of(3, 0, 8, 0) },
]);
const signer = v2SchemeValue(LEAF_CERTIFICATE).subarray(4);
const signerLength = Buffer.alloc(4);
signerLength.writeUInt32LE(signer.length * 33);
const { call } = await connectLocalToolsMcp({
REA_MCP_OUTPUT_SCHEMA_PROFILE: "off",
});
for (const { id, value, scheme, boundary, key } of [
{
id: APK_SIGNATURE_V2_ID,
value: Buffer.concat([
signerLength,
...Array.from({ length: 33 }, () => signer),
]),
scheme: "v2",
boundary: "signers",
key: "max_signers",
},
{
id: APK_SIGNATURE_V3_ID,
value: v3SchemeValue(
null,
Array.from({ length: 33 }, () => LEAF_CERTIFICATE),
),
scheme: "v3",
boundary: "lineage-nodes",
key: "max_lineage_nodes",
},
]) {
const path = join(root, `${scheme}.apk`);
await writeFile(path, withSigningBlock(archive, [{ id, value }]));
const reply = await cli.run({
arguments: ["inspect-apk-signature", path, "--json"],
});
expect(reply.exitCode, reply.stderr).toBe(1);
const error = analysisErrorProjectionSchema.parse(reply.json);
expect(error).toMatchObject({
code: "resource_constraint",
retryable: false,
details: {
operation: "inspect_apk_signature",
resource: "capacity",
reason: `APK Signature Scheme ${scheme} holds more ${boundary} than the 32 limit.`,
},
});
expect(error.details?.reported_limits).toEqual({ [key]: 32 });
expect(error.remediation.action).toBe(
`The APK Signature Scheme ${scheme} allowance of 32 ${boundary} (this release has no runtime override) is a fixed count. Waiting for an active analysis to finish does not raise it. Repeating the unchanged request fails the same way.`,
);
const rejected = await call("inspect_apk_signature", { path });
expect(parseMcpToolError(rejected).error).toEqual(error);
}
},
);