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..ba13646df8 --- /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, and the dashboard no longer flags the unused bridge as broken. 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 1d9e4bc10e..c6e94c3bfa 100644 --- a/src/crux/agent/claude_credential_bridge.go +++ b/src/crux/agent/claude_credential_bridge.go @@ -540,6 +540,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 @@ -613,8 +621,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..990e945cdb --- /dev/null +++ b/src/crux/agent/claude_operator_token_mode.go @@ -0,0 +1,53 @@ +package agent + +import "github.com/hivecommons/hive/crux" + +// 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") + }) +} + +// snapshotAgent is the manager's view of an agent's status. It is +// a.snapshot() with the one manager-level adjustment: in operator-token mode +// the Claude credential bridge is not in use, so a replaced link is not +// reported as broken — the dashboard would otherwise prompt a repair the hive +// has deliberately stopped doing. +func (m *Manager) snapshotAgent(a *AgentProcess) crux.Process { + snap := a.snapshot() + if snap.CredentialBridgeBroken && m.claudeOperatorTokenMode() { + snap.CredentialBridgeBroken = false + } + return snap +} 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..9e3de15606 --- /dev/null +++ b/src/crux/agent/claude_operator_token_mode_test.go @@ -0,0 +1,138 @@ +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() + shared := withSharedAgentHome(t) + m, sink := testManagerWithSink(t) + var logs bytes.Buffer + m.logger = slog.New(slog.NewTextHandler(&logs, &slog.HandlerOptions{Level: slog.LevelDebug})) + m.claudeOperatorToken = operatorTokenSentinel + ap := &AgentProcess{Name: "architect", UID: 2001, Config: config.AgentConfig{Backend: "claude"}} + m.mu.Lock() + m.agents["architect"] = ap + m.mu.Unlock() + link, target := brokenBridgeFixture(t, shared, "architect", + fakeClaudeCredential("fake-shared-access", time.Now().Add(8*time.Hour), "fake-shared-refresh"), + fakeClaudeCredential("fake-private-access", time.Now().Add(time.Hour), "fake-private-refresh")) + 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, +// nothing is audited, and the status no longer flags the bridge as broken. +func TestClaudeOperatorTokenMode_RebridgeIsSuspended(t *testing.T) { + m, sink, ap, 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("architect", 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 m.snapshotAgent(ap).CredentialBridgeBroken { + t.Error("status must not flag the unused bridge as broken in operator-token mode") + } + if !ap.snapshot().CredentialBridgeBroken { + t.Error("fixture sanity: the raw snapshot should still see the replaced link") + } + 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, the status reports it until then, and the watchdog probes Claude. +func TestClaudeOperatorTokenMode_UnsetKeepsTodaysBehaviour(t *testing.T) { + m, sink, ap, _, _, logs := operatorModeFixture(t) + m.claudeOperatorToken = "" + + if !m.snapshotAgent(ap).CredentialBridgeBroken { + t.Fatal("status must report the replaced link when no operator token is set") + } + if got := m.RepairClaudeCredentialBridges(claudeBridgeTriggerWatchdog); len(got) != 1 || got[0] != "architect" { + t.Fatalf("RepairClaudeCredentialBridges = %v, want [architect]", got) + } + 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/credentials_watchdog.go b/src/crux/agent/credentials_watchdog.go index 502316fce7..b437f808ab 100644 --- a/src/crux/agent/credentials_watchdog.go +++ b/src/crux/agent/credentials_watchdog.go @@ -226,7 +226,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()) @@ -261,8 +267,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 a1524e8bbf..cd2ec3ec53 100644 --- a/src/crux/agent/manager.go +++ b/src/crux/agent/manager.go @@ -610,12 +610,15 @@ type Manager struct { copilotAuthTokenRejected bool claudeAuthToken string claudeOperatorToken string // HIVE_CLAUDE_OAUTH_TOKEN, read once at construction; a dashboard sign-in never replaces it - 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) + // 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 diff --git a/src/crux/agent/manager_status.go b/src/crux/agent/manager_status.go index 295146ff98..725ed62c84 100644 --- a/src/crux/agent/manager_status.go +++ b/src/crux/agent/manager_status.go @@ -112,7 +112,7 @@ func (m *Manager) GetStatusFast(name string) (*crux.Process, error) { m.mu.RUnlock() return nil, fmt.Errorf("agent %s not found", name) } - snap := agent.snapshot() + snap := m.snapshotAgent(agent) m.mu.RUnlock() m.statusSnapMu.Lock() @@ -146,7 +146,7 @@ func (m *Manager) GetStatus(name string) (*crux.Process, error) { if !ok { return nil, fmt.Errorf("agent %s not found", name) } - snap := agent.snapshot() + snap := m.snapshotAgent(agent) return &snap, nil } @@ -199,7 +199,7 @@ func (m *Manager) AllStatuses() map[string]*crux.Process { result := make(map[string]*crux.Process, len(m.agents)) for k, v := range m.agents { m.refreshBusyVisibilityLocked(v, now) - snap := v.snapshot() + snap := m.snapshotAgent(v) result[k] = &snap } return result