A full-featured download manager.
fix(release): validate snap scope and allow larger source headers (#2411)
Dr_rOot87e1d2ae304f
diff --git a/.github/workflows/flatpak.yml b/.github/workflows/flatpak.ymlindex efee1a24..4d8f2e4b 100644--- a/.github/workflows/flatpak.yml+++ b/.github/workflows/flatpak.yml@@ -174,11 +174,18 @@ jobs:--output "$RUNNER_TEMP/flatpak-cargo-generator.py" \"https://raw.githubusercontent.com/flatpak/flatpak-builder-tools/$FLATPAK_BUILDER_TOOLS_COMMIT/cargo/flatpak-cargo-generator.py"+ - name: Verify Flatpak source response header limits+ run: >-+ "$RUNNER_TEMP/flatpak-builder-tools/bin/python"+ -B+ tests/scripts/test_flatpak_node_generator.py+- name: Generate Flatpak npm sourcesrun: |node scripts/prepare-flatpak-node-lock.mjs \pnpm-lock.yaml "$RUNNER_TEMP/flatpak-node-lock.yaml"- "$RUNNER_TEMP/flatpak-builder-tools/bin/flatpak-node-generator" \+ "$RUNNER_TEMP/flatpak-builder-tools/bin/python" \+ -B scripts/run_flatpak_node_generator.py \pnpm "$RUNNER_TEMP/flatpak-node-lock.yaml" \--pnpm-store-version v11 \--electron-node-headers \diff --git a/.github/workflows/snap-promote.yml b/.github/workflows/snap-promote.ymlindex ba5c8ee9..f1eef76c 100644--- a/.github/workflows/snap-promote.yml+++ b/.github/workflows/snap-promote.yml@@ -223,13 +223,16 @@ jobs:env:SNAPCRAFT_STORE_CREDENTIALS: ${{ secrets.SNAPCRAFT_STORE_CREDENTIALS }}PROMOTION_TARGET: ${{ inputs.target }}+ TARGET_CHANNEL: ${{ needs.preflight.outputs.target_channel }}run: |set -euo pipefailif [[ -z "${SNAPCRAFT_STORE_CREDENTIALS:-}" ]]; thenecho "Missing snap-store-${PROMOTION_TARGET} credential" >&2exit 1fi- snapcraft whoami+ python3 scripts/verify_snap_credential_scope.py \+ --snapcraft /snap/bin/snapcraft \+ --channel "$TARGET_CHANNEL"snapcraft status motrix- name: Reverify approved source revisionsdiff --git a/scripts/run_flatpak_node_generator.py b/scripts/run_flatpak_node_generator.pynew file mode 100644index 00000000..29991d05--- /dev/null+++ b/scripts/run_flatpak_node_generator.py@@ -0,0 +1,34 @@+#!/usr/bin/env python3+"""Run the pinned generator with a bounded limit for GitHub response headers."""++import contextlib+from collections.abc import AsyncIterator++import aiohttp+from flatpak_node_generator.main import main as generator_main+from flatpak_node_generator.requests import Requests+++MAX_HEADER_FIELD_SIZE = 65536+++class HeaderLimitedRequests(Requests):+ """Keep upstream fetching behavior while accepting larger CSP headers."""++ @contextlib.asynccontextmanager+ async def _open_stream(self, url: str) -> AsyncIterator[aiohttp.StreamReader]:+ # Match the pinned Requests._open_stream; change only this parser limit.+ # TLS validation, status errors, redirects, retries and caching remain+ # with aiohttp and the upstream Requests implementation.+ async with (+ aiohttp.ClientSession(+ raise_for_status=True, max_field_size=MAX_HEADER_FIELD_SIZE+ ) as session,+ session.get(url) as response,+ ):+ yield response.content+++if __name__ == "__main__":+ Requests.instance = HeaderLimitedRequests()+ generator_main()diff --git a/scripts/verify_snap_credential_scope.py b/scripts/verify_snap_credential_scope.pynew file mode 100644index 00000000..ae8990e0--- /dev/null+++ b/scripts/verify_snap_credential_scope.py@@ -0,0 +1,120 @@+#!/usr/bin/env python3+"""Verify Snapcraft's reported credential scope without accessing the credential.++Snapcraft 9 emits six plain mapping fields, with comma-separated permissions and+channels or the literal "no restrictions". Parse that complete record, including+indented plain-scalar continuations, rather than searching arbitrary log text.+Source: https://github.com/canonical/snapcraft/blob/9.1.3/snapcraft/commands/account.py+"""++import argparse+import fnmatch+import re+import subprocess+import sys+++FIELDS = {"email", "username", "id", "permissions", "channels", "expires"}+SCOPES = {"permissions", "channels"}+++class ScopeError(ValueError):+ """A credential's release scope could not be established."""+++def parse_whoami(output: str) -> dict[str, str]:+ if len(output) > 65536 or any(+ ord(character) < 32 and character not in "\r\n" for character in output+ ):+ raise ScopeError("Snapcraft whoami returned an invalid record")+ fields: dict[str, str] = {}+ previous = None+ for line in output.strip().splitlines():+ if line.startswith(" "):+ continuation = line.strip()+ if previous not in SCOPES or not continuation or ":" in continuation:+ raise ScopeError("Snapcraft whoami returned an ambiguous continuation")+ fields[previous] += " " + continuation+ continue+ match = re.fullmatch(r"([a-z]+):(?: (.*))?", line)+ if not match:+ raise ScopeError("Snapcraft whoami returned an invalid record")+ key, value = match.groups()+ if key not in FIELDS or key in fields:+ raise ScopeError("Snapcraft whoami returned unknown or duplicate fields")+ fields[key] = value or ""+ previous = key+ if fields.keys() != FIELDS:+ raise ScopeError("Snapcraft whoami is missing required fields")+ return fields+++def scope_items(value: str) -> list[str] | None:+ if value == "no restrictions":+ return None+ items = [item.strip() for item in value.split(",")]+ if not items or any(+ not item or any(character.isspace() for character in item) for item in items+ ):+ raise ScopeError("Snapcraft whoami returned an invalid scope list")+ return items+++def verify_scope(output: str, channel: str) -> None:+ match = re.fullmatch(+ r"([A-Za-z0-9][A-Za-z0-9._-]*)/(stable|candidate|beta|edge)", channel+ )+ if not match:+ raise ScopeError("Expected a track/risk target channel")+ track, risk = match.groups()+ # Match the exact channel argument sent by release-snap-build-set.mjs.+ release_channel = risk if track == "latest" else channel+ fields = parse_whoami(output)+ permissions = scope_items(fields["permissions"])+ channels = scope_items(fields["channels"])+ # Snap Store documents package_upload as including package_release.+ # https://dashboard.snapcraft.io/docs/reference/v1/macaroon.html+ if permissions is not None and not {"package_release", "package_upload"}.intersection(+ permissions+ ):+ raise ScopeError("Snap credential does not permit releasing existing revisions")+ # Store channel restrictions use Python fnmatch against the release request.+ # https://dashboard.snapcraft.io/docs/reference/v1/snap.html+ if channels is not None and not any(+ fnmatch.fnmatchcase(release_channel, pattern) for pattern in channels+ ):+ raise ScopeError(f"Snap credential does not permit release to {channel}")+++def main() -> None:+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--snapcraft", default="/snap/bin/snapcraft")+ parser.add_argument("--channel", required=True)+ options = parser.parse_args()+ try:+ result = subprocess.run(+ [options.snapcraft, "whoami", "--verbosity", "brief"],+ capture_output=True,+ text=True,+ check=False,+ timeout=120,+ )+ except (OSError, subprocess.TimeoutExpired, UnicodeError):+ raise ScopeError(+ "Snapcraft whoami failed; credential scope was not verified"+ ) from None+ if result.returncode != 0 or result.stderr.strip():+ raise ScopeError(+ "Snapcraft whoami failed or emitted diagnostics; "+ "credential scope was not verified"+ )+ verify_scope(result.stdout, options.channel)+ print(f"Verified Snap credential permits release to {options.channel}")+++if __name__ == "__main__":+ try:+ main()+ except ScopeError as error:+ print(str(error), file=sys.stderr)+ sys.exit(1)diff --git a/tests/scripts/test_flatpak_node_generator.py b/tests/scripts/test_flatpak_node_generator.pynew file mode 100644index 00000000..969d1d20--- /dev/null+++ b/tests/scripts/test_flatpak_node_generator.py@@ -0,0 +1,102 @@+"""Exercise the real pinned HTTP client against local response-header fixtures."""++import hashlib+import sys+import tempfile+import threading+import unittest+from collections import Counter+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer+from pathlib import Path++import aiohttp+from flatpak_node_generator.cache import Cache, FilesystemBasedCache+from flatpak_node_generator.requests import Requests++sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "scripts"))+from run_flatpak_node_generator import HeaderLimitedRequests, MAX_HEADER_FIELD_SIZE+++BODY = b"unchanged locked source bytes\x00\xff\n"+REQUESTS = Counter()+++class HeaderFixture(BaseHTTPRequestHandler):+ def do_GET(self):+ REQUESTS[self.path] += 1+ if self.path == "/retry" and REQUESTS[self.path] == 1:+ self.send_response(503)+ self.end_headers()+ return+ self.send_response(302 if self.path == "/redirect" else 200)+ size = MAX_HEADER_FIELD_SIZE + 1 if self.path == "/oversized" else 10000+ self.send_header("Content-Security-Policy", "x" * size)+ if self.path == "/redirect":+ self.send_header("Location", "/payload")+ self.end_headers()+ return+ self.send_header("Content-Length", str(len(BODY)))+ self.end_headers()+ try:+ self.wfile.write(BODY)+ except (BrokenPipeError, ConnectionResetError):+ pass # Expected when the client rejects a response header.++ def log_message(self, *_args):+ pass+++class HeaderLimitTests(unittest.IsolatedAsyncioTestCase):+ @classmethod+ def setUpClass(cls):+ cls.server = ThreadingHTTPServer(("127.0.0.1", 0), HeaderFixture)+ cls.thread = threading.Thread(target=cls.server.serve_forever, daemon=True)+ cls.thread.start()+ cls.base_url = f"http://127.0.0.1:{cls.server.server_port}"++ @classmethod+ def tearDownClass(cls):+ cls.server.shutdown()+ cls.server.server_close()+ cls.thread.join()++ def setUp(self):+ REQUESTS.clear()+ self.previous_retries = Requests.retries+ self.previous_cache = Cache.instance+ self.cache = tempfile.TemporaryDirectory()+ Requests.retries = 2+ Cache.instance = FilesystemBasedCache(Path(self.cache.name))++ def tearDown(self):+ Requests.retries = self.previous_retries+ Cache.instance = self.previous_cache+ self.cache.cleanup()++ async def test_fixture_exceeds_the_unmodified_client_limit(self):+ with self.assertRaises(aiohttp.ClientResponseError):+ await Requests().read_all(f"{self.base_url}/payload")++ async def test_larger_redirect_and_payload_headers_preserve_source_bytes(self):+ body = await HeaderLimitedRequests().read_all(f"{self.base_url}/redirect")+ self.assertEqual(body, BODY)+ self.assertEqual(hashlib.sha256(body).digest(), hashlib.sha256(BODY).digest())+ self.assertEqual(REQUESTS, {"/redirect": 1, "/payload": 1})++ async def test_headers_above_the_bound_still_fail_after_upstream_retries(self):+ with self.assertRaises(aiohttp.ClientResponseError):+ await HeaderLimitedRequests().read_all(f"{self.base_url}/oversized")+ self.assertEqual(REQUESTS["/oversized"], 2)++ async def test_status_retries_and_source_cache_remain_active(self):+ client = HeaderLimitedRequests()+ url = f"{self.base_url}/retry"+ self.assertEqual(await client.read_all(url, cachable=True), BODY)+ self.assertEqual(REQUESTS["/retry"], 2)+ with Cache.instance.get(f"requests:{url}").open_read() as cached:+ self.assertEqual(cached.read_all(), BODY)+ self.assertEqual(REQUESTS["/retry"], 2)+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/scripts/workflow-snap.test.ts b/tests/scripts/workflow-snap.test.tsindex cadebf82..18204155 100644--- a/tests/scripts/workflow-snap.test.ts+++ b/tests/scripts/workflow-snap.test.ts@@ -506,6 +506,33 @@ describe('Snap build workflow contract', () => {})describe('Snap promotion workflow contract', () => {+ it('verifies target credential scope before any promotion mutation', () => {+ const steps = jobSteps(workflowJob(promotionWorkflow, 'promote'))+ const credentials = steps.find(+ (step) => step.name === 'Validate scoped Store credential'+ ) as LooseRecord+ const release = steps.find(+ (step) => step.name === 'Release approved build set'+ ) as LooseRecord+ expect(steps.indexOf(credentials)).toBeLessThan(steps.indexOf(release))+ expect(credentials['continue-on-error']).toBeUndefined()+ expect(release.if).toBeUndefined()+ expect(stringField(credentials, 'run')).toContain(+ 'python3 scripts/verify_snap_credential_scope.py'+ )+ expect(stringField(credentials, 'run')).toContain(+ '--channel "$TARGET_CHANNEL"'+ )+ expect(asRecord(credentials.env, 'credential environment')).toMatchObject({+ SNAPCRAFT_STORE_CREDENTIALS: `\${{ secrets.SNAPCRAFT_STORE_CREDENTIALS }}`,+ TARGET_CHANNEL: `\${{ needs.preflight.outputs.target_channel }}`,+ })+ expect(asRecord(release.env, 'release environment')).toMatchObject({+ SNAPCRAFT_STORE_CREDENTIALS: `\${{ secrets.SNAPCRAFT_STORE_CREDENTIALS }}`,+ TARGET_CHANNEL: `\${{ needs.preflight.outputs.target_channel }}`,+ })+ })+it('is manual-only, serialized with edge publication, and runs from main', () => {const triggers = asRecord(promotionWorkflow.on, 'promotion triggers')expect(Object.keys(triggers)).toEqual(['workflow_dispatch'])@@ -628,6 +655,222 @@ describe('Snap promotion workflow contract', () => {})})+describe.skipIf(process.platform === 'win32')(+ 'Snap promotion credential scope',+ () => {+ it.each(['candidate', 'stable'])(+ 'rejects the observed edge credential before any %s mutation',+ (target) => {+ const result = runPromotionCredentialGate({+ target,+ channels: 'edge',+ permissions:+ 'package_access, package_push, package_update, package_release',+ })+ expect(result.status).toBe(1)+ expect(result.stderr).toContain(+ `does not permit release to latest/${target}`+ )+ expect(result.snapcraftCalls).toEqual(['whoami --verbosity brief'])+ expect(result.releaseCalls).toEqual([])+ }+ )++ it.each([+ { target: 'candidate', channels: 'candidate' },+ { target: 'stable', channels: 'stable' },+ { target: 'candidate', channels: 'edge, candidate, stable' },+ { target: 'stable', channels: 'no restrictions' },+ { target: 'candidate', channels: 'candi?ate' },+ { target: 'stable', channels: '*' },+ { target: 'stable', channels: '[cs]*' },+ {+ target: 'candidate',+ channels: 'candidate',+ permissions: 'package_upload',+ },+ { target: 'stable', channels: 'stable', permissions: 'no restrictions' },+ {+ target: 'stable',+ channels: 'edge,\n candidate, stable',+ permissions: 'package_access,\n package_release',+ },+ ])('accepts a scope covering the actual release request %j', (options) => {+ const result = runPromotionCredentialGate(options)+ expect(result.stderr).toBe('')+ expect(result.status).toBe(0)+ expect(result.snapcraftCalls).toEqual([+ 'whoami --verbosity brief',+ 'status motrix',+ ])+ expect(result.releaseCalls).toHaveLength(1)+ expect(result.releaseCalls[0]).toContain(+ `--channel latest/${options.target}`+ )+ })++ it.each([+ { channels: 'candidate', target: 'stable' },+ { channels: '2.0/candidate' },+ { channels: 'latest/candidate' },+ { channels: 'candidate/branch' },+ { channels: '[!c]*' },+ { permissions: 'package_access, package_push' },+ { permissions: 'package_release_extra' },+ { permissions: '' },+ { channels: '' },+ { channels: 'no restrictions, edge' },+ { channels: 'edge,,candidate' },+ { output: '' },+ {+ output:+ 'Log message mentions permissions: package_release and channels: candidate',+ },+ {+ output: snapWhoami('candidate').replace(+ 'permissions: package_access, package_release\n',+ ''+ ),+ },+ { output: `${snapWhoami('edge')}\nchannels: candidate` },+ {+ output: `warning: credential scope may be stale\n${snapWhoami('candidate')}`,+ },+ {+ output: snapWhoami('candidate').replace(+ 'channels: candidate',+ 'channels: |\n candidate'+ ),+ },+ { output: snapWhoami('candidate'), exitCode: 1 },+ { output: snapWhoami('candidate'), diagnostic: 'unexpected diagnostic' },+ ])(+ 'rejects invalid or insufficient scope before entering the release helper %j',+ (options) => {+ const result = runPromotionCredentialGate(options)+ expect(result.status).not.toBe(0)+ expect(result.releaseCalls).toEqual([])+ expect(result.snapcraftCalls).toEqual(['whoami --verbosity brief'])+ expect(result.stdout + result.stderr).not.toContain(+ )+ expect(result.stdout + result.stderr).not.toContain(+ 'fixture-secret-do-not-print'+ )+ expect(result.stdout + result.stderr).not.toContain(+ 'unexpected diagnostic'+ )+ }+ )+ }+)++function snapWhoami(+ channels: string,+ permissions = 'package_access, package_release'+) {+ return [+ 'email: [email protected]',+ 'username: fixture-account',+ 'id: fixture-id',+ `permissions: ${permissions}`,+ `channels: ${channels}`,+ 'expires: N/A',+ ].join('\n')+}++function runPromotionCredentialGate({+ target = 'candidate',+ channels = 'candidate',+ permissions = 'package_access, package_release',+ output = snapWhoami(channels, permissions),+ diagnostic = '',+ exitCode = 0,+}: {+ target?: string+ channels?: string+ permissions?: string+ output?: string+ diagnostic?: string+ exitCode?: number+}) {+ const root = mkdtempSync(path.join(tmpdir(), 'motrix-snap-credential-'))+ const whoamiFile = path.join(root, 'whoami.txt')+ const snapcraftLog = path.join(root, 'snapcraft.log')+ const releaseLog = path.join(root, 'release.log')+ writeFileSync(whoamiFile, output)+ writeFileSync(snapcraftLog, '')+ writeFileSync(releaseLog, '')+ writeFileSync(+ path.join(root, 'snapcraft'),+ [+ '#!/usr/bin/env bash',+ 'set -euo pipefail',+ 'printf \'%s\\n\' "$*" >> "$MOTRIX_TEST_SNAPCRAFT_LOG"',+ 'case "$1" in',+ ' whoami) cat "$MOTRIX_TEST_WHOAMI_FILE"; printf \'%s\' "$MOTRIX_TEST_DIAGNOSTIC" >&2; exit "$MOTRIX_TEST_EXIT_CODE" ;;',+ ' status) exit 0 ;;',+ ' *) exit 98 ;;',+ 'esac',+ ].join('\n'),+ { mode: 0o755 }+ )+ writeFileSync(+ path.join(root, 'node'),+ [+ '#!/usr/bin/env bash',+ 'set -euo pipefail',+ '[[ "$1" == scripts/release-snap-build-set.mjs ]] || exit 99',+ 'printf \'%s\\n\' "$*" >> "$MOTRIX_TEST_RELEASE_LOG"',+ ].join('\n'),+ { mode: 0o755 }+ )+ const steps = jobSteps(workflowJob(promotionWorkflow, 'promote'))+ const credentials = steps.find(+ (step) => step.name === 'Validate scoped Store credential'+ ) as LooseRecord+ const release = steps.find(+ (step) => step.name === 'Release approved build set'+ ) as LooseRecord+ // A failed credential step prevents subsequent Actions steps. Execute both+ // real commands under the credential step's errexit to prove that boundary.+ const command =+ `${stringField(credentials, 'run')}\n${stringField(release, 'run')}`+ .replaceAll('/snap/bin/snapcraft', 'snapcraft')+ .replaceAll(`\${{ needs.preflight.outputs.amd64_revision }}`, '111')+ .replaceAll(`\${{ needs.preflight.outputs.arm64_revision }}`, '112')+ try {+ const result = spawnSync('bash', ['-c', command], {+ cwd: ROOT,+ encoding: 'utf8',+ env: {+ ...process.env,+ PATH: `${root}${path.delimiter}${process.env.PATH ?? ''}`,+ SNAPCRAFT_STORE_CREDENTIALS: 'fixture-secret-do-not-print',+ PROMOTION_TARGET: target,+ TARGET_CHANNEL: `latest/${target}`,+ EXPECTED_VERSION: '2.0.0',+ MOTRIX_TEST_WHOAMI_FILE: whoamiFile,+ MOTRIX_TEST_DIAGNOSTIC: diagnostic,+ MOTRIX_TEST_EXIT_CODE: String(exitCode),+ MOTRIX_TEST_SNAPCRAFT_LOG: snapcraftLog,+ MOTRIX_TEST_RELEASE_LOG: releaseLog,+ },+ })+ return {+ ...result,+ snapcraftCalls: readFileSync(snapcraftLog, 'utf8')+ .split('\n')+ .filter(Boolean),+ releaseCalls: readFileSync(releaseLog, 'utf8')+ .split('\n')+ .filter(Boolean),+ }+ } finally {+ rmSync(root, { recursive: true, force: true })+ }+}+// The promotion job executes Bash and jq on Ubuntu; these fixtures exercise// that exact script without contacting GitHub or modifying a Git checkout.describe.skipIf(process.platform === 'win32')(