Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -83,3 +83,10 @@ orgs control over their own policy.
- Same-org mint for enrolled orgs adds zero FOREIGN API calls; optional `repos` omission uses
org-level installation lookup when callers need installation-wide scope.
- Pool org provisioning must install the e2e App and set `FULLSEND_FOREIGN_E2E_REPOS` for CI callers.

## Later note (repos scope hardening)

Same-org installation-wide tokens and unrestricted `repos` lists are no longer the default.
`repos` authorization is decided in
Comment thread
ifireball marked this conversation as resolved.
Resolved
[ADR 0077](0077-mint-repos-scope-hardening.md). FOREIGN allowlists and `target_org`
from this ADR are unchanged.
54 changes: 54 additions & 0 deletions docs/ADRs/0077-mint-repos-scope-hardening.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
---
title: "77. Mint repos scope hardening with PER_ORG_FOREIGN_COMPAT"
status: Accepted
relates_to:
- agent-infrastructure
- security-threat-model
topics:
- mint
- identity
- oidc
- least-privilege
- cross-org
---

# 77. Mint repos scope hardening with PER_ORG_FOREIGN_COMPAT

Date: 2026-08-02

## Status

Accepted

## Context

[ADR 0060](0060-cross-org-mint-authorization-via-org-variables.md) authorized cross-org minting via FOREIGN org variables and treated empty `repos` as installation-wide on both same-org and foreign paths. Same-org callers could also request arbitrary repo lists. That blast radius conflicts with least privilege in the [security threat model](../problems/security-threat-model.md): a compromised enrolled workflow could mint tokens for repos other than the one that authenticated.

Org-mode dispatch still needs limited exceptions — `.fullsend` callers minting across enrolled repos, and enrolled callers minting `{self,.fullsend}` — without restoring unrestricted same-org scope.

## Options

1. **Keep ADR 0060 defaults.** No code change; rely on WIF enrollment alone. Rejected: enrollment does not bound `repos` to the authenticating repository.
2. **Strict requesting-repo only, no exceptions.** Simplest rule. Rejected: breaks established `.fullsend` / org-mode dispatch shapes.
3. **Default-deny with an explicit compat flag.** Deny installation-wide and broad same-org lists by default; gate the known org-mode shapes behind `PER_ORG_FOREIGN_COMPAT`.

## Decision

After OIDC verification, the mint enforces `repos` scope as follows:

1. **Normalize** a sole `["*"]` entry to empty (alias for empty `repos` only). Mixed `*` lists remain invalid pattern input.
2. **Foreign (cross-org)** requests require empty `repos`. Non-empty lists are denied. FOREIGN gating from ADR 0060 still applies.
3. **Same-org** requests must list exactly the requesting repository's bare name. Empty `repos` (installation-wide) is always denied on the same-org path.
4. **`PER_ORG_FOREIGN_COMPAT`** (env / worker config; truthy = `1`/`true`/`yes`) unlocks only these same-org exceptions:
- Caller repository `.fullsend`: any non-empty validated repo list
- Other enrolled callers: exactly `[.fullsend]` or `{requestingBare, .fullsend}`
5. The effective flag is visible on `GET /v1/status` as `per_org_foreign_compat` and in `fullsend mint status` (from traffic env; absent = off).

This revises the installation-wide and unrestricted same-org `repos` consequences of ADR 0060; FOREIGN allowlists and `target_org` remain as decided there.

## Consequences

