package thin import ( "context" "database/sql" "encoding/json" "errors" "log/slog" "net/http" "os" "os/exec" "path/filepath" "slices" "sync" "time" "amadan.net/oficina/equipo/internal/runner" "amadan.net/oficina/equipo/internal/runner/connect" "amadan.net/oficina/equipo/internal/runner/containment" "amadan.net/oficina/equipo/internal/runner/metered" "amadan.net/oficina/equipo/internal/runner/provider" runnersetup "amadan.net/oficina/equipo/internal/runner/setup" "amadan.net/oficina/equipo/internal/sealbox" "amadan.net/oficina/equipo/internal/wire" "golang.org/x/sys/unix" ) const connectSchema = ` CREATE TABLE IF NOT EXISTS connect_attempts (id TEXT PRIMARY KEY, person TEXT NOT NULL, provider TEXT NOT NULL, same_machine INTEGER NOT NULL DEFAULT 0, state TEXT NOT NULL, home TEXT NOT NULL DEFAULT '', local_id TEXT NOT NULL DEFAULT '', cancelled INTEGER NOT NULL DEFAULT 0, created_at TEXT NOT NULL); CREATE TABLE IF NOT EXISTS connect_cleanups (connection TEXT PRIMARY KEY, person TEXT NOT NULL, local_id TEXT NOT NULL, report INTEGER NOT NULL, created_at TEXT NOT NULL); CREATE TABLE IF NOT EXISTS seen_seals (connection_id TEXT NOT NULL, attempt INTEGER NOT NULL, frame_id TEXT NOT NULL, created_at TEXT NOT NULL, PRIMARY KEY (connection_id, attempt)); ` // ConnectLimit ends an attempt the person did not finish (spec §2.1: ten // minutes with no progress; the Codex device code itself lasts fifteen). const ConnectLimit = 10 * time.Minute // Connector adds connections from the app (spec §2): a Codex account by // device code, a Claude account by the runner's own `claude setup-token` // with the sign-in code relayed sealed (signin.go), or from a pasted // token (token.go). // The provider's own CLI signs in, in a new dedicated home; the instance // only ever sees the provider's display code or sign-in page, the // account's email and boxes it cannot open. type Connector struct { Runner runner.Config State *State Conns *Conns // Root holds the dedicated homes (DefaultAccountsRoot). Root string Owners []string Notify func() Logger *slog.Logger // Limit bounds an attempt (default ConnectLimit). Limit time.Duration // Seal opens secrets sealed to this runner (nil: it accepts none); // RunnerID is the id they must be sealed for. Seal *sealbox.Keys RunnerID string // Manager contains a sign-in's `claude setup-token` (nil: Claude's // sign-in by a link is unavailable). Manager *containment.Manager // Mac is a Mac worker's credential operations (maccreds.go): its // guards before a token is stored or used, its darwin sign-in and // auth status, nil on Linux. Mac *macCreds // terminal starts setup-token for an attempt (contained, signin.go; // tests replace it); gone proves an attempt's namespace gone at // start (namespaceGone; tests replace it). terminal func(ctx context.Context, attempt string) (connect.Terminal, error) gone func(ctx context.Context, id string) error // spawn runs a cleanup in the background (a goroutine; tests replace // it to stop the process between a frame and its cleanup). spawn func(func()) // fault, in tests, stops a secret's delivery at a boundary ("staged", // "transaction", "committed"), a token attempt after its binding is // saved ("bound") or after a sign-out it owes is recorded ("owed"), // as if the process stopped there. fault func(stage string) error mu sync.Mutex attempts map[string]context.CancelFunc ctx context.Context // waits wakes a token attempt waiting for its secret; codes holds the // sign-in attempts waiting for a code. waits map[string]chan struct{} codes map[string]*codeWait // delivery serialises a secret's delivery with its attempt's end. delivery sync.Mutex // http and origin, in tests, send an API-key provider's requests to // a fake provider on 127.0.0.1 (apikey.go). http *http.Client origin func(provider string) string } // cleanup is a sign-out the connector owes: recorded in the transaction // that consumes its frame (or that finds a cancelled attempt saved), and // done again at startup until it is done. type cleanup struct { connection, person, local string report bool // home and provider: the signed-in home the sign-out deletes, kept in // the record from before the binding goes until the home is gone. home, provider string } func (c *Connector) background(f func()) { if c.spawn != nil { c.spawn(f) return } go f() } // owe records a cleanup in t. func owe(t *sql.Tx, k cleanup) error { report := 0 if k.report { report = 1 } _, err := t.Exec("INSERT INTO connect_cleanups(connection, person, local_id, report, created_at) VALUES(?,?,?,?,?) ON CONFLICT(connection) DO NOTHING", k.connection, k.person, k.local, report, now()) return err } // settle does one cleanup and, once done, forgets it; an attempt it // signed out is marked removed so its local id, reused later, is never // signed out again. func (c *Connector) settle(k cleanup) { if !c.remove(k) { return } _, err := c.State.db.Exec("DELETE FROM connect_cleanups WHERE connection=?", k.connection) c.log("disconnect record", err) _, err = c.State.db.Exec("UPDATE connect_attempts SET state='removed' WHERE id=? AND state='done'", k.connection) c.log("disconnect record", err) } func (c *Connector) log(msg string, err error) { if c.Logger != nil && err != nil { c.Logger.Warn(msg, "err", sanitize(err)) } } // Start reports attempts a previous process left unfinished (their sign-in // process died with it) and removes their unfinished homes. func (c *Connector) Start(ctx context.Context) error { c.mu.Lock() c.ctx, c.attempts, c.waits, c.codes = ctx, map[string]context.CancelFunc{}, map[string]chan struct{}{}, map[string]*codeWait{} c.mu.Unlock() if _, err := c.State.db.ExecContext(ctx, "DELETE FROM seen_seals WHERE created_at < ?", time.Now().Add(-sealMemory).UTC().Format(time.RFC3339Nano)); err != nil { return err } rows, err := c.State.db.QueryContext(ctx, "SELECT id, person, provider, home, kind, created_at, namespace FROM connect_attempts WHERE state='running'") if err != nil { return err } type left struct{ id, person, provider, home, kind, created, namespace string } var all []left for rows.Next() { var l left if err = rows.Scan(&l.id, &l.person, &l.provider, &l.home, &l.kind, &l.created, &l.namespace); err != nil { rows.Close() return err } all = append(all, l) } rows.Close() for _, l := range all { // A token attempt lost no process: it recovers its delivery and // waits on (or finishes) where it was. So does a sign-in attempt // whose token was committed (it is kind token then); one that was // not lost its CLI with the process, and ends below. if l.kind == wire.KindToken || l.kind == wire.KindAPIKey { if err = c.resumeToken(ctx, l.id, l.person, l.home, l.created, l.kind, l.provider); err != nil { return err } continue } // A sign-in's contained CLI is proven gone (its namespace killed // and its exit verified) before its home goes; one that cannot be // is left running, home and all, for the next start. if l.namespace != "" { if err = c.namespaceGone(ctx, l.namespace); err != nil { c.log("connect sign-in recovery", err) continue } } c.removeHome(l.home) c.finish(l.id, wire.ConnectionReport{Connection: l.id, Person: l.person, Provider: l.provider, State: wire.ConnError, Reason: "runner_offline"}) } if c.Mac != nil { // A Mac's Keychain watches its sign-ins left: settled once their // CLIs are proven gone (maccreds.go). c.Mac.settle(ctx, true) } // An attempt saved and then cancelled, stopped before it was signed // out: owed now. Then every cleanup still owed. if _, err = c.State.db.ExecContext(ctx, "INSERT INTO connect_cleanups(connection, person, local_id, report, created_at) SELECT id, person, local_id, 0, ? FROM connect_attempts WHERE state='done' AND cancelled=1 AND local_id<>'' ON CONFLICT(connection) DO NOTHING", now()); err != nil { return err } rows, err = c.State.db.QueryContext(ctx, "SELECT connection, person, local_id, report, home, provider FROM connect_cleanups ORDER BY created_at") if err != nil { return err } var owed []cleanup for rows.Next() { var k cleanup if err = rows.Scan(&k.connection, &k.person, &k.local, &k.report, &k.home, &k.provider); err != nil { rows.Close() return err } owed = append(owed, k) } rows.Close() for _, k := range owed { c.background(func() { c.settle(k) }) } return nil } // Accept records a connect command exactly once and starts the attempt. func (c *Connector) Accept(ctx context.Context, frameID string, cmd wire.ConnectCommand) error { fresh := false err := c.State.tx(ctx, func(t *sql.Tx) error { var err error if fresh, err = seen(t, frameID); err != nil || !fresh { return err } same := 0 if cmd.SameMachine { same = 1 } budget := "" if cmd.Budget != nil { raw, _ := json.Marshal(cmd.Budget) budget = string(raw) } _, err = t.Exec("INSERT INTO connect_attempts(id, person, provider, same_machine, state, kind, billing, budget, created_at) VALUES(?,?,?,?,?,?,?,?,?) ON CONFLICT DO NOTHING", cmd.Connection, cmd.Person, cmd.Provider, same, "running", cmd.Kind, cmd.Billing, budget, now()) return err }) if err != nil || !fresh { return err } // A token attempt's home is made before the next frame is read, so // its secret, however soon it follows, finds the attempt ready (the // attempt ends if this fails). _, apiKey := wire.APIKeyProviders[cmd.Provider] if (cmd.Kind == wire.KindToken && cmd.Provider == wire.ProviderClaude || cmd.Kind == wire.KindAPIKey && apiKey) && slices.Contains(c.Owners, cmd.Person) && (c.Mac == nil || macTakes(cmd)) { if _, herr := c.tokenHome(ctx, cmd.Connection); herr != nil { c.log("connect home", herr) } } c.mu.Lock() defer c.mu.Unlock() if c.ctx == nil { return errors.New("connector not started") } limit := c.Limit if limit <= 0 { limit = ConnectLimit } actx, cancel := context.WithTimeout(c.ctx, limit) c.attempts[cmd.Connection] = cancel go c.run(actx, cancel, cmd) return nil } // Cancel ends an attempt the person cancelled. The cancel is recorded in // the transaction that consumes the frame, so an attempt that succeeds // at the same moment sees it before it saves the connection, and one // already saved owes its sign-out from that same transaction. func (c *Connector) Cancel(ctx context.Context, frameID string, cmd wire.CancelConnectCommand) error { fresh := false var owed *cleanup err := c.State.tx(ctx, func(t *sql.Tx) error { var err error if fresh, err = seen(t, frameID); err != nil || !fresh { return err } if _, err = t.Exec("UPDATE connect_attempts SET cancelled=1 WHERE id=?", cmd.Connection); err != nil { return err } var state, local, person string err = t.QueryRow("SELECT state, local_id, person FROM connect_attempts WHERE id=?", cmd.Connection).Scan(&state, &local, &person) if errors.Is(err, sql.ErrNoRows) { return nil } if err != nil || state != "done" || local == "" { return err } // Ended already: a success the person cancelled does not stand // (the instance dropped its report); it is signed out here. owed = &cleanup{connection: cmd.Connection, person: person, local: local} return owe(t, *owed) }) if err != nil || !fresh { return err } c.mu.Lock() cancel := c.attempts[cmd.Connection] c.mu.Unlock() if cancel != nil { cancel() } if owed != nil { k := *owed c.background(func() { c.settle(k) }) } return nil } // Check is the person's Check again, once per frame: the connection's // real check runs in the background (a token's is a request that takes // seconds); its outcome reaches the instance in the next hello. func (c *Connector) Check(ctx context.Context, frameID string, cmd wire.CheckCommand) error { fresh := false err := c.State.tx(ctx, func(t *sql.Tx) error { var err error fresh, err = seen(t, frameID) return err }) if err != nil || !fresh { return err } if mc, ok, err := metered.Get(ctx, c.State.db, cmd.LocalID); err != nil { return err } else if ok { if mc.Person == cmd.Person && mc.Validated { c.checkMetered(mc) } return nil } b, ok := c.Conns.Binding(cmd.LocalID) if !ok || b.PersonID != cmd.Person { return nil } c.background(func() { ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute) defer cancel() c.Conns.CheckAgain(ctx, b.ID) if c.Notify != nil { c.Notify() } }) return nil } // Disconnect signs a connection out (DELETE /connections/{id}). A // command that names another runner (protocol 37: local ids repeat // across runners) is consumed and removes nothing here. func (c *Connector) Disconnect(ctx context.Context, frameID string, cmd wire.DisconnectCommand) error { fresh := false other := cmd.RunnerID != "" && cmd.RunnerID != c.RunnerID k := cleanup{connection: cmd.Connection, person: cmd.Person, local: cmd.LocalID, report: true} err := c.State.tx(ctx, func(t *sql.Tx) error { var err error if fresh, err = seen(t, frameID); err != nil || !fresh || other { return err } return owe(t, k) }) if err != nil || !fresh { return err } if other { c.log("disconnect", errors.New("a sign-out addressed to another runner; nothing removed")) return nil } c.background(func() { c.settle(k) }) return nil } // remove signs one of the person's connections out: the home is recorded // in the cleanup first; then the harness's own logout in it (tried // twice), the binding dropped, the home deleted, its state forgotten; // then signed_out is reported. A cleanup replayed after a stop finds the // home in its record when the binding has gone already. false: something // is left (the binding, or the home), and the cleanup is owed still; // success is never reported while the home exists. func (c *Connector) remove(k cleanup) bool { ctx, cancel := context.WithTimeout(context.Background(), time.Minute) defer cancel() b, bound := c.Conns.Binding(k.local) bound = bound && b.PersonID == k.person if bound { k.home, k.provider = b.ProviderHome, b.Provider if _, err := c.State.db.ExecContext(ctx, "UPDATE connect_cleanups SET home=?, provider=? WHERE connection=?", k.home, k.provider, k.connection); err != nil { c.log("disconnect record", err) return false } } // A metered connection has no binding: its record names its home. mc, isMetered, err := metered.Get(ctx, c.State.db, k.local) if err != nil { c.log("disconnect metered", err) return false } if isMetered = isMetered && mc.Person == k.person && !bound; isMetered { k.home, k.provider = mc.Home, mc.Provider if _, err := c.State.db.ExecContext(ctx, "UPDATE connect_cleanups SET home=?, provider=? WHERE connection=?", k.home, k.provider, k.connection); err != nil { c.log("disconnect record", err) return false } if !c.removeMetered(k) { return false } } _, apiKey := wire.APIKeyProviders[k.provider] // A Mac never runs a CLI it has not pinned (spec §8.2): its token's // sign-out is the home's deletion. if k.home != "" && exists(k.home) && !apiKey && c.Mac == nil { if lock, err := os.Open(k.home); err == nil { if unix.Flock(int(lock.Fd()), unix.LOCK_EX) == nil { if err := c.logout(ctx, k.provider, k.home); err != nil { c.log("disconnect logout", c.logout(ctx, k.provider, k.home)) } } lock.Close() } } if bound { if _, err := runnersetup.RemoveAccountBinding(ctx, c.Runner.AccountBindingsPath, b.ID); err != nil { c.log("disconnect binding", err) return false } c.Conns.Forget(b.ID) c.Conns.forgetExpiry(b.ID) c.Conns.changed() } if k.home != "" { c.removeHome(k.home) if exists(k.home) { c.log("disconnect home", errors.New("the home is still there")) return false } } if k.report { c.report(wire.ConnectionReport{Connection: k.connection, Person: k.person, LocalID: k.local, Provider: k.provider, State: wire.ConnSignedOut}) } return true } func exists(path string) bool { _, err := os.Lstat(path) return err == nil } // logout runs the provider's own sign-out in the home. func (c *Connector) logout(ctx context.Context, provider_, home string) error { binary, args := c.Runner.ClaudePath, []string{"auth", "logout"} if provider_ == wire.ProviderCodex { binary, args = c.Runner.CodexPath, []string{"logout"} } cmd := exec.CommandContext(ctx, binary, args...) cmd.Dir, cmd.Env = home, provider.LoginEnvironment(provider_, home) return cmd.Run() } // report sends progress on an attempt (durable). func (c *Connector) report(r wire.ConnectionReport) { err := c.State.tx(context.Background(), func(t *sql.Tx) error { return c.State.enqueue(t, wire.FrameConnection, "", r) }) c.log("connect report", err) if c.Notify != nil { c.Notify() } } // finish reports an attempt's end and marks it done, in one transaction. func (c *Connector) finish(id string, r wire.ConnectionReport) { 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=?", r.LocalID, id); err != nil { return err } return c.State.enqueue(t, wire.FrameConnection, "", r) }) c.log("connect report", err) if c.Notify != nil { c.Notify() } } func reasonOf(err error) string { switch { case errors.Is(err, connect.ErrTimedOut), errors.Is(err, context.DeadlineExceeded): return "timed_out" case errors.Is(err, connect.ErrCancelled), errors.Is(err, context.Canceled): return "cancelled" } return "provider_refused" } func (c *Connector) run(ctx context.Context, cancel context.CancelFunc, cmd wire.ConnectCommand) { defer cancel() defer func() { c.mu.Lock() delete(c.attempts, cmd.Connection) c.mu.Unlock() }() base := wire.ConnectionReport{Connection: cmd.Connection, Person: cmd.Person, Provider: cmd.Provider} fail := func(reason string) { r := base r.State, r.Reason = wire.ConnError, reason c.finish(cmd.Connection, r) } if c.Mac != nil && !macTakes(cmd) { // A Mac takes Claude alone; nothing of the attempt was made. fail(wire.ReasonMacClaudeOnly) return } if cmd.Kind == wire.KindAPIKey && slices.Contains(c.Owners, cmd.Person) { c.runAPIKey(ctx, cmd, base) return } if !slices.Contains(c.Owners, cmd.Person) || cmd.Provider != wire.ProviderClaude && cmd.Provider != wire.ProviderCodex { fail("provider_refused") return } if cmd.Kind == wire.KindToken { if cmd.Provider != wire.ProviderClaude { fail("provider_refused") return } c.runToken(ctx, cmd, base) return } // Claude signs in only by the runner's own setup-token now; a frame // that still says same_machine (an older instance) is the same. if cmd.Provider == wire.ProviderClaude { c.runSignIn(ctx, cmd, base) return } if err := os.MkdirAll(c.Root, 0700); err != nil { fail("provider_refused") return } id, home, err := nextHome(c.Root, cmd.Provider) if err == nil { err = provider.CheckLoginHome(home) } if err != nil { c.log("connect home", err) if home != "" { os.Remove(home) } fail("provider_refused") return } _, _ = c.State.db.Exec("UPDATE connect_attempts SET home=? WHERE id=?", home, cmd.Connection) lock, err := os.Open(home) if err == nil { err = unix.Flock(int(lock.Fd()), unix.LOCK_EX|unix.LOCK_NB) } if err != nil { if lock != nil { lock.Close() } c.removeHome(home) fail("provider_refused") return } defer lock.Close() env := provider.LoginEnvironment(cmd.Provider, home) acct, err := connect.CodexDeviceLogin(ctx, c.Runner.CodexPath, home, env, func(u, code string) { r := base r.State, r.Prompt = wire.ConnConnecting, &wire.ConnectPrompt{Kind: wire.PromptDeviceCode, URL: u, Code: code} c.report(r) }) if err != nil { c.log("connect sign-in", err) c.removeHome(home) fail(reasonOf(err)) return } // A cancel that came while the sign-in finished wins: nothing is saved. var cancelled int _ = c.State.db.QueryRow("SELECT cancelled FROM connect_attempts WHERE id=?", cmd.Connection).Scan(&cancelled) if cancelled == 1 || ctx.Err() != nil { c.removeHome(home) fail(reasonOf(firstErr(ctx.Err(), context.Canceled))) return } // The same account connected twice would only split one limit. observed, err := c.identify(ctx, cmd, id, home, acct.Email) if err != nil { c.removeHome(home) if errors.Is(err, errAlreadyConnected) { fail("already_connected") } else { c.log("connect identity", err) fail("identity_mismatch") } return } if c.Conns != nil { c.Conns.Forget(id) if acct.Limits != nil { c.Conns.Observe(id, *acct.Limits, acct.Plan) } c.Conns.changed() } r := base r.State, r.LocalID, r.Label, r.Plan = wire.ConnHealthy, id, observed.AccountID, acct.Plan if acct.Limits != nil { r.Headroom = acct.Limits.Headroom } c.finish(cmd.Connection, r) c.standOrGo(cmd, id, lock) } // standOrGo ends an attempt that saved its connection: one cancelled // while it was being saved does not stand. The attempt's lock on the // home is let go first: the sign-out takes the same lock. func (c *Connector) standOrGo(cmd wire.ConnectCommand, id string, lock *os.File) { lock.Close() var cancelled int _ = c.State.db.QueryRow("SELECT cancelled FROM connect_attempts WHERE id=?", cmd.Connection).Scan(&cancelled) if cancelled == 1 { k := cleanup{connection: cmd.Connection, person: cmd.Person, local: id} err := c.State.tx(context.Background(), func(t *sql.Tx) error { return owe(t, k) }) c.log("disconnect record", err) c.settle(k) } } func firstErr(errs ...error) error { for _, e := range errs { if e != nil { return e } } return nil } var errAlreadyConnected = errors.New("already connected") // identify records the signed-in home as a connection of the person's: // the account the home holds must be the one the person just signed in // (signedIn), and not one of theirs already. The home is read once; // what it reported is what is saved. func (c *Connector) identify(ctx context.Context, cmd wire.ConnectCommand, id, home, signedIn string) (provider.Identity, error) { options := provider.LoginOptions{ClaudePath: c.Runner.ClaudePath, CodexPath: c.Runner.CodexPath} probe, ok := provider.NewLoginDriver(options).(interface { Probe(context.Context, provider.Binding) (provider.Identity, error) }) if !ok { return provider.Identity{}, provider.ErrLoginUnavailable } observed, err := probe.Probe(ctx, provider.Binding{ID: id, Home: home, Provider: cmd.Provider}) if err != nil { return observed, err } if signedIn == "" || observed.AccountID != signedIn { return observed, provider.ErrIdentity } for _, b := range c.mine(cmd.Person) { if b.Provider == cmd.Provider && b.AccountID == observed.AccountID { return observed, errAlreadyConnected } } return observed, saveLogin(ctx, c.Runner, cmd.Person, cmd.Provider, id, home, observed) } func (c *Connector) mine(person string) []runner.AccountBinding { bs, _ := runner.LoadBindings(c.Runner.AccountBindingsPath) var out []runner.AccountBinding for _, b := range bs { if b.PersonID == person { out = append(out, b) } } return out } // removeHome deletes a home this connector created that never became a // connection: never one a binding names. func (c *Connector) removeHome(home string) { if home == "" || filepath.Dir(home) != filepath.Clean(c.Root) || c.meteredHome(home) { return } bs, _ := runner.LoadBindings(c.Runner.AccountBindingsPath) for _, b := range bs { if b.ProviderHome == home { return } } c.log("connect home", os.RemoveAll(home)) // The deletion (a token's file with its home) is made durable. if root, err := os.Open(c.Root); err == nil { c.log("connect home", root.Sync()) root.Close() } }