diff --git a/docs/cli/repos.md b/docs/cli/repos.md index 7c96200458..3bf0579ba1 100644 --- a/docs/cli/repos.md +++ b/docs/cli/repos.md @@ -79,7 +79,7 @@ fullsend repos migrate --project ## `repos install` -Converge repos to the desired state defined in a manifest. This is the primary command for managing per-repo installations — it handles adding repos to the manifest, provisioning new repos, repairing component drift (workflow, thin callers, variables, secrets, pipeline schedules, GitLab poller protected-ref pipeline access — a disabled GitLab schedule is reported as drift and reactivated only when `--reactivate-schedules` is passed), repairing scaffold content drift (including structural rewrites of `.gitlab/ci/fullsend-pipeline.yml` at an unchanged template ref, and removal of a leftover `.gitlab/ci/fullsend-dispatch.yml` from installs predating #7707), and upgrading scaffold refs. +Converge repos to the desired state defined in a manifest. This is the primary command for managing per-repo installations — it handles adding repos to the manifest, provisioning new repos, repairing component drift (workflow, thin callers, variables, secrets, pipeline schedules, GitLab poller protected-ref pipeline access — a disabled GitLab schedule is reported as drift and reactivated only when `--reactivate-schedules` is passed; GitLab pipeline-variable override-role inspection via `FULLSEND_GITLAB_PIPELINE_VAR_RESTRICTION`, report-only by default — see [GitLab Role-Credential Contract](../contributing/gitlab-role-credentials.md#how-a-job-selects-its-credential)), repairing scaffold content drift (including structural rewrites of `.gitlab/ci/fullsend-pipeline.yml` at an unchanged template ref, and removal of a leftover `.gitlab/ci/fullsend-dispatch.yml` from installs predating #7707), and upgrading scaffold refs. When the manifest file does not exist and positional repo arguments are provided, `repos install` bootstraps a new manifest (`version: 1`), @@ -90,7 +90,7 @@ required in this case. This enables a greenfield setup without running Runs in two phases: 1. **Manifest add** — repos specified as positional arguments that are not already in the manifest are added (`--forge` is required when the target platform cannot be inferred). Per-repo overrides (`--inference-region`, `--fullsend-ref`, `--mint-url`, `--allowed-remote-resources`, `--runtime`) are written to the manifest entry. -2. **Converge** — all manifest repos are converged through a unified probe → diff → apply pipeline. Repos whose shim workflow is not yet on the default branch are freshly installed (scaffold files, variables, secrets, a declared configuration preset as `.fullsend/config.base.yaml`, and a canonical managed `.fullsend/config.yaml` when the repository is managed) onto the initialization branch (`fullsend/scaffold-install`). That includes a re-run while the initialization PR/MR is still open: variables and secrets may already exist from the first run, but the installer still updates the same initialization PR rather than opening a competing upgrade PR. Repos whose workflow is already on the default branch are checked for drift (workflow, thin callers, variables, secrets, pipeline schedules, GitLab poller protected-ref pipeline access — repaired automatically, except a disabled GitLab schedule, which is reported as drift and reactivated only with `--reactivate-schedules`), scaffold content drift (repaired automatically, including structural rewrites of `.gitlab/ci/fullsend-pipeline.yml` at an unchanged template ref, and removal of a leftover `.gitlab/ci/fullsend-dispatch.yml` from installs predating #7707), declared configuration-preset drift against `.fullsend/config.base.yaml` (replaced wholesale; `.fullsend/config.yaml` is preserved), managed `.fullsend/config.yaml` drift (replaced wholesale for managed repositories; unmanaged files are left untouched), and scaffold ref drift (upgraded automatically). +2. **Converge** — all manifest repos are converged through a unified probe → diff → apply pipeline. Repos whose shim workflow is not yet on the default branch are freshly installed (scaffold files, variables, secrets, a declared configuration preset as `.fullsend/config.base.yaml`, and a canonical managed `.fullsend/config.yaml` when the repository is managed) onto the initialization branch (`fullsend/scaffold-install`). That includes a re-run while the initialization PR/MR is still open: variables and secrets may already exist from the first run, but the installer still updates the same initialization PR rather than opening a competing upgrade PR. Repos whose workflow is already on the default branch are checked for drift (workflow, thin callers, variables, secrets, pipeline schedules, GitLab poller protected-ref pipeline access — repaired automatically, except a disabled GitLab schedule, which is reported as drift and reactivated only with `--reactivate-schedules`; GitLab pipeline-variable override-role inspection, report-only by default), scaffold content drift (repaired automatically, including structural rewrites of `.gitlab/ci/fullsend-pipeline.yml` at an unchanged template ref, and removal of a leftover `.gitlab/ci/fullsend-dispatch.yml` from installs predating #7707), declared configuration-preset drift against `.fullsend/config.base.yaml` (replaced wholesale; `.fullsend/config.yaml` is preserved), managed `.fullsend/config.yaml` drift (replaced wholesale for managed repositories; unmanaged files are left untouched), and scaffold ref drift (upgraded automatically). `defaults.config` and per-repository `config` declare a sparse typed managed configuration for `.fullsend/config.yaml` ([ADR 0122](../ADRs/0122-declarative-repo-configuration.md)). They share the per-repo config schema except `runtime` and `allowed_remote_resources`, which remain the existing manifest shorthands — putting either key inside `config` fails validation. `defaults.config` opts every repository in; a repository `config` (including `config: {}`) opts in only that repository. Unknown fields fail validation. This is not `config_base`, which copies a preset to `.fullsend/config.base.yaml`. Every managed file carries an ownership marker; a pre-existing `.fullsend/config.yaml` that lacks the marker is reported by `repos status` as "managed configuration (adoption required)" rather than ordinary drift, and install/convergence leave it untouched until it is adopted (manually edited to carry the marker, or replaced with the rendered managed body). Once a file carries the marker, install writes the canonical sparse file, `repos status` reports whole-file differences as drift, and convergence rewrites it. Repositories with neither declaration keep their existing file and are excluded from these checks. See [Repo Management — Managed configuration](../guides/getting-started/repo-management.md#managed-configuration). Before any write of a managed file, install and converge also compare the candidate and current effective configurations through the full runtime accessor chain (`kill_switch`, `roles`, `allowed_remote_resources`, agent `enabled: false` suppressions, and `create_issues.allow_targets`). A less-restrictive candidate is rejected unless the manifest explicitly declares that relaxation; status and install output identify the affected keys. diff --git a/docs/contributing/gitlab-role-credentials.md b/docs/contributing/gitlab-role-credentials.md index 36dc55fe40..14156e12a1 100644 --- a/docs/contributing/gitlab-role-credentials.md +++ b/docs/contributing/gitlab-role-credentials.md @@ -253,16 +253,25 @@ env vars `FULLSEND_GITLAB_ROLE`, `FULLSEND_GITLAB_ROLE_SECRET`, and `FULLSEND_GITLAB_ROLE_SOURCE`. GitLab CI templates (`fullsend-poll.yml`, `fullsend-agent.yml`) source `run-poll-job.sh` and `run-agent-job.sh`, which resolve credentials via -`select-gitlab-role-token.sh`. In `run-agent-job.sh`, +`select-gitlab-role-token.sh`. Both job scripts first source +`pin-ci-job-identity.sh`, which takes project, pipeline, and ref from +the `CI_JOB_TOKEN` job record (`GET /api/v4/job`) rather than from the +overridable `CI_PROJECT_ID` / `CI_PIPELINE_ID` / `CI_COMMIT_REF_PROTECTED` +env vars, and fails closed unless the server-side `.source` matches that +job's disjoint allowlist (poller = `schedule` only, agent = `api` only; +`parent_pipeline` is not admitted) and the job ref is the project's +protected default branch. YAML `workflow:` and job `rules:` also deny +truthy `CI_DEBUG_TRACE` values (the gitlab-runner `ParseBool` truthy set: +`1`, `t`/`T`, `true`/`TRUE`/`True`) before any admit rule, because secrets +materialize at job init. In `run-agent-job.sh`, the STAGE pipeline variable that would otherwise select the role is not yet authenticated when the job starts, so the *pre-verification* -bootstrap calls (resource-group PUT, pipeline-metadata GET, bot-identity -`/user` call) always resolve the Poller credential -(`FULLSEND_GITLAB_POLLER_TOKEN`), regardless of stage — this avoids -handing a forged dispatch a higher-privilege token before the -pipeline-source/bot-identity check and HMAC verification pass. The -template only re-resolves the credential for the job's actual stage — -analyst stages use `FULLSEND_GITLAB_ANALYST_TOKEN`, coder stages use +bootstrap calls (resource-group PUT, bot-identity `/user` call) always +resolve the Poller credential (`FULLSEND_GITLAB_POLLER_TOKEN`), regardless +of stage — this avoids handing a forged dispatch a higher-privilege token +before HMAC verification passes. The template only re-resolves the +credential for the job's actual stage — analyst stages use +`FULLSEND_GITLAB_ANALYST_TOKEN`, coder stages use `FULLSEND_GITLAB_CODER_TOKEN` — once `DISPATCH_VERIFIED` is true: the `api`-sourced dispatch passed HMAC verification. This is required for every job: @@ -271,12 +280,13 @@ every job: analyst/coder secret is a real higher-privilege credential as well, and an unverified STAGE must not be allowed to select it there either. A missing `FULLSEND_DISPATCH_SECRET` -now fails the job closed instead of silently -skipping HMAC verification, and a +now fails the job closed in every gate mode instead of silently +skipping HMAC verification. A `parent_pipeline`-sourced dispatch (legacy child-pipeline installs; -current installs only ever dispatch via `api`) has no HMAC to check, so -`DISPATCH_VERIFIED` stays false. The job -now fails closed at that point (`exit 1`), rather than continuing on the +current installs only ever dispatch via `api`) is already denied at the +identity pin before reaching this gate, so it never contributes a +`DISPATCH_VERIFIED=true`. The job fails closed at that point +(`exit 1`) in every gate mode, rather than continuing on the lower-privileged Poller credential. An earlier revision of this template continued the job on the Poller credential instead, but that was not sufficient: `fullsend run` resolves its own GitLab credential internally @@ -288,14 +298,32 @@ selection, so continuing on the Poller credential in the shell did not stop the CLI from promoting the STAGE-derived role token anyway. Failing the whole job closed, before `fullsend run` or the `STAGE=fix` review-body pre-fetch below ever execute, is the only way to keep an -unverified STAGE from reaching a role-specific credential. This closes a -gap where a forged dispatch that spoofed the pipeline source (via an -overridden `CI_API_V4_URL`, the documented residual risk in ADR 0067 and -`run-agent-job.sh`) could otherwise obtain a higher-privilege role -token before any credential separation existed to matter. Poll jobs have -no such pre-verification window and resolve `FULLSEND_GITLAB_POLLER_TOKEN` -once. The Go CLI then overrides `GITLAB_TOKEN` / `PUSH_TOKEN` from the -registered role credential; historical gate values do not +unverified STAGE from reaching a role-specific credential. The identity +pin plus HMAC close the gap where a forged dispatch that spoofed the +pipeline source via overridable CI variables (an overridden +`CI_API_V4_URL`, the residual risk previously documented here and in +ADR 0067) could otherwise obtain a higher-privilege role token. The +GitLab-side `ci_pipeline_variables_minimum_override_role=owner` +restriction remains the required control against `CI_JOB_TOKEN` / +`CI_API_V4_URL` outranking; it is applied at install/converge time by +this repo (not a separate issue); the in-job pin is defense-in-depth. +`repos.EnsureGitLabPipelineVariableOverrideRole` +(`internal/repos/gitlab_pipeline_var_restriction.go`) reads and converges +this setting at install/converge time for both fresh installs and +repair of already-installed repos, idempotently. Active enforcement +(actually calling `SetPipelineVariablesMinimumOverrideRole`) is gated +behind `FULLSEND_GITLAB_PIPELINE_VAR_RESTRICTION=enforced` and defaults +to report-only: restricting to `owner` also blocks the Developer-level +poller/dispatcher's own `CreatePipeline` call +(`internal/poll/dispatch.go`) unless the poller identity is separately +raised to Owner, and that credential-cost tradeoff — which touches +`PollerCanCreatePipeline` / `EnsureGitLabPollerPipelineAccess` in +`internal/repos/gitlab_pipeline_access.go` — is still open, tracked in +#7769. Flip the env var to `enforced` fleet-wide only after that +follow-up ships. Poll jobs +resolve `FULLSEND_GITLAB_POLLER_TOKEN` once, after the schedule-only pin. +The Go CLI then overrides `GITLAB_TOKEN` / `PUSH_TOKEN` from the +registered role credential; leftover `disabled`/`rollback` gates do not restore `FULLSEND_FORGE_TOKEN`. The `STAGE=fix` review-body pre-fetch is a separate case: it looks up @@ -652,6 +680,7 @@ These two are described independently in four documents: - GitLab `Developer` + `api` is still coarse. Do not document these tokens as least-privilege API grants. - `CI_DEBUG_TRACE` remains forbidden on jobs that hold any of these - variables. + variables. YAML `workflow:` and job `rules:` deny it before any admit + rule so the job never starts; the script-level guard is defense-in-depth. - When changing credential routing, rotation, or cutover, follow the [credential-routing security checklist](#credential-routing-security-checklist). diff --git a/docs/guides/getting-started/configuring-gitlab.md b/docs/guides/getting-started/configuring-gitlab.md index d2863c7733..3bae3d40b6 100644 --- a/docs/guides/getting-started/configuring-gitlab.md +++ b/docs/guides/getting-started/configuring-gitlab.md @@ -733,8 +733,9 @@ clean it up. Install does not overwrite unrelated jobs. When an existing, non-empty file already has a `workflow:` block, fullsend sets `workflow.auto_cancel.on_new_commit: none` if that key is missing, and does not -overwrite an existing value. It also adds the protected-ref `schedule`/`api` -rules if the block has no `rules:` key. Because `workflow.rules` is an +overwrite an existing value. It also adds a `CI_DEBUG_TRACE` deny-before-admit +rule (`when: never`) followed by the protected-ref `schedule`/`api` rules if +the block has no `rules:` key. Because `workflow.rules` is an allowlist, ordinary push pipelines stop running in that case unless the block already has a matching rule; add a catch-all/push rule (or an explicit `when: always` rule) before installing, or remove the name-only `workflow:` @@ -742,9 +743,33 @@ block so fullsend can leave it absent. When an existing, non-empty file has no `workflow:` block, fullsend leaves it absent so push-triggered pipelines keep running. For a missing or empty `.gitlab-ci.yml`, fullsend instead writes a fullsend-owned `workflow:` block with a name, `auto_cancel.on_new_commit: -none`, and protected-ref `schedule`/`api` rules. Later ordinary push jobs -added to that file likewise need additional `workflow.rules` (or an explicit -`when: always` rule), or GitLab will skip them. +none`, the `CI_DEBUG_TRACE` deny rule, and protected-ref `schedule`/`api` +rules. Later ordinary push jobs added to that file likewise need additional +`workflow.rules` (or an explicit `when: always` rule), or GitLab will skip +them. + +Because `workflow:rules` gates pipeline *creation*, not individual jobs, a +truthy `CI_DEBUG_TRACE` anywhere in the pipeline skips creating the entire +run — including any non-fullsend jobs in that same pipeline — not only +fullsend's own jobs, whenever fullsend owns this `workflow:` block. This is +inherent to `workflow:rules` (CI/CD variables are visible at job init, before +any job-scoped guard could run) and is required to keep dispatch secrets from +materializing when debug tracing is enabled. + +### In-job identity pin + +Before any credential-bearing call, the poll and agent job scripts also pin +their own identity from the `CI_JOB_TOKEN` job record and fail closed unless +both hold: the job's pipeline source matches that job's allowlist (poller = +`schedule` only, agent = `api` only — `parent_pipeline` is not admitted), and +the job's ref is the project's **protected default branch**, not merely any +protected ref. The YAML `workflow:` rules above still admit any protected +ref, so a poll or agent pipeline dispatched against a protected +non-default branch (for example a release branch) starts and then aborts in +this in-job check. Keep fullsend's schedules and dispatches targeting the +project's registered default branch to avoid this fail-closed abort; see +[gitlab-role-credentials.md](../../contributing/gitlab-role-credentials.md) +for the full trust model. Repos with `on_new_commit: interruptible` (or other non-`none` values) may see agent pipelines canceled by later commits. Fullsend needs diff --git a/docs/guides/getting-started/operations.md b/docs/guides/getting-started/operations.md index cc7a44b06e..8c585b8eb7 100644 --- a/docs/guides/getting-started/operations.md +++ b/docs/guides/getting-started/operations.md @@ -84,7 +84,7 @@ For manifest-managed installations (including GitLab repos), use `repos install` fullsend repos install -f repos.yaml ``` -This is idempotent — it provisions new repos, repairs missing or drifted components (workflow, thin callers, variables, secrets, pipeline schedules, GitLab poller protected-ref pipeline access — a disabled GitLab schedule is reported as drift and reactivated only when `--reactivate-schedules` is passed), repairs scaffold content drift (including structural rewrites of `.gitlab/ci/fullsend-pipeline.yml` at an unchanged template ref, and removal of a leftover `.gitlab/ci/fullsend-dispatch.yml` from installs predating #7707), refreshes a declared configuration preset (`.fullsend/config.base.yaml`), rewrites a drifted managed `.fullsend/config.yaml`, and upgrades workflow refs. Variables with manifest-specified values (e.g. mint URL, GCP region, review app client ID) are checked for value drift; secrets and runtime-mutated variables are checked for presence only. For GitLab repos, converge also migrates any leftover legacy poll-state CI/CD variables (from installs predating #7380) into the HMAC-signed poll-state branches and deletes them, so they stop being seeded or reported as orphans. Converge also migrates the root `.gitlab-ci.yml`: an obsolete `merge_request_event` workflow rule left over from installs predating the removal of native MR dispatch (#7322) is stripped automatically, without disturbing any other fullsend or user-owned entries in the file. This automatic migration applies only to repos where fullsend owns the `workflow:` block (fresh installs, identified by the fullsend-generated `workflow.name`); repos enrolled by merging fullsend rules into a pre-existing `workflow:` block have no such ownership marker and are left untouched — remove the leftover `merge_request_event` rule from those manually, as described in the uninstall steps below. Converge separately strips a leftover empty `dispatch` stage from `stages:`, left over from installs predating the removal of the empty dispatch stage (#7337). This migration is gated differently: it applies whenever the file has the fullsend pipeline include and at least one current fullsend stage (`poll` or `agent`) already in `stages:`, and it additionally scans every job definition in the file — including ones reached only via `extends:` or the YAML merge key (`<<:`) — for a still-live reference to `dispatch`, leaving the stage in place if any job depends on it. Unmanaged `.fullsend/config.yaml` files are left untouched. +This is idempotent — it provisions new repos, repairs missing or drifted components (workflow, thin callers, variables, secrets, pipeline schedules, GitLab poller protected-ref pipeline access — a disabled GitLab schedule is reported as drift and reactivated only when `--reactivate-schedules` is passed; GitLab pipeline-variable override-role inspection via `FULLSEND_GITLAB_PIPELINE_VAR_RESTRICTION`, report-only by default — see [GitLab Role-Credential Contract](../../contributing/gitlab-role-credentials.md#how-a-job-selects-its-credential)), repairs scaffold content drift (including structural rewrites of `.gitlab/ci/fullsend-pipeline.yml` at an unchanged template ref, and removal of a leftover `.gitlab/ci/fullsend-dispatch.yml` from installs predating #7707), refreshes a declared configuration preset (`.fullsend/config.base.yaml`), rewrites a drifted managed `.fullsend/config.yaml`, and upgrades workflow refs. Variables with manifest-specified values (e.g. mint URL, GCP region, review app client ID) are checked for value drift; secrets and runtime-mutated variables are checked for presence only. For GitLab repos, converge also migrates any leftover legacy poll-state CI/CD variables (from installs predating #7380) into the HMAC-signed poll-state branches and deletes them, so they stop being seeded or reported as orphans. Converge also migrates the root `.gitlab-ci.yml`: an obsolete `merge_request_event` workflow rule left over from installs predating the removal of native MR dispatch (#7322) is stripped automatically, without disturbing any other fullsend or user-owned entries in the file. This automatic migration applies only to repos where fullsend owns the `workflow:` block (fresh installs, identified by the fullsend-generated `workflow.name`); repos enrolled by merging fullsend rules into a pre-existing `workflow:` block have no such ownership marker and are left untouched — remove the leftover `merge_request_event` rule from those manually, as described in the uninstall steps below. Converge separately strips a leftover empty `dispatch` stage from `stages:`, left over from installs predating the removal of the empty dispatch stage (#7337). This migration is gated differently: it applies whenever the file has the fullsend pipeline include and at least one current fullsend stage (`poll` or `agent`) already in `stages:`, and it additionally scans every job definition in the file — including ones reached only via `extends:` or the YAML merge key (`<<:`) — for a still-live reference to `dispatch`, leaving the stage in place if any job depends on it. Converge also backfills a missing `CI_DEBUG_TRACE` deny-before-admit workflow rule (ADR 0125) into `workflow:rules` for repos where fullsend owns the `workflow:` block; as with the other root-file migrations above, repos enrolled by merging fullsend rules into a pre-existing `workflow:` block have no ownership marker, so converge leaves them untouched — add that deny rule to those repos manually. Unmanaged `.fullsend/config.yaml` files are left untouched. ## Uninstalling @@ -100,9 +100,9 @@ To remove fullsend from a single repository: **GitLab repos:** -1. Run `fullsend repos uninstall "$PROJECT_PATH"` (the full `group/subgroup/project` path) to open a PR that removes fullsend entries from `.gitlab-ci.yml` and deletes `.gitlab/ci/fullsend-pipeline.yml`, `.gitlab/ci/fullsend-agent.yml`, `.gitlab/ci/fullsend-poll.yml`, leftover `.gitlab/ci/fullsend-dispatch.yml` from installs predating #7707, `.gitlab/ci/scripts/trust-ci-server-ca.sh`, `.gitlab/ci/scripts/select-gitlab-role-token.sh`, `.gitlab/ci/scripts/install-fullsend-cli.sh`, `.gitlab/ci/scripts/run-poll-job.sh`, `.gitlab/ci/scripts/run-agent-job.sh`, `.gitlab/ci/scripts/checkout-mr-source.sh`, and `.fullsend/config.yaml` (pass `--direct` to push those file changes to the default branch). Variables, secrets, and the `fullsend-poll-state-slash` / `fullsend-poll-state-events` branches are deleted immediately via the API. If you prefer manual removal: delete `.gitlab/ci/fullsend-*.yml`, `.gitlab/ci/scripts/*.sh`, and `.fullsend/config.yaml`, then edit `.gitlab-ci.yml` to remove the fullsend pipeline include entry, the fullsend stages (`poll`, `agent`, and `dispatch` on installs from before the empty dispatch stage was removed), the fullsend workflow rules (`schedule`, `api`, and `merge_request_event` on installs from before native MR dispatch was removed), and the `auto_cancel` block if fullsend added it. Only delete `.gitlab-ci.yml` entirely if it contains no non-fullsend configuration. Also delete the two poll-state branches if they are still present. +1. Run `fullsend repos uninstall "$PROJECT_PATH"` (the full `group/subgroup/project` path) to open a PR that removes fullsend entries from `.gitlab-ci.yml` and deletes `.gitlab/ci/fullsend-pipeline.yml`, `.gitlab/ci/fullsend-agent.yml`, `.gitlab/ci/fullsend-poll.yml`, leftover `.gitlab/ci/fullsend-dispatch.yml` from installs predating #7707, `.gitlab/ci/scripts/trust-ci-server-ca.sh`, `.gitlab/ci/scripts/pin-ci-job-identity.sh`, `.gitlab/ci/scripts/select-gitlab-role-token.sh`, `.gitlab/ci/scripts/install-fullsend-cli.sh`, `.gitlab/ci/scripts/run-poll-job.sh`, `.gitlab/ci/scripts/run-agent-job.sh`, `.gitlab/ci/scripts/checkout-mr-source.sh`, and `.fullsend/config.yaml` (pass `--direct` to push those file changes to the default branch). Variables, secrets, and the `fullsend-poll-state-slash` / `fullsend-poll-state-events` branches are deleted immediately via the API. If you prefer manual removal: delete `.gitlab/ci/fullsend-*.yml`, `.gitlab/ci/scripts/*.sh`, and `.fullsend/config.yaml`, then edit `.gitlab-ci.yml` to remove the fullsend pipeline include entry, the fullsend stages (`poll`, `agent`, and `dispatch` on installs from before the empty dispatch stage was removed), the fullsend workflow rules (the `CI_DEBUG_TRACE` deny-before-admit rule, `schedule`, `api`, and `merge_request_event` on installs from before native MR dispatch was removed), and the `auto_cancel` block if fullsend added it. Only delete `.gitlab-ci.yml` entirely if it contains no non-fullsend configuration. Also delete the two poll-state branches if they are still present. -> **Note:** During install, fullsend sets `workflow.auto_cancel.on_new_commit: none` when an existing, non-empty `.gitlab-ci.yml` already has a `workflow:` block and that key is missing; it does not overwrite an existing value. If that existing block has no `rules:` key, fullsend also adds protected-ref `schedule`/`api` rules, which can stop ordinary push pipelines unless the block already has a matching rule; add a catch-all/push rule (or an explicit `when: always` rule) before installing, or remove the name-only block so fullsend can leave `workflow:` absent. If an existing, non-empty file has no `workflow:` block, fullsend leaves it absent so push-triggered pipelines are not disrupted. For a missing or empty `.gitlab-ci.yml`, fullsend writes a fullsend-owned `workflow:` block with protected-ref `schedule`/`api` rules; later push jobs added to that file likewise need additional `workflow.rules` or an explicit `when: always` rule, or GitLab will skip them. Repos with `on_new_commit: interruptible` (or other non-`none` values) may experience agent pipeline cancellations because fullsend requires `on_new_commit: none` for reliable agent runs. If you see unexpected pipeline cancellations, set `on_new_commit: none` in your `.gitlab-ci.yml` workflow block. +> **Note:** During install, fullsend sets `workflow.auto_cancel.on_new_commit: none` when an existing, non-empty `.gitlab-ci.yml` already has a `workflow:` block and that key is missing; it does not overwrite an existing value. If that existing block has no `rules:` key, fullsend also adds a `CI_DEBUG_TRACE` deny-before-admit rule (`when: never`) followed by the protected-ref `schedule`/`api` rules, which can stop ordinary push pipelines unless the block already has a matching rule; add a catch-all/push rule (or an explicit `when: always` rule) before installing, or remove the name-only block so fullsend can leave `workflow:` absent. If an existing, non-empty file has no `workflow:` block, fullsend leaves it absent so push-triggered pipelines are not disrupted. For a missing or empty `.gitlab-ci.yml`, fullsend writes a fullsend-owned `workflow:` block with the `CI_DEBUG_TRACE` deny rule and protected-ref `schedule`/`api` rules; later push jobs added to that file likewise need additional `workflow.rules` or an explicit `when: always` rule, or GitLab will skip them. Repos with `on_new_commit: interruptible` (or other non-`none` values) may experience agent pipeline cancellations because fullsend requires `on_new_commit: none` for reliable agent runs. If you see unexpected pipeline cancellations, set `on_new_commit: none` in your `.gitlab-ci.yml` workflow block. 2. Delete all CI/CD variables prefixed with `FULLSEND_`. If you set `OPENAI_API_KEY` for the static-key route, delete it yourself too if you want it gone — fullsend never created it (it is a plain CI/CD variable, not `FULLSEND_`-prefixed) and does not delete it as part of uninstall 3. Confirm that project access tokens created for this repo — `fullsend-bot`, `fullsend-poller`, `fullsend-analyst`, `fullsend-coder`, and any `fullsend-role-*` tokens — were revoked. `repos uninstall` revokes them automatically when it can list project access tokens; if uninstall failed on token revocation, retry it, then revoke any that remain from Settings → Access Tokens. A 403 from the token-list API fails uninstall closed rather than being treated as "nothing to revoke" — GitLab returns the identical error for plan-tier feature gating, group-level PAT disablement, and insufficient token permissions, so silently continuing risks leaving tokens live after a reported-successful uninstall. Only a confirmed-gone project (404) is treated as an empty inventory. If the project access token API is genuinely and permanently unavailable for this project (for example, a plan tier that doesn't offer it), retrying will not converge — finish the teardown by revoking any remaining tokens by hand from Settings → Access Tokens, then run `fullsend repos uninstall "$PROJECT_PATH" --manifest-only` to drop the manifest entry once cleanup is confirmed @@ -143,7 +143,7 @@ For organizations that separate GCP and GitHub responsibilities across teams, fu | GCP Admin (Mint) | `fullsend mint status` | Inspect mint state and PEM health | | Fleet Admin | `fullsend repos migrate --project ` | Migrate an org from per-org to per-repo install, generating a `repos.yaml` manifest | -| Platform Admin | `fullsend repos install [repos...]` | Converge repos to desired state: provision new, repair component drift (workflow, thin callers, variables, secrets, pipeline schedules, GitLab poller protected-ref pipeline access), repair scaffold content drift, refresh a declared configuration preset, rewrite a drifted managed `.fullsend/config.yaml`, upgrade refs | +| Platform Admin | `fullsend repos install [repos...]` | Converge repos to desired state: provision new, repair component drift (workflow, thin callers, variables, secrets, pipeline schedules, GitLab poller protected-ref pipeline access, GitLab pipeline-variable override-role inspection — report-only by default), repair scaffold content drift, refresh a declared configuration preset, rewrite a drifted managed `.fullsend/config.yaml`, upgrade refs | | Platform Admin | `fullsend repos uninstall ` | Tear down fullsend from repos and remove from manifest | | Fleet Admin | `fullsend repos status` | Compare manifest against actual per-repo state: detect missing or drifted components, ref drift, scaffold content drift, declared configuration-preset drift, managed `.fullsend/config.yaml` drift, and GitLab `protected-ref-pipeline` drift | | Fleet Admin | `fullsend repos set-default ` | Set or remove a platform-level default in the manifest | diff --git a/docs/guides/getting-started/repo-management.md b/docs/guides/getting-started/repo-management.md index b029a51f5c..ad3f6fff5d 100644 --- a/docs/guides/getting-started/repo-management.md +++ b/docs/guides/getting-started/repo-management.md @@ -317,7 +317,8 @@ Install runs in two phases: separate upgrade PR. Repos whose workflow is already on the default branch are checked for component drift (workflow, thin callers, variables, secrets, pipeline schedules, GitLab poller protected-ref - pipeline access), scaffold content drift, managed `.fullsend/config.yaml` + pipeline access, GitLab pipeline-variable override-role inspection — + report-only by default), scaffold content drift, managed `.fullsend/config.yaml` drift, scaffold ref drift, and declared configuration-preset drift against `.fullsend/config.base.yaml`. Missing or drifted components are repaired automatically; ref updates are committed as PRs (or direct pushes with @@ -389,7 +390,8 @@ fullsend repos status -f repos.yaml --json Run `repos install` to detect and fix component drift (workflow, thin callers, variables, secrets, pipeline schedules, GitLab poller -protected-ref pipeline access), scaffold ref drift, +protected-ref pipeline access, GitLab pipeline-variable override-role +inspection — report-only by default), scaffold ref drift, scaffold content drift, declared configuration-preset drift, and managed `.fullsend/config.yaml` drift across all manifest repos: @@ -407,7 +409,8 @@ The convergence phase checks all components (workflow, thin callers, variables, secrets, pipeline schedules, GitLab poller protected-ref pipeline access — a disabled GitLab schedule is reported as drift and reactivated only when `--reactivate-schedules` is -passed), scaffold content drift (including structural rewrites of +passed; GitLab pipeline-variable override-role inspection, report-only +by default), scaffold content drift (including structural rewrites of `.gitlab/ci/fullsend-pipeline.yml` at an unchanged template ref, and removal of a leftover `.gitlab/ci/fullsend-dispatch.yml` from installs predating #7707), diff --git a/internal/cli/repos.go b/internal/cli/repos.go index aa784374d6..5fdad97b5c 100644 --- a/internal/cli/repos.go +++ b/internal/cli/repos.go @@ -1181,6 +1181,16 @@ func runReposInstall(ctx context.Context, opts *reposInstallConfig) error { roleFailInstalledCount++ } roleFailedRepos = append(roleFailedRepos, item.r) + continue + } + if err := ensureGitLabPipelineVariableOverrideRole(ctx, fc.Client, printer, item.r.Owner, item.r.Repo, opts.dryRun); err != nil { + printer.StepWarn(fmt.Sprintf("[%s/%s] GitLab pipeline-variable override role failed: %v", item.r.Owner, item.r.Repo, err)) + roleFail++ + item.r.Error = err + if item.fresh { + roleFailInstalledCount++ + } + roleFailedRepos = append(roleFailedRepos, item.r) } } } diff --git a/internal/cli/repos_gitlab.go b/internal/cli/repos_gitlab.go index c94876a106..d89d39d5ed 100644 --- a/internal/cli/repos_gitlab.go +++ b/internal/cli/repos_gitlab.go @@ -253,6 +253,35 @@ func ensureGitLabPollerPipelineAccess(ctx context.Context, client forge.Client, return nil } +// ensureGitLabPipelineVariableOverrideRole converges a GitLab project's +// ci_pipeline_variables_minimum_override_role toward owner (#7769). It +// is called for both fresh installs and converge/repair of +// already-installed repos, and is idempotent: an already-owner project +// reports Action "none" every time. Enforcement itself defaults to off +// (see repos.GitLabPipelineVarRestrictionEnforced) pending the poller +// credential follow-up tracked in #7769, so this is safe to call +// unconditionally today — it currently only reports drift. Action +// "report-only" (not-owner, enforcement disabled) is surfaced via +// StepWarn rather than StepDone so a skimming operator does not mistake +// "control not yet applied" for "control applied". +func ensureGitLabPipelineVariableOverrideRole(ctx context.Context, client forge.Client, printer *ui.Printer, owner, repo string, dryRun bool) error { + repoFullName := owner + "/" + repo + res, err := repos.EnsureGitLabPipelineVariableOverrideRole(ctx, client, owner, repo, dryRun) + if err != nil { + printer.StepFail(fmt.Sprintf("[%s] GitLab pipeline-variable override role: %v", repoFullName, err)) + return err + } + if res.Detail != "" { + msg := fmt.Sprintf("[%s] %s", repoFullName, res.Detail) + if res.Action == "report-only" { + printer.StepWarn(msg) + } else { + printer.StepDone(msg) + } + } + return nil +} + type gitlabTokenAdapter struct { c *gitlab.LiveClient } diff --git a/internal/cli/repos_test.go b/internal/cli/repos_test.go index 3f65090a8c..6319628470 100644 --- a/internal/cli/repos_test.go +++ b/internal/cli/repos_test.go @@ -2187,6 +2187,7 @@ func assertGitLabInitMRComplete(t *testing.T, fc *forge.FakeClient) { ".gitlab/ci/fullsend-agent.yml", ".gitlab/ci/fullsend-poll.yml", ".gitlab/ci/scripts/trust-ci-server-ca.sh", + ".gitlab/ci/scripts/pin-ci-job-identity.sh", ".gitlab/ci/scripts/select-gitlab-role-token.sh", ".gitlab/ci/scripts/install-fullsend-cli.sh", ".gitlab/ci/scripts/run-poll-job.sh", diff --git a/internal/repos/converge.go b/internal/repos/converge.go index 87f0a615ba..5277ad8e8c 100644 --- a/internal/repos/converge.go +++ b/internal/repos/converge.go @@ -1418,17 +1418,21 @@ func activatePipelineSchedules(ctx context.Context, client forge.Client, // convergeGitLabRootCIFiles migrates already-enrolled GitLab repos whose // root .gitlab-ci.yml still carries entries that fullsend no longer -// requires: obsolete workflow:rules (the native merge_request_event +// requires — obsolete workflow:rules (the native merge_request_event // dispatch rule removed in #7322) and obsolete stages (the empty -// "dispatch" stage removed in #7337). The root file is user-owned and -// is otherwise only touched by the install merge path (fresh installs) -// and the uninstall unmerge path (teardown) — neither runs during -// upgrade/converge, so without this step an obsolete entry would survive -// convergence forever. StripObsoleteGitLabWorkflowRules only rewrites -// the file when it can prove fullsend owns the workflow block (see -// gitlabCIWorkflowIsFullsendOwned), so merge-path enrollments without -// the fullsend workflow.name are intentionally left for manual cleanup -// rather than risking a user's own MR gate. StripObsoleteGitLabStages +// "dispatch" stage removed in #7337) — and backfills entries a newer +// fullsend version now requires but an older enrollment never received +// (the CI_DEBUG_TRACE deny-before-admit rule added by ADR 0125). The root +// file is user-owned and is otherwise only touched by the install merge +// path (fresh installs, or installs onto a repo HasFullsendEntries judges +// incompletely migrated) and the uninstall unmerge path (teardown) — +// neither runs during upgrade/converge, so without this step a missing or +// obsolete entry would survive convergence forever. +// StripObsoleteGitLabWorkflowRules and MergeMissingGitLabDebugTraceRule +// only rewrite the file when they can prove fullsend owns the workflow +// block (see gitlabCIWorkflowIsFullsendOwned), so merge-path enrollments +// without the fullsend workflow.name are intentionally left for manual +// cleanup rather than risking a user's own configuration. StripObsoleteGitLabStages // gates on the fullsend pipeline include plus a current fullsend stage // (see that function's doc comment). It does not commit — the caller // batches all scaffold file changes into a single atomic commit. @@ -1491,6 +1495,35 @@ func convergeGitLabRootCIFiles(ctx context.Context, } } + merged, debugTraceRuleAdded, mergeErr := MergeMissingGitLabDebugTraceRule(content) + if mergeErr != nil { + actions = append(actions, ComponentAction{ + Component: "gitlab-ci-rules", + Action: "error", + Detail: fmt.Sprintf("error checking .gitlab-ci.yml for missing CI_DEBUG_TRACE workflow rule: %v", mergeErr), + }) + return nil, actions + } + if debugTraceRuleAdded { + content = merged + changed = true + if cfg.DryRun { + actions = append(actions, ComponentAction{ + Component: "gitlab-ci-rules", + Action: "update", + Detail: "would add missing CI_DEBUG_TRACE deny-before-admit workflow rule to .gitlab-ci.yml", + }) + progress(repoFullName, "dry-run", "Would add missing CI_DEBUG_TRACE deny-before-admit workflow rule to .gitlab-ci.yml") + } else { + actions = append(actions, ComponentAction{ + Component: "gitlab-ci-rules", + Action: "update", + Detail: "added missing CI_DEBUG_TRACE deny-before-admit workflow rule to .gitlab-ci.yml", + }) + progress(repoFullName, "repair", "Adding missing CI_DEBUG_TRACE deny-before-admit workflow rule to .gitlab-ci.yml") + } + } + stripped, stagesChanged, stripErr := StripObsoleteGitLabStages(content) if stripErr != nil { actions = append(actions, ComponentAction{ diff --git a/internal/repos/converge_test.go b/internal/repos/converge_test.go index fc116df46a..bb7112217c 100644 --- a/internal/repos/converge_test.go +++ b/internal/repos/converge_test.go @@ -3254,6 +3254,13 @@ workflow: } } +// TestConverge_GitLab_NoObsoleteWorkflowRuleNoAction covers a repo that has +// no obsolete merge_request_event rule but is still missing the +// CI_DEBUG_TRACE deny-before-admit rule (ADR 0125) — the state of a repo +// enrolled via the merge path before that rule existed. convergeGitLabRootCIFiles +// must backfill it via MergeMissingGitLabDebugTraceRule, since the install +// merge path only reruns when HasFullsendEntries is false and the periodic +// converge path otherwise never touches workflow:rules. func TestConverge_GitLab_NoObsoleteWorkflowRuleNoAction(t *testing.T) { fc := newFakeClientForBatch("acme/api") fc.FileContents["acme/api/"+fullsendPipelineInclude] = []byte(" ref: v2.5.0\n") @@ -3271,7 +3278,9 @@ func TestConverge_GitLab_NoObsoleteWorkflowRuleNoAction(t *testing.T) { {ID: 1, Description: "fullsend slash poll", Active: true}, {ID: 2, Description: "fullsend event poll", Active: true}, } - // Already migrated — no obsolete rule present. + // No obsolete merge_request_event rule, but also no CI_DEBUG_TRACE + // rule — this repo enrolled via the merge path before ADR 0125 added + // that guard. fc.FileContents["acme/api/.gitlab-ci.yml"] = []byte(`--- include: - local: '.gitlab/ci/fullsend-pipeline.yml' @@ -3303,6 +3312,185 @@ workflow: InferenceRegion: "us-central1", } + sc := &spyScaffoldCommit{} + result, err := Converge(context.Background(), cfg, newTestClientFactory(fc), sc.fn(), noopProgress) + if err != nil { + t.Fatalf("Converge() error: %v", err) + } + if len(result.Failed()) != 0 { + t.Fatalf("expected 0 failed, got %d: %+v", len(result.Failed()), result.Results[0].Error) + } + + found := false + for _, a := range result.Results[0].Actions { + if a.Component == "gitlab-ci-rules" && a.Action == "update" { + found = true + } + } + if !found { + t.Errorf("expected a gitlab-ci-rules update action backfilling the debug-trace rule, got %+v", result.Results[0].Actions) + } + + sc.mu.Lock() + defer sc.mu.Unlock() + var updated []byte + for _, f := range sc.files { + if f.Path == ".gitlab-ci.yml" { + updated = f.Content + } + } + if updated == nil { + t.Fatalf("expected .gitlab-ci.yml to be committed, got files: %+v", sc.files) + } + s := string(updated) + debugIdx := strings.Index(s, debugTraceDenyRuleIf) + if debugIdx == -1 { + t.Fatalf("expected debug-trace deny rule to be inserted, got:\n%s", s) + } + scheduleIdx := strings.Index(s, `$CI_PIPELINE_SOURCE == "schedule"`) + if scheduleIdx == -1 { + t.Fatalf("expected schedule admit rule to be preserved, got:\n%s", s) + } + if debugIdx >= scheduleIdx { + t.Errorf("expected debug-trace deny rule to precede the schedule admit rule, got:\n%s", s) + } + if !strings.Contains(s, `$CI_PIPELINE_SOURCE == "api"`) { + t.Errorf("expected current api rule to be preserved, got:\n%s", s) + } +} + +// TestConverge_GitLab_DebugTraceRuleBackfillDryRun is the DryRun +// counterpart of TestConverge_GitLab_NoObsoleteWorkflowRuleNoAction: the +// missing CI_DEBUG_TRACE rule is reported as a would-be update, but +// nothing is actually committed. +func TestConverge_GitLab_DebugTraceRuleBackfillDryRun(t *testing.T) { + fc := newFakeClientForBatch("acme/api") + fc.FileContents["acme/api/"+fullsendPipelineInclude] = []byte(" ref: v2.5.0\n") + fc.VariableValues["acme/api/"+forge.VarLastPollAtFast] = "2026-01-01T00:00:00Z" + fc.VariableValues["acme/api/"+forge.VarLastPollAtFull] = "2026-01-01T00:00:00Z" + fc.VariableValues["acme/api/"+forge.VarLabelState] = "{}" + fc.VariableValues["acme/api/"+forge.VarDispatchedKeysFast] = "{}" + fc.VariableValues["acme/api/"+forge.VarDispatchedKeysFull] = "{}" + fc.VariableValues["acme/api/"+forge.VarFailedKeysFast] = "{}" + fc.VariableValues["acme/api/"+forge.VarFailedKeysFull] = "{}" + fc.Secrets["acme/api/"+forge.SecretGCPProjectID] = true + fc.Secrets["acme/api/"+forge.SecretGCPWIFProvider] = true + fc.Secrets["acme/api/"+forge.SecretForgeToken] = true + fc.PipelineSchedules["acme/api"] = []forge.PipelineSchedule{ + {ID: 1, Description: "fullsend slash poll", Active: true}, + {ID: 2, Description: "fullsend event poll", Active: true}, + } + fc.FileContents["acme/api/.gitlab-ci.yml"] = []byte(`--- +include: + - local: '.gitlab/ci/fullsend-pipeline.yml' + +workflow: + name: 'fullsend $CI_PIPELINE_SOURCE $STAGE $RESOURCE_KEY' + auto_cancel: + on_new_commit: none + rules: + - if: $CI_PIPELINE_SOURCE == "schedule" && $CI_COMMIT_REF_PROTECTED == "true" + - if: $CI_PIPELINE_SOURCE == "api" && $CI_COMMIT_REF_PROTECTED == "true" && $STAGE +`) + + m := &Manifest{ + Version: 1, + GitLab: &PlatformConfig{ + URL: "https://gitlab.example.com", + FullsendRef: "v2.5.0", + Repos: []RepoEntry{{Name: "acme/api"}}, + }, + } + cfg := ConvergeConfig{ + Manifest: m, + MaxConcurrency: 4, + Roles: []string{"triage"}, + Direct: true, + InferenceProject: "test-inference", + InferenceProjectNumber: "123456789", + InferenceRegion: "us-central1", + DryRun: true, + } + + sc := &fakeScaffoldCommit{} + result, err := Converge(context.Background(), cfg, newTestClientFactory(fc), sc.fn(), noopProgress) + if err != nil { + t.Fatalf("Converge() error: %v", err) + } + if len(result.Failed()) != 0 { + t.Fatalf("expected 0 failed, got %d: %+v", len(result.Failed()), result.Results[0].Error) + } + + var detail string + for _, a := range result.Results[0].Actions { + if a.Component == "gitlab-ci-rules" && a.Action == "update" { + detail = a.Detail + } + } + if !strings.Contains(detail, "would add") { + t.Errorf("expected a dry-run gitlab-ci-rules update action, got %+v", result.Results[0].Actions) + } + if sc.called { + t.Error("scaffold commit should not be called in dry-run mode") + } +} + +// TestConverge_GitLab_FullyMigratedNoAction covers a repo that already has +// both fullsend's current workflow rules and the CI_DEBUG_TRACE +// deny-before-admit rule — convergeGitLabRootCIFiles must not report any +// gitlab-ci-rules action for it. +func TestConverge_GitLab_FullyMigratedNoAction(t *testing.T) { + fc := newFakeClientForBatch("acme/api") + fc.FileContents["acme/api/"+fullsendPipelineInclude] = []byte(" ref: v2.5.0\n") + fc.VariableValues["acme/api/"+forge.VarLastPollAtFast] = "2026-01-01T00:00:00Z" + fc.VariableValues["acme/api/"+forge.VarLastPollAtFull] = "2026-01-01T00:00:00Z" + fc.VariableValues["acme/api/"+forge.VarLabelState] = "{}" + fc.VariableValues["acme/api/"+forge.VarDispatchedKeysFast] = "{}" + fc.VariableValues["acme/api/"+forge.VarDispatchedKeysFull] = "{}" + fc.VariableValues["acme/api/"+forge.VarFailedKeysFast] = "{}" + fc.VariableValues["acme/api/"+forge.VarFailedKeysFull] = "{}" + fc.Secrets["acme/api/"+forge.SecretGCPProjectID] = true + fc.Secrets["acme/api/"+forge.SecretGCPWIFProvider] = true + fc.Secrets["acme/api/"+forge.SecretForgeToken] = true + fc.PipelineSchedules["acme/api"] = []forge.PipelineSchedule{ + {ID: 1, Description: "fullsend slash poll", Active: true}, + {ID: 2, Description: "fullsend event poll", Active: true}, + } + // Fully migrated — no obsolete rule, and the debug-trace rule is + // already present. + fc.FileContents["acme/api/.gitlab-ci.yml"] = []byte(`--- +include: + - local: '.gitlab/ci/fullsend-pipeline.yml' + +workflow: + name: 'fullsend $CI_PIPELINE_SOURCE $STAGE $RESOURCE_KEY' + auto_cancel: + on_new_commit: none + rules: + - if: ` + debugTraceDenyRuleIf + ` + when: never + - if: $CI_PIPELINE_SOURCE == "schedule" && $CI_COMMIT_REF_PROTECTED == "true" + - if: $CI_PIPELINE_SOURCE == "api" && $CI_COMMIT_REF_PROTECTED == "true" && $STAGE +`) + + m := &Manifest{ + Version: 1, + GitLab: &PlatformConfig{ + URL: "https://gitlab.example.com", + FullsendRef: "v2.5.0", + Repos: []RepoEntry{{Name: "acme/api"}}, + }, + } + cfg := ConvergeConfig{ + Manifest: m, + MaxConcurrency: 4, + Roles: []string{"triage"}, + Direct: true, + InferenceProject: "test-inference", + InferenceProjectNumber: "123456789", + InferenceRegion: "us-central1", + } + sc := &fakeScaffoldCommit{} result, err := Converge(context.Background(), cfg, newTestClientFactory(fc), sc.fn(), noopProgress) if err != nil { @@ -4749,6 +4937,7 @@ func gitlabRequiredScaffoldPaths() []string { ".gitlab/ci/fullsend-agent.yml", ".gitlab/ci/fullsend-poll.yml", ".gitlab/ci/scripts/trust-ci-server-ca.sh", + ".gitlab/ci/scripts/pin-ci-job-identity.sh", ".gitlab/ci/scripts/select-gitlab-role-token.sh", ".gitlab/ci/scripts/install-fullsend-cli.sh", ".gitlab/ci/scripts/run-poll-job.sh", diff --git a/internal/repos/gitlab_pipeline_var_restriction.go b/internal/repos/gitlab_pipeline_var_restriction.go new file mode 100644 index 0000000000..e04c6eb584 --- /dev/null +++ b/internal/repos/gitlab_pipeline_var_restriction.go @@ -0,0 +1,119 @@ +package repos + +import ( + "context" + "errors" + "fmt" + "os" + + "github.com/fullsend-ai/fullsend/internal/forge" +) + +// GitLabPipelineVarRestrictionEnv gates whether install/converge actively +// enforces ci_pipeline_variables_minimum_override_role=owner on enrolled +// GitLab repos (#7769). Defaulting to unset/report-only reflects that +// raising the poller/dispatcher identity to Owner-level access — needed +// so the restriction does not also block the poller's own API-triggered +// dispatch pipeline, see internal/repos/gitlab_pipeline_access.go and +// internal/poll/dispatch.go — is an explicit, not-yet-made credential- +// cost decision (ADR 0125 Status/Caveats). Set to "enforced" once that +// follow-up ships. +const GitLabPipelineVarRestrictionEnv = "FULLSEND_GITLAB_PIPELINE_VAR_RESTRICTION" + +// GitLabPipelineVarRestrictionEnforced reports whether install/converge +// should actively set ci_pipeline_variables_minimum_override_role=owner, +// as opposed to only reporting drift against that target. +func GitLabPipelineVarRestrictionEnforced() bool { + return os.Getenv(GitLabPipelineVarRestrictionEnv) == "enforced" +} + +// GitLabPipelineVarRestrictionResult describes what +// EnsureGitLabPipelineVariableOverrideRole did or would do for a repo. +type GitLabPipelineVarRestrictionResult struct { + // Role is the value observed before any change ("" if GitLab never + // returned one, e.g. an older instance/edition). + Role string + // Action is one of "none", "report-only", "update", "would-update", + // or "unsupported". "none" means the project is already owner. + // "report-only" means the project is not owner but active + // enforcement is disabled, so no write was attempted. + Action string + Detail string +} + +// EnsureGitLabPipelineVariableOverrideRole reads a GitLab project's +// ci_pipeline_variables_minimum_override_role and, when enforcement is +// enabled (GitLabPipelineVarRestrictionEnforced), converges it to +// forge.PipelineVarOverrideOwner. It is idempotent: a project already +// set to owner is left untouched and reported as Action "none", so +// calling this repeatedly (fresh install, converge/repair, or an +// already-correct repo) never issues a redundant write. A project that +// is not owner while enforcement is disabled is reported as Action +// "report-only" (not "none"), so callers can distinguish "control +// already applied" from "control not yet applied" instead of rendering +// both as the same success status. GitHub repos, and any forge client +// that returns forge.ErrNotSupported, report Action "unsupported" and +// are never an error. +// +// Enforcement defaults to off (report-only) because setting this to +// owner also blocks the Developer-level poller/dispatcher's own +// CreatePipeline(variables) call (internal/poll/dispatch.go) until the +// poller identity is raised to Owner — a credential-cost decision ADR +// 0125 and #7769 track as still open, and internal/repos/gitlab_roles.go +// / internal/repos/gitlab_pipeline_access.go are built assuming a +// Developer-level poller throughout. Do not flip +// GitLabPipelineVarRestrictionEnv to "enforced" fleet-wide until that +// follow-up ships; doing so before then breaks the poller's own +// dispatch pipeline on every enrolled repo. +func EnsureGitLabPipelineVariableOverrideRole(ctx context.Context, client forge.Client, owner, repo string, dryRun bool) (GitLabPipelineVarRestrictionResult, error) { + current, err := client.GetPipelineVariablesMinimumOverrideRole(ctx, owner, repo) + if err != nil { + if errors.Is(err, forge.ErrNotSupported) { + return GitLabPipelineVarRestrictionResult{Action: "unsupported"}, nil + } + return GitLabPipelineVarRestrictionResult{}, fmt.Errorf("reading ci_pipeline_variables_minimum_override_role: %w", err) + } + + if current == forge.PipelineVarOverrideOwner { + return GitLabPipelineVarRestrictionResult{ + Role: current, + Action: "none", + Detail: "ci_pipeline_variables_minimum_override_role already owner", + }, nil + } + + if !GitLabPipelineVarRestrictionEnforced() { + return GitLabPipelineVarRestrictionResult{ + Role: current, + Action: "report-only", + Detail: fmt.Sprintf( + "ci_pipeline_variables_minimum_override_role is %s, not owner; enforcement is disabled pending the poller credential follow-up tracked in #7769 (set %s=enforced to converge)", + displayPipelineVarRole(current), GitLabPipelineVarRestrictionEnv), + }, nil + } + + if dryRun { + return GitLabPipelineVarRestrictionResult{ + Role: current, + Action: "would-update", + Detail: fmt.Sprintf("would set ci_pipeline_variables_minimum_override_role to owner (was %s)", displayPipelineVarRole(current)), + }, nil + } + + if err := client.SetPipelineVariablesMinimumOverrideRole(ctx, owner, repo, forge.PipelineVarOverrideOwner); err != nil { + return GitLabPipelineVarRestrictionResult{}, fmt.Errorf("setting ci_pipeline_variables_minimum_override_role to owner: %w", err) + } + + return GitLabPipelineVarRestrictionResult{ + Role: current, + Action: "update", + Detail: fmt.Sprintf("set ci_pipeline_variables_minimum_override_role to owner (was %s)", displayPipelineVarRole(current)), + }, nil +} + +func displayPipelineVarRole(role string) string { + if role == "" { + return "(unset)" + } + return fmt.Sprintf("%q", role) +} diff --git a/internal/repos/gitlab_pipeline_var_restriction_test.go b/internal/repos/gitlab_pipeline_var_restriction_test.go new file mode 100644 index 0000000000..facb3e6f53 --- /dev/null +++ b/internal/repos/gitlab_pipeline_var_restriction_test.go @@ -0,0 +1,148 @@ +package repos + +import ( + "context" + "errors" + "os" + "testing" + + "github.com/fullsend-ai/fullsend/internal/forge" +) + +func TestEnsureGitLabPipelineVariableOverrideRole_AlreadyOwner(t *testing.T) { + // Already-correct scenario: a repo whose GitLab project is already + // set to owner must be left untouched, whether or not enforcement is + // enabled, and reported as Action "none". + fc := forge.NewFakeClient() + fc.PipelineVarOverrideRoles = map[string]string{"acme/widgets": forge.PipelineVarOverrideOwner} + + res, err := EnsureGitLabPipelineVariableOverrideRole(context.Background(), fc, "acme", "widgets", false) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if res.Action != "none" { + t.Errorf("Action = %q, want %q", res.Action, "none") + } + if got := fc.PipelineVarOverrideRoles["acme/widgets"]; got != forge.PipelineVarOverrideOwner { + t.Errorf("role changed to %q, want unchanged owner", got) + } +} + +func TestEnsureGitLabPipelineVariableOverrideRole_FreshInstall_ReportOnlyByDefault(t *testing.T) { + // Fresh install scenario: a newly enrolled repo has no override role + // set yet (empty string, mirroring GitLab's "field absent" case). + // Enforcement defaults to off, so this must report drift without + // calling Set. + t.Setenv(GitLabPipelineVarRestrictionEnv, "") + fc := forge.NewFakeClient() + + res, err := EnsureGitLabPipelineVariableOverrideRole(context.Background(), fc, "acme", "new-repo", false) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if res.Action != "report-only" { + t.Errorf("Action = %q, want %q (report-only default)", res.Action, "report-only") + } + if _, ok := fc.PipelineVarOverrideRoles["acme/new-repo"]; ok { + t.Errorf("Set should not have been called while enforcement is disabled") + } +} + +func TestEnsureGitLabPipelineVariableOverrideRole_ConvergeRepair_Enforced(t *testing.T) { + // Converge/repair scenario: an already-installed repo drifted away + // from (or never had) owner. With enforcement enabled, converge must + // call Set to bring it to owner. + t.Setenv(GitLabPipelineVarRestrictionEnv, "enforced") + fc := forge.NewFakeClient() + fc.PipelineVarOverrideRoles = map[string]string{"acme/widgets": forge.PipelineVarOverrideDeveloper} + + res, err := EnsureGitLabPipelineVariableOverrideRole(context.Background(), fc, "acme", "widgets", false) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if res.Action != "update" { + t.Errorf("Action = %q, want %q", res.Action, "update") + } + if got := fc.PipelineVarOverrideRoles["acme/widgets"]; got != forge.PipelineVarOverrideOwner { + t.Errorf("role = %q, want %q", got, forge.PipelineVarOverrideOwner) + } + + // Idempotent: converging again is a no-op Set-wise. + res2, err := EnsureGitLabPipelineVariableOverrideRole(context.Background(), fc, "acme", "widgets", false) + if err != nil { + t.Fatalf("unexpected error on second converge: %v", err) + } + if res2.Action != "none" { + t.Errorf("second converge Action = %q, want %q (idempotent)", res2.Action, "none") + } +} + +func TestEnsureGitLabPipelineVariableOverrideRole_Enforced_DryRun(t *testing.T) { + t.Setenv(GitLabPipelineVarRestrictionEnv, "enforced") + fc := forge.NewFakeClient() + fc.PipelineVarOverrideRoles = map[string]string{"acme/widgets": forge.PipelineVarOverrideMaintainer} + + res, err := EnsureGitLabPipelineVariableOverrideRole(context.Background(), fc, "acme", "widgets", true) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if res.Action != "would-update" { + t.Errorf("Action = %q, want %q", res.Action, "would-update") + } + if got := fc.PipelineVarOverrideRoles["acme/widgets"]; got != forge.PipelineVarOverrideMaintainer { + t.Errorf("dry run must not write; role = %q, want unchanged maintainer", got) + } +} + +func TestEnsureGitLabPipelineVariableOverrideRole_Unsupported(t *testing.T) { + // Mirrors GitHub's forge.Client implementation, which returns + // forge.ErrNotSupported for both methods. + fc := &forge.FakeClient{ + Errors: map[string]error{"GetPipelineVariablesMinimumOverrideRole": forge.ErrNotSupported}, + } + + res, err := EnsureGitLabPipelineVariableOverrideRole(context.Background(), fc, "acme", "widgets", false) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if res.Action != "unsupported" { + t.Errorf("Action = %q, want %q", res.Action, "unsupported") + } +} + +func TestEnsureGitLabPipelineVariableOverrideRole_GetError(t *testing.T) { + wantErr := errors.New("boom") + fc := &forge.FakeClient{ + Errors: map[string]error{"GetPipelineVariablesMinimumOverrideRole": wantErr}, + } + + _, err := EnsureGitLabPipelineVariableOverrideRole(context.Background(), fc, "acme", "widgets", false) + if err == nil || !errors.Is(err, wantErr) { + t.Errorf("err = %v, want wrapping %v", err, wantErr) + } +} + +func TestGitLabPipelineVarRestrictionEnforced(t *testing.T) { + cases := map[string]bool{ + "": false, + "disabled": false, + "Enforced": false, // exact match only + "enforced": true, + } + for val, want := range cases { + t.Run(val, func(t *testing.T) { + old, hadOld := os.LookupEnv(GitLabPipelineVarRestrictionEnv) + os.Setenv(GitLabPipelineVarRestrictionEnv, val) + defer func() { + if hadOld { + os.Setenv(GitLabPipelineVarRestrictionEnv, old) + } else { + os.Unsetenv(GitLabPipelineVarRestrictionEnv) + } + }() + if got := GitLabPipelineVarRestrictionEnforced(); got != want { + t.Errorf("GitLabPipelineVarRestrictionEnforced() with env=%q = %v, want %v", val, got, want) + } + }) + } +} diff --git a/internal/repos/gitlabci.go b/internal/repos/gitlabci.go index d1a224b565..9e6918abfc 100644 --- a/internal/repos/gitlabci.go +++ b/internal/repos/gitlabci.go @@ -73,12 +73,27 @@ var nonJobTopLevelKeys = map[string]bool{ "cache": true, } +// debugTraceDenyRuleIf is the workflow:rules if: condition that denies a +// debug-trace pipeline before any admit rule (ADR 0125 deny-before-admit). +// It matches the full truthy set gitlab-runner accepts for CI_DEBUG_TRACE +// (Go strconv.ParseBool: "1", "t"/"T", "true"/"TRUE"/"True") via a +// case-insensitive regex, not just an exact "true" — an exact-match +// condition would miss runner-recognized truthy variants and let a +// debug-trace pipeline reach an admit rule. +const debugTraceDenyRuleIf = `$CI_DEBUG_TRACE =~ /^(1|t|true)$/i` + // fullsendWorkflowRules are the workflow:rules entries that fullsend // requires in the root .gitlab-ci.yml. GitLab does not merge workflow: // definitions across includes, so these must be in the root file. // Native merge_request_event dispatch was removed in #7322; all events // route through the cron poller (schedule) and API-triggered agent jobs. +// The CI_DEBUG_TRACE deny rule is first: GitLab evaluates rules +// first-match, so a debug-trace pipeline must not reach an admit rule +// (ADR 0125 deny-before-admit). mergeWorkflowRules prepends When=never +// rules so already-enrolled repos pick up the guard in front of any +// previously merged admit rules. var fullsendWorkflowRules = []workflowRule{ + {If: debugTraceDenyRuleIf, When: "never"}, {If: `$CI_PIPELINE_SOURCE == "schedule" && $CI_COMMIT_REF_PROTECTED == "true"`}, {If: `$CI_PIPELINE_SOURCE == "api" && $CI_COMMIT_REF_PROTECTED == "true" && $STAGE`}, } @@ -95,14 +110,17 @@ var fullsendWorkflowRules = []workflowRule{ // own independently-configured MR gate, so it is left in place — an // acceptable, one-shot leftover since uninstall is a single user action. var unmergeWorkflowRules = []workflowRule{ + {If: debugTraceDenyRuleIf, When: "never"}, {If: `$CI_PIPELINE_SOURCE == "schedule" && $CI_COMMIT_REF_PROTECTED == "true"`}, {If: `$CI_PIPELINE_SOURCE == "api" && $CI_COMMIT_REF_PROTECTED == "true" && $STAGE`}, } // workflowRule represents a single GitLab CI workflow:rules entry -// identified by its if: condition. +// identified by its if: condition. When, if set, is the rule's when: +// value ("never" for deny-before-admit guards). type workflowRule struct { - If string + If string + When string } // obsoleteGitLabWorkflowRules are workflow:rules entries that previous @@ -245,6 +263,71 @@ func gitlabCIWorkflowIsFullsendOwned(workflow *yaml.Node) bool { return nameVal != nil && strings.HasPrefix(nameVal.Value, fullsendWorkflowNamePrefix) } +// MergeMissingGitLabDebugTraceRule adds fullsend's CI_DEBUG_TRACE +// deny-before-admit workflow rule (ADR 0125) to an existing .gitlab-ci.yml +// when it is missing, leaving everything else — including any +// already-present fullsend rules, the workflow name, auto_cancel +// settings, and any user configuration — untouched. +// +// This backfills already-enrolled repos: MergeGitLabCI (and the debug-trace +// rule it adds via fullsendWorkflowRules) only runs on fresh installs — the +// install call site skips it once HasFullsendEntries is true — and the +// periodic converge/upgrade path does not otherwise touch workflow:rules. +// Without this, a repo enrolled before this rule existed would never pick +// it up, leaving a debug-trace pipeline able to reach an admit rule and +// dump secrets at job init. +// +// The rule is only merged when gitlabCIWorkflowIsFullsendOwned finds +// positive evidence that fullsend, not the repo owner, installed the +// workflow block — the same ownership gate StripObsoleteGitLabWorkflowRules +// uses — so a user's own hand-written workflow: block is never modified. +// +// Returns the original content and changed=false when there is nothing to +// merge (no workflow: block, the rule is already present, or fullsend +// ownership of the block can't be established). +func MergeMissingGitLabDebugTraceRule(existing []byte) (result []byte, changed bool, err error) { + if len(bytes.TrimSpace(existing)) == 0 { + return existing, false, nil + } + + var doc yaml.Node + if err := yaml.Unmarshal(existing, &doc); err != nil { + return nil, false, fmt.Errorf("parsing .gitlab-ci.yml: %w", err) + } + if doc.Kind != yaml.DocumentNode || len(doc.Content) == 0 { + return existing, false, nil + } + + root := doc.Content[0] + if root.Kind != yaml.MappingNode { + return existing, false, nil + } + + workflowVal := findMappingValue(root, "workflow") + if workflowVal == nil || workflowVal.Kind != yaml.MappingNode { + return existing, false, nil + } + + // Only touch a workflow: block fullsend can prove it owns — same + // ownership gate as StripObsoleteGitLabWorkflowRules. + if !gitlabCIWorkflowIsFullsendOwned(workflowVal) { + return existing, false, nil + } + + rulesVal := findMappingValue(workflowVal, "rules") + if rulesVal != nil && rulesVal.Kind == yaml.SequenceNode && debugTraceDenyRuleSatisfied(rulesVal.Content) { + return existing, false, nil + } + + mergeWorkflowRules(workflowVal) + + out, marshalErr := marshalNode(&doc) + if marshalErr != nil { + return nil, false, marshalErr + } + return out, true, nil +} + // StripObsoleteGitLabStages removes obsolete fullsend stages (see // obsoleteGitLabStages) from an existing .gitlab-ci.yml, leaving // everything else — including fullsend's current stages, user stages, @@ -1099,7 +1182,7 @@ func UnmergeGitLabCI(existing []byte) ([]byte, error) { // whatever name they already have (or none). This avoids overwriting // user-chosen pipeline names. func newGitLabCI() ([]byte, error) { - content := `--- + const template = `--- include: - local: '.gitlab/ci/fullsend-pipeline.yml' @@ -1108,9 +1191,12 @@ workflow: auto_cancel: on_new_commit: none rules: + - if: %s + when: never - if: $CI_PIPELINE_SOURCE == "schedule" && $CI_COMMIT_REF_PROTECTED == "true" - if: $CI_PIPELINE_SOURCE == "api" && $CI_COMMIT_REF_PROTECTED == "true" && $STAGE ` + content := fmt.Sprintf(template, debugTraceDenyRuleIf) return []byte(content), nil } @@ -1323,8 +1409,55 @@ func mergeAutoCancel(workflow *yaml.Node) { // If on_new_commit exists, leave the user's value alone. } -// mergeWorkflowRules appends fullsend's rules to workflow.rules, -// deduplicating by if: condition. +// debugTraceDenyRuleSatisfied reports whether rules already contains a +// correctly-shaped CI_DEBUG_TRACE deny-before-admit guard: if: equal to +// debugTraceDenyRuleIf, when: equal to "never", and positioned first in +// the list. GitLab's default when: (when omitted) is "always", not +// "never", and rules are evaluated first-match, so a same-if: rule with +// the wrong when:, or one that isn't first, would let a debug-trace +// pipeline reach whatever rule precedes it — that rule is not treated as +// satisfying the guard. +func debugTraceDenyRuleSatisfied(rules []*yaml.Node) bool { + if len(rules) == 0 { + return false + } + first := rules[0] + if first.Kind != yaml.MappingNode { + return false + } + ifVal := findMappingValue(first, "if") + whenVal := findMappingValue(first, "when") + return ifVal != nil && ifVal.Value == debugTraceDenyRuleIf && + whenVal != nil && whenVal.Value == "never" +} + +// removeRuleByIf returns rules with any mapping entry whose if: equals +// ifCond removed. Used when backfilling a corrected deny-before-admit +// rule to replace an existing same-if: rule that has the wrong when: or +// the wrong position, rather than leaving a duplicate if: condition in +// the merged rules list. +func removeRuleByIf(rules []*yaml.Node, ifCond string) []*yaml.Node { + kept := make([]*yaml.Node, 0, len(rules)) + for _, item := range rules { + if item.Kind == yaml.MappingNode { + if v := findMappingValue(item, "if"); v != nil && v.Value == ifCond { + continue + } + } + kept = append(kept, item) + } + return kept +} + +// mergeWorkflowRules merges fullsend's rules into workflow.rules, +// deduplicating by if: condition. Deny-before-admit rules (When=never) +// are prepended so first-match evaluation sees them before any admit +// rule that was already present on an enrolled repo — a same-if: rule +// with the wrong when: or the wrong position does not count as already +// present (see debugTraceDenyRuleSatisfied) and is replaced rather than +// left in place, so the merged list never carries a duplicate if: +// condition for the same guard. Other missing rules are appended as +// before, deduplicated by if: alone. func mergeWorkflowRules(workflow *yaml.Node) { rulesVal := findMappingValue(workflow, "rules") if rulesVal == nil { @@ -1342,7 +1475,8 @@ func mergeWorkflowRules(workflow *yaml.Node) { return } - // Collect existing if: conditions for deduplication. + // Collect existing if: conditions for deduplication of admit rules + // (When == ""). existing := make(map[string]bool) for _, item := range rulesVal.Content { if item.Kind == yaml.MappingNode { @@ -1352,23 +1486,44 @@ func mergeWorkflowRules(workflow *yaml.Node) { } } - // Append missing rules. + var prepend []*yaml.Node + var appendMissing []*yaml.Node for _, r := range fullsendWorkflowRules { - if !existing[r.If] { - rulesVal.Content = append(rulesVal.Content, makeRuleNode(r)) + if r.When == "never" { + if debugTraceDenyRuleSatisfied(rulesVal.Content) { + continue + } + // A same-if: rule with the wrong when: or wrong position is + // superseded by the correctly-shaped rule prepended below, + // rather than left in place as a duplicate if: condition. + rulesVal.Content = removeRuleByIf(rulesVal.Content, r.If) + prepend = append(prepend, makeRuleNode(r)) + continue } + if existing[r.If] { + continue + } + appendMissing = append(appendMissing, makeRuleNode(r)) } + rulesVal.Content = append(prepend, append(rulesVal.Content, appendMissing...)...) } // makeRuleNode creates a YAML mapping node for a workflow rule. func makeRuleNode(r workflowRule) *yaml.Node { + content := []*yaml.Node{ + {Kind: yaml.ScalarNode, Value: "if", Tag: "!!str"}, + {Kind: yaml.ScalarNode, Value: r.If, Tag: "!!str"}, + } + if r.When != "" { + content = append(content, + &yaml.Node{Kind: yaml.ScalarNode, Value: "when", Tag: "!!str"}, + &yaml.Node{Kind: yaml.ScalarNode, Value: r.When, Tag: "!!str"}, + ) + } return &yaml.Node{ - Kind: yaml.MappingNode, - Tag: "!!map", - Content: []*yaml.Node{ - {Kind: yaml.ScalarNode, Value: "if", Tag: "!!str"}, - {Kind: yaml.ScalarNode, Value: r.If, Tag: "!!str"}, - }, + Kind: yaml.MappingNode, + Tag: "!!map", + Content: content, } } diff --git a/internal/repos/gitlabci_test.go b/internal/repos/gitlabci_test.go index ed86277729..3f2f23502a 100644 --- a/internal/repos/gitlabci_test.go +++ b/internal/repos/gitlabci_test.go @@ -22,8 +22,15 @@ func TestMergeGitLabCI_NoExistingFile(t *testing.T) { assert.Contains(t, s, "on_new_commit: none") assert.NotContains(t, s, `$CI_PIPELINE_SOURCE == "merge_request_event"`, "native MR dispatch was removed in #7322") + assert.Contains(t, s, debugTraceDenyRuleIf) + assert.Contains(t, s, "when: never") assert.Contains(t, s, `$CI_PIPELINE_SOURCE == "schedule"`) assert.Contains(t, s, `$CI_PIPELINE_SOURCE == "api"`) + debugIdx := strings.Index(s, debugTraceDenyRuleIf) + scheduleIdx := strings.Index(s, `$CI_PIPELINE_SOURCE == "schedule"`) + require.NotEqual(t, -1, debugIdx) + require.NotEqual(t, -1, scheduleIdx) + assert.Less(t, debugIdx, scheduleIdx, "debug-trace deny must precede schedule admit") } func TestMergeGitLabCI_EmptyFile(t *testing.T) { @@ -144,6 +151,212 @@ workflow: assert.Equal(t, 1, strings.Count(s, `$CI_PIPELINE_SOURCE == "api"`)) } +func TestMergeGitLabCI_PrependsDebugTraceDeny(t *testing.T) { + existing := []byte(`--- +include: + - local: '.gitlab/ci/fullsend-pipeline.yml' + +workflow: + auto_cancel: + on_new_commit: none + rules: + - if: $CI_PIPELINE_SOURCE == "schedule" && $CI_COMMIT_REF_PROTECTED == "true" + - if: $CI_PIPELINE_SOURCE == "api" && $CI_COMMIT_REF_PROTECTED == "true" && $STAGE +`) + result, err := MergeGitLabCI(existing) + require.NoError(t, err) + s := string(result) + + debugIdx := strings.Index(s, debugTraceDenyRuleIf) + require.NotEqual(t, -1, debugIdx, "merge must add the debug-trace deny rule") + scheduleIdx := strings.Index(s, `$CI_PIPELINE_SOURCE == "schedule"`) + require.NotEqual(t, -1, scheduleIdx) + assert.Less(t, debugIdx, scheduleIdx, "debug-trace deny must be prepended before existing admit rules") + assert.Contains(t, s, "when: never") + assert.Equal(t, 1, strings.Count(s, debugTraceDenyRuleIf)) +} + +// --- MergeMissingGitLabDebugTraceRule tests --- + +func TestMergeMissingGitLabDebugTraceRule_AddsMissingRule(t *testing.T) { + existing := []byte(`--- +include: + - local: '.gitlab/ci/fullsend-pipeline.yml' + +workflow: + name: 'fullsend $CI_PIPELINE_SOURCE $STAGE $RESOURCE_KEY' + auto_cancel: + on_new_commit: none + rules: + - if: $CI_PIPELINE_SOURCE == "schedule" && $CI_COMMIT_REF_PROTECTED == "true" + - if: $CI_PIPELINE_SOURCE == "api" && $CI_COMMIT_REF_PROTECTED == "true" && $STAGE +`) + result, changed, err := MergeMissingGitLabDebugTraceRule(existing) + require.NoError(t, err) + require.True(t, changed, "expected the missing debug-trace rule to be added") + s := string(result) + + debugIdx := strings.Index(s, debugTraceDenyRuleIf) + require.NotEqual(t, -1, debugIdx, "expected the debug-trace deny rule to be added") + scheduleIdx := strings.Index(s, `$CI_PIPELINE_SOURCE == "schedule"`) + require.NotEqual(t, -1, scheduleIdx) + assert.Less(t, debugIdx, scheduleIdx, "debug-trace deny must precede existing admit rules") + assert.Contains(t, s, "when: never") + assert.Contains(t, s, `$CI_PIPELINE_SOURCE == "api"`, "existing admit rules must be preserved") +} + +func TestMergeMissingGitLabDebugTraceRule_AlreadyPresentNoAction(t *testing.T) { + existing := []byte(`--- +include: + - local: '.gitlab/ci/fullsend-pipeline.yml' + +workflow: + name: 'fullsend $CI_PIPELINE_SOURCE $STAGE $RESOURCE_KEY' + auto_cancel: + on_new_commit: none + rules: + - if: ` + debugTraceDenyRuleIf + ` + when: never + - if: $CI_PIPELINE_SOURCE == "schedule" && $CI_COMMIT_REF_PROTECTED == "true" + - if: $CI_PIPELINE_SOURCE == "api" && $CI_COMMIT_REF_PROTECTED == "true" && $STAGE +`) + result, changed, err := MergeMissingGitLabDebugTraceRule(existing) + require.NoError(t, err) + assert.False(t, changed, "rule already present — nothing to merge") + assert.Equal(t, existing, result) +} + +func TestMergeMissingGitLabDebugTraceRule_WrongWhenBackfilled(t *testing.T) { + // Same if: condition as the guard, but when: is missing (GitLab + // defaults an omitted when: to "always", not "never"), so the rule + // does nothing to deny a debug-trace pipeline. Must be replaced by a + // correctly-shaped when: never rule, not treated as already present. + existing := []byte(`--- +include: + - local: '.gitlab/ci/fullsend-pipeline.yml' + +workflow: + name: 'fullsend $CI_PIPELINE_SOURCE $STAGE $RESOURCE_KEY' + auto_cancel: + on_new_commit: none + rules: + - if: ` + debugTraceDenyRuleIf + ` + - if: $CI_PIPELINE_SOURCE == "schedule" && $CI_COMMIT_REF_PROTECTED == "true" + - if: $CI_PIPELINE_SOURCE == "api" && $CI_COMMIT_REF_PROTECTED == "true" && $STAGE +`) + result, changed, err := MergeMissingGitLabDebugTraceRule(existing) + require.NoError(t, err) + require.True(t, changed, "wrong when: must be treated as missing, not already present") + s := string(result) + + assert.Equal(t, 1, strings.Count(s, debugTraceDenyRuleIf), "must not leave a duplicate if: condition") + debugIdx := strings.Index(s, debugTraceDenyRuleIf) + scheduleIdx := strings.Index(s, `$CI_PIPELINE_SOURCE == "schedule"`) + require.NotEqual(t, -1, debugIdx) + require.NotEqual(t, -1, scheduleIdx) + assert.Less(t, debugIdx, scheduleIdx, "debug-trace deny must precede admit rules") + assert.Contains(t, s, "when: never") +} + +func TestMergeMissingGitLabDebugTraceRule_WrongOrderBackfilled(t *testing.T) { + // Correctly-shaped if:/when: never rule, but positioned after an + // admit rule — first-match evaluation would let the admit rule win + // for a debug-trace pipeline. Must be repositioned, not treated as + // already present. + existing := []byte(`--- +include: + - local: '.gitlab/ci/fullsend-pipeline.yml' + +workflow: + name: 'fullsend $CI_PIPELINE_SOURCE $STAGE $RESOURCE_KEY' + auto_cancel: + on_new_commit: none + rules: + - if: $CI_PIPELINE_SOURCE == "schedule" && $CI_COMMIT_REF_PROTECTED == "true" + - if: ` + debugTraceDenyRuleIf + ` + when: never + - if: $CI_PIPELINE_SOURCE == "api" && $CI_COMMIT_REF_PROTECTED == "true" && $STAGE +`) + result, changed, err := MergeMissingGitLabDebugTraceRule(existing) + require.NoError(t, err) + require.True(t, changed, "wrong order must be treated as missing, not already present") + s := string(result) + + assert.Equal(t, 1, strings.Count(s, debugTraceDenyRuleIf), "must not leave a duplicate if: condition") + debugIdx := strings.Index(s, debugTraceDenyRuleIf) + scheduleIdx := strings.Index(s, `$CI_PIPELINE_SOURCE == "schedule"`) + require.NotEqual(t, -1, debugIdx) + require.NotEqual(t, -1, scheduleIdx) + assert.Less(t, debugIdx, scheduleIdx, "debug-trace deny must precede admit rules") + assert.Contains(t, s, "when: never") +} + +func TestMergeMissingGitLabDebugTraceRule_NotFullsendOwnedNoAction(t *testing.T) { + // No workflow.name — fullsend can't prove it owns this workflow block, + // so a user's own configuration (missing the rule for its own reasons) + // must not be modified. + existing := []byte(`--- +include: + - local: '.gitlab/ci/fullsend-pipeline.yml' + +workflow: + auto_cancel: + on_new_commit: none + rules: + - if: $CI_PIPELINE_SOURCE == "schedule" && $CI_COMMIT_REF_PROTECTED == "true" + - if: $CI_PIPELINE_SOURCE == "api" && $CI_COMMIT_REF_PROTECTED == "true" && $STAGE +`) + result, changed, err := MergeMissingGitLabDebugTraceRule(existing) + require.NoError(t, err) + assert.False(t, changed) + assert.Equal(t, existing, result) +} + +func TestMergeMissingGitLabDebugTraceRule_NoWorkflowBlockNoAction(t *testing.T) { + existing := []byte(`--- +include: + - local: '.gitlab/ci/fullsend-pipeline.yml' +`) + result, changed, err := MergeMissingGitLabDebugTraceRule(existing) + require.NoError(t, err) + assert.False(t, changed) + assert.Equal(t, existing, result) +} + +func TestMergeMissingGitLabDebugTraceRule_EmptyFileNoAction(t *testing.T) { + result, changed, err := MergeMissingGitLabDebugTraceRule(nil) + require.NoError(t, err) + assert.False(t, changed) + assert.Nil(t, result) +} + +func TestMergeMissingGitLabDebugTraceRule_InvalidYAMLReturnsError(t *testing.T) { + existing := []byte("workflow: [1,2\n") + result, changed, err := MergeMissingGitLabDebugTraceRule(existing) + require.Error(t, err) + assert.False(t, changed) + assert.Nil(t, result) +} + +func TestMergeMissingGitLabDebugTraceRule_CommentOnlyDocumentNoAction(t *testing.T) { + // A comment-only file parses without error but yields no document + // content node — must be treated as nothing-to-merge, not a panic on + // an empty doc.Content slice. + existing := []byte("# just a comment\n") + result, changed, err := MergeMissingGitLabDebugTraceRule(existing) + require.NoError(t, err) + assert.False(t, changed) + assert.Equal(t, existing, result) +} + +func TestMergeMissingGitLabDebugTraceRule_RootNotMappingNoAction(t *testing.T) { + existing := []byte("- a\n- b\n") + result, changed, err := MergeMissingGitLabDebugTraceRule(existing) + require.NoError(t, err) + assert.False(t, changed) + assert.Equal(t, existing, result) +} + func TestMergeGitLabCI_SingleIncludeScalar(t *testing.T) { existing := []byte(`--- include: 'other.yml' @@ -603,6 +816,8 @@ workflow: auto_cancel: on_new_commit: none rules: + - if: ` + debugTraceDenyRuleIf + ` + when: never - if: $CI_PIPELINE_SOURCE == "merge_request_event" - if: $CI_PIPELINE_SOURCE == "schedule" && $CI_COMMIT_REF_PROTECTED == "true" - if: $CI_PIPELINE_SOURCE == "api" && $CI_COMMIT_REF_PROTECTED == "true" && $STAGE @@ -678,12 +893,30 @@ workflow: auto_cancel: on_new_commit: none rules: + - if: ` + debugTraceDenyRuleIf + ` + when: never - if: $CI_PIPELINE_SOURCE == "schedule" && $CI_COMMIT_REF_PROTECTED == "true" - if: $CI_PIPELINE_SOURCE == "api" && $CI_COMMIT_REF_PROTECTED == "true" && $STAGE ` assert.True(t, HasFullsendEntries([]byte(yaml))) } +func TestHasFullsendEntries_MissingDebugTraceDeny(t *testing.T) { + yaml := `--- +include: + - local: '.gitlab/ci/fullsend-pipeline.yml' + +workflow: + auto_cancel: + on_new_commit: none + rules: + - if: $CI_PIPELINE_SOURCE == "schedule" && $CI_COMMIT_REF_PROTECTED == "true" + - if: $CI_PIPELINE_SOURCE == "api" && $CI_COMMIT_REF_PROTECTED == "true" && $STAGE +` + assert.False(t, HasFullsendEntries([]byte(yaml)), + "workflow rules without the debug-trace deny are drift") +} + func TestHasFullsendEntries_MissingWorkflowRules(t *testing.T) { yaml := `--- include: diff --git a/internal/repos/install_test.go b/internal/repos/install_test.go index 3f80dbfd27..8f940b5600 100644 --- a/internal/repos/install_test.go +++ b/internal/repos/install_test.go @@ -1353,6 +1353,7 @@ func TestBuildScaffoldFiles_GitLab(t *testing.T) { ".gitlab/ci/fullsend-agent.yml", ".gitlab/ci/fullsend-poll.yml", ".gitlab/ci/scripts/select-gitlab-role-token.sh", + ".gitlab/ci/scripts/pin-ci-job-identity.sh", ".gitlab/ci/scripts/install-fullsend-cli.sh", ".gitlab/ci/scripts/run-poll-job.sh", ".gitlab/ci/scripts/run-agent-job.sh", diff --git a/internal/repos/remote_scaffold.go b/internal/repos/remote_scaffold.go index 81bfce2e37..f0595dce18 100644 --- a/internal/repos/remote_scaffold.go +++ b/internal/repos/remote_scaffold.go @@ -20,6 +20,7 @@ var scaffoldGitLabPaths = []struct { {"internal/scaffold/fullsend-repo-gitlab/.gitlab/ci/fullsend-agent.yml", ".gitlab/ci/fullsend-agent.yml"}, {"internal/scaffold/fullsend-repo-gitlab/.gitlab/ci/fullsend-poll.yml", ".gitlab/ci/fullsend-poll.yml"}, {"internal/scaffold/fullsend-repo-gitlab/.gitlab/ci/scripts/trust-ci-server-ca.sh", ".gitlab/ci/scripts/trust-ci-server-ca.sh"}, + {"internal/scaffold/fullsend-repo-gitlab/.gitlab/ci/scripts/pin-ci-job-identity.sh", ".gitlab/ci/scripts/pin-ci-job-identity.sh"}, {"internal/scaffold/fullsend-repo-gitlab/.gitlab/ci/scripts/select-gitlab-role-token.sh", ".gitlab/ci/scripts/select-gitlab-role-token.sh"}, {"internal/scaffold/fullsend-repo-gitlab/.gitlab/ci/scripts/install-fullsend-cli.sh", ".gitlab/ci/scripts/install-fullsend-cli.sh"}, {"internal/scaffold/fullsend-repo-gitlab/.gitlab/ci/scripts/run-poll-job.sh", ".gitlab/ci/scripts/run-poll-job.sh"}, diff --git a/internal/repos/remote_scaffold_test.go b/internal/repos/remote_scaffold_test.go index 37884b0b79..09757d3cb8 100644 --- a/internal/repos/remote_scaffold_test.go +++ b/internal/repos/remote_scaffold_test.go @@ -64,6 +64,33 @@ func TestFetchRemoteScaffold_GitLab(t *testing.T) { } } +func TestGitLabScaffoldListsIncludePinCIJobIdentityScript(t *testing.T) { + files, err := scaffold.CollectGitLabPerRepoInstallFiles(nil, nil, "", "") + if err != nil { + t.Fatalf("CollectGitLabPerRepoInstallFiles() error: %v", err) + } + found := false + for _, f := range files { + if f.Path == gitlabPinCIJobIdentityScriptPath { + found = true + break + } + } + if !found { + t.Error("embedded GitLab install files missing pin-ci-job-identity.sh") + } + remoteFound := false + for _, sp := range scaffoldGitLabPaths { + if sp.outPath == gitlabPinCIJobIdentityScriptPath { + remoteFound = true + break + } + } + if !remoteFound { + t.Error("scaffoldGitLabPaths missing pin-ci-job-identity.sh") + } +} + func TestGitLabScaffoldListsIncludeTrustScript(t *testing.T) { files, err := scaffold.CollectGitLabPerRepoInstallFiles(nil, nil, "", "") if err != nil { diff --git a/internal/repos/uninstall.go b/internal/repos/uninstall.go index 74f57b6ec2..b789d22e09 100644 --- a/internal/repos/uninstall.go +++ b/internal/repos/uninstall.go @@ -71,6 +71,7 @@ var gitlabScaffoldPaths = []string{ fullsendDispatchInclude, ".gitlab/ci/fullsend-poll.yml", ".gitlab/ci/scripts/trust-ci-server-ca.sh", + ".gitlab/ci/scripts/pin-ci-job-identity.sh", ".gitlab/ci/scripts/select-gitlab-role-token.sh", ".gitlab/ci/scripts/install-fullsend-cli.sh", ".gitlab/ci/scripts/run-poll-job.sh", @@ -88,6 +89,8 @@ var gitlabRetiredScaffoldPaths = []string{ const gitlabTrustScriptPath = ".gitlab/ci/scripts/trust-ci-server-ca.sh" +const gitlabPinCIJobIdentityScriptPath = ".gitlab/ci/scripts/pin-ci-job-identity.sh" + const gitlabRoleTokenScriptPath = ".gitlab/ci/scripts/select-gitlab-role-token.sh" const gitlabInstallCLIScriptPath = ".gitlab/ci/scripts/install-fullsend-cli.sh" @@ -104,6 +107,7 @@ const gitlabCheckoutMRSourceScriptPath = ".gitlab/ci/scripts/checkout-mr-source. func gitlabAuxiliaryScriptPaths() []string { return []string{ gitlabTrustScriptPath, + gitlabPinCIJobIdentityScriptPath, gitlabRoleTokenScriptPath, gitlabInstallCLIScriptPath, gitlabPollJobScriptPath, diff --git a/internal/repos/uninstall_test.go b/internal/repos/uninstall_test.go index 020c940316..4a04cafe5a 100644 --- a/internal/repos/uninstall_test.go +++ b/internal/repos/uninstall_test.go @@ -649,6 +649,7 @@ func TestUninstall_GitLabExtractedJobScripts_Deleted(t *testing.T) { } for _, path := range []string{ gitlabInstallCLIScriptPath, + gitlabPinCIJobIdentityScriptPath, gitlabPollJobScriptPath, gitlabAgentJobScriptPath, gitlabCheckoutMRSourceScriptPath, diff --git a/internal/scaffold/checkout_mr_source_test.go b/internal/scaffold/checkout_mr_source_test.go index f6eb730321..395f31128f 100644 --- a/internal/scaffold/checkout_mr_source_test.go +++ b/internal/scaffold/checkout_mr_source_test.go @@ -74,6 +74,9 @@ if [ "$1" != "resolve-mr-source" ]; then echo "unexpected fullsend subcommand: $1" >&2 exit 1 fi +if [ -n "${RESOLVE_ARGS_FILE:-}" ]; then + printf '%s\n' "$@" > "${RESOLVE_ARGS_FILE}" +fi if [ -n "${RESOLVE_ERROR:-}" ]; then echo "${RESOLVE_ERROR}" >&2 exit 1 @@ -91,7 +94,7 @@ exit 1 // the given branch/sha/source-project-path. checkout-mr-source.sh // always resolves through this subcommand (fast-path // CI_MERGE_REQUEST_SOURCE_* variables are cross-checked against it or -// against CI_PROJECT_ID/CI_PROJECT_PATH directly, never trusted +// against FULLSEND_PINNED_PROJECT_ID/PATH directly, never trusted // outright), so any test that sets those fast-path variables also // needs a matching stub response or resolution fails first. func stubResolveMRSource(t *testing.T, branch, sha, sourceProjectPath string) (extraEnv []string, pathPrefix string) { @@ -229,6 +232,15 @@ func runCheckoutScript(t *testing.T, env checkoutEnv, extra []string, pathPrefix "CI_SERVER_URL=" + env.serverRoot, "CI_PROJECT_PATH=" + env.targetProjectPath, "CI_PROJECT_ID=" + env.targetID, + // checkout-mr-source.sh now resolves and fetches the MR source + // from FULLSEND_PINNED_* (verified via the CI_JOB_TOKEN job + // record), not CI_PROJECT_PATH/CI_PROJECT_ID/CI_SERVER_URL. In + // this base env the pinned values match the CI_* values above; + // tests proving the CI_* variables are ignored override these + // with distinct, unpinned values instead. + "FULLSEND_PINNED_PROJECT_ID=" + env.targetID, + "FULLSEND_PINNED_PROJECT_PATH=" + env.targetProjectPath, + "FULLSEND_PINNED_GITLAB_URL=" + env.serverRoot, "FULLSEND_JOB_TOKEN=***", "MR_IID=7", "GIT_CONFIG_NOSYSTEM=1", @@ -330,29 +342,60 @@ func TestCheckoutMRSource_CrossProjectSourceRejected(t *testing.T) { // TestCheckoutMRSource_ProjectPathMismatchFailsClosed proves the // untrusted-input fix: an untrusted CI_MERGE_REQUEST_SOURCE_PROJECT_PATH -// that disagrees with CI_PROJECT_PATH must be rejected, not trusted -// outright as the fetch source. +// that disagrees with the pinned project path must be rejected, not +// trusted outright as the fetch source. func TestCheckoutMRSource_ProjectPathMismatchFailsClosed(t *testing.T) { env := seedSameProjectOrigin(t) out, err := runCheckoutScript(t, env, []string{ "CI_MERGE_REQUEST_SOURCE_PROJECT_PATH=missing/project", }, "") require.Error(t, err, "stdout/stderr: %s", out) - assert.Contains(t, out, "does not match this project's CI_PROJECT_PATH") + assert.Contains(t, out, "does not match the pinned project path") } // TestCheckoutMRSource_ProjectIDMismatchFailsClosed mirrors // TestCheckoutMRSource_ProjectPathMismatchFailsClosed for the numeric // fast-path variable: an untrusted CI_MERGE_REQUEST_SOURCE_PROJECT_ID -// that disagrees with CI_PROJECT_ID must be rejected outright, since -// this helper only supports same-project MRs. +// that disagrees with the pinned project id must be rejected outright, +// since this helper only supports same-project MRs. func TestCheckoutMRSource_ProjectIDMismatchFailsClosed(t *testing.T) { env := seedSameProjectOrigin(t) out, err := runCheckoutScript(t, env, []string{ "CI_MERGE_REQUEST_SOURCE_PROJECT_ID=999999", }, "") require.Error(t, err, "stdout/stderr: %s", out) - assert.Contains(t, out, "does not match this project's CI_PROJECT_ID") + assert.Contains(t, out, "does not match the pinned project id") +} + +// TestCheckoutMRSource_ResolvesUsingPinnedProjectAndGitLabURLNotUnpinnedCIVars +// is a regression test for the logic-error finding: CI_PROJECT_PATH, +// CI_PROJECT_ID, and CI_SERVER_URL are ordinary, overridable pipeline +// variables — the same outrankable class ADR 0125 already establishes for +// CI_PROJECT_ID elsewhere. checkout-mr-source.sh must resolve and fetch +// the MR source using FULLSEND_PINNED_PROJECT_PATH/FULLSEND_PINNED_GITLAB_URL +// (verified via the CI_JOB_TOKEN job record) even when those CI_* variables +// point somewhere else entirely. +func TestCheckoutMRSource_ResolvesUsingPinnedProjectAndGitLabURLNotUnpinnedCIVars(t *testing.T) { + env := seedSameProjectOrigin(t) + resolveExtra, pathPrefix := stubResolveMRSource(t, env.sourceBranch, env.sourceSHA, env.sourceProjectPath) + argsFile := filepath.Join(t.TempDir(), "resolve-args.txt") + out, err := runCheckoutScript(t, env, append([]string{ + "RESOLVE_ARGS_FILE=" + argsFile, + "CI_PROJECT_PATH=unpinned/project", + "CI_PROJECT_ID=999999", + "CI_SERVER_URL=https://unpinned.example", + }, resolveExtra...), pathPrefix) + require.NoError(t, err, "stdout/stderr: %s", out) + assert.Contains(t, out, "SOURCE_SHA="+env.sourceSHA) + assert.Contains(t, out, "HEAD="+env.sourceSHA) + + argsRaw, readErr := os.ReadFile(argsFile) + require.NoError(t, readErr) + args := strings.Split(strings.TrimRight(string(argsRaw), "\n"), "\n") + assert.Contains(t, args, env.targetProjectPath) + assert.Contains(t, args, env.serverRoot) + assert.NotContains(t, args, "unpinned/project") + assert.NotContains(t, args, "https://unpinned.example") } // TestCheckoutMRSource_BranchFastPathMismatchFailsClosed proves the @@ -465,6 +508,24 @@ func TestCheckoutMRSource_DebugTraceAborts(t *testing.T) { assert.Contains(t, out, "CI_DEBUG_TRACE enabled") } +// TestCheckoutMRSource_DebugTraceAbortsOnTruthyVariants is the +// checkout-mr-source.sh counterpart of +// TestRunAgentJobScript_DebugTraceAbortsOnTruthyVariants: this script is +// sourced from run-agent-job.sh's fix stage after that broader guard +// already ran, but its own guard must independently match the full +// truthy set gitlab-runner accepts for CI_DEBUG_TRACE, not just an +// exact "true", so it never becomes a weaker leftover check. +func TestCheckoutMRSource_DebugTraceAbortsOnTruthyVariants(t *testing.T) { + for _, v := range []string{"1", "TRUE", "T"} { + t.Run(v, func(t *testing.T) { + env := seedSameProjectOrigin(t) + out, err := runCheckoutScript(t, env, []string{"CI_DEBUG_TRACE=" + v}, "") + require.Error(t, err, "stdout/stderr: %s", out) + assert.Contains(t, out, "CI_DEBUG_TRACE enabled") + }) + } +} + // TestCheckoutMRSource_HTTPSCredentialHelperFetchesWithToken exercises the // oauth2 credential-helper branch against a real HTTPS git server that // requires the FULLSEND_JOB_TOKEN as the basic-auth password, the way diff --git a/internal/scaffold/fullsend-repo-gitlab/.gitlab-ci.yml b/internal/scaffold/fullsend-repo-gitlab/.gitlab-ci.yml index 0a2842e965..bd072ad979 100644 --- a/internal/scaffold/fullsend-repo-gitlab/.gitlab-ci.yml +++ b/internal/scaffold/fullsend-repo-gitlab/.gitlab-ci.yml @@ -10,6 +10,15 @@ workflow: # auto_cancel per pipeline source. on_new_commit: none rules: + # Deny-before-admit (ADR 0125): GitLab evaluates workflow:rules + # first-match, so a debug-trace pipeline must not reach an admit + # rule. Secrets materialize at job init; a script abort is too late. + # Matches the full truthy set gitlab-runner accepts for this + # variable (Go strconv.ParseBool: "1", "t"/"T", "true"/"TRUE"/"True"), + # not just an exact "true" — a case-insensitive regex is required + # because exact-match misses runner-recognized truthy variants. + - if: $CI_DEBUG_TRACE =~ /^(1|t|true)$/i + when: never # Scheduled polling (issues, comments, labels, MR open/merge/close) - if: $CI_PIPELINE_SOURCE == "schedule" && $CI_COMMIT_REF_PROTECTED == "true" # API-triggered pipelines from the cron-poller (dispatched via diff --git a/internal/scaffold/fullsend-repo-gitlab/.gitlab/ci/fullsend-agent.yml b/internal/scaffold/fullsend-repo-gitlab/.gitlab/ci/fullsend-agent.yml index 46cabf03c5..50a3a84a65 100644 --- a/internal/scaffold/fullsend-repo-gitlab/.gitlab/ci/fullsend-agent.yml +++ b/internal/scaffold/fullsend-repo-gitlab/.gitlab/ci/fullsend-agent.yml @@ -39,4 +39,11 @@ stages: expire_in: 1 week resource_group: "fullsend-${STAGE}-${RESOURCE_KEY}" rules: - - if: $STAGE + # Deny-before-admit: GitLab evaluates rules first-match, so a + # debug-trace pipeline must not reach the STAGE admit rule. + # Secrets materialize at job init; a script-level abort is too late. + # Matches the full truthy set gitlab-runner accepts for this + # variable (Go strconv.ParseBool: "1", "t"/"T", "true"/"TRUE"/"True"). + - if: $CI_DEBUG_TRACE =~ /^(1|t|true)$/i + when: never + - if: $STAGE && $CI_DEBUG_TRACE !~ /^(1|t|true)$/i diff --git a/internal/scaffold/fullsend-repo-gitlab/.gitlab/ci/fullsend-pipeline.yml b/internal/scaffold/fullsend-repo-gitlab/.gitlab/ci/fullsend-pipeline.yml index bd363377d7..2e6e4f5643 100644 --- a/internal/scaffold/fullsend-repo-gitlab/.gitlab/ci/fullsend-pipeline.yml +++ b/internal/scaffold/fullsend-repo-gitlab/.gitlab/ci/fullsend-pipeline.yml @@ -18,7 +18,13 @@ include: - local: '.gitlab/ci/fullsend-poll.yml' rules: - - if: $CI_PIPELINE_SOURCE == "schedule" + # Deny-before-admit (ADR 0125): debug-trace must not reach the + # schedule include. Job-level rules repeat this guard. Matches + # the full truthy set gitlab-runner accepts for this variable + # (Go strconv.ParseBool: "1", "t"/"T", "true"/"TRUE"/"True"). + - if: $CI_DEBUG_TRACE =~ /^(1|t|true)$/i + when: never + - if: $CI_PIPELINE_SOURCE == "schedule" && $CI_DEBUG_TRACE !~ /^(1|t|true)$/i # Native merge_request_event dispatch (fullsend-dispatch.yml) was # removed in #7322, and the leftover stub was dropped in #7707. All # events route through the cron poller, which creates standalone @@ -26,7 +32,9 @@ include: # include the agent template via the rule below. - local: '.gitlab/ci/fullsend-agent.yml' rules: - - if: $CI_PIPELINE_SOURCE == "api" && $STAGE + - if: $CI_DEBUG_TRACE =~ /^(1|t|true)$/i + when: never + - if: $CI_PIPELINE_SOURCE == "api" && $STAGE && $CI_DEBUG_TRACE !~ /^(1|t|true)$/i stages: # Native MR dispatch was removed in #7322. The empty 'dispatch' stage diff --git a/internal/scaffold/fullsend-repo-gitlab/.gitlab/ci/fullsend-poll.yml b/internal/scaffold/fullsend-repo-gitlab/.gitlab/ci/fullsend-poll.yml index d8472f7a4b..58d564f092 100644 --- a/internal/scaffold/fullsend-repo-gitlab/.gitlab/ci/fullsend-poll.yml +++ b/internal/scaffold/fullsend-repo-gitlab/.gitlab/ci/fullsend-poll.yml @@ -14,7 +14,14 @@ spec: tags: __CONTROL_RUNNER_TAGS__ resource_group: "fullsend-poll-$FULLSEND_POLL_MODE" rules: - - if: $CI_PIPELINE_SOURCE == "schedule" && $CI_COMMIT_REF_PROTECTED == "true" + # Deny-before-admit: GitLab evaluates rules first-match, so a + # debug-trace pipeline must not reach the schedule admit rule. + # Secrets materialize at job init; a script-level abort is too late. + # Matches the full truthy set gitlab-runner accepts for this + # variable (Go strconv.ParseBool: "1", "t"/"T", "true"/"TRUE"/"True"). + - if: $CI_DEBUG_TRACE =~ /^(1|t|true)$/i + when: never + - if: $CI_PIPELINE_SOURCE == "schedule" && $CI_COMMIT_REF_PROTECTED == "true" && $CI_DEBUG_TRACE !~ /^(1|t|true)$/i variables: FULLSEND_FORGE: "gitlab" FULLSEND_POLL_MODE: "events" diff --git a/internal/scaffold/fullsend-repo-gitlab/.gitlab/ci/scripts/checkout-mr-source.sh b/internal/scaffold/fullsend-repo-gitlab/.gitlab/ci/scripts/checkout-mr-source.sh index 44b5f42e6b..c8b10e352d 100644 --- a/internal/scaffold/fullsend-repo-gitlab/.gitlab/ci/scripts/checkout-mr-source.sh +++ b/internal/scaffold/fullsend-repo-gitlab/.gitlab/ci/scripts/checkout-mr-source.sh @@ -24,14 +24,22 @@ # Same-project MRs only: `resolve-mr-source` fails closed when the # merge request's source lives in a different project (a fork), and # this script re-checks the resolved project path against -# CI_PROJECT_PATH before fetching. fullsend has no supported way to -# check out — or push a fix commit back to — a fork source today: that -# would need push-capable credentials scoped to a project the -# target-project token cannot write to. run-agent-job.sh's fork gate -# already refuses the fix/code stages whenever IS_FORK is true -# (internal/poll/dispatch.go sets IS_FORK from source-project != +# FULLSEND_PINNED_PROJECT_PATH before fetching. fullsend has no +# supported way to check out — or push a fix commit back to — a fork +# source today: that would need push-capable credentials scoped to a +# project the target-project token cannot write to. run-agent-job.sh's +# fork gate already refuses the fix/code stages whenever IS_FORK is +# true (internal/poll/dispatch.go sets IS_FORK from source-project != # target-project), so this script's same-project check is defense in # depth, not the primary control. +# +# Project/host identity for the resolve call and the fetch URL comes +# from FULLSEND_PINNED_PROJECT_PATH / FULLSEND_PINNED_GITLAB_URL +# (exported by pin-ci-job-identity.sh, verified via the CI_JOB_TOKEN +# job record), not the overridable CI_PROJECT_PATH / CI_SERVER_URL +# pipeline variables — same outrankable class as CI_PROJECT_ID +# (ADR 0125). This script always runs after run-agent-job.sh sources +# pin-ci-job-identity.sh, so the pinned variables are always set. fullsend_validate_mr_source_ref() { _fs_kind=$1 @@ -115,10 +123,18 @@ fullsend_git_fetch_mr_source() { } fullsend_checkout_mr_source() { - if [ "${CI_DEBUG_TRACE:-}" = "true" ]; then - echo "ERROR: CI_DEBUG_TRACE enabled — aborting to protect secrets" >&2 - return 1 - fi + # Matches the full truthy set gitlab-runner accepts for this variable + # (Go strconv.ParseBool: "1", "t"/"T", "true"/"TRUE"/"True"), not just + # an exact "true" — same guard as run-agent-job.sh / run-poll-job.sh. + # This script only runs sourced from run-agent-job.sh's fix stage, + # after that broader guard already ran, but keeps its own guard in + # lockstep so it never becomes a weaker independent check. + case "${CI_DEBUG_TRACE:-}" in + 1|[tT]|[tT][rR][uU][eE]) + echo "ERROR: CI_DEBUG_TRACE enabled — aborting to protect secrets" >&2 + return 1 + ;; + esac case "${MR_IID:-}" in ''|0|*[!0-9]*) @@ -132,14 +148,14 @@ fullsend_checkout_mr_source() { return 1 fi - case "${CI_PROJECT_ID:-}" in + case "${FULLSEND_PINNED_PROJECT_ID:-}" in ''|*[!0-9]*) - echo "ERROR: CI_PROJECT_ID is required to resolve merge request !${MR_IID}" >&2 + echo "ERROR: FULLSEND_PINNED_PROJECT_ID is required to resolve merge request !${MR_IID}" >&2 return 1 ;; esac - if [ -z "${CI_PROJECT_PATH:-}" ]; then - echo "ERROR: CI_PROJECT_PATH is required to resolve merge request !${MR_IID}" >&2 + if [ -z "${FULLSEND_PINNED_PROJECT_PATH:-}" ]; then + echo "ERROR: FULLSEND_PINNED_PROJECT_PATH is required to resolve merge request !${MR_IID}" >&2 return 1 fi if [ -z "${FULLSEND_JOB_TOKEN:-}" ]; then @@ -147,10 +163,10 @@ fullsend_checkout_mr_source() { return 1 fi - _FS_SERVER_URL="${CI_SERVER_URL:-}" + _FS_SERVER_URL="${FULLSEND_PINNED_GITLAB_URL:-}" _FS_SERVER_URL="${_FS_SERVER_URL%/}" if [ -z "${_FS_SERVER_URL}" ]; then - echo "ERROR: CI_SERVER_URL is required to fetch the MR source revision" >&2 + echo "ERROR: FULLSEND_PINNED_GITLAB_URL is required to fetch the MR source revision" >&2 return 1 fi @@ -162,8 +178,9 @@ fullsend_checkout_mr_source() { # is always invoked and is the sole source of truth for the branch and # SHA; a fast-path value that disagrees with it fails closed instead of # being trusted. The two project-identity fast-path variables are - # cross-checked directly against CI_PROJECT_ID/CI_PROJECT_PATH (both - # trustworthy, GitLab-set values for this job) rather than against a + # cross-checked directly against FULLSEND_PINNED_PROJECT_ID/PATH + # (verified via the CI_JOB_TOKEN job record) rather than the + # overridable CI_PROJECT_ID/CI_PROJECT_PATH pipeline variables or a # second API call, because this helper only supports same-project MRs # (see the module comment above). _FS_FASTPATH_BRANCH="${CI_MERGE_REQUEST_SOURCE_BRANCH_NAME:-}" @@ -171,13 +188,13 @@ fullsend_checkout_mr_source() { _FS_FASTPATH_PROJECT_ID="${CI_MERGE_REQUEST_SOURCE_PROJECT_ID:-}" _FS_FASTPATH_PROJECT_PATH="${CI_MERGE_REQUEST_SOURCE_PROJECT_PATH:-}" - if [ -n "${_FS_FASTPATH_PROJECT_ID}" ] && [ "${_FS_FASTPATH_PROJECT_ID}" != "${CI_PROJECT_ID}" ]; then - echo "ERROR: CI_MERGE_REQUEST_SOURCE_PROJECT_ID '${_FS_FASTPATH_PROJECT_ID}' does not match this project's CI_PROJECT_ID '${CI_PROJECT_ID}' — cross-project MR source checkout is not supported" >&2 + if [ -n "${_FS_FASTPATH_PROJECT_ID}" ] && [ "${_FS_FASTPATH_PROJECT_ID}" != "${FULLSEND_PINNED_PROJECT_ID}" ]; then + echo "ERROR: CI_MERGE_REQUEST_SOURCE_PROJECT_ID '${_FS_FASTPATH_PROJECT_ID}' does not match the pinned project id '${FULLSEND_PINNED_PROJECT_ID}' — cross-project MR source checkout is not supported" >&2 unset _FS_FASTPATH_BRANCH _FS_FASTPATH_SHA _FS_FASTPATH_PROJECT_ID _FS_FASTPATH_PROJECT_PATH return 1 fi - if [ -n "${_FS_FASTPATH_PROJECT_PATH}" ] && [ "${_FS_FASTPATH_PROJECT_PATH}" != "${CI_PROJECT_PATH}" ]; then - echo "ERROR: CI_MERGE_REQUEST_SOURCE_PROJECT_PATH '${_FS_FASTPATH_PROJECT_PATH}' does not match this project's CI_PROJECT_PATH '${CI_PROJECT_PATH}' — cross-project MR source checkout is not supported" >&2 + if [ -n "${_FS_FASTPATH_PROJECT_PATH}" ] && [ "${_FS_FASTPATH_PROJECT_PATH}" != "${FULLSEND_PINNED_PROJECT_PATH}" ]; then + echo "ERROR: CI_MERGE_REQUEST_SOURCE_PROJECT_PATH '${_FS_FASTPATH_PROJECT_PATH}' does not match the pinned project path '${FULLSEND_PINNED_PROJECT_PATH}' — cross-project MR source checkout is not supported" >&2 unset _FS_FASTPATH_BRANCH _FS_FASTPATH_SHA _FS_FASTPATH_PROJECT_ID _FS_FASTPATH_PROJECT_PATH return 1 fi @@ -188,7 +205,7 @@ fullsend_checkout_mr_source() { # an argv flag would additionally expose it via /proc//cmdline, # `ps`, and execve audit logs. if ! _FS_RESOLVED=$(fullsend resolve-mr-source \ - --project "${CI_PROJECT_PATH}" \ + --project "${FULLSEND_PINNED_PROJECT_PATH}" \ --mr-iid "${MR_IID}" \ --gitlab-url "${_FS_SERVER_URL}"); then echo "ERROR: cannot resolve merge request !${MR_IID} — refusing to run the fix agent without the source revision" >&2 @@ -231,8 +248,8 @@ fullsend_checkout_mr_source() { # different project, but re-checking here means a bug in that # resolver can never silently widen this script to fetch from — or # construct forge credentials for — an unexpected remote. - if [ "${SOURCE_PROJECT_PATH}" != "${CI_PROJECT_PATH}" ]; then - echo "ERROR: resolved source project '${SOURCE_PROJECT_PATH}' does not match this project '${CI_PROJECT_PATH}' — cross-project MR source checkout is not supported" >&2 + if [ "${SOURCE_PROJECT_PATH}" != "${FULLSEND_PINNED_PROJECT_PATH}" ]; then + echo "ERROR: resolved source project '${SOURCE_PROJECT_PATH}' does not match the pinned project '${FULLSEND_PINNED_PROJECT_PATH}' — cross-project MR source checkout is not supported" >&2 unset _FS_FASTPATH_BRANCH _FS_FASTPATH_SHA _FS_FASTPATH_PROJECT_ID _FS_FASTPATH_PROJECT_PATH return 1 fi @@ -269,8 +286,9 @@ fullsend_checkout_mr_source() { # the helper via the _FS_CRED_HOST environment variable at fetch # invocation time — the same way _FS_GIT_PASSWORD is passed — # rather than interpolated into the generated script's source, so - # a shell metacharacter (e.g. a stray quote) in CI_SERVER_URL - # cannot break out of the helper's source text and execute. + # a shell metacharacter (e.g. a stray quote) in + # FULLSEND_PINNED_GITLAB_URL cannot break out of the helper's + # source text and execute. _FS_CRED_HOST="${_FS_SOURCE_FETCH_URL#*://}" _FS_CRED_HOST="${_FS_CRED_HOST#*@}" _FS_CRED_HOST="${_FS_CRED_HOST%%/*}" diff --git a/internal/scaffold/fullsend-repo-gitlab/.gitlab/ci/scripts/pin-ci-job-identity.sh b/internal/scaffold/fullsend-repo-gitlab/.gitlab/ci/scripts/pin-ci-job-identity.sh new file mode 100644 index 0000000000..959a50d9fb --- /dev/null +++ b/internal/scaffold/fullsend-repo-gitlab/.gitlab/ci/scripts/pin-ci-job-identity.sh @@ -0,0 +1,348 @@ +#!/usr/bin/env bash +# pin-ci-job-identity.sh — Pin job identity to the CI_JOB_TOKEN job record. +# +# Source this file (do not execute it) after the CI_DEBUG_TRACE guard and +# before any PAT-bearing call or admit logic. The dispatcher job (#7771) +# reuses the same helper with FULLSEND_ADMIT_SOURCE=trigger. +# +# Required caller-set input: +# FULLSEND_ADMIT_SOURCE exactly one of api|schedule|trigger +# (disjoint per-job allowlists; never a union) +# +# Exports on success: +# FULLSEND_PINNED_PROJECT_ID +# FULLSEND_PINNED_PIPELINE_ID +# FULLSEND_PINNED_REF +# FULLSEND_PINNED_PIPELINE_SOURCE +# FULLSEND_PINNED_PIPELINE_RESPONSE +# FULLSEND_PINNED_PROJECT_PATH (path_with_namespace, e.g. group/project) +# FULLSEND_PINNED_GITLAB_URL (validated API root with /api/v4 stripped) +# +# FULLSEND_PINNED_PROJECT_PATH / FULLSEND_PINNED_GITLAB_URL exist so +# callers can pass the fullsend CLI's --project/--status-repo and +# --gitlab-url flags the pinned job-record identity, instead of the +# overridable CI_PROJECT_PATH / FULLSEND_GITLAB_URL / CI_SERVER_URL +# pipeline variables (same outrankable class as CI_PROJECT_ID, ADR +# 0125). See run-poll-job.sh and run-agent-job.sh for that reuse. +# +# Trust model (ADR 0125): +# The GitLab-side pipeline-variable restriction +# (ci_pipeline_variables_minimum_override_role=owner, with the +# poller/dispatcher on an Owner-role PAT and the webhook trigger +# token minted under a sub-Owner identity) is the REQUIRED control +# that stops a trigger-token holder from outranking CI_JOB_TOKEN, +# CI_API_V4_URL, and dispatch secrets. This repo's install/converge +# path (internal/repos/gitlab_pipeline_var_restriction.go) reads and +# can converge that setting, but active enforcement defaults to +# report-only (an opt-in environment variable switches it to enforced) +# until the poller/dispatcher identity is separately raised to Owner — +# see that file and docs/contributing/gitlab-role-credentials.md for +# the open credential-cost decision tracked in #7769. This helper is +# defense-in-depth: it +# takes project, pipeline, and ref from GET /api/v4/job (the job +# that owns the supplied token) rather than from the overridable +# CI_PROJECT_ID / CI_PIPELINE_ID / CI_COMMIT_REF_PROTECTED env +# vars, and it fails closed unless the server-side .source equals +# FULLSEND_ADMIT_SOURCE and the job ref is the project's +# protected default branch. +# +# GET /api/v4/job still needs a bootstrap URL (CI_API_V4_URL). +# That URL is in the same overridable class; the restriction is +# what makes the bootstrap trustworthy. An invalid CI_JOB_TOKEN +# override fails closed here (the lookup 401s/404s). A valid +# foreign job token would mis-resolve the pin to that foreign +# job — residual, closed by the restriction rather than by this +# script. Live verification of the valid-foreign-token case is +# tracked as follow-up once a second job token can be minted. +# +# Transport: gate curls ignore trigger-influenced proxy settings +# (--noproxy '*', proxy env stripped), disable curlrc (-q, CURLRC/ +# CURL_HOME stripped), disable URL brace/bracket-range globbing +# (--globoff, plus a CI_API_V4_URL character check below) so a +# crafted API root cannot fan a single call out to an attacker host, +# and pin CA from trust-ci-server-ca.sh (runner-provisioned +# CI_SERVER_TLS_CA_FILE), after unsetting SSL_CERT_FILE/GIT_SSL_CAINFO/ +# CURL_CA_BUNDLE/REQUESTS_CA_BUNDLE/NODE_EXTRA_CA_CERTS/SSL_CERT_DIR/ +# SSLKEYLOGFILE (also stripped per-call by fullsend_gate_curl) so a +# trigger-supplied CA/keylog override cannot stick from job init. Only +# JOB-TOKEN is sent on the identity-pin +# calls this script makes below. A caller's `-H "JOB-TOKEN: ..."` or +# `-H "PRIVATE-TOKEN: ..."` argument is rewritten to `-H @tempfile` +# before exec'ing curl, so the token value itself never appears in +# curl's argv (/proc//cmdline, `ps`, execve audit logs). +# fullsend_gate_curl itself is transport-only (it does not choose +# which auth header to send): once this file is sourced, the function +# stays defined in the caller's shell, and callers reuse it for their +# own PAT-bearing calls after the pin succeeds so those calls get the +# same proxy-stripping, CA-pinning, and argv-hygiene protections. See +# run-agent-job.sh and run-poll-job.sh for that reuse pattern. + +fullsend_gate_curl() { + # Diagnostic output must stay on stderr: callers capture stdout. + # + # -q (--disable) must be curl's first argument: it makes curl ignore + # curlrc, so a trigger-influenced CURLRC/CURL_HOME cannot inject + # extra options (e.g. a proxy or a different CA) into these calls. + # --globoff disables curl's URL brace/bracket-range globbing so a + # CI_API_V4_URL such as https://{attacker.example,gitlab.example}/api/v4 + # cannot make a single call fan out to an attacker-chosen host with + # the JOB-TOKEN/PRIVATE-TOKEN header attached. + _fs_curl_args=( + -q + --silent --show-error --fail + --retry 3 --retry-delay 2 --retry-all-errors + --noproxy '*' --proto '=https' --max-redirs 0 --globoff + ) + if [ -n "${CURL_CA_BUNDLE:-}" ] && [ -f "${CURL_CA_BUNDLE}" ]; then + _fs_curl_args+=(--cacert "${CURL_CA_BUNDLE}") + fi + + # Rewrite a caller's `-H "JOB-TOKEN: ..."` / `-H "PRIVATE-TOKEN: ..."` + # into `-H @tempfile` (curl >=7.55 loads headers from a file with this + # syntax) so the token itself never appears in curl's argv — visible + # via /proc//cmdline, `ps`, or execve audit logs otherwise. Every + # caller keeps passing the header the same way; this rewrite is + # transparent so the auth-header hygiene lives in one place instead of + # needing to be repeated at each call site. + local _fs_header_file="" + local -a _fs_call_args=() + local _fs_arg _fs_next + while [ "$#" -gt 0 ]; do + _fs_arg=$1 + if [ "${_fs_arg}" = "-H" ] && [ "$#" -gt 1 ]; then + _fs_next=$2 + case "${_fs_next}" in + 'JOB-TOKEN: '*|'PRIVATE-TOKEN: '*) + _fs_header_file=$(mktemp) + chmod 600 "${_fs_header_file}" + printf '%s\n' "${_fs_next}" > "${_fs_header_file}" + _fs_call_args+=(-H "@${_fs_header_file}") + shift 2 + continue + ;; + esac + fi + _fs_call_args+=("${_fs_arg}") + shift + done + + local _fs_gate_curl_status + env -u HTTP_PROXY -u HTTPS_PROXY -u ALL_PROXY \ + -u http_proxy -u https_proxy -u all_proxy \ + -u CURLRC -u CURL_HOME \ + -u SSL_CERT_DIR -u SSLKEYLOGFILE \ + curl "${_fs_curl_args[@]}" "${_fs_call_args[@]}" + _fs_gate_curl_status=$? + [ -n "${_fs_header_file}" ] && rm -f "${_fs_header_file}" + unset _fs_curl_args _fs_call_args _fs_header_file _fs_arg _fs_next + return "${_fs_gate_curl_status}" +} + +fullsend_pin_ci_job_identity() { + case "${FULLSEND_ADMIT_SOURCE:-}" in + api|schedule|trigger) ;; + *) + echo "ERROR: FULLSEND_ADMIT_SOURCE must be 'api', 'schedule', or 'trigger' (disjoint per-job allowlist), got '${FULLSEND_ADMIT_SOURCE:-}'" >&2 + return 1 + ;; + esac + + if [ -z "${CI_JOB_TOKEN:-}" ]; then + echo "ERROR: CI_JOB_TOKEN is empty — cannot pin job identity (fail-closed)" >&2 + return 1 + fi + + _fs_api="${CI_API_V4_URL:-}" + _fs_api="${_fs_api%/}" + case "${_fs_api}" in + https://*/api/v4) ;; + *) + echo "ERROR: CI_API_V4_URL is not an https GitLab API root — refusing to bootstrap the identity pin (fail-closed)" >&2 + unset _fs_api + return 1 + ;; + esac + # The case glob above only requires an https://*/api/v4 shape: bash's + # `*` matches any characters, including brace/bracket-range syntax + # (e.g. https://{attacker.example,gitlab.example}/api/v4 or + # https://gitlab[1-2].example/api/v4) that curl expands into multiple + # requests by default, and userinfo (https://real-host@attacker/api/v4, + # where curl actually connects to "attacker"). --globoff above closes + # the expansion path; this check closes it at validation time too and + # rejects userinfo and stray whitespace/quote/angle-bracket characters + # that have no legitimate place in a GitLab API root. + # + # A bracketed IPv6 literal host (https://[2001:db8::1]/api/v4, or with + # a :port) legitimately contains '[' and ']', so it is allow-listed + # here before the general bracket ban below — --globoff already + # neutralizes curl's own range-expansion behavior for it, so admitting + # it does not reopen the fan-out vector the general ban closes. + _fs_ipv6_literal=0 + _fs_host_and_port="${_fs_api#https://}" + _fs_host_and_port="${_fs_host_and_port%/api/v4}" + if [[ "${_fs_host_and_port}" =~ ^\[[0-9A-Fa-f:]+\](:[0-9]+)?$ ]]; then + _fs_ipv6_literal=1 + fi + unset _fs_host_and_port + if [ "${_fs_ipv6_literal}" -ne 1 ]; then + case "${_fs_api}" in + *[\{\}\[\]\<\>\"\'@]*|*[$' \t\n\r']*) + echo "ERROR: CI_API_V4_URL contains characters not permitted in a GitLab API root (braces, brackets, angle brackets, quotes, '@', or whitespace) — refusing to bootstrap the identity pin (fail-closed)" >&2 + unset _fs_api _fs_ipv6_literal + return 1 + ;; + esac + fi + unset _fs_ipv6_literal + + # Force a fresh CA-trust pass so a trigger-supplied CURL_CA_BUNDLE + # or FULLSEND_CI_SERVER_CA_TRUSTED=1 cannot stick from job init. + unset _fullsend_trust_ci_server_ca_done + unset FULLSEND_CI_SERVER_CA_TRUSTED + unset SSL_CERT_FILE GIT_SSL_CAINFO CURL_CA_BUNDLE REQUESTS_CA_BUNDLE NODE_EXTRA_CA_CERTS + unset SSL_CERT_DIR SSLKEYLOGFILE + _fs_trust="${CI_PROJECT_DIR:-.}/.gitlab/ci/scripts/trust-ci-server-ca.sh" + if [ ! -f "${_fs_trust}" ]; then + echo "ERROR: ${_fs_trust} is missing — cannot pin transport for the identity gate (fail-closed)" >&2 + unset _fs_api _fs_trust + return 1 + fi + # shellcheck disable=SC1090 + . "${_fs_trust}" + + _fs_job_json="" + if ! _fs_job_json=$(fullsend_gate_curl \ + -H "JOB-TOKEN: ${CI_JOB_TOKEN}" \ + "${_fs_api}/job"); then + echo "ERROR: CI_JOB_TOKEN job lookup failed — aborting (fail-closed)" >&2 + unset _fs_api _fs_trust _fs_job_json + return 1 + fi + + FULLSEND_PINNED_PROJECT_ID=$(printf '%s' "${_fs_job_json}" | jq -r '.pipeline.project_id // empty') + FULLSEND_PINNED_PIPELINE_ID=$(printf '%s' "${_fs_job_json}" | jq -r '.pipeline.id // empty') + FULLSEND_PINNED_REF=$(printf '%s' "${_fs_job_json}" | jq -r '.ref // .pipeline.ref // empty') + unset _fs_job_json + + case "${FULLSEND_PINNED_PROJECT_ID}" in + ''|*[!0-9]*) + echo "ERROR: CI_JOB_TOKEN job record is missing a numeric pipeline.project_id — aborting (fail-closed)" >&2 + unset _fs_api _fs_trust FULLSEND_PINNED_PROJECT_ID FULLSEND_PINNED_PIPELINE_ID FULLSEND_PINNED_REF + return 1 + ;; + esac + case "${FULLSEND_PINNED_PIPELINE_ID}" in + ''|*[!0-9]*) + echo "ERROR: CI_JOB_TOKEN job record is missing a numeric pipeline.id — aborting (fail-closed)" >&2 + unset _fs_api _fs_trust FULLSEND_PINNED_PROJECT_ID FULLSEND_PINNED_PIPELINE_ID FULLSEND_PINNED_REF + return 1 + ;; + esac + case "${FULLSEND_PINNED_REF}" in + ''|*[$'\n\r']*|*'..'*|*' '*|*$'\t'*) + echo "ERROR: CI_JOB_TOKEN job record ref is empty or unsafe — aborting (fail-closed)" >&2 + unset _fs_api _fs_trust FULLSEND_PINNED_PROJECT_ID FULLSEND_PINNED_PIPELINE_ID FULLSEND_PINNED_REF + return 1 + ;; + esac + FULLSEND_PINNED_REF="${FULLSEND_PINNED_REF#refs/heads/}" + + _fs_project_json="" + if ! _fs_project_json=$(fullsend_gate_curl \ + -H "JOB-TOKEN: ${CI_JOB_TOKEN}" \ + "${_fs_api}/projects/${FULLSEND_PINNED_PROJECT_ID}"); then + echo "ERROR: cannot read pinned project ${FULLSEND_PINNED_PROJECT_ID} — aborting (fail-closed)" >&2 + unset _fs_api _fs_trust _fs_project_json FULLSEND_PINNED_PROJECT_ID FULLSEND_PINNED_PIPELINE_ID FULLSEND_PINNED_REF + return 1 + fi + _fs_default_branch=$(printf '%s' "${_fs_project_json}" | jq -r '.default_branch // empty') + FULLSEND_PINNED_PROJECT_PATH=$(printf '%s' "${_fs_project_json}" | jq -r '.path_with_namespace // empty') + unset _fs_project_json + _fs_default_branch="${_fs_default_branch#refs/heads/}" + if [ -z "${_fs_default_branch}" ]; then + echo "ERROR: pinned project has no default_branch — aborting (fail-closed)" >&2 + unset _fs_api _fs_trust _fs_default_branch FULLSEND_PINNED_PROJECT_ID FULLSEND_PINNED_PIPELINE_ID FULLSEND_PINNED_REF FULLSEND_PINNED_PROJECT_PATH + return 1 + fi + if [ -z "${FULLSEND_PINNED_PROJECT_PATH}" ]; then + echo "ERROR: pinned project has no path_with_namespace — aborting (fail-closed)" >&2 + unset _fs_api _fs_trust _fs_default_branch FULLSEND_PINNED_PROJECT_ID FULLSEND_PINNED_PIPELINE_ID FULLSEND_PINNED_REF FULLSEND_PINNED_PROJECT_PATH + return 1 + fi + if [ "${FULLSEND_PINNED_REF}" != "${_fs_default_branch}" ]; then + echo "ERROR: job ref '${FULLSEND_PINNED_REF}' is not the enrolled default branch '${_fs_default_branch}' — refusing a protected-but-non-default ref (fail-closed)" >&2 + unset _fs_api _fs_trust _fs_default_branch FULLSEND_PINNED_PROJECT_ID FULLSEND_PINNED_PIPELINE_ID FULLSEND_PINNED_REF FULLSEND_PINNED_PROJECT_PATH + return 1 + fi + + # GET /projects/:id/repository/branches/:branch is a same-project call + # (FULLSEND_PINNED_PROJECT_ID is the project_id of the pipeline that owns + # the supplied CI_JOB_TOKEN, from GET /job above) rather than a + # cross-project one. GitLab's CI/CD job token *scope* allowlist restricts + # only cross-project access; it has never gated a token's calls into its + # own project. GitLab's fine-grained job-token permissions documentation + # (introduced for cross-project grants, GA in 18.3) separately lists + # "GET /projects/:id/repository/branches" under the read_repository + # policy, the same family as this single-branch lookup. Both facts + # support CI_JOB_TOKEN authenticating this same-project read on current + # GitLab; this has not been checked against the oldest self-hosted + # GitLab version fullsend supports. + _fs_ref_enc=$(printf '%s' "${FULLSEND_PINNED_REF}" | jq -sRr @uri) + _fs_branch_json="" + if ! _fs_branch_json=$(fullsend_gate_curl \ + -H "JOB-TOKEN: ${CI_JOB_TOKEN}" \ + "${_fs_api}/projects/${FULLSEND_PINNED_PROJECT_ID}/repository/branches/${_fs_ref_enc}"); then + echo "ERROR: cannot read pinned branch '${FULLSEND_PINNED_REF}' — aborting (fail-closed)" >&2 + unset _fs_api _fs_trust _fs_default_branch _fs_ref_enc _fs_branch_json FULLSEND_PINNED_PROJECT_ID FULLSEND_PINNED_PIPELINE_ID FULLSEND_PINNED_REF FULLSEND_PINNED_PROJECT_PATH + return 1 + fi + _fs_protected=$(printf '%s' "${_fs_branch_json}" | jq -r '.protected // false') + unset _fs_branch_json _fs_ref_enc + if [ "${_fs_protected}" != "true" ]; then + echo "ERROR: enrolled default branch '${FULLSEND_PINNED_REF}' is not protected — aborting (fail-closed)" >&2 + unset _fs_api _fs_trust _fs_default_branch _fs_protected FULLSEND_PINNED_PROJECT_ID FULLSEND_PINNED_PIPELINE_ID FULLSEND_PINNED_REF FULLSEND_PINNED_PROJECT_PATH + return 1 + fi + unset _fs_default_branch _fs_protected + + FULLSEND_PINNED_PIPELINE_RESPONSE="" + if ! FULLSEND_PINNED_PIPELINE_RESPONSE=$(fullsend_gate_curl \ + -H "JOB-TOKEN: ${CI_JOB_TOKEN}" \ + "${_fs_api}/projects/${FULLSEND_PINNED_PROJECT_ID}/pipelines/${FULLSEND_PINNED_PIPELINE_ID}"); then + echo "ERROR: cannot read pinned pipeline ${FULLSEND_PINNED_PIPELINE_ID} — aborting (fail-closed)" >&2 + unset _fs_api _fs_trust FULLSEND_PINNED_PROJECT_ID FULLSEND_PINNED_PIPELINE_ID FULLSEND_PINNED_REF FULLSEND_PINNED_PIPELINE_RESPONSE FULLSEND_PINNED_PROJECT_PATH + return 1 + fi + FULLSEND_PINNED_PIPELINE_SOURCE=$(printf '%s' "${FULLSEND_PINNED_PIPELINE_RESPONSE}" | jq -r '.source // empty') + if [ "${FULLSEND_PINNED_PIPELINE_SOURCE}" != "${FULLSEND_ADMIT_SOURCE}" ]; then + echo "ERROR: pinned pipeline source '${FULLSEND_PINNED_PIPELINE_SOURCE:-}' is not '${FULLSEND_ADMIT_SOURCE}' — disjoint allowlist deny (fail-closed)" >&2 + unset _fs_api _fs_trust FULLSEND_PINNED_PROJECT_ID FULLSEND_PINNED_PIPELINE_ID FULLSEND_PINNED_REF FULLSEND_PINNED_PIPELINE_SOURCE FULLSEND_PINNED_PIPELINE_RESPONSE FULLSEND_PINNED_PROJECT_PATH + return 1 + fi + + export FULLSEND_PINNED_PROJECT_ID + export FULLSEND_PINNED_PIPELINE_ID + export FULLSEND_PINNED_REF + export FULLSEND_PINNED_PIPELINE_SOURCE + export FULLSEND_PINNED_PIPELINE_RESPONSE + export FULLSEND_PINNED_PROJECT_PATH + FULLSEND_PINNED_GITLAB_URL="${_fs_api%/api/v4}" + export FULLSEND_PINNED_GITLAB_URL + unset _fs_api _fs_trust + + # fullsend_gate_curl only strips proxy env vars for its own curl + # invocations (env -u ...); it does not remove them from this shell. + # The subsequent fullsend poll/run Go processes inherit this shell's + # exported environment and build their http.Client with a nil + # Transport (ProxyFromEnvironment), so a trigger-influenced + # HTTP_PROXY/HTTPS_PROXY left in the parent shell could still + # CONNECT-proxy PAT-bearing API traffic after the pin succeeds. Unset + # them here (the names Go's ProxyFromEnvironment honors) so later + # CLI calls in this job cannot be steered by a trigger-supplied proxy. + # ALL_PROXY/all_proxy is included too: git (used for post-pin, + # credential-bearing fetches elsewhere in the scaffold) honors it as + # a fallback, matching the set fullsend_gate_curl already strips. + unset HTTP_PROXY HTTPS_PROXY http_proxy https_proxy ALL_PROXY all_proxy +} + +fullsend_pin_ci_job_identity diff --git a/internal/scaffold/fullsend-repo-gitlab/.gitlab/ci/scripts/run-agent-job.sh b/internal/scaffold/fullsend-repo-gitlab/.gitlab/ci/scripts/run-agent-job.sh index db605a937e..218f58481d 100644 --- a/internal/scaffold/fullsend-repo-gitlab/.gitlab/ci/scripts/run-agent-job.sh +++ b/internal/scaffold/fullsend-repo-gitlab/.gitlab/ci/scripts/run-agent-job.sh @@ -7,6 +7,45 @@ set -euo pipefail +# CI_DEBUG_TRACE guard — deny-before-admit. YAML rules also refuse to +# start the job when debug tracing is enabled (secrets materialize at +# job init, so a mid-script abort is too late). This script-level +# guard is defense-in-depth and MUST run before any identity pin, +# token select, or admit/allowlist logic. Matches the full truthy set +# gitlab-runner accepts for this variable (Go strconv.ParseBool: "1", +# "t"/"T", "true"/"TRUE"/"True"), not just an exact "true". +case "${CI_DEBUG_TRACE:-}" in + 1|[tT]|[tT][rR][uU][eE]) + echo "ERROR: CI_DEBUG_TRACE enabled — aborting to protect secrets" >&2 + exit 1 + ;; +esac + +# Pin job/pipeline/project identity to the CI_JOB_TOKEN job record +# and admit only source=api. Disjoint from the poller (schedule) and +# the dispatcher (trigger, #7771). Runs before any PAT-bearing call. +# shellcheck disable=SC2034 # consumed by sourced pin-ci-job-identity.sh +FULLSEND_ADMIT_SOURCE=api +. "${CI_PROJECT_DIR:-.}/.gitlab/ci/scripts/pin-ci-job-identity.sh" +PIPELINE_SOURCE="${FULLSEND_PINNED_PIPELINE_SOURCE}" +PIPELINE_RESPONSE="${FULLSEND_PINNED_PIPELINE_RESPONSE}" + +# Every PAT-bearing fullsend_gate_curl call below targets this pinned API +# root, not the overridable CI_API_V4_URL pipeline variable — same +# outrankable class as CI_PROJECT_ID (ADR 0125). FULLSEND_PINNED_GITLAB_URL +# is exported by pin-ci-job-identity.sh (derived from the same CI_API_V4_URL +# value, but only after that value passed the pin's validation and was used +# to fetch GET /job), so same-process env cannot diverge it from CI_API_V4_URL +# after the pin succeeds; routing through it here is for consistency with +# the pin's stated contract, not an independent new protection. Fail closed +# rather than silently fall back to the overridable variable if it is ever +# unexpectedly unset. +if [ -z "${FULLSEND_PINNED_GITLAB_URL:-}" ]; then + echo "ERROR: FULLSEND_PINNED_GITLAB_URL is unset after a successful identity pin — refusing to make PAT-bearing calls without a pinned API root (fail-closed)" >&2 + exit 1 +fi +FULLSEND_PINNED_API_V4_URL="${FULLSEND_PINNED_GITLAB_URL}/api/v4" + # Back-link to the poll job that dispatched this pipeline if [ -n "${FULLSEND_POLL_JOB_URL:-}" ]; then case "${FULLSEND_POLL_JOB_URL}" in @@ -15,12 +54,6 @@ if [ -n "${FULLSEND_POLL_JOB_URL:-}" ]; then esac fi -# CI_DEBUG_TRACE guard -if [ "${CI_DEBUG_TRACE:-}" = "true" ]; then - echo "ERROR: CI_DEBUG_TRACE enabled — aborting to protect secrets" >&2 - exit 1 -fi - # Bot token from the registered role credential when the # migration gate is migrating/enforced; otherwise the shared # FULLSEND_FORGE_TOKEN (ADR-0067 / gitlab-role-credentials.md). @@ -78,64 +111,53 @@ fi # Resource group self-heal — set process_mode to newest_first so stale # locks from cancelled/deleted pipelines are preempted by new jobs. -# Best-effort: failures don't block the job. -curl -sf --retry 2 --retry-delay 1 --retry-all-errors \ - -X PUT "${CI_API_V4_URL}/projects/${CI_PROJECT_ID}/resource_groups/fullsend-${STAGE}-${RESOURCE_KEY}" \ +# Best-effort: failures don't block the job. Routed through +# fullsend_gate_curl (not plain curl) so a trigger-supplied +# HTTP_PROXY/HTTPS_PROXY cannot intercept this PAT-bearing call. Uses +# the pinned project id (from the CI_JOB_TOKEN job record), not the +# overridable CI_PROJECT_ID pipeline variable — this call runs with +# the poller/role PAT before HMAC verification. +fullsend_gate_curl \ + -X PUT "${FULLSEND_PINNED_API_V4_URL}/projects/${FULLSEND_PINNED_PROJECT_ID}/resource_groups/fullsend-${STAGE}-${RESOURCE_KEY}" \ -H "PRIVATE-TOKEN: ${FULLSEND_JOB_TOKEN}" \ -H "Content-Type: application/x-www-form-urlencoded" \ -d "process_mode=newest_first" > /dev/null 2>&1 || true -# Bot identity verification (#5572 mitigation #1) — uses the -# Pipelines API to fetch the server-side .source field (unforgeable, -# unlike the CI_PIPELINE_SOURCE env var) and .user.id (stable across -# human job retries, unlike the Jobs API). Deny-by-default: only -# "api" and "parent_pipeline" are recognized; unknown/empty sources -# abort the job. -# -# RESIDUAL RISK: CI_API_V4_URL, CI_PROJECT_ID, CI_PIPELINE_ID are -# overridable by pipeline variables. An attacker who overrides -# CI_API_V4_URL can redirect these API calls. Mitigation #2 -# (HMAC signing below) reduces this risk — the HMAC computation -# uses no CI-provided URLs, but its gating condition depends on -# PIPELINE_SOURCE (derived from CI_API_V4_URL). -PIPELINE_RESPONSE="" -if ! PIPELINE_RESPONSE=$(curl -sf --retry 3 --retry-delay 2 --retry-all-errors \ - "${CI_API_V4_URL}/projects/${CI_PROJECT_ID}/pipelines/${CI_PIPELINE_ID}" \ +# Bot identity verification (#5572 mitigation #1) — PIPELINE_SOURCE +# was already re-derived from the CI_JOB_TOKEN job record by +# pin-ci-job-identity.sh and admitted only as "api" (disjoint from +# the poller's schedule allowlist; parent_pipeline is no longer +# admitted). Confirm the pinned pipeline's creator is this bot. +# Some GitLab versions omit .user on the job-token pipeline GET; +# re-fetch with the poller PAT using the pinned IDs (never the +# overridable CI_PROJECT_ID / CI_PIPELINE_ID) when needed. +if [ -z "$(printf '%s' "${PIPELINE_RESPONSE}" | jq -r '.user.id // empty')" ]; then + if ! PIPELINE_RESPONSE=$(fullsend_gate_curl \ + -H "PRIVATE-TOKEN: ${FULLSEND_JOB_TOKEN}" \ + "${FULLSEND_PINNED_API_V4_URL}/projects/${FULLSEND_PINNED_PROJECT_ID}/pipelines/${FULLSEND_PINNED_PIPELINE_ID}"); then + echo "ERROR: Cannot re-fetch pinned pipeline metadata — aborting (fail-closed)" >&2 + exit 1 + fi +fi +BOT_USER_ID="" +if BOT_RESPONSE=$(fullsend_gate_curl \ + "${FULLSEND_PINNED_API_V4_URL}/user" \ -H "PRIVATE-TOKEN: ${FULLSEND_JOB_TOKEN}"); then - echo "ERROR: Cannot fetch pipeline metadata — aborting (fail-closed)" >&2 + BOT_USER_ID=$(printf '%s' "${BOT_RESPONSE}" | jq -r '.id // empty') +fi +if [ -z "${BOT_USER_ID}" ]; then + echo "ERROR: Cannot verify bot identity — aborting (fail-closed)" >&2 + exit 1 +fi +PIPELINE_CREATOR_ID=$(printf '%s' "${PIPELINE_RESPONSE}" | jq -r '.user.id // empty') +if [ -z "${PIPELINE_CREATOR_ID}" ]; then + echo "ERROR: Cannot read pipeline creator — aborting (fail-closed)" >&2 + exit 1 +fi +if [ "${PIPELINE_CREATOR_ID}" != "${BOT_USER_ID}" ]; then + echo "ERROR: Pipeline created by user ${PIPELINE_CREATOR_ID}, expected bot ${BOT_USER_ID} — rejecting forged dispatch" >&2 exit 1 fi -PIPELINE_SOURCE=$(printf '%s' "${PIPELINE_RESPONSE}" | jq -r '.source // empty') -case "${PIPELINE_SOURCE}" in - api) - BOT_USER_ID="" - if BOT_RESPONSE=$(curl -sf --retry 3 --retry-delay 2 --retry-all-errors \ - "${CI_API_V4_URL}/user" \ - -H "PRIVATE-TOKEN: ${FULLSEND_JOB_TOKEN}"); then - BOT_USER_ID=$(printf '%s' "${BOT_RESPONSE}" | jq -r '.id // empty') - fi - if [ -z "${BOT_USER_ID}" ]; then - echo "ERROR: Cannot verify bot identity — aborting (fail-closed)" >&2 - exit 1 - fi - PIPELINE_CREATOR_ID=$(printf '%s' "${PIPELINE_RESPONSE}" | jq -r '.user.id // empty') - if [ -z "${PIPELINE_CREATOR_ID}" ]; then - echo "ERROR: Cannot read pipeline creator — aborting (fail-closed)" >&2 - exit 1 - fi - if [ "${PIPELINE_CREATOR_ID}" != "${BOT_USER_ID}" ]; then - echo "ERROR: Pipeline created by user ${PIPELINE_CREATOR_ID}, expected bot ${BOT_USER_ID} — rejecting forged dispatch" >&2 - exit 1 - fi - ;; - parent_pipeline) - # MR child pipeline — creator is the MR author, not the bot - ;; - *) - echo "ERROR: unexpected pipeline source '${PIPELINE_SOURCE:-}' — aborting (fail-closed)" >&2 - exit 1 - ;; -esac # Gate mode — every mode is role-aware now: select-gitlab-role-token.sh # no longer has a shared-token path for disabled/rollback (it always @@ -147,16 +169,10 @@ esac # HMAC dispatch signature verification (#5572 mitigation #2) — # verifies the dispatch variables were signed by the poller using -# a shared secret (FULLSEND_DISPATCH_SECRET). Reduces the residual -# risk where CI_API_V4_URL can be overridden to redirect mitigation -# #1's API calls — the HMAC computation uses no CI-provided URLs, -# but the gating condition depends on PIPELINE_SOURCE (derived -# from CI_API_V4_URL). -# Only applies to API-triggered pipelines; parent_pipeline (MR -# dispatch) variables are set by the trusted parent job and have no -# HMAC to check — DISPATCH_VERIFIED stays false for that path, so -# the job fails closed below in every gate mode (see that gate -# further down) instead of continuing. +# a shared secret (FULLSEND_DISPATCH_SECRET). The identity pin +# above already admitted only source=api from the CI_JOB_TOKEN +# job record; HMAC authenticates the dispatch fields themselves. +# parent_pipeline is no longer admitted (disjoint allowlist). # # IMPORTANT: FULLSEND_DISPATCH_SECRET MUST be configured as a # protected, masked CI/CD variable. Pipeline variables can be @@ -188,9 +204,9 @@ fi # Fail closed for the rest of the job when STAGE has not actually # been authenticated. Do not treat a skipped or impossible check as -# a pass: a parent_pipeline dispatch (not HMAC-signed) or a missing -# dispatch secret (already fail-closed above) both leave -# DISPATCH_VERIFIED false. +# a pass: a missing dispatch secret (already fail-closed above) +# leaves DISPATCH_VERIFIED false. parent_pipeline is denied at the +# identity pin, so it never reaches this gate. # # An earlier revision of this template continued the job on the # poller bootstrap credential in this situation instead of exiting. @@ -227,7 +243,7 @@ if [ "${DISPATCH_VERIFIED}" = "true" ]; then . "${CI_PROJECT_DIR:-.}/.gitlab/ci/scripts/select-gitlab-role-token.sh" # BOT_USER_ID/BOT_RESPONSE above were populated by the /user call - # made with the poller bootstrap token (line ~220), so they describe + # made with the poller bootstrap token, so they describe # the poller's bot identity — GitLab assigns a distinct bot user per # project access token (gitlab-role-credentials.md's "Identity # continuity" section). Downstream blocks (review's prior-review @@ -245,16 +261,30 @@ fi # include the pipeline commit. Save the SHA so later steps (eval # measurement manifests) can reuse the same trusted tip even if # FETCH_HEAD moves. +# +# Fetch FULLSEND_PINNED_REF (the CI_JOB_TOKEN job record's ref, +# already proven equal to the project's enrolled protected default +# branch by pin-ci-job-identity.sh), not the overridable +# CI_DEFAULT_BRANCH pipeline variable — same outrankable class as +# CI_PROJECT_ID (ADR 0125). A pipeline/schedule variable named +# CI_DEFAULT_BRANCH could otherwise point this fetch at stale or +# attacker-influenced config, or empty it to skip the kill-switch and +# role-enablement checks below entirely (fail-open). FULLSEND_PINNED_REF +# is always non-empty here (pin-ci-job-identity.sh already fails closed +# above if it can't be resolved), so this fetch is now unconditional; +# fail closed rather than silently skip if it is ever unexpectedly unset. CONFIG_YAML="" DEFAULT_BRANCH_SHA="" -if [ -n "${CI_DEFAULT_BRANCH:-}" ]; then - if ! git fetch origin "${CI_DEFAULT_BRANCH}" --depth=1; then - echo "ERROR: cannot fetch default branch — refusing to run without trusted config" >&2 - exit 1 - fi - DEFAULT_BRANCH_SHA=$(git rev-parse FETCH_HEAD) - CONFIG_YAML=$(git show "${DEFAULT_BRANCH_SHA}:.fullsend/config.yaml" 2>/dev/null || echo "") +if [ -z "${FULLSEND_PINNED_REF:-}" ]; then + echo "ERROR: FULLSEND_PINNED_REF is unset — refusing to fetch trusted config without a pinned ref (fail-closed)" >&2 + exit 1 +fi +if ! git fetch origin "${FULLSEND_PINNED_REF}" --depth=1; then + echo "ERROR: cannot fetch default branch — refusing to run without trusted config" >&2 + exit 1 fi +DEFAULT_BRANCH_SHA=$(git rev-parse FETCH_HEAD) +CONFIG_YAML=$(git show "${DEFAULT_BRANCH_SHA}:.fullsend/config.yaml" 2>/dev/null || echo "") # Kill switch — halt all agent dispatch when active if [ -n "${CONFIG_YAML}" ]; then @@ -305,9 +335,17 @@ if [ "${STAGE}" != "retro" ] && [ "${STAGE}" != "prioritize" ]; then echo "WARNING: No actor identity available — skipping stage (fail-closed)" exit 0 fi + # CI_MERGE_REQUEST_PROJECT_ID is an overridable pipeline variable; only + # trust it when it agrees with the project id pinned from the + # CI_JOB_TOKEN job record, rather than letting it silently pick which + # project's member list the role PAT is sent to. + if [ -n "${CI_MERGE_REQUEST_PROJECT_ID:-}" ] && [ "${CI_MERGE_REQUEST_PROJECT_ID}" != "${FULLSEND_PINNED_PROJECT_ID}" ]; then + echo "ERROR: CI_MERGE_REQUEST_PROJECT_ID '${CI_MERGE_REQUEST_PROJECT_ID}' does not match the pinned project ${FULLSEND_PINNED_PROJECT_ID} — refusing to trust an unverified CI variable to select the project (fail-closed)" >&2 + exit 1 + fi AUTHOR_ACCESS=0 - if MEMBER_RESPONSE=$(curl -sf --retry 3 --retry-delay 2 --retry-all-errors \ - "${CI_API_V4_URL}/projects/${CI_MERGE_REQUEST_PROJECT_ID:-${CI_PROJECT_ID}}/members/all/${AUTH_ACTOR_ID}" \ + if MEMBER_RESPONSE=$(fullsend_gate_curl \ + "${FULLSEND_PINNED_API_V4_URL}/projects/${FULLSEND_PINNED_PROJECT_ID}/members/all/${AUTH_ACTOR_ID}" \ -H "PRIVATE-TOKEN: ${FULLSEND_JOB_TOKEN}"); then AUTHOR_ACCESS=$(echo "${MEMBER_RESPONSE}" | jq -r '.access_level // 0') else @@ -349,15 +387,49 @@ GITLAB_ISSUE_URL="" case "${EVENT_TYPE:-}" in issue_*) if [[ -n "${STATUS_IID:-}" && "${STATUS_IID}" != "0" ]]; then - GITLAB_ISSUE_URL="${CI_SERVER_URL}/${CI_PROJECT_PATH}/-/issues/${STATUS_IID}" + GITLAB_ISSUE_URL="${FULLSEND_PINNED_GITLAB_URL}/${FULLSEND_PINNED_PROJECT_PATH}/-/issues/${STATUS_IID}" fi + # This job's admit source is api only, so GitLab never natively + # populates CI_MERGE_REQUEST_IID for an issue event — any value + # present is an ordinary, outrankable project/group/pipeline CI/CD + # variable. newGitLabClientFromEnv (internal/cli/reconcilestatus.go) + # sets the note target to merge_requests whenever CI_MERGE_REQUEST_IID + # is merely non-empty, regardless of FULLSEND_NOTE_TARGET, so unset it + # here to keep status-comment API calls on the issues target. + unset CI_MERGE_REQUEST_IID + # FULLSEND_NOTE_TARGET is the same class of outrankable + # project/group/pipeline CI/CD variable — a pre-set + # FULLSEND_NOTE_TARGET=merge_requests would otherwise survive into + # this arm and misdirect the status comment. Pin it explicitly. + export FULLSEND_NOTE_TARGET="issues" ;; *) - _fs_mr_iid="${CI_MERGE_REQUEST_IID:-${STATUS_IID:-}}" - if [[ -n "${_fs_mr_iid}" && "${_fs_mr_iid}" != "0" ]]; then - GITLAB_ISSUE_URL="${CI_SERVER_URL}/${CI_PROJECT_PATH}/-/merge_requests/${_fs_mr_iid}" + # STATUS_IID is part of the HMAC-signed dispatch message; + # CI_MERGE_REQUEST_IID is not. This job's admit source is api + # only, so GitLab never natively populates CI_MERGE_REQUEST_IID + # here — any value comes solely from an ordinary, outrankable + # project/group/pipeline CI/CD variable. Prefer the signed value, + # fail closed if a non-empty CI_MERGE_REQUEST_IID disagrees with a + # non-zero STATUS_IID, and — when STATUS_IID is empty or "0" — + # ignore CI_MERGE_REQUEST_IID entirely rather than falling back to + # it, mirroring the code|fix|review MR_IID resolution below. + case "${CI_MERGE_REQUEST_IID:-}" in + ''|*[!0-9]*) _fs_issue_url_mr_iid="" ;; + *) _fs_issue_url_mr_iid="${CI_MERGE_REQUEST_IID}" ;; + esac + if [[ -n "${STATUS_IID:-}" && "${STATUS_IID}" != "0" ]]; then + if [[ -n "${_fs_issue_url_mr_iid}" && "${_fs_issue_url_mr_iid}" != "${STATUS_IID}" ]]; then + echo "ERROR: CI_MERGE_REQUEST_IID '${_fs_issue_url_mr_iid}' does not match the signed dispatch STATUS_IID '${STATUS_IID}' — refusing to trust an unverified CI variable to select the merge request" >&2 + exit 1 + fi + _fs_mr_iid="${STATUS_IID}" + else + _fs_mr_iid="" fi - unset _fs_mr_iid + if [[ -n "${_fs_mr_iid:-}" && "${_fs_mr_iid}" != "0" ]]; then + GITLAB_ISSUE_URL="${FULLSEND_PINNED_GITLAB_URL}/${FULLSEND_PINNED_PROJECT_PATH}/-/merge_requests/${_fs_mr_iid}" + fi + unset _fs_mr_iid _fs_issue_url_mr_iid export FULLSEND_NOTE_TARGET="merge_requests" ;; esac @@ -383,7 +455,35 @@ fi # author check. This is an inherent GitLab API limitation — the # Notes API has no app-level provenance metadata. if [ "${STAGE}" = "review" ]; then - MR_IID="${CI_MERGE_REQUEST_IID:-${STATUS_IID:-0}}" + # MR identity for the prior-review lookup below. STATUS_IID is part + # of the HMAC-signed dispatch message (see HMAC_MESSAGE above); + # CI_MERGE_REQUEST_IID is not. This job's admit source is api only, + # so GitLab never natively populates CI_MERGE_REQUEST_IID here — any + # value comes solely from an ordinary, outrankable project/group/ + # pipeline CI/CD variable. Prefer the signed value, fail closed if a + # non-empty CI_MERGE_REQUEST_IID disagrees with a non-zero + # STATUS_IID, and — when STATUS_IID is empty or "0" — ignore + # CI_MERGE_REQUEST_IID entirely rather than falling back to it, + # mirroring the shared code|fix|review MR_IID resolution further + # down this script — this lookup runs before that block, so it + # can't reuse its result and must apply the same fail-closed + # cross-check itself rather than letting the unverified CI variable + # win. + case "${CI_MERGE_REQUEST_IID:-}" in + ''|*[!0-9]*) _FS_REVIEW_CI_MR_IID="" ;; + *) _FS_REVIEW_CI_MR_IID="${CI_MERGE_REQUEST_IID}" ;; + esac + if [ -n "${STATUS_IID:-}" ] && [ "${STATUS_IID}" != "0" ]; then + if [ -n "${_FS_REVIEW_CI_MR_IID}" ] && [ "${_FS_REVIEW_CI_MR_IID}" != "${STATUS_IID}" ]; then + echo "ERROR: CI_MERGE_REQUEST_IID '${_FS_REVIEW_CI_MR_IID}' does not match the signed dispatch STATUS_IID '${STATUS_IID}' — refusing to trust an unverified CI variable to select the merge request" >&2 + unset _FS_REVIEW_CI_MR_IID + exit 1 + fi + MR_IID="${STATUS_IID}" + else + MR_IID="0" + fi + unset _FS_REVIEW_CI_MR_IID PRIOR_REVIEW_FILE=$(mktemp) PRIOR_REVIEW_SHA="" PRIOR_REVIEW_PROVENANCE="none" @@ -392,8 +492,8 @@ if [ "${STAGE}" = "review" ]; then # (api-triggered pipelines); otherwise resolve from the forge token. BOT_ID="${BOT_USER_ID:-}" if [ -z "${BOT_ID}" ]; then - if BOT_RESP=$(curl -sf --retry 3 --retry-delay 2 --retry-all-errors \ - "${CI_API_V4_URL}/user" \ + if BOT_RESP=$(fullsend_gate_curl \ + "${FULLSEND_PINNED_API_V4_URL}/user" \ -H "PRIVATE-TOKEN: ${FULLSEND_JOB_TOKEN}"); then BOT_ID=$(printf '%s' "${BOT_RESP}" | jq -r '.id // empty') fi @@ -404,8 +504,8 @@ if [ "${STAGE}" = "review" ]; then REVIEW_NOTE="" PAGE=1 while [ "${PAGE}" -le 20 ] && [ -z "${REVIEW_NOTE}" ]; do - NOTES_PAGE=$(curl -sf --retry 3 --retry-delay 2 --retry-all-errors \ - "${CI_API_V4_URL}/projects/${CI_PROJECT_ID}/merge_requests/${MR_IID}/notes?sort=desc&per_page=100&page=${PAGE}" \ + NOTES_PAGE=$(fullsend_gate_curl \ + "${FULLSEND_PINNED_API_V4_URL}/projects/${FULLSEND_PINNED_PROJECT_ID}/merge_requests/${MR_IID}/notes?sort=desc&per_page=100&page=${PAGE}" \ -H "PRIVATE-TOKEN: ${FULLSEND_JOB_TOKEN}" \ 2>/dev/null || echo "[]") @@ -475,8 +575,8 @@ if [ "${STAGE}" = "code" ] || [ "${STAGE}" = "fix" ] || [ "${STAGE}" = "review" _BOT_USERNAME=$(printf '%s' "${BOT_RESPONSE}" | jq -r '.username // empty') fi if [ -z "${_BOT_USERNAME}" ]; then - if _BOT_RESP=$(curl -sf --retry 3 --retry-delay 2 --retry-all-errors \ - "${CI_API_V4_URL}/user" \ + if _BOT_RESP=$(fullsend_gate_curl \ + "${FULLSEND_PINNED_API_V4_URL}/user" \ -H "PRIVATE-TOKEN: ${FULLSEND_JOB_TOKEN}"); then _BOT_USERNAME=$(printf '%s' "${_BOT_RESP}" | jq -r '.username // empty') fi @@ -502,13 +602,17 @@ if [ "${STAGE}" = "code" ] || [ "${STAGE}" = "fix" ] || [ "${STAGE}" = "review" # to key the merge-request API call in checkout-mr-source.sh that # selects which MR's source gets fetched into --target-repo. # STATUS_IID is part of the HMAC-signed dispatch message (see - # HMAC_MESSAGE above); CI_MERGE_REQUEST_IID is not, and an - # ordinary project/group CI/CD variable can define it. Prefer the - # signed value and fail closed if a non-empty CI_MERGE_REQUEST_IID - # disagrees with a non-zero STATUS_IID, rather than letting an - # unverified CI variable pick which merge request's source is - # checked out — mirroring the fail-closed cross-checks already - # applied to CI_MERGE_REQUEST_SOURCE_* in checkout-mr-source.sh. + # HMAC_MESSAGE above); CI_MERGE_REQUEST_IID is not. This job's admit + # source is api only, so GitLab never natively populates + # CI_MERGE_REQUEST_IID here — any value comes solely from an + # ordinary, outrankable project/group/pipeline CI/CD variable. + # Prefer the signed value, fail closed if a non-empty + # CI_MERGE_REQUEST_IID disagrees with a non-zero STATUS_IID, and — + # when STATUS_IID is empty or "0" — ignore CI_MERGE_REQUEST_IID + # entirely rather than letting an unverified CI variable pick which + # merge request's source is checked out — mirroring the fail-closed + # cross-checks already applied to CI_MERGE_REQUEST_SOURCE_* in + # checkout-mr-source.sh. case "${CI_MERGE_REQUEST_IID:-}" in ''|*[!0-9]*) _FS_CI_MR_IID="" ;; *) _FS_CI_MR_IID="${CI_MERGE_REQUEST_IID}" ;; @@ -521,12 +625,12 @@ if [ "${STAGE}" = "code" ] || [ "${STAGE}" = "fix" ] || [ "${STAGE}" = "review" fi MR_IID="${STATUS_IID}" else - MR_IID="${_FS_CI_MR_IID:-0}" + MR_IID="0" fi unset _FS_CI_MR_IID export MR_NUMBER="${MR_IID}" if [ "${MR_IID}" != "0" ]; then - export GITLAB_MR_URL="${CI_SERVER_URL}/${CI_PROJECT_PATH}/-/merge_requests/${MR_IID}" + export GITLAB_MR_URL="${FULLSEND_PINNED_GITLAB_URL}/${FULLSEND_PINNED_PROJECT_PATH}/-/merge_requests/${MR_IID}" else export GITLAB_MR_URL="" fi @@ -560,8 +664,8 @@ if [ "${STAGE}" = "fix" ]; then FULLSEND_JOB_KIND=agent FULLSEND_JOB_AGENT=review if . "${CI_PROJECT_DIR:-.}/.gitlab/ci/scripts/select-gitlab-role-token.sh"; then - if BOT_RESP=$(curl -sf --retry 3 --retry-delay 2 --retry-all-errors \ - "${CI_API_V4_URL}/user" \ + if BOT_RESP=$(fullsend_gate_curl \ + "${FULLSEND_PINNED_API_V4_URL}/user" \ -H "PRIVATE-TOKEN: ${FULLSEND_JOB_TOKEN}"); then BOT_ID=$(printf '%s' "${BOT_RESP}" | jq -r '.id // empty') fi @@ -580,8 +684,8 @@ if [ "${STAGE}" = "fix" ]; then # transiently, retry here with this stage's own (now-restored) # token — not the analyst token used for BOT_ID above. if [ -z "${_BOT_USERNAME}" ]; then - if _BOT_RESP=$(curl -sf --retry 3 --retry-delay 2 --retry-all-errors \ - "${CI_API_V4_URL}/user" \ + if _BOT_RESP=$(fullsend_gate_curl \ + "${FULLSEND_PINNED_API_V4_URL}/user" \ -H "PRIVATE-TOKEN: ${FULLSEND_JOB_TOKEN}"); then _BOT_USERNAME=$(printf '%s' "${_BOT_RESP}" | jq -r '.username // empty') fi @@ -592,8 +696,8 @@ if [ "${STAGE}" = "fix" ]; then REVIEW_NOTE="" PAGE=1 while [ "${PAGE}" -le 20 ] && [ -z "${REVIEW_NOTE}" ]; do - NOTES_PAGE=$(curl -sf --retry 3 --retry-delay 2 --retry-all-errors \ - "${CI_API_V4_URL}/projects/${CI_PROJECT_ID}/merge_requests/${MR_IID}/notes?sort=desc&per_page=100&page=${PAGE}" \ + NOTES_PAGE=$(fullsend_gate_curl \ + "${FULLSEND_PINNED_API_V4_URL}/projects/${FULLSEND_PINNED_PROJECT_ID}/merge_requests/${MR_IID}/notes?sort=desc&per_page=100&page=${PAGE}" \ -H "PRIVATE-TOKEN: ${FULLSEND_JOB_TOKEN}" \ 2>/dev/null || echo "[]") @@ -661,21 +765,34 @@ if [ "${STAGE}" = "fix" ]; then # "Record pre-agent HEAD", and "Run fix agent" steps. These are # required by the fix harness env.runner and forge.gitlab blocks. - # Target branch (MR base branch). MR-triggered (parent_pipeline) - # runs have CI_MERGE_REQUEST_TARGET_BRANCH_NAME; API-dispatched - # runs must query the MR API. - if [ -n "${CI_MERGE_REQUEST_TARGET_BRANCH_NAME:-}" ]; then - TARGET_BRANCH="${CI_MERGE_REQUEST_TARGET_BRANCH_NAME}" - elif [ "${MR_IID}" != "0" ]; then - TARGET_BRANCH=$(curl -sf --retry 3 --retry-delay 2 --retry-all-errors \ - "${CI_API_V4_URL}/projects/${CI_PROJECT_ID}/merge_requests/${MR_IID}" \ + # Target branch (MR base branch). This job's admit source is + # api-only (parent_pipeline is not an admitted arm — see + # FULLSEND_ADMIT_SOURCE above), so GitLab does not natively populate + # CI_MERGE_REQUEST_TARGET_BRANCH_NAME here; a non-empty value is an + # ordinary, overridable project/group/pipeline CI/CD variable of the + # same outrankable class ADR 0125 already establishes for + # CI_PROJECT_ID/CI_DEFAULT_BRANCH. Always resolve TARGET_BRANCH from + # the pinned-project MR API, falling back to FULLSEND_PINNED_REF (the + # CI_JOB_TOKEN job record's ref) — never from + # CI_MERGE_REQUEST_TARGET_BRANCH_NAME. If that variable is non-empty + # and disagrees with the resolved value, fail closed instead of + # trusting an unverified CI variable to pick the fix push's target + # branch (mirroring the CI_MERGE_REQUEST_IID vs STATUS_IID pattern + # above). + if [ "${MR_IID}" != "0" ]; then + TARGET_BRANCH=$(fullsend_gate_curl \ + "${FULLSEND_PINNED_API_V4_URL}/projects/${FULLSEND_PINNED_PROJECT_ID}/merge_requests/${MR_IID}" \ -H "PRIVATE-TOKEN: ${FULLSEND_JOB_TOKEN}" \ | jq -r '.target_branch // empty' 2>/dev/null || echo "") if [ -z "${TARGET_BRANCH}" ]; then - TARGET_BRANCH="${CI_DEFAULT_BRANCH:-main}" + TARGET_BRANCH="${FULLSEND_PINNED_REF}" fi else - TARGET_BRANCH="${CI_DEFAULT_BRANCH:-main}" + TARGET_BRANCH="${FULLSEND_PINNED_REF}" + fi + if [ -n "${CI_MERGE_REQUEST_TARGET_BRANCH_NAME:-}" ] && [ "${CI_MERGE_REQUEST_TARGET_BRANCH_NAME}" != "${TARGET_BRANCH}" ]; then + echo "ERROR: CI_MERGE_REQUEST_TARGET_BRANCH_NAME '${CI_MERGE_REQUEST_TARGET_BRANCH_NAME}' does not match the pinned/API target branch '${TARGET_BRANCH}' — refusing to trust an unverified CI variable to select the fix push target" >&2 + exit 1 fi export TARGET_BRANCH @@ -698,8 +815,8 @@ if [ "${STAGE}" = "fix" ]; then | jq -r '.note_author_id // empty' 2>/dev/null || echo "") case "${_NOTE_AUTHOR_ID}" in ''|*[!0-9]*) _NOTE_AUTHOR_ID="" ;; esac if [ -n "${_NOTE_AUTHOR_ID}" ]; then - TRIGGER_SOURCE=$(curl -sf --retry 3 --retry-delay 2 --retry-all-errors \ - "${CI_API_V4_URL}/users/${_NOTE_AUTHOR_ID}" \ + TRIGGER_SOURCE=$(fullsend_gate_curl \ + "${FULLSEND_PINNED_API_V4_URL}/users/${_NOTE_AUTHOR_ID}" \ -H "PRIVATE-TOKEN: ${FULLSEND_JOB_TOKEN}" \ | jq -r '.username // empty' 2>/dev/null || echo "") fi @@ -738,8 +855,8 @@ if [ "${STAGE}" = "fix" ]; then if [ "${MR_IID}" != "0" ]; then _COMMIT_PAGE=1 while [ "${_COMMIT_PAGE}" -le 5 ]; do - _COMMITS_BATCH=$(curl -sf --retry 3 --retry-delay 2 --retry-all-errors \ - "${CI_API_V4_URL}/projects/${CI_PROJECT_ID}/merge_requests/${MR_IID}/commits?per_page=100&page=${_COMMIT_PAGE}" \ + _COMMITS_BATCH=$(fullsend_gate_curl \ + "${FULLSEND_PINNED_API_V4_URL}/projects/${FULLSEND_PINNED_PROJECT_ID}/merge_requests/${MR_IID}/commits?per_page=100&page=${_COMMIT_PAGE}" \ -H "PRIVATE-TOKEN: ${FULLSEND_JOB_TOKEN}" 2>/dev/null || echo "[]") _BATCH_FIX=$(printf '%s' "${_COMMITS_BATCH}" \ | jq '[.[] | select(.author_name == "fullsend-fix")] | length' 2>/dev/null || echo "0") @@ -806,14 +923,24 @@ if [ "${STAGE}" = "fix" ]; then fi mkdir -p "${CI_PROJECT_DIR}/output" set +e +# --status-repo uses the pinned project path (from the CI_JOB_TOKEN +# job record), not the overridable CI_PROJECT_PATH pipeline variable +# — same outrankable class as CI_PROJECT_ID (ADR 0125). `fullsend run` +# has no --gitlab-url flag; its GitLab client instead resolves the API +# host from FULLSEND_GITLAB_URL, then GITLAB_API_URL, then CI_SERVER_URL +# (newGitLabClientFromEnv in internal/cli/reconcilestatus.go) — all +# overridable pipeline variables in the same outrankable class. Export +# the pin-validated API root so that resolution never falls through to +# one of those instead. +export FULLSEND_GITLAB_URL="${FULLSEND_PINNED_GITLAB_URL}" fullsend run "${STAGE}" \ --fullsend-dir .fullsend \ --target-repo "${_FS_TARGET_REPO}" \ --output-dir "${CI_PROJECT_DIR}/output" \ --forge gitlab \ --run-url "${CI_PIPELINE_URL}" \ - --status-repo "${CI_PROJECT_PATH}" \ - --status-number "${MR_NUMBER:-${STATUS_IID:-${CI_MERGE_REQUEST_IID:-0}}}" + --status-repo "${FULLSEND_PINNED_PROJECT_PATH}" \ + --status-number "${MR_NUMBER:-${STATUS_IID:-0}}" RUN_STATUS=$? set -e diff --git a/internal/scaffold/fullsend-repo-gitlab/.gitlab/ci/scripts/run-poll-job.sh b/internal/scaffold/fullsend-repo-gitlab/.gitlab/ci/scripts/run-poll-job.sh index 74c82703f7..2eb24b2d76 100644 --- a/internal/scaffold/fullsend-repo-gitlab/.gitlab/ci/scripts/run-poll-job.sh +++ b/internal/scaffold/fullsend-repo-gitlab/.gitlab/ci/scripts/run-poll-job.sh @@ -6,11 +6,39 @@ set -euo pipefail -# CI_DEBUG_TRACE guard — prevents PAT exposure via debug trace logging. -if [ "${CI_DEBUG_TRACE:-}" = "true" ]; then - echo "ERROR: CI_DEBUG_TRACE enabled — aborting to protect secrets" >&2 +# CI_DEBUG_TRACE guard — deny-before-admit. YAML rules also refuse to +# start the job when debug tracing is enabled (secrets materialize at +# job init, so a mid-script abort is too late). This script-level +# guard is defense-in-depth and MUST run before any identity pin, +# token select, or admit/allowlist logic. Matches the full truthy set +# gitlab-runner accepts for this variable (Go strconv.ParseBool: "1", +# "t"/"T", "true"/"TRUE"/"True"), not just an exact "true". +case "${CI_DEBUG_TRACE:-}" in + 1|[tT]|[tT][rR][uU][eE]) + echo "ERROR: CI_DEBUG_TRACE enabled — aborting to protect secrets" >&2 + exit 1 + ;; +esac + +# Pin job/pipeline/project identity to the CI_JOB_TOKEN job record +# and admit only source=schedule. Disjoint from the agent (api) and +# the dispatcher (trigger, #7771). Runs before any PAT-bearing call +# so a trigger-token holder who forges CI_PIPELINE_SOURCE=schedule +# cannot reach the poller PAT. +# shellcheck disable=SC2034 # consumed by sourced pin-ci-job-identity.sh +FULLSEND_ADMIT_SOURCE=schedule +. "${CI_PROJECT_DIR:-.}/.gitlab/ci/scripts/pin-ci-job-identity.sh" + +# The PAT-bearing fullsend_gate_curl call below targets this pinned API +# root, not the overridable CI_API_V4_URL pipeline variable — same +# outrankable class as CI_PROJECT_ID (ADR 0125). Fail closed rather than +# silently fall back to the overridable variable if it is ever +# unexpectedly unset after a successful identity pin. +if [ -z "${FULLSEND_PINNED_GITLAB_URL:-}" ]; then + echo "ERROR: FULLSEND_PINNED_GITLAB_URL is unset after a successful identity pin — refusing to make PAT-bearing calls without a pinned API root (fail-closed)" >&2 exit 1 fi +FULLSEND_PINNED_API_V4_URL="${FULLSEND_PINNED_GITLAB_URL}/api/v4" # Bot token from the registered Poller credential — required in # every gate mode; there is no shared FULLSEND_FORGE_TOKEN fallback @@ -58,23 +86,40 @@ esac # cancelled/deleted pipelines are preempted by new jobs. # slash mode: newest_first (latest command wins) # events mode: oldest_first (complete long-running discovery) -# Best-effort: failures don't block the job. +# Best-effort: failures don't block the job. Routed through +# fullsend_gate_curl (not plain curl) so a trigger-supplied +# HTTP_PROXY/HTTPS_PROXY cannot intercept this PAT-bearing call. Uses +# the pinned project id (from the CI_JOB_TOKEN job record), not the +# overridable CI_PROJECT_ID pipeline variable. PROCESS_MODE="newest_first" if [ "${FULLSEND_POLL_MODE:-events}" = "events" ]; then PROCESS_MODE="oldest_first" fi -curl -sf --retry 2 --retry-delay 1 --retry-all-errors \ - -X PUT "${CI_API_V4_URL}/projects/${CI_PROJECT_ID}/resource_groups/fullsend-poll-${FULLSEND_POLL_MODE:-events}" \ +fullsend_gate_curl \ + -X PUT "${FULLSEND_PINNED_API_V4_URL}/projects/${FULLSEND_PINNED_PROJECT_ID}/resource_groups/fullsend-poll-${FULLSEND_POLL_MODE:-events}" \ -H "PRIVATE-TOKEN: ${FULLSEND_JOB_TOKEN}" \ -H "Content-Type: application/x-www-form-urlencoded" \ -d "process_mode=${PROCESS_MODE}" > /dev/null 2>&1 || true # Run the poller — dispatches pipelines directly via the GitLab API. # No child pipeline generation needed: the poller creates standalone -# pipelines for each discovered event and logs clickable URLs. +# pipelines for each discovered event and logs clickable URLs. Uses +# the pinned project path/API root (from the CI_JOB_TOKEN job +# record), not the overridable CI_PROJECT_PATH / FULLSEND_GITLAB_URL / +# CI_SERVER_URL pipeline variables — same outrankable class as +# CI_PROJECT_ID (ADR 0125). +# +# `fullsend poll` has no --ref flag; internal/cli/poll.go instead reads +# the dispatch ref from CI_COMMIT_REF_NAME, falling back to +# CI_DEFAULT_BRANCH — both overridable pipeline variables in the same +# outrankable class. A pipeline/schedule variable of either name could +# retarget dispatched pipelines to a different (possibly stale, +# pre-hardening) ref while this poller job itself stays correctly +# pinned. Export the pinned ref so the CLI picks it up instead. +export CI_COMMIT_REF_NAME="${FULLSEND_PINNED_REF}" fullsend poll \ --forge gitlab \ - --project "${CI_PROJECT_PATH}" \ - --gitlab-url "${FULLSEND_GITLAB_URL:-${CI_SERVER_URL}}" \ + --project "${FULLSEND_PINNED_PROJECT_PATH}" \ + --gitlab-url "${FULLSEND_PINNED_GITLAB_URL}" \ --fullsend-dir .fullsend \ --mode "${FULLSEND_POLL_MODE:-events}" diff --git a/internal/scaffold/fullsend-repo-gitlab/.gitlab/ci/scripts/trust-ci-server-ca.sh b/internal/scaffold/fullsend-repo-gitlab/.gitlab/ci/scripts/trust-ci-server-ca.sh index 357d3d08d5..0f82ceaa16 100644 --- a/internal/scaffold/fullsend-repo-gitlab/.gitlab/ci/scripts/trust-ci-server-ca.sh +++ b/internal/scaffold/fullsend-repo-gitlab/.gitlab/ci/scripts/trust-ci-server-ca.sh @@ -16,7 +16,11 @@ # Source this file (do not execute it) so the exports persist. fullsend_trust_ci_server_ca() { - if [ "${FULLSEND_CI_SERVER_CA_TRUSTED:-}" = "1" ]; then + # Idempotency is a shell-local flag, not the exported + # FULLSEND_CI_SERVER_CA_TRUSTED env var: that name is in the same + # trigger-overridable class as other CI variables, so a caller who + # sets it to 1 must not skip CA pinning. + if [ "${_fullsend_trust_ci_server_ca_done:-}" = "1" ]; then return 0 fi @@ -75,6 +79,7 @@ fullsend_trust_ci_server_ca() { export REQUESTS_CA_BUNDLE="${combined}" export NODE_EXTRA_CA_CERTS="${combined}" export FULLSEND_CI_SERVER_CA_TRUSTED=1 + _fullsend_trust_ci_server_ca_done=1 echo "Trusted extra CA from CI_SERVER_TLS_CA_FILE (${ca_file}); combined bundle at ${combined}" >&2 } diff --git a/internal/scaffold/gitlab_job_scripts_test.go b/internal/scaffold/gitlab_job_scripts_test.go index 19a87638e2..24ae6b0151 100644 --- a/internal/scaffold/gitlab_job_scripts_test.go +++ b/internal/scaffold/gitlab_job_scripts_test.go @@ -1,9 +1,18 @@ package scaffold import ( + "crypto/hmac" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "net/http" + "net/http/cgi" + "net/http/httptest" "os" "os/exec" "path/filepath" + "strings" + "sync/atomic" "testing" "github.com/stretchr/testify/assert" @@ -21,25 +30,56 @@ func writeGitLabScript(t *testing.T, dir, relPath string) string { return path } +// setupPinnedConfigOrigin makes root a git checkout with an "origin" +// remote on branch "main", so run-agent-job.sh's trusted-config fetch +// (`git fetch origin "${FULLSEND_PINNED_REF}" --depth=1`) succeeds. +// That fetch is unconditional (fail-closed on FULLSEND_PINNED_REF, not +// gated on the overridable CI_DEFAULT_BRANCH), so any run-agent-job.sh +// test whose STAGE reaches past HMAC dispatch verification needs this, +// even when the test has nothing to do with the trusted-config content +// itself. Callers that do care about the config content should commit +// their own .fullsend/config.yaml into the upstream repo instead of +// calling this helper directly. +func setupPinnedConfigOrigin(t *testing.T, root string) { + t.Helper() + upstream := t.TempDir() + initGitRepo(t, upstream) + commitFile(t, upstream, ".fullsend/config.yaml", "kill_switch: false\n", "trusted config") + initGitRepo(t, root) + gitCmd(t, root, "remote", "add", "origin", upstream) +} + func TestRunPollJobScript_RejectsInvalidPollMode(t *testing.T) { root := t.TempDir() + writeGitLabScript(t, root, ".gitlab/ci/scripts/trust-ci-server-ca.sh") + writeGitLabScript(t, root, gitlabPinCIJobIdentityScriptPath) writeGitLabScript(t, root, ".gitlab/ci/scripts/select-gitlab-role-token.sh") script := writeGitLabScript(t, root, gitlabRunPollJobScriptPath) + st := &pinAPIState{ + jobJSON: pinJobJSON("42", "100", "main"), + projectJSON: `{"id":42,"default_branch":"main","path_with_namespace":"group/project"}`, + branchJSON: `{"name":"main","protected":true}`, + pipelineJSON: `{"id":100,"source":"schedule"}`, + } + srv := startPinAPI(t, st) + t.Cleanup(srv.Close) + cmd := exec.Command("bash", "-c", "set -euo pipefail; . \"$SCRIPT\"") - cmd.Env = []string{ + cmd.Env = append([]string{ "SCRIPT=" + script, "PATH=" + os.Getenv("PATH"), "HOME=" + t.TempDir(), "CI_PROJECT_DIR=" + root, + "RUNNER_TEMP=" + t.TempDir(), + "CI_JOB_TOKEN=job-token", "FULLSEND_FORGE_TOKEN=shared-pat", "FULLSEND_GITLAB_POLLER_TOKEN=poller-pat", "FULLSEND_POLL_MODE=bogus", - "CI_API_V4_URL=https://gitlab.example/api/v4", "CI_PROJECT_ID=1", "CI_PROJECT_PATH=group/project", "CI_SERVER_URL=https://gitlab.example", - } + }, pinTLSEnv(t, srv)...) out, err := cmd.CombinedOutput() require.Error(t, err, "stdout/stderr: %s", out) assert.Contains(t, string(out), "FULLSEND_POLL_MODE must be 'slash' or 'events'") @@ -64,35 +104,100 @@ func TestRunPollJobScript_DebugTraceAborts(t *testing.T) { assert.Contains(t, string(out), "CI_DEBUG_TRACE enabled") } +// TestRunPollJobScript_DebugTraceAbortsOnTruthyVariants covers non-"true" +// values gitlab-runner also treats as enabling debug tracing (Go +// strconv.ParseBool accepts "1", "t"/"T", "true"/"TRUE"/"True"). An +// exact-match guard would miss these and let a debug-trace pipeline dump +// secrets at job init. +func TestRunPollJobScript_DebugTraceAbortsOnTruthyVariants(t *testing.T) { + for _, v := range []string{"1", "TRUE", "T"} { + t.Run(v, func(t *testing.T) { + root := t.TempDir() + writeGitLabScript(t, root, ".gitlab/ci/scripts/select-gitlab-role-token.sh") + script := writeGitLabScript(t, root, gitlabRunPollJobScriptPath) + + cmd := exec.Command("bash", "-c", "set -euo pipefail; . \"$SCRIPT\"") + cmd.Env = []string{ + "SCRIPT=" + script, + "PATH=" + os.Getenv("PATH"), + "HOME=" + t.TempDir(), + "CI_PROJECT_DIR=" + root, + "CI_DEBUG_TRACE=" + v, + "FULLSEND_FORGE_TOKEN=shared-pat", + } + out, err := cmd.CombinedOutput() + require.Error(t, err, "stdout/stderr: %s", out) + assert.Contains(t, string(out), "CI_DEBUG_TRACE enabled") + }) + } +} + +// TestRunAgentJobScript_DebugTraceAbortsOnTruthyVariants is the +// run-agent-job.sh counterpart of TestRunPollJobScript_DebugTraceAbortsOnTruthyVariants. +func TestRunAgentJobScript_DebugTraceAbortsOnTruthyVariants(t *testing.T) { + for _, v := range []string{"1", "TRUE", "T"} { + t.Run(v, func(t *testing.T) { + root := t.TempDir() + writeGitLabScript(t, root, ".gitlab/ci/scripts/select-gitlab-role-token.sh") + script := writeGitLabScript(t, root, gitlabRunAgentJobScriptPath) + + cmd := exec.Command("bash", "-c", "set -euo pipefail; . \"$SCRIPT\"") + cmd.Env = []string{ + "SCRIPT=" + script, + "PATH=" + os.Getenv("PATH"), + "HOME=" + t.TempDir(), + "CI_PROJECT_DIR=" + root, + "CI_DEBUG_TRACE=" + v, + "FULLSEND_FORGE_TOKEN=shared-pat", + } + out, err := cmd.CombinedOutput() + require.Error(t, err, "stdout/stderr: %s", out) + assert.Contains(t, string(out), "CI_DEBUG_TRACE enabled") + }) + } +} + func TestRunPollJobScript_BlanksSiblingSecretsBeforePoll(t *testing.T) { root := t.TempDir() + writeGitLabScript(t, root, ".gitlab/ci/scripts/trust-ci-server-ca.sh") + writeGitLabScript(t, root, gitlabPinCIJobIdentityScriptPath) writeGitLabScript(t, root, ".gitlab/ci/scripts/select-gitlab-role-token.sh") script := writeGitLabScript(t, root, gitlabRunPollJobScriptPath) + st := &pinAPIState{ + jobJSON: pinJobJSON("42", "100", "main"), + projectJSON: `{"id":42,"default_branch":"main","path_with_namespace":"group/project"}`, + branchJSON: `{"name":"main","protected":true}`, + pipelineJSON: `{"id":100,"source":"schedule"}`, + } + srv := startPinAPI(t, st) + t.Cleanup(srv.Close) + bin := t.TempDir() writeStub := func(name, body string) { path := filepath.Join(bin, name) require.NoError(t, os.WriteFile(path, []byte("#!/bin/sh\n"+body), 0o755)) } - writeStub("curl", "exit 0\n") writeStub("fullsend", "echo POLL_RAN\nexit 0\n") cmd := exec.Command("bash", "-c", `set -euo pipefail; . "$SCRIPT"; echo ANALYST="${FULLSEND_GITLAB_ANALYST_TOKEN-unset}"; echo CODER="${FULLSEND_GITLAB_CODER_TOKEN-unset}"; echo SHARED="${FULLSEND_FORGE_TOKEN-unset}"; echo JOB="${FULLSEND_JOB_TOKEN-unset}"`) - cmd.Env = []string{ + cmd.Env = append([]string{ "SCRIPT=" + script, "PATH=" + bin + ":" + os.Getenv("PATH"), "HOME=" + t.TempDir(), "CI_PROJECT_DIR=" + root, + "RUNNER_TEMP=" + t.TempDir(), + "CI_JOB_TOKEN=job-token", + "FULLSEND_GITLAB_ROLE_MIGRATION=enforced", "FULLSEND_GITLAB_POLLER_TOKEN=poll-pat", "FULLSEND_GITLAB_ANALYST_TOKEN=analyst-pat", "FULLSEND_GITLAB_CODER_TOKEN=coder-pat", "FULLSEND_FORGE_TOKEN=shared-pat", "FULLSEND_POLL_MODE=events", - "CI_API_V4_URL=https://gitlab.example/api/v4", "CI_PROJECT_ID=1", "CI_PROJECT_PATH=group/project", "CI_SERVER_URL=https://gitlab.example", - } + }, pinTLSEnv(t, srv)...) out, err := cmd.CombinedOutput() require.NoError(t, err, "stdout/stderr: %s", out) got := string(out) @@ -139,3 +244,1146 @@ func TestInstallFullsendCLIScript_DebugTraceAborts(t *testing.T) { require.Error(t, err, "stdout/stderr: %s", out) assert.Contains(t, string(out), "CI_DEBUG_TRACE enabled") } + +func TestRunPollJobScript_DeniesNonSchedulePinnedSource(t *testing.T) { + root := t.TempDir() + writeGitLabScript(t, root, ".gitlab/ci/scripts/trust-ci-server-ca.sh") + writeGitLabScript(t, root, gitlabPinCIJobIdentityScriptPath) + writeGitLabScript(t, root, ".gitlab/ci/scripts/select-gitlab-role-token.sh") + script := writeGitLabScript(t, root, gitlabRunPollJobScriptPath) + + st := &pinAPIState{ + jobJSON: pinJobJSON("42", "100", "main"), + projectJSON: `{"id":42,"default_branch":"main","path_with_namespace":"group/project"}`, + branchJSON: `{"name":"main","protected":true}`, + pipelineJSON: `{"id":100,"source":"api"}`, + } + srv := startPinAPI(t, st) + t.Cleanup(srv.Close) + + cmd := exec.Command("bash", "-c", "set -euo pipefail; . \"$SCRIPT\"") + cmd.Env = append([]string{ + "SCRIPT=" + script, + "PATH=" + os.Getenv("PATH"), + "HOME=" + t.TempDir(), + "CI_PROJECT_DIR=" + root, + "RUNNER_TEMP=" + t.TempDir(), + "CI_JOB_TOKEN=job-token", + "FULLSEND_GITLAB_POLLER_TOKEN=poller-pat", + "FULLSEND_POLL_MODE=events", + "CI_PIPELINE_SOURCE=schedule", + "CI_PROJECT_ID=1", + "CI_PROJECT_PATH=group/project", + "CI_SERVER_URL=https://gitlab.example", + }, pinTLSEnv(t, srv)...) + out, err := cmd.CombinedOutput() + require.Error(t, err, "stdout/stderr: %s", out) + assert.Contains(t, string(out), "disjoint allowlist deny") + assert.NotContains(t, string(out), "fullsend poll") +} + +func TestRunAgentJobScript_DeniesParentPipelinePinnedSource(t *testing.T) { + root := t.TempDir() + writeGitLabScript(t, root, ".gitlab/ci/scripts/trust-ci-server-ca.sh") + writeGitLabScript(t, root, gitlabPinCIJobIdentityScriptPath) + writeGitLabScript(t, root, ".gitlab/ci/scripts/select-gitlab-role-token.sh") + script := writeGitLabScript(t, root, gitlabRunAgentJobScriptPath) + + st := &pinAPIState{ + jobJSON: pinJobJSON("42", "100", "main"), + projectJSON: `{"id":42,"default_branch":"main","path_with_namespace":"group/project"}`, + branchJSON: `{"name":"main","protected":true}`, + pipelineJSON: `{"id":100,"source":"parent_pipeline"}`, + } + srv := startPinAPI(t, st) + t.Cleanup(srv.Close) + + cmd := exec.Command("bash", "-c", "set -euo pipefail; . \"$SCRIPT\"") + cmd.Env = append([]string{ + "SCRIPT=" + script, + "PATH=" + os.Getenv("PATH"), + "HOME=" + t.TempDir(), + "CI_PROJECT_DIR=" + root, + "RUNNER_TEMP=" + t.TempDir(), + "CI_JOB_TOKEN=job-token", + "FULLSEND_GITLAB_POLLER_TOKEN=poller-pat", + "STAGE=triage", + "CI_PIPELINE_SOURCE=api", + "CI_PROJECT_ID=1", + "CI_PIPELINE_ID=99", + }, pinTLSEnv(t, srv)...) + out, err := cmd.CombinedOutput() + require.Error(t, err, "stdout/stderr: %s", out) + assert.Contains(t, string(out), "disjoint allowlist deny") + assert.NotContains(t, string(out), "HMAC") +} + +func TestRunAgentJobScript_DebugTraceAbortsBeforePin(t *testing.T) { + root := t.TempDir() + writeGitLabScript(t, root, ".gitlab/ci/scripts/trust-ci-server-ca.sh") + writeGitLabScript(t, root, gitlabPinCIJobIdentityScriptPath) + writeGitLabScript(t, root, ".gitlab/ci/scripts/select-gitlab-role-token.sh") + script := writeGitLabScript(t, root, gitlabRunAgentJobScriptPath) + + cmd := exec.Command("bash", "-c", "set -euo pipefail; . \"$SCRIPT\"") + cmd.Env = []string{ + "SCRIPT=" + script, + "PATH=" + os.Getenv("PATH"), + "HOME=" + t.TempDir(), + "CI_PROJECT_DIR=" + root, + "CI_DEBUG_TRACE=true", + "CI_JOB_TOKEN=job-token", + "FULLSEND_FORGE_TOKEN=shared-pat", + } + out, err := cmd.CombinedOutput() + require.Error(t, err, "stdout/stderr: %s", out) + assert.Contains(t, string(out), "CI_DEBUG_TRACE enabled") + assert.NotContains(t, string(out), "CI_JOB_TOKEN job lookup") +} + +func TestRunPollJobScript_DebugTraceAbortsBeforePin(t *testing.T) { + root := t.TempDir() + writeGitLabScript(t, root, ".gitlab/ci/scripts/trust-ci-server-ca.sh") + writeGitLabScript(t, root, gitlabPinCIJobIdentityScriptPath) + writeGitLabScript(t, root, ".gitlab/ci/scripts/select-gitlab-role-token.sh") + script := writeGitLabScript(t, root, gitlabRunPollJobScriptPath) + + cmd := exec.Command("bash", "-c", "set -euo pipefail; . \"$SCRIPT\"") + cmd.Env = []string{ + "SCRIPT=" + script, + "PATH=" + os.Getenv("PATH"), + "HOME=" + t.TempDir(), + "CI_PROJECT_DIR=" + root, + "CI_DEBUG_TRACE=true", + "CI_JOB_TOKEN=job-token", + "FULLSEND_FORGE_TOKEN=shared-pat", + } + out, err := cmd.CombinedOutput() + require.Error(t, err, "stdout/stderr: %s", out) + assert.Contains(t, string(out), "CI_DEBUG_TRACE enabled") + assert.NotContains(t, string(out), "CI_JOB_TOKEN job lookup") +} + +// TestRunAgentJobScript_UserlessPipelineRefetchesWithPinnedIDs exercises +// the run-agent-job.sh bot-identity block's PAT re-fetch path (some +// GitLab versions omit .user on the job-token pipeline GET). It also +// exercises the pin-ci-job-identity.sh project/branch/pipeline GET +// routes with a fail-closed-relevant assertion: the re-fetch must key +// off the pinned project/pipeline IDs, never the overridable +// CI_PROJECT_ID / CI_PIPELINE_ID pipeline variables. +func TestRunAgentJobScript_UserlessPipelineRefetchesWithPinnedIDs(t *testing.T) { + root := t.TempDir() + writeGitLabScript(t, root, ".gitlab/ci/scripts/trust-ci-server-ca.sh") + writeGitLabScript(t, root, gitlabPinCIJobIdentityScriptPath) + writeGitLabScript(t, root, ".gitlab/ci/scripts/select-gitlab-role-token.sh") + script := writeGitLabScript(t, root, gitlabRunAgentJobScriptPath) + + var sawPinnedRefetch atomic.Bool + var sawUnpinnedRefetch atomic.Bool + + mux := http.NewServeMux() + mux.HandleFunc("/api/v4/job", func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte(pinJobJSON("42", "100", "main"))) + }) + mux.HandleFunc("/api/v4/user", func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte(`{"id":7,"username":"fullsend-bot"}`)) + }) + mux.HandleFunc("/api/v4/projects/", func(w http.ResponseWriter, r *http.Request) { + path := r.URL.Path + switch { + case strings.Contains(path, "/repository/branches/"): + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte(`{"name":"main","protected":true}`)) + case strings.Contains(path, "/pipelines/"): + if strings.Contains(path, "/projects/1/pipelines/99") { + sawUnpinnedRefetch.Store(true) + } + if strings.Contains(path, "/projects/42/pipelines/100") && r.Header.Get("PRIVATE-TOKEN") != "" { + sawPinnedRefetch.Store(true) + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte(`{"id":100,"source":"api","user":{"id":7}}`)) + return + } + // The JOB-TOKEN pin call (and any other pipeline GET) gets the + // user-less payload that forces the PAT re-fetch below. + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte(`{"id":100,"source":"api"}`)) + default: + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte(`{"id":42,"default_branch":"main","path_with_namespace":"group/project"}`)) + } + }) + srv := httptest.NewTLSServer(mux) + t.Cleanup(srv.Close) + + cmd := exec.Command("bash", "-c", "set -euo pipefail; . \"$SCRIPT\"") + cmd.Env = append([]string{ + "SCRIPT=" + script, + "PATH=" + os.Getenv("PATH"), + "HOME=" + t.TempDir(), + "CI_PROJECT_DIR=" + root, + "RUNNER_TEMP=" + t.TempDir(), + "CI_JOB_TOKEN=job-token", + "FULLSEND_GITLAB_POLLER_TOKEN=poller-pat", + "STAGE=triage", + "RESOURCE_KEY=test-key", + "CI_PIPELINE_SOURCE=api", + // Deliberately different from the pinned project/pipeline (42/100) + // so a passing assertion below proves the re-fetch used the pinned + // IDs, not these overridable CI variables. + "CI_PROJECT_ID=1", + "CI_PIPELINE_ID=99", + }, pinTLSEnv(t, srv)...) + out, err := cmd.CombinedOutput() + require.Error(t, err, "stdout/stderr: %s", out) + assert.Contains(t, string(out), "FULLSEND_DISPATCH_SECRET is not configured") + assert.True(t, sawPinnedRefetch.Load(), "PAT re-fetch must use the pinned project/pipeline IDs") + assert.False(t, sawUnpinnedRefetch.Load(), "PAT re-fetch must not use the overridable CI_PROJECT_ID/CI_PIPELINE_ID") +} + +// computeDispatchHMAC builds the HMAC run-agent-job.sh's dispatch +// verification checks, matching the field order and printf format of +// HMAC_MESSAGE in run-agent-job.sh. +func computeDispatchHMAC(secret string, actorID, eventPayloadB64, eventType, pollJobURL, isFork, mrAuthorID, originatingURL, repoFullName, resourceKey, stage, statusIID string) string { + message := strings.Join([]string{ + "ACTOR_ID=" + actorID, + "EVENT_PAYLOAD_B64=" + eventPayloadB64, + "EVENT_TYPE=" + eventType, + "FULLSEND_POLL_JOB_URL=" + pollJobURL, + "IS_FORK=" + isFork, + "MR_AUTHOR_ID=" + mrAuthorID, + "ORIGINATING_URL=" + originatingURL, + "REPO_FULL_NAME=" + repoFullName, + "RESOURCE_KEY=" + resourceKey, + "STAGE=" + stage, + "STATUS_IID=" + statusIID, + }, "\n") + mac := hmac.New(sha256.New, []byte(secret)) + mac.Write([]byte(message)) + return hex.EncodeToString(mac.Sum(nil)) +} + +// TestRunAgentJobScript_UsesPinnedProjectIDForPATCalls is a regression +// test for the secret-exposure finding: after a successful identity pin, +// project-scoped PAT-bearing calls must use FULLSEND_PINNED_PROJECT_ID +// (from the CI_JOB_TOKEN job record), never the overridable CI_PROJECT_ID +// pipeline variable. Exercises the resource-group self-heal PUT (runs +// pre-HMAC-verification, on the poller PAT) and the Developer-access +// members lookup (runs post-HMAC-verification, on the role PAT) — the +// two call sites reachable without also standing up the fix-stage MR +// checkout (checkout-mr-source.sh). +func TestRunAgentJobScript_UsesPinnedProjectIDForPATCalls(t *testing.T) { + root := t.TempDir() + writeGitLabScript(t, root, ".gitlab/ci/scripts/trust-ci-server-ca.sh") + writeGitLabScript(t, root, gitlabPinCIJobIdentityScriptPath) + writeGitLabScript(t, root, ".gitlab/ci/scripts/select-gitlab-role-token.sh") + script := writeGitLabScript(t, root, gitlabRunAgentJobScriptPath) + + var sawPinnedResourceGroup, sawUnpinnedResourceGroup atomic.Bool + var sawPinnedMembers, sawUnpinnedMembers atomic.Bool + + mux := http.NewServeMux() + mux.HandleFunc("/api/v4/job", func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte(pinJobJSON("42", "100", "main"))) + }) + mux.HandleFunc("/api/v4/user", func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte(`{"id":7,"username":"fullsend-bot"}`)) + }) + mux.HandleFunc("/api/v4/projects/", func(w http.ResponseWriter, r *http.Request) { + path := r.URL.Path + switch { + case strings.Contains(path, "/repository/branches/"): + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte(`{"name":"main","protected":true}`)) + case strings.Contains(path, "/pipelines/"): + // Includes .user so the bot-identity block does not need the + // userless-pipeline PAT re-fetch (covered by a separate test). + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte(`{"id":100,"source":"api","user":{"id":7}}`)) + case strings.Contains(path, "/resource_groups/"): + if strings.Contains(path, "/projects/1/resource_groups/") { + sawUnpinnedResourceGroup.Store(true) + } + if strings.Contains(path, "/projects/42/resource_groups/") { + sawPinnedResourceGroup.Store(true) + } + w.WriteHeader(http.StatusOK) + case strings.Contains(path, "/members/all/"): + if strings.Contains(path, "/projects/1/members/all/") { + sawUnpinnedMembers.Store(true) + } + if strings.Contains(path, "/projects/42/members/all/") { + sawPinnedMembers.Store(true) + } + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte(`{"access_level":40}`)) + default: + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte(`{"id":42,"default_branch":"main","path_with_namespace":"group/project"}`)) + } + }) + srv := httptest.NewTLSServer(mux) + t.Cleanup(srv.Close) + + bin := t.TempDir() + fullsendStub := filepath.Join(bin, "fullsend") + require.NoError(t, os.WriteFile(fullsendStub, []byte("#!/bin/sh\nexit 0\n"), 0o755)) + + const secret = "test-hmac-secret" + hmacHex := computeDispatchHMAC(secret, "5", "", "", "", "", "", "", "", "test-key", "triage", "") + + // The trusted-config fetch (CONFIG_YAML/kill-switch) now always runs + // against FULLSEND_PINNED_REF, so `root` must be a real git checkout + // with an "origin" remote for `git fetch origin main --depth=1` to + // succeed. + setupPinnedConfigOrigin(t, root) + + cmd := exec.Command("bash", "-c", "set -euo pipefail; . \"$SCRIPT\"") + cmd.Dir = root + cmd.Env = append([]string{ + "SCRIPT=" + script, + "PATH=" + bin + ":" + os.Getenv("PATH"), + "HOME=" + t.TempDir(), + "CI_PROJECT_DIR=" + root, + "RUNNER_TEMP=" + t.TempDir(), + "CI_JOB_TOKEN=job-token", + "FULLSEND_GITLAB_POLLER_TOKEN=poller-pat", + "FULLSEND_GITLAB_ANALYST_TOKEN=analyst-pat", + "STAGE=triage", + "RESOURCE_KEY=test-key", + "ACTOR_ID=5", + "FULLSEND_DISPATCH_SECRET=" + secret, + "FULLSEND_DISPATCH_HMAC=" + hmacHex, + "CI_PROJECT_PATH=group/project", + "CI_SERVER_URL=https://gitlab.example", + "CI_PIPELINE_URL=https://gitlab.example/group/project/-/pipelines/100", + // Deliberately different from the pinned project (42) so a passing + // assertion below proves these calls used the pinned project id, + // not this overridable CI variable. + "CI_PROJECT_ID=1", + }, pinTLSEnv(t, srv)...) + out, err := cmd.CombinedOutput() + require.NoError(t, err, "stdout/stderr: %s", out) + + assert.True(t, sawPinnedResourceGroup.Load(), "resource-group PUT must use the pinned project id") + assert.False(t, sawUnpinnedResourceGroup.Load(), "resource-group PUT must not use the overridable CI_PROJECT_ID") + assert.True(t, sawPinnedMembers.Load(), "members lookup must use the pinned project id") + assert.False(t, sawUnpinnedMembers.Load(), "members lookup must not use the overridable CI_PROJECT_ID") +} + +// TestRunPollJobScript_UsesPinnedIdentityForCLIArgs is a regression test +// for the secret-exposure finding on the `fullsend poll` invocation: after +// a successful identity pin, --project and --gitlab-url must come from +// FULLSEND_PINNED_PROJECT_PATH / FULLSEND_PINNED_GITLAB_URL (the +// CI_JOB_TOKEN job record via pin-ci-job-identity.sh), never the +// overridable CI_PROJECT_PATH / CI_SERVER_URL / FULLSEND_GITLAB_URL +// pipeline variables. +func TestRunPollJobScript_UsesPinnedIdentityForCLIArgs(t *testing.T) { + root := t.TempDir() + writeGitLabScript(t, root, ".gitlab/ci/scripts/trust-ci-server-ca.sh") + writeGitLabScript(t, root, gitlabPinCIJobIdentityScriptPath) + writeGitLabScript(t, root, ".gitlab/ci/scripts/select-gitlab-role-token.sh") + script := writeGitLabScript(t, root, gitlabRunPollJobScriptPath) + + st := &pinAPIState{ + jobJSON: pinJobJSON("42", "100", "main"), + projectJSON: `{"id":42,"default_branch":"main","path_with_namespace":"pinned/project"}`, + branchJSON: `{"name":"main","protected":true}`, + pipelineJSON: `{"id":100,"source":"schedule"}`, + } + srv := startPinAPI(t, st) + t.Cleanup(srv.Close) + + bin := t.TempDir() + require.NoError(t, os.WriteFile(filepath.Join(bin, "fullsend"), []byte("#!/bin/sh\necho FULLSEND_ARGS: \"$@\"\n"), 0o755)) + + cmd := exec.Command("bash", "-c", "set -euo pipefail; . \"$SCRIPT\"") + cmd.Env = append([]string{ + "SCRIPT=" + script, + "PATH=" + bin + ":" + os.Getenv("PATH"), + "HOME=" + t.TempDir(), + "CI_PROJECT_DIR=" + root, + "RUNNER_TEMP=" + t.TempDir(), + "CI_JOB_TOKEN=job-token", + "FULLSEND_GITLAB_POLLER_TOKEN=poller-pat", + "FULLSEND_POLL_MODE=events", + // Deliberately distinct from the pinned project path/API root so a + // passing assertion below proves the poll CLI args use the pinned + // identity, not these overridable pipeline variables. + "CI_PROJECT_ID=1", + "CI_PROJECT_PATH=unpinned/project", + "CI_SERVER_URL=https://unpinned.example", + "FULLSEND_GITLAB_URL=https://also-unpinned.example", + }, pinTLSEnv(t, srv)...) + out, err := cmd.CombinedOutput() + require.NoError(t, err, "stdout/stderr: %s", out) + got := string(out) + assert.Contains(t, got, "--project pinned/project") + assert.Contains(t, got, "--gitlab-url "+srv.URL) + assert.NotContains(t, got, "unpinned/project") + assert.NotContains(t, got, "unpinned.example") +} + +// TestRunPollJobScript_UsesPinnedRefForDispatch is a regression test for +// the runtime-mechanism finding on the `fullsend poll` invocation: +// internal/cli/poll.go's pipelineRef (the ref new dispatched pipelines +// target) comes from CI_COMMIT_REF_NAME, falling back to +// CI_DEFAULT_BRANCH — both overridable pipeline variables, unlike this +// poller job's own identity, which pin-ci-job-identity.sh already pins +// to FULLSEND_PINNED_REF. run-poll-job.sh must export CI_COMMIT_REF_NAME +// from FULLSEND_PINNED_REF before invoking `fullsend poll`, overriding +// whatever CI_COMMIT_REF_NAME/CI_DEFAULT_BRANCH a trigger-influenced +// pipeline/schedule variable set it to. +func TestRunPollJobScript_UsesPinnedRefForDispatch(t *testing.T) { + root := t.TempDir() + writeGitLabScript(t, root, ".gitlab/ci/scripts/trust-ci-server-ca.sh") + writeGitLabScript(t, root, gitlabPinCIJobIdentityScriptPath) + writeGitLabScript(t, root, ".gitlab/ci/scripts/select-gitlab-role-token.sh") + script := writeGitLabScript(t, root, gitlabRunPollJobScriptPath) + + st := &pinAPIState{ + jobJSON: pinJobJSON("42", "100", "main"), + projectJSON: `{"id":42,"default_branch":"main","path_with_namespace":"pinned/project"}`, + branchJSON: `{"name":"main","protected":true}`, + pipelineJSON: `{"id":100,"source":"schedule"}`, + } + srv := startPinAPI(t, st) + t.Cleanup(srv.Close) + + bin := t.TempDir() + require.NoError(t, os.WriteFile(filepath.Join(bin, "fullsend"), []byte( + "#!/bin/sh\necho CI_COMMIT_REF_NAME: \"$CI_COMMIT_REF_NAME\"\n", + ), 0o755)) + + cmd := exec.Command("bash", "-c", "set -euo pipefail; . \"$SCRIPT\"") + cmd.Env = append([]string{ + "SCRIPT=" + script, + "PATH=" + bin + ":" + os.Getenv("PATH"), + "HOME=" + t.TempDir(), + "CI_PROJECT_DIR=" + root, + "RUNNER_TEMP=" + t.TempDir(), + "CI_JOB_TOKEN=job-token", + "FULLSEND_GITLAB_POLLER_TOKEN=poller-pat", + "FULLSEND_POLL_MODE=events", + "CI_PROJECT_ID=1", + "CI_PROJECT_PATH=pinned/project", + // Deliberately distinct from the pinned ref (main) so a passing + // assertion below proves the dispatch ref `fullsend poll` sees + // comes from FULLSEND_PINNED_REF, not these overridable pipeline + // variables — including the poller job's own predefined + // CI_COMMIT_REF_NAME, which normally matches the pinned ref but + // is still an overridable variable an attacker-controlled + // project/schedule variable of the same name could shadow. + "CI_COMMIT_REF_NAME=attacker-ref", + "CI_DEFAULT_BRANCH=attacker-ref", + }, pinTLSEnv(t, srv)...) + out, err := cmd.CombinedOutput() + require.NoError(t, err, "stdout/stderr: %s", out) + got := string(out) + assert.Contains(t, got, "CI_COMMIT_REF_NAME: main") + assert.NotContains(t, got, "CI_COMMIT_REF_NAME: attacker-ref") +} + +// TestRunAgentJobScript_UsesPinnedIdentityForStatusRepo is a regression +// test for the secret-exposure finding on the `fullsend run` invocation: +// after a successful identity pin, --status-repo must come from +// FULLSEND_PINNED_PROJECT_PATH (the CI_JOB_TOKEN job record), never the +// overridable CI_PROJECT_PATH pipeline variable. +func TestRunAgentJobScript_UsesPinnedIdentityForStatusRepo(t *testing.T) { + root := t.TempDir() + writeGitLabScript(t, root, ".gitlab/ci/scripts/trust-ci-server-ca.sh") + writeGitLabScript(t, root, gitlabPinCIJobIdentityScriptPath) + writeGitLabScript(t, root, ".gitlab/ci/scripts/select-gitlab-role-token.sh") + script := writeGitLabScript(t, root, gitlabRunAgentJobScriptPath) + + mux := http.NewServeMux() + mux.HandleFunc("/api/v4/job", func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte(pinJobJSON("42", "100", "main"))) + }) + mux.HandleFunc("/api/v4/user", func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte(`{"id":7,"username":"fullsend-bot"}`)) + }) + mux.HandleFunc("/api/v4/projects/", func(w http.ResponseWriter, r *http.Request) { + path := r.URL.Path + switch { + case strings.Contains(path, "/repository/branches/"): + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte(`{"name":"main","protected":true}`)) + case strings.Contains(path, "/pipelines/"): + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte(`{"id":100,"source":"api","user":{"id":7}}`)) + case strings.Contains(path, "/resource_groups/"): + w.WriteHeader(http.StatusOK) + case strings.Contains(path, "/members/all/"): + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte(`{"access_level":40}`)) + default: + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte(`{"id":42,"default_branch":"main","path_with_namespace":"pinned/project"}`)) + } + }) + srv := httptest.NewTLSServer(mux) + t.Cleanup(srv.Close) + + bin := t.TempDir() + require.NoError(t, os.WriteFile(filepath.Join(bin, "fullsend"), []byte("#!/bin/sh\necho FULLSEND_ARGS: \"$@\"\n"), 0o755)) + + const secret = "test-hmac-secret" + hmacHex := computeDispatchHMAC(secret, "5", "", "", "", "", "", "", "", "test-key", "triage", "") + + // The trusted-config fetch (CONFIG_YAML/kill-switch) now always runs + // against FULLSEND_PINNED_REF, so `root` must be a real git checkout + // with an "origin" remote for `git fetch origin main --depth=1` to + // succeed. + setupPinnedConfigOrigin(t, root) + + cmd := exec.Command("bash", "-c", "set -euo pipefail; . \"$SCRIPT\"") + cmd.Dir = root + cmd.Env = append([]string{ + "SCRIPT=" + script, + "PATH=" + bin + ":" + os.Getenv("PATH"), + "HOME=" + t.TempDir(), + "CI_PROJECT_DIR=" + root, + "RUNNER_TEMP=" + t.TempDir(), + "CI_JOB_TOKEN=job-token", + "FULLSEND_GITLAB_POLLER_TOKEN=poller-pat", + "FULLSEND_GITLAB_ANALYST_TOKEN=analyst-pat", + "STAGE=triage", + "RESOURCE_KEY=test-key", + "ACTOR_ID=5", + "FULLSEND_DISPATCH_SECRET=" + secret, + "FULLSEND_DISPATCH_HMAC=" + hmacHex, + "CI_PIPELINE_URL=https://gitlab.example/pinned/project/-/pipelines/999", + // Deliberately distinct from the pinned project path so a passing + // assertion below proves --status-repo uses the pinned identity, + // not the overridable CI_PROJECT_PATH pipeline variable. + "CI_PROJECT_ID=1", + "CI_PROJECT_PATH=unpinned/project", + "CI_SERVER_URL=https://unpinned.example", + }, pinTLSEnv(t, srv)...) + out, err := cmd.CombinedOutput() + require.NoError(t, err, "stdout/stderr: %s", out) + got := string(out) + assert.Contains(t, got, "--status-repo pinned/project") + assert.NotContains(t, got, "--status-repo unpinned/project") + assert.NotContains(t, got, "unpinned.example") +} + +// TestRunAgentJobScript_UsesPinnedGitLabURLForFullsendRun is a regression +// test for the secret-exposure finding on the `fullsend run` invocation: +// `fullsend run` has no --gitlab-url flag, so its GitLab client +// (newGitLabClientFromEnv in internal/cli/reconcilestatus.go) resolves +// the API host from FULLSEND_GITLAB_URL, then GITLAB_API_URL, then +// CI_SERVER_URL — all overridable pipeline variables in the same +// outrankable class as CI_PROJECT_ID (ADR 0125). run-agent-job.sh must +// export FULLSEND_GITLAB_URL from FULLSEND_PINNED_GITLAB_URL before +// invoking `fullsend run`, so that resolution never falls through to one +// of those instead. +func TestRunAgentJobScript_UsesPinnedGitLabURLForFullsendRun(t *testing.T) { + root := t.TempDir() + writeGitLabScript(t, root, ".gitlab/ci/scripts/trust-ci-server-ca.sh") + writeGitLabScript(t, root, gitlabPinCIJobIdentityScriptPath) + writeGitLabScript(t, root, ".gitlab/ci/scripts/select-gitlab-role-token.sh") + script := writeGitLabScript(t, root, gitlabRunAgentJobScriptPath) + + mux := http.NewServeMux() + mux.HandleFunc("/api/v4/job", func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte(pinJobJSON("42", "100", "main"))) + }) + mux.HandleFunc("/api/v4/user", func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte(`{"id":7,"username":"fullsend-bot"}`)) + }) + mux.HandleFunc("/api/v4/projects/", func(w http.ResponseWriter, r *http.Request) { + path := r.URL.Path + switch { + case strings.Contains(path, "/repository/branches/"): + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte(`{"name":"main","protected":true}`)) + case strings.Contains(path, "/pipelines/"): + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte(`{"id":100,"source":"api","user":{"id":7}}`)) + case strings.Contains(path, "/resource_groups/"): + w.WriteHeader(http.StatusOK) + case strings.Contains(path, "/members/all/"): + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte(`{"access_level":40}`)) + default: + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte(`{"id":42,"default_branch":"main","path_with_namespace":"pinned/project"}`)) + } + }) + srv := httptest.NewTLSServer(mux) + t.Cleanup(srv.Close) + + bin := t.TempDir() + require.NoError(t, os.WriteFile(filepath.Join(bin, "fullsend"), []byte( + `#!/bin/sh +if [ "$1" = "run" ]; then + echo "FULLSEND_GITLAB_URL: $FULLSEND_GITLAB_URL" +fi +`), 0o755)) + + const secret = "test-hmac-secret" + hmacHex := computeDispatchHMAC(secret, "5", "", "", "", "", "", "", "", "test-key", "triage", "") + + setupPinnedConfigOrigin(t, root) + + cmd := exec.Command("bash", "-c", "set -euo pipefail; . \"$SCRIPT\"") + cmd.Dir = root + cmd.Env = append([]string{ + "SCRIPT=" + script, + "PATH=" + bin + ":" + os.Getenv("PATH"), + "HOME=" + t.TempDir(), + "CI_PROJECT_DIR=" + root, + "RUNNER_TEMP=" + t.TempDir(), + "CI_JOB_TOKEN=job-token", + "FULLSEND_GITLAB_POLLER_TOKEN=poller-pat", + "FULLSEND_GITLAB_ANALYST_TOKEN=analyst-pat", + "STAGE=triage", + "RESOURCE_KEY=test-key", + "ACTOR_ID=5", + "FULLSEND_DISPATCH_SECRET=" + secret, + "FULLSEND_DISPATCH_HMAC=" + hmacHex, + "CI_PIPELINE_URL=https://gitlab.example/pinned/project/-/pipelines/999", + "CI_PROJECT_ID=1", + "CI_PROJECT_PATH=pinned/project", + // Deliberately distinct from the pin-validated API root so a + // passing assertion below proves the `fullsend run` child + // environment's FULLSEND_GITLAB_URL comes from + // FULLSEND_PINNED_GITLAB_URL, not these overridable variables. + "CI_SERVER_URL=https://unpinned.example", + "GITLAB_API_URL=https://also-unpinned.example", + "FULLSEND_GITLAB_URL=https://also-unpinned.example", + }, pinTLSEnv(t, srv)...) + out, err := cmd.CombinedOutput() + require.NoError(t, err, "stdout/stderr: %s", out) + got := string(out) + assert.Contains(t, got, "FULLSEND_GITLAB_URL: "+srv.URL) + assert.NotContains(t, got, "unpinned.example") +} + +// TestRunAgentJobScript_UsesPinnedRefForTrustedConfigAndTargetBranch is a +// regression test for the fail-open finding: run-agent-job.sh's +// trusted-config fetch (kill-switch/role-enablement) and its +// STAGE=fix TARGET_BRANCH fallback must both derive from +// FULLSEND_PINNED_REF (the CI_JOB_TOKEN job record's ref, already +// proven equal to the enrolled protected default branch), never the +// overridable CI_DEFAULT_BRANCH pipeline variable. +// +// The enrolled project has two branches: "main" (the pinned default +// branch, kill_switch: false) and "malicious" (kill_switch: true). +// CI_DEFAULT_BRANCH is set to "malicious". If run-agent-job.sh ever +// again reads CI_DEFAULT_BRANCH instead of FULLSEND_PINNED_REF for the +// trusted-config fetch, it fetches the malicious config, trips the +// kill switch, and the job aborts (require.NoError below fails). A +// third "feature" branch supplies the MR source revision checked out +// by checkout-mr-source.sh. +func TestRunAgentJobScript_UsesPinnedRefForTrustedConfigAndTargetBranch(t *testing.T) { + // Seed the enrolled project's three branches and a bare "GitLab + // server" repo, mirroring seedSameProjectOrigin in + // checkout_mr_source_test.go. + work := t.TempDir() + initGitRepo(t, work) + commitFile(t, work, ".fullsend/config.yaml", "kill_switch: false\n", "trusted config") + gitCmd(t, work, "checkout", "-b", "malicious") + commitFile(t, work, ".fullsend/config.yaml", "kill_switch: true\n", "malicious config") + gitCmd(t, work, "checkout", "-b", "feature", "main") + sourceSHA := commitFile(t, work, "fix.txt", "fix content\n", "feature commit") + + serverRoot := filepath.Join(t.TempDir(), "gitlab") + bare := filepath.Join(serverRoot, "group/project.git") + require.NoError(t, os.MkdirAll(filepath.Dir(bare), 0o755)) + gitCmd(t, work, "clone", "--bare", ".", bare) + + runner := filepath.Join(t.TempDir(), "runner") + gitCmd(t, t.TempDir(), "clone", "--depth=1", "--branch", "main", bare, runner) + + writeGitLabScript(t, runner, ".gitlab/ci/scripts/trust-ci-server-ca.sh") + writeGitLabScript(t, runner, gitlabPinCIJobIdentityScriptPath) + writeGitLabScript(t, runner, ".gitlab/ci/scripts/select-gitlab-role-token.sh") + writeGitLabScript(t, runner, gitlabCheckoutMRSourceScriptPath) + script := writeGitLabScript(t, runner, gitlabRunAgentJobScriptPath) + + mux := http.NewServeMux() + mux.HandleFunc("/api/v4/job", func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte(pinJobJSON("42", "100", "main"))) + }) + mux.HandleFunc("/api/v4/user", func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte(`{"id":7,"username":"fullsend-bot"}`)) + }) + mux.HandleFunc("/api/v4/projects/", func(w http.ResponseWriter, r *http.Request) { + path := r.URL.Path + switch { + case strings.Contains(path, "/repository/branches/"): + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte(`{"name":"main","protected":true}`)) + case strings.Contains(path, "/pipelines/"): + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte(`{"id":100,"source":"api","user":{"id":7}}`)) + case strings.Contains(path, "/resource_groups/"): + w.WriteHeader(http.StatusOK) + case strings.Contains(path, "/members/all/"): + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte(`{"access_level":40}`)) + case strings.Contains(path, "/merge_requests/") && strings.Contains(path, "/notes"): + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte(`[]`)) + case strings.Contains(path, "/merge_requests/") && strings.Contains(path, "/commits"): + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte(`[]`)) + case strings.Contains(path, "/merge_requests/"): + // No target_branch — forces the fallback under test. + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte(`{}`)) + default: + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte(`{"id":42,"default_branch":"main","path_with_namespace":"group/project"}`)) + } + }) + // checkout-mr-source.sh now fetches the MR source from + // FULLSEND_PINNED_GITLAB_URL (derived from the pin-validated + // CI_API_V4_URL, i.e. this same TLS server), not the overridable + // CI_SERVER_URL — so the bare "group/project.git" repo must be + // reachable over smart HTTP from this server too, alongside the + // JSON API mocks above. + mux.Handle("/group/", &cgi.Handler{ + Path: gitHTTPBackendPath(t), + Env: []string{ + "GIT_PROJECT_ROOT=" + serverRoot, + "GIT_HTTP_EXPORT_ALL=1", + "PATH=" + os.Getenv("PATH"), + "GIT_CONFIG_NOSYSTEM=1", + "GIT_CONFIG_GLOBAL=/dev/null", + "HOME=" + t.TempDir(), + }, + }) + srv := httptest.NewTLSServer(mux) + t.Cleanup(srv.Close) + + resolvedJSON, err := json.Marshal(map[string]any{ + "source_branch": "feature", + "source_sha": sourceSHA, + "source_project_path": "group/project", + }) + require.NoError(t, err) + resolvedPath := filepath.Join(t.TempDir(), "resolve.json") + require.NoError(t, os.WriteFile(resolvedPath, resolvedJSON, 0o644)) + + bin := t.TempDir() + require.NoError(t, os.WriteFile(filepath.Join(bin, "fullsend"), []byte( + `#!/bin/sh +case "$1" in + resolve-mr-source) + cat "$RESOLVE_JSON_FILE" + ;; + run) + echo "TARGET_BRANCH: $TARGET_BRANCH" + ;; + eval-measure) + exit 0 + ;; + *) + echo "unexpected fullsend subcommand: $1" >&2 + exit 1 + ;; +esac +`), 0o755)) + + const secret = "test-hmac-secret" + hmacHex := computeDispatchHMAC(secret, "5", "", "", "", "false", "", "", "", "test-key", "fix", "7") + + cmd := exec.Command("bash", "-c", "set -euo pipefail; . \"$SCRIPT\"") + cmd.Dir = runner + cmd.Env = append([]string{ + "SCRIPT=" + script, + "PATH=" + bin + ":" + os.Getenv("PATH"), + "HOME=" + t.TempDir(), + "CI_PROJECT_DIR=" + runner, + "RUNNER_TEMP=" + t.TempDir(), + "CI_JOB_TOKEN=job-token", + "FULLSEND_GITLAB_POLLER_TOKEN=poller-pat", + "FULLSEND_GITLAB_ANALYST_TOKEN=analyst-pat", + "FULLSEND_GITLAB_CODER_TOKEN=coder-pat", + "STAGE=fix", + "RESOURCE_KEY=test-key", + "ACTOR_ID=5", + "STATUS_IID=7", + "IS_FORK=false", + "FULLSEND_DISPATCH_SECRET=" + secret, + "FULLSEND_DISPATCH_HMAC=" + hmacHex, + "CI_PROJECT_ID=42", + "CI_PROJECT_PATH=group/project", + "CI_SERVER_URL=" + serverRoot, + "CI_PIPELINE_URL=" + serverRoot + "/group/project/-/pipelines/100", + "RESOLVE_JSON_FILE=" + resolvedPath, + // The attack this test defends against: an ordinary + // project/schedule CI/CD variable overriding CI_DEFAULT_BRANCH + // to a branch that exists (so the fetch itself doesn't just + // fail) but carries a different trusted-config payload and a + // different TARGET_BRANCH fallback value than the pinned ref. + "CI_DEFAULT_BRANCH=malicious", + }, pinTLSEnv(t, srv)...) + out, err := cmd.CombinedOutput() + require.NoError(t, err, "stdout/stderr: %s", out) + got := string(out) + assert.Contains(t, got, "TARGET_BRANCH: main") + assert.NotContains(t, got, "malicious") +} + +// TestRunAgentJobScript_RejectsDisagreeingMergeRequestTargetBranchName is a +// regression test for the logic-error finding: this job's admit source is +// api-only (parent_pipeline is not an admitted arm — see FULLSEND_ADMIT_SOURCE +// in run-agent-job.sh), so GitLab never natively populates +// CI_MERGE_REQUEST_TARGET_BRANCH_NAME here. A non-empty value is therefore an +// ordinary, overridable project/group/pipeline CI/CD variable — the same +// outrankable class ADR 0125 already establishes for +// CI_PROJECT_ID/CI_DEFAULT_BRANCH. run-agent-job.sh must resolve +// TARGET_BRANCH from the pinned-project MR API (falling back to +// FULLSEND_PINNED_REF) and fail closed when CI_MERGE_REQUEST_TARGET_BRANCH_NAME +// disagrees with that resolved value, instead of trusting it outright. +func TestRunAgentJobScript_RejectsDisagreeingMergeRequestTargetBranchName(t *testing.T) { + // The failure under test happens before the fix-stage MR source + // checkout, so only a "main" branch carrying trusted config is + // needed — no feature branch, resolve-mr-source stub, or git-smart- + // HTTP backend required. + work := t.TempDir() + initGitRepo(t, work) + commitFile(t, work, ".fullsend/config.yaml", "kill_switch: false\n", "trusted config") + + serverRoot := filepath.Join(t.TempDir(), "gitlab") + bare := filepath.Join(serverRoot, "group/project.git") + require.NoError(t, os.MkdirAll(filepath.Dir(bare), 0o755)) + gitCmd(t, work, "clone", "--bare", ".", bare) + + runner := filepath.Join(t.TempDir(), "runner") + gitCmd(t, t.TempDir(), "clone", "--depth=1", "--branch", "main", bare, runner) + + writeGitLabScript(t, runner, ".gitlab/ci/scripts/trust-ci-server-ca.sh") + writeGitLabScript(t, runner, gitlabPinCIJobIdentityScriptPath) + writeGitLabScript(t, runner, ".gitlab/ci/scripts/select-gitlab-role-token.sh") + writeGitLabScript(t, runner, gitlabCheckoutMRSourceScriptPath) + script := writeGitLabScript(t, runner, gitlabRunAgentJobScriptPath) + + mux := http.NewServeMux() + mux.HandleFunc("/api/v4/job", func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte(pinJobJSON("42", "100", "main"))) + }) + mux.HandleFunc("/api/v4/user", func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte(`{"id":7,"username":"fullsend-bot"}`)) + }) + mux.HandleFunc("/api/v4/projects/", func(w http.ResponseWriter, r *http.Request) { + path := r.URL.Path + switch { + case strings.Contains(path, "/repository/branches/"): + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte(`{"name":"main","protected":true}`)) + case strings.Contains(path, "/pipelines/"): + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte(`{"id":100,"source":"api","user":{"id":7}}`)) + case strings.Contains(path, "/members/all/"): + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte(`{"access_level":40}`)) + case strings.Contains(path, "/merge_requests/") && strings.Contains(path, "/notes"): + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte(`[]`)) + case strings.Contains(path, "/merge_requests/"): + // Pinned-project MR API's target branch: "main" — distinct + // from the CI_MERGE_REQUEST_TARGET_BRANCH_NAME under test. + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte(`{"target_branch":"main"}`)) + default: + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte(`{"id":42,"default_branch":"main","path_with_namespace":"group/project"}`)) + } + }) + srv := httptest.NewTLSServer(mux) + t.Cleanup(srv.Close) + + const secret = "test-hmac-secret" + hmacHex := computeDispatchHMAC(secret, "5", "", "", "", "false", "", "", "", "test-key", "fix", "7") + + cmd := exec.Command("bash", "-c", "set -euo pipefail; . \"$SCRIPT\"") + cmd.Dir = runner + cmd.Env = append([]string{ + "SCRIPT=" + script, + "PATH=" + os.Getenv("PATH"), + "HOME=" + t.TempDir(), + "CI_PROJECT_DIR=" + runner, + "RUNNER_TEMP=" + t.TempDir(), + "CI_JOB_TOKEN=job-token", + "FULLSEND_GITLAB_POLLER_TOKEN=poller-pat", + "FULLSEND_GITLAB_ANALYST_TOKEN=analyst-pat", + "FULLSEND_GITLAB_CODER_TOKEN=coder-pat", + "STAGE=fix", + "RESOURCE_KEY=test-key", + "ACTOR_ID=5", + "STATUS_IID=7", + "IS_FORK=false", + "FULLSEND_DISPATCH_SECRET=" + secret, + "FULLSEND_DISPATCH_HMAC=" + hmacHex, + "CI_PROJECT_ID=42", + "CI_PROJECT_PATH=group/project", + "CI_SERVER_URL=" + serverRoot, + "CI_PIPELINE_URL=" + serverRoot + "/group/project/-/pipelines/100", + // source=api pipelines never natively populate this variable; + // a non-empty value here can only come from an ordinary, + // overridable CI/CD variable, and it disagrees with the + // pinned-project MR API's target branch ("main") mocked above. + "CI_MERGE_REQUEST_TARGET_BRANCH_NAME=malicious", + }, pinTLSEnv(t, srv)...) + out, err := cmd.CombinedOutput() + require.Error(t, err, "stdout/stderr: %s", out) + assert.Contains(t, string(out), "does not match the pinned/API target branch") +} + +// TestRunAgentJobScript_IgnoresUnsignedMergeRequestIIDWhenStatusIIDMissing is +// a regression test for the fail-open finding: this job's admit source is +// api-only, so GitLab never natively populates CI_MERGE_REQUEST_IID here — +// any value comes solely from an ordinary, overridable project/group/ +// pipeline CI/CD variable. The existing fail-closed check only catches a +// CI_MERGE_REQUEST_IID that *disagrees* with a non-zero, HMAC-signed +// STATUS_IID; when STATUS_IID is empty (the common case for this job, which +// never natively receives it either), the unsigned CI_MERGE_REQUEST_IID must +// not be trusted as a fallback identity source for the GITLAB_ISSUE_URL +// merge-request link, the STAGE=review prior-review Notes API lookup, or the +// shared code|fix|review MR_IID/MR_NUMBER/GITLAB_MR_URL resolution — all +// three must treat the merge request as unidentified (IID "0") instead of +// keying a same-project Notes read or status link on the spoofed value. +func TestRunAgentJobScript_IgnoresUnsignedMergeRequestIIDWhenStatusIIDMissing(t *testing.T) { + root := t.TempDir() + writeGitLabScript(t, root, ".gitlab/ci/scripts/trust-ci-server-ca.sh") + writeGitLabScript(t, root, gitlabPinCIJobIdentityScriptPath) + writeGitLabScript(t, root, ".gitlab/ci/scripts/select-gitlab-role-token.sh") + script := writeGitLabScript(t, root, gitlabRunAgentJobScriptPath) + + var sawSpoofedNotesLookup atomic.Bool + mux := http.NewServeMux() + mux.HandleFunc("/api/v4/job", func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte(pinJobJSON("42", "100", "main"))) + }) + mux.HandleFunc("/api/v4/user", func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte(`{"id":7,"username":"fullsend-bot"}`)) + }) + mux.HandleFunc("/api/v4/projects/", func(w http.ResponseWriter, r *http.Request) { + path := r.URL.Path + switch { + case strings.Contains(path, "/repository/branches/"): + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte(`{"name":"main","protected":true}`)) + case strings.Contains(path, "/pipelines/"): + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte(`{"id":100,"source":"api","user":{"id":7}}`)) + case strings.Contains(path, "/members/all/"): + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte(`{"access_level":40}`)) + case strings.Contains(path, "/merge_requests/999/notes"): + // The spoofed CI_MERGE_REQUEST_IID. Any hit here means the + // fail-open bug has regressed: the unsigned, unverified + // CI variable was used to key a role-PAT Notes API read. + sawSpoofedNotesLookup.Store(true) + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte(`[]`)) + default: + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte(`{"id":42,"default_branch":"main","path_with_namespace":"pinned/project"}`)) + } + }) + srv := httptest.NewTLSServer(mux) + t.Cleanup(srv.Close) + + // run-agent-job.sh ends with `exit "${RUN_STATUS}"`, so a sourcing + // shell never returns control to any commands appended after the + // `. "$SCRIPT"` call. Observe the resolved identity by having the + // stub `fullsend` binary — invoked as a child process that inherits + // the exported environment — dump the variables under test before + // the script exits. + bin := t.TempDir() + require.NoError(t, os.WriteFile(filepath.Join(bin, "fullsend"), []byte( + "#!/bin/sh\n"+ + "echo FULLSEND_ARGS: \"$@\"\n"+ + "echo STUB_ENV GITLAB_ISSUE_URL=\"${GITLAB_ISSUE_URL:-EMPTY}\"\n"+ + "echo STUB_ENV GITLAB_MR_URL=\"${GITLAB_MR_URL:-EMPTY}\"\n"+ + "echo STUB_ENV MR_NUMBER=\"${MR_NUMBER:-EMPTY}\"\n"+ + "exit 0\n"), 0o755)) + + const secret = "test-hmac-secret" + // STATUS_IID is part of the HMAC-signed dispatch message and is + // deliberately empty here — this job never natively receives an MR + // IID either, so an empty signed value is the common case, not an + // edge case. + hmacHex := computeDispatchHMAC(secret, "5", "", "mr_note", "", "false", "", "", "", "test-key", "review", "") + + setupPinnedConfigOrigin(t, root) + + cmd := exec.Command("bash", "-c", `set -euo pipefail; . "$SCRIPT"`) + cmd.Dir = root + cmd.Env = append([]string{ + "SCRIPT=" + script, + "PATH=" + bin + ":" + os.Getenv("PATH"), + "HOME=" + t.TempDir(), + "CI_PROJECT_DIR=" + root, + "RUNNER_TEMP=" + t.TempDir(), + "CI_JOB_TOKEN=job-token", + "FULLSEND_GITLAB_POLLER_TOKEN=poller-pat", + "FULLSEND_GITLAB_ANALYST_TOKEN=analyst-pat", + "STAGE=review", + "EVENT_TYPE=mr_note", + "RESOURCE_KEY=test-key", + "ACTOR_ID=5", + "IS_FORK=false", + "FULLSEND_DISPATCH_SECRET=" + secret, + "FULLSEND_DISPATCH_HMAC=" + hmacHex, + "CI_PIPELINE_URL=https://gitlab.example/pinned/project/-/pipelines/999", + // STATUS_IID is deliberately left unset — the signed dispatch + // carries no MR identity for this run. + // CI_MERGE_REQUEST_IID is an ordinary, overridable pipeline + // variable spoofing a merge request the dispatch never signed. + "CI_MERGE_REQUEST_IID=999", + "CI_PROJECT_ID=1", + "CI_PROJECT_PATH=unpinned/project", + "CI_SERVER_URL=https://unpinned.example", + }, pinTLSEnv(t, srv)...) + out, err := cmd.CombinedOutput() + require.NoError(t, err, "stdout/stderr: %s", out) + got := string(out) + + assert.False(t, sawSpoofedNotesLookup.Load(), "must not query the Notes API for the unsigned, spoofed CI_MERGE_REQUEST_IID") + assert.Contains(t, got, "No prior review found (no bot identity or no MR IID)") + assert.NotContains(t, got, "/merge_requests/999") + assert.Contains(t, got, "STUB_ENV GITLAB_ISSUE_URL=EMPTY") + assert.Contains(t, got, "STUB_ENV GITLAB_MR_URL=EMPTY") + assert.Contains(t, got, "STUB_ENV MR_NUMBER=0") + assert.Contains(t, got, "--status-number 0") + assert.NotContains(t, got, "--status-number 999") +} + +// TestRunAgentJobScript_UnsetsMergeRequestIIDForIssueEvent is a regression +// test for the auth-bypass finding: in the issue_* EVENT_TYPE arm, this +// job's admit source is api-only, so GitLab never natively populates +// CI_MERGE_REQUEST_IID — any value present is an ordinary, outrankable +// project/group/pipeline CI/CD variable. newGitLabClientFromEnv +// (internal/cli/reconcilestatus.go) routes status-comment API calls to the +// merge_requests noteable type whenever CI_MERGE_REQUEST_IID is merely +// non-empty, regardless of FULLSEND_NOTE_TARGET — so a stray +// CI_MERGE_REQUEST_IID must not reach the fullsend CLI subprocess on an +// issue event, even when its value happens to equal the signed STATUS_IID +// (mere presence, not value mismatch, is what misdirects the note target). +func TestRunAgentJobScript_UnsetsMergeRequestIIDForIssueEvent(t *testing.T) { + root := t.TempDir() + writeGitLabScript(t, root, ".gitlab/ci/scripts/trust-ci-server-ca.sh") + writeGitLabScript(t, root, gitlabPinCIJobIdentityScriptPath) + writeGitLabScript(t, root, ".gitlab/ci/scripts/select-gitlab-role-token.sh") + script := writeGitLabScript(t, root, gitlabRunAgentJobScriptPath) + + mux := http.NewServeMux() + mux.HandleFunc("/api/v4/job", func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte(pinJobJSON("42", "100", "main"))) + }) + mux.HandleFunc("/api/v4/user", func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte(`{"id":7,"username":"fullsend-bot"}`)) + }) + mux.HandleFunc("/api/v4/projects/", func(w http.ResponseWriter, r *http.Request) { + path := r.URL.Path + switch { + case strings.Contains(path, "/repository/branches/"): + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte(`{"name":"main","protected":true}`)) + case strings.Contains(path, "/pipelines/"): + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte(`{"id":100,"source":"api","user":{"id":7}}`)) + case strings.Contains(path, "/members/all/"): + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte(`{"access_level":40}`)) + case strings.Contains(path, "/notes"): + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte(`[]`)) + default: + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte(`{"id":42,"default_branch":"main","path_with_namespace":"pinned/project"}`)) + } + }) + srv := httptest.NewTLSServer(mux) + t.Cleanup(srv.Close) + + // run-agent-job.sh ends with `exit "${RUN_STATUS}"`, so a sourcing + // shell never returns control to any commands appended after the + // `. "$SCRIPT"` call. Observe the resolved identity by having the + // stub `fullsend` binary — invoked as a child process that inherits + // the exported environment — dump the variable under test before the + // script exits. + bin := t.TempDir() + require.NoError(t, os.WriteFile(filepath.Join(bin, "fullsend"), []byte( + "#!/bin/sh\n"+ + "echo FULLSEND_ARGS: \"$@\"\n"+ + "echo STUB_ENV GITLAB_ISSUE_URL=\"${GITLAB_ISSUE_URL:-EMPTY}\"\n"+ + "echo STUB_ENV CI_MERGE_REQUEST_IID=\"${CI_MERGE_REQUEST_IID:-UNSET}\"\n"+ + "echo STUB_ENV FULLSEND_NOTE_TARGET=\"${FULLSEND_NOTE_TARGET:-UNSET}\"\n"+ + "exit 0\n"), 0o755)) + + const secret = "test-hmac-secret" + // STATUS_IID carries the signed issue IID for this issue_note dispatch. + hmacHex := computeDispatchHMAC(secret, "5", "", "issue_note", "", "false", "", "", "", "test-key", "review", "7") + + setupPinnedConfigOrigin(t, root) + + cmd := exec.Command("bash", "-c", `set -euo pipefail; . "$SCRIPT"`) + cmd.Dir = root + cmd.Env = append([]string{ + "SCRIPT=" + script, + "PATH=" + bin + ":" + os.Getenv("PATH"), + "HOME=" + t.TempDir(), + "CI_PROJECT_DIR=" + root, + "RUNNER_TEMP=" + t.TempDir(), + "CI_JOB_TOKEN=job-token", + "FULLSEND_GITLAB_POLLER_TOKEN=poller-pat", + "FULLSEND_GITLAB_ANALYST_TOKEN=analyst-pat", + "STAGE=review", + "EVENT_TYPE=issue_note", + "RESOURCE_KEY=test-key", + "ACTOR_ID=5", + "IS_FORK=false", + "FULLSEND_DISPATCH_SECRET=" + secret, + "FULLSEND_DISPATCH_HMAC=" + hmacHex, + "CI_PIPELINE_URL=https://gitlab.example/pinned/project/-/pipelines/999", + "STATUS_IID=7", + // An ordinary, overridable CI/CD variable that happens to equal + // the signed STATUS_IID. Even though the value "agrees", its mere + // presence must not reach the fullsend CLI subprocess for an + // issue event, since newGitLabClientFromEnv treats any non-empty + // CI_MERGE_REQUEST_IID as a merge_requests note target. + "CI_MERGE_REQUEST_IID=7", + "CI_PROJECT_ID=1", + "CI_PROJECT_PATH=unpinned/project", + "CI_SERVER_URL=https://unpinned.example", + // An ordinary, overridable CI/CD variable — the same class as + // CI_MERGE_REQUEST_IID above — pre-set to the value + // newGitLabClientFromEnv treats as selecting the merge_requests + // note target. The issue_* arm must override it so the fullsend + // CLI subprocess never inherits it. + "FULLSEND_NOTE_TARGET=merge_requests", + }, pinTLSEnv(t, srv)...) + out, err := cmd.CombinedOutput() + require.NoError(t, err, "stdout/stderr: %s", out) + got := string(out) + + assert.Contains(t, got, "STUB_ENV GITLAB_ISSUE_URL=https://") + assert.Contains(t, got, "/-/issues/7") + assert.Contains(t, got, "STUB_ENV CI_MERGE_REQUEST_IID=UNSET") + assert.Contains(t, got, "STUB_ENV FULLSEND_NOTE_TARGET=issues") +} diff --git a/internal/scaffold/pin_ci_job_identity_test.go b/internal/scaffold/pin_ci_job_identity_test.go new file mode 100644 index 0000000000..e53c33aad1 --- /dev/null +++ b/internal/scaffold/pin_ci_job_identity_test.go @@ -0,0 +1,537 @@ +package scaffold + +import ( + "encoding/pem" + "fmt" + "net" + "net/http" + "net/http/httptest" + "os" + "os/exec" + "path/filepath" + "strings" + "sync/atomic" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func writePinCIJobIdentityScripts(t *testing.T) (root, pinScript string) { + t.Helper() + root = t.TempDir() + writeGitLabScript(t, root, ".gitlab/ci/scripts/trust-ci-server-ca.sh") + pinScript = writeGitLabScript(t, root, gitlabPinCIJobIdentityScriptPath) + return root, pinScript +} + +func sourcePinScript(t *testing.T, root, script string, extraEnv []string) (combined string, err error) { + t.Helper() + cmd := exec.Command("bash", "-c", "set -euo pipefail; . \"$SCRIPT\"; echo PINNED_PROJECT=$FULLSEND_PINNED_PROJECT_ID; echo PINNED_PIPELINE=$FULLSEND_PINNED_PIPELINE_ID; echo PINNED_REF=$FULLSEND_PINNED_REF; echo PINNED_SOURCE=$FULLSEND_PINNED_PIPELINE_SOURCE") + cmd.Env = append([]string{ + "SCRIPT=" + script, + "PATH=" + os.Getenv("PATH"), + "HOME=" + t.TempDir(), + "CI_PROJECT_DIR=" + root, + "RUNNER_TEMP=" + t.TempDir(), + "FULLSEND_ADMIT_SOURCE=api", + "CI_JOB_TOKEN=job-token", + }, extraEnv...) + out, runErr := cmd.CombinedOutput() + return string(out), runErr +} + +type pinAPIState struct { + jobJSON string + projectJSON string + branchJSON string + pipelineJSON string + jobStatus int + projectStatus int + branchStatus int + pipelineStatus int + jobHits atomic.Int32 + sawPAT atomic.Bool + jobAuth atomic.Bool +} + +func buildPinAPIMux(st *pinAPIState) *http.ServeMux { + mux := http.NewServeMux() + mux.HandleFunc("/api/v4/job", func(w http.ResponseWriter, r *http.Request) { + st.jobHits.Add(1) + if r.Header.Get("JOB-TOKEN") == "job-token" { + st.jobAuth.Store(true) + } + if r.Header.Get("PRIVATE-TOKEN") != "" { + st.sawPAT.Store(true) + } + status := st.jobStatus + if status == 0 { + status = http.StatusOK + } + w.WriteHeader(status) + _, _ = w.Write([]byte(st.jobJSON)) + }) + mux.HandleFunc("/api/v4/projects/", func(w http.ResponseWriter, r *http.Request) { + if r.Header.Get("PRIVATE-TOKEN") != "" { + st.sawPAT.Store(true) + } + path := r.URL.Path + status := http.StatusOK + body := "" + switch { + case strings.Contains(path, "/repository/branches/"): + status = st.branchStatus + body = st.branchJSON + case strings.Contains(path, "/pipelines/"): + status = st.pipelineStatus + body = st.pipelineJSON + default: + status = st.projectStatus + body = st.projectJSON + } + if status == 0 { + status = http.StatusOK + } + w.WriteHeader(status) + _, _ = w.Write([]byte(body)) + }) + return mux +} + +func startPinAPI(t *testing.T, st *pinAPIState) *httptest.Server { + t.Helper() + return httptest.NewTLSServer(buildPinAPIMux(st)) +} + +// startPinAPIOnIPv6Loopback serves the same mock API as startPinAPI, but +// bound to the IPv6 loopback address so its httptest.Server.URL is a +// bracketed IPv6 literal (https://[::1]:PORT) — used to prove the identity +// pin's CI_API_V4_URL validation admits a real IPv6 API root rather than +// only asserting the validation didn't reject a fabricated one. +func startPinAPIOnIPv6Loopback(t *testing.T, st *pinAPIState) *httptest.Server { + t.Helper() + l, err := net.Listen("tcp", "[::1]:0") + if err != nil { + t.Skipf("IPv6 loopback unavailable in this environment: %v", err) + } + srv := httptest.NewUnstartedServer(buildPinAPIMux(st)) + srv.Listener.Close() + srv.Listener = l + srv.StartTLS() + return srv +} + +func pinJobJSON(projectID, pipelineID, ref string) string { + return fmt.Sprintf(`{"id":9,"ref":%q,"pipeline":{"id":%s,"project_id":%s,"ref":%q}}`, ref, pipelineID, projectID, ref) +} + +func pinTLSEnv(t *testing.T, srv *httptest.Server) []string { + t.Helper() + return []string{ + "CI_API_V4_URL=" + srv.URL + "/api/v4", + "CI_SERVER_TLS_CA_FILE=" + writeServerCA(t, srv), + } +} + +func writeServerCA(t *testing.T, srv *httptest.Server) string { + t.Helper() + cert := srv.Certificate() + require.NotNil(t, cert) + path := filepath.Join(t.TempDir(), "server-ca.pem") + require.NoError(t, os.WriteFile(path, pem.EncodeToMemory(&pem.Block{ + Type: "CERTIFICATE", + Bytes: cert.Raw, + }), 0o644)) + return path +} + +func TestPinCIJobIdentity_AdmitsMatchingAPISource(t *testing.T) { + root, script := writePinCIJobIdentityScripts(t) + st := &pinAPIState{ + jobJSON: pinJobJSON("42", "100", "main"), + projectJSON: `{"id":42,"default_branch":"main","path_with_namespace":"group/project"}`, + branchJSON: `{"name":"main","protected":true}`, + pipelineJSON: `{"id":100,"source":"api","user":{"id":7}}`, + } + srv := startPinAPI(t, st) + t.Cleanup(srv.Close) + + out, err := sourcePinScript(t, root, script, pinTLSEnv(t, srv)) + require.NoError(t, err, "stdout/stderr: %s", out) + assert.Contains(t, out, "PINNED_PROJECT=42") + assert.Contains(t, out, "PINNED_PIPELINE=100") + assert.Contains(t, out, "PINNED_REF=main") + assert.Contains(t, out, "PINNED_SOURCE=api") + assert.True(t, st.jobAuth.Load(), "job lookup must send JOB-TOKEN") + assert.False(t, st.sawPAT.Load(), "gate curls must not send the role PAT") +} + +func TestPinCIJobIdentity_DeniesParentPipelineSource(t *testing.T) { + root, script := writePinCIJobIdentityScripts(t) + st := &pinAPIState{ + jobJSON: pinJobJSON("42", "100", "main"), + projectJSON: `{"id":42,"default_branch":"main","path_with_namespace":"group/project"}`, + branchJSON: `{"name":"main","protected":true}`, + pipelineJSON: `{"id":100,"source":"parent_pipeline","user":{"id":7}}`, + } + srv := startPinAPI(t, st) + t.Cleanup(srv.Close) + + out, err := sourcePinScript(t, root, script, pinTLSEnv(t, srv)) + require.Error(t, err, "stdout/stderr: %s", out) + assert.Contains(t, out, "parent_pipeline") + assert.Contains(t, out, "disjoint allowlist deny") +} + +func TestPinCIJobIdentity_DeniesScheduleWhenAgentAdmitsAPI(t *testing.T) { + root, script := writePinCIJobIdentityScripts(t) + st := &pinAPIState{ + jobJSON: pinJobJSON("42", "100", "main"), + projectJSON: `{"id":42,"default_branch":"main","path_with_namespace":"group/project"}`, + branchJSON: `{"name":"main","protected":true}`, + pipelineJSON: `{"id":100,"source":"schedule"}`, + } + srv := startPinAPI(t, st) + t.Cleanup(srv.Close) + + out, err := sourcePinScript(t, root, script, pinTLSEnv(t, srv)) + require.Error(t, err, "stdout/stderr: %s", out) + assert.Contains(t, out, "schedule") + assert.Contains(t, out, "disjoint allowlist deny") +} + +func TestPinCIJobIdentity_DeniesProtectedNonDefaultRef(t *testing.T) { + root, script := writePinCIJobIdentityScripts(t) + st := &pinAPIState{ + jobJSON: pinJobJSON("42", "100", "release-1.0"), + projectJSON: `{"id":42,"default_branch":"main","path_with_namespace":"group/project"}`, + branchJSON: `{"name":"release-1.0","protected":true}`, + pipelineJSON: `{"id":100,"source":"api"}`, + } + srv := startPinAPI(t, st) + t.Cleanup(srv.Close) + + out, err := sourcePinScript(t, root, script, pinTLSEnv(t, srv)) + require.Error(t, err, "stdout/stderr: %s", out) + assert.Contains(t, out, "protected-but-non-default") + assert.Contains(t, out, "release-1.0") +} + +func TestPinCIJobIdentity_DeniesUnprotectedDefaultBranch(t *testing.T) { + root, script := writePinCIJobIdentityScripts(t) + st := &pinAPIState{ + jobJSON: pinJobJSON("42", "100", "main"), + projectJSON: `{"id":42,"default_branch":"main","path_with_namespace":"group/project"}`, + branchJSON: `{"name":"main","protected":false}`, + pipelineJSON: `{"id":100,"source":"api"}`, + } + srv := startPinAPI(t, st) + t.Cleanup(srv.Close) + + out, err := sourcePinScript(t, root, script, pinTLSEnv(t, srv)) + require.Error(t, err, "stdout/stderr: %s", out) + assert.Contains(t, out, "is not protected") +} + +func TestPinCIJobIdentity_InvalidJobTokenFailsClosed(t *testing.T) { + root, script := writePinCIJobIdentityScripts(t) + st := &pinAPIState{ + jobStatus: http.StatusUnauthorized, + jobJSON: `{"message":"401 Unauthorized"}`, + } + srv := startPinAPI(t, st) + t.Cleanup(srv.Close) + + out, err := sourcePinScript(t, root, script, pinTLSEnv(t, srv)) + require.Error(t, err, "stdout/stderr: %s", out) + assert.Contains(t, out, "CI_JOB_TOKEN job lookup failed") +} + +func TestPinCIJobIdentity_ProjectLookupFailsClosed(t *testing.T) { + root, script := writePinCIJobIdentityScripts(t) + st := &pinAPIState{ + jobJSON: pinJobJSON("42", "100", "main"), + projectStatus: http.StatusForbidden, + projectJSON: `{"message":"403 Forbidden"}`, + } + srv := startPinAPI(t, st) + t.Cleanup(srv.Close) + + out, err := sourcePinScript(t, root, script, pinTLSEnv(t, srv)) + require.Error(t, err, "stdout/stderr: %s", out) + assert.Contains(t, out, "cannot read pinned project") +} + +func TestPinCIJobIdentity_BranchLookupFailsClosed(t *testing.T) { + root, script := writePinCIJobIdentityScripts(t) + st := &pinAPIState{ + jobJSON: pinJobJSON("42", "100", "main"), + projectJSON: `{"id":42,"default_branch":"main","path_with_namespace":"group/project"}`, + branchStatus: http.StatusForbidden, + branchJSON: `{"message":"403 Forbidden"}`, + } + srv := startPinAPI(t, st) + t.Cleanup(srv.Close) + + out, err := sourcePinScript(t, root, script, pinTLSEnv(t, srv)) + require.Error(t, err, "stdout/stderr: %s", out) + assert.Contains(t, out, "cannot read pinned branch") +} + +func TestPinCIJobIdentity_PipelineLookupFailsClosed(t *testing.T) { + root, script := writePinCIJobIdentityScripts(t) + st := &pinAPIState{ + jobJSON: pinJobJSON("42", "100", "main"), + projectJSON: `{"id":42,"default_branch":"main","path_with_namespace":"group/project"}`, + branchJSON: `{"name":"main","protected":true}`, + pipelineStatus: http.StatusForbidden, + pipelineJSON: `{"message":"403 Forbidden"}`, + } + srv := startPinAPI(t, st) + t.Cleanup(srv.Close) + + out, err := sourcePinScript(t, root, script, pinTLSEnv(t, srv)) + require.Error(t, err, "stdout/stderr: %s", out) + assert.Contains(t, out, "cannot read pinned pipeline") +} + +func TestPinCIJobIdentity_EmptyJobTokenFailsClosed(t *testing.T) { + root, script := writePinCIJobIdentityScripts(t) + out, err := sourcePinScript(t, root, script, []string{ + "CI_JOB_TOKEN=", + "CI_API_V4_URL=https://gitlab.example/api/v4", + }) + require.Error(t, err, "stdout/stderr: %s", out) + assert.Contains(t, out, "CI_JOB_TOKEN is empty") +} + +func TestPinCIJobIdentity_RejectsNonHTTPSAPIURL(t *testing.T) { + root, script := writePinCIJobIdentityScripts(t) + out, err := sourcePinScript(t, root, script, []string{ + "CI_API_V4_URL=http://gitlab.example/api/v4", + }) + require.Error(t, err, "stdout/stderr: %s", out) + assert.Contains(t, out, "not an https GitLab API root") +} + +func TestPinCIJobIdentity_RejectsBraceGlobAPIURL(t *testing.T) { + root, script := writePinCIJobIdentityScripts(t) + out, err := sourcePinScript(t, root, script, []string{ + "CI_API_V4_URL=https://{attacker.example,gitlab.example}/api/v4", + }) + require.Error(t, err, "stdout/stderr: %s", out) + assert.Contains(t, out, "not permitted in a GitLab API root") +} + +func TestPinCIJobIdentity_RejectsBracketRangeAPIURL(t *testing.T) { + root, script := writePinCIJobIdentityScripts(t) + out, err := sourcePinScript(t, root, script, []string{ + "CI_API_V4_URL=https://gitlab[1-2].example/api/v4", + }) + require.Error(t, err, "stdout/stderr: %s", out) + assert.Contains(t, out, "not permitted in a GitLab API root") +} + +func TestPinCIJobIdentity_AllowsIPv6LiteralAPIURL(t *testing.T) { + root, script := writePinCIJobIdentityScripts(t) + st := &pinAPIState{ + jobJSON: pinJobJSON("42", "100", "main"), + projectJSON: `{"id":42,"default_branch":"main","path_with_namespace":"group/project"}`, + branchJSON: `{"name":"main","protected":true}`, + pipelineJSON: `{"id":100,"source":"api","user":{"id":7}}`, + } + srv := startPinAPIOnIPv6Loopback(t, st) + t.Cleanup(srv.Close) + require.Contains(t, srv.URL, "[::1]", "test setup: expected an IPv6-literal server URL") + + out, err := sourcePinScript(t, root, script, pinTLSEnv(t, srv)) + require.NoError(t, err, "stdout/stderr: %s", out) + assert.NotContains(t, out, "not permitted in a GitLab API root") + assert.Contains(t, out, "PINNED_PROJECT=42") +} + +func TestPinCIJobIdentity_RejectsUserinfoAPIURL(t *testing.T) { + root, script := writePinCIJobIdentityScripts(t) + out, err := sourcePinScript(t, root, script, []string{ + "CI_API_V4_URL=https://gitlab.example@attacker.example/api/v4", + }) + require.Error(t, err, "stdout/stderr: %s", out) + assert.Contains(t, out, "not permitted in a GitLab API root") +} + +func TestPinCIJobIdentity_RejectsUnknownAdmitSource(t *testing.T) { + root, script := writePinCIJobIdentityScripts(t) + out, err := sourcePinScript(t, root, script, []string{ + "FULLSEND_ADMIT_SOURCE=api,schedule", + "CI_API_V4_URL=https://gitlab.example/api/v4", + }) + require.Error(t, err, "stdout/stderr: %s", out) + assert.Contains(t, out, "disjoint per-job allowlist") +} + +func TestPinCIJobIdentity_IgnoresHTTPProxy(t *testing.T) { + root, script := writePinCIJobIdentityScripts(t) + st := &pinAPIState{ + jobJSON: pinJobJSON("42", "100", "main"), + projectJSON: `{"id":42,"default_branch":"main","path_with_namespace":"group/project"}`, + branchJSON: `{"name":"main","protected":true}`, + pipelineJSON: `{"id":100,"source":"api"}`, + } + srv := startPinAPI(t, st) + t.Cleanup(srv.Close) + + proxyHits := atomic.Int32{} + proxy := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + proxyHits.Add(1) + http.Error(w, "proxy should not be used", http.StatusBadGateway) + })) + t.Cleanup(proxy.Close) + + out, err := sourcePinScript(t, root, script, append(pinTLSEnv(t, srv), + "HTTP_PROXY="+proxy.URL, + "HTTPS_PROXY="+proxy.URL, + "ALL_PROXY="+proxy.URL, + "http_proxy="+proxy.URL, + "https_proxy="+proxy.URL, + "all_proxy="+proxy.URL, + )) + require.NoError(t, err, "stdout/stderr: %s", out) + assert.Equal(t, int32(0), proxyHits.Load(), "gate curls must ignore trigger-influenced proxy settings") + assert.Contains(t, out, "PINNED_SOURCE=api") +} + +// TestPinCIJobIdentity_UnsetsProxyEnvInParentShellOnSuccess is a regression +// test for the secret-exposure finding: fullsend_gate_curl only strips +// proxy env vars for its own curl invocations (env -u ...); it does not +// remove them from the sourcing shell. The subsequent fullsend poll/run Go +// processes inherit that shell's exported environment and build their +// http.Client with a nil Transport (ProxyFromEnvironment), so a +// trigger-influenced HTTP_PROXY/HTTPS_PROXY left set after a successful pin +// could still CONNECT-proxy PAT-bearing API traffic. After the pin +// succeeds, HTTP_PROXY/HTTPS_PROXY/http_proxy/https_proxy (the names Go's +// ProxyFromEnvironment honors) must be unset in the parent shell. +func TestPinCIJobIdentity_UnsetsProxyEnvInParentShellOnSuccess(t *testing.T) { + root, script := writePinCIJobIdentityScripts(t) + st := &pinAPIState{ + jobJSON: pinJobJSON("42", "100", "main"), + projectJSON: `{"id":42,"default_branch":"main","path_with_namespace":"group/project"}`, + branchJSON: `{"name":"main","protected":true}`, + pipelineJSON: `{"id":100,"source":"api"}`, + } + srv := startPinAPI(t, st) + t.Cleanup(srv.Close) + + cmd := exec.Command("bash", "-c", + "set -euo pipefail; . \"$SCRIPT\"; "+ + "echo POST_PIN_HTTP_PROXY=\"${HTTP_PROXY:-UNSET}\"; "+ + "echo POST_PIN_HTTPS_PROXY=\"${HTTPS_PROXY:-UNSET}\"; "+ + "echo POST_PIN_http_proxy=\"${http_proxy:-UNSET}\"; "+ + "echo POST_PIN_https_proxy=\"${https_proxy:-UNSET}\"; "+ + "echo POST_PIN_ALL_PROXY=\"${ALL_PROXY:-UNSET}\"; "+ + "echo POST_PIN_all_proxy=\"${all_proxy:-UNSET}\"") + cmd.Env = append([]string{ + "SCRIPT=" + script, + "PATH=" + os.Getenv("PATH"), + "HOME=" + t.TempDir(), + "CI_PROJECT_DIR=" + root, + "RUNNER_TEMP=" + t.TempDir(), + "FULLSEND_ADMIT_SOURCE=api", + "CI_JOB_TOKEN=job-token", + "HTTP_PROXY=http://attacker.example:8080", + "HTTPS_PROXY=http://attacker.example:8080", + "http_proxy=http://attacker.example:8080", + "https_proxy=http://attacker.example:8080", + "ALL_PROXY=http://attacker.example:8080", + "all_proxy=http://attacker.example:8080", + }, pinTLSEnv(t, srv)...) + out, err := cmd.CombinedOutput() + require.NoError(t, err, "stdout/stderr: %s", out) + got := string(out) + + assert.Contains(t, got, "POST_PIN_HTTP_PROXY=UNSET") + assert.Contains(t, got, "POST_PIN_HTTPS_PROXY=UNSET") + assert.Contains(t, got, "POST_PIN_http_proxy=UNSET") + assert.Contains(t, got, "POST_PIN_https_proxy=UNSET") + assert.Contains(t, got, "POST_PIN_ALL_PROXY=UNSET") + assert.Contains(t, got, "POST_PIN_all_proxy=UNSET") +} + +// TestPinCIJobIdentity_AuthHeaderNotOnCurlArgv verifies that +// fullsend_gate_curl rewrites a caller's `-H "JOB-TOKEN: ..."` into +// `-H @tempfile` before invoking curl, so the token value itself never +// appears in curl's argv (visible via /proc//cmdline, `ps`, or +// execve audit logs otherwise). A shim `curl` binary ahead of the real +// one on PATH logs its raw argv, then execs the real curl so the pin +// script still completes normally. +func TestPinCIJobIdentity_AuthHeaderNotOnCurlArgv(t *testing.T) { + realCurl, err := exec.LookPath("curl") + require.NoError(t, err) + + root, script := writePinCIJobIdentityScripts(t) + st := &pinAPIState{ + jobJSON: pinJobJSON("42", "100", "main"), + projectJSON: `{"id":42,"default_branch":"main","path_with_namespace":"group/project"}`, + branchJSON: `{"name":"main","protected":true}`, + pipelineJSON: `{"id":100,"source":"api"}`, + } + srv := startPinAPI(t, st) + t.Cleanup(srv.Close) + + argvLog := filepath.Join(t.TempDir(), "argv.log") + shimDir := t.TempDir() + shimScript := "#!/bin/sh\nprintf '%s\\n' \"$@\" >> " + argvLog + "\nexec " + realCurl + " \"$@\"\n" + require.NoError(t, os.WriteFile(filepath.Join(shimDir, "curl"), []byte(shimScript), 0o755)) + + out, err := sourcePinScript(t, root, script, append(pinTLSEnv(t, srv), + "PATH="+shimDir+string(os.PathListSeparator)+os.Getenv("PATH"), + )) + require.NoError(t, err, "stdout/stderr: %s", out) + + logged, readErr := os.ReadFile(argvLog) + require.NoError(t, readErr) + loggedStr := string(logged) + assert.NotContains(t, loggedStr, "job-token", "the raw JOB-TOKEN value must not appear in curl's argv") + assert.Contains(t, loggedStr, "-H\n@", "the auth header must be passed to curl via an @file, not a literal argument") +} + +func TestPinCIJobIdentity_PollerAdmitsScheduleOnly(t *testing.T) { + root, script := writePinCIJobIdentityScripts(t) + st := &pinAPIState{ + jobJSON: pinJobJSON("42", "100", "main"), + projectJSON: `{"id":42,"default_branch":"main","path_with_namespace":"group/project"}`, + branchJSON: `{"name":"main","protected":true}`, + pipelineJSON: `{"id":100,"source":"schedule"}`, + } + srv := startPinAPI(t, st) + t.Cleanup(srv.Close) + + out, err := sourcePinScript(t, root, script, append(pinTLSEnv(t, srv), + "FULLSEND_ADMIT_SOURCE=schedule", + )) + require.NoError(t, err, "stdout/stderr: %s", out) + assert.Contains(t, out, "PINNED_SOURCE=schedule") +} + +func TestPinCIJobIdentity_PollerDeniesAPISource(t *testing.T) { + root, script := writePinCIJobIdentityScripts(t) + st := &pinAPIState{ + jobJSON: pinJobJSON("42", "100", "main"), + projectJSON: `{"id":42,"default_branch":"main","path_with_namespace":"group/project"}`, + branchJSON: `{"name":"main","protected":true}`, + pipelineJSON: `{"id":100,"source":"api"}`, + } + srv := startPinAPI(t, st) + t.Cleanup(srv.Close) + + out, err := sourcePinScript(t, root, script, append(pinTLSEnv(t, srv), + "FULLSEND_ADMIT_SOURCE=schedule", + )) + require.Error(t, err, "stdout/stderr: %s", out) + assert.Contains(t, out, "disjoint allowlist deny") +} + +// Run*JobScript_* integration tests that exercise run-agent-job.sh / +// run-poll-job.sh end to end (not just the sourced +// pin-ci-job-identity.sh helper) live in gitlab_job_scripts_test.go, +// alongside the rest of that script-level coverage. diff --git a/internal/scaffold/scaffold_env_consistency_test.go b/internal/scaffold/scaffold_env_consistency_test.go index 7a63a9308a..46074dd16c 100644 --- a/internal/scaffold/scaffold_env_consistency_test.go +++ b/internal/scaffold/scaffold_env_consistency_test.go @@ -87,6 +87,20 @@ var gitlabCIScaffoldLocalEnvVars = map[string]struct{}{ "FULLSEND_NOTE_TARGET": {}, // trust-ci-server-ca.sh idempotency flag. "FULLSEND_CI_SERVER_CA_TRUSTED": {}, + // pin-ci-job-identity.sh caller input and pinned job-record exports. + "FULLSEND_ADMIT_SOURCE": {}, + "FULLSEND_PINNED_PROJECT_ID": {}, + "FULLSEND_PINNED_PIPELINE_ID": {}, + "FULLSEND_PINNED_REF": {}, + "FULLSEND_PINNED_PIPELINE_SOURCE": {}, + "FULLSEND_PINNED_PIPELINE_RESPONSE": {}, + "FULLSEND_PINNED_PROJECT_PATH": {}, + "FULLSEND_PINNED_GITLAB_URL": {}, + // run-agent-job.sh / run-poll-job.sh script-local derivation + // (FULLSEND_PINNED_GITLAB_URL + "/api/v4") used to route every + // post-pin PAT-bearing call through the pinned API root instead of + // the overridable CI_API_V4_URL pipeline variable. + "FULLSEND_PINNED_API_V4_URL": {}, // CLI GitLab base-URL override (internal/forge/gitlab.URLEnvVars). "FULLSEND_GITLAB_URL": {}, // Concatenation prefix for custom-role secrets @@ -181,6 +195,7 @@ func TestGitLabCIScaffoldEnvVarsAreCanonical(t *testing.T) { assert.Contains(t, scanned, ".gitlab/ci/scripts/install-fullsend-cli.sh") assert.Contains(t, scanned, ".gitlab/ci/scripts/run-poll-job.sh") assert.Contains(t, scanned, ".gitlab/ci/scripts/run-agent-job.sh") + assert.Contains(t, scanned, ".gitlab/ci/scripts/pin-ci-job-identity.sh") assert.Contains(t, scanned, ".gitlab/ci/scripts/checkout-mr-source.sh") if len(failures) > 0 { t.Errorf("scaffold FULLSEND_* names absent from forge.Secret*/Var* constants and the script-local allowlist:\n %s", diff --git a/internal/scaffold/scaffold_gitlab_test.go b/internal/scaffold/scaffold_gitlab_test.go index b66bcf86e7..e7cfe7463e 100644 --- a/internal/scaffold/scaffold_gitlab_test.go +++ b/internal/scaffold/scaffold_gitlab_test.go @@ -12,6 +12,7 @@ import ( const ( gitlabInstallCLIScriptPath = ".gitlab/ci/scripts/install-fullsend-cli.sh" + gitlabPinCIJobIdentityScriptPath = ".gitlab/ci/scripts/pin-ci-job-identity.sh" gitlabRunPollJobScriptPath = ".gitlab/ci/scripts/run-poll-job.sh" gitlabRunAgentJobScriptPath = ".gitlab/ci/scripts/run-agent-job.sh" gitlabCheckoutMRSourceScriptPath = ".gitlab/ci/scripts/checkout-mr-source.sh" @@ -40,6 +41,7 @@ func gitlabAgentScaffold(t *testing.T) string { return gitlabJoinTexts(t, ".gitlab/ci/fullsend-agent.yml", gitlabInstallCLIScriptPath, + gitlabPinCIJobIdentityScriptPath, gitlabRunAgentJobScriptPath, ) } @@ -51,6 +53,7 @@ func gitlabPollScaffold(t *testing.T) string { return gitlabJoinTexts(t, ".gitlab/ci/fullsend-poll.yml", gitlabInstallCLIScriptPath, + gitlabPinCIJobIdentityScriptPath, gitlabRunPollJobScriptPath, ) } @@ -65,6 +68,7 @@ func TestGitLabPerRepoFilesExist(t *testing.T) { ".gitlab/ci/fullsend-agent.yml", ".gitlab/ci/scripts/trust-ci-server-ca.sh", ".gitlab/ci/scripts/select-gitlab-role-token.sh", + gitlabPinCIJobIdentityScriptPath, gitlabInstallCLIScriptPath, gitlabRunPollJobScriptPath, gitlabRunAgentJobScriptPath, @@ -234,11 +238,14 @@ func TestGitLabAgentTemplateContent(t *testing.T) { assert.Contains(t, s, "FULLSEND_JOB_KIND=agent") assert.Contains(t, s, `PRIVATE-TOKEN: ${FULLSEND_JOB_TOKEN}`) assert.NotContains(t, s, `PRIVATE-TOKEN: ${FULLSEND_FORGE_TOKEN}`) - // Bot identity verification uses server-side .source from Pipelines API - // (deny-by-default case statement, not forgeable CI_PIPELINE_SOURCE env var) + // Bot identity verification pins .source from the CI_JOB_TOKEN job + // record (deny-by-default, not forgeable CI_PIPELINE_SOURCE env var) + // and admits only api — parent_pipeline is no longer an allowlist arm. assert.Contains(t, s, `jq -r '.source // empty'`) - assert.Contains(t, s, `parent_pipeline)`) - assert.Contains(t, s, "unexpected pipeline source") + assert.Contains(t, s, "FULLSEND_ADMIT_SOURCE=api") + assert.NotRegexp(t, `(?m)^\s+parent_pipeline\)\s*$`, s, + "agent job must not admit parent_pipeline as an allowlist arm") + assert.Contains(t, s, "disjoint allowlist deny") assert.Contains(t, s, "rejecting forged dispatch") // Generic runner image, not agent-specific assert.Contains(t, s, "fullsend-runner:dev") @@ -489,7 +496,7 @@ func TestGitLabAgentTemplateFixStageReviewNoteUsesAnalystIdentity(t *testing.T) // The restore must happen before the TARGET_BRANCH lookup (later in // the same fix-only block), which authenticates with FULLSEND_JOB_TOKEN // and must use the restored coder token, not the analyst token. - targetBranchIdx := strings.Index(fixBlock, "TARGET_BRANCH=$(curl") + targetBranchIdx := strings.Index(fixBlock, "TARGET_BRANCH=$(fullsend_gate_curl") require.NotEqual(t, -1, targetBranchIdx, "TARGET_BRANCH lookup not found in fix block") assert.Greater(t, targetBranchIdx, restoreIdx, "TARGET_BRANCH lookup must run after the coder token is restored") @@ -607,6 +614,34 @@ func TestGitLabAgentTemplateMRIIDPrefersSignedStatusIID(t *testing.T) { assert.Contains(t, shared, `*[!0-9]*) _FS_CI_MR_IID=""`) } +// TestGitLabAgentTemplateReviewPriorLookupPrefersSignedStatusIID guards +// against a regression of the STAGE=review prior-review-lookup block +// (which runs before the shared code|fix|review MR_IID resolution) +// trusting the unsigned CI_MERGE_REQUEST_IID over the HMAC-signed +// STATUS_IID when selecting which MR's notes to query with the role PAT. +func TestGitLabAgentTemplateReviewPriorLookupPrefersSignedStatusIID(t *testing.T) { + s := gitlabAgentScaffold(t) + + reviewMarker := `if [ "${STAGE}" = "review" ]; then` + reviewIdx := strings.Index(s, reviewMarker) + require.NotEqual(t, -1, reviewIdx, "STAGE=review prior-review block marker not found") + reviewBlock := s[reviewIdx:] + mktempIdx := strings.Index(reviewBlock, "PRIOR_REVIEW_FILE=$(mktemp)") + require.NotEqual(t, -1, mktempIdx, "PRIOR_REVIEW_FILE mktemp not found in review block") + reviewBlock = reviewBlock[:mktempIdx] + + // STATUS_IID is preferred when present and non-zero, not the unsigned + // CI_MERGE_REQUEST_IID fallback the fail-open finding flagged. + assert.Contains(t, reviewBlock, `MR_IID="${STATUS_IID}"`) + assert.NotContains(t, reviewBlock, `MR_IID="${CI_MERGE_REQUEST_IID:-${STATUS_IID:-0}}"`) + // A disagreeing CI_MERGE_REQUEST_IID fails closed instead of being trusted. + assert.Contains(t, reviewBlock, "does not match the signed dispatch STATUS_IID") + assert.Contains(t, reviewBlock, "exit 1") + // CI_MERGE_REQUEST_IID is validated as numeric before use, like the + // other untrusted CI identity variables in this file. + assert.Contains(t, reviewBlock, `*[!0-9]*) _FS_REVIEW_CI_MR_IID=""`) +} + func TestGitLabAgentTemplateKillSwitch(t *testing.T) { s := gitlabAgentScaffold(t) assert.Contains(t, s, "kill_switch") @@ -685,6 +720,13 @@ func TestGitLabPollContent(t *testing.T) { assert.Contains(t, s, "fullsend poll") assert.Contains(t, s, "schedule") assert.Contains(t, s, "CI_COMMIT_REF_PROTECTED") + assert.Contains(t, s, "FULLSEND_ADMIT_SOURCE=schedule") + assert.Contains(t, s, gitlabPinCIJobIdentityScriptPath) + debugIdx := strings.Index(s, `$CI_DEBUG_TRACE =~ /^(1|t|true)$/i`) + require.NotEqual(t, -1, debugIdx) + admitIdx := strings.Index(s, `$CI_PIPELINE_SOURCE == "schedule" && $CI_COMMIT_REF_PROTECTED == "true"`) + require.NotEqual(t, -1, admitIdx) + assert.Less(t, debugIdx, admitIdx, "poll job rules must deny debug-trace before schedule admit") // Credential selection uses the shared role-token helper. assert.Contains(t, s, "select-gitlab-role-token.sh") assert.Contains(t, s, "FULLSEND_JOB_KIND=poller") @@ -776,6 +818,13 @@ func TestGitLabRootPipelineContent(t *testing.T) { // Auto-cancel disabled to prevent queued agent pipelines from being killed assert.Contains(t, s, "auto_cancel") assert.Contains(t, s, "on_new_commit: none") + // Deny-before-admit debug-trace guard must precede admit rules. + debugIdx := strings.Index(s, `$CI_DEBUG_TRACE =~ /^(1|t|true)$/i`) + require.NotEqual(t, -1, debugIdx, "workflow:rules must deny CI_DEBUG_TRACE before admit") + scheduleIdx := strings.Index(s, `$CI_PIPELINE_SOURCE == "schedule"`) + require.NotEqual(t, -1, scheduleIdx) + assert.Less(t, debugIdx, scheduleIdx, "debug-trace deny must precede schedule admit") + assert.Contains(t, s, "when: never") // API-triggered pipeline rule for cron-poller dispatched pipelines // Requires API source + protected branch + STAGE variable assert.Contains(t, s, `$CI_PIPELINE_SOURCE == "api"`) @@ -803,6 +852,8 @@ func TestGitLabPipelineWrapperContent(t *testing.T) { assert.NotContains(t, s, "fullsend-ref:") assert.Contains(t, s, "fullsend-poll.yml") assert.Contains(t, s, "fullsend-agent.yml") + assert.Contains(t, s, `$CI_DEBUG_TRACE =~ /^(1|t|true)$/i`) + assert.Contains(t, s, "when: never") assert.Contains(t, s, "stages:") assert.NotContains(t, s, "- dispatch", "dispatch stage was removed in #7337") assert.Contains(t, s, "- poll") @@ -1124,6 +1175,8 @@ func TestGitLabJobsSourceExtractedScripts(t *testing.T) { assert.Contains(t, agentYAML, gitlabRunAgentJobScriptPath) assert.Contains(t, pollYAML, gitlabInstallCLIScriptPath) assert.Contains(t, pollYAML, gitlabRunPollJobScriptPath) + assert.Contains(t, gitlabPerRepoText(t, gitlabRunAgentJobScriptPath), gitlabPinCIJobIdentityScriptPath) + assert.Contains(t, gitlabPerRepoText(t, gitlabRunPollJobScriptPath), gitlabPinCIJobIdentityScriptPath) assert.NotContains(t, agentYAML, "set -euo pipefail") assert.NotContains(t, pollYAML, "set -euo pipefail") @@ -1146,6 +1199,7 @@ func TestCollectGitLabPerRepoInstallFiles_IncludesExtractedJobScripts(t *testing } for _, path := range []string{ gitlabInstallCLIScriptPath, + gitlabPinCIJobIdentityScriptPath, gitlabRunPollJobScriptPath, gitlabRunAgentJobScriptPath, gitlabCheckoutMRSourceScriptPath, diff --git a/internal/scaffold/trust_ci_server_ca_test.go b/internal/scaffold/trust_ci_server_ca_test.go index 7dcd88d672..5db11281f5 100644 --- a/internal/scaffold/trust_ci_server_ca_test.go +++ b/internal/scaffold/trust_ci_server_ca_test.go @@ -150,6 +150,22 @@ func firstReadableSystemCABundle() string { return "" } +func TestTrustCIServerCAScript_ExportedFlagDoesNotSkip(t *testing.T) { + script := trustCIServerCAScript(t) + caPEM := testCACertPEM(t) + caPath := filepath.Join(t.TempDir(), "extra-ca.pem") + require.NoError(t, os.WriteFile(caPath, caPEM, 0o644)) + + out, stderr, err := sourceTrustScript(t, script, []string{ + "CI_SERVER_TLS_CA_FILE=" + caPath, + "FULLSEND_CI_SERVER_CA_TRUSTED=1", + }) + require.NoError(t, err, "stderr: %s", stderr) + assert.Contains(t, stderr, "Trusted extra CA", + "a trigger-supplied FULLSEND_CI_SERVER_CA_TRUSTED=1 must not skip CA pinning") + assert.Contains(t, out, "SSL_CERT_FILE=") +} + func TestTrustCIServerCAScript_Idempotent(t *testing.T) { script := trustCIServerCAScript(t) caPEM := testCACertPEM(t)