| 1 | package thin |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "crypto/rand" |
| 6 | "database/sql" |
| 7 | "encoding/json" |
| 8 | "errors" |
| 9 | "os" |
| 10 | "path/filepath" |
| 11 | "strings" |
| 12 | "time" |
| 13 | |
| 14 | "amadan.net/oficina/equipo/internal/runner" |
| 15 | "amadan.net/oficina/equipo/internal/runner/provider" |
| 16 | runnersetup "amadan.net/oficina/equipo/internal/runner/setup" |
| 17 | "amadan.net/oficina/equipo/internal/runnerproto" |
| 18 | "amadan.net/oficina/equipo/internal/sealbox" |
| 19 | "amadan.net/oficina/equipo/internal/wire" |
| 20 | "golang.org/x/sys/unix" |
| 21 | ) |
| 22 | |
| 23 | // Token connections (Connections spec §2.4, Paul 2026-11-09): the person |
| 24 | // runs `claude setup-token`, pastes the token into the app, which seals |
| 25 | // it to this runner's seal key; the instance relays the opaque box in a |
| 26 | // durable secret frame. The runner opens it, keeps the token only in the |
| 27 | // connection's dedicated home (provider.TokenFile, 0600), and the CLI |
| 28 | // reads it from CLAUDE_CODE_OAUTH_TOKEN. The token is never logged, put |
| 29 | // in an error, a report, argv or a frame. |
| 30 | |
| 31 | // sealMemory is how long a delivered (connection, attempt) is remembered. |
| 32 | const sealMemory = 24 * time.Hour |
| 33 | |
| 34 | // credentialPresent marks an attempt whose secret is committed. |
| 35 | const credentialPresent = "credential_present" |
| 36 | |
| 37 | // errStopped is a test fault: the process stops at a delivery boundary. |
| 38 | var errStopped = errors.New("stopped") |
| 39 | |
| 40 | // tokenAttempt is a token or sign-in attempt's row. |
| 41 | type tokenAttempt struct { |
| 42 | id, person, home, state, kind, secret, provider string |
| 43 | cancelled bool |
| 44 | } |
| 45 | |
| 46 | func (a tokenAttempt) waiting() bool { |
| 47 | return a.state == "running" && (a.kind == wire.KindToken || a.kind == wire.KindAPIKey) && !a.cancelled && a.secret == "" && a.home != "" |
| 48 | } |
| 49 | |
| 50 | // sealedFor is the provider and endpoint a box for the attempt must be |
| 51 | // bound to: Claude's API for a token, the provider's own origin for an |
| 52 | // API key (connectors spec §2.2). |
| 53 | func (a tokenAttempt) sealedFor() (string, string, bool) { |
| 54 | if a.kind == wire.KindAPIKey { |
| 55 | kp, ok := wire.APIKeyProviders[a.provider] |
| 56 | return a.provider, kp.Endpoint, ok |
| 57 | } |
| 58 | return wire.ProviderClaude, wire.EndpointAnthropic, a.provider == wire.ProviderClaude |
| 59 | } |
| 60 | |
| 61 | // signIn says the attempt is Claude's sign-in by the runner's own |
| 62 | // `claude setup-token` (signin.go): Claude, not a token. Once its token |
| 63 | // is committed it is a token attempt. |
| 64 | func (a tokenAttempt) signIn() bool { |
| 65 | return a.provider == wire.ProviderClaude && a.kind != wire.KindToken |
| 66 | } |
| 67 | |
| 68 | func (c *Connector) attempt(ctx context.Context, id string) (tokenAttempt, bool, error) { |
| 69 | a := tokenAttempt{id: id} |
| 70 | var cancelled int |
| 71 | err := c.State.db.QueryRowContext(ctx, "SELECT person, home, state, kind, secret, provider, cancelled FROM connect_attempts WHERE id=?", id).Scan(&a.person, &a.home, &a.state, &a.kind, &a.secret, &a.provider, &cancelled) |
| 72 | if errors.Is(err, sql.ErrNoRows) { |
| 73 | return a, false, nil |
| 74 | } |
| 75 | a.cancelled = cancelled == 1 |
| 76 | return a, err == nil, err |
| 77 | } |
| 78 | |
| 79 | // waitFor registers the attempt's wake channel. |
| 80 | func (c *Connector) waitFor(id string) chan struct{} { |
| 81 | c.mu.Lock() |
| 82 | defer c.mu.Unlock() |
| 83 | ch := make(chan struct{}, 1) |
| 84 | c.waits[id] = ch |
| 85 | return ch |
| 86 | } |
| 87 | |
| 88 | func (c *Connector) stopWaiting(id string) { |
| 89 | c.mu.Lock() |
| 90 | defer c.mu.Unlock() |
| 91 | delete(c.waits, id) |
| 92 | } |
| 93 | |
| 94 | func (c *Connector) wake(id string) { |
| 95 | c.mu.Lock() |
| 96 | ch := c.waits[id] |
| 97 | c.mu.Unlock() |
| 98 | if ch != nil { |
| 99 | select { |
| 100 | case ch <- struct{}{}: |
| 101 | default: |
| 102 | } |
| 103 | } |
| 104 | } |
| 105 | |
| 106 | // tokenHome is the attempt's dedicated home: the one it recorded, or a |
| 107 | // new one under the accounts root. |
| 108 | func (c *Connector) tokenHome(ctx context.Context, id string) (string, error) { |
| 109 | a, ok, err := c.attempt(ctx, id) |
| 110 | if err != nil || !ok { |
| 111 | return "", firstErr(err, provider.ErrIdentity) |
| 112 | } |
| 113 | if a.home != "" { |
| 114 | return a.home, provider.CheckLoginHome(a.home) |
| 115 | } |
| 116 | if err = os.MkdirAll(c.Root, 0700); err != nil { |
| 117 | return "", err |
| 118 | } |
| 119 | name := wire.ProviderClaude |
| 120 | if a.kind == wire.KindAPIKey { |
| 121 | if _, ok := wire.APIKeyProviders[a.provider]; !ok { |
| 122 | return "", provider.ErrIdentity |
| 123 | } |
| 124 | name = a.provider |
| 125 | } |
| 126 | next := nextHome |
| 127 | if a.kind == wire.KindAPIKey { |
| 128 | // Never reused: a frame for an earlier connection can never name |
| 129 | // a later one (security round, finding 4). |
| 130 | next = uniqueHome |
| 131 | } |
| 132 | _, home, err := next(c.Root, name) |
| 133 | if err == nil { |
| 134 | err = provider.CheckLoginHome(home) |
| 135 | } |
| 136 | if err == nil { |
| 137 | _, err = c.State.db.ExecContext(ctx, "UPDATE connect_attempts SET home=? WHERE id=?", home, id) |
| 138 | } |
| 139 | if err != nil && home != "" { |
| 140 | os.Remove(home) |
| 141 | } |
| 142 | return home, err |
| 143 | } |
| 144 | |
| 145 | // failToken ends an attempt not yet saved in error and removes its home, |
| 146 | // never while a secret is being delivered to it. A home that could not |
| 147 | // be deleted (still bound) goes through the durable sign-out. |
| 148 | func (c *Connector) failToken(cmd wire.ConnectCommand, base wire.ConnectionReport, home, reason string) { |
| 149 | r := base |
| 150 | r.State, r.Reason = wire.ConnError, reason |
| 151 | c.delivery.Lock() |
| 152 | defer c.delivery.Unlock() |
| 153 | c.removeHome(home) |
| 154 | if home != "" && exists(home) { |
| 155 | go c.endToken(cmd.Connection, cmd.Person, home, r.Reason) |
| 156 | return |
| 157 | } |
| 158 | c.finish(cmd.Connection, r) |
| 159 | } |
| 160 | |
| 161 | // runToken is a token attempt: a dedicated home, the card asking for the |
| 162 | // token, then the wait for its sealed secret (Secret); once committed, |
| 163 | // the status probe, the binding and the healthy report (madeToken). |
| 164 | func (c *Connector) runToken(ctx context.Context, cmd wire.ConnectCommand, base wire.ConnectionReport) { |
| 165 | failed := func(home, reason string) { c.failToken(cmd, base, home, reason) } |
| 166 | wake := c.waitFor(cmd.Connection) |
| 167 | defer c.stopWaiting(cmd.Connection) |
| 168 | home, err := c.tokenHome(ctx, cmd.Connection) |
| 169 | if err != nil { |
| 170 | c.log("connect home", err) |
| 171 | failed(home, "provider_refused") |
| 172 | return |
| 173 | } |
| 174 | a, _, err := c.attempt(ctx, cmd.Connection) |
| 175 | if err == nil && a.secret == "" { |
| 176 | r := base |
| 177 | r.State, r.Prompt = wire.ConnConnecting, &wire.ConnectPrompt{Kind: wire.PromptToken, Code: "claude setup-token"} |
| 178 | c.report(r) |
| 179 | } |
| 180 | for err == nil && a.secret == "" && a.state == "running" { |
| 181 | select { |
| 182 | case <-ctx.Done(): |
| 183 | failed(home, reasonOf(ctx.Err())) |
| 184 | return |
| 185 | case <-wake: |
| 186 | } |
| 187 | a, _, err = c.attempt(ctx, cmd.Connection) |
| 188 | } |
| 189 | if err != nil || a.state != "running" { |
| 190 | // Ended while it waited (a refused box), or unreadable. |
| 191 | if err != nil { |
| 192 | c.log("connect token", err) |
| 193 | failed(home, "provider_refused") |
| 194 | } |
| 195 | return |
| 196 | } |
| 197 | c.madeToken(ctx, cmd, base, home, a) |
| 198 | } |
| 199 | |
| 200 | // madeToken carries on an attempt whose token is committed in its home |
| 201 | // (pasted, or printed by the runner's own sign-in): the status probe, |
| 202 | // the binding, the real check and the healthy report. |
| 203 | func (c *Connector) madeToken(ctx context.Context, cmd wire.ConnectCommand, base wire.ConnectionReport, home string, a tokenAttempt) { |
| 204 | failed := func(home, reason string) { c.failToken(cmd, base, home, reason) } |
| 205 | id := filepath.Base(home) |
| 206 | lock, err := os.Open(home) |
| 207 | if err == nil { |
| 208 | err = unix.Flock(int(lock.Fd()), unix.LOCK_EX) |
| 209 | } |
| 210 | if err != nil { |
| 211 | if lock != nil { |
| 212 | lock.Close() |
| 213 | } |
| 214 | failed(home, "provider_refused") |
| 215 | return |
| 216 | } |
| 217 | defer lock.Close() |
| 218 | // A binding this attempt saved before a stop (its home and id, the |
| 219 | // person's): a restart carries on from it, never calling it a second |
| 220 | // connection of the same account. |
| 221 | saved, bound := c.savedToken(cmd.Person, id, home) |
| 222 | if a.cancelled || ctx.Err() != nil { |
| 223 | reason := reasonOf(firstErr(ctx.Err(), context.Canceled)) |
| 224 | if bound { |
| 225 | c.undoToken(cmd, id, lock, reason) |
| 226 | } else { |
| 227 | failed(home, reason) |
| 228 | } |
| 229 | return |
| 230 | } |
| 231 | if !bound { |
| 232 | // `auth status --json`, the token in the CLI's environment: the |
| 233 | // email, if it names one. It proves nothing about the token. |
| 234 | options := provider.LoginOptions{ClaudePath: c.Runner.ClaudePath, CodexPath: c.Runner.CodexPath} |
| 235 | refresh := func(ctx context.Context, b provider.Binding) (provider.Identity, error) { |
| 236 | return provider.RefreshLogin(ctx, b, options) |
| 237 | } |
| 238 | if c.Mac != nil { |
| 239 | // A Mac's: the token by descriptor, in its turn. |
| 240 | refresh = c.Mac.authStatus |
| 241 | } |
| 242 | observed, err := refresh(ctx, provider.Binding{ID: id, Home: home, Provider: wire.ProviderClaude, Token: true}) |
| 243 | if ctx.Err() != nil { |
| 244 | failed(home, reasonOf(ctx.Err())) |
| 245 | return |
| 246 | } |
| 247 | if err != nil { |
| 248 | c.log("connect token probe", err) |
| 249 | failed(home, "provider_refused") |
| 250 | return |
| 251 | } |
| 252 | for _, b := range c.mine(cmd.Person) { |
| 253 | if b.Provider == wire.ProviderClaude && b.AccountID == observed.AccountID { |
| 254 | failed(home, "already_connected") |
| 255 | return |
| 256 | } |
| 257 | } |
| 258 | if c.Conns != nil { |
| 259 | c.Conns.Forget(id) |
| 260 | if err = c.Conns.setExpiry(id, time.Now().Add(wire.TokenLifetime)); err != nil { |
| 261 | c.log("connect token", err) |
| 262 | failed(home, "provider_refused") |
| 263 | return |
| 264 | } |
| 265 | } |
| 266 | if err = saveToken(ctx, c.Runner.AccountBindingsPath, cmd.Person, id, home, observed); err != nil { |
| 267 | c.log("connect token binding", err) |
| 268 | failed(home, "provider_refused") |
| 269 | return |
| 270 | } |
| 271 | if c.stop("bound") != nil { |
| 272 | return |
| 273 | } |
| 274 | if saved, bound = c.savedToken(cmd.Person, id, home); !bound { |
| 275 | failed(home, "provider_refused") |
| 276 | return |
| 277 | } |
| 278 | } |
| 279 | // The real check (it takes the home's lock, as every launch does). |
| 280 | // Only an answer makes the connection. A refusal, or a check that |
| 281 | // cannot finish, ends the attempt provider_refused (the app's "This |
| 282 | // token was rejected"; an attempt never ends sign_in_again). |
| 283 | _ = unix.Flock(int(lock.Fd()), unix.LOCK_UN) |
| 284 | if err = c.verifyToken(ctx, saved); err != nil { |
| 285 | c.log("connect token check", err) |
| 286 | reason := "provider_refused" |
| 287 | if ctx.Err() != nil { |
| 288 | reason = reasonOf(ctx.Err()) |
| 289 | } |
| 290 | c.undoToken(cmd, id, lock, reason) |
| 291 | return |
| 292 | } |
| 293 | if c.Conns != nil { |
| 294 | c.Conns.Validated(id) |
| 295 | c.Conns.changed() |
| 296 | } |
| 297 | r := base |
| 298 | r.State, r.LocalID, r.Label = wire.ConnHealthy, id, profileLabel(saved, c.State.profileEmails()) |
| 299 | c.finish(cmd.Connection, r) |
| 300 | c.standOrGo(cmd, id, lock) |
| 301 | } |
| 302 | |
| 303 | // savedToken is the binding a token attempt saved for its home. |
| 304 | func (c *Connector) savedToken(person, id, home string) (runner.AccountBinding, bool) { |
| 305 | for _, b := range c.mine(person) { |
| 306 | if b.ID == id && b.ProviderHome == home && b.Kind == wire.KindToken { |
| 307 | return b, true |
| 308 | } |
| 309 | } |
| 310 | return runner.AccountBinding{}, false |
| 311 | } |
| 312 | |
| 313 | // verifyToken is a saved token's real check (Conns.Verify). An unfinished |
| 314 | // attempt always runs it, whatever the connection's health says: only a |
| 315 | // real request answered by the provider makes the token a connection. |
| 316 | func (c *Connector) verifyToken(ctx context.Context, b runner.AccountBinding) error { |
| 317 | if c.Conns == nil || c.Conns.Verify == nil { |
| 318 | return provider.ErrLoginUnavailable |
| 319 | } |
| 320 | return c.Conns.Verify(ctx, b) |
| 321 | } |
| 322 | |
| 323 | // undoToken ends an attempt whose saved token must not stand: its end |
| 324 | // and the sign-out it owes go in one transaction, so even after a stop |
| 325 | // the home and the token are deleted; then the sign-out runs. |
| 326 | func (c *Connector) undoToken(cmd wire.ConnectCommand, id string, lock *os.File, reason string) { |
| 327 | lock.Close() |
| 328 | k := cleanup{connection: cmd.Connection, person: cmd.Person, local: id} |
| 329 | r := wire.ConnectionReport{Connection: cmd.Connection, Person: cmd.Person, Provider: wire.ProviderClaude, State: wire.ConnError, Reason: reason} |
| 330 | err := c.State.tx(context.Background(), func(t *sql.Tx) error { |
| 331 | if _, err := t.Exec("UPDATE connect_attempts SET state='done', local_id=? WHERE id=?", id, cmd.Connection); err != nil { |
| 332 | return err |
| 333 | } |
| 334 | if err := c.State.enqueue(t, wire.FrameConnection, "", r); err != nil { |
| 335 | return err |
| 336 | } |
| 337 | return owe(t, k) |
| 338 | }) |
| 339 | c.log("connect token", err) |
| 340 | if c.Notify != nil { |
| 341 | c.Notify() |
| 342 | } |
| 343 | if err == nil && c.stop("owed") == nil { |
| 344 | c.settle(k) |
| 345 | } |
| 346 | } |
| 347 | |
| 348 | // endToken ends a token attempt found after a restart that cannot go on |
| 349 | // (its time is up). A home with a saved binding, or one that could not be |
| 350 | // deleted, goes through the durable sign-out: the attempt's end records |
| 351 | // its local id and the cleanup in one transaction, so the binding, the |
| 352 | // home and the token are deleted even across another stop; an attempt is |
| 353 | // never recorded ended with no local id while its home survives. A |
| 354 | // recorded cancel ends it cancelled. |
| 355 | func (c *Connector) endToken(id, person, home, reason string) { |
| 356 | var cancelled int |
| 357 | kind, prov := "", wire.ProviderClaude |
| 358 | _ = c.State.db.QueryRow("SELECT cancelled, kind, provider FROM connect_attempts WHERE id=?", id).Scan(&cancelled, &kind, &prov) |
| 359 | if cancelled == 1 { |
| 360 | reason = "cancelled" |
| 361 | } |
| 362 | if kind == wire.KindAPIKey { |
| 363 | c.endAPIKey(id, person, prov, home, reason) |
| 364 | return |
| 365 | } |
| 366 | r := wire.ConnectionReport{Connection: id, Person: person, Provider: wire.ProviderClaude, State: wire.ConnError, Reason: reason} |
| 367 | // The connection's local id is its home's name. |
| 368 | local := filepath.Base(home) |
| 369 | _, bound := c.savedToken(person, local, home) |
| 370 | if !bound { |
| 371 | c.removeHome(home) |
| 372 | if home == "" || !exists(home) { |
| 373 | c.finish(id, r) |
| 374 | return |
| 375 | } |
| 376 | } |
| 377 | k := cleanup{connection: id, person: person, local: local, home: home, provider: wire.ProviderClaude} |
| 378 | err := c.State.tx(context.Background(), func(t *sql.Tx) error { |
| 379 | if _, err := t.Exec("UPDATE connect_attempts SET state='done', local_id=? WHERE id=?", local, id); err != nil { |
| 380 | return err |
| 381 | } |
| 382 | if err := c.State.enqueue(t, wire.FrameConnection, "", r); err != nil { |
| 383 | return err |
| 384 | } |
| 385 | if err := owe(t, k); err != nil { |
| 386 | return err |
| 387 | } |
| 388 | _, err := t.Exec("UPDATE connect_cleanups SET home=?, provider=? WHERE connection=?", home, wire.ProviderClaude, id) |
| 389 | return err |
| 390 | }) |
| 391 | c.log("connect token", err) |
| 392 | if c.Notify != nil { |
| 393 | c.Notify() |
| 394 | } |
| 395 | if err == nil { |
| 396 | c.background(func() { c.settle(k) }) |
| 397 | } |
| 398 | } |
| 399 | |
| 400 | // tokenLabel is what a token connection is called: the account's email |
| 401 | // when the CLI reported one, else nothing (the app names it). |
| 402 | func tokenLabel(account string) string { |
| 403 | if strings.HasPrefix(account, "token:") { |
| 404 | return "" |
| 405 | } |
| 406 | return account |
| 407 | } |
| 408 | |
| 409 | // saveToken records a token home as the person's connection: the |
| 410 | // identity file and the binding (kind token). The token stays in the home. |
| 411 | func saveToken(ctx context.Context, bindings, person, id, home string, observed provider.Identity) error { |
| 412 | observed.HomeID = rand.Text() |
| 413 | raw, _ := json.Marshal(observed) |
| 414 | if err := os.WriteFile(filepath.Join(home, provider.IdentityFile), raw, 0600); err != nil { |
| 415 | return err |
| 416 | } |
| 417 | b := provider.Binding{ID: id, Home: home, Provider: wire.ProviderClaude, Token: true, AccountID: observed.AccountID, Expected: observed} |
| 418 | return runnersetup.SaveAccountBinding(ctx, bindings, person, DefaultModels[wire.ProviderClaude], runnerproto.AccountSetup{ID: id, Provider: wire.ProviderClaude, Label: id}, b) |
| 419 | } |
| 420 | |
| 421 | // resumeToken picks a token attempt up after a restart. Recovery (spec |
| 422 | // §2.4): a staged file with no seen_seals row is deleted (the resend is |
| 423 | // processed from received); with the row, the secret is committed and |
| 424 | // the final file must be there (a rename the stop interrupted is |
| 425 | // finished); a row with neither file cannot happen and ends the attempt |
| 426 | // in error. Then the attempt waits on for the rest of its time. |
| 427 | func (c *Connector) resumeToken(ctx context.Context, id, person, home, created, kind, prov string) error { |
| 428 | var rows int |
| 429 | if err := c.State.db.QueryRowContext(ctx, "SELECT count(*) FROM seen_seals WHERE connection_id=?", id).Scan(&rows); err != nil { |
| 430 | return err |
| 431 | } |
| 432 | if home != "" { |
| 433 | dir, err := os.Open(home) |
| 434 | if err != nil { |
| 435 | c.endToken(id, person, home, "runner_offline") |
| 436 | return nil |
| 437 | } |
| 438 | defer dir.Close() |
| 439 | fd := int(dir.Fd()) |
| 440 | if rows == 0 { |
| 441 | for _, name := range []string{provider.TokenStaging, provider.TokenFile} { |
| 442 | if err = unix.Unlinkat(fd, name, 0); err != nil && err != unix.ENOENT { |
| 443 | return err |
| 444 | } |
| 445 | } |
| 446 | if _, err = c.State.db.ExecContext(ctx, "UPDATE connect_attempts SET secret='' WHERE id=?", id); err != nil { |
| 447 | return err |
| 448 | } |
| 449 | } else { |
| 450 | var st unix.Stat_t |
| 451 | if unix.Fstatat(fd, provider.TokenFile, &st, unix.AT_SYMLINK_NOFOLLOW) == unix.ENOENT { |
| 452 | if err = unix.Renameat(fd, provider.TokenStaging, fd, provider.TokenFile); err != nil { |
| 453 | dir.Close() |
| 454 | c.endToken(id, person, home, "provider_refused") |
| 455 | return nil |
| 456 | } |
| 457 | } |
| 458 | } |
| 459 | if err = dir.Sync(); err != nil { |
| 460 | return err |
| 461 | } |
| 462 | } |
| 463 | at, _ := time.Parse(time.RFC3339Nano, created) |
| 464 | limit := c.Limit |
| 465 | if limit <= 0 { |
| 466 | limit = ConnectLimit |
| 467 | } |
| 468 | if !time.Now().Before(at.Add(limit)) { |
| 469 | c.endToken(id, person, home, "timed_out") |
| 470 | return nil |
| 471 | } |
| 472 | actx, cancel := context.WithDeadline(c.ctx, at.Add(limit)) |
| 473 | c.mu.Lock() |
| 474 | c.attempts[id] = cancel |
| 475 | c.mu.Unlock() |
| 476 | cmd := wire.ConnectCommand{Connection: id, Person: person, Provider: wire.ProviderClaude, Kind: wire.KindToken} |
| 477 | if kind == wire.KindAPIKey { |
| 478 | cmd.Provider, cmd.Kind = prov, wire.KindAPIKey |
| 479 | } |
| 480 | go c.run(actx, cancel, cmd) |
| 481 | return nil |
| 482 | } |
| 483 | |
| 484 | // Secret delivers a sealed secret to the token attempt it names (spec |
| 485 | // §2.4), one durable step at a time: (i) received, nothing written; |
| 486 | // (ii) staged: the box opened and checked, the token in the home's |
| 487 | // staging file, synced with the directory, the buffer zeroed; (iii) |
| 488 | // committed: one transaction records (connection, attempt, frame) in |
| 489 | // seen_seals and the attempt's credential_present, and the staging file |
| 490 | // is renamed to the token file, the directory synced; (iv) acked by the |
| 491 | // link once this returns nil. A resend of a delivered pair is acked and |
| 492 | // nothing else. A refused box ends a waiting attempt with a reason; one |
| 493 | // for no waiting attempt is acked and dropped. A box for a sign-in |
| 494 | // attempt is a code (code, signin.go). Nothing secret reaches a log, an |
| 495 | // error or a report. |
| 496 | func (c *Connector) Secret(ctx context.Context, frameID string, cmd wire.SecretCommand) error { |
| 497 | c.delivery.Lock() |
| 498 | defer c.delivery.Unlock() |
| 499 | s := cmd.Sealed |
| 500 | var n int |
| 501 | if err := c.State.db.QueryRowContext(ctx, "SELECT count(*) FROM seen_seals WHERE connection_id=? AND attempt=?", s.ConnectionID, s.Attempt).Scan(&n); err != nil { |
| 502 | return err |
| 503 | } |
| 504 | if n > 0 { |
| 505 | return nil |
| 506 | } |
| 507 | a, found, err := c.attempt(ctx, cmd.Connection) |
| 508 | if err != nil { |
| 509 | return err |
| 510 | } |
| 511 | if found && a.signIn() { |
| 512 | return c.code(ctx, frameID, cmd, a) |
| 513 | } |
| 514 | if !found || !a.waiting() { |
| 515 | c.refused("no_attempt") |
| 516 | return nil |
| 517 | } |
| 518 | refuse := func(reason string) error { |
| 519 | c.refused(reason) |
| 520 | r := wire.ConnectionReport{Connection: a.id, Person: a.person, Provider: a.provider, State: wire.ConnError, Reason: reason} |
| 521 | c.removeHome(a.home) |
| 522 | c.finish(a.id, r) |
| 523 | c.wake(a.id) |
| 524 | return nil |
| 525 | } |
| 526 | if c.Seal == nil { |
| 527 | return refuse("provider_refused") |
| 528 | } |
| 529 | p, err := c.Seal.Open(s, time.Now()) |
| 530 | if errors.Is(err, sealbox.ErrExpired) { |
| 531 | return refuse("timed_out") |
| 532 | } |
| 533 | if err != nil { |
| 534 | return refuse("provider_refused") |
| 535 | } |
| 536 | secret := []byte(p.Secret) |
| 537 | p.Secret = "" |
| 538 | defer clear(secret) |
| 539 | prov, endpoint, known := a.sealedFor() |
| 540 | if !known || p.RunnerID != c.RunnerID || c.RunnerID == "" || p.ConnectionID != cmd.Connection || cmd.Person != a.person || p.Provider != prov || p.Endpoint != endpoint || p.Attempt < 1 || !provider.ValidToken(secret) { |
| 541 | return refuse("provider_refused") |
| 542 | } |
| 543 | dir, err := pinHome(a.home) |
| 544 | if err != nil { |
| 545 | return err |
| 546 | } |
| 547 | defer dir.Close() |
| 548 | err = c.keep(ctx, a.id, a.kind, dir, secret, func(t *sql.Tx) error { |
| 549 | if _, err := t.Exec("INSERT INTO seen_seals(connection_id, attempt, frame_id, created_at) VALUES(?,?,?,?)", s.ConnectionID, s.Attempt, frameID, now()); err != nil { |
| 550 | return err |
| 551 | } |
| 552 | _, err := t.Exec("DELETE FROM seen_seals WHERE created_at < ?", time.Now().Add(-sealMemory).UTC().Format(time.RFC3339Nano)) |
| 553 | return err |
| 554 | }) |
| 555 | if errors.Is(err, errNotWaiting) { |
| 556 | // A cancel that won the race is acked. |
| 557 | c.refused("not_waiting") |
| 558 | return nil |
| 559 | } |
| 560 | if errors.Is(err, errMacRefused) { |
| 561 | // The Mac's guards refused it: nothing was written. |
| 562 | c.log("connect token", err) |
| 563 | return refuse("provider_refused") |
| 564 | } |
| 565 | if err != nil { |
| 566 | // Anything else is retried on the resend. |
| 567 | return err |
| 568 | } |
| 569 | c.wake(a.id) |
| 570 | return nil |
| 571 | } |
| 572 | |
| 573 | // keep makes secret the attempt's token in its home dir, one durable |
| 574 | // step at a time: (ii) staged: the home's staging file written, synced |
| 575 | // with the directory, the buffer zeroed; (iii) committed: one |
| 576 | // transaction marks the attempt credential_present and kind token (with |
| 577 | // record, the rest of that transaction), and the staging file is renamed |
| 578 | // to the token file, the directory synced. Not committed, nothing of it |
| 579 | // stays. errNotWaiting: the attempt was not waiting for it (a cancel won). |
| 580 | func (c *Connector) keep(ctx context.Context, id, kind string, dir *os.File, secret []byte, record func(*sql.Tx) error) error { |
| 581 | if c.Mac != nil { |
| 582 | // A Mac keeps a token in its turn, and only while its guards pass. |
| 583 | give, err := c.Mac.store(ctx) |
| 584 | if err != nil { |
| 585 | clear(secret) |
| 586 | return err |
| 587 | } |
| 588 | defer give() |
| 589 | } |
| 590 | err := stage(dir, secret) |
| 591 | clear(secret) |
| 592 | if err != nil { |
| 593 | return err |
| 594 | } |
| 595 | if err = c.stop("staged"); err != nil { |
| 596 | return err |
| 597 | } |
| 598 | err = c.State.tx(ctx, func(t *sql.Tx) error { |
| 599 | res, err := t.Exec("UPDATE connect_attempts SET secret=?, kind=? WHERE id=? AND state='running' AND cancelled=0 AND secret=''", credentialPresent, kind, id) |
| 600 | if err != nil { |
| 601 | return err |
| 602 | } |
| 603 | if n, err := res.RowsAffected(); err != nil || n != 1 { |
| 604 | return firstErr(err, errNotWaiting) |
| 605 | } |
| 606 | if err = record(t); err != nil { |
| 607 | return err |
| 608 | } |
| 609 | if err = unix.Renameat(int(dir.Fd()), provider.TokenStaging, int(dir.Fd()), provider.TokenFile); err != nil { |
| 610 | return err |
| 611 | } |
| 612 | if err = dir.Sync(); err != nil { |
| 613 | return err |
| 614 | } |
| 615 | // A stop here leaves the token file with no committed row: the |
| 616 | // restart deletes it. |
| 617 | return c.stop("transaction") |
| 618 | }) |
| 619 | if err != nil { |
| 620 | if !errors.Is(err, errStopped) { |
| 621 | _ = unix.Unlinkat(int(dir.Fd()), provider.TokenStaging, 0) |
| 622 | _ = unix.Unlinkat(int(dir.Fd()), provider.TokenFile, 0) |
| 623 | _ = dir.Sync() |
| 624 | } |
| 625 | return err |
| 626 | } |
| 627 | return c.stop("committed") |
| 628 | } |
| 629 | |
| 630 | var errNotWaiting = errors.New("the attempt is not waiting for its secret") |
| 631 | |
| 632 | // refused logs a refused or dropped box: the category only. |
| 633 | func (c *Connector) refused(reason string) { |
| 634 | if c.Logger != nil { |
| 635 | c.Logger.Info("sealed secret refused", "reason", reason) |
| 636 | } |
| 637 | } |
| 638 | |
| 639 | // stop is the test fault at a delivery boundary. |
| 640 | func (c *Connector) stop(stage string) error { |
| 641 | if c.fault != nil { |
| 642 | return c.fault(stage) |
| 643 | } |
| 644 | return nil |
| 645 | } |
| 646 | |
| 647 | // pinHome opens a home directory without following links. |
| 648 | func pinHome(home string) (*os.File, error) { |
| 649 | fd, err := unix.Open(home, unix.O_RDONLY|unix.O_DIRECTORY|unix.O_NOFOLLOW|unix.O_CLOEXEC, 0) |
| 650 | if err != nil { |
| 651 | return nil, err |
| 652 | } |
| 653 | return os.NewFile(uintptr(fd), home), nil |
| 654 | } |
| 655 | |
| 656 | // stage writes the secret to the home's staging file (0600, new) and |
| 657 | // syncs it and the directory. |
| 658 | func stage(dir *os.File, secret []byte) error { |
| 659 | dfd := int(dir.Fd()) |
| 660 | if err := unix.Unlinkat(dfd, provider.TokenStaging, 0); err != nil && err != unix.ENOENT { |
| 661 | return err |
| 662 | } |
| 663 | fd, err := unix.Openat(dfd, provider.TokenStaging, unix.O_WRONLY|unix.O_CREAT|unix.O_EXCL|unix.O_NOFOLLOW|unix.O_CLOEXEC, 0600) |
| 664 | if err != nil { |
| 665 | return err |
| 666 | } |
| 667 | f := os.NewFile(uintptr(fd), provider.TokenStaging) |
| 668 | _, err = f.Write(secret) |
| 669 | if err == nil { |
| 670 | err = f.Sync() |
| 671 | } |
| 672 | if cerr := f.Close(); err == nil { |
| 673 | err = cerr |
| 674 | } |
| 675 | if err == nil { |
| 676 | err = dir.Sync() |
| 677 | } |
| 678 | if err != nil { |
| 679 | _ = unix.Unlinkat(dfd, provider.TokenStaging, 0) |
| 680 | } |
| 681 | return err |
| 682 | } |
| 683 | |