diff --git a/changelog.d/fixed-14778-shared-uid-reads.md b/changelog.d/fixed-14778-shared-uid-reads.md new file mode 100644 index 0000000000..1819e9082e --- /dev/null +++ b/changelog.d/fixed-14778-shared-uid-reads.md @@ -0,0 +1 @@ +- Add opt-in `github.shared_uid_read_token` for App-authenticated shared-UID deployments, delivering refreshed read-only agent tokens so GitHub reads work without a personal login while writes continue through relays ([#14778](https://github.com/hivecommons/hive/issues/14778)). diff --git a/src/cmd/crux/definitions.go b/src/cmd/crux/definitions.go index ea6c565222..c77a7270c3 100644 --- a/src/cmd/crux/definitions.go +++ b/src/cmd/crux/definitions.go @@ -125,18 +125,19 @@ func projectContextFromConfig(cfg *config.Config) crux.ProjectContext { return crux.ProjectContext{} } pc := crux.ProjectContext{ - Org: cfg.Project.Org, - Repos: cfg.Project.Repos, - RepoPaused: cfg.IsRepoPaused, - AgentRepos: cfg.ReposForAgent, - AgentPrimaryRepo: cfg.PrimaryRepoForAgent, - PrimaryRepoName: cfg.Project.PrimaryRepo, - ACMMLevel: cfg.ACMMLevelOrZero(), - PRsAllowed: cfg.Project.PRsAllowed(), - PolicyDir: policyDir(cfg.Policies), - AppAuthoredPRs: cfg.GitHub.AppAuthoredPRsEnabled(), - AppBotLogin: cfg.GitHub.BotLogin(), - BobSessionPrefix: cfg.Governor.Bob.SessionPrefix, + Org: cfg.Project.Org, + Repos: cfg.Project.Repos, + RepoPaused: cfg.IsRepoPaused, + AgentRepos: cfg.ReposForAgent, + AgentPrimaryRepo: cfg.PrimaryRepoForAgent, + PrimaryRepoName: cfg.Project.PrimaryRepo, + ACMMLevel: cfg.ACMMLevelOrZero(), + PRsAllowed: cfg.Project.PRsAllowed(), + PolicyDir: policyDir(cfg.Policies), + SharedUIDReadToken: cfg.GitHub.SharedUIDReadToken, + AppAuthoredPRs: cfg.GitHub.AppAuthoredPRsEnabled(), + AppBotLogin: cfg.GitHub.BotLogin(), + BobSessionPrefix: cfg.Governor.Bob.SessionPrefix, } if cfg.GitHub.IsGHE() { pc.GHHost = cfg.GitHub.HostLabel() diff --git a/src/cmd/hive/main.go b/src/cmd/hive/main.go index 96fcfec70f..5d8c8737ea 100644 --- a/src/cmd/hive/main.go +++ b/src/cmd/hive/main.go @@ -2121,18 +2121,19 @@ func (b *boot) bootAdvisoryWith(deps bootAdvisoryDeps) bool { // and AgentPrimaryRepo to the ones a given agent serves (#6204) — so a // pause taken or a scope edited mid-run reaches the next agent launch // without rebuilding this context. - Repos: b.cfg.Project.Repos, - RepoPaused: b.cfg.IsRepoPaused, - AgentRepos: b.cfg.ReposForAgent, - AgentPrimaryRepo: b.cfg.PrimaryRepoForAgent, - PrimaryRepoName: b.cfg.Project.PrimaryRepo, - ACMMLevel: b.acmmLevel, - PRsAllowed: b.cfg.Project.PRsAllowed(), - PolicyDir: b.policyDirPath, - AppAuthoredPRs: b.cfg.GitHub.AppAuthoredPRsEnabled(), - AppBotLogin: b.cfg.GitHub.BotLogin(), - AppBotUserID: b.appBotUserIDResolver(), - BobSessionPrefix: b.cfg.Governor.Bob.SessionPrefix, + Repos: b.cfg.Project.Repos, + RepoPaused: b.cfg.IsRepoPaused, + AgentRepos: b.cfg.ReposForAgent, + AgentPrimaryRepo: b.cfg.PrimaryRepoForAgent, + PrimaryRepoName: b.cfg.Project.PrimaryRepo, + ACMMLevel: b.acmmLevel, + PRsAllowed: b.cfg.Project.PRsAllowed(), + PolicyDir: b.policyDirPath, + SharedUIDReadToken: b.cfg.GitHub.SharedUIDReadToken, + AppAuthoredPRs: b.cfg.GitHub.AppAuthoredPRsEnabled(), + AppBotLogin: b.cfg.GitHub.BotLogin(), + AppBotUserID: b.appBotUserIDResolver(), + BobSessionPrefix: b.cfg.Governor.Bob.SessionPrefix, } return true } diff --git a/src/crux/agent/manager.go b/src/crux/agent/manager.go index 4ef743a05f..22d63ae6e4 100644 --- a/src/crux/agent/manager.go +++ b/src/crux/agent/manager.go @@ -860,7 +860,9 @@ func NewManagerWithOptions(agents map[string]config.AgentConfig, logger *slog.Lo } } if uidMap == nil { - logger.Info("no UID map found, agents will share dev UID", "path", loadUIDMapPath) + logger.Info("no UID map found, agents will share dev UID", "path", loadUIDMapPath, + "shared_uid_read_token", project.SharedUIDReadToken, + "cross_agent_read_isolation", false) } kickLogDir, kickLogRetention, kickLogMaxBytes := kickLogSettingsFromEnv() diff --git a/src/crux/agent/manager_env.go b/src/crux/agent/manager_env.go index 92d9c1611b..b1c769e7dc 100644 --- a/src/crux/agent/manager_env.go +++ b/src/crux/agent/manager_env.go @@ -442,7 +442,7 @@ func (m *Manager) agentEnvPairs(agent *AgentProcess) []agentEnvPair { vars = append(vars, agentEnvPair{config.ExplainModeEnvVar, resolveExplainMode(agent.Config, m.explainModeDefault()), false}) // GIT_SSL_CAINFO only — NOT SSL_CERT_FILE (that breaks Copilot API TLS) vars = append(vars, agentEnvPair{"GIT_SSL_CAINFO", proxyCACertPath, false}) - if agent.UID > 0 { + if m.agentTokenCacheEnabled(agent) { vars = append(vars, agentEnvPair{"HIVE_AGENT_TOKEN_CACHE", crux.AgentTokenCachePath(crux.DefaultAgentTokenCacheDir, agent.Name), false}) } if agent.UID > 0 { diff --git a/src/crux/agent/manager_tokens.go b/src/crux/agent/manager_tokens.go index 7a039f39b5..0ec176e93c 100644 --- a/src/crux/agent/manager_tokens.go +++ b/src/crux/agent/manager_tokens.go @@ -805,8 +805,8 @@ func (m *Manager) RefreshAgentTokens(ctx context.Context) { // attempt a token re-cache before pausing: the likeliest cause of a `gh` // "gh auth login" prompt on an App-authenticated hive is an expired cached // token, so refreshing it means a subsequent Resume works immediately. -// Returns an error when the agent is unknown, has no UID, or no App auth is -// wired. +// Returns an error when the agent is unknown, lacks an enabled cache path, +// or no App auth is wired. func (m *Manager) RefreshAgentTokenFor(ctx context.Context, name string) error { m.mu.RLock() auth := m.appAuth @@ -819,10 +819,10 @@ func (m *Manager) RefreshAgentTokenFor(ctx context.Context, name string) error { if !ok { return fmt.Errorf("agent %s not found", name) } - if agent.UID <= 0 { + if !m.agentTokenCacheEnabled(agent) { return fmt.Errorf("agent %s has no dedicated UID", name) } - tier := TokenTierForRole(m.agentMode(agent), agent.Config.Role) + tier := m.agentTokenTier(agent) if err := auth.WriteAgentToken(ctx, agent.Name, tier, agent.UID); err != nil { return fmt.Errorf("re-caching scoped token for %s: %w", name, err) } @@ -834,7 +834,7 @@ func (m *Manager) refreshAgentTokens(ctx context.Context) { auth := m.appAuth agents := make([]*AgentProcess, 0, len(m.agents)) for _, a := range m.agents { - if a.State == StateRunning && a.UID > 0 { + if a.State == StateRunning && m.agentTokenCacheEnabled(a) { agents = append(agents, a) } } @@ -851,7 +851,7 @@ func (m *Manager) refreshAgentTokens(ctx context.Context) { // GitHub App auth: a Linear-sourced hive with no App still needs this, // hence it runs before the auth == nil return below. for _, a := range agents { - if a.tmuxSession == "" { + if a.UID <= 0 || a.tmuxSession == "" { continue } for _, args := range m.linearRefreshTmuxArgs(a) { @@ -864,13 +864,21 @@ func (m *Manager) refreshAgentTokens(ctx context.Context) { } for _, a := range agents { - tier := TokenTierForRole(m.agentMode(a), a.Config.Role) + tier := m.agentTokenTier(a) if err := auth.WriteAgentToken(ctx, a.Name, tier, a.UID); err != nil { m.logger.Warn("agent token refresh failed", "agent", a.Name, "error", err) continue } + // App auth can arrive after launch. Publish the cache path then too, so + // the next turn can read without a restart of the shared-UID agent. + if a.UID == 0 && a.tmuxSession != "" { + _ = m.tmuxCmd(a, "set-environment", "-t", a.tmuxSession, "HIVE_AGENT_TOKEN_CACHE", + crux.AgentTokenCachePath(crux.DefaultAgentTokenCacheDir, a.Name)).Run() + } // Refresh the opt-in mint token alongside the App token (no-op when off). - m.issueAgentMintToken(a.Name, tier, a.UID) + if a.UID > 0 { + m.issueAgentMintToken(a.Name, tier, a.UID) + } // Re-inject the freshly-minted App token into the running session so the // GitHub MCP server keeps authenticating as the App bot. The scoped token // expires hourly; WriteAgentToken above rewrites the cache FILE (which the @@ -882,7 +890,7 @@ func (m *Manager) refreshAgentTokens(ctx context.Context) { // turn picks up the current token. Gated on the opt-in flag + CanPush() to // match the launch injection — advisory agents stay GITHUB_TOKEN-less, and // hives that have not opted in get nothing injected. - if m.project.AppAuthoredPRs && a.tmuxSession != "" && m.agentMode(a).CanPush() { + if a.UID > 0 && m.project.AppAuthoredPRs && a.tmuxSession != "" && m.agentMode(a).CanPush() { if data, err := os.ReadFile(crux.AgentTokenCachePath(crux.DefaultAgentTokenCacheDir, a.Name)); err == nil { if tok := strings.TrimSpace(string(data)); tok != "" { _ = m.tmuxCmd(a, "set-environment", "-t", a.tmuxSession, "GITHUB_TOKEN", tok).Run() @@ -918,10 +926,10 @@ func truncateStr(s string, maxRunes int) string { // race-free. m.appAuth is read without the lock exactly as Start's unlocked // phase always did: it is injected once at wiring time, before agents start. func (m *Manager) mintAgentTokenUnlocked(ctx context.Context, agent *AgentProcess) { - if m.appAuth == nil || agent.UID <= 0 { + if m.appAuth == nil || !m.agentTokenCacheEnabled(agent) { return } - tier := TokenTierForRole(m.agentMode(agent), agent.Config.Role) + tier := m.agentTokenTier(agent) if err := m.appAuth.WriteAgentToken(ctx, agent.Name, tier, agent.UID); err != nil && errors.Is(err, crux.ErrGitHubAppNotInstalled) { // Static misconfiguration: every tick would fail identically, so log // once per agent until a mint succeeds instead of every supervisor tick. @@ -949,5 +957,19 @@ func (m *Manager) mintAgentTokenUnlocked(ctx context.Context, agent *AgentProces } // Additionally issue an opt-in short-lived mint token (no-op when the mint // is disabled). This is additive and fail-safe — it never blocks launch. - m.issueAgentMintToken(agent.Name, tier, agent.UID) + if agent.UID > 0 { + m.issueAgentMintToken(agent.Name, tier, agent.UID) + } +} + +// agentTokenCacheEnabled keeps the shared-UID read path opt-in and App-only. +func (m *Manager) agentTokenCacheEnabled(a *AgentProcess) bool { + return a.UID > 0 || (a.UID == 0 && m.project.SharedUIDReadToken && m.appAuth != nil) +} + +func (m *Manager) agentTokenTier(a *AgentProcess) string { + if a.UID == 0 { + return crux.SharedUIDReadTokenTier + } + return TokenTierForRole(m.agentMode(a), a.Config.Role) } diff --git a/src/crux/agent/shared_uid_read_token_test.go b/src/crux/agent/shared_uid_read_token_test.go new file mode 100644 index 0000000000..f4351df613 --- /dev/null +++ b/src/crux/agent/shared_uid_read_token_test.go @@ -0,0 +1,75 @@ +package agent + +import ( + "context" + "testing" + + "github.com/hivecommons/hive/crux" + "github.com/hivecommons/hive/crux/config" +) + +func TestSharedUIDReadTokenLifecycle(t *testing.T) { + for _, tc := range []struct { + name string + enabled, app bool + uid int + wantCache bool + }{ + {"default off", false, true, 0, false}, + {"no App", true, false, 0, false}, + {"shared opt in", true, true, 0, true}, + {"dedicated UID unchanged", false, true, 2001, true}, + {"dedicated UID with opt in", true, true, 2001, true}, + } { + t.Run(tc.name, func(t *testing.T) { + m := NewManager(map[string]config.AgentConfig{ + "worker": {Backend: "claude", Mode: "ISSUES_AND_PRS", Role: "governor"}, + }, discardLogger(), ProjectContext{ACMMLevel: 5, SharedUIDReadToken: tc.enabled, AppAuthoredPRs: true}) + fm := &fakeMinter{} + if tc.app { + m.SetAppAuth(fm) + } + a := m.agents["worker"] + a.UID = tc.uid + a.tmuxSession = "" // no real tmux processes in this lifecycle unit test + a.State = StateRunning + var cache string + for _, pair := range m.agentEnvPairs(a) { + if pair.Key == "HIVE_AGENT_TOKEN_CACHE" { + cache = pair.Value + } + if tc.uid == 0 && pair.Key == "GITHUB_TOKEN" { + t.Fatal("shared agent received MCP credential") + } + } + if (cache != "") != tc.wantCache { + t.Fatalf("cache path = %q, want enabled %v", cache, tc.wantCache) + } + if tc.wantCache && cache != crux.AgentTokenCachePath(crux.DefaultAgentTokenCacheDir, a.Name) { + t.Fatalf("wrong cache path %q", cache) + } + wantTier := TokenTierForRole(m.agentMode(a), a.Config.Role) + if tc.uid == 0 { + wantTier = crux.SharedUIDReadTokenTier + } + checkMint := func(stage string, wantCalls int) { + t.Helper() + if !tc.wantCache { + wantCalls = 0 + } + if fm.calls != wantCalls || (wantCalls > 0 && fm.lastTier != wantTier) { + t.Fatalf("%s: calls %d tier %q, want calls %d tier %q", stage, fm.calls, fm.lastTier, wantCalls, wantTier) + } + } + m.mintAgentTokenUnlocked(context.Background(), a) + checkMint("launch", 1) + m.RefreshAgentTokens(context.Background()) + checkMint("periodic refresh", 2) + err := m.RefreshAgentTokenFor(context.Background(), a.Name) + if (err == nil) != tc.wantCache { + t.Fatalf("recovery error = %v, want enabled %v", err, tc.wantCache) + } + checkMint("recovery", 3) + }) + } +} diff --git a/src/crux/hivecap/credentials.go b/src/crux/hivecap/credentials.go index 194e96f2de..b74c0ff970 100644 --- a/src/crux/hivecap/credentials.go +++ b/src/crux/hivecap/credentials.go @@ -109,6 +109,14 @@ func (w *AppTokenWriter) WriteAgentToken(ctx context.Context, agentName, tier st if err != nil { return fmt.Errorf("opening agent token cache %s: %w", cachePath, err) } + // Shared-UID mode has no private agent group; keep this owner-only even + // if a previous deployment pre-created a group-readable cache. + if agentUID == 0 && tier == crux.SharedUIDReadTokenTier { + if err := f.Chmod(agentTokenCachePerms); err != nil { + _ = f.Close() + return fmt.Errorf("securing shared-UID token cache %s: %w", cachePath, err) + } + } if _, err := f.WriteString(resp.Token); err != nil { _ = f.Close() return fmt.Errorf("writing agent token cache %s: %w", cachePath, err) diff --git a/src/crux/hivecap/credentials_test.go b/src/crux/hivecap/credentials_test.go index 898e843040..d1850abe91 100644 --- a/src/crux/hivecap/credentials_test.go +++ b/src/crux/hivecap/credentials_test.go @@ -293,3 +293,34 @@ func TestSetCarriesCredentialWriters(t *testing.T) { t.Error("plain capabilities must not claim mint") } } + +func TestAppTokenWriterSharedUIDReadCache(t *testing.T) { + d := &direct{expiry: time.Now().Add(time.Hour)} + w := NewAppTokenWriter(d) + w.CacheDir = t.TempDir() + w.injectOn = func() bool { return false } + path := crux.AgentTokenCachePath(w.CacheDir, "scanner") + if err := os.WriteFile(path, []byte("stale"), 0o640); err != nil { + t.Fatal(err) + } + if err := os.Chmod(path, 0o640); err != nil { + t.Fatal(err) + } + if err := w.WriteAgentToken(context.Background(), "scanner", crux.SharedUIDReadTokenTier, 0); err != nil { + t.Fatal(err) + } + info, err := os.Stat(path) + if err != nil { + t.Fatal(err) + } + if info.Mode().Perm() != 0o600 { + t.Fatalf("mode = %o, want 600", info.Mode().Perm()) + } + if len(d.mints) != 1 || d.mints[0].Tier != crux.SharedUIDReadTokenTier { + t.Fatalf("wrong mint scope: %+v", d.mints) + } + data, err := os.ReadFile(path) + if err != nil || len(data) == 0 || string(data) == "stale" { + t.Fatalf("cache not refreshed: %v", err) + } +} diff --git a/src/crux/host_types.go b/src/crux/host_types.go index a886c9e7c1..985b05dee6 100644 --- a/src/crux/host_types.go +++ b/src/crux/host_types.go @@ -17,6 +17,9 @@ import ( // sidecar runtime will receive them over a hive-side callback endpoint // (stage 2 decides the shape). crux/agent aliases every one of them. +// SharedUIDReadTokenTier grants only GitHub reads for agents without UID isolation. +const SharedUIDReadTokenTier = "shared-uid-read" + // AppTokenMinter is implemented by the host's GitHub App auth // (pkg/github.AppAuth) to mint per-agent scoped tokens. type AppTokenMinter interface { diff --git a/src/crux/project.go b/src/crux/project.go index 30ad84d9cb..257f89423b 100644 --- a/src/crux/project.go +++ b/src/crux/project.go @@ -26,6 +26,9 @@ type ProjectContext struct { // MCP server authors PRs/commits as the App bot. Default false → no token is // injected and behavior is unchanged (opt-in per hive). AppAuthoredPRs bool + // SharedUIDReadToken permits read-only App caches without dedicated UIDs. + // Cross-agent read isolation is unavailable in this explicit opt-in mode. + SharedUIDReadToken bool // AppBotLogin and AppBotUserID identify the installed GitHub App's bot // account. When AppAuthoredPRs is on, push-capable agents use this bot's // noreply address ("+@users.noreply.github.com") for git diff --git a/src/docs/troubleshooting.md b/src/docs/troubleshooting.md index 552e234094..452badfa60 100644 --- a/src/docs/troubleshooting.md +++ b/src/docs/troubleshooting.md @@ -363,7 +363,18 @@ Common causes: - The agent is running in a deployment that does not use the per-UID manager path (native/systemd, Compose/Quadlet, or a Kubernetes pod whose UID isolation did not initialize), so `HIVE_AGENT_TOKEN_CACHE` is legitimately - absent and the native `gh auth login` fallback must be used instead. + absent. On native installs, use the native `gh auth login` fallback. + For App-identity deployments that intentionally share a UID (for example, + OpenShift `restricted-v2`), set `github.shared_uid_read_token: true` and + restart the hive. With App auth configured, the manager mints and refreshes + per-agent caches under `/var/run/hive-metrics/agent-tokens/`, owned by the + shared UID with mode `0600`, and exports `HIVE_AGENT_TOKEN_CACHE`. Tokens + grant only metadata, contents, actions, checks, pull requests and issues + **read** access, regardless of agent role; writes continue through relays. + This is default-off because shared-UID agents can read each other's caches. + The boot log reports the opt-in next to `no UID map found`. + Ensure the shared UID can write the cache directory. This option does not + restore UID isolation or clear the `uid_isolation` health alert. - The cache file exists but is empty, unreadable, or was not pre-created by the entrypoint as `dev:hive- 0640`. - The GitHub App is not installed on the repo, or token minting failed for the @@ -380,10 +391,11 @@ Check from inside the hive container: su -s /bin/sh hive- -c 'printf "%s\n" "${HIVE_AGENT_TOKEN_CACHE:-unset}"; test -r "$HIVE_AGENT_TOKEN_CACHE" && echo readable || echo MISSING' ``` -Never print the file contents. If this says `unset` on a native/shared-UID -deployment, check that the launch environment has the shared App token available -to the launcher (`HIVE_GITHUB_TOKEN`) and that `gh auth status --hostname -github.ibm.com` succeeds after launch. For GitHub Enterprise, set the primary +Never print the file contents. On an intentional shared-UID App deployment, +check the opt-in above and the manager's token-mint logs; no personal login or +shared full-privilege token fallback is needed. For a native install using a +personal login, check that `gh auth status --hostname github.ibm.com` succeeds +after launch. For GitHub Enterprise, set the primary GitHub host/base URL so agents inherit `GH_HOST=github.ibm.com`, and install/authorize the GitHub App on the target repo (`Jaedon-Paget/kie` in the reported case). On per-UID Kubernetes, `unset` or `MISSING` points to a broken diff --git a/src/hive.yaml.example b/src/hive.yaml.example index c6b8002422..295c6dbcd4 100644 --- a/src/hive.yaml.example +++ b/src/hive.yaml.example @@ -916,6 +916,10 @@ github: # app_id: 12345 # installation_id: 67890 # key_file: /secrets/gh-app-key.pem + # Opt in on shared-UID deployments (e.g. OpenShift restricted-v2). + # Gives agents read-only App caches; agents can read each other's caches. + # Writes still use the relays. Requires App auth; default false. Restart to apply. + # shared_uid_read_token: true # agent_reserve_floor: 400 # Keep this many core requests reserved for daemon scan/merge paths. # Shared GitHub App/PAT core API budget floors. When remaining core quota diff --git a/src/pkg/config/config.go b/src/pkg/config/config.go index 050b06a3fe..6b4ab40307 100644 --- a/src/pkg/config/config.go +++ b/src/pkg/config/config.go @@ -3172,6 +3172,11 @@ func (m ModeConfig) MarshalYAML() (interface{}, error) { } type GitHubConfig struct { + // SharedUIDReadToken opts shared-UID agents into per-agent read-only App + // token caches. Default off; agents sharing a UID can read each other's + // caches. Requires App auth; writes continue through the relays. + SharedUIDReadToken bool `yaml:"shared_uid_read_token,omitempty" json:"shared_uid_read_token,omitempty"` + AppID int64 `yaml:"app_id"` InstallationID int64 `yaml:"installation_id"` DocsInstallationID int64 `yaml:"docs_installation_id"` diff --git a/src/pkg/config/shared_uid_read_token_test.go b/src/pkg/config/shared_uid_read_token_test.go new file mode 100644 index 0000000000..ac968aeeef --- /dev/null +++ b/src/pkg/config/shared_uid_read_token_test.go @@ -0,0 +1,30 @@ +package config + +import ( + "gopkg.in/yaml.v3" + "testing" +) + +func TestSharedUIDReadTokenOptIn(t *testing.T) { + for _, enabled := range []bool{false, true} { + cfg := Config{GitHub: GitHubConfig{SharedUIDReadToken: enabled}} + data, err := yaml.Marshal(cfg) + if err != nil { + t.Fatal(err) + } + var loaded Config + if err := yaml.Unmarshal(data, &loaded); err != nil { + t.Fatal(err) + } + if loaded.GitHub.SharedUIDReadToken != enabled { + t.Fatalf("opt-in changed on round trip: %v", loaded.GitHub.SharedUIDReadToken) + } + } + var cfg Config + if err := yaml.Unmarshal([]byte("github: {}"), &cfg); err != nil { + t.Fatal(err) + } + if cfg.GitHub.SharedUIDReadToken { + t.Fatal("shared UID read tokens must default off") + } +} diff --git a/src/pkg/dashboard/settings_parity_allowlist.txt b/src/pkg/dashboard/settings_parity_allowlist.txt index 06bd0ed9b4..0626a4320f 100644 --- a/src/pkg/dashboard/settings_parity_allowlist.txt +++ b/src/pkg/dashboard/settings_parity_allowlist.txt @@ -165,6 +165,7 @@ duplicate_sweep.bot_authors[] # TODO #11854 evidence.complexity.enabled # TODO #11854 evidence.complexity.static_analysis # TODO #11854 github.additional_bot_logins[] # TODO #11854 +github.shared_uid_read_token # shared-UID App read-token opt-in; yaml-only, restart required (#14778) good_first_issue.exclude_labels[] # advanced scorer tuning; yaml-only (#12185) good_first_issue.repos[] # advanced scorer tuning; yaml-only (#12185) governor.first_timer_welcome.enabled # first-time contributor welcome; yaml-only diff --git a/src/pkg/github/app.go b/src/pkg/github/app.go index 05782c8f7e..b5b8d93bb3 100644 --- a/src/pkg/github/app.go +++ b/src/pkg/github/app.go @@ -304,6 +304,17 @@ func (a *AppAuth) ScopedTokenForRepos(ctx context.Context, tier string, repos [] var perms *gh.InstallationPermissions switch tier { + case crux.SharedUIDReadTokenTier: + // Shared-UID agents cannot isolate credentials from one another. + // Never deliver a write-capable token, regardless of the agent's role. + perms = &gh.InstallationPermissions{ + Metadata: gh.Ptr("read"), + Contents: gh.Ptr("read"), + Actions: gh.Ptr("read"), + Checks: gh.Ptr("read"), + PullRequests: gh.Ptr("read"), + Issues: gh.Ptr("read"), + } case "newcomer": // Newcomers (ISSUES_ONLY agents) can comment on and file issues, and // READ code — filing a meaningful issue requires reading the repo it @@ -587,6 +598,14 @@ func (a *AppAuth) WriteAgentToken(ctx context.Context, agentName, tier string, a if err != nil { return fmt.Errorf("opening agent token cache %s: %w", cachePath, err) } + // Shared-UID mode has no private agent group; keep this owner-only even + // if a previous deployment pre-created a group-readable cache. + if agentUID == 0 && tier == crux.SharedUIDReadTokenTier { + if err := f.Chmod(agentTokenCachePerms); err != nil { + _ = f.Close() + return fmt.Errorf("securing shared-UID token cache %s: %w", cachePath, err) + } + } if _, err := f.WriteString(fileToken); err != nil { _ = f.Close() // best-effort cleanup; the write error is what's returned return fmt.Errorf("writing agent token cache %s: %w", cachePath, err) diff --git a/src/pkg/github/shared_uid_read_token_test.go b/src/pkg/github/shared_uid_read_token_test.go new file mode 100644 index 0000000000..aa2c02f0a2 --- /dev/null +++ b/src/pkg/github/shared_uid_read_token_test.go @@ -0,0 +1,71 @@ +package github + +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "os" + "reflect" + "strings" + "sync/atomic" + "testing" + "time" + + "github.com/hivecommons/hive/crux" +) + +func TestSharedUIDReadTokenPermissionsAndDelivery(t *testing.T) { + auth, logs, closeAuth := newFakeAppAuth(t, "unused") + defer closeAuth() + useTempCacheDir(t) + var requests atomic.Int32 + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + var req struct { + Permissions map[string]string `json:"permissions"` + } + if err := json.NewDecoder(r.Body).Decode(&req); err != nil { + t.Error(err) + } + want := map[string]string{"metadata": "read", "contents": "read", "actions": "read", "checks": "read", "pull_requests": "read", "issues": "read"} + if !reflect.DeepEqual(req.Permissions, want) { + t.Errorf("permissions = %v, want exactly %v", req.Permissions, want) + } + requests.Add(1) + _ = json.NewEncoder(w).Encode(map[string]any{"token": "ghs_shared_read", "expires_at": time.Now().Add(time.Hour).Format(time.RFC3339)}) + })) + defer server.Close() + auth.apiURL = server.URL + for _, name := range []string{"scanner", "quality"} { + path := AgentTokenCachePath(name) + for i := 0; i < 2; i++ { + if err := auth.WriteAgentToken(context.Background(), name, crux.SharedUIDReadTokenTier, 0); err != nil { + t.Fatal(err) + } + data, err := os.ReadFile(path) + if err != nil || string(data) != "ghs_shared_read" { + t.Fatalf("cache unavailable: %v", err) + } + info, err := os.Stat(path) + if err != nil { + t.Fatal(err) + } + if info.Mode().Perm() != 0o600 { + t.Fatalf("mode = %o, want 600", info.Mode().Perm()) + } + // A pre-existing cache must also be narrowed on refresh. + if err := os.Chmod(path, 0o640); err != nil { + t.Fatal(err) + } + } + } + if requests.Load() != 4 { + t.Fatalf("mint requests = %d, want 4", requests.Load()) + } + if AgentTokenCachePath("scanner") == AgentTokenCachePath("quality") { + t.Fatal("agents share a cache path") + } + if strings.Contains(logs.String(), "ghs_shared_read") { + t.Fatal("token leaked in log") + } +}