|
1 | 1 | package cmd
|
2 | 2 |
|
3 | 3 | import (
|
| 4 | + "context" |
| 5 | + "fmt" |
4 | 6 | "net"
|
5 | 7 | "net/http"
|
6 | 8 | "net/url"
|
| 9 | + "os" |
7 | 10 | "strings"
|
8 |
| - "sync" |
9 | 11 |
|
| 12 | + "cdr.dev/coder-cli/coder-sdk" |
10 | 13 | "cdr.dev/coder-cli/internal/config"
|
11 | 14 | "cdr.dev/coder-cli/internal/loginsrv"
|
12 | 15 | "github.com/pkg/browser"
|
13 | 16 | "github.com/spf13/cobra"
|
| 17 | + "golang.org/x/sync/errgroup" |
14 | 18 | "golang.org/x/xerrors"
|
15 | 19 |
|
16 | 20 | "go.coder.com/flog"
|
17 | 21 | )
|
18 | 22 |
|
19 | 23 | func makeLoginCmd() *cobra.Command {
|
20 |
| - cmd := &cobra.Command{ |
21 |
| - Use: "login [Coder Enterprise URL eg. http://my.coder.domain/]", |
| 24 | + return &cobra.Command{ |
| 25 | + Use: "login [Coder Enterprise URL eg. https://my.coder.domain/]", |
22 | 26 | Short: "Authenticate this client for future operations",
|
23 | 27 | Args: cobra.ExactArgs(1),
|
24 |
| - RunE: login, |
25 |
| - } |
26 |
| - return cmd |
27 |
| -} |
| 28 | + RunE: func(cmd *cobra.Command, args []string) error { |
| 29 | + // Pull the URL from the args and do some sanity check. |
| 30 | + rawURL := args[0] |
| 31 | + if rawURL == "" || !strings.HasPrefix(rawURL, "http") { |
| 32 | + return xerrors.Errorf("invalid URL") |
| 33 | + } |
| 34 | + u, err := url.Parse(rawURL) |
| 35 | + if err != nil { |
| 36 | + return xerrors.Errorf("parse url: %w", err) |
| 37 | + } |
| 38 | + // Remove the trailing '/' if any. |
| 39 | + u.Path = strings.TrimSuffix(u.Path, "/") |
| 40 | + |
| 41 | + // From this point, the commandline is correct. |
| 42 | + // Don't return errors as it would print the usage. |
| 43 | + |
| 44 | + if err := login(cmd, u, config.URL, config.Session); err != nil { |
| 45 | + flog.Error("Login error: %s.", err) |
| 46 | + os.Exit(1) |
| 47 | + } |
28 | 48 |
|
29 |
| -func login(cmd *cobra.Command, args []string) error { |
30 |
| - rawURL := args[0] |
31 |
| - if rawURL == "" || !strings.HasPrefix(rawURL, "http") { |
32 |
| - return xerrors.Errorf("invalid URL") |
| 49 | + return nil |
| 50 | + }, |
33 | 51 | }
|
| 52 | +} |
34 | 53 |
|
35 |
| - u, err := url.Parse(rawURL) |
| 54 | +// newLocalListener creates up a local tcp server using port 0 (i.e. any available port). |
| 55 | +// If ipv4 is disabled, try ipv6. |
| 56 | +// It will be used by the http server waiting for the auth callback. |
| 57 | +func newLocalListener() (net.Listener, error) { |
| 58 | + l, err := net.Listen("tcp", "127.0.0.1:0") |
36 | 59 | if err != nil {
|
37 |
| - return xerrors.Errorf("parse url: %v", err) |
| 60 | + if l, err = net.Listen("tcp6", "[::1]:0"); err != nil { |
| 61 | + return nil, xerrors.Errorf("listen on a port: %w", err) |
| 62 | + } |
38 | 63 | }
|
| 64 | + return l, nil |
| 65 | +} |
39 | 66 |
|
40 |
| - listener, err := net.Listen("tcp", "127.0.0.1:0") |
41 |
| - if err != nil { |
42 |
| - return xerrors.Errorf("create login server: %+v", err) |
| 67 | +// pingAPI creates a client from the given url/token and try to exec an api call. |
| 68 | +// Not using the SDK as we want to verify the url/token pair before storing the config files. |
| 69 | +func pingAPI(ctx context.Context, envURL *url.URL, token string) error { |
| 70 | + client := &coder.Client{BaseURL: envURL, Token: token} |
| 71 | + if _, err := client.Me(ctx); err != nil { |
| 72 | + return xerrors.Errorf("call api: %w", err) |
43 | 73 | }
|
44 |
| - defer listener.Close() |
| 74 | + return nil |
| 75 | +} |
45 | 76 |
|
46 |
| - srv := &loginsrv.Server{ |
47 |
| - TokenCond: sync.NewCond(&sync.Mutex{}), |
| 77 | +// storeConfig writes the env URL and session token to the local config directory. |
| 78 | +// The config lib will handle the local config path lookup and creation. |
| 79 | +func storeConfig(envURL *url.URL, sessionToken string, urlCfg, sessionCfg config.File) error { |
| 80 | + if err := urlCfg.Write(envURL.String()); err != nil { |
| 81 | + return xerrors.Errorf("store env url: %w", err) |
48 | 82 | }
|
49 |
| - go func() { |
50 |
| - _ = http.Serve( |
51 |
| - listener, srv, |
52 |
| - ) |
53 |
| - }() |
54 |
| - |
55 |
| - err = config.URL.Write( |
56 |
| - (&url.URL{Scheme: u.Scheme, Host: u.Host}).String(), |
57 |
| - ) |
58 |
| - if err != nil { |
59 |
| - return xerrors.Errorf("write url: %v", err) |
| 83 | + if err := sessionCfg.Write(sessionToken); err != nil { |
| 84 | + return xerrors.Errorf("store session token: %w", err) |
60 | 85 | }
|
| 86 | + return nil |
| 87 | +} |
61 | 88 |
|
62 |
| - authURL := url.URL{ |
63 |
| - Scheme: u.Scheme, |
64 |
| - Host: u.Host, |
65 |
| - Path: "/internal-auth/", |
66 |
| - RawQuery: "local_service=http://" + listener.Addr().String(), |
67 |
| - } |
| 89 | +func login(cmd *cobra.Command, envURL *url.URL, urlCfg, sessionCfg config.File) error { |
| 90 | + ctx := cmd.Context() |
68 | 91 |
|
69 |
| - err = browser.OpenURL(authURL.String()) |
| 92 | + // Start by creating the listener so we can prompt the user with the URL. |
| 93 | + listener, err := newLocalListener() |
70 | 94 | if err != nil {
|
| 95 | + return xerrors.Errorf("create local listener: %w", err) |
| 96 | + } |
| 97 | + defer func() { _ = listener.Close() }() // Best effort. |
| 98 | + |
| 99 | + // Forge the auth URL with the callback set to the local server. |
| 100 | + authURL := *envURL |
| 101 | + authURL.Path = envURL.Path + "/internal-auth" |
| 102 | + authURL.RawQuery = "local_service=http://" + listener.Addr().String() |
| 103 | + |
| 104 | + // Try to open the browser on the local computer. |
| 105 | + if err := browser.OpenURL(authURL.String()); err != nil { |
| 106 | + // Discard the error as it is an expected one in non-X environments like over ssh. |
71 | 107 | // Tell the user to visit the URL instead.
|
72 |
| - flog.Info("visit %s to login", authURL.String()) |
| 108 | + _, _ = fmt.Fprintf(cmd.ErrOrStderr(), "Visit the following URL in your browser:\n\n\t%s\n\n", &authURL) // Can't fail. |
73 | 109 | }
|
74 |
| - srv.TokenCond.L.Lock() |
75 |
| - srv.TokenCond.Wait() |
76 |
| - err = config.Session.Write(srv.Token) |
77 |
| - srv.TokenCond.L.Unlock() |
78 |
| - if err != nil { |
79 |
| - return xerrors.Errorf("set session: %v", err) |
| 110 | + |
| 111 | + // Create our channel, it is going to be the central synchronization of the command. |
| 112 | + tokenChan := make(chan string) |
| 113 | + |
| 114 | + // Create the http server outside the errgroup goroutine scope so we can stop it later. |
| 115 | + srv := &http.Server{Handler: &loginsrv.Server{TokenChan: tokenChan}} |
| 116 | + defer func() { _ = srv.Close() }() // Best effort. Direct close as we are dealing with a one-off request. |
| 117 | + |
| 118 | + // Start both the readline and http server in parallel. As they are both long-running routines, |
| 119 | + // to know when to continue, we don't wait on the errgroup, but on the tokenChan. |
| 120 | + group, ctx := errgroup.WithContext(ctx) |
| 121 | + group.Go(func() error { return srv.Serve(listener) }) |
| 122 | + group.Go(func() error { return loginsrv.ReadLine(ctx, cmd.InOrStdin(), cmd.ErrOrStderr(), tokenChan) }) |
| 123 | + |
| 124 | + // Only close then tokenChan when the errgroup is done. Best effort basis. |
| 125 | + // Will not return the http route is used with a regular terminal. |
| 126 | + // Useful for non interactive session, manual input, tests or custom stdin. |
| 127 | + go func() { defer close(tokenChan); _ = group.Wait() }() |
| 128 | + |
| 129 | + var token string |
| 130 | + select { |
| 131 | + case <-ctx.Done(): |
| 132 | + return ctx.Err() |
| 133 | + case token = <-tokenChan: |
| 134 | + } |
| 135 | + |
| 136 | + // Perform an API call to verify that the token is valid. |
| 137 | + if err := pingAPI(ctx, envURL, token); err != nil { |
| 138 | + return xerrors.Errorf("ping API: %w", err) |
80 | 139 | }
|
81 |
| - flog.Success("logged in") |
| 140 | + |
| 141 | + // Success. Store the config only at this point so we don't override the local one in case of failure. |
| 142 | + if err := storeConfig(envURL, token, urlCfg, sessionCfg); err != nil { |
| 143 | + return xerrors.Errorf("store config: %w", err) |
| 144 | + } |
| 145 | + |
| 146 | + flog.Success("Logged in.") |
| 147 | + |
82 | 148 | return nil
|
83 | 149 | }
|
0 commit comments