requireOAuthToken ensures an OAuth (device flow) token is present and valid. agent-task subcommands inherit this check via PersistentPreRunE.
(f *cmdutil.Factory)
| 70 | // requireOAuthToken ensures an OAuth (device flow) token is present and valid. |
| 71 | // agent-task subcommands inherit this check via PersistentPreRunE. |
| 72 | func requireOAuthToken(f *cmdutil.Factory) error { |
| 73 | cfg, err := f.Config() |
| 74 | if err != nil { |
| 75 | return err |
| 76 | } |
| 77 | |
| 78 | authCfg := cfg.Authentication() |
| 79 | host, _ := authCfg.DefaultHost() |
| 80 | if host == "" { |
| 81 | return errors.New("no default host configured; run 'gh auth login'") |
| 82 | } |
| 83 | |
| 84 | if auth.IsEnterprise(host) { |
| 85 | return errors.New("agent tasks are not supported on this host") |
| 86 | } |
| 87 | |
| 88 | cred := authCfg.ActiveToken(host) |
| 89 | |
| 90 | // Tokens from sources "oauth_token", "keyring", and "refreshable_oauth_token" are |
| 91 | // likely minted through our device flow. The refreshable source covers an expiring |
| 92 | // login whose credential fell back to plaintext config; without it, such a login would |
| 93 | // be rejected here before the CAPI refresh path can run. |
| 94 | tokenSourceIsDeviceFlow := cred.Source == gh.TokenSourceOAuthToken || |
| 95 | cred.Source == gh.TokenSourceKeyring || |
| 96 | cred.Source == gh.TokenSourceRefreshableOAuthToken |
| 97 | // Tokens with "gho_" prefix are OAuth tokens. |
| 98 | // |
| 99 | // TODO: this matches a token prefix itself. It could ask |
| 100 | // gh.AuthConfig.ActiveTokenType instead. |
| 101 | tokenIsOAuth := strings.HasPrefix(cred.Token, "gho_") |
| 102 | |
| 103 | // Reject if the token is not from a device flow source or is not an OAuth token |
| 104 | if !tokenSourceIsDeviceFlow || !tokenIsOAuth { |
| 105 | return fmt.Errorf("this command requires an OAuth token. Re-authenticate with: gh auth login") |
| 106 | } |
| 107 | return nil |
| 108 | } |
no test coverage detected