From a7459c6e4f5d098b9908798eb36f3672215b90b6 Mon Sep 17 00:00:00 2001 From: jochen Date: Fri, 20 Nov 2026 14:02:37 +0100 Subject: [PATCH 1/2] claude-code: never write a lease over a login the manager was not handed MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A login made on a node (while the tool runner was stopped, or before the manager asked claude_code_grant for it) was overwritten by the next apply of the binding's older grant: Apply took any refresh token in the file as one already handed, and forced the write. The person's login was lost and the session asked for a login again. The node side now keeps the fingerprint of the login claude_code_grant last sealed (state login-handed, never the token). Apply leaves a file whose login is not that one untouched (applied false, reason login-not-adopted); its report makes it the manager's candidate, and the successor the manager hands back replaces it, as before without a refresh token. Builds: ADR 0206, ADR 0209; design 39 §6 (the latest login wins, a login moves its node); design 14 (a node never holds a refresh token). --- .../cmd/claude-code/claude_code_test.go | 83 ++++++++++++++++--- modules/claude-code/cmd/claude-code/grant.go | 8 ++ modules/claude-code/cmd/claude-code/node.go | 24 ++++++ 3 files changed, 103 insertions(+), 12 deletions(-) diff --git a/modules/claude-code/cmd/claude-code/claude_code_test.go b/modules/claude-code/cmd/claude-code/claude_code_test.go index f514945e3..817f3973b 100644 --- a/modules/claude-code/cmd/claude-code/claude_code_test.go +++ b/modules/claude-code/cmd/claude-code/claude_code_test.go @@ -358,18 +358,77 @@ func TestAnAppliedBindingSaysWhyAndWho(t *testing.T) { } } -func TestTheTokenANodeIsHandedReplacesALoginsGrantAndLeavesNoRefreshToken(t *testing.T) { - p, w := node(t, "laptop") - writeFile(t, p.credentials(), `{"claudeAiOauth":{"accessToken":"at-old","refreshToken":"rt-spent","expiresAt":`+ - strings.TrimSpace(string(mustJSON(now+7_200_000)))+`}}`) - var asked []string - out, err := Pull(p, seat(t, "personal", "at-new", 1, &asked), writer(w)) - if err != nil || out["applied"] != true { - t.Fatalf("%v %v", out, err) - } - c := creds(t, p) - if c["accessToken"] != "at-new" || c["refreshToken"] != nil || HoldingsOf(p).Refresh.Present { - t.Fatalf("%v", c) +// ADR 0206, ADR 0209, design 39 §6 "the latest login wins": a login in the file that was never handed to the manager +// is newer than every lease, made while the tool runner was stopped (the start's first view) or while it runs (a +// binding or the vault's change heard before the manager asked claude_code_grant). No path writes over it; once +// claude_code_grant handed it, its successor replaces it and leaves no refresh token, and a file holding no login is +// restored as before. +func TestALoginNotHandedIsNeverWrittenOverAndItsSuccessorReplacesIt(t *testing.T) { + login := `{"claudeAiOauth":{"accessToken":"at-login","refreshToken":"rt-login","expiresAt":` + + strings.TrimSpace(string(mustJSON(now+7_200_000))) + `,"refreshTokenExpiresAt":9000},"other":1}` + lease := `{"claudeAiOauth":{"accessToken":"at-lease","expiresAt":1},"other":1}` + for _, c := range []struct { + name, file string + handed bool + heard func(p Paths, ask Ask, w WriteManaged) (string, error) + want string // the access token the file holds after + }{ + {"the start's first view, a login made while stopped", login, false, func(p Paths, ask Ask, w WriteManaged) (string, error) { + return FirstBinding(p, ask, w) + }, "at-login"}, + {"binding.changed heard while it runs, before the grant was asked", login, false, func(p Paths, ask Ask, w WriteManaged) (string, error) { + return OnBindingChanged(p, []byte(`{"consumer":"laptop","licence":"personal","key":"personal","kind":"subscription","generation":9}`), ask, w) + }, "at-login"}, + {"the vault's change heard while it runs, before the grant was asked", login, false, func(p Paths, ask Ask, w WriteManaged) (string, error) { + return OnSecretChanged(p, []byte(`{"name":"licence.personal.access","generation":5}`), ask, w) + }, "at-login"}, + {"the successor of a login handed", login, true, func(p Paths, ask Ask, w WriteManaged) (string, error) { + return OnBindingChanged(p, []byte(`{"consumer":"laptop","licence":"personal","key":"personal","kind":"subscription","generation":9}`), ask, w) + }, "at-new"}, + {"a file holding the lease, older than the one handed", lease, false, func(p Paths, ask Ask, w WriteManaged) (string, error) { + return FirstBinding(p, ask, w) + }, "at-new"}, + } { + t.Run(c.name, func(t *testing.T) { + p, w := node(t, "laptop") + writeFile(t, p.binding(), `{"licence":"personal","key":"personal","kind":"subscription","generation":2}`+"\n") + writeFile(t, p.credentials(), c.file) + if c.handed { + manager, _ := GenerateKeyPair() + if a, err := GrantFor(p, manager.PublicKey); err != nil || a.Sealed == nil { + t.Fatalf("the grant: %+v %v", a, err) + } + } + var asked []string + current := seat(t, "personal", "at-new", 9, &asked) + ask := func(address string, args any) (json.RawMessage, error) { + if address == SeatVerb("bindings") { + return json.RawMessage(`[{"consumer":"laptop","licence":"personal","key":"personal","kind":"subscription","generation":9}]`), nil + } + return current(address, args) + } + before, _ := os.ReadFile(p.credentials()) + if _, err := c.heard(p, ask, writer(w)); err != nil { + t.Fatal(err) + } + got := creds(t, p) + if got["accessToken"] != c.want { + t.Fatalf("the file holds %v, want %s", got["accessToken"], c.want) + } + after, _ := os.ReadFile(p.credentials()) + if c.want == "at-login" { + if string(after) != string(before) || !HoldingsOf(p).Refresh.Present { + t.Fatalf("a login not handed was changed: %s", after) + } + return + } + // Restored: no refresh token survives (design 14, design 36 §5), the CLI's other keys stay. + var whole map[string]any + _ = json.Unmarshal(after, &whole) + if got["refreshToken"] != nil || HoldingsOf(p).Refresh.Present || whole["other"] == nil { + t.Fatalf("restored %s", after) + } + }) } } diff --git a/modules/claude-code/cmd/claude-code/grant.go b/modules/claude-code/cmd/claude-code/grant.go index e184da94c..15a7d6d85 100644 --- a/modules/claude-code/cmd/claude-code/grant.go +++ b/modules/claude-code/cmd/claude-code/grant.go @@ -122,6 +122,14 @@ func HoldsLogin(c Credentials) bool { return rt != "" } +// LoginNotHanded says the file holds a login that was never handed to the manager: handed is the fingerprint +// of the refresh token claude_code_grant last sealed, "" when none was. Such a login is newer than anything the +// manager holds, so no grant may overwrite it before the manager adopts it (ADR 0206, ADR 0209). +func LoginNotHanded(c Credentials, handed string) bool { + rt := RefreshTokenOf(c) + return rt != "" && Fingerprint(rt) != handed +} + // RefreshTokenOf is the refresh token a login left, or "". func RefreshTokenOf(c Credentials) string { rt, _ := c.oauth()["refreshToken"].(string) diff --git a/modules/claude-code/cmd/claude-code/node.go b/modules/claude-code/cmd/claude-code/node.go index 011ebb8c8..eda4cc7e5 100644 --- a/modules/claude-code/cmd/claude-code/node.go +++ b/modules/claude-code/cmd/claude-code/node.go @@ -143,6 +143,7 @@ func HomeScopeRefused(p Paths, target string) string { func (p Paths) credentials() string { return filepath.Join(p.Home, ".claude", ".credentials.json") } func (p Paths) account() string { return filepath.Join(p.Home, ".claude.json") } func (p Paths) binding() string { return filepath.Join(p.State, "licence.json") } +func (p Paths) handed() string { return filepath.Join(p.State, "login-handed") } func (p Paths) apiKey() string { return filepath.Join(p.keyDir(), "api-key") } func (p Paths) helper() string { return filepath.Join(p.keyDir(), "api-key-helper") } @@ -418,9 +419,26 @@ func GrantFor(p Paths, managerPublicKey string) (GrantAnswer, error) { if err != nil { return GrantAnswer{}, err } + // Which login was handed: only its successor may replace it (ADR 0206, ADR 0209). The fingerprint, never + // the token. + if err := fsys.MkdirAll(p.State, 0o700); err != nil { + return GrantAnswer{}, err + } + if err := fsys.WriteFile(p.handed(), []byte(Fingerprint(rt)+"\n"), 0o600); err != nil { + return GrantAnswer{}, err + } return GrantAnswer{Sealed: &box, Identity: ReadIdentity(p.account()), Fingerprint: Fingerprint(rt)}, nil } +// readHanded is the fingerprint of the login last handed to the manager, or "". +func readHanded(p Paths) string { + raw, err := fsys.ReadFile(p.handed()) + if err != nil { + return "" + } + return strings.TrimSpace(string(raw)) +} + // Pull asks the seat which licence this node holds, then the vault for that licence's access secret, sealed to this // module's key, and applies it (§19). func Pull(p Paths, ask Ask, write WriteManaged) (map[string]any, error) { @@ -609,6 +627,12 @@ func Apply(p Paths, c Current, sealed SealedBox, write WriteManaged) (map[string return nil, err } local := ReadCredentials(p.credentials()) + // A login made here that the manager has not adopted yet stays whole: the grant handed is the old + // lineage's, and writing it would spend the person's login unseen (ADR 0206, ADR 0209). The manager + // asks claude_code_grant for it on this node's report; its successor then comes as a newer generation. + if LoginNotHanded(local, readHanded(p)) { + return map[string]any{"applied": false, "licence": c.Licence, "reason": "login-not-adopted"}, nil + } // A login waiting here was handed to the manager first (ADR 0206): what comes back is its successor, // and the refresh token in the file is the one the manager just spent. d := DecideApply(GrantOf(local), g, switched || HoldsLogin(local)) From a8a0cfeb8f8a35c0afc8475061929406fb049892 Mon Sep 17 00:00:00 2001 From: jochen Date: Fri, 20 Nov 2026 14:21:47 +0100 Subject: [PATCH 2/2] claude-code: a login handed is replaced only by a grant of a newer lineage MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit One reason, login kept, on both paths, with a journal line; the not-handed return skips the binding's generation on purpose. Builds: ADR 0206, ADR 0209, design 39 §3 §6, design 14, H-A-138 (hq design/47-H1-answers-59 175ed320) --- .../cmd/claude-code/claude_code_test.go | 25 +++++++++++++++---- modules/claude-code/cmd/claude-code/grant.go | 16 ++++++++++++ modules/claude-code/cmd/claude-code/node.go | 16 +++++++++--- 3 files changed, 49 insertions(+), 8 deletions(-) diff --git a/modules/claude-code/cmd/claude-code/claude_code_test.go b/modules/claude-code/cmd/claude-code/claude_code_test.go index 817f3973b..da3ebce75 100644 --- a/modules/claude-code/cmd/claude-code/claude_code_test.go +++ b/modules/claude-code/cmd/claude-code/claude_code_test.go @@ -370,22 +370,29 @@ func TestALoginNotHandedIsNeverWrittenOverAndItsSuccessorReplacesIt(t *testing.T for _, c := range []struct { name, file string handed bool + offeredRTE int64 // the refresh token expiry the grant offered carries, 0 for none heard func(p Paths, ask Ask, w WriteManaged) (string, error) want string // the access token the file holds after }{ - {"the start's first view, a login made while stopped", login, false, func(p Paths, ask Ask, w WriteManaged) (string, error) { + {"the start's first view, a login made while stopped", login, false, 0, func(p Paths, ask Ask, w WriteManaged) (string, error) { return FirstBinding(p, ask, w) }, "at-login"}, - {"binding.changed heard while it runs, before the grant was asked", login, false, func(p Paths, ask Ask, w WriteManaged) (string, error) { + {"binding.changed heard while it runs, before the grant was asked", login, false, 0, func(p Paths, ask Ask, w WriteManaged) (string, error) { return OnBindingChanged(p, []byte(`{"consumer":"laptop","licence":"personal","key":"personal","kind":"subscription","generation":9}`), ask, w) }, "at-login"}, - {"the vault's change heard while it runs, before the grant was asked", login, false, func(p Paths, ask Ask, w WriteManaged) (string, error) { + {"the vault's change heard while it runs, before the grant was asked", login, false, 0, func(p Paths, ask Ask, w WriteManaged) (string, error) { return OnSecretChanged(p, []byte(`{"name":"licence.personal.access","generation":5}`), ask, w) }, "at-login"}, - {"the successor of a login handed", login, true, func(p Paths, ask Ask, w WriteManaged) (string, error) { + {"the successor of a login handed, of a newer lineage", login, true, 20000, func(p Paths, ask Ask, w WriteManaged) (string, error) { return OnBindingChanged(p, []byte(`{"consumer":"laptop","licence":"personal","key":"personal","kind":"subscription","generation":9}`), ask, w) }, "at-new"}, - {"a file holding the lease, older than the one handed", lease, false, func(p Paths, ask Ask, w WriteManaged) (string, error) { + {"a login handed, met by a lease older than it (H-A-138)", login, true, 100, func(p Paths, ask Ask, w WriteManaged) (string, error) { + return OnBindingChanged(p, []byte(`{"consumer":"laptop","licence":"personal","key":"personal","kind":"subscription","generation":9}`), ask, w) + }, "at-login"}, + {"a login handed, met by a lease with no lineage mark (H-A-138)", login, true, 0, func(p Paths, ask Ask, w WriteManaged) (string, error) { + return OnBindingChanged(p, []byte(`{"consumer":"laptop","licence":"personal","key":"personal","kind":"subscription","generation":9}`), ask, w) + }, "at-login"}, + {"a file holding the lease, older than the one handed", lease, false, 0, func(p Paths, ask Ask, w WriteManaged) (string, error) { return FirstBinding(p, ask, w) }, "at-new"}, } { @@ -405,6 +412,14 @@ func TestALoginNotHandedIsNeverWrittenOverAndItsSuccessorReplacesIt(t *testing.T if address == SeatVerb("bindings") { return json.RawMessage(`[{"consumer":"laptop","licence":"personal","key":"personal","kind":"subscription","generation":9}]`), nil } + if address == VaultGet && c.offeredRTE != 0 { + g, _ := json.Marshal(Grant{AccessToken: "at-new", ExpiresAt: now + 3_600_000, RefreshTokenExpiresAt: &c.offeredRTE}) + box, err := Seal(string(g), args.(map[string]any)["public_key"].(string)) + if err != nil { + t.Fatal(err) + } + return json.Marshal(map[string]any{"name": args.(map[string]any)["name"], "generation": 1, "sealed": box}) + } return current(address, args) } before, _ := os.ReadFile(p.credentials()) diff --git a/modules/claude-code/cmd/claude-code/grant.go b/modules/claude-code/cmd/claude-code/grant.go index 15a7d6d85..c06e45336 100644 --- a/modules/claude-code/cmd/claude-code/grant.go +++ b/modules/claude-code/cmd/claude-code/grant.go @@ -122,6 +122,22 @@ func HoldsLogin(c Credentials) bool { return rt != "" } +// LoginKept is the reason a grant is not written over a login (H-A-138). +const LoginKept = "login kept" + +// NewerLineage says the offered grant's refresh token expires later than the login's: the manager marks a +// successor of the login so, and a lease older than the login never does. +func NewerLineage(login Credentials, offered Grant) bool { + if offered.RefreshTokenExpiresAt == nil { + return false + } + held := GrantOf(login) + if held == nil || held.RefreshTokenExpiresAt == nil { + return true + } + return *offered.RefreshTokenExpiresAt > *held.RefreshTokenExpiresAt +} + // LoginNotHanded says the file holds a login that was never handed to the manager: handed is the fingerprint // of the refresh token claude_code_grant last sealed, "" when none was. Such a login is newer than anything the // manager holds, so no grant may overwrite it before the manager adopts it (ADR 0206, ADR 0209). diff --git a/modules/claude-code/cmd/claude-code/node.go b/modules/claude-code/cmd/claude-code/node.go index eda4cc7e5..53304d349 100644 --- a/modules/claude-code/cmd/claude-code/node.go +++ b/modules/claude-code/cmd/claude-code/node.go @@ -24,6 +24,7 @@ import ( "encoding/json" "errors" "fmt" + "log" "os" "path/filepath" "regexp" @@ -630,11 +631,20 @@ func Apply(p Paths, c Current, sealed SealedBox, write WriteManaged) (map[string // A login made here that the manager has not adopted yet stays whole: the grant handed is the old // lineage's, and writing it would spend the person's login unseen (ADR 0206, ADR 0209). The manager // asks claude_code_grant for it on this node's report; its successor then comes as a newer generation. + // This return skips the binding's generation below on purpose: later binding events pull again until + // the manager adopts the login. if LoginNotHanded(local, readHanded(p)) { - return map[string]any{"applied": false, "licence": c.Licence, "reason": "login-not-adopted"}, nil + log.Printf("login kept: the login in the credentials file was not handed to the manager yet (licence %s)", c.Licence) + return map[string]any{"applied": false, "licence": c.Licence, "reason": LoginKept}, nil + } + // A login handed to the manager is replaced only by a grant of a newer lineage (its refresh token's + // expiry later than the login's, as the manager marks it): a lease older than the login is never + // written, so the manager's failed refresh is a finding on the manager, never a lost login here + // (H-A-138, hq design/47-H1-answers-59 175ed320). + if HoldsLogin(local) && !NewerLineage(local, g) { + log.Printf("login kept: the grant offered for licence %s is not of a newer lineage than the login in the credentials file", c.Licence) + return map[string]any{"applied": false, "licence": c.Licence, "reason": LoginKept}, nil } - // A login waiting here was handed to the manager first (ADR 0206): what comes back is its successor, - // and the refresh token in the file is the one the manager just spent. d := DecideApply(GrantOf(local), g, switched || HoldsLogin(local)) if d.Apply { next := WithGrant(local, g)