mirror of
https://github.com/morluto/rea.git
synced 2026-11-17 04:04:25 +00:00
* test(mcp): check advertised schemas against a portable dialect in every profile * fix(mcp): re-emit advertised patterns in a portable regex grammar * fix(mcp): present discover_tools input through the selected profile The hot-cold catalog registered discover_tools directly with the SDK, so the default compact input profile still advertised its canonical schema, including page-size defaults clients apply on their own (#5322). Route every listed input schema, transport discovery included, through one server-owned presentation, and pass the selected presentation to the deferred server, which serves recorded tool schemas but not discovery. * fix(mcp): keep the Evidence union on described borrowed inputs borrowEvidenceInput installed its advertised projection on one schema instance. A call site's .describe() rebuilds the schema from its definition, so match_native_functions advertised left and right as unconstrained values in every input profile. Install the projection in the borrowed parser's constructor so derived schemas keep it, for both borrowed inputs and borrowed arrays. * fix(mcp): validate advertised dialect by selected profile * fix(mcp): preserve schema widening through references * feat(mcp): project compact input schemas into the portable advertised dialect One projection (advertisedDialectProjection.ts) owns the compact input advertisement: one type per node, items on every array, string literals as enums, oneOf widened to anyOf, allOf merged, tuples as element unions, exclusive bounds made inclusive, and every keyword outside the dialect dropped. Each rewrite is exact or widening; server validation is unchanged. The root description and sentences for dropped cross-field constraints move to the tool description, which Codex and Zed keep. The compact baseline falls to nullable values only (29), which the dialect cannot express without narrowing an input. The gateway shape repairs (typeArrayItemUnions, hasGatewayIncompatibleShape), the second dependentRequired-to-prose copy and the strict-gateway test denylist are removed; the dialect checker gates the inline presentation instead. * feat(mcp): omit output schemas from tools/list by default No surveyed model API reads an output schema, MCP client validators repeat REA's own result validation, and complete output schemas were about 92% of the default tools/list. REA_MCP_OUTPUT_SCHEMA_PROFILE now resolves to off through one owner (resolveMcpOutputSchemaProfile); compact and full remain selectable. structuredContent is still delivered, and the deferred server serves both off and full from the recorded catalog with the matching recorded identity. Tests and artifact verifiers that validate results against complete advertised output contracts select full explicitly. * docs: describe omitted output schemas as the default in README translations * fix(mcp): select schemas in verification workflows * fix(mcp): refuse zero-padded repeat bounds and record host-specific path patterns * fix(mcp): keep projected schemas permissive * fix(mcp): keep references valid when presentation widens their targets * fix(mcp): keep a single union branch's closure scoped to its properties * fix(mcp): select complete output schemas in the Electron verifier * fix(mcp): select complete output schemas in standalone verifier probes * fix(mcp): keep an allOf member's tuple tail with its own positions * fix(mcp): relax references into negations and conditionals presentation may remove * refactor(contracts): declare root discriminators as typed schema annotations * test(mcp): select the borrowed Evidence contract from its family * fix(mcp): keep astral literals and dynamic references widening in every mode * fix(mcp): omit astral literals and relax untracked references when presentation widens * fix(mcp): select complete output schemas in every verifier transport * fix(mcp): read reference pointers by schema position, not segment spelling * fix(mcp): protect references into collapsing boolean unions and keep referencing branches out of the collapse * fix(mcp): keep reduced schemas open when their root admits names by pattern * test(mcp): keep the reduced-schema pattern case outside the size-limited block * fix(mcp): omit patterns whose classes name astral characters * fix(mcp): decide union collapse and pointer protection from canonical branches * docs(mcp): document non-u astral matching and pin BMP agreement across V8 modes * fix(mcp): keep prototype-named properties as own properties in the dialect projection * test(mcp): select full output schemas in packet and signal schema checks * test(mcp): expect the advertised base64 schema to omit the unbounded pad-bit probe * fix(mcp): protect references into unevaluated keywords lost evaluation removes * fix(mcp): validate the doctor probe reply against the canonical output contract (#10655) * fix(mcp): validate the doctor probe reply against the canonical output contract * test(mcp): replay doctor probe validation under every output profile * test(mcp): accept typed-branch nullable unions in the advertised dialect (#10649) * test(mcp): select full output schemas in HTTP session workflows * fix(mcp): emit stack-safe classes with non-ASCII members and protect draft-07 reference siblings * fix(mcp): protect references into literal siblings of relaxed draft-07 references * feat(mcp): omit output schemas from tools/list by default (#10646) * feat(mcp): omit output schemas from tools/list by default No surveyed model API reads an output schema, MCP client validators repeat REA's own result validation, and complete output schemas were about 92% of the default tools/list. REA_MCP_OUTPUT_SCHEMA_PROFILE now resolves to off through one owner (resolveMcpOutputSchemaProfile); compact and full remain selectable. structuredContent is still delivered, and the deferred server serves both off and full from the recorded catalog with the matching recorded identity. Tests and artifact verifiers that validate results against complete advertised output contracts select full explicitly. * fix(mcp): select schemas in verification workflows * fix(mcp): select complete output schemas in the Electron verifier * fix(mcp): select complete output schemas in standalone verifier probes * fix(mcp): select complete output schemas in every verifier transport * test(mcp): select full output schemas in packet and signal schema checks * fix(mcp): validate the doctor probe reply against the canonical output contract (#10655) * fix(mcp): validate the doctor probe reply against the canonical output contract * test(mcp): replay doctor probe validation under every output profile * test(mcp): accept typed-branch nullable unions in the advertised dialect (#10649) * test(mcp): select full output schemas in HTTP session workflows * fix(mcp): keep the Evidence union on described borrowed inputs (#10597) * fix(mcp): keep the Evidence union on described borrowed inputs borrowEvidenceInput installed its advertised projection on one schema instance. A call site's .describe() rebuilds the schema from its definition, so match_native_functions advertised left and right as unconstrained values in every input profile. Install the projection in the borrowed parser's constructor so derived schemas keep it, for both borrowed inputs and borrowed arrays. * test(mcp): select the borrowed Evidence contract from its family * docs(mcp): admit baseline growth only for restored contract declarations * fix(mcp): state reduced multi-type properties as typed branches, not type lists The reduced fallback derived a property's types and emitted them as a type list, which Gemini, Moonshot and Ark reject. A property whose canonical schema is anyOf string and number therefore traded a typed union for a rejected construct when the inline projection fell back. Emit one type, or anyOf typed branches, so [T, null] becomes the dialect's nullable union. * feat(mcp)!: retire the full schema profiles and declare complete observations as a typed annotation (#10718) * refactor(mcp): declare complete observations as a typed annotation applied only on the wire * test(mcp): compare complete-observation declarations with their owning text * refactor(schema): couple Zod checks with their JSON Schema constraint keywords (#10725) * refactor(schema): couple Zod checks with their JSON Schema constraint keywords * refactor(schema): declare pattern approximations and object output roots as typed annotations (#10754) * refactor(schema): declare pattern approximations and object output roots as typed annotations * fix(schema): refuse pattern declarations JSON Schema cannot state * test(schema): select guided_workflows from its contract family * feat(mcp)!: retire the full input and output schema profiles (#10841) * feat(mcp)!: retire the full input and output schema profiles The compact input presentation is now the only advertised input schema, and output schemas are either omitted (`off`, the default) or bounded (`compact`). Catalog identity, the build-recorded digests and the recorded startup catalog collapse to those presentations: two digest profiles instead of six, one recorded catalog instead of two, and no input dialect baseline. Tests and verifiers that validated replies against listed full output schemas now validate against the canonical output contract, which REA already enforces server-side; tests that asserted canonical input restrictions read the canonical input schema instead of a full listing. BREAKING CHANGE: `REA_MCP_INPUT_SCHEMA_PROFILE=full` and `REA_MCP_OUTPUT_SCHEMA_PROFILE=full` are refused at startup and by `rea setup` with a configuration error naming the setting. Remove the setting from the client registration (or rerun setup with `REA_MCP_INPUT_SCHEMA_PROFILE=compact` / `REA_MCP_OUTPUT_SCHEMA_PROFILE=compact`). `REA_MCP_INPUT_SCHEMA_PROFILE` still accepts `compact`. Server-side validation is unchanged. * test(mcp): validate replies against canonical output contracts at every listed-schema reader tools/list omits output schemas by default, so fixtures, verifiers and the Android analysis runners that read a listed outputSchema now bind the canonical contract instead. connectLocalToolsMcp and advertisedMcpToolSchemas hand the SDK a definition carrying the canonical output schema, so the SDK client and caller-supplied validators check every successful reply. * test(mcp): resolve Android runners' output contracts from the selected repository The Android efficiency runners imported the canonical output-schema helper from the harness checkout while --repository selects the revision under test. Import it from the selected repository, as the runners already do for the SDK and Ajv. * test(mcp): let Android runners compare revisions before the canonical output helper A selected revision without scripts/lib/canonical-output-schema.mjs could not start the Android runners. Choose the output contracts in one harness helper: the selected revision's canonical contracts when it has them, otherwise its listed schemas under the full output profile it still supports. * fix(scripts): keep caller launch settings when the real Hopper verifier builds its server environment The verifier deleted REA_VERIFY_SERVER_COMMAND and REA_VERIFY_SERVER_ARGS_JSON from process.env itself before reading them, so a caller selecting an installed REA command silently ran the checkout's dist/main.js. Copy the environment, as main does, so only the child's environment changes. * test(mcp): validate whole replies against canonical output contracts wherever a listed definition is held tools/list omits output schemas by default and the full output profile is gone, so tests that handed the SDK a listed definition no longer checked complete replies. Attach the canonical output schema with withCanonicalOutputSchema at every held REA tool definition. Environment-served tools (not REA contracts), and the deferred-runtime and doctor tests that exercise per-profile listings, keep their listed definitions. * test(mcp): record the advertised catalog summary without the retired full profiles Retiring the full input and output profiles leaves only the compact input and compact output listings, so the summary drops the full-profile digests and every pattern only the full listings carried. Regenerated with npm run verify:advertised-schemas -- --update-summary.
699 lines
21 KiB
JavaScript
699 lines
21 KiB
JavaScript
#!/usr/bin/env node
|
|
import { canonicalOutputSchema } from "./lib/canonical-output-schema.mjs";
|
|
import assert from "node:assert/strict";
|
|
import { execFile } from "node:child_process";
|
|
import { createHash } from "node:crypto";
|
|
import { constants } from "node:fs";
|
|
import {
|
|
access,
|
|
copyFile,
|
|
open,
|
|
readFile,
|
|
readdir,
|
|
writeFile,
|
|
} from "node:fs/promises";
|
|
import { homedir } from "node:os";
|
|
import { join } from "node:path";
|
|
import { fileURLToPath } from "node:url";
|
|
import { promisify } from "node:util";
|
|
import { Client } from "@modelcontextprotocol/client";
|
|
import { StdioClientTransport } from "@modelcontextprotocol/client/stdio";
|
|
import { Ajv2020 } from "ajv/dist/2020.js";
|
|
import { parseEvidence } from "../dist/domain/evidence.js";
|
|
import { computeApkContentDigest } from "../dist/domain/apkSignature/apkContentDigest.js";
|
|
import {
|
|
locateApkSigningBlock,
|
|
parseZipTail,
|
|
} from "../dist/domain/apkSignature/apkSigningBlock.js";
|
|
import { VerifierFixture } from "./lib/verifier-fixture.mjs";
|
|
import { mcpTextValue, requireMcpOutput } from "./lib/mcp-verifier-results.mjs";
|
|
import { createVerifierRun, completeVerifierRun } from "./lib/verifier-run.mjs";
|
|
|
|
const execute = promisify(execFile);
|
|
const environment = Object.fromEntries(
|
|
Object.entries(process.env).filter(([, v]) => typeof v === "string"),
|
|
);
|
|
|
|
const sdkRoots = [
|
|
environment.ANDROID_HOME,
|
|
environment.ANDROID_SDK_ROOT,
|
|
join(homedir(), "Android", "Sdk"),
|
|
join(homedir(), "Library", "Android", "sdk"),
|
|
].filter((r) => typeof r === "string" && r.length > 0);
|
|
|
|
const newestExisting = async (root, sub, name) => {
|
|
try {
|
|
const versions = (await readdir(join(root, sub))).sort().reverse();
|
|
for (const v of versions) {
|
|
const candidate = join(root, sub, v, name);
|
|
try {
|
|
await access(candidate, constants.R_OK);
|
|
return candidate;
|
|
} catch {
|
|
/* next */
|
|
}
|
|
}
|
|
} catch {
|
|
/* missing */
|
|
}
|
|
return undefined;
|
|
};
|
|
const resolveSdk = async (sub, name) => {
|
|
for (const root of sdkRoots) {
|
|
const found = await newestExisting(root, sub, name);
|
|
if (found !== undefined) return found;
|
|
}
|
|
return undefined;
|
|
};
|
|
const probe = async (tool, args) => {
|
|
try {
|
|
await execute(tool, args);
|
|
return true;
|
|
} catch {
|
|
return false;
|
|
}
|
|
};
|
|
|
|
const apksigner = await resolveSdk("build-tools", "apksigner");
|
|
const aapt2 = await resolveSdk("build-tools", "aapt2");
|
|
const androidJar = await resolveSdk("platforms", "android.jar");
|
|
const keytool = (await probe("keytool", ["-help"])) ? "keytool" : undefined;
|
|
if ([apksigner, aapt2, androidJar, keytool].includes(undefined)) {
|
|
if (process.argv.includes("--require-tools"))
|
|
throw new Error(
|
|
"APK signature lane requires apksigner, aapt2, a platform android.jar and keytool.",
|
|
);
|
|
console.log(
|
|
JSON.stringify({
|
|
status: "skipped",
|
|
reason:
|
|
"APK signature lane requires the Android SDK (apksigner, aapt2, platforms/android.jar) and a JDK keytool.",
|
|
}),
|
|
);
|
|
process.exit(0);
|
|
}
|
|
|
|
const entrypoint =
|
|
process.argv.slice(2).find((arg) => !arg.startsWith("--")) ??
|
|
fileURLToPath(new URL("./rea.mjs", import.meta.url));
|
|
|
|
const run = async (tool, args) =>
|
|
execute(tool, args, {
|
|
env: environment,
|
|
timeout: 180_000,
|
|
maxBuffer: 64 * 1024 * 1024,
|
|
});
|
|
|
|
const nodeHash = (algorithm) => {
|
|
const hash = createHash(algorithm);
|
|
return {
|
|
update: (data) => {
|
|
hash.update(data);
|
|
},
|
|
digest: () => new Uint8Array(hash.digest()),
|
|
};
|
|
};
|
|
|
|
/** Change one entry byte and replace every declared content digest in the block. */
|
|
const forgeDeclaredDigests = async (original) => {
|
|
const bytes = Buffer.from(original);
|
|
const tail = parseZipTail(bytes);
|
|
assert.ok(tail.ok);
|
|
const block = locateApkSigningBlock(bytes, tail.value);
|
|
assert.ok(block.ok && block.value !== null);
|
|
const { blockStart } = block.value;
|
|
const digests = () =>
|
|
["sha256", "sha512"].map((algorithm) =>
|
|
Buffer.from(
|
|
computeApkContentDigest(
|
|
bytes,
|
|
{ tail: tail.value, blockStart, algorithm },
|
|
nodeHash,
|
|
),
|
|
),
|
|
);
|
|
const before = digests();
|
|
bytes[40] = (bytes[40] ?? 0) ^ 0xff;
|
|
const after = digests();
|
|
let replaced = 0;
|
|
for (const [index, old] of before.entries())
|
|
for (
|
|
let at = bytes.indexOf(old, blockStart);
|
|
at >= 0 && at < tail.value.centralDirectoryOffset;
|
|
at = bytes.indexOf(old, at + old.length)
|
|
) {
|
|
after[index].copy(bytes, at);
|
|
replaced += 1;
|
|
}
|
|
assert.ok(replaced > 0, "the signed data must declare a content digest");
|
|
return bytes;
|
|
};
|
|
|
|
/** The SDK's own verdict, parsed from `apksigner verify -v --print-certs`. */
|
|
const oracleVerify = async (apk) => {
|
|
try {
|
|
const { stdout } = await run(apksigner, [
|
|
"verify",
|
|
"-v",
|
|
"--print-certs",
|
|
apk,
|
|
]);
|
|
const scheme = (label) =>
|
|
new RegExp(`Verified using ${label}[^:]*: true`).test(stdout);
|
|
return {
|
|
verifies: true,
|
|
v1: scheme("v1 scheme"),
|
|
v2: scheme("v2 scheme"),
|
|
v3: scheme("v3 scheme"),
|
|
signerSha256:
|
|
stdout.match(
|
|
/Signer #1 certificate SHA-256 digest: ([0-9a-f]{64})/,
|
|
)?.[1] ?? null,
|
|
};
|
|
} catch {
|
|
return { verifies: false };
|
|
}
|
|
};
|
|
/** The JDK's view of the v1 (JAR) signer certificates, leaf first per signer. */
|
|
const oracleJarSigners = async (apk) => {
|
|
const { stdout } = await run(keytool, ["-printcert", "-jarfile", apk]);
|
|
return [...stdout.matchAll(/SHA256: ([0-9A-F:]{95})/g)].map((m) =>
|
|
m[1].replaceAll(":", "").toLowerCase(),
|
|
);
|
|
};
|
|
const oracleLineage = async (apk) => {
|
|
const { stdout } = await run(apksigner, [
|
|
"lineage",
|
|
"--in",
|
|
apk,
|
|
"--print-certs",
|
|
]);
|
|
return [
|
|
...stdout.matchAll(
|
|
/in lineage certificate SHA-256 digest: ([0-9a-f]{64})/g,
|
|
),
|
|
].map((m) => m[1]);
|
|
};
|
|
|
|
const inspectCli = async (path) => {
|
|
try {
|
|
return JSON.parse(
|
|
(
|
|
await run(process.execPath, [
|
|
entrypoint,
|
|
"inspect-apk-signature",
|
|
path,
|
|
"--format",
|
|
"json",
|
|
])
|
|
).stdout,
|
|
);
|
|
} catch (cause) {
|
|
if (typeof cause.stdout === "string" && cause.stdout.length > 0)
|
|
return JSON.parse(cause.stdout);
|
|
throw cause;
|
|
}
|
|
};
|
|
|
|
const verifierRun = createVerifierRun();
|
|
const fixture = await VerifierFixture.open({
|
|
prefix: "rea-apk-signature-verifier-",
|
|
});
|
|
const workspace = fixture.path;
|
|
const client = new Client({ name: "apk-signature-verifier", version: "1" });
|
|
const transport = new StdioClientTransport({
|
|
command: process.execPath,
|
|
args: [entrypoint, "mcp"],
|
|
env: environment,
|
|
stderr: "pipe",
|
|
});
|
|
// The MCP server child reads files under the workspace until it has exited.
|
|
fixture.releaseAfter(() => client.close());
|
|
fixture.releaseAfter(() => transport.close());
|
|
let cases = 0;
|
|
const failures = [];
|
|
|
|
try {
|
|
await client.connect(transport);
|
|
const advertised = (await client.listTools()).tools.find(
|
|
({ name }) => name === "inspect_apk_signature",
|
|
);
|
|
assert.ok(advertised, "tool must advertise an output schema");
|
|
const ajv = new Ajv2020({ strict: false, validateFormats: false });
|
|
assert.ok(ajv.validateSchema(advertised.inputSchema), "input schema invalid");
|
|
assert.ok(
|
|
ajv.validateSchema(canonicalOutputSchema(advertised.name)),
|
|
"output schema invalid",
|
|
);
|
|
|
|
/** CLI and MCP share schema-valid Evidence, with CLI-only caller spelling. */
|
|
const inspectBoth = async (path) => {
|
|
const cliValue = await inspectCli(path);
|
|
assert.equal(
|
|
cliValue.category,
|
|
undefined,
|
|
JSON.stringify(cliValue).slice(0, 300),
|
|
);
|
|
const cli = parseEvidence(cliValue);
|
|
const reply = await client.callTool(
|
|
{
|
|
name: "inspect_apk_signature",
|
|
arguments: { path, detail: "complete" },
|
|
},
|
|
{ timeout: 120000, toolDefinition: advertised },
|
|
);
|
|
assert.notEqual(reply.isError, true, mcpTextValue(reply));
|
|
assert.ok(
|
|
ajv.validate(
|
|
canonicalOutputSchema(advertised.name),
|
|
reply.structuredContent,
|
|
),
|
|
JSON.stringify(ajv.errors),
|
|
);
|
|
const mcp = parseEvidence(requireMcpOutput(reply, "inspect_apk_signature"));
|
|
const { caller_input_path: callerInputPath, ...cliShared } = cli;
|
|
assert.equal(callerInputPath, path);
|
|
assert.equal(Object.hasOwn(mcp, "caller_input_path"), false);
|
|
assert.deepEqual(cliShared, mcp, "CLI and MCP evidence differ");
|
|
cases += 2;
|
|
return mcp.normalized_result;
|
|
};
|
|
|
|
// A real minimal APK (binary manifest via aapt2) so apksigner can verify it.
|
|
await writeFile(
|
|
join(workspace, "AndroidManifest.xml"),
|
|
`<?xml version="1.0" encoding="utf-8"?>
|
|
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="tools.rea.fixture">
|
|
<uses-sdk android:minSdkVersion="24" android:targetSdkVersion="34"/>
|
|
<application android:label="rea"/>
|
|
</manifest>
|
|
`,
|
|
);
|
|
const base = join(workspace, "base.apk");
|
|
await run(aapt2, [
|
|
"link",
|
|
"-o",
|
|
base,
|
|
"--manifest",
|
|
join(workspace, "AndroidManifest.xml"),
|
|
"-I",
|
|
androidJar,
|
|
]);
|
|
const key = async (name, args) =>
|
|
run(keytool, [
|
|
"-genkeypair",
|
|
"-keystore",
|
|
join(workspace, `${name}.jks`),
|
|
"-storepass",
|
|
"pass123",
|
|
"-keypass",
|
|
"pass123",
|
|
"-alias",
|
|
name,
|
|
"-validity",
|
|
"3650",
|
|
...args,
|
|
]);
|
|
await key("k1", [
|
|
"-keyalg",
|
|
"RSA",
|
|
"-keysize",
|
|
"2048",
|
|
"-dname",
|
|
"CN=REA Lane One",
|
|
]);
|
|
await key("k2", [
|
|
"-keyalg",
|
|
"EC",
|
|
"-groupname",
|
|
"secp256r1",
|
|
"-dname",
|
|
"CN=REA Lane Two",
|
|
]);
|
|
const ks = (name) => [
|
|
"--ks",
|
|
join(workspace, `${name}.jks`),
|
|
"--ks-pass",
|
|
"pass:pass123",
|
|
];
|
|
|
|
// 1) Default v2+v3 signing: schemes, signer fingerprint and self-consistency.
|
|
const full = join(workspace, "full.apk");
|
|
await run(apksigner, ["sign", ...ks("k1"), "--out", full, base]);
|
|
const fullOracle = await oracleVerify(full);
|
|
const fullReport = await inspectBoth(full);
|
|
assert.equal(fullReport.schemes.v2.present, fullOracle.v2);
|
|
assert.equal(fullReport.schemes.v3.present, fullOracle.v3);
|
|
for (const scheme of ["v2", "v3"])
|
|
assert.equal(
|
|
fullReport.schemes[scheme].signers[0].certificate.sha256_fingerprint,
|
|
fullOracle.signerSha256,
|
|
`${scheme} signer fingerprint must equal apksigner's`,
|
|
);
|
|
assert.equal(fullReport.posture.schemes_agree_on_signer, true);
|
|
assert.equal(
|
|
fullReport.posture.self_consistent,
|
|
true,
|
|
"a freshly signed APK must be self-consistent",
|
|
);
|
|
assert.equal(fullReport.posture.v1_only, false);
|
|
|
|
// 2) v1-only signing (X-Android-APK-Signed is not read, so this cannot be
|
|
// told apart from a v2/v3 block that was removed). Android requires v2+
|
|
// for targetSdk >= 30, so this case uses a legacy-target base APK. REA's
|
|
// v1.present is structural; apksigner's "verified using v1" is platform
|
|
// applicability and is false for minSdk >= 24 even when CERT.SF exists.
|
|
await writeFile(
|
|
join(workspace, "LegacyManifest.xml"),
|
|
`<?xml version="1.0" encoding="utf-8"?>
|
|
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="tools.rea.legacy">
|
|
<uses-sdk android:minSdkVersion="21" android:targetSdkVersion="29"/>
|
|
<application android:label="rea"/>
|
|
</manifest>
|
|
`,
|
|
);
|
|
const legacyBase = join(workspace, "legacy-base.apk");
|
|
await run(aapt2, [
|
|
"link",
|
|
"-o",
|
|
legacyBase,
|
|
"--manifest",
|
|
join(workspace, "LegacyManifest.xml"),
|
|
"-I",
|
|
androidJar,
|
|
]);
|
|
const v1only = join(workspace, "v1only.apk");
|
|
await run(apksigner, [
|
|
"sign",
|
|
...ks("k1"),
|
|
"--v1-signing-enabled",
|
|
"true",
|
|
"--v2-signing-enabled",
|
|
"false",
|
|
"--v3-signing-enabled",
|
|
"false",
|
|
"--out",
|
|
v1only,
|
|
legacyBase,
|
|
]);
|
|
const v1Oracle = await oracleVerify(v1only);
|
|
assert.equal(v1Oracle.v1, true, "oracle should see v1");
|
|
const v1Report = await inspectBoth(v1only);
|
|
assert.equal(v1Report.schemes.v1.present, true);
|
|
assert.equal(v1Report.schemes.v2.present, false);
|
|
assert.equal(v1Report.posture.v1_only, true);
|
|
assert.equal(v1Report.posture.strongest_scheme, "v1");
|
|
/** REA's declared v1 signer must be the certificate apksigner and keytool name. */
|
|
const assertV1Signer = async (apk, report, expected) => {
|
|
const [signer, ...rest] = report.schemes.v1.signers;
|
|
assert.equal(rest.length, 0, "one v1 signer");
|
|
assert.equal(signer.decode_error, null, signer.decode_error ?? "");
|
|
assert.equal(signer.certificate?.sha256_fingerprint, expected);
|
|
assert.deepEqual(
|
|
signer.certificates.map((c) => c.sha256_fingerprint),
|
|
await oracleJarSigners(apk),
|
|
"REA v1 certificates must equal keytool -printcert -jarfile",
|
|
);
|
|
assert.equal(signer.signer_infos[0]?.certificate_sha256, expected);
|
|
assert.ok(signer.certificate?.subject, "v1 signer subject");
|
|
};
|
|
await assertV1Signer(v1only, v1Report, v1Oracle.signerSha256);
|
|
assert.equal(v1Report.posture.v1_signers_match_block_signers, null);
|
|
|
|
// 2b) v1 with an EC key: the block is CERT.EC (or the alias-named .EC).
|
|
const v1ec = join(workspace, "v1ec.apk");
|
|
await run(apksigner, [
|
|
"sign",
|
|
...ks("k2"),
|
|
"--v2-signing-enabled",
|
|
"false",
|
|
"--v3-signing-enabled",
|
|
"false",
|
|
"--out",
|
|
v1ec,
|
|
legacyBase,
|
|
]);
|
|
const v1ecOracle = await oracleVerify(v1ec);
|
|
const v1ecReport = await inspectBoth(v1ec);
|
|
assert.ok(v1ecReport.schemes.v1.signers[0].block_file.endsWith(".EC"));
|
|
await assertV1Signer(v1ec, v1ecReport, v1ecOracle.signerSha256);
|
|
|
|
// 2c) Default signing of a legacy-target APK carries v1, v2 and v3 with one
|
|
// key: the v1 signer equals the block signers.
|
|
const legacyFull = join(workspace, "legacy-full.apk");
|
|
await run(apksigner, ["sign", ...ks("k1"), "--out", legacyFull, legacyBase]);
|
|
const legacyOracle = await oracleVerify(legacyFull);
|
|
assert.equal(legacyOracle.v1, true, "oracle should verify v1 too");
|
|
const legacyReport = await inspectBoth(legacyFull);
|
|
await assertV1Signer(legacyFull, legacyReport, legacyOracle.signerSha256);
|
|
assert.equal(legacyReport.posture.v1_signers_match_block_signers, true);
|
|
|
|
// 3) Key rotation: lineage certificates and a signer change the APK declares.
|
|
const lineage = join(workspace, "lineage.bin");
|
|
await run(apksigner, [
|
|
"rotate",
|
|
"--out",
|
|
lineage,
|
|
"--old-signer",
|
|
...ks("k1"),
|
|
"--new-signer",
|
|
...ks("k2"),
|
|
]);
|
|
const rotated = join(workspace, "rotated.apk");
|
|
await run(apksigner, [
|
|
"sign",
|
|
...ks("k1"),
|
|
"--next-signer",
|
|
...ks("k2"),
|
|
"--lineage",
|
|
lineage,
|
|
"--rotation-min-sdk-version",
|
|
"28",
|
|
"--out",
|
|
rotated,
|
|
base,
|
|
]);
|
|
const lineageOracle = await oracleLineage(rotated);
|
|
const rotatedReport = await inspectBoth(rotated);
|
|
const reaLineage = rotatedReport.schemes.v3.signers[0].rotation.lineage.map(
|
|
(n) => n.certificate.sha256_fingerprint,
|
|
);
|
|
assert.deepEqual(
|
|
reaLineage,
|
|
lineageOracle,
|
|
"REA lineage must equal apksigner lineage (order + digests)",
|
|
);
|
|
// Observed: v2 (old key) and v3 (new key) differ. Declared: the lineage
|
|
// covers both. The two facts stay separate.
|
|
assert.equal(rotatedReport.posture.schemes_agree_on_signer, false);
|
|
assert.equal(rotatedReport.posture.signer_change_declared_by_rotation, true);
|
|
assert.deepEqual(
|
|
rotatedReport.schemes.v3.signers[0].rotation.lineage.map(
|
|
(n) => n.capabilities.installed_data,
|
|
),
|
|
[true, true],
|
|
);
|
|
|
|
// 3a) Rotation on a legacy-target APK: v1 and v2 keep the old key, v3 the
|
|
// new one. v1 is compared with v2 (the lowest block scheme), so the
|
|
// rotation does not read as a JAR-signer mismatch.
|
|
const rotatedLegacy = join(workspace, "rotated-legacy.apk");
|
|
await run(apksigner, [
|
|
"sign",
|
|
...ks("k1"),
|
|
"--next-signer",
|
|
...ks("k2"),
|
|
"--lineage",
|
|
lineage,
|
|
"--rotation-min-sdk-version",
|
|
"28",
|
|
"--out",
|
|
rotatedLegacy,
|
|
legacyBase,
|
|
]);
|
|
const rotatedLegacyReport = await inspectBoth(rotatedLegacy);
|
|
await assertV1Signer(
|
|
rotatedLegacy,
|
|
rotatedLegacyReport,
|
|
fullOracle.signerSha256,
|
|
);
|
|
assert.equal(rotatedLegacyReport.posture.schemes_agree_on_signer, false);
|
|
assert.equal(
|
|
rotatedLegacyReport.posture.v1_signers_match_block_signers,
|
|
true,
|
|
);
|
|
|
|
// 3a') The same rotation without v2: v1 keeps the original key and v3 signs
|
|
// with the new one. apksig requires the v1 signer to be the lineage's
|
|
// first node, so v1 is compared with that node, not the v3 signer.
|
|
const rotatedNoV2 = join(workspace, "rotated-legacy-no-v2.apk");
|
|
await run(apksigner, [
|
|
"sign",
|
|
...ks("k1"),
|
|
"--next-signer",
|
|
...ks("k2"),
|
|
"--lineage",
|
|
lineage,
|
|
"--rotation-min-sdk-version",
|
|
"28",
|
|
"--v2-signing-enabled",
|
|
"false",
|
|
"--out",
|
|
rotatedNoV2,
|
|
legacyBase,
|
|
]);
|
|
const noV2Oracle = await oracleVerify(rotatedNoV2);
|
|
assert.equal(noV2Oracle.verifies, true, "oracle must accept v1 + rotated v3");
|
|
assert.equal(noV2Oracle.v1, true);
|
|
assert.equal(noV2Oracle.v2, false);
|
|
const noV2Report = await inspectBoth(rotatedNoV2);
|
|
assert.equal(noV2Report.schemes.v2.present, false);
|
|
await assertV1Signer(rotatedNoV2, noV2Report, fullOracle.signerSha256);
|
|
assert.deepEqual(
|
|
noV2Report.schemes.v3.signers[0].rotation.lineage.map(
|
|
(n) => n.certificate.sha256_fingerprint,
|
|
),
|
|
await oracleLineage(rotatedNoV2),
|
|
);
|
|
assert.equal(
|
|
noV2Report.posture.v1_signers_match_block_signers,
|
|
true,
|
|
"a v1 signer equal to the lineage origin is the expected rotation layout",
|
|
);
|
|
|
|
// 3b) Rotation targeting SDK 33 is carried by v3.1; v3 keeps the original signer.
|
|
const rotated31 = join(workspace, "rotated31.apk");
|
|
await run(apksigner, [
|
|
"sign",
|
|
...ks("k1"),
|
|
"--next-signer",
|
|
...ks("k2"),
|
|
"--lineage",
|
|
lineage,
|
|
"--rotation-min-sdk-version",
|
|
"33",
|
|
"--out",
|
|
rotated31,
|
|
base,
|
|
]);
|
|
assert.equal((await oracleVerify(rotated31)).verifies, true);
|
|
const rotated31Report = await inspectBoth(rotated31);
|
|
assert.equal(rotated31Report.schemes["v3.1"].present, true);
|
|
assert.equal(rotated31Report.posture.strongest_scheme, "v3.1");
|
|
const v31Signer = rotated31Report.schemes["v3.1"].signers[0];
|
|
assert.equal(v31Signer.min_sdk, 33);
|
|
assert.deepEqual(
|
|
v31Signer.rotation.lineage.map((n) => n.certificate.sha256_fingerprint),
|
|
lineageOracle,
|
|
"v3.1 lineage must equal the apksigner lineage",
|
|
);
|
|
assert.equal(
|
|
rotated31Report.schemes.v3.signers[0].certificate.sha256_fingerprint,
|
|
fullOracle.signerSha256,
|
|
"v3 keeps the original signer below the v3.1 SDK range",
|
|
);
|
|
assert.equal(rotated31Report.posture.self_consistent, true);
|
|
assert.equal(rotated31Report.posture.schemes_agree_on_signer, false);
|
|
assert.equal(
|
|
rotated31Report.posture.signer_change_declared_by_rotation,
|
|
true,
|
|
);
|
|
|
|
// 3c) Source stamp (apksigner requires an RSA stamp key).
|
|
const stamped = join(workspace, "stamped.apk");
|
|
await run(apksigner, [
|
|
"sign",
|
|
...ks("k1"),
|
|
"--stamp-signer",
|
|
...ks("k1"),
|
|
"--out",
|
|
stamped,
|
|
base,
|
|
]);
|
|
const stampedReport = await inspectBoth(stamped);
|
|
assert.equal(stampedReport.source_stamp.present, true);
|
|
assert.equal(stampedReport.posture.source_stamp_present, true);
|
|
assert.equal(stampedReport.posture.self_consistent, true);
|
|
assert.equal(stampedReport.source_stamp.decode_error, null);
|
|
assert.equal(
|
|
stampedReport.source_stamp.certificate?.sha256_fingerprint,
|
|
fullOracle.signerSha256,
|
|
"REA must read the declared stamp certificate (k1)",
|
|
);
|
|
|
|
// 4) One changed entry byte with the declared digest left alone: apksigner
|
|
// rejects it and the declared digest no longer matches the bytes.
|
|
const tampered = join(workspace, "tampered.apk");
|
|
await copyFile(full, tampered);
|
|
const handle = await open(tampered, "r+");
|
|
const byte = Buffer.alloc(1);
|
|
await handle.read(byte, 0, 1, 40);
|
|
byte[0] = (byte[0] ?? 0) ^ 0xff;
|
|
await handle.write(byte, 0, 1, 40);
|
|
await handle.close();
|
|
assert.equal(
|
|
(await oracleVerify(tampered)).verifies,
|
|
false,
|
|
"oracle must reject the tampered APK",
|
|
);
|
|
const tamperedReport = await inspectBoth(tampered);
|
|
assert.equal(
|
|
tamperedReport.posture.self_consistent,
|
|
false,
|
|
"REA must report the tampered APK as not self-consistent",
|
|
);
|
|
|
|
// 4b) The same byte change with the declared digests recomputed and written
|
|
// back: apksigner still rejects it (the signature no longer verifies),
|
|
// while the declared digests match the bytes. self_consistent is a
|
|
// digest comparison, not a signature verification.
|
|
const forged = join(workspace, "forged-digest.apk");
|
|
await writeFile(forged, await forgeDeclaredDigests(await readFile(full)));
|
|
assert.equal(
|
|
(await oracleVerify(forged)).verifies,
|
|
false,
|
|
"oracle must reject the APK with recomputed declared digests",
|
|
);
|
|
const forgedReport = await inspectBoth(forged);
|
|
assert.equal(
|
|
forgedReport.posture.self_consistent,
|
|
true,
|
|
"a recomputed declared digest matches the bytes without a valid signature",
|
|
);
|
|
|
|
// 5) Error surface: a non-ZIP file is an unsupported target, not a crash.
|
|
const notZip = join(workspace, "not-a-zip.apk");
|
|
await writeFile(notZip, "definitely not a zip archive");
|
|
const refused = await inspectCli(notZip);
|
|
assert.equal(
|
|
refused.category,
|
|
"unsupported_target",
|
|
JSON.stringify(refused).slice(0, 300),
|
|
);
|
|
cases += 1;
|
|
} catch (cause) {
|
|
failures.push(cause);
|
|
}
|
|
|
|
try {
|
|
await fixture.release();
|
|
} catch (cause) {
|
|
failures.push(cause);
|
|
}
|
|
|
|
if (failures.length > 0)
|
|
throw new AggregateError(failures, "APK signature verification failed.");
|
|
console.log(
|
|
JSON.stringify(
|
|
{
|
|
status: "passed",
|
|
cases,
|
|
toolchain: "android-apksigner-aapt2",
|
|
entrypoint,
|
|
verifier: await completeVerifierRun(verifierRun),
|
|
},
|
|
null,
|
|
2,
|
|
),
|
|
);
|