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/fixed-claude-shared-credentials.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
- Claude auth on per-UID hives: a Claude Code token refresh writes a temp file and renames it over `~/.claude/.credentials.json`, which replaced the per-agent symlink to the shared login with a private 0600 file; the refreshed token (and the rotated refresh grant) never reached the shared credential and the fleet logged out about every eight hours. The hive now detects the replaced link at agent launch, every 5s from the credential watchdog (`HIVE_CLAUDE_CREDENTIAL_BRIDGE_INTERVAL`) and after a dashboard sign-in, reads the agent's private file as its owner through `su-exec` when the server cannot open it, publishes the newer usable token into the shared login (the previous shared file is kept as `.credentials.json.stale-<ts>`), moves the private copy aside and restores the link. Per-agent `~/.claude` memory stays isolated; only the login is shared, with no operator switch. Audited as `claude_credential_rebridged`. Also hardens the shared-home permission guard and credential promotion against non-regular files: shared logins and CLI configs are written through a randomly named temporary with fd-based mode/owner, the root guard only repairs regular files in regular directories, and the shared dot-dirs get the sticky bit.
447 changes: 326 additions & 121 deletions src/crux/agent/claude_credential_bridge.go

Large diffs are not rendered by default.

140 changes: 54 additions & 86 deletions src/crux/agent/claude_credential_bridge_internal_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,87 +3,81 @@ package agent
import (
"bytes"
"errors"
"fmt"
"log/slog"
"os"
"path/filepath"
"strings"
"syscall"
"testing"
"time"

"github.com/hivecommons/hive/crux/claude"
"github.com/hivecommons/hive/crux/config"
)

