From f015052247c6218fcb8f97b612aeaf57efb45a26 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Wed, 7 Oct 2026 20:33:14 +0200 Subject: [PATCH] fix(ci): scope release write permission to Gitea publishers --- .github/workflows/linux.yml | 12 +++ docs/gitea-preview-publication.md | 2 + scripts/test-gitea-release.py | 131 ++++++++++++++++++++++++++++++ 3 files changed, 145 insertions(+) diff --git a/.github/workflows/linux.yml b/.github/workflows/linux.yml index 980788d1..ce150266 100644 --- a/.github/workflows/linux.yml +++ b/.github/workflows/linux.yml @@ -67,6 +67,9 @@ jobs: run: scripts/check-kar-expert-gpu.sh static-cuda-package: + permissions: + contents: read + releases: write if: gitea.event_name == 'workflow_dispatch' && gitea.event.inputs.static_cuda_package == 'true' && gitea.event.repository.private needs: verify runs-on: [self-hosted, linux, x64, strata-gpu] @@ -127,6 +130,9 @@ jobs: run: rm -rf -- "${RUNNER_TEMP}/strata-static-cuda-${GITHUB_RUN_ID}" "${RUNNER_TEMP}/strata-package-build-${GITHUB_RUN_ID}" hosted-cuda-package: + permissions: + contents: read + releases: write if: gitea.event_name == 'workflow_dispatch' && (gitea.event.inputs.hosted_cuda_package == 'true' || gitea.event.inputs.hosted_cuda_ple == 'true') && gitea.event.repository.private needs: verify runs-on: ubuntu-latest @@ -324,6 +330,9 @@ jobs: rm -rf -- "$RUNNER_TEMP/strata-cuda-builder-context" "$RUNNER_TEMP/CUDA-BUILDER-IMAGE-ID" linux-static-cli: + permissions: + contents: read + releases: write needs: verify runs-on: ubuntu-latest env: @@ -478,6 +487,9 @@ jobs: run: docker image rm strata-cli-check || true release-cli: + permissions: + contents: read + releases: write if: startsWith(github.ref, 'refs/tags/v') needs: [linux-static-cli, linux-cli-container] runs-on: ubuntu-latest diff --git a/docs/gitea-preview-publication.md b/docs/gitea-preview-publication.md index 3c110b8b..074aa4a2 100644 --- a/docs/gitea-preview-publication.md +++ b/docs/gitea-preview-publication.md @@ -17,3 +17,5 @@ Publication creates a draft prerelease, streams the exact verified assets, check Receipts record CI/operator-declared source identity, not binary-to-source attestation. GPU/model qualification stays false; these publications do not establish inference quality, throughput, model readiness or deployment readiness. Synthetic tests exercise API streaming, remote corruption, interrupted uploads, exact profiles, forged rehashed receipts and the current producer validators. Real private Gitea publication remains a workflow qualification gate. The download URL profile was checked against read-only Gitea release `cuda-preview-2495-1` on git.vezha.io: `/para/leleka/releases/download/{tag}/{asset}`. Gitea 1.27.3 [RedirectDownload](https://raw.githubusercontent.com/go-gitea/gitea/v1.27.3/routers/web/repo/repo.go) finds releases by repository/tag and includes drafts for writers; it serves the associated attachment without requiring a Git tag to exist. Synthetic tests verify download and redirect hashing while the release is still draft and before tag publication, and prove that foreign redirects receive no request or token. Actual fresh CI publication remains unqualified until that gate succeeds. + +Publication jobs request `contents: read` and the Gitea-specific `releases: write` permission on their built-in job token; the workflow default and nonpublication jobs keep read-only permissions. This follows the [Gitea 1.27 token-permission contract](https://docs.gitea.com/1.27/usage/actions/token-permissions/). Owner/repository maximums can still clamp the effective token; the real publication gate must succeed before qualification. No stored PAT is read or created. diff --git a/scripts/test-gitea-release.py b/scripts/test-gitea-release.py index 8fedded3..c7d2cfc3 100644 --- a/scripts/test-gitea-release.py +++ b/scripts/test-gitea-release.py @@ -5,6 +5,7 @@ import importlib.util from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer import json from pathlib import Path +import re import tempfile import threading from urllib.parse import parse_qs, urlsplit @@ -19,6 +20,136 @@ TOKEN = 'fixture-action-token' REVISION = 'a' * 40 +def workflow_permissions(lines, indent): + """Read the workflow's explicit permission maps; reject ambiguous syntax. + + This is deliberately a bounded contract parser for the committed workflow, + not a general YAML loader. Anchors, inline maps, duplicate keys and broad + grants fail closed rather than being interpreted differently from Gitea. + """ + headers = [index for index, line in enumerate(lines) + if re.match(r'^' + ' ' * indent + r'permissions:', line)] + if not headers: + return None + if len(headers) != 1: + raise ValueError('duplicate permissions map') + start = headers[0] + if lines[start].split(':', 1)[1].split('#', 1)[0].strip(): + raise ValueError('permissions must be an explicit map') + result = {} + for line in lines[start + 1:]: + if not line.strip() or line.lstrip().startswith('#'): + continue + spaces = len(line) - len(line.lstrip(' ')) + if spaces <= indent: + break + field = re.fullmatch(' ' * (indent + 2) + r'([a-z][a-z-]*):\s*(read|write|none)\s*(?:#.*)?', line) + if field is None or field[1] in result: + raise ValueError('invalid or duplicate permission scope') + result[field[1]] = field[2] + if not result: + raise ValueError('empty permissions map') + return result + + +def publisher_workflow_contract(text): + if len(text.encode()) > 128 * 1024 or len(text.splitlines()) > 4096: + raise ValueError('workflow exceeds contract limits') + lines = text.splitlines() + if any(re.match(r'^ *\t', line) for line in lines): + raise ValueError('tab indentation is unsupported') + roots = [index for index, line in enumerate(lines) if line == 'jobs:'] + if len(roots) != 1: + raise ValueError('expected one explicit jobs map') + start = roots[0] + if workflow_permissions(lines[:start], 0) != {'contents': 'read'}: + raise ValueError('workflow default must remain contents read-only') + jobs, current = {}, None + for line in lines[start + 1:]: + if line.strip() and not line.startswith((' ', '#')): + raise ValueError('unexpected root after jobs') + header = re.fullmatch(r' ([a-zA-Z0-9_-]+):\s*(?:#.*)?', line) + if header: + current = header[1] + if current in jobs or len(jobs) >= 128: + raise ValueError('invalid job map') + jobs[current] = [] + elif (line.strip() and not line.lstrip().startswith('#') + and len(line) - len(line.lstrip(' ')) == 2): + raise ValueError('job must use an explicit block map') + elif current is not None: + jobs[current].append(line) + elif line.strip() and not line.lstrip().startswith('#'): + raise ValueError('unsupported jobs syntax') + publishers = set() + call = re.compile(r'(?:^|[\s;&|])python3?(?:\.\d+)?(?:\s+-[A-Za-z]+)*\s+[\"\']?(?:\./)?scripts/publish-gitea-release\.py[\"\']?(?:\s|$)') + for name, section in jobs.items(): + commands = [] + for index, line in enumerate(section): + run = re.fullmatch(r' run:\s*(.*)', line) + if run is None: + continue + if run[1] in ('|', '|-', '|+', '>', '>-', '>+'): + for body in section[index + 1:]: + if body.strip() and len(body) - len(body.lstrip(' ')) <= 8: + break + if not body.lstrip().startswith('#'): + commands.append(body.strip()) + else: + commands.append(run[1]) + publishes = any(call.search(command) for command in commands) + scopes = workflow_permissions(section, 4) + if publishes: + if scopes != {'contents': 'read', 'releases': 'write'}: + raise ValueError('publisher requires only contents read and releases write') + publishers.add(name) + elif scopes is not None and any(level == 'write' for level in scopes.values()): + raise ValueError('nonpublisher job must not receive writable scopes') + if len(publishers) != 4: + raise ValueError('expected four actual publisher jobs') + return publishers, jobs + + +class PublisherWorkflowTests(unittest.TestCase): + def workflow(self): + path = Path(__file__).resolve().parent.parent / '.github/workflows/linux.yml' + with path.open('rb') as source: + data = source.read(128 * 1024 + 1) + self.assertLessEqual(len(data), 128 * 1024) + return data.decode() + + def test_actual_publisher_commands_have_narrow_job_permissions(self): + publishers, jobs = publisher_workflow_contract(self.workflow()) + self.assertEqual(len(publishers), 4) + self.assertGreater(len(jobs), len(publishers)) + # Discovery follows the executed command, not a hard-coded job name. + original = sorted(publishers)[0] + renamed = self.workflow().replace(f' {original}:\n', ' renamed-publication-fixture:\n', 1) + renamed_publishers, _ = publisher_workflow_contract(renamed) + self.assertIn('renamed-publication-fixture', renamed_publishers) + self.assertNotIn(original, renamed_publishers) + + def test_permission_regressions_are_rejected_before_publication(self): + text = self.workflow() + publishers, jobs = publisher_workflow_contract(text) + nonpublisher = sorted(set(jobs) - publishers)[0] + mutations = ( + text.replace('permissions:\n contents: read', 'permissions:\n contents: write', 1), + text.replace(' releases: write', ' releases: read', 1), + text.replace(' contents: read\n releases: write', ' contents: write\n releases: write', 1), + text.replace(f' {nonpublisher}:\n', f' {nonpublisher}:\n permissions:\n contents: write\n', 1), + text.replace(' releases: write', ' releases: write\n actions: write', 1), + text + '\n inline-job: {permissions: write-all, steps: []}\n', + text + '\n alias-job: *publisher-job\n', + text + '\n anchored-job: &publisher-job\n permissions:\n contents: write\n', + ) + for index, mutation in enumerate(mutations): + with self.subTest(regression=index): + self.assertNotEqual(mutation, text) + with self.assertRaises(ValueError): + publisher_workflow_contract(mutation) + + class FakeGitea(BaseHTTPRequestHandler): def log_message(self, *_args): pass