| 1 | package remotecmd |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "errors" |
| 6 | "fmt" |
| 7 | "log" |
| 8 | "net/http" |
| 9 | "os" |
| 10 | "os/exec" |
| 11 | "path/filepath" |
| 12 | "strings" |
| 13 | "time" |
| 14 | |
| 15 | "github.com/AzureAD/microsoft-authentication-library-for-go/apps/cache" |
| 16 | "github.com/AzureAD/microsoft-authentication-library-for-go/apps/public" |
| 17 | "github.com/gregjones/httpcache" |
| 18 | "github.com/gregjones/httpcache/diskcache" |
| 19 | "github.com/peterbourgon/diskv" |
| 20 | "github.com/sassoftware/relic/v7/lib/dlog" |
| 21 | "golang.org/x/oauth2" |
| 22 | ) |
| 23 | |
| 24 | type azureSource struct { |
| 25 | cli public.Client |
| 26 | useAT bool |
| 27 | scopes []string |
| 28 | } |
| 29 | |
| 30 | func azureTokenSource(authority, clientID string, scopes []string) (oauth2.TokenSource, error) { |
| 31 | if authority == "" || clientID == "" { |
| 32 | return nil, errors.New("authority and clientID are required") |
| 33 | } |
| 34 | if len(scopes) == 0 { |
| 35 | scopes = []string{"openid"} |
| 36 | } |
| 37 | s := &azureSource{scopes: scopes} |
| 38 | // The returned access token can be used if an app-specific scope was |
| 39 | // requested. Otherwise it will be an in opaque format and we must use the |
| 40 | // generic ID token. |
| 41 | for _, scope := range scopes { |
| 42 | if strings.HasPrefix(scope, "app://"+clientID) || strings.HasPrefix(scope, "https://") { |
| 43 | s.useAT = true |
| 44 | } |
| 45 | } |
| 46 | // cache both azure metadata and the resulting tokens |
| 47 | cacheBase, err := os.UserCacheDir() |
| 48 | if err != nil { |
| 49 | return nil, err |
| 50 | } |
| 51 | cacheBase = filepath.Join(cacheBase, "relic") |
| 52 | storage := diskv.New(diskv.Options{ |
| 53 | BasePath: cacheBase, |
| 54 | TempDir: filepath.Join(cacheBase, "tmp"), |
| 55 | CacheSizeMax: 10e6, |
| 56 | }) |
| 57 | // build HTTP transport with a cache |
| 58 | tr := loggingTransport{RoundTripper: http.DefaultTransport} |
| 59 | cache := httpcache.NewTransport(diskcache.NewWithDiskv(storage)) |
| 60 | cache.Transport = tr |
| 61 | hc := &http.Client{Transport: cache} |
| 62 | // configure MSAL |
| 63 | s.cli, err = public.New(clientID, |
| 64 | public.WithAuthority(authority), |
| 65 | public.WithCache(&dvCache{ |
| 66 | dv: storage, |
| 67 | key: "msal-" + clientID, |
| 68 | }), |
| 69 | public.WithHTTPClient(hc), |
| 70 | ) |
| 71 | if err != nil { |
| 72 | return nil, err |
| 73 | } |
| 74 | return oauth2.ReuseTokenSource(nil, s), nil |
| 75 | } |
| 76 | |
| 77 | func (s *azureSource) Token() (*oauth2.Token, error) { |
| 78 | // use cached token or silently refresh |
| 79 | if acc := s.cli.Accounts(); len(acc) != 0 { |
| 80 | result, err := s.cli.AcquireTokenSilent(context.Background(), s.scopes, public.WithSilentAccount(acc[0])) |
| 81 | if err != nil { |
| 82 | log.Println("warning: failed to refresh cached token:", err) |
| 83 | } else { |
| 84 | return s.toToken(result) |
| 85 | } |
| 86 | } |
| 87 | // use browser to interactively authenticate |
| 88 | fmt.Fprintln(os.Stderr, "attempting interactive login") |
| 89 | result, err := s.cli.AcquireTokenInteractive(context.Background(), s.scopes) |
| 90 | if err == nil { |
| 91 | return s.toToken(result) |
| 92 | } else if !errors.As(err, new(*exec.ExitError)) && !errors.As(err, new(*exec.Error)) { |
| 93 | return nil, err |
| 94 | } |
| 95 | // use device code |
| 96 | fmt.Fprintln(os.Stderr, "attempting device code login") |
| 97 | dc, err := s.cli.AcquireTokenByDeviceCode(context.Background(), s.scopes) |
| 98 | if err != nil { |
| 99 | return nil, err |
| 100 | } |
| 101 | fmt.Fprintln(os.Stderr) |
| 102 | fmt.Fprintln(os.Stderr, dc.Result.Message) |
| 103 | fmt.Fprintln(os.Stderr) |
| 104 | result, err = dc.AuthenticationResult(context.Background()) |
| 105 | if err != nil { |
| 106 | return nil, err |
| 107 | } |
| 108 | return s.toToken(result) |
| 109 | } |
| 110 | |
| 111 | func (s *azureSource) toToken(res public.AuthResult) (*oauth2.Token, error) { |
| 112 | if s.useAT { |
| 113 | return &oauth2.Token{ |
| 114 | AccessToken: res.AccessToken, |
| 115 | Expiry: res.ExpiresOn, |
| 116 | }, nil |
| 117 | } |
| 118 | return &oauth2.Token{ |
| 119 | AccessToken: res.IDToken.RawToken, |
| 120 | Expiry: time.Unix(res.IDToken.ExpirationTime, 0), |
| 121 | }, nil |
| 122 | } |
| 123 | |
| 124 | // dvCache adapts the diskv key-value store to act as MSAL's persistence layer |
| 125 | type dvCache struct { |
| 126 | dv *diskv.Diskv |
| 127 | key string |
| 128 | } |
| 129 | |
| 130 | func (c *dvCache) Export(cache cache.Marshaler, key string) { |
| 131 | data, err := cache.Marshal() |
| 132 | if err == nil { |
| 133 | err = c.dv.Write(c.key, data) |
| 134 | } |
| 135 | if err != nil { |
| 136 | log.Println("error: persisting access token:", err) |
| 137 | } |
| 138 | } |
| 139 | |
| 140 | func (c *dvCache) Replace(cache cache.Unmarshaler, key string) { |
| 141 | data, err := c.dv.Read(c.key) |
| 142 | if err == nil { |
| 143 | err = cache.Unmarshal(data) |
| 144 | } |
| 145 | if err != nil && !errors.Is(err, os.ErrNotExist) { |
| 146 | log.Println("error: reading cached access token:", err) |
| 147 | } |
| 148 | } |
| 149 | |
| 150 | type loggingTransport struct { |
| 151 | RoundTripper http.RoundTripper |
| 152 | } |
| 153 | |
| 154 | func (t loggingTransport) RoundTrip(req *http.Request) (*http.Response, error) { |
| 155 | dlog.Printf(3, "auth > %s %s", req.Method, req.URL) |
| 156 | resp, err := t.RoundTripper.RoundTrip(req) |
| 157 | if err != nil { |
| 158 | dlog.Printf(3, "auth < %+v", err) |
| 159 | } else { |
| 160 | dlog.Printf(3, "auth < %s", resp.Status) |
| 161 | } |
| 162 | return resp, err |
| 163 | } |