Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
1 change: 1 addition & 0 deletions changelog.d/added-claude-long-lived-token.md
Original file line number Diff line number Diff line change
@@ -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.
Original file line number Diff line number Diff line change
@@ -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)
15 changes: 14 additions & 1 deletion src/crux/agent/claude_credential_bridge.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
38 changes: 38 additions & 0 deletions src/crux/agent/claude_operator_token_mode.go
Original file line number Diff line number Diff line change
@@ -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")
})
}
127 changes: 127 additions & 0 deletions src/crux/agent/claude_operator_token_mode_test.go
Original file line number Diff line number Diff line change
@@ -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")
}
}
167 changes: 167 additions & 0 deletions src/crux/agent/claude_operator_token_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
11 changes: 9 additions & 2 deletions src/crux/agent/credentials_watchdog.go
Original file line number Diff line number Diff line change
Expand Up @@ -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())
Expand Down Expand Up @@ -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)
Expand Down
Loading
Loading