-
Notifications
You must be signed in to change notification settings - Fork 2
feat(auth): browser-assisted CLI login + profiles + auth/team commands #84
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
8072776
feat(auth): browser-assisted CLI login + profiles + auth/team command…
LanusseMorais d2b87eb
refactor(auth): rename 'lsh team' to 'lsh profile' to free up 'teams'…
LanusseMorais f8d34e8
fix(auth): address review feedback on PD-6071 multi-profile auth (per…
LanusseMorais 0522b42
fix(auth): send API-Version header on authclient requests and travers…
LanusseMorais f9e25e7
fix(auth): review fixes + tests for PD-6071 multi-profile auth (profi…
LanusseMorais File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,23 @@ | ||
| package cli | ||
|
|
||
| import "github.com/spf13/cobra" | ||
|
|
||
| func makeOperationAuthCmd() (*cobra.Command, error) { | ||
| cmd := &cobra.Command{ | ||
| Use: "auth", | ||
| Short: "Inspect and manage your authentication state", | ||
| } | ||
| statusCmd, err := makeOperationAuthStatusCmd() | ||
| if err != nil { | ||
| return nil, err | ||
| } | ||
| cmd.AddCommand(statusCmd) | ||
|
|
||
| logoutCmd, err := makeOperationAuthLogoutCmd() | ||
| if err != nil { | ||
| return nil, err | ||
| } | ||
| cmd.AddCommand(logoutCmd) | ||
|
|
||
| return cmd, nil | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,115 @@ | ||
| package cli | ||
|
|
||
| import ( | ||
| "context" | ||
| "errors" | ||
| "fmt" | ||
| "os" | ||
|
|
||
| "github.com/latitudesh/lsh/internal/authclient" | ||
| "github.com/latitudesh/lsh/internal/config" | ||
| "github.com/latitudesh/lsh/internal/version" | ||
| "github.com/spf13/cobra" | ||
| "github.com/spf13/viper" | ||
| ) | ||
|
|
||
| // defaultAPIVersion resolves the API version sent to the API, honoring | ||
| // LATITUDE_API_VERSION with a stable fallback. | ||
| func defaultAPIVersion() string { | ||
| if v := os.Getenv("LATITUDE_API_VERSION"); v != "" { | ||
| return v | ||
| } | ||
| return "2023-06-01" | ||
| } | ||
|
|
||
| func makeOperationLoginCmd() (*cobra.Command, error) { | ||
| cmd := &cobra.Command{ | ||
| Use: "login [DEPRECATED: api-token]", | ||
| Short: "Authenticate with Latitude", | ||
| Long: `Without arguments, opens your browser to authorize this CLI through the | ||
| Latitude dashboard and saves the resulting credential locally. | ||
|
|
||
| Pass --with-token <T> to skip the browser flow and use an existing token. | ||
|
|
||
| A positional <api-token> argument is still accepted for backward | ||
| compatibility but is deprecated and will be removed in a future release.`, | ||
| Args: cobra.MaximumNArgs(1), | ||
| RunE: runOperationLogin, | ||
| } | ||
| cmd.Flags().String("with-token", "", "use an existing API token instead of the browser flow") | ||
| cmd.Flags().String("profile", "", "save credentials under this profile name (default: team slug)") | ||
| return cmd, nil | ||
| } | ||
|
|
||
| func runOperationLogin(cmd *cobra.Command, args []string) error { | ||
| token, _ := cmd.Flags().GetString("with-token") | ||
| profileName, _ := cmd.Flags().GetString("profile") | ||
|
|
||
| if len(args) == 1 { | ||
| if token != "" { | ||
| return errors.New("cannot combine positional token with --with-token") | ||
| } | ||
| fmt.Fprintln(cmd.ErrOrStderr(), | ||
| "warning: passing the token as a positional argument is deprecated; use --with-token instead") | ||
| token = args[0] | ||
| } | ||
|
|
||
| ctx := cmd.Context() | ||
| if ctx == nil { | ||
| ctx = context.Background() | ||
| } | ||
|
|
||
| client := newAuthClient() | ||
|
|
||
| if token != "" { | ||
| return loginWithToken(ctx, client, token, profileName) | ||
| } | ||
| return loginViaBrowser(ctx, client, profileName) | ||
| } | ||
|
|
||
| // newAuthClient builds an authclient using the current hostname/scheme | ||
| // from viper. This is the same configuration the generated SDK uses, | ||
| // so dev overrides (--hostname / --scheme) flow through naturally. | ||
| func newAuthClient() *authclient.Client { | ||
| hostname := viper.GetString("hostname") | ||
| if hostname == "" { | ||
| hostname = "api.latitude.sh" | ||
| } | ||
| scheme := viper.GetString("scheme") | ||
| if scheme == "" { | ||
| scheme = "https" | ||
| } | ||
| ua := fmt.Sprintf("lsh/%s", version.Version) | ||
| return authclient.New(scheme+"://"+hostname, ua, defaultAPIVersion()) | ||
| } | ||
|
|
||
| // saveProfile resolves the profile name (override > team slug > "default") | ||
| // and upserts it in the config file. SetProfile promotes it to the default | ||
| // only when no default exists yet, so logging in to add a second profile | ||
| // (e.g. another team) does not silently change the active context — use | ||
| // `lsh profile use` to switch explicitly. | ||
| func saveProfile(override string, p config.Profile) (string, error) { | ||
| f, err := config.Load() | ||
| if err != nil { | ||
| return "", err | ||
| } | ||
| name := override | ||
| if name == "" { | ||
| name = p.TeamSlug | ||
| } | ||
| if name == "" { | ||
| // No override and no team slug (e.g. a token whose team lookup | ||
| // returned empty). Saving as "default" would silently overwrite an | ||
| // existing "default" profile's credential, so require an explicit | ||
| // name in that case. | ||
| if _, exists := f.Profiles["default"]; exists { | ||
| return "", errors.New("could not determine a profile name for this token (no team was returned); pass --profile <name> so an existing profile isn't overwritten") | ||
| } | ||
| name = "default" | ||
| } | ||
| f.SetProfile(name, p) | ||
| if err := config.Save(f); err != nil { | ||
| return "", err | ||
| } | ||
| return name, nil | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,165 @@ | ||
| package cli | ||
|
|
||
| import ( | ||
| "context" | ||
| "errors" | ||
| "fmt" | ||
| "os" | ||
| "os/signal" | ||
| "time" | ||
|
|
||
| "github.com/latitudesh/lsh/internal/authclient" | ||
| "github.com/latitudesh/lsh/internal/browser" | ||
| "github.com/latitudesh/lsh/internal/config" | ||
| "github.com/latitudesh/lsh/internal/version" | ||
| ) | ||
|
|
||
| const ( | ||
| pollInterval = 2 * time.Second | ||
| pollMaxBackoff = 5 * time.Second | ||
| loginTimeout = 5*time.Minute + 30*time.Second // a touch over the API TTL | ||
|
|
||
| // Window after CreateSession during which a 404 from the poll | ||
| // endpoint is treated as "not yet visible" instead of "expired". | ||
| // Covers initial Redis propagation and the gap between the create | ||
| // returning and the dashboard/CLI being able to read the session. | ||
| earlyNotFoundGrace = 15 * time.Second | ||
| ) | ||
|
|
||
| func loginViaBrowser(ctx context.Context, client *authclient.Client, profileOverride string) error { | ||
| ctx, cancel := signal.NotifyContext(ctx, os.Interrupt) | ||
| defer cancel() | ||
|
|
||
| session, err := client.CreateSession(ctx, authclient.CreateSessionRequest{ | ||
| ClientName: "lsh", | ||
| ClientVersion: version.Version, | ||
| }) | ||
| if err != nil { | ||
| return fmt.Errorf("could not start login session: %w", err) | ||
| } | ||
|
|
||
| headless := browser.LooksHeadless() | ||
| printAuthorizePrompt(session, headless) | ||
|
|
||
| if !headless { | ||
| if err := browser.Open(session.AuthorizeURL); err != nil { | ||
| fmt.Fprintln(os.Stderr, "Could not open browser automatically; please open the URL above manually.") | ||
| } | ||
| } | ||
|
|
||
| approved, err := pollUntilApproved(ctx, client, session.ID, session.Secret) | ||
| if err != nil { | ||
| return err | ||
| } | ||
|
|
||
| if approved.APIKey == nil || approved.Team == nil || approved.User == nil { | ||
| return errors.New("login session approved but the credential payload was incomplete") | ||
| } | ||
|
|
||
| profile := config.Profile{ | ||
| Authorization: approved.APIKey.Token, | ||
| KeyID: approved.APIKey.ID, | ||
| KeyName: approved.APIKey.Name, | ||
| TeamID: approved.Team.ID, | ||
| TeamName: approved.Team.Name, | ||
| TeamSlug: approved.Team.Slug, | ||
| Email: approved.User.Email, | ||
| Source: config.SourceBrowser, | ||
| APIVersion: defaultAPIVersion(), | ||
| } | ||
|
|
||
| name, err := saveProfile(profileOverride, profile) | ||
| if err != nil { | ||
| return fmt.Errorf("could not save profile: %w", err) | ||
| } | ||
|
|
||
| fmt.Printf("\n✅ Logged in as %s on team %s (profile: %s)\n", profile.Email, profile.TeamName, name) | ||
| return nil | ||
| } | ||
|
|
||
| func printAuthorizePrompt(session *authclient.Session, headless bool) { | ||
| fmt.Println("Opening your browser to authorize this CLI...") | ||
| fmt.Println() | ||
| fmt.Println(" URL:") | ||
| fmt.Printf(" %s\n", session.AuthorizeURL) | ||
| fmt.Println() | ||
| fmt.Println(" Confirm this code matches what your browser shows:") | ||
| fmt.Printf(" %s\n", session.UserCode) | ||
| if headless { | ||
| fmt.Println() | ||
| fmt.Println(" (detected headless environment — open the URL above on a machine with a browser)") | ||
| } | ||
| fmt.Println() | ||
| fmt.Println("Waiting for approval... press Ctrl+C to cancel.") | ||
| } | ||
|
|
||
| // pollUntilApproved retries GET /auth/cli_sessions/<id> until the | ||
| // session is approved, terminally errored, or the deadline expires. | ||
| func pollUntilApproved(ctx context.Context, client *authclient.Client, id, secret string) (*authclient.Session, error) { | ||
| start := time.Now() | ||
| deadline := start.Add(loginTimeout) | ||
| interval := pollInterval | ||
|
|
||
| for { | ||
| if ctx.Err() != nil { | ||
| return nil, ctx.Err() | ||
| } | ||
| session, err := client.PollSession(ctx, id, secret) | ||
| if err == nil { | ||
| // A successful response means the server is healthy; reset the | ||
| // interval so a previous transient error doesn't keep us polling | ||
| // at the backed-off rate for the rest of the session. | ||
| interval = pollInterval | ||
| if session.Status == "approved" { | ||
| if session.APIKey != nil { | ||
| return session, nil | ||
| } | ||
| // Approval and key are written together server-side, so an | ||
| // approved session with no key is anomalous — fail fast | ||
| // instead of polling silently until the deadline. | ||
| return nil, errors.New("login was approved but no API key was returned; please run `lsh login` again") | ||
| } | ||
| // status=pending → keep polling | ||
| } else { | ||
| var httpErr *authclient.HTTPError | ||
| if errors.As(err, &httpErr) { | ||
| switch httpErr.StatusCode { | ||
| case 404: | ||
| // 404 right after CreateSession just means the session | ||
| // has not propagated yet — retry within the grace | ||
| // window before treating it as terminal. | ||
| if time.Since(start) >= earlyNotFoundGrace { | ||
| return nil, errors.New("login session expired or was cancelled") | ||
| } | ||
| case 410: | ||
| return nil, errors.New("login session has already been used; please run `lsh login` again") | ||
| case 401: | ||
| return nil, errors.New("login session secret rejected (this should not happen)") | ||
| default: | ||
| // transient — back off and retry until deadline | ||
| } | ||
| } else { | ||
| // network error — back off and retry | ||
| } | ||
| interval = nextBackoff(interval) | ||
| } | ||
|
|
||
| if time.Now().After(deadline) { | ||
| return nil, errors.New("login session expired before approval") | ||
| } | ||
|
|
||
| select { | ||
| case <-ctx.Done(): | ||
| return nil, ctx.Err() | ||
| case <-time.After(interval): | ||
| } | ||
| } | ||
| } | ||
|
|
||
| func nextBackoff(current time.Duration) time.Duration { | ||
| doubled := current * 2 | ||
| if doubled > pollMaxBackoff { | ||
| return pollMaxBackoff | ||
| } | ||
| return doubled | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,80 @@ | ||
| package cli | ||
|
|
||
| import ( | ||
| "context" | ||
| "net/http" | ||
| "net/http/httptest" | ||
| "testing" | ||
|
|
||
| "github.com/latitudesh/lsh/internal/authclient" | ||
| "github.com/latitudesh/lsh/internal/browser" | ||
| "github.com/latitudesh/lsh/internal/config" | ||
| ) | ||
|
|
||
| func TestLoginWithTokenSavesProfile(t *testing.T) { | ||
| withTempHome(t) | ||
|
|
||
| srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | ||
| switch r.URL.Path { | ||
| case "/user/profile": | ||
| w.Write([]byte(`{"data":{"attributes":{"id":"u","email":"u@example.com"}}}`)) | ||
| case "/team": | ||
| w.Write([]byte(`{"data":[{"id":"team_abc","attributes":{"name":"Acme","slug":"acme"}}]}`)) | ||
| default: | ||
| t.Errorf("unexpected path %s", r.URL.Path) | ||
| } | ||
| })) | ||
| defer srv.Close() | ||
|
|
||
| client := authclient.New(srv.URL, "lsh-test", "2023-06-01") | ||
| if err := loginWithToken(context.Background(), client, "ak_xxx", ""); err != nil { | ||
| t.Fatalf("loginWithToken: %v", err) | ||
| } | ||
|
|
||
| f, _ := config.Load() | ||
| p, ok := f.Profiles["acme"] | ||
| if !ok { | ||
| t.Fatalf("expected profile 'acme', got %+v", f.Profiles) | ||
| } | ||
| if p.Authorization != "ak_xxx" || p.Email != "u@example.com" || p.TeamSlug != "acme" { | ||
| t.Fatalf("unexpected profile: %+v", p) | ||
| } | ||
| if p.Source != config.SourceWithToken { | ||
| t.Fatalf("expected with-token source, got %q", p.Source) | ||
| } | ||
| } | ||
|
|
||
| func TestLoginViaBrowserSavesProfile(t *testing.T) { | ||
| withTempHome(t) | ||
|
|
||
| prevOpener := browser.Opener | ||
| browser.Opener = func(string) error { return nil } | ||
| t.Cleanup(func() { browser.Opener = prevOpener }) | ||
|
|
||
| srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | ||
| switch { | ||
| case r.Method == http.MethodPost && r.URL.Path == "/auth/cli_sessions": | ||
| w.WriteHeader(http.StatusCreated) | ||
| w.Write([]byte(`{"data":{"id":"sid","secret":"shh","authorize_url":"https://example/auth","user_code":"WXYZ","expires_at":"2030-01-01T00:00:00Z"}}`)) | ||
| case r.Method == http.MethodGet && r.URL.Path == "/auth/cli_sessions/sid": | ||
| w.Write([]byte(`{"data":{"status":"approved","api_key":{"id":"k","token":"ak_browser","name":"lsh"},"team":{"id":"team_abc","name":"Acme","slug":"acme"},"user":{"id":"u","email":"u@example.com"}}}`)) | ||
| default: | ||
| t.Errorf("unexpected %s %s", r.Method, r.URL.Path) | ||
| } | ||
| })) | ||
| defer srv.Close() | ||
|
|
||
| client := authclient.New(srv.URL, "lsh-test", "2023-06-01") | ||
| if err := loginViaBrowser(context.Background(), client, ""); err != nil { | ||
| t.Fatalf("loginViaBrowser: %v", err) | ||
| } | ||
|
|
||
| f, _ := config.Load() | ||
| p, ok := f.Profiles["acme"] | ||
| if !ok { | ||
| t.Fatalf("expected profile 'acme', got %+v", f.Profiles) | ||
| } | ||
| if p.Authorization != "ak_browser" || p.KeyID != "k" || p.Source != config.SourceBrowser { | ||
| t.Fatalf("unexpected profile: %+v", p) | ||
| } | ||
| } |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.