oficina / equipo Public

Token round 2: real validation tracked; expired recovery cleans up

A token is a connection only once a real request is answered: a
durable validated time set by the connect check, Check again or an
answered run; the CLI's local status never sets it, so an unvalidated
token is neither chosen nor shown, and an unfinished attempt always
runs the real check. A restart after the attempt's time, with its
binding saved, goes through the durable sign-out (local id recorded,
binding, home and token deleted; cancelled if a cancel was recorded).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev accaa5ff2ae119e37c23a0ba800701346ec2be47 parent 5ad31a4
4 files changed, +257 −39
  • internal/headless/token_test.go +10 −0
  • internal/runner/thin/conns.go +70 −9
  • internal/runner/thin/token.go +60 −22
  • internal/runner/thin/token_test.go +117 −8

CI passed — run details

diff --git a/internal/headless/token_test.go b/internal/headless/token_test.go
index 297d59e8..61114c68 100644
--- a/internal/headless/token_test.go
+++ b/internal/headless/token_test.go
@@ -1,6 +1,7 @@
package headless
import (
+ "context"
"crypto/ed25519"
"crypto/rand"
"encoding/base64"
@@ -13,6 +14,7 @@ import (
"amadan.net/oficina/equipo/internal/fakeclaude"
"amadan.net/oficina/equipo/internal/runner/provider"
+ "amadan.net/oficina/equipo/internal/runner/thin"
"amadan.net/oficina/equipo/internal/runnerproto"
"amadan.net/oficina/equipo/internal/sealbox"
"amadan.net/oficina/equipo/internal/thintest"
@@ -33,6 +35,14 @@ func (r *localRunner) addToken(t *testing.T, id, email string) string {
writeJSON(t, filepath.Join(home, "equipo-identity.json"), identity)
bs := append(r.bindings(t), map[string]any{"id": id, "local_id": id, "label": id, "person_id": thintest.Owner, "provider": "claude", "family": "claude", "model": "claude-opus-5-5", "account_id": email, "provider_home": home, "kind": "token", "expected_identity": identity})
writeJSON(t, r.cfg.AccountBindingsPath, bs)
+ // As the connect check would: a real request answered, recorded on the
+ // runner, so the token is a connection.
+ st, err := thin.OpenState(context.Background(), r.cfg.StateDir)
+ if err != nil {
+ t.Fatal(err)
+ }
+ (&thin.Conns{Runner: r.cfg, State: st}).Validated(id)
+ st.Close()
return token
}
diff --git a/internal/runner/thin/conns.go b/internal/runner/thin/conns.go
index 186a1343..7804fc38 100644
--- a/internal/runner/thin/conns.go
+++ b/internal/runner/thin/conns.go
@@ -18,6 +18,7 @@ import (
const connSchema = `
CREATE TABLE IF NOT EXISTS conn_state (id TEXT PRIMARY KEY, state TEXT NOT NULL, resets_at TEXT NOT NULL DEFAULT '', window TEXT NOT NULL DEFAULT '', cooloff INTEGER NOT NULL DEFAULT 0, headroom TEXT NOT NULL DEFAULT '', plan TEXT NOT NULL DEFAULT '', updated_at TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS conn_expiry (id TEXT PRIMARY KEY, expires_at TEXT NOT NULL);
+CREATE TABLE IF NOT EXISTS conn_validated (id TEXT PRIMARY KEY, at TEXT NOT NULL);
`
// ErrNoConnection: nothing the person connected can run the role now.
@@ -54,7 +55,11 @@ type Conns struct {
mu sync.Mutex
live map[string]connState
- now func() time.Time
+ // validated is when a real request on each connection last got the
+ // provider's answer (conn_validated): a token connection is a
+ // connection only from then; its CLI's local status never sets it.
+ validated map[string]time.Time
+ now func() time.Time
}
func (c *Conns) clock() time.Time {
@@ -70,7 +75,20 @@ func (c *Conns) load(ctx context.Context) error {
if c.live != nil {
return nil
}
- c.live = map[string]connState{}
+ c.live, c.validated = map[string]connState{}, map[string]time.Time{}
+ vrows, err := c.State.db.QueryContext(ctx, "SELECT id, at FROM conn_validated")
+ if err != nil {
+ return err
+ }
+ for vrows.Next() {
+ var id, at string
+ if vrows.Scan(&id, &at) == nil {
+ if t, err := time.Parse(time.RFC3339Nano, at); err == nil {
+ c.validated[id] = t
+ }
+ }
+ }
+ vrows.Close()
rows, err := c.State.db.QueryContext(ctx, "SELECT id, state, resets_at, window, cooloff, headroom, plan FROM conn_state")
if err != nil {
return err
@@ -150,6 +168,10 @@ func (c *Conns) Mine(person string) []runner.AccountBinding {
func (c *Conns) candidate(b runner.AccountBinding) connect.Candidate {
cs := c.live[b.ID]
+ if b.Kind == wire.KindToken && c.validated[b.ID].IsZero() {
+ // Never answered a real request: not a connection yet.
+ cs.State = ""
+ }
cand := connect.Candidate{ID: b.ID, Provider: b.Provider, State: cs.State, ResetsAt: cs.ResetsAt}
if cs.Headroom != nil && cs.Headroom.Utilization != nil {
cand.Used, cand.Known = *cs.Headroom.Utilization, true
@@ -350,6 +372,11 @@ func (c *Conns) Held() []wire.HeldConnection {
defer c.mu.Unlock()
now := c.clock()
for _, b := range bs {
+ if b.Kind == wire.KindToken && c.validated[b.ID].IsZero() {
+ // Saved, never validated by a real request: its attempt is
+ // still running (or ends undone); not a connection to show.
+ continue
+ }
cs := c.live[b.ID]
state := cs.State
if state == "" || state == wire.ConnLimited && c.candidate(b).Usable(now) {
@@ -462,13 +489,9 @@ func (c *Conns) checkOne(ctx context.Context, b runner.AccountBinding) {
return
}
if b.Kind == wire.KindToken && err == nil {
- // The CLI's status for a token proves only that it is there.
- c.mu.Lock()
- unknown := c.live[b.ID].State == ""
- c.mu.Unlock()
- if !unknown {
- return
- }
+ // The CLI's status for a token proves only that it is there: it
+ // never makes a token healthy or validated.
+ return
}
c.checked(b.ID, err)
}
@@ -496,9 +519,39 @@ func (c *Conns) Answered(id string) {
if c.load(context.Background()) != nil {
return
}
+ c.Validated(id)
+}
+
+// Validated records a real request on the connection answered by the
+// provider (a token's check, Check again, or any answered run): durably,
+// then the state it proves.
+func (c *Conns) Validated(id string) {
+ if c.load(context.Background()) != nil {
+ return
+ }
+ at := c.clock().UTC()
+ if _, err := c.State.db.Exec("INSERT INTO conn_validated(id, at) VALUES(?,?) ON CONFLICT(id) DO UPDATE SET at=excluded.at", id, at.Format(time.RFC3339Nano)); err != nil {
+ if c.Logger != nil {
+ c.Logger.Warn("connection validated", "err", sanitize(err))
+ }
+ return
+ }
+ c.mu.Lock()
+ c.validated[id] = at
+ c.mu.Unlock()
c.checked(id, nil)
}
+// ValidatedAt is when a real request on the connection was last answered.
+func (c *Conns) ValidatedAt(id string) time.Time {
+ if c.load(context.Background()) != nil {
+ return time.Time{}
+ }
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ return c.validated[id]
+}
+
// checkToken checks a token connection (a busy home proves nothing).
func (c *Conns) checkToken(ctx context.Context, b runner.AccountBinding) {
if c.Verify == nil {
@@ -508,6 +561,10 @@ func (c *Conns) checkToken(ctx context.Context, b runner.AccountBinding) {
if ctx.Err() != nil || errors.Is(err, provider.ErrAccountBusy) {
return
}
+ if err == nil {
+ c.Validated(b.ID)
+ return
+ }
c.checked(b.ID, err)
}
@@ -554,5 +611,9 @@ func (c *Conns) Forget(id string) {
c.mu.Lock()
defer c.mu.Unlock()
delete(c.live, id)
+ if c.validated != nil {
+ delete(c.validated, id)
+ }
_, _ = c.State.db.Exec("DELETE FROM conn_state WHERE id=?", id)
+ _, _ = c.State.db.Exec("DELETE FROM conn_validated WHERE id=?", id)
}
diff --git a/internal/runner/thin/token.go b/internal/runner/thin/token.go
index 6654e10b..0e7dd554 100644
--- a/internal/runner/thin/token.go
+++ b/internal/runner/thin/token.go
@@ -121,6 +121,11 @@ func (c *Connector) runToken(ctx context.Context, cmd wire.ConnectCommand, base
c.delivery.Lock()
defer c.delivery.Unlock()
c.removeHome(home)
+ if home != "" && exists(home) {
+ // Not deleted (still bound): the durable sign-out does it.
+ go c.endToken(cmd.Connection, cmd.Person, home, r.Reason)
+ return
+ }
c.finish(cmd.Connection, r)
}
failed := func(home, reason string) {
@@ -241,7 +246,7 @@ func (c *Connector) runToken(ctx context.Context, cmd wire.ConnectCommand, base
return
}
if c.Conns != nil {
- c.Conns.checked(id, nil)
+ c.Conns.Validated(id)
c.Conns.changed()
}
r := base
@@ -260,20 +265,13 @@ func (c *Connector) savedToken(person, id, home string) (runner.AccountBinding,
return runner.AccountBinding{}, false
}
-// verifyToken is a saved token's check (Conns.Verify), skipped when this
-// attempt passed it before a stop.
+// verifyToken is a saved token's real check (Conns.Verify). An unfinished
+// attempt always runs it, whatever the connection's health says: only a
+// real request answered by the provider makes the token a connection.
func (c *Connector) verifyToken(ctx context.Context, b runner.AccountBinding) error {
if c.Conns == nil || c.Conns.Verify == nil {
return provider.ErrLoginUnavailable
}
- if c.Conns.load(ctx) == nil {
- c.Conns.mu.Lock()
- cs := c.Conns.live[b.ID]
- c.Conns.mu.Unlock()
- if cs.State == wire.ConnHealthy {
- return nil
- }
- }
return c.Conns.Verify(ctx, b)
}
@@ -302,6 +300,53 @@ func (c *Connector) undoToken(cmd wire.ConnectCommand, id string, lock *os.File,
}
}
+// endToken ends a token attempt found after a restart that cannot go on
+// (its time is up). A home with a saved binding, or one that could not be
+// deleted, goes through the durable sign-out: the attempt's end records
+// its local id and the cleanup in one transaction, so the binding, the
+// home and the token are deleted even across another stop; an attempt is
+// never recorded ended with no local id while its home survives. A
+// recorded cancel ends it cancelled.
+func (c *Connector) endToken(id, person, home, reason string) {
+ var cancelled int
+ _ = c.State.db.QueryRow("SELECT cancelled FROM connect_attempts WHERE id=?", id).Scan(&cancelled)
+ if cancelled == 1 {
+ reason = "cancelled"
+ }
+ r := wire.ConnectionReport{Connection: id, Person: person, Provider: wire.ProviderClaude, State: wire.ConnError, Reason: reason}
+ // The connection's local id is its home's name.
+ local := filepath.Base(home)
+ _, bound := c.savedToken(person, local, home)
+ if !bound {
+ c.removeHome(home)
+ if home == "" || !exists(home) {
+ c.finish(id, r)
+ return
+ }
+ }
+ k := cleanup{connection: id, person: person, local: local, home: home, provider: wire.ProviderClaude}
+ err := c.State.tx(context.Background(), func(t *sql.Tx) error {
+ if _, err := t.Exec("UPDATE connect_attempts SET state='done', local_id=? WHERE id=?", local, id); err != nil {
+ return err
+ }
+ if err := c.State.enqueue(t, wire.FrameConnection, "", r); err != nil {
+ return err
+ }
+ if err := owe(t, k); err != nil {
+ return err
+ }
+ _, err := t.Exec("UPDATE connect_cleanups SET home=?, provider=? WHERE connection=?", home, wire.ProviderClaude, id)
+ return err
+ })
+ c.log("connect token", err)
+ if c.Notify != nil {
+ c.Notify()
+ }
+ if err == nil {
+ c.background(func() { c.settle(k) })
+ }
+}
+
// tokenLabel is what a token connection is called: the account's email
// when the CLI reported one, else nothing (the app names it).
func tokenLabel(account string) string {
@@ -330,7 +375,6 @@ func saveToken(ctx context.Context, bindings, person, id, home string, observed
// finished); a row with neither file cannot happen and ends the attempt
// in error. Then the attempt waits on for the rest of its time.
func (c *Connector) resumeToken(ctx context.Context, id, person, home, created string) error {
- base := wire.ConnectionReport{Connection: id, Person: person, Provider: wire.ProviderClaude}
var rows int
if err := c.State.db.QueryRowContext(ctx, "SELECT count(*) FROM seen_seals WHERE connection_id=?", id).Scan(&rows); err != nil {
return err
@@ -338,8 +382,7 @@ func (c *Connector) resumeToken(ctx context.Context, id, person, home, created s
if home != "" {
dir, err := os.Open(home)
if err != nil {
- c.removeHome(home)
- c.finish(id, wire.ConnectionReport{Connection: id, Person: person, Provider: wire.ProviderClaude, State: wire.ConnError, Reason: "runner_offline"})
+ c.endToken(id, person, home, "runner_offline")
return nil
}
defer dir.Close()
@@ -357,10 +400,8 @@ func (c *Connector) resumeToken(ctx context.Context, id, person, home, created s
var st unix.Stat_t
if unix.Fstatat(fd, provider.TokenFile, &st, unix.AT_SYMLINK_NOFOLLOW) == unix.ENOENT {
if err = unix.Renameat(fd, provider.TokenStaging, fd, provider.TokenFile); err != nil {
- c.removeHome(home)
- r := base
- r.State, r.Reason = wire.ConnError, "provider_refused"
- c.finish(id, r)
+ dir.Close()
+ c.endToken(id, person, home, "provider_refused")
return nil
}
}
@@ -375,10 +416,7 @@ func (c *Connector) resumeToken(ctx context.Context, id, person, home, created s
limit = ConnectLimit
}
if !time.Now().Before(at.Add(limit)) {
- c.removeHome(home)
- r := base
- r.State, r.Reason = wire.ConnError, "timed_out"
- c.finish(id, r)
+ c.endToken(id, person, home, "timed_out")
return nil
}
actx, cancel := context.WithDeadline(c.ctx, at.Add(limit))
diff --git a/internal/runner/thin/token_test.go b/internal/runner/thin/token_test.go
index cf4d13d1..86f6d0ca 100644
--- a/internal/runner/thin/token_test.go
+++ b/internal/runner/thin/token_test.go
@@ -53,13 +53,15 @@ func (l *lockedBuffer) String() string { return string(l.Bytes()) }
type tokenRig struct {
t *testing.T
dir, root string
- state *State
- cfg runner.Config
- conns *Conns
- keys sealbox.Keys
- logs lockedBuffer
- errs []error
- ctx context.Context
+ // limit is the next connector's attempt limit (default an hour).
+ limit time.Duration
+ state *State
+ cfg runner.Config
+ conns *Conns
+ keys sealbox.Keys
+ logs lockedBuffer
+ errs []error
+ ctx context.Context
// checks counts the real-request checks (verify); refuse makes the
// next ones fail for another reason than the token.
checks atomic.Int64
@@ -121,7 +123,11 @@ func (r *tokenRig) verify(ctx context.Context, b runner.AccountBinding) error {
// connector starts a connector, as a runner process does.
func (r *tokenRig) connector() *Connector {
keys := r.keys
- c := &Connector{Runner: r.cfg, State: r.state, Conns: r.conns, Root: r.root, Owners: []string{connPerson}, Seal: &keys, RunnerID: tokenRunner, Limit: time.Hour, Logger: slog.New(slog.NewTextHandler(&r.logs, nil))}
+ limit := time.Hour
+ if r.limit > 0 {
+ limit = r.limit
+ }
+ c := &Connector{Runner: r.cfg, State: r.state, Conns: r.conns, Root: r.root, Owners: []string{connPerson}, Seal: &keys, RunnerID: tokenRunner, Limit: limit, Logger: slog.New(slog.NewTextHandler(&r.logs, nil))}
c.spawn = func(f func()) { f() }
if err := c.Start(r.ctx); err != nil {
r.t.Fatal(err)
@@ -839,3 +845,106 @@ func TestTokenSecretRightAfterConnect(t *testing.T) {
_ = r.state.db.QueryRow("SELECT home FROM connect_attempts WHERE id='cn_q1'").Scan(&home)
r.healthy("cn_q1", home, token, "q@example.com")
}
+
+// stopAtBound runs a token attempt to its saved binding and stops the
+// runner there (before the real check and the attempt's end).
+func (r *tokenRig) stopAtBound(id, token string) string {
+ r.t.Helper()
+ first := r.connector()
+ stopped := make(chan struct{})
+ first.fault = func(at string) error {
+ if at == "bound" {
+ close(stopped)
+ return errStopped
+ }
+ return nil
+ }
+ home := r.connect(first, id)
+ if !r.deliver(first, "f-secret-"+id, r.sealed(id, token, nil)) {
+ r.t.Fatal(r.errs)
+ }
+ select {
+ case <-stopped:
+ case <-time.After(20 * time.Second):
+ r.t.Fatal("never reached the saved binding")
+ }
+ r.waitFor(func() bool {
+ _, ok := r.binding(filepath.Base(home))
+ return ok
+ }, "the saved binding")
+ return home
+}
+
+// Astra round 2: the hourly pass between the saved binding and the real
+// check never makes the token a connection (its CLI status says signed in
+// for any token), and the resumed attempt still makes the real request.
+func TestTokenHourlyPassBeforeTheCheck(t *testing.T) {
+ r := newTokenRig(t)
+ token := fakeclaude.Token("race@example.com")
+ home := r.stopAtBound("cn_race", token)
+ local := filepath.Base(home)
+ paths := provider.LoginOptions{ClaudePath: r.cfg.ClaudePath, CodexPath: r.cfg.CodexPath}
+ r.conns.Refresh = func(ctx context.Context, b provider.Binding) (provider.Identity, error) {
+ return provider.RefreshLogin(ctx, b, paths)
+ }
+ before := r.checks.Load()
+ r.conns.Check(r.ctx)
+ if len(r.conns.Held()) != 0 || !r.conns.ValidatedAt(local).IsZero() {
+ t.Fatalf("the CLI's status made the token a connection: %+v", r.conns.Held())
+ }
+ if _, _, err := r.conns.Choose(r.ctx, connPerson, "coordinator", "", nil); err == nil {
+ t.Fatal("an unvalidated token was chosen")
+ }
+ r.connector()
+ r.healthy("cn_race", home, token, "race@example.com")
+ if r.checks.Load() != before+1 || r.conns.ValidatedAt(local).IsZero() {
+ t.Fatalf("the resumed attempt made %d real requests; validated %v", r.checks.Load()-before, r.conns.ValidatedAt(local))
+ }
+}
+
+// Astra round 2: a restart after the attempt's time is up, with its
+// binding saved, goes through the durable sign-out: the binding, the home
+// and the token go; the end records the attempt's local id, never an
+// empty one while the home survives; a recorded cancel ends it cancelled.
+func TestTokenExpiredRecoveryCleansUp(t *testing.T) {
+ for _, cancelled := range []bool{false, true} {
+ t.Run(map[bool]string{false: "expired", true: "cancelled"}[cancelled], func(t *testing.T) {
+ r := newTokenRig(t)
+ id := "cn_x_" + map[bool]string{false: "e", true: "c"}[cancelled]
+ home := r.stopAtBound(id, fakeclaude.Token("late@example.com"))
+ local := filepath.Base(home)
+ if cancelled {
+ if _, err := r.state.db.Exec("UPDATE connect_attempts SET cancelled=1 WHERE id=?", id); err != nil {
+ t.Fatal(err)
+ }
+ }
+ r.limit = time.Nanosecond
+ r.connector()
+ want := map[bool]string{false: "timed_out", true: "cancelled"}[cancelled]
+ var end wire.ConnectionReport
+ r.waitFor(func() bool {
+ rs := r.reports(id)
+ if len(rs) == 0 {
+ return false
+ }
+ end = rs[len(rs)-1]
+ return end.State != wire.ConnConnecting
+ }, "the attempt's end")
+ if end.State != wire.ConnError || end.Reason != want {
+ t.Fatalf("end %+v", end)
+ }
+ var recorded string
+ _ = r.state.db.QueryRow("SELECT local_id FROM connect_attempts WHERE id=?", id).Scan(&recorded)
+ if recorded == "" {
+ t.Fatal("the attempt ended with no local id while its home survived")
+ }
+ r.waitFor(func() bool {
+ _, err := os.Lstat(home)
+ var owed int
+ _ = r.state.db.QueryRow("SELECT count(*) FROM connect_cleanups").Scan(&owed)
+ _, bound := r.binding(local)
+ return os.IsNotExist(err) && owed == 0 && !bound
+ }, "the expired token's binding and home deleted, nothing owed")
+ })
+ }
+}