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 eba2619a75..634c456733 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 @@ -93,3 +93,11 @@ Same-org installation-wide tokens and unrestricted `repos` lists are no longer t `repos` authorization is decided in [ADR 0077](0077-mint-repos-scope-hardening.md). FOREIGN allowlists and `target_org` from this ADR are unchanged. + +## Later note (repo-level foreign grants) + +[ADR 0083](0083-repo-level-foreign-allow-list.md) extends the FOREIGN +mechanism with repo-level `FULLSEND_FOREIGN__REPOS` variables. +Repo-level grants additionally require `actions_variables: read` on the +target repos (in addition to the `organization_actions_variables: read` +needed for org-level grants from this ADR). diff --git a/docs/ADRs/0077-mint-repos-scope-hardening.md b/docs/ADRs/0077-mint-repos-scope-hardening.md index 361e769e2e..0f09b9f01e 100644 --- a/docs/ADRs/0077-mint-repos-scope-hardening.md +++ b/docs/ADRs/0077-mint-repos-scope-hardening.md @@ -52,3 +52,8 @@ This revises the installation-wide and unrestricted same-org `repos` consequence - 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). + +> **Later note:** [ADR 0083](0083-repo-level-foreign-allow-list.md) relaxes +> the foreign empty-repos constraint. Cross-org requests with non-empty +> `repos` are now permitted when each target repo has a repo-level +> `FULLSEND_FOREIGN__REPOS` variable authorizing the caller. diff --git a/docs/ADRs/0083-repo-level-foreign-allow-list.md b/docs/ADRs/0083-repo-level-foreign-allow-list.md new file mode 100644 index 0000000000..e07b8a2508 --- /dev/null +++ b/docs/ADRs/0083-repo-level-foreign-allow-list.md @@ -0,0 +1,150 @@ +--- +title: "83. Repo-level foreign allow-list" +status: Accepted +relates_to: + - agent-infrastructure + - security-threat-model +topics: + - mint + - identity + - oidc + - least-privilege + - cross-org +--- + +# 83. Repo-level foreign allow-list + +Date: 2026-08-05 + +## Status + +Accepted + +Builds on [ADR 0060](0060-cross-org-mint-authorization-via-org-variables.md) +and [ADR 0078](0078-simplified-mint-authorization-policy.md). + +## Context + +[ADR 0060](0060-cross-org-mint-authorization-via-org-variables.md) introduced +cross-org mint authorization via org-level `FULLSEND_FOREIGN__REPOS` +variables. This works well for broad org-wide grants but has two gaps: + +1. **No repo-level granularity.** Operators cannot authorize a specific caller + to mint tokens for *one* repository without authorizing them for the entire + target org. Org-level FOREIGN grants produce installation-wide tokens, + violating least privilege when only a single repo is needed. + +2. **No intra-org cross-repo grants.** A per-repo caller + (`PER_REPO_WIF_REPOS`) can only mint tokens scoped to its own repository. + There is no mechanism for a per-repo caller to access another repository + in the *same* org without adding the caller's org to `ALLOWED_ORGS` (which + broadens access to all org-mode shapes) or setting up a cross-org flow + with `target_org`. + +Both gaps push operators toward overly broad grants. +[ADR 0078](0078-simplified-mint-authorization-policy.md) simplified the +authorization model by removing `PER_ORG_FOREIGN_COMPAT`, making this a +clean extension point. + +## Decision + +### Repo-level FOREIGN variable + +The same `FULLSEND_FOREIGN__REPOS` variable name used at the org level +can now be set as a **repo-level** GitHub Actions variable on any target +repository. The variable format is unchanged: comma-separated list of +`org/repo` (exact `repository` match) and/or bare `org` +(`repository_owner` match). + +### Cross-org with specific repos + +When a cross-org request specifies non-empty `repos` (e.g., +`repos: ["target-repo"]`), the handler authorizes **exclusively** via +per-repo FOREIGN grants — the org-level variable is not consulted: + +1. Check the **repo-level** `FULLSEND_FOREIGN__REPOS` on each + requested repository. +2. If **all** requested repos individually authorize the caller via their + repo-level variables, mint proceeds scoped to those repos only. +3. If any requested repo does not authorize the caller, the request is denied. + +Cross-org requests with `repos: ["*"]` (installation-wide) continue to use +only the org-level variable, unchanged from ADR 0060. + +### Authorization boundary + +Org-level and repo-level FOREIGN grants serve distinct scopes: + +- **Org-level grant** → authorizes only installation-wide tokens + (`repos: ["*"]`). Not consulted for repo-scoped requests. +- **Repo-level grant** → authorizes only the specific repos that set the + variable. Not consulted for installation-wide requests. + +### Intra-org cross-repo grants + +Per-repo callers (`PER_REPO_WIF_REPOS`) requesting repos other than their +own within the same org are normally denied by `validateReposScope`. With +repo-level FOREIGN variables, the handler falls back to checking repo-level +grants when the scope check fails: + +1. `validateReposScope` denies the per-repo caller for requesting non-self + repos. +2. The handler checks repo-level `FULLSEND_FOREIGN__REPOS` on each + requested repo. +3. If all repos authorize the caller, the scope denial is overridden and + the token is minted scoped to those repos. + +This enables controlled intra-org cross-repo access without requiring the +caller's org to be in `ALLOWED_ORGS` and without changing the per-repo +caller's enrollment mode. + +### Scope restriction + +Repo-level grants restrict the minted token to the specific repos that set +the variable. A repo-level grant on `target-repo` does **not** authorize +access to other repos in the same org. This is the key difference from +org-level grants, which cover the entire org. + +### Caching + +Repo-level FOREIGN lookups use the same in-memory cache and inflight dedup +as org-level lookups, with a distinct cache key format: +`targetOrg/targetRepo/role` (vs `targetOrg/role` for org-level). Same TTL +(60 seconds), same negative caching. + +### API permissions + +Reading repo-level Actions variables requires `actions_variables: read` +(repo-level permission), distinct from the `organization_actions_variables: +read` used for org-level variables. The policy token for repo-level lookups +is scoped to the specific target repo. + +## Consequences + +- Operators can grant controlled cross-repo access at repo granularity + without installation-wide tokens. +- Repo-level FOREIGN lookups add GitHub API calls (repo installation lookup, + policy token creation, variable read) per target repo per uncached request. + Cached lookups are free. +- Roles used with repo-level FOREIGN grants need `actions_variables: read` + on their App permissions for the target repos. +- The `validateReposScope` constraint "foreign mint requires empty repos" is + relaxed: cross-org requests may now specify non-empty repos when repo-level + FOREIGN variables are set. Requests with `repos: ["*"]` continue to require + org-level authorization. +- Per-repo callers gain a new authorization path for intra-org cross-repo + access, gated by repo-level FOREIGN variables. This does not change the + default behavior (without FOREIGN variables, per-repo callers are still + restricted to their own repo). +- CLI management of FOREIGN variables (`fullsend admin foreign`) will need + updates for repo-level support (tracked separately in + [#2229](https://github.com/fullsend-ai/fullsend/issues/2229)). + +### Related ADRs + +| Topic | ADR | +|-------|-----| +| Cross-org mint authorization (org-level) | [0060](0060-cross-org-mint-authorization-via-org-variables.md) | +| Simplified mint authorization policy | [0078](0078-simplified-mint-authorization-policy.md) | +| Separate workflow-host allow-list | [0082](0082-workflow-host-allow-list.md) | +| Repos scope hardening | [0077](0077-mint-repos-scope-hardening.md) | diff --git a/docs/architecture.md b/docs/architecture.md index 74d55047f4..4cd98aa89b 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -195,8 +195,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` ([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). Per-repo callers (repo in `PER_REPO_WIF_REPOS`) must list exactly the requesting repository. Per-org callers (org in `ALLOWED_ORGS`, repo not in `PER_REPO_WIF_REPOS`) get org-mode shapes: `.fullsend` callers may use any non-empty validated list; other callers may use `[.fullsend]` or `{self,.fullsend}`. Same-org installation-wide tokens are denied ([ADR 0077](ADRs/0077-mint-repos-scope-hardening.md), simplified in [ADR 0078](ADRs/0078-simplified-mint-authorization-policy.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)). Repo-level `FULLSEND_FOREIGN__REPOS` variables enable per-repo foreign grants (scoped to the specific target repo) and intra-org cross-repo access for per-repo callers, with disjoint authorization boundaries from org-level grants — repo-level for repo-scoped requests, org-level for installation-wide requests ([ADR 0083](ADRs/0083-repo-level-foreign-allow-list.md)). +- Mint `repos` scope: foreign mints with `repos: ["*"]` require an org-level FOREIGN grant; foreign mints with specific repos require per-repo FOREIGN grants on each requested repo (org-level grants are not consulted for repo-scoped requests). Per-repo callers (repo in `PER_REPO_WIF_REPOS`) must list exactly the requesting repository unless authorized by repo-level FOREIGN grants for other repos. Per-org callers (org in `ALLOWED_ORGS`, repo not in `PER_REPO_WIF_REPOS`) get org-mode shapes: `.fullsend` callers may use any non-empty validated list; other callers may use `[.fullsend]` or `{self,.fullsend}`. Same-org installation-wide tokens are denied ([ADR 0077](ADRs/0077-mint-repos-scope-hardening.md), simplified in [ADR 0078](ADRs/0078-simplified-mint-authorization-policy.md)). - Workflow-host allow-list: `WORKFLOW_HOST_REPOS` controls which repos may host workflows calling the mint for per-repo and public-mode callers (default: `fullsend-ai/fullsend`). Per-org callers hard-wire to `{org}/.fullsend` and upstream. Public mode is not special-cased — it uses the same per-repo validation path with `WORKFLOW_HOST_REPOS` and the basename allowlist. This separates caller enrollment from workflow-host trust ([ADR 0082](ADRs/0082-workflow-host-allow-list.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)). diff --git a/docs/guides/dev/e2e-testing.md b/docs/guides/dev/e2e-testing.md index 6f8ddde296..270c0d3eff 100644 --- a/docs/guides/dev/e2e-testing.md +++ b/docs/guides/dev/e2e-testing.md @@ -131,6 +131,17 @@ Existing pool orgs (`halfsend-01` … `halfsend-12`) need a one-time operator pa go run ./cmd/fullsend admin foreign allow --org halfsend-NN --role e2e --caller fullsend-ai/fullsend ``` +For repo-level grants (scoped to a specific target repo rather than the +entire org), add `--repo`: + +```bash +go run ./cmd/fullsend admin foreign allow --org halfsend-NN --role e2e --caller fullsend-ai/fullsend --repo target-repo +go run ./cmd/fullsend admin foreign list --org halfsend-NN --repo target-repo +``` + +See [ADR 0083](../../ADRs/0083-repo-level-foreign-allow-list.md) for details +on repo-level foreign grants. + ## CI authorization Pull requests trigger e2e via `pull_request_target` in diff --git a/docs/guides/infrastructure/mint-administration.md b/docs/guides/infrastructure/mint-administration.md index da7b49ccae..26170d899f 100644 --- a/docs/guides/infrastructure/mint-administration.md +++ b/docs/guides/infrastructure/mint-administration.md @@ -627,3 +627,5 @@ gcloud functions logs read fullsend-mint \ - [Standalone Mint](standalone-mint.md) — Running the mint without GCP, with custom agent roles - [Infrastructure Reference](infrastructure-reference.md) — Token mint, WIF, and secrets deployment details - [CLI Internals](../dev/cli-internals.md) — Command structure and implementation details +- [Cross-org authorization (ADR 0060)](../../ADRs/0060-cross-org-mint-authorization-via-org-variables.md) — Org-level FOREIGN authorization via `FULLSEND_FOREIGN__REPOS` org variables +- [Repo-level foreign grants (ADR 0083)](../../ADRs/0083-repo-level-foreign-allow-list.md) — Per-repo FOREIGN authorization grants; manage with `fullsend admin foreign` commands diff --git a/internal/cli/foreign.go b/internal/cli/foreign.go index f8334dc6cd..59a7d57047 100644 --- a/internal/cli/foreign.go +++ b/internal/cli/foreign.go @@ -17,8 +17,12 @@ import ( func newForeignCmd() *cobra.Command { cmd := &cobra.Command{ Use: "foreign", - Short: "Manage cross-org mint authorization on a target org", - Long: "Manage FULLSEND_FOREIGN__REPOS org variables that authorize foreign workflows to mint tokens for this org.", + Short: "Manage cross-org mint authorization on a target org or repo", + Long: "Manage FULLSEND_FOREIGN__REPOS variables that authorize foreign workflows to mint tokens.\n\n" + + "Without --repo, manages org-level variables (installation-wide grants).\n" + + "With --repo, manages repo-level variables (repo-scoped grants).\n\n" + + "--repo accepts owner/repo (e.g. acme/api) so --org can be omitted,\n" + + "or --org --repo as the split form.", } cmd.AddCommand(newForeignAllowCmd()) cmd.AddCommand(newForeignListCmd()) @@ -27,10 +31,10 @@ func newForeignCmd() *cobra.Command { } func newForeignAllowCmd() *cobra.Command { - var org string + var org, repo string cmd := &cobra.Command{ Use: "allow", - Short: "Authorize a foreign org/repo to mint for a role on this org", + Short: "Authorize a foreign org/repo to mint for a role on this org or repo", RunE: func(cmd *cobra.Command, args []string) error { role, err := cmd.Flags().GetString("role") if err != nil { @@ -40,10 +44,8 @@ func newForeignAllowCmd() *cobra.Command { if err != nil { return err } - if org == "" { - return fmt.Errorf("--org is required") - } - if err := validateOrgName(org); err != nil { + target, err := resolveForeignTarget(org, repo) + if err != nil { return err } if err := mintcore.ValidateRoleName(role); err != nil { @@ -62,7 +64,13 @@ func newForeignAllowCmd() *cobra.Command { ctx := cmd.Context() varName := mintcore.ForeignVariableName(role) - allowlist, err := loadForeignAllowlist(ctx, client, org, varName) + + var allowlist []string + if target.isRepoLevel() { + allowlist, err = loadRepoForeignAllowlist(ctx, client, target.org, target.repo, varName) + } else { + allowlist, err = loadForeignAllowlist(ctx, client, target.org, varName) + } if err != nil { return err } @@ -73,24 +81,34 @@ func newForeignAllowCmd() *cobra.Command { } value := strings.Join(allowlist, ", ") - if alreadyListed { - printer.StepStart(fmt.Sprintf("Ensuring %s is org-wide on %s", varName, org)) + targetLabel := target.label() + if target.isRepoLevel() { + printer.StepStart(fmt.Sprintf("Updating %s on repo %s", varName, targetLabel)) + if err := client.CreateOrUpdateRepoVariable(ctx, target.org, target.repo, varName, value); err != nil { + printer.StepFail(fmt.Sprintf("Failed to update %s on repo %s", varName, targetLabel)) + return err + } } else { - printer.StepStart(fmt.Sprintf("Updating %s on %s", varName, org)) - } - if err := client.CreateOrUpdateOrgVariableAll(ctx, org, varName, value); err != nil { - printer.StepFail(fmt.Sprintf("Failed to update %s", varName)) - return err + if alreadyListed { + printer.StepStart(fmt.Sprintf("Ensuring %s is org-wide on %s", varName, targetLabel)) + } else { + printer.StepStart(fmt.Sprintf("Updating %s on %s", varName, targetLabel)) + } + if err := client.CreateOrUpdateOrgVariableAll(ctx, target.org, varName, value); err != nil { + printer.StepFail(fmt.Sprintf("Failed to update %s", varName)) + return err + } } if alreadyListed { - printer.StepDone(fmt.Sprintf("%s already lists %q (org-wide visibility ensured)", varName, caller)) + printer.StepDone(fmt.Sprintf("%s already lists %q on %s", varName, caller, targetLabel)) } else { - printer.StepDone(fmt.Sprintf("Added %q to %s", caller, varName)) + printer.StepDone(fmt.Sprintf("Added %q to %s on %s", caller, varName, targetLabel)) } return nil }, } cmd.Flags().StringVar(&org, "org", "", "Target GitHub organization") + cmd.Flags().StringVar(&repo, "repo", "", "Target repository (owner/repo or bare name with --org)") cmd.Flags().String("role", "", "Agent role (e.g. e2e)") cmd.Flags().String("caller", "", "Foreign caller: org/repo or bare org") _ = cmd.MarkFlagRequired("role") @@ -99,16 +117,14 @@ func newForeignAllowCmd() *cobra.Command { } func newForeignListCmd() *cobra.Command { - var org string + var org, repo string var role string cmd := &cobra.Command{ Use: "list", - Short: "List foreign caller allowlists on an org", + Short: "List foreign caller allowlists on an org or repo", RunE: func(cmd *cobra.Command, args []string) error { - if org == "" { - return fmt.Errorf("--org is required") - } - if err := validateOrgName(org); err != nil { + target, err := resolveForeignTarget(org, repo) + if err != nil { return err } if role != "" { @@ -125,9 +141,15 @@ func newForeignListCmd() *cobra.Command { printer := ui.New(os.Stdout) ctx := cmd.Context() + targetLabel := target.label() + + if target.isRepoLevel() { + return listRepoForeign(ctx, client, printer, target, role) + } + if role != "" { varName := mintcore.ForeignVariableName(role) - allowlist, err := loadForeignAllowlist(ctx, client, org, varName) + allowlist, err := loadForeignAllowlist(ctx, client, target.org, varName) if err != nil { return err } @@ -142,7 +164,7 @@ func newForeignListCmd() *cobra.Command { return nil } - vars, err := client.ListOrgVariables(ctx, org) + vars, err := client.ListOrgVariables(ctx, target.org) if err != nil { return err } @@ -161,7 +183,7 @@ func newForeignListCmd() *cobra.Command { }{role: roleName, allowlist: mintcore.ParseForeignAllowlist(v.Value)}) } if len(foreign) == 0 { - printer.StepInfo("No FULLSEND_FOREIGN_* variables found") + printer.StepInfo(fmt.Sprintf("No FULLSEND_FOREIGN_* variables found on %s", targetLabel)) return nil } sort.Slice(foreign, func(i, j int) bool { return foreign[i].role < foreign[j].role }) @@ -179,12 +201,68 @@ func newForeignListCmd() *cobra.Command { }, } cmd.Flags().StringVar(&org, "org", "", "Target GitHub organization") + cmd.Flags().StringVar(&repo, "repo", "", "Target repository (owner/repo or bare name with --org)") cmd.Flags().StringVar(&role, "role", "", "Filter to a single role (optional)") return cmd } +func listRepoForeign(ctx context.Context, client *gh.LiveClient, printer *ui.Printer, target foreignTarget, role string) error { + targetLabel := target.label() + if role != "" { + varName := mintcore.ForeignVariableName(role) + allowlist, err := loadRepoForeignAllowlist(ctx, client, target.org, target.repo, varName) + if err != nil { + return err + } + if len(allowlist) == 0 { + printer.StepInfo(fmt.Sprintf("%s on %s: (not set)", varName, targetLabel)) + return nil + } + printer.StepInfo(fmt.Sprintf("%s on %s:", varName, targetLabel)) + for _, entry := range allowlist { + printer.StepInfo(fmt.Sprintf(" - %s", entry)) + } + return nil + } + + vars, err := client.ListRepoVariables(ctx, target.org, target.repo) + if err != nil { + return err + } + var foreign []struct { + role string + allowlist []string + } + for name, value := range vars { + roleName, ok := parseForeignVariableName(name) + if !ok { + continue + } + foreign = append(foreign, struct { + role string + allowlist []string + }{role: roleName, allowlist: mintcore.ParseForeignAllowlist(value)}) + } + if len(foreign) == 0 { + printer.StepInfo(fmt.Sprintf("No FULLSEND_FOREIGN_* variables found on %s", targetLabel)) + return nil + } + sort.Slice(foreign, func(i, j int) bool { return foreign[i].role < foreign[j].role }) + for _, entry := range foreign { + printer.StepInfo(fmt.Sprintf("%s:", mintcore.ForeignVariableName(entry.role))) + if len(entry.allowlist) == 0 { + printer.StepInfo(" (empty)") + continue + } + for _, caller := range entry.allowlist { + printer.StepInfo(fmt.Sprintf(" - %s", caller)) + } + } + return nil +} + func newForeignRevokeCmd() *cobra.Command { - var org string + var org, repo string cmd := &cobra.Command{ Use: "revoke", Short: "Remove a foreign caller from a role allowlist", @@ -197,10 +275,8 @@ func newForeignRevokeCmd() *cobra.Command { if err != nil { return err } - if org == "" { - return fmt.Errorf("--org is required") - } - if err := validateOrgName(org); err != nil { + target, err := resolveForeignTarget(org, repo) + if err != nil { return err } if err := mintcore.ValidateRoleName(role); err != nil { @@ -219,36 +295,58 @@ func newForeignRevokeCmd() *cobra.Command { ctx := cmd.Context() varName := mintcore.ForeignVariableName(role) - allowlist, err := loadForeignAllowlist(ctx, client, org, varName) + targetLabel := target.label() + + var allowlist []string + if target.isRepoLevel() { + allowlist, err = loadRepoForeignAllowlist(ctx, client, target.org, target.repo, varName) + } else { + allowlist, err = loadForeignAllowlist(ctx, client, target.org, varName) + } if err != nil { return err } updated, changed := removeForeignCaller(allowlist, caller) if !changed { - printer.StepInfo(fmt.Sprintf("%q not in %s", caller, varName)) + printer.StepInfo(fmt.Sprintf("%q not in %s on %s", caller, varName, targetLabel)) return nil } - printer.StepStart(fmt.Sprintf("Updating %s on %s", varName, org)) + printer.StepStart(fmt.Sprintf("Updating %s on %s", varName, targetLabel)) if len(updated) == 0 { - if err := client.DeleteOrgVariable(ctx, org, varName); err != nil { - printer.StepFail(fmt.Sprintf("Failed to delete %s", varName)) - return err + if target.isRepoLevel() { + if err := client.DeleteRepoVariable(ctx, target.org, target.repo, varName); err != nil { + printer.StepFail(fmt.Sprintf("Failed to delete %s on %s", varName, targetLabel)) + return err + } + } else { + if err := client.DeleteOrgVariable(ctx, target.org, varName); err != nil { + printer.StepFail(fmt.Sprintf("Failed to delete %s", varName)) + return err + } } - printer.StepDone(fmt.Sprintf("Removed %q; deleted empty %s", caller, varName)) + printer.StepDone(fmt.Sprintf("Removed %q; deleted empty %s on %s", caller, varName, targetLabel)) return nil } value := strings.Join(updated, ", ") - if err := client.CreateOrUpdateOrgVariableAll(ctx, org, varName, value); err != nil { - printer.StepFail(fmt.Sprintf("Failed to update %s", varName)) - return err + if target.isRepoLevel() { + if err := client.CreateOrUpdateRepoVariable(ctx, target.org, target.repo, varName, value); err != nil { + printer.StepFail(fmt.Sprintf("Failed to update %s on %s", varName, targetLabel)) + return err + } + } else { + if err := client.CreateOrUpdateOrgVariableAll(ctx, target.org, varName, value); err != nil { + printer.StepFail(fmt.Sprintf("Failed to update %s", varName)) + return err + } } - printer.StepDone(fmt.Sprintf("Removed %q from %s", caller, varName)) + printer.StepDone(fmt.Sprintf("Removed %q from %s on %s", caller, varName, targetLabel)) return nil }, } cmd.Flags().StringVar(&org, "org", "", "Target GitHub organization") + cmd.Flags().StringVar(&repo, "repo", "", "Target repository (owner/repo or bare name with --org)") cmd.Flags().String("role", "", "Agent role (e.g. e2e)") cmd.Flags().String("caller", "", "Foreign caller to remove") _ = cmd.MarkFlagRequired("role") @@ -256,6 +354,74 @@ func newForeignRevokeCmd() *cobra.Command { return cmd } +// foreignTarget holds the resolved org and optional repo for foreign +// variable operations. When repo is non-empty, operations target a +// repo-level variable; otherwise they target an org-level variable. +type foreignTarget struct { + org string + repo string +} + +// resolveForeignTarget parses --org and --repo flags into a foreignTarget. +// +// --repo accepts two forms: +// - owner/repo (full form, --org can be omitted) +// - repo (short form, --org is required) +// +// Without --repo, --org is required and the target is org-level. +func resolveForeignTarget(org, repo string) (foreignTarget, error) { + if repo == "" { + // Org-level mode: --org is required. + if org == "" { + return foreignTarget{}, fmt.Errorf("--org is required (or use --repo owner/repo)") + } + if err := validateOrgName(org); err != nil { + return foreignTarget{}, err + } + return foreignTarget{org: org}, nil + } + + // Repo-level mode. + if strings.Contains(repo, "/") { + // Full owner/repo form. + parts := strings.SplitN(repo, "/", 2) + repoOrg, repoName := parts[0], parts[1] + if org != "" && !strings.EqualFold(org, repoOrg) { + return foreignTarget{}, fmt.Errorf("--org %q conflicts with owner in --repo %q", org, repo) + } + if err := validateOrgName(repoOrg); err != nil { + return foreignTarget{}, fmt.Errorf("invalid owner in --repo: %w", err) + } + if repoName == "" || !githubRepoPattern.MatchString(repoName) { + return foreignTarget{}, fmt.Errorf("invalid repo name in --repo %q", repo) + } + return foreignTarget{org: repoOrg, repo: repoName}, nil + } + + // Short repo name: --org is required. + if org == "" { + return foreignTarget{}, fmt.Errorf("--org is required when --repo is a bare name (or use --repo owner/repo)") + } + if err := validateOrgName(org); err != nil { + return foreignTarget{}, err + } + if !githubRepoPattern.MatchString(repo) { + return foreignTarget{}, fmt.Errorf("invalid repo name in --repo %q", repo) + } + return foreignTarget{org: org, repo: repo}, nil +} + +func (t foreignTarget) isRepoLevel() bool { + return t.repo != "" +} + +func (t foreignTarget) label() string { + if t.repo != "" { + return t.org + "/" + t.repo + } + return t.org +} + func loadForeignAllowlist(ctx context.Context, client *gh.LiveClient, org, varName string) ([]string, error) { value, exists, err := client.GetOrgVariable(ctx, org, varName) if err != nil { @@ -267,6 +433,17 @@ func loadForeignAllowlist(ctx context.Context, client *gh.LiveClient, org, varNa return mintcore.ParseForeignAllowlist(value), nil } +func loadRepoForeignAllowlist(ctx context.Context, client *gh.LiveClient, owner, repo, varName string) ([]string, error) { + value, exists, err := client.GetRepoVariable(ctx, owner, repo, varName) + if err != nil { + return nil, err + } + if !exists { + return nil, nil + } + return mintcore.ParseForeignAllowlist(value), nil +} + func parseForeignVariableName(name string) (role string, ok bool) { const prefix = "FULLSEND_FOREIGN_" const suffix = "_REPOS" diff --git a/internal/cli/foreign_test.go b/internal/cli/foreign_test.go index c964c738c7..b9b38dde63 100644 --- a/internal/cli/foreign_test.go +++ b/internal/cli/foreign_test.go @@ -99,9 +99,14 @@ func TestLoadForeignAllowlist_NotSet(t *testing.T) { } type foreignVarState struct { - mu sync.Mutex - vars map[string]string - deleted []string + mu sync.Mutex + vars map[string]string // org-level vars + repoVars map[string]string // repo-level vars, keyed by "owner/repo/VAR_NAME" + deleted []string +} + +func (s *foreignVarState) repoVarKey(owner, repo, name string) string { + return owner + "/" + repo + "/" + name } func (s *foreignVarState) handler(t *testing.T) http.HandlerFunc { @@ -109,6 +114,12 @@ func (s *foreignVarState) handler(t *testing.T) http.HandlerFunc { s.mu.Lock() defer s.mu.Unlock() + // Repo-level variable endpoints: /repos/{owner}/{repo}/actions/variables[/{name}] + if strings.HasPrefix(r.URL.Path, "/repos/") { + s.handleRepoVars(t, w, r) + return + } + switch { case r.Method == http.MethodGet && strings.Contains(r.URL.Path, "/actions/variables/FULLSEND_FOREIGN_"): name := strings.TrimPrefix(r.URL.Path, "/orgs/pool-org/actions/variables/") @@ -154,6 +165,73 @@ func (s *foreignVarState) handler(t *testing.T) http.HandlerFunc { } } +// handleRepoVars dispatches repo-level variable API requests. +// Path format: /repos/{owner}/{repo}/actions/variables[/{name}] +func (s *foreignVarState) handleRepoVars(t *testing.T, w http.ResponseWriter, r *http.Request) { + // Parse: /repos/{owner}/{repo}/actions/variables[/{name}] + path := strings.TrimPrefix(r.URL.Path, "/repos/") + parts := strings.SplitN(path, "/", 3) // owner, repo, rest + if len(parts) < 3 { + t.Errorf("malformed repo path: %s", r.URL.Path) + http.NotFound(w, r) + return + } + owner, repo := parts[0], parts[1] + rest := parts[2] // "actions/variables" or "actions/variables/{name}" + + switch { + case r.Method == http.MethodGet && rest == "actions/variables": + // List repo variables. + prefix := owner + "/" + repo + "/" + var out []map[string]string + for key, val := range s.repoVars { + if strings.HasPrefix(key, prefix) { + name := strings.TrimPrefix(key, prefix) + out = append(out, map[string]string{"name": name, "value": val}) + } + } + json.NewEncoder(w).Encode(map[string]any{ + "total_count": len(out), + "variables": out, + }) + case r.Method == http.MethodGet && strings.HasPrefix(rest, "actions/variables/"): + name := strings.TrimPrefix(rest, "actions/variables/") + key := s.repoVarKey(owner, repo, name) + if val, ok := s.repoVars[key]; ok { + json.NewEncoder(w).Encode(map[string]string{"name": name, "value": val}) + return + } + w.WriteHeader(http.StatusNotFound) + case r.Method == http.MethodPatch && strings.HasPrefix(rest, "actions/variables/"): + name := strings.TrimPrefix(rest, "actions/variables/") + key := s.repoVarKey(owner, repo, name) + var body struct { + Value string `json:"value"` + } + json.NewDecoder(r.Body).Decode(&body) + s.repoVars[key] = body.Value + w.WriteHeader(http.StatusNoContent) + case r.Method == http.MethodPost && rest == "actions/variables": + var body struct { + Name string `json:"name"` + Value string `json:"value"` + } + json.NewDecoder(r.Body).Decode(&body) + key := s.repoVarKey(owner, repo, body.Name) + s.repoVars[key] = body.Value + w.WriteHeader(http.StatusCreated) + case r.Method == http.MethodDelete && strings.HasPrefix(rest, "actions/variables/"): + name := strings.TrimPrefix(rest, "actions/variables/") + key := s.repoVarKey(owner, repo, name) + delete(s.repoVars, key) + s.deleted = append(s.deleted, key) + w.WriteHeader(http.StatusNoContent) + default: + t.Errorf("unexpected repo %s %s", r.Method, r.URL.Path) + http.NotFound(w, r) + } +} + func runForeignCmd(t *testing.T, srvURL string, args ...string) (string, error) { t.Helper() t.Setenv("GH_TOKEN", "test-token") @@ -301,3 +379,184 @@ func TestForeignCmd_ValidationErrors(t *testing.T) { require.Error(t, err) assert.Contains(t, err.Error(), "--org is required") } + +// --- Repo-level foreign CLI tests --- + +func TestResolveForeignTarget(t *testing.T) { + tests := []struct { + name string + org string + repo string + wantOrg string + wantRepo string + wantErr string + }{ + {"org only", "pool-org", "", "pool-org", "", ""}, + {"full owner/repo", "", "pool-org/target-repo", "pool-org", "target-repo", ""}, + {"full owner/repo with --org match", "pool-org", "pool-org/target-repo", "pool-org", "target-repo", ""}, + {"full owner/repo with --org conflict", "other-org", "pool-org/target-repo", "", "", "--org \"other-org\" conflicts"}, + {"bare repo with --org", "pool-org", "target-repo", "pool-org", "target-repo", ""}, + {"bare repo without --org", "", "target-repo", "", "", "--org is required"}, + {"no flags", "", "", "", "", "--org is required"}, + {"invalid org in owner/repo", "", "bad org/repo", "", "", "invalid owner"}, + {"invalid repo name", "pool-org", "bad repo", "", "", "invalid repo name"}, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + got, err := resolveForeignTarget(tc.org, tc.repo) + if tc.wantErr != "" { + require.Error(t, err) + assert.Contains(t, err.Error(), tc.wantErr) + return + } + require.NoError(t, err) + assert.Equal(t, tc.wantOrg, got.org) + assert.Equal(t, tc.wantRepo, got.repo) + }) + } +} + +func TestForeignAllowCmd_RepoLevel(t *testing.T) { + state := &foreignVarState{ + vars: map[string]string{}, + repoVars: map[string]string{}, + } + srv := httptest.NewServer(state.handler(t)) + defer srv.Close() + + _, err := runForeignCmd(t, srv.URL, "allow", "--repo", "pool-org/target-repo", "--role", "e2e", "--caller", "fullsend-ai/fullsend") + require.NoError(t, err) + assert.Equal(t, "fullsend-ai/fullsend", state.repoVars["pool-org/target-repo/FULLSEND_FOREIGN_E2E_REPOS"]) +} + +func TestForeignAllowCmd_RepoLevel_SplitForm(t *testing.T) { + state := &foreignVarState{ + vars: map[string]string{}, + repoVars: map[string]string{}, + } + srv := httptest.NewServer(state.handler(t)) + defer srv.Close() + + _, err := runForeignCmd(t, srv.URL, "allow", "--org", "pool-org", "--repo", "target-repo", "--role", "e2e", "--caller", "fullsend-ai/fullsend") + require.NoError(t, err) + assert.Equal(t, "fullsend-ai/fullsend", state.repoVars["pool-org/target-repo/FULLSEND_FOREIGN_E2E_REPOS"]) +} + +func TestForeignAllowCmd_RepoLevel_AppendsCaller(t *testing.T) { + state := &foreignVarState{ + vars: map[string]string{}, + repoVars: map[string]string{ + "pool-org/target-repo/FULLSEND_FOREIGN_E2E_REPOS": "konflux-ci", + }, + } + srv := httptest.NewServer(state.handler(t)) + defer srv.Close() + + _, err := runForeignCmd(t, srv.URL, "allow", "--repo", "pool-org/target-repo", "--role", "e2e", "--caller", "fullsend-ai/fullsend") + require.NoError(t, err) + val := state.repoVars["pool-org/target-repo/FULLSEND_FOREIGN_E2E_REPOS"] + assert.Contains(t, val, "konflux-ci") + assert.Contains(t, val, "fullsend-ai/fullsend") +} + +func TestForeignListCmd_RepoLevel_SingleRole(t *testing.T) { + state := &foreignVarState{ + vars: map[string]string{}, + repoVars: map[string]string{ + "pool-org/target-repo/FULLSEND_FOREIGN_E2E_REPOS": "fullsend-ai/fullsend", + }, + } + srv := httptest.NewServer(state.handler(t)) + defer srv.Close() + + _, err := runForeignCmd(t, srv.URL, "list", "--repo", "pool-org/target-repo", "--role", "e2e") + require.NoError(t, err) +} + +func TestForeignListCmd_RepoLevel_AllVars(t *testing.T) { + state := &foreignVarState{ + vars: map[string]string{}, + repoVars: map[string]string{ + "pool-org/target-repo/FULLSEND_FOREIGN_E2E_REPOS": "fullsend-ai", + "pool-org/target-repo/FULLSEND_FOREIGN_CODER_REPOS": "acme/api", + "pool-org/target-repo/OTHER_VAR": "ignored", + }, + } + srv := httptest.NewServer(state.handler(t)) + defer srv.Close() + + _, err := runForeignCmd(t, srv.URL, "list", "--repo", "pool-org/target-repo") + require.NoError(t, err) +} + +func TestForeignListCmd_RepoLevel_NoVars(t *testing.T) { + state := &foreignVarState{ + vars: map[string]string{}, + repoVars: map[string]string{}, + } + srv := httptest.NewServer(state.handler(t)) + defer srv.Close() + + _, err := runForeignCmd(t, srv.URL, "list", "--repo", "pool-org/target-repo") + require.NoError(t, err) +} + +func TestForeignRevokeCmd_RepoLevel(t *testing.T) { + state := &foreignVarState{ + vars: map[string]string{}, + repoVars: map[string]string{ + "pool-org/target-repo/FULLSEND_FOREIGN_E2E_REPOS": "fullsend-ai/fullsend, konflux-ci", + }, + } + srv := httptest.NewServer(state.handler(t)) + defer srv.Close() + + _, err := runForeignCmd(t, srv.URL, "revoke", "--repo", "pool-org/target-repo", "--role", "e2e", "--caller", "konflux-ci") + require.NoError(t, err) + assert.Equal(t, "fullsend-ai/fullsend", state.repoVars["pool-org/target-repo/FULLSEND_FOREIGN_E2E_REPOS"]) +} + +func TestForeignRevokeCmd_RepoLevel_DeletesEmpty(t *testing.T) { + state := &foreignVarState{ + vars: map[string]string{}, + repoVars: map[string]string{ + "pool-org/target-repo/FULLSEND_FOREIGN_E2E_REPOS": "fullsend-ai/fullsend", + }, + } + srv := httptest.NewServer(state.handler(t)) + defer srv.Close() + + _, err := runForeignCmd(t, srv.URL, "revoke", "--repo", "pool-org/target-repo", "--role", "e2e", "--caller", "fullsend-ai/fullsend") + require.NoError(t, err) + assert.NotContains(t, state.repoVars, "pool-org/target-repo/FULLSEND_FOREIGN_E2E_REPOS") +} + +func TestForeignRevokeCmd_RepoLevel_NotPresent(t *testing.T) { + state := &foreignVarState{ + vars: map[string]string{}, + repoVars: map[string]string{ + "pool-org/target-repo/FULLSEND_FOREIGN_E2E_REPOS": "fullsend-ai/fullsend", + }, + } + srv := httptest.NewServer(state.handler(t)) + defer srv.Close() + + _, err := runForeignCmd(t, srv.URL, "revoke", "--repo", "pool-org/target-repo", "--role", "e2e", "--caller", "missing/repo") + require.NoError(t, err) + assert.Equal(t, "fullsend-ai/fullsend", state.repoVars["pool-org/target-repo/FULLSEND_FOREIGN_E2E_REPOS"]) +} + +func TestForeignAllowCmd_OrgLevelStillWorks(t *testing.T) { + // Ensure existing org-level behavior is preserved when --repo is not used. + state := &foreignVarState{ + vars: map[string]string{}, + repoVars: map[string]string{}, + } + srv := httptest.NewServer(state.handler(t)) + defer srv.Close() + + _, err := runForeignCmd(t, srv.URL, "allow", "--org", "pool-org", "--role", "e2e", "--caller", "fullsend-ai/fullsend") + require.NoError(t, err) + assert.Equal(t, "fullsend-ai/fullsend", state.vars["FULLSEND_FOREIGN_E2E_REPOS"]) + assert.Empty(t, state.repoVars) +} diff --git a/internal/dispatch/gcf/mintsrc/mintcore/foreign.go.embed b/internal/dispatch/gcf/mintsrc/mintcore/foreign.go.embed index 4e2b6e999f..34479bfb3e 100644 --- a/internal/dispatch/gcf/mintsrc/mintcore/foreign.go.embed +++ b/internal/dispatch/gcf/mintsrc/mintcore/foreign.go.embed @@ -49,6 +49,12 @@ func foreignCacheKey(targetOrg, role string) string { return strings.ToLower(targetOrg) + "/" + strings.ToLower(role) } +// repoForeignCacheKey builds a cache key for repo-level policy lookups +// (target org + repo + role), distinct from the org-level foreignCacheKey. +func repoForeignCacheKey(targetOrg, targetRepo, role string) string { + return strings.ToLower(targetOrg) + "/" + strings.ToLower(targetRepo) + "/" + strings.ToLower(role) +} + // validateTargetOrg checks target_org when cross-org mint is requested. func validateTargetOrg(targetOrg string) error { if err := ValidateOrgName(targetOrg); err != nil { diff --git a/internal/dispatch/gcf/mintsrc/mintcore/github.go.embed b/internal/dispatch/gcf/mintsrc/mintcore/github.go.embed index 265e514d54..3f8da5dcfa 100644 --- a/internal/dispatch/gcf/mintsrc/mintcore/github.go.embed +++ b/internal/dispatch/gcf/mintsrc/mintcore/github.go.embed @@ -314,8 +314,9 @@ func FindOrgInstallation(ctx context.Context, httpClient HTTPDoer, githubBaseURL return inst.ID, nil } -// orgVariableResponse is the response from GET /orgs/{org}/actions/variables/{name}. -type orgVariableResponse struct { +// variableResponse is the JSON shape for GET /orgs/{org}/actions/variables/{name} +// and GET /repos/{owner}/{repo}/actions/variables/{name} (identical schema). +type variableResponse struct { Name string `json:"name"` Value string `json:"value"` } @@ -344,18 +345,54 @@ func GetOrgVariable(ctx context.Context, httpClient HTTPDoer, githubBaseURL, ins return "", false, fmt.Errorf("getting org variable %s returned status %d", name, resp.StatusCode) } - var varResp orgVariableResponse + var varResp variableResponse if err := json.NewDecoder(resp.Body).Decode(&varResp); err != nil { return "", false, fmt.Errorf("decoding org variable: %w", err) } return varResp.Value, true, nil } +// GetRepoVariable reads a repo-level Actions variable using an installation token. +func GetRepoVariable(ctx context.Context, httpClient HTTPDoer, githubBaseURL, installationToken, owner, repo, name string) (value string, exists bool, err error) { + reqURL := fmt.Sprintf("%s/repos/%s/%s/actions/variables/%s", githubBaseURL, owner, repo, name) + req, err := http.NewRequestWithContext(ctx, http.MethodGet, reqURL, nil) + if err != nil { + return "", false, fmt.Errorf("creating repo variable request: %w", err) + } + req.Header.Set("Authorization", "Bearer "+installationToken) + req.Header.Set("Accept", "application/vnd.github+json") + + resp, err := httpClient.Do(req) + if err != nil { + return "", false, fmt.Errorf("getting repo variable: %w", err) + } + defer resp.Body.Close() + + if resp.StatusCode == http.StatusNotFound { + return "", false, nil + } + if resp.StatusCode != http.StatusOK { + io.Copy(io.Discard, io.LimitReader(resp.Body, 4096)) + return "", false, fmt.Errorf("getting repo variable %s on %s/%s returned status %d", name, owner, repo, resp.StatusCode) + } + + var varResp variableResponse + if err := json.NewDecoder(resp.Body).Decode(&varResp); err != nil { + return "", false, fmt.Errorf("decoding repo variable: %w", err) + } + return varResp.Value, true, nil +} + // foreignPolicyPermissions are requested when reading FULLSEND_FOREIGN_* org variables. var foreignPolicyPermissions = map[string]string{ "organization_actions_variables": "read", } +// repoForeignPolicyPermissions are requested when reading FULLSEND_FOREIGN_* repo variables. +var repoForeignPolicyPermissions = map[string]string{ + "actions_variables": "read", +} + // createInstallationTokenWithPermissions creates an installation access token with explicit permissions. func createInstallationTokenWithPermissions(ctx context.Context, httpClient HTTPDoer, githubBaseURL, jwt string, installationID int64, perms map[string]string, repos []string) (string, error) { tokenReqBody := map[string]interface{}{ @@ -418,6 +455,26 @@ func ReadForeignAllowlist(ctx context.Context, httpClient HTTPDoer, githubBaseUR return ParseForeignAllowlist(value), nil } +// ReadForeignAllowlistFromRepo reads FULLSEND_FOREIGN__REPOS from a +// specific target repository. This is the repo-level counterpart of +// ReadForeignAllowlist, enabling per-repo foreign authorization grants. +func ReadForeignAllowlistFromRepo(ctx context.Context, httpClient HTTPDoer, githubBaseURL, jwt string, installationID int64, targetOrg, targetRepo, role string) ([]string, error) { + policyToken, err := createInstallationTokenWithPermissions(ctx, httpClient, githubBaseURL, jwt, installationID, + repoForeignPolicyPermissions, []string{targetRepo}) + if err != nil { + return nil, fmt.Errorf("creating repo policy check token: %w", err) + } + + value, exists, err := GetRepoVariable(ctx, httpClient, githubBaseURL, policyToken, targetOrg, targetRepo, ForeignVariableName(role)) + if err != nil { + return nil, err + } + if !exists || strings.TrimSpace(value) == "" { + return nil, nil + } + return ParseForeignAllowlist(value), nil +} + // CreateInstallationToken exchanges a JWT for an installation access token, // scoped to the given repos and role-specific permissions. func CreateInstallationToken(ctx context.Context, httpClient HTTPDoer, githubBaseURL, jwt string, installationID int64, role string, repos []string) (string, string, *GrantedScope, error) { diff --git a/internal/dispatch/gcf/mintsrc/mintcore/handler.go.embed b/internal/dispatch/gcf/mintsrc/mintcore/handler.go.embed index 6d90e1c88f..e23eebd772 100644 --- a/internal/dispatch/gcf/mintsrc/mintcore/handler.go.embed +++ b/internal/dispatch/gcf/mintsrc/mintcore/handler.go.embed @@ -330,13 +330,29 @@ func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { writeError(w, http.StatusUnauthorized, "authentication failed") return } - shape, err := validateReposScope(isTargetForeign, claims.Repository, req.Repos, isPerRepo) - if err != nil { - writeError(w, http.StatusForbidden, err.Error()) + shape, scopeErr := validateReposScope(isTargetForeign, claims.Repository, req.Repos, isPerRepo) + if scopeErr != nil && !isTargetForeign { + // Same-org scope denied. For per-repo callers requesting repos + // beyond their own (specific per-repo denial), check repo-level + // FOREIGN grants. Only override the per-repo cross-repo denial; + // other denial reasons (empty repos, org-mode shape violations) + // must not be overridden. + if isPerRepo && len(req.Repos) > 0 && errors.Is(scopeErr, errPerRepoCrossRepo) { + if fErr := h.checkRepoForeignGrants(ctx, claims, callerOrg, req.Role, req.Repos); fErr == nil { + log.Printf("intra-org repo-level foreign grant: caller=%s target_org=%s repos=%v role=%s", + claims.Repository, callerOrg, req.Repos, req.Role) + scopeErr = nil + } else { + log.Printf("intra-org repo-level foreign grant check failed: %v", fErr) + } + } + } + if scopeErr != nil { + writeError(w, http.StatusForbidden, scopeErr.Error()) return } if shape != "" { - log.Printf("org-mode repos scope shape=%s requested_repos=%v source_repo=%s target_org=%s role=%s", + log.Printf("repos scope shape=%s requested_repos=%v source_repo=%s target_org=%s role=%s", shape, req.Repos, claims.Repository, targetOrg, req.Role) } @@ -497,18 +513,29 @@ func (h *Handler) mintToken(ctx context.Context, org, role string, repos []strin } func (h *Handler) mintTokenCrossOrg(ctx context.Context, claims *Claims, targetOrg, role string, repos []string) (string, string, *GrantedScope, error) { + // Specific repos requested → authorize exclusively via per-repo + // FOREIGN grants. Org-level FOREIGN is not consulted for repo-scoped + // requests; it authorizes only installation-wide tokens. + if len(repos) > 0 { + if err := h.checkRepoForeignGrants(ctx, claims, targetOrg, role, repos); err != nil { + log.Printf("repo-level foreign grant check failed: %v", err) + return "", "", nil, &mintError{status: http.StatusForbidden, msg: "foreign caller not authorized for target repos"} + } + log.Printf("repo-level foreign grant: caller=%s target_org=%s repos=%v role=%s", + claims.Repository, targetOrg, repos, role) + return h.mintToken(ctx, targetOrg, role, repos) + } + + // Installation-wide (empty repos) → org-level FOREIGN check only. allowlist, err := h.loadForeignAllowlist(ctx, targetOrg, role) if err != nil { return "", "", nil, &mintError{status: http.StatusBadGateway, msg: err.Error()} } - if len(allowlist) == 0 { - return "", "", nil, &mintError{status: http.StatusForbidden, msg: "foreign caller not authorized for target org"} - } - if !CallerAllowed(allowlist, claims.Repository, claims.RepositoryOwner) { - return "", "", nil, &mintError{status: http.StatusForbidden, msg: "foreign caller not authorized for target org"} + if CallerAllowed(allowlist, claims.Repository, claims.RepositoryOwner) { + return h.mintToken(ctx, targetOrg, role, repos) } - return h.mintToken(ctx, targetOrg, role, repos) + return "", "", nil, &mintError{status: http.StatusForbidden, msg: "foreign caller not authorized for target org"} } func (h *Handler) loadForeignAllowlist(ctx context.Context, targetOrg, role string) ([]string, error) { @@ -588,6 +615,110 @@ func (h *Handler) fetchForeignAllowlist(ctx context.Context, targetOrg, role str return allowlist, nil } +// checkRepoForeignGrants verifies that every repo in repos has a repo-level +// FULLSEND_FOREIGN__REPOS variable that authorizes the caller. +// +// This function serves two distinct authorization paths: +// - Cross-org primary authorization: called from mintTokenCrossOrg when +// a foreign request carries specific repos (repo-scoped FOREIGN grant). +// - Intra-org fallback: called from the main handler when a per-repo +// caller requests repos beyond its own repository within the same org +// (errPerRepoCrossRepo), allowing cross-repo access via repo-level grants. +func (h *Handler) checkRepoForeignGrants(ctx context.Context, claims *Claims, targetOrg, role string, repos []string) error { + for _, repo := range repos { + allowlist, err := h.loadRepoForeignAllowlist(ctx, targetOrg, repo, role) + if err != nil { + return fmt.Errorf("checking repo-level foreign grant on %s/%s: %v", targetOrg, repo, err) + } + if !CallerAllowed(allowlist, claims.Repository, claims.RepositoryOwner) { + return fmt.Errorf("caller %s not authorized by repo-level foreign grant on %s/%s", claims.Repository, targetOrg, repo) + } + } + return nil +} + +// loadRepoForeignAllowlist loads the repo-level FOREIGN allowlist for a +// specific target repo, with in-memory caching and inflight dedup (same +// pattern as loadForeignAllowlist for org-level). +func (h *Handler) loadRepoForeignAllowlist(ctx context.Context, targetOrg, targetRepo, role string) ([]string, error) { + key := repoForeignCacheKey(targetOrg, targetRepo, role) + + h.foreignCacheMu.Lock() + if entry, ok := h.foreignCache[key]; ok && time.Since(entry.fetchedAt) < h.foreignCacheTTL { + allowlist := append([]string(nil), entry.allowlist...) + h.foreignCacheMu.Unlock() + return allowlist, nil + } + if inflight, ok := h.foreignInflight[key]; ok { + h.foreignCacheMu.Unlock() + inflight.wg.Wait() + if inflight.err != nil { + return nil, inflight.err + } + return append([]string(nil), inflight.allowlist...), nil + } + inflight := &foreignInflight{} + inflight.wg.Add(1) + h.foreignInflight[key] = inflight + h.foreignCacheMu.Unlock() + + allowlist, err := h.fetchRepoForeignAllowlist(ctx, targetOrg, targetRepo, role) + + h.foreignCacheMu.Lock() + delete(h.foreignInflight, key) + if err == nil { + h.foreignCache[key] = foreignCacheEntry{ + allowlist: append([]string(nil), allowlist...), + fetchedAt: time.Now(), + } + } + inflight.allowlist = allowlist + inflight.err = err + inflight.wg.Done() + h.foreignCacheMu.Unlock() + + if err != nil { + return nil, err + } + return allowlist, nil +} + +// fetchRepoForeignAllowlist reads FULLSEND_FOREIGN__REPOS from a +// specific target repo's repo-level Actions variables. +func (h *Handler) fetchRepoForeignAllowlist(ctx context.Context, targetOrg, targetRepo, role string) ([]string, error) { + appID, err := h.lookupRoleAppID(role) + if err != nil { + return nil, fmt.Errorf("looking up app ID for role %s: %v", role, err) + } + + pemData, err := h.pemAccessor.AccessPEM(ctx, role) + if err != nil { + return nil, fmt.Errorf("reading PEM secret for role %s: %v", role, err) + } + defer func() { + for i := range pemData { + pemData[i] = 0 + } + }() + + jwt, err := GenerateAppJWT(appID, pemData) + if err != nil { + return nil, fmt.Errorf("generating app JWT: %v", err) + } + + installationID, err := FindInstallation(ctx, h.httpClient, h.githubBaseURL, jwt, targetOrg, targetRepo) + if err != nil { + return nil, fmt.Errorf("finding repo installation on %s/%s: %v", targetOrg, targetRepo, err) + } + + allowlist, err := ReadForeignAllowlistFromRepo(ctx, h.httpClient, h.githubBaseURL, jwt, installationID, targetOrg, targetRepo, role) + if err != nil { + return nil, err + } + + return allowlist, nil +} + func (h *Handler) checkAllowedRole(role string) bool { for _, entry := range h.allowedRoles { if entry == role { diff --git a/internal/dispatch/gcf/mintsrc/mintcore/repos_scope.go.embed b/internal/dispatch/gcf/mintsrc/mintcore/repos_scope.go.embed index a3218174f8..73815bc557 100644 --- a/internal/dispatch/gcf/mintsrc/mintcore/repos_scope.go.embed +++ b/internal/dispatch/gcf/mintsrc/mintcore/repos_scope.go.embed @@ -1,14 +1,26 @@ package mintcore import ( + "errors" "fmt" "strings" ) -// Org-mode shape labels returned by validateReposScope when a per-org caller -// uses a broader-than-self same-org repos list. Empty means the default path -// (foreign empty repos, or same-org requesting-repo-only). +// errPerRepoCrossRepo is a sentinel returned when a per-repo caller +// requests repos beyond its own repository. The handler checks this +// sentinel to decide whether to try repo-level FOREIGN grants. +var errPerRepoCrossRepo = errors.New("per-repo mint requires repos to be exactly the requesting repository") + +// Shape labels returned by validateReposScope. A non-empty shape signals that +// the caller must take path-specific action (see each constant's doc). const ( + // reposScopeShapeForeignRepoScoped is returned for foreign (cross-org) + // requests with non-empty repos. The caller MUST perform repo-level + // FOREIGN grant authorization (via mintTokenCrossOrg) before minting. + // Treating this shape as "fully authorized" without the follow-up check + // would bypass authorization entirely. + reposScopeShapeForeignRepoScoped = "foreign-repo-scoped" + reposScopeShapeFullsendAny = "fullsend-any" reposScopeShapeEnrolledFullsend = "enrolled-fullsend" reposScopeShapeEnrolledPair = "enrolled-pair" @@ -42,7 +54,14 @@ func repositoryBareName(repository string) string { // validateReposScope enforces mint repos authorization after OIDC verification. // -// Foreign (cross-org) requests may only omit repos (or use "*" → empty). +// For foreign (cross-org) requests with non-empty repos, this function returns +// reposScopeShapeForeignRepoScoped to signal that repo-level FOREIGN grant +// authorization is required. Callers MUST check for this shape and invoke +// mintTokenCrossOrg — treating a nil error alone as "fully authorized" would +// bypass repo-level authorization entirely. Foreign requests with empty repos +// (installation-wide) return an empty shape; org-level FOREIGN authorization +// is handled by mintTokenCrossOrg's own empty-repos path. +// // Same-org requests differ based on whether the caller is per-repo or per-org: // // - Per-repo callers (perRepo=true): must list exactly the requesting @@ -52,12 +71,18 @@ func repositoryBareName(repository string) string { // other callers: exactly [.fullsend] or {requestingBare, .fullsend}. // Same-org installation-wide (empty repos) is always denied. // -// On success, shape is non-empty only when an org-mode exception matched. +// On success, a non-empty shape signals a path-specific authorization +// requirement (foreign-repo-scoped or org-mode exception). func validateReposScope(isTargetForeign bool, requestingRepo string, repos []string, perRepo bool) (shape string, err error) { if isTargetForeign { - if len(repos) != 0 { - return "", fmt.Errorf("foreign mint requires empty repos") + if len(repos) > 0 { + // Non-empty repos → repo-scoped. Return the sentinel shape + // so the caller knows repo-level FOREIGN grant authorization + // is required (performed in mintTokenCrossOrg). + return reposScopeShapeForeignRepoScoped, nil } + // Empty repos → installation-wide (org-level FOREIGN grant + // checked in mintTokenCrossOrg). return "", nil } @@ -71,7 +96,7 @@ func validateReposScope(isTargetForeign bool, requestingRepo string, repos []str } if perRepo { - return "", fmt.Errorf("per-repo mint requires repos to be exactly the requesting repository") + return "", errPerRepoCrossRepo } // Per-org callers get org-mode shapes. diff --git a/internal/mintcore/foreign.go b/internal/mintcore/foreign.go index 4e2b6e999f..34479bfb3e 100644 --- a/internal/mintcore/foreign.go +++ b/internal/mintcore/foreign.go @@ -49,6 +49,12 @@ func foreignCacheKey(targetOrg, role string) string { return strings.ToLower(targetOrg) + "/" + strings.ToLower(role) } +// repoForeignCacheKey builds a cache key for repo-level policy lookups +// (target org + repo + role), distinct from the org-level foreignCacheKey. +func repoForeignCacheKey(targetOrg, targetRepo, role string) string { + return strings.ToLower(targetOrg) + "/" + strings.ToLower(targetRepo) + "/" + strings.ToLower(role) +} + // validateTargetOrg checks target_org when cross-org mint is requested. func validateTargetOrg(targetOrg string) error { if err := ValidateOrgName(targetOrg); err != nil { diff --git a/internal/mintcore/foreign_test.go b/internal/mintcore/foreign_test.go index 1cf5fd7beb..6671ca3459 100644 --- a/internal/mintcore/foreign_test.go +++ b/internal/mintcore/foreign_test.go @@ -45,3 +45,15 @@ func TestCallerAllowed(t *testing.T) { t.Fatal("expected case-insensitive repo match") } } + +func TestRepoForeignCacheKey(t *testing.T) { + got := repoForeignCacheKey("TargetOrg", "TargetRepo", "Coder") + if got != "targetorg/targetrepo/coder" { + t.Fatalf("got %q", got) + } + // Distinct from org-level key. + orgKey := foreignCacheKey("TargetOrg", "Coder") + if got == orgKey { + t.Fatal("repo cache key should differ from org cache key") + } +} diff --git a/internal/mintcore/github.go b/internal/mintcore/github.go index 265e514d54..3f8da5dcfa 100644 --- a/internal/mintcore/github.go +++ b/internal/mintcore/github.go @@ -314,8 +314,9 @@ func FindOrgInstallation(ctx context.Context, httpClient HTTPDoer, githubBaseURL return inst.ID, nil } -// orgVariableResponse is the response from GET /orgs/{org}/actions/variables/{name}. -type orgVariableResponse struct { +// variableResponse is the JSON shape for GET /orgs/{org}/actions/variables/{name} +// and GET /repos/{owner}/{repo}/actions/variables/{name} (identical schema). +type variableResponse struct { Name string `json:"name"` Value string `json:"value"` } @@ -344,18 +345,54 @@ func GetOrgVariable(ctx context.Context, httpClient HTTPDoer, githubBaseURL, ins return "", false, fmt.Errorf("getting org variable %s returned status %d", name, resp.StatusCode) } - var varResp orgVariableResponse + var varResp variableResponse if err := json.NewDecoder(resp.Body).Decode(&varResp); err != nil { return "", false, fmt.Errorf("decoding org variable: %w", err) } return varResp.Value, true, nil } +// GetRepoVariable reads a repo-level Actions variable using an installation token. +func GetRepoVariable(ctx context.Context, httpClient HTTPDoer, githubBaseURL, installationToken, owner, repo, name string) (value string, exists bool, err error) { + reqURL := fmt.Sprintf("%s/repos/%s/%s/actions/variables/%s", githubBaseURL, owner, repo, name) + req, err := http.NewRequestWithContext(ctx, http.MethodGet, reqURL, nil) + if err != nil { + return "", false, fmt.Errorf("creating repo variable request: %w", err) + } + req.Header.Set("Authorization", "Bearer "+installationToken) + req.Header.Set("Accept", "application/vnd.github+json") + + resp, err := httpClient.Do(req) + if err != nil { + return "", false, fmt.Errorf("getting repo variable: %w", err) + } + defer resp.Body.Close() + + if resp.StatusCode == http.StatusNotFound { + return "", false, nil + } + if resp.StatusCode != http.StatusOK { + io.Copy(io.Discard, io.LimitReader(resp.Body, 4096)) + return "", false, fmt.Errorf("getting repo variable %s on %s/%s returned status %d", name, owner, repo, resp.StatusCode) + } + + var varResp variableResponse + if err := json.NewDecoder(resp.Body).Decode(&varResp); err != nil { + return "", false, fmt.Errorf("decoding repo variable: %w", err) + } + return varResp.Value, true, nil +} + // foreignPolicyPermissions are requested when reading FULLSEND_FOREIGN_* org variables. var foreignPolicyPermissions = map[string]string{ "organization_actions_variables": "read", } +// repoForeignPolicyPermissions are requested when reading FULLSEND_FOREIGN_* repo variables. +var repoForeignPolicyPermissions = map[string]string{ + "actions_variables": "read", +} + // createInstallationTokenWithPermissions creates an installation access token with explicit permissions. func createInstallationTokenWithPermissions(ctx context.Context, httpClient HTTPDoer, githubBaseURL, jwt string, installationID int64, perms map[string]string, repos []string) (string, error) { tokenReqBody := map[string]interface{}{ @@ -418,6 +455,26 @@ func ReadForeignAllowlist(ctx context.Context, httpClient HTTPDoer, githubBaseUR return ParseForeignAllowlist(value), nil } +// ReadForeignAllowlistFromRepo reads FULLSEND_FOREIGN__REPOS from a +// specific target repository. This is the repo-level counterpart of +// ReadForeignAllowlist, enabling per-repo foreign authorization grants. +func ReadForeignAllowlistFromRepo(ctx context.Context, httpClient HTTPDoer, githubBaseURL, jwt string, installationID int64, targetOrg, targetRepo, role string) ([]string, error) { + policyToken, err := createInstallationTokenWithPermissions(ctx, httpClient, githubBaseURL, jwt, installationID, + repoForeignPolicyPermissions, []string{targetRepo}) + if err != nil { + return nil, fmt.Errorf("creating repo policy check token: %w", err) + } + + value, exists, err := GetRepoVariable(ctx, httpClient, githubBaseURL, policyToken, targetOrg, targetRepo, ForeignVariableName(role)) + if err != nil { + return nil, err + } + if !exists || strings.TrimSpace(value) == "" { + return nil, nil + } + return ParseForeignAllowlist(value), nil +} + // CreateInstallationToken exchanges a JWT for an installation access token, // scoped to the given repos and role-specific permissions. func CreateInstallationToken(ctx context.Context, httpClient HTTPDoer, githubBaseURL, jwt string, installationID int64, role string, repos []string) (string, string, *GrantedScope, error) { diff --git a/internal/mintcore/github_test.go b/internal/mintcore/github_test.go index f7d3dfd450..07882b6f6e 100644 --- a/internal/mintcore/github_test.go +++ b/internal/mintcore/github_test.go @@ -347,7 +347,7 @@ func TestFindOrgInstallation_OrgMismatch(t *testing.T) { func TestGetOrgVariable(t *testing.T) { mockGH := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { assert.Equal(t, "/orgs/pool-org/actions/variables/FULLSEND_FOREIGN_E2E_REPOS", r.URL.Path) - json.NewEncoder(w).Encode(orgVariableResponse{ + json.NewEncoder(w).Encode(variableResponse{ Name: "FULLSEND_FOREIGN_E2E_REPOS", Value: "fullsend-ai/fullsend", }) @@ -380,7 +380,7 @@ func TestReadForeignAllowlist(t *testing.T) { w.WriteHeader(http.StatusCreated) json.NewEncoder(w).Encode(installationTokenResponse{Token: "ghs_policy"}) case r.URL.Path == "/orgs/pool-org/actions/variables/FULLSEND_FOREIGN_E2E_REPOS": - json.NewEncoder(w).Encode(orgVariableResponse{ + json.NewEncoder(w).Encode(variableResponse{ Name: "FULLSEND_FOREIGN_E2E_REPOS", Value: "fullsend-ai/fullsend, fullsend-ai", }) @@ -437,3 +437,90 @@ func TestGetOrgVariable_ErrorStatus(t *testing.T) { require.Error(t, err) assert.Contains(t, err.Error(), "status 403") } + +func TestGetRepoVariable(t *testing.T) { + mockGH := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/repos/target-org/target-repo/actions/variables/MY_VAR" && r.Method == http.MethodGet { + json.NewEncoder(w).Encode(variableResponse{ + Name: "MY_VAR", + Value: "hello", + }) + return + } + t.Errorf("unexpected %s %s", r.Method, r.URL.Path) + http.NotFound(w, r) + })) + defer mockGH.Close() + + val, exists, err := GetRepoVariable(t.Context(), http.DefaultClient, mockGH.URL, "ghs_tok", "target-org", "target-repo", "MY_VAR") + require.NoError(t, err) + assert.True(t, exists) + assert.Equal(t, "hello", val) +} + +func TestGetRepoVariable_NotFound(t *testing.T) { + mockGH := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusNotFound) + })) + defer mockGH.Close() + + _, exists, err := GetRepoVariable(t.Context(), http.DefaultClient, mockGH.URL, "ghs_tok", "target-org", "target-repo", "MY_VAR") + require.NoError(t, err) + assert.False(t, exists) +} + +func TestGetRepoVariable_ErrorStatus(t *testing.T) { + mockGH := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusForbidden) + })) + defer mockGH.Close() + + _, _, err := GetRepoVariable(t.Context(), http.DefaultClient, mockGH.URL, "ghs_tok", "target-org", "target-repo", "MY_VAR") + require.Error(t, err) + assert.Contains(t, err.Error(), "status 403") +} + +func TestReadForeignAllowlistFromRepo(t *testing.T) { + var tokenCalls int + mockGH := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch { + case strings.HasPrefix(r.URL.Path, "/app/installations/42/access_tokens") && r.Method == http.MethodPost: + tokenCalls++ + w.WriteHeader(http.StatusCreated) + json.NewEncoder(w).Encode(installationTokenResponse{Token: "ghs_repo_policy"}) + case r.URL.Path == "/repos/pool-org/target-repo/actions/variables/FULLSEND_FOREIGN_E2E_REPOS": + json.NewEncoder(w).Encode(variableResponse{ + Name: "FULLSEND_FOREIGN_E2E_REPOS", + Value: "fullsend-ai/fullsend, caller-org", + }) + default: + t.Errorf("unexpected %s %s", r.Method, r.URL.Path) + http.NotFound(w, r) + } + })) + defer mockGH.Close() + + got, err := ReadForeignAllowlistFromRepo(t.Context(), http.DefaultClient, mockGH.URL, "app-jwt", 42, "pool-org", "target-repo", "e2e") + require.NoError(t, err) + assert.Equal(t, []string{"fullsend-ai/fullsend", "caller-org"}, got) + assert.Equal(t, 1, tokenCalls) +} + +func TestReadForeignAllowlistFromRepo_Empty(t *testing.T) { + mockGH := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch { + case strings.HasPrefix(r.URL.Path, "/app/installations/42/access_tokens"): + w.WriteHeader(http.StatusCreated) + json.NewEncoder(w).Encode(installationTokenResponse{Token: "ghs_repo_policy"}) + case strings.Contains(r.URL.Path, "/actions/variables/"): + w.WriteHeader(http.StatusNotFound) + default: + t.Errorf("unexpected %s %s", r.Method, r.URL.Path) + } + })) + defer mockGH.Close() + + got, err := ReadForeignAllowlistFromRepo(t.Context(), http.DefaultClient, mockGH.URL, "app-jwt", 42, "pool-org", "target-repo", "e2e") + require.NoError(t, err) + assert.Nil(t, got) +} diff --git a/internal/mintcore/handler.go b/internal/mintcore/handler.go index 6d90e1c88f..e23eebd772 100644 --- a/internal/mintcore/handler.go +++ b/internal/mintcore/handler.go @@ -330,13 +330,29 @@ func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { writeError(w, http.StatusUnauthorized, "authentication failed") return } - shape, err := validateReposScope(isTargetForeign, claims.Repository, req.Repos, isPerRepo) - if err != nil { - writeError(w, http.StatusForbidden, err.Error()) + shape, scopeErr := validateReposScope(isTargetForeign, claims.Repository, req.Repos, isPerRepo) + if scopeErr != nil && !isTargetForeign { + // Same-org scope denied. For per-repo callers requesting repos + // beyond their own (specific per-repo denial), check repo-level + // FOREIGN grants. Only override the per-repo cross-repo denial; + // other denial reasons (empty repos, org-mode shape violations) + // must not be overridden. + if isPerRepo && len(req.Repos) > 0 && errors.Is(scopeErr, errPerRepoCrossRepo) { + if fErr := h.checkRepoForeignGrants(ctx, claims, callerOrg, req.Role, req.Repos); fErr == nil { + log.Printf("intra-org repo-level foreign grant: caller=%s target_org=%s repos=%v role=%s", + claims.Repository, callerOrg, req.Repos, req.Role) + scopeErr = nil + } else { + log.Printf("intra-org repo-level foreign grant check failed: %v", fErr) + } + } + } + if scopeErr != nil { + writeError(w, http.StatusForbidden, scopeErr.Error()) return } if shape != "" { - log.Printf("org-mode repos scope shape=%s requested_repos=%v source_repo=%s target_org=%s role=%s", + log.Printf("repos scope shape=%s requested_repos=%v source_repo=%s target_org=%s role=%s", shape, req.Repos, claims.Repository, targetOrg, req.Role) } @@ -497,18 +513,29 @@ func (h *Handler) mintToken(ctx context.Context, org, role string, repos []strin } func (h *Handler) mintTokenCrossOrg(ctx context.Context, claims *Claims, targetOrg, role string, repos []string) (string, string, *GrantedScope, error) { + // Specific repos requested → authorize exclusively via per-repo + // FOREIGN grants. Org-level FOREIGN is not consulted for repo-scoped + // requests; it authorizes only installation-wide tokens. + if len(repos) > 0 { + if err := h.checkRepoForeignGrants(ctx, claims, targetOrg, role, repos); err != nil { + log.Printf("repo-level foreign grant check failed: %v", err) + return "", "", nil, &mintError{status: http.StatusForbidden, msg: "foreign caller not authorized for target repos"} + } + log.Printf("repo-level foreign grant: caller=%s target_org=%s repos=%v role=%s", + claims.Repository, targetOrg, repos, role) + return h.mintToken(ctx, targetOrg, role, repos) + } + + // Installation-wide (empty repos) → org-level FOREIGN check only. allowlist, err := h.loadForeignAllowlist(ctx, targetOrg, role) if err != nil { return "", "", nil, &mintError{status: http.StatusBadGateway, msg: err.Error()} } - if len(allowlist) == 0 { - return "", "", nil, &mintError{status: http.StatusForbidden, msg: "foreign caller not authorized for target org"} - } - if !CallerAllowed(allowlist, claims.Repository, claims.RepositoryOwner) { - return "", "", nil, &mintError{status: http.StatusForbidden, msg: "foreign caller not authorized for target org"} + if CallerAllowed(allowlist, claims.Repository, claims.RepositoryOwner) { + return h.mintToken(ctx, targetOrg, role, repos) } - return h.mintToken(ctx, targetOrg, role, repos) + return "", "", nil, &mintError{status: http.StatusForbidden, msg: "foreign caller not authorized for target org"} } func (h *Handler) loadForeignAllowlist(ctx context.Context, targetOrg, role string) ([]string, error) { @@ -588,6 +615,110 @@ func (h *Handler) fetchForeignAllowlist(ctx context.Context, targetOrg, role str return allowlist, nil } +// checkRepoForeignGrants verifies that every repo in repos has a repo-level +// FULLSEND_FOREIGN__REPOS variable that authorizes the caller. +// +// This function serves two distinct authorization paths: +// - Cross-org primary authorization: called from mintTokenCrossOrg when +// a foreign request carries specific repos (repo-scoped FOREIGN grant). +// - Intra-org fallback: called from the main handler when a per-repo +// caller requests repos beyond its own repository within the same org +// (errPerRepoCrossRepo), allowing cross-repo access via repo-level grants. +func (h *Handler) checkRepoForeignGrants(ctx context.Context, claims *Claims, targetOrg, role string, repos []string) error { + for _, repo := range repos { + allowlist, err := h.loadRepoForeignAllowlist(ctx, targetOrg, repo, role) + if err != nil { + return fmt.Errorf("checking repo-level foreign grant on %s/%s: %v", targetOrg, repo, err) + } + if !CallerAllowed(allowlist, claims.Repository, claims.RepositoryOwner) { + return fmt.Errorf("caller %s not authorized by repo-level foreign grant on %s/%s", claims.Repository, targetOrg, repo) + } + } + return nil +} + +// loadRepoForeignAllowlist loads the repo-level FOREIGN allowlist for a +// specific target repo, with in-memory caching and inflight dedup (same +// pattern as loadForeignAllowlist for org-level). +func (h *Handler) loadRepoForeignAllowlist(ctx context.Context, targetOrg, targetRepo, role string) ([]string, error) { + key := repoForeignCacheKey(targetOrg, targetRepo, role) + + h.foreignCacheMu.Lock() + if entry, ok := h.foreignCache[key]; ok && time.Since(entry.fetchedAt) < h.foreignCacheTTL { + allowlist := append([]string(nil), entry.allowlist...) + h.foreignCacheMu.Unlock() + return allowlist, nil + } + if inflight, ok := h.foreignInflight[key]; ok { + h.foreignCacheMu.Unlock() + inflight.wg.Wait() + if inflight.err != nil { + return nil, inflight.err + } + return append([]string(nil), inflight.allowlist...), nil + } + inflight := &foreignInflight{} + inflight.wg.Add(1) + h.foreignInflight[key] = inflight + h.foreignCacheMu.Unlock() + + allowlist, err := h.fetchRepoForeignAllowlist(ctx, targetOrg, targetRepo, role) + + h.foreignCacheMu.Lock() + delete(h.foreignInflight, key) + if err == nil { + h.foreignCache[key] = foreignCacheEntry{ + allowlist: append([]string(nil), allowlist...), + fetchedAt: time.Now(), + } + } + inflight.allowlist = allowlist + inflight.err = err + inflight.wg.Done() + h.foreignCacheMu.Unlock() + + if err != nil { + return nil, err + } + return allowlist, nil +} + +// fetchRepoForeignAllowlist reads FULLSEND_FOREIGN__REPOS from a +// specific target repo's repo-level Actions variables. +func (h *Handler) fetchRepoForeignAllowlist(ctx context.Context, targetOrg, targetRepo, role string) ([]string, error) { + appID, err := h.lookupRoleAppID(role) + if err != nil { + return nil, fmt.Errorf("looking up app ID for role %s: %v", role, err) + } + + pemData, err := h.pemAccessor.AccessPEM(ctx, role) + if err != nil { + return nil, fmt.Errorf("reading PEM secret for role %s: %v", role, err) + } + defer func() { + for i := range pemData { + pemData[i] = 0 + } + }() + + jwt, err := GenerateAppJWT(appID, pemData) + if err != nil { + return nil, fmt.Errorf("generating app JWT: %v", err) + } + + installationID, err := FindInstallation(ctx, h.httpClient, h.githubBaseURL, jwt, targetOrg, targetRepo) + if err != nil { + return nil, fmt.Errorf("finding repo installation on %s/%s: %v", targetOrg, targetRepo, err) + } + + allowlist, err := ReadForeignAllowlistFromRepo(ctx, h.httpClient, h.githubBaseURL, jwt, installationID, targetOrg, targetRepo, role) + if err != nil { + return nil, err + } + + return allowlist, nil +} + func (h *Handler) checkAllowedRole(role string) bool { for _, entry := range h.allowedRoles { if entry == role { diff --git a/internal/mintcore/handler_test.go b/internal/mintcore/handler_test.go index 2a499f6144..bed64e74ef 100644 --- a/internal/mintcore/handler_test.go +++ b/internal/mintcore/handler_test.go @@ -755,7 +755,7 @@ func TestHandler_EmptyRepos_CrossOrgStarAlias(t *testing.T) { RepositorySelection: "all", }) case r.URL.Path == "/orgs/pool-org/actions/variables/FULLSEND_FOREIGN_E2E_REPOS" && r.Method == http.MethodGet: - json.NewEncoder(w).Encode(orgVariableResponse{ + json.NewEncoder(w).Encode(variableResponse{ Name: "FULLSEND_FOREIGN_E2E_REPOS", Value: "fullsend-ai/fullsend", }) @@ -2880,7 +2880,7 @@ func TestHandler_CrossOrgFullFlow(t *testing.T) { RepositorySelection: "all", }) case r.URL.Path == "/orgs/pool-org/actions/variables/FULLSEND_FOREIGN_E2E_REPOS" && r.Method == http.MethodGet: - json.NewEncoder(w).Encode(orgVariableResponse{ + json.NewEncoder(w).Encode(variableResponse{ Name: "FULLSEND_FOREIGN_E2E_REPOS", Value: "fullsend-ai/fullsend", }) @@ -2909,6 +2909,9 @@ func TestHandler_CrossOrgFullFlow(t *testing.T) { } func TestHandler_CrossOrgNonEmptyReposDenied(t *testing.T) { + // Cross-org with specific repos is now allowed by validateReposScope + // (repo-level FOREIGN grants), but still denied if neither org-level + // nor repo-level FOREIGN variables authorize the caller. t.Setenv("ALLOWED_ORGS", "test-org,fullsend-ai") t.Setenv("ROLE_APP_IDS", `{"e2e":"300"}`) @@ -2924,6 +2927,40 @@ func TestHandler_CrossOrgNonEmptyReposDenied(t *testing.T) { "job_workflow_ref": "fullsend-ai/fullsend/.github/workflows/e2e.yml@refs/heads/main", }) + github := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch { + case r.URL.Path == "/orgs/pool-org/installation" && r.Method == http.MethodGet: + json.NewEncoder(w).Encode(installationResponse{ + ID: 999, Account: struct { + Login string `json:"login"` + }{Login: "pool-org"}, + }) + case r.URL.Path == "/app/installations/999/access_tokens" && r.Method == http.MethodPost: + w.WriteHeader(http.StatusCreated) + json.NewEncoder(w).Encode(installationTokenResponse{Token: "ghs_policy_token"}) + case r.URL.Path == "/orgs/pool-org/actions/variables/FULLSEND_FOREIGN_E2E_REPOS" && r.Method == http.MethodGet: + // Org-level variable does not authorize this caller. + w.WriteHeader(http.StatusNotFound) + case r.URL.Path == "/repos/pool-org/e2e-lock/installation" && r.Method == http.MethodGet: + json.NewEncoder(w).Encode(installationResponse{ + ID: 998, Account: struct { + Login string `json:"login"` + }{Login: "pool-org"}, + }) + case r.URL.Path == "/app/installations/998/access_tokens" && r.Method == http.MethodPost: + w.WriteHeader(http.StatusCreated) + json.NewEncoder(w).Encode(installationTokenResponse{Token: "ghs_repo_policy"}) + case r.URL.Path == "/repos/pool-org/e2e-lock/actions/variables/FULLSEND_FOREIGN_E2E_REPOS" && r.Method == http.MethodGet: + // Repo-level variable not set either. + w.WriteHeader(http.StatusNotFound) + default: + t.Errorf("unexpected request: %s %s", r.Method, r.URL.Path) + w.WriteHeader(http.StatusNotFound) + } + })) + defer github.Close() + env.handler.githubBaseURL = github.URL + body := `{"role":"e2e","target_org":"pool-org","repos":["e2e-lock"]}` rec := httptest.NewRecorder() req := httptest.NewRequest(http.MethodPost, "/v1/token", strings.NewReader(body)) @@ -2933,13 +2970,6 @@ func TestHandler_CrossOrgNonEmptyReposDenied(t *testing.T) { 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) { @@ -2981,7 +3011,7 @@ func TestHandler_ForeignAllowlistCached(t *testing.T) { }) case r.URL.Path == "/orgs/pool-org/actions/variables/FULLSEND_FOREIGN_E2E_REPOS" && r.Method == http.MethodGet: foreignReads++ - json.NewEncoder(w).Encode(orgVariableResponse{ + json.NewEncoder(w).Encode(variableResponse{ Name: "FULLSEND_FOREIGN_E2E_REPOS", Value: "fullsend-ai/fullsend", }) @@ -3054,7 +3084,7 @@ func TestHandler_ForeignAllowlistConcurrent(t *testing.T) { foreignReads++ mu.Unlock() time.Sleep(50 * time.Millisecond) - json.NewEncoder(w).Encode(orgVariableResponse{ + json.NewEncoder(w).Encode(variableResponse{ Name: "FULLSEND_FOREIGN_E2E_REPOS", Value: "fullsend-ai/fullsend", }) @@ -3163,7 +3193,7 @@ func TestHandler_CrossOrgForeignDenied(t *testing.T) { w.WriteHeader(http.StatusCreated) json.NewEncoder(w).Encode(installationTokenResponse{Token: "ghs_policy_token"}) case r.URL.Path == "/orgs/pool-org/actions/variables/FULLSEND_FOREIGN_E2E_REPOS" && r.Method == http.MethodGet: - json.NewEncoder(w).Encode(orgVariableResponse{ + json.NewEncoder(w).Encode(variableResponse{ Name: "FULLSEND_FOREIGN_E2E_REPOS", Value: "fullsend-ai/fullsend", }) @@ -3185,3 +3215,445 @@ func TestHandler_CrossOrgForeignDenied(t *testing.T) { t.Fatalf("expected 403, got %d: %s", rec.Code, rec.Body.String()) } } + +// --- Repo-level foreign allow-list tests (ADR 0083) --- + +func TestHandler_RepoLevelForeignGrant_CrossOrg(t *testing.T) { + t.Setenv("ALLOWED_ORGS", "test-org,fullsend-ai") + t.Setenv("ROLE_APP_IDS", `{"coder":"400"}`) + + 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": "fullsend-ai/fullsend", + "repository_owner": "fullsend-ai", + "job_workflow_ref": "fullsend-ai/fullsend/.github/workflows/code.yml@refs/heads/main", + }) + + var tokenCalls int + github := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch { + // Repo-level foreign: variable set → authorized. + // Org-level endpoints are NOT called for repo-scoped requests. + case r.URL.Path == "/repos/target-org/target-repo/installation" && r.Method == http.MethodGet: + json.NewEncoder(w).Encode(installationResponse{ + ID: 801, Account: struct { + Login string `json:"login"` + }{Login: "target-org"}, + }) + case r.URL.Path == "/app/installations/801/access_tokens" && r.Method == http.MethodPost: + tokenCalls++ + w.WriteHeader(http.StatusCreated) + if tokenCalls <= 1 { + // Policy token for reading repo variable. + json.NewEncoder(w).Encode(installationTokenResponse{Token: "ghs_repo_policy"}) + } else { + // Mint token for the actual scoped access. + json.NewEncoder(w).Encode(installationTokenResponse{ + Token: "ghs_coder_token", + ExpiresAt: "2026-08-06T12:00:00Z", + Permissions: map[string]string{"contents": "write"}, + RepositorySelection: "selected", + Repositories: []installationTokenRepository{ + {FullName: "target-org/target-repo"}, + }, + }) + } + case r.URL.Path == "/repos/target-org/target-repo/actions/variables/FULLSEND_FOREIGN_CODER_REPOS" && r.Method == http.MethodGet: + json.NewEncoder(w).Encode(variableResponse{ + Name: "FULLSEND_FOREIGN_CODER_REPOS", + Value: "fullsend-ai/fullsend", + }) + default: + t.Errorf("unexpected request: %s %s", r.Method, r.URL.Path) + w.WriteHeader(http.StatusNotFound) + } + })) + defer github.Close() + env.handler.githubBaseURL = github.URL + + body := `{"role":"coder","target_org":"target-org","repos":["target-repo"]}` + 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("expected 200, got %d: %s", rec.Code, rec.Body.String()) + } + var resp mintResponse + json.NewDecoder(rec.Body).Decode(&resp) + if resp.Token != "ghs_coder_token" { + t.Fatalf("expected coder token, got %q", resp.Token) + } +} + +func TestHandler_RepoLevelForeignGrant_Denied(t *testing.T) { + t.Setenv("ALLOWED_ORGS", "test-org,evil-org") + t.Setenv("ROLE_APP_IDS", `{"coder":"400"}`) + + 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": "evil-org/.fullsend", + "repository_owner": "evil-org", + "job_workflow_ref": "evil-org/.fullsend/.github/workflows/code.yml@refs/heads/main", + }) + + github := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch { + // Repo-level foreign: variable authorizes fullsend-ai/fullsend, not evil-org. + // Org-level endpoints are NOT called for repo-scoped requests. + case r.URL.Path == "/repos/target-org/target-repo/installation" && r.Method == http.MethodGet: + json.NewEncoder(w).Encode(installationResponse{ + ID: 801, Account: struct { + Login string `json:"login"` + }{Login: "target-org"}, + }) + case r.URL.Path == "/app/installations/801/access_tokens" && r.Method == http.MethodPost: + w.WriteHeader(http.StatusCreated) + json.NewEncoder(w).Encode(installationTokenResponse{Token: "ghs_repo_policy"}) + case r.URL.Path == "/repos/target-org/target-repo/actions/variables/FULLSEND_FOREIGN_CODER_REPOS" && r.Method == http.MethodGet: + json.NewEncoder(w).Encode(variableResponse{ + Name: "FULLSEND_FOREIGN_CODER_REPOS", + Value: "fullsend-ai/fullsend", + }) + default: + t.Errorf("unexpected request: %s %s", r.Method, r.URL.Path) + w.WriteHeader(http.StatusNotFound) + } + })) + defer github.Close() + env.handler.githubBaseURL = github.URL + + body := `{"role":"coder","target_org":"target-org","repos":["target-repo"]}` + 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()) + } +} + +func TestHandler_RepoLevelForeignGrant_OrgLevelForInstallationWide(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/pool-org/installation" && r.Method == http.MethodGet: + json.NewEncoder(w).Encode(installationResponse{ + ID: 999, Account: struct { + Login string `json:"login"` + }{Login: "pool-org"}, + }) + case r.URL.Path == "/app/installations/999/access_tokens" && r.Method == http.MethodPost: + tokenCalls++ + w.WriteHeader(http.StatusCreated) + if tokenCalls == 1 { + json.NewEncoder(w).Encode(installationTokenResponse{Token: "ghs_policy_token"}) + return + } + json.NewEncoder(w).Encode(installationTokenResponse{ + Token: "ghs_e2e_token", + ExpiresAt: "2026-08-06T12:00:00Z", + Permissions: map[string]string{"contents": "write"}, + RepositorySelection: "all", + }) + case r.URL.Path == "/orgs/pool-org/actions/variables/FULLSEND_FOREIGN_E2E_REPOS" && r.Method == http.MethodGet: + json.NewEncoder(w).Encode(variableResponse{ + 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) + } + })) + defer github.Close() + env.handler.githubBaseURL = github.URL + + 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) + env.handler.ServeHTTP(rec, req) + + if rec.Code != http.StatusOK { + t.Fatalf("expected 200, got %d: %s", rec.Code, rec.Body.String()) + } +} + +func TestHandler_IntraOrgRepoForeignGrant(t *testing.T) { + // Caller is per-repo enrolled only; not in ALLOWED_ORGS. + t.Setenv("ALLOWED_ORGS", "other-org") + t.Setenv("PER_REPO_WIF_REPOS", "test-org/caller-repo") + t.Setenv("ROLE_APP_IDS", `{"coder":"400"}`) + t.Setenv("WORKFLOW_HOST_REPOS", "test-org/caller-repo") + + 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/caller-repo", + "repository_owner": "test-org", + "job_workflow_ref": "test-org/caller-repo/.github/workflows/code.yml@refs/heads/main", + }) + + var tokenCalls int + github := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch { + case r.URL.Path == "/repos/test-org/target-repo/installation" && r.Method == http.MethodGet: + json.NewEncoder(w).Encode(installationResponse{ + ID: 900, Account: struct { + Login string `json:"login"` + }{Login: "test-org"}, + }) + case r.URL.Path == "/app/installations/900/access_tokens" && r.Method == http.MethodPost: + tokenCalls++ + w.WriteHeader(http.StatusCreated) + if tokenCalls == 1 { + json.NewEncoder(w).Encode(installationTokenResponse{Token: "ghs_repo_policy"}) + } else { + json.NewEncoder(w).Encode(installationTokenResponse{ + Token: "ghs_coder_token", + ExpiresAt: "2026-08-06T12:00:00Z", + Permissions: map[string]string{"contents": "write"}, + RepositorySelection: "selected", + Repositories: []installationTokenRepository{ + {FullName: "test-org/target-repo"}, + }, + }) + } + case r.URL.Path == "/repos/test-org/target-repo/actions/variables/FULLSEND_FOREIGN_CODER_REPOS" && r.Method == http.MethodGet: + json.NewEncoder(w).Encode(variableResponse{ + Name: "FULLSEND_FOREIGN_CODER_REPOS", + Value: "test-org/caller-repo", + }) + default: + t.Errorf("unexpected request: %s %s", r.Method, r.URL.Path) + w.WriteHeader(http.StatusNotFound) + } + })) + defer github.Close() + env.handler.githubBaseURL = github.URL + + body := `{"role":"coder","repos":["target-repo"]}` + 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("expected 200, got %d: %s", rec.Code, rec.Body.String()) + } + var resp mintResponse + json.NewDecoder(rec.Body).Decode(&resp) + if resp.Token != "ghs_coder_token" { + t.Fatalf("expected coder token, got %q", resp.Token) + } +} + +func TestHandler_IntraOrgRepoForeignGrant_PartialDenied(t *testing.T) { + // Per-repo caller requests two intra-org repos, but only one has a + // repo-level FOREIGN grant. All-or-nothing semantics should deny. + t.Setenv("ALLOWED_ORGS", "other-org") + t.Setenv("PER_REPO_WIF_REPOS", "test-org/caller-repo") + t.Setenv("ROLE_APP_IDS", `{"coder":"400"}`) + t.Setenv("WORKFLOW_HOST_REPOS", "test-org/caller-repo") + + 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/caller-repo", + "repository_owner": "test-org", + "job_workflow_ref": "test-org/caller-repo/.github/workflows/code.yml@refs/heads/main", + }) + + github := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch { + // authorized-repo: has FOREIGN grant for the caller. + case r.URL.Path == "/repos/test-org/authorized-repo/installation" && r.Method == http.MethodGet: + json.NewEncoder(w).Encode(installationResponse{ + ID: 900, Account: struct { + Login string `json:"login"` + }{Login: "test-org"}, + }) + case r.URL.Path == "/app/installations/900/access_tokens" && r.Method == http.MethodPost: + w.WriteHeader(http.StatusCreated) + json.NewEncoder(w).Encode(installationTokenResponse{Token: "ghs_auth_policy"}) + case r.URL.Path == "/repos/test-org/authorized-repo/actions/variables/FULLSEND_FOREIGN_CODER_REPOS" && r.Method == http.MethodGet: + json.NewEncoder(w).Encode(variableResponse{ + Name: "FULLSEND_FOREIGN_CODER_REPOS", + Value: "test-org/caller-repo", + }) + // unauthorized-repo: no FOREIGN grant. + case r.URL.Path == "/repos/test-org/unauthorized-repo/installation" && r.Method == http.MethodGet: + json.NewEncoder(w).Encode(installationResponse{ + ID: 901, Account: struct { + Login string `json:"login"` + }{Login: "test-org"}, + }) + case r.URL.Path == "/app/installations/901/access_tokens" && r.Method == http.MethodPost: + w.WriteHeader(http.StatusCreated) + json.NewEncoder(w).Encode(installationTokenResponse{Token: "ghs_unauth_policy"}) + case r.URL.Path == "/repos/test-org/unauthorized-repo/actions/variables/FULLSEND_FOREIGN_CODER_REPOS" && r.Method == http.MethodGet: + w.WriteHeader(http.StatusNotFound) + default: + t.Errorf("unexpected request: %s %s", r.Method, r.URL.Path) + w.WriteHeader(http.StatusNotFound) + } + })) + defer github.Close() + env.handler.githubBaseURL = github.URL + + body := `{"role":"coder","repos":["authorized-repo","unauthorized-repo"]}` + 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 partial intra-org grant, got %d: %s", rec.Code, rec.Body.String()) + } +} + +func TestHandler_RepoLevelForeignGrant_ScopeRestriction(t *testing.T) { + t.Setenv("ALLOWED_ORGS", "test-org,fullsend-ai") + t.Setenv("ROLE_APP_IDS", `{"coder":"400"}`) + + 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": "fullsend-ai/fullsend", + "repository_owner": "fullsend-ai", + "job_workflow_ref": "fullsend-ai/fullsend/.github/workflows/code.yml@refs/heads/main", + }) + + github := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch { + // Org-level endpoints are NOT called for repo-scoped requests. + case r.URL.Path == "/repos/target-org/other-repo/installation" && r.Method == http.MethodGet: + json.NewEncoder(w).Encode(installationResponse{ + ID: 802, Account: struct { + Login string `json:"login"` + }{Login: "target-org"}, + }) + case r.URL.Path == "/app/installations/802/access_tokens" && r.Method == http.MethodPost: + w.WriteHeader(http.StatusCreated) + json.NewEncoder(w).Encode(installationTokenResponse{Token: "ghs_other_policy"}) + case r.URL.Path == "/repos/target-org/other-repo/actions/variables/FULLSEND_FOREIGN_CODER_REPOS" && r.Method == http.MethodGet: + w.WriteHeader(http.StatusNotFound) + default: + t.Errorf("unexpected request: %s %s", r.Method, r.URL.Path) + w.WriteHeader(http.StatusNotFound) + } + })) + defer github.Close() + env.handler.githubBaseURL = github.URL + + body := `{"role":"coder","target_org":"target-org","repos":["other-repo"]}` + 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()) + } +} + +// TestHandler_OrgLevelForeignDoesNotAuthorizeRepoScoped verifies the disjoint +// authorization boundary from ADR 0083: an org-level FOREIGN grant does NOT +// authorize cross-org requests with specific repos when no repo-level grant +// exists on the target repo. +func TestHandler_OrgLevelForeignDoesNotAuthorizeRepoScoped(t *testing.T) { + t.Setenv("ALLOWED_ORGS", "test-org,fullsend-ai") + t.Setenv("ROLE_APP_IDS", `{"coder":"400"}`) + + 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": "fullsend-ai/fullsend", + "repository_owner": "fullsend-ai", + "job_workflow_ref": "fullsend-ai/fullsend/.github/workflows/code.yml@refs/heads/main", + }) + + github := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch { + // Repo-level lookup for target-repo: no FOREIGN variable set. + case r.URL.Path == "/repos/target-org/target-repo/installation" && r.Method == http.MethodGet: + json.NewEncoder(w).Encode(installationResponse{ + ID: 801, Account: struct { + Login string `json:"login"` + }{Login: "target-org"}, + }) + case r.URL.Path == "/app/installations/801/access_tokens" && r.Method == http.MethodPost: + w.WriteHeader(http.StatusCreated) + json.NewEncoder(w).Encode(installationTokenResponse{Token: "ghs_repo_policy"}) + case r.URL.Path == "/repos/target-org/target-repo/actions/variables/FULLSEND_FOREIGN_CODER_REPOS" && r.Method == http.MethodGet: + // No repo-level variable — 404. + w.WriteHeader(http.StatusNotFound) + // Org-level endpoints should NOT be called for repo-scoped requests. + case r.URL.Path == "/orgs/target-org/installation": + t.Errorf("org-level installation lookup should not be called for repo-scoped request") + w.WriteHeader(http.StatusNotFound) + case strings.HasPrefix(r.URL.Path, "/orgs/target-org/actions/variables/"): + t.Errorf("org-level variable lookup should not be called for repo-scoped request") + w.WriteHeader(http.StatusNotFound) + default: + t.Errorf("unexpected request: %s %s", r.Method, r.URL.Path) + w.WriteHeader(http.StatusNotFound) + } + })) + defer github.Close() + env.handler.githubBaseURL = github.URL + + body := `{"role":"coder","target_org":"target-org","repos":["target-repo"]}` + 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 (org-level FOREIGN should not authorize repo-scoped request), got %d: %s", rec.Code, rec.Body.String()) + } +} diff --git a/internal/mintcore/repos_scope.go b/internal/mintcore/repos_scope.go index a3218174f8..73815bc557 100644 --- a/internal/mintcore/repos_scope.go +++ b/internal/mintcore/repos_scope.go @@ -1,14 +1,26 @@ package mintcore import ( + "errors" "fmt" "strings" ) -// Org-mode shape labels returned by validateReposScope when a per-org caller -// uses a broader-than-self same-org repos list. Empty means the default path -// (foreign empty repos, or same-org requesting-repo-only). +// errPerRepoCrossRepo is a sentinel returned when a per-repo caller +// requests repos beyond its own repository. The handler checks this +// sentinel to decide whether to try repo-level FOREIGN grants. +var errPerRepoCrossRepo = errors.New("per-repo mint requires repos to be exactly the requesting repository") + +// Shape labels returned by validateReposScope. A non-empty shape signals that +// the caller must take path-specific action (see each constant's doc). const ( + // reposScopeShapeForeignRepoScoped is returned for foreign (cross-org) + // requests with non-empty repos. The caller MUST perform repo-level + // FOREIGN grant authorization (via mintTokenCrossOrg) before minting. + // Treating this shape as "fully authorized" without the follow-up check + // would bypass authorization entirely. + reposScopeShapeForeignRepoScoped = "foreign-repo-scoped" + reposScopeShapeFullsendAny = "fullsend-any" reposScopeShapeEnrolledFullsend = "enrolled-fullsend" reposScopeShapeEnrolledPair = "enrolled-pair" @@ -42,7 +54,14 @@ func repositoryBareName(repository string) string { // validateReposScope enforces mint repos authorization after OIDC verification. // -// Foreign (cross-org) requests may only omit repos (or use "*" → empty). +// For foreign (cross-org) requests with non-empty repos, this function returns +// reposScopeShapeForeignRepoScoped to signal that repo-level FOREIGN grant +// authorization is required. Callers MUST check for this shape and invoke +// mintTokenCrossOrg — treating a nil error alone as "fully authorized" would +// bypass repo-level authorization entirely. Foreign requests with empty repos +// (installation-wide) return an empty shape; org-level FOREIGN authorization +// is handled by mintTokenCrossOrg's own empty-repos path. +// // Same-org requests differ based on whether the caller is per-repo or per-org: // // - Per-repo callers (perRepo=true): must list exactly the requesting @@ -52,12 +71,18 @@ func repositoryBareName(repository string) string { // other callers: exactly [.fullsend] or {requestingBare, .fullsend}. // Same-org installation-wide (empty repos) is always denied. // -// On success, shape is non-empty only when an org-mode exception matched. +// On success, a non-empty shape signals a path-specific authorization +// requirement (foreign-repo-scoped or org-mode exception). func validateReposScope(isTargetForeign bool, requestingRepo string, repos []string, perRepo bool) (shape string, err error) { if isTargetForeign { - if len(repos) != 0 { - return "", fmt.Errorf("foreign mint requires empty repos") + if len(repos) > 0 { + // Non-empty repos → repo-scoped. Return the sentinel shape + // so the caller knows repo-level FOREIGN grant authorization + // is required (performed in mintTokenCrossOrg). + return reposScopeShapeForeignRepoScoped, nil } + // Empty repos → installation-wide (org-level FOREIGN grant + // checked in mintTokenCrossOrg). return "", nil } @@ -71,7 +96,7 @@ func validateReposScope(isTargetForeign bool, requestingRepo string, repos []str } if perRepo { - return "", fmt.Errorf("per-repo mint requires repos to be exactly the requesting repository") + return "", errPerRepoCrossRepo } // Per-org callers get org-mode shapes. diff --git a/internal/mintcore/repos_scope_test.go b/internal/mintcore/repos_scope_test.go index bb2b80b1bc..d631692f9a 100644 --- a/internal/mintcore/repos_scope_test.go +++ b/internal/mintcore/repos_scope_test.go @@ -1,6 +1,7 @@ package mintcore import ( + "errors" "strings" "testing" ) @@ -53,8 +54,6 @@ func TestValidateReposScope(t *testing.T) { const emptyDeny = "same-org mint requires non-empty repos" const perRepoDeny = "per-repo mint requires repos to be exactly the requesting repository" const perOrgDeny = "repos scope not allowed for per-org caller" - const foreignDeny = "foreign mint requires empty repos" - tests := []struct { name string foreign bool @@ -65,7 +64,8 @@ func TestValidateReposScope(t *testing.T) { wantShape string }{ {"foreign empty", true, "fullsend-ai/fullsend", nil, false, "", ""}, - {"foreign non-empty", true, "fullsend-ai/fullsend", []string{"e2e-lock"}, false, foreignDeny, ""}, + {"foreign non-empty allowed", true, "fullsend-ai/fullsend", []string{"e2e-lock"}, false, "", reposScopeShapeForeignRepoScoped}, + {"foreign non-empty multi", true, "fullsend-ai/fullsend", []string{"a", "b"}, true, "", reposScopeShapeForeignRepoScoped}, {"same self", false, "acme/api", []string{"api"}, false, "", ""}, {"same empty per-org", false, "acme/api", nil, false, emptyDeny, ""}, {"same empty per-repo", false, "acme/api", nil, true, emptyDeny, ""}, @@ -106,3 +106,14 @@ func TestValidateReposScope(t *testing.T) { }) } } + +func TestValidateReposScope_PerRepoSentinel(t *testing.T) { + t.Parallel() + _, err := validateReposScope(false, "acme/api", []string{"other"}, true) + if err == nil { + t.Fatal("expected error") + } + if !errors.Is(err, errPerRepoCrossRepo) { + t.Fatalf("expected errPerRepoCrossRepo sentinel, got %v", err) + } +}