// TestRepairClaudeCredentialBridge_PromotionKeepsSharedOwner: the promoted
// shared credential is written by the hive process, so without a chown it would
// belong to whoever runs hive. It must keep the owner and group of the file it
// replaces. The chown is a seam so this runs without root or real agent uids.
func TestRepairClaudeCredentialBridge_PromotionKeepsSharedOwner(t *testing.T) {
shared := withSharedAgentHome(t)
m, _ := testManagerWithSink(t)
now := time.Now()
link, target := brokenBridgeFixture(t, shared, "coder",
fakeClaudeCredential("fake-old-access", now.Add(-time.Hour), "fake-old-refresh"),
fakeClaudeCredential("fake-new-access", now.Add(8*time.Hour), "fake-new-refresh"))
info, err := os.Stat(target)
if err != nil {
// Fixture helpers shared by the tests in this file (the v6 #17253 suite).
// fakeClaudeCredential is a credentials file in the on-disk shape Claude Code
// writes, with fake token strings.
func fakeClaudeCredential(access string, expiresAt time.Time, refresh string) string {
return fmt.Sprintf(`{"claudeAiOauth":{"accessToken":%q,"refreshToken":%q,"expiresAt":%d,"scopes":["user:inference"]}}`,
access, refresh, expiresAt.UnixMilli())
}

// brokenBridgeFixture lays out a per-agent home whose credential symlink a
// token refresh has replaced: the shared credential holds sharedJSON and the
// agent's .claude/.credentials.json is a REGULAR file holding agentJSON, mode
// 0600 as the CLI writes it. Returns (link, target).
func brokenBridgeFixture(t *testing.T, shared, agentName, sharedJSON, agentJSON string) (string, string) {
t.Helper()
target := filepath.Join(shared, ".claude", ".credentials.json")
if err := os.MkdirAll(filepath.Dir(target), 0o755); err != nil {
t.Fatal(err)
}
st := info.Sys().(*syscall.Stat_t)

type chownCall struct {
path string
uid, gid int
if sharedJSON != "" {
if err := os.WriteFile(target, []byte(sharedJSON), 0o660); err != nil {
t.Fatal(err)
}
}
var calls []chownCall
orig := chownClaudeCredential
chownClaudeCredential = func(path string, uid, gid int) error {
calls = append(calls, chownCall{path, uid, gid})
return nil
link := filepath.Join(shared, "agents", agentName, ".claude", ".credentials.json")
if err := os.MkdirAll(filepath.Dir(link), 0o700); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(link, []byte(agentJSON), 0o600); err != nil {
t.Fatal(err)
}
t.Cleanup(func() { chownClaudeCredential = orig })
return link, target
}

rep := m.rebridgeClaudeCredential("coder", link, target, claudeBridgeTriggerWatchdog)
if rep == nil || rep.kept != "agent" {
t.Fatalf("repair = %+v, want kept=agent", rep)
func assertBridgeRestored(t *testing.T, link, target string) {
t.Helper()
info, err := os.Lstat(link)
if err != nil {
t.Fatalf("credential link missing after repair: %v", err)
}
if len(calls) != 1 || calls[0].uid != int(st.Uid) || calls[0].gid != int(st.Gid) {
t.Fatalf("chown calls = %+v, want one call with the previous shared owner %d:%d", calls, st.Uid, st.Gid)
if info.Mode()&os.ModeSymlink == 0 {
t.Fatalf("%s is still a regular file (mode %v); the bridge was not restored", link, info.Mode())
}
if filepath.Dir(calls[0].path) != filepath.Dir(target) {
t.Errorf("chown applied to %q, want the replacement written beside %q", calls[0].path, target)
if got, _ := os.Readlink(link); got != target {
t.Fatalf("credential link -> %q, want %q", got, target)
}
}

// TestRepairClaudeCredentialBridge_StaleNamesNeverCollide: two repairs in the
// same second must not overwrite the first moved-aside file.
func TestRepairClaudeCredentialBridge_StaleNamesNeverCollide(t *testing.T) {
shared := withSharedAgentHome(t)
m, _ := testManagerWithSink(t)
fixed := time.Date(2026, 11, 7, 14, 54, 0, 0, time.UTC)
orig := claudeBridgeNow
claudeBridgeNow = func() time.Time { return fixed }
t.Cleanup(func() { claudeBridgeNow = orig })

sharedJSON := fakeClaudeCredential("fake-shared-access", time.Now().Add(8*time.Hour), "fake-shared-refresh")
link, target := brokenBridgeFixture(t, shared, "tester", sharedJSON,
fakeClaudeCredential("fake-first-access", time.Now().Add(time.Hour), "fake-first-refresh"))
m.rebridgeClaudeCredential("tester", link, target, claudeBridgeTriggerWatchdog)

// The CLI refreshes again within the same second.
if err := os.Remove(link); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(link, []byte(fakeClaudeCredential("fake-second-access", time.Now().Add(time.Hour), "fake-second-refresh")), 0o600); err != nil {
// staleFiles lists the moved-aside credentials in dir.
func staleFiles(t *testing.T, dir string) []string {
t.Helper()
matches, err := filepath.Glob(filepath.Join(dir, ".credentials.json.stale-*"))
if err != nil {
t.Fatal(err)
}
m.rebridgeClaudeCredential("tester", link, target, claudeBridgeTriggerWatchdog)
return matches
}

if got := staleFiles(t, filepath.Dir(link)); len(got) != 2 {
t.Fatalf("want two distinct moved-aside files, got %v", got)
func readFileString(t *testing.T, path string) string {
t.Helper()
b, err := os.ReadFile(path)
if err != nil {
t.Fatal(err)
}
assertBridgeRestored(t, link, target)
return string(b)
}

// TestAgentSnapshot_ReportsCredentialBridgeBroken: the status the dashboard
Expand Down Expand Up @@ -117,32 +111,6 @@ func TestAgentSnapshot_ReportsCredentialBridgeBroken(t *testing.T) {
}
}

// TestPreferAgentClaudeCredential pins the "newer AND usable" rule.
func TestPreferAgentClaudeCredential(t *testing.T) {
now := time.Now()
tok := func(exp time.Duration, refresh string) *claude.OAuthTokens {
return &claude.OAuthTokens{AccessToken: "fake", RefreshToken: refresh, ExpiresAt: now.Add(exp).UnixMilli()}
}
cases := []struct {
name string
agent, shared *claude.OAuthTokens
want bool
}{
{"agent newer and live", tok(8*time.Hour, "r"), tok(time.Hour, "r"), true},
{"shared newer", tok(time.Hour, "r"), tok(8*time.Hour, "r"), false},
{"tie keeps shared", tok(time.Hour, "r"), tok(time.Hour, "r"), false},
{"agent expired but refreshable, shared absent", tok(-time.Hour, "r"), nil, true},
{"agent unusable, shared absent", tok(-time.Hour, ""), nil, false},
{"agent usable, shared unusable", tok(-time.Minute, "r"), tok(-2*time.Hour, ""), true},
{"agent absent", nil, tok(time.Hour, "r"), false},
}
for _, c := range cases {
if got := preferAgentClaudeCredential(c.agent, c.shared, now); got != c.want {
t.Errorf("%s: got %v, want %v", c.name, got, c.want)
}
}
}

// legacyDirLinkFixture lays out the pre-#17031 layout that the launch path
// retires but the credential watchdog still walks for a paused or stopped
// agent: the agent's whole ~/.claude is a directory symlink to the shared
Expand Down Expand Up @@ -213,7 +181,7 @@ func TestRepairClaudeCredentialBridge_LegacyDirLinkUsableSharedUntouched(t *test
sharedJSON := fakeClaudeCredential("fake-shared-access", time.Now().Add(8*time.Hour), "fake-shared-refresh")
link, target, before := legacyDirLinkFixture(t, shared, "reviewer", 2005, sharedJSON)

rep, err := m.repairClaudeCredentialBridge("reviewer", link, target)
rep, err := m.repairClaudeCredentialBridge("reviewer", link, target, claudeBridgeTriggerWatchdog)
if rep != nil || !errors.Is(err, errClaudeBridgeLinkIsTarget) {
t.Fatalf("repair = (%+v, %v), want (nil, errClaudeBridgeLinkIsTarget)", rep, err)
}
Expand All @@ -237,7 +205,7 @@ func TestRepairClaudeCredentialBridge_LegacyDirLinkTokenlessSharedNotSelfLinked(
const sharedJSON = `{}`
link, target, before := legacyDirLinkFixture(t, shared, "scanner", 2003, sharedJSON)

if _, err := m.repairClaudeCredentialBridge("scanner", link, target); !errors.Is(err, errClaudeBridgeLinkIsTarget) {
if _, err := m.repairClaudeCredentialBridge("scanner", link, target, claudeBridgeTriggerWatchdog); !errors.Is(err, errClaudeBridgeLinkIsTarget) {
t.Fatalf("repair error = %v, want errClaudeBridgeLinkIsTarget", err)
}
assertSharedCredentialUntouched(t, target, before, sharedJSON)
Expand Down Expand Up @@ -291,7 +259,7 @@ func TestRepairClaudeCredentialBridge_RefusesLinkEqualToTarget(t *testing.T) {
t.Fatal(err)
}

rep, err := m.repairClaudeCredentialBridge("coder", target, target)
rep, err := m.repairClaudeCredentialBridge("coder", target, target, claudeBridgeTriggerWatchdog)
if rep != nil || !errors.Is(err, errClaudeBridgeLinkIsTarget) {
t.Fatalf("repair = (%+v, %v), want (nil, errClaudeBridgeLinkIsTarget)", rep, err)
}
Expand Down
Loading
Loading