carlos auth login: one pending file per attempt; approved ends the attempt
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
3 files changed,
+122
−28
auth.go+5 −3authpending.go+69 −24authpending_test.go+48 −1
Intent
Human
<task-notification> <task-id>b0l5z8q3s</task-id> <tool-use-id>toolu_014rVNTutgjU3UcATqURMTqE</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/a1de5273-c148-49b8-8267-3dee9d49c9c1/tasks/b0l5z8q3s.output</output-file> <status>completed</status> <summary>Background command "Run Astra whole-branch review" completed (exit code 0)</summary> </task-notification>
diff --git a/auth.go b/auth.go| index 3559b4e9a..e9ed0a058 100644 |
| --- a/auth.go |
| +++ b/auth.go |
| @@ -761,7 +761,7 @@ func pollLogin(ctx context.Context, c *consoleClient, base, deviceCode, label st |
| return terminalLoginError{errors.New("the console does not recognise this login. run this again")} |
| case "approved": |
| if poll.Token == "" { |
| - return errors.New("the console approved the login but returned no token") |
| + return terminalLoginError{errors.New("the console approved the login but returned no token. run carlos auth login again")} |
| } |
| now := time.Now().UTC() |
| expires := now.Add(90 * 24 * time.Hour) |
| @@ -770,14 +770,16 @@ func pollLogin(ctx context.Context, c *consoleClient, base, deviceCode, label st |
| expires = t |
| } |
| } |
| + // From here the console has consumed the attempt: a retry would be |
| + // told "unknown". So a storage failure ends the attempt too. |
| f, err := loadCredentials() |
| if err != nil { |
| - return err |
| + return terminalLoginError{fmt.Errorf("the console approved this login but the token could not be saved (%w). start a new login with carlos auth login", err)} |
| } |
| f.put(credential{Console: base, Address: poll.Address, Token: poll.Token, |
| Label: label, CreatedAt: now, ExpiresAt: expires}) |
| if err := f.save(); err != nil { |
| - return fmt.Errorf("storing the credential: %w", err) |
| + return terminalLoginError{fmt.Errorf("the console approved this login but the token could not be saved (%w). start a new login with carlos auth login", err)} |
| } |
| // Checked here as well as in whoami: this is the moment a bearer |
| // token first exists on this machine, and a pre-existing file with |
diff --git a/authpending.go b/authpending.go| index b781645af..adb9700ed 100644 |
| --- a/authpending.go |
| +++ b/authpending.go |
| @@ -1,10 +1,13 @@ |
| package main |
| import ( |
| + "crypto/sha256" |
| + "encoding/hex" |
| "encoding/json" |
| "errors" |
| "os" |
| "path/filepath" |
| + "strings" |
| "time" |
| ) |
| @@ -20,17 +23,27 @@ type pendingLogin struct { |
| Interval int `json:"interval"` |
| } |
| -// pendingLoginPath sits beside the credentials file, so one override |
| -// (CARLOS_CREDENTIALS) moves both. |
| +// pendingLoginPath is a directory beside the credentials file (so one |
| +// override, CARLOS_CREDENTIALS, moves both) holding one file per attempt. |
| +// One file per attempt means no process ever rewrites or removes another |
| +// attempt's file: a finishing --wait removes only its own exact path, so it |
| +// cannot take a newer --no-wait with it, and no OS lock is needed. |
| func pendingLoginPath() string { |
| - return filepath.Join(filepath.Dir(credentialsPath()), "login-pending") |
| + return filepath.Join(filepath.Dir(credentialsPath()), "login-pending.d") |
| } |
| -// savePendingLogin replaces the file, 0600, through a temp file in the same |
| -// directory. The device code is a secret until the login is claimed. |
| +// pendingLoginFile is the exact path for one attempt, named by a short hash |
| +// of its device code so the secret itself is not in a file name. |
| +func pendingLoginFile(deviceCode string) string { |
| + sum := sha256.Sum256([]byte(deviceCode)) |
| + return filepath.Join(pendingLoginPath(), hex.EncodeToString(sum[:16])+".json") |
| +} |
| + |
| +// savePendingLogin writes this attempt's own file, 0600 through a temp file |
| +// in the same directory, then removes every other attempt's file: the newest |
| +// --no-wait wins. The device code is a secret until the login is claimed. |
| func savePendingLogin(p pendingLogin) error { |
| - path := pendingLoginPath() |
| - dir := filepath.Dir(path) |
| + dir := pendingLoginPath() |
| if err := os.MkdirAll(dir, 0o700); err != nil { |
| return err |
| } |
| @@ -39,7 +52,7 @@ func savePendingLogin(p pendingLogin) error { |
| return err |
| } |
| body = append(body, '\n') |
| - tmp, err := os.CreateTemp(dir, ".login-pending-*") |
| + tmp, err := os.CreateTemp(dir, ".pending-*") |
| if err != nil { |
| return err |
| } |
| @@ -55,35 +68,67 @@ func savePendingLogin(p pendingLogin) error { |
| if err := tmp.Close(); err != nil { |
| return err |
| } |
| - return os.Rename(tmp.Name(), path) |
| + own := pendingLoginFile(p.DeviceCode) |
| + if err := os.Rename(tmp.Name(), own); err != nil { |
| + return err |
| + } |
| + entries, err := os.ReadDir(dir) |
| + if err != nil { |
| + return err |
| + } |
| + for _, e := range entries { |
| + path := filepath.Join(dir, e.Name()) |
| + if path == own || !strings.HasSuffix(e.Name(), ".json") { |
| + continue |
| + } |
| + if err := os.Remove(path); err != nil && !errors.Is(err, os.ErrNotExist) { |
| + return err |
| + } |
| + } |
| + return nil |
| } |
| -// loadPendingLogin returns nil, nil when no login is waiting. |
| +// loadPendingLogin returns the newest attempt (latest ExpiresAt), or nil, nil |
| +// when none is waiting. Expired attempts are still returned: --wait turns |
| +// one into the "expired" answer and removes it by its exact path. |
| func loadPendingLogin() (*pendingLogin, error) { |
| - raw, err := os.ReadFile(pendingLoginPath()) |
| + entries, err := os.ReadDir(pendingLoginPath()) |
| if errors.Is(err, os.ErrNotExist) { |
| return nil, nil |
| } |
| if err != nil { |
| return nil, err |
| } |
| - var p pendingLogin |
| - if err := json.Unmarshal(raw, &p); err != nil { |
| - return nil, errors.New(pendingLoginPath() + " is not readable as a pending login; delete it and run carlos auth login --no-wait again") |
| + var best *pendingLogin |
| + for _, e := range entries { |
| + if !strings.HasSuffix(e.Name(), ".json") { |
| + continue |
| + } |
| + raw, err := os.ReadFile(filepath.Join(pendingLoginPath(), e.Name())) |
| + if errors.Is(err, os.ErrNotExist) { |
| + continue |
| + } |
| + if err != nil { |
| + return nil, err |
| + } |
| + var p pendingLogin |
| + if err := json.Unmarshal(raw, &p); err != nil { |
| + return nil, errors.New(filepath.Join(pendingLoginPath(), e.Name()) + " is not readable as a pending login; delete it and run carlos auth login --no-wait again") |
| + } |
| + if best == nil || p.ExpiresAt.After(best.ExpiresAt) { |
| + cp := p |
| + best = &cp |
| + } |
| } |
| - return &p, nil |
| + return best, nil |
| } |
| -// clearPendingLoginIf deletes the file only if it still holds deviceCode, so |
| -// a --wait that finishes late cannot remove the login a newer --no-wait |
| -// started. Compare-then-remove, no OS lock: the window is two syscalls wide, |
| -// and it builds the same on every platform. |
| +// clearPendingLoginIf removes the file for exactly this attempt, by its own |
| +// path. It never reads or removes another attempt's file, so a --wait that |
| +// finishes late cannot delete the login a newer --no-wait started. The name |
| +// is kept from the single-file version; the "if" is now the path itself. |
| func clearPendingLoginIf(deviceCode string) error { |
| - p, err := loadPendingLogin() |
| - if err != nil || p == nil || p.DeviceCode != deviceCode { |
| - return nil |
| - } |
| - if err := os.Remove(pendingLoginPath()); err != nil && !errors.Is(err, os.ErrNotExist) { |
| + if err := os.Remove(pendingLoginFile(deviceCode)); err != nil && !errors.Is(err, os.ErrNotExist) { |
| return err |
| } |
| return nil |
diff --git a/authpending_test.go b/authpending_test.go| index d93f761ce..782f4a90a 100644 |
| --- a/authpending_test.go |
| +++ b/authpending_test.go |
| @@ -41,12 +41,59 @@ func TestPendingLoginNewerSurvivesOlderWait(t *testing.T) { |
| } |
| } |
| +// A --wait that loaded attempt A, then a --no-wait saved B, then A's cleanup |
| +// ran: B must survive and be what the next --wait picks. |
| +func TestPendingLoginInterleavedCleanupKeepsNewer(t *testing.T) { |
| + useTempCredentials(t) |
| + a := pendingLogin{Console: "https://a.example", DeviceCode: "dev-A", ExpiresAt: time.Now().Add(time.Minute)} |
| + if err := savePendingLogin(a); err != nil { |
| + t.Fatal(err) |
| + } |
| + loaded, err := loadPendingLogin() // the older --wait has A in hand |
| + if err != nil || loaded == nil || loaded.DeviceCode != "dev-A" { |
| + t.Fatalf("loaded = %+v, %v", loaded, err) |
| + } |
| + b := pendingLogin{Console: "https://b.example", DeviceCode: "dev-B", ExpiresAt: time.Now().Add(2 * time.Minute)} |
| + if err := savePendingLogin(b); err != nil { // a newer --no-wait lands |
| + t.Fatal(err) |
| + } |
| + if err := clearPendingLoginIf(loaded.DeviceCode); err != nil { // A's cleanup runs late |
| + t.Fatal(err) |
| + } |
| + if _, err := os.Stat(pendingLoginFile("dev-B")); err != nil { |
| + t.Fatalf("B's file is gone: %v", err) |
| + } |
| + if got, _ := loadPendingLogin(); got == nil || got.DeviceCode != "dev-B" { |
| + t.Fatalf("next --wait would pick %+v, want B", got) |
| + } |
| +} |
| + |
| +func TestAuthLoginApprovedButUnsavableEndsTheAttempt(t *testing.T) { |
| + path := useTempCredentials(t) |
| + fc := newFakeConsole(t) |
| + var out bytes.Buffer |
| + if err := authLogin(&out, []string{"-console", fc.ts.URL, "--no-wait"}); err != nil { |
| + t.Fatal(err) |
| + } |
| + // A directory where the credentials file should be: load and save both fail. |
| + if err := os.MkdirAll(path, 0o700); err != nil { |
| + t.Fatal(err) |
| + } |
| + err := authLogin(&out, []string{"--wait"}) |
| + if err == nil || !strings.Contains(err.Error(), "approved") || !strings.Contains(err.Error(), "could not be saved") { |
| + t.Fatalf("err = %v, want approved-but-not-saved", err) |
| + } |
| + if p, _ := loadPendingLogin(); p != nil { |
| + t.Fatalf("pending file survived a consumed attempt: %+v", p) |
| + } |
| +} |
| + |
| func TestPendingLoginFileMode(t *testing.T) { |
| useTempCredentials(t) |
| if err := savePendingLogin(pendingLogin{Console: "https://a.example", DeviceCode: "d"}); err != nil { |
| t.Fatal(err) |
| } |
| - fi, err := os.Stat(pendingLoginPath()) |
| + fi, err := os.Stat(pendingLoginFile("d")) |
| if err != nil { |
| t.Fatal(err) |
| } |