diff --git a/docs/contributing/config-source-inventory.md b/docs/contributing/config-source-inventory.md index cea0237ff2..21b6110355 100644 --- a/docs/contributing/config-source-inventory.md +++ b/docs/contributing/config-source-inventory.md @@ -109,7 +109,7 @@ The Go accessor layers these. The bash steps in `.github/workflows/reusable-disp | `runtime`, and per-agent `agents[].runtime` | Which runtime runs (`claude`, `pi`, `codex`, `dummy`) | `--runtime`, `FULLSEND_RUNTIME` (repository variable copied by `setup-agent-env.sh`), agent entry, repo `runtime:`, compiled `claude` | Flag, then `FULLSEND_RUNTIME`, then the agent entry, then repo `runtime:`, then `claude` (`docs/cli/run.md`) | `fullsend run` | File should win. Flag stays first. `FULLSEND_RUNTIME` stays as the fallback | Yes, for the fleet default. | | `agents[].model` | Model for one agent | `--model`, `FULLSEND_MODEL`, then `FULLSEND_PI_MODEL` or `FULLSEND_CODEX_MODEL` when that runtime is selected, agent entry, harness, frontmatter | Flag, then `FULLSEND_MODEL`, then the runtime-scoped alias, then the agent entry | `fullsend run` | File should win. Same fallback rule | The shared default can live on the base-file agent entry. | | `agents[].effort` | Effort for one agent | `--effort`, `FULLSEND_EFFORT`, agent entry, harness | Flag, then `FULLSEND_EFFORT`, then the agent entry | `fullsend run` | File should win. Same fallback rule | Same as model. | -| `mint_url` | Token mint address | `--mint-url`, `FULLSEND_MINT_URL`, layered `mint_url`, compiled `https://mint.fullsend.sh` | On `fullsend run`: flag, then `FULLSEND_MINT_URL`. The accessor is not consulted on that path. Workflows pass `vars.FULLSEND_MINT_URL` in as the `mint-url` input, so the flag is set | `fullsend run`, mint-token action. GitLab jobs never mint; `forgePlatform == "gitlab"` skips that path throughout `run.go`, and the GitLab scaffold has no mint reference | File should win once the binary reads `mint_url` before the variable. The workflow must keep passing `mint-url` until old binaries read the file. Setup already copies the effective file value into `FULLSEND_MINT_URL` | Yes. | +| `mint_url` | Token mint address | `--mint-url`, `FULLSEND_MINT_URL`, layered `mint_url`, compiled `https://mint.fullsend.sh` | `fullsend run` and `reconcile-status --fullsend-dir`: flag, then layered `mint_url`, then `FULLSEND_MINT_URL` (`resolveMintURL`, #8400). Only `runAgent`'s agent-token mint downgrades a file-sourced value to warn-and-skip (ambient `GH_TOKEN`) when GitHub Actions OIDC is unavailable; `reconcile-status` and the status-comment mint still attempt it and fail — fail-closed for `reconcile-status`, a per-call warning for status comments. `mint token` has no `--fullsend-dir`, so it stays flag then env | `fullsend run`, `reconcile-status`, `mint token`. GitLab never mints | File should win: done for `run` and `reconcile-status`. This has a live effect today, not only a future one: `action.yml` (`MINT_FLAGS`) omits `--mint-url` entirely when the composite action's `mint_url` input is empty, rather than passing an empty value, and the `prioritize` paths (`reusable-prioritize.yml` and the inlined `prioritize` job in `reusable-dispatch.yml`) have no upfront mint-token step gating on `FULLSEND_MINT_URL` the way triage/code/review/fix/retro/harness-run do. So when that repository variable is unset, those two paths (and any other composite-action caller that leaves `mint-url` empty) already mint — and notify — from a file-only `mint_url` inside real GitHub Actions runs with working OIDC. Every other dispatched stage still passes `mint-url` built from the possibly-stale variable, so the flag wins there until the `route` job computes the value from the file itself. `mint token` stays flag-then-env; it has no directory to layer from. The OIDC downgrade should extend to `reconcile-status` and status comments for consistency — tracked, not yet done. Confirming the mint endpoint serves the `prioritize` role wherever `mint_url` is file-only is tracked, not yet done (#8400 review) | Yes. | | `inference.region` | GCP region for inference | Layered `inference.region`, compiled `global`. Workflows pass `vars.FULLSEND_GCP_REGION` as `gcp_region`, which becomes `CLOUD_ML_REGION`. GitLab `run-agent-job.sh` exports `CLOUD_ML_REGION` from `FULLSEND_GCP_REGION` | The job environment, not the file. Setup writes the file's effective region into `FULLSEND_GCP_REGION` at install time. A later edit to the file does not change the variable | Vertex client via `CLOUD_ML_REGION`. The accessor is used at install and converge | File should win for the binary. Keep `FULLSEND_GCP_REGION` as the fallback and as the value old workflows still pass | Yes. | | `inference.project` | GCP project for inference | Layered `inference.project` (no compiled default), secret `FULLSEND_GCP_PROJECT_ID` | The secret. Workflows export it as `ANTHROPIC_VERTEX_PROJECT_ID`. `setup-gcp` uses the same secret to authenticate before the binary runs | Google auth action and the Vertex client | Leave the secret for the auth action. The file should be what the binary reads, with the secret as fallback. Do not put the secret value only in git if the auth action still needs it | Yes for the project id the binary uses. The secret remains for the auth action. | | `inference.wif_provider` | Workload Identity provider resource name | Layered `inference.wif_provider` (no compiled default), secret `FULLSEND_GCP_WIF_PROVIDER` | The secret. `setup-gcp` reads it | Google auth action | Leave the secret for the auth action. The file should describe the provider the binary needs. Same split as the project id | Yes for the non-secret resource name. The credential material stays a secret. | diff --git a/docs/guides/dev/cli-internals.md b/docs/guides/dev/cli-internals.md index 5f7fb31cad..34442d1fc3 100644 --- a/docs/guides/dev/cli-internals.md +++ b/docs/guides/dev/cli-internals.md @@ -134,7 +134,7 @@ fullsend │ ├── --run-url # CI/CD run URL for status comments │ ├── --status-repo # Repository for status comments │ ├── --status-number # Issue/PR number for status comments -│ └── --mint-url # Mint service URL for on-demand status tokens +│ └── --mint-url # Mint service URL for agent and status tokens (default: layered mint_url, then $FULLSEND_MINT_URL) ├── fetch-skill # Fetch a skill at runtime (in-sandbox) ├── scan # Run security scanner on input/output │ ├── input # Scan event payload for prompt injection @@ -213,10 +213,10 @@ fullsend ├── --run-url # Workflow run URL (optional) ├── --sha # Commit SHA (optional) ├── --reason # Termination reason: terminated or cancelled (default: terminated) - ├── --mint-url # Mint service URL for on-demand token (default: $FULLSEND_MINT_URL) - ├── --role # Agent role for minting (required with --mint-url) + ├── --mint-url # Mint service URL for on-demand token (default: layered mint_url from --fullsend-dir, then $FULLSEND_MINT_URL) + ├── --role # Agent role for minting (required to mint a token) ├── --forge # Forge platform (github, gitlab); auto-detected from CI env - ├── --fullsend-dir # Path to fullsend config directory (completion mode detection and tracker routing) + ├── --fullsend-dir # Path to fullsend config directory (completion mode detection, layered mint_url resolution, and tracker routing) ├── --job-status # Job outcome from CI runner (e.g. success, failure, cancelled) ├── --was-skipped # Pre-script decided to skip the run; forces synthesis under on_failure └── --review-run # Built-in GitHub review agent; enables current-HEAD-aware cancellation guidance diff --git a/docs/guides/user/bring-your-own-agent.md b/docs/guides/user/bring-your-own-agent.md index c41ef75400..ff5d5f33fc 100644 --- a/docs/guides/user/bring-your-own-agent.md +++ b/docs/guides/user/bring-your-own-agent.md @@ -181,9 +181,11 @@ sequenceDiagram The dispatch workflow matches the comment against the `trigger:` of every registered harness and starts `fullsend run` for each match. `fullsend run` gets a short-lived GitHub token for the harness's `role:` from the mint (a -local run without `--mint-url` or `FULLSEND_MINT_URL` skips this and uses -your `GH_TOKEN`), sets up the providers on the OpenShell gateway, and starts -the sandbox. For GitHub and OpenAI the agent never holds a real credential: +local run with no mint URL from `--mint-url`, `config.yaml`/`config.base.yaml`, +or `FULLSEND_MINT_URL` — or where GitHub Actions OIDC isn't available — +skips this and uses your `GH_TOKEN`), sets up the providers on the OpenShell +gateway, and starts the sandbox. For GitHub and OpenAI the agent never holds +a real credential: the gateway gives it a placeholder and swaps in the real value on each request a declared provider covers. On the Vertex route the GCP credentials file is copied into the sandbox, and the model calls use it directly. After diff --git a/docs/guides/user/running-agents-locally.md b/docs/guides/user/running-agents-locally.md index 080735deba..89db662981 100644 --- a/docs/guides/user/running-agents-locally.md +++ b/docs/guides/user/running-agents-locally.md @@ -406,7 +406,7 @@ target issue/PR. These flags mirror what the CI workflows pass automatically: | `--run-url` | URL of the CI/CD run shown in the status comment | | `--status-repo` | Repository (`owner/repo`) to post status comments on | | `--status-number` | Issue or PR number for status comments | -| `--mint-url` | Mint service URL for on-demand status comment tokens (default: `$FULLSEND_MINT_URL`) | +| `--mint-url` | Mint service URL for on-demand status comment tokens (default: layered `mint_url` from `--fullsend-dir`, then `$FULLSEND_MINT_URL`) | | `--forge` | Forge platform (`github` or `gitlab`); when omitted, resolved from `forge:` in the `config.yaml` at the root of `--fullsend-dir`, then `GITHUB_ACTIONS`/`GITLAB_CI` | Example: diff --git a/internal/cli/orgconfig.go b/internal/cli/orgconfig.go index 82f17a09a2..f292b19c50 100644 --- a/internal/cli/orgconfig.go +++ b/internal/cli/orgconfig.go @@ -32,6 +32,27 @@ func tryLoadFullsendConfig(path string, printer *ui.Printer) config.ConfigWriter // tryLoadOrgConfig is an alias of tryLoadFullsendConfig (best-effort). var tryLoadOrgConfig = tryLoadFullsendConfig +// tryLoadLayeredFullsendConfig attempts to load the layered fullsend +// config (config.yaml over config.base.yaml) from fullsendDir. +// Unlike tryLoadFullsendConfig, it does not require config.yaml to +// exist on disk: a base-only layout (config.base.yaml present, +// config.yaml absent) is honored, matching loadLockConfig's semantics. +// Returns nil without error when neither layer exists, or when the +// config is malformed (best-effort, with a warning printed via +// printer in the malformed case). The returned ConfigWriter has +// ensured defaults. +func tryLoadLayeredFullsendConfig(fullsendDir string, printer *ui.Printer) config.ConfigWriter { + writer, err := config.LoadConfigWriter(fullsendDir, config.LoadOpts{MissingOK: false}) + if err != nil { + if !errors.Is(err, os.ErrNotExist) { + printer.StepWarn("Config malformed (remote resource allowlist unavailable): " + err.Error()) + } + return nil + } + writer.SetAllowedRemoteResources(config.EnsureDefaultAllowedRemoteResources(writer.AllowedResources())) + return writer +} + // requireFullsendConfig loads a .fullsend config.yaml from the // given path with strict error handling. Returns differentiated errors // for missing files, unreadable files, and parse failures. diff --git a/internal/cli/reconcilestatus.go b/internal/cli/reconcilestatus.go index bf6d860c43..2318003d75 100644 --- a/internal/cli/reconcilestatus.go +++ b/internal/cli/reconcilestatus.go @@ -98,6 +98,31 @@ finalized, this is a no-op.`, return fmt.Errorf("--number must be a positive integer, got %d", number) } + // Loaded once, before mint-URL resolution and completion-mode + // lookup below, so both consult the same layered config.yaml/ + // config.base.yaml snapshot. orgCfg stays nil when + // --fullsend-dir was not provided or the config failed to + // load; downstream readers treat that as "no file layer". + var orgCfg config.ConfigReader + completionMode := "" + if fullsendDir != "" { + writer, err := config.LoadConfigWriter(fullsendDir, config.LoadOpts{MissingOK: true}) + switch { + case err != nil: + fmt.Fprintf(os.Stderr, "WARNING: could not load config from %s: %v; using default completion mode\n", fullsendDir, err) + default: + orgCfg = writer + // ConfigWriter embeds StatusNotificationsReader (via + // ConfigReader) directly, so no type assertion is + // needed. + if sn := writer.StatusNotifications(); sn != nil { + completionMode = sn.Comment.Completion + } else { + fmt.Fprintf(os.Stderr, "WARNING: no status_notifications configured at %s; using default completion mode\n", fullsendDir) + } + } + } + if trackerSource == "jira" { var jErr error tc, jErr = reconcileNewJiraTrackerClient() @@ -125,7 +150,7 @@ finalized, this is a no-op.`, } } else { var githubErr error - statusForgeClient, githubErr = reconcileGitHubClient(cmd, mintURL, role, repoName) + statusForgeClient, githubErr = reconcileGitHubClient(cmd, mintURL, role, repoName, orgCfg) if githubErr != nil { return githubErr } @@ -143,31 +168,12 @@ finalized, this is a no-op.`, termReason = statuscomment.ReasonTerminated } - completionMode := "" - if fullsendDir != "" { - writer, err := config.LoadConfigWriter(fullsendDir, config.LoadOpts{MissingOK: true}) - switch { - case err != nil: - fmt.Fprintf(os.Stderr, "WARNING: could not load config from %s: %v; using default completion mode\n", fullsendDir, err) - default: - // ConfigWriter embeds StatusNotificationsReader (via - // ConfigReader) directly, so no type assertion is - // needed. - if sn := writer.StatusNotifications(); sn != nil { - completionMode = sn.Comment.Completion - } else { - fmt.Fprintf(os.Stderr, "WARNING: no status_notifications configured at %s; using default completion mode\n", fullsendDir) - } - } - } - agentDescription := titleCase(strings.ReplaceAll(role, "-", " ")) guidance := "" if reviewRun && termReason == statuscomment.ReasonCancelled { var guidanceErr error guidance, guidanceErr = resolveBuiltInGitHubReviewCancellationGuidance( - cmd.Context(), statusForgeClient, "review", forgePlatform, trackerSource, - project, number, sha, + cmd.Context(), statusForgeClient, "review", forgePlatform, trackerSource, project, number, sha, ) if guidanceErr != nil { fmt.Fprintf(os.Stderr, "WARNING: could not determine whether cancelled review was superseded; omitting retry guidance: %v\n", guidanceErr) @@ -185,10 +191,10 @@ finalized, this is a no-op.`, cmd.Flags().StringVar(&runURL, "run-url", "", "URL to the workflow run (optional)") cmd.Flags().StringVar(&sha, "sha", "", "commit SHA (optional, shown as short hash)") cmd.Flags().StringVar(&reason, "reason", "terminated", "termination reason: terminated or cancelled") - cmd.Flags().StringVar(&mintURL, "mint-url", "", "mint service URL for on-demand token (default: $FULLSEND_MINT_URL)") - cmd.Flags().StringVar(&role, "role", "", "agent role for minting (required with --mint-url)") + cmd.Flags().StringVar(&mintURL, "mint-url", "", "mint service URL for on-demand token (default: layered mint_url from --fullsend-dir, then $FULLSEND_MINT_URL)") + cmd.Flags().StringVar(&role, "role", "", "agent role for minting (required to mint a token)") cmd.Flags().StringVar(&forgeFlag, "forge", "", `forge platform (e.g. "github", "gitlab"); auto-detected from CI env vars when omitted`) - cmd.Flags().StringVar(&fullsendDir, "fullsend-dir", "", "path to fullsend config directory (used to detect completion mode and read normalized event for tracker routing)") + cmd.Flags().StringVar(&fullsendDir, "fullsend-dir", "", "path to fullsend config directory (used to detect completion mode, resolve a layered mint_url, and read normalized event for tracker routing)") cmd.Flags().StringVar(&jobStatus, "job-status", "", "job outcome from the CI runner (e.g. success, failure, cancelled)") cmd.Flags().BoolVar(&wasSkipped, "was-skipped", false, "whether the pre-script decided to skip the run (forces synthesis under on_failure even when --job-status is success)") cmd.Flags().BoolVar(&reviewRun, "review-run", false, "whether this is the built-in GitHub review agent (enables GitHub-specific cancellation guidance)") @@ -198,16 +204,20 @@ finalized, this is a no-op.`, } // reconcileGitHubClient mints a GitHub token and returns a forge client. -func reconcileGitHubClient(cmd *cobra.Command, mintURL, role, repoName string) (forge.Client, error) { - if mintURL == "" { - mintURL = os.Getenv("FULLSEND_MINT_URL") - } +// mintURL resolution mirrors fullsend run's precedence (flag > layered +// config.yaml/config.base.yaml mint_url > FULLSEND_MINT_URL) so that +// reconcile-status agrees with run on which mint endpoint to use when both +// are invoked with the same --fullsend-dir in the same CI job (#8400). +// orgCfg may be nil when --fullsend-dir was not provided or its config +// failed to load; resolveMintURL treats that the same as "no file layer". +func reconcileGitHubClient(cmd *cobra.Command, mintURL, role, repoName string, orgCfg config.ConfigReader) (forge.Client, error) { + mintURL, _ = resolveMintURL(mintURL, orgCfg, os.Getenv) if mintURL == "" { - return nil, fmt.Errorf("--mint-url or FULLSEND_MINT_URL required") + return nil, fmt.Errorf("--mint-url, a layered mint_url in config.yaml/config.base.yaml, or FULLSEND_MINT_URL required") } if role == "" { - return nil, fmt.Errorf("--role is required when using --mint-url") + return nil, fmt.Errorf("--role is required to mint a token") } result, err := reconcileMintToken(cmd.Context(), mintclient.MintRequest{ MintURL: mintURL, diff --git a/internal/cli/reconcilestatus_test.go b/internal/cli/reconcilestatus_test.go index 6a48fc8d25..b2cb690393 100644 --- a/internal/cli/reconcilestatus_test.go +++ b/internal/cli/reconcilestatus_test.go @@ -55,7 +55,7 @@ func TestNewReconcileStatusCmd_ValidationErrors(t *testing.T) { { name: "missing mint-url", args: []string{"--repo", "org/repo", "--number", "7", "--run-id", "run-1"}, - wantErr: "--mint-url or FULLSEND_MINT_URL required", + wantErr: "--mint-url, a layered mint_url in config.yaml/config.base.yaml, or FULLSEND_MINT_URL required", }, { name: "invalid number", @@ -70,7 +70,7 @@ func TestNewReconcileStatusCmd_ValidationErrors(t *testing.T) { { name: "mint-url without role", args: []string{"--repo", "org/repo", "--number", "7", "--run-id", "run-1", "--mint-url", "https://mint.example.com"}, - wantErr: "--role is required when using --mint-url", + wantErr: "--role is required to mint a token", }, } for _, tt := range tests { @@ -111,6 +111,53 @@ func TestNewReconcileStatusCmd_MintURLFromEnv(t *testing.T) { assert.Contains(t, err.Error(), "minting status token") } +// TestNewReconcileStatusCmd_MintURLFromFile checks that reconcile-status must resolve mint_url from the +// same layered config.yaml/config.base.yaml that fullsend run reads via +// --fullsend-dir, not just --mint-url/FULLSEND_MINT_URL, so the two agree +// on a mint endpoint within the same CI job. +func TestNewReconcileStatusCmd_MintURLFromFile(t *testing.T) { + dir := t.TempDir() + + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte("[]")) + })) + defer srv.Close() + + require.NoError(t, os.WriteFile(filepath.Join(dir, "config.yaml"), []byte("version: \"1\"\nmint_url: "+srv.URL+"\n"), 0o644)) + + var capturedMintURL string + origMint := reconcileMintToken + reconcileMintToken = func(_ context.Context, req mintclient.MintRequest) (*mintclient.MintResult, error) { + capturedMintURL = req.MintURL + return &mintclient.MintResult{Token: "ghs_file_minted_token"}, nil + } + defer func() { reconcileMintToken = origMint }() + + origForge := reconcileNewForgeClient + reconcileNewForgeClient = func(token string) forge.Client { + return gh.New(token).WithBaseURL(srv.URL) + } + defer func() { reconcileNewForgeClient = origForge }() + + // A stale/different value in the environment — simulating a repository + // variable the file has since overridden — must lose to the file. + t.Setenv("FULLSEND_MINT_URL", "https://mint-from-env.example.com") + + cmd := newReconcileStatusCmd() + cmd.SetArgs([]string{ + "--repo", "org/repo", + "--number", "7", + "--run-id", "run-1", + "--role", "review", + "--fullsend-dir", dir, + }) + + err := cmd.Execute() + require.NoError(t, err) + assert.Equal(t, srv.URL, capturedMintURL, "config.yaml's mint_url must win over FULLSEND_MINT_URL") +} + func TestNewReconcileStatusCmd_TokenFlagRemoved(t *testing.T) { cmd := newReconcileStatusCmd() f := cmd.Flags().Lookup("token") diff --git a/internal/cli/run.go b/internal/cli/run.go index b6debfd87b..a008382dae 100644 --- a/internal/cli/run.go +++ b/internal/cli/run.go @@ -471,7 +471,7 @@ func newRunCmd() *cobra.Command { cmd.Flags().StringVar(&sOpts.statusRepo, "status-repo", "", "repository (owner/repo) for status comments") cmd.Flags().IntVar(&sOpts.statusNum, "status-number", 0, "issue/PR number for status comments") cmd.Flags().IntVar(&sOpts.statusComment, "status-comment-id", 0, "ID of the triggering comment, for comment-scoped reactions on slash-command runs (optional)") - cmd.Flags().StringVar(&sOpts.mintURL, "mint-url", "", "mint service URL for on-demand status tokens (default: $FULLSEND_MINT_URL)") + cmd.Flags().StringVar(&sOpts.mintURL, "mint-url", "", "mint service URL for agent and status tokens (default: layered mint_url from --fullsend-dir, then $FULLSEND_MINT_URL)") cmd.Flags().StringVar(&oFlags.runtime, "runtime", "", "override the agent runtime from config.yaml for this run (claude, pi, codex, opencode, dummy or dummy-playback; also $FULLSEND_RUNTIME)") cmd.Flags().StringVar(&oFlags.model, "model", "", "override the harness/agent model for this run (alias such as opus/sonnet/haiku, a model id, or provider/id on pi, codex, and opencode — codex takes OpenAI ids and gateway/ only; also $FULLSEND_MODEL)") cmd.Flags().StringVar(&oFlags.effort, "effort", "", "override the harness effort level for this run (low, medium, high, xhigh, max; also $FULLSEND_EFFORT)") @@ -903,9 +903,31 @@ func runAgent(ctx context.Context, agentName, fullsendDir, outputBase, targetRep // credential (Poller/Analyst/Coder or a custom role) and export // GITLAB_TOKEN / PUSH_TOKEN from that CI/CD variable. Missing role // credentials fail closed; there is no shared-token fallback. #6865 #7499. - mintURL := sOpts.mintURL - if mintURL == "" { - mintURL = os.Getenv("FULLSEND_MINT_URL") + // Precedence: flag > config.yaml/config.base.yaml mint_url > env (#8192). + mintURL, mintSource := resolveMintURL(sOpts.mintURL, orgCfg, os.Getenv) + // A mint_url that only came from the file layer is an implicit default + // meant to make CI convenient; it must not turn a previously-safe local + // run into a hard failure by attempting a GitHub Actions OIDC exchange + // that isn't available outside Actions. A flag or FULLSEND_MINT_URL is + // an explicit signal from the operator, so those stay fail-closed below + // (#8400). Two conditions narrow the downgrade to a genuine local run, + // not just "OIDC env happens to be empty" (review feedback on #8400): + // - FULLSEND_MINT_URL must also be unset. The file wins the endpoint + // precedence either way, but an operator who separately set the + // env var still signalled real intent to mint, even though that + // value is shadowed, so a mint failure must stay loud. + // - GITHUB_ACTIONS must not be "true". Downgrading solely on missing + // OIDC env would also silently fall back to the ambient (often + // broader) GH_TOKEN inside Actions when a workflow is missing + // id-token: write — a misconfiguration that should fail loudly, + // not swap in unscoped credentials. + mintSkipWarning := "" + if mintSource == mintURLSourceFile && + os.Getenv("FULLSEND_MINT_URL") == "" && + os.Getenv("GITHUB_ACTIONS") != "true" && + !hasActionsOIDCEnv(os.Getenv) { + mintSkipWarning = "config.yaml/config.base.yaml sets mint_url for a local run with no FULLSEND_MINT_URL, but GitHub Actions OIDC is unavailable; skipping token minting for role " + h.Role + mintURL = "" } runtimeLevel := h.PrivilegeLevelForStage(harness.PrivilegeStageRuntime) var minted bool @@ -921,7 +943,10 @@ func runAgent(ctx context.Context, agentName, fullsendDir, outputBase, targetRep if mintErr != nil { return fmt.Errorf("agent token minting failed: %w", mintErr) } - if !minted && mintURL == "" { + switch { + case mintSkipWarning != "": + printer.StepWarn(mintSkipWarning) + case !minted && mintURL == "": printer.StepWarn("No --mint-url provided; skipping token minting for role " + h.Role) } } @@ -1381,7 +1406,15 @@ func runAgent(ctx context.Context, agentName, fullsendDir, outputBase, targetRep defer dCancel() if status == "cancelled" && builtInGitHubReview(agentName, forgePlatform, sOpts.trackerSource) { parts := strings.SplitN(sOpts.statusRepo, "/", 2) - client, err := newStatusGitHubForgeClient(dCtx, sOpts.mintURL, h.Role, parts[1]) + // Resolve through the same flag > layered config file > + // env precedence as setupStatusNotifierGitHub, not just + // flag > env: otherwise a file-only mint_url mints + // against "" here (even though the start comment above + // minted correctly), and a file value competing with a + // different FULLSEND_MINT_URL would mint against the + // env endpoint instead of the file-selected one (#8400). + cancelMintURL, _ := resolveMintURL(sOpts.mintURL, orgCfg, os.Getenv) + client, err := newStatusGitHubForgeClient(dCtx, cancelMintURL, h.Role, parts[1]) if err == nil { // Reuse this freshly minted write client for completion so // cancellation cleanup does not spend time on a second mint. @@ -6375,8 +6408,8 @@ func titleCase(s string) string { // code-hosting forge (ADR 0093). func setupStatusNotifier(fullsendDir string, role string, forgePlatform string, sOpts statusOpts, printer *ui.Printer) (*statuscomment.Notifier, error) { var notifyCfg config.StatusNotificationConfig - orgConfigPath := filepath.Join(fullsendDir, "config.yaml") - if fsCfg := tryLoadFullsendConfig(orgConfigPath, printer); fsCfg != nil { + fsCfg := tryLoadLayeredFullsendConfig(fullsendDir, printer) + if fsCfg != nil { // StatusNotifications is part of the shared ConfigReader interface, // so this works for both orgConfig and perRepoConfig. if sn := fsCfg.StatusNotifications(); sn != nil { @@ -6401,7 +6434,7 @@ func setupStatusNotifier(fullsendDir string, role string, forgePlatform string, if forgePlatform == "gitlab" { return setupStatusNotifierGitLab(notifyCfg, owner, repo, sOpts, printer) } - return setupStatusNotifierGitHub(notifyCfg, owner, repo, role, sOpts, printer) + return setupStatusNotifierGitHub(notifyCfg, fsCfg, owner, repo, role, sOpts, printer) } // builtInGitHubReview identifies the one review run that can be retried with @@ -6450,11 +6483,8 @@ func resolveBuiltInGitHubReviewCancellationGuidance( // setupStatusNotifierGitHub creates a status notifier for GitHub. It mints // a fresh token via the mint service for each API call and reads SHA/run ID // from GitHub Actions environment variables. -func setupStatusNotifierGitHub(notifyCfg config.StatusNotificationConfig, owner, repo, role string, sOpts statusOpts, printer *ui.Printer) (*statuscomment.Notifier, error) { - mintURL := sOpts.mintURL - if mintURL == "" { - mintURL = os.Getenv("FULLSEND_MINT_URL") - } +func setupStatusNotifierGitHub(notifyCfg config.StatusNotificationConfig, orgCfg config.ConfigReader, owner, repo, role string, sOpts statusOpts, printer *ui.Printer) (*statuscomment.Notifier, error) { + mintURL, _ := resolveMintURL(sOpts.mintURL, orgCfg, os.Getenv) if mintURL == "" { return nil, fmt.Errorf("no mint URL available (set --mint-url or FULLSEND_MINT_URL)") } @@ -6908,6 +6938,62 @@ func maybeRemintAgentTokenForStage(ctx context.Context, h *harness.Harness, mint }, nil } +// mintURLSource identifies where resolveMintURL's returned value came +// from. Callers with a fail-closed mint path (e.g. runAgent) use this to +// distinguish an explicit signal — a flag or FULLSEND_MINT_URL, where an +// operator deliberately asked for minting — from the implicit file layer, +// so a config.yaml/config.base.yaml-sourced mint_url does not turn a +// previously-safe local run into a hard failure when GitHub Actions OIDC +// isn't available (#8400). +type mintURLSource int + +const ( + mintURLSourceNone mintURLSource = iota + mintURLSourceFlag + mintURLSourceFile + mintURLSourceEnv +) + +// resolveMintURL resolves the token mint URL with the precedence order +// documented in docs/contributing/config-source-inventory.md's mint_url +// row: an explicit flag value wins outright (one-run override); then +// config.yaml/config.base.yaml's mint_url ("file should win" over the +// variable kept for older workflows/binaries); then FULLSEND_MINT_URL; +// then "" so callers keep today's warn-and-skip-minting behavior. The +// compiled default (DefaultPerRepoMintURL) is deliberately not consulted +// here — ConfigMintURLFromFile stops short of it, so an installed repo +// that never configured mint_url anywhere still resolves to "". +// +// orgCfg may be nil (no config loaded) or may not implement +// PerRepoConfigReader (e.g. deprecated org-mode config); both cases +// simply skip the file layer and fall through to the environment. +func resolveMintURL(flagValue string, orgCfg config.ConfigReader, getenv func(string) string) (string, mintURLSource) { + if flagValue != "" { + return flagValue, mintURLSourceFlag + } + if prc, ok := orgCfg.(config.PerRepoConfigReader); ok { + if u := prc.ConfigMintURLFromFile(); u != "" { + return u, mintURLSourceFile + } + } + if u := getenv("FULLSEND_MINT_URL"); u != "" { + return u, mintURLSourceEnv + } + return "", mintURLSourceNone +} + +// hasActionsOIDCEnv reports whether the GitHub Actions OIDC request +// environment variables are present. mintclient.MintToken's only +// credential path is exchanging a GitHub Actions OIDC JWT +// (ACTIONS_ID_TOKEN_REQUEST_URL / ACTIONS_ID_TOKEN_REQUEST_TOKEN), so +// their absence means any mint attempt is guaranteed to fail with a +// generic "is this running in GitHub Actions" error. Callers use this to +// decide whether to downgrade an implicit (file-sourced) mint attempt to +// a warn-and-skip instead of a hard failure (#8400). +func hasActionsOIDCEnv(getenv func(string) string) bool { + return getenv("ACTIONS_ID_TOKEN_REQUEST_URL") != "" && getenv("ACTIONS_ID_TOKEN_REQUEST_TOKEN") != "" +} + // mintAgentToken mints a write-level GitHub App installation token for the // agent's role. Callers that select a privilege level (ADR 0073) should use // mintAgentTokenAtLevel instead. Existing tests and status-adjacent helpers diff --git a/internal/cli/run_test.go b/internal/cli/run_test.go index f28125109c..15140fc9e6 100644 --- a/internal/cli/run_test.go +++ b/internal/cli/run_test.go @@ -576,6 +576,51 @@ func TestTryLoadFullsendConfig_OmittedAllowlist(t *testing.T) { "omitted field must get defaults") } +func TestTryLoadLayeredFullsendConfig_BaseOnly(t *testing.T) { + dir := t.TempDir() + require.NoError(t, os.WriteFile(filepath.Join(dir, "config.base.yaml"), []byte( + "version: \"1\"\nmint_url: https://mint-from-base.example.com\n", + ), 0o644)) + + printer := ui.New(io.Discard) + cfg := tryLoadLayeredFullsendConfig(dir, printer) + require.NotNil(t, cfg, "config.base.yaml alone (no config.yaml) must be honored") + prc, ok := cfg.(config.PerRepoConfigReader) + require.True(t, ok) + assert.Equal(t, "https://mint-from-base.example.com", prc.ConfigMintURLFromFile()) +} + +func TestTryLoadLayeredFullsendConfig_NeitherFileExists(t *testing.T) { + dir := t.TempDir() + printer := ui.New(io.Discard) + assert.Nil(t, tryLoadLayeredFullsendConfig(dir, printer)) +} + +func TestTryLoadLayeredFullsendConfig_OverlayWinsOverBase(t *testing.T) { + dir := t.TempDir() + require.NoError(t, os.WriteFile(filepath.Join(dir, "config.base.yaml"), []byte( + "version: \"1\"\nmint_url: https://mint-from-base.example.com\n", + ), 0o644)) + require.NoError(t, os.WriteFile(filepath.Join(dir, "config.yaml"), []byte( + "version: \"1\"\nmint_url: https://mint-from-overlay.example.com\n", + ), 0o644)) + + printer := ui.New(io.Discard) + cfg := tryLoadLayeredFullsendConfig(dir, printer) + require.NotNil(t, cfg) + prc, ok := cfg.(config.PerRepoConfigReader) + require.True(t, ok) + assert.Equal(t, "https://mint-from-overlay.example.com", prc.ConfigMintURLFromFile()) +} + +func TestTryLoadLayeredFullsendConfig_MalformedBase(t *testing.T) { + dir := t.TempDir() + require.NoError(t, os.WriteFile(filepath.Join(dir, "config.base.yaml"), []byte("[[[not yaml"), 0o644)) + + printer := ui.New(io.Discard) + assert.Nil(t, tryLoadLayeredFullsendConfig(dir, printer)) +} + func TestRequireFullsendConfig_OrgGetsDefaultAllowlist(t *testing.T) { dir := t.TempDir() path := filepath.Join(dir, "config.yaml") @@ -5359,6 +5404,112 @@ func TestSetupStatusNotifier_MintURLFromEnv(t *testing.T) { assert.True(t, n.HasClientFactory(), "client factory should be set from FULLSEND_MINT_URL env var") } +func TestSetupStatusNotifier_MintURLFileWinsOverEnv(t *testing.T) { + tmpDir := t.TempDir() + printer := ui.New(io.Discard) + + require.NoError(t, os.WriteFile( + filepath.Join(tmpDir, "config.yaml"), + []byte("version: \"1\"\nmint_url: https://mint-from-file.example.com\n"), + 0o644, + )) + + origMint := statusMintToken + defer func() { statusMintToken = origMint }() + statusMintToken = func(_ context.Context, req mintclient.MintRequest) (*mintclient.MintResult, error) { + assert.Equal(t, "https://mint-from-file.example.com", req.MintURL, "config.yaml's mint_url must win over FULLSEND_MINT_URL") + return &mintclient.MintResult{Token: "ghs_test_minted"}, nil + } + + sOpts := statusOpts{ + statusRepo: "org/repo", + statusNum: 7, + } + + t.Setenv("FULLSEND_MINT_URL", "https://mint-from-env.example.com") + t.Setenv("GITHUB_RUN_ID", "run-42") + t.Setenv("GITHUB_ACTIONS", "true") + + n, err := setupStatusNotifier(tmpDir, "code", "", sOpts, printer) + require.NoError(t, err) + require.NotNil(t, n) + + client, err := n.InvokeClientFactory(context.Background()) + require.NoError(t, err) + assert.NotNil(t, client) +} + +// TestSetupStatusNotifier_MintURLFromBaseFileWinsOverEnv covers the +// base-only layout (config.base.yaml present, config.yaml absent from +// disk) that tryLoadFullsendConfig used to silently drop entirely, +// since it gated on config.yaml's mere existence before ever +// consulting config.base.yaml. setupStatusNotifier must resolve +// mint_url from the base file and prefer it over FULLSEND_MINT_URL, +// matching runAgent's resolveMintURL precedence +// (TestRunAgent_MintURLFromBaseFileWinsOverEnv). +func TestSetupStatusNotifier_MintURLFromBaseFileWinsOverEnv(t *testing.T) { + tmpDir := t.TempDir() + printer := ui.New(io.Discard) + + require.NoError(t, os.WriteFile( + filepath.Join(tmpDir, "config.base.yaml"), + []byte("version: \"1\"\nmint_url: https://mint-from-base.example.com\n"), + 0o644, + )) + + origMint := statusMintToken + defer func() { statusMintToken = origMint }() + statusMintToken = func(_ context.Context, req mintclient.MintRequest) (*mintclient.MintResult, error) { + assert.Equal(t, "https://mint-from-base.example.com", req.MintURL, + "config.base.yaml's mint_url must win over FULLSEND_MINT_URL when config.yaml is absent") + return &mintclient.MintResult{Token: "ghs_base_test_minted"}, nil + } + + sOpts := statusOpts{ + statusRepo: "org/repo", + statusNum: 7, + } + + t.Setenv("FULLSEND_MINT_URL", "https://mint-from-env.example.com") + t.Setenv("GITHUB_RUN_ID", "run-42") + t.Setenv("GITHUB_ACTIONS", "true") + + n, err := setupStatusNotifier(tmpDir, "code", "", sOpts, printer) + require.NoError(t, err) + require.NotNil(t, n) + + client, err := n.InvokeClientFactory(context.Background()) + require.NoError(t, err) + assert.NotNil(t, client) +} + +// TestSetupStatusNotifier_MintURLFromBaseFileWithoutEnv confirms the +// base-only mint_url is honored even when FULLSEND_MINT_URL is unset, +// so the file layer is genuinely consulted rather than the test only +// passing by coincidence of the env-var fallback. +func TestSetupStatusNotifier_MintURLFromBaseFileWithoutEnv(t *testing.T) { + tmpDir := t.TempDir() + printer := ui.New(io.Discard) + + require.NoError(t, os.WriteFile( + filepath.Join(tmpDir, "config.base.yaml"), + []byte("version: \"1\"\nmint_url: https://mint-from-base.example.com\n"), + 0o644, + )) + + sOpts := statusOpts{ + statusRepo: "org/repo", + statusNum: 7, + } + + t.Setenv("GITHUB_RUN_ID", "run-42") + + n, err := setupStatusNotifier(tmpDir, "review", "", sOpts, printer) + require.NoError(t, err) + assert.NotNil(t, n) + assert.True(t, n.HasClientFactory(), "client factory should be set from config.base.yaml's mint_url with no env var set") +} + func TestSetupStatusNotifier_NoMintURL(t *testing.T) { tmpDir := t.TempDir() printer := ui.New(io.Discard) @@ -7962,7 +8113,119 @@ func TestRunAgent_FallsBackToFULLSEND_MINT_URL(t *testing.T) { assert.True(t, mintCalled, "should have used FULLSEND_MINT_URL env var fallback") } -func TestRunAgent_MintsRuntimePrivilegeLevel(t *testing.T) { +// TestResolveMintURL_Source verifies resolveMintURL reports where its +// returned value came from, which runAgent (#8400 follow-up) relies on to +// decide whether a missing GitHub Actions OIDC environment should warn-and- +// skip (file source) or stay fail-closed (flag/env source). +func TestResolveMintURL_Source(t *testing.T) { + fileCfgDir := t.TempDir() + require.NoError(t, os.WriteFile( + filepath.Join(fileCfgDir, "config.yaml"), + []byte("version: \"1\"\nmint_url: https://mint-from-file.example.com\n"), + 0o644, + )) + fileCfg, err := config.LoadConfigWriter(fileCfgDir, config.LoadOpts{MissingOK: true}) + require.NoError(t, err) + + emptyCfgDir := t.TempDir() + emptyCfg, err := config.LoadConfigWriter(emptyCfgDir, config.LoadOpts{MissingOK: true}) + require.NoError(t, err) + + getenvWith := func(v string) func(string) string { + return func(key string) string { + if key == "FULLSEND_MINT_URL" { + return v + } + return "" + } + } + + tests := []struct { + name string + flagValue string + orgCfg config.ConfigReader + getenv func(string) string + wantURL string + wantSource mintURLSource + }{ + { + name: "flag wins over file and env", + flagValue: "https://mint-from-flag.example.com", + orgCfg: fileCfg, + getenv: getenvWith("https://mint-from-env.example.com"), + wantURL: "https://mint-from-flag.example.com", + wantSource: mintURLSourceFlag, + }, + { + name: "file wins over env when no flag", + flagValue: "", + orgCfg: fileCfg, + getenv: getenvWith("https://mint-from-env.example.com"), + wantURL: "https://mint-from-file.example.com", + wantSource: mintURLSourceFile, + }, + { + name: "env used when file is silent", + flagValue: "", + orgCfg: emptyCfg, + getenv: getenvWith("https://mint-from-env.example.com"), + wantURL: "https://mint-from-env.example.com", + wantSource: mintURLSourceEnv, + }, + { + name: "env used when orgCfg is nil", + flagValue: "", + orgCfg: nil, + getenv: getenvWith("https://mint-from-env.example.com"), + wantURL: "https://mint-from-env.example.com", + wantSource: mintURLSourceEnv, + }, + { + name: "none when nothing is set", + flagValue: "", + orgCfg: emptyCfg, + getenv: getenvWith(""), + wantURL: "", + wantSource: mintURLSourceNone, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + gotURL, gotSource := resolveMintURL(tt.flagValue, tt.orgCfg, tt.getenv) + assert.Equal(t, tt.wantURL, gotURL) + assert.Equal(t, tt.wantSource, gotSource) + }) + } +} + +// TestHasActionsOIDCEnv verifies the gate runAgent uses to decide whether a +// file-sourced mint_url can be attempted: both OIDC request env vars must +// be present, matching mintclient.fetchOIDCJWT's own requirement. +func TestHasActionsOIDCEnv(t *testing.T) { + tests := []struct { + name string + requestURL string + requestToken string + want bool + }{ + {"both set", "https://actions.example.com", "tok", true}, + {"url missing", "", "tok", false}, + {"token missing", "https://actions.example.com", "", false}, + {"neither set", "", "", false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + env := map[string]string{ + "ACTIONS_ID_TOKEN_REQUEST_URL": tt.requestURL, + "ACTIONS_ID_TOKEN_REQUEST_TOKEN": tt.requestToken, + } + got := hasActionsOIDCEnv(func(k string) string { return env[k] }) + assert.Equal(t, tt.want, got) + }) + } +} + +func TestRunAgent_MintURLFileWinsOverEnv(t *testing.T) { useFakeOpenshell(t) dir := t.TempDir() require.NoError(t, os.MkdirAll(filepath.Join(dir, "harness"), 0o755)) @@ -7976,27 +8239,38 @@ func TestRunAgent_MintsRuntimePrivilegeLevel(t *testing.T) { )) require.NoError(t, os.WriteFile( filepath.Join(dir, "harness", "code.yaml"), - []byte("agent: agents/code.md\nrole: coder\npolicy: policies/base.yaml\nprivilege_levels:\n runtime: read\n"), + []byte("agent: agents/code.md\nrole: coder\npolicy: policies/base.yaml\n"), 0o644, )) require.NoError(t, os.WriteFile( filepath.Join(dir, "config.yaml"), - []byte("agents:\n - harness/code.yaml\n"), + []byte("agents:\n - harness/code.yaml\nmint_url: https://mint-from-file.example.com\n"), 0o644, )) origMint := statusMintToken defer func() { statusMintToken = origMint }() - var gotLevel string + var mintCalled bool statusMintToken = func(_ context.Context, req mintclient.MintRequest) (*mintclient.MintResult, error) { - gotLevel = req.Level - return &mintclient.MintResult{Token: "ghs_read_token", ExpiresAt: "2026-06-15T12:00:00Z"}, nil + mintCalled = true + assert.Equal(t, "https://mint-from-file.example.com", req.MintURL, "config.yaml's mint_url must win over FULLSEND_MINT_URL") + return &mintclient.MintResult{Token: "ghs_file_token", ExpiresAt: "2026-06-15T12:00:00Z"}, nil } - t.Setenv("FULLSEND_MINT_URL", "https://mint.example.com") + // A stale/different value in the environment — simulating a + // repository variable set at install time that the file has since + // overridden without anyone updating the variable. + t.Setenv("FULLSEND_MINT_URL", "https://mint-from-env.example.com") t.Setenv("REPO_FULL_NAME", "org/my-repo") t.Setenv("GH_TOKEN", "") + t.Setenv("PUSH_TOKEN", "") + t.Setenv("PUSH_TOKEN_SOURCE", "") + // A file-sourced mint_url only proceeds to mint when GitHub Actions + // OIDC is available; otherwise it is a warn-and-skip (#8400). Set + // both so this test exercises the "mint attempted" branch. + t.Setenv("ACTIONS_ID_TOKEN_REQUEST_URL", "https://actions.example.com/oidc") + t.Setenv("ACTIONS_ID_TOKEN_REQUEST_TOKEN", "fake-oidc-request-token") var buf bytes.Buffer rFlags := resolveFlags{maxDepth: 10, maxResources: 50} @@ -8006,10 +8280,10 @@ func TestRunAgent_MintsRuntimePrivilegeLevel(t *testing.T) { require.Error(t, err) assert.Contains(t, err.Error(), "openshell") - assert.Equal(t, "read", gotLevel, "initial mint must request the runtime privilege level") + assert.True(t, mintCalled, "should have minted using config.yaml's mint_url") } -func TestRunAgent_WarnsWhenNoMintURL(t *testing.T) { +func TestRunAgent_MintURLFromBaseFileWinsOverEnv(t *testing.T) { useFakeOpenshell(t) dir := t.TempDir() require.NoError(t, os.MkdirAll(filepath.Join(dir, "harness"), 0o755)) @@ -8026,6 +8300,13 @@ func TestRunAgent_WarnsWhenNoMintURL(t *testing.T) { []byte("agent: agents/code.md\nrole: coder\npolicy: policies/base.yaml\n"), 0o644, )) + // config.base.yaml carries mint_url; config.yaml is present (so the + // repo is in layered mode) but does not override it. + require.NoError(t, os.WriteFile( + filepath.Join(dir, "config.base.yaml"), + []byte("version: \"1\"\nmint_url: https://mint-from-base.example.com\n"), + 0o644, + )) require.NoError(t, os.WriteFile( filepath.Join(dir, "config.yaml"), []byte("agents:\n - harness/code.yaml\n"), @@ -8035,12 +8316,23 @@ func TestRunAgent_WarnsWhenNoMintURL(t *testing.T) { origMint := statusMintToken defer func() { statusMintToken = origMint }() - statusMintToken = func(_ context.Context, _ mintclient.MintRequest) (*mintclient.MintResult, error) { - t.Fatal("mint should not be called when no mint URL is available") - return nil, nil + var mintCalled bool + statusMintToken = func(_ context.Context, req mintclient.MintRequest) (*mintclient.MintResult, error) { + mintCalled = true + assert.Equal(t, "https://mint-from-base.example.com", req.MintURL, "config.base.yaml's mint_url must win over FULLSEND_MINT_URL when config.yaml is silent") + return &mintclient.MintResult{Token: "ghs_base_file_token", ExpiresAt: "2026-06-15T12:00:00Z"}, nil } - t.Setenv("FULLSEND_MINT_URL", "") + t.Setenv("FULLSEND_MINT_URL", "https://mint-from-env.example.com") + t.Setenv("REPO_FULL_NAME", "org/my-repo") + t.Setenv("GH_TOKEN", "") + t.Setenv("PUSH_TOKEN", "") + t.Setenv("PUSH_TOKEN_SOURCE", "") + // A file-sourced mint_url only proceeds to mint when GitHub Actions + // OIDC is available; otherwise it is a warn-and-skip (#8400). Set + // both so this test exercises the "mint attempted" branch. + t.Setenv("ACTIONS_ID_TOKEN_REQUEST_URL", "https://actions.example.com/oidc") + t.Setenv("ACTIONS_ID_TOKEN_REQUEST_TOKEN", "fake-oidc-request-token") var buf bytes.Buffer rFlags := resolveFlags{maxDepth: 10, maxResources: 50} @@ -8049,14 +8341,16 @@ func TestRunAgent_WarnsWhenNoMintURL(t *testing.T) { err := runAgent(context.Background(), "code", dir, "", repoDir, "", nil, false, "", "", "", rFlags, statusOpts{}, printer, false, runOverrideFlags{}) require.Error(t, err) - assert.Contains(t, buf.String(), "skipping token minting") + assert.Contains(t, err.Error(), "openshell") + assert.True(t, mintCalled, "should have minted using config.base.yaml's mint_url") } -func TestRunAgent_MintTokenError(t *testing.T) { +func TestRunAgent_MintURLFlagWinsOverFile(t *testing.T) { useFakeOpenshell(t) dir := t.TempDir() require.NoError(t, os.MkdirAll(filepath.Join(dir, "harness"), 0o755)) require.NoError(t, os.MkdirAll(filepath.Join(dir, "agents"), 0o755)) + writePolicyFixture(t, dir) require.NoError(t, os.WriteFile( filepath.Join(dir, "agents", "code.md"), @@ -8065,39 +8359,44 @@ func TestRunAgent_MintTokenError(t *testing.T) { )) require.NoError(t, os.WriteFile( filepath.Join(dir, "harness", "code.yaml"), - []byte("agent: agents/code.md\nrole: coder\n"), + []byte("agent: agents/code.md\nrole: coder\npolicy: policies/base.yaml\n"), 0o644, )) require.NoError(t, os.WriteFile( filepath.Join(dir, "config.yaml"), - []byte("agents:\n - harness/code.yaml\n"), + []byte("agents:\n - harness/code.yaml\nmint_url: https://mint-from-file.example.com\n"), 0o644, )) origMint := statusMintToken defer func() { statusMintToken = origMint }() - statusMintToken = func(_ context.Context, _ mintclient.MintRequest) (*mintclient.MintResult, error) { - return nil, fmt.Errorf("OIDC token exchange failed") + var mintCalled bool + statusMintToken = func(_ context.Context, req mintclient.MintRequest) (*mintclient.MintResult, error) { + mintCalled = true + assert.Equal(t, "https://mint-from-flag.example.com", req.MintURL, "--mint-url flag must win over config.yaml's mint_url") + return &mintclient.MintResult{Token: "ghs_flag_token", ExpiresAt: "2026-06-15T12:00:00Z"}, nil } - t.Setenv("FULLSEND_MINT_URL", "https://mint.example.com") + t.Setenv("FULLSEND_MINT_URL", "https://mint-from-env.example.com") t.Setenv("REPO_FULL_NAME", "org/my-repo") + t.Setenv("GH_TOKEN", "") + t.Setenv("PUSH_TOKEN", "") + t.Setenv("PUSH_TOKEN_SOURCE", "") var buf bytes.Buffer rFlags := resolveFlags{maxDepth: 10, maxResources: 50} printer := ui.New(&buf) repoDir := t.TempDir() - err := runAgent(context.Background(), "code", dir, "", repoDir, "", nil, false, "", "", "", rFlags, statusOpts{}, printer, false, runOverrideFlags{}) + sOpts := statusOpts{mintURL: "https://mint-from-flag.example.com"} + err := runAgent(context.Background(), "code", dir, "", repoDir, "", nil, false, "", "", "", rFlags, sOpts, printer, false, runOverrideFlags{}) require.Error(t, err) - assert.Contains(t, err.Error(), "agent token minting failed") + assert.Contains(t, err.Error(), "openshell") + assert.True(t, mintCalled, "should have minted using the --mint-url flag") } -// TestRunAgent_GitLabSkipsMint verifies that mintAgentToken is not called -// when --forge=gitlab. Minting is GitHub-only; on GitLab the registered -// role credential serves as the push/API token. #6865 #7499. -func TestRunAgent_GitLabSkipsMint(t *testing.T) { +func TestRunAgent_MintURLFromFileSkipsWithoutOIDC(t *testing.T) { useFakeOpenshell(t) dir := t.TempDir() require.NoError(t, os.MkdirAll(filepath.Join(dir, "harness"), 0o755)) @@ -8116,48 +8415,61 @@ func TestRunAgent_GitLabSkipsMint(t *testing.T) { )) require.NoError(t, os.WriteFile( filepath.Join(dir, "config.yaml"), - []byte("agents:\n - harness/code.yaml\n"), + []byte("agents:\n - harness/code.yaml\nmint_url: https://mint-from-file.example.com\n"), 0o644, )) - origMint := statusMintToken - defer func() { statusMintToken = origMint }() - - statusMintToken = func(_ context.Context, _ mintclient.MintRequest) (*mintclient.MintResult, error) { - t.Fatal("mint should not be called on GitLab") - return nil, nil - } - - t.Setenv("FULLSEND_MINT_URL", "https://mint.example.com") + // No --mint-url flag, no FULLSEND_MINT_URL, and critically no + // ACTIONS_ID_TOKEN_REQUEST_URL/_TOKEN — this is the local-run case from + // docs/guides/user/running-agents-locally.md: the ambient GH_TOKEN is + // used directly and minting is skipped, exactly as it was before + // config.yaml's mint_url was consulted at all. + t.Setenv("FULLSEND_MINT_URL", "") + t.Setenv("ACTIONS_ID_TOKEN_REQUEST_URL", "") + t.Setenv("ACTIONS_ID_TOKEN_REQUEST_TOKEN", "") + t.Setenv("GITHUB_ACTIONS", "") t.Setenv("REPO_FULL_NAME", "org/my-repo") - t.Setenv(forge.SecretForgeToken, "glpat-test-shared") - t.Setenv(forge.SecretGitLabPollerToken, "glpat-test-poller") - t.Setenv(forge.SecretGitLabAnalystToken, "glpat-test-analyst") - t.Setenv(forge.SecretGitLabCoderToken, "glpat-test-coder") - t.Setenv(forge.VarGitLabRoleRegistry, "") + t.Setenv("GH_TOKEN", "fake-gh-token") + t.Setenv("PUSH_TOKEN", "") + t.Setenv("PUSH_TOKEN_SOURCE", "") var buf bytes.Buffer rFlags := resolveFlags{maxDepth: 10, maxResources: 50} printer := ui.New(&buf) repoDir := t.TempDir() - err := runAgent(context.Background(), "code", dir, "", repoDir, "", nil, false, "", "gitlab", "", rFlags, statusOpts{}, printer, false, runOverrideFlags{}) + err := runAgent(context.Background(), "code", dir, "", repoDir, "", nil, false, "", "", "", rFlags, statusOpts{}, printer, false, runOverrideFlags{}) - // Expect error from openshell, not from minting require.Error(t, err) - assert.Contains(t, err.Error(), "openshell") - // No "skipping token minting" warning on GitLab - assert.NotContains(t, buf.String(), "skipping token minting") - assert.NotContains(t, buf.String(), "glpat-") -} - -// TestRunAgent_GitLabMissingRoleFailsClosed verifies leftover disabled -// gates no longer fall back to a directly-set GITLAB_TOKEN. Runtime -// authentication requires the registered role secret. -func TestRunAgent_GitLabMissingRoleFailsClosed(t *testing.T) { + assert.NotContains(t, err.Error(), "agent token minting failed", "a file-sourced mint_url without OIDC must not hard-fail the run") + assert.Contains(t, err.Error(), "openshell", "run should proceed past the skipped mint to the shell stage") + assert.Contains(t, buf.String(), "GitHub Actions OIDC is unavailable", "should warn that the file-sourced mint_url was skipped") + // mintAgentTokenAtLevel only calls os.Setenv("GH_TOKEN", ...) after a + // successful mint; skipping the mint attempt means that call never + // happens, so GH_TOKEN must still hold the ambient value set above, + // not a minted one. The fake openshell stub exits before reading any + // env vars, so this is the only way this test can observe that the + // ambient credential was left for the (unexercised) shell to use. + assert.Equal(t, "fake-gh-token", os.Getenv("GH_TOKEN"), "GH_TOKEN must remain the ambient token; minting must not have touched it") +} + +// TestRunAgent_MintURLFlagFailsClosedWithoutOIDC confirms the other half of +// the #8400 follow-up fix: unlike a file-sourced mint_url, an explicit +// --mint-url flag (or FULLSEND_MINT_URL) is a deliberate signal from the +// operator and stays fail-closed — it must still hard-fail when GitHub +// Actions OIDC is unavailable, rather than silently degrading. +// TestRunAgent_MintURLFromFileFailsClosedWhenEnvAlsoSet is a regression test +// for review feedback on #8400: the file wins the mint_url endpoint +// precedence, so resolveMintURL reports mintURLSourceFile even when +// FULLSEND_MINT_URL is also set — but an operator who set the env var still +// signalled real intent to mint, even though that value is shadowed. The +// downgrade must not fire in that case; a missing OIDC environment must +// still hard-fail the run. +func TestRunAgent_MintURLFromFileFailsClosedWhenEnvAlsoSet(t *testing.T) { useFakeOpenshell(t) dir := t.TempDir() require.NoError(t, os.MkdirAll(filepath.Join(dir, "harness"), 0o755)) require.NoError(t, os.MkdirAll(filepath.Join(dir, "agents"), 0o755)) + writePolicyFixture(t, dir) require.NoError(t, os.WriteFile( filepath.Join(dir, "agents", "code.md"), @@ -8166,37 +8478,39 @@ func TestRunAgent_GitLabMissingRoleFailsClosed(t *testing.T) { )) require.NoError(t, os.WriteFile( filepath.Join(dir, "harness", "code.yaml"), - []byte("agent: agents/code.md\nrole: coder\n"), + []byte("agent: agents/code.md\nrole: coder\npolicy: policies/base.yaml\n"), 0o644, )) require.NoError(t, os.WriteFile( filepath.Join(dir, "config.yaml"), - []byte("agents:\n - harness/code.yaml\n"), + []byte("agents:\n - harness/code.yaml\nmint_url: https://mint-from-file.example.com\n"), 0o644, )) + t.Setenv("FULLSEND_MINT_URL", "https://mint-from-env.example.com") + t.Setenv("ACTIONS_ID_TOKEN_REQUEST_URL", "") + t.Setenv("ACTIONS_ID_TOKEN_REQUEST_TOKEN", "") + t.Setenv("GITHUB_ACTIONS", "") t.Setenv("REPO_FULL_NAME", "org/my-repo") - t.Setenv(forge.SecretForgeToken, "") - t.Setenv(forge.VarGitLabRoleRegistry, "") - t.Setenv("GITLAB_TOKEN", "glpat-preset-by-user") + t.Setenv("GH_TOKEN", "fake-gh-token") var buf bytes.Buffer rFlags := resolveFlags{maxDepth: 10, maxResources: 50} printer := ui.New(&buf) repoDir := t.TempDir() - err := runAgent(context.Background(), "code", dir, "", repoDir, "", nil, false, "", "gitlab", "", rFlags, statusOpts{}, printer, false, runOverrideFlags{}) + err := runAgent(context.Background(), "code", dir, "", repoDir, "", nil, false, "", "", "", rFlags, statusOpts{}, printer, false, runOverrideFlags{}) require.Error(t, err) - assert.ErrorIs(t, err, gitlabroles.ErrUnconfigured) - assert.Contains(t, err.Error(), forge.SecretGitLabCoderToken) - assert.NotContains(t, buf.String(), "FULLSEND_FORGE_TOKEN is not set") - assert.NotContains(t, err.Error(), "openshell") + assert.Contains(t, err.Error(), "agent token minting failed", "a competing FULLSEND_MINT_URL must stay fail-closed even though the file wins the endpoint") } -// TestRunAgent_SetsEnvFromFlags verifies that run.go exports TARGET_REPO_DIR, -// REPO_FULL_NAME, and ISSUE_NUMBER from their CLI flag values before harness -// env validation runs. #6865. -func TestRunAgent_SetsEnvFromFlags(t *testing.T) { +// TestRunAgent_MintURLFromFileFailsClosedInGitHubActions is a regression +// test for review feedback on #8400: downgrading solely on missing OIDC env +// would also silently fall back to the ambient GH_TOKEN inside GitHub +// Actions when a workflow is missing id-token: write — a misconfiguration +// that must fail loudly, not swap in unscoped credentials. The downgrade +// must only apply to a genuine local (non-Actions) run. +func TestRunAgent_MintURLFromFileFailsClosedInGitHubActions(t *testing.T) { useFakeOpenshell(t) dir := t.TempDir() require.NoError(t, os.MkdirAll(filepath.Join(dir, "harness"), 0o755)) @@ -8210,12 +8524,327 @@ func TestRunAgent_SetsEnvFromFlags(t *testing.T) { )) require.NoError(t, os.WriteFile( filepath.Join(dir, "harness", "code.yaml"), - []byte("agent: agents/code.md\nrole: coder\npolicy: policies/base.yaml\nrunner_env:\n MY_REPO: ${REPO_FULL_NAME}\n MY_TARGET: ${TARGET_REPO_DIR}\n MY_ISSUE: ${ISSUE_NUMBER}\n"), + []byte("agent: agents/code.md\nrole: coder\npolicy: policies/base.yaml\n"), 0o644, )) require.NoError(t, os.WriteFile( filepath.Join(dir, "config.yaml"), - []byte("agents:\n - harness/code.yaml\n"), + []byte("agents:\n - harness/code.yaml\nmint_url: https://mint-from-file.example.com\n"), + 0o644, + )) + + // Simulates a workflow missing id-token: write permission: genuinely + // inside GitHub Actions, but the OIDC request env vars never showed up. + t.Setenv("FULLSEND_MINT_URL", "") + t.Setenv("ACTIONS_ID_TOKEN_REQUEST_URL", "") + t.Setenv("ACTIONS_ID_TOKEN_REQUEST_TOKEN", "") + t.Setenv("GITHUB_ACTIONS", "true") + t.Setenv("REPO_FULL_NAME", "org/my-repo") + t.Setenv("GH_TOKEN", "fake-gh-token") + + var buf bytes.Buffer + rFlags := resolveFlags{maxDepth: 10, maxResources: 50} + printer := ui.New(&buf) + repoDir := t.TempDir() + err := runAgent(context.Background(), "code", dir, "", repoDir, "", nil, false, "", "", "", rFlags, statusOpts{}, printer, false, runOverrideFlags{}) + + require.Error(t, err) + assert.Contains(t, err.Error(), "agent token minting failed", "a missing id-token: write permission inside Actions must fail loudly, not fall back to the ambient GH_TOKEN") +} + +func TestRunAgent_MintURLFlagFailsClosedWithoutOIDC(t *testing.T) { + useFakeOpenshell(t) + dir := t.TempDir() + require.NoError(t, os.MkdirAll(filepath.Join(dir, "harness"), 0o755)) + require.NoError(t, os.MkdirAll(filepath.Join(dir, "agents"), 0o755)) + writePolicyFixture(t, dir) + + require.NoError(t, os.WriteFile( + filepath.Join(dir, "agents", "code.md"), + []byte("You are a coding agent."), + 0o644, + )) + require.NoError(t, os.WriteFile( + filepath.Join(dir, "harness", "code.yaml"), + []byte("agent: agents/code.md\nrole: coder\npolicy: policies/base.yaml\n"), + 0o644, + )) + require.NoError(t, os.WriteFile( + filepath.Join(dir, "config.yaml"), + []byte("agents:\n - harness/code.yaml\n"), + 0o644, + )) + + t.Setenv("ACTIONS_ID_TOKEN_REQUEST_URL", "") + t.Setenv("ACTIONS_ID_TOKEN_REQUEST_TOKEN", "") + t.Setenv("REPO_FULL_NAME", "org/my-repo") + t.Setenv("GH_TOKEN", "fake-gh-token") + + var buf bytes.Buffer + rFlags := resolveFlags{maxDepth: 10, maxResources: 50} + printer := ui.New(&buf) + repoDir := t.TempDir() + sOpts := statusOpts{mintURL: "https://mint-from-flag.example.com"} + err := runAgent(context.Background(), "code", dir, "", repoDir, "", nil, false, "", "", "", rFlags, sOpts, printer, false, runOverrideFlags{}) + + require.Error(t, err) + assert.Contains(t, err.Error(), "agent token minting failed", "an explicit --mint-url must stay fail-closed even without OIDC") +} + +func TestRunAgent_MintsRuntimePrivilegeLevel(t *testing.T) { + useFakeOpenshell(t) + dir := t.TempDir() + require.NoError(t, os.MkdirAll(filepath.Join(dir, "harness"), 0o755)) + require.NoError(t, os.MkdirAll(filepath.Join(dir, "agents"), 0o755)) + writePolicyFixture(t, dir) + + require.NoError(t, os.WriteFile( + filepath.Join(dir, "agents", "code.md"), + []byte("You are a coding agent."), + 0o644, + )) + require.NoError(t, os.WriteFile( + filepath.Join(dir, "harness", "code.yaml"), + []byte("agent: agents/code.md\nrole: coder\npolicy: policies/base.yaml\nprivilege_levels:\n runtime: read\n"), + 0o644, + )) + require.NoError(t, os.WriteFile( + filepath.Join(dir, "config.yaml"), + []byte("agents:\n - harness/code.yaml\n"), + 0o644, + )) + + origMint := statusMintToken + defer func() { statusMintToken = origMint }() + + var gotLevel string + statusMintToken = func(_ context.Context, req mintclient.MintRequest) (*mintclient.MintResult, error) { + gotLevel = req.Level + return &mintclient.MintResult{Token: "ghs_read_token", ExpiresAt: "2026-06-15T12:00:00Z"}, nil + } + + t.Setenv("FULLSEND_MINT_URL", "https://mint.example.com") + t.Setenv("REPO_FULL_NAME", "org/my-repo") + t.Setenv("GH_TOKEN", "") + + var buf bytes.Buffer + rFlags := resolveFlags{maxDepth: 10, maxResources: 50} + printer := ui.New(&buf) + repoDir := t.TempDir() + err := runAgent(context.Background(), "code", dir, "", repoDir, "", nil, false, "", "", "", rFlags, statusOpts{}, printer, false, runOverrideFlags{}) + + require.Error(t, err) + assert.Contains(t, err.Error(), "openshell") + assert.Equal(t, "read", gotLevel, "initial mint must request the runtime privilege level") +} + +func TestRunAgent_WarnsWhenNoMintURL(t *testing.T) { + useFakeOpenshell(t) + dir := t.TempDir() + require.NoError(t, os.MkdirAll(filepath.Join(dir, "harness"), 0o755)) + require.NoError(t, os.MkdirAll(filepath.Join(dir, "agents"), 0o755)) + writePolicyFixture(t, dir) + + require.NoError(t, os.WriteFile( + filepath.Join(dir, "agents", "code.md"), + []byte("You are a coding agent."), + 0o644, + )) + require.NoError(t, os.WriteFile( + filepath.Join(dir, "harness", "code.yaml"), + []byte("agent: agents/code.md\nrole: coder\npolicy: policies/base.yaml\n"), + 0o644, + )) + require.NoError(t, os.WriteFile( + filepath.Join(dir, "config.yaml"), + []byte("agents:\n - harness/code.yaml\n"), + 0o644, + )) + + origMint := statusMintToken + defer func() { statusMintToken = origMint }() + + statusMintToken = func(_ context.Context, _ mintclient.MintRequest) (*mintclient.MintResult, error) { + t.Fatal("mint should not be called when no mint URL is available") + return nil, nil + } + + t.Setenv("FULLSEND_MINT_URL", "") + + var buf bytes.Buffer + rFlags := resolveFlags{maxDepth: 10, maxResources: 50} + printer := ui.New(&buf) + repoDir := t.TempDir() + err := runAgent(context.Background(), "code", dir, "", repoDir, "", nil, false, "", "", "", rFlags, statusOpts{}, printer, false, runOverrideFlags{}) + + require.Error(t, err) + assert.Contains(t, buf.String(), "skipping token minting") +} + +func TestRunAgent_MintTokenError(t *testing.T) { + useFakeOpenshell(t) + dir := t.TempDir() + require.NoError(t, os.MkdirAll(filepath.Join(dir, "harness"), 0o755)) + require.NoError(t, os.MkdirAll(filepath.Join(dir, "agents"), 0o755)) + + require.NoError(t, os.WriteFile( + filepath.Join(dir, "agents", "code.md"), + []byte("You are a coding agent."), + 0o644, + )) + require.NoError(t, os.WriteFile( + filepath.Join(dir, "harness", "code.yaml"), + []byte("agent: agents/code.md\nrole: coder\n"), + 0o644, + )) + require.NoError(t, os.WriteFile( + filepath.Join(dir, "config.yaml"), + []byte("agents:\n - harness/code.yaml\n"), + 0o644, + )) + + origMint := statusMintToken + defer func() { statusMintToken = origMint }() + + statusMintToken = func(_ context.Context, _ mintclient.MintRequest) (*mintclient.MintResult, error) { + return nil, fmt.Errorf("OIDC token exchange failed") + } + + t.Setenv("FULLSEND_MINT_URL", "https://mint.example.com") + t.Setenv("REPO_FULL_NAME", "org/my-repo") + + var buf bytes.Buffer + rFlags := resolveFlags{maxDepth: 10, maxResources: 50} + printer := ui.New(&buf) + repoDir := t.TempDir() + err := runAgent(context.Background(), "code", dir, "", repoDir, "", nil, false, "", "", "", rFlags, statusOpts{}, printer, false, runOverrideFlags{}) + + require.Error(t, err) + assert.Contains(t, err.Error(), "agent token minting failed") +} + +// TestRunAgent_GitLabSkipsMint verifies that mintAgentToken is not called +// when --forge=gitlab. Minting is GitHub-only; on GitLab the registered +// role credential serves as the push/API token. #6865 #7499. +func TestRunAgent_GitLabSkipsMint(t *testing.T) { + useFakeOpenshell(t) + dir := t.TempDir() + require.NoError(t, os.MkdirAll(filepath.Join(dir, "harness"), 0o755)) + require.NoError(t, os.MkdirAll(filepath.Join(dir, "agents"), 0o755)) + writePolicyFixture(t, dir) + + require.NoError(t, os.WriteFile( + filepath.Join(dir, "agents", "code.md"), + []byte("You are a coding agent."), + 0o644, + )) + require.NoError(t, os.WriteFile( + filepath.Join(dir, "harness", "code.yaml"), + []byte("agent: agents/code.md\nrole: coder\npolicy: policies/base.yaml\n"), + 0o644, + )) + require.NoError(t, os.WriteFile( + filepath.Join(dir, "config.yaml"), + []byte("agents:\n - harness/code.yaml\n"), + 0o644, + )) + + origMint := statusMintToken + defer func() { statusMintToken = origMint }() + + statusMintToken = func(_ context.Context, _ mintclient.MintRequest) (*mintclient.MintResult, error) { + t.Fatal("mint should not be called on GitLab") + return nil, nil + } + + t.Setenv("FULLSEND_MINT_URL", "https://mint.example.com") + t.Setenv("REPO_FULL_NAME", "org/my-repo") + t.Setenv(forge.SecretForgeToken, "glpat-test-shared") + t.Setenv(forge.SecretGitLabPollerToken, "glpat-test-poller") + t.Setenv(forge.SecretGitLabAnalystToken, "glpat-test-analyst") + t.Setenv(forge.SecretGitLabCoderToken, "glpat-test-coder") + t.Setenv(forge.VarGitLabRoleRegistry, "") + + var buf bytes.Buffer + rFlags := resolveFlags{maxDepth: 10, maxResources: 50} + printer := ui.New(&buf) + repoDir := t.TempDir() + err := runAgent(context.Background(), "code", dir, "", repoDir, "", nil, false, "", "gitlab", "", rFlags, statusOpts{}, printer, false, runOverrideFlags{}) + + // Expect error from openshell, not from minting + require.Error(t, err) + assert.Contains(t, err.Error(), "openshell") + // No "skipping token minting" warning on GitLab + assert.NotContains(t, buf.String(), "skipping token minting") + assert.NotContains(t, buf.String(), "glpat-") +} + +// TestRunAgent_GitLabMissingRoleFailsClosed verifies leftover disabled +// gates no longer fall back to a directly-set GITLAB_TOKEN. Runtime +// authentication requires the registered role secret. +func TestRunAgent_GitLabMissingRoleFailsClosed(t *testing.T) { + useFakeOpenshell(t) + dir := t.TempDir() + require.NoError(t, os.MkdirAll(filepath.Join(dir, "harness"), 0o755)) + require.NoError(t, os.MkdirAll(filepath.Join(dir, "agents"), 0o755)) + + require.NoError(t, os.WriteFile( + filepath.Join(dir, "agents", "code.md"), + []byte("You are a coding agent."), + 0o644, + )) + require.NoError(t, os.WriteFile( + filepath.Join(dir, "harness", "code.yaml"), + []byte("agent: agents/code.md\nrole: coder\n"), + 0o644, + )) + require.NoError(t, os.WriteFile( + filepath.Join(dir, "config.yaml"), + []byte("agents:\n - harness/code.yaml\n"), + 0o644, + )) + + t.Setenv("REPO_FULL_NAME", "org/my-repo") + t.Setenv(forge.SecretForgeToken, "") + t.Setenv(forge.VarGitLabRoleRegistry, "") + t.Setenv("GITLAB_TOKEN", "glpat-preset-by-user") + + var buf bytes.Buffer + rFlags := resolveFlags{maxDepth: 10, maxResources: 50} + printer := ui.New(&buf) + repoDir := t.TempDir() + err := runAgent(context.Background(), "code", dir, "", repoDir, "", nil, false, "", "gitlab", "", rFlags, statusOpts{}, printer, false, runOverrideFlags{}) + + require.Error(t, err) + assert.ErrorIs(t, err, gitlabroles.ErrUnconfigured) + assert.Contains(t, err.Error(), forge.SecretGitLabCoderToken) + assert.NotContains(t, buf.String(), "FULLSEND_FORGE_TOKEN is not set") + assert.NotContains(t, err.Error(), "openshell") +} + +// TestRunAgent_SetsEnvFromFlags verifies that run.go exports TARGET_REPO_DIR, +// REPO_FULL_NAME, and ISSUE_NUMBER from their CLI flag values before harness +// env validation runs. #6865. +func TestRunAgent_SetsEnvFromFlags(t *testing.T) { + useFakeOpenshell(t) + dir := t.TempDir() + require.NoError(t, os.MkdirAll(filepath.Join(dir, "harness"), 0o755)) + require.NoError(t, os.MkdirAll(filepath.Join(dir, "agents"), 0o755)) + writePolicyFixture(t, dir) + + require.NoError(t, os.WriteFile( + filepath.Join(dir, "agents", "code.md"), + []byte("You are a coding agent."), + 0o644, + )) + require.NoError(t, os.WriteFile( + filepath.Join(dir, "harness", "code.yaml"), + []byte("agent: agents/code.md\nrole: coder\npolicy: policies/base.yaml\nrunner_env:\n MY_REPO: ${REPO_FULL_NAME}\n MY_TARGET: ${TARGET_REPO_DIR}\n MY_ISSUE: ${ISSUE_NUMBER}\n"), + 0o644, + )) + require.NoError(t, os.WriteFile( + filepath.Join(dir, "config.yaml"), + []byte("agents:\n - harness/code.yaml\n"), 0o644, )) @@ -8361,6 +8990,161 @@ func TestRunAgent_CancelledReviewUsesCurrentHeadGuidance(t *testing.T) { assert.NotContains(t, body, "/fs-review") } +// TestRunAgent_CancelledReviewMintsFromFileOnlyMintURL guards against a +// regression where the cancellation finalizer's own mint call (distinct +// from the start-comment mint set up by setupStatusNotifierGitHub) passed +// the raw --mint-url flag value straight to newStatusGitHubForgeClient +// instead of resolving it through the same flag > layered config file > +// FULLSEND_MINT_URL precedence as everywhere else. With no flag and no env +// var, that bug minted against "" for the finalizer even though the start +// comment (and the agent-token mint) correctly used config.yaml's mint_url +// (#8400). +func TestRunAgent_CancelledReviewMintsFromFileOnlyMintURL(t *testing.T) { + useFakeOpenshell(t) + dir := t.TempDir() + require.NoError(t, os.MkdirAll(filepath.Join(dir, "harness"), 0o755)) + require.NoError(t, os.MkdirAll(filepath.Join(dir, "agents"), 0o755)) + writePolicyFixture(t, dir) + + require.NoError(t, os.WriteFile( + filepath.Join(dir, "agents", "review.md"), + []byte("You are a review agent."), + 0o644, + )) + require.NoError(t, os.WriteFile( + filepath.Join(dir, "harness", "review.yaml"), + []byte("agent: agents/review.md\nrole: review\npolicy: policies/base.yaml\n"), + 0o644, + )) + require.NoError(t, os.WriteFile( + filepath.Join(dir, "config.yaml"), + []byte("agents:\n - harness/review.yaml\nmint_url: https://mint-from-file.example.com\n"), + 0o644, + )) + + origMint := statusMintToken + origNewClient := statusNewForgeClientFn + t.Cleanup(func() { + statusMintToken = origMint + statusNewForgeClientFn = origNewClient + }) + var mintCalls int + statusMintToken = func(_ context.Context, req mintclient.MintRequest) (*mintclient.MintResult, error) { + mintCalls++ + assert.Equal(t, "https://mint-from-file.example.com", req.MintURL, + "call #%d (role=%s, level=%s) must use config.yaml's mint_url, not \"\"", mintCalls, req.Role, req.Level) + return &mintclient.MintResult{Token: "ghs_test_token", ExpiresAt: "2026-06-15T12:00:00Z"}, nil + } + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + cancel() + fc := forge.NewFakeClient() + fc.PullRequestHeadSHA = "new-head" + statusNewForgeClientFn = func(token string) forge.Client { + assert.Equal(t, "ghs_test_token", token) + return fc + } + + t.Setenv("GITHUB_RUN_ID", "run-42") + t.Setenv("PR_HEAD_SHA", "cancelled-head") + t.Setenv("GH_TOKEN", "") + t.Setenv("PUSH_TOKEN", "") + t.Setenv("PUSH_TOKEN_SOURCE", "") + t.Setenv("FULLSEND_MINT_URL", "") + + var buf bytes.Buffer + // No --mint-url flag: statusOpts.mintURL is left empty so the only + // source of a mint URL is config.yaml's layered mint_url. + err := runAgent(ctx, "review", dir, "", t.TempDir(), "", nil, false, "", "github", "", resolveFlags{maxDepth: 10, maxResources: 50}, statusOpts{ + statusRepo: "org/my-repo", + statusNum: 42, + trackerSource: "github", + }, ui.New(&buf), false, runOverrideFlags{}) + require.Error(t, err) + comments := fc.IssueComments["org/my-repo/42"] + require.NotEmpty(t, comments, "output: %s; all comments: %#v", buf.String(), fc.IssueComments) + body := comments[len(comments)-1].Body + assert.Contains(t, body, "superseded by a newer commit") + // At least the start-comment mint and the finalizer mint must both + // have happened for this regression to be meaningfully covered. + assert.GreaterOrEqual(t, mintCalls, 2, "expected both the start-comment mint and the cancellation-finalizer mint to occur") +} + +// TestRunAgent_CancelledReviewFileMintURLWinsOverEnv guards against the +// same cancellation-finalizer bug as above, but for the case where a +// competing FULLSEND_MINT_URL is also set: the finalizer must mint against +// config.yaml's mint_url (matching the start comment), not silently fall +// back to the env var (#8400). +func TestRunAgent_CancelledReviewFileMintURLWinsOverEnv(t *testing.T) { + useFakeOpenshell(t) + dir := t.TempDir() + require.NoError(t, os.MkdirAll(filepath.Join(dir, "harness"), 0o755)) + require.NoError(t, os.MkdirAll(filepath.Join(dir, "agents"), 0o755)) + writePolicyFixture(t, dir) + + require.NoError(t, os.WriteFile( + filepath.Join(dir, "agents", "review.md"), + []byte("You are a review agent."), + 0o644, + )) + require.NoError(t, os.WriteFile( + filepath.Join(dir, "harness", "review.yaml"), + []byte("agent: agents/review.md\nrole: review\npolicy: policies/base.yaml\n"), + 0o644, + )) + require.NoError(t, os.WriteFile( + filepath.Join(dir, "config.yaml"), + []byte("agents:\n - harness/review.yaml\nmint_url: https://mint-from-file.example.com\n"), + 0o644, + )) + + origMint := statusMintToken + origNewClient := statusNewForgeClientFn + t.Cleanup(func() { + statusMintToken = origMint + statusNewForgeClientFn = origNewClient + }) + var mintCalls int + statusMintToken = func(_ context.Context, req mintclient.MintRequest) (*mintclient.MintResult, error) { + mintCalls++ + assert.Equal(t, "https://mint-from-file.example.com", req.MintURL, + "call #%d (role=%s, level=%s) must use config.yaml's mint_url, not the competing FULLSEND_MINT_URL", mintCalls, req.Role, req.Level) + return &mintclient.MintResult{Token: "ghs_test_token", ExpiresAt: "2026-06-15T12:00:00Z"}, nil + } + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + cancel() + fc := forge.NewFakeClient() + fc.PullRequestHeadSHA = "new-head" + statusNewForgeClientFn = func(token string) forge.Client { + assert.Equal(t, "ghs_test_token", token) + return fc + } + + t.Setenv("GITHUB_RUN_ID", "run-42") + t.Setenv("PR_HEAD_SHA", "cancelled-head") + t.Setenv("GH_TOKEN", "") + t.Setenv("PUSH_TOKEN", "") + t.Setenv("PUSH_TOKEN_SOURCE", "") + // A stale/different value in the environment — simulating a + // repository variable set at install time that the file has since + // overridden without anyone updating the variable. + t.Setenv("FULLSEND_MINT_URL", "https://mint-from-env.example.com") + + var buf bytes.Buffer + err := runAgent(ctx, "review", dir, "", t.TempDir(), "", nil, false, "", "github", "", resolveFlags{maxDepth: 10, maxResources: 50}, statusOpts{ + statusRepo: "org/my-repo", + statusNum: 42, + trackerSource: "github", + }, ui.New(&buf), false, runOverrideFlags{}) + require.Error(t, err) + comments := fc.IssueComments["org/my-repo/42"] + require.NotEmpty(t, comments, "output: %s; all comments: %#v", buf.String(), fc.IssueComments) + body := comments[len(comments)-1].Body + assert.Contains(t, body, "superseded by a newer commit") + assert.GreaterOrEqual(t, mintCalls, 2, "expected both the start-comment mint and the cancellation-finalizer mint to occur") +} + type runStatusEventWriter func(string) func (w runStatusEventWriter) Write(p []byte) (int, error) { diff --git a/internal/config/defaults.go b/internal/config/defaults.go index a1f50f0f0e..e468b511d5 100644 --- a/internal/config/defaults.go +++ b/internal/config/defaults.go @@ -65,6 +65,11 @@ func (d *perRepoDefaults) IsOwnersFileAuthEnabled() bool { return false } // ConfigMintURL returns the default mint URL (hosted public mint). func (d *perRepoDefaults) ConfigMintURL() string { return DefaultPerRepoMintURL } +// ConfigMintURLFromFile returns "" — the compiled-defaults layer has no +// file to read from, so it is always the terminal "nothing in the file" +// case for ConfigMintURLFromFile's overlay/base-only chain. +func (d *perRepoDefaults) ConfigMintURLFromFile() string { return "" } + // ConfigInferenceProvider returns the default inference provider. func (d *perRepoDefaults) ConfigInferenceProvider() string { return DefaultPerRepoInferenceProvider } diff --git a/internal/config/defaults_test.go b/internal/config/defaults_test.go index 995aa27311..57187df173 100644 --- a/internal/config/defaults_test.go +++ b/internal/config/defaults_test.go @@ -31,6 +31,7 @@ func TestPerRepoDefaults_CodeDefaults(t *testing.T) { // Mint/inference operational defaults. assert.Equal(t, DefaultPerRepoMintURL, d.ConfigMintURL()) + assert.Empty(t, d.ConfigMintURLFromFile(), "the defaults layer has no file to read from") assert.Equal(t, DefaultPerRepoInferenceProvider, d.ConfigInferenceProvider()) assert.Equal(t, "", d.ConfigInferenceProject(), "project has no code default") assert.Equal(t, DefaultPerRepoInferenceRegion, d.ConfigInferenceRegion()) @@ -54,6 +55,7 @@ func TestPerRepoConfig_EmptyConfigResolvesDefaults(t *testing.T) { // Mint/inference fields fall through to code defaults. assert.Equal(t, DefaultPerRepoMintURL, cfg.ConfigMintURL()) + assert.Empty(t, cfg.ConfigMintURLFromFile(), "neither file sets mint_url, and the defaults layer is not a file") assert.Equal(t, DefaultPerRepoInferenceProvider, cfg.ConfigInferenceProvider()) assert.Equal(t, "", cfg.ConfigInferenceProject(), "project has no code default") assert.Equal(t, DefaultPerRepoInferenceRegion, cfg.ConfigInferenceRegion()) diff --git a/internal/config/interfaces.go b/internal/config/interfaces.go index b5933f8932..7b1a792238 100644 --- a/internal/config/interfaces.go +++ b/internal/config/interfaces.go @@ -66,6 +66,14 @@ type PerRepoConfigReader interface { ConfigForge() string ConfigTracker() string ConfigMintURL() string + // ConfigMintURLFromFile returns the mint URL as set in config.yaml or + // config.base.yaml only. Empty means neither file sets mint_url — the + // compiled default is not consulted here (contrast with + // ConfigMintURL, which falls all the way through to the compiled + // default). Callers that need to distinguish "the file is silent" from + // "the file resolves to the default" (e.g. fullsend run's + // warn-and-skip-minting fallback) use this instead of ConfigMintURL. + ConfigMintURLFromFile() string ConfigKeepHistory() bool ConfigInferenceProvider() string ConfigInferenceProject() string @@ -419,6 +427,20 @@ func (c *perRepoConfig) ConfigMintURL() string { return "" } +// ConfigMintURLFromFile returns the mint URL as set in config.yaml or +// config.base.yaml only; see the PerRepoConfigReader doc comment for why +// this stops short of the compiled default that ConfigMintURL falls +// through to. +func (c *perRepoConfig) ConfigMintURLFromFile() string { + if c.MintURL != "" { + return c.MintURL + } + if c.parent != nil { + return c.parent.ConfigMintURLFromFile() + } + return "" +} + // ConfigInferenceProvider returns the inference provider (e.g. "vertex"). func (c *perRepoConfig) ConfigInferenceProvider() string { if c.Inference != nil && c.Inference.Provider != "" { diff --git a/internal/config/interfaces_test.go b/internal/config/interfaces_test.go index a704231e04..7e6425bfc6 100644 --- a/internal/config/interfaces_test.go +++ b/internal/config/interfaces_test.go @@ -381,6 +381,40 @@ func TestPerRepoConfig_MintURL_Fallback(t *testing.T) { }) } +// TestPerRepoConfig_MintURLFromFile_Fallback checks that +// ConfigMintURLFromFile stops at "" instead of reaching the compiled +// default — it never asks the perRepoDefaults layer for a value. +func TestPerRepoConfig_MintURLFromFile_Fallback(t *testing.T) { + t.Run("empty falls through to parent", func(t *testing.T) { + parent := &perRepoConfig{ + MintURL: "https://mint.example.com", + parent: &perRepoDefaults{}, + } + overlay := &perRepoConfig{parent: parent} + assert.Equal(t, "https://mint.example.com", overlay.ConfigMintURLFromFile()) + }) + + t.Run("local overrides parent", func(t *testing.T) { + parent := &perRepoConfig{ + MintURL: "https://base-mint.example.com", + parent: &perRepoDefaults{}, + } + overlay := &perRepoConfig{ + MintURL: "https://overlay-mint.example.com", + parent: parent, + } + assert.Equal(t, "https://overlay-mint.example.com", overlay.ConfigMintURLFromFile()) + }) + + t.Run("empty when neither file sets it, unlike ConfigMintURL", func(t *testing.T) { + cfg := &perRepoConfig{parent: &perRepoDefaults{}} + assert.Empty(t, cfg.ConfigMintURLFromFile()) + // Sanity check that this genuinely differs from ConfigMintURL, + // not just a copy-paste of the same assertion. + assert.Equal(t, DefaultPerRepoMintURL, cfg.ConfigMintURL()) + }) +} + // --- Inference provider fallback --- func TestPerRepoConfig_InferenceProvider_Fallback(t *testing.T) { diff --git a/internal/config/load_test.go b/internal/config/load_test.go index 4c35c9534c..a500485146 100644 --- a/internal/config/load_test.go +++ b/internal/config/load_test.go @@ -486,6 +486,7 @@ inference: // Overlay overrides mint_url. assert.Equal(t, "https://overlay-mint.example.com", pcr.ConfigMintURL()) + assert.Equal(t, "https://overlay-mint.example.com", pcr.ConfigMintURLFromFile()) // Inference fields fall through to base. assert.Equal(t, "vertex", pcr.ConfigInferenceProvider()) assert.Equal(t, "base-project", pcr.ConfigInferenceProject()) @@ -493,6 +494,47 @@ inference: assert.Equal(t, "projects/123/locations/global/workloadIdentityPools/pool/providers/prov", pcr.ConfigInferenceWIFProvider()) } +// TestConfigMintURLFromFile_BaseOnly checks that when the overlay +// is silent on mint_url, ConfigMintURLFromFile falls through to the base +// file, same as ConfigMintURL. +func TestConfigMintURLFromFile_BaseOnly(t *testing.T) { + dir := t.TempDir() + base := "version: \"1\"\nmint_url: https://base-mint.example.com\n" + overlay := "version: \"1\"\n" + require.NoError(t, os.WriteFile(filepath.Join(dir, "config.base.yaml"), []byte(base), 0o644)) + require.NoError(t, os.WriteFile(filepath.Join(dir, "config.yaml"), []byte(overlay), 0o644)) + + cfg, err := LoadConfig(dir, LoadOpts{}) + require.NoError(t, err) + + pcr, ok := cfg.(PerRepoConfigReader) + require.True(t, ok) + + assert.Equal(t, "https://base-mint.example.com", pcr.ConfigMintURL()) + assert.Equal(t, "https://base-mint.example.com", pcr.ConfigMintURLFromFile()) +} + +// TestConfigMintURLFromFile_NeitherSet is the critical divergence from +// ConfigMintURL: when neither config.yaml nor config.base.yaml sets +// mint_url, ConfigMintURL falls through to the compiled default +// (DefaultPerRepoMintURL), but ConfigMintURLFromFile stops at "" — it +// never consults the compiled-defaults layer. This is what lets +// fullsend run distinguish "the file is silent" from "the file resolves +// to the default". +func TestConfigMintURLFromFile_NeitherSet(t *testing.T) { + dir := t.TempDir() + require.NoError(t, os.WriteFile(filepath.Join(dir, "config.yaml"), []byte("version: \"1\"\n"), 0o644)) + + cfg, err := LoadConfig(dir, LoadOpts{}) + require.NoError(t, err) + + pcr, ok := cfg.(PerRepoConfigReader) + require.True(t, ok) + + assert.Equal(t, DefaultPerRepoMintURL, pcr.ConfigMintURL()) + assert.Empty(t, pcr.ConfigMintURLFromFile()) +} + func TestLoadConfig_OnlyBase_MintInference(t *testing.T) { dir := t.TempDir() base := `version: "1"