- Same-org workflows that omitted `repos` or listed unrelated repos break until they request only the calling repo, or operators enable `PER_ORG_FOREIGN_COMPAT` for the documented org-mode shapes.
- Foreign mints cannot carry a non-empty `repos` list; installation-wide foreign tokens remain possible only with empty `repos` plus FOREIGN authorization.
- Hosted and standalone mints must set `PER_ORG_FOREIGN_COMPAT` explicitly where org-mode dispatch is required; the default is off.
- ADR 0060's earlier allowance of same-org installation-wide tokens is superseded for `repos` policy by this decision (FOREIGN mechanism unchanged).
3 changes: 2 additions & 1 deletion docs/architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -178,7 +178,8 @@ Identity is not the same as trust. An agent's identity lets it authenticate to e
- Credential delivery model: four tiers — (1) prefetch + post-process for agents with enumerable inputs (zero credential access), (2) OpenShell providers + L7 egress policies for static token auth (credentials never enter sandbox), (3) host-side REST server for operations providers cannot handle — long-running operations, sandbox capability gaps, credentials in request bodies, response transformation, and multi-step atomic operations (see [ADR 0046](ADRs/0046-host-side-api-server-design.md)), (4) host files + L7 policies for complex auth requiring in-sandbox credential files. L7 policies enforce both method + path and binary-level restrictions. Providers are preferred over REST servers when viable ([ADR 0017](ADRs/0017-credential-isolation-for-sandboxed-agents.md), extended by [ADR 0025](ADRs/0025-provider-credential-delivery-for-sandboxed-agents.md)).
- Host-side API server design: Credential delivery tier 3 servers follow a uniform process contract (`--port`, `--token`, `--bind-address`, `/healthz`, `/tools.json`, `SIGTERM`). Network access is controlled via composable provider profiles — atomic capability profiles composed per-harness. Per-run UUID bearer tokens are delivered through OpenShell provider placeholders. File transfer uses `openshell sandbox upload/download` ([ADR 0046](ADRs/0046-host-side-api-server-design.md)).
- Per-role GitHub Apps with manifest-based creation. Each agent role gets its own app with scoped permissions. PEMs stored in Secret Manager as `fullsend-{role}-app-pem` — one secret per role, shared across orgs on a mint. `ROLE_APP_IDS` uses the same shared-per-role model (`coder` → app ID). Org isolation is enforced via `ALLOWED_ORGS`, WIF conditions, and installation verification ([ADR 0007](ADRs/0007-per-role-github-apps.md), [ADR 0033](ADRs/0033-per-repo-installation-mode.md)). Public multi-tenant mint (`ALLOWED_ORGS=*`) with upstream-only workflow provenance is defined in [ADR 0059](ADRs/0059-public-mint-mode-with-wildcard-allowlists.md); upstream-only provenance limits which workflows can call the mint, complementing [ADR 0029](ADRs/0029-central-token-mint-secretless-fullsend.md) multi-tenant blast-radius concerns.
- Cross-org mint authorization: workflows may request tokens for a different org via optional `target_org` when the target org installs the role App and sets `FULLSEND_FOREIGN_<role>_REPOS`. Empty `repos` yields installation-wide tokens on either path; cross-org adds FOREIGN gating, same-org relies on WIF/OIDC enrollment ([ADR 0060](ADRs/0060-cross-org-mint-authorization-via-org-variables.md)).
- Cross-org mint authorization: workflows may request tokens for a different org via optional `target_org` when the target org installs the role App and sets `FULLSEND_FOREIGN_<role>_REPOS` ([ADR 0060](ADRs/0060-cross-org-mint-authorization-via-org-variables.md)).
- Mint `repos` scope: foreign mints require empty `repos` (or `["*"]` as an empty alias). Same-org mints must list exactly the requesting repository by default; `PER_ORG_FOREIGN_COMPAT` unlocks org-mode shapes (broad non-empty lists from `.fullsend`, or `[.fullsend]` / `{self,.fullsend}` from enrolled callers). Same-org installation-wide tokens are denied ([ADR 0077](ADRs/0077-mint-repos-scope-hardening.md)).
- Standalone mint deployment: `cmd/mint/` provides a self-contained HTTP server that uses direct JWKS verification and filesystem PEM storage instead of GCP infrastructure. It shares the `internal/mintcore/` library with the GCF mint and adds support for custom role permissions and a fallback proxy to an upstream mint. Custom role permissions live in mintcore (not `cmd/mint/`) so that `RolePermissionsFor`, `HasRole`, and `CreateInstallationToken` return a unified view without callers needing to distinguish built-in from custom roles. The GCF mint never calls `RegisterCustomRolePermissions`, so the code is inert there. See the [standalone mint guide](guides/infrastructure/standalone-mint.md).
- Hosted public community mint: steady-state deployment on Cloudflare Workers (JWKS + WAF + single ops console), with interim GCP Cloud Function acceptable until the Worker port is production-ready. Trust policy (`ALLOWED_ORGS=*`, upstream-only workflow provenance) is in [ADR 0059](ADRs/0059-public-mint-mode-with-wildcard-allowlists.md); deployment, edge security, monitoring, and phasing are in [ADR 0068](ADRs/0068-public-community-mint-architecture.md). Enrollment is installing the shared Apps—no per-org mint env registration ([#1145](https://github.com/fullsend-ai/fullsend/issues/1145)).
- Named privilege levels: each role defines ordered named levels (`read`, `write`), where each level's permissions are a superset of preceding levels. `read` for built-in roles is derived by downgrading `*:write` permissions to their `read` counterparts. The mint API accepts an optional `level` field (default `read`); omitting it produces narrower tokens than the current behavior. `write` is defined as the current max permission set for each built-in role. `CUSTOM_ROLE_PERMISSIONS` auto-detects a multi-level JSON shape alongside the existing flat format, with mixed format supported per role. The harness `privilege_levels` flag maps run-stages to levels; omitting it defaults to `write`, preserving backward compatibility for existing harness configurations ([ADR 0073](ADRs/0073-named-mint-privilege-levels.md)).
Expand Down
3 changes: 2 additions & 1 deletion docs/guides/infrastructure/infrastructure-reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -132,8 +132,9 @@ A single mint instance can serve multiple orgs:
- **Authorization:** Any valid OIDC token from an allowed org — no role restriction
- **Response:**
```json
{"org": "my-org", "roles": ["coder", "review", "triage"]}
{"org": "my-org", "roles": ["coder", "review", "triage"], "per_org_foreign_compat": false}
```
`per_org_foreign_compat` is always present (bool; `false` when `PER_ORG_FOREIGN_COMPAT` is unset).
- **Use case:** Workflow diagnostics — discover which roles are available before requesting a token
- **Security:** Returns only the requesting org and its role names (not app IDs, not other orgs' roles)

Expand Down
3 changes: 2 additions & 1 deletion docs/guides/infrastructure/standalone-mint.md
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,7 @@ The standalone mint is configured entirely through environment variables:
| `FALLBACK_MINT_URL` | Upstream mint URL for roles without local PEMs | `https://fullsend-mint-gljhbkcloq-uc.a.run.app` |
| `CUSTOM_ROLE_PERMISSIONS` | JSON map of custom role permissions (see below) | `{"scanner":{"contents":"read"}}` |
| `PER_REPO_WIF_REPOS` | Comma-separated repos requiring per-repo WIF | `myorg/private-repo` |
| `PER_ORG_FOREIGN_COMPAT` | When `1`/`true`/`yes`, allow org-mode `repos` shapes: any non-empty list from `.fullsend` callers; `[.fullsend]` or `{self,.fullsend}` from enrolled callers. Default off (same-org = requesting repo only). Does not allow same-org installation-wide tokens. | `true` |
| `PORT` | HTTP listen port | `8080` (default) |

### Public mint mode
Expand Down Expand Up @@ -261,7 +262,7 @@ When `FALLBACK_MINT_URL` is set, the standalone mint acts as a transparent proxy
| `POST /v1/token` with a role in `ROLE_APP_IDS` | Handled locally |
| `POST /v1/token` with an unknown role | Forwarded to `FALLBACK_MINT_URL` |
| `GET /health` | Always handled locally |
| `GET /v1/status` | Always handled locally |
| `GET /v1/status` | Always handled locally (`per_org_foreign_compat` bool; default `false` when unset) |

The proxy forwards the original OIDC bearer token and request body to the upstream mint, and returns the upstream response verbatim. The upstream mint performs its own OIDC validation — your organization must be enrolled on the upstream mint for proxied requests to succeed.

Expand Down
43 changes: 43 additions & 0 deletions internal/cli/deploy_identity.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
package cli
Comment thread
ifireball marked this conversation as resolved.
Resolved

import (
"bytes"
"os"
"os/exec"
"strings"
)

// resolveMintDeployCommit returns the commit to stamp into a mint deploy.
// When commit is already set to something other than "dev"/empty, it is
// returned unchanged. When deploying from on-disk source (sourceDir exists)
// and commit is unset, it tries git -C sourceDir rev-parse HEAD. Embedded
// deploys (missing sourceDir) never invoke git.
func resolveMintDeployCommit(commit, sourceDir string) string {
Comment thread
qodo-code-review[bot] marked this conversation as resolved.
Resolved
if commit != "" && commit != "dev" {
return commit
}
if sourceDir == "" {
return commit
}
info, err := os.Stat(sourceDir)
if err != nil || !info.IsDir() {
return commit
}
sha, err := gitRevParse(sourceDir, "HEAD")
if err != nil || sha == "" {
return commit
Comment thread
qodo-code-review[bot] marked this conversation as resolved.
Resolved
}
return sha
}

func gitRevParse(dir string, args ...string) (string, error) {
cmdArgs := append([]string{"-C", dir, "rev-parse"}, args...)
cmd := exec.Command("git", cmdArgs...)
var stdout, stderr bytes.Buffer
cmd.Stdout = &stdout
cmd.Stderr = &stderr
if err := cmd.Run(); err != nil {
return "", err
}
return strings.TrimSpace(stdout.String()), nil
}
87 changes: 87 additions & 0 deletions internal/cli/deploy_identity_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
package cli

import (
"os"
"os/exec"
"path/filepath"
"regexp"
"strings"
"testing"
)

func TestResolveMintDeployCommit_PreservesNonDev(t *testing.T) {
t.Parallel()
got := resolveMintDeployCommit("abc123def", "/nonexistent")
if got != "abc123def" {
t.Fatalf("got %q, want preserved commit", got)
}
}

func TestResolveMintDeployCommit_MissingSourceDir(t *testing.T) {
t.Parallel()
dir := filepath.Join(t.TempDir(), "no-such-dir")
got := resolveMintDeployCommit("dev", dir)
if got != "dev" {
t.Fatalf("got %q, want dev when source missing", got)
}
got = resolveMintDeployCommit("", "")
if got != "" {
t.Fatalf("got %q, want empty when sourceDir empty", got)
}
}

func TestResolveMintDeployCommit_NotAGitRepo(t *testing.T) {
t.Parallel()
dir := t.TempDir()
got := resolveMintDeployCommit("dev", dir)
if got != "dev" {
t.Fatalf("got %q, want dev when not a git work tree", got)
}
}

func TestResolveMintDeployCommit_FromCheckout(t *testing.T) {
t.Parallel()
dir := t.TempDir()
runGit := func(args ...string) {
t.Helper()
cmd := exec.Command("git", append([]string{"-C", dir}, args...)...)
cmd.Env = append(os.Environ(),
"GIT_CONFIG_COUNT=1",
"GIT_CONFIG_KEY_0=commit.gpgsign",
"GIT_CONFIG_VALUE_0=false",
)
out, err := cmd.CombinedOutput()
if err != nil {
t.Fatalf("git %v: %v\n%s", args, err, out)
}
}
runGit("init")
runGit("config", "user.email", "test@example.com")
runGit("config", "user.name", "Test")
if err := os.WriteFile(filepath.Join(dir, "README"), []byte("x\n"), 0o644); err != nil {
t.Fatal(err)
}
runGit("add", "README")
runGit("commit", "-m", "init")

wantCmd := exec.Command("git", "-C", dir, "rev-parse", "HEAD")
wantOut, err := wantCmd.Output()
if err != nil {
t.Fatal(err)
}
want := strings.TrimSpace(string(wantOut))

got := resolveMintDeployCommit("dev", dir)
if got != want {
t.Fatalf("got %q, want %q", got, want)
}
if !regexp.MustCompile(`^[0-9a-f]{40}$`).MatchString(got) {
t.Fatalf("expected full SHA, got %q", got)
}

// Empty commit also resolves.
got = resolveMintDeployCommit("", dir)
if got != want {
t.Fatalf("empty commit: got %q, want %q", got, want)
}
}
34 changes: 32 additions & 2 deletions internal/cli/mint.go
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,20 @@ func isPublicMintAllowedOrgs(allowedOrgs string) bool {
return mintcore.IsPublicMint(parseAllowedOrgs(allowedOrgs))
}

// perOrgForeignCompatLabel returns "on" or "off" for display from traffic env.
Comment thread
ifireball marked this conversation as resolved.
Resolved
// Missing/empty/nil trafficEnv is treated as off (compatible with older mints).
func perOrgForeignCompatLabel(trafficEnv map[string]string) string {
if trafficEnv == nil {
return "off"
}
switch strings.ToLower(strings.TrimSpace(trafficEnv["PER_ORG_FOREIGN_COMPAT"])) {
case "1", "true", "yes":
return "on"
default:
return "off"
}
}

// mintValidationMessage returns the success message after validating an existing mint.
func mintValidationMessage(trafficEnv map[string]string, envErr error) string {
if envErr == nil && isPublicMintAllowedOrgs(trafficEnv["ALLOWED_ORGS"]) {
Expand Down Expand Up @@ -520,6 +534,11 @@ func runMintDeployGCP(ctx context.Context, project, region, sourceDir string, sk
sourceDir = gcf.DefaultFunctionSourceDir()
}

deployCommit := resolveMintDeployCommit(commitSHA, sourceDir)
if deployCommit != commitSHA && deployCommit != "" && deployCommit != "dev" {
printer.StepInfo(fmt.Sprintf("Resolved mint commit from checkout: %s", deployCommit))
}

deployMode := gcf.DeployAuto
if skipDeploy {
deployMode = gcf.DeploySkip
Expand All @@ -531,7 +550,7 @@ func runMintDeployGCP(ctx context.Context, project, region, sourceDir string, sk
FunctionSourceDir: sourceDir,
DeployMode: deployMode,
Version: version,
Commit: commitSHA,
Commit: deployCommit,
PublicMint: public,
}

Expand Down Expand Up @@ -570,6 +589,8 @@ func runMintDeployGCP(ctx context.Context, project, region, sourceDir string, sk
fmt.Sprintf("Project: %s", project),
fmt.Sprintf("Region: %s", region),
fmt.Sprintf("URL: %s", mintURL),
fmt.Sprintf("Version: %s", version),
fmt.Sprintf("Commit: %s", deployCommit),
}
if pemDir != "" {
summaryLines = append(summaryLines, fmt.Sprintf("App set: %s (PEMs bootstrapped)", appsetup.DefaultAppSet))
Expand Down Expand Up @@ -634,13 +655,18 @@ func runMintDeployCloudflare(ctx context.Context, workerName, sourceDir string,
sourceDir = cf.DefaultWorkerSourceDir()
}

deployCommit := resolveMintDeployCommit(commitSHA, sourceDir)
if deployCommit != commitSHA && deployCommit != "" && deployCommit != "dev" {
printer.StepInfo(fmt.Sprintf("Resolved mint commit from checkout: %s", deployCommit))
}

cfg := cf.Config{
AccountID: accountID,
WorkerName: workerName,
DeployMode: deployMode,
SourceDir: sourceDir,
Version: version,
Commit: commitSHA,
Commit: deployCommit,
}

wrangler := mintCFWranglerFactory(accountID)
Expand Down Expand Up @@ -669,6 +695,8 @@ func runMintDeployCloudflare(ctx context.Context, workerName, sourceDir string,
fmt.Sprintf("Worker: %s", effectiveName),
fmt.Sprintf("URL: %s", mintURL),
fmt.Sprintf("Mode: %s", modeLabel),
fmt.Sprintf("Version: %s", version),
fmt.Sprintf("Commit: %s", deployCommit),
}
if preview {
summaryLines = append(summaryLines, "Teardown: fullsend mint deploy --platform=cloudflare --worker-name="+effectiveName+" --preview (then delete)")
Expand Down Expand Up @@ -1490,6 +1518,8 @@ func runMintStatus(ctx context.Context, printer *ui.Printer, project, region, or
}
roleOnlyIDs := mintcore.RoleOnlyAppIDs(roleAppIDs)

printer.KeyValue("Per-org foreign compat", perOrgForeignCompatLabel(trafficEnv))

publicMint := trafficEnv != nil && isPublicMintAllowedOrgs(trafficEnv["ALLOWED_ORGS"])
if publicMint {
printer.Blank()
Expand Down
Loading
Loading