From f882168ecefe4588f84b5e62f176d784349e50f0 Mon Sep 17 00:00:00 2001 From: ShuaixinHuang <1836656514@qq.com> Date: Thu, 19 Nov 2026 21:38:14 +0800 Subject: [PATCH 01/11] fix(desktop): verify single-stanza APT source identity --- src/domain/desktop/aptRepositories.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/domain/desktop/aptRepositories.ts b/src/domain/desktop/aptRepositories.ts index 7a4491c0571..bc70d273032 100644 --- a/src/domain/desktop/aptRepositories.ts +++ b/src/domain/desktop/aptRepositories.ts @@ -334,7 +334,8 @@ export const entryForTarget = ( ); if (at === undefined) return undefined; const { uris, suites, ...entry } = at; - const single = uris.length === 1 && suites.length === 1; + const single = + !at.file.endsWith(".sources") && uris.length === 1 && suites.length === 1; // A one-line entry has one URI and one suite. Only deb822 needs a URI lookup. const matches = single ? uris From 55b141b035b5f68651bb832fe19006a0bcc815dc Mon Sep 17 00:00:00 2001 From: ShuaixinHuang <1836656514@qq.com> Date: Thu, 19 Nov 2026 21:38:17 +0800 Subject: [PATCH 02/11] fix(desktop): verify single-stanza APT source identity --- src/domain/desktop/aptRepositories.test.ts | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/src/domain/desktop/aptRepositories.test.ts b/src/domain/desktop/aptRepositories.test.ts index d958fc73f90..fa66a480b0f 100644 --- a/src/domain/desktop/aptRepositories.test.ts +++ b/src/domain/desktop/aptRepositories.test.ts @@ -433,6 +433,25 @@ describe("APT source URI lookup", () => { codename: null, }); + it("requires a single deb822 declaration to match the observed URI and suite", () => { + const stanzas = parseDeb822Sources( + "Types: deb\nURIs: https://vendor.invalid/archive\nSuites: stable\nComponents: main\n", + file, + ); + expect( + entryForTarget(targetFor("https://vendor.invalid/archive/"), stanzas), + ).toMatchObject({ suite: "stable" }); + expect( + entryForTarget(targetFor("https://other.invalid/archive/"), stanzas), + ).toBeUndefined(); + expect( + entryForTarget( + { ...targetFor("https://vendor.invalid/archive/"), release: "testing" }, + stanzas, + ), + ).toBeUndefined(); + }); + it("matches APT's deb822 Repo-URI spellings without changing the source URI", () => { const stanzas = parseDeb822Sources( [ From 01536432f39399472d0066777bc8c2c744bb5c97 Mon Sep 17 00:00:00 2001 From: morluto <76467478+morluto@users.noreply.github.com> Date: Thu, 19 Nov 2026 09:15:00 -0500 Subject: [PATCH 03/11] fix(desktop): match APT suites using its configured architecture --- .../vendor-packages/spec.md | 5 +- src/desktop/AptRepositoryInventory.test.ts | 10 +- src/desktop/AptRepositoryInventory.ts | 57 ++++++----- src/domain/desktop/aptRepositories.test.ts | 96 ++++++++++++++----- src/domain/desktop/aptRepositories.ts | 36 +++++-- 5 files changed, 145 insertions(+), 59 deletions(-) diff --git a/docs/specs/desktop-app-environments/vendor-packages/spec.md b/docs/specs/desktop-app-environments/vendor-packages/spec.md index 4ff8d703dda..8292f93a0e7 100644 --- a/docs/specs/desktop-app-environments/vendor-packages/spec.md +++ b/docs/specs/desktop-app-environments/vendor-packages/spec.md @@ -22,7 +22,10 @@ that key, with those libraries, and starts it. bytes leaves repository attribution unknown. Flat repositories (suite `./` or `/`, no components), `[signed-by=…]` and `Signed-By:` options and architecture options are read; a deb822 stanza's URIs and suites are - kept as lists, never expanded into every pair. `release` is the release's + kept as lists, never expanded into every pair. REA matches a suite's + `$(ARCH)` against the effective architecture read from `apt-config` and + keeps the authored suite for replay. A template match requires that + configuration fact. `release` is the release's Suite (`a=`), or else its Codename, from the same index target. A user name or password in a URI, up to the last `@` before its path as apt reads it, is removed from every sources entry, from `apt-get indextargets`' diff --git a/src/desktop/AptRepositoryInventory.test.ts b/src/desktop/AptRepositoryInventory.test.ts index d958dd93316..02b47fb944b 100644 --- a/src/desktop/AptRepositoryInventory.test.ts +++ b/src/desktop/AptRepositoryInventory.test.ts @@ -511,11 +511,16 @@ describe.skipIf( `Dir::Etc::Trusted=${selected.trusted}`, "-o", `Dir::State::status=${selected.status}`, + "-o", + "APT::Architecture=armhf", ...argv, ], signal, ); - expect(await resolveAptLocations(configured, undefined)).toEqual(selected); + expect(await resolveAptLocations(configured, undefined)).toEqual({ + ...selected, + configuredArchitecture: "armhf", + }); }); it("reads the lists folder an APT_CONFIG file names, resolved under Dir::State", async () => { @@ -523,7 +528,7 @@ describe.skipIf( const config = join(root, "apt.conf"); await writeFile( config, - `Dir::State "${root}/state";\nDir::State::Lists "user lists";\n`, + `Dir::State "${root}/state";\nDir::State::Lists "user lists";\nAPT::Architecture "amd64";\n`, ); const configured: QueryRunner = (command, argv, signal) => runHostQuery("env", [`APT_CONFIG=${config}`, command, ...argv], signal); @@ -535,6 +540,7 @@ describe.skipIf( trustedParts: "/etc/apt/trusted.gpg.d/", trusted: "/etc/apt/trusted.gpg", status: "/var/lib/dpkg/status", + configuredArchitecture: "amd64", }); expect( await resolveAptLocations( diff --git a/src/desktop/AptRepositoryInventory.ts b/src/desktop/AptRepositoryInventory.ts index bbd2db6f4f5..dc5e17bf2bd 100644 --- a/src/desktop/AptRepositoryInventory.ts +++ b/src/desktop/AptRepositoryInventory.ts @@ -22,15 +22,17 @@ import { type VerifiedKey, } from "./GpgvKeyCheck.js"; import { hostFileKind, readHostFile } from "./HostFileRead.js"; -import { succeeded, type QueryRunner } from "./HostQuery.js"; +import { queryUtf8Text, type QueryRunner } from "./HostQuery.js"; -/** Where apt keeps trusted keys, downloaded lists and installed state. */ +/** APT configuration used for repository lookup and suite identity. */ export interface AptLocations { readonly trustedParts: string; readonly trusted: string; readonly lists: string; /** Omitted by injected hosts that use APT's default installed database. */ readonly status?: string; + /** Omitted when apt-config did not establish the architecture. */ + readonly configuredArchitecture?: string; } export const APT_LOCATIONS: AptLocations = { @@ -44,31 +46,33 @@ export const APT_LOCATIONS: AptLocations = { * apt's folders as `apt-config` resolves them under `Dir`, which an * `APT_CONFIG` file can move, as a user-space `apt-get update` does with its * lists. Each is the fallback's when apt-config is missing, fails or does not - * name it. + * name it. APT::Architecture requires a successful configuration query. */ export const resolveAptLocations = async ( runQuery: QueryRunner, signal: AbortSignal | undefined, fallback: AptLocations = APT_LOCATIONS, ): Promise => { - const output = succeeded( - await runQuery( - "apt-config", - [ - "shell", - "LISTS", - "Dir::State::Lists/d", - "PARTS", - "Dir::Etc::TrustedParts/d", - "TRUSTED", - "Dir::Etc::Trusted/f", - "STATUS", - "Dir::State::status/f", - ], - signal, - ), + const output = await queryUtf8Text( + runQuery, + "apt-config", + [ + "shell", + "LISTS", + "Dir::State::Lists/d", + "PARTS", + "Dir::Etc::TrustedParts/d", + "TRUSTED", + "Dir::Etc::Trusted/f", + "STATUS", + "Dir::State::status/f", + "ARCH", + "APT::Architecture", + ], + signal, ); - const values = parseAptConfigShell(output ?? ""); + const values = parseAptConfigShell(output.kind === "read" ? output.text : ""); + const architecture = values.get("ARCH"); const value = (name: string) => { const found = values.get(name); return found?.startsWith("/") === true ? found : undefined; @@ -78,6 +82,10 @@ export const resolveAptLocations = async ( trustedParts: value("PARTS") ?? fallback.trustedParts, trusted: value("TRUSTED") ?? fallback.trusted, status: value("STATUS") ?? fallback.status ?? DEFAULT_DPKG_STATUS_SOURCE, + ...(architecture === undefined || + !/^[a-z0-9][a-z0-9-]*$/u.test(architecture) + ? {} + : { configuredArchitecture: architecture }), }; }; @@ -105,6 +113,7 @@ const UBUNTU_PRO = const indexTargets = async ( runQuery: QueryRunner, signal: AbortSignal | undefined, + configuredArchitecture?: string, ): Promise< | { readonly entries: ReadonlyMap; @@ -121,7 +130,7 @@ const indexTargets = async ( if (typeof query !== "object" || query.exitCode !== 0) return undefined; const output = query.stdoutBuffer ?? query.stdout; const targets = new Map(); - for (const target of parseAptIndexTargets(output)) + for (const target of parseAptIndexTargets(output, configuredArchitecture)) if (!targets.has(target.description)) targets.set(target.description, target); return { @@ -343,7 +352,11 @@ export const inspectAptRepositories = async ( indexTargets: new Map(), limitations: [], }; - const targets = await indexTargets(host.runQuery, signal); + const targets = await indexTargets( + host.runQuery, + signal, + host.apt.configuredArchitecture, + ); const files = sourcesFiles(signal); return withGpgvKeyCheck(host.runQuery, signal, async (check) => { const context: RepositoryContext = { diff --git a/src/domain/desktop/aptRepositories.test.ts b/src/domain/desktop/aptRepositories.test.ts index fa66a480b0f..709433dcfeb 100644 --- a/src/domain/desktop/aptRepositories.test.ts +++ b/src/domain/desktop/aptRepositories.test.ts @@ -141,6 +141,7 @@ describe("parseOneLineSources", () => { { file: TYPORA_LIST, position: 1, + format: "one-line", uris: [ { uri: "https://downloads.typora.io/linux", credentials: false }, ], @@ -412,31 +413,31 @@ describe("apt index targets", () => { }); }); -describe("APT source URI lookup", () => { - const file = "/etc/apt/sources.list.d/vendor.sources"; +const deb822LookupFile = "/etc/apt/sources.list.d/vendor.sources"; - const targetFor = ( - repoUri: string, - description = repoUri, - component = "main", - ) => ({ - description, - sourcesFile: file, - position: 1, - repoUri, - release: "stable", - component, - baseUri: `${repoUri}dists/stable/`, - filename: "/var/lib/apt/lists/vendor", - origin: null, - suite: null, - codename: null, - }); +const targetFor = ( + repoUri: string, + description = repoUri, + component = "main", +) => ({ + description, + sourcesFile: deb822LookupFile, + position: 1, + repoUri, + release: "stable", + component, + baseUri: `${repoUri}dists/stable/`, + filename: "/var/lib/apt/lists/vendor", + origin: null, + suite: null, + codename: null, +}); +describe("single-stanza APT source identity", () => { it("requires a single deb822 declaration to match the observed URI and suite", () => { const stanzas = parseDeb822Sources( "Types: deb\nURIs: https://vendor.invalid/archive\nSuites: stable\nComponents: main\n", - file, + deb822LookupFile, ); expect( entryForTarget(targetFor("https://vendor.invalid/archive/"), stanzas), @@ -452,6 +453,53 @@ describe("APT source URI lookup", () => { ).toBeUndefined(); }); + it("uses APT's configured architecture for both exact-path source identity and attribution", () => { + const suite = "unstable/binary-$(ARCH)/"; + const uri = "https://vendor.invalid/archive"; + const stanzas = parseDeb822Sources( + `Types: deb\nURIs: ${uri}\nSuites: ${suite}\n`, + deb822LookupFile, + ); + const description = `${uri} unstable/binary-amd64/ Packages`; + // Offline APT emits the expanded Release and no per-target Architecture + // on this flat index. The source file and index still retain different facts. + const transcript = [ + `Description: ${description}`, + "Filename: /var/lib/apt/lists/apt-owned-Packages", + `Base-URI: ${uri}/unstable/binary-amd64/`, + `Repo-URI: ${uri}/`, + "Release: unstable/binary-amd64/", + `Sourcesentry: ${deb822LookupFile}:1`, + ].join("\n"); + const repository = { + source: description, + uri, + repo_uri: `${uri}/`, + sources_file: deb822LookupFile, + uri_credentials_removed: false, + suite, + components: [], + }; + for (const architecture of ["amd64", "arm64", undefined]) { + const [target] = parseAptIndexTargets(transcript, architecture); + if (target === undefined) throw new Error("Missing APT target"); + const entry = entryForTarget(target, stanzas); + const files = declaredPackageFiles( + [repository], + new Map([[description, target]]), + ); + if (architecture === "amd64") { + expect(entry).toMatchObject({ suite, components: [] }); + expect(files).toEqual(new Set([description])); + } else { + expect(entry).toBeUndefined(); + expect(files).toEqual(new Set()); + } + } + }); +}); + +describe("APT source URI lookup", () => { it("matches APT's deb822 Repo-URI spellings without changing the source URI", () => { const stanzas = parseDeb822Sources( [ @@ -460,7 +508,7 @@ describe("APT source URI lookup", () => { "Suites: stable", "Components: main", ].join("\n"), - file, + deb822LookupFile, ); // Repo-URI values from apt-get indextargets --no-release-info (APT 3.2.0). @@ -499,7 +547,7 @@ describe("APT source URI lookup", () => { where === "before the stanza" ? Buffer.concat([comment, Buffer.from("\n"), types, fields]) : Buffer.concat([types, comment, fields]); - const stanzas = parseDeb822Sources(source, file); + const stanzas = parseDeb822Sources(source, deb822LookupFile); expect(stanzas).toHaveLength(1); expect( entryForTarget(targetFor("https://good.invalid/archive/"), stanzas), @@ -514,7 +562,7 @@ describe("APT source URI lookup", () => { Buffer.from(declaration("bad.invalid/ÿ"), "latin1"), Buffer.from(`\n${declaration("good.invalid")}`), ]); - const stanzas = parseDeb822Sources(source, file); + const stanzas = parseDeb822Sources(source, deb822LookupFile); expect(stanzas).toHaveLength(1); expect( entryForTarget( @@ -532,7 +580,7 @@ describe("APT source URI lookup", () => { "Suites: stable", "Components: main", ].join("\n"), - file, + deb822LookupFile, ); expect( diff --git a/src/domain/desktop/aptRepositories.ts b/src/domain/desktop/aptRepositories.ts index bc70d273032..1425ec63a38 100644 --- a/src/domain/desktop/aptRepositories.ts +++ b/src/domain/desktop/aptRepositories.ts @@ -12,6 +12,7 @@ export interface AptSourceStanza { readonly file: string; /** apt's number for the entry: a one-line entry's line, a deb822 entry's stanza, counted from 1. */ readonly position: number; + readonly format: "one-line" | "deb822"; readonly uris: readonly AptSourceUri[]; readonly suites: readonly string[]; readonly components: readonly string[]; @@ -31,7 +32,7 @@ interface AptSourceUri { /** One `deb` entry of an apt sources file for one URI and suite. */ export interface AptSourceEntry extends Omit< AptSourceStanza, - "uris" | "suites" + "uris" | "suites" | "format" > { readonly uri: string | null; /** Whether the entry's URI held a user name or password, which `uri` leaves out. */ @@ -106,9 +107,18 @@ const inlineKeyBlock = (value: string): string | null => { return `${lines.slice(begin, end < begin ? lines.length : end + 1).join("\n")}\n`; }; -/** Whether a suite as an entry writes it is a target's release, which apt leaves empty for the flat suite `/`. */ -const isRelease = (suite: string, release: string): boolean => - suite === release || (suite === "/" && release === ""); +/** Match the selected release without changing an authored suite. */ +const isRelease = (suite: string, target: AptIndexTarget): boolean => { + const architectureVariable = "$(ARCH)"; + if (suite.includes(architectureVariable)) { + if (target.configuredArchitecture === undefined) return false; + suite = suite.replaceAll( + architectureVariable, + target.configuredArchitecture, + ); + } + return suite === target.release || (suite === "/" && target.release === ""); +}; const stanza = ( at: { readonly file: string; readonly position: number }, @@ -124,6 +134,7 @@ const stanza = ( const inlineKey = inlineKeyBlock(signedBy); return { ...at, + format: fields.oneLine === true ? "one-line" : "deb822", uris: fields.uris.map((source) => { const uri = withoutCredentials(source); return fields.oneLine === true && ONE_LINE_ESCAPED_USER_INFO.test(uri) @@ -262,8 +273,10 @@ export interface AptIndexTarget { /** Without a user name or password, as `baseUri`, whether or not apt printed them. */ readonly repoUri: string; readonly repoUriCredentialsRemoved?: true; - /** The suite as the entry writes it; empty for the flat suite `/`. */ + /** APT's selected suite after variable expansion; empty for the flat suite `/`. */ readonly release: string; + /** Effective APT::Architecture from apt-config, distinct from an index's architecture. */ + readonly configuredArchitecture?: string; /** The entry's component the index belongs to; null for a flat repository. */ readonly component: string | null; /** The URI of the folder holding the release's InRelease, Release and Release.gpg. */ @@ -281,6 +294,7 @@ const SOURCES_ENTRY = /^(?\/.*):(?[1-9]\d*)$/u; /** The index targets of `apt-get indextargets` output; a paragraph missing a field REA needs is skipped. */ export const parseAptIndexTargets = ( output: string | Buffer, + configuredArchitecture?: string, ): readonly AptIndexTarget[] => deb822Paragraphs(output).flatMap((fields) => { const at = SOURCES_ENTRY.exec(fields.get("sourcesentry") ?? "")?.groups; @@ -309,6 +323,9 @@ export const parseAptIndexTargets = ( ? {} : { repoUriCredentialsRemoved: true as const }), release: fields.get("release") ?? "", + ...(configuredArchitecture === undefined + ? {} + : { configuredArchitecture }), component: optional("component"), baseUri: withoutCredentials(baseUri), filename, @@ -333,9 +350,8 @@ export const entryForTarget = ( candidate.position === target.position, ); if (at === undefined) return undefined; - const { uris, suites, ...entry } = at; - const single = - !at.file.endsWith(".sources") && uris.length === 1 && suites.length === 1; + const { uris, suites, format, ...entry } = at; + const single = format === "one-line"; // A one-line entry has one URI and one suite. Only deb822 needs a URI lookup. const matches = single ? uris @@ -348,7 +364,7 @@ export const entryForTarget = ( first.uri === null ? null : withoutOptionalTrailingSlash(first.uri); const suite = single ? suites[0] - : suites.find((listed) => isRelease(listed, target.release)); + : suites.find((listed) => isRelease(listed, target)); if ( suite === undefined || matches.some(({ uri: listed }) => @@ -489,7 +505,7 @@ export const declaredPackageFiles = ( declarations.some( ({ repoUri, suite, components }) => repoUri === target.repoUri && - isRelease(suite, target.release) && + isRelease(suite, target) && (target.component === null ? components.length === 0 : components.includes(target.component)), From e4fdc8f9370536a2d34a31abcb0425fb77aa404b Mon Sep 17 00:00:00 2001 From: morluto <76467478+morluto@users.noreply.github.com> Date: Thu, 19 Nov 2026 09:16:46 -0500 Subject: [PATCH 04/11] fix(desktop): match APT URI architecture templates --- .../vendor-packages/spec.md | 6 +- src/domain/desktop/aptRepositories.test.ts | 99 +++++++++++-------- src/domain/desktop/aptRepositories.ts | 38 ++++--- 3 files changed, 86 insertions(+), 57 deletions(-) diff --git a/docs/specs/desktop-app-environments/vendor-packages/spec.md b/docs/specs/desktop-app-environments/vendor-packages/spec.md index 8292f93a0e7..b0a168f0f21 100644 --- a/docs/specs/desktop-app-environments/vendor-packages/spec.md +++ b/docs/specs/desktop-app-environments/vendor-packages/spec.md @@ -22,9 +22,9 @@ that key, with those libraries, and starts it. bytes leaves repository attribution unknown. Flat repositories (suite `./` or `/`, no components), `[signed-by=…]` and `Signed-By:` options and architecture options are read; a deb822 stanza's URIs and suites are - kept as lists, never expanded into every pair. REA matches a suite's - `$(ARCH)` against the effective architecture read from `apt-config` and - keeps the authored suite for replay. A template match requires that + kept as lists, never expanded into every pair. REA matches `$(ARCH)` in + a URI or suite against the effective architecture read from `apt-config` + and keeps the authored URI and suite. A template match requires that configuration fact. `release` is the release's Suite (`a=`), or else its Codename, from the same index target. A user name or password in a URI, up to the last `@` before its path as apt reads it, diff --git a/src/domain/desktop/aptRepositories.test.ts b/src/domain/desktop/aptRepositories.test.ts index 709433dcfeb..af3ef92de7f 100644 --- a/src/domain/desktop/aptRepositories.test.ts +++ b/src/domain/desktop/aptRepositories.test.ts @@ -453,50 +453,65 @@ describe("single-stanza APT source identity", () => { ).toBeUndefined(); }); - it("uses APT's configured architecture for both exact-path source identity and attribution", () => { - const suite = "unstable/binary-$(ARCH)/"; - const uri = "https://vendor.invalid/archive"; - const stanzas = parseDeb822Sources( - `Types: deb\nURIs: ${uri}\nSuites: ${suite}\n`, - deb822LookupFile, - ); - const description = `${uri} unstable/binary-amd64/ Packages`; - // Offline APT emits the expanded Release and no per-target Architecture - // on this flat index. The source file and index still retain different facts. - const transcript = [ - `Description: ${description}`, - "Filename: /var/lib/apt/lists/apt-owned-Packages", - `Base-URI: ${uri}/unstable/binary-amd64/`, - `Repo-URI: ${uri}/`, - "Release: unstable/binary-amd64/", - `Sourcesentry: ${deb822LookupFile}:1`, - ].join("\n"); - const repository = { - source: description, - uri, - repo_uri: `${uri}/`, - sources_file: deb822LookupFile, - uri_credentials_removed: false, - suite, - components: [], - }; - for (const architecture of ["amd64", "arm64", undefined]) { - const [target] = parseAptIndexTargets(transcript, architecture); - if (target === undefined) throw new Error("Missing APT target"); - const entry = entryForTarget(target, stanzas); - const files = declaredPackageFiles( - [repository], - new Map([[description, target]]), + it.each([ + { + field: "suite", + uri: "https://vendor.invalid/archive", + suite: "unstable/binary-$(ARCH)/", + }, + { + field: "URI", + uri: "https://vendor.invalid/archive-$(ARCH)", + suite: "unstable/binary-amd64/", + }, + ])( + "uses APT's configured architecture in a deb822 $field for identity and attribution", + ({ field, uri, suite }) => { + const observedUri = uri.replace("$(ARCH)", "amd64"); + const stanzas = parseDeb822Sources( + `Types: deb\nURIs: ${uri}\nSuites: ${suite}\n`, + deb822LookupFile, ); - if (architecture === "amd64") { - expect(entry).toMatchObject({ suite, components: [] }); - expect(files).toEqual(new Set([description])); - } else { - expect(entry).toBeUndefined(); - expect(files).toEqual(new Set()); + const description = `${observedUri} unstable/binary-amd64/ Packages`; + // Offline APT emits the expanded Release and no per-target Architecture + // on this flat index. The source file and index still retain different facts. + const transcript = [ + `Description: ${description}`, + "Filename: /var/lib/apt/lists/apt-owned-Packages", + `Base-URI: ${observedUri}/unstable/binary-amd64/`, + `Repo-URI: ${observedUri}/`, + "Release: unstable/binary-amd64/", + `Sourcesentry: ${deb822LookupFile}:1`, + ].join("\n"); + const repository = { + source: description, + uri, + repo_uri: `${observedUri}/`, + sources_file: deb822LookupFile, + uri_credentials_removed: false, + suite, + components: [], + }; + for (const architecture of ["amd64", "arm64", undefined]) { + const [target] = parseAptIndexTargets(transcript, architecture); + if (target === undefined) throw new Error("Missing APT target"); + const entry = entryForTarget(target, stanzas); + const files = declaredPackageFiles( + [repository], + new Map([[description, target]]), + ); + if (architecture === "amd64") { + expect(entry).toMatchObject({ uri, suite, components: [] }); + expect(files).toEqual(new Set([description])); + } else { + expect(entry).toBeUndefined(); + // A historical capture can replay an already materialized Repo-URI. + // The authored suite has no separate expanded value in that contract. + expect(files).toEqual(new Set(field === "URI" ? [description] : [])); + } } - } - }); + }, + ); }); describe("APT source URI lookup", () => { diff --git a/src/domain/desktop/aptRepositories.ts b/src/domain/desktop/aptRepositories.ts index 1425ec63a38..11604dd5b5c 100644 --- a/src/domain/desktop/aptRepositories.ts +++ b/src/domain/desktop/aptRepositories.ts @@ -107,17 +107,24 @@ const inlineKeyBlock = (value: string): string | null => { return `${lines.slice(begin, end < begin ? lines.length : end + 1).join("\n")}\n`; }; +/** APT expands this variable in repository URIs and suites using APT::Architecture. */ +const expandAptArchitecture = ( + value: string, + architecture: string | undefined, +): string | undefined => { + const variable = "$(ARCH)"; + if (!value.includes(variable)) return value; + return architecture === undefined + ? undefined + : value.replaceAll(variable, architecture); +}; + /** Match the selected release without changing an authored suite. */ const isRelease = (suite: string, target: AptIndexTarget): boolean => { - const architectureVariable = "$(ARCH)"; - if (suite.includes(architectureVariable)) { - if (target.configuredArchitecture === undefined) return false; - suite = suite.replaceAll( - architectureVariable, - target.configuredArchitecture, - ); - } - return suite === target.release || (suite === "/" && target.release === ""); + const selected = expandAptArchitecture(suite, target.configuredArchitecture); + return ( + selected === target.release || (selected === "/" && target.release === "") + ); }; const stanza = ( @@ -355,9 +362,16 @@ export const entryForTarget = ( // A one-line entry has one URI and one suite. Only deb822 needs a URI lookup. const matches = single ? uris - : uris.filter( - ({ uri }) => uri !== null && deb822RepoUri(uri) === target.repoUri, - ); + : uris.filter(({ uri }) => { + if (uri === null) return false; + const selected = expandAptArchitecture( + uri, + target.configuredArchitecture, + ); + return ( + selected !== undefined && deb822RepoUri(selected) === target.repoUri + ); + }); const first = matches[0]; if (first === undefined) return undefined; const uri = From f2d9d947c3fe96566cf505fe82d63b39a31f698a Mon Sep 17 00:00:00 2001 From: ShuaixinHuang Date: Thu, 19 Nov 2026 23:35:39 +0800 Subject: [PATCH 05/11] fix(desktop): normalize empty APT URI ports --- src/domain/desktop/aptRepositories.test.ts | 3 ++- src/domain/desktop/aptRepositories.ts | 6 +++--- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/src/domain/desktop/aptRepositories.test.ts b/src/domain/desktop/aptRepositories.test.ts index af3ef92de7f..3d3318b0ff7 100644 --- a/src/domain/desktop/aptRepositories.test.ts +++ b/src/domain/desktop/aptRepositories.test.ts @@ -519,7 +519,7 @@ describe("APT source URI lookup", () => { const stanzas = parseDeb822Sources( [ "Types: deb", - "URIs: file:///srv/a%20b copy:/srv/repo https://vendor.invalid:00080/archive https://[2001:db8::11]:08443/apt file:/srv/double//", + "URIs: file:///srv/a%20b copy:/srv/repo https://vendor.invalid:00080/archive https://empty.invalid:/archive https://[2001:db8::11]:08443/apt file:/srv/double//", "Suites: stable", "Components: main", ].join("\n"), @@ -530,6 +530,7 @@ describe("APT source URI lookup", () => { const spellings = [ ["file:/srv/a%20b/", "file:///srv/a%20b"], ["copy:/srv/repo/", "copy:/srv/repo"], + ["https://empty.invalid/archive/", "https://empty.invalid:/archive"], [ "https://vendor.invalid:80/archive/", "https://vendor.invalid:00080/archive", diff --git a/src/domain/desktop/aptRepositories.ts b/src/domain/desktop/aptRepositories.ts index 11604dd5b5c..564beb514cb 100644 --- a/src/domain/desktop/aptRepositories.ts +++ b/src/domain/desktop/aptRepositories.ts @@ -77,15 +77,15 @@ const withTrailingSlash = (uri: string): string => uri.endsWith("/") ? uri : `${uri}/`; const EMPTY_AUTHORITY = /^([a-z][a-z0-9+.-]*:)\/\/(?=\/)/iu; -const NUMERIC_PORT = - /^([a-z][a-z0-9+.-]*:\/\/(?:\[[^\]]+\]|[^/:]+)):([0-9]+)(?=\/|$)/iu; +const DECIMAL_PORT = + /^([a-z][a-z0-9+.-]*:\/\/(?:\[[^\]]+\]|[^/:]+)):([0-9]*)(?=\/|$)/iu; /** APT fixes up deb822 URIs before emitting Repo-URI, leaving path octets intact. */ const deb822RepoUri = (uri: string): string => withTrailingSlash( uri .replace(EMPTY_AUTHORITY, "$1") - .replace(NUMERIC_PORT, (_match, authority: string, port: string) => { + .replace(DECIMAL_PORT, (_match, authority: string, port: string) => { const digits = port.replace(/^0+/u, ""); return digits === "" ? authority : `${authority}:${digits}`; }), From 11870da401ab2c795ceba0fef60e4869066be4de Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Thu, 19 Nov 2026 15:39:48 +0000 Subject: [PATCH 06/11] test(desktop): regress empty-port APT repository identity Assert entryForTarget and repository facts keep the authored empty-port URI while matching the portless Repo-URI APT 2.8.3 emits, including the signing key. Co-authored-by: morluto --- src/desktop/AptRepositoryInventory.test.ts | 65 ++++++++++++++++++++++ src/domain/desktop/aptRepositories.test.ts | 28 ++++++++++ src/domain/desktop/aptRepositories.ts | 2 + 3 files changed, 95 insertions(+) diff --git a/src/desktop/AptRepositoryInventory.test.ts b/src/desktop/AptRepositoryInventory.test.ts index 02b47fb944b..f9cd41f63b3 100644 --- a/src/desktop/AptRepositoryInventory.test.ts +++ b/src/desktop/AptRepositoryInventory.test.ts @@ -207,6 +207,71 @@ it.each([ }, ); +it("retains an empty-port deb822 URI, its suite, and its signing key", async () => { + const root = await createTestTempDirectory("apt-empty-port-"); + const sources = join(root, "vendor.sources"); + const key = join(root, "vendor.gpg"); + const lists = join(root, "lists"); + const authored = "https://vendor.invalid:/archive"; + const repoUri = "https://vendor.invalid/archive/"; + const baseUri = `${repoUri}dists/stable/`; + const source = "https://vendor.invalid/archive stable/main amd64 Packages"; + await mkdir(lists); + await writeFile(key, VENDOR_A.key); + await writeFile( + join(lists, `${aptListFileName(baseUri)}InRelease`), + "controlled release", + ); + await writeFile( + sources, + `Types: deb\nURIs: ${authored}\nSuites: stable\nComponents: main\nSigned-By: ${key}\n`, + ); + const targets = [ + `Description: ${source}`, + `Sourcesentry: ${sources}:1`, + `Repo-URI: ${repoUri}`, + "Release: stable", + "Suite: stable", + "Component: main", + `Base-URI: ${baseUri}`, + `Filename: ${join(lists, "Packages")}`, + ].join("\n"); + const runQuery: QueryRunner = async (command) => { + if (command === "apt-get") return { stdout: targets, exitCode: 0 }; + if (command !== "gpgv") throw new Error(`Unexpected query ${command}`); + return { stdout: GPGV_A_ONLY, exitCode: 2 }; + }; + const facts = await inspectAptRepositories( + { sources: [source], origins: ["Vendor"] }, + { + runQuery, + apt: { lists, trustedParts: root, trusted: join(root, "trusted.gpg") }, + }, + undefined, + ); + + expect(facts.repositories).toHaveLength(1); + const repository = facts.repositories[0]; + expect(repository).toMatchObject({ + source, + sources_file: sources, + uri: authored, + repo_uri: repoUri, + uri_credentials_removed: false, + suite: "stable", + components: ["main"], + architectures: [], + release: "stable", + signing_key: { + path: key, + format: "binary", + fingerprint: VENDOR_A.fingerprint, + }, + }); + expect(repository).not.toHaveProperty("signing_key_reason"); + expect([...facts.keys.values()]).toEqual([VENDOR_A.key]); +}); + it("withholds an undecodable APT index and preserves an intact peer", async () => { const root = await createTestTempDirectory("apt-index-encoding-"); const file = join(root, "vendor.list"); diff --git a/src/domain/desktop/aptRepositories.test.ts b/src/domain/desktop/aptRepositories.test.ts index 3d3318b0ff7..0948a4cafb8 100644 --- a/src/domain/desktop/aptRepositories.test.ts +++ b/src/domain/desktop/aptRepositories.test.ts @@ -453,6 +453,34 @@ describe("single-stanza APT source identity", () => { ).toBeUndefined(); }); + it.each([ + ["https://vendor.invalid:/archive", "https://vendor.invalid/archive/"], + ["https://[2001:db8::11]:/apt", "https://[2001:db8::11]/apt/"], + ])( + "matches empty port %s to APT's portless Repo-URI and keeps the authored URI", + (authored, repoUri) => { + const stanzas = parseDeb822Sources( + `Types: deb\nURIs: ${authored}\nSuites: stable\nComponents: main\n`, + deb822LookupFile, + ); + // APT 2.8.3 `indextargets` reports the portless Repo-URI, not the colon. + expect(entryForTarget(targetFor(repoUri), stanzas)).toEqual({ + file: deb822LookupFile, + position: 1, + uri: authored, + credentials: false, + suite: "stable", + components: ["main"], + architectures: [], + signedBy: [], + inlineKey: null, + }); + expect( + entryForTarget(targetFor(`${authored}/`), stanzas), + ).toBeUndefined(); + }, + ); + it.each([ { field: "suite", diff --git a/src/domain/desktop/aptRepositories.ts b/src/domain/desktop/aptRepositories.ts index 564beb514cb..60af2850476 100644 --- a/src/domain/desktop/aptRepositories.ts +++ b/src/domain/desktop/aptRepositories.ts @@ -77,6 +77,8 @@ const withTrailingSlash = (uri: string): string => uri.endsWith("/") ? uri : `${uri}/`; const EMPTY_AUTHORITY = /^([a-z][a-z0-9+.-]*:)\/\/(?=\/)/iu; +// APT's URI parser takes the host's last :suffix with atoi and emits a port +// only when it is non-zero, so an empty or all-zero port loses its colon. const DECIMAL_PORT = /^([a-z][a-z0-9+.-]*:\/\/(?:\[[^\]]+\]|[^/:]+)):([0-9]*)(?=\/|$)/iu; From 27ea7d34f5c4f40045be4ce51694ef7aa93a0400 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Thu, 19 Nov 2026 16:31:38 +0000 Subject: [PATCH 07/11] fix(desktop): parse APT port suffixes with atoi Match deb822 Repo-URI identity to APT's unsigned port: the host's last colon suffix is atoi'd, zero is omitted, and IPv6 brackets stay intact while the authored URI is kept. Co-authored-by: morluto --- src/desktop/AptRepositoryInventory.test.ts | 136 +++++++++++---------- src/domain/desktop/aptRepositories.test.ts | 51 +++++++- src/domain/desktop/aptRepositories.ts | 110 +++++++++++++++-- 3 files changed, 216 insertions(+), 81 deletions(-) diff --git a/src/desktop/AptRepositoryInventory.test.ts b/src/desktop/AptRepositoryInventory.test.ts index f9cd41f63b3..55794fc7ca0 100644 --- a/src/desktop/AptRepositoryInventory.test.ts +++ b/src/desktop/AptRepositoryInventory.test.ts @@ -207,70 +207,80 @@ it.each([ }, ); -it("retains an empty-port deb822 URI, its suite, and its signing key", async () => { - const root = await createTestTempDirectory("apt-empty-port-"); - const sources = join(root, "vendor.sources"); - const key = join(root, "vendor.gpg"); - const lists = join(root, "lists"); - const authored = "https://vendor.invalid:/archive"; - const repoUri = "https://vendor.invalid/archive/"; - const baseUri = `${repoUri}dists/stable/`; - const source = "https://vendor.invalid/archive stable/main amd64 Packages"; - await mkdir(lists); - await writeFile(key, VENDOR_A.key); - await writeFile( - join(lists, `${aptListFileName(baseUri)}InRelease`), - "controlled release", - ); - await writeFile( - sources, - `Types: deb\nURIs: ${authored}\nSuites: stable\nComponents: main\nSigned-By: ${key}\n`, - ); - const targets = [ - `Description: ${source}`, - `Sourcesentry: ${sources}:1`, - `Repo-URI: ${repoUri}`, - "Release: stable", - "Suite: stable", - "Component: main", - `Base-URI: ${baseUri}`, - `Filename: ${join(lists, "Packages")}`, - ].join("\n"); - const runQuery: QueryRunner = async (command) => { - if (command === "apt-get") return { stdout: targets, exitCode: 0 }; - if (command !== "gpgv") throw new Error(`Unexpected query ${command}`); - return { stdout: GPGV_A_ONLY, exitCode: 2 }; - }; - const facts = await inspectAptRepositories( - { sources: [source], origins: ["Vendor"] }, - { - runQuery, - apt: { lists, trustedParts: root, trusted: join(root, "trusted.gpg") }, - }, - undefined, - ); +it.each([ + ["https://vendor.invalid:/archive", "https://vendor.invalid/archive/"], + [ + "https://vendor.invalid:80abc/archive", + "https://vendor.invalid:80/archive/", + ], + ["https://vendor.invalid:https/archive", "https://vendor.invalid/archive/"], + ["https://[2001:db8::11]:80abc/apt", "https://[2001:db8::11]:80/apt/"], + ["https://[2001:db8::11]:https/apt", "https://[2001:db8::11]/apt/"], +])( + "retains authored %s when APT reports %s, including its signing key", + async (authored, repoUri) => { + const root = await createTestTempDirectory("apt-port-suffix-"); + const sources = join(root, "vendor.sources"); + const key = join(root, "vendor.gpg"); + const lists = join(root, "lists"); + const baseUri = `${repoUri}dists/stable/`; + const source = `${repoUri.slice(0, -1)} stable/main amd64 Packages`; + await mkdir(lists); + await writeFile(key, VENDOR_A.key); + await writeFile( + join(lists, `${aptListFileName(baseUri)}InRelease`), + "controlled release", + ); + await writeFile( + sources, + `Types: deb\nURIs: ${authored}\nSuites: stable\nComponents: main\nSigned-By: ${key}\n`, + ); + const targets = [ + `Description: ${source}`, + `Sourcesentry: ${sources}:1`, + `Repo-URI: ${repoUri}`, + "Release: stable", + "Suite: stable", + "Component: main", + `Base-URI: ${baseUri}`, + `Filename: ${join(lists, "Packages")}`, + ].join("\n"); + const runQuery: QueryRunner = async (command) => { + if (command === "apt-get") return { stdout: targets, exitCode: 0 }; + if (command !== "gpgv") throw new Error(`Unexpected query ${command}`); + return { stdout: GPGV_A_ONLY, exitCode: 2 }; + }; + const facts = await inspectAptRepositories( + { sources: [source], origins: ["Vendor"] }, + { + runQuery, + apt: { lists, trustedParts: root, trusted: join(root, "trusted.gpg") }, + }, + undefined, + ); - expect(facts.repositories).toHaveLength(1); - const repository = facts.repositories[0]; - expect(repository).toMatchObject({ - source, - sources_file: sources, - uri: authored, - repo_uri: repoUri, - uri_credentials_removed: false, - suite: "stable", - components: ["main"], - architectures: [], - release: "stable", - signing_key: { - path: key, - format: "binary", - fingerprint: VENDOR_A.fingerprint, - }, - }); - expect(repository).not.toHaveProperty("signing_key_reason"); - expect([...facts.keys.values()]).toEqual([VENDOR_A.key]); -}); + expect(facts.repositories).toEqual([ + expect.objectContaining({ + source, + sources_file: sources, + uri: authored, + repo_uri: repoUri, + uri_credentials_removed: false, + suite: "stable", + components: ["main"], + architectures: [], + release: "stable", + signing_key: expect.objectContaining({ + path: key, + format: "binary", + fingerprint: VENDOR_A.fingerprint, + }), + }), + ]); + expect(facts.repositories[0]).not.toHaveProperty("signing_key_reason"); + expect([...facts.keys.values()]).toEqual([VENDOR_A.key]); + }, +); it("withholds an undecodable APT index and preserves an intact peer", async () => { const root = await createTestTempDirectory("apt-index-encoding-"); diff --git a/src/domain/desktop/aptRepositories.test.ts b/src/domain/desktop/aptRepositories.test.ts index 0948a4cafb8..49644f3ab35 100644 --- a/src/domain/desktop/aptRepositories.test.ts +++ b/src/domain/desktop/aptRepositories.test.ts @@ -456,14 +456,55 @@ describe("single-stanza APT source identity", () => { it.each([ ["https://vendor.invalid:/archive", "https://vendor.invalid/archive/"], ["https://[2001:db8::11]:/apt", "https://[2001:db8::11]/apt/"], + [ + "https://vendor.invalid:80abc/archive", + "https://vendor.invalid:80/archive/", + ], + ["https://vendor.invalid:https/archive", "https://vendor.invalid/archive/"], + [ + "https://vendor.invalid:0080abc/archive", + "https://vendor.invalid:80/archive/", + ], + [ + "https://vendor.invalid:+80abc/archive", + "https://vendor.invalid:80/archive/", + ], + [ + "https://vendor.invalid:-80/archive", + "https://vendor.invalid:4294967216/archive/", + ], + [ + "https://vendor.invalid:4294967296/archive", + "https://vendor.invalid/archive/", + ], + [ + "https://vendor.invalid:2147483648abc/archive", + "https://vendor.invalid:2147483648/archive/", + ], + [ + "https://vendor.invalid:999999999999999999999/archive", + "https://vendor.invalid:4294967295/archive/", + ], + ["https://[2001:db8::11]:80abc/apt", "https://[2001:db8::11]:80/apt/"], + ["https://[2001:db8::11]:https/apt", "https://[2001:db8::11]/apt/"], + ["https://[::1]:80:abc/apt", "https://[::1:80]/apt/"], + [ + "https://vendor.invalid:foo:80abc/archive", + "https://[vendor.invalid:foo]:80/archive/", + ], + [ + "https://vendor.invalid/archive:80abc/x", + "https://vendor.invalid/archive:80abc/x/", + ], + ["file://hostname:80abc/path", "file://hostname:80/path/"], + ["file:///srv/a%20b", "file:/srv/a%20b/"], ])( - "matches empty port %s to APT's portless Repo-URI and keeps the authored URI", + "matches %s to the Repo-URI APT emits and keeps the authored URI", (authored, repoUri) => { const stanzas = parseDeb822Sources( `Types: deb\nURIs: ${authored}\nSuites: stable\nComponents: main\n`, deb822LookupFile, ); - // APT 2.8.3 `indextargets` reports the portless Repo-URI, not the colon. expect(entryForTarget(targetFor(repoUri), stanzas)).toEqual({ file: deb822LookupFile, position: 1, @@ -475,9 +516,9 @@ describe("single-stanza APT source identity", () => { signedBy: [], inlineKey: null, }); - expect( - entryForTarget(targetFor(`${authored}/`), stanzas), - ).toBeUndefined(); + const untouched = authored.endsWith("/") ? authored : `${authored}/`; + if (untouched !== repoUri) + expect(entryForTarget(targetFor(untouched), stanzas)).toBeUndefined(); }, ); diff --git a/src/domain/desktop/aptRepositories.ts b/src/domain/desktop/aptRepositories.ts index 60af2850476..66f712e9b7e 100644 --- a/src/domain/desktop/aptRepositories.ts +++ b/src/domain/desktop/aptRepositories.ts @@ -76,22 +76,106 @@ export const withoutCredentialsIn = (text: string): string => const withTrailingSlash = (uri: string): string => uri.endsWith("/") ? uri : `${uri}/`; -const EMPTY_AUTHORITY = /^([a-z][a-z0-9+.-]*:)\/\/(?=\/)/iu; -// APT's URI parser takes the host's last :suffix with atoi and emits a port -// only when it is non-zero, so an empty or all-zero port loses its colon. -const DECIMAL_PORT = - /^([a-z][a-z0-9+.-]*:\/\/(?:\[[^\]]+\]|[^/:]+)):([0-9]*)(?=\/|$)/iu; +const SCHEME_AUTHORITY = /^([a-z][a-z0-9+.-]*):\/\//iu; +const LONG_MAX = (1n << 63n) - 1n; +const LONG_MIN = -(1n << 63n); + +const isAsciiSpace = (character: string): boolean => + character === " " || + character === "\t" || + character === "\n" || + character === "\v" || + character === "\f" || + character === "\r"; + +/** + * APT assigns `atoi(suffix)` to an unsigned 32-bit port. Trailing junk stops + * the conversion, and a zero result is omitted. + */ +const aptPort = (suffix: string): number => { + let index = 0; + while (index < suffix.length && isAsciiSpace(suffix[index] ?? "")) index += 1; + const sign = suffix[index]; + const negative = sign === "-"; + if (sign === "+" || sign === "-") index += 1; + let magnitude = 0n; + while (index < suffix.length) { + const code = suffix.charCodeAt(index); + if (code < 48 || code > 57) break; + magnitude = magnitude * 10n + BigInt(code - 48); + index += 1; + } + let value = negative ? -magnitude : magnitude; + if (value > LONG_MAX) value = LONG_MAX; + else if (value < LONG_MIN) value = LONG_MIN; + return Number(BigInt.asUintN(32, BigInt.asIntN(32, value))); +}; + +/** The first path slash, ignoring a slash inside an IPv6 bracket. */ +const authorityEnd = (value: string): number => { + let inBracket = false; + for (let index = 0; index < value.length; index += 1) { + const character = value[index]; + if (character === "[") inBracket = true; + else if (character === "]" && inBracket) inBracket = false; + else if (character === "/" && !inBracket) return index; + } + return value.length; +}; + +/** + * APT's deb822 Repo-URI host and port. Path octets stay as authored. An + * unclosed IPv6 bracket or a port that consumes the host drops the authority. + */ +const aptAuthorityUri = (uri: string): string => { + const scheme = SCHEME_AUTHORITY.exec(uri); + if (scheme === null) return uri; + const schemeText = scheme[1] ?? ""; + const rest = uri.slice(scheme[0].length); + const end = authorityEnd(rest); + const authority = rest.slice(0, end); + const path = rest.slice(end); + if (authority.length === 0) return `${schemeText}:${path}`; + + const at = authority.lastIndexOf("@"); + const userinfo = at === -1 ? "" : authority.slice(0, at + 1); + let host = at === -1 ? authority : authority.slice(at + 1); + let portEnd = 0; + let inBracket = false; + let index = 0; + while (index < host.length) { + const character = host[index]; + if (character === "[") { + inBracket = true; + host = `${host.slice(0, index)}${host.slice(index + 1)}`; + continue; + } + if (inBracket && character === "]") { + inBracket = false; + host = `${host.slice(0, index)}${host.slice(index + 1)}`; + portEnd = index; + continue; + } + index += 1; + } + if (inBracket) return `${schemeText}:${path}`; + + const colon = host.lastIndexOf(":"); + let port = 0; + if (colon !== -1 && colon >= portEnd) { + port = aptPort(host.slice(colon + 1)); + host = host.slice(0, colon); + } + if (host.length === 0) return `${schemeText}:${path}`; + const rendered = + host.includes(":") || host.includes("/") ? `[${host}]` : host; + const renderedPort = port === 0 ? "" : `:${String(port)}`; + return `${schemeText}://${userinfo}${rendered}${renderedPort}${path}`; +}; /** APT fixes up deb822 URIs before emitting Repo-URI, leaving path octets intact. */ const deb822RepoUri = (uri: string): string => - withTrailingSlash( - uri - .replace(EMPTY_AUTHORITY, "$1") - .replace(DECIMAL_PORT, (_match, authority: string, port: string) => { - const digits = port.replace(/^0+/u, ""); - return digits === "" ? authority : `${authority}:${digits}`; - }), - ); + withTrailingSlash(aptAuthorityUri(uri)); /** * The key block a deb822 Signed-By field holds, as apt writes it to a key From 7a0863c7f9a4ec8cab0d521c01a89e924344e1d7 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Thu, 19 Nov 2026 16:48:33 +0000 Subject: [PATCH 08/11] fix(desktop): accept GNU architecture names and bound port scans Keep x86_64 as an APT architecture token for $(ARCH) identity, and stop growing a port magnitude once it passes the signed 64-bit limit. Co-authored-by: morluto --- src/desktop/AptRepositoryInventory.test.ts | 42 ++++++++++++ src/desktop/AptRepositoryInventory.ts | 11 ++-- src/domain/desktop/aptRepositories.test.ts | 77 ++++++++++++++++++++++ src/domain/desktop/aptRepositories.ts | 28 ++++++-- 4 files changed, 148 insertions(+), 10 deletions(-) diff --git a/src/desktop/AptRepositoryInventory.test.ts b/src/desktop/AptRepositoryInventory.test.ts index 55794fc7ca0..121a6c8377e 100644 --- a/src/desktop/AptRepositoryInventory.test.ts +++ b/src/desktop/AptRepositoryInventory.test.ts @@ -598,6 +598,48 @@ describe.skipIf( }); }); + it.each([ + ["x86_64", "x86_64"], + ["amd64", "amd64"], + ["../etc", undefined], + ["x86_64/etc", undefined], + ] as const)( + "keeps APT architecture %s only when it is an architecture token", + async (configured, kept) => { + const root = await createTestTempDirectory("apt-config-arch-"); + const selected = { + lists: `${root}/lists/`, + trustedParts: `${root}/trusted/`, + trusted: `${root}/trusted.gpg`, + status: `${root}/status`, + }; + const configuredQuery: QueryRunner = (command, argv, signal) => + runHostQuery( + command, + [ + "-o", + `Dir::State::Lists=${selected.lists}`, + "-o", + `Dir::Etc::TrustedParts=${selected.trustedParts}`, + "-o", + `Dir::Etc::Trusted=${selected.trusted}`, + "-o", + `Dir::State::status=${selected.status}`, + "-o", + `APT::Architecture=${configured}`, + ...argv, + ], + signal, + ); + const locations = await resolveAptLocations(configuredQuery, undefined); + expect(locations).toEqual( + kept === undefined + ? selected + : { ...selected, configuredArchitecture: kept }, + ); + }, + ); + it("reads the lists folder an APT_CONFIG file names, resolved under Dir::State", async () => { const root = await createTestTempDirectory("apt-config-"); const config = join(root, "apt.conf"); diff --git a/src/desktop/AptRepositoryInventory.ts b/src/desktop/AptRepositoryInventory.ts index dc5e17bf2bd..f1095a54bf1 100644 --- a/src/desktop/AptRepositoryInventory.ts +++ b/src/desktop/AptRepositoryInventory.ts @@ -82,10 +82,13 @@ export const resolveAptLocations = async ( trustedParts: value("PARTS") ?? fallback.trustedParts, trusted: value("TRUSTED") ?? fallback.trusted, status: value("STATUS") ?? fallback.status ?? DEFAULT_DPKG_STATUS_SOURCE, - ...(architecture === undefined || - !/^[a-z0-9][a-z0-9-]*$/u.test(architecture) - ? {} - : { configuredArchitecture: architecture }), + // Debian architecture words use letters, digits, and hyphens. GNU CPU + // names such as x86_64 also use underscores. APT substitutes either form + // for $(ARCH). Dots, slashes, and whitespace are not architecture tokens. + ...(architecture !== undefined && + /^[a-z0-9][a-z0-9_-]*$/u.test(architecture) + ? { configuredArchitecture: architecture } + : {}), }; }; diff --git a/src/domain/desktop/aptRepositories.test.ts b/src/domain/desktop/aptRepositories.test.ts index 49644f3ab35..b036ee8b985 100644 --- a/src/domain/desktop/aptRepositories.test.ts +++ b/src/domain/desktop/aptRepositories.test.ts @@ -583,6 +583,83 @@ describe("single-stanza APT source identity", () => { ); }); +describe("APT architecture tokens and saturated ports", () => { + it("matches an x86_64 $(ARCH) template to APT's expanded URI and release", () => { + const uri = "https://vendor.invalid/archive/$(ARCH)"; + const suite = "stable/binary-$(ARCH)/"; + const stanzas = parseDeb822Sources( + `Types: deb\nURIs: ${uri}\nSuites: ${suite}\nComponents: main\n`, + deb822LookupFile, + ); + const repoUri = "https://vendor.invalid/archive/x86_64/"; + const release = "stable/binary-x86_64/"; + const transcript = [ + `Description: ${repoUri.slice(0, -1)} ${release} Packages`, + "Filename: /var/lib/apt/lists/vendor", + `Base-URI: ${repoUri}${release}`, + `Repo-URI: ${repoUri}`, + `Release: ${release}`, + `Sourcesentry: ${deb822LookupFile}:1`, + ].join("\n"); + const [target] = parseAptIndexTargets(transcript, "x86_64"); + if (target === undefined) throw new Error("Missing APT target"); + expect(entryForTarget(target, stanzas)).toEqual({ + file: deb822LookupFile, + position: 1, + uri, + credentials: false, + suite, + components: [], + architectures: [], + signedBy: [], + inlineKey: null, + }); + const [unconfigured] = parseAptIndexTargets(transcript); + if (unconfigured === undefined) throw new Error("Missing APT target"); + expect(entryForTarget(unconfigured, stanzas)).toBeUndefined(); + }); + + it.each([ + ["decimal", "80", "80"], + ["trailing junk", "80abc", "80"], + ["non-numeric", "https", ""], + ["leading zeros", "0080", "80"], + ["long leading zeros", `${"0".repeat(5000)}80`, "80"], + ["long positive", "9".repeat(5000), "4294967295"], + ["long negative", `-${"9".repeat(5000)}`, ""], + ["long positive sign and junk", `+${"9".repeat(5000)}abc`, "4294967295"], + ["signed maximum", "9223372036854775807", "4294967295"], + ["one past signed maximum", "9223372036854775808", "4294967295"], + ["signed minimum", "-9223372036854775808", ""], + ["one above signed minimum", "-9223372036854775807", "1"], + ["negative wrap", "-80", "4294967216"], + ] as const)( + "maps a %s port suffix to APT's unsigned port", + (_kind, suffix, port) => { + const authored = `https://vendor.invalid:${suffix}/archive`; + const repoUri = + port === "" + ? "https://vendor.invalid/archive/" + : `https://vendor.invalid:${port}/archive/`; + const stanzas = parseDeb822Sources( + `Types: deb\nURIs: ${authored}\nSuites: stable\nComponents: main\n`, + deb822LookupFile, + ); + expect(entryForTarget(targetFor(repoUri), stanzas)).toEqual({ + file: deb822LookupFile, + position: 1, + uri: authored, + credentials: false, + suite: "stable", + components: ["main"], + architectures: [], + signedBy: [], + inlineKey: null, + }); + }, + ); +}); + describe("APT source URI lookup", () => { it("matches APT's deb822 Repo-URI spellings without changing the source URI", () => { const stanzas = parseDeb822Sources( diff --git a/src/domain/desktop/aptRepositories.ts b/src/domain/desktop/aptRepositories.ts index 66f712e9b7e..39574d2010e 100644 --- a/src/domain/desktop/aptRepositories.ts +++ b/src/domain/desktop/aptRepositories.ts @@ -79,6 +79,8 @@ const withTrailingSlash = (uri: string): string => const SCHEME_AUTHORITY = /^([a-z][a-z0-9+.-]*):\/\//iu; const LONG_MAX = (1n << 63n) - 1n; const LONG_MIN = -(1n << 63n); +/** Largest magnitude strtol can return: LONG_MAX, or LONG_MIN's absolute value. */ +const PORT_MAGNITUDE_LIMIT = LONG_MAX + 1n; const isAsciiSpace = (character: string): boolean => character === " " || @@ -89,8 +91,9 @@ const isAsciiSpace = (character: string): boolean => character === "\r"; /** - * APT assigns `atoi(suffix)` to an unsigned 32-bit port. Trailing junk stops - * the conversion, and a zero result is omitted. + * APT assigns `atoi(suffix)` to an unsigned 32-bit port. The magnitude stops + * growing once it passes the signed 64-bit limit; further digits are skipped. + * Trailing junk ends the conversion, and a zero result is omitted. */ const aptPort = (suffix: string): number => { let index = 0; @@ -99,15 +102,28 @@ const aptPort = (suffix: string): number => { const negative = sign === "-"; if (sign === "+" || sign === "-") index += 1; let magnitude = 0n; + let overflow = false; while (index < suffix.length) { const code = suffix.charCodeAt(index); if (code < 48 || code > 57) break; - magnitude = magnitude * 10n + BigInt(code - 48); index += 1; + if (overflow) continue; + const digit = BigInt(code - 48); + if (magnitude > (PORT_MAGNITUDE_LIMIT - digit) / 10n) { + overflow = true; + continue; + } + magnitude = magnitude * 10n + digit; } - let value = negative ? -magnitude : magnitude; - if (value > LONG_MAX) value = LONG_MAX; - else if (value < LONG_MIN) value = LONG_MIN; + const value = overflow + ? negative + ? LONG_MIN + : LONG_MAX + : negative + ? -magnitude + : magnitude > LONG_MAX + ? LONG_MAX + : magnitude; return Number(BigInt.asUintN(32, BigInt.asIntN(32, value))); }; From 11f1d171b571994168ec7eff14be1121f50f7fef Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Thu, 19 Nov 2026 17:02:24 +0000 Subject: [PATCH 09/11] fix(desktop): keep file:// as APT's empty-path Repo-URI An empty host with no path stays scheme://, matching APT 2.8.3. A path after that host still drops it, so file:///srv remains file:/srv. Co-authored-by: morluto --- src/domain/desktop/aptRepositories.test.ts | 41 ++++++++++++++++++++++ src/domain/desktop/aptRepositories.ts | 5 ++- 2 files changed, 45 insertions(+), 1 deletion(-) diff --git a/src/domain/desktop/aptRepositories.test.ts b/src/domain/desktop/aptRepositories.test.ts index b036ee8b985..4ac66ae90d4 100644 --- a/src/domain/desktop/aptRepositories.test.ts +++ b/src/domain/desktop/aptRepositories.test.ts @@ -497,6 +497,8 @@ describe("single-stanza APT source identity", () => { "https://vendor.invalid/archive:80abc/x/", ], ["file://hostname:80abc/path", "file://hostname:80/path/"], + ["file://", "file://"], + ["file:///", "file:/"], ["file:///srv/a%20b", "file:/srv/a%20b/"], ])( "matches %s to the Repo-URI APT emits and keeps the authored URI", @@ -660,6 +662,45 @@ describe("APT architecture tokens and saturated ports", () => { ); }); +describe("empty-authority file URIs", () => { + it("accepts file:// when its Packages index is present and keeps the authored URI and suite", () => { + const uri = "file://"; + const suite = "stable"; + const stanzas = parseDeb822Sources( + `Types: deb\nURIs: ${uri}\nSuites: ${suite}\nComponents: main\n`, + deb822LookupFile, + ); + const transcript = [ + "Description: file:/ stable/main amd64 Packages", + "Filename: /var/lib/apt/lists/dists_stable_main_binary-amd64_Packages", + "Base-URI: file://dists/stable/", + "Repo-URI: file://", + "Release: stable", + "Component: main", + "Created-By: Packages", + `Sourcesentry: ${deb822LookupFile}:1`, + ].join("\n"); + const [target] = parseAptIndexTargets(transcript); + if (target === undefined) throw new Error("Missing APT target"); + expect(target).toMatchObject({ + repoUri: "file://", + release: "stable", + component: "main", + }); + expect(entryForTarget(target, stanzas)).toEqual({ + file: deb822LookupFile, + position: 1, + uri, + credentials: false, + suite, + components: ["main"], + architectures: [], + signedBy: [], + inlineKey: null, + }); + }); +}); + describe("APT source URI lookup", () => { it("matches APT's deb822 Repo-URI spellings without changing the source URI", () => { const stanzas = parseDeb822Sources( diff --git a/src/domain/desktop/aptRepositories.ts b/src/domain/desktop/aptRepositories.ts index 39574d2010e..c135126073b 100644 --- a/src/domain/desktop/aptRepositories.ts +++ b/src/domain/desktop/aptRepositories.ts @@ -151,7 +151,10 @@ const aptAuthorityUri = (uri: string): string => { const end = authorityEnd(rest); const authority = rest.slice(0, end); const path = rest.slice(end); - if (authority.length === 0) return `${schemeText}:${path}`; + // `file://` has no path, and APT keeps both slashes. A path after the + // empty host, as in `file:///srv`, drops that host. + if (authority.length === 0) + return path.length === 0 ? `${schemeText}://` : `${schemeText}:${path}`; const at = authority.lastIndexOf("@"); const userinfo = at === -1 ? "" : authority.slice(0, at + 1); From d3d54bb1e3c24ed33097e1e9e523d8402ab4a190 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Thu, 19 Nov 2026 18:44:16 +0000 Subject: [PATCH 10/11] fix(desktop): normalize APT scheme:host URIs in one host pass APT 2.8.3 rewrites http:127.0.0.1:18743/archive to an http:// Repo-URI. Identity comparison follows that form and keeps the authored URI. Bracket removal copies each host character once. Co-authored-by: morluto --- src/domain/desktop/aptRepositories.test.ts | 52 ++++++++++ src/domain/desktop/aptRepositories.ts | 107 +++++++++++++++------ 2 files changed, 127 insertions(+), 32 deletions(-) diff --git a/src/domain/desktop/aptRepositories.test.ts b/src/domain/desktop/aptRepositories.test.ts index 4ac66ae90d4..9b52d59cc3c 100644 --- a/src/domain/desktop/aptRepositories.test.ts +++ b/src/domain/desktop/aptRepositories.test.ts @@ -701,6 +701,58 @@ describe("empty-authority file URIs", () => { }); }); +describe("APT scheme:host shorthand", () => { + it.each([ + ["http:127.0.0.1:18743/archive", "http://127.0.0.1:18743/archive/"], + ["http:[::1]:18743/archive", "http://[::1]:18743/archive/"], + ["https:vendor.invalid:/archive", "https://vendor.invalid/archive/"], + ["copy:/srv/repo", "copy:/srv/repo/"], + ])( + "matches shorthand %s to APT's Repo-URI and keeps the authored URI", + (authored, repoUri) => { + const stanzas = parseDeb822Sources( + `Types: deb\nURIs: ${authored}\nSuites: stable\nComponents: main\n`, + deb822LookupFile, + ); + expect(entryForTarget(targetFor(repoUri), stanzas)).toEqual({ + file: deb822LookupFile, + position: 1, + uri: authored, + credentials: false, + suite: "stable", + components: ["main"], + architectures: [], + signedBy: [], + inlineKey: null, + }); + const untouched = authored.endsWith("/") ? authored : `${authored}/`; + if (untouched !== repoUri) + expect(entryForTarget(targetFor(untouched), stanzas)).toBeUndefined(); + }, + ); + + it("reads a long bracketed host in one pass and keeps the authored URI", () => { + const repeats = 16_384; + const authored = `https://${"[a]".repeat(repeats)}:18743/archive`; + const repoUri = `https://${"a".repeat(repeats)}:18743/archive/`; + const stanzas = parseDeb822Sources( + `Types: deb\nURIs: ${authored}\nSuites: stable\nComponents: main\n`, + deb822LookupFile, + ); + expect(entryForTarget(targetFor(repoUri), stanzas)).toEqual({ + file: deb822LookupFile, + position: 1, + uri: authored, + credentials: false, + suite: "stable", + components: ["main"], + architectures: [], + signedBy: [], + inlineKey: null, + }); + }); +}); + describe("APT source URI lookup", () => { it("matches APT's deb822 Repo-URI spellings without changing the source URI", () => { const stanzas = parseDeb822Sources( diff --git a/src/domain/desktop/aptRepositories.ts b/src/domain/desktop/aptRepositories.ts index c135126073b..28e80079063 100644 --- a/src/domain/desktop/aptRepositories.ts +++ b/src/domain/desktop/aptRepositories.ts @@ -76,7 +76,7 @@ export const withoutCredentialsIn = (text: string): string => const withTrailingSlash = (uri: string): string => uri.endsWith("/") ? uri : `${uri}/`; -const SCHEME_AUTHORITY = /^([a-z][a-z0-9+.-]*):\/\//iu; +const SCHEME_PREFIX = /^([a-z][a-z0-9+.-]*):/iu; const LONG_MAX = (1n << 63n) - 1n; const LONG_MIN = -(1n << 63n); /** Largest magnitude strtol can return: LONG_MAX, or LONG_MIN's absolute value. */ @@ -139,49 +139,70 @@ const authorityEnd = (value: string): number => { return value.length; }; +/** + * One pass over a host: copy every non-bracket character once, and remember + * the debracketed offset where a port suffix may begin. + */ +const debracketHost = ( + host: string, +): { + readonly text: string; + readonly portEnd: number; + readonly open: boolean; +} => { + const pieces: string[] = []; + let start = 0; + let length = 0; + let portEnd = 0; + let inBracket = false; + for (let index = 0; index < host.length; index += 1) { + const character = host[index]; + const opening = character === "["; + const closing = inBracket && character === "]"; + if (!opening && !closing) continue; + if (index > start) { + pieces.push(host.slice(start, index)); + length += index - start; + } + start = index + 1; + if (opening) inBracket = true; + else { + inBracket = false; + portEnd = length; + } + } + if (start < host.length) pieces.push(host.slice(start)); + return { text: pieces.join(""), portEnd, open: inBracket }; +}; + /** * APT's deb822 Repo-URI host and port. Path octets stay as authored. An * unclosed IPv6 bracket or a port that consumes the host drops the authority. + * `scheme:host/path` gains the slashes APT inserts; `scheme:/path` does not. */ -const aptAuthorityUri = (uri: string): string => { - const scheme = SCHEME_AUTHORITY.exec(uri); - if (scheme === null) return uri; - const schemeText = scheme[1] ?? ""; - const rest = uri.slice(scheme[0].length); - const end = authorityEnd(rest); - const authority = rest.slice(0, end); - const path = rest.slice(end); +const renderHostUri = ( + schemeText: string, + authority: string, + path: string, + sawSlashes: boolean, +): string => { // `file://` has no path, and APT keeps both slashes. A path after the // empty host, as in `file:///srv`, drops that host. if (authority.length === 0) - return path.length === 0 ? `${schemeText}://` : `${schemeText}:${path}`; + return sawSlashes && path.length === 0 + ? `${schemeText}://` + : `${schemeText}:${path}`; const at = authority.lastIndexOf("@"); const userinfo = at === -1 ? "" : authority.slice(0, at + 1); - let host = at === -1 ? authority : authority.slice(at + 1); - let portEnd = 0; - let inBracket = false; - let index = 0; - while (index < host.length) { - const character = host[index]; - if (character === "[") { - inBracket = true; - host = `${host.slice(0, index)}${host.slice(index + 1)}`; - continue; - } - if (inBracket && character === "]") { - inBracket = false; - host = `${host.slice(0, index)}${host.slice(index + 1)}`; - portEnd = index; - continue; - } - index += 1; - } - if (inBracket) return `${schemeText}:${path}`; - + const separated = debracketHost( + at === -1 ? authority : authority.slice(at + 1), + ); + if (separated.open) return `${schemeText}:${path}`; + let host = separated.text; const colon = host.lastIndexOf(":"); let port = 0; - if (colon !== -1 && colon >= portEnd) { + if (colon !== -1 && colon >= separated.portEnd) { port = aptPort(host.slice(colon + 1)); host = host.slice(0, colon); } @@ -192,6 +213,28 @@ const aptAuthorityUri = (uri: string): string => { return `${schemeText}://${userinfo}${rendered}${renderedPort}${path}`; }; +const aptAuthorityUri = (uri: string): string => { + const scheme = SCHEME_PREFIX.exec(uri); + if (scheme === null) return uri; + const schemeText = scheme[1] ?? ""; + const after = uri.slice(scheme[0].length); + if (after.startsWith("//")) { + const rest = after.slice(2); + const end = authorityEnd(rest); + return renderHostUri(schemeText, rest.slice(0, end), rest.slice(end), true); + } + // `copy:/srv` is a path. `http:127.0.0.1:18743/archive` is a host APT + // rewrites with `//`. + if (after.startsWith("/")) return `${schemeText}:${after}`; + const end = authorityEnd(after); + return renderHostUri( + schemeText, + after.slice(0, end), + after.slice(end), + false, + ); +}; + /** APT fixes up deb822 URIs before emitting Repo-URI, leaving path octets intact. */ const deb822RepoUri = (uri: string): string => withTrailingSlash(aptAuthorityUri(uri)); From 3a1cb5b34aa1a6cebe06bcfb5931c29724820668 Mon Sep 17 00:00:00 2001 From: morluto <76467478+morluto@users.noreply.github.com> Date: Thu, 19 Nov 2026 20:56:04 -0500 Subject: [PATCH 11/11] fix(desktop): replay the APT suite selected during capture --- .../vendor-packages/spec.md | 9 +- src/desktop/AptRepositoryInventory.test.ts | 43 ++++++++++ src/desktop/AptRepositoryInventory.ts | 6 ++ src/domain/desktop/appExportInstall.test.ts | 16 ++++ src/domain/desktop/appExportInstall.ts | 12 ++- src/domain/desktop/aptRepositories.test.ts | 13 ++- src/domain/desktop/aptRepositories.ts | 84 ++++++++++++++----- src/domain/desktop/desktopCapture.ts | 2 + 8 files changed, 144 insertions(+), 41 deletions(-) diff --git a/docs/specs/desktop-app-environments/vendor-packages/spec.md b/docs/specs/desktop-app-environments/vendor-packages/spec.md index b0a168f0f21..7a46c05f4d9 100644 --- a/docs/specs/desktop-app-environments/vendor-packages/spec.md +++ b/docs/specs/desktop-app-environments/vendor-packages/spec.md @@ -17,7 +17,9 @@ that key, with those libraries, and starts it. deb822 stanza; `sources.list`, one-line `*.list` or deb822 `*.sources`) with its authored URI, suite, components and architecture restriction. The optional `repo_uri` field records the index's sanitized `Repo-URI` independently of - the authored URI. Undecodable UTF-8 entries and index paragraphs are withheld + the authored URI. When APT selects a different suite, `repo_suite` + records the index's source suite separately from the authored value. + Undecodable UTF-8 entries and index paragraphs are withheld without substituting replacement characters. A policy query with undecodable bytes leaves repository attribution unknown. Flat repositories (suite `./` or `/`, no components), `[signed-by=…]` and `Signed-By:` options @@ -96,8 +98,9 @@ that key, with those libraries, and starts it. `uri` still holds them is refused whole, since its library packages counted that repository), it is reached over http or https, and its architecture restriction includes the host's. AgentEnv writes a deb822 source. The - exporter and package attribution use the same URI that reproduces the - observed index identity. A legacy one-line source with percent escapes + exporter and package attribution share the URI and concrete suite that + reproduce the observed index identity. A capture with a templated suite + needs `repo_suite` to replay it. A legacy one-line source with percent escapes needs a new capture with `repo_uri`. A URI that cannot be represented as one deb822 token is withheld with the reason. With none usable, the export is refused naming each repository, by its URI without credentials, and its reason; the diff --git a/src/desktop/AptRepositoryInventory.test.ts b/src/desktop/AptRepositoryInventory.test.ts index 121a6c8377e..7dc3d481568 100644 --- a/src/desktop/AptRepositoryInventory.test.ts +++ b/src/desktop/AptRepositoryInventory.test.ts @@ -207,6 +207,49 @@ it.each([ }, ); +it("records an expanded APT source suite separately from the authored suite", async () => { + const root = await createTestTempDirectory("apt-source-suite-"); + const file = join(root, "vendor.sources"); + const uri = "https://vendor.invalid/archive/"; + const suite = "stable/binary-$(ARCH)/"; + const repoSuite = "stable/binary-x86_64/"; + await writeFile( + file, + `Types: deb\nURIs: ${uri}\nSuites: ${suite} fallback/\n`, + ); + const source = `${uri.slice(0, -1)} ${repoSuite} Packages`; + const output = [ + `Description: ${source}`, + `Sourcesentry: ${file}:1`, + `Repo-URI: ${uri}`, + `Release: ${repoSuite}`, + `Base-URI: ${uri}${repoSuite}`, + `Filename: ${join(root, "Packages")}`, + ].join("\n"); + const runQuery: QueryRunner = async (command) => { + if (command !== "apt-get") throw new Error(`Unexpected query ${command}`); + return { stdout: output, exitCode: 0 }; + }; + const facts = await inspectAptRepositories( + { sources: [source], origins: ["Vendor"] }, + { + runQuery, + apt: { + lists: root, + trustedParts: root, + trusted: join(root, "trusted.gpg"), + configuredArchitecture: "x86_64", + }, + }, + undefined, + ); + expect(facts.repositories[0]).toMatchObject({ + suite, + repo_suite: repoSuite, + release: null, + }); +}); + it.each([ ["https://vendor.invalid:/archive", "https://vendor.invalid/archive/"], [ diff --git a/src/desktop/AptRepositoryInventory.ts b/src/desktop/AptRepositoryInventory.ts index f1095a54bf1..db68f1c520b 100644 --- a/src/desktop/AptRepositoryInventory.ts +++ b/src/desktop/AptRepositoryInventory.ts @@ -3,6 +3,7 @@ import { dirname, join } from "node:path"; import { aptListFileName, + aptIndexSourceSuite, entryForTarget, isUbuntuProRepository, parseAptConfigShell, @@ -295,6 +296,11 @@ const repositoryBase = ( uri_credentials_removed: entry?.credentials === true || target?.repoUriCredentialsRemoved === true, suite: entry?.suite ?? null, + ...(target === undefined || + entry === undefined || + entry.suite === aptIndexSourceSuite(target) + ? {} + : { repo_suite: aptIndexSourceSuite(target) }), components: [...(entry?.components ?? [])], architectures: [...(entry?.architectures ?? [])], release: target?.suite ?? target?.codename ?? null, diff --git a/src/domain/desktop/appExportInstall.test.ts b/src/domain/desktop/appExportInstall.test.ts index c4e1da0d09d..e9ddb0e2b95 100644 --- a/src/domain/desktop/appExportInstall.test.ts +++ b/src/domain/desktop/appExportInstall.test.ts @@ -57,6 +57,22 @@ const typora = ( unpackaged_libraries: [], }); +it("replays the observed suite of a repository whose authored suite is templated", () => { + const authored = repository({ + sources_file: "/etc/apt/sources.list.d/vendor.sources", + suite: "stable/binary-$(ARCH)/", + repo_suite: "stable/binary-x86_64/", + }); + const install = exportInstall(typora([authored]), "typora", "x64"); + + expect(install.ok && install.value.sources[0]?.suite).toBe( + "stable/binary-x86_64/", + ); + expect(repositoryRefusal({ ...authored, repo_suite: undefined })).toContain( + "Capture the application again", + ); +}); + describe("exportInstall", () => { it("installs from a vendor repository whose key the capture verified", () => { const install = exportInstall(typora([repository()]), "typora", "arm64"); diff --git a/src/domain/desktop/appExportInstall.ts b/src/domain/desktop/appExportInstall.ts index 091262feb59..754632b3e1e 100644 --- a/src/domain/desktop/appExportInstall.ts +++ b/src/domain/desktop/appExportInstall.ts @@ -2,7 +2,7 @@ import { err, ok, type Result } from "../result.js"; import type { DownloadInstall } from "./appDownloadInstall.js"; import { aptRepositoryHoldsCredentials, - aptRepositoryReplayUri, + aptRepositoryReplay, withoutCredentials, withoutCredentialsIn, } from "./aptRepositories.js"; @@ -129,15 +129,13 @@ const describe = (repository: AptRepository): string => /** Check the source, key, and replay spelling at the export boundary. */ const repositoryReplay = (repository: AptRepository) => { - const replay = aptRepositoryReplayUri(repository); + const replay = aptRepositoryReplay(repository); if (!replay.ok && replay.error.kind === "credentials") return err(replay.error.reason); if (repository.signing_key === null) return err( repository.signing_key_reason ?? "its signing key was not verified", ); - if (repository.suite === null) - return err("no apt sources entry configures it"); return replay.ok ? replay : err(replay.error.reason); }; @@ -179,16 +177,16 @@ const declaredSources = ( const refused: string[] = []; const kept: AptRepository[] = []; for (const repository of repositories) { - const { suite, components, signing_key: key } = repository; + const { components, signing_key: key } = repository; const replay = repositoryReplay(repository); const reason = replay.ok ? architectureRefusal(repository, architecture) : replay.error; - if (!replay.ok || reason !== undefined || key === null || suite === null) { + if (!replay.ok || reason !== undefined || key === null) { refused.push(`${describe(repository)}: ${reason ?? "it is unusable"}`); continue; } - const { uri, repoUri } = replay.value; + const { uri, repoUri, suite } = replay.value; const id = `${repoUri}\n${suite}`; const existing = declared.get(id); if (existing !== undefined && existing.keySha256 !== key.sha256) { diff --git a/src/domain/desktop/aptRepositories.test.ts b/src/domain/desktop/aptRepositories.test.ts index 9b52d59cc3c..56bbf21fd3e 100644 --- a/src/domain/desktop/aptRepositories.test.ts +++ b/src/domain/desktop/aptRepositories.test.ts @@ -561,6 +561,7 @@ describe("single-stanza APT source identity", () => { sources_file: deb822LookupFile, uri_credentials_removed: false, suite, + ...(field === "suite" ? { repo_suite: "unstable/binary-amd64/" } : {}), components: [], }; for (const architecture of ["amd64", "arm64", undefined]) { @@ -571,15 +572,11 @@ describe("single-stanza APT source identity", () => { [repository], new Map([[description, target]]), ); - if (architecture === "amd64") { + if (architecture === "amd64") expect(entry).toMatchObject({ uri, suite, components: [] }); - expect(files).toEqual(new Set([description])); - } else { - expect(entry).toBeUndefined(); - // A historical capture can replay an already materialized Repo-URI. - // The authored suite has no separate expanded value in that contract. - expect(files).toEqual(new Set(field === "URI" ? [description] : [])); - } + else expect(entry).toBeUndefined(); + // Recorded replay facts need no second expansion against host settings. + expect(files).toEqual(new Set([description])); } }, ); diff --git a/src/domain/desktop/aptRepositories.ts b/src/domain/desktop/aptRepositories.ts index 28e80079063..dd77ab1c1c2 100644 --- a/src/domain/desktop/aptRepositories.ts +++ b/src/domain/desktop/aptRepositories.ts @@ -267,13 +267,14 @@ const expandAptArchitecture = ( : value.replaceAll(variable, architecture); }; +/** The source suite as selected by APT, including the flat suite `/`. */ +export const aptIndexSourceSuite = (target: AptIndexTarget): string => + target.release || "/"; + /** Match the selected release without changing an authored suite. */ -const isRelease = (suite: string, target: AptIndexTarget): boolean => { - const selected = expandAptArchitecture(suite, target.configuredArchitecture); - return ( - selected === target.release || (selected === "/" && target.release === "") - ); -}; +const isRelease = (suite: string, target: AptIndexTarget): boolean => + expandAptArchitecture(suite, target.configuredArchitecture) === + aptIndexSourceSuite(target); const stanza = ( at: { readonly file: string; readonly position: number }, @@ -545,21 +546,24 @@ export const entryForTarget = ( }; }; -type ReplayRepository = Pick< +type ReplayUriRepository = Pick< AptRepository, "uri" | "repo_uri" | "uri_credentials_removed" > & Partial>; -type RepositoryDeclaration = ReplayRepository & - Pick; +type ReplayRepository = ReplayUriRepository & + Pick; -const oneLineSource = (repository: ReplayRepository): boolean => +type RepositoryDeclaration = ReplayRepository & + Pick; + +const oneLineSource = (repository: ReplayUriRepository): boolean => repository.sources_file?.endsWith(".sources") !== true; /** Detect credentials left in a legacy or externally supplied capture. */ export const aptRepositoryHoldsCredentials = ( - repository: ReplayRepository, + repository: ReplayUriRepository, ): boolean => { const { uri, repo_uri } = repository; return ( @@ -571,17 +575,19 @@ export const aptRepositoryHoldsCredentials = ( }; type AptReplayRefusal = { - readonly kind: "credentials" | "uri"; + readonly kind: "credentials" | "uri" | "suite"; readonly reason: string; }; const httpSourceUri = (uri: string): boolean => /^https?:\/\/[^/]+/u.test(uri); -const isDeb822UriToken = (uri: string): boolean => - !/[\s\p{Cc}]/u.test(uri) && !uri.includes("$(ARCH)"); +const isDeb822ReplayToken = (value: string): boolean => + value.length !== 0 && + !/[\s\p{Cc}]/u.test(value) && + !value.includes("$(ARCH)"); /** Admit one AgentEnv deb822 URI and the APT Repo-URI it reproduces. */ -export const aptRepositoryReplayUri = ( - repository: ReplayRepository, +const replayUri = ( + repository: ReplayUriRepository, ): Result< { readonly uri: string; readonly repoUri: string }, AptReplayRefusal @@ -624,10 +630,13 @@ export const aptRepositoryReplayUri = ( const repoUri = observed ?? deb822RepoUri(uri); const declaration = - deb822RepoUri(uri) === repoUri && isDeb822UriToken(uri) + deb822RepoUri(uri) === repoUri && isDeb822ReplayToken(uri) ? uri : withoutOptionalTrailingSlash(repoUri); - if (!isDeb822UriToken(declaration) || deb822RepoUri(declaration) !== repoUri) + if ( + !isDeb822ReplayToken(declaration) || + deb822RepoUri(declaration) !== repoUri + ) return err({ kind: "uri", reason: @@ -636,6 +645,34 @@ export const aptRepositoryReplayUri = ( return ok({ uri: declaration, repoUri }); }; +/** The concrete deb822 URI and suite that reproduce the captured source index. */ +export const aptRepositoryReplay = ( + repository: ReplayRepository, +): Result< + { readonly uri: string; readonly repoUri: string; readonly suite: string }, + AptReplayRefusal +> => { + const uri = replayUri(repository); + if (!uri.ok) return uri; + const authored = repository.suite; + if (authored === null) + return err({ kind: "suite", reason: "no apt sources entry configures it" }); + if (repository.repo_suite === undefined && authored.includes("$(ARCH)")) + return err({ + kind: "suite", + reason: + "its sources entry templates the suite and the capture does not record apt's selected suite. Capture the application again", + }); + const suite = repository.repo_suite ?? authored; + if (!isDeb822ReplayToken(suite)) + return err({ + kind: "suite", + reason: + "apt's selected suite cannot be represented as one AgentEnv deb822 suite token", + }); + return ok({ ...uri.value, suite }); +}; + /** * The package files, as `apt-cache policy` prints them, that apt reads once * these repositories are declared: every index of the same URI and suite in @@ -648,16 +685,17 @@ export const declaredPackageFiles = ( ): ReadonlySet => { const declarations = repositories.flatMap((repository) => { const observed = targets.get(repository.source); - const replay = aptRepositoryReplayUri(repository); + const replay = aptRepositoryReplay(repository); return !replay.ok || - observed?.repoUri !== replay.value.repoUri || - repository.suite === null + observed === undefined || + observed.repoUri !== replay.value.repoUri || + aptIndexSourceSuite(observed) !== replay.value.suite ? [] : [ { ...repository, repoUri: replay.value.repoUri, - suite: repository.suite, + suite: replay.value.suite, }, ]; }); @@ -667,7 +705,7 @@ export const declaredPackageFiles = ( declarations.some( ({ repoUri, suite, components }) => repoUri === target.repoUri && - isRelease(suite, target) && + suite === aptIndexSourceSuite(target) && (target.component === null ? components.length === 0 : components.includes(target.component)), diff --git a/src/domain/desktop/desktopCapture.ts b/src/domain/desktop/desktopCapture.ts index 0ece431d37b..f5f697b8bce 100644 --- a/src/domain/desktop/desktopCapture.ts +++ b/src/domain/desktop/desktopCapture.ts @@ -198,6 +198,8 @@ const aptRepositorySchema = z.strictObject({ /** Whether the entry or index URI held credentials, which REA does not record. */ uri_credentials_removed: z.boolean().optional(), suite: z.string().nullable(), + /** The index's selected source suite, recorded when it differs from the authored suite. */ + repo_suite: z.string().min(1).optional(), /** Empty for a flat repository. */ components: z.array(z.string()), /** The entry's architecture restriction; empty when it names none, absent from captures written before it was recorded. */