Skip to content

πŸ› Sessions: adopt a Codex or OpenCode login refreshed in a session back into the shared login - #18793

Merged
hivecommons-hive[bot] merged 8 commits into
hivecommons:v5from
Danathar:fix/session-login-adopt-back-codex-opencode
Nov 17, 2026
Merged

hivecommons-hive[bot] merged 8 commits into
hivecommons:v5from
Danathar:fix/session-login-adopt-back-codex-opencode

Conversation

@Danathar

Copy link
Copy Markdown
Contributor

A session gets a full copy of the hive's Codex and OpenCode logins. Both can hold a refresh token that rotates, so a session that refreshes its copy ends up with the only valid login, and the agents fail at their next refresh.

This PR uses the adopt-back from #18728 (Claude) for these two files. When a session holds a strictly newer login, the hive writes it into the shared file the agents link to, keeps the old file beside it, and audits it.

For the operator: agents on Codex or OpenCode recover within one poll (5 s by default) without a new sign-in, and deleting a session can no longer delete the only valid login.

Refs #18740

What this changes

  • A newer Codex ChatGPT login, or a newer OpenCode OAuth provider entry, found in a session HOME is adopted into the shared file.
  • The replaced shared file is kept as auth.json.stale-<UTC time>.
  • A user_session_login_adopted audit entry records the session, trigger, vendor and file. It never holds token material.
  • A session whose newer login cannot be adopted is not deleted. This is the same rule as for Claude.

Why

Codex agents symlink CODEX_HOME/auth.json to /data/home/.codex/auth.json. OpenCode agents symlink their data dir to the shared opencode dir. That shared file is the single owner of each login, and the agents' CLIs write their refreshes into it. A session's copy was a second holder with nothing that brought a refresh back.

How it works

The check decides "strictly newer" from the files' own freshness fields and modification times only:

  • Codex: the session's file was written after the shared one and holds a ChatGPT login with a later last_refresh and a different refresh token. The shared file must itself hold a ChatGPT login. An API-key login does not rotate and is never replaced. Only tokens, last_refresh and auth_mode are taken from the session; everything else in the shared file stays.
  • OpenCode, per provider entry: both entries are oauth, and the session's entry has a later expires and a different refresh token. Only those entries are replaced. Other entries are kept, and a provider the shared file does not hold is not added.

Example: an agent's shared Codex file has last_refresh 09:00. The session's CLI refreshes at 11:00 and rotates the token. At the next poll the shared file gets the 11:00 login, and the 09:00 file is kept as auth.json.stale-….

It runs at the same points as the Claude check: at boot, on every credential-bridge poll, at a session's start or resume, and before a session is removed. The hive never overwrites a shared file that changed after it was compared, for example when an agent's CLI wrote its own refresh in between. The new file keeps the old one's mode and, where the hive is allowed to set it, its owner.

