Skip to content

πŸ› [v6] claude auth: never re-bridge a credential that resolves to the shared login file - #17590

Merged
hivecommons-hive[bot] merged 2 commits into
hivecommons:v6from
Danathar:fix/claude-bridge-legacy-dirlink
Nov 10, 2026
Merged

hivecommons-hive[bot] merged 2 commits into
hivecommons:v6from
Danathar:fix/claude-bridge-legacy-dirlink

Conversation

@Danathar

Copy link
Copy Markdown
Contributor

Summary

The Claude credential bridge repair (Refs #17253) could rename the fleet's shared Claude login out from under every agent, and in one case link it to itself. That happened for an agent whose whole ~/.claude was still the old directory symlink to /data/home/.claude. Through that link the agent's "private credential" is the shared login file. This PR makes the repair resolve the link's directory first and refuse to touch a path that is, or resolves to, the shared file. The dashboard's "credential bridge broken" signal follows the same rule. Such an agent is skipped with one warning, and its next launch already replaces the directory link.

What went wrong

  • Since πŸ› agents: give each agent its own CLI memory β€” stop bridging .claude/.gemini/.bob state to the shared homeΒ #17039, each agent gets a real per-agent ~/.claude at launch, and the old whole-directory symlink is removed then. An agent that stayed paused or stopped was never relaunched, so it kept the old layout.
  • The credential watchdog runs the bridge repair every cycle over all managed agents, paused and stopped ones included. The repair builds <agent home>/.claude/.credentials.json and checks it with os.Lstat. Because the symlink is the parent directory, not the file, that Lstat sees a regular file: the shared login.
  • The repair then moves that file aside as .credentials.json.stale-<UTC>.
    • If the file has a usable token, the repair promotes the same bytes back into the shared path and the final os.Symlink fails with EEXIST. Nothing breaks, but the shared login is rewritten and a new .stale-* file is left on every cycle.
    • If the file has no token (a logged-out file), nothing is promoted, the shared path is now empty, and os.Symlink(target, link) succeeds. The result is /data/home/.claude/.credentials.json -> /data/home/.claude/.credentials.json, a symlink to itself, so every Claude agent is logged out.

Evidence from a live v6 hive: 182 .stale-* files beside the shared credential between 2026-11-08T16:41Z and 2026-11-09T19:41Z, then the self-loop at 19:41:54Z. The login detector paused every Claude agent, and the operator had to recover by hand. That hive was running a build that already included #17253. The files touched here have not changed between that build and the current v6 tip.

What changes

  • One guard, used by every path. A new helper, claudeBridgeLinkIsTarget(link, target), reports whether the link path equals the target or sits in a directory that resolves (via filepath.EvalSymlinks, then os.SameFile as a fallback for bind mounts) to the target's directory.
    • repairClaudeCredentialBridge calls it before anything is moved aside. On a match it returns an error wrapping errClaudeBridgeLinkIsTarget, so nothing is renamed, written or linked. This is the check that every repair goes through: launch, watchdog and sign-in.
    • If either directory cannot be resolved, the repair skips quietly (debug log only) instead of guessing.
    • claudeCredentialBridgeBroken (which feeds the dashboard's "credential bridge broken (private stale file)" label) applies the same rule, so the legacy layout is no longer shown as a broken bridge.
  • One warning per agent, not per cycle. rebridgeClaudeCredential turns that error into a skip and logs one WARN per agent (deduplicated with a package-level sync.Map keyed by the link path). The warning names the legacy directory link and says the next launch retires it. It is not audited, because nothing changed. The mark is cleared on any other outcome, so if the layout comes back it is logged again.
  • Docs. src/docs/agent-configuration.md gains a short paragraph about the skipped layout.

Why there is no new launch migration

#17039 already handles this at launch. In setupPerAgentCLIHome, a symlinked ~/.claude is removed (os.Remove), and the function returns early if that fails. Then mkdirAllNoFollow creates a real directory, refusing any symlinked component, and only after that does it call rebridgeClaudeCredential. So the launch path never sees the shared file through the old link. A new test pins this order. The agents on the live hive kept the old layout only because they were not relaunched while the watchdog kept visiting them.

Files

Tests

None were run locally. The repo's AGENTS.md leaves that to CI; only gofmt -l was run.

  • TestRepairClaudeCredentialBridge_LegacyDirLinkUsableSharedUntouched: old layout with a usable shared token. The repair returns errClaudeBridgeLinkIsTarget, the shared file has the same inode and bytes, and there are no .stale-* files. On the tip, the shared file is renamed aside and rewritten (new inode, one stale file).
  • TestRepairClaudeCredentialBridge_LegacyDirLinkTokenlessSharedNotSelfLinked: old layout with a token-less shared file. No symlink is created and the file stays a regular file. On the tip, this produces the self-loop.
  • TestRepairClaudeCredentialBridges_LegacyDirLinkSurvivesWatchdogCyclesWarnsOnce: four watchdog passes. Nothing is re-bridged, the shared file is untouched, the warning is logged exactly once, and there is no "repair failed" line. On the tip, every pass adds a stale file.
  • TestRepairClaudeCredentialBridge_RefusesLinkEqualToTarget: link == target is refused before anything is moved. On the tip, it renames the file and links it to itself.
  • TestClaudeCredentialBridgeBroken_LegacyDirLinkIsNotBroken: false for the old layout (true on the tip), and still true for a real per-agent .claude holding a private regular file.
  • TestSetupInteractiveHome_LegacyDirLinkLaunchRetiresBeforeRebridge: pins the launch order described above. The shared file is untouched, .claude becomes a real directory, and the credential link points at the shared file. This already passes on the tip; it guards the order.
  • TestWriteCredentialsReplacesSelfAndDanglingSymlinks (crux/claude): pins how recovery works. A dashboard sign-in's WriteCredentials renames over the path, which replaces a self-referencing or dangling symlink with a regular file holding the new tokens.

Open question (out of scope)

Why did the refresh at about 19:08Z on 2026-11-09 leave a logged-out shared file? One possibility is refresh-token rotation between agents that share one file through the old layout. This PR changes no refresh handling.

Out of scope / follow-ups

  • The "API Usage Billing" banner after a sign-in, because the sign-in omits subscriptionType.
  • Cleaning up existing .credentials.json.stale-* files. They are still never removed automatically.
  • A dashboard hint of its own for the old layout ("legacy ~/.claude link, relaunch to migrate"). No existing field fits cheaply: it would need a new field through crux.Process, the dashboard status payload, the agent card JS and the API reference. For now, the hive log warning is the signal.

Refs #17253

πŸ€– Generated with Claude Code

https://claude.ai/code/session_01BQYnPGFJx81c8JXR3o1sg1

… shared login file

An agent whose whole ~/.claude is still the legacy directory symlink to
/data/home/.claude (paused or stopped since before the per-agent split,
so no launch retired it) has a credential path that IS the shared login.
The credential watchdog walks every managed agent, so the repair saw the
shared file as a "private copy": it renamed it to .stale-<UTC> every
cycle and, when the shared file held no token, linked .credentials.json
to itself, logging every Claude agent out.

The repair now resolves the link's directory before moving anything and
refuses when the link path is, or resolves to, its target; the caller
skips that layout with one warning per agent. The dashboard's
credential-bridge-broken signal applies the same rule. The launch path
already retires the directory link before it runs the repair (hivecommons#17039),
so no new migration is added. Also pins that a sign-in's
WriteCredentials replaces a self-referencing or dangling symlink.

Refs hivecommons#17253

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BQYnPGFJx81c8JXR3o1sg1
Signed-off-by: Danathar <Danathar@users.noreply.github.com>
@kubestellar-prow kubestellar-prow Bot added the dco-signoff: yes Indicates the PR's author has signed the DCO. label Nov 10, 2026
@kubestellar-prow

Copy link
Copy Markdown
Contributor

[APPROVALNOTIFIER] This PR is NOT APPROVED

This pull-request has been approved by:
Once this PR has been reviewed and has the lgtm label, please assign clubanderson for approval. For more information see the Code Review Process.

The full list of commands accepted by this bot can be found here.

Details Needs approval from an approver in each of these files:

Approvers can indicate their approval by writing /approve in a comment
Approvers can cancel approval by writing /approve cancel in a comment

@kubestellar-prow kubestellar-prow Bot added the size/L Denotes a PR that changes 100-499 lines, ignoring generated files. label Nov 10, 2026

@hivecommons-hive hivecommons-hive Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Correctness review (head b2ec457) β€” the guard does what the body says: claudeBridgeLinkIsTarget runs before moveAsideClaudeCredential (src/crux/agent/claude_credential_bridge.go:228-238), the launch path still retires the dir link before re-bridging (src/crux/agent/interactive_home.go:414 β†’ :423 β†’ :445), and the new tests pin both the untouched-inode and warn-once behaviours. No blocker.

One low-severity behaviour change to be aware of (advisory, not blocking):

Shared .claude dir absent β†’ repair and dashboard signal both go quiet. claudeBridgeLinkIsTarget returns an error when EvalSymlinks(filepath.Dir(target)) fails (claude_credential_bridge.go:177-180). repairClaudeCredentialBridge turns that into nil, nil at debug level (:229-235), and claudeCredentialBridgeBroken returns false (:140-141). Before this PR, a real per-agent regular file with no shared dir was still moved aside and the symlink restored (dangling until the next sign-in), and the card showed "credential bridge broken". Now that agent is silently skipped every cycle and never reported. The link's own directory is known to exist (the Lstat at :218 succeeded), so a missing target dir can never be the same directory β€” it is safe to treat ErrNotExist there as "not the same" rather than "unknown":

	targetDir, err := filepath.EvalSymlinks(filepath.Dir(target))
	if err != nil {
		if errors.Is(err, fs.ErrNotExist) {
			// The link's directory exists (the caller just Lstat'ed a file in
			// it), so an absent shared directory cannot be the same one.
			return false, nil
		}
		return false, err
	}

(needs "io/fs" in the import block.) If skipping is the intended choice, consider logging at Warn rather than Debug so the lost dashboard signal has a visible replacement.

β€” hive: agent=adjudicator backend=copilot model=claude-fable-5.1 copilot=1.0.88

@hivecommons-hive

Copy link
Copy Markdown
Contributor

Review follow-ups (below review.backlog.min_severity: P2)

Non-blocking findings below the backlog filing line are listed here instead of as issues, one comment per PR, updated in place. Tick them off as they are fixed; set review.backlog.min_severity: P3 to file every finding.

  • P3 low security β€” Credential bridge repair still follows agent-controlled parent symlinks (check-then-act) (src/crux/agent/claude_credential_bridge.go:243): Pre-existing, not introduced here. repairClaudeCredentialBridge operates on link via path-based os.Lstat (line 218), os.Rename inside moveAsideClaudeCredential (line 243) and os.Symlink (line 265),…

@hivecommons-hive

hivecommons-hive Bot commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor

Hive status β€” updated in place; edits do not notify. Full history is in the Activity Monitor.

Review findings from reviewer-2 (folded here because this head already carries its hive review):

Style / idiom review (read at head b2ec457; claude_credential_bridge.go, the internal test file, manager.go, manager_tokens.go). The guard itself reads cleanly and the ordering comments make the intent obvious. One idiom divergence worth fixing before merge, one nit.

1. Once-per-agent warning state is a package global; the repo idiom is a Manager field keyed by agent name

src/crux/agent/claude_credential_bridge.go:159 adds var claudeBridgeLegacyWarned sync.Map, keyed by link path with true values (lines 380, 388). The same "log once per agent until the condition clears" pattern already exists as a Manager field: manager.go:616 appNotInstalledWarned sync.Map // agent name -> struct{}, used via LoadOrStore(agent.Name, struct{}{}) / Delete(agent.Name) in manager_tokens.go:842,860.

Why it matters beyond consistency: a process-wide map outlives any Manager, so every testManagerWithSink in the package shares one dedup set and a later test that reuses an agent name and sharedAgentHome would silently lose its warning; and an agent removed from the fleet keeps its entry forever (only a non-legacy repair outcome deletes it). Keying by agent name also matches what the watchdog iterates (RepairClaudeCredentialBridges snapshots name), and the link path is derived from the name anyway.

--- a/src/crux/agent/manager.go
+++ b/src/crux/agent/manager.go
@@ -616 +616,2 @@
 	appNotInstalledWarned    sync.Map        // agent name -> struct{}: not-installed mint failure already logged
+	claudeBridgeLegacyWarned sync.Map        // agent name -> struct{}: legacy ~/.claude dir-link skip already logged
--- a/src/crux/agent/claude_credential_bridge.go
+++ b/src/crux/agent/claude_credential_bridge.go
@@ -155,6 +155,0 @@
-// claudeBridgeLegacyWarned holds the credential links the legacy-layout skip
-// has already been logged for, so the watchdog, which walks every managed
-// agent each cycle, logs it once per agent instead of every cycle. Keyed by
-// the link path, which names the agent.
-var claudeBridgeLegacyWarned sync.Map
-
@@ -380 +374 @@
-		if _, seen := claudeBridgeLegacyWarned.LoadOrStore(link, true); !seen {
+		if _, seen := m.claudeBridgeLegacyWarned.LoadOrStore(agentName, struct{}{}); !seen {
@@ -388 +382 @@
-	claudeBridgeLegacyWarned.Delete(link)
+	m.claudeBridgeLegacyWarned.Delete(agentName)

(Advisory, not required here: that same idiom pairs the once-warning with m.observeCondition(crux.Class…, agent.Name, …) at manager_tokens.go:846, which is an existing per-agent standing signal. The PR body says no existing field fits a dashboard hint for the legacy layout; a condition class may be the cheap route for the follow-up.)

2. Nit: log attribute keys differ from the sibling lines

claude_credential_bridge.go:382 emits "dir", filepath.Dir(link), "shared", target, while the other bridge lines in the same function/file use "link", link and "target", target (lines 231, 394). Using the same keys keeps the lines greppable together.

				"agent", agentName, "trigger", trigger, "link", link, "target", target)
Evidence bundle `#175908a4efeb` sha256:ba03e22d3fdfb4e155be38fdee69737dbf2019f995748183952d0ea1e17ade28 β€” download from the dashboard or `hivectl review evidence #17590`.

@hivecommons-hive
hivecommons-hive Bot merged commit 91692c8 into hivecommons:v6 Nov 10, 2026
69 of 70 checks passed
@hivecommons-hive

Copy link
Copy Markdown
Contributor

merged by Hive trusted-author auto-merge: author @Danathar holds role owner and GitHub permission maintain on repo; CI green at 8a4efeb.

clubanderson added a commit that referenced this pull request Nov 12, 2026
…omes and harden shared-home permission handling (#17807)

Top-up of #17767 (v5 squash 0cf675d) onto v6, merged into the
credential bridge v6 already carries from #17253/#17590:

- keeps v6's dashboard surface (credentialBridgeBroken, resume after
  sign-in) and the legacy-dir-link rules;
- brings the sharedfile-based promotion, owner read through su-exec,
  newest-expiresAt rule, 5s bridge cadence
  (HIVE_CLAUDE_CREDENTIAL_BRIDGE_INTERVAL), and the fail-safe handling
  of an unreadable private file (left in place except on sign-in);
- hardens the shared-home permission guard and credential promotion
  against non-regular files (entrypoint guard, sticky shared dot-dirs,
  crux/sharedfile writer for the Claude login and Copilot config);
- a dashboard sign-in still recovers a shared credential path that is a
  dangling or self-referencing link (#17590), by unlinking it first.

Supersedes #17678 and #17748.

(cherry picked from commit 0cf675d)

Signed-off-by: Andrew Anderson <andy@clubanderson.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

dco-signoff: yes Indicates the PR's author has signed the DCO. size/L Denotes a PR that changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant