|
| 1 | +//go:generate go run github.com/maxbrunsfeld/counterfeiter/v6 -generate |
| 2 | + |
| 3 | +package auth |
| 4 | + |
| 5 | +import ( |
| 6 | + "context" |
| 7 | + "errors" |
| 8 | + "fmt" |
| 9 | + "time" |
| 10 | + |
| 11 | + "github.com/fatih/color" |
| 12 | + "github.com/google/go-github/v69/github" |
| 13 | +) |
| 14 | + |
| 15 | +const ( |
| 16 | + // GitHub endpoints |
| 17 | + deviceCodeURL = "https://github.com/login/device/code" |
| 18 | + tokenURL = "https://github.com/login/oauth/access_token" //nolint:gosec // not a credential |
| 19 | + |
| 20 | + // The SLSA sourcetool app OAuth client ID |
| 21 | + oauthClientID = "Ov23lidVQsiU5R5tod3z" |
| 22 | + |
| 23 | + // App's config directory name |
| 24 | + configDirName = "slsa" |
| 25 | + |
| 26 | + // Token filename |
| 27 | + githubTokenFileName = "sourcetool.github.token" |
| 28 | +) |
| 29 | + |
| 30 | +var oauthScopes = []string{ |
| 31 | + "repo", "user:email", |
| 32 | +} |
| 33 | + |
| 34 | +type Authenticator struct { |
| 35 | + impl authenticatorImplementation |
| 36 | +} |
| 37 | + |
| 38 | +// DeviceCodeResponse models the github device code response |
| 39 | +type DeviceCodeResponse struct { |
| 40 | + DeviceCode string `json:"device_code"` |
| 41 | + UserCode string `json:"user_code"` |
| 42 | + VerificationURI string `json:"verification_uri"` |
| 43 | + ExpiresIn int `json:"expires_in"` |
| 44 | + Interval int `json:"interval"` |
| 45 | +} |
| 46 | + |
| 47 | +// TokenResponse is the data structure returned when exchanging tokens |
| 48 | +type TokenResponse struct { |
| 49 | + AccessToken string `json:"access_token"` |
| 50 | + TokenType string `json:"token_type"` |
| 51 | + Scope string `json:"scope"` |
| 52 | + Error string `json:"error"` |
| 53 | + ErrorDesc string `json:"error_description"` |
| 54 | +} |
| 55 | + |
| 56 | +// NewGitHubApp creates a new GitHub OAuth application for device flow |
| 57 | +func New() *Authenticator { |
| 58 | + return &Authenticator{ |
| 59 | + impl: &defaultImplementation{}, |
| 60 | + } |
| 61 | +} |
| 62 | + |
| 63 | +// Authenticate performs the complete device flow authentication in the |
| 64 | +// user's terminal and web browser |
| 65 | +func (a *Authenticator) Authenticate(ctx context.Context) error { |
| 66 | + fmt.Println("Starting authentication flow...") |
| 67 | + |
| 68 | + // Get a device code |
| 69 | + deviceResp, err := a.impl.requestDeviceCode(ctx) |
| 70 | + if err != nil { |
| 71 | + return fmt.Errorf("failed to request device code: %w", err) |
| 72 | + } |
| 73 | + |
| 74 | + // Send the user to the authentication page |
| 75 | + fmt.Printf("\nYour browser will be opened to: %s\n\n", deviceResp.VerificationURI) |
| 76 | + fmt.Printf(" 🔑 Enter this code: %s\n\n", color.New(color.FgHiWhite, color.BgBlack).Sprint(deviceResp.UserCode)) |
| 77 | + |
| 78 | + // Try to open browser automatically |
| 79 | + if err := a.impl.openBrowser(deviceResp.VerificationURI); err != nil { |
| 80 | + fmt.Println("Failed to open browser, please manually visit the URL above.") |
| 81 | + fmt.Println() |
| 82 | + } else { |
| 83 | + fmt.Println("Please complete the authentication flow by pasting the above code in") |
| 84 | + fmt.Println("the page displayed on your browser.") |
| 85 | + } |
| 86 | + fmt.Println() |
| 87 | + |
| 88 | + fmt.Println("⏳ Waiting for authentication...") |
| 89 | + |
| 90 | + pollInterval := 5 * time.Second |
| 91 | + if deviceResp.Interval > 0 { |
| 92 | + pollInterval = time.Duration(deviceResp.Interval) * time.Second |
| 93 | + } |
| 94 | + |
| 95 | + // Wait for the user to complete the flow while polling the server to |
| 96 | + // get the newly issued token |
| 97 | + token, err := a.impl.pollForToken(ctx, deviceResp.DeviceCode, pollInterval) |
| 98 | + if err != nil { |
| 99 | + return fmt.Errorf("failed to get access token: %w", err) |
| 100 | + } |
| 101 | + |
| 102 | + fmt.Println("✅ Authentication successful!") |
| 103 | + fmt.Println() |
| 104 | + fmt.Println("At any point, you can find out the logged-in identity by running:") |
| 105 | + fmt.Println("> sourcetool auth whoami") |
| 106 | + fmt.Println() |
| 107 | + |
| 108 | + // Persist the token to disk |
| 109 | + return a.impl.persistToken(token) |
| 110 | +} |
| 111 | + |
| 112 | +// ReadToken reads the persisted token and returns it |
| 113 | +func (a *Authenticator) ReadToken() (string, error) { |
| 114 | + return a.impl.readToken() |
| 115 | +} |
| 116 | + |
| 117 | +// GetGitHubClient returns a GitHub client preconfigured with |
| 118 | +// the logged-in token. |
| 119 | +func (a *Authenticator) GetGitHubClient() (*github.Client, error) { |
| 120 | + token, err := a.impl.readToken() |
| 121 | + if err != nil { |
| 122 | + return nil, fmt.Errorf("reading token: %w", err) |
| 123 | + } |
| 124 | + if token == "" { |
| 125 | + return nil, errors.New("token is empty") |
| 126 | + } |
| 127 | + return github.NewClient(nil).WithAuthToken(token), nil |
| 128 | +} |
| 129 | + |
| 130 | +// WhoAmI returns the user authenticated with the token |
| 131 | +func (a *Authenticator) WhoAmI() (*github.User, error) { |
| 132 | + token, err := a.impl.readToken() |
| 133 | + if err != nil { |
| 134 | + return nil, fmt.Errorf("reading token: %w", err) |
| 135 | + } |
| 136 | + |
| 137 | + // If no token is set, then no error, only nil |
| 138 | + if token == "" { |
| 139 | + return nil, nil |
| 140 | + } |
| 141 | + |
| 142 | + client, err := a.GetGitHubClient() |
| 143 | + if err != nil { |
| 144 | + return nil, err |
| 145 | + } |
| 146 | + |
| 147 | + user, _, err := client.Users.Get(context.Background(), "") |
| 148 | + if err != nil { |
| 149 | + return nil, fmt.Errorf("fetching user data: %w", err) |
| 150 | + } |
| 151 | + |
| 152 | + return user, nil |
| 153 | +} |
0 commit comments