File formats assumed, not checked against a live install. Codex: tokens.refresh_token (the hive's own authprobe.go reads the same shape) and an RFC3339 last_refresh. OpenCode: per-provider entries with type: "oauth", refresh, access and expires in milliseconds. If a CLI writes something else, the check finds no newer login and adopts nothing, which is how things work today.

Not done: a copy that cannot refresh (option 2). I could not verify, without running the CLIs, that Codex or OpenCode accepts a login file with no refresh token. So a session still holds a copy it can refresh. If a session and an agent refresh the same token within one poll, the shared file converges on the newer login at the next poll. Nothing prevents the double refresh itself. Option 2 would close that gap, but only after someone checks it against each CLI.

Files

  • src/crux/agent/usersession_login_rotating.go (new): adoptCodexLogin, adoptOpenCodeLogin, reconcileRotatingLogin, replaceSharedLogin, syncRotatingLogin, syncUserSessionRotatingLogins.
  • src/crux/agent/usersession_login.go: the manager sweep also runs the Codex/OpenCode check; the audit sink lookup is shared (loginAudit).
  • src/crux/agent/usersession_home.go: copyLoginFiles adopts first at start or resume.
  • src/crux/agent/usersession_remove.go: Remove checks these logins too; the keep-or-continue rule is now keepSessionForLogin.
  • src/crux/audit.go, src/crux/usersession_types.go: comments name the new vendors.
  • src/docs/security-model.md, src/docs/api-reference/sessions.md, changelog.d/fixed-18740-session-login-adopt-back-codex-opencode.md.

Tests

src/crux/agent/usersession_login_rotating_test.go uses synthetic credentials only. Every token carries a sentinel, and each test checks that the sentinel never appears in a log line, audit field or error.

Guarantee Test
A refresh inside a session never leaves the shared login stale TestSessionRefresh_CodexAndOpenCodeNeverLeaveTheSharedLoginStale, TestUserSessionStart_AdoptsANewerCodexLogin
Deleting a session never destroys the only valid login TestSessionRemove_NeverDestroysTheOnlyValidCodexOrOpenCodeLogin
Holders converge on one login (not prevented, see above) TestSessionLogin_ConcurrentCodexChecksConvergeOnOneLogin, TestReplaceSharedLogin_RefusesASharedFileThatChanged, TestSessionLogin_OlderSessionCodexLoginIsNeverAdopted
Decision rules TestAdoptCodexLogin, TestAdoptOpenCodeLogin

CI: this PR's own checks. Only gofmt -l was run locally, as AGENTS.md requires.

πŸ€– Generated with Claude Code

https://claude.ai/code/session_01WcWm7qFmFJp26r9LPdmi3t

…ck into the shared login

A session gets a full copy of .codex/auth.json and
.local/share/opencode/auth.json. Codex's ChatGPT login and an OpenCode
OAuth entry rotate their refresh token on refresh, so a session that
refreshed its copy held the only valid login and the shared file the agents
link to went stale.

Reuse the Claude adopt-back from hivecommons#18728 for these two files: when a session
HOME holds a strictly newer login (Codex: later last_refresh, different
refresh token; OpenCode per provider entry: later expires, different
refresh token; file written after the shared one), adopt it into the shared
file atomically, keep the replaced file as .stale-<time>, and audit
user_session_login_adopted with vendor and file. Runs at boot, on the
bridge poll, at session start/resume and before removal (a login that
cannot be adopted keeps the session). The shared file is never replaced if
it changed after it was compared.

A refresh-less copy (option 2) is not done: whether each CLI accepts a
login without its refresh token is unverified.

Refs hivecommons#18740

Signed-off-by: Danathar <6772335+Danathar@users.noreply.github.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WcWm7qFmFJp26r9LPdmi3t
@kubestellar-prow kubestellar-prow Bot added the dco-signoff: yes Indicates the PR's author has signed the DCO. label Nov 17, 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/XL Denotes a PR that changes 500-999 lines, ignoring generated files. label Nov 17, 2026
@github-actions

github-actions Bot commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

Open PR overlap check

βœ… Resolved: no conflicting open PRs or same-file overlaps remain against v5.

@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.

Security perspective, head 1428505. I read the diff and usersession_login.go around sessionClaudeLoginNewer and readSessionLogin.

1. Session-controlled freshness fields have no upper bound, and OpenCode entries are copied whole (medium).
adoptCodexLogin accepts the session file when sLast.After(hLast) (usersession_login_rotating.go:241). adoptOpenCodeLogin accepts it when s.Expires > h.Expires (:299) and then does sharedTop[provider] = sessTop[provider] (:302).
The session file is written by the sandboxed session uid, which is the less-trusted party. readSessionLogin reads it as that uid. A session can therefore write a login for a different account with last_refresh or expires set far in the future. The hive promotes it into the fleet-wide shared file that every agent links to. Every agent's traffic then goes out under that login, and no genuine refresh can ever be "newer" again.
For OpenCode the whole provider entry is copied, so any extra field in it (for example an endpoint field) also lands in the shared file.
The Claude path is only partly comparable: it gates on claudeBridgePromotable(sess, now), which takes now. These two paths take no now.

Requested change:

  • Reject a session value dated later than now plus a small skew.
  • For OpenCode, copy only the known fields (type, access, refresh, expires, plus accountId if the CLI uses it) instead of the raw entry.
-	if !ok || sRefresh == hRefresh || !sLast.After(hLast) {
+	if !ok || sRefresh == hRefresh || !sLast.After(hLast) || sLast.After(time.Now().Add(5*time.Minute)) {
-		if !ok || s.Access == "" || s.Refresh == h.Refresh || s.Expires <= h.Expires {
+		if !ok || s.Access == "" || s.Refresh == h.Refresh || s.Expires <= h.Expires ||
+			s.Expires > time.Now().Add(48*time.Hour).UnixMilli() {
 			continue
 		}
-		sharedTop[provider] = sessTop[provider]
+		clean, _ := json.Marshal(map[string]any{"type": "oauth", "access": s.Access, "refresh": s.Refresh, "expires": s.Expires})
+		sharedTop[provider] = clean

(Adjust the expiry cap to the longest real token lifetime. Add tests for a future-dated session file.)

2. Stale-file growth (low).
Each adoption keeps an auth.json.stale-<time> file (replaceSharedLogin, :397). A session that keeps writing a "newer" file produces one per poll, with no cap or pruning in this diff. Consider pruning to the last N files.

Neither item is blocking beyond item 1. The token values are not logged or audited, which is what the diff's own tests are meant to prove.

β€” hive: agent=adjudicator-4 backend=claude model=claude-sonnet-5-5 claude=2.1.326

// and, where the hive may, its owner, so every agent reaches it as before.
func replaceSharedLogin(target string, data []byte, judged os.FileInfo, now time.Time) (string, error) {
info, err := sharedfile.CheckLocation(target)
if err != nil {

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.

Session-controlled expires/last_refresh has no upper bound, and the whole provider entry is copied at :302. A session uid can inject a far-future login for another account into the fleet-wide shared file. Bound the freshness field to now+skew and copy only known fields (see the summary diff).

@hivecommons-hive

hivecommons-hive Bot commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

@Danathar this PR is back in your court (stage/072-returned-to-contributor). The hive will not merge it until the head changes.

Failing checks:

  • test (agent 4/5)

Reply here or push a new head to this branch (same sign-off); CI and the review swarm re-run automatically and the PR returns to the normal path.

Queued in your relay fix queue (8 waiting): fixes are handed out before new work as soon as you have capacity.

@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.

Delta re-review at 18e8792: the delta is a merge of v5 (198 files). The PR's own files, including src/crux/agent/usersession_login_rotating.go (375 lines, identical at both heads), are unchanged, so both earlier security findings are still present.

  1. Session-controlled freshness is unbounded: still present. In usersession_login_rotating.go:140-166 (Codex) and :192-221 (OpenCode), adoption only needs the session's last_refresh (Codex) or expires (OpenCode) to be later than the shared file's. Neither value is capped against now, and a session-written file can carry any value. A session that writes a far-future last_refresh or expires and a different refresh token replaces the fleet-wide login. Any later legitimate refresh then looks older and is never adopted. Suggested fix: in the adopt functions, reject values later than now + small skew. Pass now in from o.now() and check sLast.After(now.Add(5*time.Minute)). For OpenCode, bound s.Expires against now plus a sane maximum token lifetime.
  2. Stale-file accumulation: still present. replaceSharedLogin (:297-313) calls preserveClaudeCredential (claude_credential_bridge.go:491-515) on every adoption. That function writes a new <name>.stale-<time> file and nothing prunes it. Together with finding 1, a session can force an adoption on every poll and fill the shared home with copies of live credentials, each at mode 0600. Suggested fix: keep only the last N stale files per login, and rate-limit adoptions per session.

β€” hive: agent=adjudicator-2 backend=claude model=claude-sonnet-5-5 claude=2.1.326

return nil
}
_, hRefresh, hLast, ok := parseCodexLogin(shared)
if !ok || sRefresh == hRefresh || !sLast.After(hLast) {

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.

Freshness (sLast here, s.Expires at line 207) is session-controlled and has no upper bound. Reject values later than now plus a small skew, e.g. pass now into adopt and require !sLast.After(now.Add(5*time.Minute)).

if info == nil || !info.ModTime().Equal(judged.ModTime()) || info.Size() != judged.Size() {
return "", errSharedLoginChanged
}
stale, err := preserveClaudeCredential(target, now)

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.

Each adoption writes a new .stale-<time> copy of the credential and nothing prunes them. Keep the last N and rate-limit adoptions per session.

@hivecommons-hive

hivecommons-hive Bot commented Nov 17, 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):

Code reads correct to me; the open point is a credential trust decision, not a defect.

I read usersession_login_rotating.go in full. The adoption conditions are tight: session file newer by mtime, complete ChatGPT login, later last_refresh, different refresh token, shared file must itself be a ChatGPT login (API-key logins are never replaced); OpenCode replaces only existing oauth entries with later expires. Writes are mutex-serialised, re-check the shared file's mtime/size before replace (replaceSharedLogin), keep a .stale-<time> copy, and the audit/log paths carry no token material.

The decision: adoption promotes whatever a session HOME holds into the file every agent links to. "Newer" is judged only from the session file's own last_refresh/expires and mtime, so a session user who can write their HOME can supply a login for a different account with a future last_refresh, and it becomes the fleet's Codex/OpenCode identity. The PR cites the Claude precedent (#18728) as the same rule; if that exposure was already accepted for Claude, a one-line confirmation here covers it. The stale copy and audit entry make it recoverable, not prevented.

Also noted by the author and not a defect: sessions keep a full refreshable copy, so adopt-back narrows but does not remove the same-token double-refresh window.

Findings not on a changed line

Evidence bundle `#18793001d6ce` sha256:bd246ddba6ef876b458044d8e21997a2d69a411ce40afac90cb04bb5838499e2 β€” download from the dashboard or `hivectl review evidence #18793`.

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

@hivecommons-hive

Copy link
Copy Markdown
Contributor

Needs a decision, not a merge:

  • the reviewer swarm returned requires_human @59e39d9
  • the review found: the reviewer marked this change high-risk
  • reviewer question: @clubanderson should decide whether a session HOME's Codex/OpenCode login may overwrite the hive's shared login for every agent, given that the session side is user-writable.
  • the automerge lane will not merge this unattended

Head: verdict requires_human @59e39d9, 63/65 checks green, 2 pending, DCO yes, soak 0s of 10m0s.

How to release it:

  • After reading the verdict, a trusted merger can submit a GitHub Approve review for the current head and the lane clears the hold on its next pass; /hive approve replies on a PR are acknowledged but not consumed. An ordinary contributor cannot release their own PR.

Clear the cause and the hive re-evaluates on its next pass; the stage moves to stage/090-ready-for-human-merge, stage/095-pre-merge-soak or the merge queue on its own. Approval does not bypass CI, hold labels or other merge gates.

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/XL Denotes a PR that changes 500-999 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant