diff --git a/internal/provider/commandcode_plan.go b/internal/provider/commandcode_plan.go index 15f6607a5..f0ee8da3d 100644 --- a/internal/provider/commandcode_plan.go +++ b/internal/provider/commandcode_plan.go @@ -19,6 +19,7 @@ package provider import ( "context" "encoding/json" + "errors" "fmt" "io" "net" @@ -416,6 +417,9 @@ func startCommandCodeSignIn(s *signInFlow) error { return nil } +// cmdWhoamiWait is how long a sign-in waits to ask whoami again. +var cmdWhoamiWait = time.Second + // cmdOrigins are the Studio pages that may post to the callback. var cmdOrigins = []string{"https://commandcode.ai", "https://staging.commandcode.ai"} @@ -540,8 +544,12 @@ func (s *signInFlow) commandCodeCallback(w http.ResponseWriter, r *http.Request) answer(true, "") } -// cmdSignedIn checks a new key and names its account, as the CLI does -// with whoami, and reads its plan. +// cmdSignedIn names a new key's account with whoami, and reads its plan. +// Only whoami turning the key down (401, 403) fails the sign-in: the CLI's +// own browser sign-in keeps the key Studio posts without asking whoami at +// all, and whoami has answered a key just made with a 500, so a whoami +// that errs is asked again a few times and then passed over for the name +// Studio sent with the key. func cmdSignedIn(ctx context.Context, a cmdAuth) (who, plan string, err error) { var me struct { User struct { @@ -551,8 +559,25 @@ func cmdSignedIn(ctx context.Context, a cmdAuth) (who, plan string, err error) { Email string `json:"email"` } `json:"user"` } - if err := accountJSON(ctx, cmdAPI+"/alpha/whoami", a.APIKey, nil, &me); err != nil { - return "", "", fmt.Errorf("Command Code didn't take the new key: %w", err) + for try := 0; ; try++ { + err := accountJSON(ctx, cmdAPI+"/alpha/whoami", a.APIKey, nil, &me) + var st *accountStatusError + if err == nil { + break + } + if errors.As(err, &st) && (st.status == http.StatusUnauthorized || st.status == http.StatusForbidden) { + return "", "", fmt.Errorf("Command Code didn't take the new key: %w", err) + } + if try == 2 || ctx.Err() != nil { + if firstNonEmpty(a.UserName, a.UserID) == "" { + return "", "", fmt.Errorf("Command Code couldn't say which account signed in: %w", err) + } + break + } + select { + case <-ctx.Done(): + case <-time.After(cmdWhoamiWait): + } } who = firstNonEmpty(me.User.UserName, a.UserName, me.User.Email, me.User.ID, a.UserID) if who == "" { diff --git a/internal/provider/commandcode_plan_test.go b/internal/provider/commandcode_plan_test.go index 52ac1c905..89cc5acac 100644 --- a/internal/provider/commandcode_plan_test.go +++ b/internal/provider/commandcode_plan_test.go @@ -9,6 +9,7 @@ import ( "os" "path/filepath" "strings" + "sync/atomic" "testing" "time" ) @@ -197,3 +198,56 @@ func TestCommandCodePlanName(t *testing.T) { t.Fatalf("ms: %v", tm) } } + +// A whoami that errs on a key just made doesn't fail the sign-in (tigger_ultra: +// "Command Code didn't take the new key: Internal Server Error"): it is asked +// again, then passed over for the name Studio sent; only a key it turns down +// fails. +func TestCommandCodeSignInWhoamiDown(t *testing.T) { + signIn(t) + var asked atomic.Int32 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + key := strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ") + switch { + case key == "bad-key": + w.WriteHeader(401) + case r.URL.Path == "/alpha/whoami": + asked.Add(1) + w.WriteHeader(500) + case r.URL.Path == "/alpha/billing/subscriptions": + _ = json.NewEncoder(w).Encode(map[string]any{"success": true, "data": map[string]any{"planId": "individual-pro-monthly", "status": "active"}}) + default: + w.WriteHeader(404) + } + })) + defer srv.Close() + oldAPI, oldWait := cmdAPI, cmdWhoamiWait + cmdAPI, cmdWhoamiWait = srv.URL, 10*time.Millisecond + defer func() { cmdAPI, cmdWhoamiWait = oldAPI, oldWait }() + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + noFollow := &http.Client{CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }} + + for _, c := range []struct{ key, user, state, errText string }{ + {"new-key", "tigger", "done", ""}, + {"bad-key", "evil", "failed", "Command Code didn't take the new key: Unauthorized"}, + {"new-key", "", "failed", "Command Code couldn't say which account signed in: Internal Server Error"}, + } { + asked.Store(0) + st, err := StartSignIn(CommandCodePlanID) + if err != nil { + t.Fatal(err) + } + u, _ := url.Parse(st.URL) + if _, err := noFollow.PostForm(u.Query().Get("callback"), url.Values{"apiKey": {c.key}, "state": {u.Query().Get("state")}, "userName": {c.user}}); err != nil { + t.Fatal(err) + } + st, _ = WaitSignIn(ctx, st.ID) + if st.State != c.state || st.Error != c.errText { + t.Fatalf("%s %q: %+v", c.key, c.user, st) + } + if c.state == "done" && (st.User != c.user || st.Plan != "Pro" || asked.Load() != 3) { + t.Fatalf("signed in: %+v, whoami asked %d times", st, asked.Load()) + } + } +}