mirror of
https://github.com/morluto/rea.git
synced 2026-12-02 11:33:10 +00:00
chore(desktop): stage the APT single-stanza dependency for review
This commit is contained in:
commit
0ec334abea
8 files changed
+843
-97
No files matched your search
@@ -17,12 +17,17 @@ 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
|
||||
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 `$(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,
|
||||
is removed from every sources entry, from `apt-get indextargets`'
|
||||
@@ -93,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
|
||||
|
||||
@@ -221,6 +221,124 @@ 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/"],
|
||||
[
|
||||
"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).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-");
|
||||
const file = join(root, "vendor.list");
|
||||
@@ -525,19 +643,66 @@ 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.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");
|
||||
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);
|
||||
@@ -549,6 +714,7 @@ describe.skipIf(
|
||||
trustedParts: "/etc/apt/trusted.gpg.d/",
|
||||
trusted: "/etc/apt/trusted.gpg",
|
||||
status: "/var/lib/dpkg/status",
|
||||
configuredArchitecture: "amd64",
|
||||
});
|
||||
expect(
|
||||
await resolveAptLocations(
|
||||
|
||||
@@ -3,6 +3,7 @@ import { dirname, join } from "node:path";
|
||||
|
||||
import {
|
||||
aptListFileName,
|
||||
aptIndexSourceSuite,
|
||||
entryForTarget,
|
||||
isUbuntuProRepository,
|
||||
parseAptConfigShell,
|
||||
@@ -22,15 +23,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 +47,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<AptLocations> => {
|
||||
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 +83,13 @@ export const resolveAptLocations = async (
|
||||
trustedParts: value("PARTS") ?? fallback.trustedParts,
|
||||
trusted: value("TRUSTED") ?? fallback.trusted,
|
||||
status: value("STATUS") ?? fallback.status ?? DEFAULT_DPKG_STATUS_SOURCE,
|
||||
// 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 }
|
||||
: {}),
|
||||
};
|
||||
};
|
||||
|
||||
@@ -105,6 +117,7 @@ const UBUNTU_PRO =
|
||||
const indexTargets = async (
|
||||
runQuery: QueryRunner,
|
||||
signal: AbortSignal | undefined,
|
||||
configuredArchitecture?: string,
|
||||
): Promise<
|
||||
| {
|
||||
readonly entries: ReadonlyMap<string, AptIndexTarget>;
|
||||
@@ -121,7 +134,7 @@ const indexTargets = async (
|
||||
if (typeof query !== "object" || query.exitCode !== 0) return undefined;
|
||||
const output = query.stdoutBuffer ?? query.stdout;
|
||||
const targets = new Map<string, AptIndexTarget>();
|
||||
for (const target of parseAptIndexTargets(output))
|
||||
for (const target of parseAptIndexTargets(output, configuredArchitecture))
|
||||
if (!targets.has(target.description))
|
||||
targets.set(target.description, target);
|
||||
return {
|
||||
@@ -283,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,
|
||||
@@ -343,7 +361,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 = {
|
||||
|
||||
@@ -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");
|
||||
|
||||
@@ -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);
|
||||
};
|
||||
|
||||
@@ -183,16 +181,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, packageArchitecture)
|
||||
: 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) {
|
||||
|
||||
@@ -142,6 +142,7 @@ describe("parseOneLineSources", () => {
|
||||
{
|
||||
file: TYPORA_LIST,
|
||||
position: 1,
|
||||
format: "one-line",
|
||||
uris: [
|
||||
{ uri: "https://downloads.typora.io/linux", credentials: false },
|
||||
],
|
||||
@@ -443,42 +444,360 @@ 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",
|
||||
deb822LookupFile,
|
||||
);
|
||||
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.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://", "file://"],
|
||||
["file:///", "file:/"],
|
||||
["file:///srv/a%20b", "file:/srv/a%20b/"],
|
||||
])(
|
||||
"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,
|
||||
);
|
||||
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.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,
|
||||
);
|
||||
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,
|
||||
...(field === "suite" ? { repo_suite: "unstable/binary-amd64/" } : {}),
|
||||
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: [] });
|
||||
else expect(entry).toBeUndefined();
|
||||
// Recorded replay facts need no second expansion against host settings.
|
||||
expect(files).toEqual(new Set([description]));
|
||||
}
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
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("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 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(
|
||||
[
|
||||
"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"),
|
||||
file,
|
||||
deb822LookupFile,
|
||||
);
|
||||
|
||||
// Repo-URI values from apt-get indextargets --no-release-info (APT 3.2.0).
|
||||
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",
|
||||
@@ -511,7 +830,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),
|
||||
@@ -526,7 +845,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(
|
||||
@@ -544,7 +863,7 @@ describe("APT source URI lookup", () => {
|
||||
"Suites: stable",
|
||||
"Components: main",
|
||||
].join("\n"),
|
||||
file,
|
||||
deb822LookupFile,
|
||||
);
|
||||
|
||||
expect(
|
||||
|
||||
@@ -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. */
|
||||
@@ -88,20 +89,168 @@ export const withoutCredentialsIn = (text: string): string =>
|
||||
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 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. */
|
||||
const PORT_MAGNITUDE_LIMIT = LONG_MAX + 1n;
|
||||
|
||||
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. 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;
|
||||
while (index < suffix.length && isAsciiSpace(suffix[index] ?? "")) index += 1;
|
||||
const sign = suffix[index];
|
||||
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;
|
||||
index += 1;
|
||||
if (overflow) continue;
|
||||
const digit = BigInt(code - 48);
|
||||
if (magnitude > (PORT_MAGNITUDE_LIMIT - digit) / 10n) {
|
||||
overflow = true;
|
||||
continue;
|
||||
}
|
||||
magnitude = magnitude * 10n + digit;
|
||||
}
|
||||
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)));
|
||||
};
|
||||
|
||||
/** 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;
|
||||
};
|
||||
|
||||
/**
|
||||
* 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 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 sawSlashes && path.length === 0
|
||||
? `${schemeText}://`
|
||||
: `${schemeText}:${path}`;
|
||||
|
||||
const at = authority.lastIndexOf("@");
|
||||
const userinfo = at === -1 ? "" : authority.slice(0, at + 1);
|
||||
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 >= separated.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}`;
|
||||
};
|
||||
|
||||
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(
|
||||
uri
|
||||
.replace(EMPTY_AUTHORITY, "$1")
|
||||
.replace(NUMERIC_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
|
||||
@@ -119,9 +268,26 @@ 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 === "");
|
||||
/** 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);
|
||||
};
|
||||
|
||||
/** 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 =>
|
||||
expandAptArchitecture(suite, target.configuredArchitecture) ===
|
||||
aptIndexSourceSuite(target);
|
||||
|
||||
const stanza = (
|
||||
at: { readonly file: string; readonly position: number },
|
||||
@@ -137,6 +303,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)
|
||||
@@ -321,8 +488,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. */
|
||||
@@ -340,6 +509,7 @@ const SOURCES_ENTRY = /^(?<file>\/.*):(?<position>[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;
|
||||
@@ -368,6 +538,9 @@ export const parseAptIndexTargets = (
|
||||
? {}
|
||||
: { repoUriCredentialsRemoved: true as const }),
|
||||
release: fields.get("release") ?? "",
|
||||
...(configuredArchitecture === undefined
|
||||
? {}
|
||||
: { configuredArchitecture }),
|
||||
component: optional("component"),
|
||||
baseUri: withoutCredentials(baseUri),
|
||||
filename,
|
||||
@@ -392,21 +565,28 @@ export const entryForTarget = (
|
||||
candidate.position === target.position,
|
||||
);
|
||||
if (at === undefined) return undefined;
|
||||
const { uris, suites, ...entry } = at;
|
||||
const single = 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
|
||||
: 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 =
|
||||
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 }) =>
|
||||
@@ -425,21 +605,24 @@ export const entryForTarget = (
|
||||
};
|
||||
};
|
||||
|
||||
type ReplayRepository = Pick<
|
||||
type ReplayUriRepository = Pick<
|
||||
AptRepository,
|
||||
"uri" | "repo_uri" | "uri_credentials_removed"
|
||||
> &
|
||||
Partial<Pick<AptRepository, "sources_file">>;
|
||||
|
||||
type RepositoryDeclaration = ReplayRepository &
|
||||
Pick<AptRepository, "source" | "suite" | "components">;
|
||||
type ReplayRepository = ReplayUriRepository &
|
||||
Pick<AptRepository, "suite" | "repo_suite">;
|
||||
|
||||
const oneLineSource = (repository: ReplayRepository): boolean =>
|
||||
type RepositoryDeclaration = ReplayRepository &
|
||||
Pick<AptRepository, "source" | "components">;
|
||||
|
||||
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 (
|
||||
@@ -451,17 +634,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
|
||||
@@ -504,10 +689,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:
|
||||
@@ -516,6 +704,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
|
||||
@@ -528,16 +744,17 @@ export const declaredPackageFiles = (
|
||||
): ReadonlySet<string> => {
|
||||
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,
|
||||
},
|
||||
];
|
||||
});
|
||||
@@ -547,7 +764,7 @@ export const declaredPackageFiles = (
|
||||
declarations.some(
|
||||
({ repoUri, suite, components }) =>
|
||||
repoUri === target.repoUri &&
|
||||
isRelease(suite, target.release) &&
|
||||
suite === aptIndexSourceSuite(target) &&
|
||||
(target.component === null
|
||||
? components.length === 0
|
||||
: components.includes(target.component)),
|
||||
|
||||
@@ -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. `all` allows architecture-independent packages. An empty list depends on the host's APT defaults. Older captures omit this field. */
|
||||
|
||||
Reference in new issue
Block a user