diff --git a/.github/workflows/reusable-dispatch.yml b/.github/workflows/reusable-dispatch.yml index d8415c8caa..44b177b20e 100644 --- a/.github/workflows/reusable-dispatch.yml +++ b/.github/workflows/reusable-dispatch.yml @@ -119,9 +119,16 @@ jobs: issues: read pull-requests: read outputs: - stage: ${{ steps.role-check.outputs.skipped != 'true' && steps.agent-check.outputs.skipped != 'true' && steps.route.outputs.stage || '' }} + stage: ${{ steps.kill-switch.outputs.skipped != 'true' && steps.role-check.outputs.skipped != 'true' && steps.agent-check.outputs.skipped != 'true' && steps.route.outputs.stage || '' }} trigger_source: ${{ steps.route.outputs.trigger_source }} event_payload: ${{ steps.payload.outputs.event_payload }} + authorization_denied: ${{ steps.authorization.outputs.authorization_denied || 'false' }} + authorization_actor: ${{ steps.authorization.outputs.authorization_actor || '' }} + authorization_actor_id: ${{ steps.authorization.outputs.authorization_actor_id || '' }} + authorization_number: ${{ steps.authorization.outputs.authorization_number || '' }} + dispatch_blocked_reason: ${{ steps.authorization.outputs.dispatch_blocked_reason || '' }} + legacy_command_applicable: ${{ steps.route.outputs.command_applicable || 'false' }} + authorization_check_failed: ${{ steps.route.outputs.authorization_check_failed || 'false' }} steps: - name: Validate event_action if: ${{ inputs.event_action == '' }} @@ -155,6 +162,8 @@ jobs: COMMENT_BODY: ${{ github.event.comment.body }} COMMENT_USER_TYPE: ${{ github.event.comment.user.type }} COMMENT_USER_LOGIN: ${{ github.event.comment.user.login }} + COMMENT_USER_ID: ${{ github.event.comment.user.id }} + ISSUE_NUMBER: ${{ github.event.issue.number }} ISSUE_LABELS: ${{ join(github.event.issue.labels.*.name, ',') }} PR_LABELS: ${{ join(github.event.pull_request.labels.*.name, ',') }} @@ -174,7 +183,10 @@ jobs: set -euo pipefail STAGE="" + REQUESTED_STAGE="" TRIGGER_SOURCE="" + AUTH_CHECK_FAILED=false + AUTHORIZATION_DENIED=false # Report whether the lowercased user is in an OWNERS list. An entry # that names an OWNERS_ALIASES key matches only that alias's members, @@ -246,6 +258,7 @@ jobs: api_err=$(mktemp) || { echo "::warning::Failed to create temp file for permission check of ${username}" >&2 + AUTH_CHECK_FAILED=true return 1 } role=$(gh api "repos/${GITHUB_REPOSITORY}/collaborators/${username}/permission" \ @@ -263,6 +276,7 @@ jobs: else "none" end else "none" end' 2>"${api_err}") || { echo "::warning::Permission API call failed for ${username}: $(cat "${api_err}")" >&2 + AUTH_CHECK_FAILED=true rm -f "${api_err}" return 1 } @@ -281,6 +295,23 @@ jobs: has_repo_permission "${COMMENT_USER_LOGIN}" "${1:-write}" } + # Record an explicit denial at the point where the slash-command + # authorization check fails. Downstream steps must not infer this + # from an empty stage, because an empty stage also represents a + # kill-switch pause and other intentional skips. + set_command_stage() { + local stage="${1}" min="${2:-write}" + REQUESTED_STAGE="${stage}" + if [[ "${COMMENT_USER_TYPE}" == "Bot" ]]; then + return 0 + fi + if is_authorized "${min}"; then + STAGE="${stage}" + elif [[ "${AUTH_CHECK_FAILED}" != "true" ]]; then + AUTHORIZATION_DENIED=true + fi + } + # Event-actor auth; $1=user, optional $2 = write|triage (default write). is_event_actor_authorized() { has_repo_permission "${1:-}" "${2:-write}" @@ -301,45 +332,43 @@ jobs: COMMAND="$(printf '%s\n' "${COMMENT_BODY}" | head -1 | tr -d '\r' | awk '{print $1}' | sed 's/[.,;:!?]*$//')" fi + COMMAND_APPLICABLE=false + case "${EVENT_NAME}" in issue_comment) case "${COMMAND}" in /fs-triage) - if [[ "${COMMENT_USER_TYPE}" != "Bot" ]] && is_authorized triage; then - STAGE="triage" - fi + COMMAND_APPLICABLE=true + set_command_stage triage triage ;; /fs-code) if [[ "${ISSUE_IS_PR}" == "false" ]]; then - if [[ "${COMMENT_USER_TYPE}" != "Bot" ]] && is_authorized; then - STAGE="code" - fi + COMMAND_APPLICABLE=true + set_command_stage code fi ;; /fs-review) if [[ "${ISSUE_IS_PR}" == "true" ]]; then - if [[ "${COMMENT_USER_TYPE}" != "Bot" ]] && is_authorized triage; then - STAGE="review" - fi + COMMAND_APPLICABLE=true + set_command_stage review triage fi ;; /fs-fix) if [[ "${ISSUE_IS_PR}" == "true" ]]; then - if [[ "${COMMENT_USER_TYPE}" != "Bot" ]] && is_authorized; then - STAGE="fix" + COMMAND_APPLICABLE=true + set_command_stage fix + if [[ "${STAGE}" == "fix" ]]; then TRIGGER_SOURCE="${COMMENT_USER_LOGIN}" fi fi ;; /fs-retro) - if [[ "${COMMENT_USER_TYPE}" != "Bot" ]] && is_authorized; then - STAGE="retro" - fi + COMMAND_APPLICABLE=true + set_command_stage retro ;; /fs-prioritize) - if [[ "${COMMENT_USER_TYPE}" != "Bot" ]] && is_authorized; then - STAGE="prioritize" - fi + COMMAND_APPLICABLE=true + set_command_stage prioritize ;; *) ;; @@ -421,15 +450,34 @@ jobs: ;; esac + # Automatic webhook routes set STAGE directly. Mirror it into the + # requested-stage guard so kill-switch, role, and agent checks apply + # to those routes as well as explicit slash commands. + if [[ -z "${REQUESTED_STAGE}" && -n "${STAGE}" ]]; then + REQUESTED_STAGE="${STAGE}" + fi + if [[ -z "${STAGE}" ]]; then echo "No stage matched — skipping dispatch" - echo "stage=" >> "${GITHUB_OUTPUT}" + { + echo "stage=" + echo "requested_stage=${REQUESTED_STAGE}" + echo "command_applicable=${COMMAND_APPLICABLE}" + echo "authorization_check_failed=${AUTH_CHECK_FAILED}" + echo "authorization_denied=${AUTHORIZATION_DENIED}" + } >> "${GITHUB_OUTPUT}" exit 0 fi echo "Routed to stage: ${STAGE}" - echo "stage=${STAGE}" >> "${GITHUB_OUTPUT}" - echo "trigger_source=${TRIGGER_SOURCE}" >> "${GITHUB_OUTPUT}" + { + echo "stage=${STAGE}" + echo "requested_stage=${REQUESTED_STAGE}" + echo "trigger_source=${TRIGGER_SOURCE}" + echo "command_applicable=${COMMAND_APPLICABLE}" + echo "authorization_check_failed=${AUTH_CHECK_FAILED}" + echo "authorization_denied=${AUTHORIZATION_DENIED}" + } >> "${GITHUB_OUTPUT}" - name: Validate routed stage if: steps.route.outputs.stage != '' @@ -452,7 +500,10 @@ jobs: fi - name: Check kill switch - if: steps.route.outputs.stage != '' + id: kill-switch + if: steps.route.outputs.requested_stage != '' + env: + REQUESTED_STAGE: ${{ steps.route.outputs.requested_stage }} run: | set -euo pipefail # Mirrors internal/config's IsKillSwitchActive(): if @@ -490,13 +541,17 @@ jobs: KILL_SWITCH="${KILL_SWITCH#\"}" KILL_SWITCH="${KILL_SWITCH%\"}" if [[ "$KILL_SWITCH" == "true" || "$KILL_SWITCH" == "yes" ]]; then - echo "::error::Kill switch is active — all agent dispatch halted" - echo "::error::Set kill_switch: false in .fullsend/config.yaml or .fullsend/config.base.yaml to resume" - exit 1 + # An engaged kill switch is an intentional quiet pause, not a + # failed workflow. Leave the stage empty and let the shared + # notification job tell explicit launchers that dispatch is + # paused, without mislabeling them as unauthorized. + echo "::notice::Stage '${REQUESTED_STAGE}' skipped — kill switch is active" + echo "skipped=true" >> "${GITHUB_OUTPUT}" fi - name: Validate agents config - if: steps.route.outputs.stage != '' + id: validate-agents + if: steps.route.outputs.requested_stage != '' && steps.kill-switch.outputs.skipped != 'true' run: | set -euo pipefail if [[ ! -f .fullsend/config.yaml ]]; then @@ -537,9 +592,9 @@ jobs: - name: Check role is enabled id: role-check - if: steps.route.outputs.stage != '' + if: steps.route.outputs.requested_stage != '' && steps.kill-switch.outputs.skipped != 'true' env: - STAGE: ${{ steps.route.outputs.stage }} + STAGE: ${{ steps.route.outputs.requested_stage }} run: | set -euo pipefail if [[ ! -f .fullsend/config.yaml ]]; then @@ -563,9 +618,9 @@ jobs: - name: Check agent is enabled id: agent-check - if: steps.route.outputs.stage != '' && steps.role-check.outputs.skipped != 'true' + if: steps.route.outputs.requested_stage != '' && steps.kill-switch.outputs.skipped != 'true' && steps.role-check.outputs.skipped != 'true' env: - STAGE: ${{ steps.route.outputs.stage }} + STAGE: ${{ steps.route.outputs.requested_stage }} run: | set -euo pipefail if [[ ! -f .fullsend/config.yaml ]]; then @@ -625,6 +680,60 @@ jobs: echo "${DELIM}" } >> "${GITHUB_OUTPUT}" + - name: Emit authorization denial metadata + id: authorization + if: always() + env: + EVENT_NAME: ${{ github.event_name }} + COMMENT_USER_TYPE: ${{ github.event.comment.user.type }} + COMMENT_USER_LOGIN: ${{ github.event.comment.user.login }} + COMMENT_USER_ID: ${{ github.event.comment.user.id }} + ISSUE_NUMBER: ${{ github.event.issue.number }} + COMMAND_APPLICABLE: ${{ steps.route.outputs.command_applicable }} + REQUESTED_STAGE: ${{ steps.route.outputs.requested_stage }} + STAGE: ${{ steps.route.outputs.stage }} + AUTH_CHECK_FAILED: ${{ steps.route.outputs.authorization_check_failed }} + ROUTE_AUTHORIZATION_DENIED: ${{ steps.route.outputs.authorization_denied }} + KILL_SWITCH_SKIPPED: ${{ steps.kill-switch.outputs.skipped }} + ROLE_SKIPPED: ${{ steps.role-check.outputs.skipped }} + AGENT_SKIPPED: ${{ steps.agent-check.outputs.skipped }} + run: | + set -euo pipefail + echo "authorization_denied=false" >> "${GITHUB_OUTPUT}" + echo "dispatch_blocked_reason=" >> "${GITHUB_OUTPUT}" + if [[ "${EVENT_NAME}" != "issue_comment" \ + || "${COMMENT_USER_TYPE}" == "Bot" \ + || "${COMMAND_APPLICABLE}" != "true" \ + || -z "${REQUESTED_STAGE}" \ + || "${AUTH_CHECK_FAILED}" == "true" \ + || ! "${COMMENT_USER_ID}" =~ ^[1-9][0-9]*$ \ + || ! "${ISSUE_NUMBER}" =~ ^[1-9][0-9]*$ \ + || ! "${COMMENT_USER_LOGIN}" =~ ^[A-Za-z0-9_-]+$ ]]; then + exit 0 + fi + if [[ "${KILL_SWITCH_SKIPPED}" == "true" ]]; then + echo "::notice::User ${COMMENT_USER_LOGIN} requested an agent while dispatch is paused by the kill switch" + { + echo "dispatch_blocked_reason=kill_switch" + echo "authorization_actor=${COMMENT_USER_LOGIN}" + echo "authorization_actor_id=${COMMENT_USER_ID}" + echo "authorization_number=${ISSUE_NUMBER}" + } >> "${GITHUB_OUTPUT}" + exit 0 + fi + if [[ "${ROUTE_AUTHORIZATION_DENIED}" != "true" \ + || "${ROLE_SKIPPED}" == "true" \ + || "${AGENT_SKIPPED}" == "true" ]]; then + exit 0 + fi + echo "::notice::User ${COMMENT_USER_LOGIN} is not authorized to launch the requested agent" + { + echo "authorization_denied=true" + echo "authorization_actor=${COMMENT_USER_LOGIN}" + echo "authorization_actor_id=${COMMENT_USER_ID}" + echo "authorization_number=${ISSUE_NUMBER}" + } >> "${GITHUB_OUTPUT}" + - name: Build event payload id: payload if: steps.route.outputs.stage != '' @@ -660,6 +769,167 @@ jobs: echo "${DELIM}" } >> "${GITHUB_OUTPUT}" + authorization-notice: + name: Authorization notice + needs: [route, harness-dispatch] + if: >- + ${{ always() && !cancelled() && + (needs.route.outputs.dispatch_blocked_reason == 'kill_switch' || + needs.route.outputs.authorization_denied == 'true' || + needs.harness-dispatch.outputs.dispatch_blocked_reason == 'kill_switch' || + (needs.harness-dispatch.outputs.authorization_denied == 'true' && + (needs.route.outputs.stage == '' || + needs.route.outputs.legacy_command_applicable != 'true' || + needs.route.outputs.authorization_check_failed == 'true'))) }} + runs-on: ${{ inputs.runner_image }} + permissions: + issues: write + contents: read + concurrency: + group: fullsend-authorization-notice-${{ github.repository }}-${{ needs.route.outputs.authorization_number || needs.harness-dispatch.outputs.authorization_number }}-${{ needs.route.outputs.authorization_actor_id || needs.harness-dispatch.outputs.authorization_actor_id }} + cancel-in-progress: false + env: + GH_TOKEN: ${{ github.token }} + REPOSITORY: ${{ github.repository }} + ISSUE_NUMBER: ${{ needs.route.outputs.authorization_number || needs.harness-dispatch.outputs.authorization_number }} + ACTOR_LOGIN: ${{ needs.route.outputs.authorization_actor || needs.harness-dispatch.outputs.authorization_actor }} + ACTOR_ID: ${{ needs.route.outputs.authorization_actor_id || needs.harness-dispatch.outputs.authorization_actor_id }} + BLOCKED_REASON: ${{ needs.route.outputs.dispatch_blocked_reason || needs.harness-dispatch.outputs.dispatch_blocked_reason || 'authorization_denied' }} + steps: + - name: Checkout caller repository + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: ${{ (github.event_name == 'pull_request_target' || github.event_name == 'pull_request_review') && github.event.pull_request.base.sha || github.sha }} + persist-credentials: false + allow-unsafe-pr-checkout: ${{ github.event_name == 'pull_request_target' }} + sparse-checkout: | + .fullsend/ + .defaults/action.yml + .defaults/.github/actions/install-fullsend-cli/ + .fullsend/.defaults/action.yml + sparse-checkout-cone-mode: false + + - name: Detect authorization notice CLI mode + id: mode + shell: bash + run: | + set -euo pipefail + if [[ -f .defaults/action.yml || -f .fullsend/.defaults/action.yml ]]; then + echo "mode=vendored" >> "${GITHUB_OUTPUT}" + else + echo "mode=upstream" >> "${GITHUB_OUTPUT}" + fi + + - name: Guard vendored install + if: steps.mode.outputs.mode == 'vendored' + shell: bash + run: | + set -euo pipefail + if [[ ! -f .fullsend/bin/fullsend ]]; then + echo "::error::broken --vendor install: vendored marker present but .fullsend/bin/fullsend is missing" + exit 1 + fi + + - name: Restore fullsend CLI cache + id: cli-cache + uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + path: ${{ runner.temp }}/fullsend-cache + key: fullsend-cli-${{ steps.mode.outputs.mode }}-${{ job.workflow_sha }} + + - name: Install fullsend CLI (vendored defaults) + if: steps.mode.outputs.mode == 'vendored' && steps.cli-cache.outputs.cache-hit != 'true' + uses: ./.defaults/.github/actions/install-fullsend-cli + with: + mode: vendored + vendored_path: .fullsend/bin/fullsend + github_token: ${{ github.token }} + + - name: Checkout upstream install action + if: steps.mode.outputs.mode == 'upstream' && steps.cli-cache.outputs.cache-hit != 'true' + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + repository: ${{ job.workflow_repository }} + ref: ${{ job.workflow_sha }} + path: .workflow-actions + fetch-depth: 1 + sparse-checkout: | + .github/actions/install-fullsend-cli/ + sparse-checkout-cone-mode: false + + - name: Install fullsend CLI (upstream workflow) + if: steps.mode.outputs.mode == 'upstream' && steps.cli-cache.outputs.cache-hit != 'true' + uses: ./.workflow-actions/.github/actions/install-fullsend-cli + with: + mode: upstream + workflow_repository: ${{ job.workflow_repository }} + workflow_sha: ${{ job.workflow_sha }} + github_token: ${{ github.token }} + + - name: Expose cached fullsend CLI + if: steps.cli-cache.outputs.cache-hit == 'true' + shell: bash + run: | + set -euo pipefail + install_dir="${RUNNER_TEMP}/fullsend" + mkdir -p "${install_dir}" + cp "${RUNNER_TEMP}/fullsend-cache/fullsend" "${install_dir}/fullsend" + chmod +x "${install_dir}/fullsend" + echo "${install_dir}" >> "${GITHUB_PATH}" + + - name: Prepare fullsend CLI cache artifact + if: steps.cli-cache.outputs.cache-hit != 'true' + shell: bash + run: | + set -euo pipefail + mkdir -p "${RUNNER_TEMP}/fullsend-cache" + cp "${RUNNER_TEMP}/fullsend/fullsend" "${RUNNER_TEMP}/fullsend-cache/fullsend" + + - name: Save fullsend CLI cache + if: steps.cli-cache.outputs.cache-hit != 'true' + uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + path: ${{ runner.temp }}/fullsend-cache + key: fullsend-cli-${{ steps.mode.outputs.mode }}-${{ job.workflow_sha }} + + - name: Create first-denial comment + shell: bash + run: | + set -euo pipefail + if [[ ! "${ISSUE_NUMBER}" =~ ^[1-9][0-9]*$ ]]; then + echo "::warning::Skipping authorization notice: invalid issue number" + exit 0 + fi + if [[ ! "${ACTOR_LOGIN}" =~ ^[A-Za-z0-9_-]+$ ]]; then + echo "::warning::Skipping authorization notice: invalid actor login" + exit 0 + fi + if [[ ! "${ACTOR_ID}" =~ ^[1-9][0-9]*$ ]]; then + echo "::warning::Skipping authorization notice: invalid actor ID" + exit 0 + fi + + if [[ "${BLOCKED_REASON}" == "kill_switch" ]]; then + MARKER="" + BODY_FILE="${RUNNER_TEMP}/dispatch-paused.md" + MESSAGE="@${ACTOR_LOGIN}, this agent request was not run because Fullsend agent dispatch is temporarily disabled for this repository. This is a repository-wide pause, not a permissions denial." + else + MARKER="" + BODY_FILE="${RUNNER_TEMP}/authorization-denied.md" + MESSAGE="@${ACTOR_LOGIN}, this agent launch was blocked because you are not authorized to launch Fullsend agents on this work item. Ask a repository maintainer for access." + fi + { + printf '%s\n\n' "${MARKER}" + printf '%s\n' "${MESSAGE}" + } > "${BODY_FILE}" + fullsend issues post-comment \ + --tracker github \ + --project "${REPOSITORY}" \ + --number "${ISSUE_NUMBER}" \ + --marker "${MARKER}" \ + --result "${BODY_FILE}" \ + --keep-history=false + triage: name: Triage needs: route @@ -1509,6 +1779,11 @@ jobs: pull-requests: read outputs: matrix: ${{ steps.dispatch.outputs.matrix }} + authorization_denied: ${{ steps.dispatch.outputs.authorization_denied || 'false' }} + dispatch_blocked_reason: ${{ steps.dispatch.outputs.dispatch_blocked_reason || '' }} + authorization_actor: ${{ steps.dispatch.outputs.authorization_actor || '' }} + authorization_actor_id: ${{ steps.dispatch.outputs.authorization_actor_id || '' }} + authorization_number: ${{ steps.dispatch.outputs.authorization_number || '' }} steps: - name: Validate event_action if: ${{ inputs.event_action == '' }} diff --git a/docs/contributing/ci-workflows.md b/docs/contributing/ci-workflows.md index 59c9cfbbb0..a2d4e514a2 100644 --- a/docs/contributing/ci-workflows.md +++ b/docs/contributing/ci-workflows.md @@ -170,6 +170,39 @@ When refactoring between action types, audit every `job.*` and `github.*` refere - Never use `permissions: write-all` or omit permissions (which defaults to the repo's broad default token permissions). - Separate jobs that need elevated permissions (e.g., `pull-requests: write`) from jobs that check out untrusted code. +### Serialized authorization notices + +When multiple dispatch paths can detect the same authorization denial, route their +metadata to one notification job. The job should use the existing +`fullsend issues post-comment` command, backed by `forge.Client`, for marker +deduplication and comment creation. This may cost an additional runner, but it +keeps the check-and-create operation serialized and prevents legacy and CEL +dispatch paths from racing to create duplicate notices. The dispatch binary +should emit only the metadata needed by that job; it should not introduce a +second comment-posting implementation. + +The CEL path requires both sides of the denial signal: the pre-CEL +authorization gate must reject the actor, and at least one harness trigger +must match the event. A role failure by itself is not a launch attempt, and a +CEL non-match is not an authorization failure; for example, an ordinary +comment without the harness's slash command remains silent. The execution +path still filters unauthorized harnesses before projecting refs. Dispatch +uses a separate non-dispatching trigger evaluation only to decide whether +denial metadata is warranted, and never emits refs from that probe. + +### Kill-switch pause notices + +An engaged `kill_switch` is an intentional repository-wide pause, not a +permission failure by the person who requested an agent. The reusable workflow +therefore keeps routing successful with an empty stage output, so an operator +does not create a red CI run for every event during the pause. Explicit human +launch commands still emit metadata to the serialized notification job. That +job uses the same `fullsend issues post-comment` path and work-item +concurrency, but a distinct `kill_switch` reason and marker, so the comment +explains that dispatch is temporarily disabled rather than claiming the actor +is unauthorized. Non-launch events do not produce comments, and callers must +use the stage output—not route-job success alone—to decide whether an agent ran. + ## Secrets in pull_request_target jobs Jobs triggered by `pull_request_target` that check out and execute PR-head code can expose secrets to untrusted authors. This is the well-documented "pwn request" vulnerability class. Five components form the attack chain: diff --git a/docs/contributing/config-source-inventory.md b/docs/contributing/config-source-inventory.md index 2705108faf..b32cd4093a 100644 --- a/docs/contributing/config-source-inventory.md +++ b/docs/contributing/config-source-inventory.md @@ -94,7 +94,13 @@ enroll every repository. Base file: no. ## File fields a workflow reads too narrowly -The Go accessor layers these. The bash steps in `.github/workflows/reusable-dispatch.yml` read `.fullsend/config.yaml` and skip `config.base.yaml`. A baseline that exists only in the base file does not affect those steps. If `config.yaml` is missing, the role check exits without applying a base-file role list. +The Go accessor layers these. The bash steps in +`.github/workflows/reusable-dispatch.yml` still read only +`.fullsend/config.yaml` for the fields below and skip `config.base.yaml`. A +baseline that exists only in the base file does not affect those steps. The +kill switch is intentionally excluded from this gap: both GitHub and GitLab +now layer its direct read, and the GitHub workflow reports an explicit launch +attempt as a paused-dispatch notice rather than an authorization denial. | Setting | Controls | Set from | Wins today | Read by | Decision | Base file? | |---|---|---|---|---|---|---| diff --git a/docs/contributing/harness-fields.md b/docs/contributing/harness-fields.md index 8618030894..794fbd32f3 100644 --- a/docs/contributing/harness-fields.md +++ b/docs/contributing/harness-fields.md @@ -120,6 +120,12 @@ a single-key map of that source to file overrides; a `plugins[]` entry can be a path string or a `{path, env, pi}` map. Scalar security leaf values retain their own validation and defaults; this type table does not override them. +Normalized-event actor metadata is separate from harness composition. The +optional `actor.numeric_id` is a stable forge-native identifier populated by +event adapters when available; it is suitable for identity-stable bookkeeping +but is not a harness field, a CEL authorization input, or a replacement for +the human-readable `actor.id`. + The planned `schema_version` field (absent = `1` once implemented) will declare this contract; an incompatible field-type change will require a version bump and an update to this table in the same change. Backward-compatible field diff --git a/docs/guides/user/cel-triggers-reference.md b/docs/guides/user/cel-triggers-reference.md index a51c761a2c..3cf1493374 100644 --- a/docs/guides/user/cel-triggers-reference.md +++ b/docs/guides/user/cel-triggers-reference.md @@ -12,7 +12,7 @@ When you register a custom agent and give it a `trigger` expression, fullsend ha 2. **Normalize.** The `gha-event` input driver converts the raw GitHub event into a [`NormalizedEvent`](../../normative/normalized-event/v1/) — a forge-neutral struct with fields like `event.entity.kind`, `event.transition.kind`, and `event.actor.role`. -3. **Authorize.** `fullsend dispatch` enforces the platform authorization gate before any agent is considered. Authorization is a platform-level decision — your CEL trigger does not need to implement permission checks (though you can add guards like `event.actor.role` if your agent has stricter requirements). +3. **Authorize.** `fullsend dispatch` enforces the platform authorization gate before any agent is considered. Authorization is a platform-level decision — your CEL trigger does not need to implement permission checks (though you can add guards like `event.actor.role` if your agent has stricter requirements). When a human launch is denied, Fullsend posts one explanatory comment for that user and work item; repeated denied attempts do not add duplicate comments. 4. **Enumerate.** Dispatch loads all registered agents from the merged repository-local config (the `agents:` list in `.fullsend/config.yaml`, optionally layered over `.fullsend/config.base.yaml`, plus scaffold discovery). Each harness with a non-empty `trigger` field is a candidate. If a registered agent's harness cannot be resolved or loaded, dispatch logs a GitHub Actions `::error::` annotation and skips that agent so other agents can still run. If every registered agent fails to load, `fullsend dispatch` exits non-zero instead of emitting an empty matrix — a fully unreadable harness set is a configuration error, not a "no trigger matched" result. diff --git a/docs/normative/normalized-event/v1/README.md b/docs/normative/normalized-event/v1/README.md index 7c7b3a1053..81f855e9a1 100644 --- a/docs/normative/normalized-event/v1/README.md +++ b/docs/normative/normalized-event/v1/README.md @@ -91,6 +91,11 @@ remains the normative stricter check. Adding a new `transition.kind` is **non-breaking** — CEL triggers use boolean expressions, not exhaustive enum matching. +The optional `actor.numeric_id` field is an additive v1.x change under this +policy. Existing payloads without it remain valid; consumers with pinned strict +schema copies must update those copies before accepting payloads that include +the field. + Normalized-event and entity-context-snapshot v1 carry independently versioned copies of the actor-role vocabulary. The entity-context-snapshot `bot` marker is a non-authority kind marker, not a normalized-event repository permission, @@ -238,6 +243,11 @@ gate denies a bot with `role_verified` set but no recognized `bot_role` on non-label paths. The production adapters do not emit the fields yet, so triggers that read them must guard with `has()`. +GitHub adapters also populate the optional `actor.numeric_id` from the event +sender's stable numeric account ID when it is present. This field is intended +for identity-stable bookkeeping such as notification deduplication; it is not +an authorization input and must not replace the login in user-facing mentions. + ### Fork security (`state.change_proposal.is_fork`) `is_fork` is `true` when `head_repo` differs from `base_repo` (fork-based diff --git a/docs/normative/normalized-event/v1/normalized-event.schema.json b/docs/normative/normalized-event/v1/normalized-event.schema.json index 48e4377389..b0db277b81 100644 --- a/docs/normative/normalized-event/v1/normalized-event.schema.json +++ b/docs/normative/normalized-event/v1/normalized-event.schema.json @@ -301,6 +301,11 @@ "maxLength": 255, "description": "Forge login or service account identifier." }, + "numeric_id": { + "type": "integer", + "minimum": 1, + "description": "Optional stable forge-native numeric actor identifier. GitHub adapters populate this from the event sender; it is metadata for identity-stable external bookkeeping, not an authorization input." + }, "kind": { "type": "string", "enum": ["human", "bot"] diff --git a/docs/reference/config-reference.md b/docs/reference/config-reference.md index 363c7a4558..a70b48584b 100644 --- a/docs/reference/config-reference.md +++ b/docs/reference/config-reference.md @@ -137,7 +137,16 @@ setup. Emergency stop. When set to `true`, all agent dispatch is disabled for the repository. Uses pointer semantics in the layered config system — `nil` (omitted) falls through to parent; an explicit `false` is a local decision -that does not fall through. +that does not fall through. In the reusable GitHub dispatch workflow, an active +kill switch records a successful skip with an empty stage output rather than +failing the routing job; callers must use the stage output to determine whether +an agent ran. When a human explicitly requests an agent while the switch is +active, the workflow uses the shared notification job to post one explanatory +comment for that actor and work item. The comment says that dispatch is +temporarily paused, rather than incorrectly saying that the actor is +unauthorized. Ordinary events do not create pause comments. This keeps an +intentional emergency stop quiet at the CI level while still giving a person +who requested work an actionable explanation. ### `keep_history` diff --git a/e2e/behaviour/features/dispatch/owners-auth.feature b/e2e/behaviour/features/dispatch/owners-auth.feature index 01dd645c00..f81166c8aa 100644 --- a/e2e/behaviour/features/dispatch/owners-auth.feature +++ b/e2e/behaviour/features/dispatch/owners-auth.feature @@ -58,6 +58,7 @@ Feature: OWNERS file authorization for bash routing And an issue When the outsider posts "/fs-code" on the issue Then the dispatch run does not authorize via OWNERS + And the issue has a comment containing "not authorized to launch Fullsend agents on this work item" Scenario: Unlisted collaborator falls through to API authorization Given an OWNERS file listing the outsider as a reviewer only diff --git a/internal/cli/dispatch.go b/internal/cli/dispatch.go index 26be77fe5d..f554a1474e 100644 --- a/internal/cli/dispatch.go +++ b/internal/cli/dispatch.go @@ -4,6 +4,7 @@ import ( "context" "fmt" "os" + "strconv" "strings" "github.com/spf13/cobra" @@ -103,17 +104,24 @@ func runDispatch(ctx context.Context, opts dispatchOpts) error { return err } - refs, err := harnessdispatch.Dispatch(ctx, harnessdispatch.Options{ + result, err := harnessdispatch.DispatchResult(ctx, harnessdispatch.Options{ ConfigDir: opts.configDir, Event: event, }) if err != nil { return err } + // Only gha-event has live GitHub authorization context. JSON evaluation + // remains read-only and never writes workflow notification metadata. + if inDriver == "gha-event" { + if err := writeDispatchOutput(event, result.AuthorizationDenied, result.DispatchBlockedReason); err != nil { + return err + } + } switch strings.ToLower(opts.outputDriver) { case "gha-matrix", "": - data, err := output.WriteGHAMatrix(refs) + data, err := output.WriteGHAMatrix(result.Refs) if err != nil { return err } @@ -124,7 +132,7 @@ func runDispatch(ctx context.Context, opts dispatchOpts) error { fmt.Println() } case "json": - if err := output.WriteJSON(os.Stdout, refs); err != nil { + if err := output.WriteJSON(os.Stdout, result.Refs); err != nil { return err } default: @@ -132,3 +140,52 @@ func runDispatch(ctx context.Context, opts dispatchOpts) error { } return nil } + +func writeDispatchOutput(event *normevent.Event, denied bool, blockedReason string) error { + if !isExplicitHumanSlashCommand(event) || (!denied && blockedReason != "kill_switch") { + return nil + } + path := os.Getenv("GITHUB_OUTPUT") + if path == "" || event.Entity.ID < 1 || event.Actor.NumericID < 1 || !validGitHubLogin(event.Actor.ID) { + return nil + } + + outputs := [][2]string{ + {"authorization_actor", event.Actor.ID}, + {"authorization_actor_id", strconv.FormatInt(event.Actor.NumericID, 10)}, + {"authorization_number", strconv.Itoa(event.Entity.ID)}, + } + if blockedReason == "kill_switch" { + outputs = append([][2]string{{"dispatch_blocked_reason", blockedReason}}, outputs...) + } else { + outputs = append([][2]string{{"authorization_denied", "true"}}, outputs...) + } + for _, output := range outputs { + if err := writeGitHubOutput(path, output[0], output[1]); err != nil { + return fmt.Errorf("write authorization output %s: %w", output[0], err) + } + } + return nil +} + +func isExplicitHumanSlashCommand(event *normevent.Event) bool { + if event == nil || event.Source.RawType != "issue_comment" || + event.Transition.Kind != normevent.TransitionCommentAdded || + event.Actor.Kind != normevent.ActorHuman || event.Transition.Comment == nil { + return false + } + command := strings.TrimSpace(event.Transition.Comment.Command) + return strings.HasPrefix(command, "/") && len(command) > 1 +} + +func validGitHubLogin(login string) bool { + if login == "" { + return false + } + for _, r := range login { + if (r < 'A' || r > 'Z') && (r < 'a' || r > 'z') && (r < '0' || r > '9') && r != '_' && r != '-' { + return false + } + } + return true +} diff --git a/internal/cli/dispatch_test.go b/internal/cli/dispatch_test.go index cd7b4a3a1e..a3c23f83fa 100644 --- a/internal/cli/dispatch_test.go +++ b/internal/cli/dispatch_test.go @@ -14,8 +14,142 @@ import ( "gopkg.in/yaml.v3" "github.com/fullsend-ai/fullsend/internal/config" + "github.com/fullsend-ai/fullsend/internal/normevent" ) +func TestWriteDispatchOutput_AuthorizationDenied(t *testing.T) { + path := filepath.Join(t.TempDir(), "github-output") + t.Setenv("GITHUB_OUTPUT", path) + require.NoError(t, os.WriteFile(path, nil, 0o600)) + event := &normevent.Event{ + Entity: normevent.Entity{ID: 42}, + Actor: normevent.Actor{ID: "alice", NumericID: 1234, Kind: normevent.ActorHuman}, + Transition: normevent.Transition{ + Kind: normevent.TransitionCommentAdded, + Comment: &normevent.Comment{Command: "/fs-code"}, + }, + Source: normevent.Source{RawType: "issue_comment"}, + } + + require.NoError(t, writeDispatchOutput(event, true, "")) + data, err := os.ReadFile(path) + require.NoError(t, err) + assert.Equal(t, "authorization_denied=true\nauthorization_actor=alice\nauthorization_actor_id=1234\nauthorization_number=42\n", string(data)) +} + +func TestWriteDispatchOutput_AuthorizationDeniedSupportsCustomSlashCommand(t *testing.T) { + path := filepath.Join(t.TempDir(), "github-output") + t.Setenv("GITHUB_OUTPUT", path) + require.NoError(t, os.WriteFile(path, nil, 0o600)) + event := &normevent.Event{ + Entity: normevent.Entity{ID: 42}, + Actor: normevent.Actor{ID: "alice", NumericID: 1234, Kind: normevent.ActorHuman}, + Transition: normevent.Transition{ + Kind: normevent.TransitionCommentAdded, + Comment: &normevent.Comment{Command: "/analyze"}, + }, + Source: normevent.Source{RawType: "issue_comment"}, + } + + require.NoError(t, writeDispatchOutput(event, true, "")) + data, err := os.ReadFile(path) + require.NoError(t, err) + assert.Contains(t, string(data), "authorization_actor_id=1234") +} + +func TestWriteDispatchOutput_KillSwitch(t *testing.T) { + path := filepath.Join(t.TempDir(), "github-output") + t.Setenv("GITHUB_OUTPUT", path) + require.NoError(t, os.WriteFile(path, nil, 0o600)) + event := &normevent.Event{ + Entity: normevent.Entity{ID: 42}, + Actor: normevent.Actor{ID: "alice", NumericID: 1234, Kind: normevent.ActorHuman}, + Transition: normevent.Transition{ + Kind: normevent.TransitionCommentAdded, + Comment: &normevent.Comment{Command: "/fs-code"}, + }, + Source: normevent.Source{RawType: "issue_comment"}, + } + + require.NoError(t, writeDispatchOutput(event, false, "kill_switch")) + data, err := os.ReadFile(path) + require.NoError(t, err) + assert.Equal(t, "dispatch_blocked_reason=kill_switch\nauthorization_actor=alice\nauthorization_actor_id=1234\nauthorization_number=42\n", string(data)) +} + +func TestWriteDispatchOutput_SkipsNonDeniedOrNonHuman(t *testing.T) { + path := filepath.Join(t.TempDir(), "github-output") + t.Setenv("GITHUB_OUTPUT", path) + for _, event := range []*normevent.Event{ + {Entity: normevent.Entity{ID: 42}, Actor: normevent.Actor{ID: "alice", NumericID: 1234, Kind: normevent.ActorHuman}}, + {Entity: normevent.Entity{ID: 42}, Actor: normevent.Actor{ID: "agent[bot]", Kind: normevent.ActorBot}}, + } { + require.NoError(t, writeDispatchOutput(event, false, "")) + } + _, err := os.Stat(path) + assert.ErrorIs(t, err, os.ErrNotExist) +} + +func TestWriteDispatchOutput_SkipsInvalidLogin(t *testing.T) { + path := filepath.Join(t.TempDir(), "github-output") + t.Setenv("GITHUB_OUTPUT", path) + event := &normevent.Event{ + Entity: normevent.Entity{ID: 42}, + Actor: normevent.Actor{ID: "alice\nforged", NumericID: 1234, Kind: normevent.ActorHuman}, + Transition: normevent.Transition{Kind: normevent.TransitionCommentAdded, Comment: &normevent.Comment{Command: "/fs-code"}}, + Source: normevent.Source{RawType: "issue_comment"}, + } + + require.NoError(t, writeDispatchOutput(event, true, "")) + _, err := os.Stat(path) + assert.ErrorIs(t, err, os.ErrNotExist) +} + +func TestWriteDispatchOutput_SkipsAutomaticTrigger(t *testing.T) { + path := filepath.Join(t.TempDir(), "github-output") + t.Setenv("GITHUB_OUTPUT", path) + event := &normevent.Event{ + Entity: normevent.Entity{ID: 42}, + Actor: normevent.Actor{ID: "alice", NumericID: 1234, Kind: normevent.ActorHuman}, + Transition: normevent.Transition{Kind: normevent.TransitionOpened}, + Source: normevent.Source{RawType: "issues"}, + } + + require.NoError(t, writeDispatchOutput(event, true, "")) + _, err := os.Stat(path) + assert.ErrorIs(t, err, os.ErrNotExist) +} + +func TestWriteDispatchOutput_SkipsMissingNumericID(t *testing.T) { + path := filepath.Join(t.TempDir(), "github-output") + t.Setenv("GITHUB_OUTPUT", path) + event := &normevent.Event{ + Entity: normevent.Entity{ID: 42}, + Actor: normevent.Actor{ID: "alice", Kind: normevent.ActorHuman}, + Transition: normevent.Transition{Kind: normevent.TransitionCommentAdded, Comment: &normevent.Comment{Command: "/fs-code"}}, + Source: normevent.Source{RawType: "issue_comment"}, + } + + require.NoError(t, writeDispatchOutput(event, true, "")) + _, err := os.Stat(path) + assert.ErrorIs(t, err, os.ErrNotExist) +} + +func TestWriteDispatchOutput_ReportsOutputError(t *testing.T) { + outputPath := t.TempDir() + t.Setenv("GITHUB_OUTPUT", outputPath) + event := &normevent.Event{ + Entity: normevent.Entity{ID: 42}, + Actor: normevent.Actor{ID: "alice", NumericID: 1234, Kind: normevent.ActorHuman}, + Transition: normevent.Transition{Kind: normevent.TransitionCommentAdded, Comment: &normevent.Comment{Command: "/fs-code"}}, + Source: normevent.Source{RawType: "issue_comment"}, + } + + err := writeDispatchOutput(event, true, "") + require.Error(t, err) + assert.Contains(t, err.Error(), "write authorization output") +} + func TestRunDispatch_JSONDriver(t *testing.T) { dir := t.TempDir() writeDispatchFixture(t, dir) diff --git a/internal/harnessdispatch/auth.go b/internal/harnessdispatch/auth.go index 5e6a49ef85..81ce6e4268 100644 --- a/internal/harnessdispatch/auth.go +++ b/internal/harnessdispatch/auth.go @@ -140,8 +140,10 @@ func IsAuthorized(event *normevent.Event) bool { } // FilterAuthorizedHarnesses returns the subset of harnesses that event is -// authorized to dispatch, keyed on each harness role: field. Run it before -// MatchHarnesses so CEL only evaluates authorized harnesses. +// authorized to dispatch, keyed on each harness role: field. The execution +// path runs it before its normal MatchHarnesses call; a separate +// non-dispatching notice probe may evaluate denied candidates to establish +// whether a denied event actually matched a harness. func FilterAuthorizedHarnesses(harnesses []TriggeredHarness, event *normevent.Event) []TriggeredHarness { var out []TriggeredHarness for _, m := range harnesses { diff --git a/internal/harnessdispatch/core.go b/internal/harnessdispatch/core.go index 62599826a5..b87ec4a513 100644 --- a/internal/harnessdispatch/core.go +++ b/internal/harnessdispatch/core.go @@ -28,23 +28,55 @@ type Options struct { FetchPolicy *fetch.FetchPolicy } +// Result describes a dispatch evaluation. AuthorizationDenied is set only +// when a confirmed authorization failure prevents at least one matching +// harness from running; kill-switch and no-trigger results leave it false. +type Result struct { + Refs []ExecutionRef + AuthorizationDenied bool + DispatchBlockedReason string +} + // Dispatch evaluates authorization, kill switch, harness triggers, and returns execution refs. // Returns empty slice (not error) when denied, kill-switched, or no triggers match. // Returns an error when every registered harness fails to resolve or load. func Dispatch(ctx context.Context, opts Options) ([]ExecutionRef, error) { + result, err := DispatchResult(ctx, opts) + return result.Refs, err +} + +// DispatchResult evaluates authorization, kill switch, harness triggers, and +// returns execution refs together with the reason an empty result occurred. +func DispatchResult(ctx context.Context, opts Options) (Result, error) { if opts.Event == nil { - return nil, fmt.Errorf("event is required") + return Result{}, fmt.Errorf("event is required") } if opts.ConfigDir == "" { - return nil, fmt.Errorf("config dir is required") + return Result{}, fmt.Errorf("config dir is required") } dirCfg, err := config.LoadConfig(opts.ConfigDir, config.LoadOpts{MissingOK: true}) if err != nil { - return nil, err + return Result{}, err } - if dirCfg.IsKillSwitchActive() { - return nil, nil + killSwitchActive := dirCfg.IsKillSwitchActive() + if killSwitchActive { + // A kill switch blocks execution, but it must not turn every slash + // command into a paused-agent notice. Evaluate triggers first so the + // caller can distinguish an actual agent launch request from commands + // handled by another workflow, such as /fs-fix-stop. + candidates, err := ListTriggeredHarnesses(ctx, opts.ConfigDir, dirCfg, opts.FetchPolicy) + if err != nil { + return Result{}, nil + } + matched, err := MatchHarnesses(candidates, opts.Event) + if err != nil { + return Result{}, err + } + if len(matched) == 0 { + return Result{}, nil + } + return Result{DispatchBlockedReason: "kill_switch"}, nil } // Compute the effective role for the auth gate without mutating the @@ -67,20 +99,53 @@ func Dispatch(ctx context.Context, opts Options) ([]ExecutionRef, error) { authCheck := *opts.Event authCheck.Actor.Role = effectiveRole - if !IsEventAuthorized(&authCheck) { - return nil, nil + eventAuthorized := IsEventAuthorized(&authCheck) + if !eventAuthorized && !opts.Event.AuthorizationAvailable() { + return Result{}, nil } candidates, err := ListTriggeredHarnesses(ctx, opts.ConfigDir, dirCfg, opts.FetchPolicy) if err != nil { - return nil, err + // An already-denied event cannot launch anything, so an unavailable + // harness should not turn the denial-notification path into a failure. + // Authorized events still surface resolution errors normally. + if !eventAuthorized { + return Result{}, nil + } + return Result{}, err } - candidates = FilterAuthorizedHarnesses(candidates, &authCheck) + if !eventAuthorized { + // Keep the execution gate fail-closed, but use a non-dispatching CEL + // probe to establish whether this denied event actually targeted a + // harness. A denial notice is only justified when both gates fail: an + // authorization failure and a matching trigger. No execution refs are + // projected from this branch. + matched, err := MatchHarnesses(candidates, opts.Event) + if err != nil { + return Result{}, err + } + return Result{AuthorizationDenied: len(matched) > 0}, nil + } + + authorizedCandidates, deniedCandidates := partitionHarnessesByAuthorization(candidates, &authCheck) - matched, err := MatchHarnesses(candidates, opts.Event) + matched, err := MatchHarnesses(authorizedCandidates, opts.Event) if err != nil { - return nil, err + return Result{}, err + } + + // The normal dispatch path evaluates CEL only for authorized candidates. + // For the notice path, evaluate denied candidates separately and never + // project their refs; this distinguishes a denied launch from an event + // that simply does not match any harness. + var authorizationDenied bool + if len(deniedCandidates) > 0 { + deniedMatches, err := MatchHarnesses(deniedCandidates, opts.Event) + if err != nil { + return Result{}, err + } + authorizationDenied = len(deniedMatches) > 0 } matched = dropGitHubRoutedBuiltins(matched, opts.Event) @@ -89,11 +154,29 @@ func Dispatch(ctx context.Context, opts Options) ([]ExecutionRef, error) { role := m.Harness.Role ref, err := ProjectExecutionRef(m.Name, role, opts.Event) if err != nil { - return nil, fmt.Errorf("projecting %s: %w", m.Name, err) + return Result{}, fmt.Errorf("projecting %s: %w", m.Name, err) } refs = append(refs, ref) } - return refs, nil + return Result{Refs: refs, AuthorizationDenied: authorizationDenied}, nil +} + +// partitionHarnessesByAuthorization keeps the dispatch path's CEL input +// restricted to authorized harnesses while retaining denied candidates for a +// separate, non-dispatching notice probe. +func partitionHarnessesByAuthorization(harnesses []TriggeredHarness, event *normevent.Event) (authorized, denied []TriggeredHarness) { + for _, harness := range harnesses { + role := "" + if harness.Harness != nil { + role = harness.Harness.Role + } + if IsHarnessAuthorized(event, role) { + authorized = append(authorized, harness) + } else { + denied = append(denied, harness) + } + } + return authorized, denied } // dropGitHubRoutedBuiltins removes matched harnesses registered under a diff --git a/internal/harnessdispatch/core_test.go b/internal/harnessdispatch/core_test.go index f2a1da4f0b..ee1b8ccd99 100644 --- a/internal/harnessdispatch/core_test.go +++ b/internal/harnessdispatch/core_test.go @@ -3,6 +3,7 @@ package harnessdispatch import ( "bytes" "context" + "fmt" "log" "os" "path/filepath" @@ -19,16 +20,45 @@ import ( func TestDispatch_KillSwitch(t *testing.T) { dir := t.TempDir() - cfg := config.NewPerRepoConfig(nil, "o/r") - cfg.SetKillSwitch(true) - data, err := yaml.Marshal(cfg) - require.NoError(t, err) - require.NoError(t, os.WriteFile(filepath.Join(dir, "config.yaml"), data, 0o644)) + writeHarnessConfig(t, dir, killSwitchLabelHarnessYAML(), func(cfg config.PerRepoConfigWriter) { + cfg.SetKillSwitch(true) + }) ev := mustEvent(t, "ready-to-code-labeled.json") - refs, err := Dispatch(context.Background(), Options{ConfigDir: dir, Event: ev}) + result, err := DispatchResult(context.Background(), Options{ConfigDir: dir, Event: ev}) require.NoError(t, err) - assert.Empty(t, refs) + assert.Empty(t, result.Refs) + assert.Equal(t, "kill_switch", result.DispatchBlockedReason) + assert.False(t, result.AuthorizationDenied) +} + +func TestDispatchResult_KillSwitchOnlyForMatchingHumanCommand(t *testing.T) { + for _, tc := range []struct { + name string + command string + wantBlocked bool + }{ + {name: "unmatched fix stop command", command: "/fs-fix-stop"}, + {name: "matched custom launch command", command: "/analyze", wantBlocked: true}, + } { + t.Run(tc.name, func(t *testing.T) { + dir := t.TempDir() + writeHarnessConfig(t, dir, slashCommandHarnessYAML("/analyze"), func(cfg config.PerRepoConfigWriter) { + cfg.SetKillSwitch(true) + }) + + ev := mustEvent(t, "fs-fix-comment.json") + ev.Transition.Comment.Command = tc.command + result, err := DispatchResult(context.Background(), Options{ConfigDir: dir, Event: ev}) + require.NoError(t, err) + assert.Empty(t, result.Refs) + if tc.wantBlocked { + assert.Equal(t, "kill_switch", result.DispatchBlockedReason) + } else { + assert.Empty(t, result.DispatchBlockedReason) + } + }) + } } func TestDispatch_AuthDeny(t *testing.T) { @@ -36,9 +66,72 @@ func TestDispatch_AuthDeny(t *testing.T) { writeHarnessConfig(t, dir, issuePingHarnessYAML()) ev := mustEvent(t, "issue-opened.json") - refs, err := Dispatch(context.Background(), Options{ConfigDir: dir, Event: ev}) + result, err := DispatchResult(context.Background(), Options{ConfigDir: dir, Event: ev}) require.NoError(t, err) - assert.Empty(t, refs) + assert.Empty(t, result.Refs) + assert.False(t, result.AuthorizationDenied, "an unauthorized event with no matching harness is not a launch attempt") +} + +func TestDispatchResult_AuthDenyOnlyForMatchingHarness(t *testing.T) { + dir := t.TempDir() + writeHarnessConfigSubdir(t, dir, issueOpenedHarnessYAML()) + + result, err := DispatchResult(context.Background(), Options{ + ConfigDir: filepath.Join(dir, ".fullsend"), + Event: mustEvent(t, "issue-opened.json"), + }) + require.NoError(t, err) + assert.Empty(t, result.Refs) + assert.True(t, result.AuthorizationDenied) +} + +func TestDispatchResult_PerHarnessAuthDenyRequiresCELMatch(t *testing.T) { + dir := t.TempDir() + writeHarnessesConfig(t, dir, map[string]string{ + "issue-triage": issueOpenedHarnessYAML(), + "issue-code": issueOpenedCoderHarnessYAML(), + }) + + ev := mustEvent(t, "issue-opened.json") + ev.Actor.Role = normevent.RoleTriage + result, err := DispatchResult(context.Background(), Options{ConfigDir: dir, Event: ev}) + require.NoError(t, err) + require.Len(t, result.Refs, 1) + assert.Equal(t, "issue-triage", result.Refs[0].Agent) + assert.True(t, result.AuthorizationDenied, "a matching harness above the actor's threshold warrants a denial notice") +} + +func TestDispatchResult_AuthDenyDoesNotReportCELNonMatch(t *testing.T) { + dir := t.TempDir() + writeHarnessConfig(t, dir, slashCommandHarnessYAML("/analyze")) + + ev := mustEvent(t, "fs-fix-comment.json") + ev.Actor.Role = normevent.RoleNone + ev.Transition.Comment.Command = "/other" + result, err := DispatchResult(context.Background(), Options{ConfigDir: dir, Event: ev}) + require.NoError(t, err) + assert.Empty(t, result.Refs) + assert.False(t, result.AuthorizationDenied, "an unauthorized comment without a matching slash command is not a launch attempt") +} + +func TestDispatchResult_PermissionLookupFailureDoesNotNotify(t *testing.T) { + dir := t.TempDir() + writeHarnessConfigSubdir(t, dir, issueOpenedHarnessYAML()) + ev := mustEvent(t, "issue-opened.json") + ev.MarkAuthorizationUnavailable() + + result, err := DispatchResult(context.Background(), Options{ + ConfigDir: filepath.Join(dir, ".fullsend"), + Event: ev, + }) + require.NoError(t, err) + assert.Empty(t, result.Refs) + assert.False(t, result.AuthorizationDenied) +} + +func TestDispatchResult_EmptyConfigDir(t *testing.T) { + _, err := DispatchResult(context.Background(), Options{Event: mustEvent(t, "issue-opened.json")}) + require.EqualError(t, err, "config dir is required") } func TestDispatch_CELIssueMatch(t *testing.T) { @@ -192,6 +285,30 @@ trigger: | ` } +func killSwitchLabelHarnessYAML() string { + return `agent: agents/triage.md +role: triage +slug: fullsend-ai-kill-switch-label +model: opus +image: ghcr.io/fullsend-ai/fullsend-sandbox:latest +trigger: | + event.transition.kind == "label_changed" + && event.transition.label.name == "ready-to-code" +` +} + +func slashCommandHarnessYAML(command string) string { + return fmt.Sprintf(`agent: agents/triage.md +role: triage +slug: fullsend-ai-slash-command +model: opus +image: ghcr.io/fullsend-ai/fullsend-sandbox:latest +trigger: | + event.transition.kind == "comment_added" + && event.transition.comment.command == %q +`, command) +} + func TestDispatch_OwnersUpgradesActorRole(t *testing.T) { // issue-opened (not label-added) with a role: coder harness requires // write. RoleNone is denied without the OWNERS approver upgrade, so diff --git a/internal/harnessdispatch/input/ghaevent.go b/internal/harnessdispatch/input/ghaevent.go index 4b1db7ab5d..74e47a8b51 100644 --- a/internal/harnessdispatch/input/ghaevent.go +++ b/internal/harnessdispatch/input/ghaevent.go @@ -5,8 +5,10 @@ import ( "encoding/json" "fmt" "log" + "math" "net/url" "os" + "strconv" "strings" "unicode/utf8" @@ -73,6 +75,7 @@ func mapGitHubWebhook(ctx context.Context, opts GHAEventOptions, raw map[string] sender := nestedMap(raw, "sender") actorID := stringField(sender, "login") + actorNumericID := int64Field(sender, "id") if actorID == "" { actorID = opts.GitHubActor } @@ -82,12 +85,14 @@ func mapGitHubWebhook(ctx context.Context, opts GHAEventOptions, raw map[string] } role := normevent.RoleNone + authorizationUnavailable := true if opts.Forge != nil && actorID != "" { parts := strings.SplitN(opts.Repository, "/", 2) if len(parts) == 2 { if gh, ok := opts.Forge.(forge.GitHubExtensions); ok { if perm, err := gh.GetCollaboratorPermission(ctx, parts[0], parts[1], actorID); err == nil { role = normevent.MapGitHubPermission(perm) + authorizationUnavailable = false } else { log.Printf("harness dispatch: collaborator permission lookup failed for %s on %s: %v", actorID, opts.Repository, err) } @@ -99,6 +104,7 @@ func mapGitHubWebhook(ctx context.Context, opts GHAEventOptions, raw map[string] Repo: opts.Repository, Actor: normevent.Actor{ ID: actorID, + NumericID: actorNumericID, Kind: actorKind, Role: role, IsEntityAuthor: false, @@ -111,6 +117,9 @@ func mapGitHubWebhook(ctx context.Context, opts GHAEventOptions, raw map[string] Labels: []string{}, }, } + if authorizationUnavailable { + ev.MarkAuthorizationUnavailable() + } if action != "" { ev.Source.RawAction = action } @@ -123,7 +132,7 @@ func mapGitHubWebhook(ctx context.Context, opts GHAEventOptions, raw map[string] case "pull_request_review": return mapPRReviewEvent(ev, raw, action, actorID) case "issue_comment": - return mapIssueCommentEvent(ctx, opts, raw, action, actorID) + return mapIssueCommentEvent(ctx, opts, ev, raw, action, actorID) default: return nil, fmt.Errorf("unsupported github event name %q", opts.EventName) } @@ -263,47 +272,11 @@ func mapPREvent(ev *normevent.Event, raw map[string]any, action, actorID string) return ev, nil } -func mapIssueCommentEvent(ctx context.Context, opts GHAEventOptions, raw map[string]any, action, actorID string) (*normevent.Event, error) { +func mapIssueCommentEvent(ctx context.Context, opts GHAEventOptions, ev *normevent.Event, raw map[string]any, action, actorID string) (*normevent.Event, error) { issue := nestedMap(raw, "issue") if issue == nil { return nil, fmt.Errorf("issue_comment missing issue") } - ev := &normevent.Event{ - Repo: opts.Repository, - Actor: normevent.Actor{ - ID: actorID, - Kind: normevent.ActorHuman, - Role: normevent.RoleNone, - IsEntityAuthor: false, - }, - Source: normevent.Source{ - System: normevent.SystemGitHub, - RawType: opts.EventName, - }, - State: normevent.State{ - Labels: []string{}, - }, - } - if action != "" { - ev.Source.RawAction = action - } - - sender := nestedMap(raw, "sender") - if strings.HasSuffix(strings.ToLower(actorID), "[bot]") || stringField(sender, "type") == "Bot" { - ev.Actor.Kind = normevent.ActorBot - } - if opts.Forge != nil && actorID != "" { - parts := strings.SplitN(opts.Repository, "/", 2) - if len(parts) == 2 { - if gh, ok := opts.Forge.(forge.GitHubExtensions); ok { - if perm, err := gh.GetCollaboratorPermission(ctx, parts[0], parts[1], actorID); err == nil { - ev.Actor.Role = normevent.MapGitHubPermission(perm) - } else { - log.Printf("harness dispatch: collaborator permission lookup failed for %s on %s: %v", actorID, opts.Repository, err) - } - } - } - } ev.Entity = entityFromIssue(issue) ev.Actor.IsEntityAuthor = strings.EqualFold(stringField(issue, "user", "login"), actorID) @@ -500,6 +473,34 @@ func intField(m map[string]any, key string) int { } } +func int64Field(m map[string]any, key string) int64 { + switch v := m[key].(type) { + case float64: + if v < 1 || v >= float64(math.MaxInt64) || math.Trunc(v) != v { + return 0 + } + return int64(v) + case int: + if v < 1 { + return 0 + } + return int64(v) + case int64: + if v < 1 { + return 0 + } + return v + case json.Number: + i, err := strconv.ParseInt(string(v), 10, 64) + if err != nil || i < 1 { + return 0 + } + return i + default: + return 0 + } +} + func boolField(m map[string]any, key string) bool { v, _ := m[key].(bool) return v diff --git a/internal/harnessdispatch/input/ghaevent_internal_test.go b/internal/harnessdispatch/input/ghaevent_internal_test.go new file mode 100644 index 0000000000..36d9fae08b --- /dev/null +++ b/internal/harnessdispatch/input/ghaevent_internal_test.go @@ -0,0 +1,34 @@ +package input + +import ( + "encoding/json" + "math" + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestInt64Field(t *testing.T) { + tests := []struct { + name string + value any + want int64 + }{ + {name: "float", value: float64(1234), want: 1234}, + {name: "fractional float", value: 12.5}, + {name: "too large float", value: float64(math.MaxInt64)}, + {name: "int", value: 1234, want: 1234}, + {name: "negative int", value: -1}, + {name: "int64", value: int64(1234), want: 1234}, + {name: "negative int64", value: int64(-1)}, + {name: "json number", value: json.Number("1234"), want: 1234}, + {name: "invalid json number", value: json.Number("not-a-number")}, + {name: "unsupported", value: "1234"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + assert.Equal(t, tt.want, int64Field(map[string]any{"id": tt.value}, "id")) + }) + } + assert.Zero(t, int64Field(nil, "id")) +} diff --git a/internal/harnessdispatch/input/ghaevent_test.go b/internal/harnessdispatch/input/ghaevent_test.go index c6f3a10331..2d4e200776 100644 --- a/internal/harnessdispatch/input/ghaevent_test.go +++ b/internal/harnessdispatch/input/ghaevent_test.go @@ -116,6 +116,33 @@ func TestLoadGHAEvent_PROpenedByBot(t *testing.T) { assert.Equal(t, normevent.RoleNone, ev.Actor.Role) } +func TestLoadGHAEvent_PermissionLookupFailureIsUnavailable(t *testing.T) { + raw := map[string]any{ + "action": "opened", + "pull_request": map[string]any{ + "number": float64(100), + "html_url": "https://github.com/o/r/pull/100", + "user": map[string]any{"login": "alice"}, + "labels": []any{}, + "head": map[string]any{"ref": "feature", "sha": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", "repo": map[string]any{"full_name": "o/r"}}, + "base": map[string]any{"ref": "main", "repo": map[string]any{"full_name": "o/r"}}, + }, + "sender": map[string]any{"login": "alice", "type": "User"}, + } + path := writeEventFile(t, raw) + client := forge.NewFakeClient() + client.Errors["GetCollaboratorPermission"] = assert.AnError + + ev, err := input.LoadGHAEvent(context.Background(), input.GHAEventOptions{ + EventPath: path, + EventName: "pull_request_target", + Repository: "o/r", + Forge: client, + }) + require.NoError(t, err) + assert.False(t, ev.AuthorizationAvailable()) +} + func TestLoadGHAEvent_PRLabeled(t *testing.T) { raw := map[string]any{ "action": "labeled", @@ -166,7 +193,7 @@ func TestLoadGHAEvent_IssueComment(t *testing.T) { "comment": map[string]any{ "body": "/fs-fix please repair", }, - "sender": map[string]any{"login": "alice", "type": "User"}, + "sender": map[string]any{"login": "alice", "id": float64(1234), "type": "User"}, } path := writeEventFile(t, raw) @@ -193,6 +220,7 @@ func TestLoadGHAEvent_IssueComment(t *testing.T) { }) require.NoError(t, err) assert.Equal(t, normevent.TransitionCommentAdded, ev.Transition.Kind) + assert.Equal(t, int64(1234), ev.Actor.NumericID) assert.Equal(t, "/fs-fix", ev.Transition.Comment.Command) assert.NotNil(t, ev.Entity.LinkedChangeProposal) assert.Equal(t, 42, ev.Entity.LinkedChangeProposal.ID) diff --git a/internal/normevent/event.go b/internal/normevent/event.go index 9f446637b8..47715bc9c8 100644 --- a/internal/normevent/event.go +++ b/internal/normevent/event.go @@ -16,6 +16,29 @@ type Event struct { Actor Actor `json:"actor"` State State `json:"state"` Source Source `json:"source"` + + // authorizationUnavailable is input-driver metadata. It is deliberately + // not serialized into normalized events: a failed live permission lookup + // must fail closed without being mistaken for a confirmed denial notice. + // Its zero value means available for hand-built and JSON events, whose + // normalized role is already explicit; the gha-event driver marks live + // lookup failures unavailable. + authorizationUnavailable bool +} + +// MarkAuthorizationUnavailable records that the live permission lookup could +// not be completed for this event. Dispatch remains fail-closed, but callers +// must not present the result as a confirmed authorization denial. +func (e *Event) MarkAuthorizationUnavailable() { + if e != nil { + e.authorizationUnavailable = true + } +} + +// AuthorizationAvailable reports whether the input driver resolved the +// actor's live authorization state. +func (e *Event) AuthorizationAvailable() bool { + return e != nil && !e.authorizationUnavailable } // EntityKind identifies work items, change proposals, or conversations. @@ -127,6 +150,7 @@ const ( // completed (including a successful no-match) and false means it failed. type Actor struct { ID string `json:"id"` + NumericID int64 `json:"numeric_id,omitempty"` Kind ActorKind `json:"kind"` Role ActorRole `json:"role"` BotRole string `json:"bot_role,omitempty"` diff --git a/internal/normevent/event_test.go b/internal/normevent/event_test.go index 4d5a9b0787..3f90e2b279 100644 --- a/internal/normevent/event_test.go +++ b/internal/normevent/event_test.go @@ -51,6 +51,18 @@ func TestIsWriteAuthorized(t *testing.T) { assert.False(t, IsWriteAuthorized(RoleNone)) } +func TestAuthorizationAvailability(t *testing.T) { + event := &Event{} + assert.True(t, event.AuthorizationAvailable()) + + event.MarkAuthorizationUnavailable() + assert.False(t, event.AuthorizationAvailable()) + + var nilEvent *Event + assert.False(t, nilEvent.AuthorizationAvailable()) + nilEvent.MarkAuthorizationUnavailable() +} + func TestIsTriageAuthorized(t *testing.T) { assert.True(t, IsTriageAuthorized(RoleAdmin)) assert.True(t, IsTriageAuthorized(RoleMaintain)) diff --git a/internal/scaffold/github_kill_switch_test.go b/internal/scaffold/github_kill_switch_test.go index 46c8e98c31..9596aba883 100644 --- a/internal/scaffold/github_kill_switch_test.go +++ b/internal/scaffold/github_kill_switch_test.go @@ -6,6 +6,7 @@ import ( "path/filepath" "testing" + "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "gopkg.in/yaml.v3" ) @@ -213,15 +214,95 @@ func TestCheckKillSwitchStep_ConsultsConfigBaseYAML(t *testing.T) { scriptPath := filepath.Join(root, "check-kill-switch.sh") require.NoError(t, os.WriteFile(scriptPath, []byte(script), 0o755)) + outputPath := filepath.Join(root, "github-output") + require.NoError(t, os.WriteFile(outputPath, nil, 0o600)) cmd := exec.Command("bash", scriptPath) cmd.Dir = root + cmd.Env = append(os.Environ(), "REQUESTED_STAGE=code", "GITHUB_OUTPUT="+outputPath) out, err := cmd.CombinedOutput() + output, readErr := os.ReadFile(outputPath) + require.NoError(t, readErr) + require.NoError(t, err, "stdout/stderr: %s", out) if tc.wantHalt { - require.Error(t, err, "stdout/stderr: %s", out) + assert.Contains(t, string(output), "skipped=true") } else { - require.NoError(t, err, "stdout/stderr: %s", out) + assert.NotContains(t, string(output), "skipped=true") + } + }) + } +} + +func TestAuthorizationMetadataStep_EmitsPauseForHumanLaunch(t *testing.T) { + script := extractReusableDispatchStepScript(t, "route", "Emit authorization denial metadata") + cases := []struct { + name string + killSwitch string + roleSkipped string + agentSkipped string + wantPause bool + wantDenied bool + }{ + { + name: "kill switch emits pause notice metadata", + killSwitch: "true", + wantPause: true, + }, + { + name: "disabled role suppresses denial", + roleSkipped: "true", + }, + { + name: "disabled agent suppresses denial", + agentSkipped: "true", + }, + { + name: "runnable unauthorized launch emits denial", + wantDenied: true, + }, + } + + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + root := t.TempDir() + scriptPath := filepath.Join(root, "emit-authorization-metadata.sh") + require.NoError(t, os.WriteFile(scriptPath, []byte(script), 0o755)) + outputPath := filepath.Join(root, "github-output") + require.NoError(t, os.WriteFile(outputPath, nil, 0o600)) + + cmd := exec.Command("bash", scriptPath) + cmd.Dir = root + cmd.Env = append(os.Environ(), + "EVENT_NAME=issue_comment", + "COMMENT_USER_TYPE=User", + "COMMENT_USER_LOGIN=alice", + "COMMENT_USER_ID=1234", + "ISSUE_NUMBER=42", + "COMMAND_APPLICABLE=true", + "REQUESTED_STAGE=code", + "AUTH_CHECK_FAILED=false", + "ROUTE_AUTHORIZATION_DENIED=true", + "KILL_SWITCH_SKIPPED="+tc.killSwitch, + "ROLE_SKIPPED="+tc.roleSkipped, + "AGENT_SKIPPED="+tc.agentSkipped, + "GITHUB_OUTPUT="+outputPath, + ) + out, err := cmd.CombinedOutput() + require.NoError(t, err, "stdout/stderr: %s", out) + + output, err := os.ReadFile(outputPath) + require.NoError(t, err) + if tc.wantPause { + assert.Contains(t, string(output), "dispatch_blocked_reason=kill_switch\n") + assert.Contains(t, string(output), "authorization_actor=alice\n") + assert.Contains(t, string(output), "authorization_actor_id=1234\n") + assert.Contains(t, string(output), "authorization_number=42\n") + } + if tc.wantDenied { + assert.Contains(t, string(output), "authorization_denied=true\n") + } else { + assert.NotContains(t, string(output), "authorization_denied=true\n") } }) } diff --git a/internal/scaffold/workflow_call_alignment_test.go b/internal/scaffold/workflow_call_alignment_test.go index d00f666e4f..035ba113db 100644 --- a/internal/scaffold/workflow_call_alignment_test.go +++ b/internal/scaffold/workflow_call_alignment_test.go @@ -148,7 +148,7 @@ var dispatchStageConcurrencyExpectations = map[string]stageConcurrencyExpectatio // dispatchNonAgentJobs lists reusable-dispatch.yml jobs that intentionally // carry no concurrency expectation. Every other job in the workflow must have // an entry in dispatchStageConcurrencyExpectations. -var dispatchNonAgentJobs = []string{"route", "harness-dispatch"} +var dispatchNonAgentJobs = []string{"route", "harness-dispatch", "authorization-notice"} // stepDeclRe matches a YAML step declaration line: " - name: ". var stepDeclRe = regexp.MustCompile(`(?m)^ - name: (.+)$`) @@ -957,6 +957,30 @@ func TestDispatchPerStageAuthorization(t *testing.T) { for _, wc := range cases { t.Run(wc.name, func(t *testing.T) { s := string(wc.content(t)) + assert.Contains(t, s, "authorization_denied", + "unauthorized slash commands must expose a route output for notification") + assert.Contains(t, s, "dispatch_blocked_reason", + "kill-switch launch attempts must expose a distinct notification reason") + assert.Contains(t, s, "fullsend-authorization-notice-", + "authorization notices must be serialized per work item") + assert.Contains(t, s, "fullsend:authorization-denied:", + "authorization notices must use the shared first-denial marker") + assert.Contains(t, s, "fullsend:dispatch-paused:", + "kill-switch notices must use a distinct first-pause marker") + assert.Regexp(t, `route:\n(?s:.*?)permissions:\n\s+contents: read\n\s+issues: read`, s, + "route must retain least-privilege issue read access") + assert.Regexp(t, `authorization-notice:\n(?s:.*?)permissions:\n\s+issues: write`, s, + "only the notification job needs issue-comment write access") + assert.Contains(t, s, "harness-dispatch:\n name: Harness dispatch\n if: ${{ inputs.matrix == '' }}", + "CEL dispatch must remain enabled for legacy slash-command events") + assert.Contains(t, s, "needs.route.outputs.authorization_number || needs.harness-dispatch.outputs.authorization_number", + "notification concurrency must use the CEL fallback work-item number") + assert.Contains(t, s, "needs.route.outputs.stage == ''", + "a CEL denial must remain visible when a legacy command is applicable but its stage is unavailable") + assert.Contains(t, s, "needs.route.outputs.authorization_check_failed == 'true'", + "a failed legacy permission lookup must not suppress a confirmed CEL denial") + assert.Contains(t, s, `if [[ -z "${REQUESTED_STAGE}" && -n "${STAGE}" ]]`, + "automatic routes must pass through the same stage availability checks as slash commands") assert.Contains(t, s, "has_repo_permission", "permission helper should be parameterized by min role") @@ -964,12 +988,12 @@ func TestDispatchPerStageAuthorization(t *testing.T) { "triage arm must return explicitly (not rely on [[ ]] exit status)") // Observation slash commands (triage min level) - assert.Regexp(t, `/fs-triage\)\s*\n\s+if \[\[ "\$\{COMMENT_USER_TYPE\}" != "Bot" \]\] && is_authorized triage;`, s) - assert.Regexp(t, `is_authorized triage; then\s*\n\s+STAGE="review"`, s) + assert.Contains(t, s, "set_command_stage triage triage") + assert.Contains(t, s, "set_command_stage review triage") // Mutation slash commands stay at write+ (default is_authorized) - assert.Regexp(t, `is_authorized; then\s*\n\s+STAGE="code"`, s) - assert.Regexp(t, `is_authorized; then\s*\n\s+STAGE="fix"`, s) + assert.Contains(t, s, "set_command_stage code") + assert.Contains(t, s, "set_command_stage fix") // Auto-triage and auto-review event paths accept triage assert.Contains(t, s, `is_event_actor_authorized "${ISSUE_USER_LOGIN}" triage`) diff --git a/pkg/behaviourtest/steps/actors.go b/pkg/behaviourtest/steps/actors.go index 0de5a6df6d..1b2ffdcea1 100644 --- a/pkg/behaviourtest/steps/actors.go +++ b/pkg/behaviourtest/steps/actors.go @@ -3,6 +3,7 @@ package steps import ( "context" "fmt" + "strings" "time" "github.com/cucumber/godog" @@ -30,6 +31,9 @@ func registerActorSteps(sc *godog.ScenarioContext) { sc.Step(`^the comment "([^"]+)" on the issue is authored by the (`+actorAlternation+`)$`, func(ctx context.Context, body, actor string) (context.Context, error) { return ctx, thenIssueCommentAuthoredBy(world.FromContext(ctx), body, actor) }) + sc.Step(`^the issue has a comment containing "([^"]+)"$`, func(ctx context.Context, fragment string) (context.Context, error) { + return ctx, thenIssueCommentContains(world.FromContext(ctx), fragment) + }) } // actorIdentity returns the SCM driver and login of a human-like test @@ -131,3 +135,20 @@ func thenIssueCommentAuthoredBy(w *world.World, body, actor string) error { } return nil } + +func thenIssueCommentContains(w *world.World, fragment string) error { + if w.IssueNumber == 0 { + return fmt.Errorf("no issue created") + } + comments, err := w.SCM.ListComments(context.Background(), + w.RepoOwner, w.RepoName, w.IssueNumber) + if err != nil { + return fmt.Errorf("listing comments on issue #%d: %w", w.IssueNumber, err) + } + for _, comment := range comments { + if strings.Contains(comment.Body, fragment) { + return nil + } + } + return fmt.Errorf("no comment on issue #%d contains %q", w.IssueNumber, fragment) +} diff --git a/pkg/behaviourtest/steps/actors_test.go b/pkg/behaviourtest/steps/actors_test.go index b1b5ec34d9..1e4c4034fd 100644 --- a/pkg/behaviourtest/steps/actors_test.go +++ b/pkg/behaviourtest/steps/actors_test.go @@ -195,6 +195,36 @@ func TestThenIssueCommentAuthoredBy(t *testing.T) { }) } +func TestThenIssueCommentContains(t *testing.T) { + t.Parallel() + + newWorld := func(comments []forge.IssueComment, listErr error) *world.World { + w, drivers := actorWorld() + w.IssueNumber = 7 + drivers["default"].comments = comments + drivers["default"].listErr = listErr + return w + } + + t.Run("fragment found", func(t *testing.T) { + t.Parallel() + w := newWorld([]forge.IssueComment{{Body: "agent launch was blocked because you are not authorized"}}, nil) + require.NoError(t, thenIssueCommentContains(w, "not authorized")) + }) + + t.Run("fragment missing", func(t *testing.T) { + t.Parallel() + w := newWorld([]forge.IssueComment{{Body: "other"}}, nil) + require.ErrorContains(t, thenIssueCommentContains(w, "not authorized"), "no comment on issue #7 contains") + }) + + t.Run("list error", func(t *testing.T) { + t.Parallel() + w := newWorld(nil, errors.New("HTTP 502")) + require.ErrorContains(t, thenIssueCommentContains(w, "not authorized"), "listing comments on issue #7") + }) +} + func TestWhenIssueOpenedForOwnersAuth_SelectsDriver(t *testing.T) { t.Parallel()