diff --git a/src/domain/analysisView/analysisView.ts b/src/domain/analysisView/analysisView.ts index ab95b1dedb4..0e91a4ea1d0 100644 --- a/src/domain/analysisView/analysisView.ts +++ b/src/domain/analysisView/analysisView.ts @@ -3,6 +3,7 @@ import { projectNativeProcedureReferencesView } from "./nativeProcedureReference import { projectPlaywrightTraceView } from "./playwrightTraceView.js"; import { projectWebPageView } from "./webPageView.js"; import { projectWebExecutionView } from "./webExecutionView.js"; +import { projectApktoolResourcesView } from "./apktoolResourcesView.js"; import { projectApiContractView } from "./apiContractView.js"; import { isNativeObservationOperation, @@ -249,6 +250,7 @@ const retainedViewProjectors = new Map([ retain("analyze_web_bundle", projectWebBundleView), retain("inspect_web_page", projectWebPageView), retain("observe_web_execution", projectWebExecutionView), + retain("decode_android_resources", projectApktoolResourcesView), retain("trace_web_source_location", projectWebSourceLocationView), ]); diff --git a/src/domain/analysisView/analysisViewRequest.ts b/src/domain/analysisView/analysisViewRequest.ts index d87a86a4eb0..63b76b7173f 100644 --- a/src/domain/analysisView/analysisViewRequest.ts +++ b/src/domain/analysisView/analysisViewRequest.ts @@ -20,6 +20,7 @@ import { javaScriptRoutesViewRequestSchema } from "./javascriptRoutesView.js"; import { webBundleViewRequestSchema } from "./webBundleView.js"; import { webPageViewRequestSchema } from "./webPageView.js"; import { webExecutionViewRequestSchema } from "./webExecutionView.js"; +import { apktoolResourcesViewRequestSchema } from "../apktool/apktoolResourcesQuery.js"; import { sourceToBundleViewRequestSchema } from "./sourceToBundleView.js"; import { endpointComparisonViewRequestSchema } from "./endpointComparisonView.js"; import { featureTraceViewRequestSchema } from "./featureTraceView.js"; @@ -106,6 +107,7 @@ export const analysisViewRequestSchema = z.discriminatedUnion("kind", [ webBundleViewRequestSchema, webPageViewRequestSchema, webExecutionViewRequestSchema, + apktoolResourcesViewRequestSchema, nativeFunctionMatchingViewRequestSchema, sourceToBundleViewRequestSchema, endpointComparisonViewRequestSchema, diff --git a/src/domain/analysisView/analysisViewResult.ts b/src/domain/analysisView/analysisViewResult.ts index 2573fb05e07..f8e7b9e6149 100644 --- a/src/domain/analysisView/analysisViewResult.ts +++ b/src/domain/analysisView/analysisViewResult.ts @@ -304,6 +304,10 @@ import { webExecutionPageViewResultSchema, webExecutionSummaryViewResultSchema, } from "./summarySchemas/webExecutionSummarySchemas.js"; +import { + apktoolResourcesPageViewResultSchema, + apktoolResourcesSummaryViewResultSchema, +} from "./summarySchemas/apktoolResourcesSummarySchemas.js"; import { webNetworkCaptureSummaryViewResultSchema } from "./summarySchemas/webNetworkCaptureSummarySchema.js"; import { webSourceLocationMatchesViewResultSchema, @@ -388,6 +392,8 @@ export { webPageSummaryViewResultSchema, webExecutionPageViewResultSchema, webExecutionSummaryViewResultSchema, + apktoolResourcesPageViewResultSchema, + apktoolResourcesSummaryViewResultSchema, webNetworkCaptureSummaryViewResultSchema, webSourceLocationMatchesViewResultSchema, webSourceLocationSummaryViewResultSchema, @@ -697,6 +703,7 @@ export const analysisViewResultSchema = z.discriminatedUnion("kind", [ webBundlePageViewResultSchema, webPagePageViewResultSchema, webExecutionPageViewResultSchema, + apktoolResourcesPageViewResultSchema, sourceToBundlePageViewResultSchema, endpointComparisonPageViewResultSchema, apiContractPageViewResultSchema, @@ -809,6 +816,7 @@ export const analysisViewResultSchema = z.discriminatedUnion("kind", [ webBundleSummaryViewResultSchema, webPageSummaryViewResultSchema, webExecutionSummaryViewResultSchema, + apktoolResourcesSummaryViewResultSchema, nugetNupkgSummaryViewResultSchema, ]), z.strictObject({ diff --git a/src/domain/analysisView/apktoolResourcesView.ts b/src/domain/analysisView/apktoolResourcesView.ts new file mode 100644 index 00000000000..827636f0103 --- /dev/null +++ b/src/domain/analysisView/apktoolResourcesView.ts @@ -0,0 +1,263 @@ +import { z } from "zod"; + +import { + apktoolResultSchemas, + stringTableSchema, + type ApktoolDecodeResult, +} from "../apktool/apktoolResourceAnalysis.js"; +import { apktoolResourcesViewRequestSchema } from "../apktool/apktoolResourcesQuery.js"; +import type { JsonValue } from "../jsonValue.js"; +import { isRecord } from "../../kernel/isRecord.js"; +import { err, ok } from "../result.js"; +import { + PLACEHOLDER_COVERAGE, + selectByteBoundedViewRows, +} from "./byteBoundedViewRows.js"; +import { analysisViewInputError } from "./analysisViewErrors.js"; +import { + createAnalysisViewResultReader, + type AnalysisViewParent, +} from "./analysisViewParent.js"; +import { + boundedViewMessages, + completeWithinViewCoverage, + pageViewCoverage, +} from "./analysisViewCoverage.js"; +import { + assertOwnedView, + type AdmittedView, + type SummaryAnalysisView, +} from "./analysisViewShape.js"; +import { + analysisTextPage, + analysisTextPageItemSchema, +} from "./analysisViewText.js"; + +export const DECODE_ANDROID_RESOURCES_OPERATION = + "decode_android_resources" as const; + +const decodeSchema = apktoolResultSchemas.decode_android_resources; +type ResourcesView = z.output; + +/** A decoded table's facts without its string rows, which page separately. */ +export const apktoolStringTableSummarySchema = stringTableSchema + .omit({ strings: true }) + .extend({ returned_count: z.int().nonnegative() }); + +/** The decode without manifest text or string rows. */ +export const apktoolResourcesSummarySchema = decodeSchema + .omit({ manifest: true, strings: true, string_tables: true }) + .extend({ + manifest: z + .strictObject({ code_units: z.int().nonnegative() }) + .nullable() + .describe( + "The decoded manifest's length in UTF-16 code units, or null when it was not decoded; page it with facet manifest", + ), + primary_strings: z.strictObject({ + returned_count: z.int().nonnegative(), + }), + string_tables: z.array(apktoolStringTableSummarySchema).optional(), + }); + +/** One decoded string with the table it came from. */ +export const apktoolStringRowSchema = z.strictObject({ + locale: z.string().nullable(), + name: z.string().min(1), + value: z.string(), +}); + +export const apktoolManifestPageItemSchema = analysisTextPageItemSchema; + +const readReport = createAnalysisViewResultReader(decodeSchema); + +type StringRow = z.output; + +/** + * Every decoded string with the table it came from, built once per retained + * decode. A decode that reported string_tables owns its rows there; otherwise + * the primary strings are the selected table's. + */ +const decodedRows = new WeakMap(); +const stringRows = (report: ApktoolDecodeResult): readonly StringRow[] => { + const known = decodedRows.get(report); + if (known !== undefined) return known; + const tables = report.string_tables ?? [ + { locale: report.locale, strings: report.strings }, + ]; + const rows = tables.flatMap((table) => + table.strings.map((row) => ({ locale: table.locale, ...row })), + ); + decodedRows.set(report, rows); + return rows; +}; + +/** The decode's own record that it read no strings, when it says so. */ +const stringsUnread = (parent: AnalysisViewParent) => + isRecord(parent.parameters) && parent.parameters.include_strings === false; + +const summarize = ( + report: ApktoolDecodeResult, +): z.output => { + const { manifest, strings, string_tables, ...facts } = report; + return { + ...facts, + manifest: manifest === null ? null : { code_units: manifest.length }, + primary_strings: { returned_count: strings.length }, + ...(string_tables === undefined + ? {} + : { + string_tables: string_tables.map(({ strings: rows, ...table }) => ({ + ...table, + returned_count: rows.length, + })), + }), + }; +}; + +const invalid = (path: string, message: string) => + err( + analysisViewInputError([ + { path: ["view", path], reason: "invalid_value", message }, + ]), + ); + +/** One page of string rows across the selected decoded tables. */ +const stringsPage = ( + parent: AnalysisViewParent, + report: ApktoolDecodeResult, + view: Extract, + shared: Shared, +) => { + if (stringsUnread(parent)) + return invalid( + "facet", + "This decode did not read strings (include_strings false); decode again with include_strings true to page them.", + ); + const rows = stringRows(report); + const locales = + view.locales === undefined ? undefined : new Set(view.locales); + if (locales !== undefined) { + const decoded = new Set( + (report.string_tables ?? [{ locale: report.locale }]).map( + (table) => table.locale, + ), + ); + const missing = [...locales].filter((locale) => !decoded.has(locale)); + if (missing.length > 0) + return invalid( + "locales", + `This decode has no string table for ${missing.map((locale) => JSON.stringify(locale)).join(", ")}; decode those locales first. Decoded tables: ${[...decoded].map((locale) => JSON.stringify(locale)).join(", ")}.`, + ); + } + const exact = view.names === undefined ? undefined : new Set(view.names); + const prefixes = view.name_prefixes; + const matches = + locales === undefined && exact === undefined && prefixes === undefined + ? undefined + : (row: StringRow) => + (locales === undefined || locales.has(row.locale)) && + (exact === undefined || exact.has(row.name)) && + (prefixes === undefined || + prefixes.some((prefix) => row.name.startsWith(prefix))); + const context = { + ...shared, + kind: "android-resources" as const, + facet: "strings" as const, + view, + // Each selected table's own completeness travels with every page. + tables: (report.string_tables ?? []).flatMap( + ({ strings: tableRows, ...table }) => + locales === undefined || locales.has(table.locale) + ? [{ ...table, returned_count: tableRows.length }] + : [], + ), + decode_coverage: report.coverage, + }; + const page = selectByteBoundedViewRows( + rows, + view, + { matches, project: (row) => row }, + { + parentEvidenceId: parent.evidenceId, + envelope: { + ...context, + items: [], + byte_limited: false, + coverage: PLACEHOLDER_COVERAGE, + } as unknown as JsonValue, + facet: "strings", + }, + ); + if (!page.ok) return page; + return ok({ + ...context, + items: page.value.rows, + byte_limited: page.value.byte_limited, + coverage: pageViewCoverage( + view.offset, + page.value.rows.length, + page.value.total, + ), + }); +}; + +/** Project a retained decode's summary, one strings page or one manifest page. */ +export const projectApktoolResourcesView = ( + parent: AnalysisViewParent, + admitted: AdmittedView, +) => { + if (admitted.kind !== "android-resources" && admitted.kind !== "summary") + return invalid("kind", "Select an android-resources or summary view."); + assertOwnedView( + admitted, + "summary", + "android-resources", + ); + const parsed = readReport(parent); + if (!parsed.ok) return parsed; + const report = parsed.value; + const shared = { + parent_evidence_id: parent.evidenceId, + parent_operation: DECODE_ANDROID_RESOURCES_OPERATION, + parent_digest: parent.evidenceId.slice(3), + artifact: { path: report.target.path, sha256: report.target.sha256 }, + limitations: boundedViewMessages( + [...parent.limitations], + parent.evidenceId, + "limitations", + ), + unknowns: [ + "Decoded resources are static declarations; they do not establish which strings or components the app uses at runtime.", + ], + }; + if (admitted.kind === "summary") + return ok({ + ...shared, + kind: "summary" as const, + view: admitted, + summary: summarize(report), + coverage: completeWithinViewCoverage(1), + }); + const view = admitted; + if (view.facet === "manifest") { + if (report.manifest === null) + return invalid("facet", "This decode recorded no manifest text."); + const page = analysisTextPage( + report.manifest, + view.offset, + view.limit, + "Manifest", + ); + if (!page.ok) return page; + return ok({ + ...shared, + kind: "android-resources" as const, + facet: "manifest" as const, + view, + item: page.value.item, + coverage: page.value.coverage, + }); + } + return stringsPage(parent, report, view, shared); +}; diff --git a/src/domain/analysisView/byteBoundedViewRows.test.ts b/src/domain/analysisView/byteBoundedViewRows.test.ts new file mode 100644 index 00000000000..3289de9b076 --- /dev/null +++ b/src/domain/analysisView/byteBoundedViewRows.test.ts @@ -0,0 +1,68 @@ +import { expect, it } from "vitest"; + +import { ANALYSIS_VIEW_PAGE_BYTES } from "./analysisViewErrors.js"; +import { selectByteBoundedViewRows } from "./byteBoundedViewRows.js"; + +const owner = { + parentEvidenceId: `ev_${"a".repeat(64)}`, + envelope: { kind: "probe" }, + facet: "rows", +}; + +it("projects only the page's rows when unfiltered", () => { + const projected: number[] = []; + const page = selectByteBoundedViewRows( + Array.from({ length: 1_000 }, (_, index) => index), + { offset: 10, limit: 3 }, + { + matches: undefined, + project: (row) => { + projected.push(row); + return { row }; + }, + }, + owner, + ); + expect(page).toEqual({ + ok: true, + value: { + rows: [{ row: 10 }, { row: 11 }, { row: 12 }], + total: 1_000, + byte_limited: false, + }, + }); + expect(projected).toEqual([10, 11, 12]); +}); + +it("counts every match after a byte-limited page", () => { + const big = "x".repeat(ANALYSIS_VIEW_PAGE_BYTES / 3); + const page = selectByteBoundedViewRows( + Array.from({ length: 8 }, (_, index) => ({ index, big })), + { offset: 0, limit: 64 }, + { matches: (row) => row.index % 2 === 0, project: (row) => row }, + owner, + ); + if (!page.ok) throw page.error; + expect(page.value.rows.map((row) => row.index)).toEqual([0, 2]); + expect(page.value).toMatchObject({ total: 4, byte_limited: true }); +}); + +it("refuses a row that cannot fit a page alone and names the parent", () => { + const page = selectByteBoundedViewRows( + ["x".repeat(ANALYSIS_VIEW_PAGE_BYTES)], + { offset: 0, limit: 1 }, + { matches: undefined, project: (row) => row }, + owner, + ); + expect(page).toMatchObject({ + ok: false, + error: { + _tag: "AnalysisResourceConstraintError", + reportedLimits: { + parent_evidence_id: owner.parentEvidenceId, + facet: "rows", + limit_bytes: ANALYSIS_VIEW_PAGE_BYTES, + }, + }, + }); +}); diff --git a/src/domain/analysisView/byteBoundedViewRows.ts b/src/domain/analysisView/byteBoundedViewRows.ts new file mode 100644 index 00000000000..9aa6a1f7c0f --- /dev/null +++ b/src/domain/analysisView/byteBoundedViewRows.ts @@ -0,0 +1,104 @@ +import type { AnalysisResourceConstraintError } from "../analysisErrorCore.js"; +import type { JsonValue } from "../jsonValue.js"; +import { jsonValueByteLength } from "../jsonValueByteLength.js"; +import { ok, type Result } from "../result.js"; +import { + ANALYSIS_VIEW_PAGE_BYTES as PAGE_BYTES, + analysisViewPageTooLarge, +} from "./analysisViewErrors.js"; + +/** Bytes the view digest adds after projection. */ +const DIGEST_BYTES = jsonValueByteLength({ view_digest: "0".repeat(64) }) - 1; + +/** The widest page coverage, for measuring a page envelope before its rows. */ +export const PLACEHOLDER_COVERAGE = { + status: "page", + examined: Number.MAX_SAFE_INTEGER, + total: Number.MAX_SAFE_INTEGER, + next_offset: Number.MAX_SAFE_INTEGER, + exhausted: false, +} as const; + +/** A page of rows, the number of matching rows, and whether bytes ended it early. */ +export interface ByteBoundedRows { + readonly rows: Row[]; + readonly total: number; + /** Rows after these fit `limit` but not the analysis-view page bytes. */ + readonly byte_limited: boolean; +} + +/** How a byte-bounded page names itself when one row cannot fit. */ +export interface ByteBoundedPageOwner { + readonly parentEvidenceId: string; + /** The page result without its rows, measured once as the page's fixed cost. */ + readonly envelope: JsonValue; + readonly facet: string; +} + +/** + * Select rows from `offset` up to `limit` that fit the analysis-view page + * bytes beside `owner.envelope`. A row that does not fit ends the page with + * byte_limited, so the next offset continues after the last returned row; a + * first row that cannot fit alone is refused, naming the parent. Without + * `matches`, only the page's rows are visited, and `project` runs only on + * rows the page returns. + */ +export const selectByteBoundedViewRows = ( + rows: readonly Source[], + view: { readonly offset: number; readonly limit: number }, + { + matches, + project, + }: { + readonly matches: ((row: Source, index: number) => boolean) | undefined; + readonly project: (row: Source, index: number) => Row; + }, + owner: ByteBoundedPageOwner, +): Result, AnalysisResourceConstraintError> => { + const tooLarge = () => + analysisViewPageTooLarge( + owner.parentEvidenceId, + `One ${owner.facet} row exceeds the analysis-view page bytes on its own. Complete parent Evidence remains retained; select complete detail or export the Evidence bundle to read it.`, + { facet: owner.facet }, + ); + let bytes = + DIGEST_BYTES + + jsonValueByteLength(owner.envelope, PAGE_BYTES - DIGEST_BYTES); + if (bytes > PAGE_BYTES) return tooLarge(); + const selected: Row[] = []; + let byteLimited = false; + /** Admit one projected row, or end the page; false refuses the page. */ + const admit = (row: Row): boolean => { + const size = + jsonValueByteLength(row as unknown as JsonValue, PAGE_BYTES - bytes) + + Number(selected.length > 0); + if (bytes + size > PAGE_BYTES) { + if (selected.length === 0) return false; + byteLimited = true; + return true; + } + bytes += size; + selected.push(row); + return true; + }; + if (matches === undefined) { + const start = Math.min(view.offset, rows.length); + const end = Math.min(rows.length, start + view.limit); + for (let index = start; index < end && !byteLimited; index += 1) + if (!admit(project(rows[index]!, index))) return tooLarge(); + return ok({ + rows: selected, + total: rows.length, + byte_limited: byteLimited, + }); + } + let total = 0; + for (let index = 0; index < rows.length; index += 1) { + const row = rows[index]!; + if (!matches(row, index)) continue; + if (total >= view.offset && selected.length < view.limit && !byteLimited) + if (!admit(project(row, index))) return tooLarge(); + total++; + } + return ok({ rows: selected, total, byte_limited: byteLimited }); +}; diff --git a/src/domain/analysisView/summarySchemas/apktoolResourcesSummarySchemas.ts b/src/domain/analysisView/summarySchemas/apktoolResourcesSummarySchemas.ts new file mode 100644 index 00000000000..1bec2cb6141 --- /dev/null +++ b/src/domain/analysisView/summarySchemas/apktoolResourcesSummarySchemas.ts @@ -0,0 +1,54 @@ +import { z } from "zod"; + +import { knownCoverageStatusSchema } from "../../coverage.js"; +import { + apktoolManifestViewRequestSchema, + apktoolStringsViewRequestSchema, +} from "../../apktool/apktoolResourcesQuery.js"; +import { + summaryViewResultBase, + viewResultBaseFields, +} from "../analysisViewBase.js"; +import { + apktoolManifestPageItemSchema, + apktoolResourcesSummarySchema, + apktoolStringRowSchema, + apktoolStringTableSummarySchema, +} from "../apktoolResourcesView.js"; + +const parent_operation = z.literal("decode_android_resources"); + +/** Counts and table facts of one retained decode_android_resources result. */ +export const apktoolResourcesSummaryViewResultSchema = z.strictObject({ + ...summaryViewResultBase, + parent_operation, + summary: apktoolResourcesSummarySchema, +}); + +/** One page of decoded strings, with the selected tables' own completeness. */ +export const apktoolStringsViewResultSchema = z.strictObject({ + ...viewResultBaseFields, + kind: z.literal("android-resources"), + facet: z.literal("strings"), + parent_operation, + view: apktoolStringsViewRequestSchema, + tables: z.array(apktoolStringTableSummarySchema), + decode_coverage: knownCoverageStatusSchema, + items: z.array(apktoolStringRowSchema), + byte_limited: z.boolean(), +}); + +/** One UTF-16 page of the decoded manifest text. */ +export const apktoolManifestViewResultSchema = z.strictObject({ + ...viewResultBaseFields, + kind: z.literal("android-resources"), + facet: z.literal("manifest"), + parent_operation, + view: apktoolManifestViewRequestSchema, + item: apktoolManifestPageItemSchema, +}); + +export const apktoolResourcesPageViewResultSchema = z.discriminatedUnion( + "facet", + [apktoolStringsViewResultSchema, apktoolManifestViewResultSchema], +); diff --git a/src/domain/apktool/apktoolResourcesQuery.ts b/src/domain/apktool/apktoolResourcesQuery.ts new file mode 100644 index 00000000000..27fa75b3f55 --- /dev/null +++ b/src/domain/apktool/apktoolResourcesQuery.ts @@ -0,0 +1,34 @@ +import { z } from "zod"; + +const names = (description: string) => + z.array(z.string().min(1)).min(1).optional().describe(description); + +/** One page of the decoded string rows, across the decoded tables. */ +export const apktoolStringsViewRequestSchema = z.strictObject({ + kind: z.literal("android-resources"), + facet: z.literal("strings"), + offset: z.int().nonnegative().default(0), + limit: z.int().positive().default(64), + locales: z + .array(z.string().min(1).nullable()) + .min(1) + .optional() + .describe( + "Decoded tables to read: null for the default table, or a locale exactly as string_tables[].locale reports it. Omit for every decoded table.", + ), + names: names("Exact string resource names"), + name_prefixes: names("String resource name prefixes, matched exactly"), +}); + +/** Exact decoded AndroidManifest.xml text; positions count UTF-16 code units. */ +export const apktoolManifestViewRequestSchema = z.strictObject({ + kind: z.literal("android-resources"), + facet: z.literal("manifest"), + offset: z.int().nonnegative().default(0), + limit: z.int().positive().max(65_536).default(16_384), +}); + +export const apktoolResourcesViewRequestSchema = z.discriminatedUnion("facet", [ + apktoolStringsViewRequestSchema, + apktoolManifestViewRequestSchema, +]);