|
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 | funcmakeLoginCmd()*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 |
| -returncmd |
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 | +ifrawURL==""||!strings.HasPrefix(rawURL,"http") { |
| 32 | +returnxerrors.Errorf("invalid URL") |
| 33 | +} |
| 34 | +u,err:=url.Parse(rawURL) |
| 35 | +iferr!=nil { |
| 36 | +returnxerrors.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 | +iferr:=login(cmd,u,config.URL,config.Session);err!=nil { |
| 45 | +flog.Error("Login error: %s.",err) |
| 46 | +os.Exit(1) |
| 47 | +} |
28 | 48 |
|
29 |
| -funclogin(cmd*cobra.Command,args []string)error { |
30 |
| -rawURL:=args[0] |
31 |
| -ifrawURL==""||!strings.HasPrefix(rawURL,"http") { |
32 |
| -returnxerrors.Errorf("invalid URL") |
| 49 | +returnnil |
| 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 | +funcnewLocalListener() (net.Listener,error) { |
| 58 | +l,err:=net.Listen("tcp","127.0.0.1:0") |
36 | 59 | iferr!=nil {
|
37 |
| -returnxerrors.Errorf("parse url: %v",err) |
| 60 | +ifl,err=net.Listen("tcp6","[::1]:0");err!=nil { |
| 61 | +returnnil,xerrors.Errorf("listen on a port: %w",err) |
| 62 | +} |
38 | 63 | }
|
| 64 | +returnl,nil |
| 65 | +} |
39 | 66 |
|
40 |
| -listener,err:=net.Listen("tcp","127.0.0.1:0") |
41 |
| -iferr!=nil { |
42 |
| -returnxerrors.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 | +funcpingAPI(ctx context.Context,envURL*url.URL,tokenstring)error { |
| 70 | +client:=&coder.Client{BaseURL:envURL,Token:token} |
| 71 | +if_,err:=client.Me(ctx);err!=nil { |
| 72 | +returnxerrors.Errorf("call api: %w",err) |
43 | 73 | }
|
44 |
| -deferlistener.Close() |
| 74 | +returnnil |
| 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 | +funcstoreConfig(envURL*url.URL,sessionTokenstring,urlCfg,sessionCfg config.File)error { |
| 80 | +iferr:=urlCfg.Write(envURL.String());err!=nil { |
| 81 | +returnxerrors.Errorf("store env url: %w",err) |
48 | 82 | }
|
49 |
| -gofunc() { |
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 |
| -iferr!=nil { |
59 |
| -returnxerrors.Errorf("write url: %v",err) |
| 83 | +iferr:=sessionCfg.Write(sessionToken);err!=nil { |
| 84 | +returnxerrors.Errorf("store session token: %w",err) |
60 | 85 | }
|
| 86 | +returnnil |
| 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 | +funclogin(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 | iferr!=nil {
|
| 95 | +returnxerrors.Errorf("create local listener: %w",err) |
| 96 | +} |
| 97 | +deferfunc() {_=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 | +iferr:=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 |
| -iferr!=nil { |
79 |
| -returnxerrors.Errorf("set session: %v",err) |
| 110 | + |
| 111 | +// Create our channel, it is going to be the central synchronization of the command. |
| 112 | +tokenChan:=make(chanstring) |
| 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 | +deferfunc() {_=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 {returnsrv.Serve(listener) }) |
| 122 | +group.Go(func()error {returnloginsrv.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 | +gofunc() {deferclose(tokenChan);_=group.Wait() }() |
| 128 | + |
| 129 | +vartokenstring |
| 130 | +select { |
| 131 | +case<-ctx.Done(): |
| 132 | +returnctx.Err() |
| 133 | +casetoken=<-tokenChan: |
| 134 | +} |
| 135 | + |
| 136 | +// Perform an API call to verify that the token is valid. |
| 137 | +iferr:=pingAPI(ctx,envURL,token);err!=nil { |
| 138 | +returnxerrors.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 | +iferr:=storeConfig(envURL,token,urlCfg,sessionCfg);err!=nil { |
| 143 | +returnxerrors.Errorf("store config: %w",err) |
| 144 | +} |
| 145 | + |
| 146 | +flog.Success("Logged in.") |
| 147 | + |
82 | 148 | returnnil
|
83 | 149 | }
|