From a95cef435d0f8449ae20582372a4057e85af3101 Mon Sep 17 00:00:00 2001 From: Barak Korren Date: Wed, 29 Jul 2026 14:13:42 +0300 Subject: [PATCH 1/9] feat(mint): harden repos scope against cross-repo minting Restrict same-org mints to the requesting repo by default, allow only empty repos on foreign mints, and gate org-mode exceptions behind PER_ORG_FOREIGN_COMPAT so workflows keep working when enabled. Signed-off-by: Barak Korren Co-authored-by: Cursor --- ...rg-mint-authorization-via-org-variables.md | 8 + docs/architecture.md | 2 +- docs/guides/infrastructure/standalone-mint.md | 1 + .../gcf/mintsrc/mintcore/config.go.embed | 12 +- .../gcf/mintsrc/mintcore/handler.go.embed | 28 +- .../gcf/mintsrc/mintcore/repos_scope.go.embed | 79 ++++++ internal/dispatch/gcf/provisioner.go | 3 +- internal/dispatch/gcf/provisioner_test.go | 1 + internal/mintcore/config.go | 12 +- internal/mintcore/config_test.go | 1 + internal/mintcore/handler.go | 28 +- internal/mintcore/handler_test.go | 253 +++++++++++++++--- internal/mintcore/repos_scope.go | 79 ++++++ internal/mintcore/repos_scope_test.go | 98 +++++++ internal/mintcore/testmain_test.go | 1 + 15 files changed, 549 insertions(+), 57 deletions(-) create mode 100644 internal/dispatch/gcf/mintsrc/mintcore/repos_scope.go.embed create mode 100644 internal/mintcore/repos_scope.go create mode 100644 internal/mintcore/repos_scope_test.go 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..a54956fd78 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,11 @@ 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. +Cross-org (foreign) requests still require empty `repos` (or the `["*"]` alias for empty). +Same-org requests must list exactly the requesting repository unless `PER_ORG_FOREIGN_COMPAT` +is enabled: then `.fullsend` callers may pass any non-empty validated list, and enrolled +callers may mint exactly `[.fullsend]` or `{self,.fullsend}` for org-mode dispatch. diff --git a/docs/architecture.md b/docs/architecture.md index 5e9c4fccba..fb6b96563d 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -178,7 +178,7 @@ 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`. Foreign (cross-org) mints require empty `repos` (or `["*"]` as an empty alias) and FOREIGN gating. Same-org mints must scope `repos` to 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 0060](ADRs/0060-cross-org-mint-authorization-via-org-variables.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/standalone-mint.md b/docs/guides/infrastructure/standalone-mint.md index 2c40599860..78707ce5ac 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 diff --git a/internal/dispatch/gcf/mintsrc/mintcore/config.go.embed b/internal/dispatch/gcf/mintsrc/mintcore/config.go.embed index 35e456758f..06c05cb4f9 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..9c402e8086 100644 --- a/internal/dispatch/gcf/mintsrc/mintcore/handler.go.embed +++ b/internal/dispatch/gcf/mintsrc/mintcore/handler.go.embed @@ -64,6 +64,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 +85,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 +204,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 +239,12 @@ func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { targetOrg = callerOrg } + foreign := !strings.EqualFold(targetOrg, callerOrg) + if err := validateReposScope(foreign, claims.Repository, req.Repos, h.perOrgForeignCompat); err != nil { + writeError(w, http.StatusForbidden, err.Error()) + return + } + 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 +253,7 @@ func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { var token, expiresAt string var granted *GrantedScope - if strings.EqualFold(targetOrg, callerOrg) { + if !foreign { 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) 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..58ab0d9f67 --- /dev/null +++ b/internal/dispatch/gcf/mintsrc/mintcore/repos_scope.go.embed @@ -0,0 +1,79 @@ +package mintcore + +import ( + "fmt" + "strings" +) + +// 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 { + if i := strings.LastIndex(repository, "/"); i >= 0 { + return repository[i+1:] + } + return repository +} + +// 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} +func validateReposScope(foreign bool, requestingRepo string, repos []string, compat bool) error { + if foreign { + if len(repos) != 0 { + return fmt.Errorf("foreign mint requires empty repos") + } + return nil + } + + if len(repos) == 0 { + return fmt.Errorf("repos scope not allowed for requesting repository") + } + + bare := repositoryBareName(requestingRepo) + if len(repos) == 1 && strings.EqualFold(repos[0], bare) { + return nil + } + + if !compat { + return fmt.Errorf("repos scope not allowed for requesting repository") + } + + if strings.EqualFold(bare, ".fullsend") { + return nil + } + + if len(repos) == 1 && strings.EqualFold(repos[0], ".fullsend") { + return 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 nil + } + } + + return fmt.Errorf("repos scope not allowed for requesting repository") +} diff --git a/internal/dispatch/gcf/provisioner.go b/internal/dispatch/gcf/provisioner.go index 9e621d4f98..df5dddd947 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 66389c86f4..de77716a6a 100644 --- a/internal/dispatch/gcf/provisioner_test.go +++ b/internal/dispatch/gcf/provisioner_test.go @@ -1347,6 +1347,7 @@ 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") diff --git a/internal/mintcore/config.go b/internal/mintcore/config.go index 35e456758f..06c05cb4f9 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..9c402e8086 100644 --- a/internal/mintcore/handler.go +++ b/internal/mintcore/handler.go @@ -64,6 +64,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 +85,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 +204,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 +239,12 @@ func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { targetOrg = callerOrg } + foreign := !strings.EqualFold(targetOrg, callerOrg) + if err := validateReposScope(foreign, claims.Repository, req.Repos, h.perOrgForeignCompat); err != nil { + writeError(w, http.StatusForbidden, err.Error()) + return + } + 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 +253,7 @@ func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { var token, expiresAt string var granted *GrantedScope - if strings.EqualFold(targetOrg, callerOrg) { + if !foreign { 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) diff --git a/internal/mintcore/handler_test.go b/internal/mintcore/handler_test.go index 07001d60fb..bae2473988 100644 --- a/internal/mintcore/handler_test.go +++ b/internal/mintcore/handler_test.go @@ -628,6 +628,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 +640,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"], "repos scope not allowed") { + 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 +740,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 +752,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 +799,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 +817,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 +826,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/.fullsend + + 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()) } } @@ -1906,7 +2058,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 +2084,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 +2104,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 +2135,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 +2161,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 +2398,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 +2424,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 +2492,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 +2514,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 +2532,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 +2692,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 +2707,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 +2723,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 +2941,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 +2990,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..58ab0d9f67 --- /dev/null +++ b/internal/mintcore/repos_scope.go @@ -0,0 +1,79 @@ +package mintcore + +import ( + "fmt" + "strings" +) + +// 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 { + if i := strings.LastIndex(repository, "/"); i >= 0 { + return repository[i+1:] + } + return repository +} + +// 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} +func validateReposScope(foreign bool, requestingRepo string, repos []string, compat bool) error { + if foreign { + if len(repos) != 0 { + return fmt.Errorf("foreign mint requires empty repos") + } + return nil + } + + if len(repos) == 0 { + return fmt.Errorf("repos scope not allowed for requesting repository") + } + + bare := repositoryBareName(requestingRepo) + if len(repos) == 1 && strings.EqualFold(repos[0], bare) { + return nil + } + + if !compat { + return fmt.Errorf("repos scope not allowed for requesting repository") + } + + if strings.EqualFold(bare, ".fullsend") { + return nil + } + + if len(repos) == 1 && strings.EqualFold(repos[0], ".fullsend") { + return 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 nil + } + } + + return fmt.Errorf("repos scope not allowed 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..9c0bc39623 --- /dev/null +++ b/internal/mintcore/repos_scope_test.go @@ -0,0 +1,98 @@ +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 deny = "repos scope not allowed" + const foreignDeny = "foreign mint requires empty repos" + + tests := []struct { + name string + foreign bool + requestingRepo string + repos []string + compat bool + wantErrSubstr 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, deny}, + {"same other flag off", false, "acme/.fullsend", []string{"api"}, false, deny}, + {"fullsend other flag on", false, "acme/.fullsend", []string{"api"}, true, ""}, + {"fullsend multi flag on", false, "acme/.fullsend", []string{"a", "b", "c"}, true, ""}, + {"fullsend pair flag on", false, "acme/.fullsend", []string{"api", ".fullsend"}, true, ""}, + {"fullsend self", false, "acme/.fullsend", []string{".fullsend"}, false, ""}, + {"enrolled fullsend flag on", false, "acme/api", []string{".fullsend"}, true, ""}, + {"enrolled pair flag on", false, "acme/api", []string{"api", ".fullsend"}, true, ""}, + {"enrolled pair reverse", false, "acme/api", []string{".fullsend", "api"}, true, ""}, + {"enrolled other flag on", false, "acme/api", []string{"other"}, true, deny}, + {"enrolled multi flag on", false, "acme/api", []string{"api", ".fullsend", "x"}, true, deny}, + {"enrolled pair flag off", false, "acme/api", []string{"api", ".fullsend"}, false, deny}, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + err := validateReposScope(tc.foreign, tc.requestingRepo, tc.repos, tc.compat) + if tc.wantErrSubstr == "" { + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + return + } + if err == nil { + t.Fatal("expected error") + } + 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..02faf25005 100644 --- a/internal/mintcore/testmain_test.go +++ b/internal/mintcore/testmain_test.go @@ -12,6 +12,7 @@ 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": "true", } for k, v := range defaults { if os.Getenv(k) == "" { From 35b0226e17b7866475eb582b316a08de11dc0a0d Mon Sep 17 00:00:00 2001 From: Barak Korren Date: Thu, 30 Jul 2026 10:13:45 +0300 Subject: [PATCH 2/9] fix(mint): resolve deploy commit from local source checkout When mint deploy uses on-disk source and CLI commitSHA is still unset, stamp git HEAD into the mint and show Version/Commit in the summary. Signed-off-by: Barak Korren Co-authored-by: Cursor --- internal/cli/deploy_identity.go | 43 ++++++++++++++ internal/cli/deploy_identity_test.go | 87 ++++++++++++++++++++++++++++ internal/cli/mint.go | 18 +++++- 3 files changed, 146 insertions(+), 2 deletions(-) create mode 100644 internal/cli/deploy_identity.go create mode 100644 internal/cli/deploy_identity_test.go diff --git a/internal/cli/deploy_identity.go b/internal/cli/deploy_identity.go new file mode 100644 index 0000000000..68cd8b0086 --- /dev/null +++ b/internal/cli/deploy_identity.go @@ -0,0 +1,43 @@ +package cli + +import ( + "bytes" + "os" + "os/exec" + "strings" +) + +// 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. +func resolveMintDeployCommit(commit, sourceDir string) string { + if commit != "" && commit != "dev" { + return commit + } + if sourceDir == "" { + return commit + } + info, err := os.Stat(sourceDir) + if err != nil || !info.IsDir() { + return commit + } + sha, err := gitRevParse(sourceDir, "HEAD") + if err != nil || sha == "" { + return commit + } + return sha +} + +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 { + 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..3847b8c83d --- /dev/null +++ b/internal/cli/deploy_identity_test.go @@ -0,0 +1,87 @@ +package cli + +import ( + "os" + "os/exec" + "path/filepath" + "regexp" + "strings" + "testing" +) + +func TestResolveMintDeployCommit_PreservesNonDev(t *testing.T) { + t.Parallel() + got := resolveMintDeployCommit("abc123def", "/nonexistent") + 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 := resolveMintDeployCommit("dev", dir) + if got != "dev" { + t.Fatalf("got %q, want dev when source missing", got) + } + got = resolveMintDeployCommit("", "") + if got != "" { + t.Fatalf("got %q, want empty when sourceDir empty", got) + } +} + +func TestResolveMintDeployCommit_NotAGitRepo(t *testing.T) { + t.Parallel() + dir := t.TempDir() + got := resolveMintDeployCommit("dev", dir) + if got != "dev" { + t.Fatalf("got %q, want dev when not a git work tree", got) + } +} + +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 := resolveMintDeployCommit("dev", dir) + 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) + } + + // Empty commit also resolves. + got = resolveMintDeployCommit("", dir) + if got != want { + t.Fatalf("empty commit: got %q, want %q", got, want) + } +} diff --git a/internal/cli/mint.go b/internal/cli/mint.go index e1fa37f6a9..707bcaf3b2 100644 --- a/internal/cli/mint.go +++ b/internal/cli/mint.go @@ -520,6 +520,11 @@ func runMintDeployGCP(ctx context.Context, project, region, sourceDir string, sk sourceDir = gcf.DefaultFunctionSourceDir() } + deployCommit := resolveMintDeployCommit(commitSHA, sourceDir) + if deployCommit != commitSHA && deployCommit != "" && deployCommit != "dev" { + printer.StepInfo(fmt.Sprintf("Resolved mint commit from checkout: %s", deployCommit)) + } + deployMode := gcf.DeployAuto if skipDeploy { deployMode = gcf.DeploySkip @@ -531,7 +536,7 @@ func runMintDeployGCP(ctx context.Context, project, region, sourceDir string, sk FunctionSourceDir: sourceDir, DeployMode: deployMode, Version: version, - Commit: commitSHA, + Commit: deployCommit, PublicMint: public, } @@ -570,6 +575,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)) @@ -634,13 +641,18 @@ func runMintDeployCloudflare(ctx context.Context, workerName, sourceDir string, sourceDir = cf.DefaultWorkerSourceDir() } + deployCommit := resolveMintDeployCommit(commitSHA, sourceDir) + if deployCommit != commitSHA && deployCommit != "" && deployCommit != "dev" { + printer.StepInfo(fmt.Sprintf("Resolved mint commit from checkout: %s", deployCommit)) + } + cfg := cf.Config{ AccountID: accountID, WorkerName: workerName, DeployMode: deployMode, SourceDir: sourceDir, Version: version, - Commit: commitSHA, + Commit: deployCommit, } wrangler := mintCFWranglerFactory(accountID) @@ -669,6 +681,8 @@ func runMintDeployCloudflare(ctx context.Context, workerName, sourceDir string, fmt.Sprintf("Worker: %s", effectiveName), fmt.Sprintf("URL: %s", mintURL), fmt.Sprintf("Mode: %s", modeLabel), + fmt.Sprintf("Version: %s", version), + fmt.Sprintf("Commit: %s", deployCommit), } if preview { summaryLines = append(summaryLines, "Teardown: fullsend mint deploy --platform=cloudflare --worker-name="+effectiveName+" --preview (then delete)") From 17daebdb05ff2aefac6165125551d1741142b65b Mon Sep 17 00:00:00 2001 From: Barak Korren Date: Thu, 30 Jul 2026 12:11:56 +0300 Subject: [PATCH 3/9] feat(mint): report per_org_foreign_compat in status Expose PER_ORG_FOREIGN_COMPAT on GET /v1/status and print it from traffic env in fullsend mint status (absent = off for older mints). Signed-off-by: Barak Korren Co-authored-by: Cursor --- .../infrastructure-reference.md | 3 +- docs/guides/infrastructure/standalone-mint.md | 2 +- internal/cli/mint.go | 16 +++++ internal/cli/mint_test.go | 59 +++++++++++++++++++ .../gcf/mintsrc/mintcore/handler.go.embed | 18 +++--- internal/mintcore/handler.go | 18 +++--- internal/mintcore/handler_test.go | 32 ++++++++++ 7 files changed, 130 insertions(+), 18 deletions(-) diff --git a/docs/guides/infrastructure/infrastructure-reference.md b/docs/guides/infrastructure/infrastructure-reference.md index d31f793ac0..99648ad278 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 78707ce5ac..db62167138 100644 --- a/docs/guides/infrastructure/standalone-mint.md +++ b/docs/guides/infrastructure/standalone-mint.md @@ -262,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/mint.go b/internal/cli/mint.go index 707bcaf3b2..a1de3c7822 100644 --- a/internal/cli/mint.go +++ b/internal/cli/mint.go @@ -93,6 +93,20 @@ 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" + } + switch strings.ToLower(strings.TrimSpace(trafficEnv["PER_ORG_FOREIGN_COMPAT"])) { + case "1", "true", "yes": + return "on" + default: + 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"]) { @@ -1504,6 +1518,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 cd2b2d28c8..1e2c51a403 100644 --- a/internal/cli/mint_test.go +++ b/internal/cli/mint_test.go @@ -1008,6 +1008,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)) @@ -1292,6 +1302,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/gcf/mintsrc/mintcore/handler.go.embed b/internal/dispatch/gcf/mintsrc/mintcore/handler.go.embed index 9c402e8086..6be339ab70 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. @@ -340,10 +341,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.go b/internal/mintcore/handler.go index 9c402e8086..6be339ab70 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. @@ -340,10 +341,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 bae2473988..bfee9fa08a 100644 --- a/internal/mintcore/handler_test.go +++ b/internal/mintcore/handler_test.go @@ -284,6 +284,38 @@ func TestHandler_StatusEndpoint(t *testing.T) { if strings.Contains(body, "orgs") { t.Fatalf("status response should not contain orgs array: %s", body) } + + // TestMain enables PER_ORG_FOREIGN_COMPAT by default. + if !resp.PerOrgForeignCompat { + t.Fatal("expected per_org_foreign_compat true (TestMain default)") + } +} + +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) { From d7d444c3241b18690b6fc61bf8df55402135e399 Mon Sep 17 00:00:00 2001 From: Barak Korren Date: Sun, 2 Aug 2026 11:49:31 +0300 Subject: [PATCH 4/9] docs(adr): record mint repos scope hardening (ADR 0077) Capture the PER_ORG_FOREIGN_COMPAT repos policy as an accepted ADR and point ADR 0060 / architecture.md at it. Signed-off-by: Barak Korren Co-authored-by: Cursor --- ...rg-mint-authorization-via-org-variables.md | 7 ++- docs/ADRs/0077-mint-repos-scope-hardening.md | 54 +++++++++++++++++++ docs/architecture.md | 3 +- 3 files changed, 59 insertions(+), 5 deletions(-) create mode 100644 docs/ADRs/0077-mint-repos-scope-hardening.md 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 a54956fd78..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 @@ -87,7 +87,6 @@ orgs control over their own policy. ## Later note (repos scope hardening) Same-org installation-wide tokens and unrestricted `repos` lists are no longer the default. -Cross-org (foreign) requests still require empty `repos` (or the `["*"]` alias for empty). -Same-org requests must list exactly the requesting repository unless `PER_ORG_FOREIGN_COMPAT` -is enabled: then `.fullsend` callers may pass any non-empty validated list, and enrolled -callers may mint exactly `[.fullsend]` or `{self,.fullsend}` for org-mode dispatch. +`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 fb6b96563d..032d209c02 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`. Foreign (cross-org) mints require empty `repos` (or `["*"]` as an empty alias) and FOREIGN gating. Same-org mints must scope `repos` to 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 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)). From 833d11fd1e318d7209771afd3124c75895269ecf Mon Sep 17 00:00:00 2001 From: Barak Korren Date: Sun, 2 Aug 2026 12:34:23 +0300 Subject: [PATCH 5/9] fix(mint): address review findings for repos-scope PR Update embedded zip file count, wire PER_ORG_FOREIGN_COMPAT into the CF Worker config JSON, stop enabling compat in TestMain by default, return distinct repos-scope errors, and warn when checkout commit resolution fails. Signed-off-by: Barak Korren Co-authored-by: Cursor --- internal/cli/deploy_identity.go | 25 +++++--- internal/cli/deploy_identity_test.go | 30 ++++++++-- internal/cli/mint.go | 12 ++-- internal/dispatch/cf/workersrc/src/index.ts | 3 + .../gcf/mintsrc/mintcore/repos_scope.go.embed | 6 +- internal/dispatch/gcf/provisioner_test.go | 2 +- internal/mintcore/handler_test.go | 60 ++++++++++++++----- internal/mintcore/repos_scope.go | 6 +- internal/mintcore/repos_scope_test.go | 14 +++-- internal/mintcore/testmain_test.go | 3 +- 10 files changed, 116 insertions(+), 45 deletions(-) diff --git a/internal/cli/deploy_identity.go b/internal/cli/deploy_identity.go index 68cd8b0086..636f72eede 100644 --- a/internal/cli/deploy_identity.go +++ b/internal/cli/deploy_identity.go @@ -2,6 +2,7 @@ package cli import ( "bytes" + "fmt" "os" "os/exec" "strings" @@ -12,22 +13,28 @@ import ( // 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. -func resolveMintDeployCommit(commit, sourceDir string) string { +// +// 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 + return commit, nil } if sourceDir == "" { - return commit + return commit, nil } info, err := os.Stat(sourceDir) if err != nil || !info.IsDir() { - return commit + return commit, nil } sha, err := gitRevParse(sourceDir, "HEAD") - if err != nil || sha == "" { - return commit + if err != nil { + return commit, fmt.Errorf("git rev-parse HEAD in %s: %w", sourceDir, err) } - return sha + if sha == "" { + return commit, fmt.Errorf("git rev-parse HEAD in %s returned empty", sourceDir) + } + return sha, nil } func gitRevParse(dir string, args ...string) (string, error) { @@ -37,6 +44,10 @@ func gitRevParse(dir string, args ...string) (string, error) { 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 index 3847b8c83d..308cc260f5 100644 --- a/internal/cli/deploy_identity_test.go +++ b/internal/cli/deploy_identity_test.go @@ -11,7 +11,10 @@ import ( func TestResolveMintDeployCommit_PreservesNonDev(t *testing.T) { t.Parallel() - got := resolveMintDeployCommit("abc123def", "/nonexistent") + 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) } @@ -20,11 +23,17 @@ func TestResolveMintDeployCommit_PreservesNonDev(t *testing.T) { func TestResolveMintDeployCommit_MissingSourceDir(t *testing.T) { t.Parallel() dir := filepath.Join(t.TempDir(), "no-such-dir") - got := resolveMintDeployCommit("dev", 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 = resolveMintDeployCommit("", "") + got, err = resolveMintDeployCommit("", "") + if err != nil { + t.Fatalf("unexpected err: %v", err) + } if got != "" { t.Fatalf("got %q, want empty when sourceDir empty", got) } @@ -33,7 +42,10 @@ func TestResolveMintDeployCommit_MissingSourceDir(t *testing.T) { func TestResolveMintDeployCommit_NotAGitRepo(t *testing.T) { t.Parallel() dir := t.TempDir() - got := resolveMintDeployCommit("dev", dir) + 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) } @@ -71,7 +83,10 @@ func TestResolveMintDeployCommit_FromCheckout(t *testing.T) { } want := strings.TrimSpace(string(wantOut)) - got := resolveMintDeployCommit("dev", dir) + 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) } @@ -80,7 +95,10 @@ func TestResolveMintDeployCommit_FromCheckout(t *testing.T) { } // Empty commit also resolves. - got = resolveMintDeployCommit("", dir) + 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) } diff --git a/internal/cli/mint.go b/internal/cli/mint.go index a1de3c7822..ffae3d05e3 100644 --- a/internal/cli/mint.go +++ b/internal/cli/mint.go @@ -534,8 +534,10 @@ func runMintDeployGCP(ctx context.Context, project, region, sourceDir string, sk sourceDir = gcf.DefaultFunctionSourceDir() } - deployCommit := resolveMintDeployCommit(commitSHA, sourceDir) - if deployCommit != commitSHA && deployCommit != "" && deployCommit != "dev" { + deployCommit, resolveErr := resolveMintDeployCommit(commitSHA, sourceDir) + if resolveErr != nil { + printer.StepWarn(fmt.Sprintf("Could not resolve mint commit from checkout: %v", resolveErr)) + } else if deployCommit != commitSHA && deployCommit != "" && deployCommit != "dev" { printer.StepInfo(fmt.Sprintf("Resolved mint commit from checkout: %s", deployCommit)) } @@ -655,8 +657,10 @@ func runMintDeployCloudflare(ctx context.Context, workerName, sourceDir string, sourceDir = cf.DefaultWorkerSourceDir() } - deployCommit := resolveMintDeployCommit(commitSHA, sourceDir) - if deployCommit != commitSHA && deployCommit != "" && deployCommit != "dev" { + deployCommit, resolveErr := resolveMintDeployCommit(commitSHA, sourceDir) + if resolveErr != nil { + printer.StepWarn(fmt.Sprintf("Could not resolve mint commit from checkout: %v", resolveErr)) + } else if deployCommit != commitSHA && deployCommit != "" && deployCommit != "dev" { printer.StepInfo(fmt.Sprintf("Resolved mint commit from checkout: %s", deployCommit)) } 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/repos_scope.go.embed b/internal/dispatch/gcf/mintsrc/mintcore/repos_scope.go.embed index 58ab0d9f67..c091ebe314 100644 --- a/internal/dispatch/gcf/mintsrc/mintcore/repos_scope.go.embed +++ b/internal/dispatch/gcf/mintsrc/mintcore/repos_scope.go.embed @@ -48,7 +48,7 @@ func validateReposScope(foreign bool, requestingRepo string, repos []string, com } if len(repos) == 0 { - return fmt.Errorf("repos scope not allowed for requesting repository") + return fmt.Errorf("same-org mint requires non-empty repos") } bare := repositoryBareName(requestingRepo) @@ -57,7 +57,7 @@ func validateReposScope(foreign bool, requestingRepo string, repos []string, com } if !compat { - return fmt.Errorf("repos scope not allowed for requesting repository") + return fmt.Errorf("same-org mint requires repos to be exactly the requesting repository") } if strings.EqualFold(bare, ".fullsend") { @@ -75,5 +75,5 @@ func validateReposScope(foreign bool, requestingRepo string, repos []string, com } } - return fmt.Errorf("repos scope not allowed for requesting repository") + return fmt.Errorf("repos scope not allowed under PER_ORG_FOREIGN_COMPAT for requesting repository") } diff --git a/internal/dispatch/gcf/provisioner_test.go b/internal/dispatch/gcf/provisioner_test.go index de77716a6a..9062821c1b 100644 --- a/internal/dispatch/gcf/provisioner_test.go +++ b/internal/dispatch/gcf/provisioner_test.go @@ -1351,7 +1351,7 @@ func TestBundleEmbeddedMintSource(t *testing.T) { 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/handler_test.go b/internal/mintcore/handler_test.go index bfee9fa08a..548760179a 100644 --- a/internal/mintcore/handler_test.go +++ b/internal/mintcore/handler_test.go @@ -154,7 +154,10 @@ func (e *testOIDCEnv) signToken(t *testing.T, claimsOverrides map[string]interfa "aud": "fullsend-mint", "iat": now.Unix(), "exp": now.Add(10 * time.Minute).Unix(), - "repository": "test-org/.fullsend", + // 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", } @@ -285,9 +288,32 @@ func TestHandler_StatusEndpoint(t *testing.T) { t.Fatalf("status response should not contain orgs array: %s", body) } - // TestMain enables PER_ORG_FOREIGN_COMPAT by default. + // 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 (TestMain default)") + t.Fatal("expected per_org_foreign_compat true when env is truthy") } } @@ -685,7 +711,7 @@ func TestHandler_EmptyRepos_FullOrgToken(t *testing.T) { if err := json.NewDecoder(rec.Body).Decode(&resp); err != nil { t.Fatalf("decode: %v", err) } - if !strings.Contains(resp["error"], "repos scope not allowed") { + if !strings.Contains(resp["error"], "same-org mint requires non-empty repos") { t.Fatalf("unexpected error: %s", resp["error"]) } } @@ -1229,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 { @@ -1238,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) { @@ -1307,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"` @@ -1328,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) @@ -1378,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"` @@ -1399,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) @@ -1585,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", }) @@ -1651,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", }) @@ -1743,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", } @@ -1837,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, } @@ -1909,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", }) diff --git a/internal/mintcore/repos_scope.go b/internal/mintcore/repos_scope.go index 58ab0d9f67..c091ebe314 100644 --- a/internal/mintcore/repos_scope.go +++ b/internal/mintcore/repos_scope.go @@ -48,7 +48,7 @@ func validateReposScope(foreign bool, requestingRepo string, repos []string, com } if len(repos) == 0 { - return fmt.Errorf("repos scope not allowed for requesting repository") + return fmt.Errorf("same-org mint requires non-empty repos") } bare := repositoryBareName(requestingRepo) @@ -57,7 +57,7 @@ func validateReposScope(foreign bool, requestingRepo string, repos []string, com } if !compat { - return fmt.Errorf("repos scope not allowed for requesting repository") + return fmt.Errorf("same-org mint requires repos to be exactly the requesting repository") } if strings.EqualFold(bare, ".fullsend") { @@ -75,5 +75,5 @@ func validateReposScope(foreign bool, requestingRepo string, repos []string, com } } - return fmt.Errorf("repos scope not allowed for requesting repository") + 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 index 9c0bc39623..98c8182970 100644 --- a/internal/mintcore/repos_scope_test.go +++ b/internal/mintcore/repos_scope_test.go @@ -50,7 +50,9 @@ func TestEnvTruthy(t *testing.T) { func TestValidateReposScope(t *testing.T) { t.Parallel() - const deny = "repos scope not allowed" + 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 { @@ -64,8 +66,8 @@ func TestValidateReposScope(t *testing.T) { {"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, deny}, - {"same other flag off", false, "acme/.fullsend", []string{"api"}, false, deny}, + {"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, ""}, {"fullsend multi flag on", false, "acme/.fullsend", []string{"a", "b", "c"}, true, ""}, {"fullsend pair flag on", false, "acme/.fullsend", []string{"api", ".fullsend"}, true, ""}, @@ -73,9 +75,9 @@ func TestValidateReposScope(t *testing.T) { {"enrolled fullsend flag on", false, "acme/api", []string{".fullsend"}, true, ""}, {"enrolled pair flag on", false, "acme/api", []string{"api", ".fullsend"}, true, ""}, {"enrolled pair reverse", false, "acme/api", []string{".fullsend", "api"}, true, ""}, - {"enrolled other flag on", false, "acme/api", []string{"other"}, true, deny}, - {"enrolled multi flag on", false, "acme/api", []string{"api", ".fullsend", "x"}, true, deny}, - {"enrolled pair flag off", false, "acme/api", []string{"api", ".fullsend"}, false, deny}, + {"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) { diff --git a/internal/mintcore/testmain_test.go b/internal/mintcore/testmain_test.go index 02faf25005..4e9a9f5d45 100644 --- a/internal/mintcore/testmain_test.go +++ b/internal/mintcore/testmain_test.go @@ -12,7 +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": "true", + // 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) == "" { From bdd3db78305fbaeff12943778f576bc35f542a46 Mon Sep 17 00:00:00 2001 From: Barak Korren Date: Sun, 2 Aug 2026 13:00:00 +0300 Subject: [PATCH 6/9] test(mint): raise patch coverage for deploy commit helpers Extract resolveAndReportMintDeployCommit, cover warn/info/empty-SHA paths, and exercise GCP --skip-deploy commit reporting so codecov patch meets the 80% target. Signed-off-by: Barak Korren Co-authored-by: Cursor --- internal/cli/deploy_identity.go | 20 +++- internal/cli/deploy_identity_test.go | 132 ++++++++++++++++++++++++++- internal/cli/mint.go | 14 +-- internal/cli/mint_test.go | 39 ++++++++ 4 files changed, 191 insertions(+), 14 deletions(-) diff --git a/internal/cli/deploy_identity.go b/internal/cli/deploy_identity.go index 636f72eede..8020586311 100644 --- a/internal/cli/deploy_identity.go +++ b/internal/cli/deploy_identity.go @@ -6,8 +6,13 @@ import ( "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) @@ -27,7 +32,7 @@ func resolveMintDeployCommit(commit, sourceDir string) (string, error) { if err != nil || !info.IsDir() { return commit, nil } - sha, err := gitRevParse(sourceDir, "HEAD") + sha, err := revParse(sourceDir, "HEAD") if err != nil { return commit, fmt.Errorf("git rev-parse HEAD in %s: %w", sourceDir, err) } @@ -37,6 +42,19 @@ func resolveMintDeployCommit(commit, sourceDir string) (string, error) { 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...) diff --git a/internal/cli/deploy_identity_test.go b/internal/cli/deploy_identity_test.go index 308cc260f5..5485b9e465 100644 --- a/internal/cli/deploy_identity_test.go +++ b/internal/cli/deploy_identity_test.go @@ -1,12 +1,15 @@ 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) { @@ -39,6 +42,21 @@ func TestResolveMintDeployCommit_MissingSourceDir(t *testing.T) { } } +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() @@ -51,6 +69,48 @@ func TestResolveMintDeployCommit_NotAGitRepo(t *testing.T) { } } +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() @@ -94,7 +154,6 @@ func TestResolveMintDeployCommit_FromCheckout(t *testing.T) { t.Fatalf("expected full SHA, got %q", got) } - // Empty commit also resolves. got, err = resolveMintDeployCommit("", dir) if err != nil { t.Fatalf("unexpected err: %v", err) @@ -103,3 +162,74 @@ func TestResolveMintDeployCommit_FromCheckout(t *testing.T) { 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 ffae3d05e3..45b6ed040d 100644 --- a/internal/cli/mint.go +++ b/internal/cli/mint.go @@ -534,12 +534,7 @@ func runMintDeployGCP(ctx context.Context, project, region, sourceDir string, sk sourceDir = gcf.DefaultFunctionSourceDir() } - deployCommit, resolveErr := resolveMintDeployCommit(commitSHA, sourceDir) - if resolveErr != nil { - printer.StepWarn(fmt.Sprintf("Could not resolve mint commit from checkout: %v", resolveErr)) - } else if deployCommit != commitSHA && deployCommit != "" && deployCommit != "dev" { - printer.StepInfo(fmt.Sprintf("Resolved mint commit from checkout: %s", deployCommit)) - } + deployCommit := resolveAndReportMintDeployCommit(printer, commitSHA, sourceDir) deployMode := gcf.DeployAuto if skipDeploy { @@ -657,12 +652,7 @@ func runMintDeployCloudflare(ctx context.Context, workerName, sourceDir string, sourceDir = cf.DefaultWorkerSourceDir() } - deployCommit, resolveErr := resolveMintDeployCommit(commitSHA, sourceDir) - if resolveErr != nil { - printer.StepWarn(fmt.Sprintf("Could not resolve mint commit from checkout: %v", resolveErr)) - } else if deployCommit != commitSHA && deployCommit != "" && deployCommit != "dev" { - printer.StepInfo(fmt.Sprintf("Resolved mint commit from checkout: %s", deployCommit)) - } + deployCommit := resolveAndReportMintDeployCommit(printer, commitSHA, sourceDir) cfg := cf.Config{ AccountID: accountID, diff --git a/internal/cli/mint_test.go b/internal/cli/mint_test.go index 1e2c51a403..3becfa7593 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" @@ -168,6 +169,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_DryRunPublic(t *testing.T) { cmd := newRootCmd() cmd.SetArgs([]string{"mint", "deploy", "--project=my-project-id", "--dry-run", "--public"}) From c8140fe11411a04cbfde1446924938f3bb4f0017 Mon Sep 17 00:00:00 2001 From: Barak Korren Date: Mon, 3 Aug 2026 09:38:50 +0300 Subject: [PATCH 7/9] fix(mint): share EnvTruthy for per-org compat status label Export mintcore.EnvTruthy and use it from the CLI status label so truthy parsing stays in one place; fix stale default-claim test comment. Signed-off-by: Barak Korren Co-authored-by: Cursor --- internal/cli/mint.go | 6 ++---- internal/dispatch/gcf/mintsrc/mintcore/config.go.embed | 2 +- internal/dispatch/gcf/mintsrc/mintcore/handler.go.embed | 2 +- internal/dispatch/gcf/mintsrc/mintcore/repos_scope.go.embed | 4 ++-- internal/mintcore/config.go | 2 +- internal/mintcore/handler.go | 2 +- internal/mintcore/handler_test.go | 2 +- internal/mintcore/repos_scope.go | 4 ++-- internal/mintcore/repos_scope_test.go | 4 ++-- 9 files changed, 13 insertions(+), 15 deletions(-) diff --git a/internal/cli/mint.go b/internal/cli/mint.go index bf453d2077..7163fb5692 100644 --- a/internal/cli/mint.go +++ b/internal/cli/mint.go @@ -99,12 +99,10 @@ func perOrgForeignCompatLabel(trafficEnv map[string]string) string { if trafficEnv == nil { return "off" } - switch strings.ToLower(strings.TrimSpace(trafficEnv["PER_ORG_FOREIGN_COMPAT"])) { - case "1", "true", "yes": + if mintcore.EnvTruthy(trafficEnv["PER_ORG_FOREIGN_COMPAT"]) { return "on" - default: - return "off" } + return "off" } // mintValidationMessage returns the success message after validating an existing mint. diff --git a/internal/dispatch/gcf/mintsrc/mintcore/config.go.embed b/internal/dispatch/gcf/mintsrc/mintcore/config.go.embed index 06c05cb4f9..018f309d3c 100644 --- a/internal/dispatch/gcf/mintsrc/mintcore/config.go.embed +++ b/internal/dispatch/gcf/mintsrc/mintcore/config.go.embed @@ -89,7 +89,7 @@ func ParseWorkerConfig(cfg WorkerConfig, pemAccessor PEMAccessor, oidcVerifier O if err != nil { return nil, err } - h.perOrgForeignCompat = envTruthy(cfg.PerOrgForeignCompat) + h.perOrgForeignCompat = EnvTruthy(cfg.PerOrgForeignCompat) return h, nil } diff --git a/internal/dispatch/gcf/mintsrc/mintcore/handler.go.embed b/internal/dispatch/gcf/mintsrc/mintcore/handler.go.embed index 6be339ab70..dc773e5f8d 100644 --- a/internal/dispatch/gcf/mintsrc/mintcore/handler.go.embed +++ b/internal/dispatch/gcf/mintsrc/mintcore/handler.go.embed @@ -93,7 +93,7 @@ func NewHandler(pemAccessor PEMAccessor, oidcVerifier OIDCVerifier) (*Handler, e foreignCache: make(map[string]foreignCacheEntry), foreignInflight: make(map[string]*foreignInflight), foreignCacheTTL: defaultForeignCacheTTL, - perOrgForeignCompat: envTruthy(os.Getenv("PER_ORG_FOREIGN_COMPAT")), + perOrgForeignCompat: EnvTruthy(os.Getenv("PER_ORG_FOREIGN_COMPAT")), } if raw := os.Getenv("ROLE_APP_IDS"); raw != "" { diff --git a/internal/dispatch/gcf/mintsrc/mintcore/repos_scope.go.embed b/internal/dispatch/gcf/mintsrc/mintcore/repos_scope.go.embed index c091ebe314..b01d253e20 100644 --- a/internal/dispatch/gcf/mintsrc/mintcore/repos_scope.go.embed +++ b/internal/dispatch/gcf/mintsrc/mintcore/repos_scope.go.embed @@ -14,8 +14,8 @@ func normalizeMintRepos(repos []string) []string { return repos } -// envTruthy reports whether v is a truthy feature-flag value. -func envTruthy(v string) bool { +// 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 diff --git a/internal/mintcore/config.go b/internal/mintcore/config.go index 06c05cb4f9..018f309d3c 100644 --- a/internal/mintcore/config.go +++ b/internal/mintcore/config.go @@ -89,7 +89,7 @@ func ParseWorkerConfig(cfg WorkerConfig, pemAccessor PEMAccessor, oidcVerifier O if err != nil { return nil, err } - h.perOrgForeignCompat = envTruthy(cfg.PerOrgForeignCompat) + h.perOrgForeignCompat = EnvTruthy(cfg.PerOrgForeignCompat) return h, nil } diff --git a/internal/mintcore/handler.go b/internal/mintcore/handler.go index 6be339ab70..dc773e5f8d 100644 --- a/internal/mintcore/handler.go +++ b/internal/mintcore/handler.go @@ -93,7 +93,7 @@ func NewHandler(pemAccessor PEMAccessor, oidcVerifier OIDCVerifier) (*Handler, e foreignCache: make(map[string]foreignCacheEntry), foreignInflight: make(map[string]*foreignInflight), foreignCacheTTL: defaultForeignCacheTTL, - perOrgForeignCompat: envTruthy(os.Getenv("PER_ORG_FOREIGN_COMPAT")), + perOrgForeignCompat: EnvTruthy(os.Getenv("PER_ORG_FOREIGN_COMPAT")), } if raw := os.Getenv("ROLE_APP_IDS"); raw != "" { diff --git a/internal/mintcore/handler_test.go b/internal/mintcore/handler_test.go index 05c24dd308..8d17a3b1b2 100644 --- a/internal/mintcore/handler_test.go +++ b/internal/mintcore/handler_test.go @@ -963,7 +963,7 @@ func TestHandler_ReposScope_CompatOff(t *testing.T) { env := newTestOIDCEnv(t, &fakePEMAccessor{ pems: map[string][]byte{"coder": pemData}, }) - token := env.signToken(t, nil) // test-org/.fullsend + token := env.signToken(t, nil) // test-org/test-repo (default from signToken) body := `{"role":"coder","repos":["api"]}` rec := httptest.NewRecorder() diff --git a/internal/mintcore/repos_scope.go b/internal/mintcore/repos_scope.go index c091ebe314..b01d253e20 100644 --- a/internal/mintcore/repos_scope.go +++ b/internal/mintcore/repos_scope.go @@ -14,8 +14,8 @@ func normalizeMintRepos(repos []string) []string { return repos } -// envTruthy reports whether v is a truthy feature-flag value. -func envTruthy(v string) bool { +// 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 diff --git a/internal/mintcore/repos_scope_test.go b/internal/mintcore/repos_scope_test.go index 98c8182970..b760106c7c 100644 --- a/internal/mintcore/repos_scope_test.go +++ b/internal/mintcore/repos_scope_test.go @@ -37,12 +37,12 @@ func TestNormalizeMintRepos(t *testing.T) { func TestEnvTruthy(t *testing.T) { t.Parallel() for _, v := range []string{"1", "true", "TRUE", "Yes", " yes "} { - if !envTruthy(v) { + if !EnvTruthy(v) { t.Fatalf("%q should be truthy", v) } } for _, v := range []string{"", "0", "false", "no", "on"} { - if envTruthy(v) { + if EnvTruthy(v) { t.Fatalf("%q should not be truthy", v) } } From 5dedbb4c633da7367945cd2d8af05fd60c04ef9d Mon Sep 17 00:00:00 2001 From: Barak Korren Date: Mon, 3 Aug 2026 12:25:30 +0300 Subject: [PATCH 8/9] fix(mint): address rh-hemartin review on repos-scope naming Rename the cross-org boolean to isTargetForeign, use strings.Split for bare repo names, and add a blank line before the two-repo compat check. Signed-off-by: Barak Korren Co-authored-by: Cursor --- .../dispatch/gcf/mintsrc/mintcore/handler.go.embed | 6 +++--- .../gcf/mintsrc/mintcore/repos_scope.go.embed | 11 +++++------ internal/mintcore/handler.go | 6 +++--- internal/mintcore/repos_scope.go | 11 +++++------ 4 files changed, 16 insertions(+), 18 deletions(-) diff --git a/internal/dispatch/gcf/mintsrc/mintcore/handler.go.embed b/internal/dispatch/gcf/mintsrc/mintcore/handler.go.embed index dc773e5f8d..a2ee06f152 100644 --- a/internal/dispatch/gcf/mintsrc/mintcore/handler.go.embed +++ b/internal/dispatch/gcf/mintsrc/mintcore/handler.go.embed @@ -240,8 +240,8 @@ func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { targetOrg = callerOrg } - foreign := !strings.EqualFold(targetOrg, callerOrg) - if err := validateReposScope(foreign, claims.Repository, req.Repos, h.perOrgForeignCompat); err != nil { + isTargetForeign := !strings.EqualFold(targetOrg, callerOrg) + if err := validateReposScope(isTargetForeign, claims.Repository, req.Repos, h.perOrgForeignCompat); err != nil { writeError(w, http.StatusForbidden, err.Error()) return } @@ -254,7 +254,7 @@ func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { var token, expiresAt string var granted *GrantedScope - if !foreign { + 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) diff --git a/internal/dispatch/gcf/mintsrc/mintcore/repos_scope.go.embed b/internal/dispatch/gcf/mintsrc/mintcore/repos_scope.go.embed index b01d253e20..46f6ae9fe1 100644 --- a/internal/dispatch/gcf/mintsrc/mintcore/repos_scope.go.embed +++ b/internal/dispatch/gcf/mintsrc/mintcore/repos_scope.go.embed @@ -26,10 +26,8 @@ func EnvTruthy(v string) bool { // repositoryBareName returns the repository name without the org prefix. func repositoryBareName(repository string) string { - if i := strings.LastIndex(repository, "/"); i >= 0 { - return repository[i+1:] - } - return repository + parts := strings.Split(repository, "/") + return parts[len(parts)-1] } // validateReposScope enforces mint repos authorization after OIDC verification. @@ -39,8 +37,8 @@ func repositoryBareName(repository string) string { // PER_ORG_FOREIGN_COMPAT is on: // - caller .fullsend: any non-empty validated list // - other callers: exactly [.fullsend] or {requestingBare, .fullsend} -func validateReposScope(foreign bool, requestingRepo string, repos []string, compat bool) error { - if foreign { +func validateReposScope(isTargetForeign bool, requestingRepo string, repos []string, compat bool) error { + if isTargetForeign { if len(repos) != 0 { return fmt.Errorf("foreign mint requires empty repos") } @@ -67,6 +65,7 @@ func validateReposScope(foreign bool, requestingRepo string, repos []string, com if len(repos) == 1 && strings.EqualFold(repos[0], ".fullsend") { return nil } + if len(repos) == 2 { a, b := repos[0], repos[1] if (strings.EqualFold(a, bare) && strings.EqualFold(b, ".fullsend")) || diff --git a/internal/mintcore/handler.go b/internal/mintcore/handler.go index dc773e5f8d..a2ee06f152 100644 --- a/internal/mintcore/handler.go +++ b/internal/mintcore/handler.go @@ -240,8 +240,8 @@ func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { targetOrg = callerOrg } - foreign := !strings.EqualFold(targetOrg, callerOrg) - if err := validateReposScope(foreign, claims.Repository, req.Repos, h.perOrgForeignCompat); err != nil { + isTargetForeign := !strings.EqualFold(targetOrg, callerOrg) + if err := validateReposScope(isTargetForeign, claims.Repository, req.Repos, h.perOrgForeignCompat); err != nil { writeError(w, http.StatusForbidden, err.Error()) return } @@ -254,7 +254,7 @@ func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { var token, expiresAt string var granted *GrantedScope - if !foreign { + 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) diff --git a/internal/mintcore/repos_scope.go b/internal/mintcore/repos_scope.go index b01d253e20..46f6ae9fe1 100644 --- a/internal/mintcore/repos_scope.go +++ b/internal/mintcore/repos_scope.go @@ -26,10 +26,8 @@ func EnvTruthy(v string) bool { // repositoryBareName returns the repository name without the org prefix. func repositoryBareName(repository string) string { - if i := strings.LastIndex(repository, "/"); i >= 0 { - return repository[i+1:] - } - return repository + parts := strings.Split(repository, "/") + return parts[len(parts)-1] } // validateReposScope enforces mint repos authorization after OIDC verification. @@ -39,8 +37,8 @@ func repositoryBareName(repository string) string { // PER_ORG_FOREIGN_COMPAT is on: // - caller .fullsend: any non-empty validated list // - other callers: exactly [.fullsend] or {requestingBare, .fullsend} -func validateReposScope(foreign bool, requestingRepo string, repos []string, compat bool) error { - if foreign { +func validateReposScope(isTargetForeign bool, requestingRepo string, repos []string, compat bool) error { + if isTargetForeign { if len(repos) != 0 { return fmt.Errorf("foreign mint requires empty repos") } @@ -67,6 +65,7 @@ func validateReposScope(foreign bool, requestingRepo string, repos []string, com if len(repos) == 1 && strings.EqualFold(repos[0], ".fullsend") { return nil } + if len(repos) == 2 { a, b := repos[0], repos[1] if (strings.EqualFold(a, bare) && strings.EqualFold(b, ".fullsend")) || From d21b4d9bb683f6b15aeace79a0b977dbd86fea48 Mon Sep 17 00:00:00 2001 From: Barak Korren Date: Mon, 3 Aug 2026 13:15:23 +0300 Subject: [PATCH 9/9] fix(mint): log PER_ORG_FOREIGN_COMPAT repos scope shape Return a shape label from validateReposScope and log it when a compat exception allows broader-than-self same-org repos for auditability. Signed-off-by: Barak Korren Co-authored-by: Cursor --- .../gcf/mintsrc/mintcore/handler.go.embed | 7 +++- .../gcf/mintsrc/mintcore/repos_scope.go.embed | 31 ++++++++++----- internal/mintcore/handler.go | 7 +++- internal/mintcore/repos_scope.go | 31 ++++++++++----- internal/mintcore/repos_scope_test.go | 39 +++++++++++-------- 5 files changed, 77 insertions(+), 38 deletions(-) diff --git a/internal/dispatch/gcf/mintsrc/mintcore/handler.go.embed b/internal/dispatch/gcf/mintsrc/mintcore/handler.go.embed index a2ee06f152..0f07754177 100644 --- a/internal/dispatch/gcf/mintsrc/mintcore/handler.go.embed +++ b/internal/dispatch/gcf/mintsrc/mintcore/handler.go.embed @@ -241,10 +241,15 @@ func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { } isTargetForeign := !strings.EqualFold(targetOrg, callerOrg) - if err := validateReposScope(isTargetForeign, claims.Repository, req.Repos, h.perOrgForeignCompat); err != nil { + 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", diff --git a/internal/dispatch/gcf/mintsrc/mintcore/repos_scope.go.embed b/internal/dispatch/gcf/mintsrc/mintcore/repos_scope.go.embed index 46f6ae9fe1..cd9093ca01 100644 --- a/internal/dispatch/gcf/mintsrc/mintcore/repos_scope.go.embed +++ b/internal/dispatch/gcf/mintsrc/mintcore/repos_scope.go.embed @@ -5,6 +5,15 @@ import ( "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 { @@ -37,42 +46,44 @@ func repositoryBareName(repository string) string { // PER_ORG_FOREIGN_COMPAT is on: // - caller .fullsend: any non-empty validated list // - other callers: exactly [.fullsend] or {requestingBare, .fullsend} -func validateReposScope(isTargetForeign bool, requestingRepo string, repos []string, compat bool) error { +// +// 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 "", fmt.Errorf("foreign mint requires empty repos") } - return nil + return "", nil } if len(repos) == 0 { - return fmt.Errorf("same-org mint requires non-empty repos") + return "", fmt.Errorf("same-org mint requires non-empty repos") } bare := repositoryBareName(requestingRepo) if len(repos) == 1 && strings.EqualFold(repos[0], bare) { - return nil + return "", nil } if !compat { - return fmt.Errorf("same-org mint requires repos to be exactly the requesting repository") + return "", fmt.Errorf("same-org mint requires repos to be exactly the requesting repository") } if strings.EqualFold(bare, ".fullsend") { - return nil + return reposScopeShapeFullsendAny, nil } if len(repos) == 1 && strings.EqualFold(repos[0], ".fullsend") { - return nil + 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 nil + return reposScopeShapeEnrolledPair, nil } } - return fmt.Errorf("repos scope not allowed under PER_ORG_FOREIGN_COMPAT for requesting repository") + return "", fmt.Errorf("repos scope not allowed under PER_ORG_FOREIGN_COMPAT for requesting repository") } diff --git a/internal/mintcore/handler.go b/internal/mintcore/handler.go index a2ee06f152..0f07754177 100644 --- a/internal/mintcore/handler.go +++ b/internal/mintcore/handler.go @@ -241,10 +241,15 @@ func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { } isTargetForeign := !strings.EqualFold(targetOrg, callerOrg) - if err := validateReposScope(isTargetForeign, claims.Repository, req.Repos, h.perOrgForeignCompat); err != nil { + 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", diff --git a/internal/mintcore/repos_scope.go b/internal/mintcore/repos_scope.go index 46f6ae9fe1..cd9093ca01 100644 --- a/internal/mintcore/repos_scope.go +++ b/internal/mintcore/repos_scope.go @@ -5,6 +5,15 @@ import ( "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 { @@ -37,42 +46,44 @@ func repositoryBareName(repository string) string { // PER_ORG_FOREIGN_COMPAT is on: // - caller .fullsend: any non-empty validated list // - other callers: exactly [.fullsend] or {requestingBare, .fullsend} -func validateReposScope(isTargetForeign bool, requestingRepo string, repos []string, compat bool) error { +// +// 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 "", fmt.Errorf("foreign mint requires empty repos") } - return nil + return "", nil } if len(repos) == 0 { - return fmt.Errorf("same-org mint requires non-empty repos") + return "", fmt.Errorf("same-org mint requires non-empty repos") } bare := repositoryBareName(requestingRepo) if len(repos) == 1 && strings.EqualFold(repos[0], bare) { - return nil + return "", nil } if !compat { - return fmt.Errorf("same-org mint requires repos to be exactly the requesting repository") + return "", fmt.Errorf("same-org mint requires repos to be exactly the requesting repository") } if strings.EqualFold(bare, ".fullsend") { - return nil + return reposScopeShapeFullsendAny, nil } if len(repos) == 1 && strings.EqualFold(repos[0], ".fullsend") { - return nil + 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 nil + return reposScopeShapeEnrolledPair, nil } } - return fmt.Errorf("repos scope not allowed under PER_ORG_FOREIGN_COMPAT for requesting repository") + 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 index b760106c7c..b06b03c440 100644 --- a/internal/mintcore/repos_scope_test.go +++ b/internal/mintcore/repos_scope_test.go @@ -62,36 +62,43 @@ func TestValidateReposScope(t *testing.T) { 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, ""}, - {"fullsend multi flag on", false, "acme/.fullsend", []string{"a", "b", "c"}, true, ""}, - {"fullsend pair flag on", false, "acme/.fullsend", []string{"api", ".fullsend"}, true, ""}, - {"fullsend self", false, "acme/.fullsend", []string{".fullsend"}, false, ""}, - {"enrolled fullsend flag on", false, "acme/api", []string{".fullsend"}, true, ""}, - {"enrolled pair flag on", false, "acme/api", []string{"api", ".fullsend"}, true, ""}, - {"enrolled pair reverse", false, "acme/api", []string{".fullsend", "api"}, true, ""}, - {"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}, + {"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() - err := validateReposScope(tc.foreign, tc.requestingRepo, tc.repos, tc.compat) + 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) }