diff --git a/changelog.d/security-18740-session-codex-opencode-refreshless.md b/changelog.d/security-18740-session-codex-opencode-refreshless.md new file mode 100644 index 0000000000..002e8f5cad --- /dev/null +++ b/changelog.d/security-18740-session-codex-opencode-refreshless.md @@ -0,0 +1 @@ +- **Sessions: Codex and OpenCode logins are copied without a refresh token.** A session's copy of `.codex/auth.json` and `opencode/auth.json` now keeps the refresh key (both CLIs require it) but empties its value, like the Claude login since #18724, so the CLI in a session can no longer rotate the fleet's Codex or OpenCode login and race an agent's refresh into two diverged logins. The shared file the agents link to is the only refreshable holder; the hive replaces each session's copy when that file changes, adopts a complete newer login found in a session (a copy from an earlier release, or a sign-in inside the session) and then puts the session back on a refresh-less copy. A session now depends on an agent or a sign-in refreshing that login before its access token expires ([#18740](https://github.com/hivecommons/hive/issues/18740)). diff --git a/src/crux/agent/usersession_home.go b/src/crux/agent/usersession_home.go index 7346493ef7..324add64bc 100644 --- a/src/crux/agent/usersession_home.go +++ b/src/crux/agent/usersession_home.go @@ -23,9 +23,10 @@ import ( // session write access to the shared file (and, for settings.json, a hook that // every agent would run). Instead a fixed allowlist of the minimal login // files per vendor (userSessionLoginFiles) is COPIED into the session HOME as -// read-only (0400), session-owned files; the Claude login is copied without -// its refresh token, so a session can never rotate the fleet's login -// (usersession_login.go). Nothing that can execute a command +// read-only (0400), session-owned files; the Claude, Codex and OpenCode +// logins are copied without their refresh tokens, so a session can never +// rotate the fleet's login (usersession_login.go, +// usersession_login_rotating.go). Nothing that can execute a command // (settings.json, hooks, MCP/extension config) is ever copied, and ~/.config // (gh's hosts.yml, goose extensions) is not bridged at all. const ( @@ -168,10 +169,11 @@ func (r *UserSessionRuntime) prepareSandbox(id string, uid int) error { // refresh token, and a newer login already in the session HOME is adopted // into the shared file first (usersession_login.go). // -// A Codex or OpenCode login the session's CLI refreshed is adopted into the -// shared file first when it is strictly newer (usersession_login_rotating.go). +// Codex and OpenCode logins follow the same rules: the session gets them with +// the refresh token emptied, and a strictly newer login in the session HOME is +// adopted into the shared file first (usersession_login_rotating.go). // -// For every vendor but Claude the copy is skipped when the session's file was +// For the other vendors the copy is skipped when the session's file was // written after the shared one. That is the state of an unchanged copy from // an earlier start, and also of a login the CLI in the session rewrote itself // (a token refresh): re-copying an older shared file over it on a resume @@ -187,10 +189,12 @@ func (r *UserSessionRuntime) copyLoginFiles(id string, uid int) { continue } if l, ok := rotatingSessionLoginFor(rel); ok { - // A login the session's CLI refreshed (Codex, OpenCode) goes into - // the shared file first (usersession_login_rotating.go). Reported - // inside; a failure must not block the session. - _ = r.syncRotatingLogin(id, sessionLoginTriggerStart, l) + // Codex and OpenCode: a newer login in the session goes into the + // shared file first, and the session gets a refresh-less copy + // (usersession_login_rotating.go). Reported inside; a failure + // must not block the session. + _ = r.syncRotatingLogin(id, sessionLoginTriggerStart, l, sessionLoginModeStart) + continue } src := filepath.Join(sharedAgentHome, rel) dest := filepath.Join(home, rel) diff --git a/src/crux/agent/usersession_isolation_test.go b/src/crux/agent/usersession_isolation_test.go index e8b45b1e87..c8e9702a69 100644 --- a/src/crux/agent/usersession_isolation_test.go +++ b/src/crux/agent/usersession_isolation_test.go @@ -294,6 +294,11 @@ func TestUserSessionLoginsAreCopiedNeverSymlinkedOrBridgedConfig(t *testing.T) { // (usersession_login.go); the fixture is synthetic. content = string(bridgeTestCreds(t, "shared", time.Now().Add(time.Hour).UnixMilli())) } + if l, ok := rotatingSessionLoginFor(rel); ok { + // Codex and OpenCode logins are copied only when they parse as a + // login of that vendor (usersession_login_rotating.go). + content = string(rotatingTestVendors()[l.vendor].login("shared", time.Now())) + } writeSharedLogin(t, rel, content) } // Files that execute commands or hold unrelated secrets must never travel. diff --git a/src/crux/agent/usersession_login.go b/src/crux/agent/usersession_login.go index ad04e8bc00..1c04cb4901 100644 --- a/src/crux/agent/usersession_login.go +++ b/src/crux/agent/usersession_login.go @@ -239,18 +239,27 @@ func (o sessionLoginOps) writeSessionLogin(home, path, target string) (bool, err if !ok { return false, nil } + if err := o.writeSessionCopy(home, path, copyBytes); err != nil { + return false, err + } + return true, nil +} + +// writeSessionCopy replaces the session's login file at path with data, +// atomically, read-only (0400) and as the session's own uid. +func (o sessionLoginOps) writeSessionCopy(home, path string, data []byte) error { uid, err := o.sessionUID(home) if err != nil { - return false, err + return err } ctx, cancel := context.WithTimeout(context.Background(), userSessionCmdTimeout) defer cancel() // The script writes nothing to its output, so the output is safe to keep // in the error. - if out, err := o.priv(ctx, userSessionSpec(uid), bytes.NewReader(copyBytes), "sh", "-c", userSessionCopyLoginScript, "sh", path); err != nil { - return false, outputErr("writing the session's login copy", err, out) + if out, err := o.priv(ctx, userSessionSpec(uid), bytes.NewReader(data), "sh", "-c", userSessionCopyLoginScript, "sh", path); err != nil { + return outputErr("writing the session's login copy", err, out) } - return true, nil + return nil } // fileModTime is the modification time of path, zero when it cannot be read. diff --git a/src/crux/agent/usersession_login_rotating.go b/src/crux/agent/usersession_login_rotating.go index 58f646f2f7..78b80cc001 100644 --- a/src/crux/agent/usersession_login_rotating.go +++ b/src/crux/agent/usersession_login_rotating.go @@ -1,6 +1,7 @@ package agent import ( + "bytes" "encoding/json" "errors" "fmt" @@ -15,37 +16,50 @@ import ( "github.com/hivecommons/hive/crux/sharedfile" ) -// Codex and OpenCode logins in a session HOME, adopted back into the shared -// login when a session refreshed them (#18740, a follow-up to #18724). +// Codex and OpenCode logins in a session HOME: what a session is given, and +// how a login that still ends up there gets back to the shared login (#18740, +// a follow-up to #18724). // -// A session gets a plain copy of these two files (userSessionLoginFiles). -// Both can hold a ROTATING refresh token: Codex's ChatGPT login, and an -// OpenCode provider entry of type "oauth". When the CLI in a session refreshes -// its copy, the refresh rotates the token, the session's copy becomes the -// only valid login, and the shared file every agent uses is left stale. The -// agents link to that shared file (Codex: each agent's CODEX_HOME/auth.json -// is a symlink to it, setupCodexHome; OpenCode: each agent's -// $XDG_DATA_HOME/opencode is a symlink to the shared directory, -// xdgDataSharedBridges), so the shared file is the single owner of each -// login, and the CLIs of the agents write their own refreshes into it. +// Both files can hold a ROTATING refresh token: Codex's ChatGPT login, and an +// OpenCode provider entry of type "oauth". The agents link to the shared file +// (Codex: each agent's CODEX_HOME/auth.json is a symlink to it, +// setupCodexHome; OpenCode: each agent's $XDG_DATA_HOME/opencode is a symlink +// to the shared directory, xdgDataSharedBridges), so the shared file is the +// single owner of each login, and the CLIs of the agents write their own +// refreshes into it. A session used to get a full copy: when the CLI in the +// session refreshed it, the refresh rotated the token, the session's copy +// became a second, diverging holder of the grant, and a session refresh and +// an agent refresh in the same window left two logins of which at most one +// still worked. // -// The fix here is ADOPT-BACK, the same safety net usersession_login.go has for -// Claude: when a session's file holds a strictly newer login than the shared -// file, that login is written into the shared file atomically, the replaced -// shared file is kept beside it as ".stale-", and -// user_session_login_adopted is audited. 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's sandbox is removed (a login that -// cannot be adopted keeps the sandbox). +// The same three rules as the Claude login (usersession_login.go): // -// What a session is NOT given here, unlike Claude, is a copy that cannot -// refresh. Codex (tokens.refresh_token) and OpenCode (an oauth entry's -// refresh) both treat the refresh token as a required field, so a copy -// without it, or with a placeholder, would log the person out of the session -// (#18740). The session keeps a full copy; adopt-back makes the fleet -// converge on the newest login within one poll, and it never writes the -// session's copy. It does not stop a session and an agent refreshing the same -// token in the same few seconds. +// 1. A session is never a refresh holder. Its copy is the shared file with +// every refresh token EMPTIED (sessionCodexLogin, sessionOpenCodeLogin). +// The key stays: both CLIs require it in their login file, but accept an +// empty value; the CLI then keeps using the access token and a refresh it +// attempts fails without rotating anything. Nothing else changes, so the +// session sees the fleet's account, mode and API-key entries as before. +// 2. The session's copy follows the shared login. When the shared file was +// written after the copy (an agent refreshed, an operator signed in), the +// copy is replaced, atomically and as the session's uid. A session +// therefore depends on an agent or a sign-in refreshing the shared login +// before its access token expires; it cannot refresh it itself. +// 3. A login that is in a session HOME anyway (a full copy from an earlier +// release, refreshed there, or a person signing in inside the session) is +// never lost and never left to diverge: when it is strictly newer than the +// shared file it is ADOPTED into it atomically, the replaced shared file +// is kept beside it as ".stale-", and +// user_session_login_adopted is audited. The session is then put back on +// a refresh-less copy. A full copy carrying the shared file's own refresh +// token is put on a refresh-less copy too. A refresh token the shared +// file does not hold and that is not adoptable is the session's own login +// and is left alone. +// +// 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's sandbox is removed (a login that cannot be adopted keeps the +// sandbox). // // "Strictly newer" is decided from the files' own freshness fields and // modification times only: @@ -71,8 +85,8 @@ const ( userSessionOpenCodeLoginRel = ".local/share/opencode/auth.json" ) -// rotatingSessionLogin is one vendor login a session holds as a full copy -// whose refresh token rotates. +// rotatingSessionLogin is one vendor login whose refresh token rotates. A +// session holds it only as a refresh-less copy. type rotatingSessionLogin struct { rel string // relative to HOME, in the session and in the shared home vendor string // for logs and the audit detail @@ -80,13 +94,23 @@ type rotatingSessionLogin struct { // strictly newer login than shared, nil when there is nothing to adopt. // It never logs and never returns token material in an error. adopt func(sess, shared []byte, sessMod, sharedMod time.Time) []byte + // sessionCopy returns what a session is given for the shared file: the + // same file with every refresh token emptied. ok is false when shared is + // not a login file of this vendor; such a file is not handed out. + sessionCopy func(shared []byte) ([]byte, bool) + // refreshTokens returns every non-empty refresh token data holds. + refreshTokens func(data []byte) []string } var rotatingSessionLogins = []rotatingSessionLogin{ - {rel: userSessionCodexLoginRel, vendor: "codex", adopt: adoptCodexLogin}, - {rel: userSessionOpenCodeLoginRel, vendor: "opencode", adopt: adoptOpenCodeLogin}, + {rel: userSessionCodexLoginRel, vendor: "codex", adopt: adoptCodexLogin, sessionCopy: sessionCodexLogin, refreshTokens: codexRefreshTokens}, + {rel: userSessionOpenCodeLoginRel, vendor: "opencode", adopt: adoptOpenCodeLogin, sessionCopy: sessionOpenCodeLogin, refreshTokens: openCodeRefreshTokens}, } +// emptyJSONString is the value a session copy holds in place of a refresh +// token: the key both CLIs require, with nothing to redeem. +var emptyJSONString = json.RawMessage(`""`) + // rotatingSessionLoginFor returns the rotating login stored at rel. func rotatingSessionLoginFor(rel string) (rotatingSessionLogin, bool) { for _, l := range rotatingSessionLogins { @@ -98,8 +122,9 @@ func rotatingSessionLoginFor(rel string) (rotatingSessionLogin, bool) { } // sessionRotatingLoginMu serialises every read-compare-write of a rotating -// shared login made by the hive (the manager's poll, a session's start and -// its removal), so two sessions holding newer logins settle on the later one. +// login made by the hive (the manager's poll, a session's start and its +// removal), so two sessions holding newer logins settle on the later one and +// a copy is never written from a shared file another check is replacing. // The agents' CLIs write the shared file without it; replaceSharedLogin // refuses to replace a shared file that changed after it was judged. var sessionRotatingLoginMu sync.Mutex @@ -167,6 +192,47 @@ func adoptCodexLogin(sess, shared []byte, sessMod, sharedMod time.Time) []byte { return append(out, '\n') } +// sessionCodexLogin implements rotatingSessionLogin.sessionCopy for Codex: +// the shared file with tokens.refresh_token emptied. A file without a tokens +// block (an API-key login) is handed out unchanged in content. +func sessionCodexLogin(shared []byte) ([]byte, bool) { + if len(shared) > claudeBridgeMaxCredentialBytes { + return nil, false + } + var top map[string]json.RawMessage + if err := json.Unmarshal(shared, &top); err != nil || top == nil { + return nil, false + } + if raw, ok := top["tokens"]; ok { + var tokens map[string]json.RawMessage + if err := json.Unmarshal(raw, &tokens); err != nil { + return nil, false + } + if _, has := tokens["refresh_token"]; has { + tokens["refresh_token"] = emptyJSONString + b, err := json.Marshal(tokens) + if err != nil { + return nil, false + } + top["tokens"] = b + } + } + out, err := json.MarshalIndent(top, "", " ") + if err != nil { + return nil, false + } + return append(out, '\n'), true +} + +// codexRefreshTokens implements rotatingSessionLogin.refreshTokens for Codex. +func codexRefreshTokens(data []byte) []string { + var f codexLoginFile + if json.Unmarshal(data, &f) != nil || f.Tokens == nil || f.Tokens.RefreshToken == "" { + return nil + } + return []string{f.Tokens.RefreshToken} +} + // ---- OpenCode // openCodeAuthEntry is the part of one OpenCode auth.json provider entry the @@ -222,17 +288,89 @@ func adoptOpenCodeLogin(sess, shared []byte, sessMod, sharedMod time.Time) []byt return out } +// sessionOpenCodeLogin implements rotatingSessionLogin.sessionCopy for +// OpenCode: the shared file with the refresh token of every "oauth" entry +// emptied. Every other entry (API keys, well-known logins) is kept as it is. +func sessionOpenCodeLogin(shared []byte) ([]byte, bool) { + if len(shared) > claudeBridgeMaxCredentialBytes { + return nil, false + } + var top map[string]json.RawMessage + if err := json.Unmarshal(shared, &top); err != nil || top == nil { + return nil, false + } + for provider, raw := range top { + var entry map[string]json.RawMessage + if json.Unmarshal(raw, &entry) != nil || entry == nil { + continue + } + var typ string + if json.Unmarshal(entry["type"], &typ) != nil || typ != "oauth" { + continue + } + if _, has := entry["refresh"]; !has { + continue + } + entry["refresh"] = emptyJSONString + b, err := json.Marshal(entry) + if err != nil { + return nil, false + } + top[provider] = b + } + out, err := json.MarshalIndent(top, "", " ") + if err != nil { + return nil, false + } + return out, true +} + +// openCodeRefreshTokens implements rotatingSessionLogin.refreshTokens for +// OpenCode: the refresh token of every "oauth" entry that has one. +func openCodeRefreshTokens(data []byte) []string { + var top map[string]json.RawMessage + if json.Unmarshal(data, &top) != nil { + return nil + } + var out []string + for _, raw := range top { + if e, ok := openCodeOAuthEntry(raw); ok { + out = append(out, e.Refresh) + } + } + return out +} + +// refreshTokenOverlap reports whether sess holds a refresh token shared does +// not (the session's own login) and whether it holds one shared does too (a +// full copy of the shared login). Only equality is used. +func refreshTokenOverlap(sess, shared []string) (own, copied bool) { + for _, s := range sess { + found := false + for _, h := range shared { + if s == h { + found = true + break + } + } + if found { + copied = true + } else { + own = true + } + } + return own, copied +} + // ---- the check // rotatingLoginKey is the sessionLoginCache key of one session's rotating // login; the Claude check keys the same cache by the bare session id. func rotatingLoginKey(id, rel string) string { return id + "\x00" + rel } -// reconcileRotatingLogin adopts a strictly newer login of one vendor from a -// session HOME into the shared file. The session's copy is never written: -// after an adoption it holds the same login as the shared file. The caller -// holds sessionRotatingLoginMu. -func (o sessionLoginOps) reconcileRotatingLogin(id string, l rotatingSessionLogin) (sessionLoginResult, error) { +// reconcileRotatingLogin applies the three rules of the file comment to one +// vendor login of one session. The caller holds sessionRotatingLoginMu. +func (o sessionLoginOps) reconcileRotatingLogin(id string, l rotatingSessionLogin, mode sessionLoginMode) (sessionLoginResult, error) { var none sessionLoginResult home := userSessionHome(id) path := filepath.Join(home, l.rel) @@ -240,7 +378,18 @@ func (o sessionLoginOps) reconcileRotatingLogin(id string, l rotatingSessionLogi info, err := os.Lstat(path) if errors.Is(err, fs.ErrNotExist) { - return none, nil + if mode != sessionLoginModeStart { + return none, nil + } + shared, ok := readLoginSource(target) + if !ok { + return none, nil + } + written, werr := o.writeRotatingCopy(home, path, l, []byte(shared)) + if werr != nil || !written { + return none, werr + } + return sessionLoginResult{action: sessionLoginInstalled}, nil } if err != nil { return none, fmt.Errorf("inspecting the session's %s login: %w", l.vendor, err) @@ -250,23 +399,26 @@ func (o sessionLoginOps) reconcileRotatingLogin(id string, l rotatingSessionLogi } sharedInfo, err := os.Lstat(target) if errors.Is(err, fs.ErrNotExist) { - // No shared login to split from. + // No shared login to split from or to follow. return none, nil } if err != nil { return none, fmt.Errorf("inspecting the shared %s login: %w", l.vendor, err) } - if !info.ModTime().After(sharedInfo.ModTime()) { - // Not written after the shared file: an unchanged copy, or one an - // adoption already settled. Nothing is read. - return none, nil - } + sessNewer := info.ModTime().After(sharedInfo.ModTime()) if !sharedInfo.Mode().IsRegular() { + if !sessNewer { + return none, nil + } // The session's file may hold the newest login, and the shared one // is nothing hive could compare or replace: report it, so a removal // keeps the session. return none, fmt.Errorf("%w: the shared %s login %s is not a regular file", sharedfile.ErrUnsafeLocation, l.vendor, target) } + if !sessNewer && mode == sessionLoginModeRemove { + // Nothing to adopt, and the copy is about to be deleted. + return none, nil + } data, err := o.readSessionLogin(home, path) if errors.Is(err, fs.ErrNotExist) { return none, nil @@ -281,15 +433,61 @@ func (o sessionLoginOps) reconcileRotatingLogin(id string, l rotatingSessionLogi if err != nil { return none, fmt.Errorf("reading the shared %s login: %w", l.vendor, err) } - merged := l.adopt(data, shared, info.ModTime(), sharedInfo.ModTime()) - if merged == nil { + if sessNewer { + if merged := l.adopt(data, shared, info.ModTime(), sharedInfo.ModTime()); merged != nil { + stale, err := replaceSharedLogin(target, merged, sharedInfo, o.now()) + if err != nil { + return none, fmt.Errorf("%w (%s); adopting it failed: %w", crux.ErrUserSessionHoldsLogin, l.vendor, err) + } + res := sessionLoginResult{action: sessionLoginAdopted, staleShared: stale} + if mode == sessionLoginModeRemove { + return res, nil + } + // The session stops being a second refresh holder. A failure here + // loses nothing: the login is in the shared file, and the next + // check replaces the copy. + if _, werr := o.writeRotatingCopy(home, path, l, merged); werr != nil { + return res, fmt.Errorf("the %s login was adopted, but the session's copy could not be replaced: %w", l.vendor, werr) + } + return res, nil + } + } + if mode == sessionLoginModeRemove { return none, nil } - stale, err := replaceSharedLogin(target, merged, sharedInfo, o.now()) - if err != nil { - return none, fmt.Errorf("%w (%s); adopting it failed: %w", crux.ErrUserSessionHoldsLogin, l.vendor, err) + own, copied := refreshTokenOverlap(l.refreshTokens(data), l.refreshTokens(shared)) + if own { + // A refresh token the shared login does not hold and that was not + // adoptable: the session's own login, left alone. + return none, nil } - return sessionLoginResult{action: sessionLoginAdopted, staleShared: stale}, nil + if sessNewer && !copied { + // A refresh-less copy the shared login has not moved past. + return none, nil + } + want, ok := l.sessionCopy(shared) + if !ok || bytes.Equal(want, data) { + return none, nil + } + written, werr := o.writeRotatingCopy(home, path, l, shared) + if werr != nil || !written { + return none, werr + } + return sessionLoginResult{action: sessionLoginRefreshed}, nil +} + +// writeRotatingCopy replaces the session's copy with the refresh-less form of +// shared, as the session's uid. written is false, with no error, when shared +// is not a login that can be handed out. +func (o sessionLoginOps) writeRotatingCopy(home, path string, l rotatingSessionLogin, shared []byte) (bool, error) { + copyBytes, ok := l.sessionCopy(shared) + if !ok { + return false, nil + } + if err := o.writeSessionCopy(home, path, copyBytes); err != nil { + return false, err + } + return true, nil } // replaceSharedLogin writes data over the shared login target, keeping the @@ -315,10 +513,10 @@ func replaceSharedLogin(target string, data []byte, judged os.FileInfo, now time } // checkRotatingLogin runs one check under sessionRotatingLoginMu. -func (o sessionLoginOps) checkRotatingLogin(id string, l rotatingSessionLogin) (sessionLoginResult, error) { +func (o sessionLoginOps) checkRotatingLogin(id string, l rotatingSessionLogin, mode sessionLoginMode) (sessionLoginResult, error) { sessionRotatingLoginMu.Lock() defer sessionRotatingLoginMu.Unlock() - return o.reconcileRotatingLogin(id, l) + return o.reconcileRotatingLogin(id, l, mode) } // reportRotatingLogin logs and audits one check. Only an adoption is @@ -338,6 +536,9 @@ func reportRotatingLogin(logger *slog.Logger, audit func(action string, fields m "stale_shared_file", res.staleShared, )) } + } else if res.action != "" { + logger.Debug("user session login: session copy brought up to date with the shared login", + "session", id, "trigger", trigger, "vendor", l.vendor, "action", res.action) } if err != nil { logger.Warn("user session login: check failed", "session", id, "trigger", trigger, "vendor", l.vendor, "error", err) @@ -345,8 +546,8 @@ func reportRotatingLogin(logger *slog.Logger, audit func(action string, fields m } // syncRotatingLogin checks one session's login of one vendor and reports it. -func (r *UserSessionRuntime) syncRotatingLogin(id, trigger string, l rotatingSessionLogin) error { - res, err := r.loginOps().checkRotatingLogin(id, l) +func (r *UserSessionRuntime) syncRotatingLogin(id, trigger string, l rotatingSessionLogin, mode sessionLoginMode) error { + res, err := r.loginOps().checkRotatingLogin(id, l, mode) reportRotatingLogin(r.logger, r.loginAudit(), id, trigger, l, res, err) return err } @@ -368,7 +569,7 @@ func (m *Manager) syncUserSessionRotatingLogins(id, trigger string, ops sessionL if !m.sessionLogins.due(key, stamp, now, force) { continue } - res, err := ops.checkRotatingLogin(id, l) + res, err := ops.checkRotatingLogin(id, l, sessionLoginModeWatch) reportRotatingLogin(m.logger, func(action string, fields map[string]any) { m.audit(action, "", fields) }, id, trigger, l, res, err) if after, aok := sessionLoginStampOf(path, target); aok { m.sessionLogins.record(key, after, now) diff --git a/src/crux/agent/usersession_login_rotating_copy_test.go b/src/crux/agent/usersession_login_rotating_copy_test.go new file mode 100644 index 0000000000..bb43f43753 --- /dev/null +++ b/src/crux/agent/usersession_login_rotating_copy_test.go @@ -0,0 +1,330 @@ +package agent + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "io" + "os" + "path/filepath" + "strings" + "sync" + "testing" + "time" +) + +// Every credential in this file is synthetic: each token string carries +// bridgeTestTokenSentinel (see usersession_login_rotating_test.go). + +// A session's copy of a Codex or OpenCode login keeps every field but the +// refresh token, whose key stays (both CLIs require it) with nothing in it. +func TestSessionRotatingLoginCopy_EmptiesEveryRefreshToken(t *testing.T) { + now := time.Now() + cases := []struct { + name string + copyFn func([]byte) ([]byte, bool) + shared []byte + wantOK bool + // check inspects the decoded copy. + check func(t *testing.T, top map[string]any) + }{ + { + name: "codex ChatGPT login", copyFn: sessionCodexLogin, + shared: []byte(strings.Replace(string(codexTestLogin("shared", now)), `"OPENAI_API_KEY": null`, `"OPENAI_API_KEY": null, "future_field": 7`, 1)), + wantOK: true, + check: func(t *testing.T, top map[string]any) { + tokens, _ := top["tokens"].(map[string]any) + if tokens["refresh_token"] != "" || tokens["access_token"] != testAccess("shared") || + tokens["id_token"] != "id-shared-"+bridgeTestTokenSentinel || tokens["account_id"] != "account-test" { + t.Errorf("tokens = %v", tokens) + } + if top["auth_mode"] != "chatgpt" || top["last_refresh"] == nil || top["future_field"] != float64(7) { + t.Error("the copy dropped a field other than the refresh token") + } + }, + }, + { + name: "codex API-key login", copyFn: sessionCodexLogin, + shared: []byte(`{"OPENAI_API_KEY":"sk-` + bridgeTestTokenSentinel + `"}`), + wantOK: true, + check: func(t *testing.T, top map[string]any) { + if top["OPENAI_API_KEY"] != "sk-"+bridgeTestTokenSentinel { + t.Error("an API-key login was changed") + } + }, + }, + {name: "codex not JSON", copyFn: sessionCodexLogin, shared: []byte("not a login")}, + {name: "codex tokens not an object", copyFn: sessionCodexLogin, shared: []byte(`{"tokens":"x"}`)}, + { + name: "opencode oauth and api entries", copyFn: sessionOpenCodeLogin, + shared: []byte(fmt.Sprintf(`{"anthropic":%s,"openai":%s,"openrouter":{"type":"api","key":"key-fleet"},"odd":[1]}`, + openCodeTestEntry("a", now), openCodeTestEntry("o", now))), + wantOK: true, + check: func(t *testing.T, top map[string]any) { + for _, p := range []string{"anthropic", "openai"} { + e, _ := top[p].(map[string]any) + if e["refresh"] != "" || e["type"] != "oauth" || e["access"] == "" || e["expires"] == nil { + t.Errorf("%s entry = %v", p, e) + } + } + if e, _ := top["openrouter"].(map[string]any); e["key"] != "key-fleet" { + t.Error("an API-key entry was changed") + } + if top["odd"] == nil { + t.Error("an entry hive does not understand was dropped") + } + }, + }, + {name: "opencode not JSON", copyFn: sessionOpenCodeLogin, shared: []byte("[]")}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + out, ok := c.copyFn(c.shared) + if ok != c.wantOK { + t.Fatalf("ok = %v, want %v", ok, c.wantOK) + } + if !ok { + return + } + if bytes.Contains(out, []byte(`"ref-`)) { + t.Error("the copy carries a refresh token") + } + var top map[string]any + if err := json.Unmarshal(out, &top); err != nil { + t.Fatal(err) + } + c.check(t, top) + }) + } +} + +// The CLI in a session cannot write a refresh that diverges from the shared +// login, whatever its copy goes through. Each case sets up the session's file +// after a start and runs one manager sweep; the shared file must change only +// by an adoption of a strictly newer full login, and the session must end on +// a refresh-less copy unless the file is a login of the session's own. +func TestSessionRotatingLogin_SessionCannotWriteADivergingRefresh(t *testing.T) { + type setup struct { + // session is what the session's file holds before the sweep, nil to + // keep the copy the start made; sessionMod is its modification time. + session func(v rotatingTestVendor, now time.Time) []byte + sessionMod time.Duration + // agent, when set, is an agent refresh of the shared file before the + // sweep, written at agentMod. + agent bool + agentMod time.Duration + } + cases := []struct { + name string + setup + wantAdopted bool + wantSharedTag string // the login the shared file must end on + wantSessionTag string // the access token of the session's refresh-less copy; "" = left alone + }{ + { + name: "the CLI rewrites its refresh-less copy (a failed refresh)", + setup: setup{session: refreshlessRewrite, sessionMod: time.Minute}, + wantSharedTag: "shared", + }, + { + name: "an agent refreshed the shared login", + setup: setup{agent: true, agentMod: time.Hour}, + wantSharedTag: "agent", + wantSessionTag: "agent", + }, + { + name: "a full copy from an earlier release", + setup: setup{session: func(v rotatingTestVendor, now time.Time) []byte { + return v.login("shared", now.Add(-2*time.Hour)) + }, sessionMod: time.Minute}, + wantSharedTag: "shared", + wantSessionTag: "shared", + }, + { + name: "a full copy refreshed in the session", + setup: setup{session: func(v rotatingTestVendor, now time.Time) []byte { + return v.login("rotated", now.Add(8*time.Hour)) + }, sessionMod: time.Minute}, + wantAdopted: true, + wantSharedTag: "rotated", + wantSessionTag: "rotated", + }, + { + name: "a full copy refreshed in the session, but an agent refreshed later", + setup: setup{session: func(v rotatingTestVendor, now time.Time) []byte { + return v.login("rotated", now.Add(8*time.Hour)) + }, sessionMod: time.Minute, agent: true, agentMod: time.Hour}, + wantSharedTag: "agent", + }, + } + for vendor, v := range rotatingTestVendors() { + for _, c := range cases { + t.Run(vendor+"/"+c.name, func(t *testing.T) { + f := newSessionLoginFixture(t) + now := time.Now() + target := filepath.Join(sharedAgentHome, v.rel) + writeLoginAt(t, target, v.login("shared", now.Add(-2*time.Hour)), now.Add(-time.Hour)) + f.start(t) + path := filepath.Join(userSessionHome(testSessionID), v.rel) + assertRotatingRefreshless(t, v.rel, path, testAccess("shared")) + var before []byte + if c.session != nil { + before = c.session(v, now) + writeLoginAt(t, path, before, now.Add(c.sessionMod)) + } + if c.agent { + writeLoginAt(t, target, v.login("agent", now.Add(16*time.Hour)), now.Add(c.agentMod)) + } + + f.m.syncUserSessionClaudeLogins(sessionLoginTriggerSignIn) + + if got := len(f.adoptionsOf(vendor)); (got == 1) != c.wantAdopted || got > 1 { + t.Errorf("%d adoptions, want adopted=%v", got, c.wantAdopted) + } + access, _, _ := rotatingAccessAndRefresh(t, v.rel, mustRead(t, target)) + if access != testAccess(c.wantSharedTag) { + t.Errorf("the shared login is not the %q login", c.wantSharedTag) + } + if c.wantSessionTag != "" { + assertRotatingRefreshless(t, v.rel, path, testAccess(c.wantSessionTag)) + } else if before != nil && !bytes.Equal(mustRead(t, path), before) { + t.Error("a session file hive must leave alone was rewritten") + } + f.assertNoTokenMaterial(t) + }) + } + } +} + +// refreshlessRewrite is the session's copy as a CLI might rewrite it after a +// refresh it could not make: still refresh-less, with later freshness fields. +func refreshlessRewrite(v rotatingTestVendor, now time.Time) []byte { + l, _ := rotatingSessionLoginFor(v.rel) + out, _ := l.sessionCopy(v.login("shared", now.Add(24*time.Hour))) + return out +} + +// safeSessionPriv is a goroutine-safe stand-in for su-exec that only knows the +// login copy script, writing the copy as the script does: a temporary renamed +// over the destination, mode 0400. +func safeSessionPriv(_ context.Context, _ string, stdin io.Reader, argv ...string) ([]byte, error) { + if len(argv) < 5 || argv[0] != "sh" || argv[2] != userSessionCopyLoginScript { + return nil, fmt.Errorf("unexpected helper %q", argv) + } + data, err := io.ReadAll(stdin) + if err != nil { + return nil, err + } + dest := argv[4] + tmp, err := os.CreateTemp(filepath.Dir(dest), ".hive-new-*") + if err != nil { + return nil, err + } + if _, err := tmp.Write(data); err != nil { + _ = tmp.Close() + return nil, err + } + if err := tmp.Close(); err != nil { + return nil, err + } + if err := os.Chmod(tmp.Name(), 0o400); err != nil { + return nil, err + } + return nil, os.Rename(tmp.Name(), dest) +} + +// Agents refresh the shared login (the single owner) while the hive's sweep +// and session starts check the session's copy concurrently. The shared file +// must only ever hold what an agent wrote, never be replaced by the hive, and +// the session must end on a refresh-less copy of the last agent refresh. +func TestSessionRotatingLogin_ConcurrentAgentRefreshStaysTheSingleSource(t *testing.T) { + const ( + agentRefreshes = 20 + checkers = 4 + ) + for vendor, v := range rotatingTestVendors() { + t.Run(vendor, func(t *testing.T) { + f := newSessionLoginFixture(t) + now := time.Now() + target := filepath.Join(sharedAgentHome, v.rel) + writeLoginAt(t, target, v.login("shared", now.Add(-2*time.Hour)), now.Add(-time.Hour)) + f.start(t) + path := filepath.Join(userSessionHome(testSessionID), v.rel) + useSessionLoginPriv(t, safeSessionPriv) + ops := sessionLoginOps{priv: safeSessionPriv, statUID: func(string) (int, error) { return testSessionUID, nil }, now: time.Now} + l, _ := rotatingSessionLoginFor(v.rel) + + agentWrites := map[string]bool{} + for i := 1; i <= agentRefreshes; i++ { + agentWrites[string(v.login(fmt.Sprintf("agent%d", i), now.Add(time.Duration(i)*time.Hour)))] = true + } + var wg sync.WaitGroup + done := make(chan struct{}) + errs := make(chan error, agentRefreshes+checkers) + wg.Add(1) + go func() { + defer wg.Done() + defer close(done) + for i := 1; i <= agentRefreshes; i++ { + // An agent's CLI writes the shared file the way the CLIs + // do: a temporary renamed over it, a later mtime each time. + data := v.login(fmt.Sprintf("agent%d", i), now.Add(time.Duration(i)*time.Hour)) + mod := now.Add(time.Duration(i) * time.Hour) + tmp := target + ".agent-tmp" + if err := os.WriteFile(tmp, data, 0o600); err != nil { + errs <- err + return + } + if err := os.Chtimes(tmp, mod, mod); err != nil { + errs <- err + return + } + if err := os.Rename(tmp, target); err != nil { + errs <- err + return + } + } + }() + for i := 0; i < checkers; i++ { + wg.Add(1) + go func(i int) { + defer wg.Done() + for { + select { + case <-done: + return + default: + } + if i%2 == 0 { + f.m.syncUserSessionClaudeLogins(sessionLoginTriggerSignIn) + } else { + _, _ = ops.checkRotatingLogin(testSessionID, l, sessionLoginModeStart) + } + // The shared file only ever holds an agent's write. + if data, err := os.ReadFile(target); err == nil && !agentWrites[string(data)] && !bytes.Equal(data, v.login("shared", now.Add(-2*time.Hour))) { + errs <- fmt.Errorf("the shared login holds something no agent wrote") + return + } + } + }(i) + } + wg.Wait() + close(errs) + for err := range errs { + t.Error(err) + } + f.m.syncUserSessionClaudeLogins(sessionLoginTriggerSignIn) + + last := v.login(fmt.Sprintf("agent%d", agentRefreshes), now.Add(agentRefreshes*time.Hour)) + if !bytes.Equal(mustRead(t, target), last) { + t.Error("the shared login is not the last agent refresh") + } + if f.adoptions() != 0 || len(staleFilesBeside(t, target)) != 0 { + t.Error("the hive replaced the shared login although no session held a newer one") + } + assertRotatingRefreshless(t, v.rel, path, testAccess(fmt.Sprintf("agent%d", agentRefreshes))) + f.assertNoTokenMaterial(t) + }) + } +} diff --git a/src/crux/agent/usersession_login_rotating_test.go b/src/crux/agent/usersession_login_rotating_test.go index d9e3722aa7..213064fdf3 100644 --- a/src/crux/agent/usersession_login_rotating_test.go +++ b/src/crux/agent/usersession_login_rotating_test.go @@ -80,6 +80,63 @@ func openCodeRefresh(t *testing.T, path, provider string) string { return e.Refresh } +// rotatingAccessAndRefresh returns the access token and the refresh token of +// the vendor's login in data (OpenCode: the "anthropic" entry) and whether +// the refresh key is present at all. It accepts a refresh-less copy. +func rotatingAccessAndRefresh(t *testing.T, rel string, data []byte) (access, refresh string, hasKey bool) { + t.Helper() + switch rel { + case userSessionCodexLoginRel: + var f struct { + Tokens map[string]*string `json:"tokens"` + } + if err := json.Unmarshal(data, &f); err != nil || f.Tokens == nil { + t.Fatalf("not a Codex ChatGPT login: %v", err) + } + if a := f.Tokens["access_token"]; a != nil { + access = *a + } + r, ok := f.Tokens["refresh_token"] + if ok && r != nil { + refresh = *r + } + return access, refresh, ok + case userSessionOpenCodeLoginRel: + var top map[string]map[string]any + if err := json.Unmarshal(data, &top); err != nil || top["anthropic"] == nil { + t.Fatalf("not an OpenCode login with an anthropic entry: %v", err) + } + e := top["anthropic"] + access, _ = e["access"].(string) + r, ok := e["refresh"] + refresh, _ = r.(string) + return access, refresh, ok + } + t.Fatalf("no rotating login at %s", rel) + return "", "", false +} + +// assertRotatingRefreshless fails unless the session's copy at path is a +// refresh-less copy holding wantAccess: the refresh key kept (both CLIs +// require it) with nothing in it, and no refresh token anywhere in the file. +func assertRotatingRefreshless(t *testing.T, rel, path, wantAccess string) { + t.Helper() + raw := mustRead(t, path) + access, refresh, hasKey := rotatingAccessAndRefresh(t, rel, raw) + l, _ := rotatingSessionLoginFor(rel) + if refresh != "" || !hasKey || len(l.refreshTokens(raw)) != 0 || bytes.Contains(raw, []byte(`"ref-`)) { + t.Error("the session's copy carries a refresh token (or lost the required key): the session could rotate the fleet's login") + } + if access != wantAccess { + t.Error("the session's copy does not hold the expected access token") + } + if st, err := os.Lstat(path); err != nil || st.Mode().Perm() != 0o400 { + t.Errorf("the session's copy is not read-only: %v", err) + } +} + +func testAccess(tag string) string { return "acc-" + tag + "-" + bridgeTestTokenSentinel } + // rotatingTestVendor drives one vendor through the shared scenarios. type rotatingTestVendor struct { rel string @@ -219,9 +276,7 @@ func TestSessionRefresh_CodexAndOpenCodeNeverLeaveTheSharedLoginStale(t *testing writeLoginAt(t, target, v.login("shared", now.Add(-2*time.Hour)), now.Add(-time.Hour)) f.start(t) path := filepath.Join(userSessionHome(testSessionID), v.rel) - if got := v.refresh(t, path); got != "ref-shared-"+bridgeTestTokenSentinel { - t.Fatal("the session did not get the shared login") - } + assertRotatingRefreshless(t, v.rel, path, testAccess("shared")) if len(f.adoptionsOf(vendor)) != 0 { t.Fatal("a plain start adopted a login") } @@ -254,20 +309,20 @@ func TestSessionRefresh_CodexAndOpenCodeNeverLeaveTheSharedLoginStale(t *testing if !bytes.Equal(mustRead(t, target), before) || len(f.adoptionsOf(vendor)) != 1 { t.Error("the login did not settle after one adoption") } - if got := v.refresh(t, path); got != "ref-rotated-"+bridgeTestTokenSentinel { - t.Error("the session lost the login it refreshed") - } + // The session keeps using the login it refreshed, now as a + // refresh-less copy of the shared file. + assertRotatingRefreshless(t, v.rel, path, testAccess("rotated")) f.assertNoTokenMaterial(t) }) } } // The shared login stays the single owner of the refresh token (#18740): an -// adoption moves the session's login INTO the shared file and never writes -// the session's own copy, so after it exactly one file the hive manages -// holds the refreshed token as its authority, and a later agent refresh of -// the shared file is not undone by the session's older copy. -func TestSessionRefresh_AdoptionNeverWritesTheSessionCopy(t *testing.T) { +// adoption moves the session's login INTO the shared file and puts the +// session back on a refresh-less copy, so after it exactly one file the hive +// manages holds the refreshed token, and a later agent refresh of the shared +// file reaches the session and is not undone by it. +func TestSessionRefresh_AdoptionPutsTheSessionBackOnARefreshlessCopy(t *testing.T) { for vendor, v := range rotatingTestVendors() { t.Run(vendor, func(t *testing.T) { f := newSessionLoginFixture(t) @@ -277,33 +332,23 @@ func TestSessionRefresh_AdoptionNeverWritesTheSessionCopy(t *testing.T) { f.start(t) path := filepath.Join(userSessionHome(testSessionID), v.rel) writeLoginAt(t, path, v.login("rotated", now.Add(8*time.Hour)), now) - sessBefore := mustRead(t, path) - infoBefore, err := os.Stat(path) - if err != nil { - t.Fatal(err) - } f.m.syncUserSessionClaudeLogins(sessionLoginTriggerWatchdog) if len(f.adoptionsOf(vendor)) != 1 { t.Fatal("the session's refreshed login was not adopted") } - infoAfter, err := os.Stat(path) - if err != nil { - t.Fatal(err) - } - if !bytes.Equal(mustRead(t, path), sessBefore) || !infoAfter.ModTime().Equal(infoBefore.ModTime()) { - t.Error("an adoption wrote the session's own copy") - } + assertRotatingRefreshless(t, v.rel, path, testAccess("rotated")) - // An agent refreshes the shared login afterwards: the session's - // older copy must not take it back. + // An agent refreshes the shared login afterwards: the session + // must follow it and must not take it back. agent := v.login("agent", now.Add(16*time.Hour)) - writeLoginAt(t, target, agent, now.Add(time.Minute)) + writeLoginAt(t, target, agent, now.Add(time.Hour)) f.m.syncUserSessionClaudeLogins(sessionLoginTriggerSignIn) f.r.copyLoginFiles(testSessionID, testSessionUID) if !bytes.Equal(mustRead(t, target), agent) || len(f.adoptionsOf(vendor)) != 1 { t.Error("the session's older copy displaced the agents' newer shared login") } + assertRotatingRefreshless(t, v.rel, path, testAccess("agent")) f.assertNoTokenMaterial(t) }) } @@ -503,7 +548,7 @@ func TestSessionLogin_ConcurrentCodexChecksConvergeOnOneLogin(t *testing.T) { wg.Add(2) go func(id string) { defer wg.Done() - _, _ = ops.checkRotatingLogin(id, codex) + _, _ = ops.checkRotatingLogin(id, codex, sessionLoginModeWatch) }(id) go func() { defer wg.Done() diff --git a/src/crux/agent/usersession_login_test.go b/src/crux/agent/usersession_login_test.go index b33f00b9c6..e4bad2bcb8 100644 --- a/src/crux/agent/usersession_login_test.go +++ b/src/crux/agent/usersession_login_test.go @@ -585,12 +585,12 @@ func TestSessionLogin_ConcurrentChecksConvergeOnOneLogin(t *testing.T) { } } -// Other vendors' logins are still plain copies, but a resume no longer -// replaces a file the session's CLI rewrote after the shared one was written -// (a token refresh inside the session) with the older shared file. +// Logins that do not rotate (Copilot, Gemini) are still plain copies, but a +// resume no longer replaces a file the session's CLI rewrote after the shared +// one was written with the older shared file. func TestUserSessionLoginCopy_KeepsASessionFileNewerThanTheSharedOne(t *testing.T) { f := newSessionLoginFixture(t) - const rel = ".codex/auth.json" + const rel = ".copilot/config.json" src := filepath.Join(sharedAgentHome, rel) now := time.Now() writeLoginAt(t, src, []byte("fleet-login-1"), now.Add(-time.Hour)) diff --git a/src/crux/agent/usersession_remove.go b/src/crux/agent/usersession_remove.go index 5e7f6f2e87..d423091d92 100644 --- a/src/crux/agent/usersession_remove.go +++ b/src/crux/agent/usersession_remove.go @@ -82,7 +82,7 @@ func (r *UserSessionRuntime) Remove(id string) error { // The same for a Codex or OpenCode login the session's CLI refreshed // (usersession_login_rotating.go). for _, l := range rotatingSessionLogins { - if err := keepSessionForLogin(r.syncRotatingLogin(id, sessionLoginTriggerRemove, l)); err != nil { + if err := keepSessionForLogin(r.syncRotatingLogin(id, sessionLoginTriggerRemove, l, sessionLoginModeRemove)); err != nil { return err } } diff --git a/src/docs/api-reference/sessions.md b/src/docs/api-reference/sessions.md index 3d3881c0ff..96b3e468cb 100644 --- a/src/docs/api-reference/sessions.md +++ b/src/docs/api-reference/sessions.md @@ -132,7 +132,9 @@ The Claude login is copied **without its refresh token**. A session uses the fle If a session's HOME holds a complete Claude login that is usable and strictly newer than the shared one (a copy from an older release that the CLI refreshed, or a sign-in done inside the session), the hive adopts it into the shared login, keeps the replaced file as `.credentials.json.stale-`, and records `user_session_login_adopted` with `session`, `trigger` (`boot`, `watchdog`, `sign-in`, `session-start` or `session-remove`) and `stale_shared_file`, never token material. The check also runs before a session is deleted. Having nothing to adopt (no login file, an expired copy, a copy without a refresh token, a file that is not a credential) is not a failure and does not slow the delete. Only a strictly newer, usable login that cannot be adopted stops it: nothing is removed, the session is kept, and its `delete_error` reads `this session holds the hive's current sign-in; adopting it failed: ` (logged at WARN and audited). A login file that cannot be read at all also keeps the session, with the reason. A hive whose agents were locked out this way recovers at its next boot or poll without a new sign-in, provided the session that holds the login has not been deleted. -Codex's ChatGPT login and an OpenCode OAuth provider entry are copied whole, refresh token included, and rotate when the CLI in the session refreshes them. When the session's file holds a strictly newer login than the shared one (Codex: a later `last_refresh` and a different refresh token; OpenCode, per provider entry: a later `expires` and a different refresh token; in both cases the file was written after the shared one), the hive adopts it into the shared file at the same points and with the same delete rule as the Claude login. The replaced file is kept as `auth.json.stale-`, and `user_session_login_adopted` also carries `vendor` (`codex` or `opencode`) and `login` (the file). An API-key login is never replaced, and an OpenCode provider the shared file does not hold is not added ([#18740](https://github.com/hivecommons/hive/issues/18740)). +Codex's ChatGPT login and every OpenCode OAuth provider entry are copied the same way: **without a refresh token**. The `refresh_token` (Codex) and `refresh` (OpenCode) keys stay, because both CLIs require them, but are empty, so the CLI in a session uses the fleet's current access token and a refresh it attempts fails without rotating anything. Every other field and entry (API keys, account id, `auth_mode`) is copied as it is. The hive replaces the copy within one credential-bridge poll whenever the shared file is written after it (an agent's CLI refreshed it, or someone signed in). A session therefore depends on a Codex or OpenCode agent, or a sign-in, refreshing the shared login before its access token expires; until then the session reports an expired login. + +When a session's file holds a complete, strictly newer login than the shared one anyway (a copy from an older release that the CLI refreshed, or a sign-in done inside the session; Codex: a later `last_refresh` and a different refresh token; OpenCode, per provider entry: a later `expires` and a different refresh token; in both cases the file was written after the shared one), the hive adopts it into the shared file at the same points and with the same delete rule as the Claude login, then puts the session back on a refresh-less copy. The replaced file is kept as `auth.json.stale-`, and `user_session_login_adopted` also carries `vendor` (`codex` or `opencode`) and `login` (the file). An API-key login is never replaced, an OpenCode provider the shared file does not hold is not added, and a refresh token the shared file does not hold that is not newer (a login of the session's own) is left alone ([#18740](https://github.com/hivecommons/hive/issues/18740)). ## Seeding from the Inbox diff --git a/src/docs/security-model.md b/src/docs/security-model.md index e4ea2a1cb6..91ca0a9071 100644 --- a/src/docs/security-model.md +++ b/src/docs/security-model.md @@ -710,58 +710,61 @@ importance: session in with an account of their own, and that login becomes the hive's when it is newer. The audit entry is the record of it, and a dashboard sign-in puts the hive back on the operator's account. - The other vendors' files are still plain copies, refresh token included - where the vendor stores one. Gemini's Google refresh token and the Copilot - CLI token do not rotate. Codex's ChatGPT login (`.codex/auth.json`) and an - OpenCode OAuth entry (`opencode/auth.json`) do, so a session that refreshes - its copy holds the only valid login; for these two the hive **adopts** that - login back into the shared file the agents link to - ([#18740](https://github.com/hivecommons/hive/issues/18740)). Codex: the - session's file was written after the shared one, holds a ChatGPT login - with a different refresh token and records a later `last_refresh`, and the - shared file itself holds a ChatGPT login (an API-key login does not rotate - and is never replaced). OpenCode, per provider entry: both entries are - `oauth`, the session's has a different refresh token and a later - `expires`, and the session's file was written after the shared one; only - those entries are replaced, every other entry of the shared file is kept, - and a provider the shared file does not hold is not added. Only those - fields and modification times decide; token values are never logged. The - replaced file is kept as `auth.json.stale-`, the new one keeps the - old one's mode (and owner, where the hive may set it), and - `user_session_login_adopted` names the session, trigger, vendor and file. - It runs when the Claude check runs, deletion included: a newer login that - cannot be adopted keeps the session. Unlike Claude, a session still holds a - copy that can refresh, on purpose. Both CLIs keep the refresh token as a - field their login file schema requires (from their source, not yet - confirmed on a live install) (Codex: `tokens.refresh_token`; OpenCode: - `refresh` of an `oauth` entry), so a copy with that field removed is read - as a corrupt or logged-out login, and one with a placeholder fails at its - first refresh: either would sign the person out of the session, which is - worse than the window it closes, and hive has no way to route a CLI's - refresh through the shared file. The adoption above is therefore the - safety net and the shared file stays the single owner: an adoption only - ever writes the shared file, never the session's copy, and the hive never - replaces a shared file that changed after it was compared, so a session - refresh and an agent refresh of the same token within one poll cannot - leave two diverged logins for long; the shared file converges on the newer - one at the next poll. If that file is ever needed again, the stale file the - adoption kept (`auth.json.stale-`, next to the shared login, same - mode) holds the login it replaced. + Codex's ChatGPT login (`.codex/auth.json`) and an OpenCode OAuth entry + (`opencode/auth.json`) rotate too, and follow the same three rules + ([#18740](https://github.com/hivecommons/hive/issues/18740)). A session + gets them **without a refresh token**: the key stays (Codex: + `tokens.refresh_token`; OpenCode: `refresh` of an `oauth` entry), because + both CLIs require it in their login file, but its value is empty. Both CLIs + accept an empty value (from their sources, Codex 0.170.0 and OpenCode v1; + the live check below confirms it on a real install): the CLI keeps using + the access token, and a refresh it attempts fails without rotating + anything. Every other field is copied as it is. So the shared file, which + each agent links to, is the only refreshable holder of the grant, and only + the agents' CLIs refresh it; a session refresh and an agent refresh can no + longer race. The hive replaces a session's copy, atomically and as the + session's uid, when the shared file was written after it. A session + therefore depends on an agent or a sign-in refreshing that login before + its access token expires. As a safety net, a complete login that is in a + session home anyway (a full copy from an earlier release, refreshed there, + or a person signing in inside the session) is **adopted** into the shared + file when it is strictly newer. Codex: the session's file was written + after the shared one, holds a ChatGPT login with a different refresh token + and records a later `last_refresh`, and the shared file itself holds a + ChatGPT login (an API-key login does not rotate and is never replaced). + OpenCode, per provider entry: both entries are `oauth`, the session's has a + different refresh token and a later `expires`, and the session's file was + written after the shared one; only those entries are replaced, every other + entry of the shared file is kept, and a provider the shared file does not + hold is not added. Only those fields and modification times decide; token + values are never logged. The replaced file is kept as + `auth.json.stale-`, the new one keeps the old one's mode (and + owner, where the hive may set it), `user_session_login_adopted` names the + session, trigger, vendor and file, and the session is put back on a + refresh-less copy. A full copy that carries the shared file's own refresh + token is put on a refresh-less copy too; a refresh token the shared file + does not hold that is not newer is the session's own login and is left + alone. It runs when the Claude check runs, deletion included: a newer login + that cannot be adopted keeps the session. The hive never replaces a shared + file that changed after it was compared, so an agent refresh that lands + during a check is never overwritten. Gemini's Google refresh token and the + Copilot CLI token do not rotate and are still plain copies. Manual check, needs a person and a real install (not run in CI, so the assumed file formats stay unconfirmed until it is done, [#18740](https://github.com/hivecommons/hive/issues/18740)): on a hive with a signed-in Codex and OpenCode, (1) start a session, confirm `.codex/auth.json` and `opencode/auth.json` in its home match the shared - files' shape (compare key names only, never print values); (2) in the - session force a refresh (Codex: `codex login status` after setting an - older `last_refresh`; OpenCode: wait past `expires`) and confirm the next - poll writes the shared file, leaves an `auth.json.stale-*` beside it and - audits `user_session_login_adopted` with vendor `codex` or `opencode`; + files' shape (compare key names only, never print values); (2) confirm + the refresh keys in the session's copies are present and empty, that the + CLI in the session still works, and that once its access token expires + (Codex: a request past the token's expiry; OpenCode: past `expires`) its + refresh attempt fails without changing the shared file and without an + `auth.json.stale-*` or a `user_session_login_adopted` entry; (3) confirm an agent of that vendor is still logged in; (4) remove the session and confirm the shared login still works; (5) grep the hive log for the access and refresh token values: there must be none. Attach a - redacted real file, with token values replaced, as the test fixture. For all of these vendors a resume - no longer overwrites a file the session's CLI rewrote after the shared one + redacted real file, with token values replaced, as the test fixture. For Gemini and Copilot a resume no + longer overwrites a file the session's CLI rewrote after the shared one was written. - **Terminal access is bound.** ttyd listens on loopback without a secret a session uid could not read (its `-c` credential is visible in `/proc`), so