From 98ab8268efb05bb916a6865893a77bf14c245e3f Mon Sep 17 00:00:00 2001 From: Barak Korren Date: Thu, 8 Oct 2026 14:24:54 +0300 Subject: [PATCH 01/15] ci(#7555): notify users when agent launch is unauthorized Add first-denial notices for legacy slash commands and CEL dispatch while preserving shared authorization behavior. Signed-off-by: Barak Korren Assisted-by: Codex (gpt-5.6-sol) --- .github/workflows/reusable-dispatch.yml | 79 ++++++++++++++++- docs/guides/user/cel-triggers-reference.md | 2 +- internal/cli/dispatch.go | 14 +++- .../harnessdispatch/authorization_comment.go | 64 ++++++++++++++ .../authorization_comment_test.go | 84 +++++++++++++++++++ internal/harnessdispatch/core.go | 33 ++++++-- internal/harnessdispatch/core_test.go | 5 ++ .../scaffold/workflow_call_alignment_test.go | 10 ++- 8 files changed, 276 insertions(+), 15 deletions(-) create mode 100644 internal/harnessdispatch/authorization_comment.go create mode 100644 internal/harnessdispatch/authorization_comment_test.go diff --git a/.github/workflows/reusable-dispatch.yml b/.github/workflows/reusable-dispatch.yml index c293a9595a..d3825d23ac 100644 --- a/.github/workflows/reusable-dispatch.yml +++ b/.github/workflows/reusable-dispatch.yml @@ -107,12 +107,15 @@ jobs: runs-on: ${{ inputs.runner_image }} permissions: contents: read - issues: read + issues: write pull-requests: read outputs: stage: ${{ steps.role-check.outputs.skipped != 'true' && steps.agent-check.outputs.skipped != 'true' && steps.pr-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.route.outputs.authorization_denied || 'false' }} + authorization_actor: ${{ steps.route.outputs.authorization_actor || '' }} + authorization_number: ${{ steps.route.outputs.authorization_number || '' }} steps: - name: Validate event_action if: ${{ inputs.event_action == '' }} @@ -145,6 +148,7 @@ jobs: COMMENT_BODY: ${{ github.event.comment.body }} COMMENT_USER_TYPE: ${{ github.event.comment.user.type }} COMMENT_USER_LOGIN: ${{ github.event.comment.user.login }} + ISSUE_NUMBER: ${{ github.event.issue.number }} ISSUE_LABELS: ${{ join(github.event.issue.labels.*.name, ',') }} PR_LABELS: ${{ join(github.event.pull_request.labels.*.name, ',') }} @@ -165,6 +169,7 @@ jobs: STAGE="" TRIGGER_SOURCE="" + AUTH_CHECK_FAILED=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, @@ -236,6 +241,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" \ @@ -253,6 +259,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 } @@ -291,16 +298,20 @@ 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) + COMMAND_APPLICABLE=true if [[ "${COMMENT_USER_TYPE}" != "Bot" ]] && is_authorized triage; then STAGE="triage" fi ;; /fs-code) if [[ "${ISSUE_IS_PR}" == "false" ]]; then + COMMAND_APPLICABLE=true if [[ "${COMMENT_USER_TYPE}" != "Bot" ]] && is_authorized; then STAGE="code" fi @@ -308,6 +319,7 @@ jobs: ;; /fs-review) if [[ "${ISSUE_IS_PR}" == "true" ]]; then + COMMAND_APPLICABLE=true if [[ "${COMMENT_USER_TYPE}" != "Bot" ]] && is_authorized triage; then STAGE="review" fi @@ -315,6 +327,7 @@ jobs: ;; /fs-fix) if [[ "${ISSUE_IS_PR}" == "true" ]]; then + COMMAND_APPLICABLE=true if [[ "${COMMENT_USER_TYPE}" != "Bot" ]] && is_authorized; then STAGE="fix" TRIGGER_SOURCE="${COMMENT_USER_LOGIN}" @@ -322,11 +335,13 @@ jobs: fi ;; /fs-retro) + COMMAND_APPLICABLE=true if [[ "${COMMENT_USER_TYPE}" != "Bot" ]] && is_authorized; then STAGE="retro" fi ;; /fs-prioritize) + COMMAND_APPLICABLE=true if [[ "${COMMENT_USER_TYPE}" != "Bot" ]] && is_authorized; then STAGE="prioritize" fi @@ -411,6 +426,21 @@ jobs: ;; esac + # Keep legacy slash-command denial visible without turning + # unrelated comments, bot comments, or inapplicable commands into + # authorization notices. The CEL path posts the same marker from + # the fullsend binary when its shared gate denies the event. + if [[ "${EVENT_NAME}" == "issue_comment" \ + && "${COMMENT_USER_TYPE}" != "Bot" \ + && "${COMMAND_APPLICABLE}" == "true" \ + && -z "${STAGE}" \ + && "${AUTH_CHECK_FAILED}" != "true" ]]; then + echo "::notice::User ${COMMENT_USER_LOGIN} is not authorized to launch the requested agent" + echo "authorization_denied=true" >> "${GITHUB_OUTPUT}" + echo "authorization_actor=${COMMENT_USER_LOGIN}" >> "${GITHUB_OUTPUT}" + echo "authorization_number=${ISSUE_NUMBER}" >> "${GITHUB_OUTPUT}" + fi + if [[ -z "${STAGE}" ]]; then echo "No stage matched — skipping dispatch" echo "stage=" >> "${GITHUB_OUTPUT}" @@ -668,6 +698,52 @@ jobs: echo "${DELIM}" } >> "${GITHUB_OUTPUT}" + authorization-notice: + name: Authorization notice + needs: route + if: needs.route.outputs.authorization_denied == 'true' + runs-on: ${{ inputs.runner_image }} + timeout-minutes: 5 + permissions: + issues: write + concurrency: + group: fullsend-authorization-notice-${{ github.repository }}-${{ needs.route.outputs.authorization_number }} + cancel-in-progress: false + env: + GH_TOKEN: ${{ github.token }} + REPOSITORY: ${{ github.repository }} + ISSUE_NUMBER: ${{ needs.route.outputs.authorization_number }} + ACTOR_LOGIN: ${{ needs.route.outputs.authorization_actor }} + steps: + - 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 + + MARKER="" + COMMENTS="$(gh api "repos/${REPOSITORY}/issues/${ISSUE_NUMBER}/comments" --paginate --jq '.[].body')" || { + echo "::warning::Could not inspect existing authorization-denial comments" + exit 0 + } + if grep -Fq "${MARKER}" <<<"${COMMENTS}"; then + echo "Authorization-denial comment already exists for ${ACTOR_LOGIN}" + exit 0 + fi + + BODY="${MARKER} + + @${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." + gh api "repos/${REPOSITORY}/issues/${ISSUE_NUMBER}/comments" \ + -f body="${BODY}" >/dev/null + triage: name: Triage needs: route @@ -1524,6 +1600,7 @@ jobs: permissions: actions: write contents: read + issues: write pull-requests: read outputs: matrix: ${{ steps.dispatch.outputs.matrix }} diff --git a/docs/guides/user/cel-triggers-reference.md b/docs/guides/user/cel-triggers-reference.md index 19645b353f..ef61de64ab 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/internal/cli/dispatch.go b/internal/cli/dispatch.go index 26be77fe5d..ddc9b29528 100644 --- a/internal/cli/dispatch.go +++ b/internal/cli/dispatch.go @@ -103,17 +103,25 @@ 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 } + if result.AuthorizationDenied { + if err := harnessdispatch.AuthorizationDeniedComment(ctx, client, event); err != nil { + // Authorization remains denied even if the explanatory comment cannot + // be posted. Keep the dispatch matrix empty and surface the best-effort + // notification failure in the Actions log. + fmt.Fprintf(os.Stderr, "::warning::could not post authorization-denial comment: %v\n", 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: diff --git a/internal/harnessdispatch/authorization_comment.go b/internal/harnessdispatch/authorization_comment.go new file mode 100644 index 0000000000..28ca543295 --- /dev/null +++ b/internal/harnessdispatch/authorization_comment.go @@ -0,0 +1,64 @@ +package harnessdispatch + +import ( + "context" + "fmt" + "strings" + + "github.com/fullsend-ai/fullsend/internal/forge" + "github.com/fullsend-ai/fullsend/internal/normevent" +) + +const authorizationDeniedMarkerPrefix = "" +} + +func validGitHubLogin(login string) bool { + for _, r := range login { + if (r < 'A' || r > 'Z') && (r < 'a' || r > 'z') && (r < '0' || r > '9') && r != '_' && r != '-' { + return false + } + } + return login != "" +} diff --git a/internal/harnessdispatch/authorization_comment_test.go b/internal/harnessdispatch/authorization_comment_test.go new file mode 100644 index 0000000000..2cc5ba88ec --- /dev/null +++ b/internal/harnessdispatch/authorization_comment_test.go @@ -0,0 +1,84 @@ +package harnessdispatch + +import ( + "context" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/fullsend-ai/fullsend/internal/forge" + "github.com/fullsend-ai/fullsend/internal/normevent" +) + +func TestAuthorizationDeniedCommentCreatesOncePerActor(t *testing.T) { + client := forge.NewFakeClient() + event := &normevent.Event{ + Repo: "acme/widgets", + Entity: normevent.Entity{Kind: normevent.EntityWorkItem, ID: 42, URL: "https://github.com/acme/widgets/issues/42"}, + Actor: normevent.Actor{ID: "external-user", Kind: normevent.ActorHuman, Role: normevent.RoleNone}, + Source: normevent.Source{System: normevent.SystemGitHub, RawType: "issue_comment"}, + } + + require.NoError(t, AuthorizationDeniedComment(context.Background(), client, event)) + require.NoError(t, AuthorizationDeniedComment(context.Background(), client, event)) + + comments := client.IssueComments["acme/widgets/42"] + require.Len(t, comments, 1) + assert.Contains(t, comments[0].Body, "") + assert.Contains(t, comments[0].Body, "@external-user") +} + +func TestAuthorizationDeniedCommentSeparatesActors(t *testing.T) { + client := forge.NewFakeClient() + event := &normevent.Event{ + Repo: "acme/widgets", + Entity: normevent.Entity{Kind: normevent.EntityChangeProposal, ID: 7, URL: "https://github.com/acme/widgets/pull/7"}, + Actor: normevent.Actor{ID: "first-user", Kind: normevent.ActorHuman, Role: normevent.RoleNone}, + Source: normevent.Source{System: normevent.SystemGitHub, RawType: "pull_request_target"}, + } + + require.NoError(t, AuthorizationDeniedComment(context.Background(), client, event)) + event.Actor.ID = "second-user" + require.NoError(t, AuthorizationDeniedComment(context.Background(), client, event)) + + comments := client.IssueComments["acme/widgets/7"] + require.Len(t, comments, 2) + assert.Contains(t, comments[0].Body, "first-user") + assert.Contains(t, comments[1].Body, "second-user") +} + +func TestAuthorizationDeniedCommentIgnoresNonHumanOrNonGitHub(t *testing.T) { + for _, tc := range []struct { + name string + kind normevent.ActorKind + system normevent.SourceSystem + }{ + {name: "bot", kind: normevent.ActorBot, system: normevent.SystemGitHub}, + {name: "gitlab", kind: normevent.ActorHuman, system: normevent.SystemGitLab}, + } { + t.Run(tc.name, func(t *testing.T) { + client := forge.NewFakeClient() + event := &normevent.Event{ + Repo: "acme/widgets", + Entity: normevent.Entity{Kind: normevent.EntityWorkItem, ID: 42, URL: "https://example.test/42"}, + Actor: normevent.Actor{ID: "actor", Kind: tc.kind, Role: normevent.RoleNone}, + Source: normevent.Source{System: tc.system, RawType: "issue"}, + } + require.NoError(t, AuthorizationDeniedComment(context.Background(), client, event)) + assert.Empty(t, client.IssueComments) + }) + } +} + +func TestAuthorizationDeniedCommentIgnoresInvalidLogin(t *testing.T) { + client := forge.NewFakeClient() + event := &normevent.Event{ + Repo: "acme/widgets", + Entity: normevent.Entity{Kind: normevent.EntityWorkItem, ID: 42, URL: "https://github.com/acme/widgets/issues/42"}, + Actor: normevent.Actor{ID: "untrusted\nlogin", Kind: normevent.ActorHuman, Role: normevent.RoleNone}, + Source: normevent.Source{System: normevent.SystemGitHub, RawType: "issue_comment"}, + } + require.NoError(t, AuthorizationDeniedComment(context.Background(), client, event)) + assert.Empty(t, client.IssueComments) +} diff --git a/internal/harnessdispatch/core.go b/internal/harnessdispatch/core.go index f28d86bda8..eb617a3af2 100644 --- a/internal/harnessdispatch/core.go +++ b/internal/harnessdispatch/core.go @@ -26,23 +26,38 @@ type Options struct { FetchPolicy *fetch.FetchPolicy } +// Result describes a dispatch evaluation. AuthorizationDenied is set when +// the shared authorization gate rejected the event before any harness could +// run; kill-switch and no-trigger results leave it false. +type Result struct { + Refs []ExecutionRef + AuthorizationDenied bool +} + // 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 + return Result{}, nil } // Compute the effective role for the auth gate without mutating the @@ -66,17 +81,17 @@ func Dispatch(ctx context.Context, opts Options) ([]ExecutionRef, error) { authCheck := *opts.Event authCheck.Actor.Role = effectiveRole if !IsAuthorized(&authCheck) { - return nil, nil + return Result{AuthorizationDenied: true}, nil } candidates, err := ListTriggeredHarnesses(ctx, opts.ConfigDir, dirCfg, opts.FetchPolicy) if err != nil { - return nil, err + return Result{}, err } matched, err := MatchHarnesses(candidates, opts.Event) if err != nil { - return nil, err + return Result{}, err } var refs []ExecutionRef @@ -84,9 +99,9 @@ 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}, nil } diff --git a/internal/harnessdispatch/core_test.go b/internal/harnessdispatch/core_test.go index 80ac24c793..d3d7ee0afb 100644 --- a/internal/harnessdispatch/core_test.go +++ b/internal/harnessdispatch/core_test.go @@ -38,6 +38,11 @@ func TestDispatch_AuthDeny(t *testing.T) { assert.Empty(t, refs) } +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) { dir := t.TempDir() writeHarnessConfig(t, dir, issuePingHarnessYAML()) diff --git a/internal/scaffold/workflow_call_alignment_test.go b/internal/scaffold/workflow_call_alignment_test.go index 5244dc218d..a5168511e2 100644 --- a/internal/scaffold/workflow_call_alignment_test.go +++ b/internal/scaffold/workflow_call_alignment_test.go @@ -787,6 +787,14 @@ 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, "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, "issues: write", + "the route and notification jobs need issue-comment write access") assert.Contains(t, s, "has_repo_permission", "permission helper should be parameterized by min role") @@ -794,7 +802,7 @@ 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, `/fs-triage\)\s*\n(?:\s+COMMAND_APPLICABLE=true\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) // Mutation slash commands stay at write+ (default is_authorized) From 6d7ac36b72b0955b87d2a343e5e2a06d25afd32a Mon Sep 17 00:00:00 2001 From: Barak Korren Date: Thu, 8 Oct 2026 15:18:07 +0300 Subject: [PATCH 02/15] fix(#7555): scope authorization denial notices Notify only for confirmed, applicable launch denials and centralize comment creation in the workflow. Signed-off-by: Barak Korren Assisted-by: Codex (gpt-5.6-sol) --- .github/workflows/reusable-dispatch.yml | 26 +++--- internal/cli/dispatch.go | 41 +++++++-- internal/cli/dispatch_test.go | 42 ++++++++++ .../harnessdispatch/authorization_comment.go | 64 -------------- .../authorization_comment_test.go | 84 ------------------- internal/harnessdispatch/core.go | 24 ++++-- internal/harnessdispatch/core_test.go | 33 +++++++- internal/harnessdispatch/input/ghaevent.go | 12 +++ .../harnessdispatch/input/ghaevent_test.go | 27 ++++++ internal/normevent/event.go | 20 +++++ internal/normevent/event_test.go | 12 +++ .../scaffold/workflow_call_alignment_test.go | 8 +- 12 files changed, 220 insertions(+), 173 deletions(-) delete mode 100644 internal/harnessdispatch/authorization_comment.go delete mode 100644 internal/harnessdispatch/authorization_comment_test.go diff --git a/.github/workflows/reusable-dispatch.yml b/.github/workflows/reusable-dispatch.yml index d3825d23ac..0e00054d69 100644 --- a/.github/workflows/reusable-dispatch.yml +++ b/.github/workflows/reusable-dispatch.yml @@ -107,7 +107,7 @@ jobs: runs-on: ${{ inputs.runner_image }} permissions: contents: read - issues: write + issues: read pull-requests: read outputs: stage: ${{ steps.role-check.outputs.skipped != 'true' && steps.agent-check.outputs.skipped != 'true' && steps.pr-check.outputs.skipped != 'true' && steps.route.outputs.stage || '' }} @@ -116,6 +116,7 @@ jobs: authorization_denied: ${{ steps.route.outputs.authorization_denied || 'false' }} authorization_actor: ${{ steps.route.outputs.authorization_actor || '' }} authorization_number: ${{ steps.route.outputs.authorization_number || '' }} + legacy_command_applicable: ${{ steps.route.outputs.command_applicable || 'false' }} steps: - name: Validate event_action if: ${{ inputs.event_action == '' }} @@ -428,8 +429,8 @@ jobs: # Keep legacy slash-command denial visible without turning # unrelated comments, bot comments, or inapplicable commands into - # authorization notices. The CEL path posts the same marker from - # the fullsend binary when its shared gate denies the event. + # authorization notices. The CEL path exposes the same denial + # metadata through the fullsend dispatch step. if [[ "${EVENT_NAME}" == "issue_comment" \ && "${COMMENT_USER_TYPE}" != "Bot" \ && "${COMMAND_APPLICABLE}" == "true" \ @@ -444,12 +445,14 @@ jobs: if [[ -z "${STAGE}" ]]; then echo "No stage matched — skipping dispatch" echo "stage=" >> "${GITHUB_OUTPUT}" + echo "command_applicable=${COMMAND_APPLICABLE}" >> "${GITHUB_OUTPUT}" exit 0 fi echo "Routed to stage: ${STAGE}" echo "stage=${STAGE}" >> "${GITHUB_OUTPUT}" echo "trigger_source=${TRIGGER_SOURCE}" >> "${GITHUB_OUTPUT}" + echo "command_applicable=${COMMAND_APPLICABLE}" >> "${GITHUB_OUTPUT}" - name: Check for existing PRs id: pr-check @@ -700,8 +703,8 @@ jobs: authorization-notice: name: Authorization notice - needs: route - if: needs.route.outputs.authorization_denied == 'true' + needs: [route, harness-dispatch] + if: ${{ always() && !cancelled() && (needs.route.outputs.authorization_denied == 'true' || needs.harness-dispatch.outputs.authorization_denied == 'true') }} runs-on: ${{ inputs.runner_image }} timeout-minutes: 5 permissions: @@ -712,8 +715,8 @@ jobs: env: GH_TOKEN: ${{ github.token }} REPOSITORY: ${{ github.repository }} - ISSUE_NUMBER: ${{ needs.route.outputs.authorization_number }} - ACTOR_LOGIN: ${{ needs.route.outputs.authorization_actor }} + 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 }} steps: - name: Create first-denial comment shell: bash @@ -729,7 +732,7 @@ jobs: fi MARKER="" - COMMENTS="$(gh api "repos/${REPOSITORY}/issues/${ISSUE_NUMBER}/comments" --paginate --jq '.[].body')" || { + COMMENTS="$(gh api "repos/${REPOSITORY}/issues/${ISSUE_NUMBER}/comments" --paginate --jq '.[] | select(.user.login == "github-actions[bot]") | .body')" || { echo "::warning::Could not inspect existing authorization-denial comments" exit 0 } @@ -1595,15 +1598,18 @@ jobs: harness-dispatch: name: Harness dispatch - if: ${{ inputs.matrix == '' }} + needs: route + if: ${{ inputs.matrix == '' && needs.route.outputs.legacy_command_applicable != 'true' }} runs-on: ${{ inputs.runner_image }} permissions: actions: write contents: read - issues: write pull-requests: read outputs: matrix: ${{ steps.dispatch.outputs.matrix }} + authorization_denied: ${{ steps.dispatch.outputs.authorization_denied || 'false' }} + authorization_actor: ${{ steps.dispatch.outputs.authorization_actor || '' }} + authorization_number: ${{ steps.dispatch.outputs.authorization_number || '' }} steps: - name: Validate event_action if: ${{ inputs.event_action == '' }} diff --git a/internal/cli/dispatch.go b/internal/cli/dispatch.go index ddc9b29528..073ce1be33 100644 --- a/internal/cli/dispatch.go +++ b/internal/cli/dispatch.go @@ -110,12 +110,9 @@ func runDispatch(ctx context.Context, opts dispatchOpts) error { if err != nil { return err } - if result.AuthorizationDenied { - if err := harnessdispatch.AuthorizationDeniedComment(ctx, client, event); err != nil { - // Authorization remains denied even if the explanatory comment cannot - // be posted. Keep the dispatch matrix empty and surface the best-effort - // notification failure in the Actions log. - fmt.Fprintf(os.Stderr, "::warning::could not post authorization-denial comment: %v\n", err) + if inDriver == "gha-event" { + if err := writeAuthorizationOutput(event, result.AuthorizationDenied); err != nil { + return err } } @@ -140,3 +137,35 @@ func runDispatch(ctx context.Context, opts dispatchOpts) error { } return nil } + +func writeAuthorizationOutput(event *normevent.Event, denied bool) error { + if event == nil || event.Actor.Kind != normevent.ActorHuman || !denied { + return nil + } + path := os.Getenv("GITHUB_OUTPUT") + if path == "" || event.Entity.ID < 1 || !validGitHubLogin(event.Actor.ID) { + return nil + } + + f, err := os.OpenFile(path, os.O_WRONLY|os.O_APPEND, 0o600) + if err != nil { + return fmt.Errorf("open GitHub output file: %w", err) + } + defer f.Close() + if _, err := fmt.Fprintf(f, "authorization_denied=true\nauthorization_actor=%s\nauthorization_number=%d\n", event.Actor.ID, event.Entity.ID); err != nil { + return fmt.Errorf("write authorization output: %w", err) + } + return nil +} + +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..37dd490421 100644 --- a/internal/cli/dispatch_test.go +++ b/internal/cli/dispatch_test.go @@ -14,8 +14,50 @@ import ( "gopkg.in/yaml.v3" "github.com/fullsend-ai/fullsend/internal/config" + "github.com/fullsend-ai/fullsend/internal/normevent" ) +func TestWriteAuthorizationOutput(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", Kind: normevent.ActorHuman}, + } + + require.NoError(t, writeAuthorizationOutput(event, true)) + data, err := os.ReadFile(path) + require.NoError(t, err) + assert.Equal(t, "authorization_denied=true\nauthorization_actor=alice\nauthorization_number=42\n", string(data)) +} + +func TestWriteAuthorizationOutputSkipsNonDeniedOrNonHuman(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", Kind: normevent.ActorHuman}}, + {Entity: normevent.Entity{ID: 42}, Actor: normevent.Actor{ID: "agent[bot]", Kind: normevent.ActorBot}}, + } { + require.NoError(t, writeAuthorizationOutput(event, false)) + } + _, err := os.Stat(path) + assert.ErrorIs(t, err, os.ErrNotExist) +} + +func TestWriteAuthorizationOutputSkipsInvalidLogin(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", Kind: normevent.ActorHuman}, + } + + require.NoError(t, writeAuthorizationOutput(event, true)) + _, err := os.Stat(path) + assert.ErrorIs(t, err, os.ErrNotExist) +} + func TestRunDispatch_JSONDriver(t *testing.T) { dir := t.TempDir() writeDispatchFixture(t, dir) diff --git a/internal/harnessdispatch/authorization_comment.go b/internal/harnessdispatch/authorization_comment.go deleted file mode 100644 index 28ca543295..0000000000 --- a/internal/harnessdispatch/authorization_comment.go +++ /dev/null @@ -1,64 +0,0 @@ -package harnessdispatch - -import ( - "context" - "fmt" - "strings" - - "github.com/fullsend-ai/fullsend/internal/forge" - "github.com/fullsend-ai/fullsend/internal/normevent" -) - -const authorizationDeniedMarkerPrefix = "" -} - -func validGitHubLogin(login string) bool { - for _, r := range login { - if (r < 'A' || r > 'Z') && (r < 'a' || r > 'z') && (r < '0' || r > '9') && r != '_' && r != '-' { - return false - } - } - return login != "" -} diff --git a/internal/harnessdispatch/authorization_comment_test.go b/internal/harnessdispatch/authorization_comment_test.go deleted file mode 100644 index 2cc5ba88ec..0000000000 --- a/internal/harnessdispatch/authorization_comment_test.go +++ /dev/null @@ -1,84 +0,0 @@ -package harnessdispatch - -import ( - "context" - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - "github.com/fullsend-ai/fullsend/internal/forge" - "github.com/fullsend-ai/fullsend/internal/normevent" -) - -func TestAuthorizationDeniedCommentCreatesOncePerActor(t *testing.T) { - client := forge.NewFakeClient() - event := &normevent.Event{ - Repo: "acme/widgets", - Entity: normevent.Entity{Kind: normevent.EntityWorkItem, ID: 42, URL: "https://github.com/acme/widgets/issues/42"}, - Actor: normevent.Actor{ID: "external-user", Kind: normevent.ActorHuman, Role: normevent.RoleNone}, - Source: normevent.Source{System: normevent.SystemGitHub, RawType: "issue_comment"}, - } - - require.NoError(t, AuthorizationDeniedComment(context.Background(), client, event)) - require.NoError(t, AuthorizationDeniedComment(context.Background(), client, event)) - - comments := client.IssueComments["acme/widgets/42"] - require.Len(t, comments, 1) - assert.Contains(t, comments[0].Body, "") - assert.Contains(t, comments[0].Body, "@external-user") -} - -func TestAuthorizationDeniedCommentSeparatesActors(t *testing.T) { - client := forge.NewFakeClient() - event := &normevent.Event{ - Repo: "acme/widgets", - Entity: normevent.Entity{Kind: normevent.EntityChangeProposal, ID: 7, URL: "https://github.com/acme/widgets/pull/7"}, - Actor: normevent.Actor{ID: "first-user", Kind: normevent.ActorHuman, Role: normevent.RoleNone}, - Source: normevent.Source{System: normevent.SystemGitHub, RawType: "pull_request_target"}, - } - - require.NoError(t, AuthorizationDeniedComment(context.Background(), client, event)) - event.Actor.ID = "second-user" - require.NoError(t, AuthorizationDeniedComment(context.Background(), client, event)) - - comments := client.IssueComments["acme/widgets/7"] - require.Len(t, comments, 2) - assert.Contains(t, comments[0].Body, "first-user") - assert.Contains(t, comments[1].Body, "second-user") -} - -func TestAuthorizationDeniedCommentIgnoresNonHumanOrNonGitHub(t *testing.T) { - for _, tc := range []struct { - name string - kind normevent.ActorKind - system normevent.SourceSystem - }{ - {name: "bot", kind: normevent.ActorBot, system: normevent.SystemGitHub}, - {name: "gitlab", kind: normevent.ActorHuman, system: normevent.SystemGitLab}, - } { - t.Run(tc.name, func(t *testing.T) { - client := forge.NewFakeClient() - event := &normevent.Event{ - Repo: "acme/widgets", - Entity: normevent.Entity{Kind: normevent.EntityWorkItem, ID: 42, URL: "https://example.test/42"}, - Actor: normevent.Actor{ID: "actor", Kind: tc.kind, Role: normevent.RoleNone}, - Source: normevent.Source{System: tc.system, RawType: "issue"}, - } - require.NoError(t, AuthorizationDeniedComment(context.Background(), client, event)) - assert.Empty(t, client.IssueComments) - }) - } -} - -func TestAuthorizationDeniedCommentIgnoresInvalidLogin(t *testing.T) { - client := forge.NewFakeClient() - event := &normevent.Event{ - Repo: "acme/widgets", - Entity: normevent.Entity{Kind: normevent.EntityWorkItem, ID: 42, URL: "https://github.com/acme/widgets/issues/42"}, - Actor: normevent.Actor{ID: "untrusted\nlogin", Kind: normevent.ActorHuman, Role: normevent.RoleNone}, - Source: normevent.Source{System: normevent.SystemGitHub, RawType: "issue_comment"}, - } - require.NoError(t, AuthorizationDeniedComment(context.Background(), client, event)) - assert.Empty(t, client.IssueComments) -} diff --git a/internal/harnessdispatch/core.go b/internal/harnessdispatch/core.go index eb617a3af2..688ab887e3 100644 --- a/internal/harnessdispatch/core.go +++ b/internal/harnessdispatch/core.go @@ -26,9 +26,9 @@ type Options struct { FetchPolicy *fetch.FetchPolicy } -// Result describes a dispatch evaluation. AuthorizationDenied is set when -// the shared authorization gate rejected the event before any harness could -// run; kill-switch and no-trigger results leave it false. +// 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 @@ -80,12 +80,19 @@ func DispatchResult(ctx context.Context, opts Options) (Result, error) { authCheck := *opts.Event authCheck.Actor.Role = effectiveRole - if !IsAuthorized(&authCheck) { - return Result{AuthorizationDenied: true}, nil + authorized := IsAuthorized(&authCheck) + if !authorized && !opts.Event.AuthorizationAvailable() { + return Result{}, nil } candidates, err := ListTriggeredHarnesses(ctx, opts.ConfigDir, dirCfg, opts.FetchPolicy) if err != nil { + // 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 !authorized { + return Result{}, nil + } return Result{}, err } @@ -94,6 +101,13 @@ func DispatchResult(ctx context.Context, opts Options) (Result, error) { return Result{}, err } + if !authorized { + if !opts.Event.AuthorizationAvailable() { + return Result{}, nil + } + return Result{AuthorizationDenied: len(matched) > 0}, nil + } + var refs []ExecutionRef for _, m := range matched { role := m.Harness.Role diff --git a/internal/harnessdispatch/core_test.go b/internal/harnessdispatch/core_test.go index d3d7ee0afb..5f1fd1f291 100644 --- a/internal/harnessdispatch/core_test.go +++ b/internal/harnessdispatch/core_test.go @@ -33,9 +33,38 @@ 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_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) { diff --git a/internal/harnessdispatch/input/ghaevent.go b/internal/harnessdispatch/input/ghaevent.go index 4b1db7ab5d..2c46cb7582 100644 --- a/internal/harnessdispatch/input/ghaevent.go +++ b/internal/harnessdispatch/input/ghaevent.go @@ -82,12 +82,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) } @@ -111,6 +113,9 @@ func mapGitHubWebhook(ctx context.Context, opts GHAEventOptions, raw map[string] Labels: []string{}, }, } + if authorizationUnavailable { + ev.MarkAuthorizationUnavailable() + } if action != "" { ev.Source.RawAction = action } @@ -293,16 +298,23 @@ func mapIssueCommentEvent(ctx context.Context, opts GHAEventOptions, raw map[str ev.Actor.Kind = normevent.ActorBot } if opts.Forge != nil && actorID != "" { + authorizationUnavailable := true 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) + authorizationUnavailable = false } else { log.Printf("harness dispatch: collaborator permission lookup failed for %s on %s: %v", actorID, opts.Repository, err) } } } + if authorizationUnavailable { + ev.MarkAuthorizationUnavailable() + } + } else { + ev.MarkAuthorizationUnavailable() } ev.Entity = entityFromIssue(issue) diff --git a/internal/harnessdispatch/input/ghaevent_test.go b/internal/harnessdispatch/input/ghaevent_test.go index c6f3a10331..843834c89a 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", diff --git a/internal/normevent/event.go b/internal/normevent/event.go index 7efd004333..9edcf4e3e3 100644 --- a/internal/normevent/event.go +++ b/internal/normevent/event.go @@ -16,6 +16,26 @@ 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. + 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. diff --git a/internal/normevent/event_test.go b/internal/normevent/event_test.go index 8f4b4e9e4d..afce505234 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 TestMapGitHubPermission(t *testing.T) { assert.Equal(t, RoleWrite, MapGitHubPermission("write")) assert.Equal(t, RoleNone, MapGitHubPermission("unknown")) diff --git a/internal/scaffold/workflow_call_alignment_test.go b/internal/scaffold/workflow_call_alignment_test.go index a5168511e2..6acd8f5ec1 100644 --- a/internal/scaffold/workflow_call_alignment_test.go +++ b/internal/scaffold/workflow_call_alignment_test.go @@ -793,8 +793,12 @@ func TestDispatchPerStageAuthorization(t *testing.T) { "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, "issues: write", - "the route and notification jobs need issue-comment write access") + 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.NotContains(t, s, "harness-dispatch:\n name: Harness dispatch\n if: ${{ inputs.matrix == '' }}\n runs-on: ${{ inputs.runner_image }}\n permissions:\n actions: write\n contents: read\n issues: write", + "harness dispatch must not receive issue-comment write access") assert.Contains(t, s, "has_repo_permission", "permission helper should be parameterized by min role") From fd9eefdf171291107afc1cb7d4553a2b88e03e0e Mon Sep 17 00:00:00 2001 From: Barak Korren Date: Thu, 8 Oct 2026 15:21:08 +0300 Subject: [PATCH 03/15] ci(#7555): satisfy workflow output lint Group related GITHUB_OUTPUT writes in the authorization route. Signed-off-by: Barak Korren Assisted-by: Codex (gpt-5.6-sol) --- .github/workflows/reusable-dispatch.yml | 22 ++++++++++++++-------- 1 file changed, 14 insertions(+), 8 deletions(-) diff --git a/.github/workflows/reusable-dispatch.yml b/.github/workflows/reusable-dispatch.yml index 0e00054d69..56b437e398 100644 --- a/.github/workflows/reusable-dispatch.yml +++ b/.github/workflows/reusable-dispatch.yml @@ -437,22 +437,28 @@ jobs: && -z "${STAGE}" \ && "${AUTH_CHECK_FAILED}" != "true" ]]; then echo "::notice::User ${COMMENT_USER_LOGIN} is not authorized to launch the requested agent" - echo "authorization_denied=true" >> "${GITHUB_OUTPUT}" - echo "authorization_actor=${COMMENT_USER_LOGIN}" >> "${GITHUB_OUTPUT}" - echo "authorization_number=${ISSUE_NUMBER}" >> "${GITHUB_OUTPUT}" + { + echo "authorization_denied=true" + echo "authorization_actor=${COMMENT_USER_LOGIN}" + echo "authorization_number=${ISSUE_NUMBER}" + } >> "${GITHUB_OUTPUT}" fi if [[ -z "${STAGE}" ]]; then echo "No stage matched — skipping dispatch" - echo "stage=" >> "${GITHUB_OUTPUT}" - echo "command_applicable=${COMMAND_APPLICABLE}" >> "${GITHUB_OUTPUT}" + { + echo "stage=" + echo "command_applicable=${COMMAND_APPLICABLE}" + } >> "${GITHUB_OUTPUT}" exit 0 fi echo "Routed to stage: ${STAGE}" - echo "stage=${STAGE}" >> "${GITHUB_OUTPUT}" - echo "trigger_source=${TRIGGER_SOURCE}" >> "${GITHUB_OUTPUT}" - echo "command_applicable=${COMMAND_APPLICABLE}" >> "${GITHUB_OUTPUT}" + { + echo "stage=${STAGE}" + echo "trigger_source=${TRIGGER_SOURCE}" + echo "command_applicable=${COMMAND_APPLICABLE}" + } >> "${GITHUB_OUTPUT}" - name: Check for existing PRs id: pr-check From e51d6c4efa74eff3c12b0fd3fa11e4ff730b911c Mon Sep 17 00:00:00 2001 From: Barak Korren Date: Sun, 11 Oct 2026 09:44:22 +0300 Subject: [PATCH 04/15] fix(#7555): preserve CEL dispatch for legacy commands Keep custom CEL evaluation independent while suppressing only conflicting denial notices from the legacy route. Signed-off-by: Barak Korren Assisted-by: Codex (gpt-5.6-sol) --- .github/workflows/reusable-dispatch.yml | 7 ++-- internal/cli/dispatch.go | 4 +- internal/harnessdispatch/core.go | 3 -- internal/harnessdispatch/input/ghaevent.go | 42 +------------------ internal/normevent/event.go | 3 ++ .../scaffold/workflow_call_alignment_test.go | 6 ++- 6 files changed, 15 insertions(+), 50 deletions(-) diff --git a/.github/workflows/reusable-dispatch.yml b/.github/workflows/reusable-dispatch.yml index 56b437e398..2e89289519 100644 --- a/.github/workflows/reusable-dispatch.yml +++ b/.github/workflows/reusable-dispatch.yml @@ -710,13 +710,13 @@ jobs: authorization-notice: name: Authorization notice needs: [route, harness-dispatch] - if: ${{ always() && !cancelled() && (needs.route.outputs.authorization_denied == 'true' || needs.harness-dispatch.outputs.authorization_denied == 'true') }} + if: ${{ always() && !cancelled() && (needs.route.outputs.authorization_denied == 'true' || (needs.harness-dispatch.outputs.authorization_denied == 'true' && needs.route.outputs.legacy_command_applicable != 'true')) }} runs-on: ${{ inputs.runner_image }} timeout-minutes: 5 permissions: issues: write concurrency: - group: fullsend-authorization-notice-${{ github.repository }}-${{ needs.route.outputs.authorization_number }} + group: fullsend-authorization-notice-${{ github.repository }}-${{ needs.route.outputs.authorization_number || needs.harness-dispatch.outputs.authorization_number }}-${{ needs.route.outputs.authorization_actor || needs.harness-dispatch.outputs.authorization_actor }} cancel-in-progress: false env: GH_TOKEN: ${{ github.token }} @@ -1604,8 +1604,7 @@ jobs: harness-dispatch: name: Harness dispatch - needs: route - if: ${{ inputs.matrix == '' && needs.route.outputs.legacy_command_applicable != 'true' }} + if: ${{ inputs.matrix == '' }} runs-on: ${{ inputs.runner_image }} permissions: actions: write diff --git a/internal/cli/dispatch.go b/internal/cli/dispatch.go index 073ce1be33..0063a390d3 100644 --- a/internal/cli/dispatch.go +++ b/internal/cli/dispatch.go @@ -110,6 +110,8 @@ func runDispatch(ctx context.Context, opts dispatchOpts) error { 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 := writeAuthorizationOutput(event, result.AuthorizationDenied); err != nil { return err @@ -147,7 +149,7 @@ func writeAuthorizationOutput(event *normevent.Event, denied bool) error { return nil } - f, err := os.OpenFile(path, os.O_WRONLY|os.O_APPEND, 0o600) + f, err := os.OpenFile(path, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0o600) if err != nil { return fmt.Errorf("open GitHub output file: %w", err) } diff --git a/internal/harnessdispatch/core.go b/internal/harnessdispatch/core.go index 688ab887e3..d338ee0769 100644 --- a/internal/harnessdispatch/core.go +++ b/internal/harnessdispatch/core.go @@ -102,9 +102,6 @@ func DispatchResult(ctx context.Context, opts Options) (Result, error) { } if !authorized { - if !opts.Event.AuthorizationAvailable() { - return Result{}, nil - } return Result{AuthorizationDenied: len(matched) > 0}, nil } diff --git a/internal/harnessdispatch/input/ghaevent.go b/internal/harnessdispatch/input/ghaevent.go index 2c46cb7582..c091b27a4b 100644 --- a/internal/harnessdispatch/input/ghaevent.go +++ b/internal/harnessdispatch/input/ghaevent.go @@ -128,7 +128,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) } @@ -268,54 +268,16 @@ 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 != "" { - authorizationUnavailable := true - 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) - authorizationUnavailable = false - } else { - log.Printf("harness dispatch: collaborator permission lookup failed for %s on %s: %v", actorID, opts.Repository, err) - } - } - } - if authorizationUnavailable { - ev.MarkAuthorizationUnavailable() - } - } else { - ev.MarkAuthorizationUnavailable() - } ev.Entity = entityFromIssue(issue) ev.Actor.IsEntityAuthor = strings.EqualFold(stringField(issue, "user", "login"), actorID) diff --git a/internal/normevent/event.go b/internal/normevent/event.go index 9edcf4e3e3..d74484717c 100644 --- a/internal/normevent/event.go +++ b/internal/normevent/event.go @@ -20,6 +20,9 @@ type Event struct { // 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 } diff --git a/internal/scaffold/workflow_call_alignment_test.go b/internal/scaffold/workflow_call_alignment_test.go index 6acd8f5ec1..0749dbd835 100644 --- a/internal/scaffold/workflow_call_alignment_test.go +++ b/internal/scaffold/workflow_call_alignment_test.go @@ -797,8 +797,10 @@ func TestDispatchPerStageAuthorization(t *testing.T) { "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.NotContains(t, s, "harness-dispatch:\n name: Harness dispatch\n if: ${{ inputs.matrix == '' }}\n runs-on: ${{ inputs.runner_image }}\n permissions:\n actions: write\n contents: read\n issues: write", - "harness dispatch must not receive 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, "has_repo_permission", "permission helper should be parameterized by min role") From 40cf55ec16db1c4dfcd3c63885e900b59a6ea162 Mon Sep 17 00:00:00 2001 From: Barak Korren Date: Sun, 11 Oct 2026 10:05:50 +0300 Subject: [PATCH 05/15] fix(#7555): preserve denial notices after partial auth failure Expose legacy permission lookup failure so a confirmed CEL denial is not suppressed, and reuse the shared GitHub output writer for authorization metadata. Signed-off-by: Barak Korren Assisted-by: Codex (gpt-5.6-sol) --- .github/workflows/reusable-dispatch.yml | 5 ++++- internal/cli/dispatch.go | 14 ++++++++------ internal/scaffold/workflow_call_alignment_test.go | 2 ++ 3 files changed, 14 insertions(+), 7 deletions(-) diff --git a/.github/workflows/reusable-dispatch.yml b/.github/workflows/reusable-dispatch.yml index 2e89289519..20a8f9a8d1 100644 --- a/.github/workflows/reusable-dispatch.yml +++ b/.github/workflows/reusable-dispatch.yml @@ -117,6 +117,7 @@ jobs: authorization_actor: ${{ steps.route.outputs.authorization_actor || '' }} authorization_number: ${{ steps.route.outputs.authorization_number || '' }} 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 == '' }} @@ -449,6 +450,7 @@ jobs: { echo "stage=" echo "command_applicable=${COMMAND_APPLICABLE}" + echo "authorization_check_failed=${AUTH_CHECK_FAILED}" } >> "${GITHUB_OUTPUT}" exit 0 fi @@ -458,6 +460,7 @@ jobs: echo "stage=${STAGE}" echo "trigger_source=${TRIGGER_SOURCE}" echo "command_applicable=${COMMAND_APPLICABLE}" + echo "authorization_check_failed=${AUTH_CHECK_FAILED}" } >> "${GITHUB_OUTPUT}" - name: Check for existing PRs @@ -710,7 +713,7 @@ jobs: authorization-notice: name: Authorization notice needs: [route, harness-dispatch] - if: ${{ always() && !cancelled() && (needs.route.outputs.authorization_denied == 'true' || (needs.harness-dispatch.outputs.authorization_denied == 'true' && needs.route.outputs.legacy_command_applicable != 'true')) }} + if: ${{ always() && !cancelled() && (needs.route.outputs.authorization_denied == 'true' || (needs.harness-dispatch.outputs.authorization_denied == 'true' && (needs.route.outputs.legacy_command_applicable != 'true' || needs.route.outputs.authorization_check_failed == 'true'))) }} runs-on: ${{ inputs.runner_image }} timeout-minutes: 5 permissions: diff --git a/internal/cli/dispatch.go b/internal/cli/dispatch.go index 0063a390d3..434a212244 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" @@ -149,13 +150,14 @@ func writeAuthorizationOutput(event *normevent.Event, denied bool) error { return nil } - f, err := os.OpenFile(path, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0o600) - if err != nil { - return fmt.Errorf("open GitHub output file: %w", err) + if err := writeGitHubOutput(path, "authorization_denied", "true"); err != nil { + return fmt.Errorf("write authorization output authorization_denied: %w", err) + } + if err := writeGitHubOutput(path, "authorization_actor", event.Actor.ID); err != nil { + return fmt.Errorf("write authorization output authorization_actor: %w", err) } - defer f.Close() - if _, err := fmt.Fprintf(f, "authorization_denied=true\nauthorization_actor=%s\nauthorization_number=%d\n", event.Actor.ID, event.Entity.ID); err != nil { - return fmt.Errorf("write authorization output: %w", err) + if err := writeGitHubOutput(path, "authorization_number", strconv.Itoa(event.Entity.ID)); err != nil { + return fmt.Errorf("write authorization output authorization_number: %w", err) } return nil } diff --git a/internal/scaffold/workflow_call_alignment_test.go b/internal/scaffold/workflow_call_alignment_test.go index 0749dbd835..f441901aac 100644 --- a/internal/scaffold/workflow_call_alignment_test.go +++ b/internal/scaffold/workflow_call_alignment_test.go @@ -801,6 +801,8 @@ func TestDispatchPerStageAuthorization(t *testing.T) { "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.authorization_check_failed == 'true'", + "a failed legacy permission lookup must not suppress a confirmed CEL denial") assert.Contains(t, s, "has_repo_permission", "permission helper should be parameterized by min role") From 181cba387a52b079518d2a6b71bc1bf83e22a8f5 Mon Sep 17 00:00:00 2001 From: Barak Korren Date: Sun, 11 Oct 2026 11:01:48 +0300 Subject: [PATCH 06/15] fix(#7555): align workflow and event mapping cleanup Use the repository timeout policy and rely on the normalized actor initialized by the common webhook mapper. Signed-off-by: Barak Korren Assisted-by: Codex (gpt-5.6-sol) --- .github/workflows/reusable-dispatch.yml | 1 - internal/harnessdispatch/input/ghaevent.go | 5 ----- 2 files changed, 6 deletions(-) diff --git a/.github/workflows/reusable-dispatch.yml b/.github/workflows/reusable-dispatch.yml index 20a8f9a8d1..cfef4d2722 100644 --- a/.github/workflows/reusable-dispatch.yml +++ b/.github/workflows/reusable-dispatch.yml @@ -715,7 +715,6 @@ jobs: needs: [route, harness-dispatch] if: ${{ always() && !cancelled() && (needs.route.outputs.authorization_denied == 'true' || (needs.harness-dispatch.outputs.authorization_denied == 'true' && (needs.route.outputs.legacy_command_applicable != 'true' || needs.route.outputs.authorization_check_failed == 'true'))) }} runs-on: ${{ inputs.runner_image }} - timeout-minutes: 5 permissions: issues: write concurrency: diff --git a/internal/harnessdispatch/input/ghaevent.go b/internal/harnessdispatch/input/ghaevent.go index c091b27a4b..7f2119001b 100644 --- a/internal/harnessdispatch/input/ghaevent.go +++ b/internal/harnessdispatch/input/ghaevent.go @@ -274,11 +274,6 @@ func mapIssueCommentEvent(ctx context.Context, opts GHAEventOptions, ev *normeve return nil, fmt.Errorf("issue_comment missing issue") } - sender := nestedMap(raw, "sender") - if strings.HasSuffix(strings.ToLower(actorID), "[bot]") || stringField(sender, "type") == "Bot" { - ev.Actor.Kind = normevent.ActorBot - } - ev.Entity = entityFromIssue(issue) ev.Actor.IsEntityAuthor = strings.EqualFold(stringField(issue, "user", "login"), actorID) ev.State.Labels = labelNames(issue) From 620ea410673a18efe0671ea61586affac6ecc09c Mon Sep 17 00:00:00 2001 From: Barak Korren Date: Sun, 11 Oct 2026 12:28:14 +0300 Subject: [PATCH 07/15] ci(#7555): harden authorization denial notices Route first-denial comments through the existing fullsend issues command, gate notices on actual stage availability, restrict CEL notices to explicit human slash commands, and deduplicate by immutable actor ID. Signed-off-by: Barak Korren Assisted-by: Codex (gpt-5.6-sol) --- .github/workflows/reusable-dispatch.yml | 231 ++++++++++++++---- docs/contributing/harness-fields.md | 6 + docs/normative/normalized-event/v1/README.md | 5 + .../v1/normalized-event.schema.json | 5 + internal/cli/dispatch.go | 34 ++- internal/cli/dispatch_test.go | 62 ++++- internal/harnessdispatch/input/ghaevent.go | 32 +++ .../input/ghaevent_internal_test.go | 34 +++ .../harnessdispatch/input/ghaevent_test.go | 3 +- internal/normevent/event.go | 1 + 10 files changed, 353 insertions(+), 60 deletions(-) create mode 100644 internal/harnessdispatch/input/ghaevent_internal_test.go diff --git a/.github/workflows/reusable-dispatch.yml b/.github/workflows/reusable-dispatch.yml index cfef4d2722..ad8d937918 100644 --- a/.github/workflows/reusable-dispatch.yml +++ b/.github/workflows/reusable-dispatch.yml @@ -110,12 +110,13 @@ jobs: issues: read pull-requests: read outputs: - stage: ${{ steps.role-check.outputs.skipped != 'true' && steps.agent-check.outputs.skipped != 'true' && steps.pr-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.pr-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.route.outputs.authorization_denied || 'false' }} - authorization_actor: ${{ steps.route.outputs.authorization_actor || '' }} - authorization_number: ${{ steps.route.outputs.authorization_number || '' }} + 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 || '' }} legacy_command_applicable: ${{ steps.route.outputs.command_applicable || 'false' }} authorization_check_failed: ${{ steps.route.outputs.authorization_check_failed || 'false' }} steps: @@ -150,6 +151,7 @@ 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, ',') }} @@ -170,6 +172,7 @@ jobs: set -euo pipefail STAGE="" + REQUESTED_STAGE="" TRIGGER_SOURCE="" AUTH_CHECK_FAILED=false @@ -310,6 +313,7 @@ jobs: if [[ "${COMMENT_USER_TYPE}" != "Bot" ]] && is_authorized triage; then STAGE="triage" fi + REQUESTED_STAGE="triage" ;; /fs-code) if [[ "${ISSUE_IS_PR}" == "false" ]]; then @@ -317,6 +321,7 @@ jobs: if [[ "${COMMENT_USER_TYPE}" != "Bot" ]] && is_authorized; then STAGE="code" fi + REQUESTED_STAGE="code" fi ;; /fs-review) @@ -325,6 +330,7 @@ jobs: if [[ "${COMMENT_USER_TYPE}" != "Bot" ]] && is_authorized triage; then STAGE="review" fi + REQUESTED_STAGE="review" fi ;; /fs-fix) @@ -334,6 +340,7 @@ jobs: STAGE="fix" TRIGGER_SOURCE="${COMMENT_USER_LOGIN}" fi + REQUESTED_STAGE="fix" fi ;; /fs-retro) @@ -341,12 +348,14 @@ jobs: if [[ "${COMMENT_USER_TYPE}" != "Bot" ]] && is_authorized; then STAGE="retro" fi + REQUESTED_STAGE="retro" ;; /fs-prioritize) COMMAND_APPLICABLE=true if [[ "${COMMENT_USER_TYPE}" != "Bot" ]] && is_authorized; then STAGE="prioritize" fi + REQUESTED_STAGE="prioritize" ;; *) ;; @@ -428,27 +437,11 @@ jobs: ;; esac - # Keep legacy slash-command denial visible without turning - # unrelated comments, bot comments, or inapplicable commands into - # authorization notices. The CEL path exposes the same denial - # metadata through the fullsend dispatch step. - if [[ "${EVENT_NAME}" == "issue_comment" \ - && "${COMMENT_USER_TYPE}" != "Bot" \ - && "${COMMAND_APPLICABLE}" == "true" \ - && -z "${STAGE}" \ - && "${AUTH_CHECK_FAILED}" != "true" ]]; then - 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_number=${ISSUE_NUMBER}" - } >> "${GITHUB_OUTPUT}" - fi - if [[ -z "${STAGE}" ]]; then echo "No stage matched — skipping dispatch" { echo "stage=" + echo "requested_stage=${REQUESTED_STAGE}" echo "command_applicable=${COMMAND_APPLICABLE}" echo "authorization_check_failed=${AUTH_CHECK_FAILED}" } >> "${GITHUB_OUTPUT}" @@ -458,6 +451,7 @@ jobs: echo "Routed to stage: ${STAGE}" { 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}" @@ -465,7 +459,7 @@ jobs: - name: Check for existing PRs id: pr-check - if: steps.route.outputs.stage == 'code' + if: steps.route.outputs.requested_stage == 'code' env: GH_TOKEN: ${{ github.token }} ISSUE_NUMBER: ${{ github.event.issue.number }} @@ -533,20 +527,22 @@ 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 if [[ -f .fullsend/config.yaml ]]; then KILL_SWITCH=$(yq '.kill_switch // false' .fullsend/config.yaml) if [[ "$KILL_SWITCH" == "true" ]]; then - echo "::error::Kill switch is active — all agent dispatch halted" - echo "::error::Set kill_switch: false in .fullsend/config.yaml to resume" - exit 1 + echo "::notice::Stage '${REQUESTED_STAGE}' skipped — kill switch is active" + echo "skipped=true" >> "${GITHUB_OUTPUT}" fi fi - name: Validate agents config - if: steps.route.outputs.stage != '' + if: steps.route.outputs.requested_stage != '' && steps.kill-switch.outputs.skipped != 'true' run: | set -euo pipefail if [[ ! -f .fullsend/config.yaml ]]; then @@ -587,9 +583,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 @@ -613,9 +609,9 @@ jobs: - name: Check agent is enabled id: agent-check - if: steps.route.outputs.stage != '' && steps.role-check.outputs.skipped != 'true' && steps.pr-check.outputs.skipped != 'true' + if: steps.route.outputs.requested_stage != '' && steps.kill-switch.outputs.skipped != 'true' && steps.role-check.outputs.skipped != 'true' && steps.pr-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 @@ -675,6 +671,49 @@ 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 }} + KILL_SWITCH_SKIPPED: ${{ steps.kill-switch.outputs.skipped }} + ROLE_SKIPPED: ${{ steps.role-check.outputs.skipped }} + AGENT_SKIPPED: ${{ steps.agent-check.outputs.skipped }} + PR_SKIPPED: ${{ steps.pr-check.outputs.skipped }} + run: | + set -euo pipefail + echo "authorization_denied=false" >> "${GITHUB_OUTPUT}" + if [[ "${EVENT_NAME}" != "issue_comment" \ + || "${COMMENT_USER_TYPE}" == "Bot" \ + || "${COMMAND_APPLICABLE}" != "true" \ + || -z "${REQUESTED_STAGE}" \ + || -n "${STAGE}" \ + || "${AUTH_CHECK_FAILED}" == "true" \ + || "${KILL_SWITCH_SKIPPED}" == "true" \ + || "${ROLE_SKIPPED}" == "true" \ + || "${AGENT_SKIPPED}" == "true" \ + || "${PR_SKIPPED}" == "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 + 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 != '' @@ -717,15 +756,114 @@ jobs: runs-on: ${{ inputs.runner_image }} permissions: issues: write + actions: 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 || needs.harness-dispatch.outputs.authorization_actor }} + 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 }} 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: | @@ -738,22 +876,24 @@ jobs: echo "::warning::Skipping authorization notice: invalid actor login" exit 0 fi - - MARKER="" - COMMENTS="$(gh api "repos/${REPOSITORY}/issues/${ISSUE_NUMBER}/comments" --paginate --jq '.[] | select(.user.login == "github-actions[bot]") | .body')" || { - echo "::warning::Could not inspect existing authorization-denial comments" - exit 0 - } - if grep -Fq "${MARKER}" <<<"${COMMENTS}"; then - echo "Authorization-denial comment already exists for ${ACTOR_LOGIN}" + if [[ ! "${ACTOR_ID}" =~ ^[1-9][0-9]*$ ]]; then + echo "::warning::Skipping authorization notice: invalid actor ID" exit 0 fi - BODY="${MARKER} - - @${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." - gh api "repos/${REPOSITORY}/issues/${ISSUE_NUMBER}/comments" \ - -f body="${BODY}" >/dev/null + MARKER="" + BODY_FILE="${RUNNER_TEMP}/authorization-denied.md" + { + printf '%s\n\n' "${MARKER}" + printf '@%s, this agent launch was blocked because you are not authorized to launch Fullsend agents on this work item. Ask a repository maintainer for access.\n' "${ACTOR_LOGIN}" + } > "${BODY_FILE}" + fullsend issues post-comment \ + --tracker github \ + --project "${REPOSITORY}" \ + --number "${ISSUE_NUMBER}" \ + --marker "${MARKER}" \ + --result "${BODY_FILE}" \ + --keep-history=false triage: name: Triage @@ -1616,6 +1756,7 @@ jobs: matrix: ${{ steps.dispatch.outputs.matrix }} authorization_denied: ${{ steps.dispatch.outputs.authorization_denied || 'false' }} 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 diff --git a/docs/contributing/harness-fields.md b/docs/contributing/harness-fields.md index 5165ba31ce..bdabd22a9f 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/normative/normalized-event/v1/README.md b/docs/normative/normalized-event/v1/README.md index 8155d6685a..eee28c0a82 100644 --- a/docs/normative/normalized-event/v1/README.md +++ b/docs/normative/normalized-event/v1/README.md @@ -171,6 +171,11 @@ the repository (typically `write`), not `none` — the collaborator API often returns 404 for `[bot]` accounts even when the app has write access via installation token. +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 432bf0dfa2..9da128fa0a 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/internal/cli/dispatch.go b/internal/cli/dispatch.go index 434a212244..02cd23e014 100644 --- a/internal/cli/dispatch.go +++ b/internal/cli/dispatch.go @@ -142,26 +142,42 @@ func runDispatch(ctx context.Context, opts dispatchOpts) error { } func writeAuthorizationOutput(event *normevent.Event, denied bool) error { - if event == nil || event.Actor.Kind != normevent.ActorHuman || !denied { + if !isExplicitHumanSlashCommand(event) || !denied { return nil } path := os.Getenv("GITHUB_OUTPUT") - if path == "" || event.Entity.ID < 1 || !validGitHubLogin(event.Actor.ID) { + if path == "" || event.Entity.ID < 1 || event.Actor.NumericID < 1 || !validGitHubLogin(event.Actor.ID) { return nil } - if err := writeGitHubOutput(path, "authorization_denied", "true"); err != nil { - return fmt.Errorf("write authorization output authorization_denied: %w", err) + outputs := [][2]string{ + {"authorization_denied", "true"}, + {"authorization_actor", event.Actor.ID}, + {"authorization_actor_id", strconv.FormatInt(event.Actor.NumericID, 10)}, + {"authorization_number", strconv.Itoa(event.Entity.ID)}, } - if err := writeGitHubOutput(path, "authorization_actor", event.Actor.ID); err != nil { - return fmt.Errorf("write authorization output authorization_actor: %w", err) - } - if err := writeGitHubOutput(path, "authorization_number", strconv.Itoa(event.Entity.ID)); err != nil { - return fmt.Errorf("write authorization output authorization_number: %w", err) + 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 + } + switch event.Transition.Comment.Command { + case "/fs-triage", "/fs-code", "/fs-review", "/fs-fix", "/fs-retro", "/fs-prioritize": + return true + default: + return false + } +} + func validGitHubLogin(login string) bool { if login == "" { return false diff --git a/internal/cli/dispatch_test.go b/internal/cli/dispatch_test.go index 37dd490421..f542927e90 100644 --- a/internal/cli/dispatch_test.go +++ b/internal/cli/dispatch_test.go @@ -23,20 +23,25 @@ func TestWriteAuthorizationOutput(t *testing.T) { require.NoError(t, os.WriteFile(path, nil, 0o600)) event := &normevent.Event{ Entity: normevent.Entity{ID: 42}, - Actor: normevent.Actor{ID: "alice", Kind: normevent.ActorHuman}, + 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, writeAuthorizationOutput(event, true)) data, err := os.ReadFile(path) require.NoError(t, err) - assert.Equal(t, "authorization_denied=true\nauthorization_actor=alice\nauthorization_number=42\n", string(data)) + assert.Equal(t, "authorization_denied=true\nauthorization_actor=alice\nauthorization_actor_id=1234\nauthorization_number=42\n", string(data)) } func TestWriteAuthorizationOutputSkipsNonDeniedOrNonHuman(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", Kind: normevent.ActorHuman}}, + {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, writeAuthorizationOutput(event, false)) @@ -49,8 +54,25 @@ func TestWriteAuthorizationOutputSkipsInvalidLogin(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", Kind: normevent.ActorHuman}, + 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, writeAuthorizationOutput(event, true)) + _, err := os.Stat(path) + assert.ErrorIs(t, err, os.ErrNotExist) +} + +func TestWriteAuthorizationOutputSkipsAutomaticTrigger(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, writeAuthorizationOutput(event, true)) @@ -58,6 +80,36 @@ func TestWriteAuthorizationOutputSkipsInvalidLogin(t *testing.T) { assert.ErrorIs(t, err, os.ErrNotExist) } +func TestWriteAuthorizationOutputSkipsMissingNumericID(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, writeAuthorizationOutput(event, true)) + _, err := os.Stat(path) + assert.ErrorIs(t, err, os.ErrNotExist) +} + +func TestWriteAuthorizationOutputReportsOutputError(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 := writeAuthorizationOutput(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/input/ghaevent.go b/internal/harnessdispatch/input/ghaevent.go index 7f2119001b..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 } @@ -101,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, @@ -469,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 843834c89a..2d4e200776 100644 --- a/internal/harnessdispatch/input/ghaevent_test.go +++ b/internal/harnessdispatch/input/ghaevent_test.go @@ -193,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) @@ -220,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 d74484717c..d73821c7d0 100644 --- a/internal/normevent/event.go +++ b/internal/normevent/event.go @@ -143,6 +143,7 @@ const ( // Actor is the user or service account that caused the transition. type Actor struct { ID string `json:"id"` + NumericID int64 `json:"numeric_id,omitempty"` Kind ActorKind `json:"kind"` Role ActorRole `json:"role"` IsEntityAuthor bool `json:"is_entity_author"` From 656d21f1410f4acd15a1993a252041a7cfba1d5e Mon Sep 17 00:00:00 2001 From: Barak Korren Date: Sun, 11 Oct 2026 12:47:31 +0300 Subject: [PATCH 08/15] ci(#7555): close authorization routing gaps Apply availability checks to automatic routes, recognize custom CEL slash commands, and suppress notices when prerequisite checks fail. Signed-off-by: Barak Korren Assisted-by: Codex (gpt-5.6-sol) --- .github/workflows/reusable-dispatch.yml | 25 +++++++++++++++++-- docs/normative/normalized-event/v1/README.md | 3 +++ internal/cli/dispatch.go | 8 ++---- internal/cli/dispatch_test.go | 20 +++++++++++++++ .../scaffold/workflow_call_alignment_test.go | 2 ++ 5 files changed, 50 insertions(+), 8 deletions(-) diff --git a/.github/workflows/reusable-dispatch.yml b/.github/workflows/reusable-dispatch.yml index ad8d937918..737adaf208 100644 --- a/.github/workflows/reusable-dispatch.yml +++ b/.github/workflows/reusable-dispatch.yml @@ -437,6 +437,13 @@ 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" { @@ -536,12 +543,16 @@ jobs: if [[ -f .fullsend/config.yaml ]]; then KILL_SWITCH=$(yq '.kill_switch // false' .fullsend/config.yaml) if [[ "$KILL_SWITCH" == "true" ]]; then + # Keep routing successful while marking the stage unavailable; + # authorization metadata must not be emitted for a disabled + # stage. echo "::notice::Stage '${REQUESTED_STAGE}' skipped — kill switch is active" echo "skipped=true" >> "${GITHUB_OUTPUT}" fi fi - name: Validate agents config + id: validate-agents if: steps.route.outputs.requested_stage != '' && steps.kill-switch.outputs.skipped != 'true' run: | set -euo pipefail @@ -688,6 +699,11 @@ jobs: ROLE_SKIPPED: ${{ steps.role-check.outputs.skipped }} AGENT_SKIPPED: ${{ steps.agent-check.outputs.skipped }} PR_SKIPPED: ${{ steps.pr-check.outputs.skipped }} + KILL_SWITCH_OUTCOME: ${{ steps.kill-switch.outcome }} + VALIDATE_AGENTS_OUTCOME: ${{ steps.validate-agents.outcome }} + ROLE_CHECK_OUTCOME: ${{ steps.role-check.outcome }} + AGENT_CHECK_OUTCOME: ${{ steps.agent-check.outcome }} + PR_CHECK_OUTCOME: ${{ steps.pr-check.outcome }} run: | set -euo pipefail echo "authorization_denied=false" >> "${GITHUB_OUTPUT}" @@ -700,12 +716,18 @@ jobs: || "${KILL_SWITCH_SKIPPED}" == "true" \ || "${ROLE_SKIPPED}" == "true" \ || "${AGENT_SKIPPED}" == "true" \ - || "${PR_SKIPPED}" == "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 + [[ "${KILL_SWITCH_OUTCOME}" == "success" ]] || exit 0 + [[ "${VALIDATE_AGENTS_OUTCOME}" == "success" ]] || exit 0 + [[ "${ROLE_CHECK_OUTCOME}" == "success" ]] || exit 0 + [[ "${AGENT_CHECK_OUTCOME}" == "success" ]] || exit 0 + if [[ "${REQUESTED_STAGE}" == "code" && ("${PR_SKIPPED}" == "true" || "${PR_CHECK_OUTCOME}" != "success") ]]; then + exit 0 + fi echo "::notice::User ${COMMENT_USER_LOGIN} is not authorized to launch the requested agent" { echo "authorization_denied=true" @@ -756,7 +778,6 @@ jobs: runs-on: ${{ inputs.runner_image }} permissions: issues: write - actions: 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 }} diff --git a/docs/normative/normalized-event/v1/README.md b/docs/normative/normalized-event/v1/README.md index eee28c0a82..514c651f5d 100644 --- a/docs/normative/normalized-event/v1/README.md +++ b/docs/normative/normalized-event/v1/README.md @@ -175,6 +175,9 @@ 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. +Events that omit this optional field remain valid; consumers validating against +a pinned strict schema must update that schema before accepting events that +include it. ### Fork security (`state.change_proposal.is_fork`) diff --git a/internal/cli/dispatch.go b/internal/cli/dispatch.go index 02cd23e014..4a90d38919 100644 --- a/internal/cli/dispatch.go +++ b/internal/cli/dispatch.go @@ -170,12 +170,8 @@ func isExplicitHumanSlashCommand(event *normevent.Event) bool { event.Actor.Kind != normevent.ActorHuman || event.Transition.Comment == nil { return false } - switch event.Transition.Comment.Command { - case "/fs-triage", "/fs-code", "/fs-review", "/fs-fix", "/fs-retro", "/fs-prioritize": - return true - default: - return false - } + command := strings.TrimSpace(event.Transition.Comment.Command) + return strings.HasPrefix(command, "/fs-") && len(command) > len("/fs-") } func validGitHubLogin(login string) bool { diff --git a/internal/cli/dispatch_test.go b/internal/cli/dispatch_test.go index f542927e90..7dcee06479 100644 --- a/internal/cli/dispatch_test.go +++ b/internal/cli/dispatch_test.go @@ -37,6 +37,26 @@ func TestWriteAuthorizationOutput(t *testing.T) { assert.Equal(t, "authorization_denied=true\nauthorization_actor=alice\nauthorization_actor_id=1234\nauthorization_number=42\n", string(data)) } +func TestWriteAuthorizationOutputSupportsCustomSlashCommand(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-analyze"}, + }, + Source: normevent.Source{RawType: "issue_comment"}, + } + + require.NoError(t, writeAuthorizationOutput(event, true)) + data, err := os.ReadFile(path) + require.NoError(t, err) + assert.Contains(t, string(data), "authorization_actor_id=1234") +} + func TestWriteAuthorizationOutputSkipsNonDeniedOrNonHuman(t *testing.T) { path := filepath.Join(t.TempDir(), "github-output") t.Setenv("GITHUB_OUTPUT", path) diff --git a/internal/scaffold/workflow_call_alignment_test.go b/internal/scaffold/workflow_call_alignment_test.go index f441901aac..6266b078a0 100644 --- a/internal/scaffold/workflow_call_alignment_test.go +++ b/internal/scaffold/workflow_call_alignment_test.go @@ -803,6 +803,8 @@ func TestDispatchPerStageAuthorization(t *testing.T) { "notification concurrency must use the CEL fallback work-item number") 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") From d7a71e4052cfaefc289ab2e435eac02d4bd2f26e Mon Sep 17 00:00:00 2001 From: Barak Korren Date: Sun, 11 Oct 2026 14:41:09 +0300 Subject: [PATCH 09/15] ci(#7555): cover generic CEL commands Recognize every explicit slash command for CEL denial metadata and document the serialized notification worker and v1 compatibility contracts. Signed-off-by: Barak Korren Assisted-by: Codex (gpt-5.6-sol) --- docs/contributing/ci-workflows.md | 11 +++++++++++ docs/normative/normalized-event/v1/README.md | 8 +++++--- docs/reference/config-reference.md | 5 ++++- internal/cli/dispatch.go | 2 +- internal/cli/dispatch_test.go | 2 +- 5 files changed, 22 insertions(+), 6 deletions(-) diff --git a/docs/contributing/ci-workflows.md b/docs/contributing/ci-workflows.md index bd7977f4a4..8d26ca10fc 100644 --- a/docs/contributing/ci-workflows.md +++ b/docs/contributing/ci-workflows.md @@ -170,6 +170,17 @@ 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. + ## 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/normative/normalized-event/v1/README.md b/docs/normative/normalized-event/v1/README.md index 514c651f5d..6918292638 100644 --- a/docs/normative/normalized-event/v1/README.md +++ b/docs/normative/normalized-event/v1/README.md @@ -65,6 +65,11 @@ Breaking changes require `docs/normative/normalized-event/v2/`. 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. + ## Adapters Input drivers map native forge events into this struct: @@ -175,9 +180,6 @@ 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. -Events that omit this optional field remain valid; consumers validating against -a pinned strict schema must update that schema before accepting events that -include it. ### Fork security (`state.change_proposal.is_fork`) diff --git a/docs/reference/config-reference.md b/docs/reference/config-reference.md index 6cd83e6dd2..a65b71ab00 100644 --- a/docs/reference/config-reference.md +++ b/docs/reference/config-reference.md @@ -127,7 +127,10 @@ 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. ### `keep_history` diff --git a/internal/cli/dispatch.go b/internal/cli/dispatch.go index 4a90d38919..c9a55ad5ee 100644 --- a/internal/cli/dispatch.go +++ b/internal/cli/dispatch.go @@ -171,7 +171,7 @@ func isExplicitHumanSlashCommand(event *normevent.Event) bool { return false } command := strings.TrimSpace(event.Transition.Comment.Command) - return strings.HasPrefix(command, "/fs-") && len(command) > len("/fs-") + return strings.HasPrefix(command, "/") && len(command) > 1 } func validGitHubLogin(login string) bool { diff --git a/internal/cli/dispatch_test.go b/internal/cli/dispatch_test.go index 7dcee06479..833b7aa6c4 100644 --- a/internal/cli/dispatch_test.go +++ b/internal/cli/dispatch_test.go @@ -46,7 +46,7 @@ func TestWriteAuthorizationOutputSupportsCustomSlashCommand(t *testing.T) { Actor: normevent.Actor{ID: "alice", NumericID: 1234, Kind: normevent.ActorHuman}, Transition: normevent.Transition{ Kind: normevent.TransitionCommentAdded, - Comment: &normevent.Comment{Command: "/fs-analyze"}, + Comment: &normevent.Comment{Command: "/analyze"}, }, Source: normevent.Source{RawType: "issue_comment"}, } From 99186dd84d97c94eaaa6fd90967b3de4e93570d1 Mon Sep 17 00:00:00 2001 From: Barak Korren Date: Sun, 11 Oct 2026 14:52:43 +0300 Subject: [PATCH 10/15] ci(#7555): preserve CEL denial notices Allow confirmed CEL authorization denials through when an applicable legacy stage is unavailable, while retaining shared deduplication for successful legacy launches. Signed-off-by: Barak Korren Assisted-by: Codex (gpt-5.6-sol) --- .github/workflows/reusable-dispatch.yml | 8 +++++++- internal/scaffold/workflow_call_alignment_test.go | 2 ++ 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/.github/workflows/reusable-dispatch.yml b/.github/workflows/reusable-dispatch.yml index 737adaf208..b3568dd46e 100644 --- a/.github/workflows/reusable-dispatch.yml +++ b/.github/workflows/reusable-dispatch.yml @@ -774,7 +774,13 @@ jobs: authorization-notice: name: Authorization notice needs: [route, harness-dispatch] - if: ${{ always() && !cancelled() && (needs.route.outputs.authorization_denied == 'true' || (needs.harness-dispatch.outputs.authorization_denied == 'true' && (needs.route.outputs.legacy_command_applicable != 'true' || needs.route.outputs.authorization_check_failed == 'true'))) }} + if: >- + ${{ always() && !cancelled() && + (needs.route.outputs.authorization_denied == 'true' || + (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 diff --git a/internal/scaffold/workflow_call_alignment_test.go b/internal/scaffold/workflow_call_alignment_test.go index 6266b078a0..d9e19bd98a 100644 --- a/internal/scaffold/workflow_call_alignment_test.go +++ b/internal/scaffold/workflow_call_alignment_test.go @@ -801,6 +801,8 @@ func TestDispatchPerStageAuthorization(t *testing.T) { "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}" ]]`, From 012db96b945778a35000273032590b51de45a648 Mon Sep 17 00:00:00 2001 From: Barak Korren Date: Sun, 18 Oct 2026 16:03:03 +0300 Subject: [PATCH 11/15] ci(#7555): make dispatch decision metadata explicit Record slash-command authorization denials at the routing decision instead of inferring them from an empty stage. Evaluate kill-switch pauses before denial handling, remove the unused CLI test wrapper, and cover the paused human-launch workflow path. Signed-off-by: Barak Korren Assisted-by: Codex (gpt-5.6-sol) --- .github/workflows/reusable-dispatch.yml | 71 ++++++++----------- internal/cli/dispatch.go | 4 -- internal/cli/dispatch_test.go | 14 ++-- internal/scaffold/github_kill_switch_test.go | 35 +++++++++ .../scaffold/workflow_call_alignment_test.go | 8 +-- 5 files changed, 75 insertions(+), 57 deletions(-) diff --git a/.github/workflows/reusable-dispatch.yml b/.github/workflows/reusable-dispatch.yml index 08d095a9c3..74681eb63a 100644 --- a/.github/workflows/reusable-dispatch.yml +++ b/.github/workflows/reusable-dispatch.yml @@ -179,6 +179,7 @@ jobs: 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, @@ -287,6 +288,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}" @@ -314,52 +332,36 @@ jobs: case "${COMMAND}" in /fs-triage) COMMAND_APPLICABLE=true - if [[ "${COMMENT_USER_TYPE}" != "Bot" ]] && is_authorized triage; then - STAGE="triage" - fi - REQUESTED_STAGE="triage" + set_command_stage triage triage ;; /fs-code) if [[ "${ISSUE_IS_PR}" == "false" ]]; then COMMAND_APPLICABLE=true - if [[ "${COMMENT_USER_TYPE}" != "Bot" ]] && is_authorized; then - STAGE="code" - fi - REQUESTED_STAGE="code" + set_command_stage code fi ;; /fs-review) if [[ "${ISSUE_IS_PR}" == "true" ]]; then COMMAND_APPLICABLE=true - if [[ "${COMMENT_USER_TYPE}" != "Bot" ]] && is_authorized triage; then - STAGE="review" - fi - REQUESTED_STAGE="review" + set_command_stage review triage fi ;; /fs-fix) if [[ "${ISSUE_IS_PR}" == "true" ]]; then COMMAND_APPLICABLE=true - if [[ "${COMMENT_USER_TYPE}" != "Bot" ]] && is_authorized; then - STAGE="fix" + set_command_stage fix + if [[ "${STAGE}" == "fix" ]]; then TRIGGER_SOURCE="${COMMENT_USER_LOGIN}" fi - REQUESTED_STAGE="fix" fi ;; /fs-retro) COMMAND_APPLICABLE=true - if [[ "${COMMENT_USER_TYPE}" != "Bot" ]] && is_authorized; then - STAGE="retro" - fi - REQUESTED_STAGE="retro" + set_command_stage retro ;; /fs-prioritize) COMMAND_APPLICABLE=true - if [[ "${COMMENT_USER_TYPE}" != "Bot" ]] && is_authorized; then - STAGE="prioritize" - fi - REQUESTED_STAGE="prioritize" + set_command_stage prioritize ;; *) ;; @@ -455,6 +457,7 @@ jobs: 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 @@ -466,6 +469,7 @@ jobs: 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: Check for existing PRs @@ -731,15 +735,8 @@ jobs: 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 }} - PR_SKIPPED: ${{ steps.pr-check.outputs.skipped }} - KILL_SWITCH_OUTCOME: ${{ steps.kill-switch.outcome }} - VALIDATE_AGENTS_OUTCOME: ${{ steps.validate-agents.outcome }} - ROLE_CHECK_OUTCOME: ${{ steps.role-check.outcome }} - AGENT_CHECK_OUTCOME: ${{ steps.agent-check.outcome }} - PR_CHECK_OUTCOME: ${{ steps.pr-check.outcome }} run: | set -euo pipefail echo "authorization_denied=false" >> "${GITHUB_OUTPUT}" @@ -748,11 +745,7 @@ jobs: || "${COMMENT_USER_TYPE}" == "Bot" \ || "${COMMAND_APPLICABLE}" != "true" \ || -z "${REQUESTED_STAGE}" \ - || -n "${STAGE}" \ || "${AUTH_CHECK_FAILED}" == "true" \ - || "${KILL_SWITCH_SKIPPED}" == "true" \ - || "${ROLE_SKIPPED}" == "true" \ - || "${AGENT_SKIPPED}" == "true" \ || ! "${COMMENT_USER_ID}" =~ ^[1-9][0-9]*$ \ || ! "${ISSUE_NUMBER}" =~ ^[1-9][0-9]*$ \ || ! "${COMMENT_USER_LOGIN}" =~ ^[A-Za-z0-9_-]+$ ]]; then @@ -768,13 +761,7 @@ jobs: } >> "${GITHUB_OUTPUT}" exit 0 fi - [[ "${KILL_SWITCH_OUTCOME}" == "success" ]] || exit 0 - [[ "${VALIDATE_AGENTS_OUTCOME}" == "success" ]] || exit 0 - [[ "${ROLE_CHECK_OUTCOME}" == "success" ]] || exit 0 - [[ "${AGENT_CHECK_OUTCOME}" == "success" ]] || exit 0 - if [[ "${REQUESTED_STAGE}" == "code" && ("${PR_SKIPPED}" == "true" || "${PR_CHECK_OUTCOME}" != "success") ]]; then - exit 0 - fi + [[ "${ROUTE_AUTHORIZATION_DENIED}" == "true" ]] || exit 0 echo "::notice::User ${COMMENT_USER_LOGIN} is not authorized to launch the requested agent" { echo "authorization_denied=true" diff --git a/internal/cli/dispatch.go b/internal/cli/dispatch.go index e9d96d1b1b..f554a1474e 100644 --- a/internal/cli/dispatch.go +++ b/internal/cli/dispatch.go @@ -141,10 +141,6 @@ func runDispatch(ctx context.Context, opts dispatchOpts) error { return nil } -func writeAuthorizationOutput(event *normevent.Event, denied bool) error { - return writeDispatchOutput(event, denied, "") -} - func writeDispatchOutput(event *normevent.Event, denied bool, blockedReason string) error { if !isExplicitHumanSlashCommand(event) || (!denied && blockedReason != "kill_switch") { return nil diff --git a/internal/cli/dispatch_test.go b/internal/cli/dispatch_test.go index ec38c244d2..47644f48c1 100644 --- a/internal/cli/dispatch_test.go +++ b/internal/cli/dispatch_test.go @@ -31,7 +31,7 @@ func TestWriteAuthorizationOutput(t *testing.T) { Source: normevent.Source{RawType: "issue_comment"}, } - require.NoError(t, writeAuthorizationOutput(event, true)) + 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)) @@ -51,7 +51,7 @@ func TestWriteAuthorizationOutputSupportsCustomSlashCommand(t *testing.T) { Source: normevent.Source{RawType: "issue_comment"}, } - require.NoError(t, writeAuthorizationOutput(event, true)) + require.NoError(t, writeDispatchOutput(event, true, "")) data, err := os.ReadFile(path) require.NoError(t, err) assert.Contains(t, string(data), "authorization_actor_id=1234") @@ -84,7 +84,7 @@ func TestWriteAuthorizationOutputSkipsNonDeniedOrNonHuman(t *testing.T) { {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, writeAuthorizationOutput(event, false)) + require.NoError(t, writeDispatchOutput(event, false, "")) } _, err := os.Stat(path) assert.ErrorIs(t, err, os.ErrNotExist) @@ -100,7 +100,7 @@ func TestWriteAuthorizationOutputSkipsInvalidLogin(t *testing.T) { Source: normevent.Source{RawType: "issue_comment"}, } - require.NoError(t, writeAuthorizationOutput(event, true)) + require.NoError(t, writeDispatchOutput(event, true, "")) _, err := os.Stat(path) assert.ErrorIs(t, err, os.ErrNotExist) } @@ -115,7 +115,7 @@ func TestWriteAuthorizationOutputSkipsAutomaticTrigger(t *testing.T) { Source: normevent.Source{RawType: "issues"}, } - require.NoError(t, writeAuthorizationOutput(event, true)) + require.NoError(t, writeDispatchOutput(event, true, "")) _, err := os.Stat(path) assert.ErrorIs(t, err, os.ErrNotExist) } @@ -130,7 +130,7 @@ func TestWriteAuthorizationOutputSkipsMissingNumericID(t *testing.T) { Source: normevent.Source{RawType: "issue_comment"}, } - require.NoError(t, writeAuthorizationOutput(event, true)) + require.NoError(t, writeDispatchOutput(event, true, "")) _, err := os.Stat(path) assert.ErrorIs(t, err, os.ErrNotExist) } @@ -145,7 +145,7 @@ func TestWriteAuthorizationOutputReportsOutputError(t *testing.T) { Source: normevent.Source{RawType: "issue_comment"}, } - err := writeAuthorizationOutput(event, true) + err := writeDispatchOutput(event, true, "") require.Error(t, err) assert.Contains(t, err.Error(), "write authorization output") } diff --git a/internal/scaffold/github_kill_switch_test.go b/internal/scaffold/github_kill_switch_test.go index 918f0756f7..251583223d 100644 --- a/internal/scaffold/github_kill_switch_test.go +++ b/internal/scaffold/github_kill_switch_test.go @@ -233,3 +233,38 @@ func TestCheckKillSwitchStep_ConsultsConfigBaseYAML(t *testing.T) { }) } } + +func TestAuthorizationMetadataStep_EmitsPauseForHumanLaunch(t *testing.T) { + script := extractReusableDispatchStepScript(t, "route", "Emit authorization denial metadata") + 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=true", + "GITHUB_OUTPUT="+outputPath, + ) + out, err := cmd.CombinedOutput() + require.NoError(t, err, "stdout/stderr: %s", out) + + output, err := os.ReadFile(outputPath) + require.NoError(t, err) + 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") + assert.NotContains(t, string(output), "authorization_denied=true") +} diff --git a/internal/scaffold/workflow_call_alignment_test.go b/internal/scaffold/workflow_call_alignment_test.go index f793930c8a..3cc37605f3 100644 --- a/internal/scaffold/workflow_call_alignment_test.go +++ b/internal/scaffold/workflow_call_alignment_test.go @@ -890,12 +890,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+COMMAND_APPLICABLE=true\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`) From f0cea583db7dd07e698dc39887462dd73d4f04d9 Mon Sep 17 00:00:00 2001 From: Barak Korren Date: Sun, 18 Oct 2026 17:02:29 +0300 Subject: [PATCH 12/15] ci(#7555): suppress denials for unavailable stages Only emit legacy authorization-denied metadata when the requested stage remains runnable. Keep kill-switch pause notices independent, and add executable coverage for disabled roles, disabled agents, existing code PRs, and runnable unauthorized launches. Signed-off-by: Barak Korren Assisted-by: Codex (gpt-5.6-sol) --- .github/workflows/reusable-dispatch.yml | 10 +- internal/scaffold/github_kill_switch_test.go | 103 +++++++++++++------ 2 files changed, 83 insertions(+), 30 deletions(-) diff --git a/.github/workflows/reusable-dispatch.yml b/.github/workflows/reusable-dispatch.yml index f115c6be41..0f281c5284 100644 --- a/.github/workflows/reusable-dispatch.yml +++ b/.github/workflows/reusable-dispatch.yml @@ -744,6 +744,9 @@ jobs: 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 }} + PR_SKIPPED: ${{ steps.pr-check.outputs.skipped }} run: | set -euo pipefail echo "authorization_denied=false" >> "${GITHUB_OUTPUT}" @@ -768,7 +771,12 @@ jobs: } >> "${GITHUB_OUTPUT}" exit 0 fi - [[ "${ROUTE_AUTHORIZATION_DENIED}" == "true" ]] || exit 0 + if [[ "${ROUTE_AUTHORIZATION_DENIED}" != "true" \ + || "${ROLE_SKIPPED}" == "true" \ + || "${AGENT_SKIPPED}" == "true" \ + || "${PR_SKIPPED}" == "true" ]]; then + exit 0 + fi echo "::notice::User ${COMMENT_USER_LOGIN} is not authorized to launch the requested agent" { echo "authorization_denied=true" diff --git a/internal/scaffold/github_kill_switch_test.go b/internal/scaffold/github_kill_switch_test.go index 251583223d..2094b129ac 100644 --- a/internal/scaffold/github_kill_switch_test.go +++ b/internal/scaffold/github_kill_switch_test.go @@ -236,35 +236,80 @@ func TestCheckKillSwitchStep_ConsultsConfigBaseYAML(t *testing.T) { func TestAuthorizationMetadataStep_EmitsPauseForHumanLaunch(t *testing.T) { script := extractReusableDispatchStepScript(t, "route", "Emit authorization denial metadata") - 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)) + cases := []struct { + name string + killSwitch string + roleSkipped string + agentSkipped string + prSkipped 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: "existing code PR suppresses denial", + prSkipped: "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=true", - "GITHUB_OUTPUT="+outputPath, - ) - out, err := cmd.CombinedOutput() - require.NoError(t, err, "stdout/stderr: %s", out) + 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, + "PR_SKIPPED="+tc.prSkipped, + "GITHUB_OUTPUT="+outputPath, + ) + out, err := cmd.CombinedOutput() + require.NoError(t, err, "stdout/stderr: %s", out) - output, err := os.ReadFile(outputPath) - require.NoError(t, err) - 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") - assert.NotContains(t, string(output), "authorization_denied=true") + 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") + } + }) + } } From 4ba768d08ded14d8c179b84b3f2d837a625f3a24 Mon Sep 17 00:00:00 2001 From: Barak Korren Date: Sun, 18 Oct 2026 17:04:40 +0300 Subject: [PATCH 13/15] test(#7555): classify authorization notice as non-agent job Keep the reusable-dispatch concurrency contract test aligned with the serialized authorization-notice worker. Signed-off-by: Barak Korren Assisted-by: Codex (gpt-5.6-sol) --- internal/scaffold/workflow_call_alignment_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/internal/scaffold/workflow_call_alignment_test.go b/internal/scaffold/workflow_call_alignment_test.go index 62718f9ba8..240a0b6d1b 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: (.+)$`) From ee95fda2c7640a4fa855c27d62860ea645e149cb Mon Sep 17 00:00:00 2001 From: Barak Korren Date: Thu, 22 Oct 2026 14:41:22 +0300 Subject: [PATCH 14/15] fix(#7555): gate pause notices on matching launches Evaluate registered harness triggers while the kill switch is active so unmatched slash commands do not receive agent-pause notices. Add coverage for matched and unmatched commands, normalize dispatch test names, and verify the unauthorized behaviour path posts its issue comment. Signed-off-by: Barak Korren Assisted-by: Codex (gpt-5.6-sol) --- .../features/dispatch/owners-auth.feature | 1 + internal/cli/dispatch_test.go | 16 ++--- internal/harnessdispatch/core.go | 18 +++++- internal/harnessdispatch/core_test.go | 62 +++++++++++++++++-- pkg/behaviourtest/steps/actors.go | 21 +++++++ pkg/behaviourtest/steps/actors_test.go | 30 +++++++++ 6 files changed, 134 insertions(+), 14 deletions(-) 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_test.go b/internal/cli/dispatch_test.go index 47644f48c1..a3c23f83fa 100644 --- a/internal/cli/dispatch_test.go +++ b/internal/cli/dispatch_test.go @@ -17,7 +17,7 @@ import ( "github.com/fullsend-ai/fullsend/internal/normevent" ) -func TestWriteAuthorizationOutput(t *testing.T) { +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)) @@ -37,7 +37,7 @@ func TestWriteAuthorizationOutput(t *testing.T) { assert.Equal(t, "authorization_denied=true\nauthorization_actor=alice\nauthorization_actor_id=1234\nauthorization_number=42\n", string(data)) } -func TestWriteAuthorizationOutputSupportsCustomSlashCommand(t *testing.T) { +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)) @@ -57,7 +57,7 @@ func TestWriteAuthorizationOutputSupportsCustomSlashCommand(t *testing.T) { assert.Contains(t, string(data), "authorization_actor_id=1234") } -func TestWriteDispatchOutputKillSwitch(t *testing.T) { +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)) @@ -77,7 +77,7 @@ func TestWriteDispatchOutputKillSwitch(t *testing.T) { assert.Equal(t, "dispatch_blocked_reason=kill_switch\nauthorization_actor=alice\nauthorization_actor_id=1234\nauthorization_number=42\n", string(data)) } -func TestWriteAuthorizationOutputSkipsNonDeniedOrNonHuman(t *testing.T) { +func TestWriteDispatchOutput_SkipsNonDeniedOrNonHuman(t *testing.T) { path := filepath.Join(t.TempDir(), "github-output") t.Setenv("GITHUB_OUTPUT", path) for _, event := range []*normevent.Event{ @@ -90,7 +90,7 @@ func TestWriteAuthorizationOutputSkipsNonDeniedOrNonHuman(t *testing.T) { assert.ErrorIs(t, err, os.ErrNotExist) } -func TestWriteAuthorizationOutputSkipsInvalidLogin(t *testing.T) { +func TestWriteDispatchOutput_SkipsInvalidLogin(t *testing.T) { path := filepath.Join(t.TempDir(), "github-output") t.Setenv("GITHUB_OUTPUT", path) event := &normevent.Event{ @@ -105,7 +105,7 @@ func TestWriteAuthorizationOutputSkipsInvalidLogin(t *testing.T) { assert.ErrorIs(t, err, os.ErrNotExist) } -func TestWriteAuthorizationOutputSkipsAutomaticTrigger(t *testing.T) { +func TestWriteDispatchOutput_SkipsAutomaticTrigger(t *testing.T) { path := filepath.Join(t.TempDir(), "github-output") t.Setenv("GITHUB_OUTPUT", path) event := &normevent.Event{ @@ -120,7 +120,7 @@ func TestWriteAuthorizationOutputSkipsAutomaticTrigger(t *testing.T) { assert.ErrorIs(t, err, os.ErrNotExist) } -func TestWriteAuthorizationOutputSkipsMissingNumericID(t *testing.T) { +func TestWriteDispatchOutput_SkipsMissingNumericID(t *testing.T) { path := filepath.Join(t.TempDir(), "github-output") t.Setenv("GITHUB_OUTPUT", path) event := &normevent.Event{ @@ -135,7 +135,7 @@ func TestWriteAuthorizationOutputSkipsMissingNumericID(t *testing.T) { assert.ErrorIs(t, err, os.ErrNotExist) } -func TestWriteAuthorizationOutputReportsOutputError(t *testing.T) { +func TestWriteDispatchOutput_ReportsOutputError(t *testing.T) { outputPath := t.TempDir() t.Setenv("GITHUB_OUTPUT", outputPath) event := &normevent.Event{ diff --git a/internal/harnessdispatch/core.go b/internal/harnessdispatch/core.go index ff7fd3887b..56f71f2669 100644 --- a/internal/harnessdispatch/core.go +++ b/internal/harnessdispatch/core.go @@ -57,7 +57,23 @@ func DispatchResult(ctx context.Context, opts Options) (Result, error) { if err != nil { return Result{}, err } - if dirCfg.IsKillSwitchActive() { + 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 } diff --git a/internal/harnessdispatch/core_test.go b/internal/harnessdispatch/core_test.go index 0e9153cd06..bad98c4dfb 100644 --- a/internal/harnessdispatch/core_test.go +++ b/internal/harnessdispatch/core_test.go @@ -2,6 +2,7 @@ package harnessdispatch import ( "context" + "fmt" "os" "path/filepath" "testing" @@ -16,11 +17,9 @@ 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") result, err := DispatchResult(context.Background(), Options{ConfigDir: dir, Event: ev}) @@ -30,6 +29,35 @@ func TestDispatch_KillSwitch(t *testing.T) { 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) { dir := t.TempDir() writeHarnessConfig(t, dir, issuePingHarnessYAML()) @@ -148,6 +176,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) { // Use issue-opened (not label-added) so IsAuthorized requires // write-level access. Without the OWNERS approver upgrade the 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() From 62af794391cd100ba8dbfe3f1a452263790ca4ec Mon Sep 17 00:00:00 2001 From: Barak Korren Date: Thu, 22 Oct 2026 23:27:43 +0300 Subject: [PATCH 15/15] fix(#7555): remove obsolete existing PR gate The existing-PR gate was removed from main in #8133 but reintroduced by the workflow changes for #7555. Drop the gate and its authorization metadata/test plumbing so code dispatch is not incorrectly suppressed by unrelated open PRs. Signed-off-by: Barak Korren Assisted-by: Codex (gpt-5.6-sol) --- .github/workflows/reusable-dispatch.yml | 57 ++------------------ internal/scaffold/github_kill_switch_test.go | 6 --- 2 files changed, 3 insertions(+), 60 deletions(-) diff --git a/.github/workflows/reusable-dispatch.yml b/.github/workflows/reusable-dispatch.yml index 5e1cc5f413..44b177b20e 100644 --- a/.github/workflows/reusable-dispatch.yml +++ b/.github/workflows/reusable-dispatch.yml @@ -119,7 +119,7 @@ jobs: issues: read pull-requests: read outputs: - stage: ${{ steps.kill-switch.outputs.skipped != 'true' && steps.role-check.outputs.skipped != 'true' && steps.agent-check.outputs.skipped != 'true' && steps.pr-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' }} @@ -479,55 +479,6 @@ jobs: echo "authorization_denied=${AUTHORIZATION_DENIED}" } >> "${GITHUB_OUTPUT}" - - name: Check for existing PRs - id: pr-check - if: steps.route.outputs.requested_stage == 'code' - env: - GH_TOKEN: ${{ github.token }} - ISSUE_NUMBER: ${{ github.event.issue.number }} - SOURCE_REPO: ${{ github.repository }} - run: | - set -euo pipefail - # Query for PRs that actually close this issue (Fixes/Closes/Resolves - # keywords), not a substring search over title/body — the latter - # false-positives on any PR that merely references the issue (#5575). - # closedByPullRequestsReferences also returns MERGED PRs regardless of - # includeClosedPrs, so filter on .state explicitly. Exclude the code- - # agent bot via __typename + login so it can re-dispatch even when it - # already has an open PR (#5974); other bots (e.g. Renovate) still - # block. See docs/contributing/bot-identities.md for the login format. - # NOTE: bot identity is checked in three places — (1) this existing-PR - # guard (GraphQL __typename), (2) the fix eligibility script - # (.defaults/.github/scripts/check-fix-eligibility.sh — gh pr view - # is_bot/login), (3) org-scaffold dispatch.yml:226 (webhook [bot]$ - # regex). See docs/contributing/bot-identities.md. - OWNER="${SOURCE_REPO%%/*}" - REPO_NAME="${SOURCE_REPO##*/}" - GQL_ERR=$(mktemp) - if ! LINKED_PRS=$(gh api graphql -f query=' - query($owner: String!, $repo: String!, $number: Int!) { - repository(owner: $owner, name: $repo) { - issue(number: $number) { - closedByPullRequestsReferences(first: 20) { - nodes { number state author { login __typename } } - } - } - } - }' -f owner="${OWNER}" -f repo="${REPO_NAME}" -F number="${ISSUE_NUMBER}" \ - --jq '[.data.repository.issue.closedByPullRequestsReferences.nodes[] - | select(.state == "OPEN") - | select(.author.__typename != "Bot" or .author.login != "fullsend-ai-coder")] - | map("#\(.number)") | join(", ")' \ - 2>"${GQL_ERR}"); then - echo "::warning::Linked-PR query failed for issue #${ISSUE_NUMBER}: $(tr '\n' ' ' < "${GQL_ERR}" | sed 's/::/__/g')" - LINKED_PRS="" - fi - rm -f "${GQL_ERR}" - if [[ -n "${LINKED_PRS}" ]]; then - echo "::notice::Skipping code dispatch — issue #${ISSUE_NUMBER} has open PR(s) ${LINKED_PRS}" - echo "skipped=true" >> "${GITHUB_OUTPUT}" - fi - - name: Validate routed stage if: steps.route.outputs.stage != '' env: @@ -667,7 +618,7 @@ jobs: - name: Check agent is enabled id: agent-check - if: steps.route.outputs.requested_stage != '' && steps.kill-switch.outputs.skipped != 'true' && steps.role-check.outputs.skipped != 'true' && steps.pr-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.requested_stage }} run: | @@ -746,7 +697,6 @@ jobs: KILL_SWITCH_SKIPPED: ${{ steps.kill-switch.outputs.skipped }} ROLE_SKIPPED: ${{ steps.role-check.outputs.skipped }} AGENT_SKIPPED: ${{ steps.agent-check.outputs.skipped }} - PR_SKIPPED: ${{ steps.pr-check.outputs.skipped }} run: | set -euo pipefail echo "authorization_denied=false" >> "${GITHUB_OUTPUT}" @@ -773,8 +723,7 @@ jobs: fi if [[ "${ROUTE_AUTHORIZATION_DENIED}" != "true" \ || "${ROLE_SKIPPED}" == "true" \ - || "${AGENT_SKIPPED}" == "true" \ - || "${PR_SKIPPED}" == "true" ]]; then + || "${AGENT_SKIPPED}" == "true" ]]; then exit 0 fi echo "::notice::User ${COMMENT_USER_LOGIN} is not authorized to launch the requested agent" diff --git a/internal/scaffold/github_kill_switch_test.go b/internal/scaffold/github_kill_switch_test.go index 2094b129ac..9596aba883 100644 --- a/internal/scaffold/github_kill_switch_test.go +++ b/internal/scaffold/github_kill_switch_test.go @@ -241,7 +241,6 @@ func TestAuthorizationMetadataStep_EmitsPauseForHumanLaunch(t *testing.T) { killSwitch string roleSkipped string agentSkipped string - prSkipped string wantPause bool wantDenied bool }{ @@ -258,10 +257,6 @@ func TestAuthorizationMetadataStep_EmitsPauseForHumanLaunch(t *testing.T) { name: "disabled agent suppresses denial", agentSkipped: "true", }, - { - name: "existing code PR suppresses denial", - prSkipped: "true", - }, { name: "runnable unauthorized launch emits denial", wantDenied: true, @@ -291,7 +286,6 @@ func TestAuthorizationMetadataStep_EmitsPauseForHumanLaunch(t *testing.T) { "KILL_SWITCH_SKIPPED="+tc.killSwitch, "ROLE_SKIPPED="+tc.roleSkipped, "AGENT_SKIPPED="+tc.agentSkipped, - "PR_SKIPPED="+tc.prSkipped, "GITHUB_OUTPUT="+outputPath, ) out, err := cmd.CombinedOutput()