diff --git a/changelog.d/added-claude-long-lived-token.md b/changelog.d/added-claude-long-lived-token.md new file mode 100644 index 0000000000..9c84edba5b --- /dev/null +++ b/changelog.d/added-claude-long-lived-token.md @@ -0,0 +1 @@ +- Claude agents can run on an operator-supplied long-lived token: set `HIVE_CLAUDE_OAUTH_TOKEN` (or mount it at `/secrets/claude-oauth-token`, or point `HIVE_CLAUDE_OAUTH_TOKEN_FILE` at it) to a `claude setup-token` token and every `claude`-backend agent is launched with it as `CLAUDE_CODE_OAUTH_TOKEN`, ahead of the 8-hour dashboard sign-in; unset, nothing changes. diff --git a/changelog.d/changed-claude-operator-token-suspends-rebridge.md b/changelog.d/changed-claude-operator-token-suspends-rebridge.md new file mode 100644 index 0000000000..22c625b98c --- /dev/null +++ b/changelog.d/changed-claude-operator-token-suspends-rebridge.md @@ -0,0 +1 @@ +- Claude auth: while `HIVE_CLAUDE_OAUTH_TOKEN` (or its secret file) is set, Claude agents run on the operator's long-lived token and the shared `~/.claude/.credentials.json` is not what they authenticate with, so the per-agent credential re-bridge (launch, watchdog poll and post-sign-in) and the durable-credential watchdog's Claude probe are suspended: no credential files are moved, no `claude_token_missing` audit or "durable credential unusable" warning is raised for Claude. The suspension is logged once at startup; Copilot watching is unchanged, and with the token unset everything behaves exactly as before. (#17760) diff --git a/src/crux/agent/claude_credential_bridge.go b/src/crux/agent/claude_credential_bridge.go index b511e8d955..1f36cb2096 100644 --- a/src/crux/agent/claude_credential_bridge.go +++ b/src/crux/agent/claude_credential_bridge.go @@ -521,6 +521,14 @@ func preserveClaudeCredential(path string, now time.Time) (string, error) { // outcome. It is the single entry point the launch path, the watchdog poll and // the sign-in hook share, so all three log and audit identically. func (m *Manager) rebridgeClaudeCredential(agentName, link, target, trigger string) *claudeBridgeRepair { + // Operator-token mode: agents do not authenticate with the shared + // credentials file, so a private copy left by a refresh is nothing to + // repair (claude_operator_token_mode.go). Covers launch, watchdog and + // sign-in alike. + if m.claudeOperatorTokenMode() { + m.logClaudeOperatorTokenModeOnce() + return nil + } rep, err := m.repairClaudeCredentialBridge(agentName, link, target, trigger) if errors.Is(err, errClaudeBridgeLinkIsTarget) { // The legacy layout: skipped, and said once per agent rather than on @@ -594,8 +602,13 @@ func (m *Manager) logClaudeBridgeUnreadable(agentName, link, trigger string, err // RepairClaudeCredentialBridges checks every per-agent Claude credential // bridge and repairs each one a regular file has replaced. It returns the // names of the agents it re-bridged, sorted. Agents are snapshotted under m.mu -// and repaired after it is released. +// and repaired after it is released. In operator-token mode it does nothing +// and returns nil (claude_operator_token_mode.go). func (m *Manager) RepairClaudeCredentialBridges(trigger string) []string { + if m.claudeOperatorTokenMode() { + m.logClaudeOperatorTokenModeOnce() + return nil + } type candidate struct { name string uid int diff --git a/src/crux/agent/claude_operator_token_mode.go b/src/crux/agent/claude_operator_token_mode.go new file mode 100644 index 0000000000..76898bd3ea --- /dev/null +++ b/src/crux/agent/claude_operator_token_mode.go @@ -0,0 +1,38 @@ +package agent + +// Operator-token mode for Claude (#17760). +// +// With HIVE_CLAUDE_OAUTH_TOKEN set, every claude-backend agent runs on the +// operator's long-lived `claude setup-token` token through +// CLAUDE_CODE_OAUTH_TOKEN (manager_env.go). That token is never refreshed, so +// the machinery built around the shared ~/.claude/.credentials.json — the +// per-agent credential re-bridge that publishes a refreshed token back into +// the shared login, and the durable-credential watchdog that alerts when that +// file is missing or spent — has nothing to act on: the file is not what the +// agents authenticate with. Acting anyway would move credential files around +// for no reason; alerting would send an operator to redo a dashboard sign-in +// that the fleet does not use. Both are therefore suspended for Claude while +// the token is set and behave exactly as before when it is unset. The token's +// own health (a 401 from the API) is surfaced separately (#17759). + +// claudeOperatorTokenMode reports whether Claude agents run on the operator's +// long-lived token rather than the shared credentials file. The token is read +// once at construction (claudeOperatorToken), so the mode is fixed for the +// life of the process. +func (m *Manager) claudeOperatorTokenMode() bool { + return m.claudeOperatorToken != "" +} + +// logClaudeOperatorTokenModeOnce says, once per process, that the Claude +// credential re-bridge and watchdog alerts are suspended, so an operator +// reading the log knows why neither will ever fire. Never logs the token. +func (m *Manager) logClaudeOperatorTokenModeOnce() { + if !m.claudeOperatorTokenMode() { + return + } + m.claudeOperatorModeLogOnce.Do(func() { + m.logger.Info("claude auth: operator-supplied long-lived token is set; Claude agents run on it, so the shared credentials file is not in use — credential re-bridge and durable-credential watchdog alerts are suspended for the claude backend", + "source", "HIVE_CLAUDE_OAUTH_TOKEN", + "suspended", "claude credential re-bridge, claude durable-credential watchdog") + }) +} diff --git a/src/crux/agent/claude_operator_token_mode_test.go b/src/crux/agent/claude_operator_token_mode_test.go new file mode 100644 index 0000000000..e34eb37464 --- /dev/null +++ b/src/crux/agent/claude_operator_token_mode_test.go @@ -0,0 +1,127 @@ +package agent + +import ( + "bytes" + "log/slog" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/hivecommons/hive/crux/config" +) + +// operatorModeFixture is a manager in operator-token mode (the token field set +// as NewManager does from HIVE_CLAUDE_OAUTH_TOKEN) with one claude agent whose +// credential link a refresh replaced, plus the log it writes. +func operatorModeFixture(t *testing.T) (*Manager, *fakeAuditSink, *AgentProcess, string, string, *bytes.Buffer) { + t.Helper() + m, sink, ap, link, target := bridgeTestFixture(t) + var logs bytes.Buffer + m.logger = slog.New(slog.NewTextHandler(&logs, &slog.HandlerOptions{Level: slog.LevelDebug})) + m.claudeOperatorToken = operatorTokenSentinel + now := time.Now() + if err := os.WriteFile(target, bridgeTestCreds(t, "shared", now.Add(10*time.Minute).UnixMilli()), 0o660); err != nil { + t.Fatal(err) + } + simulateClaudeRefresh(t, link, bridgeTestCreds(t, "private", now.Add(8*time.Hour).UnixMilli())) + return m, sink, ap, link, target, &logs +} + +// While the operator token is set the re-bridge does nothing on any trigger: +// the private file stays a private file, the shared login is untouched, +// and nothing is audited. +func TestClaudeOperatorTokenMode_RebridgeIsSuspended(t *testing.T) { + m, sink, _, link, target, logs := operatorModeFixture(t) + sharedBefore, err := os.ReadFile(target) + if err != nil { + t.Fatal(err) + } + agentBefore, err := os.ReadFile(link) + if err != nil { + t.Fatal(err) + } + + for _, trigger := range []string{claudeBridgeTriggerWatchdog, claudeBridgeTriggerSignIn} { + if got := m.RepairClaudeCredentialBridges(trigger); len(got) != 0 { + t.Fatalf("trigger %s: RepairClaudeCredentialBridges = %v, want none in operator-token mode", trigger, got) + } + } + if rep := m.rebridgeClaudeCredential("scanner", link, target, claudeBridgeTriggerLaunch); rep != nil { + t.Fatalf("launch re-bridge ran in operator-token mode: %+v", rep) + } + m.rebridgeClaudeCredentialsAfterSignIn() + + if fi, err := os.Lstat(link); err != nil || !fi.Mode().IsRegular() { + t.Fatalf("agent's private credential must be left exactly where it is; Lstat: %v %v", fi, err) + } + if got, _ := os.ReadFile(link); !bytes.Equal(got, agentBefore) { + t.Error("agent's private credential was rewritten") + } + if got, _ := os.ReadFile(target); !bytes.Equal(got, sharedBefore) { + t.Error("shared credential was rewritten") + } + if stale, _ := filepath.Glob(filepath.Join(filepath.Dir(link), "*"+claudeCredentialStaleInfix+"*")); len(stale) != 0 { + t.Errorf("files were moved aside: %v", stale) + } + if n := sink.count(); n != 0 { + t.Errorf("re-bridge audited %d entries in operator-token mode, want 0", n) + } + if n := strings.Count(logs.String(), "watchdog alerts are suspended"); n != 1 { + t.Errorf("suspension logged %d times across several calls, want exactly once:\n%s", n, logs.String()) + } + if strings.Contains(logs.String(), operatorTokenSentinel) { + t.Fatal("operator token reached the log") + } +} + +// While the operator token is set the watchdog never alerts about the Claude +// credentials file — absent, spent or otherwise — but still watches Copilot. +func TestClaudeOperatorTokenMode_WatchdogClaudeProbeIsSuspended(t *testing.T) { + m, sink, _, _, _, logs := operatorModeFixture(t) + m.mu.Lock() + m.agents["reviewer"] = &AgentProcess{Name: "reviewer", UID: 2002, Config: config.AgentConfig{Backend: "copilot"}} + m.mu.Unlock() + + missing := filepath.Join(t.TempDir(), "missing") + last := map[string]bool{"claude": true} // a stale observation from before token mode is cleared, not re-alerted + m.evalCredentialWatch(credentialWatch{backend: "claude", path: missing, + auditAction: AuditClaudeTokenMissing, probe: claudeTokenUsable}, last) + if sink.count() != 0 { + t.Fatalf("claude watch audited %d entries in operator-token mode, want 0", sink.count()) + } + if _, tracked := last["claude"]; tracked { + t.Error("suspended claude watch must not keep a transition record") + } + if strings.Contains(logs.String(), "durable credential unusable") { + t.Errorf("claude watch warned in operator-token mode:\n%s", logs.String()) + } + + m.evalCredentialWatch(credentialWatch{backend: "copilot", path: missing, + auditAction: AuditCopilotTokenMissing, probe: copilotTokenUsable}, last) + if e := sink.find(AuditCopilotTokenMissing); e == nil { + t.Fatal("copilot watch must keep alerting in operator-token mode") + } +} + +// Unset, the same fixture behaves exactly as today: the re-bridge repairs the +// link and the watchdog probes Claude. +func TestClaudeOperatorTokenMode_UnsetKeepsTodaysBehaviour(t *testing.T) { + m, sink, _, link, target, logs := operatorModeFixture(t) + m.claudeOperatorToken = "" + + if got := m.RepairClaudeCredentialBridges(claudeBridgeTriggerWatchdog); len(got) != 1 || got[0] != "scanner" { + t.Fatalf("RepairClaudeCredentialBridges = %v, want [scanner]", got) + } + assertLinkRestored(t, link, target) + last := map[string]bool{} + m.evalCredentialWatch(credentialWatch{backend: "claude", path: filepath.Join(t.TempDir(), "missing"), + auditAction: AuditClaudeTokenMissing, probe: claudeTokenUsable}, last) + if e := sink.find(AuditClaudeTokenMissing); e == nil { + t.Fatal("claude watch must alert when no operator token is set") + } + if strings.Contains(logs.String(), "watchdog alerts are suspended") { + t.Error("suspension must not be logged when the token is unset") + } +} diff --git a/src/crux/agent/claude_operator_token_test.go b/src/crux/agent/claude_operator_token_test.go new file mode 100644 index 0000000000..8ad2b15647 --- /dev/null +++ b/src/crux/agent/claude_operator_token_test.go @@ -0,0 +1,167 @@ +package agent + +import ( + "bytes" + "log/slog" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/hivecommons/hive/crux/claude" + "github.com/hivecommons/hive/crux/config" +) + +const operatorTokenSentinel = "sk-ant-oat01-OPERATOR-SENTINEL-7f3c9a1e5b" + +// stageOperatorToken makes claude.OperatorToken hermetic: the env var holds +// token ("" for unset) and the default secret file points at a missing path. +func stageOperatorToken(t *testing.T, token string) { + t.Helper() + t.Setenv(claude.OperatorTokenEnvVar, token) + t.Setenv(claude.OperatorTokenFileEnvVar, "") + orig := claude.OperatorTokenFile + claude.OperatorTokenFile = filepath.Join(t.TempDir(), "missing") + t.Cleanup(func() { claude.OperatorTokenFile = orig }) +} + +// With a long-lived operator token set, an agent whose credential file is +// readable and fresh still runs on the operator token: that file is the +// 8-hour login that logs the fleet out (#17753). +func TestClaudeOperatorToken_InjectedOverAReadableCredential(t *testing.T) { + stageSharedClaudeCredential(t, map[string]any{ + "accessToken": "sk-ant-oat-live", + "expiresAt": time.Now().Add(6 * time.Hour).UnixMilli(), + }) + stageOperatorToken(t, operatorTokenSentinel) + m, agent := claudeAgentFixture(t, "sk-ant-oat-snapshot-from-boot") + + pair, ok := envPairsByKey(m, agent)["CLAUDE_CODE_OAUTH_TOKEN"] + if !ok || pair.Value != operatorTokenSentinel { + t.Fatalf("pair = %+v, %v; want the operator token over a readable credential", pair, ok) + } + if !pair.Secret { + t.Fatal("the operator token must be a secret pair (tmux set-environment, never a command line)") + } +} + +// With no credential file at all, the operator token is still injected, and it +// beats the dashboard snapshot the last-resort fallback would otherwise use. +func TestClaudeOperatorToken_InjectedWithNoCredentialFile(t *testing.T) { + stageSharedClaudeCredential(t, nil) + stageOperatorToken(t, operatorTokenSentinel) + m, agent := claudeAgentFixture(t, "sk-ant-oat-from-dashboard-login") + + pair, ok := envPairsByKey(m, agent)["CLAUDE_CODE_OAUTH_TOKEN"] + if !ok || pair.Value != operatorTokenSentinel || !pair.Secret { + t.Fatalf("pair = %+v, %v; want the operator token as a secret pair", pair, ok) + } +} + +// A dashboard sign-in after boot only replaces claudeAuthToken; it must not +// switch agents back to the 8-hour token. +func TestClaudeOperatorToken_WinsOverALaterDashboardSignIn(t *testing.T) { + stageSharedClaudeCredential(t, nil) + stageOperatorToken(t, operatorTokenSentinel) + m, agent := claudeAgentFixture(t, "") + m.mu.Lock() + m.claudeAuthToken = "sk-ant-oat-fresh-dashboard-login" + m.mu.Unlock() + + pairs := m.agentEnvPairs(agent) + var got []string + for _, p := range pairs { + if p.Key == "CLAUDE_CODE_OAUTH_TOKEN" { + got = append(got, p.Value) + } + } + if len(got) != 1 || got[0] != operatorTokenSentinel { + t.Fatalf("CLAUDE_CODE_OAUTH_TOKEN values = %q; want exactly the operator token", got) + } +} + +// Unset: behaviour is exactly today's — no override over a readable +// credential, the dashboard snapshot when nothing is readable. +func TestClaudeOperatorToken_UnsetKeepsTodaysBehaviour(t *testing.T) { + stageSharedClaudeCredential(t, map[string]any{ + "accessToken": "sk-ant-oat-live", + "expiresAt": time.Now().Add(6 * time.Hour).UnixMilli(), + }) + stageOperatorToken(t, "") + m, agent := claudeAgentFixture(t, "sk-ant-oat-snapshot-from-boot") + if _, ok := envPairsByKey(m, agent)["CLAUDE_CODE_OAUTH_TOKEN"]; ok { + t.Fatal("with the operator token unset, nothing may be injected over a readable credential") + } + + stageSharedClaudeCredential(t, nil) + m, agent = claudeAgentFixture(t, "sk-ant-oat-from-dashboard-login") + if pair := envPairsByKey(m, agent)["CLAUDE_CODE_OAUTH_TOKEN"]; pair.Value != "sk-ant-oat-from-dashboard-login" { + t.Fatalf("with the operator token unset, the last-resort fallback must be unchanged: %+v", pair) + } +} + +// The token can come from the secret-file form and is never sent to an agent +// on another backend. +func TestClaudeOperatorToken_FileFormAndOtherBackends(t *testing.T) { + stageSharedClaudeCredential(t, nil) + stageOperatorToken(t, "") + path := filepath.Join(t.TempDir(), "claude-oauth-token") + if err := os.WriteFile(path, []byte(operatorTokenSentinel+"\n"), 0o600); err != nil { + t.Fatal(err) + } + t.Setenv(claude.OperatorTokenFileEnvVar, path) + + m, agent := claudeAgentFixture(t, "") + if pair := envPairsByKey(m, agent)["CLAUDE_CODE_OAUTH_TOKEN"]; pair.Value != operatorTokenSentinel { + t.Fatalf("file form not injected: %+v", pair) + } + + other := NewManager(map[string]config.AgentConfig{ + "scanner": {Backend: "copilot"}, + }, discardLogger(), ProjectContext{ACMMLevel: 5}) + other.mu.RLock() + otherAgent := other.agents["scanner"] + other.mu.RUnlock() + if _, ok := envPairsByKey(other, otherAgent)["CLAUDE_CODE_OAUTH_TOKEN"]; ok { + t.Fatal("a copilot agent must not receive the operator Claude token") + } +} + +// The manager never writes the operator token to its log while loading it +// and building an agent's environment. +func TestClaudeOperatorToken_NeverLogged(t *testing.T) { + stageSharedClaudeCredential(t, nil) + stageOperatorToken(t, operatorTokenSentinel) + var buf bytes.Buffer + logger := slog.New(slog.NewJSONHandler(&buf, &slog.HandlerOptions{Level: slog.LevelDebug})) + m := NewManager(map[string]config.AgentConfig{ + "scanner": {Backend: "claude", Model: "claude-sonnet-5"}, + }, logger, ProjectContext{ACMMLevel: 5}) + m.mu.RLock() + agent := m.agents["scanner"] + m.mu.RUnlock() + _ = m.agentEnvPairs(agent) + _ = m.buildEnvPrefix(agent) + + if strings.Contains(buf.String(), operatorTokenSentinel) { + t.Fatalf("operator token written to the hive log: %s", buf.String()) + } + if strings.Contains(m.buildEnvPrefix(agent), operatorTokenSentinel) { + t.Fatal("operator token reached the shell command-line env prefix") + } +} + +// The hive process holds HIVE_CLAUDE_OAUTH_TOKEN in its own environment, and +// every tmux server it starts inherits that globally. applySessionEnv must +// strip it (with -r, so the global value is hidden too) or every pane of every +// backend — copilot, codex, bob — could read the year-long token under its +// original name. The claude backend receives it only as CLAUDE_CODE_OAUTH_TOKEN. +func TestClaudeOperatorToken_StrippedFromInheritedPaneEnv(t *testing.T) { + for _, k := range inheritedCredentialEnvVars { + if k == claude.OperatorTokenEnvVar { + return + } + } + t.Fatalf("%s is not in inheritedCredentialEnvVars; it would reach every agent pane via the tmux global environment", claude.OperatorTokenEnvVar) +} diff --git a/src/crux/agent/credentials_watchdog.go b/src/crux/agent/credentials_watchdog.go index 5a3c02d85e..7259d488e0 100644 --- a/src/crux/agent/credentials_watchdog.go +++ b/src/crux/agent/credentials_watchdog.go @@ -220,7 +220,13 @@ func credentialWatches() []credentialWatch { // Safe to start unconditionally at boot: like StartAgentTokenRefresh it tracks // live state each tick rather than a boot-time snapshot, so a hive that gains // or loses a backend via config reload is evaluated correctly. +// +// Operator-token mode (HIVE_CLAUDE_OAUTH_TOKEN set): the Claude agents do not +// use the shared credentials file, so the Claude re-bridge and the Claude +// probe are suspended and said so once at start; Copilot is watched as +// before. See claude_operator_token_mode.go. func (m *Manager) StartCredentialWatchdog(ctx context.Context) { + m.logClaudeOperatorTokenModeOnce() ticker := time.NewTicker(credentialWatchdogInterval()) defer ticker.Stop() bridgeTicker := time.NewTicker(claudeBridgeInterval()) @@ -254,8 +260,9 @@ func (m *Manager) StartCredentialWatchdog(ctx context.Context) { // use) and emits a transition-edge log + audit event. lastUnusable carries the // previous observation per backend across ticks. func (m *Manager) evalCredentialWatch(w credentialWatch, lastUnusable map[string]bool) { - if !m.backendInUse(w.backend) { - // Not in use: nothing to watch. Reset the tracker so a later config + if !m.backendInUse(w.backend) || (w.backend == "claude" && m.claudeOperatorTokenMode()) { + // Not in use (or, for Claude, the operator token is in use instead of + // the file): nothing to watch. Reset the tracker so a later config // change that adds this backend with a bad credential alerts on its // first miss rather than being masked as "no transition". delete(lastUnusable, w.backend) diff --git a/src/crux/agent/manager.go b/src/crux/agent/manager.go index 92102c3b9d..9713d21661 100644 --- a/src/crux/agent/manager.go +++ b/src/crux/agent/manager.go @@ -594,12 +594,16 @@ type Manager struct { // precedence for whatever fresh token the operator supplied. copilotAuthTokenRejected bool claudeAuthToken string - uidMap *UIDMap - sharedPool SharedSessionPool - uidMapPath string - appAuth AppTokenMinter - appNotInstalledWarned sync.Map // agent name -> struct{}: not-installed mint failure already logged - agentMint AgentMintIssuer // optional, opt-in mint credential (nil ⇒ off) + claudeOperatorToken string // HIVE_CLAUDE_OAUTH_TOKEN, read once at construction; a dashboard sign-in never replaces it + // claudeOperatorModeLogOnce guards the one-time "re-bridge and watchdog + // suspended" log for operator-token mode (claude_operator_token_mode.go). + claudeOperatorModeLogOnce sync.Once + uidMap *UIDMap + sharedPool SharedSessionPool + uidMapPath string + appAuth AppTokenMinter + appNotInstalledWarned sync.Map // agent name -> struct{}: not-installed mint failure already logged + agentMint AgentMintIssuer // optional, opt-in mint credential (nil ⇒ off) // sharedPoolRenewInterval overrides the lease watcher tick (zero means // defaultSharedPoolRenewInterval). Set before any watcher starts; it is @@ -886,6 +890,7 @@ func NewManagerWithOptions(agents map[string]config.AgentConfig, logger *slog.Lo copilotAuthTokenAuthoritative: copilotTokenAuthoritative, copilotAuthTokenSource: copilotTokenSource, claudeAuthToken: claudeToken, + claudeOperatorToken: claude.OperatorToken(), uidMap: uidMap, sharedPool: opts.sharedPool, uidMapPath: selectedUIDMapPath, diff --git a/src/crux/agent/manager_env.go b/src/crux/agent/manager_env.go index c930d652aa..9e866de3d2 100644 --- a/src/crux/agent/manager_env.go +++ b/src/crux/agent/manager_env.go @@ -422,7 +422,15 @@ func (m *Manager) agentEnvPairs(agent *AgentProcess) []agentEnvPair { // keeps the variable doing the job it was added for (#c5648bc9: deliver a // dashboard-obtained token to an agent that cannot see the file) and stops // it overriding a credential that can still refresh itself. - if m.claudeAuthToken != "" && backend == "claude" && !claudeCredentialReachable(agent, backend) { + // + // An operator-supplied long-lived token (HIVE_CLAUDE_OAUTH_TOKEN, from + // `claude setup-token`) is the exception: it lasts about a year and never + // needs a refresh, so pinning it is the point. It is injected whether or + // not a credentials file is reachable and wins over the dashboard + // sign-in, which only ever updates claudeAuthToken. + if m.claudeOperatorToken != "" && backend == "claude" { + vars = append(vars, agentEnvPair{"CLAUDE_CODE_OAUTH_TOKEN", m.claudeOperatorToken, true}) + } else if m.claudeAuthToken != "" && backend == "claude" && !claudeCredentialReachable(agent, backend) { vars = append(vars, agentEnvPair{"CLAUDE_CODE_OAUTH_TOKEN", m.claudeAuthToken, true}) } // bob reads its key from BOBSHELL_API_KEY in 1.x and BOB_API_KEY in 2.x. diff --git a/src/crux/agent/manager_tmux.go b/src/crux/agent/manager_tmux.go index 87932ded5e..4358f9b333 100644 --- a/src/crux/agent/manager_tmux.go +++ b/src/crux/agent/manager_tmux.go @@ -11,6 +11,7 @@ import ( "time" "github.com/hivecommons/hive/crux/agent/tmux" + "github.com/hivecommons/hive/crux/claude" "github.com/hivecommons/hive/crux/config" "github.com/hivecommons/hive/crux/internal/textutil" "github.com/hivecommons/hive/crux/upstreamproxy" @@ -50,8 +51,15 @@ var defaultTmuxSocket string // global value from every process forked afterwards; the sanctioned // per-agent pair set afterwards overrides the removal for the one variable // the agent is meant to have. +// +// HIVE_CLAUDE_OAUTH_TOKEN is the operator's long-lived Claude token. It is +// delivered to claude-backend agents only, as CLAUDE_CODE_OAUTH_TOKEN via +// agentEnvPairs; under its own name it must reach no pane at all, or every +// copilot/codex/bob shell (and every tool shell they spawn) could read a +// year-long credential it has no use for. var inheritedCredentialEnvVars = []string{ "HIVE_GITHUB_TOKEN", + claude.OperatorTokenEnvVar, linearAPIKeyEnvVar, linearAccessTokenEnvVar, "LINEAR_CLIENT_ID", diff --git a/src/crux/agent/tmux_inherited_env_test.go b/src/crux/agent/tmux_inherited_env_test.go index 2b8a40b799..bf9821249a 100644 --- a/src/crux/agent/tmux_inherited_env_test.go +++ b/src/crux/agent/tmux_inherited_env_test.go @@ -62,6 +62,7 @@ func TestApplySessionEnv_RemovesInheritedCredentialsFromPanes(t *testing.T) { "HIVE_UPSTREAM_PROXY_HOSTS=ghe.corp.example", "HIVE_UPSTREAM_PROXY_NO_PROXY=10.0.0.0/8", "HIVE_NO_PROXY=10.0.0.0/8", + "HIVE_CLAUDE_OAUTH_TOKEN=sk-ant-oat01-operator_leaked", ) if out, err := start.CombinedOutput(); err != nil { t.Fatalf("starting tmux server: %v: %s", err, out) @@ -126,7 +127,7 @@ func TestApplySessionEnv_RemovesInheritedCredentialsFromPanes(t *testing.T) { "LINEAR_API_KEY", "LINEAR_CLIENT_SECRET", "LINEAR_WEBHOOK_SECRET", "HIVE_GITHUB_TOKEN", "GITHUB_TOKEN", "DASHBOARD_AUTH_TOKEN", "HIVE_DASHBOARD_TOKEN", "HIVE_TERMINAL_KEY", "HIVE_INVITE_KEY", "HIVE_HEARTBEAT_KEY", "HIVE_HUB_SECRET", "HIVE_TTYD_CREDENTIAL", "HIVE_UPSTREAM_PROXY_URL", "HIVE_UPSTREAM_PROXY_HOSTS", - "HIVE_UPSTREAM_PROXY_NO_PROXY", "HIVE_NO_PROXY", + "HIVE_UPSTREAM_PROXY_NO_PROXY", "HIVE_NO_PROXY", "HIVE_CLAUDE_OAUTH_TOKEN", } { if v, ok := after[k]; ok { t.Errorf("%s=%q still reaches a pane after applySessionEnv — the inherited credential was not removed", k, v) diff --git a/src/crux/claude/operator_token.go b/src/crux/claude/operator_token.go new file mode 100644 index 0000000000..f0f7bb3b00 --- /dev/null +++ b/src/crux/claude/operator_token.go @@ -0,0 +1,40 @@ +package claude + +import ( + "os" + "strings" +) + +const ( + // OperatorTokenEnvVar holds an operator-generated long-lived token + // (`claude setup-token`). When set, every claude-backend agent runs on it + // through CLAUDE_CODE_OAUTH_TOKEN instead of the dashboard sign-in. + OperatorTokenEnvVar = "HIVE_CLAUDE_OAUTH_TOKEN" + + // OperatorTokenFileEnvVar names a file holding the same token, for + // deployments that mount it as a secret rather than an env var. + OperatorTokenFileEnvVar = "HIVE_CLAUDE_OAUTH_TOKEN_FILE" +) + +// OperatorTokenFile is the mounted Secret key read when neither variable is +// set, mirroring the dashboard token's /secrets/dashboard-token. A var so tests +// can point it at a hermetic path. +var OperatorTokenFile = "/secrets/claude-oauth-token" + +// OperatorToken returns the operator-supplied long-lived Claude token, or "" +// when none is configured. The env var wins over the file. The value is a +// secret: callers must only hand it to an agent as a secret env pair. +func OperatorToken() string { + if v := strings.TrimSpace(os.Getenv(OperatorTokenEnvVar)); v != "" { + return v + } + path := strings.TrimSpace(os.Getenv(OperatorTokenFileEnvVar)) + if path == "" { + path = OperatorTokenFile + } + data, err := os.ReadFile(path) + if err != nil { + return "" + } + return strings.TrimSpace(string(data)) +} diff --git a/src/crux/claude/operator_token_test.go b/src/crux/claude/operator_token_test.go new file mode 100644 index 0000000000..ec3e5223ef --- /dev/null +++ b/src/crux/claude/operator_token_test.go @@ -0,0 +1,41 @@ +package claude + +import ( + "os" + "path/filepath" + "testing" +) + +func TestOperatorTokenSources(t *testing.T) { + dir := t.TempDir() + orig := OperatorTokenFile + OperatorTokenFile = filepath.Join(dir, "default-token") + t.Cleanup(func() { OperatorTokenFile = orig }) + t.Setenv(OperatorTokenEnvVar, "") + t.Setenv(OperatorTokenFileEnvVar, "") + + if got := OperatorToken(); got != "" { + t.Fatalf("unset: got %q, want empty", got) + } + + if err := os.WriteFile(OperatorTokenFile, []byte(" sk-ant-oat01-default \n"), 0o600); err != nil { + t.Fatal(err) + } + if got := OperatorToken(); got != "sk-ant-oat01-default" { + t.Fatalf("default secret file: got %q", got) + } + + named := filepath.Join(dir, "named-token") + if err := os.WriteFile(named, []byte("sk-ant-oat01-named\n"), 0o600); err != nil { + t.Fatal(err) + } + t.Setenv(OperatorTokenFileEnvVar, named) + if got := OperatorToken(); got != "sk-ant-oat01-named" { + t.Fatalf("%s: got %q", OperatorTokenFileEnvVar, got) + } + + t.Setenv(OperatorTokenEnvVar, " sk-ant-oat01-env ") + if got := OperatorToken(); got != "sk-ant-oat01-env" { + t.Fatalf("env must win over the file: got %q", got) + } +} diff --git a/src/docs/agent-configuration.md b/src/docs/agent-configuration.md index e270605f8b..49a8f6bba0 100644 --- a/src/docs/agent-configuration.md +++ b/src/docs/agent-configuration.md @@ -157,6 +157,32 @@ The dashboard API can update this field through [`POST /api/effort/{agent}/{effo The dashboard shows a reasoning-effort dropdown next to the model picker for every method that has an effort control (`codex`, `agy`, `claude`, and `omp`). The value is validated at set time against the method's own set, so a `codex`-only level such as `minimal` is refused for a `claude` agent rather than stored and dropped at launch. For `omp`, the dropdown is per selected model: Hive reads `omp models --json` and uses that model's `thinking` levels, hiding the control for models that report no thinking support. Picking `default` clears the stored value; for `claude` and `omp` that means no effort flag at all and the CLI's own default. The dropdown persists through the same path as the model picker (`hive.yaml` plus the per-agent overlay under `agents_dir`), which is the durable path on a hosted spoke: a hand edit of the agent's file is reverted by the next sync, the dashboard write is not. Each dropdown change is recorded in the audit trail as `set_reasoning_effort` with the new value, like the other per-agent setting changes. The effort the agent was actually launched with is what the run rows and the `- hive:` PR trailer report, so a `claude` agent at `xhigh` shows `effort=xhigh` there and an agent with no stored effort shows none. +#### Claude setup-token + +For `backend: claude`, an operator can use a long-lived token instead of the +dashboard sign-in. Run `claude setup-token` interactively as the licensed +operator and complete the prompts. The resulting token lasts about a year and +is inference-only; it is not a general-purpose account credential. See +[Claude Code authentication](https://code.claude.com/docs/en/authentication). + +Supply it to the Hive process as the secret `HIVE_CLAUDE_OAUTH_TOKEN`, or mount +it in a secret file readable by Hive. Set `HIVE_CLAUDE_OAUTH_TOKEN_FILE` to +that file's path, or use the default `/secrets/claude-oauth-token`. The +non-empty environment variable wins over the file. Do not put the token in +`hive.yaml`, shell history, logs, issues, or agent panes. + +Hive passes the token to Claude agents as `CLAUDE_CODE_OAUTH_TOKEN` at launch, +even when a credentials file exists. It takes precedence over dashboard sign-in; +signing in again on the dashboard does not replace it. Each agent retains its +own Claude home and private state; sharing the token does not require sharing +the whole home. Without an operator token, dashboard sign-in works as before. + +To replace an expired or revoked token, run `claude setup-token` again, update +the configured secret source, then recreate or restart Hive to load the new +token and restart the affected Claude agents so their new sessions receive +the replacement. Verify an agent completes a turn. See the +[backend auth recovery runbook](backend-auth-recovery-runbook.md). + #### Oh My Pi (`omp`) hub agents `backend: omp` launches the OMP CLI as a first-class dashboard method. Hive gives each agent its own durable HOME under `/data/home/agents/`, so `~/.omp/agent/agent.db` can hold several provider sign-ins for that one agent (for example `openai-codex` for the primary model and `anthropic` for an advisor) without sharing refresh-token writers across agents. Select models with their provider prefix (`provider/model`). The dashboard model probe runs `omp models --json` and uses each model's `thinking` list for the effort dropdown. At launch Hive passes `--approval-mode ${HIVE_OMP_APPROVAL_MODE:-yolo}`, `--model `, and `--thinking ` when set. diff --git a/src/docs/backend-auth-recovery-runbook.md b/src/docs/backend-auth-recovery-runbook.md index 5045b55ac1..76a710ea0c 100644 --- a/src/docs/backend-auth-recovery-runbook.md +++ b/src/docs/backend-auth-recovery-runbook.md @@ -51,11 +51,27 @@ recovered and no action is needed. | `backendAuthStatus` | First action | |---|---| | `unlicensed` | Check the seat at . If it is active, the hive is presenting a token the account no longer owns: follow the `/login` recovery in [troubleshooting.md](troubleshooting.md). | -| `token-expired` | If `backendAuthRefreshable` is `true` (provider `auth_state: refreshable`), restart the affected agents: Claude Code redeems the refresh grant on start and no login is needed. Otherwise run `/login` in any agent's Terminal with a licensed identity and wait about 30 seconds for the reconciler; affected agents relaunch onto the new token. | +| `token-expired` | For Claude with an operator setup token, replace it as described below; dashboard `/login` does not override it. Otherwise, if `backendAuthRefreshable` is `true` (provider `auth_state: refreshable`), restart the affected agents so Claude Code redeems the refresh grant. If not, run `/login` in any agent's Terminal with a licensed identity and wait about 30 seconds for the reconciler. | | `forbidden` | Cause is undetermined (bare 403). Read which credential was refused (dashboard model dropdown hover, or the `copilot model discovery rejected by upstream` log line's `credential` field) before re-logging in; an org policy denial is not fixed by a new login. | | `unreachable` | The inference backend is down or unroutable. Check the backend's own health and network path from the pod; re-login will not help. | | `quota` | The provider is refusing calls on quota. Wait for the window to reset, add quota, or switch the agents to another backend. Do not restart agents in a loop. | +### Replace a Claude operator token + +If `HIVE_CLAUDE_OAUTH_TOKEN` or its secret file is configured, a rejected +token may have expired or been revoked. Run `claude setup-token` interactively +as the licensed operator and complete its prompts. The replacement lasts about +a year and is inference-only. Store it securely in the same Hive environment +secret or in the file named by `HIVE_CLAUDE_OAUTH_TOKEN_FILE` (default +`/secrets/claude-oauth-token`); the non-empty environment variable takes +precedence over the file. Never paste the token into a pane, log, or report. + +Recreate or restart Hive to load the changed secret, then restart affected +Claude agents to give their new sessions the replacement. Follow the +verification steps below. A dashboard sign-in does not supersede the configured +operator token. See [Claude setup-token](agent-configuration.md#claude-setup-token) +for initial setup. + ## 3. Verify recovery 1. Within one reconciler tick (about 30 seconds) the affected agents drop diff --git a/src/docs/env-vars.md b/src/docs/env-vars.md index fd410f8a76..8f317217ad 100644 --- a/src/docs/env-vars.md +++ b/src/docs/env-vars.md @@ -295,6 +295,8 @@ and [network/credential controls](security-model.md#5-network-and-credentials). | `HIVE_BOB_API_URL` | No | `https://api.us-east.bob.ibm.com` | Bob key-test endpoint base URL override. | | `BOBSHELL_API_KEY` | Required by Bob CLI when Hive injects or contributor mode uses Bob | none | API key name read by bobshell itself. | | `COPILOT_GITHUB_TOKEN` | No | dashboard device-flow token file, if present | Copilot completion/model-discovery token and explicit agent injection. | +| `HIVE_CLAUDE_OAUTH_TOKEN` | No | none | Hive-side secret from `claude setup-token`; takes precedence over the secret file and dashboard sign-in for Claude agents. See [Claude setup-token](agent-configuration.md#claude-setup-token). | +| `HIVE_CLAUDE_OAUTH_TOKEN_FILE` | No | `/secrets/claude-oauth-token` | Path to a file containing the setup token, used when `HIVE_CLAUDE_OAUTH_TOKEN` is empty. Keep the file readable by Hive and restricted as a secret. | | `ANTHROPIC_API_KEY` | Required by `cmd/apiproxy` to inject an upstream key; agent inference backends receive a synthetic value | none | Anthropic-compatible **upstream** API key. Never used to authenticate callers of `cmd/apiproxy`. | | `PROXY_AUTH_TOKEN` | **Required** by `cmd/apiproxy`; the binary exits at startup when unset and the proxy handler returns `503` | none | **Client auth token** callers must present to `cmd/apiproxy` via `Authorization: Bearer` or `X-Api-Key`. Validated in constant time and stripped before the upstream request. Mandatory because an unauthenticated proxy would let any co-resident loopback caller spend the host `ANTHROPIC_API_KEY`. | | `CONTEXT7_API_KEY` | No | none | Optional key for Context7 knowledge API integration. | @@ -386,7 +388,7 @@ Set conditionally: | `COPILOT_GITHUB_TOKEN` | When the hive holds a Copilot auth token | Copilot OAuth token (authenticates the AI model, not GitHub writes). **Secret.** | | `GITHUB_TOKEN` | Only when App-authored PRs are enabled (`AppAuthoredPRs`), an App is configured, and the agent's mode can push | The per-agent tier-scoped App installation token, so the built-in GitHub MCP server writes as the App bot. Advisory agents have `GITHUB_TOKEN` deliberately stripped. **Secret.** | | `LINEAR_ACCESS_TOKEN` / `LINEAR_API_KEY` | ISSUES_ONLY+ agents on Linear-connected hives | See the [Linear agent integration](#linear-agent-integration) note above. | -| `CLAUDE_CODE_OAUTH_TOKEN` | Last resort: claude backend **and** no readable credential file | Dashboard-obtained access token; never injected when the agent can read (and refresh) `~/.claude/.credentials.json` itself. **Secret.** | +| `CLAUDE_CODE_OAUTH_TOKEN` | Claude backend with an operator token, or as a last resort when no credential file is readable | Hive injects the operator's setup token when configured, even if a credential file exists. Otherwise the fallback is the dashboard-obtained access token only when no credential file is readable. **Secret.** | | `BOBSHELL_API_KEY`, `BOB_API_KEY`, `BOBSHELL_DEFAULT_AUTH_TYPE` | bob backend only | The resolved Bob API key for Bob 1.x / 2.x (**secret**) and the literal `api-key` auth-type selector (non-secret by design - see the #2228 relaunch note in code). | | `HIVE_BOB_SESSION_LABEL` | bob backend only when `governor.bob.session_prefix` or `agents..bob.session_label` is set | The Bob session label also passed to Bob as `--instance-id`. A label only: `HIVE_AGENT` and all functional Hive identity are unchanged. See [agent-configuration.md](agent-configuration.md). | | `HIVE_BOB_DISPLAY_NAME` | bob backend only | Legacy alias for the Bob session label, falling back to the agent name for older scripts. Prefer `HIVE_BOB_SESSION_LABEL` when present. |