diff --git a/.ci/sai/README.md b/.ci/sai/README.md index 8965a7d..c683dd7 100644 --- a/.ci/sai/README.md +++ b/.ci/sai/README.md @@ -11,9 +11,9 @@ neither stage requests explicit Slurm memory. | Event | Source sent to SAI | Approval | | --- | --- | --- | -| Push or merge to protected `develop` or `main` | Pushed commit | Automatic once enabled | +| Push or merge to upstream `develop` or `main` | Pushed commit | Automatic once enabled | | PR opened, reopened or updated against either branch | Current PR head, including for forks | A maintainer approves that run; a new commit needs new approval | -| Manual run on either protected branch | Supplied full commit SHA | A maintainer approves that run | +| Manual run on either branch | Supplied full commit SHA | A maintainer approves that run | Push and PR checks work on `develop` as soon as it contains the workflow. Bring the workflow to `main` to cover pushes there and expose **Run workflow** in @@ -22,9 +22,9 @@ remain failures; the job uploads available JUnit, logs and Slurm evidence. ## Repository owner -1. Protect `develop` and `main` with required review, including workflow changes; - restrict direct and force pushes. Under **Settings > Actions > General**, - require approval for fork workflows from **all outside collaborators**. +1. Review who can push to `develop` and `main`: their pushes are trusted to run + on SAI. Branch protection is optional for this integration. PRs, including + forks, require a maintainer's approval for the current run. 2. Under **Settings > Environments**, keep required maintainer reviewers on `sai-libddla` and allow the branch patterns `main`, `develop` and `refs/pull/*/merge`. Review the source SHA in the run title before approving: @@ -32,9 +32,9 @@ remain failures; the job uploads available JUnit, logs and Slurm evidence. `main` and `develop` allowed and no required reviewer. Neither needs secrets. 3. Under **Settings > Actions > Runners**, privately give SAI a short-lived **repository runner registration token** for the initial setup. Agree on - renewal for disposable runners and reviewer logins with SAI. Provide the site - publisher read access to Actions, Contents, Pull requests and Variables for - this repository. No repository-write token or SAI SSH key is needed by a job. + renewal for disposable runners and reviewer logins with SAI. Each job shares + its automatically issued, read-only `GITHUB_TOKEN` with the site publisher; + no separate PAT or repository-write credential is needed. 4. Once SAI confirms isolation, set the repository Actions variable `SAI_CI_ENABLED=true` for a supervised first run on `develop`. Keep it on after verifying reporting and cancellation; removing it disables new @@ -43,21 +43,25 @@ remain failures; the job uploads available JUnit, logs and Slurm evidence. ## SAI administrators - Register clean, disposable Linux x64 runners labeled `sai-libddla-results`, - with Bash and jq and one concurrent job to match site capacity. Give jobs - **only read-only access to published results** at - `/srv/sai-libddla/results`: no site credentials, SSH agent, controller socket, + with Bash and jq and one concurrent job to match site capacity. Mount published + results at `/srv/sai-libddla/results` read-only and a separate request mailbox + at `/srv/sai-libddla/requests` writable. The mailbox must be private to this + repository's runner and publisher, and must never be uploaded as an artifact. + Give the runner no site credentials, SSH agent, controller socket, private storage or cluster network access. Retire any credential-bearing runner accessible to this public repository before accepting PR workflows. A label or an Environment cannot stop a fork from changing workflow steps. - On the trusted side, install a reviewed copy of [publish.py](publish.py) and the existing [site controller](https://github.com/Stardust0831/LibDDLA/tree/66b2c419de961618671c9fbd99298dc6c4b2d255/.ci/sai). Keep SSH, the restricted endpoint and Slurm quotas there. Run one publisher - at a time on a short timer (e.g. every 20 seconds) with Python 3.10+ and an - authenticated `gh` bound to github.com. It polls GitHub directly; it does not - accept commands or source files from the runner. + at a time on a short timer (e.g. every 20 seconds) with Python 3.10+ and `gh`. + It reads the job's short-lived token from the mailbox and verifies the run + independently with GitHub. It accepts no commands or source files from jobs. - Configure the publisher's `SAI_RELAY` and `SAI_SSH_CONFIG` paths, a private `SAI_WORK` directory, the site-writable `SAI_RESULTS` directory exported - read-only to jobs, and comma-separated trusted `SAI_REVIEWERS` GitHub logins. + read-only to jobs, the `SAI_REQUESTS` mailbox, and comma-separated trusted + `SAI_REVIEWERS` GitHub logins. Ensure the publisher can read token files created + by the runner; remove stale tokens after terminated runs. The existing endpoint requires the exact SHA during both prepare and submit. For automatic admission, provide a site-owned `SAI_AUTHORIZE` executable: it receives `event branch sha run_id` after verification and must authorize diff --git a/.ci/sai/publish.py b/.ci/sai/publish.py index dea07a5..f8893e7 100644 --- a/.ci/sai/publish.py +++ b/.ci/sai/publish.py @@ -5,6 +5,7 @@ import re import shutil import signal +import stat import subprocess import sys @@ -32,8 +33,6 @@ def admission(run, reviewers): require(run["path"] == WORKFLOW and run["repository"]["full_name"] == REPO and match, "Unknown workflow or invalid request") pr, sha = match.groups() - if event != "workflow_dispatch": - require(api("actions/variables/SAI_CI_ENABLED")["value"] == "true", "Automatic CI is off") branch = run["head_branch"] if event == "pull_request": pull = api(f"pulls/{pr}") @@ -45,11 +44,11 @@ def admission(run, reviewers): else: require(event in {"push", "workflow_dispatch"} and pr == "0" and run["head_repository"]["full_name"] == REPO, "Unexpected event or repository") - require(branch in BRANCHES and api(f"branches/{branch}")["protected"], "Unprotected base") + require(branch in BRANCHES, "Unexpected base branch") if event == "push": require(sha == run["head_sha"] and api(f"compare/{sha}...{branch}")["status"] in {"ahead", "identical"}, - "Push SHA is not on the protected branch") + "Push SHA is not on the trusted branch") else: decisions = [a for a in api(f"actions/runs/{run['id']}/approvals") if any(e["name"] == REVIEW_ENV for e in a["environments"])] @@ -120,15 +119,33 @@ def main(): require(private.is_dir() and public.is_dir() and not private.is_relative_to(public) and not public.is_relative_to(private), "Private work and public results must be separate directories") reviewers = {login.strip().lower() for login in os.environ["SAI_REVIEWERS"].split(",") if login.strip()} - page = 1 - while True: - runs = api(f"actions/runs?status=in_progress&per_page=100&page={page}")["workflow_runs"] - for run in runs: + for request in sorted(Path(os.environ["SAI_REQUESTS"]).glob("gh-*-*.token")): + match = re.fullmatch(r"gh-([1-9][0-9]*)-([1-9][0-9]*)\.token", request.name) + if not match or (public / request.stem).exists(): + continue + descriptor = None + try: + # This mailbox is writable by jobs. Never follow links or read special files. + descriptor = os.open(request, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK) + require(stat.S_ISREG(os.fstat(descriptor).st_mode), "Token is not a regular file") + token = os.read(descriptor, 257).decode("ascii") + require(re.fullmatch(r"[A-Za-z0-9_]{20,256}", token), "Invalid token format") + os.environ["GH_TOKEN"] = token + run = api(f"actions/runs/{match[1]}") + if run["run_attempt"] != int(match[2]) or run["status"] == "completed": + request.unlink(missing_ok=True) + continue + require(run["status"] == "in_progress", "Request is not active yet") if run["path"] == WORKFLOW: publish(run, reviewers) - if len(runs) < 100: - return - page += 1 + except (OSError, ValueError, subprocess.SubprocessError) as error: + print(f"{request.name}: {type(error).__name__}", file=sys.stderr, flush=True) + finally: + if descriptor is not None: + os.close(descriptor) + os.environ.pop("GH_TOKEN", None) + if (public / request.stem / "completion.json").is_file(): + request.unlink(missing_ok=True) if __name__ == "__main__": diff --git a/.ci/sai/test_publish.py b/.ci/sai/test_publish.py index 18ab53e..ec4b74c 100644 --- a/.ci/sai/test_publish.py +++ b/.ci/sai/test_publish.py @@ -21,8 +21,6 @@ def setUp(self): base=dict(ref="develop", repo=self.repo)) self.routes = { "actions/runs/17": self.run, "pulls/3": self.pull, - "branches/develop": {"protected": True}, "branches/main": {"protected": True}, - "actions/variables/SAI_CI_ENABLED": {"value": "true"}, "actions/runs/17/approvals": [{"state": "approved", "user": {"login": "owner"}, "environments": [{"name": site.REVIEW_ENV}]}], "actions/runs/17/attempts/1/jobs": {"jobs": [{"status": "in_progress", @@ -49,9 +47,7 @@ def test_push_and_manual_sources(self): display_title=f"SAI CUDA / 0 / {self.sha}") self.routes[f"compare/{self.sha}...main"] = {"status": "ahead"} self.assertEqual(site.admission(self.run, set()), ("main", self.sha, "0")) - for path, bad in [("actions/variables/SAI_CI_ENABLED", {"value": "false"}), - ("branches/main", {"protected": False}), - (f"compare/{self.sha}...main", {"status": "diverged"})]: + for path, bad in [(f"compare/{self.sha}...main", {"status": "diverged"})]: with self.subTest(path=path), patch.dict(self.routes, {path: bad}), self.assertRaises(ValueError): site.admission(self.run, set()) self.run.update(event="workflow_dispatch", display_title=f"SAI CUDA / 0 / {'b' * 40}") @@ -62,6 +58,31 @@ def test_push_and_manual_sources(self): with self.assertRaises(ValueError): site.admission(self.run, {"owner"}) + def test_request_tokens_are_scoped_and_links_rejected(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + for folder in ("work", "results", "requests"): + (root / folder).mkdir() + token = "ghs_" + "a" * 36 + request = root / "requests/gh-17-1.token" + request.write_text(token) + env = {"SAI_WORK": str(root / "work"), "SAI_RESULTS": str(root / "results"), + "SAI_REQUESTS": str(root / "requests"), "SAI_REVIEWERS": "owner"} + with patch.dict(os.environ, env), patch.object(site, "publish") as publish: + publish.side_effect = lambda *args: self.assertEqual(os.environ["GH_TOKEN"], token) + site.main() + publish.assert_called_once_with(self.run, {"owner"}) + self.assertNotIn("GH_TOKEN", os.environ) + publish.reset_mock() + self.run["status"] = "completed" + site.main() + publish.assert_not_called() + self.assertFalse(request.exists()) + request.symlink_to(root / "secret") + (root / "secret").write_text(token) + site.main() + publish.assert_not_called() + def test_receipt_and_cancellation(self): for exit_status in (0, 1, "cancel"): with self.subTest(exit_status=exit_status), tempfile.TemporaryDirectory() as tmp: diff --git a/.github/workflows/sai-validation.yml b/.github/workflows/sai-validation.yml index be104d8..a586414 100644 --- a/.github/workflows/sai-validation.yml +++ b/.github/workflows/sai-validation.yml @@ -16,6 +16,8 @@ on: permissions: contents: read + actions: read + pull-requests: read concurrency: group: sai-cuda-${{ github.event.pull_request.number || github.run_id }} @@ -25,11 +27,11 @@ jobs: cuda: if: >- github.repository == 'userchba/LibDDLA' && - ((github.event_name == 'workflow_dispatch' && github.ref_protected && + ((github.event_name == 'workflow_dispatch' && (github.ref == 'refs/heads/main' || github.ref == 'refs/heads/develop')) || (vars.SAI_CI_ENABLED == 'true' && (github.event_name == 'pull_request' || - (github.event_name == 'push' && github.ref_protected && !github.event.deleted)))) + (github.event_name == 'push' && !github.event.deleted)))) name: SAI V100, full CUDA suite and six-rank matrix tests runs-on: [self-hosted, Linux, X64, sai-libddla-results] environment: ${{ github.event_name == 'push' && 'sai-libddla-push' || 'sai-libddla' }} @@ -38,6 +40,15 @@ jobs: DDLA_SOURCE_SHA: ${{ github.event.pull_request.head.sha || inputs.source_sha || github.sha }} DDLA_RUN_ID: gh-${{ github.run_id }}-${{ github.run_attempt }} steps: + - name: Give the site service this attempt's read-only token + env: + GH_TOKEN: ${{ github.token }} + run: | + set -euo pipefail + umask 022 + request="/srv/sai-libddla/requests/$DDLA_RUN_ID.token" + (set -o noclobber; printf '%s' "$GH_TOKEN" > "$request") + - name: Read this attempt's result from SAI timeout-minutes: 175 run: | @@ -60,3 +71,7 @@ jobs: path: /srv/sai-libddla/results/${{ env.DDLA_RUN_ID }}/ if-no-files-found: error retention-days: 30 + + - name: Remove this attempt's API token + if: always() + run: rm -f -- "/srv/sai-libddla/requests/$DDLA_RUN_ID.token"