diff --git a/.github/workflows/reusable-poll-jira.yml b/.github/workflows/reusable-poll-jira.yml index 0bbe60e618..91252c17dd 100644 --- a/.github/workflows/reusable-poll-jira.yml +++ b/.github/workflows/reusable-poll-jira.yml @@ -6,30 +6,36 @@ # - Optional secrets: FULLSEND_JIRA_TOKEN / FULLSEND_JIRA_EMAIL for API-token # authentication, or FULLSEND_JIRA_CLIENT_ID / FULLSEND_JIRA_CLIENT_SECRET # for OAuth 2.0 client credentials. The Jira client validates the pair. -# - Optional inputs: runner_image (runner for the poll job) and timeout_minutes -# (job timeout; defaults to 15 minutes and can be raised by the caller). +# - Optional secrets FULLSEND_JIRA_WRITE_GROUPS, FULLSEND_JIRA_WRITE_ACCOUNTS, +# FULLSEND_JIRA_TRIAGE_GROUPS and FULLSEND_JIRA_TRIAGE_ACCOUNTS: the jira +# authorization lists that .fullsend/config.yaml reads with groups_from and +# accounts_from, so the lists stay out of a public repository (#9132). +# - Optional inputs: runner_image (runner for both jobs) and timeout_minutes +# (timeout of each job; defaults to 15 minutes and can be raised by the +# caller). # - Output: matrix is the JSON include matrix for reusable-dispatch.yml; an -# empty include array means there were no Jira issues to dispatch. +# empty include array means there were no Jira issues to dispatch. The matrix +# job sets it, not the poll job (see the comment on that job). # Runs `fullsend poll --input-driver jira-poll` against the caller's # .fullsend/config.yaml and returns the dispatch matrix to the caller. The # caller passes it to reusable-dispatch.yml at the same ref (ADR 62). # The poll normally completes within 15 minutes; the caller controls the job # timeout through timeout_minutes to account for its runner and Jira latency. # -# Security: Jira credentials reach only the poll step. They are never -# forwarded to agents or the runner-secret bundle. +# Security: Jira credentials reach only the poll and check steps. They are +# never forwarded to agents or the runner-secret bundle. name: Jira poll on: workflow_call: inputs: runner_image: - description: GitHub Actions runner image for the poll job. + description: GitHub Actions runner image for the Jira poll jobs. type: string required: false default: "ubuntu-24.04" timeout_minutes: - description: Maximum runtime in minutes for the Jira poll job. + description: Maximum runtime in minutes for each Jira poll job. type: number required: false default: 15 @@ -42,10 +48,18 @@ on: required: false FULLSEND_JIRA_CLIENT_SECRET: required: false + FULLSEND_JIRA_WRITE_GROUPS: + required: false + FULLSEND_JIRA_WRITE_ACCOUNTS: + required: false + FULLSEND_JIRA_TRIAGE_GROUPS: + required: false + FULLSEND_JIRA_TRIAGE_ACCOUNTS: + required: false outputs: matrix: description: Dispatch matrix accepted by reusable-dispatch.yml. - value: ${{ jobs.poll.outputs.matrix }} + value: ${{ jobs.matrix.outputs.matrix || '{"include":[]}' }} jobs: poll: @@ -55,7 +69,8 @@ jobs: permissions: contents: read outputs: - matrix: ${{ steps.matrix.outputs.matrix }} + dispatch_count: ${{ steps.check.outputs.count }} + artifact_suffix: ${{ steps.check.outputs.artifact_suffix }} steps: - name: Checkout caller repository uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 @@ -104,6 +119,12 @@ jobs: FULLSEND_JIRA_EMAIL: ${{ secrets.FULLSEND_JIRA_EMAIL }} FULLSEND_JIRA_CLIENT_ID: ${{ secrets.FULLSEND_JIRA_CLIENT_ID }} FULLSEND_JIRA_CLIENT_SECRET: ${{ secrets.FULLSEND_JIRA_CLIENT_SECRET }} + # The poller reads these only when config.yaml names them with + # groups_from or accounts_from, and never prints them. + FULLSEND_JIRA_WRITE_GROUPS: ${{ secrets.FULLSEND_JIRA_WRITE_GROUPS }} + FULLSEND_JIRA_WRITE_ACCOUNTS: ${{ secrets.FULLSEND_JIRA_WRITE_ACCOUNTS }} + FULLSEND_JIRA_TRIAGE_GROUPS: ${{ secrets.FULLSEND_JIRA_TRIAGE_GROUPS }} + FULLSEND_JIRA_TRIAGE_ACCOUNTS: ${{ secrets.FULLSEND_JIRA_TRIAGE_ACCOUNTS }} TARGET_REPO: ${{ github.repository }} run: | set -euo pipefail @@ -113,16 +134,95 @@ jobs: --output dispatches.json \ --fullsend-dir .fullsend + # The matrix job has no secrets, so GitHub no longer blocks a Jira + # credential in its output. Check for one here instead. + - name: Check dispatches + id: check + env: + FULLSEND_JIRA_TOKEN: ${{ secrets.FULLSEND_JIRA_TOKEN }} + FULLSEND_JIRA_EMAIL: ${{ secrets.FULLSEND_JIRA_EMAIL }} + FULLSEND_JIRA_CLIENT_ID: ${{ secrets.FULLSEND_JIRA_CLIENT_ID }} + FULLSEND_JIRA_CLIENT_SECRET: ${{ secrets.FULLSEND_JIRA_CLIENT_SECRET }} + run: | + set -euo pipefail + jq -e 'type == "array"' dispatches.json > /dev/null + # JSON escapes characters such as quotes, so search the decoded + # strings, not the file. + jq -r '.. | strings' dispatches.json > dispatch-strings.txt + for name in FULLSEND_JIRA_TOKEN FULLSEND_JIRA_EMAIL FULLSEND_JIRA_CLIENT_ID FULLSEND_JIRA_CLIENT_SECRET; do + # Trim the value as the CLI does. An empty grep pattern matches + # every line, and a padded one matches nothing. + value="$(sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//' -e '/^$/d' <<< "${!name}")" + if [[ -n "${value}" ]] && grep -qF -f <(printf '%s\n' "${value}") dispatch-strings.txt; then + echo "::error::dispatches.json contains ${name}; not passing it on." + exit 1 + fi + done + # A run can call this workflow more than once, and artifact names are + # unique per run, so each call names its artifact with its own suffix. + echo "artifact_suffix=$(openssl rand -hex 8)" >> "${GITHUB_OUTPUT}" + echo "count=$(jq length dispatches.json)" >> "${GITHUB_OUTPUT}" + + # The poller has already advanced its Jira checkpoints, so a failed + # upload would lose this cycle's dispatches. Try it twice. + - name: Save dispatches + id: save + if: ${{ steps.check.outputs.count != '0' }} + continue-on-error: true + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: fullsend-jira-dispatches-${{ steps.check.outputs.artifact_suffix }} + path: dispatches.json + if-no-files-found: error + retention-days: 1 + overwrite: true + + - name: Save dispatches (second try) + if: ${{ steps.save.outcome == 'failure' }} + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: fullsend-jira-dispatches-${{ steps.check.outputs.artifact_suffix }} + path: dispatches.json + if-no-files-found: error + retention-days: 1 + overwrite: true + + # Builds the matrix in a job without secrets. GitHub drops a job output that + # contains the value of a secret the job has, and the matrix holds the ID of + # the account that acted, which can equal a list secret such as + # FULLSEND_JIRA_WRITE_ACCOUNTS. + matrix: + name: Build dispatch matrix + needs: poll + # "!= '0'", not "> 0": an empty (dropped) count still runs this job. + if: ${{ needs.poll.outputs.dispatch_count != '0' }} + runs-on: ${{ inputs.runner_image }} + timeout-minutes: ${{ inputs.timeout_minutes }} + permissions: {} + outputs: + matrix: ${{ steps.matrix.outputs.matrix }} + steps: + # If both tries fail, "Re-run failed jobs" reads the artifact again + # while it is kept (1 day). "Re-run all jobs" would poll again and find + # nothing. + - name: Read dispatches + id: read + continue-on-error: true + uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 + with: + name: fullsend-jira-dispatches-${{ needs.poll.outputs.artifact_suffix }} + + - name: Read dispatches (second try) + if: ${{ steps.read.outcome == 'failure' }} + uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 + with: + name: fullsend-jira-dispatches-${{ needs.poll.outputs.artifact_suffix }} + - name: Build dispatch matrix id: matrix run: | set -euo pipefail - jq -e 'type == "array"' dispatches.json > /dev/null - if jq -e 'length == 0' dispatches.json > /dev/null; then - echo "No dispatches." - echo 'matrix={"include":[]}' >> "${GITHUB_OUTPUT}" - exit 0 - fi + jq -e 'type == "array" and length > 0' dispatches.json > /dev/null MATRIX=$(jq -c '{include: .}' dispatches.json) DELIM="MATRIX_$(openssl rand -hex 8)" { diff --git a/docs/cli/repos.md b/docs/cli/repos.md index c5d95574dc..9f608c9efa 100644 --- a/docs/cli/repos.md +++ b/docs/cli/repos.md @@ -677,6 +677,16 @@ flag or environment variable supplies them. When install manages the caller, it checks that its upstream ref contains `reusable-poll-jira.yml`. An older pin fails with no credential or workflow changes; upgrade the pin to a ref that includes the workflow. + When the `jira` authorization entry reads a list with `groups_from` or + `accounts_from`, the poll job also receives the + `FULLSEND_JIRA_WRITE_GROUPS`, `FULLSEND_JIRA_WRITE_ACCOUNTS`, + `FULLSEND_JIRA_TRIAGE_GROUPS`, or `FULLSEND_JIRA_TRIAGE_ACCOUNTS` secret it + names. Install warns about any other name, which the caller cannot pass. + It also warns when a poll workflow you maintain calls + `reusable-poll-jira.yml` without passing a secret the entry names. + You set these secrets + yourself; install and uninstall never write or delete them. See + [Keeping the lists out of the repository](../guides/user/jira-integration.md#keeping-the-lists-out-of-the-repository). Install changes the file only when it carries the `# fullsend-component: jira-poll` marker line. A workflow at that path without the marker, such as one copied from the Jira guide, is reported and @@ -692,7 +702,12 @@ flag or environment variable supplies them. environment variable available to all environments. The same rules apply to `--jira-client-secret` and an existing `FULLSEND_JIRA_CLIENT_SECRET`. Supplying any Jira credential flag when no selected repo enables polling - fails the run. + fails the run. When the `jira` authorization entry uses `groups_from` or + `accounts_from` and `fullsend_ref` pins a release that predates them, the + repo fails before any write, on GitHub and GitLab, with polling enabled or + not. On GitHub with polling enabled, it also fails when a poll workflow you + maintain calls a `reusable-poll-jira.yml` that predates them, unless the + install is vendored. `repos status` reports the same errors. - **Dry run.** `--dry-run` lists Jira secrets by name only and reports the poll-resource changes it would make. - **Command-line only.** `--jira-token`, `--jira-email`, `--jira-client-id`, diff --git a/docs/guides/getting-started/operations.md b/docs/guides/getting-started/operations.md index 9efdd77657..2e3424d206 100644 --- a/docs/guides/getting-started/operations.md +++ b/docs/guides/getting-started/operations.md @@ -44,6 +44,7 @@ fullsend github set "$OWNER/$REPO" FULLSEND_GCP_REGION global | `FULLSEND_JIRA_TOKEN` | Repo secret | Jira API token for polling and Jira-originated agent status updates when effective `tracker.jira.poll.enabled` is `true`, written by `repos install --jira-token` (required on the first install unless client credentials are supplied; an omitted flag keeps the existing secret; `repos uninstall` deletes it) | (Jira API token) | | `FULLSEND_JIRA_EMAIL` | Repo secret | Optional Jira account email for the same poller and agent status calls, written by `repos install --jira-email`; an omitted flag keeps the existing secret; `repos uninstall` deletes it | `poller@example.com` | | `FULLSEND_JIRA_CLIENT_ID` / `FULLSEND_JIRA_CLIENT_SECRET` | Repo secret | A service account's OAuth 2.0 credential, used instead of `FULLSEND_JIRA_TOKEN` (never both). GitHub poll and Jira-originated dispatch workflows forward them to the Jira client; `repos install` writes them on GitHub and GitLab. `repos uninstall` deletes them | (OAuth client credentials) | +| `FULLSEND_JIRA_WRITE_GROUPS` / `FULLSEND_JIRA_WRITE_ACCOUNTS` / `FULLSEND_JIRA_TRIAGE_GROUPS` / `FULLSEND_JIRA_TRIAGE_ACCOUNTS` | Repo secret (optional) | Comma-separated Jira group IDs or account IDs that the `jira` authorization entry reads with `groups_from` or `accounts_from`, so the lists stay out of the repository. The managed poll workflow passes the ones the entry names to the poll job only. Set with `gh secret set`; `repos install` and `repos uninstall` never write or delete them. See [Keeping the lists out of the repository](../user/jira-integration.md#keeping-the-lists-out-of-the-repository) | `,` | | `FULLSEND_TRACE_SIGNING_KEY` | Repo secret | Trace-context signing key ([ADR 0154](../../ADRs/0154-correlate-work-item-and-behaviour-scenario-traces.md)): standard base64 of a 32-byte Ed25519 seed, generated by `repos install`, which records its public key in `repos.yaml` as `config.trace_context`. [Trace signing keys](../../cli/repos.md#trace-signing-keys) lists when install writes it. Nothing reads it yet. `fullsend run` keeps it from harnesses. `repos uninstall` deletes it | (generated) | | `FULLSEND_GITHUB_RUNNER_SECRETS` | Repo or org secret (optional) | JSON object of name → value for host-side scripts, read through each harness's `env.runner`. Set with `gh secret set`, not `fullsend github set`; see [Pass secrets to host-side scripts](../user/bring-your-own-agent.md#pass-secrets-to-host-side-scripts-github) | `{"JIRA_API_TOKEN":"..."}` | diff --git a/docs/guides/infrastructure/infrastructure-reference.md b/docs/guides/infrastructure/infrastructure-reference.md index bb8de5bf54..055c7d7b3a 100644 --- a/docs/guides/infrastructure/infrastructure-reference.md +++ b/docs/guides/infrastructure/infrastructure-reference.md @@ -348,6 +348,11 @@ Secrets and variables are deployed on the target repository. not by `github setup`) - `FULLSEND_JIRA_TOKEN`, `FULLSEND_JIRA_EMAIL` — Jira API token and optional account email for repos whose effective `tracker.jira.poll.enabled` is `true`, used by the poller and Jira-originated agent status updates (written by `repos install --jira-token` / `--jira-email`; an omitted flag keeps the existing secret; deleted by `repos uninstall`; not set by `github setup`) - `FULLSEND_JIRA_CLIENT_ID`, `FULLSEND_JIRA_CLIENT_SECRET` — a service account's OAuth 2.0 credential, an alternative to `FULLSEND_JIRA_TOKEN` (never both). GitHub poll and Jira-originated dispatch workflows forward them to the Jira client, and `repos install` writes them on GitHub and GitLab; `repos uninstall` deletes them +- `FULLSEND_JIRA_WRITE_GROUPS`, `FULLSEND_JIRA_WRITE_ACCOUNTS`, + `FULLSEND_JIRA_TRIAGE_GROUPS`, `FULLSEND_JIRA_TRIAGE_ACCOUNTS` — optional, + set by you: the Jira group or account IDs that the `jira` authorization + entry reads with `groups_from` or `accounts_from` + ([setup](../user/jira-integration.md#keeping-the-lists-out-of-the-repository)) - `FULLSEND_TRACE_SIGNING_KEY` — trace-context signing key ([ADR 0154](../../ADRs/0154-correlate-work-item-and-behaviour-scenario-traces.md)): standard base64 of a 32-byte Ed25519 seed, generated by `repos install`, diff --git a/docs/guides/user/custom-poller-example.md b/docs/guides/user/custom-poller-example.md index e9928aa76e..574cd33730 100644 --- a/docs/guides/user/custom-poller-example.md +++ b/docs/guides/user/custom-poller-example.md @@ -112,6 +112,14 @@ tracker: See [Jira Integration § Custom JQL](jira-integration.md#custom-jql). +> **If the poll job receives a `jira` authorization list secret** (see +> [Keeping the lists out of the repository](jira-integration.md#keeping-the-lists-out-of-the-repository)), +> do not set the `matrix` output in that job, as this example does. GitHub +> drops a job output that contains the value of a secret the job has, and +> the matrix contains the ID of the account that acted. Set the output from +> a second job that receives no list secret. See +> [GitHub: Vault or another secret store](jira-integration.md#github-vault-or-another-secret-store). + ## Matrix Format The `matrix` input (a GitHub Actions [matrix strategy](https://docs.github.com/en/actions/writing-workflows/choosing-what-your-workflow-does/running-variations-of-jobs-in-a-workflow#using-a-matrix-strategy) that runs parallel jobs) must follow the format produced by `fullsend dispatch --output-driver gha-matrix`: diff --git a/docs/guides/user/jira-integration.md b/docs/guides/user/jira-integration.md index 16201c9d38..860200fab6 100644 --- a/docs/guides/user/jira-integration.md +++ b/docs/guides/user/jira-integration.md @@ -962,7 +962,10 @@ commit or pull request as the rest of the installation. The workflow: - passes the selected Jira credential set to the poll job. For Jira-originated runs, it passes the same set to Fullsend's status writer; the values do not enter the runner-secret bundle or sandbox. The built-in agents' harnesses - map the same set in `env.runner` for their post-scripts' own Jira writes. + map the same set in `env.runner` for their post-scripts' own Jira writes; +- passes the poll job the authorization list secrets that the `jira` entry + reads, if any (see + [Keeping the lists out of the repository](#keeping-the-lists-out-of-the-repository)). The workflow has no Jira URL, project, or query inputs. The poller reads them from the configuration. Both reusable workflows are pinned to the scaffold's @@ -980,7 +983,8 @@ earlier version of this guide, it has no marker: install reports it and leaves it untouched. Delete that file and re-run `repos install` to switch to the managed workflow. -**How this works:** The poll job queries Jira and builds a dispatch matrix in +**How this works:** The poll job queries Jira and saves the dispatch records. +A second job, which receives no secrets, turns them into a dispatch matrix in the format expected by `reusable-dispatch.yml`. When the `matrix` input is provided, `reusable-dispatch.yml` skips its routing and dispatch steps and goes directly to running harness agents with the pre-computed matrix. Because @@ -1297,7 +1301,7 @@ The `event_payload` field is a structured execution payload object wrapping issu } }, "actor": { - "id": "5f7c012e0b2a4c001f3d9876", + "id": "712020:00000000-0000-0000-0000-000000000000", "kind": "human", "role": "write", "is_entity_author": false, @@ -1332,7 +1336,7 @@ authorization: - provider: jira write: # Fullsend role write groups: [example-team-developers] - accounts: ["5f7c012e0b2a4c001f3d9876"] # Jira account IDs + accounts: ["712020:00000000-0000-0000-0000-000000000000"] # Jira account IDs triage: # Fullsend role triage groups: [example-team] accounts: [] @@ -1385,6 +1389,193 @@ Jira's user-groups API, once per actor per poll cycle. Account entries are compared with the actor's account ID directly. To find an account ID, open the user's Jira profile: the ID is the last part of its URL. +### Keeping the lists out of the repository + +On a public repository, anyone can read `.fullsend/config.yaml`, and so the +`jira` lists: + +- An account ID identifies a person on your Atlassian site. +- A group name often describes the team. +- Together, the lists show which accounts can make the agents change the + repository. + +List groups by group ID, not by name, and use groups rather than `accounts`. +Jira returns a group's name or members only to a caller with the *Browse +users and groups* global permission +([Get users from group](https://developer.atlassian.com/cloud/jira/platform/rest/v3/api-group-groups/#api-rest-api-3-group-member-get)). +A site does not grant it to people who are not signed in unless an admin +chose to +([Prevent or remove public access](https://confluence.atlassian.com/servicedeskcloud/prevent-or-remove-public-access-1097175896.html)). +To keep the IDs private whatever the site's settings, read a list from an +environment variable with `groups_from` or `accounts_from`: + +```yaml +authorization: + - provider: jira + write: + groups_from: FULLSEND_JIRA_WRITE_GROUPS # value: "," + triage: + groups_from: FULLSEND_JIRA_TRIAGE_GROUPS + labels: allowlist +``` + +- The variable holds a comma-separated list. One entry per line also works. + The poller trims spaces around each entry and drops empty entries. Write + the entries bare, with no quotes or brackets. Entries match like the + inline list: a group name or group ID for `groups_from`, an account ID + for `accounts_from`. +- The poller reads the variable on every poll, so a new value applies from + the next poll, with no change to the repository. +- An unset or empty variable grants no one, like an empty inline list. The + list still counts as set, so Jira project roles do not decide instead. The + poller logs a warning that names the variable on every poll. +- A role sets either `groups` or `groups_from`, and either `accounts` or + `accounts_from`. Config loading fails when a role sets both forms of one + field. Mixing fields is fine, for example `groups_from` with inline + `accounts`. +- The poller never prints the values or the groups it resolves. +- The lists stay out of the repository, but the account that acts is not + hidden. On GitHub, when an account triggers an agent, its account ID is in + that run's dispatch record. The record is in the poll run's artifact and in + the agent job's log, as it is with inline lists. Groups are never in it. +- Every job runs the CLI at the repository's `fullsend_ref`, and a release + that predates `groups_from` and `accounts_from` can't load the config. When + the `jira` entry uses them and `fullsend_ref` pins such a release, + `fullsend repos install` fails before it changes anything. Upgrade + `fullsend_ref` and run install again. + +The poll job checks the roles, so the variable must be in the poll job's +environment. + +#### GitHub: repository secrets + +The managed poll workflow can pass four repository secrets to the poller: +`FULLSEND_JIRA_WRITE_GROUPS`, `FULLSEND_JIRA_WRITE_ACCOUNTS`, +`FULLSEND_JIRA_TRIAGE_GROUPS`, and `FULLSEND_JIRA_TRIAGE_ACCOUNTS`. + +1. Store each list as a repository secret: + + ```bash + gh secret set FULLSEND_JIRA_WRITE_GROUPS --repo / --body "," + ``` + +2. Name the secret in the `jira` entry, as in the example above. +3. Run `fullsend repos install`. Install adds the secrets that the `jira` + entry names to `.github/workflows/fullsend-poll-jira.yml`, which passes + them to the poll job only. GitHub masks secret values in logs. + +To change who is authorized, update the secret. Install never writes or +deletes these secrets, and `repos uninstall` leaves them in place. + +When the `jira` entry names any other variable, install warns: the managed +workflow cannot pass it, so that list grants no one unless the runner's own +environment sets the variable. + +#### GitHub: Vault or another secret store + +Fullsend does not read Vault or any other store itself. Choose one route: + +- Keep the managed workflow, and let the store keep the repository secret + above up to date. For example, Vault Enterprise secrets sync can write + GitHub repository secrets. +- Maintain your own poll workflow (see [Scheduled workflow](#scheduled-workflow) + for how install treats a workflow without the marker line). Add a step + before the step that runs `fullsend poll --input-driver jira-poll`, and + give the variable any name. + +In your own workflow, `hashicorp/vault-action` can read Vault with GitHub's +OIDC token, so GitHub stores no Vault token. The job needs +`id-token: write`, and Vault needs a JWT role bound to the repository and +workflow. The action exports each value as an environment variable and masks +it in logs: + +```yaml + - name: Read the Jira lists from Vault + uses: hashicorp/vault-action@ # pin to a release + with: + url: https://vault.example.com + method: jwt + role: fullsend-jira-poll + secrets: | + secret/data/fullsend/jira write_groups | FULLSEND_JIRA_WRITE_GROUPS ; + secret/data/fullsend/jira triage_groups | FULLSEND_JIRA_TRIAGE_GROUPS +``` + +Your workflow must install a fullsend release that supports `groups_from` +and `accounts_from`. An older release rejects them as unknown fields. + +For a store with no GitHub Action: + +1. Fetch the value in a script step, as one line: + + ```bash + VALUE="$( | tr -s '\r\n' ',')" + ``` + + `tr` joins a list stored one entry per line. Without it, step 2 masks + only the first line and prints the others. +2. Mask it before anything else prints it: + + ```bash + echo "::add-mask::$VALUE" + ``` + + GitHub then replaces the value with `***` in logs. +3. Append `NAME=value` to `$GITHUB_ENV`: + + ```bash + echo "FULLSEND_JIRA_WRITE_GROUPS=$VALUE" >> "$GITHUB_ENV" + ``` + + Later steps in the job, including the poll step, then see the variable. + +Set the dispatch matrix output in a job that does not receive the list +secrets. GitHub drops a job output that contains a value of a secret the job +has, and the matrix contains the ID of the account that acted, which can equal +a list value. For example, save the dispatch file as an artifact in the poll +job, and set the output from a second job that reads it. +`reusable-poll-jira.yml` does it this way. + +#### GitLab: CI/CD variables + +The Jira poll job receives the project's CI/CD variables, so any variable +name works. Use a name without the `FULLSEND_` prefix, for example +`JIRA_WRITE_GROUPS`: `fullsend repos status` reports a `FULLSEND_` variable +it does not manage as an orphan and exits with an error. Add one CI/CD +variable per list, under the name the `jira` entry uses, set up like +fullsend's own secrets: + +- **Type:** Variable, not File. +- **Environments:** All (default). +- **Visibility:** Masked and hidden (GitLab 17.4 or later), or Masked. +- **Flags:** select **Protect variable** and clear **Expand variable + reference**. GitLab masks a value that contains a comma only when + expansion is off, and only in GitLab 15.9 or later. See + [Mask a CI/CD variable](https://docs.gitlab.com/ci/variables/#mask-a-cicd-variable). +- **Value:** at least 8 characters, with no spaces, for example + `,`. A group name that contains a space can't be + masked, so use the group ID. + +GitLab gives the variable to every job in pipelines on protected branches or +tags, not only the Jira poll job: agent jobs and the project's own jobs get it +too. The poller never prints the value, and if another job does, the log +shows `[MASKED]`. + +GitLab refuses to save a masked variable whose value breaks its masking +rules. Before GitLab 15.9 a masked value can't contain a comma, so only a +list with one entry can be masked there: upgrade GitLab to store a longer +list. Do not save the list unmasked. + +A pipeline variable with the same name, such as one set on a pipeline +schedule, replaces the project variable +([CI/CD variable precedence](https://docs.gitlab.com/ci/variables/#cicd-variable-precedence)). +Keep `ci_pipeline_variables_minimum_override_role` at `no_one_allowed`, which +`fullsend repos install` requires +([Prerequisites](../getting-started/configuring-gitlab.md#prerequisites)): +GitLab then refuses new schedule variables. A variable added to a schedule +earlier still applies, so run `fullsend repos install` after you apply the +setting: it replaces a Jira poll schedule that has variables. + ### Minimum Jira permissions | Permission | When the poller account needs it | @@ -1533,6 +1724,9 @@ However, more pollers against the same Jira project means more API calls per cyc | `load project roles for PROJ: ... 401 You cannot edit the configuration of this project` | The poller read Jira project roles without Administer Projects. That happens with no `jira` entry in `.fullsend/config.yaml`, with `labels: project_roles`, or on a slash command when the entry sets no lists | Add a `jira` entry with `write`/`triage` lists so project roles are not read, or grant the poller account the **Administrators** project role. See [Minimum Jira permissions](#minimum-jira-permissions) | | `resolve jira list groups: ... get user groups` errors | The `jira` lists name groups, or project-role resolution found a role granted to a group, but the poller account lacks the Browse users and groups global permission | Grant Browse users and groups, or list account IDs instead of groups | | Slash command ignored (with `jira` lists) | Actor is not in the `write` list (or the `triage` list for triage-level agents) | Add the actor's account ID or one of their groups to the right list — see [Actor role resolution](#actor-role-resolution) | +| Everyone is denied after a list moves to `groups_from` or `accounts_from`, and the poll log shows ` is unset or empty, so it grants no one` | The variable is unset or empty in the poll job: the secret is missing, or the managed GitHub workflow cannot pass its name (install warns) | Set the variable. On GitHub with the managed workflow, use one of the four `FULLSEND_JIRA_*` secret names and run `fullsend repos install` — see [Keeping the lists out of the repository](#keeping-the-lists-out-of-the-repository) | +| `pinned fullsend_ref "..." does not support` or `the installed scaffold's ref "..." does not support` from `repos install` | The repository's jobs run a release that predates `groups_from` and `accounts_from` | Set `fullsend_ref` to a release that includes them and run install again | +| `set groups or groups_from, not both` (or `accounts`) | One role sets both the inline list and its `*_from` form | Keep one form for that field | | Slash command ignored (without `jira` lists) | Actor lacks `write` role in Jira project | The actor must be a member of a Jira project role named exactly "Developers" or "Administrators" — see [Project role mapping](#project-role-mapping) if you use custom role names | | Issue opened or edited on Jira never dispatches triage | A `jira` entry is present but sets no `write` or `triage` list and not `labels: project_roles`, so opened and edited events are unresolved (with no `jira` entry, or with `labels: project_roles` and no lists, they resolve through project roles) | Add `write`/`triage` lists to the entry, or set `labels: project_roles`. See [Actor role resolution](#actor-role-resolution) | | Label added but nothing dispatched | There is no `jira` entry, or it sets `labels: allowlist` or `labels: project_roles`, and the label author is not authorized by it | Add the author to the lists, or add a `jira` entry with the default `labels: jira_editors` | diff --git a/docs/reference/config-reference.md b/docs/reference/config-reference.md index a937ef8efa..9030a48b64 100644 --- a/docs/reference/config-reference.md +++ b/docs/reference/config-reference.md @@ -89,9 +89,9 @@ authorization: # Extra sources of permission for triggerin - provider: jira # Jira (jira-poll): who may trigger agents from Jira events write: # Fullsend role write groups: [example-team-developers] # Jira group names (or group IDs) - accounts: ["5f7c012e0b2a4c001f3d9876"] # Jira account IDs + accounts: ["712020:00000000-0000-0000-0000-000000000000"] # Jira account IDs triage: # Fullsend role triage - groups: [example-team] + groups_from: FULLSEND_JIRA_TRIAGE_GROUPS # Or read a list from an environment variable (GitLab: use a name without the FULLSEND_ prefix) accounts: [] labels: jira_editors # Label-added events: jira_editors (default), allowlist, project_roles @@ -692,6 +692,7 @@ GitLab authorization |---|---| | `write.groups`, `write.accounts` | Jira groups (by name or group ID) and Jira account IDs granted the fullsend `write` role | | `triage.groups`, `triage.accounts` | Jira groups and account IDs granted the fullsend `triage` role | +| `write.groups_from`, `write.accounts_from`, `triage.groups_from`, `triage.accounts_from` | The name of an environment variable that holds that list as comma-separated values, instead of the inline list | | `labels` | How a label-added event is authorized: `jira_editors` (default once the entry is present), `allowlist`, or `project_roles` | - **Slash commands and other non-label events:** when the entry sets a @@ -718,14 +719,31 @@ GitLab authorization resolution calls the same API for an actor when a project role is granted to a group. +- **Lists from the environment:** on a public repository, anyone can read + `config.yaml`, including the lists. `groups_from` and `accounts_from` name + an environment variable instead, such as a GitHub repository secret. The + poller reads it on every poll, splits it on commas and newlines, trims each + entry, and drops empty ones. It never prints the values. An unset or empty variable grants + no one, the list still counts as set, and the poller logs a warning that + names the variable. A role cannot set both `groups` + and `groups_from`, or both `accounts` and `accounts_from`. The variable + name must use letters, digits, and underscores, and must not start with a + digit. The managed GitHub poll workflow passes only + `FULLSEND_JIRA_WRITE_GROUPS`, `FULLSEND_JIRA_WRITE_ACCOUNTS`, + `FULLSEND_JIRA_TRIAGE_GROUPS`, and `FULLSEND_JIRA_TRIAGE_ACCOUNTS`. On + GitLab, use a name without the `FULLSEND_` prefix, such as + `JIRA_TRIAGE_GROUPS` + ([GitLab: CI/CD variables](../guides/user/jira-integration.md#gitlab-cicd-variables)). See + [Keeping the lists out of the repository](../guides/user/jira-integration.md#keeping-the-lists-out-of-the-repository). + To keep today's behavior explicitly, use the two-line entry `- provider: jira` with `labels: project_roles` and no lists. The provider is opt-in. Without a `jira` entry, every Jira event, including label-added events, resolves through the project role lookup and takes the per-harness role threshold, which needs Administer Projects. Unknown keys in a `jira` entry, an -unknown `labels` value, and empty group or account entries fail config -loading. See +unknown `labels` value, empty group or account entries, and an empty or +invalid `*_from` variable name fail config loading. See [Jira integration](../guides/user/jira-integration.md#actor-role-resolution) for the permissions each setting needs. diff --git a/internal/cli/poll.go b/internal/cli/poll.go index 5ff2d42e40..846158fc9b 100644 --- a/internal/cli/poll.go +++ b/internal/cli/poll.go @@ -3,6 +3,7 @@ package cli import ( "context" "fmt" + "log" "os" "regexp" "strconv" @@ -204,7 +205,7 @@ func runJiraPoll(cmd *cobra.Command, jiraURL, jiraProject, jqlOverride, targetRe return fmt.Errorf("build CEL matcher: %w", err) } - poller := jirapoll.New(jiraClient, matcher, jiraPollOptions(args, matcher)) + poller := jirapoll.New(jiraClient, matcher, jiraPollOptions(args, matcher, os.Getenv)) return poller.Run(cmd.Context()) } @@ -564,10 +565,11 @@ func jiraAuthOptions(p *config.AuthorizationProvider) harnessdispatch.AuthOption // jiraPollOptions builds the poller options every jira-poll target forge // shares: the Jira connection, the query, the output path and the jira -// authorization provider the matcher loaded. Forge-specific callers set +// authorization provider the matcher loaded, with any groups_from and +// accounts_from list read through getenv. Forge-specific callers set // their own TargetForge, GitLabURL and Dispatcher on the result, so the // authorization lists reach the poller on every target. -func jiraPollOptions(args jiraPollArgs, matcher *celMatcher) jirapoll.Options { +func jiraPollOptions(args jiraPollArgs, matcher *celMatcher, getenv func(string) string) jirapoll.Options { return jirapoll.Options{ TargetRepo: args.targetRepo, JiraBaseURL: args.jira.baseURL, @@ -575,27 +577,43 @@ func jiraPollOptions(args jiraPollArgs, matcher *celMatcher) jirapoll.Options { JQL: args.jira.jql, OutputPath: args.outputPath, - Authorization: jiraPollAuthorization(matcher.jiraAuth), + Authorization: jiraPollAuthorization(matcher.jiraAuth, getenv), } } // jiraPollAuthorization converts the jira authorization provider to the -// poller's option type. A nil provider is the zero value. -func jiraPollAuthorization(p *config.AuthorizationProvider) jirapoll.Authorization { +// poller's option type, reading each groups_from and accounts_from list +// through getenv on every poll. An unset or empty variable leaves that list +// empty, which denies everyone it would have named, and logs a warning. A +// nil provider is the zero value. The resolved lists can identify people, +// so they are never logged. +func jiraPollAuthorization(p *config.AuthorizationProvider, getenv func(string) string) jirapoll.Authorization { if p == nil { return jirapoll.Authorization{} } - list := func(l *config.JiraActorList) jirapoll.ActorList { - if l == nil { - return jirapoll.ActorList{} + list := func(role string, l *config.JiraActorList) jirapoll.ActorList { + groups, accounts := l.Resolved(getenv) + if l != nil { + warnEmptyJiraEnvList(role+".groups_from", l.GroupsFrom, groups) + warnEmptyJiraEnvList(role+".accounts_from", l.AccountsFrom, accounts) } - return jirapoll.ActorList{Groups: l.Groups, Accounts: l.Accounts} + return jirapoll.ActorList{Groups: groups, Accounts: accounts} } return jirapoll.Authorization{ Configured: true, - Write: list(p.Write), - Triage: list(p.Triage), + Write: list("write", p.Write), + Triage: list("triage", p.Triage), ListsConfigured: p.Write != nil || p.Triage != nil, Labels: p.EffectiveJiraLabels(), } } + +// warnEmptyJiraEnvList logs when the variable a groups_from or accounts_from +// key names grants no one, so a missing secret does not stop every agent +// without a sign. It prints the variable's name, which config.yaml already +// shows, never its value. +func warnEmptyJiraEnvList(key, name string, entries []string) { + if name != "" && len(entries) == 0 { + log.Printf("WARNING: jira authorization %s: %s is unset or empty, so it grants no one", key, name) + } +} diff --git a/internal/cli/poll_jira_gitlab.go b/internal/cli/poll_jira_gitlab.go index 090f0f5e1b..e3a9b372b5 100644 --- a/internal/cli/poll_jira_gitlab.go +++ b/internal/cli/poll_jira_gitlab.go @@ -156,7 +156,7 @@ func runJiraPollGitLab(cmd *cobra.Command, f jiraPollGitLabFlags) error { ChildDispatchJobToken: childJobToken, }) - opts := jiraPollOptions(args, matcher) + opts := jiraPollOptions(args, matcher, os.Getenv) opts.TargetForge = jirapoll.TargetForgeGitLab opts.GitLabURL = gitlabURL opts.Dispatcher = jiradispatch.GitLabDispatcher{Poller: glPoller} diff --git a/internal/cli/poll_test.go b/internal/cli/poll_test.go index 918d534409..d07baa6fef 100644 --- a/internal/cli/poll_test.go +++ b/internal/cli/poll_test.go @@ -1,7 +1,9 @@ package cli import ( + "bytes" "context" + "log" "net/http" "net/http/httptest" "os" @@ -737,7 +739,7 @@ authorization: Triage: jirapoll.ActorList{Accounts: []string{"acct"}}, ListsConfigured: true, Labels: config.JiraLabelsAllowlist, - }, jiraPollAuthorization(m.jiraAuth)) + }, jiraPollAuthorization(m.jiraAuth, noJiraEnv)) // Kill switch keeps the provider so the poller's role resolution is // configured consistently. @@ -750,7 +752,7 @@ authorization: require.NoError(t, err) require.NotNil(t, m.jiraAuth) assert.True(t, m.Auth.JiraLabelsByEditPermission) - assert.Equal(t, jirapoll.Authorization{Configured: true, Labels: config.JiraLabelsEditors}, jiraPollAuthorization(m.jiraAuth)) + assert.Equal(t, jirapoll.Authorization{Configured: true, Labels: config.JiraLabelsEditors}, jiraPollAuthorization(m.jiraAuth, noJiraEnv)) // An invalid labels value fails config loading. require.NoError(t, os.WriteFile(filepath.Join(dir, "config.yaml"), []byte(`version: "1" @@ -763,6 +765,9 @@ authorization: assert.Contains(t, err.Error(), "invalid labels") } +// noJiraEnv is a getenv that sets no variable. +func noJiraEnv(string) string { return "" } + func TestJiraPollOptions_ForwardsAuthorization(t *testing.T) { dir := t.TempDir() require.NoError(t, os.WriteFile(filepath.Join(dir, "config.yaml"), []byte(`version: "1" @@ -781,7 +786,7 @@ authorization: jira: jiraPollSettings{baseURL: "https://jira.example.com", apiURL: config.DefaultJiraAPIURL, project: "PROJ", jql: "project = PROJ", enabled: true}, targetRepo: "group/sub/repo", outputPath: "out.json", fullsendDir: dir, } - opts := jiraPollOptions(args, m) + opts := jiraPollOptions(args, m, noJiraEnv) assert.Equal(t, jirapoll.Options{ TargetRepo: "group/sub/repo", JiraBaseURL: "https://jira.example.com", @@ -805,13 +810,39 @@ authorization: assert.True(t, opts.Authorization.Configured) assert.Equal(t, jirapoll.ActorList{Groups: []string{"devs"}}, opts.Authorization.Write) + // Lists read from the environment convert to the same authorization. + // An unset variable leaves its list empty, which denies everyone, and + // logs a warning that names the variable. + require.NoError(t, os.WriteFile(filepath.Join(dir, "config.yaml"), []byte(`version: "1" +authorization: + - provider: jira + write: + groups_from: WRITE_GROUPS + triage: + accounts_from: TRIAGE_ACCOUNTS + labels: allowlist +`), 0o644)) + m, err = newCELMatcher(context.Background(), dir) + require.NoError(t, err) + var logs bytes.Buffer + prevOut := log.Writer() + log.SetOutput(&logs) + t.Cleanup(func() { log.SetOutput(prevOut) }) + env := map[string]string{"WRITE_GROUPS": "devs", "TRIAGE_ACCOUNTS": "acct"} + assert.Equal(t, opts.Authorization, jiraPollOptions(args, m, func(k string) string { return env[k] }).Authorization) + assert.Empty(t, logs.String()) + assert.Equal(t, jirapoll.Authorization{Configured: true, ListsConfigured: true, Labels: config.JiraLabelsAllowlist}, + jiraPollOptions(args, m, noJiraEnv).Authorization) + assert.Contains(t, logs.String(), "write.groups_from: WRITE_GROUPS is unset or empty") + assert.Contains(t, logs.String(), "triage.accounts_from: TRIAGE_ACCOUNTS is unset or empty") + // With no jira entry both forges get the zero value: project roles for // every event, as before the provider existed. require.NoError(t, os.WriteFile(filepath.Join(dir, "config.yaml"), []byte(`version: "1" `), 0o644)) m, err = newCELMatcher(context.Background(), dir) require.NoError(t, err) - assert.Equal(t, jirapoll.Authorization{}, jiraPollOptions(args, m).Authorization) + assert.Equal(t, jirapoll.Authorization{}, jiraPollOptions(args, m, noJiraEnv).Authorization) } func TestNewCELMatcher_RejectsInvalidAuthorization(t *testing.T) { @@ -849,10 +880,10 @@ func TestJiraPollAuthorization_EmptyListsStayConfigured(t *testing.T) { got := jiraPollAuthorization(&config.AuthorizationProvider{ Provider: config.AuthProviderJira, Write: &config.JiraActorList{}, - }) + }, noJiraEnv) assert.True(t, got.ListsConfigured) assert.True(t, got.HasLists()) - assert.False(t, jiraPollAuthorization(&config.AuthorizationProvider{Provider: config.AuthProviderJira}).HasLists()) + assert.False(t, jiraPollAuthorization(&config.AuthorizationProvider{Provider: config.AuthProviderJira}, noJiraEnv).HasLists()) } func TestNewCELMatcher_NullListKeysStayConfigured(t *testing.T) { @@ -869,7 +900,7 @@ func TestNewCELMatcher_NullListKeysStayConfigured(t *testing.T) { m, err := newCELMatcher(context.Background(), dir) require.NoError(t, err) require.NotNil(t, m.jiraAuth) - got := jiraPollAuthorization(m.jiraAuth) + got := jiraPollAuthorization(m.jiraAuth, noJiraEnv) assert.True(t, got.ListsConfigured) assert.True(t, got.HasLists()) }) @@ -886,6 +917,6 @@ func TestNewCELMatcher_RejectsAliasedMisspelledJiraKey(t *testing.T) { } func TestJiraPollAuthorization_NilProvider(t *testing.T) { - assert.Equal(t, jirapoll.Authorization{}, jiraPollAuthorization(nil)) + assert.Equal(t, jirapoll.Authorization{}, jiraPollAuthorization(nil, noJiraEnv)) assert.False(t, jiraAuthOptions(nil).JiraLabelsByEditPermission) } diff --git a/internal/config/config.go b/internal/config/config.go index 2e0a7b4ea7..5d7619cc74 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -361,16 +361,85 @@ type AuthorizationProvider struct { // JiraActorList names the Jira actors granted one Fullsend role by the // jira authorization provider. Groups are Jira group names (or group IDs); // accounts are Jira account IDs. +// +// GroupsFrom and AccountsFrom name an environment variable that holds the +// list instead, as comma-separated values, so the list stays out of a +// public repository. The poller reads the variable on every run (see +// Resolved). A list sets either Groups or GroupsFrom, and either Accounts +// or AccountsFrom, not both. type JiraActorList struct { - Groups []string `yaml:"groups,omitempty"` - Accounts []string `yaml:"accounts,omitempty"` + Groups []string `yaml:"groups,omitempty"` + GroupsFrom string `yaml:"groups_from,omitempty"` + Accounts []string `yaml:"accounts,omitempty"` + AccountsFrom string `yaml:"accounts_from,omitempty"` } -// IsEmpty reports whether l lists no group and no account. +// IsEmpty reports whether l lists no group and no account, and names no +// environment variable to read them from. func (l *JiraActorList) IsEmpty() bool { - return l == nil || (len(l.Groups) == 0 && len(l.Accounts) == 0) + return l == nil || (len(l.Groups) == 0 && len(l.Accounts) == 0 && l.GroupsFrom == "" && l.AccountsFrom == "") } +// Resolved returns the groups and accounts l grants. Inline entries are +// returned as configured. A GroupsFrom or AccountsFrom variable is read +// with getenv and split on commas and newlines; blank entries are dropped, so an unset +// or empty variable grants no one. The values can identify people: callers +// must never log or print them. +func (l *JiraActorList) Resolved(getenv func(string) string) (groups, accounts []string) { + if l == nil { + return nil, nil + } + groups, accounts = l.Groups, l.Accounts + if l.GroupsFrom != "" { + groups = splitJiraActorEnv(getenv(l.GroupsFrom)) + } + if l.AccountsFrom != "" { + accounts = splitJiraActorEnv(getenv(l.AccountsFrom)) + } + return groups, accounts +} + +// splitJiraActorEnv splits a *_from variable's value on commas and +// newlines, trimming each entry and dropping blank ones. Newlines separate +// entries so a secret stored one ID per line still matches. Spaces do not, +// because a Jira group name can contain them. +func splitJiraActorEnv(value string) []string { + var out []string + for _, entry := range strings.FieldsFunc(value, func(r rune) bool { return r == ',' || r == '\n' }) { + if entry = strings.TrimSpace(entry); entry != "" { + out = append(out, entry) + } + } + return out +} + +// JiraEnvNames returns the sorted, de-duplicated environment variable +// names that the jira provider's write: and triage: lists read through +// groups_from and accounts_from. It returns nil when p is nil or names none. +func (p *AuthorizationProvider) JiraEnvNames() []string { + if p == nil { + return nil + } + var names []string + for _, l := range []*JiraActorList{p.Write, p.Triage} { + if l == nil { + continue + } + for _, name := range []string{l.GroupsFrom, l.AccountsFrom} { + if name != "" && !slices.Contains(names, name) { + names = append(names, name) + } + } + } + slices.Sort(names) + return names +} + +// validJiraEnvName matches a groups_from or accounts_from value: a portable +// environment variable name, using only the characters that GitHub Actions +// secret names and GitLab CI/CD variable keys allow. +var validJiraEnvName = regexp.MustCompile(`^[A-Za-z_][A-Za-z0-9_]*$`) + // HasJiraLists reports whether the jira provider sets a write: or triage: // list, even an empty one. When it does, the lists are authoritative for // Jira actors (an actor they do not name is denied) and the Jira project @@ -393,7 +462,7 @@ var jiraProviderKeys = map[string]bool{"provider": true, "write": true, "triage" // jiraActorListKeys are the keys allowed in a jira provider write:/triage: // mapping. -var jiraActorListKeys = map[string]bool{"groups": true, "accounts": true} +var jiraActorListKeys = map[string]bool{"groups": true, "groups_from": true, "accounts": true, "accounts_from": true} // UnmarshalYAML implements yaml.Unmarshaler. Per-repo config is decoded // without strict field checking, so a jira provider entry's keys (and its @@ -429,6 +498,13 @@ func (p *AuthorizationProvider) UnmarshalYAML(value *yaml.Node) error { if err := checkMappingKeys(v, jiraActorListKeys, "authorization: jira provider "+key); err != nil { return err } + // An empty or null *_from decodes to "", which would read + // as "not set" and silently drop the key. + for _, from := range []string{"groups_from", "accounts_from"} { + if f := mappingNode(v, from); f != nil && f.Kind == yaml.ScalarNode && (f.Tag == "!!null" || strings.TrimSpace(f.Value) == "") { + return managedFieldError(f, fmt.Sprintf("authorization: jira provider %s.%s: empty environment variable name", key, from)) + } + } } } } @@ -524,6 +600,24 @@ func validateJiraProvider(p AuthorizationProvider) error { if l.list == nil { continue } + for _, f := range []struct { + field, from string + inline bool + }{ + // A present inline key conflicts even when its list is empty. + {"groups", l.list.GroupsFrom, l.list.Groups != nil}, + {"accounts", l.list.AccountsFrom, l.list.Accounts != nil}, + } { + if f.from == "" { + continue + } + if f.inline { + return fmt.Errorf("jira provider %s: set %s or %s_from, not both", l.name, f.field, f.field) + } + if !validJiraEnvName.MatchString(f.from) { + return fmt.Errorf("jira provider %s.%s_from: invalid environment variable name %q: use letters, digits and underscores, not starting with a digit", l.name, f.field, f.from) + } + } for _, g := range l.list.Groups { if strings.TrimSpace(g) == "" { return fmt.Errorf("jira provider %s.groups: empty group name", l.name) diff --git a/internal/config/config_test.go b/internal/config/config_test.go index 7b31480a1b..dcc34b380c 100644 --- a/internal/config/config_test.go +++ b/internal/config/config_test.go @@ -205,7 +205,7 @@ authorization: - provider: jira write: groups: [example-team-developers] - accounts: ["5f7c012e0b2a4c001f3d9876"] + accounts: ["712020:00000000-0000-0000-0000-000000000000"] triage: groups: [example-team] accounts: [] @@ -216,7 +216,7 @@ authorization: ja := cfg.JiraAuthorization() require.NotNil(t, ja) assert.Equal(t, []string{"example-team-developers"}, ja.Write.Groups) - assert.Equal(t, []string{"5f7c012e0b2a4c001f3d9876"}, ja.Write.Accounts) + assert.Equal(t, []string{"712020:00000000-0000-0000-0000-000000000000"}, ja.Write.Accounts) assert.Equal(t, []string{"example-team"}, ja.Triage.Groups) assert.True(t, ja.HasJiraLists()) assert.Equal(t, JiraLabelsAllowlist, ja.EffectiveJiraLabels()) @@ -227,6 +227,66 @@ authorization: assert.Equal(t, []string{"example-team-developers"}, cfg.JiraAuthorization().Write.Groups) } +func TestParsePerRepoConfig_JiraAuthorizationFromEnv(t *testing.T) { + cfg, err := ParsePerRepoConfig([]byte(` +authorization: + - provider: jira + write: + groups_from: FULLSEND_JIRA_WRITE_GROUPS + accounts_from: FULLSEND_JIRA_WRITE_ACCOUNTS + triage: + groups_from: FULLSEND_JIRA_TRIAGE_GROUPS + accounts: ["712020:00000000-0000-0000-0000-000000000000"] + labels: allowlist +`)) + require.NoError(t, err) + require.NoError(t, cfg.(PerRepoConfigWriter).Validate()) + ja := cfg.JiraAuthorization() + require.NotNil(t, ja) + assert.Equal(t, &JiraActorList{GroupsFrom: "FULLSEND_JIRA_WRITE_GROUPS", AccountsFrom: "FULLSEND_JIRA_WRITE_ACCOUNTS"}, ja.Write) + // Different fields of one role may use different forms. + assert.Equal(t, &JiraActorList{GroupsFrom: "FULLSEND_JIRA_TRIAGE_GROUPS", Accounts: []string{"712020:00000000-0000-0000-0000-000000000000"}}, ja.Triage) + assert.False(t, ja.Write.IsEmpty()) + assert.Equal(t, []string{"FULLSEND_JIRA_TRIAGE_GROUPS", "FULLSEND_JIRA_WRITE_ACCOUNTS", "FULLSEND_JIRA_WRITE_GROUPS"}, ja.JiraEnvNames()) +} + +func TestJiraActorList_Resolved(t *testing.T) { + env := map[string]string{ + "GROUPS": " gid-1 , gid-2,, ,gid-3 ", + "ACCOUNTS": "712020:00000000-0000-0000-0000-000000000000", + "LINES": "gid-1\r\ngid-2\n", + "BLANK": " , ", + "EMPTY": "", + } + getenv := func(k string) string { return env[k] } + + groups, accounts := (&JiraActorList{GroupsFrom: "GROUPS", AccountsFrom: "ACCOUNTS"}).Resolved(getenv) + assert.Equal(t, []string{"gid-1", "gid-2", "gid-3"}, groups) + assert.Equal(t, []string{"712020:00000000-0000-0000-0000-000000000000"}, accounts) + + groups, _ = (&JiraActorList{GroupsFrom: "LINES"}).Resolved(getenv) + assert.Equal(t, []string{"gid-1", "gid-2"}, groups, "one entry per line") + + groups, accounts = (&JiraActorList{Groups: []string{"devs"}, Accounts: []string{"acct"}}).Resolved(getenv) + assert.Equal(t, []string{"devs"}, groups) + assert.Equal(t, []string{"acct"}, accounts) + + for _, name := range []string{"UNSET", "EMPTY", "BLANK"} { + groups, accounts = (&JiraActorList{GroupsFrom: name, AccountsFrom: name}).Resolved(getenv) + assert.Empty(t, groups, name) + assert.Empty(t, accounts, name) + } +} + +func TestJiraEnvNames_Deduplicates(t *testing.T) { + p := &AuthorizationProvider{ + Provider: AuthProviderJira, + Write: &JiraActorList{GroupsFrom: "SHARED"}, + Triage: &JiraActorList{GroupsFrom: "SHARED"}, + } + assert.Equal(t, []string{"SHARED"}, p.JiraEnvNames()) +} + func TestParsePerRepoConfig_JiraAuthorizationDefaults(t *testing.T) { cfg, err := ParsePerRepoConfig([]byte("authorization:\n - provider: jira\n")) require.NoError(t, err) @@ -274,6 +334,31 @@ func TestParsePerRepoConfig_JiraAuthorizationRejectsInvalid(t *testing.T) { yaml: "authorization:\n - provider: jira\n triage:\n accounts: [\" \"]\n", wantErr: "empty account ID", }, + { + name: "groups and groups_from on one role", + yaml: "authorization:\n - provider: jira\n write:\n groups: [g]\n groups_from: WRITE_GROUPS\n", + wantErr: "jira provider write: set groups or groups_from, not both", + }, + { + name: "empty inline list with its _from form", + yaml: "authorization:\n - provider: jira\n write:\n accounts: []\n accounts_from: WRITE_ACCOUNTS\n", + wantErr: "jira provider write: set accounts or accounts_from, not both", + }, + { + name: "env name written as an expansion", + yaml: "authorization:\n - provider: jira\n write:\n groups_from: ${WRITE_GROUPS}\n", + wantErr: `jira provider write.groups_from: invalid environment variable name "${WRITE_GROUPS}"`, + }, + { + name: "empty groups_from", + yaml: "authorization:\n - provider: jira\n write:\n groups_from: \"\"\n", + wantErr: "jira provider write.groups_from: empty environment variable name", + }, + { + name: "null accounts_from", + yaml: "authorization:\n - provider: jira\n triage:\n accounts_from:\n", + wantErr: "jira provider triage.accounts_from: empty environment variable name", + }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { @@ -408,6 +493,17 @@ func TestPerRepoConfigValidate_JiraAuthorization(t *testing.T) { err = jiraFieldsOnOwners.Validate() require.Error(t, err) assert.Contains(t, err.Error(), "only valid for provider") + + bothForms := &perRepoConfig{ + Version: "1", + Authorization: []AuthorizationProvider{{ + Provider: AuthProviderJira, + Triage: &JiraActorList{Groups: []string{"g"}, GroupsFrom: "TRIAGE_GROUPS"}, + }}, + } + err = bothForms.Validate() + require.Error(t, err) + assert.Contains(t, err.Error(), "authorization[0]: jira provider triage: set groups or groups_from, not both") } func TestParsePerRepoConfig(t *testing.T) { diff --git a/internal/config/effective_test.go b/internal/config/effective_test.go index 3607b65415..f1eaba77c7 100644 --- a/internal/config/effective_test.go +++ b/internal/config/effective_test.go @@ -107,7 +107,7 @@ func TestEffectiveYAML_InheritsInferenceGateway(t *testing.T) { } func TestEffectiveYAML_ListsJiraAuthorizationProvider(t *testing.T) { - overlay, err := ParsePerRepoConfigWriter([]byte("authorization:\n - provider: jira\n write:\n accounts: [acct]\n")) + overlay, err := ParsePerRepoConfigWriter([]byte("authorization:\n - provider: jira\n write:\n accounts: [acct]\n triage:\n groups_from: TRIAGE_GROUPS\n")) require.NoError(t, err) layered, err := LayerOnBase(overlay, nil) require.NoError(t, err) @@ -118,6 +118,7 @@ func TestEffectiveYAML_ListsJiraAuthorizationProvider(t *testing.T) { assert.Equal(t, []any{map[string]any{ "provider": "jira", "write": map[string]any{"accounts": []any{"acct"}}, + "triage": map[string]any{"groups_from": "TRIAGE_GROUPS"}, "labels": JiraLabelsEditors, }}, got["authorization"]) } @@ -148,6 +149,9 @@ func TestCloneAuthorizationSlice_DeepCopiesJiraLists(t *testing.T) { out[0].Write.Groups[0] = "changed" assert.Equal(t, "g", in[0].Write.Groups[0]) assert.Nil(t, out[0].Triage) + + fromEnv := []AuthorizationProvider{{Provider: AuthProviderJira, Write: &JiraActorList{GroupsFrom: "G", AccountsFrom: "A"}}} + assert.Equal(t, &JiraActorList{GroupsFrom: "G", AccountsFrom: "A"}, cloneAuthorizationSlice(fromEnv)[0].Write) } func TestEffectiveYAML_CodeDefaultsAndNil(t *testing.T) { diff --git a/internal/config/managed-config-schema b/internal/config/managed-config-schema index 5b721307dd..97b34b1e56 100644 --- a/internal/config/managed-config-schema +++ b/internal/config/managed-config-schema @@ -3,4 +3,8 @@ # render .fullsend/config.yaml in the shape that ref reads. Increment it, and # config.ManagedConfigSchemaVersion with a renderer for the previous version, # whenever a per-repo configuration change is not readable by older releases. +# +# groups_from and accounts_from (#9132) did not increment it, although older +# releases reject them: install and status refuse them for an older ref with +# checkJiraAuthorizationEnvSupport (internal/repos/jira_poll.go). 3 diff --git a/internal/config/managed.go b/internal/config/managed.go index 814bd88174..bf4e3c0ffe 100644 --- a/internal/config/managed.go +++ b/internal/config/managed.go @@ -600,10 +600,10 @@ func cloneAuthorizationProvider(p AuthorizationProvider) AuthorizationProvider { if l == nil { return nil } - return &JiraActorList{ - Groups: slices.Clone(l.Groups), - Accounts: slices.Clone(l.Accounts), - } + out := *l + out.Groups = slices.Clone(l.Groups) + out.Accounts = slices.Clone(l.Accounts) + return &out } p.Write = cloneList(p.Write) p.Triage = cloneList(p.Triage) diff --git a/internal/repos/converge.go b/internal/repos/converge.go index 387f6c5d50..e16403e206 100644 --- a/internal/repos/converge.go +++ b/internal/repos/converge.go @@ -851,7 +851,7 @@ func Converge(ctx context.Context, cfg ConvergeConfig, } if presetErr != nil { excludedUsesJira = true - } else if jira, jiraErr := effectiveJiraTracking(excludedResolved, excludedPreset); jiraErr != nil || jira.PollEnabled() { + } else if st, jiraErr := effectiveJiraPollState(excludedResolved, excludedPreset); jiraErr != nil || st.enabled { excludedUsesJira = true } } @@ -989,12 +989,11 @@ func Converge(ctx context.Context, cfg ConvergeConfig, discoveries[idx] = convergeDiscovery{repo: rr, resolved: resolved, configErr: inputErr} return } - jiraTracking, jiraErr := effectiveJiraTracking(resolved, presetData) + jiraState, jiraErr := effectiveJiraPollState(resolved, presetData) if jiraErr != nil { discoveries[idx] = convergeDiscovery{repo: rr, resolved: resolved, configErr: jiraErr} return } - jiraState := jiraPollState{jira: jiraTracking, enabled: jiraTracking.PollEnabled()} repoFullName := rr.Owner + "/" + rr.Repo progress(repoFullName, "discover", "Checking installation status") @@ -1578,6 +1577,10 @@ func convergeRepo(ctx context.Context, return cr } } + if err := checkJiraAuthorizationEnvSupport(ctx, d, cfg, refResolver); err != nil { + cr.Error = err + return cr + } if err := checkGitHubJiraPollWorkflow(ctx, d, cfg, refResolver); err != nil { cr.Error = err return cr diff --git a/internal/repos/github_jira_poll.go b/internal/repos/github_jira_poll.go index b897561fd5..beae3f7cc0 100644 --- a/internal/repos/github_jira_poll.go +++ b/internal/repos/github_jira_poll.go @@ -5,6 +5,7 @@ import ( "context" "errors" "fmt" + "slices" "sort" "strings" @@ -152,18 +153,10 @@ func userJiraCallerOAuthUses(caller []byte) ([]string, bool) { // rejected, since its OAuth support cannot be established. func requireUserJiraCallerWorkflowsOAuth(ctx context.Context, resolved ResolvedConfig, refResolver *RefResolver, uses []string) error { for _, u := range uses { - var content []byte - var err error - if localPath, local := strings.CutPrefix(u, "./"); local { - content, err = resolved.ForgeConfig.Client.GetFileContent(ctx, resolved.Owner, resolved.Repo, localPath) - } else { - target, ref, hasRef := strings.Cut(u, "@") - parts := strings.SplitN(target, "/", 3) - if !hasRef || len(parts) != 3 || refResolver == nil { - return fmt.Errorf("%s/%s: %s calls %q, whose Jira OAuth support cannot be verified; pin it to owner/repo/path@ref of a Fullsend version that supports OAuth credentials (existing Jira credentials were left unchanged)", - resolved.Owner, resolved.Repo, scaffold.JiraPollCallerPath, u) - } - content, err = refResolver.client.GetFileContentAtRef(ctx, parts[0], parts[1], parts[2], ref) + content, located, err := readUserJiraCallerWorkflow(ctx, resolved, refResolver, u) + if !located { + return fmt.Errorf("%s/%s: %s calls %q, whose Jira OAuth support cannot be verified; pin it to owner/repo/path@ref of a Fullsend version that supports OAuth credentials (existing Jira credentials were left unchanged)", + resolved.Owner, resolved.Repo, scaffold.JiraPollCallerPath, u) } if err != nil { return fmt.Errorf("%s/%s: %s calls %q, whose Jira OAuth support could not be verified: %w (existing Jira credentials were left unchanged)", @@ -177,6 +170,86 @@ func requireUserJiraCallerWorkflowsOAuth(ctx context.Context, resolved ResolvedC return nil } +// readUserJiraCallerWorkflow reads the reusable workflow a user-owned caller's +// `uses` names: at the ref it pins, or from the caller's own repository for a +// local `./` reference. located is false when the reference has no +// owner/repo/path@ref form or no upstream client can read it. +func readUserJiraCallerWorkflow(ctx context.Context, resolved ResolvedConfig, refResolver *RefResolver, uses string) (content []byte, located bool, err error) { + if localPath, local := strings.CutPrefix(uses, "./"); local { + content, err = resolved.ForgeConfig.Client.GetFileContent(ctx, resolved.Owner, resolved.Repo, localPath) + return content, true, err + } + target, ref, hasRef := strings.Cut(uses, "@") + parts := strings.SplitN(target, "/", 3) + if !hasRef || len(parts) != 3 || refResolver == nil { + return nil, false, nil + } + content, err = refResolver.client.GetFileContentAtRef(ctx, parts[0], parts[1], parts[2], ref) + return content, true, err +} + +// checkUserJiraCallerAuthorizationEnv fails when a user-owned Jira poll caller +// calls a reusable-poll-jira.yml that predates groups_from and accounts_from. +// That workflow installs the CLI at its own ref, and an older CLI cannot load +// the config, so every poll would fail. A vendored install runs its own +// binary there, so it is not checked. Neither is a reference that cannot be +// located. +func checkUserJiraCallerAuthorizationEnv(ctx context.Context, d convergeDiscovery, refResolver *RefResolver) error { + resolved := d.resolved + if resolved.Forge != ForgeGitHub || !d.jira.enabled || resolved.Vendor { + return nil + } + caller, exists, err := readJiraPollCaller(ctx, jiraPollRequest{ + Client: resolved.ForgeConfig.Client, + Owner: resolved.Owner, + Repo: resolved.Repo, + }) + if err != nil { + return fmt.Errorf("%s/%s: checking %s for groups_from/accounts_from support: %w", + resolved.Owner, resolved.Repo, scaffold.JiraPollCallerPath, err) + } + if !exists || scaffold.IsManagedJiraPollCaller(caller) { + return nil + } + for _, u := range userJiraCallerPollUses(caller) { + content, located, err := readUserJiraCallerWorkflow(ctx, resolved, refResolver, u) + if !located { + continue + } + if err != nil && !forge.IsNotFound(err) { + return fmt.Errorf("%s/%s: checking %q, called by %s, for groups_from/accounts_from support: %w", + resolved.Owner, resolved.Repo, u, scaffold.JiraPollCallerPath, err) + } + if err != nil || !bytes.Contains(content, []byte(jiraAuthorizationEnvMarker)) { + return fmt.Errorf("%s/%s: config.yaml reads %s with groups_from/accounts_from, which %q, called by %s, does not support; update the reference to a release that includes them", + resolved.Owner, resolved.Repo, strings.Join(d.jira.authEnv, ", "), u, scaffold.JiraPollCallerPath) + } + } + return nil +} + +// userJiraCallerPollUses returns the sorted, de-duplicated `uses` references +// of a user-owned caller's jobs that call the reusable Jira poll workflow. A +// caller that does not parse returns none. +func userJiraCallerPollUses(caller []byte) []string { + var wf struct { + Jobs map[string]struct { + Uses string `yaml:"uses"` + } `yaml:"jobs"` + } + if err := yaml.Unmarshal(caller, &wf); err != nil { + return nil + } + var uses []string + for _, job := range wf.Jobs { + if strings.Contains(job.Uses, "reusable-poll-jira.yml") && !slices.Contains(uses, job.Uses) { + uses = append(uses, job.Uses) + } + } + sort.Strings(uses) + return uses +} + // missingJiraOAuthSecret returns the first Jira OAuth client secret a workflow // does not declare, or "" when it declares them all. func missingJiraOAuthSecret(content []byte) string { @@ -188,25 +261,82 @@ func missingJiraOAuthSecret(content []byte) string { return "" } +// splitJiraAuthorizationEnv splits the variables the jira authorization +// lists read (#9132) into those the managed caller forwards to the poll +// job, in scaffold.JiraAuthorizationSecrets order, and the others, which +// it cannot pass. +func splitJiraAuthorizationEnv(names []string) (forwarded, unforwarded []string) { + for _, name := range scaffold.JiraAuthorizationSecrets { + if slices.Contains(names, name) { + forwarded = append(forwarded, name) + } + } + for _, name := range names { + if !slices.Contains(scaffold.JiraAuthorizationSecrets, name) { + unforwarded = append(unforwarded, name) + } + } + return forwarded, unforwarded +} + // jiraJobForwardsOAuth reports whether a job's secrets node is `inherit` or a // mapping that names every Jira OAuth client secret. func jiraJobForwardsOAuth(secrets yaml.Node) bool { + return len(jiraJobUnforwarded(secrets, jiraOAuthSecrets)) == 0 +} + +// jiraJobUnforwarded returns the names a job's secrets node does not pass to +// the workflow it calls: none for `inherit`, and for a mapping the names it +// leaves out. Any other node passes nothing. +func jiraJobUnforwarded(secrets yaml.Node, names []string) []string { + named := map[string]bool{} switch secrets.Kind { case yaml.ScalarNode: - return secrets.Value == "inherit" + if secrets.Value == "inherit" { + return nil + } case yaml.MappingNode: - named := map[string]bool{} for i := 0; i+1 < len(secrets.Content); i += 2 { named[secrets.Content[i].Value] = true } - for _, name := range jiraOAuthSecrets { - if !named[name] { - return false + } + var missing []string + for _, name := range names { + if !named[name] { + missing = append(missing, name) + } + } + return missing +} + +// userJiraCallerUnforwarded returns the names that a user-owned caller's +// jobs calling the reusable Jira poll workflow do not pass to it, and +// reports whether it has such a job. A caller that runs the poller itself, +// or does not parse, returns none: only its owner knows what its +// environment sets. +func userJiraCallerUnforwarded(caller []byte, names []string) (missing []string, calls bool) { + var wf struct { + Jobs map[string]struct { + Uses string `yaml:"uses"` + Secrets yaml.Node `yaml:"secrets"` + } `yaml:"jobs"` + } + if err := yaml.Unmarshal(caller, &wf); err != nil { + return nil, false + } + for _, job := range wf.Jobs { + if !strings.Contains(job.Uses, "reusable-poll-jira.yml") { + continue + } + calls = true + for _, name := range jiraJobUnforwarded(job.Secrets, names) { + if !slices.Contains(missing, name) { + missing = append(missing, name) } } - return true } - return false + sort.Strings(missing) + return missing, calls } // requireJiraOAuthSecrets rejects a reusable workflow that does not declare @@ -221,7 +351,8 @@ func requireJiraOAuthSecrets(resolved ResolvedConfig, source, ref, workflowPath // Ensure makes the managed caller present and current. func (githubJiraPollReconciler) Ensure(ctx context.Context, req jiraPollRequest) ([]ComponentAction, error) { - want, err := scaffold.RenderJiraPollCaller(req.Render, req.EmailConfigured, req.OAuthConfigured) + forwarded, unforwarded := splitJiraAuthorizationEnv(req.AuthorizationEnv) + want, err := scaffold.RenderJiraPollCaller(req.Render, req.EmailConfigured, req.OAuthConfigured, forwarded) if err != nil { return nil, err } @@ -230,6 +361,17 @@ func (githubJiraPollReconciler) Ensure(ctx context.Context, req jiraPollRequest) return nil, err } if exists && !scaffold.IsManagedJiraPollCaller(have) { + // A reusable workflow gets only the secrets its caller passes, and + // the poll workflow accepts only the fixed names. + missing, calls := userJiraCallerUnforwarded(have, forwarded) + if len(missing) > 0 && req.Warn != nil { + req.Warn(fmt.Sprintf("authorization: jira groups_from/accounts_from reads %s, which %s does not pass to reusable-poll-jira.yml; add it to that job's secrets, or that list grants no one", + strings.Join(missing, ", "), scaffold.JiraPollCallerPath)) + } + if calls && len(unforwarded) > 0 && req.Warn != nil { + req.Warn(fmt.Sprintf("authorization: jira groups_from/accounts_from reads %s, which reusable-poll-jira.yml does not pass to the poller; rename it to one of %s, or run the poller in your own job", + strings.Join(unforwarded, ", "), strings.Join(scaffold.JiraAuthorizationSecrets, ", "))) + } return []ComponentAction{{ Component: jiraPollComponent, Action: "none", @@ -237,6 +379,13 @@ func (githubJiraPollReconciler) Ensure(ctx context.Context, req jiraPollRequest) scaffold.JiraPollCallerPath), }}, nil } + // The managed caller passes only the fixed names. The poller finds any + // other variable unset, so that list grants no one unless the runner + // itself sets it. + if len(unforwarded) > 0 && req.Warn != nil { + req.Warn(fmt.Sprintf("authorization: jira groups_from/accounts_from reads %s, which the managed %s does not pass to the poller; rename it to one of %s, or set it in the runner's environment", + strings.Join(unforwarded, ", "), scaffold.JiraPollCallerPath, strings.Join(scaffold.JiraAuthorizationSecrets, ", "))) + } if exists && bytes.Equal(have, want) { return []ComponentAction{{ Component: jiraPollComponent, diff --git a/internal/repos/github_jira_poll_test.go b/internal/repos/github_jira_poll_test.go index c1ca8bc3a0..55adf6c263 100644 --- a/internal/repos/github_jira_poll_test.go +++ b/internal/repos/github_jira_poll_test.go @@ -5,6 +5,7 @@ import ( "errors" "slices" "strings" + "sync" "testing" "github.com/stretchr/testify/assert" @@ -60,16 +61,33 @@ func assertNoUnrelatedFiles(t *testing.T, spy *spyScaffoldCommit) { // runJiraConverge converges acme/api with raw as its repository config. func runJiraConverge(t *testing.T, fc *forge.FakeClient, raw string, mutate func(*ConvergeConfig)) (*ConvergeResult, *spyScaffoldCommit) { + t.Helper() + cr, spy, _ := runJiraConvergeWarnings(t, fc, raw, mutate) + return cr, spy +} + +// runJiraConvergeWarnings is runJiraConverge that also returns the +// warnings the run reported, one per line. +func runJiraConvergeWarnings(t *testing.T, fc *forge.FakeClient, raw string, mutate func(*ConvergeConfig)) (*ConvergeResult, *spyScaffoldCommit, string) { t.Helper() cfg := withoutInferenceInputs(convergeCfgWithDefaults(jiraManifest(t, raw))) if mutate != nil { mutate(&cfg) } spy := &spyScaffoldCommit{} - result, err := Converge(context.Background(), cfg, newTestClientFactory(fc), spy.fn(), noopProgress) + var mu sync.Mutex + var warnings []string + progress := func(_, phase, message string) { + if phase == "warning" { + mu.Lock() + defer mu.Unlock() + warnings = append(warnings, message) + } + } + result, err := Converge(context.Background(), cfg, newTestClientFactory(fc), spy.fn(), progress) require.NoError(t, err) require.Len(t, result.Results, 1) - return &result.Results[0], spy + return &result.Results[0], spy, strings.Join(warnings, "\n") } func TestConverge_GitHubJiraPoll_FreshInstallCommitsCaller(t *testing.T) { @@ -152,7 +170,7 @@ func TestConverge_GitHubJiraPoll_EstablishedInstallAddsThenIsIdempotent(t *testi func TestConverge_GitHubJiraPoll_StaleManagedCallerUpdated(t *testing.T) { fc := installedJiraRepo(forge.SecretJiraToken) - stale, err := scaffold.RenderJiraPollCaller(scaffold.RenderOptions{UpstreamRef: "v0.9.0"}, true, false) + stale, err := scaffold.RenderJiraPollCaller(scaffold.RenderOptions{UpstreamRef: "v0.9.0"}, true, false, nil) require.NoError(t, err) fc.FileContents[jiraCallerKey] = stale @@ -179,7 +197,7 @@ func TestConverge_GitHubJiraPoll_DisabledRemovesManagedCaller(t *testing.T) { } { t.Run(name, func(t *testing.T) { fc := installedJiraRepo(forge.SecretJiraToken, forge.SecretJiraEmail) - managed, err := scaffold.RenderJiraPollCaller(scaffold.RenderOptions{}, false, false) + managed, err := scaffold.RenderJiraPollCaller(scaffold.RenderOptions{}, false, false, nil) require.NoError(t, err) fc.FileContents[jiraCallerKey] = managed fc.FileContents[unrelatedKey] = []byte(unrelatedFlow) @@ -246,7 +264,7 @@ func TestConverge_GitHubJiraPoll_DryRunStagesNothing(t *testing.T) { t.Run("remove", func(t *testing.T) { fc := installedJiraRepo() - managed, err := scaffold.RenderJiraPollCaller(scaffold.RenderOptions{}, false, false) + managed, err := scaffold.RenderJiraPollCaller(scaffold.RenderOptions{}, false, false, nil) require.NoError(t, err) fc.FileContents[jiraCallerKey] = managed cr, spy := runJiraConverge(t, fc, "", func(c *ConvergeConfig) { c.DryRun = true }) @@ -435,7 +453,7 @@ func TestCheckGitHubJiraPollWorkflowUserOwnedCallerOAuth(t *testing.T) { func TestGitHubJiraPollReconciler_RequiresScaffoldCommit(t *testing.T) { fc := forge.NewFakeClient() - managed, err := scaffold.RenderJiraPollCaller(scaffold.RenderOptions{}, false, false) + managed, err := scaffold.RenderJiraPollCaller(scaffold.RenderOptions{}, false, false, nil) require.NoError(t, err) req := jiraPollRequest{Client: fc, Owner: "acme", Repo: "api"} @@ -450,7 +468,7 @@ func TestGitHubJiraPollReconciler_RequiresScaffoldCommit(t *testing.T) { } func TestUninstall_RemovesManagedJiraPollCaller(t *testing.T) { - managed, err := scaffold.RenderJiraPollCaller(scaffold.RenderOptions{}, true, false) + managed, err := scaffold.RenderJiraPollCaller(scaffold.RenderOptions{}, true, false, nil) require.NoError(t, err) tests := []struct { @@ -506,3 +524,127 @@ func TestUninstall_RemovesManagedJiraPollCaller(t *testing.T) { }) } } + +// jiraAuthFromEnvConfig reads two lists from secrets the caller can forward. +const jiraAuthFromEnvConfig = jiraPollEnabledConfig + `authorization: + - provider: jira + write: + groups_from: FULLSEND_JIRA_WRITE_GROUPS + triage: + accounts_from: FULLSEND_JIRA_TRIAGE_ACCOUNTS +` + +func TestConverge_GitHubJiraPoll_ForwardsAuthorizationListSecrets(t *testing.T) { + fc := installedJiraRepo(forge.SecretJiraToken) + + cr, spy, warnings := runJiraConvergeWarnings(t, fc, jiraAuthFromEnvConfig, nil) + require.NoError(t, cr.Error) + assert.Empty(t, warnings) + f, ok := stagedJiraCaller(t, spy) + require.True(t, ok) + var caller renderedJiraPollCaller + require.NoError(t, yaml.Unmarshal(f.Content, &caller)) + poll := caller.Jobs["poll"].Secrets + assert.Contains(t, poll, "FULLSEND_JIRA_WRITE_GROUPS") + assert.Contains(t, poll, "FULLSEND_JIRA_TRIAGE_ACCOUNTS") + assert.NotContains(t, poll, "FULLSEND_JIRA_WRITE_ACCOUNTS") + assert.NotContains(t, poll, "FULLSEND_JIRA_TRIAGE_GROUPS") + + // The poller reads the names from the committed config. + spy.mu.Lock() + defer spy.mu.Unlock() + var configYAML string + for _, file := range spy.files { + if file.Path == ".fullsend/config.yaml" { + configYAML = string(file.Content) + } + } + assert.Contains(t, configYAML, "groups_from: FULLSEND_JIRA_WRITE_GROUPS") + assert.Contains(t, configYAML, "accounts_from: FULLSEND_JIRA_TRIAGE_ACCOUNTS") +} + +func TestConverge_JiraAuthorizationEnv_RejectsOldPinBeforeWrites(t *testing.T) { + fc := newFakeClientForBatch("acme/api") + fc.FileContentsRef[shimOwner+"/"+shimRepo+"/"+reusableJiraPollWorkflowPath+"@v0.54.0"] = []byte(jiraOAuthWorkflowFixture) + m := jiraManifest(t, jiraAuthFromEnvConfig) + m.GitHub.Repos[0].FullsendRef = "v0.54.0" + cfg := convergeCfgWithDefaults(m) + cfg.JiraToken = testJiraToken + spy := &spyScaffoldCommit{} + + result, err := Converge(context.Background(), cfg, newTestClientFactory(fc), spy.fn(), noopProgress) + require.NoError(t, err) + require.Len(t, result.Failed(), 1) + assert.ErrorContains(t, result.Results[0].Error, `pinned fullsend_ref "v0.54.0" does not support`) + assert.Empty(t, jiraSecretWrites(fc)) + _, staged := stagedJiraCaller(t, spy) + assert.False(t, staged) +} + +func TestStatus_JiraAuthorizationEnv_ReportsOldPin(t *testing.T) { + // Not installed: the schema check alone would call the config compatible. + for name, fc := range map[string]*forge.FakeClient{ + "installed": installedJiraRepo(forge.SecretJiraToken), + "not installed": newFakeClientForBatch("acme/api"), + } { + t.Run(name, func(t *testing.T) { + fc.FileContentsRef[shimOwner+"/"+shimRepo+"/"+reusableJiraPollWorkflowPath+"@v0.54.0"] = []byte(jiraOAuthWorkflowFixture) + m := jiraManifest(t, jiraAuthFromEnvConfig) + m.GitHub.Repos[0].FullsendRef = "v0.54.0" + + status, err := Status(context.Background(), m, newTestClientFactory(fc), 4, nil) + require.NoError(t, err) + require.Len(t, status.Repos, 1) + assert.Contains(t, status.Repos[0].Error, `pinned fullsend_ref "v0.54.0" does not support`) + assert.Empty(t, status.Repos[0].ConfigCompatibility) + }) + } +} + +func TestConverge_GitHubJiraPoll_WarnsAboutListVariableItCannotForward(t *testing.T) { + raw := jiraPollEnabledConfig + `authorization: + - provider: jira + write: + groups_from: MY_WRITE_GROUPS +` + t.Run("managed caller", func(t *testing.T) { + cr, _, warnings := runJiraConvergeWarnings(t, installedJiraRepo(forge.SecretJiraToken), raw, nil) + require.NoError(t, cr.Error, "the runner may still set the variable") + assert.Contains(t, warnings, "reads MY_WRITE_GROUPS") + }) + + t.Run("user-owned caller", func(t *testing.T) { + fc := installedJiraRepo(forge.SecretJiraToken) + fc.FileContents[jiraCallerKey] = []byte(userJiraCaller) + cr, _, warnings := runJiraConvergeWarnings(t, fc, raw, nil) + require.NoError(t, cr.Error) + assert.Empty(t, warnings, "a workflow that runs the poller itself can set any variable") + }) + + t.Run("user-owned caller of the reusable workflow", func(t *testing.T) { + const job = "jobs:\n poll:\n uses: fullsend-ai/fullsend/.github/workflows/reusable-poll-jira.yml@v1.0.0\n" + const mapping = " secrets:\n FULLSEND_JIRA_TOKEN: ${{ secrets.FULLSEND_JIRA_TOKEN }}\n" + const rename = "reads MY_WRITE_GROUPS, which reusable-poll-jira.yml does not pass to the poller; rename it" + const add = "reads FULLSEND_JIRA_WRITE_GROUPS, which " + scaffold.JiraPollCallerPath + " does not pass to reusable-poll-jira.yml; add it" + for _, tc := range []struct{ name, variable, secrets, want string }{ + {"other name, mapping", "MY_WRITE_GROUPS", mapping, rename}, + {"other name, inherit", "MY_WRITE_GROUPS", " secrets: inherit\n", rename}, + {"fixed name, mapping without it", "FULLSEND_JIRA_WRITE_GROUPS", mapping, add}, + {"fixed name, inherit", "FULLSEND_JIRA_WRITE_GROUPS", " secrets: inherit\n", ""}, + } { + t.Run(tc.name, func(t *testing.T) { + fc := installedJiraRepo(forge.SecretJiraToken) + fc.FileContents[jiraCallerKey] = []byte(userJiraCaller + job + tc.secrets) + _, _, warnings := runJiraConvergeWarnings(t, fc, strings.Replace(raw, "MY_WRITE_GROUPS", tc.variable, 1), nil) + if tc.want == "" { + assert.Empty(t, warnings) + return + } + assert.Contains(t, warnings, tc.want) + if tc.want == rename { + assert.NotContains(t, warnings, "add it", "the poll workflow rejects a secret it does not declare") + } + }) + } + }) +} diff --git a/internal/repos/jira_poll.go b/internal/repos/jira_poll.go index 714b07f852..8c1c0efdba 100644 --- a/internal/repos/jira_poll.go +++ b/internal/repos/jira_poll.go @@ -1,8 +1,10 @@ package repos import ( + "bytes" "context" "fmt" + "strings" "github.com/fullsend-ai/fullsend/internal/config" "github.com/fullsend-ai/fullsend/internal/forge" @@ -33,6 +35,15 @@ type jiraPollRequest struct { // workflows pinned to a ref that predates OAuth support. Only // meaningful for Ensure. OAuthConfigured bool + // AuthorizationEnv names the environment variables the effective jira + // authorization lists read with groups_from and accounts_from (#9132). + // The GitHub caller forwards those in scaffold.JiraAuthorizationSecrets + // to the poll job and cannot pass any other. Only meaningful for Ensure. + AuthorizationEnv []string + // Warn reports a problem that does not fail the run, such as a list + // variable the managed caller cannot pass. It is nil when nothing + // listens. + Warn func(detail string) // DryRun asks the reconciler to report the actions it would take // without any forge write. DryRun bool @@ -108,6 +119,9 @@ type jiraPollState struct { // clientSecretDefect names why an existing GitLab // FULLSEND_JIRA_CLIENT_SECRET cannot be reused; empty when it can. clientSecretDefect string + // authEnv names the environment variables the effective jira + // authorization lists read with groups_from and accounts_from, sorted. + authEnv []string } // jiraTokenSecrets and jiraOAuthSecrets are the two mutually exclusive Jira @@ -135,27 +149,119 @@ func jiraUsesOAuth(st jiraPollState, cfg ConvergeConfig) bool { return !st.tokenExists && (st.clientIDExists || st.clientSecretExists) } -// effectiveJiraTracking returns the repository's effective tracker.jira -// mapping, the managed configuration layered over the declared preset (the -// same layers committed as the .fullsend files), or nil when the selected -// tracker provider is not Jira. When polling is enabled the connection -// settings are validated, so an incomplete mapping fails before any write. -// URL, project and query never come from flags or the environment. -func effectiveJiraTracking(resolved ResolvedConfig, preset []byte) (*config.JiraTrackingConfig, error) { +// effectiveJiraPollState returns the Jira polling state that the effective +// configuration sets: the managed configuration layered over the declared +// preset (the same layers committed as the .fullsend files). It holds the +// tracker.jira mapping, or nil when the selected tracker provider is not +// Jira, whether polling is enabled, and the variables the jira authorization +// lists read. When polling is enabled the connection settings are validated, +// so an incomplete mapping fails before any write. URL, project and query +// never come from flags or the environment. The secret probes are filled in +// later by probeJiraPollSecrets. +func effectiveJiraPollState(resolved ResolvedConfig, preset []byte) (jiraPollState, error) { layered, err := config.LayerOnBase(resolved.Managed, preset) if err != nil { - return nil, fmt.Errorf("%s/%s: reading the effective configuration: %w", resolved.Owner, resolved.Repo, err) + return jiraPollState{}, fmt.Errorf("%s/%s: reading the effective configuration: %w", resolved.Owner, resolved.Repo, err) } + // Collected for any tracker: every job loads the config, not only the poller. + authEnv := layered.JiraAuthorization().JiraEnvNames() tracking := layered.IssueTracking() if tracking.Provider() != config.TrackingProviderJira { - return nil, nil + return jiraPollState{authEnv: authEnv}, nil } if tracking.Jira.PollEnabled() { if err := tracking.Jira.ValidateConnection(); err != nil { - return nil, fmt.Errorf("%s/%s: tracker.jira.poll.enabled is true: %w", resolved.Owner, resolved.Repo, err) + return jiraPollState{}, fmt.Errorf("%s/%s: tracker.jira.poll.enabled is true: %w", resolved.Owner, resolved.Repo, err) } } - return tracking.Jira, nil + return jiraPollState{ + jira: tracking.Jira, + enabled: tracking.Jira.PollEnabled(), + authEnv: authEnv, + }, nil +} + +// jiraAuthorizationEnvMarker appears in reusable-poll-jira.yml at every ref +// whose CLI supports groups_from and accounts_from: both landed together +// (#9132). +const jiraAuthorizationEnvMarker = "FULLSEND_JIRA_WRITE_GROUPS" + +// checkJiraAuthorizationEnvSupport fails before any write when the config +// reads a jira authorization list with groups_from or accounts_from and the +// repository's jobs run a release that predates them. Every job runs the CLI +// at the scaffold's ref, and an older CLI rejects the keys, so no job could +// load the config. The ref checked is the pinned fullsend_ref, or the ref the +// installed scaffold is stamped with when install will not refresh it (see +// establishedScaffoldRef). Any other repository runs the current release. +func checkJiraAuthorizationEnvSupport(ctx context.Context, d convergeDiscovery, cfg ConvergeConfig, refResolver *RefResolver) error { + if len(d.jira.authEnv) == 0 { + return nil + } + resolved := d.resolved + // A vendored install runs its own binary and workflows. Only the managed + // GitHub poll caller still calls upstream at that ref, and the workflow + // there must declare each list secret the caller passes. A poll caller + // the user maintains does not call upstream at that ref. + if resolved.Vendor { + forwarded, _ := splitJiraAuthorizationEnv(d.jira.authEnv) + if resolved.Forge != ForgeGitHub || !d.jira.enabled || len(forwarded) == 0 { + return nil + } + caller, exists, err := readJiraPollCaller(ctx, jiraPollRequest{Client: resolved.ForgeConfig.Client, Owner: resolved.Owner, Repo: resolved.Repo}) + if err != nil { + return fmt.Errorf("%s/%s: checking %s for groups_from/accounts_from support: %w", + resolved.Owner, resolved.Repo, scaffold.JiraPollCallerPath, err) + } + if exists && !scaffold.IsManagedJiraPollCaller(caller) { + return nil + } + } + if err := checkUserJiraCallerAuthorizationEnv(ctx, d, refResolver); err != nil { + return err + } + ref, source := resolveTargetRef(ctx, resolved.FullsendRef, cfg.UpstreamRef, cfg.UpstreamTag, refResolver).manifestRef, "pinned fullsend_ref" + if ref == "" { + // A stamped scaffold's ref cannot be read without an upstream GitHub + // client, so it is not checked, as in checkGitLabJiraOAuthSupport. + if refResolver == nil { + return nil + } + ref, source = establishedScaffoldRef(resolved, cfg, d.components), "the installed scaffold's ref" + } + if ref == "" { + return nil + } + names := strings.Join(d.jira.authEnv, ", ") + if refResolver == nil { + return fmt.Errorf("%s/%s: config.yaml reads %s with groups_from/accounts_from, and %s %q cannot be checked for support without an upstream GitHub client", + resolved.Owner, resolved.Repo, names, source, ref) + } + content, err := refResolver.client.GetFileContentAtRef(ctx, shimOwner, shimRepo, reusableJiraPollWorkflowPath, ref) + if err != nil && !forge.IsNotFound(err) { + return fmt.Errorf("%s/%s: checking %s %q for groups_from/accounts_from support: %w", + resolved.Owner, resolved.Repo, source, ref, err) + } + if err != nil || !bytes.Contains(content, []byte(jiraAuthorizationEnvMarker)) { + return fmt.Errorf("%s/%s: config.yaml reads %s with groups_from/accounts_from, which %s %q does not support; set fullsend_ref to a release that includes them", + resolved.Owner, resolved.Repo, names, source, ref) + } + return nil +} + +// establishedScaffoldRef returns the ref an installed scaffold is stamped +// with when this run will not move it: the manifest sets no fullsend_ref and +// the build has no release ref. It returns "" for a missing or unstamped +// scaffold, which convergence renders from the embedded templates. +func establishedScaffoldRef(resolved ResolvedConfig, cfg ConvergeConfig, components []ComponentStatus) string { + if resolved.FullsendRef != "" || cfg.UpstreamRef != "" { + return "" + } + for _, c := range components { + if c.Name == "workflow" && c.Present && !isUnstampedInstallRef(resolved.Forge, c.Actual) { + return c.Actual + } + } + return "" } // probeJiraPollSecrets reads whether the Jira credential secrets exist. It @@ -424,6 +530,8 @@ func convergeJiraPoll(ctx context.Context, d convergeDiscovery, cfg ConvergeConf _, emailSupplied := values[forge.SecretJiraEmail] req.EmailConfigured = !useOAuth && (d.jira.emailExists || emailSupplied) req.OAuthConfigured = useOAuth + req.AuthorizationEnv = d.jira.authEnv + req.Warn = func(detail string) { progress(repoFullName, "warning", detail) } ensured, err := reconciler.Ensure(ctx, req) actions = append(actions, ensured...) if err != nil { diff --git a/internal/repos/jira_poll_test.go b/internal/repos/jira_poll_test.go index eab8d1b526..9b201ee952 100644 --- a/internal/repos/jira_poll_test.go +++ b/internal/repos/jira_poll_test.go @@ -4,6 +4,7 @@ import ( "context" "errors" "fmt" + "os" "strings" "sync" "testing" @@ -11,7 +12,9 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "github.com/fullsend-ai/fullsend/internal/config" "github.com/fullsend-ai/fullsend/internal/forge" + "github.com/fullsend-ai/fullsend/internal/scaffold" ) const ( @@ -496,7 +499,7 @@ func TestProbeJiraPollSecrets(t *testing.T) { } } -func TestEffectiveJiraTracking(t *testing.T) { +func TestEffectiveJiraPollState(t *testing.T) { resolve := func(t *testing.T, raw string) ResolvedConfig { t.Helper() m := jiraManifest(t, raw) @@ -506,37 +509,37 @@ func TestEffectiveJiraTracking(t *testing.T) { } t.Run("managed config enables polling", func(t *testing.T) { - jira, err := effectiveJiraTracking(resolve(t, jiraPollEnabledConfig), nil) + st, err := effectiveJiraPollState(resolve(t, jiraPollEnabledConfig), nil) require.NoError(t, err) - assert.True(t, jira.PollEnabled()) + assert.True(t, st.enabled) }) t.Run("preset enables polling", func(t *testing.T) { - jira, err := effectiveJiraTracking(resolve(t, ""), []byte(jiraPollEnabledConfig)) + st, err := effectiveJiraPollState(resolve(t, ""), []byte(jiraPollEnabledConfig)) require.NoError(t, err) - assert.True(t, jira.PollEnabled()) + assert.True(t, st.enabled) }) t.Run("managed config overrides preset", func(t *testing.T) { - jira, err := effectiveJiraTracking(resolve(t, jiraPollDisabledConfig), []byte(jiraPollEnabledConfig)) + st, err := effectiveJiraPollState(resolve(t, jiraPollDisabledConfig), []byte(jiraPollEnabledConfig)) require.NoError(t, err) - assert.False(t, jira.PollEnabled()) + assert.False(t, st.enabled) }) t.Run("other provider", func(t *testing.T) { - jira, err := effectiveJiraTracking(resolve(t, "tracker:\n github: {}\n"), nil) + st, err := effectiveJiraPollState(resolve(t, "tracker:\n github: {}\n"), nil) require.NoError(t, err) - assert.Nil(t, jira) + assert.Nil(t, st.jira) }) t.Run("enabled with incomplete connection", func(t *testing.T) { - _, err := effectiveJiraTracking(resolve(t, ""), []byte("tracker:\n jira:\n poll:\n enabled: true\n")) + _, err := effectiveJiraPollState(resolve(t, ""), []byte("tracker:\n jira:\n poll:\n enabled: true\n")) require.Error(t, err) assert.True(t, strings.Contains(err.Error(), "tracker.jira.poll.enabled is true"), err.Error()) }) t.Run("invalid preset", func(t *testing.T) { - _, err := effectiveJiraTracking(resolve(t, ""), []byte("tracker: [\n")) + _, err := effectiveJiraPollState(resolve(t, ""), []byte("tracker: [\n")) require.Error(t, err) assert.Contains(t, err.Error(), "reading the effective configuration") }) @@ -792,3 +795,118 @@ func TestConverge_JiraPoll_GitHubAcceptsOAuth(t *testing.T) { forge.SecretJiraClientSecret: testJiraClientSecret, }, jiraSecretWrites(fc)) } + +func TestCheckJiraAuthorizationEnvSupport(t *testing.T) { + const pin = "v0.54.0" + const upstreamPoll = shimOwner + "/" + shimRepo + "/" + reusableJiraPollWorkflowPath + serve := func(content string) func(*forge.FakeClient) { + return func(fc *forge.FakeClient) { + fc.FileContentsRef[shimOwner+"/"+shimRepo+"/"+reusableJiraPollWorkflowPath+"@"+pin] = []byte(content) + } + } + tests := []struct { + name string + setup func(*forge.FakeClient) + authEnv []string + ref string + installed string // ref the installed scaffold is stamped with + enabled bool + vendored bool // a vendored GitHub install + managed bool // the managed GitHub poll caller is already committed + uses string // poll workflow a user-owned GitHub caller calls + wantErr string + }{ + {name: "config reads no list from the environment", authEnv: nil, ref: pin, enabled: true}, + {name: "unpinned repository runs the current release", authEnv: []string{"WRITE_GROUPS"}, enabled: true}, + {name: "pin that supports the keys", setup: serve(jiraAuthListsWorkflowFixture), authEnv: []string{"WRITE_GROUPS"}, ref: pin, enabled: true}, + // Agent runs load the config too, so the check does not depend on polling. + {name: "pin that predates the keys, polling disabled", setup: serve(jiraOAuthWorkflowFixture), authEnv: []string{"MY_GROUPS"}, ref: pin, + wantErr: `config.yaml reads MY_GROUPS with groups_from/accounts_from, which pinned fullsend_ref "v0.54.0" does not support`}, + {name: "pin without the Jira poll workflow", authEnv: []string{"WRITE_GROUPS"}, ref: pin, enabled: true, wantErr: "does not support"}, + {name: "fetch error fails closed", setup: func(fc *forge.FakeClient) { fc.Errors["GetFileContentAtRef"] = errors.New("upstream unavailable") }, + authEnv: []string{"WRITE_GROUPS"}, ref: pin, enabled: true, wantErr: "upstream unavailable"}, + // With no fullsend_ref and no release ref, install leaves a stamped scaffold where it is. + {name: "installed scaffold that predates the keys", setup: serve(jiraOAuthWorkflowFixture), authEnv: []string{"WRITE_GROUPS"}, installed: pin, enabled: true, + wantErr: `which the installed scaffold's ref "v0.54.0" does not support`}, + {name: "installed scaffold that supports the keys", setup: serve(jiraAuthListsWorkflowFixture), authEnv: []string{"WRITE_GROUPS"}, installed: pin, enabled: true}, + // A vendored install runs its own binary, but its managed poll caller calls upstream at the pin. + {name: "vendored, polling disabled", setup: serve(jiraOAuthWorkflowFixture), authEnv: []string{"FULLSEND_JIRA_WRITE_GROUPS"}, ref: pin, vendored: true}, + {name: "vendored, caller passes no list secret", setup: serve(jiraOAuthWorkflowFixture), authEnv: []string{"MY_GROUPS"}, ref: pin, enabled: true, vendored: true}, + {name: "vendored, caller passes a list secret", setup: serve(jiraOAuthWorkflowFixture), authEnv: []string{"FULLSEND_JIRA_WRITE_GROUPS"}, ref: pin, enabled: true, vendored: true, + wantErr: "does not support"}, + {name: "vendored, committed managed caller passes a list secret", setup: serve(jiraOAuthWorkflowFixture), authEnv: []string{"FULLSEND_JIRA_WRITE_GROUPS"}, ref: pin, enabled: true, vendored: true, managed: true, + wantErr: "does not support"}, + // The reusable poll workflow installs the CLI at the ref the caller pins, not at fullsend_ref. + {name: "user-owned caller pins a poll workflow that predates the keys", setup: serve(jiraOAuthWorkflowFixture), authEnv: []string{"WRITE_GROUPS"}, enabled: true, uses: upstreamPoll + "@" + pin, + wantErr: `which "fullsend-ai/fullsend/.github/workflows/reusable-poll-jira.yml@v0.54.0", called by .github/workflows/fullsend-poll-jira.yml, does not support`}, + {name: "user-owned caller pins a poll workflow that supports the keys", setup: serve(jiraAuthListsWorkflowFixture), authEnv: []string{"WRITE_GROUPS"}, enabled: true, uses: upstreamPoll + "@" + pin}, + {name: "user-owned caller calls its own copy that predates the keys", setup: func(fc *forge.FakeClient) { + fc.FileContents["group/project/"+reusableJiraPollWorkflowPath] = []byte(jiraOAuthWorkflowFixture) + }, authEnv: []string{"WRITE_GROUPS"}, enabled: true, uses: "./" + reusableJiraPollWorkflowPath, wantErr: "does not support"}, + {name: "user-owned caller whose reference has no ref is not checked", authEnv: []string{"WRITE_GROUPS"}, enabled: true, uses: upstreamPoll}, + // The old workflow then runs the vendored binary, which supports the keys. + {name: "vendored, user-owned caller pins a poll workflow that predates the keys", setup: serve(jiraOAuthWorkflowFixture), authEnv: []string{"FULLSEND_JIRA_WRITE_GROUPS"}, enabled: true, vendored: true, uses: upstreamPoll + "@" + pin}, + {name: "vendored, caller read error fails closed", setup: func(fc *forge.FakeClient) { + fc.GetFileContentErrors = map[string]error{"group/project/" + scaffold.JiraPollCallerPath: errors.New("api down")} + }, authEnv: []string{"FULLSEND_JIRA_WRITE_GROUPS"}, ref: pin, enabled: true, vendored: true, wantErr: "api down"}, + {name: "vendored, user-owned caller, fullsend_ref predates the keys", setup: serve(jiraOAuthWorkflowFixture), authEnv: []string{"FULLSEND_JIRA_WRITE_GROUPS"}, ref: pin, enabled: true, vendored: true, uses: upstreamPoll + "@" + pin}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + fc := forge.NewFakeClient() + if tt.setup != nil { + tt.setup(fc) + } + d := gitlabJiraDiscovery(fc, jiraPollState{authEnv: tt.authEnv}) + d.jira.enabled = tt.enabled + d.resolved.FullsendRef = tt.ref + if tt.vendored { + d.resolved.Vendor, d.resolved.Forge = true, ForgeGitHub + } + if tt.managed { + fc.FileContents["group/project/"+scaffold.JiraPollCallerPath] = []byte(scaffold.JiraPollCallerMarker + "\n") + } + if tt.uses != "" { + d.resolved.Forge = ForgeGitHub + fc.FileContents["group/project/"+scaffold.JiraPollCallerPath] = []byte("jobs:\n poll:\n uses: " + tt.uses + "\n secrets: inherit\n") + } + if tt.installed != "" { + d.components = []ComponentStatus{{Name: "workflow", Present: true, Actual: tt.installed}} + } + err := checkJiraAuthorizationEnvSupport(context.Background(), d, ConvergeConfig{}, NewRefResolver(fc)) + if tt.wantErr == "" { + require.NoError(t, err) + return + } + require.ErrorContains(t, err, tt.wantErr) + }) + } + + // The check finds supporting refs by this marker, so the workflow must keep it. + t.Run("the current workflow carries the marker", func(t *testing.T) { + content, err := os.ReadFile("../../" + reusableJiraPollWorkflowPath) + require.NoError(t, err) + assert.Contains(t, string(content), jiraAuthorizationEnvMarker) + }) + + t.Run("pin without an upstream client", func(t *testing.T) { + d := gitlabJiraDiscovery(forge.NewFakeClient(), jiraPollState{authEnv: []string{"WRITE_GROUPS"}}) + d.resolved.FullsendRef = pin + require.ErrorContains(t, checkJiraAuthorizationEnvSupport(context.Background(), d, ConvergeConfig{}, nil), "cannot be checked") + }) + + t.Run("stamped scaffold without an upstream client", func(t *testing.T) { + d := gitlabJiraDiscovery(forge.NewFakeClient(), jiraPollState{authEnv: []string{"WRITE_GROUPS"}}) + d.components = []ComponentStatus{{Name: "workflow", Present: true, Actual: pin}} + require.NoError(t, checkJiraAuthorizationEnvSupport(context.Background(), d, ConvergeConfig{}, nil)) + }) +} + +func TestEffectiveJiraPollState_CollectsListVariablesForAnyTracker(t *testing.T) { + managed, err := config.ParsePerRepoConfigWriter([]byte("authorization:\n - provider: jira\n write:\n groups_from: WRITE_GROUPS\n")) + require.NoError(t, err) + st, err := effectiveJiraPollState(ResolvedConfig{Owner: "acme", Repo: "api", Managed: managed}, nil) + require.NoError(t, err) + assert.Nil(t, st.jira) + assert.Equal(t, []string{"WRITE_GROUPS"}, st.authEnv) +} diff --git a/internal/repos/status.go b/internal/repos/status.go index db49fb5090..225833b0a1 100644 --- a/internal/repos/status.go +++ b/internal/repos/status.go @@ -386,6 +386,20 @@ func checkRepoStatus(ctx context.Context, cfg ResolvedConfig, dcfg DriftConfig, status.Error = fmt.Sprintf("probing components for %s/%s: %v", owner, repo, probeErr) return status } + // jiraAuthorizationEnvError is the configuration error install would fail + // on: the release the repository's jobs run cannot load a config that uses + // groups_from or accounts_from. + jiraAuthorizationEnvError := func() error { + if !presetLoaded { + return nil + } + jira, err := effectiveJiraPollState(cfg, cfg.ProposedBase) + if err != nil { + return nil + } + d := convergeDiscovery{resolved: cfg, components: components, jira: jira} + return checkJiraAuthorizationEnvSupport(ctx, d, ConvergeConfig{UpstreamRef: dcfg.UpstreamRef, UpstreamTag: dcfg.UpstreamTag}, resolver) + } if !anyComponentPresent(components) { // Leftover credentials of an unselected method are drift even // when none of the selected method's components exist. @@ -403,6 +417,12 @@ func checkRepoStatus(ctx context.Context, cfg ResolvedConfig, dcfg DriftConfig, if status.Error != "" { return status } + // Before the drift check, which would report the config as + // compatible with the pinned ref's schema. + if err := jiraAuthorizationEnvError(); err != nil { + status.Error = err.Error() + return status + } checkManagedConfigDrift(ctx, cfg, &status) if status.Error != "" { return status @@ -447,6 +467,11 @@ func checkRepoStatus(ctx context.Context, cfg ResolvedConfig, dcfg DriftConfig, }) } + if err := jiraAuthorizationEnvError(); err != nil { + status.Error = err.Error() + return status + } + // Report the configuration error install would fail on: nothing will // refresh a live agent job script that ignores the service account. if workflowPresent && presetLoaded { diff --git a/internal/repos/workflow_test_helper_test.go b/internal/repos/workflow_test_helper_test.go index b38a55084c..afdda9bed5 100644 --- a/internal/repos/workflow_test_helper_test.go +++ b/internal/repos/workflow_test_helper_test.go @@ -11,6 +11,8 @@ import ( // jiraOAuthWorkflowFixture stands in for a reusable workflow that declares // the Jira OAuth client credential secrets. jiraPreOAuthWorkflowFixture is // a pre-OAuth workflow that exists but lacks those declarations. +// jiraAuthListsWorkflowFixture also declares the jira authorization list +// secrets, like the current release. const ( jiraOAuthWorkflowFixture = `name: Jira poll on: @@ -29,6 +31,15 @@ on: secrets: FULLSEND_JIRA_TOKEN: required: false +` + jiraAuthListsWorkflowFixture = jiraOAuthWorkflowFixture + ` FULLSEND_JIRA_WRITE_GROUPS: + required: false + FULLSEND_JIRA_WRITE_ACCOUNTS: + required: false + FULLSEND_JIRA_TRIAGE_GROUPS: + required: false + FULLSEND_JIRA_TRIAGE_ACCOUNTS: + required: false ` ) @@ -68,7 +79,7 @@ func newFakeClientForBatch(repos ...string) *forge.FakeClient { } // v1.0.0 is the current-release fixture for tests that enable GitHub // Jira polling. Older pins intentionally lack this file in the fixture. - fc.FileContentsRef[shimOwner+"/"+shimRepo+"/"+reusableJiraPollWorkflowPath+"@v1.0.0"] = []byte(jiraOAuthWorkflowFixture) + fc.FileContentsRef[shimOwner+"/"+shimRepo+"/"+reusableJiraPollWorkflowPath+"@v1.0.0"] = []byte(jiraAuthListsWorkflowFixture) // A GitHub OpenAI install that cannot fetch its explicit pin's scaffold // fails closed, so the default test pin serves the embedded per-repo // shim and thin callers, which forward the key and match what the diff --git a/internal/scaffold/fullsend-repo/templates/jira-poll-per-repo.yaml b/internal/scaffold/fullsend-repo/templates/jira-poll-per-repo.yaml index 3a7e6f07a4..dc1cddeb76 100644 --- a/internal/scaffold/fullsend-repo/templates/jira-poll-per-repo.yaml +++ b/internal/scaffold/fullsend-repo/templates/jira-poll-per-repo.yaml @@ -13,7 +13,9 @@ # # Security: Jira credentials reach the poll job and are passed to the agent # workflow only for Jira-originated status writes. They are never put in the -# runner-secret bundle. +# runner-secret bundle. The jira authorization list secrets, rendered only when +# config.yaml reads them with groups_from or accounts_from, reach the poll job +# alone. # # Concurrency: overlapping poll cycles queue rather than cancel each other. name: fullsend Jira poll @@ -41,6 +43,10 @@ jobs: FULLSEND_JIRA_EMAIL: ${{ secrets.FULLSEND_JIRA_EMAIL }} FULLSEND_JIRA_CLIENT_ID: ${{ secrets.FULLSEND_JIRA_CLIENT_ID }} FULLSEND_JIRA_CLIENT_SECRET: ${{ secrets.FULLSEND_JIRA_CLIENT_SECRET }} + FULLSEND_JIRA_WRITE_GROUPS: ${{ secrets.FULLSEND_JIRA_WRITE_GROUPS }} + FULLSEND_JIRA_WRITE_ACCOUNTS: ${{ secrets.FULLSEND_JIRA_WRITE_ACCOUNTS }} + FULLSEND_JIRA_TRIAGE_GROUPS: ${{ secrets.FULLSEND_JIRA_TRIAGE_GROUPS }} + FULLSEND_JIRA_TRIAGE_ACCOUNTS: ${{ secrets.FULLSEND_JIRA_TRIAGE_ACCOUNTS }} dispatch: needs: poll diff --git a/internal/scaffold/github_kill_switch_test.go b/internal/scaffold/github_kill_switch_test.go index 46c8e98c31..8473e62512 100644 --- a/internal/scaffold/github_kill_switch_test.go +++ b/internal/scaffold/github_kill_switch_test.go @@ -35,15 +35,20 @@ type ghWorkflowFile struct { // Actions run. func extractReusableDispatchStepScript(t *testing.T, jobName, stepName string) string { t.Helper() - path := filepath.Join("..", "..", ".github", "workflows", "reusable-dispatch.yml") - content, err := os.ReadFile(path) + return extractWorkflowStepScript(t, "reusable-dispatch.yml", jobName, stepName) +} + +// extractWorkflowStepScript does the same for any file in .github/workflows. +func extractWorkflowStepScript(t *testing.T, file, jobName, stepName string) string { + t.Helper() + content, err := os.ReadFile(filepath.Join("..", "..", ".github", "workflows", file)) require.NoError(t, err) var wf ghWorkflowFile require.NoError(t, yaml.Unmarshal(content, &wf)) job, ok := wf.Jobs[jobName] - require.True(t, ok, "job %q not found in reusable-dispatch.yml", jobName) + require.True(t, ok, "job %q not found in %s", jobName, file) for _, step := range job.Steps { if step.Name == stepName { require.NotEmpty(t, step.Run, "step %q has no run script", stepName) diff --git a/internal/scaffold/jira_poll.go b/internal/scaffold/jira_poll.go index 408bbfae43..b4e97322df 100644 --- a/internal/scaffold/jira_poll.go +++ b/internal/scaffold/jira_poll.go @@ -2,6 +2,7 @@ package scaffold import ( "fmt" + "slices" "strings" "github.com/fullsend-ai/fullsend/internal/config" @@ -37,6 +38,22 @@ var jiraPollOAuthSecretLines = []string{ " FULLSEND_JIRA_CLIENT_SECRET: ${{ secrets.FULLSEND_JIRA_CLIENT_SECRET }}\n", } +// JiraAuthorizationSecrets are the secrets the managed GitHub Jira poll +// caller can forward to the poll job for the jira authorization provider's +// groups_from and accounts_from lists (#9132). The managed caller cannot pass +// any other variable to the poller. +var JiraAuthorizationSecrets = []string{ + "FULLSEND_JIRA_WRITE_GROUPS", + "FULLSEND_JIRA_WRITE_ACCOUNTS", + "FULLSEND_JIRA_TRIAGE_GROUPS", + "FULLSEND_JIRA_TRIAGE_ACCOUNTS", +} + +// jiraPollSecretLine is the caller line that forwards secret name. +func jiraPollSecretLine(name string) string { + return " " + name + ": ${{ secrets." + name + " }}\n" +} + // RenderJiraPollCaller renders the managed GitHub Jira poll caller. Its // reusable workflows are pinned to the upstream ref in opts; the caller // always references the upstream repository, so it does not depend on a @@ -45,8 +62,11 @@ var jiraPollOAuthSecretLines = []string{ // credentials to Jira-originated Fullsend status updates only. oauthConfigured // controls whether the OAuth client credentials are forwarded; a token-only // caller omits them so it stays valid against reusable workflows pinned to a -// ref that predates OAuth support. -func RenderJiraPollCaller(opts RenderOptions, emailConfigured, oauthConfigured bool) ([]byte, error) { +// ref that predates OAuth support. authorizationSecrets lists the +// JiraAuthorizationSecrets the poll job receives; the others are omitted for +// the same reason, so a caller whose config reads none of them is unchanged. +// Any other name is ignored: the caller cannot forward it. +func RenderJiraPollCaller(opts RenderOptions, emailConfigured, oauthConfigured bool, authorizationSecrets []string) ([]byte, error) { raw, err := FullsendRepoFile(jiraPollCallerTemplate) if err != nil { return nil, fmt.Errorf("loading Jira poll caller template: %w", err) @@ -66,6 +86,15 @@ func RenderJiraPollCaller(opts RenderOptions, emailConfigured, oauthConfigured b out = strings.ReplaceAll(out, line, "") } } + for _, name := range JiraAuthorizationSecrets { + line := jiraPollSecretLine(name) + if strings.Count(out, line) != 1 { + return nil, fmt.Errorf("the Jira poll caller template must forward %s to the poll job", name) + } + if !slices.Contains(authorizationSecrets, name) { + out = strings.Replace(out, line, "", 1) + } + } upstream := opts upstream.Vendored = false out = strings.ReplaceAll(out, "__REUSABLE_WORKFLOW__", upstreamReusableWorkflowUses("reusable-poll-jira.yml", upstream)) diff --git a/internal/scaffold/jira_poll_test.go b/internal/scaffold/jira_poll_test.go index d6f5d07225..74281264a6 100644 --- a/internal/scaffold/jira_poll_test.go +++ b/internal/scaffold/jira_poll_test.go @@ -1,7 +1,9 @@ package scaffold import ( + "encoding/json" "os" + "os/exec" "path/filepath" "strings" "testing" @@ -15,7 +17,7 @@ func TestRenderJiraPollCaller(t *testing.T) { pinned := RenderOptions{UpstreamRef: "0123456789abcdef0123456789abcdef01234567", UpstreamTag: "v1.2.3"} t.Run("with email", func(t *testing.T) { - out, err := RenderJiraPollCaller(pinned, true, true) + out, err := RenderJiraPollCaller(pinned, true, true, nil) require.NoError(t, err) s := string(out) @@ -53,7 +55,7 @@ func TestRenderJiraPollCaller(t *testing.T) { }) t.Run("without email", func(t *testing.T) { - out, err := RenderJiraPollCaller(pinned, false, true) + out, err := RenderJiraPollCaller(pinned, false, true, nil) require.NoError(t, err) assert.Contains(t, string(out), "FULLSEND_JIRA_TOKEN: ${{ secrets.FULLSEND_JIRA_TOKEN }}") var wf callerWorkflow @@ -68,7 +70,7 @@ func TestRenderJiraPollCaller(t *testing.T) { }) t.Run("token only omits the OAuth client credentials", func(t *testing.T) { - out, err := RenderJiraPollCaller(pinned, true, false) + out, err := RenderJiraPollCaller(pinned, true, false, nil) require.NoError(t, err) assert.NotContains(t, string(out), "FULLSEND_JIRA_CLIENT_ID") assert.NotContains(t, string(out), "FULLSEND_JIRA_CLIENT_SECRET") @@ -84,8 +86,24 @@ func TestRenderJiraPollCaller(t *testing.T) { assert.Contains(t, wf.Jobs["dispatch"].Secrets, "FULLSEND_JIRA_TOKEN") }) + t.Run("authorization list secrets", func(t *testing.T) { + out, err := RenderJiraPollCaller(pinned, true, false, []string{"FULLSEND_JIRA_WRITE_GROUPS", "FULLSEND_JIRA_TRIAGE_ACCOUNTS"}) + require.NoError(t, err) + var wf callerWorkflow + require.NoError(t, yaml.Unmarshal(out, &wf)) + assert.Equal(t, map[string]string{ + "FULLSEND_JIRA_TOKEN": "${{ secrets.FULLSEND_JIRA_TOKEN }}", + "FULLSEND_JIRA_EMAIL": "${{ secrets.FULLSEND_JIRA_EMAIL }}", + "FULLSEND_JIRA_WRITE_GROUPS": "${{ secrets.FULLSEND_JIRA_WRITE_GROUPS }}", + "FULLSEND_JIRA_TRIAGE_ACCOUNTS": "${{ secrets.FULLSEND_JIRA_TRIAGE_ACCOUNTS }}", + }, wf.Jobs["poll"].Secrets) + for _, name := range JiraAuthorizationSecrets { + assert.NotContains(t, wf.Jobs["dispatch"].Secrets, name, "agents never receive the lists") + } + }) + t.Run("default ref and vendored install", func(t *testing.T) { - out, err := RenderJiraPollCaller(RenderOptions{Vendored: true}, true, true) + out, err := RenderJiraPollCaller(RenderOptions{Vendored: true}, true, true, nil) require.NoError(t, err) s := string(out) assert.Contains(t, s, "uses: fullsend-ai/fullsend/.github/workflows/reusable-poll-jira.yml@main\n", @@ -96,9 +114,9 @@ func TestRenderJiraPollCaller(t *testing.T) { }) t.Run("idempotent", func(t *testing.T) { - a, err := RenderJiraPollCaller(pinned, true, true) + a, err := RenderJiraPollCaller(pinned, true, true, nil) require.NoError(t, err) - b, err := RenderJiraPollCaller(pinned, true, true) + b, err := RenderJiraPollCaller(pinned, true, true, nil) require.NoError(t, err) assert.Equal(t, a, b) }) @@ -108,7 +126,7 @@ func TestRenderJiraPollCaller(t *testing.T) { // against the workflow_call interface of reusable-dispatch.yml: it passes // every required input and secret, and nothing undeclared. func TestJiraPollCallerDispatchAlignment(t *testing.T) { - out, err := RenderJiraPollCaller(RenderOptions{}, true, true) + out, err := RenderJiraPollCaller(RenderOptions{}, true, true, JiraAuthorizationSecrets) require.NoError(t, err) var caller callerWorkflow require.NoError(t, yaml.Unmarshal(out, &caller)) @@ -140,7 +158,7 @@ func TestJiraPollCallerDispatchAlignment(t *testing.T) { // TestJiraPollCallerPollAlignment checks the poll caller against the shared // reusable Jira poll workflow's workflow_call contract and output. func TestJiraPollCallerPollAlignment(t *testing.T) { - out, err := RenderJiraPollCaller(RenderOptions{}, true, true) + out, err := RenderJiraPollCaller(RenderOptions{}, true, true, JiraAuthorizationSecrets) require.NoError(t, err) var caller callerWorkflow require.NoError(t, yaml.Unmarshal(out, &caller)) @@ -183,10 +201,88 @@ func TestJiraPollCallerPollAlignment(t *testing.T) { assert.Contains(t, reusable.On.WorkflowCall.Secrets, name, "secret %q is not declared by reusable-poll-jira.yml", name) } - assert.Equal(t, "${{ jobs.poll.outputs.matrix }}", reusable.On.WorkflowCall.Outputs["matrix"].Value) - assert.Equal(t, "${{ steps.matrix.outputs.matrix }}", reusable.Jobs["poll"].Outputs["matrix"]) + assert.Equal(t, `${{ jobs.matrix.outputs.matrix || '{"include":[]}' }}`, reusable.On.WorkflowCall.Outputs["matrix"].Value) + assert.Equal(t, "${{ steps.matrix.outputs.matrix }}", reusable.Jobs["matrix"].Outputs["matrix"]) assert.Equal(t, "${{ needs.poll.outputs.matrix }}", caller.Jobs["dispatch"].With["matrix"]) - assert.Equal(t, "${{ inputs.timeout_minutes }}", reusable.Jobs["poll"].TimeoutMinutes) + for _, job := range []string{"poll", "matrix"} { + assert.Equal(t, "${{ inputs.timeout_minutes }}", reusable.Jobs[job].TimeoutMinutes, job) + } + + // GitHub drops a job output that contains a value of a secret the job + // has, so the job that holds the secrets outputs only a count and a + // random artifact suffix, and the job that sets the matrix holds none. + assert.Equal(t, map[string]string{ + "dispatch_count": "${{ steps.check.outputs.count }}", + "artifact_suffix": "${{ steps.check.outputs.artifact_suffix }}", + }, reusable.Jobs["poll"].Outputs) + var raw struct { + Jobs map[string]yaml.Node `yaml:"jobs"` + } + require.NoError(t, yaml.Unmarshal(content, &raw)) + matrixNode := raw.Jobs["matrix"] + matrixJob, err := yaml.Marshal(&matrixNode) + require.NoError(t, err) + require.Contains(t, string(matrixJob), "download-artifact", "the matrix job was parsed") + assert.NotContains(t, string(matrixJob), "secrets.") +} + +// The check step must find a Jira credential that JSON escaped inside +// event_payload, an object as the poller writes it. +func TestJiraPollWorkflowCheckDispatches(t *testing.T) { + if _, err := exec.LookPath("jq"); err != nil { + t.Skip("jq not found in PATH") + } + script := extractWorkflowStepScript(t, "reusable-poll-jira.yml", "poll", "Check dispatches") + + // Only the secret under test is set. The others are empty, as the secrets + // of the unused credential type are, and an empty one must match nothing. + secrets := map[string]string{ + "FULLSEND_JIRA_TOKEN": `to"k<1`, + "FULLSEND_JIRA_EMAIL": "poller@example.invalid", + "FULLSEND_JIRA_CLIENT_ID": "client-id-1", + "FULLSEND_JIRA_CLIENT_SECRET": "client-secret-1", + } + tests := []struct { + name, comment string + want string // the secret the step must name, or "" to pass + }{ + {name: "no credential", comment: "/fs-triage"}, + {name: "token that JSON escapes", comment: "my token is " + secrets["FULLSEND_JIRA_TOKEN"], want: "FULLSEND_JIRA_TOKEN"}, + {name: "email", comment: "ask " + secrets["FULLSEND_JIRA_EMAIL"], want: "FULLSEND_JIRA_EMAIL"}, + {name: "client ID", comment: "id " + secrets["FULLSEND_JIRA_CLIENT_ID"], want: "FULLSEND_JIRA_CLIENT_ID"}, + {name: "client secret", comment: "secret " + secrets["FULLSEND_JIRA_CLIENT_SECRET"], want: "FULLSEND_JIRA_CLIENT_SECRET"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + payload := map[string]any{"comment": map[string]any{"body": tt.comment}} + dispatches, err := json.Marshal([]map[string]any{{"agent": "triage", "event_payload": payload}}) + require.NoError(t, err) + dir := t.TempDir() + require.NoError(t, os.WriteFile(filepath.Join(dir, "dispatches.json"), dispatches, 0o600)) + output := filepath.Join(dir, "output") + + cmd := exec.Command("bash", "-c", script) + cmd.Dir = dir + cmd.Env = append(os.Environ(), "GITHUB_OUTPUT="+output) + for name, value := range secrets { + if name != tt.want { + value = "" + } + cmd.Env = append(cmd.Env, name+"="+value) + } + out, err := cmd.CombinedOutput() + if tt.want != "" { + require.Error(t, err) + assert.Contains(t, string(out), "dispatches.json contains "+tt.want) + assert.NotContains(t, string(out), secrets[tt.want]) + return + } + require.NoError(t, err, string(out)) + got, err := os.ReadFile(output) + require.NoError(t, err) + assert.Contains(t, string(got), "count=1\n") + }) + } } func TestIsManagedJiraPollCaller(t *testing.T) { diff --git a/internal/scaffold/workflow_call_alignment_test.go b/internal/scaffold/workflow_call_alignment_test.go index 714f631741..8abc1ed04d 100644 --- a/internal/scaffold/workflow_call_alignment_test.go +++ b/internal/scaffold/workflow_call_alignment_test.go @@ -927,20 +927,34 @@ func TestJiraSecretsActionWiring(t *testing.T) { // TestJiraPollWorkflowSecretThreading validates the GitHub poller workflow // contract and its scaffold caller. OAuth credentials must reach the poll // step, while the caller also forwards them to reusable-dispatch for Jira -// run-status updates. +// run-status updates. The jira authorization list secrets (#9132) reach the +// poll step under their own names. func TestJiraPollWorkflowSecretThreading(t *testing.T) { content := string(loadRepoFile(".github/workflows/reusable-poll-jira.yml")(t)) var parsed reusableWorkflow require.NoError(t, yaml.Unmarshal([]byte(content), &parsed)) - for _, name := range []string{"FULLSEND_JIRA_TOKEN", "FULLSEND_JIRA_EMAIL", "FULLSEND_JIRA_CLIENT_ID", "FULLSEND_JIRA_CLIENT_SECRET"} { + credentials := []string{"FULLSEND_JIRA_TOKEN", "FULLSEND_JIRA_EMAIL", "FULLSEND_JIRA_CLIENT_ID", "FULLSEND_JIRA_CLIENT_SECRET"} + names := append(append([]string{}, credentials...), JiraAuthorizationSecrets...) + // Scoped to the step: the check step also reads the credentials. + pollStep := extractStepSection(t, content, "Poll Jira") + for _, name := range names { secret, ok := parsed.On.WorkflowCall.Secrets[name] require.True(t, ok, "reusable-poll-jira.yml must declare %s", name) - assert.False(t, secret.Required, "%s must be optional so either credential type can be used", name) - assert.Contains(t, content, name+": ${{ secrets."+name+" }}", "poll step must receive %s", name) + assert.False(t, secret.Required, "%s must be optional: either credential type can be used, and the lists are opt-in", name) + assert.Contains(t, pollStep, name+": ${{ secrets."+name+" }}", "poll step must receive %s", name) + } + // The check step looks for every credential in the dispatches. It must + // not get a list secret: a list holds the ID of the account that acted. + checkStep := extractStepSection(t, content, "Check dispatches") + for _, name := range credentials { + assert.Contains(t, checkStep, name+": ${{ secrets."+name+" }}", "check step must receive %s", name) + } + for _, name := range JiraAuthorizationSecrets { + assert.NotContains(t, checkStep, name, "check step must not look for %s", name) } caller := string(loadScaffoldFile("templates/jira-poll-per-repo.yaml")(t)) - for _, name := range []string{"FULLSEND_JIRA_TOKEN", "FULLSEND_JIRA_EMAIL", "FULLSEND_JIRA_CLIENT_ID", "FULLSEND_JIRA_CLIENT_SECRET"} { + for _, name := range names { assert.Contains(t, caller, name+": ${{ secrets."+name+" }}", "managed poll caller must forward %s", name) } }