Repository navigation
Expand file tree
/
Copy pathstatus.go
More file actions
554 lines (485 loc) · 19.3 KB
/
Copy pathstatus.go
File metadata and controls
554 lines (485 loc) · 19.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
package status
import (
"errors"
"fmt"
"net"
"net/http"
"path/filepath"
"slices"
"strings"
"time"
"github.com/MakeNowJust/heredoc"
"github.com/cli/cli/v2/api"
"github.com/cli/cli/v2/internal/config"
"github.com/cli/cli/v2/internal/gh"
"github.com/cli/cli/v2/internal/text"
"github.com/cli/cli/v2/pkg/cmd/auth/shared"
"github.com/cli/cli/v2/pkg/cmdutil"
"github.com/cli/cli/v2/pkg/iostreams"
"github.com/spf13/cobra"
)
type authEntryState string
const (
authEntryStateSuccess = "success"
authEntryStateTimeout = "timeout"
authEntryStateError = "error"
authEntryStateRefreshExpired = "refresh_expired"
)
type authEntry struct {
State authEntryState `json:"state"`
Error string `json:"error,omitempty"`
Active bool `json:"active"`
Host string `json:"host"`
Login string `json:"login"`
TokenSource string `json:"tokenSource"`
Token string `json:"token,omitempty"`
Scopes string `json:"scopes,omitempty"`
GitProtocol string `json:"gitProtocol"`
Refreshable bool `json:"refreshable,omitempty"`
TokenExpiresAt *time.Time `json:"tokenExpiresAt,omitempty"`
RefreshTokenExpiresAt *time.Time `json:"refreshTokenExpiresAt,omitempty"`
// justRefreshed reports whether gh renewed this account's expiring token during this run. It drives a
// display-only notice and is never serialized.
justRefreshed bool
// expiredWithoutRefresh reports whether the token check failed because the expiring token had already expired
// and --no-refresh kept gh from renewing it. It drives a display-only hint and is never serialized.
expiredWithoutRefresh bool
}
type authStatus struct {
Hosts map[string][]authEntry `json:"hosts"`
}
func newAuthStatus() *authStatus {
return &authStatus{
Hosts: make(map[string][]authEntry),
}
}
var authStatusFields = []string{
"hosts",
}
func (a authStatus) ExportData(fields []string) map[string]any {
return cmdutil.StructExportData(a, fields)
}
// timeNow is the clock used to render relative token-expiry times. It is a package variable so tests can pin it for
// deterministic output.
var timeNow = time.Now
// relativeToNow renders a fuzzy, human readable description of when t occurs relative to the current time, for
// annotating the absolute expiry timestamp. Future times read as "in about 7 hours" and already-elapsed times as
// "expired about 2 days ago".
func relativeToNow(t time.Time) string {
now := timeNow()
if t.After(now) {
return text.FuzzyIn(now, t)
}
return "expired " + text.FuzzyAgo(now, t)
}
func (e authEntry) String(cs *iostreams.ColorScheme) string {
var sb strings.Builder
switch e.State {
case authEntryStateSuccess:
sb.WriteString(
fmt.Sprintf(" %s Logged in to %s account %s (%s)\n", cs.SuccessIcon(), e.Host, cs.Bold(e.Login), e.TokenSource),
)
activeStr := fmt.Sprintf("%v", e.Active)
sb.WriteString(fmt.Sprintf(" - Active account: %s\n", cs.Bold(activeStr)))
sb.WriteString(fmt.Sprintf(" - Git operations protocol: %s\n", cs.Bold(e.GitProtocol)))
sb.WriteString(fmt.Sprintf(" - Token: %s\n", cs.Bold(e.Token)))
if e.Refreshable {
e.writeExpiry(&sb, cs)
if e.justRefreshed {
sb.WriteString(" - Token refreshed just now\n")
}
}
if expectScopes(e.Token) {
sb.WriteString(fmt.Sprintf(" - Token scopes: %s\n", cs.Bold(displayScopes(e.Scopes))))
if err := shared.HeaderHasMinimumScopes(e.Scopes); err != nil {
if missingScopesError, ok := errors.AsType[*shared.MissingScopesError](err); ok {
missingScopes := strings.Join(missingScopesError.MissingScopes, ",")
sb.WriteString(fmt.Sprintf(" %s Missing required token scopes: %s\n",
cs.WarningIcon(),
cs.Bold(displayScopes(missingScopes))))
refreshInstructions := fmt.Sprintf("gh auth refresh -h %s", e.Host)
sb.WriteString(fmt.Sprintf(" - To request missing scopes, run: %s\n", cs.Bold(refreshInstructions)))
}
}
}
case authEntryStateError:
if e.expiredWithoutRefresh {
sb.WriteString(fmt.Sprintf(" %s Token for %s account %s (%s) has expired\n", cs.Red("X"), e.Host, cs.Bold(e.Login), e.TokenSource))
activeStr := fmt.Sprintf("%v", e.Active)
sb.WriteString(fmt.Sprintf(" - Active account: %s\n", cs.Bold(activeStr)))
e.writeExpiry(&sb, cs)
if e.RefreshTokenExpiresAt != nil && !e.RefreshTokenExpiresAt.After(timeNow()) {
loginInstructions := fmt.Sprintf("gh auth login -h %s", e.Host)
sb.WriteString(fmt.Sprintf(" - To re-authenticate, run: %s\n", cs.Bold(loginInstructions)))
} else {
sb.WriteString(fmt.Sprintf(" - To refresh it, run %s (without %s)\n", cs.Bold("gh auth status"), cs.Bold("--no-refresh")))
}
break
}
if e.Login != "" {
sb.WriteString(fmt.Sprintf(" %s Failed to log in to %s account %s (%s)\n", cs.Red("X"), e.Host, cs.Bold(e.Login), e.TokenSource))
} else {
sb.WriteString(fmt.Sprintf(" %s Failed to log in to %s using token (%s)\n", cs.Red("X"), e.Host, e.TokenSource))
}
activeStr := fmt.Sprintf("%v", e.Active)
sb.WriteString(fmt.Sprintf(" - Active account: %s\n", cs.Bold(activeStr)))
sb.WriteString(fmt.Sprintf(" - The token in %s is invalid.\n", e.TokenSource))
if authTokenWriteable(e.TokenSource) {
loginInstructions := fmt.Sprintf("gh auth login -h %s", e.Host)
if shared.AuthTokenRefreshable(e.Token, e.TokenSource) {
loginInstructions = fmt.Sprintf("gh auth refresh -h %s", e.Host)
}
logoutInstructions := fmt.Sprintf("gh auth logout -h %s -u %s", e.Host, e.Login)
sb.WriteString(fmt.Sprintf(" - To re-authenticate, run: %s\n", cs.Bold(loginInstructions)))
sb.WriteString(fmt.Sprintf(" - To forget about this account, run: %s\n", cs.Bold(logoutInstructions)))
}
case authEntryStateTimeout:
if e.Login != "" {
sb.WriteString(fmt.Sprintf(" %s Timeout trying to log in to %s account %s (%s)\n", cs.Red("X"), e.Host, cs.Bold(e.Login), e.TokenSource))
} else {
sb.WriteString(fmt.Sprintf(" %s Timeout trying to log in to %s using token (%s)\n", cs.Red("X"), e.Host, e.TokenSource))
}
activeStr := fmt.Sprintf("%v", e.Active)
sb.WriteString(fmt.Sprintf(" - Active account: %s\n", cs.Bold(activeStr)))
case authEntryStateRefreshExpired:
if e.Login != "" {
sb.WriteString(fmt.Sprintf(" %s Refresh token for %s account %s was rejected\n", cs.Red("X"), e.Host, cs.Bold(e.Login)))
} else {
sb.WriteString(fmt.Sprintf(" %s Refresh token for %s was rejected\n", cs.Red("X"), e.Host))
}
activeStr := fmt.Sprintf("%v", e.Active)
sb.WriteString(fmt.Sprintf(" - Active account: %s\n", cs.Bold(activeStr)))
sb.WriteString(" - The stored expiring credential was removed because its refresh token is no longer valid.\n")
loginInstructions := fmt.Sprintf("gh auth login -h %s", e.Host)
sb.WriteString(fmt.Sprintf(" - To re-authenticate, run: %s\n", cs.Bold(loginInstructions)))
}
if e.Error != "" {
sb.WriteString(fmt.Sprintf(" - Error: %s\n", e.Error))
}
return sb.String()
}
func (e authEntry) writeExpiry(sb *strings.Builder, cs *iostreams.ColorScheme) {
sb.WriteString(" - Expiring token that gh refreshes automatically\n")
if e.TokenExpiresAt != nil {
expiresAt := e.TokenExpiresAt.UTC()
sb.WriteString(fmt.Sprintf(" - Token expires: %s (%s)\n",
cs.Bold(expiresAt.Format(time.RFC3339)), relativeToNow(expiresAt)))
}
if e.RefreshTokenExpiresAt != nil {
refreshExpiresAt := e.RefreshTokenExpiresAt.UTC()
sb.WriteString(fmt.Sprintf(" - Refresh token expires: %s (%s)\n",
cs.Bold(refreshExpiresAt.Format(time.RFC3339)), relativeToNow(refreshExpiresAt)))
}
}
type StatusOptions struct {
HttpClient func() (*http.Client, error)
IO *iostreams.IOStreams
Config func() (gh.Config, error)
Exporter cmdutil.Exporter
Hostname string
ShowToken bool
Active bool
NoRefresh bool
}
func NewCmdStatus(f *cmdutil.Factory, runF func(*StatusOptions) error) *cobra.Command {
opts := &StatusOptions{
HttpClient: f.HttpClient,
IO: f.IOStreams,
Config: f.Config,
}
cmd := &cobra.Command{
Use: "status",
Args: cobra.ExactArgs(0),
Short: "Display active account and authentication state on each known GitHub host",
Long: heredoc.Docf(`
Display active account and authentication state on each known GitHub host.
For each host, the authentication state of each known account is tested and any issues are included in the output.
Each host section will indicate the active account, which will be used when targeting that host.
If an account on any host (or only the one given via %[1]s--hostname%[1]s) has authentication issues,
the command will exit with 1 and output to stderr. Note that when using the %[1]s--json%[1]s option, the command
will always exit with zero regardless of any authentication issues, unless there is a fatal error.
Any expired or near-expiry token that supports refreshing is refreshed automatically, unless %[1]s--no-refresh%[1]s is given.
To change the active account for a host, see %[1]sgh auth switch%[1]s.
`, "`"),
Example: heredoc.Doc(`
# Display authentication status for all accounts on all hosts
$ gh auth status
# Display authentication status for the active account on a specific host
$ gh auth status --active --hostname github.example.com
# Display tokens in plain text
$ gh auth status --show-token
# Format authentication status as JSON
$ gh auth status --json hosts
# Include plain text token in JSON output
$ gh auth status --json hosts --show-token
# Format hosts as a flat JSON array
$ gh auth status --json hosts --jq '.hosts | add'
`),
RunE: func(cmd *cobra.Command, args []string) error {
if runF != nil {
return runF(opts)
}
return statusRun(opts)
},
}
cmd.Flags().StringVarP(&opts.Hostname, "hostname", "h", "", "Check only a specific hostname's auth status")
cmd.Flags().BoolVarP(&opts.ShowToken, "show-token", "t", false, "Display the auth token")
cmd.Flags().BoolVarP(&opts.Active, "active", "a", false, "Display the active account only")
cmd.Flags().BoolVar(&opts.NoRefresh, "no-refresh", false, "Do not automatically refresh expired tokens")
// the json flags are intentionally not given a shorthand to avoid conflict with -t/--show-token
cmdutil.AddJSONFlagsWithoutShorthand(cmd, &opts.Exporter, authStatusFields)
return cmd
}
func statusRun(opts *StatusOptions) error {
cfg, err := opts.Config()
if err != nil {
return err
}
authCfg := cfg.Authentication()
stderr := opts.IO.ErrOut
stdout := opts.IO.Out
cs := opts.IO.ColorScheme()
hostnames := authCfg.Hosts()
if len(hostnames) == 0 {
fmt.Fprintf(stderr,
"You are not logged into any GitHub hosts. To log in, run: %s\n", cs.Bold("gh auth login"))
if opts.Exporter != nil {
// In machine-friendly mode, we always exit with no error.
opts.Exporter.Write(opts.IO, newAuthStatus())
return nil
}
return cmdutil.SilentError
}
if opts.Hostname != "" && !slices.Contains(hostnames, opts.Hostname) {
fmt.Fprintf(stderr,
"You are not logged into any accounts on %s\n", opts.Hostname)
if opts.Exporter != nil {
// In machine-friendly mode, we always exit with no error.
opts.Exporter.Write(opts.IO, newAuthStatus())
return nil
}
return cmdutil.SilentError
}
httpClient, err := opts.HttpClient()
if err != nil {
return err
}
var finalErr error
statuses := newAuthStatus()
for _, hostname := range hostnames {
if opts.Hostname != "" && opts.Hostname != hostname {
continue
}
var activeUser string
gitProtocol := cfg.GitProtocol(hostname).Value
activeCred, activeRefreshStatus := resolveCredential(authCfg, hostname, "", opts.NoRefresh)
if authTokenWriteable(activeCred.Source) {
activeUser, _ = authCfg.ActiveUser(hostname)
}
entry := buildEntry(httpClient, buildEntryOptions{
active: true,
gitProtocol: gitProtocol,
hostname: hostname,
credential: activeCred,
refreshStatus: activeRefreshStatus,
noRefresh: opts.NoRefresh,
username: activeUser,
})
statuses.Hosts[hostname] = append(statuses.Hosts[hostname], entry)
if finalErr == nil && entry.State != authEntryStateSuccess {
finalErr = cmdutil.SilentError
}
if opts.Active {
continue
}
users := authCfg.UsersForHost(hostname)
for _, username := range users {
if username == activeUser {
continue
}
cred, refreshStatus := resolveCredential(authCfg, hostname, username, opts.NoRefresh)
entry := buildEntry(httpClient, buildEntryOptions{
active: false,
gitProtocol: gitProtocol,
hostname: hostname,
credential: cred,
refreshStatus: refreshStatus,
noRefresh: opts.NoRefresh,
username: username,
})
statuses.Hosts[hostname] = append(statuses.Hosts[hostname], entry)
if finalErr == nil && entry.State != authEntryStateSuccess {
finalErr = cmdutil.SilentError
}
}
}
if !opts.ShowToken {
for _, host := range statuses.Hosts {
for i := range host {
if opts.Exporter != nil {
// In machine-readable we just drop the token
host[i].Token = ""
} else {
host[i].Token = maskToken(host[i].Token)
}
}
}
}
if opts.Exporter != nil {
// In machine-friendly mode, we always exit with no error.
opts.Exporter.Write(opts.IO, statuses)
return nil
}
prevEntry := false
for _, hostname := range hostnames {
entries, ok := statuses.Hosts[hostname]
if !ok {
continue
}
stream := stdout
if finalErr != nil {
stream = stderr
}
if prevEntry {
fmt.Fprint(stream, "\n")
}
prevEntry = true
fmt.Fprintf(stream, "%s\n", cs.Bold(hostname))
for i, entry := range entries {
fmt.Fprintf(stream, "%s", entry.String(cs))
if i < len(entries)-1 {
fmt.Fprint(stream, "\n")
}
}
}
return finalErr
}
// knownTokenPrefixes contains GitHub's token format prefixes.
// See [GitHub token formats].
//
// TODO: gh.TokenTypes now carries these same prefixes, so this list duplicates
// it. Use that instead.
//
// [GitHub token formats]: https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/about-authentication-to-github#githubs-token-formats
var knownTokenPrefixes = []string{"github_pat_", "ghp_", "gho_", "ghu_", "ghs_", "ghr_"}
func maskToken(token string) string {
for _, prefix := range knownTokenPrefixes {
if strings.HasPrefix(token, prefix) {
return prefix + strings.Repeat("*", len(token)-len(prefix))
}
}
return strings.Repeat("*", len(token))
}
func displayScopes(scopes string) string {
if scopes == "" {
return "none"
}
list := strings.Split(scopes, ",")
for i, s := range list {
list[i] = fmt.Sprintf("'%s'", strings.TrimSpace(s))
}
return strings.Join(list, ", ")
}
// TODO: this matches a token prefix itself. It could ask
// gh.AuthConfig.ActiveTokenType instead.
func expectScopes(token string) bool {
return strings.HasPrefix(token, "ghp_") || strings.HasPrefix(token, "gho_")
}
type buildEntryOptions struct {
active bool
gitProtocol string
hostname string
credential gh.Credential
refreshStatus gh.RefreshStatus
noRefresh bool
username string
}
func buildEntry(httpClient *http.Client, opts buildEntryOptions) authEntry {
tokenSource := opts.credential.Source
if tokenSource == gh.TokenSourceOAuthToken || tokenSource == gh.TokenSourceRefreshableOAuthToken {
// The go-gh function TokenForHost returns this value as source for tokens read from the
// config file, but we want the file path instead. This attempts to reconstruct it.
tokenSource = filepath.Join(config.ConfigDir(), "hosts.yml")
}
entry := authEntry{
Active: opts.active,
Host: opts.hostname,
Login: opts.username,
TokenSource: tokenSource,
Token: opts.credential.Token,
GitProtocol: opts.gitProtocol,
Refreshable: opts.credential.IsRefreshable(),
TokenExpiresAt: opts.credential.ExpiresAt,
RefreshTokenExpiresAt: opts.credential.RefreshTokenExpiresAt,
justRefreshed: opts.refreshStatus == gh.RefreshStatusDone,
}
// A rejected refresh token means the stored credential was already removed during resolution, leaving an empty
// token behind. Sending a scope request with it would produce a misleading generic failure, so surface the real
// reason and stop here. The token source is left empty on purpose: the credential is gone, so where it used to
// live is of no use to the user now.
if opts.refreshStatus == gh.RefreshStatusExpired {
entry.State = authEntryStateRefreshExpired
entry.Error = fmt.Sprintf("refresh token for %s was rejected; the stored credential was removed", opts.hostname)
return entry
}
// If token is not writeable, then it came from an environment variable and
// we need to fetch the username as it won't be stored in the config.
if !authTokenWriteable(tokenSource) {
// The httpClient will automatically use the correct token here as
// the token from the environment variable take highest precedence.
apiClient := api.NewClientFromHTTP(httpClient)
var err error
entry.Login, err = api.CurrentLoginName(apiClient, opts.hostname)
if err != nil {
entry.State = authEntryStateError
entry.Error = err.Error()
return entry
}
}
// Get scopes for token.
scopesHeader, err := shared.GetScopes(httpClient, opts.hostname, opts.credential.Token)
if err != nil {
var networkError net.Error
if errors.As(err, &networkError) && networkError.Timeout() {
entry.State = authEntryStateTimeout
entry.Error = err.Error()
return entry
}
entry.State = authEntryStateError
entry.Error = err.Error()
// Without a refresh, an expiring token past its expiry time is bound to be rejected with HTTP 401. Flag it so
// the output can explain the failure instead of reporting the token as invalid. The expiry check runs only
// after a rejection, so a server that still accepts the token (for example, under clock skew) reports success,
// and unrelated failures (for example, HTTP 503) keep the generic error output.
httpErr, isHTTPErr := errors.AsType[api.HTTPError](err)
entry.expiredWithoutRefresh = opts.noRefresh && entry.Refreshable &&
isHTTPErr && httpErr.StatusCode == http.StatusUnauthorized &&
entry.TokenExpiresAt != nil && !entry.TokenExpiresAt.After(timeNow())
return entry
}
entry.Scopes = scopesHeader
entry.State = authEntryStateSuccess
return entry
}
func authTokenWriteable(src string) bool {
return !strings.HasSuffix(src, "_TOKEN")
}
// resolveCredential returns the credential gh should present for the host and optional user (an empty username means the
// active account), refreshing an expiring token unless noRefresh is set. Refresh is best effort: a failed
// refresh yields the last stored credential, which the caller still validates via the scope check. The returned status
// reports whether a refresh happened.
func resolveCredential(authCfg gh.AuthConfig, hostname, username string, noRefresh bool) (gh.Credential, gh.RefreshStatus) {
if noRefresh {
if username == "" {
return authCfg.ActiveToken(hostname), gh.RefreshStatusInapplicable
}
credential, _ := authCfg.TokenForUser(hostname, username)
return credential, gh.RefreshStatusInapplicable
}
if username == "" {
credential, status, _ := authCfg.ActiveTokenWithRefresh(hostname)
return credential, status
}
credential, status, _ := authCfg.TokenForUserWithRefresh(hostname, username)
return credential, status
}