diff --git a/docs/ADRs/0060-cross-org-mint-authorization-via-org-variables.md b/docs/ADRs/0060-cross-org-mint-authorization-via-org-variables.md index 615b9f65fc..1acf06554e 100644 --- a/docs/ADRs/0060-cross-org-mint-authorization-via-org-variables.md +++ b/docs/ADRs/0060-cross-org-mint-authorization-via-org-variables.md @@ -83,3 +83,10 @@ orgs control over their own policy. - Same-org mint for enrolled orgs adds zero FOREIGN API calls; optional `repos` omission uses org-level installation lookup when callers need installation-wide scope. - Pool org provisioning must install the e2e App and set `FULLSEND_FOREIGN_E2E_REPOS` for CI callers. + +## Later note (repos scope hardening) + +Same-org installation-wide tokens and unrestricted `repos` lists are no longer the default. +`repos` authorization is decided in +[ADR 0077](0077-mint-repos-scope-hardening.md). FOREIGN allowlists and `target_org` +from this ADR are unchanged. diff --git a/docs/ADRs/0077-mint-repos-scope-hardening.md b/docs/ADRs/0077-mint-repos-scope-hardening.md new file mode 100644 index 0000000000..361e769e2e --- /dev/null +++ b/docs/ADRs/0077-mint-repos-scope-hardening.md @@ -0,0 +1,54 @@ +--- +title: "77. Mint repos scope hardening with PER_ORG_FOREIGN_COMPAT" +status: Accepted +relates_to: + - agent-infrastructure + - security-threat-model +topics: + - mint + - identity + - oidc + - least-privilege + - cross-org +--- + +# 77. Mint repos scope hardening with PER_ORG_FOREIGN_COMPAT + +Date: 2026-08-02 + +## Status + +Accepted + +## Context + +[ADR 0060](0060-cross-org-mint-authorization-via-org-variables.md) authorized cross-org minting via FOREIGN org variables and treated empty `repos` as installation-wide on both same-org and foreign paths. Same-org callers could also request arbitrary repo lists. That blast radius conflicts with least privilege in the [security threat model](../problems/security-threat-model.md): a compromised enrolled workflow could mint tokens for repos other than the one that authenticated. + +Org-mode dispatch still needs limited exceptions — `.fullsend` callers minting across enrolled repos, and enrolled callers minting `{self,.fullsend}` — without restoring unrestricted same-org scope. + +## Options + +1. **Keep ADR 0060 defaults.** No code change; rely on WIF enrollment alone. Rejected: enrollment does not bound `repos` to the authenticating repository. +2. **Strict requesting-repo only, no exceptions.** Simplest rule. Rejected: breaks established `.fullsend` / org-mode dispatch shapes. +3. **Default-deny with an explicit compat flag.** Deny installation-wide and broad same-org lists by default; gate the known org-mode shapes behind `PER_ORG_FOREIGN_COMPAT`. + +## Decision + +After OIDC verification, the mint enforces `repos` scope as follows: + +1. **Normalize** a sole `["*"]` entry to empty (alias for empty `repos` only). Mixed `*` lists remain invalid pattern input. +2. **Foreign (cross-org)** requests require empty `repos`. Non-empty lists are denied. FOREIGN gating from ADR 0060 still applies. +3. **Same-org** requests must list exactly the requesting repository's bare name. Empty `repos` (installation-wide) is always denied on the same-org path. +4. **`PER_ORG_FOREIGN_COMPAT`** (env / worker config; truthy = `1`/`true`/`yes`) unlocks only these same-org exceptions: + - Caller repository `.fullsend`: any non-empty validated repo list + - Other enrolled callers: exactly `[.fullsend]` or `{requestingBare, .fullsend}` +5. The effective flag is visible on `GET /v1/status` as `per_org_foreign_compat` and in `fullsend mint status` (from traffic env; absent = off). + +This revises the installation-wide and unrestricted same-org `repos` consequences of ADR 0060; FOREIGN allowlists and `target_org` remain as decided there. + +## Consequences + +- Same-org workflows that omitted `repos` or listed unrelated repos break until they request only the calling repo, or operators enable `PER_ORG_FOREIGN_COMPAT` for the documented org-mode shapes. +- Foreign mints cannot carry a non-empty `repos` list; installation-wide foreign tokens remain possible only with empty `repos` plus FOREIGN authorization. +- Hosted and standalone mints must set `PER_ORG_FOREIGN_COMPAT` explicitly where org-mode dispatch is required; the default is off. +- ADR 0060's earlier allowance of same-org installation-wide tokens is superseded for `repos` policy by this decision (FOREIGN mechanism unchanged). diff --git a/docs/architecture.md b/docs/architecture.md index f0db72baae..0b3712e3bd 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -178,7 +178,8 @@ Identity is not the same as trust. An agent's identity lets it authenticate to e - Credential delivery model: four tiers — (1) prefetch + post-process for agents with enumerable inputs (zero credential access), (2) OpenShell providers + L7 egress policies for static token auth (credentials never enter sandbox), (3) host-side REST server for operations providers cannot handle — long-running operations, sandbox capability gaps, credentials in request bodies, response transformation, and multi-step atomic operations (see [ADR 0046](ADRs/0046-host-side-api-server-design.md)), (4) host files + L7 policies for complex auth requiring in-sandbox credential files. L7 policies enforce both method + path and binary-level restrictions. Providers are preferred over REST servers when viable ([ADR 0017](ADRs/0017-credential-isolation-for-sandboxed-agents.md), extended by [ADR 0025](ADRs/0025-provider-credential-delivery-for-sandboxed-agents.md)). - Host-side API server design: Credential delivery tier 3 servers follow a uniform process contract (`--port`, `--token`, `--bind-address`, `/healthz`, `/tools.json`, `SIGTERM`). Network access is controlled via composable provider profiles — atomic capability profiles composed per-harness. Per-run UUID bearer tokens are delivered through OpenShell provider placeholders. File transfer uses `openshell sandbox upload/download` ([ADR 0046](ADRs/0046-host-side-api-server-design.md)). - Per-role GitHub Apps with manifest-based creation. Each agent role gets its own app with scoped permissions. PEMs stored in Secret Manager as `fullsend-{role}-app-pem` — one secret per role, shared across orgs on a mint. `ROLE_APP_IDS` uses the same shared-per-role model (`coder` → app ID). Org isolation is enforced via `ALLOWED_ORGS`, WIF conditions, and installation verification ([ADR 0007](ADRs/0007-per-role-github-apps.md), [ADR 0033](ADRs/0033-per-repo-installation-mode.md)). Public multi-tenant mint (`ALLOWED_ORGS=*`) with upstream-only workflow provenance is defined in [ADR 0059](ADRs/0059-public-mint-mode-with-wildcard-allowlists.md); upstream-only provenance limits which workflows can call the mint, complementing [ADR 0029](ADRs/0029-central-token-mint-secretless-fullsend.md) multi-tenant blast-radius concerns. -- Cross-org mint authorization: workflows may request tokens for a different org via optional `target_org` when the target org installs the role App and sets `FULLSEND_FOREIGN__REPOS`. Empty `repos` yields installation-wide tokens on either path; cross-org adds FOREIGN gating, same-org relies on WIF/OIDC enrollment ([ADR 0060](ADRs/0060-cross-org-mint-authorization-via-org-variables.md)). +- Cross-org mint authorization: workflows may request tokens for a different org via optional `target_org` when the target org installs the role App and sets `FULLSEND_FOREIGN__REPOS` ([ADR 0060](ADRs/0060-cross-org-mint-authorization-via-org-variables.md)). +- Mint `repos` scope: foreign mints require empty `repos` (or `["*"]` as an empty alias). Same-org mints must list exactly the requesting repository by default; `PER_ORG_FOREIGN_COMPAT` unlocks org-mode shapes (broad non-empty lists from `.fullsend`, or `[.fullsend]` / `{self,.fullsend}` from enrolled callers). Same-org installation-wide tokens are denied ([ADR 0077](ADRs/0077-mint-repos-scope-hardening.md)). - Standalone mint deployment: `cmd/mint/` provides a self-contained HTTP server that uses direct JWKS verification and filesystem PEM storage instead of GCP infrastructure. It shares the `internal/mintcore/` library with the GCF mint and adds support for custom role permissions and a fallback proxy to an upstream mint. Custom role permissions live in mintcore (not `cmd/mint/`) so that `RolePermissionsFor`, `HasRole`, and `CreateInstallationToken` return a unified view without callers needing to distinguish built-in from custom roles. The GCF mint never calls `RegisterCustomRolePermissions`, so the code is inert there. See the [standalone mint guide](guides/infrastructure/standalone-mint.md). - Hosted public community mint: steady-state deployment on Cloudflare Workers (JWKS + WAF + single ops console), with interim GCP Cloud Function acceptable until the Worker port is production-ready. Trust policy (`ALLOWED_ORGS=*`, upstream-only workflow provenance) is in [ADR 0059](ADRs/0059-public-mint-mode-with-wildcard-allowlists.md); deployment, edge security, monitoring, and phasing are in [ADR 0068](ADRs/0068-public-community-mint-architecture.md). Enrollment is installing the shared Apps—no per-org mint env registration ([#1145](https://github.com/fullsend-ai/fullsend/issues/1145)). - Named privilege levels: each role defines ordered named levels (`read`, `write`), where each level's permissions are a superset of preceding levels. `read` for built-in roles is derived by downgrading `*:write` permissions to their `read` counterparts. The mint API accepts an optional `level` field (default `read`); omitting it produces narrower tokens than the current behavior. `write` is defined as the current max permission set for each built-in role. `CUSTOM_ROLE_PERMISSIONS` auto-detects a multi-level JSON shape alongside the existing flat format, with mixed format supported per role. The harness `privilege_levels` flag maps run-stages to levels; omitting it defaults to `write`, preserving backward compatibility for existing harness configurations ([ADR 0073](ADRs/0073-named-mint-privilege-levels.md)). diff --git a/docs/guides/infrastructure/infrastructure-reference.md b/docs/guides/infrastructure/infrastructure-reference.md index 26d6f69685..1604f60fb2 100644 --- a/docs/guides/infrastructure/infrastructure-reference.md +++ b/docs/guides/infrastructure/infrastructure-reference.md @@ -132,8 +132,9 @@ A single mint instance can serve multiple orgs: - **Authorization:** Any valid OIDC token from an allowed org — no role restriction - **Response:** ```json - {"org": "my-org", "roles": ["coder", "review", "triage"]} + {"org": "my-org", "roles": ["coder", "review", "triage"], "per_org_foreign_compat": false} ``` + `per_org_foreign_compat` is always present (bool; `false` when `PER_ORG_FOREIGN_COMPAT` is unset). - **Use case:** Workflow diagnostics — discover which roles are available before requesting a token - **Security:** Returns only the requesting org and its role names (not app IDs, not other orgs' roles) diff --git a/docs/guides/infrastructure/standalone-mint.md b/docs/guides/infrastructure/standalone-mint.md index 698ac72706..abc8557707 100644 --- a/docs/guides/infrastructure/standalone-mint.md +++ b/docs/guides/infrastructure/standalone-mint.md @@ -116,6 +116,7 @@ The standalone mint is configured entirely through environment variables: | `FALLBACK_MINT_URL` | Upstream mint URL for roles without local PEMs | `https://fullsend-mint-gljhbkcloq-uc.a.run.app` | | `CUSTOM_ROLE_PERMISSIONS` | JSON map of custom role permissions (see below) | `{"scanner":{"contents":"read"}}` | | `PER_REPO_WIF_REPOS` | Comma-separated repos requiring per-repo WIF | `myorg/private-repo` | +| `PER_ORG_FOREIGN_COMPAT` | When `1`/`true`/`yes`, allow org-mode `repos` shapes: any non-empty list from `.fullsend` callers; `[.fullsend]` or `{self,.fullsend}` from enrolled callers. Default off (same-org = requesting repo only). Does not allow same-org installation-wide tokens. | `true` | | `PORT` | HTTP listen port | `8080` (default) | ### Public mint mode @@ -261,7 +262,7 @@ When `FALLBACK_MINT_URL` is set, the standalone mint acts as a transparent proxy | `POST /v1/token` with a role in `ROLE_APP_IDS` | Handled locally | | `POST /v1/token` with an unknown role | Forwarded to `FALLBACK_MINT_URL` | | `GET /health` | Always handled locally | -| `GET /v1/status` | Always handled locally | +| `GET /v1/status` | Always handled locally (`per_org_foreign_compat` bool; default `false` when unset) | The proxy forwards the original OIDC bearer token and request body to the upstream mint, and returns the upstream response verbatim. The upstream mint performs its own OIDC validation — your organization must be enrolled on the upstream mint for proxied requests to succeed. diff --git a/internal/cli/deploy_identity.go b/internal/cli/deploy_identity.go new file mode 100644 index 0000000000..8020586311 --- /dev/null +++ b/internal/cli/deploy_identity.go @@ -0,0 +1,72 @@ +package cli + +import ( + "bytes" + "fmt" + "os" + "os/exec" + "strings" + + "github.com/fullsend-ai/fullsend/internal/ui" +) + +// revParse runs git rev-parse. Overridden in tests. +var revParse = gitRevParse + +// resolveMintDeployCommit returns the commit to stamp into a mint deploy. +// When commit is already set to something other than "dev"/empty, it is +// returned unchanged. When deploying from on-disk source (sourceDir exists) +// and commit is unset, it tries git -C sourceDir rev-parse HEAD. Embedded +// deploys (missing sourceDir) never invoke git. +// +// If sourceDir exists but git resolution fails, the original commit is +// returned with a non-nil error so callers can warn without failing deploy. +func resolveMintDeployCommit(commit, sourceDir string) (string, error) { + if commit != "" && commit != "dev" { + return commit, nil + } + if sourceDir == "" { + return commit, nil + } + info, err := os.Stat(sourceDir) + if err != nil || !info.IsDir() { + return commit, nil + } + sha, err := revParse(sourceDir, "HEAD") + if err != nil { + return commit, fmt.Errorf("git rev-parse HEAD in %s: %w", sourceDir, err) + } + if sha == "" { + return commit, fmt.Errorf("git rev-parse HEAD in %s returned empty", sourceDir) + } + return sha, nil +} + +// resolveAndReportMintDeployCommit resolves the deploy commit and prints +// warn/info messages for the operator. Always returns a stamp value +// (possibly still "dev"/empty on failure). +func resolveAndReportMintDeployCommit(printer *ui.Printer, commit, sourceDir string) string { + deployCommit, resolveErr := resolveMintDeployCommit(commit, sourceDir) + if resolveErr != nil { + printer.StepWarn(fmt.Sprintf("Could not resolve mint commit from checkout: %v", resolveErr)) + } else if deployCommit != commit && deployCommit != "" && deployCommit != "dev" { + printer.StepInfo(fmt.Sprintf("Resolved mint commit from checkout: %s", deployCommit)) + } + return deployCommit +} + +func gitRevParse(dir string, args ...string) (string, error) { + cmdArgs := append([]string{"-C", dir, "rev-parse"}, args...) + cmd := exec.Command("git", cmdArgs...) + var stdout, stderr bytes.Buffer + cmd.Stdout = &stdout + cmd.Stderr = &stderr + if err := cmd.Run(); err != nil { + msg := strings.TrimSpace(stderr.String()) + if msg != "" { + return "", fmt.Errorf("%w: %s", err, msg) + } + return "", err + } + return strings.TrimSpace(stdout.String()), nil +} diff --git a/internal/cli/deploy_identity_test.go b/internal/cli/deploy_identity_test.go new file mode 100644 index 0000000000..5485b9e465 --- /dev/null +++ b/internal/cli/deploy_identity_test.go @@ -0,0 +1,235 @@ +package cli + +import ( + "errors" + "os" + "os/exec" + "path/filepath" + "regexp" + "strings" + "testing" + + "github.com/fullsend-ai/fullsend/internal/ui" +) + +func TestResolveMintDeployCommit_PreservesNonDev(t *testing.T) { + t.Parallel() + got, err := resolveMintDeployCommit("abc123def", "/nonexistent") + if err != nil { + t.Fatalf("unexpected err: %v", err) + } + if got != "abc123def" { + t.Fatalf("got %q, want preserved commit", got) + } +} + +func TestResolveMintDeployCommit_MissingSourceDir(t *testing.T) { + t.Parallel() + dir := filepath.Join(t.TempDir(), "no-such-dir") + got, err := resolveMintDeployCommit("dev", dir) + if err != nil { + t.Fatalf("unexpected err: %v", err) + } + if got != "dev" { + t.Fatalf("got %q, want dev when source missing", got) + } + got, err = resolveMintDeployCommit("", "") + if err != nil { + t.Fatalf("unexpected err: %v", err) + } + if got != "" { + t.Fatalf("got %q, want empty when sourceDir empty", got) + } +} + +func TestResolveMintDeployCommit_SourceNotDirectory(t *testing.T) { + t.Parallel() + f := filepath.Join(t.TempDir(), "file") + if err := os.WriteFile(f, []byte("x\n"), 0o644); err != nil { + t.Fatal(err) + } + got, err := resolveMintDeployCommit("dev", f) + if err != nil { + t.Fatalf("unexpected err: %v", err) + } + if got != "dev" { + t.Fatalf("got %q, want dev when sourceDir is a file", got) + } +} + +func TestResolveMintDeployCommit_NotAGitRepo(t *testing.T) { + t.Parallel() + dir := t.TempDir() + got, err := resolveMintDeployCommit("dev", dir) + if err == nil { + t.Fatal("expected error when sourceDir is not a git work tree") + } + if got != "dev" { + t.Fatalf("got %q, want dev when not a git work tree", got) + } +} + +func TestResolveMintDeployCommit_EmptySHA(t *testing.T) { + old := revParse + revParse = func(string, ...string) (string, error) { return "", nil } + t.Cleanup(func() { revParse = old }) + + got, err := resolveMintDeployCommit("dev", t.TempDir()) + if err == nil { + t.Fatal("expected error for empty SHA") + } + if !strings.Contains(err.Error(), "returned empty") { + t.Fatalf("unexpected err: %v", err) + } + if got != "dev" { + t.Fatalf("got %q, want dev", got) + } +} + +func TestGitRevParse_IncludesStderr(t *testing.T) { + t.Parallel() + _, err := gitRevParse(t.TempDir(), "HEAD") + if err == nil { + t.Fatal("expected error") + } + // Non-repo dirs produce stderr from git; ensure it is wrapped in. + if !strings.Contains(err.Error(), "exit status") && !strings.Contains(err.Error(), "not a git") { + t.Fatalf("unexpected err: %v", err) + } +} + +func TestGitRevParse_ErrorWithoutStderr(t *testing.T) { + dir := t.TempDir() + fakeGit := filepath.Join(dir, "git") + if err := os.WriteFile(fakeGit, []byte("#!/bin/sh\nexit 1\n"), 0o755); err != nil { + t.Fatal(err) + } + t.Setenv("PATH", dir) + _, err := gitRevParse(t.TempDir(), "HEAD") + if err == nil { + t.Fatal("expected error") + } +} + +func TestResolveMintDeployCommit_FromCheckout(t *testing.T) { + t.Parallel() + dir := t.TempDir() + runGit := func(args ...string) { + t.Helper() + cmd := exec.Command("git", append([]string{"-C", dir}, args...)...) + cmd.Env = append(os.Environ(), + "GIT_CONFIG_COUNT=1", + "GIT_CONFIG_KEY_0=commit.gpgsign", + "GIT_CONFIG_VALUE_0=false", + ) + out, err := cmd.CombinedOutput() + if err != nil { + t.Fatalf("git %v: %v\n%s", args, err, out) + } + } + runGit("init") + runGit("config", "user.email", "test@example.com") + runGit("config", "user.name", "Test") + if err := os.WriteFile(filepath.Join(dir, "README"), []byte("x\n"), 0o644); err != nil { + t.Fatal(err) + } + runGit("add", "README") + runGit("commit", "-m", "init") + + wantCmd := exec.Command("git", "-C", dir, "rev-parse", "HEAD") + wantOut, err := wantCmd.Output() + if err != nil { + t.Fatal(err) + } + want := strings.TrimSpace(string(wantOut)) + + got, err := resolveMintDeployCommit("dev", dir) + if err != nil { + t.Fatalf("unexpected err: %v", err) + } + if got != want { + t.Fatalf("got %q, want %q", got, want) + } + if !regexp.MustCompile(`^[0-9a-f]{40}$`).MatchString(got) { + t.Fatalf("expected full SHA, got %q", got) + } + + got, err = resolveMintDeployCommit("", dir) + if err != nil { + t.Fatalf("unexpected err: %v", err) + } + if got != want { + t.Fatalf("empty commit: got %q, want %q", got, want) + } +} + +func TestResolveAndReportMintDeployCommit_WarnOnFailure(t *testing.T) { + out := &strings.Builder{} + printer := ui.New(out) + got := resolveAndReportMintDeployCommit(printer, "dev", t.TempDir()) + if got != "dev" { + t.Fatalf("got %q, want dev", got) + } + if !strings.Contains(out.String(), "Could not resolve mint commit from checkout") { + t.Fatalf("expected warn in output, got %q", out.String()) + } +} + +func TestResolveAndReportMintDeployCommit_InfoOnSuccess(t *testing.T) { + dir := t.TempDir() + runGit := func(args ...string) { + t.Helper() + cmd := exec.Command("git", append([]string{"-C", dir}, args...)...) + cmd.Env = append(os.Environ(), + "GIT_CONFIG_COUNT=1", + "GIT_CONFIG_KEY_0=commit.gpgsign", + "GIT_CONFIG_VALUE_0=false", + ) + if out, err := cmd.CombinedOutput(); err != nil { + t.Fatalf("git %v: %v\n%s", args, err, out) + } + } + runGit("init") + runGit("config", "user.email", "test@example.com") + runGit("config", "user.name", "Test") + if err := os.WriteFile(filepath.Join(dir, "README"), []byte("x\n"), 0o644); err != nil { + t.Fatal(err) + } + runGit("add", "README") + runGit("commit", "-m", "init") + + out := &strings.Builder{} + printer := ui.New(out) + got := resolveAndReportMintDeployCommit(printer, "dev", dir) + if got == "dev" || got == "" { + t.Fatalf("expected resolved SHA, got %q", got) + } + if !strings.Contains(out.String(), "Resolved mint commit from checkout") { + t.Fatalf("expected info in output, got %q", out.String()) + } +} + +func TestResolveAndReportMintDeployCommit_PreservesExplicit(t *testing.T) { + out := &strings.Builder{} + printer := ui.New(out) + got := resolveAndReportMintDeployCommit(printer, "abc123", t.TempDir()) + if got != "abc123" { + t.Fatalf("got %q", got) + } + if strings.Contains(out.String(), "resolve") || strings.Contains(out.String(), "Resolved") { + t.Fatalf("unexpected resolve messaging: %q", out.String()) + } +} + +func TestRevParseHook_ErrorWithoutStderr(t *testing.T) { + old := revParse + revParse = func(string, ...string) (string, error) { + return "", errors.New("boom") + } + t.Cleanup(func() { revParse = old }) + + _, err := resolveMintDeployCommit("dev", t.TempDir()) + if err == nil || !strings.Contains(err.Error(), "boom") { + t.Fatalf("unexpected err: %v", err) + } +} diff --git a/internal/cli/mint.go b/internal/cli/mint.go index 0a6ca887fb..b3ac68529e 100644 --- a/internal/cli/mint.go +++ b/internal/cli/mint.go @@ -93,6 +93,18 @@ func isPublicMintAllowedOrgs(allowedOrgs string) bool { return mintcore.IsPublicMint(parseAllowedOrgs(allowedOrgs)) } +// perOrgForeignCompatLabel returns "on" or "off" for display from traffic env. +// Missing/empty/nil trafficEnv is treated as off (compatible with older mints). +func perOrgForeignCompatLabel(trafficEnv map[string]string) string { + if trafficEnv == nil { + return "off" + } + if mintcore.EnvTruthy(trafficEnv["PER_ORG_FOREIGN_COMPAT"]) { + return "on" + } + return "off" +} + // mintValidationMessage returns the success message after validating an existing mint. func mintValidationMessage(trafficEnv map[string]string, envErr error) string { if envErr == nil && isPublicMintAllowedOrgs(trafficEnv["ALLOWED_ORGS"]) { @@ -533,6 +545,8 @@ func runMintDeployGCP(ctx context.Context, project, region, sourceDir string, sk gcpClient := mintGCFClientFactory(project) + deployCommit := resolveAndReportMintDeployCommit(printer, commitSHA, sourceDir) + deployMode := gcf.DeployAuto if skipDeploy { deployMode = gcf.DeploySkip @@ -544,7 +558,7 @@ func runMintDeployGCP(ctx context.Context, project, region, sourceDir string, sk FunctionSourceDir: sourceDir, DeployMode: deployMode, Version: version, - Commit: commitSHA, + Commit: deployCommit, PublicMint: public, } @@ -583,6 +597,8 @@ func runMintDeployGCP(ctx context.Context, project, region, sourceDir string, sk fmt.Sprintf("Project: %s", project), fmt.Sprintf("Region: %s", region), fmt.Sprintf("URL: %s", mintURL), + fmt.Sprintf("Version: %s", version), + fmt.Sprintf("Commit: %s", deployCommit), } if pemDir != "" { summaryLines = append(summaryLines, fmt.Sprintf("App set: %s (PEMs bootstrapped)", appsetup.DefaultAppSet)) @@ -661,6 +677,8 @@ func runMintDeployCloudflare(ctx context.Context, workerName, sourceDir, preview return nil } + deployCommit := resolveAndReportMintDeployCommit(printer, commitSHA, sourceDir) + cfg := cf.Config{ AccountID: accountID, WorkerName: workerName, @@ -668,7 +686,7 @@ func runMintDeployCloudflare(ctx context.Context, workerName, sourceDir, preview PreviewAlias: previewAlias, SourceDir: sourceDir, Version: version, - Commit: commitSHA, + Commit: deployCommit, } wrangler := mintCFWranglerFactory(accountID) @@ -700,6 +718,10 @@ func runMintDeployCloudflare(ctx context.Context, workerName, sourceDir, preview } else { summaryLines = append(summaryLines, "Mode: durable") } + summaryLines = append(summaryLines, + fmt.Sprintf("Version: %s", version), + fmt.Sprintf("Commit: %s", deployCommit), + ) printer.Summary("Deployment complete", summaryLines) return nil @@ -1517,6 +1539,8 @@ func runMintStatus(ctx context.Context, printer *ui.Printer, project, region, or } roleOnlyIDs := mintcore.RoleOnlyAppIDs(roleAppIDs) + printer.KeyValue("Per-org foreign compat", perOrgForeignCompatLabel(trafficEnv)) + publicMint := trafficEnv != nil && isPublicMintAllowedOrgs(trafficEnv["ALLOWED_ORGS"]) if publicMint { printer.Blank() diff --git a/internal/cli/mint_test.go b/internal/cli/mint_test.go index 4d1f842d30..a450960c53 100644 --- a/internal/cli/mint_test.go +++ b/internal/cli/mint_test.go @@ -2,6 +2,7 @@ package cli import ( "bufio" + "bytes" "context" "crypto/rand" "crypto/rsa" @@ -169,6 +170,44 @@ func TestMintDeployCmd_DryRun(t *testing.T) { require.NoError(t, err) } +func TestRunMintDeployGCP_SkipDeployReportsCommitResolution(t *testing.T) { + withMintGCFClient(t, gcf.NewFakeGCFClient( + gcf.WithFakeFunctionInfo(&gcf.FunctionInfo{ + URI: "https://fullsend-mint-abc123-uc.a.run.app", + State: "ACTIVE", + EnvVars: map[string]string{ + "ROLE_APP_IDS": `{"coder":"100"}`, + "ALLOWED_ORGS": "existing-org", + }, + }), + gcf.WithFakeTrafficEnvVars(map[string]string{ + "ROLE_APP_IDS": `{"coder":"100"}`, + "ALLOWED_ORGS": "existing-org", + }), + gcf.WithFakeWIFProvider(&gcf.WIFProviderInfo{ + AttributeCondition: "assertion.repository_owner in ['existing-org']", + }), + )) + + r, w, err := os.Pipe() + require.NoError(t, err) + oldStdout := os.Stdout + os.Stdout = w + deployErr := runMintDeployGCP(context.Background(), "my-project-id", "us-central1", t.TempDir(), true, false, "", false) + require.NoError(t, w.Close()) + os.Stdout = oldStdout + require.NoError(t, deployErr) + + var buf bytes.Buffer + _, copyErr := io.Copy(&buf, r) + require.NoError(t, copyErr) + out := buf.String() + assert.Contains(t, out, "Could not resolve mint commit from checkout") + assert.Contains(t, out, "Version:") + assert.Contains(t, out, "Commit:") + assert.Contains(t, out, "Deployment complete") +} + func TestMintDeployCmd_DryRunShowsResolvedSource(t *testing.T) { // When --source-dir is not provided and the default checkout path // exists on disk, dry-run should show the resolved path. @@ -1182,6 +1221,16 @@ func TestIsPublicMintAllowedOrgs(t *testing.T) { assert.False(t, isPublicMintAllowedOrgs("")) } +func TestPerOrgForeignCompatLabel(t *testing.T) { + assert.Equal(t, "off", perOrgForeignCompatLabel(nil)) + assert.Equal(t, "off", perOrgForeignCompatLabel(map[string]string{})) + assert.Equal(t, "off", perOrgForeignCompatLabel(map[string]string{"PER_ORG_FOREIGN_COMPAT": ""})) + assert.Equal(t, "off", perOrgForeignCompatLabel(map[string]string{"PER_ORG_FOREIGN_COMPAT": "false"})) + assert.Equal(t, "on", perOrgForeignCompatLabel(map[string]string{"PER_ORG_FOREIGN_COMPAT": "true"})) + assert.Equal(t, "on", perOrgForeignCompatLabel(map[string]string{"PER_ORG_FOREIGN_COMPAT": "1"})) + assert.Equal(t, "on", perOrgForeignCompatLabel(map[string]string{"PER_ORG_FOREIGN_COMPAT": "YES"})) +} + func TestMintValidationMessage(t *testing.T) { assert.Equal(t, "Mint validated (public mode — org registration not required)", mintValidationMessage(map[string]string{"ALLOWED_ORGS": "*"}, nil)) @@ -1466,6 +1515,55 @@ func TestRunMintStatus_Healthy(t *testing.T) { require.NoError(t, err) assert.Contains(t, out.String(), "coder = 100") assert.Contains(t, out.String(), "existing-org") + // Older mints omit PER_ORG_FOREIGN_COMPAT; status treats missing as off. + assert.Contains(t, out.String(), "Per-org foreign compat") + assert.Contains(t, out.String(), "off") +} + +func TestRunMintStatus_PerOrgForeignCompatOn(t *testing.T) { + client := gcf.NewFakeGCFClient( + gcf.WithFakeFunctionInfo(&gcf.FunctionInfo{ + URI: "https://mint.example.com", + EnvVars: map[string]string{ + "ROLE_APP_IDS": `{"coder":"100"}`, + "ALLOWED_ORGS": "test-org", + "PER_ORG_FOREIGN_COMPAT": "true", + }, + }), + gcf.WithFakeTrafficEnvVars(map[string]string{ + "ROLE_APP_IDS": `{"coder":"100"}`, + "ALLOWED_ORGS": "test-org", + "PER_ORG_FOREIGN_COMPAT": "true", + }), + gcf.WithFakeRevisionInfo(&gcf.ServiceRevisionInfo{ + TrafficRevisionShort: "fullsend-mint-00001", + TrafficPercent: 100, + TemplateMatchesTraffic: true, + TrafficEnvVars: map[string]string{ + "ROLE_APP_IDS": `{"coder":"100"}`, + "ALLOWED_ORGS": "test-org", + "PER_ORG_FOREIGN_COMPAT": "true", + }, + RecentRevisions: []gcf.RevisionSummary{{ + Name: "fullsend-mint-00001", + CreateTime: "2026-06-16T12:00:00Z", + Active: true, + }}, + }), + gcf.WithFakeWIFProvider(&gcf.WIFProviderInfo{ + AttributeCondition: "assertion.repository_owner in ['test-org']", + }), + gcf.WithFakeSecrets(map[string]bool{ + "fullsend-coder-pem": true, + }), + ) + withMintGCFClient(t, client) + out := &strings.Builder{} + printer := ui.New(out) + err := runMintStatus(context.Background(), printer, "my-project", "us-central1", "test-org") + require.NoError(t, err) + assert.Contains(t, out.String(), "Per-org foreign compat") + assert.Contains(t, out.String(), "on") } func TestRunMintStatus_WithHealthVersion(t *testing.T) { diff --git a/internal/dispatch/cf/workersrc/src/index.ts b/internal/dispatch/cf/workersrc/src/index.ts index 70ab53bdb0..c541dbc94e 100644 --- a/internal/dispatch/cf/workersrc/src/index.ts +++ b/internal/dispatch/cf/workersrc/src/index.ts @@ -63,6 +63,8 @@ export interface Env { PER_REPO_WIF_REPOS?: string; /** JSON-encoded map of custom role permissions. */ CUSTOM_ROLE_PERMISSIONS?: string; + /** When truthy (1/true/yes), enable org-mode repos scope exceptions. */ + PER_ORG_FOREIGN_COMPAT?: string; /** * Dynamic secret access: Worker secrets are accessed by name. @@ -164,6 +166,7 @@ function buildWasmConfig(env: Env): string { AllowedWorkflowFiles: env.ALLOWED_WORKFLOW_FILES ?? "", PerRepoWIFRepos: env.PER_REPO_WIF_REPOS ?? "", CustomRolePermissions: env.CUSTOM_ROLE_PERMISSIONS ?? "", + PerOrgForeignCompat: env.PER_ORG_FOREIGN_COMPAT ?? "", // Version constants are imported from the generated version.ts file // (written by writeVersionTS at deploy time) rather than read from // env vars, so they cannot diverge from the deployed code. diff --git a/internal/dispatch/gcf/mintsrc/mintcore/config.go.embed b/internal/dispatch/gcf/mintsrc/mintcore/config.go.embed index 35e456758f..018f309d3c 100644 --- a/internal/dispatch/gcf/mintsrc/mintcore/config.go.embed +++ b/internal/dispatch/gcf/mintsrc/mintcore/config.go.embed @@ -43,6 +43,11 @@ type WorkerConfig struct { // Commit is the git SHA stamped on the deployed Worker. Commit string + + // PerOrgForeignCompat enables org-mode repos scope exceptions. + // Same format as the PER_ORG_FOREIGN_COMPAT environment variable + // (truthy: "1", "true", "yes"). + PerOrgForeignCompat string } // ParseWorkerConfig parses a WorkerConfig and returns a Handler. @@ -80,7 +85,12 @@ func ParseWorkerConfig(cfg WorkerConfig, pemAccessor PEMAccessor, oidcVerifier O } } - return NewHandlerFromConfig(cfg.RoleAppIDs, cfg.AllowedRoles, pemAccessor, oidcVerifier, httpClient) + h, err := NewHandlerFromConfig(cfg.RoleAppIDs, cfg.AllowedRoles, pemAccessor, oidcVerifier, httpClient) + if err != nil { + return nil, err + } + h.perOrgForeignCompat = EnvTruthy(cfg.PerOrgForeignCompat) + return h, nil } // SplitCSV splits a comma-separated string into trimmed, non-empty entries. diff --git a/internal/dispatch/gcf/mintsrc/mintcore/handler.go.embed b/internal/dispatch/gcf/mintsrc/mintcore/handler.go.embed index 8b951277d4..0f07754177 100644 --- a/internal/dispatch/gcf/mintsrc/mintcore/handler.go.embed +++ b/internal/dispatch/gcf/mintsrc/mintcore/handler.go.embed @@ -42,10 +42,11 @@ type mintResponse struct { // statusResponse is returned by the /v1/status diagnostic endpoint. type statusResponse struct { - Org string `json:"org"` - Roles []string `json:"roles"` - Version string `json:"version,omitempty"` - Commit string `json:"commit,omitempty"` + Org string `json:"org"` + Roles []string `json:"roles"` + Version string `json:"version,omitempty"` + Commit string `json:"commit,omitempty"` + PerOrgForeignCompat bool `json:"per_org_foreign_compat"` } // Handler holds dependencies for the token mint HTTP server. @@ -64,6 +65,9 @@ type Handler struct { foreignInflight map[string]*foreignInflight foreignCacheTTL time.Duration foreignCacheMu sync.Mutex + + // perOrgForeignCompat enables org-mode repos shapes under PER_ORG_FOREIGN_COMPAT. + perOrgForeignCompat bool } type foreignInflight struct { @@ -82,13 +86,14 @@ func NewHandler(pemAccessor PEMAccessor, oidcVerifier OIDCVerifier) (*Handler, e httpClient := &http.Client{Timeout: 30 * time.Second} h := &Handler{ - httpClient: httpClient, - pemAccessor: pemAccessor, - oidcVerifier: oidcVerifier, - githubBaseURL: "https://api.github.com", - foreignCache: make(map[string]foreignCacheEntry), - foreignInflight: make(map[string]*foreignInflight), - foreignCacheTTL: defaultForeignCacheTTL, + httpClient: httpClient, + pemAccessor: pemAccessor, + oidcVerifier: oidcVerifier, + githubBaseURL: "https://api.github.com", + foreignCache: make(map[string]foreignCacheEntry), + foreignInflight: make(map[string]*foreignInflight), + foreignCacheTTL: defaultForeignCacheTTL, + perOrgForeignCompat: EnvTruthy(os.Getenv("PER_ORG_FOREIGN_COMPAT")), } if raw := os.Getenv("ROLE_APP_IDS"); raw != "" { @@ -200,6 +205,8 @@ func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { return } + req.Repos = normalizeMintRepos(req.Repos) + if len(req.Repos) > maxRepos { writeError(w, http.StatusBadRequest, fmt.Sprintf("too many repos (max %d)", maxRepos)) return @@ -233,6 +240,17 @@ func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { targetOrg = callerOrg } + isTargetForeign := !strings.EqualFold(targetOrg, callerOrg) + shape, err := validateReposScope(isTargetForeign, claims.Repository, req.Repos, h.perOrgForeignCompat) + if err != nil { + writeError(w, http.StatusForbidden, err.Error()) + return + } + if shape != "" { + log.Printf("PER_ORG_FOREIGN_COMPAT allowed repos scope shape=%s requested_repos=%v source_repo=%s target_org=%s role=%s", + shape, req.Repos, claims.Repository, targetOrg, req.Role) + } + if len(req.Repos) == 0 { log.Printf("WARNING: mint request omitted repos; issuing installation-wide token for target_org=%s role=%s caller_org=%s source_repo=%s", targetOrg, req.Role, callerOrg, claims.Repository) @@ -241,7 +259,7 @@ func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { var token, expiresAt string var granted *GrantedScope - if strings.EqualFold(targetOrg, callerOrg) { + if !isTargetForeign { token, expiresAt, granted, err = h.mintToken(ctx, callerOrg, req.Role, req.Repos) } else { token, expiresAt, granted, err = h.mintTokenCrossOrg(ctx, claims, targetOrg, req.Role, req.Repos) @@ -328,10 +346,11 @@ func (h *Handler) handleStatus(w http.ResponseWriter, claims *Claims) { w.Header().Set("Cache-Control", "no-store") w.WriteHeader(http.StatusOK) if err := json.NewEncoder(w).Encode(statusResponse{ - Org: org, - Roles: roles, - Version: Version, - Commit: Commit, + Org: org, + Roles: roles, + Version: Version, + Commit: Commit, + PerOrgForeignCompat: h.perOrgForeignCompat, }); err != nil { log.Printf("encoding status response: %v", err) } diff --git a/internal/dispatch/gcf/mintsrc/mintcore/repos_scope.go.embed b/internal/dispatch/gcf/mintsrc/mintcore/repos_scope.go.embed new file mode 100644 index 0000000000..cd9093ca01 --- /dev/null +++ b/internal/dispatch/gcf/mintsrc/mintcore/repos_scope.go.embed @@ -0,0 +1,89 @@ +package mintcore + +import ( + "fmt" + "strings" +) + +// Compat shape labels returned by validateReposScope when PER_ORG_FOREIGN_COMPAT +// allows a broader-than-self same-org repos list. Empty means the default path +// (foreign empty repos, or same-org requesting-repo-only). +const ( + reposScopeShapeFullsendAny = "fullsend-any" + reposScopeShapeEnrolledFullsend = "enrolled-fullsend" + reposScopeShapeEnrolledPair = "enrolled-pair" +) + +// normalizeMintRepos treats a single "*" entry as an alias for an empty +// repos list (installation-wide scope on the foreign path). +func normalizeMintRepos(repos []string) []string { + if len(repos) == 1 && repos[0] == "*" { + return nil + } + return repos +} + +// EnvTruthy reports whether v is a truthy feature-flag value. +func EnvTruthy(v string) bool { + switch strings.ToLower(strings.TrimSpace(v)) { + case "1", "true", "yes": + return true + default: + return false + } +} + +// repositoryBareName returns the repository name without the org prefix. +func repositoryBareName(repository string) string { + parts := strings.Split(repository, "/") + return parts[len(parts)-1] +} + +// validateReposScope enforces mint repos authorization after OIDC verification. +// +// Foreign (cross-org) requests may only omit repos (or use "*" → empty). +// Same-org requests must list exactly the requesting repository, unless +// PER_ORG_FOREIGN_COMPAT is on: +// - caller .fullsend: any non-empty validated list +// - other callers: exactly [.fullsend] or {requestingBare, .fullsend} +// +// On success, shape is non-empty only when a compat exception matched. +func validateReposScope(isTargetForeign bool, requestingRepo string, repos []string, compat bool) (shape string, err error) { + if isTargetForeign { + if len(repos) != 0 { + return "", fmt.Errorf("foreign mint requires empty repos") + } + return "", nil + } + + if len(repos) == 0 { + return "", fmt.Errorf("same-org mint requires non-empty repos") + } + + bare := repositoryBareName(requestingRepo) + if len(repos) == 1 && strings.EqualFold(repos[0], bare) { + return "", nil + } + + if !compat { + return "", fmt.Errorf("same-org mint requires repos to be exactly the requesting repository") + } + + if strings.EqualFold(bare, ".fullsend") { + return reposScopeShapeFullsendAny, nil + } + + if len(repos) == 1 && strings.EqualFold(repos[0], ".fullsend") { + return reposScopeShapeEnrolledFullsend, nil + } + + if len(repos) == 2 { + a, b := repos[0], repos[1] + if (strings.EqualFold(a, bare) && strings.EqualFold(b, ".fullsend")) || + (strings.EqualFold(b, bare) && strings.EqualFold(a, ".fullsend")) { + return reposScopeShapeEnrolledPair, nil + } + } + + return "", fmt.Errorf("repos scope not allowed under PER_ORG_FOREIGN_COMPAT for requesting repository") +} diff --git a/internal/dispatch/gcf/provisioner.go b/internal/dispatch/gcf/provisioner.go index c38684f457..125fcd7981 100644 --- a/internal/dispatch/gcf/provisioner.go +++ b/internal/dispatch/gcf/provisioner.go @@ -43,7 +43,7 @@ const ( // ErrFunctionNotFound is returned when the mint function does not exist. var ErrFunctionNotFound = errors.New("mint function not found") -//go:embed mintsrc/go.mod.embed mintsrc/go.sum.embed mintsrc/main.go.embed mintsrc/mintcore/go.mod.embed mintsrc/mintcore/go.sum.embed mintsrc/mintcore/claims.go.embed mintsrc/mintcore/config.go.embed mintsrc/mintcore/foreign.go.embed mintsrc/mintcore/gcp_pem.go.embed mintsrc/mintcore/github.go.embed mintsrc/mintcore/handler.go.embed mintsrc/mintcore/interfaces.go.embed mintsrc/mintcore/jwks_verifier.go.embed mintsrc/mintcore/patterns.go.embed mintsrc/mintcore/sts_verifier.go.embed mintsrc/mintcore/version.go.embed mintsrc/mintcore/wif.go.embed +//go:embed mintsrc/go.mod.embed mintsrc/go.sum.embed mintsrc/main.go.embed mintsrc/mintcore/go.mod.embed mintsrc/mintcore/go.sum.embed mintsrc/mintcore/claims.go.embed mintsrc/mintcore/config.go.embed mintsrc/mintcore/foreign.go.embed mintsrc/mintcore/gcp_pem.go.embed mintsrc/mintcore/github.go.embed mintsrc/mintcore/handler.go.embed mintsrc/mintcore/interfaces.go.embed mintsrc/mintcore/jwks_verifier.go.embed mintsrc/mintcore/patterns.go.embed mintsrc/mintcore/repos_scope.go.embed mintsrc/mintcore/sts_verifier.go.embed mintsrc/mintcore/version.go.embed mintsrc/mintcore/wif.go.embed var embeddedMintSource embed.FS // embeddedMintFiles maps embedded filenames (.embed suffix avoids @@ -64,6 +64,7 @@ var embeddedMintFiles = map[string]string{ "mintcore/interfaces.go.embed": "mintcore/interfaces.go", "mintcore/jwks_verifier.go.embed": "mintcore/jwks_verifier.go", "mintcore/patterns.go.embed": "mintcore/patterns.go", + "mintcore/repos_scope.go.embed": "mintcore/repos_scope.go", "mintcore/sts_verifier.go.embed": "mintcore/sts_verifier.go", "mintcore/version.go.embed": "mintcore/version.go", "mintcore/wif.go.embed": "mintcore/wif.go", diff --git a/internal/dispatch/gcf/provisioner_test.go b/internal/dispatch/gcf/provisioner_test.go index 52b087af75..e843ca0981 100644 --- a/internal/dispatch/gcf/provisioner_test.go +++ b/internal/dispatch/gcf/provisioner_test.go @@ -1371,10 +1371,11 @@ func TestBundleEmbeddedMintSource(t *testing.T) { assert.Contains(t, names, "mintcore/wif.go") assert.Contains(t, names, "mintcore/handler.go") assert.Contains(t, names, "mintcore/foreign.go") + assert.Contains(t, names, "mintcore/repos_scope.go") assert.Contains(t, names, "mintcore/interfaces.go") assert.Contains(t, names, "mintcore/go.sum") assert.Contains(t, names, "mintcore/version.go") - assert.Len(t, names, 17) + assert.Len(t, names, 18) } func TestBundleEmbeddedMintSource_StampsVersion(t *testing.T) { diff --git a/internal/mintcore/config.go b/internal/mintcore/config.go index 35e456758f..018f309d3c 100644 --- a/internal/mintcore/config.go +++ b/internal/mintcore/config.go @@ -43,6 +43,11 @@ type WorkerConfig struct { // Commit is the git SHA stamped on the deployed Worker. Commit string + + // PerOrgForeignCompat enables org-mode repos scope exceptions. + // Same format as the PER_ORG_FOREIGN_COMPAT environment variable + // (truthy: "1", "true", "yes"). + PerOrgForeignCompat string } // ParseWorkerConfig parses a WorkerConfig and returns a Handler. @@ -80,7 +85,12 @@ func ParseWorkerConfig(cfg WorkerConfig, pemAccessor PEMAccessor, oidcVerifier O } } - return NewHandlerFromConfig(cfg.RoleAppIDs, cfg.AllowedRoles, pemAccessor, oidcVerifier, httpClient) + h, err := NewHandlerFromConfig(cfg.RoleAppIDs, cfg.AllowedRoles, pemAccessor, oidcVerifier, httpClient) + if err != nil { + return nil, err + } + h.perOrgForeignCompat = EnvTruthy(cfg.PerOrgForeignCompat) + return h, nil } // SplitCSV splits a comma-separated string into trimmed, non-empty entries. diff --git a/internal/mintcore/config_test.go b/internal/mintcore/config_test.go index 17e71eb6ec..6a4b412579 100644 --- a/internal/mintcore/config_test.go +++ b/internal/mintcore/config_test.go @@ -292,6 +292,7 @@ func TestNewHandlerFromConfig_FullMintFlow(t *testing.T) { t.Fatalf("NewHandlerFromConfig: %v", err) } h.githubBaseURL = github.URL + h.perOrgForeignCompat = true body := `{"role":"coder","repos":["test-repo"]}` rec := httptest.NewRecorder() diff --git a/internal/mintcore/handler.go b/internal/mintcore/handler.go index 8b951277d4..0f07754177 100644 --- a/internal/mintcore/handler.go +++ b/internal/mintcore/handler.go @@ -42,10 +42,11 @@ type mintResponse struct { // statusResponse is returned by the /v1/status diagnostic endpoint. type statusResponse struct { - Org string `json:"org"` - Roles []string `json:"roles"` - Version string `json:"version,omitempty"` - Commit string `json:"commit,omitempty"` + Org string `json:"org"` + Roles []string `json:"roles"` + Version string `json:"version,omitempty"` + Commit string `json:"commit,omitempty"` + PerOrgForeignCompat bool `json:"per_org_foreign_compat"` } // Handler holds dependencies for the token mint HTTP server. @@ -64,6 +65,9 @@ type Handler struct { foreignInflight map[string]*foreignInflight foreignCacheTTL time.Duration foreignCacheMu sync.Mutex + + // perOrgForeignCompat enables org-mode repos shapes under PER_ORG_FOREIGN_COMPAT. + perOrgForeignCompat bool } type foreignInflight struct { @@ -82,13 +86,14 @@ func NewHandler(pemAccessor PEMAccessor, oidcVerifier OIDCVerifier) (*Handler, e httpClient := &http.Client{Timeout: 30 * time.Second} h := &Handler{ - httpClient: httpClient, - pemAccessor: pemAccessor, - oidcVerifier: oidcVerifier, - githubBaseURL: "https://api.github.com", - foreignCache: make(map[string]foreignCacheEntry), - foreignInflight: make(map[string]*foreignInflight), - foreignCacheTTL: defaultForeignCacheTTL, + httpClient: httpClient, + pemAccessor: pemAccessor, + oidcVerifier: oidcVerifier, + githubBaseURL: "https://api.github.com", + foreignCache: make(map[string]foreignCacheEntry), + foreignInflight: make(map[string]*foreignInflight), + foreignCacheTTL: defaultForeignCacheTTL, + perOrgForeignCompat: EnvTruthy(os.Getenv("PER_ORG_FOREIGN_COMPAT")), } if raw := os.Getenv("ROLE_APP_IDS"); raw != "" { @@ -200,6 +205,8 @@ func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { return } + req.Repos = normalizeMintRepos(req.Repos) + if len(req.Repos) > maxRepos { writeError(w, http.StatusBadRequest, fmt.Sprintf("too many repos (max %d)", maxRepos)) return @@ -233,6 +240,17 @@ func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { targetOrg = callerOrg } + isTargetForeign := !strings.EqualFold(targetOrg, callerOrg) + shape, err := validateReposScope(isTargetForeign, claims.Repository, req.Repos, h.perOrgForeignCompat) + if err != nil { + writeError(w, http.StatusForbidden, err.Error()) + return + } + if shape != "" { + log.Printf("PER_ORG_FOREIGN_COMPAT allowed repos scope shape=%s requested_repos=%v source_repo=%s target_org=%s role=%s", + shape, req.Repos, claims.Repository, targetOrg, req.Role) + } + if len(req.Repos) == 0 { log.Printf("WARNING: mint request omitted repos; issuing installation-wide token for target_org=%s role=%s caller_org=%s source_repo=%s", targetOrg, req.Role, callerOrg, claims.Repository) @@ -241,7 +259,7 @@ func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { var token, expiresAt string var granted *GrantedScope - if strings.EqualFold(targetOrg, callerOrg) { + if !isTargetForeign { token, expiresAt, granted, err = h.mintToken(ctx, callerOrg, req.Role, req.Repos) } else { token, expiresAt, granted, err = h.mintTokenCrossOrg(ctx, claims, targetOrg, req.Role, req.Repos) @@ -328,10 +346,11 @@ func (h *Handler) handleStatus(w http.ResponseWriter, claims *Claims) { w.Header().Set("Cache-Control", "no-store") w.WriteHeader(http.StatusOK) if err := json.NewEncoder(w).Encode(statusResponse{ - Org: org, - Roles: roles, - Version: Version, - Commit: Commit, + Org: org, + Roles: roles, + Version: Version, + Commit: Commit, + PerOrgForeignCompat: h.perOrgForeignCompat, }); err != nil { log.Printf("encoding status response: %v", err) } diff --git a/internal/mintcore/handler_test.go b/internal/mintcore/handler_test.go index 07001d60fb..8d17a3b1b2 100644 --- a/internal/mintcore/handler_test.go +++ b/internal/mintcore/handler_test.go @@ -150,11 +150,14 @@ func (e *testOIDCEnv) signToken(t *testing.T, claimsOverrides map[string]interfa header, _ := json.Marshal(map[string]string{"alg": "RS256", "typ": "JWT", "kid": e.kid}) now := time.Now() claims := map[string]interface{}{ - "iss": e.issuerURL, - "aud": "fullsend-mint", - "iat": now.Unix(), - "exp": now.Add(10 * time.Minute).Unix(), - "repository": "test-org/.fullsend", + "iss": e.issuerURL, + "aud": "fullsend-mint", + "iat": now.Unix(), + "exp": now.Add(10 * time.Minute).Unix(), + // Default claim matches common ["test-repo"] mint bodies so tests + // exercise requesting-repo-only scope (compat off) unless overridden. + // job_workflow_ref stays on .fullsend so OIDC enrollment checks pass. + "repository": "test-org/test-repo", "repository_owner": "test-org", "job_workflow_ref": "test-org/.fullsend/.github/workflows/code.yml@refs/heads/main", } @@ -284,6 +287,61 @@ func TestHandler_StatusEndpoint(t *testing.T) { if strings.Contains(body, "orgs") { t.Fatalf("status response should not contain orgs array: %s", body) } + + // Default (unset) is off — dedicated tests opt into compat explicitly. + if resp.PerOrgForeignCompat { + t.Fatal("expected per_org_foreign_compat false by default") + } +} + +func TestHandler_StatusEndpoint_PerOrgForeignCompatOn(t *testing.T) { + t.Setenv("ROLE_APP_IDS", `{"coder":"200"}`) + t.Setenv("ALLOWED_ORGS", "test-org") + t.Setenv("PER_ORG_FOREIGN_COMPAT", "true") + + env := newTestOIDCEnv(t, &fakePEMAccessor{}) + rec := httptest.NewRecorder() + req := httptest.NewRequest(http.MethodGet, "/v1/status", nil) + req.Header.Set("Authorization", "Bearer "+env.signToken(t, nil)) + env.handler.ServeHTTP(rec, req) + + if rec.Code != http.StatusOK { + t.Fatalf("expected 200, got %d: %s", rec.Code, rec.Body.String()) + } + var resp statusResponse + if err := json.NewDecoder(rec.Body).Decode(&resp); err != nil { + t.Fatalf("decode: %v", err) + } + if !resp.PerOrgForeignCompat { + t.Fatal("expected per_org_foreign_compat true when env is truthy") + } +} + +func TestHandler_StatusEndpoint_PerOrgForeignCompatOff(t *testing.T) { + t.Setenv("ROLE_APP_IDS", `{"coder":"200"}`) + t.Setenv("ALLOWED_ORGS", "test-org") + t.Setenv("PER_ORG_FOREIGN_COMPAT", "false") + + env := newTestOIDCEnv(t, &fakePEMAccessor{}) + rec := httptest.NewRecorder() + req := httptest.NewRequest(http.MethodGet, "/v1/status", nil) + req.Header.Set("Authorization", "Bearer "+env.signToken(t, nil)) + env.handler.ServeHTTP(rec, req) + + if rec.Code != http.StatusOK { + t.Fatalf("expected 200, got %d: %s", rec.Code, rec.Body.String()) + } + body := rec.Body.String() + var resp statusResponse + if err := json.Unmarshal([]byte(body), &resp); err != nil { + t.Fatalf("decode: %v", err) + } + if resp.PerOrgForeignCompat { + t.Fatal("expected per_org_foreign_compat false") + } + if !strings.Contains(body, `"per_org_foreign_compat":false`) { + t.Fatalf("expected explicit false in JSON body: %s", body) + } } func TestHandler_StatusEndpoint_IncludesVersion(t *testing.T) { @@ -628,6 +686,7 @@ func TestHandler_InvalidRepoName(t *testing.T) { func TestHandler_EmptyRepos_FullOrgToken(t *testing.T) { t.Setenv("ROLE_APP_IDS", `{"coder":"200"}`) + t.Setenv("PER_ORG_FOREIGN_COMPAT", "true") pemData, err := generateTestRSAKey() if err != nil { @@ -639,27 +698,98 @@ func TestHandler_EmptyRepos_FullOrgToken(t *testing.T) { }) token := env.signToken(t, nil) + body := `{"role":"coder"}` + rec := httptest.NewRecorder() + req := httptest.NewRequest(http.MethodPost, "/v1/token", strings.NewReader(body)) + req.Header.Set("Authorization", "Bearer "+token) + env.handler.ServeHTTP(rec, req) + + if rec.Code != http.StatusForbidden { + t.Fatalf("expected 403 for same-org empty repos, got %d: %s", rec.Code, rec.Body.String()) + } + var resp map[string]string + if err := json.NewDecoder(rec.Body).Decode(&resp); err != nil { + t.Fatalf("decode: %v", err) + } + if !strings.Contains(resp["error"], "same-org mint requires non-empty repos") { + t.Fatalf("unexpected error: %s", resp["error"]) + } +} + +func TestHandler_StarRepos_SameOrgDenied(t *testing.T) { + t.Setenv("ROLE_APP_IDS", `{"coder":"200"}`) + t.Setenv("PER_ORG_FOREIGN_COMPAT", "true") + + pemData, err := generateTestRSAKey() + if err != nil { + t.Fatalf("generating test key: %v", err) + } + + env := newTestOIDCEnv(t, &fakePEMAccessor{ + pems: map[string][]byte{"coder": pemData}, + }) + token := env.signToken(t, nil) + + body := `{"role":"coder","repos":["*"]}` + rec := httptest.NewRecorder() + req := httptest.NewRequest(http.MethodPost, "/v1/token", strings.NewReader(body)) + req.Header.Set("Authorization", "Bearer "+token) + env.handler.ServeHTTP(rec, req) + + if rec.Code != http.StatusForbidden { + t.Fatalf("expected 403 for same-org * repos, got %d: %s", rec.Code, rec.Body.String()) + } +} + +func TestHandler_EmptyRepos_CrossOrgInstallationWide(t *testing.T) { + t.Setenv("ALLOWED_ORGS", "test-org,fullsend-ai") + t.Setenv("ROLE_APP_IDS", `{"e2e":"300"}`) + + pemData, err := generateTestRSAKey() + if err != nil { + t.Fatalf("generating test key: %v", err) + } + + env := newTestOIDCEnv(t, &fakePEMAccessor{pems: map[string][]byte{"e2e": pemData}}) + token := env.signToken(t, map[string]interface{}{ + "repository": "fullsend-ai/fullsend", + "repository_owner": "fullsend-ai", + "job_workflow_ref": "fullsend-ai/fullsend/.github/workflows/e2e.yml@refs/heads/main", + }) + + var tokenCalls int github := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { switch { - case r.URL.Path == "/orgs/test-org/installation" && r.Method == http.MethodGet: + case r.URL.Path == "/orgs/pool-org/installation" && r.Method == http.MethodGet: json.NewEncoder(w).Encode(installationResponse{ - ID: 12345, Account: struct { + ID: 999, Account: struct { Login string `json:"login"` - }{Login: "test-org"}, + }{Login: "pool-org"}, }) - case strings.HasPrefix(r.URL.Path, "/app/installations/12345/access_tokens") && r.Method == http.MethodPost: + case r.URL.Path == "/app/installations/999/access_tokens" && r.Method == http.MethodPost: + tokenCalls++ var body map[string]interface{} json.NewDecoder(r.Body).Decode(&body) + if tokenCalls == 1 { + w.WriteHeader(http.StatusCreated) + json.NewEncoder(w).Encode(installationTokenResponse{Token: "ghs_policy_token"}) + return + } if _, ok := body["repositories"]; ok { t.Error("expected installation token request to omit repositories") } w.WriteHeader(http.StatusCreated) json.NewEncoder(w).Encode(installationTokenResponse{ - Token: "ghs_full_org_token", + Token: "ghs_e2e_full_org", ExpiresAt: "2026-05-06T12:00:00Z", Permissions: map[string]string{"contents": "write", "metadata": "read"}, RepositorySelection: "all", }) + case r.URL.Path == "/orgs/pool-org/actions/variables/FULLSEND_FOREIGN_E2E_REPOS" && r.Method == http.MethodGet: + json.NewEncoder(w).Encode(orgVariableResponse{ + Name: "FULLSEND_FOREIGN_E2E_REPOS", + Value: "fullsend-ai/fullsend", + }) default: t.Errorf("unexpected request: %s %s", r.Method, r.URL.Path) w.WriteHeader(http.StatusNotFound) @@ -668,7 +798,7 @@ func TestHandler_EmptyRepos_FullOrgToken(t *testing.T) { defer github.Close() env.handler.githubBaseURL = github.URL - body := `{"role":"coder"}` + body := `{"role":"e2e","target_org":"pool-org"}` rec := httptest.NewRecorder() req := httptest.NewRequest(http.MethodPost, "/v1/token", strings.NewReader(body)) req.Header.Set("Authorization", "Bearer "+token) @@ -680,15 +810,15 @@ func TestHandler_EmptyRepos_FullOrgToken(t *testing.T) { var resp mintResponse json.NewDecoder(rec.Body).Decode(&resp) - if resp.Token != "ghs_full_org_token" { - t.Fatalf("expected token=ghs_full_org_token, got %s", resp.Token) + if resp.Token != "ghs_e2e_full_org" { + t.Fatalf("expected token=ghs_e2e_full_org, got %s", resp.Token) } if resp.RepoSelection != "all" { t.Fatalf("expected repository_selection=all, got %s", resp.RepoSelection) } } -func TestHandler_EmptyRepos_CrossOrgInstallationWide(t *testing.T) { +func TestHandler_EmptyRepos_CrossOrgStarAlias(t *testing.T) { t.Setenv("ALLOWED_ORGS", "test-org,fullsend-ai") t.Setenv("ROLE_APP_IDS", `{"e2e":"300"}`) @@ -727,7 +857,7 @@ func TestHandler_EmptyRepos_CrossOrgInstallationWide(t *testing.T) { } w.WriteHeader(http.StatusCreated) json.NewEncoder(w).Encode(installationTokenResponse{ - Token: "ghs_e2e_full_org", + Token: "ghs_e2e_star", ExpiresAt: "2026-05-06T12:00:00Z", Permissions: map[string]string{"contents": "write", "metadata": "read"}, RepositorySelection: "all", @@ -745,7 +875,7 @@ func TestHandler_EmptyRepos_CrossOrgInstallationWide(t *testing.T) { defer github.Close() env.handler.githubBaseURL = github.URL - body := `{"role":"e2e","target_org":"pool-org"}` + body := `{"role":"e2e","target_org":"pool-org","repos":["*"]}` rec := httptest.NewRecorder() req := httptest.NewRequest(http.MethodPost, "/v1/token", strings.NewReader(body)) req.Header.Set("Authorization", "Bearer "+token) @@ -754,14 +884,94 @@ func TestHandler_EmptyRepos_CrossOrgInstallationWide(t *testing.T) { if rec.Code != http.StatusOK { t.Fatalf("expected 200, got %d: %s", rec.Code, rec.Body.String()) } - var resp mintResponse json.NewDecoder(rec.Body).Decode(&resp) - if resp.Token != "ghs_e2e_full_org" { - t.Fatalf("expected token=ghs_e2e_full_org, got %s", resp.Token) + if resp.Token != "ghs_e2e_star" { + t.Fatalf("expected token=ghs_e2e_star, got %s", resp.Token) } - if resp.RepoSelection != "all" { - t.Fatalf("expected repository_selection=all, got %s", resp.RepoSelection) +} + +func TestHandler_ReposScope_EnrolledCompat(t *testing.T) { + t.Setenv("ROLE_APP_IDS", `{"coder":"200"}`) + t.Setenv("PER_ORG_FOREIGN_COMPAT", "true") + + pemData, err := generateTestRSAKey() + if err != nil { + t.Fatalf("generating test key: %v", err) + } + + env := newTestOIDCEnv(t, &fakePEMAccessor{ + pems: map[string][]byte{"coder": pemData}, + }) + token := env.signToken(t, map[string]interface{}{ + "repository": "test-org/api", + "repository_owner": "test-org", + "job_workflow_ref": "test-org/.fullsend/.github/workflows/code.yml@refs/heads/main", + }) + + github := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch { + case strings.Contains(r.URL.Path, "/installation") && r.Method == http.MethodGet: + json.NewEncoder(w).Encode(installationResponse{ + ID: 1, Account: struct { + Login string `json:"login"` + }{Login: "test-org"}, + }) + case strings.HasSuffix(r.URL.Path, "/access_tokens"): + w.WriteHeader(http.StatusCreated) + json.NewEncoder(w).Encode(installationTokenResponse{ + Token: "ghs_ok", + ExpiresAt: "2026-05-06T12:00:00Z", + }) + default: + w.WriteHeader(http.StatusNotFound) + } + })) + defer github.Close() + env.handler.githubBaseURL = github.URL + + for _, repos := range []string{`[".fullsend"]`, `["api",".fullsend"]`, `["api"]`} { + body := `{"role":"coder","repos":` + repos + `}` + rec := httptest.NewRecorder() + req := httptest.NewRequest(http.MethodPost, "/v1/token", strings.NewReader(body)) + req.Header.Set("Authorization", "Bearer "+token) + env.handler.ServeHTTP(rec, req) + if rec.Code != http.StatusOK { + t.Fatalf("repos=%s: expected 200, got %d: %s", repos, rec.Code, rec.Body.String()) + } + } + + body := `{"role":"coder","repos":["other"]}` + rec := httptest.NewRecorder() + req := httptest.NewRequest(http.MethodPost, "/v1/token", strings.NewReader(body)) + req.Header.Set("Authorization", "Bearer "+token) + env.handler.ServeHTTP(rec, req) + if rec.Code != http.StatusForbidden { + t.Fatalf("expected 403 for other repo, got %d: %s", rec.Code, rec.Body.String()) + } +} + +func TestHandler_ReposScope_CompatOff(t *testing.T) { + t.Setenv("ROLE_APP_IDS", `{"coder":"200"}`) + t.Setenv("PER_ORG_FOREIGN_COMPAT", "false") + + pemData, err := generateTestRSAKey() + if err != nil { + t.Fatalf("generating test key: %v", err) + } + + env := newTestOIDCEnv(t, &fakePEMAccessor{ + pems: map[string][]byte{"coder": pemData}, + }) + token := env.signToken(t, nil) // test-org/test-repo (default from signToken) + + body := `{"role":"coder","repos":["api"]}` + rec := httptest.NewRecorder() + req := httptest.NewRequest(http.MethodPost, "/v1/token", strings.NewReader(body)) + req.Header.Set("Authorization", "Bearer "+token) + env.handler.ServeHTTP(rec, req) + if rec.Code != http.StatusForbidden { + t.Fatalf("expected 403 with compat off, got %d: %s", rec.Code, rec.Body.String()) } } @@ -1045,6 +1255,7 @@ func TestHandler_FullFlowGrantedScopeAll(t *testing.T) { func TestHandler_FullFlowWithRepos(t *testing.T) { t.Setenv("ROLE_APP_IDS", `{"coder":"200"}`) + t.Setenv("PER_ORG_FOREIGN_COMPAT", "true") pemData, err := generateTestRSAKey() if err != nil { @@ -1054,7 +1265,12 @@ func TestHandler_FullFlowWithRepos(t *testing.T) { env := newTestOIDCEnv(t, &fakePEMAccessor{ pems: map[string][]byte{"coder": pemData}, }) - token := env.signToken(t, nil) + // .fullsend caller + compat may mint a multi-repo list. + token := env.signToken(t, map[string]interface{}{ + "repository": "test-org/.fullsend", + "repository_owner": "test-org", + "job_workflow_ref": "test-org/.fullsend/.github/workflows/code.yml@refs/heads/main", + }) var capturedTokenReq map[string]interface{} github := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { @@ -1123,7 +1339,7 @@ func TestHandler_FullFlowWithRepos_Retro(t *testing.T) { var capturedTokenReq map[string]interface{} github := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { switch { - case r.URL.Path == "/repos/test-org/my-repo/installation": + case r.URL.Path == "/repos/test-org/test-repo/installation": json.NewEncoder(w).Encode(installationResponse{ ID: 1, Account: struct { Login string `json:"login"` @@ -1144,7 +1360,7 @@ func TestHandler_FullFlowWithRepos_Retro(t *testing.T) { defer github.Close() env.handler.githubBaseURL = github.URL - body := `{"role":"retro","repos":["my-repo"]}` + body := `{"role":"retro","repos":["test-repo"]}` rec := httptest.NewRecorder() req := httptest.NewRequest(http.MethodPost, "/v1/token", strings.NewReader(body)) req.Header.Set("Authorization", "Bearer "+token) @@ -1194,7 +1410,7 @@ func TestHandler_FullFlowWithRepos_Prioritize(t *testing.T) { var capturedTokenReq map[string]interface{} github := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { switch { - case r.URL.Path == "/repos/test-org/my-repo/installation": + case r.URL.Path == "/repos/test-org/test-repo/installation": json.NewEncoder(w).Encode(installationResponse{ ID: 1, Account: struct { Login string `json:"login"` @@ -1215,7 +1431,7 @@ func TestHandler_FullFlowWithRepos_Prioritize(t *testing.T) { defer github.Close() env.handler.githubBaseURL = github.URL - body := `{"role":"prioritize","repos":["my-repo"]}` + body := `{"role":"prioritize","repos":["test-repo"]}` rec := httptest.NewRecorder() req := httptest.NewRequest(http.MethodPost, "/v1/token", strings.NewReader(body)) req.Header.Set("Authorization", "Bearer "+token) @@ -1401,7 +1617,7 @@ func TestHandler_MultiOrg_FullFlow(t *testing.T) { pems: map[string][]byte{"coder": pemData}, }) token := env.signToken(t, map[string]interface{}{ - "repository": "other-org/.fullsend", + "repository": "other-org/test-repo", "repository_owner": "other-org", "job_workflow_ref": "other-org/.fullsend/.github/workflows/code.yml@refs/heads/main", }) @@ -1467,7 +1683,7 @@ func TestHandler_CrossOrgInstallationMismatch(t *testing.T) { pems: map[string][]byte{"retro": pemData}, }) token := env.signToken(t, map[string]interface{}{ - "repository": "org-a/.fullsend", + "repository": "org-a/seshi", "repository_owner": "org-a", "job_workflow_ref": "org-a/.fullsend/.github/workflows/retro.yml@refs/heads/main", }) @@ -1559,7 +1775,7 @@ func TestHandler_STSVerifier_Integration(t *testing.T) { "aud": "fullsend-mint", "iat": now.Unix(), "exp": now.Add(10 * time.Minute).Unix(), - "repository": "test-org/.fullsend", + "repository": "test-org/my-repo", "repository_owner": "test-org", "job_workflow_ref": "test-org/.fullsend/.github/workflows/code.yml@refs/heads/main", } @@ -1653,7 +1869,7 @@ func TestHandler_STSVerifier_RestrictedWorkflows(t *testing.T) { "aud": "fullsend-mint", "iat": now.Unix(), "exp": now.Add(10 * time.Minute).Unix(), - "repository": "test-org/.fullsend", + "repository": "test-org/my-repo", "repository_owner": "test-org", "job_workflow_ref": workflowRef, } @@ -1725,7 +1941,7 @@ func TestHandler_CrossOrgInstallation_SameOrgPasses(t *testing.T) { pems: map[string][]byte{"retro": pemData}, }) token := env.signToken(t, map[string]interface{}{ - "repository": "org-a/.fullsend", + "repository": "org-a/seshi", "repository_owner": "org-a", "job_workflow_ref": "org-a/.fullsend/.github/workflows/retro.yml@refs/heads/main", }) @@ -1906,7 +2122,7 @@ func TestHandler_PerRepoWIF_RestrictedWorkflows(t *testing.T) { github := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { switch { - case r.URL.Path == "/repos/test-org/test-repo/installation": + case r.URL.Path == "/repos/test-org/custom-repo/installation": json.NewEncoder(w).Encode(installationResponse{ ID: 55555, Account: struct { Login string `json:"login"` @@ -1932,7 +2148,7 @@ func TestHandler_PerRepoWIF_RestrictedWorkflows(t *testing.T) { "job_workflow_ref": "test-org/custom-repo/.github/workflows/ci.yml@refs/heads/main", }) rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodPost, "/v1/token", strings.NewReader(`{"role":"coder","repos":["test-repo"]}`)) + req := httptest.NewRequest(http.MethodPost, "/v1/token", strings.NewReader(`{"role":"coder","repos":["custom-repo"]}`)) req.Header.Set("Authorization", "Bearer "+allowedToken) env.handler.ServeHTTP(rec, req) @@ -1952,7 +2168,7 @@ func TestHandler_PerRepoWIF_RestrictedWorkflows(t *testing.T) { "job_workflow_ref": "test-org/custom-repo/.github/workflows/evil.yml@refs/heads/main", }) rec2 := httptest.NewRecorder() - req2 := httptest.NewRequest(http.MethodPost, "/v1/token", strings.NewReader(`{"role":"coder","repos":["test-repo"]}`)) + req2 := httptest.NewRequest(http.MethodPost, "/v1/token", strings.NewReader(`{"role":"coder","repos":["custom-repo"]}`)) req2.Header.Set("Authorization", "Bearer "+disallowedToken) env.handler.ServeHTTP(rec2, req2) @@ -1983,7 +2199,7 @@ func TestHandler_UpstreamWorkflowRef(t *testing.T) { github := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { switch { - case r.URL.Path == "/repos/test-org/test-repo/installation": + case r.URL.Path == "/repos/test-org/some-repo/installation": json.NewEncoder(w).Encode(installationResponse{ ID: 55555, Account: struct { Login string `json:"login"` @@ -2009,7 +2225,7 @@ func TestHandler_UpstreamWorkflowRef(t *testing.T) { }) rec := httptest.NewRecorder() req := httptest.NewRequest(http.MethodPost, "/v1/token", - strings.NewReader(`{"role":"coder","repos":["test-repo"]}`)) + strings.NewReader(`{"role":"coder","repos":["some-repo"]}`)) req.Header.Set("Authorization", "Bearer "+token) env.handler.ServeHTTP(rec, req) @@ -2246,7 +2462,7 @@ func TestHandler_PerRepoMixedCase(t *testing.T) { github := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { switch { - case r.URL.Path == "/repos/test-org/test-repo/installation": + case r.URL.Path == "/repos/test-org/My-Repo/installation": json.NewEncoder(w).Encode(installationResponse{ ID: 55555, Account: struct { Login string `json:"login"` @@ -2272,7 +2488,7 @@ func TestHandler_PerRepoMixedCase(t *testing.T) { }) rec := httptest.NewRecorder() req := httptest.NewRequest(http.MethodPost, "/v1/token", - strings.NewReader(`{"role":"coder","repos":["test-repo"]}`)) + strings.NewReader(`{"role":"coder","repos":["My-Repo"]}`)) req.Header.Set("Authorization", "Bearer "+token) env.handler.ServeHTTP(rec, req) @@ -2340,7 +2556,7 @@ func TestHandler_STSVerifier_PerRepoWIF_RestrictedWorkflows(t *testing.T) { github := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { switch { - case r.URL.Path == "/repos/test-org/test-repo/installation": + case r.URL.Path == "/repos/test-org/custom-repo/installation": json.NewEncoder(w).Encode(installationResponse{ ID: 55555, Account: struct { Login string `json:"login"` @@ -2362,7 +2578,7 @@ func TestHandler_STSVerifier_PerRepoWIF_RestrictedWorkflows(t *testing.T) { // Allowed per-repo workflow via STSVerifier rec := httptest.NewRecorder() req := httptest.NewRequest(http.MethodPost, "/v1/token", - strings.NewReader(`{"role":"coder","repos":["test-repo"]}`)) + strings.NewReader(`{"role":"coder","repos":["custom-repo"]}`)) req.Header.Set("Authorization", "Bearer "+buildToken( "test-org/custom-repo", "test-org/custom-repo/.github/workflows/ci.yml@refs/heads/main")) @@ -2380,7 +2596,7 @@ func TestHandler_STSVerifier_PerRepoWIF_RestrictedWorkflows(t *testing.T) { // Disallowed per-repo workflow via STSVerifier rec2 := httptest.NewRecorder() req2 := httptest.NewRequest(http.MethodPost, "/v1/token", - strings.NewReader(`{"role":"coder","repos":["test-repo"]}`)) + strings.NewReader(`{"role":"coder","repos":["custom-repo"]}`)) req2.Header.Set("Authorization", "Bearer "+buildToken( "test-org/custom-repo", "test-org/custom-repo/.github/workflows/evil.yml@refs/heads/main")) @@ -2540,20 +2756,13 @@ func TestHandler_CrossOrgFullFlow(t *testing.T) { Token: "ghs_e2e_token", ExpiresAt: "2026-05-06T12:00:00Z", Permissions: map[string]string{"contents": "write", "metadata": "read"}, - Repositories: []installationTokenRepository{{FullName: "pool-org/e2e-lock"}}, - RepositorySelection: "selected", + RepositorySelection: "all", }) case r.URL.Path == "/orgs/pool-org/actions/variables/FULLSEND_FOREIGN_E2E_REPOS" && r.Method == http.MethodGet: json.NewEncoder(w).Encode(orgVariableResponse{ Name: "FULLSEND_FOREIGN_E2E_REPOS", Value: "fullsend-ai/fullsend", }) - case r.URL.Path == "/repos/pool-org/e2e-lock/installation" && r.Method == http.MethodGet: - json.NewEncoder(w).Encode(installationResponse{ - ID: 999, Account: struct { - Login string `json:"login"` - }{Login: "pool-org"}, - }) default: t.Errorf("unexpected request: %s %s", r.Method, r.URL.Path) w.WriteHeader(http.StatusNotFound) @@ -2562,7 +2771,7 @@ func TestHandler_CrossOrgFullFlow(t *testing.T) { defer github.Close() env.handler.githubBaseURL = github.URL - body := `{"role":"e2e","target_org":"pool-org","repos":["e2e-lock"]}` + body := `{"role":"e2e","target_org":"pool-org"}` rec := httptest.NewRecorder() req := httptest.NewRequest(http.MethodPost, "/v1/token", strings.NewReader(body)) req.Header.Set("Authorization", "Bearer "+token) @@ -2578,6 +2787,40 @@ func TestHandler_CrossOrgFullFlow(t *testing.T) { } } +func TestHandler_CrossOrgNonEmptyReposDenied(t *testing.T) { + t.Setenv("ALLOWED_ORGS", "test-org,fullsend-ai") + t.Setenv("ROLE_APP_IDS", `{"e2e":"300"}`) + + pemData, err := generateTestRSAKey() + if err != nil { + t.Fatalf("generating test key: %v", err) + } + + env := newTestOIDCEnv(t, &fakePEMAccessor{pems: map[string][]byte{"e2e": pemData}}) + token := env.signToken(t, map[string]interface{}{ + "repository": "fullsend-ai/fullsend", + "repository_owner": "fullsend-ai", + "job_workflow_ref": "fullsend-ai/fullsend/.github/workflows/e2e.yml@refs/heads/main", + }) + + body := `{"role":"e2e","target_org":"pool-org","repos":["e2e-lock"]}` + rec := httptest.NewRecorder() + req := httptest.NewRequest(http.MethodPost, "/v1/token", strings.NewReader(body)) + req.Header.Set("Authorization", "Bearer "+token) + env.handler.ServeHTTP(rec, req) + + if rec.Code != http.StatusForbidden { + t.Fatalf("expected 403, got %d: %s", rec.Code, rec.Body.String()) + } + var resp map[string]string + if err := json.NewDecoder(rec.Body).Decode(&resp); err != nil { + t.Fatalf("decode: %v", err) + } + if resp["error"] != "foreign mint requires empty repos" { + t.Fatalf("unexpected error: %s", resp["error"]) + } +} + func TestHandler_ForeignAllowlistCached(t *testing.T) { t.Setenv("ALLOWED_ORGS", "test-org,fullsend-ai") t.Setenv("ROLE_APP_IDS", `{"e2e":"300"}`) @@ -2762,7 +3005,7 @@ func TestHandler_CrossOrgForeignVariableMissing(t *testing.T) { defer github.Close() env.handler.githubBaseURL = github.URL - body := `{"role":"e2e","target_org":"pool-org","repos":["e2e-lock"]}` + body := `{"role":"e2e","target_org":"pool-org"}` rec := httptest.NewRecorder() req := httptest.NewRequest(http.MethodPost, "/v1/token", strings.NewReader(body)) req.Header.Set("Authorization", "Bearer "+token) @@ -2811,7 +3054,7 @@ func TestHandler_CrossOrgForeignDenied(t *testing.T) { defer github.Close() env.handler.githubBaseURL = github.URL - body := `{"role":"e2e","target_org":"pool-org","repos":["e2e-lock"]}` + body := `{"role":"e2e","target_org":"pool-org"}` rec := httptest.NewRecorder() req := httptest.NewRequest(http.MethodPost, "/v1/token", strings.NewReader(body)) req.Header.Set("Authorization", "Bearer "+token) diff --git a/internal/mintcore/repos_scope.go b/internal/mintcore/repos_scope.go new file mode 100644 index 0000000000..cd9093ca01 --- /dev/null +++ b/internal/mintcore/repos_scope.go @@ -0,0 +1,89 @@ +package mintcore + +import ( + "fmt" + "strings" +) + +// Compat shape labels returned by validateReposScope when PER_ORG_FOREIGN_COMPAT +// allows a broader-than-self same-org repos list. Empty means the default path +// (foreign empty repos, or same-org requesting-repo-only). +const ( + reposScopeShapeFullsendAny = "fullsend-any" + reposScopeShapeEnrolledFullsend = "enrolled-fullsend" + reposScopeShapeEnrolledPair = "enrolled-pair" +) + +// normalizeMintRepos treats a single "*" entry as an alias for an empty +// repos list (installation-wide scope on the foreign path). +func normalizeMintRepos(repos []string) []string { + if len(repos) == 1 && repos[0] == "*" { + return nil + } + return repos +} + +// EnvTruthy reports whether v is a truthy feature-flag value. +func EnvTruthy(v string) bool { + switch strings.ToLower(strings.TrimSpace(v)) { + case "1", "true", "yes": + return true + default: + return false + } +} + +// repositoryBareName returns the repository name without the org prefix. +func repositoryBareName(repository string) string { + parts := strings.Split(repository, "/") + return parts[len(parts)-1] +} + +// validateReposScope enforces mint repos authorization after OIDC verification. +// +// Foreign (cross-org) requests may only omit repos (or use "*" → empty). +// Same-org requests must list exactly the requesting repository, unless +// PER_ORG_FOREIGN_COMPAT is on: +// - caller .fullsend: any non-empty validated list +// - other callers: exactly [.fullsend] or {requestingBare, .fullsend} +// +// On success, shape is non-empty only when a compat exception matched. +func validateReposScope(isTargetForeign bool, requestingRepo string, repos []string, compat bool) (shape string, err error) { + if isTargetForeign { + if len(repos) != 0 { + return "", fmt.Errorf("foreign mint requires empty repos") + } + return "", nil + } + + if len(repos) == 0 { + return "", fmt.Errorf("same-org mint requires non-empty repos") + } + + bare := repositoryBareName(requestingRepo) + if len(repos) == 1 && strings.EqualFold(repos[0], bare) { + return "", nil + } + + if !compat { + return "", fmt.Errorf("same-org mint requires repos to be exactly the requesting repository") + } + + if strings.EqualFold(bare, ".fullsend") { + return reposScopeShapeFullsendAny, nil + } + + if len(repos) == 1 && strings.EqualFold(repos[0], ".fullsend") { + return reposScopeShapeEnrolledFullsend, nil + } + + if len(repos) == 2 { + a, b := repos[0], repos[1] + if (strings.EqualFold(a, bare) && strings.EqualFold(b, ".fullsend")) || + (strings.EqualFold(b, bare) && strings.EqualFold(a, ".fullsend")) { + return reposScopeShapeEnrolledPair, nil + } + } + + return "", fmt.Errorf("repos scope not allowed under PER_ORG_FOREIGN_COMPAT for requesting repository") +} diff --git a/internal/mintcore/repos_scope_test.go b/internal/mintcore/repos_scope_test.go new file mode 100644 index 0000000000..b06b03c440 --- /dev/null +++ b/internal/mintcore/repos_scope_test.go @@ -0,0 +1,107 @@ +package mintcore + +import ( + "strings" + "testing" +) + +func TestNormalizeMintRepos(t *testing.T) { + t.Parallel() + tests := []struct { + name string + in []string + want []string + }{ + {"nil", nil, nil}, + {"empty", []string{}, []string{}}, + {"star alone", []string{"*"}, nil}, + {"star with other", []string{"*", "api"}, []string{"*", "api"}}, + {"normal", []string{"api"}, []string{"api"}}, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + got := normalizeMintRepos(tc.in) + if len(got) != len(tc.want) { + t.Fatalf("len=%d want %d (%v)", len(got), len(tc.want), got) + } + for i := range got { + if got[i] != tc.want[i] { + t.Fatalf("got %v want %v", got, tc.want) + } + } + }) + } +} + +func TestEnvTruthy(t *testing.T) { + t.Parallel() + for _, v := range []string{"1", "true", "TRUE", "Yes", " yes "} { + if !EnvTruthy(v) { + t.Fatalf("%q should be truthy", v) + } + } + for _, v := range []string{"", "0", "false", "no", "on"} { + if EnvTruthy(v) { + t.Fatalf("%q should not be truthy", v) + } + } +} + +func TestValidateReposScope(t *testing.T) { + t.Parallel() + const emptyDeny = "same-org mint requires non-empty repos" + const selfDeny = "same-org mint requires repos to be exactly the requesting repository" + const compatDeny = "repos scope not allowed under PER_ORG_FOREIGN_COMPAT" + const foreignDeny = "foreign mint requires empty repos" + + tests := []struct { + name string + foreign bool + requestingRepo string + repos []string + compat bool + wantErrSubstr string + wantShape string + }{ + {"foreign empty", true, "fullsend-ai/fullsend", nil, false, "", ""}, + {"foreign non-empty", true, "fullsend-ai/fullsend", []string{"e2e-lock"}, false, foreignDeny, ""}, + {"same self", false, "acme/api", []string{"api"}, false, "", ""}, + {"same empty", false, "acme/api", nil, true, emptyDeny, ""}, + {"same other flag off", false, "acme/.fullsend", []string{"api"}, false, selfDeny, ""}, + {"fullsend other flag on", false, "acme/.fullsend", []string{"api"}, true, "", reposScopeShapeFullsendAny}, + {"fullsend multi flag on", false, "acme/.fullsend", []string{"a", "b", "c"}, true, "", reposScopeShapeFullsendAny}, + {"fullsend pair flag on", false, "acme/.fullsend", []string{"api", ".fullsend"}, true, "", reposScopeShapeFullsendAny}, + {"fullsend self", false, "acme/.fullsend", []string{".fullsend"}, false, "", ""}, + {"enrolled fullsend flag on", false, "acme/api", []string{".fullsend"}, true, "", reposScopeShapeEnrolledFullsend}, + {"enrolled pair flag on", false, "acme/api", []string{"api", ".fullsend"}, true, "", reposScopeShapeEnrolledPair}, + {"enrolled pair reverse", false, "acme/api", []string{".fullsend", "api"}, true, "", reposScopeShapeEnrolledPair}, + {"enrolled other flag on", false, "acme/api", []string{"other"}, true, compatDeny, ""}, + {"enrolled multi flag on", false, "acme/api", []string{"api", ".fullsend", "x"}, true, compatDeny, ""}, + {"enrolled pair flag off", false, "acme/api", []string{"api", ".fullsend"}, false, selfDeny, ""}, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + shape, err := validateReposScope(tc.foreign, tc.requestingRepo, tc.repos, tc.compat) + if tc.wantErrSubstr == "" { + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if shape != tc.wantShape { + t.Fatalf("shape=%q want %q", shape, tc.wantShape) + } + return + } + if err == nil { + t.Fatal("expected error") + } + if shape != "" { + t.Fatalf("expected empty shape on error, got %q", shape) + } + if !strings.Contains(err.Error(), tc.wantErrSubstr) { + t.Fatalf("error %q does not contain %q", err.Error(), tc.wantErrSubstr) + } + }) + } +} diff --git a/internal/mintcore/testmain_test.go b/internal/mintcore/testmain_test.go index 04f4ea90b7..4e9a9f5d45 100644 --- a/internal/mintcore/testmain_test.go +++ b/internal/mintcore/testmain_test.go @@ -12,6 +12,8 @@ func TestMain(m *testing.M) { "OIDC_AUDIENCE": "fullsend-mint", "ROLE_APP_IDS": `{"triage":"100","coder":"200","review":"300","fullsend":"500","retro":"600","prioritize":"700"}`, "ALLOWED_WORKFLOW_FILES": "*", + // PER_ORG_FOREIGN_COMPAT stays unset (default off) so handler tests + // exercise requesting-repo-only scope unless a test opts in. } for k, v := range defaults { if os.Getenv(k) == "" {