From 5574aa3698dbe3a4be97ff4864d4f5dc91b06408 Mon Sep 17 00:00:00 2001 From: "hivecommons-hive[bot]" <280983584+hivecommons-hive[bot]@users.noreply.github.com> Date: Thu, 12 Nov 2026 05:35:43 +0000 Subject: [PATCH 1/4] =?UTF-8?q?=E2=9C=A8=20claude=20auth:=20run=20Claude?= =?UTF-8?q?=20agents=20on=20an=20operator-supplied=20long-lived=20token=20?= =?UTF-8?q?(HIVE=5FCLAUDE=5FOAUTH=5FTOKEN)=20(#17762)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * ✨ claude auth: inject operator-supplied long-lived token via HIVE_CLAUDE_OAUTH_TOKEN Signed-off-by: scanner <280983584+hivecommons-hive[bot]@users.noreply.github.com> Co-authored-by: Danathar <6772335+Danathar@users.noreply.github.com> * 🐛 claude auth: honor HIVE_CLAUDE_OAUTH_TOKEN in headless launches; resync api-reference citations HeadlessCredentialEnv now applies the same precedence as agentEnvPairs: the operator-supplied long-lived token wins over the short-lived credentials snapshot, so hub-launched claude CLIs no longer pin to a token that cannot refresh. Adds a unit test for the new path. api-reference.md citations for GET /api/logs/sources and /api/logs/read resynced via check-api-reference-citations.sh --fix after the import added in api_logs.go shifted the registrations by one line. Hive-Fix-Attempt: 1/6 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Signed-off-by: scanner <280983584+hivecommons-hive[bot]@users.noreply.github.com> * 🔒 claude auth: strip HIVE_CLAUDE_OAUTH_TOKEN from every agent pane's inherited env The hive process holds HIVE_CLAUDE_OAUTH_TOKEN in its own environment, and each tmux server it starts inherits that into its GLOBAL environment, which tmux copies into every pane it forks. applySessionEnv never removed it, so copilot/codex/bob agent shells (and every tool shell they spawn) could read the year-long token under its original name — contradicting the claim that the token never appears in a pane. The claude backend was unaffected in practice only because it also receives the value as CLAUDE_CODE_OAUTH_TOKEN. Add claude.OperatorTokenEnvVar to inheritedCredentialEnvVars so the creation-time strip records a `set-environment -r` removal for it, hiding the global value from every process forked afterwards. The file form (HIVE_CLAUDE_OAUTH_TOKEN_FILE) carries only a path and is unaffected. The real-tmux leak test now plants the variable in the server env and asserts a fresh pane no longer sees it; a tmux-free unit test pins the entry in inheritedCredentialEnvVars. Hive-Fix-Attempt: 2/6 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Signed-off-by: scanner <280983584+hivecommons-hive[bot]@users.noreply.github.com> * 🌱 chore: retrigger build after buildx GHA cache BlobNotFound Signed-off-by: scanner <280983584+hivecommons-hive[bot]@users.noreply.github.com> --------- Signed-off-by: scanner <280983584+hivecommons-hive[bot]@users.noreply.github.com> Co-authored-by: scanner <280983584+hivecommons-hive[bot]@users.noreply.github.com> Co-authored-by: Danathar <6772335+Danathar@users.noreply.github.com> Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> (cherry picked from commit 8c35975f2d2cf371656e9e2c64a79e0db31397da) Signed-off-by: scanner <280983584+hivecommons-hive[bot]@users.noreply.github.com> --- changelog.d/added-claude-long-lived-token.md | 1 + src/crux/agent/claude_operator_token_test.go | 167 +++++++++++++++++++ src/crux/agent/manager.go | 2 + src/crux/agent/manager_env.go | 10 +- src/crux/agent/manager_tmux.go | 8 + src/crux/agent/tmux_inherited_env_test.go | 3 +- src/crux/claude/operator_token.go | 40 +++++ src/crux/claude/operator_token_test.go | 41 +++++ 8 files changed, 270 insertions(+), 2 deletions(-) create mode 100644 changelog.d/added-claude-long-lived-token.md create mode 100644 src/crux/agent/claude_operator_token_test.go create mode 100644 src/crux/claude/operator_token.go create mode 100644 src/crux/claude/operator_token_test.go 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/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/manager.go b/src/crux/agent/manager.go index 92102c3b9d..e8ff1a6d05 100644 --- a/src/crux/agent/manager.go +++ b/src/crux/agent/manager.go @@ -594,6 +594,7 @@ type Manager struct { // precedence for whatever fresh token the operator supplied. 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 @@ -886,6 +887,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) + } +} From 8d0a34ca740bfcdb435596223e3d73677114717e Mon Sep 17 00:00:00 2001 From: Karibhou <157208370+Karibhou@users.noreply.github.com> Date: Thu, 12 Nov 2026 06:58:52 +0100 Subject: [PATCH 2/4] =?UTF-8?q?=F0=9F=93=96=20docs:=20explain=20Claude=20s?= =?UTF-8?q?etup-token=20operator=20flow=20(#17841)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * 📖 docs: explain Claude setup-token operator flow Hive-Run: hivecommons/hive#17761 Hive-Plan: 17753 item 8 documentation Hive-Spec: 17753#docs Signed-off-by: Karibhou * chore: correct PR closing reference Remove the unrelated closing reference from the PR description; this signed follow-up requests a fresh review. Signed-off-by: Karibhou --------- Signed-off-by: Karibhou Co-authored-by: Karibhou Co-authored-by: hivecommons-hive[bot] <280983584+hivecommons-hive[bot]@users.noreply.github.com> (cherry picked from commit 7f27bbaa3859cdeb22811537d69ce24644b729fc) Signed-off-by: scanner <280983584+hivecommons-hive[bot]@users.noreply.github.com> --- src/docs/agent-configuration.md | 26 +++++++++++++++++++++++ src/docs/backend-auth-recovery-runbook.md | 18 +++++++++++++++- src/docs/env-vars.md | 4 +++- 3 files changed, 46 insertions(+), 2 deletions(-) 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. | From 794ab950903a9652c2ef74ba1f847c7fd62b2c0b Mon Sep 17 00:00:00 2001 From: "hivecommons-hive[bot]" <280983584+hivecommons-hive[bot]@users.noreply.github.com> Date: Thu, 12 Nov 2026 06:34:43 +0000 Subject: [PATCH 3/4] =?UTF-8?q?=F0=9F=90=9B=20claude=20auth:=20suspend=20t?= =?UTF-8?q?he=20credential=20re-bridge=20and=20durable-credential=20watchd?= =?UTF-8?q?og=20while=20HIVE=5FCLAUDE=5FOAUTH=5FTOKEN=20is=20set=20(#17858?= =?UTF-8?q?)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit With the operator's long-lived token set, Claude agents authenticate through CLAUDE_CODE_OAUTH_TOKEN and the shared ~/.claude/.credentials.json is not in use. The per-agent credential re-bridge (launch, watchdog poll, post-sign-in) and the watchdog's Claude probe now do nothing in that mode: no files moved, no claude_token_missing audit or warning, no broken-bridge flag in status. The suspension is logged once at startup; Copilot watching is unchanged, and with the token unset nothing changes. Fixes #17760 Signed-off-by: Andrew Anderson Signed-off-by: scanner <280983584+hivecommons-hive[bot]@users.noreply.github.com> Co-authored-by: Andrew Anderson (cherry picked from commit 9903fea75b994e36310fc97c1623f5d40e77c5cb) Signed-off-by: scanner <280983584+hivecommons-hive[bot]@users.noreply.github.com> --- ...claude-operator-token-suspends-rebridge.md | 1 + src/crux/agent/claude_credential_bridge.go | 15 +- src/crux/agent/claude_operator_token_mode.go | 53 +++++++ .../agent/claude_operator_token_mode_test.go | 138 ++++++++++++++++++ src/crux/agent/credentials_watchdog.go | 11 +- src/crux/agent/manager.go | 15 +- src/crux/agent/manager_status.go | 6 +- 7 files changed, 227 insertions(+), 12 deletions(-) create mode 100644 changelog.d/changed-claude-operator-token-suspends-rebridge.md create mode 100644 src/crux/agent/claude_operator_token_mode.go create mode 100644 src/crux/agent/claude_operator_token_mode_test.go 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 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..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 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 e8ff1a6d05..9713d21661 100644 --- a/src/crux/agent/manager.go +++ b/src/crux/agent/manager.go @@ -595,12 +595,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 ca65ffb915..6ab79433c9 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 From 4c3fa9509de03df345e65b40e13950b8a5f9830f Mon Sep 17 00:00:00 2001 From: scanner <280983584+hivecommons-hive[bot]@users.noreply.github.com> Date: Thu, 12 Nov 2026 01:58:02 -0500 Subject: [PATCH 4/4] =?UTF-8?q?=F0=9F=90=9B=20fix(claude):=20adapt=20long-?= =?UTF-8?q?lived=20token=20port=20to=20v5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit v5 has no HeadlessCredentialEnv, no /api/logs read API and no CredentialBridgeBroken status field, so those parts of the v6 commits have nothing to attach to here: the headless and log-scrub hunks were dropped during the #17762 cherry-pick, and the manager-level status override (snapshotAgent) from #17858 is removed. The operator-token-mode tests now build on v5's bridgeTestFixture/simulateClaudeRefresh helpers. Signed-off-by: scanner <280983584+hivecommons-hive[bot]@users.noreply.github.com> Co-authored-by: clubanderson <407614+clubanderson@users.noreply.github.com> --- ...claude-operator-token-suspends-rebridge.md | 2 +- src/crux/agent/claude_operator_token_mode.go | 15 ------- .../agent/claude_operator_token_mode_test.go | 39 +++++++------------ src/crux/agent/manager_status.go | 6 +-- 4 files changed, 18 insertions(+), 44 deletions(-) diff --git a/changelog.d/changed-claude-operator-token-suspends-rebridge.md b/changelog.d/changed-claude-operator-token-suspends-rebridge.md index ba13646df8..22c625b98c 100644 --- a/changelog.d/changed-claude-operator-token-suspends-rebridge.md +++ b/changelog.d/changed-claude-operator-token-suspends-rebridge.md @@ -1 +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) +- 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_operator_token_mode.go b/src/crux/agent/claude_operator_token_mode.go index 990e945cdb..76898bd3ea 100644 --- a/src/crux/agent/claude_operator_token_mode.go +++ b/src/crux/agent/claude_operator_token_mode.go @@ -1,7 +1,5 @@ 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 @@ -38,16 +36,3 @@ func (m *Manager) logClaudeOperatorTokenModeOnce() { "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 index 9e3de15606..e34eb37464 100644 --- a/src/crux/agent/claude_operator_token_mode_test.go +++ b/src/crux/agent/claude_operator_token_mode_test.go @@ -17,26 +17,23 @@ import ( // 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) + 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 - 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")) + 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, -// nothing is audited, and the status no longer flags the bridge as broken. +// and nothing is audited. func TestClaudeOperatorTokenMode_RebridgeIsSuspended(t *testing.T) { - m, sink, ap, link, target, logs := operatorModeFixture(t) + m, sink, _, link, target, logs := operatorModeFixture(t) sharedBefore, err := os.ReadFile(target) if err != nil { t.Fatal(err) @@ -51,7 +48,7 @@ func TestClaudeOperatorTokenMode_RebridgeIsSuspended(t *testing.T) { t.Fatalf("trigger %s: RepairClaudeCredentialBridges = %v, want none in operator-token mode", trigger, got) } } - if rep := m.rebridgeClaudeCredential("architect", link, target, claudeBridgeTriggerLaunch); rep != nil { + if rep := m.rebridgeClaudeCredential("scanner", link, target, claudeBridgeTriggerLaunch); rep != nil { t.Fatalf("launch re-bridge ran in operator-token mode: %+v", rep) } m.rebridgeClaudeCredentialsAfterSignIn() @@ -71,12 +68,6 @@ func TestClaudeOperatorTokenMode_RebridgeIsSuspended(t *testing.T) { 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()) } @@ -115,17 +106,15 @@ func TestClaudeOperatorTokenMode_WatchdogClaudeProbeIsSuspended(t *testing.T) { } // 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. +// link and the watchdog probes Claude. func TestClaudeOperatorTokenMode_UnsetKeepsTodaysBehaviour(t *testing.T) { - m, sink, ap, _, _, logs := operatorModeFixture(t) + m, sink, _, link, target, 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) + 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) diff --git a/src/crux/agent/manager_status.go b/src/crux/agent/manager_status.go index 6ab79433c9..ca65ffb915 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 := m.snapshotAgent(agent) + snap := agent.snapshot() 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 := m.snapshotAgent(agent) + snap := agent.snapshot() 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 := m.snapshotAgent(v) + snap := v.snapshot() result[k] = &snap } return result