|
| 1 | +package auth |
| 2 | + |
| 3 | +import ( |
| 4 | + "encoding/json" |
| 5 | + "fmt" |
| 6 | + "io" |
| 7 | + "net/http" |
| 8 | + "net/url" |
| 9 | + "os" |
| 10 | + "strings" |
| 11 | + "time" |
| 12 | + |
| 13 | + "github.com/adrg/xdg" |
| 14 | +) |
| 15 | + |
| 16 | +const ( |
| 17 | + FirebaseAPIKey = "AIzaSyCxsrwjABEF-dWLzUqmwiL-ct02cnG9GCs" |
| 18 | + TokenBaseURL = "https://securetoken.googleapis.com" |
| 19 | + EnvVarCloudQueryAPIKey = "CLOUDQUERY_API_KEY" |
| 20 | + ExpiryBuffer = 60 * time.Second |
| 21 | +) |
| 22 | + |
| 23 | +type tokenResponse struct { |
| 24 | + AccessToken string `json:"access_token"` |
| 25 | + ExpiresIn string `json:"expires_in"` |
| 26 | + TokenType string `json:"token_type"` |
| 27 | + RefreshToken string `json:"refresh_token"` |
| 28 | + IDToken string `json:"id_token"` |
| 29 | + UserID string `json:"user_id"` |
| 30 | + ProjectID string `json:"project_id"` |
| 31 | +} |
| 32 | + |
| 33 | +type TokenClient struct { |
| 34 | + url string |
| 35 | + apiKey string |
| 36 | + idToken string |
| 37 | + expiresAt time.Time |
| 38 | +} |
| 39 | + |
| 40 | +func NewTokenClient() *TokenClient { |
| 41 | + return &TokenClient{ |
| 42 | + url: TokenBaseURL, |
| 43 | + apiKey: FirebaseAPIKey, |
| 44 | + } |
| 45 | +} |
| 46 | + |
| 47 | +// GetToken returns the ID token |
| 48 | +// If CLOUDQUERY_API_KEY is set, it returns that value, otherwise it returns an ID token generated from the refresh token. |
| 49 | +func (tc *TokenClient) GetToken() (string, error) { |
| 50 | + if token := os.Getenv(EnvVarCloudQueryAPIKey); token != "" { |
| 51 | + return token, nil |
| 52 | + } |
| 53 | + |
| 54 | + // If the token is not expired, return it |
| 55 | + if !tc.expiresAt.IsZero() && tc.expiresAt.Sub(time.Now().UTC()) > ExpiryBuffer { |
| 56 | + return tc.idToken, nil |
| 57 | + } |
| 58 | + |
| 59 | + refreshToken, err := ReadRefreshToken() |
| 60 | + if err != nil { |
| 61 | + return "", fmt.Errorf("failed to read refresh token: %w. Hint: You may need to run `cloudquery login` or set %s", err, EnvVarCloudQueryAPIKey) |
| 62 | + } |
| 63 | + if refreshToken == "" { |
| 64 | + return "", fmt.Errorf("authentication token not found. Hint: You may need to run `cloudquery login` or set %s", EnvVarCloudQueryAPIKey) |
| 65 | + } |
| 66 | + tokenResponse, err := tc.generateToken(refreshToken) |
| 67 | + if err != nil { |
| 68 | + return "", fmt.Errorf("failed to sign in with custom token: %w", err) |
| 69 | + } |
| 70 | + |
| 71 | + if err := SaveRefreshToken(tokenResponse.RefreshToken); err != nil { |
| 72 | + return "", fmt.Errorf("failed to save refresh token: %w", err) |
| 73 | + } |
| 74 | + |
| 75 | + if err := tc.updateIDToken(tokenResponse); err != nil { |
| 76 | + return "", fmt.Errorf("failed to update ID token: %w", err) |
| 77 | + } |
| 78 | + |
| 79 | + return tc.idToken, nil |
| 80 | +} |
| 81 | + |
| 82 | +func (tc *TokenClient) generateToken(refreshToken string) (*tokenResponse, error) { |
| 83 | + data := url.Values{} |
| 84 | + data.Set("grant_type", "refresh_token") |
| 85 | + data.Set("refresh_token", refreshToken) |
| 86 | + |
| 87 | + resp, err := http.PostForm(fmt.Sprintf("%s/v1/token?key=%s", tc.url, tc.apiKey), data) |
| 88 | + if err != nil { |
| 89 | + return nil, err |
| 90 | + } |
| 91 | + defer resp.Body.Close() |
| 92 | + if resp.StatusCode != http.StatusOK { |
| 93 | + body, readErr := io.ReadAll(resp.Body) |
| 94 | + if readErr != nil { |
| 95 | + return nil, fmt.Errorf("failed to read response body: %w", readErr) |
| 96 | + } |
| 97 | + return nil, fmt.Errorf("failed to refresh token: %s: %s", resp.Status, body) |
| 98 | + } |
| 99 | + |
| 100 | + var tr tokenResponse |
| 101 | + body, err := io.ReadAll(resp.Body) |
| 102 | + if err != nil { |
| 103 | + return nil, err |
| 104 | + } |
| 105 | + if err := parseToken(body, &tr); err != nil { |
| 106 | + return nil, err |
| 107 | + } |
| 108 | + |
| 109 | + return &tr, nil |
| 110 | +} |
| 111 | + |
| 112 | +func (tc *TokenClient) updateIDToken(tr *tokenResponse) error { |
| 113 | + // Convert string duration in seconds to time.Duration |
| 114 | + duration, err := time.ParseDuration(tr.ExpiresIn + "s") |
| 115 | + if err != nil { |
| 116 | + return err |
| 117 | + } |
| 118 | + |
| 119 | + tc.expiresAt = time.Now().UTC().Add(duration) |
| 120 | + tc.idToken = tr.IDToken |
| 121 | + return nil |
| 122 | +} |
| 123 | + |
| 124 | +func parseToken(response []byte, tr *tokenResponse) error { |
| 125 | + err := json.Unmarshal(response, tr) |
| 126 | + if err != nil { |
| 127 | + return err |
| 128 | + } |
| 129 | + return nil |
| 130 | +} |
| 131 | + |
| 132 | +// SaveRefreshToken saves the refresh token to the token file |
| 133 | +func SaveRefreshToken(refreshToken string) error { |
| 134 | + tokenFilePath, err := xdg.DataFile("cloudquery/token") |
| 135 | + if err != nil { |
| 136 | + return fmt.Errorf("failed to get token file path: %w", err) |
| 137 | + } |
| 138 | + tokenFile, err := os.OpenFile(tokenFilePath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644) |
| 139 | + if err != nil { |
| 140 | + return fmt.Errorf("failed to open token file %q for writing: %w", tokenFilePath, err) |
| 141 | + } |
| 142 | + defer func() { |
| 143 | + if closeErr := tokenFile.Close(); closeErr != nil { |
| 144 | + fmt.Printf("error closing token file: %v", closeErr) |
| 145 | + } |
| 146 | + }() |
| 147 | + if _, err = tokenFile.WriteString(refreshToken); err != nil { |
| 148 | + return fmt.Errorf("failed to write token to %q: %w", tokenFilePath, err) |
| 149 | + } |
| 150 | + return nil |
| 151 | +} |
| 152 | + |
| 153 | +// ReadRefreshToken reads the refresh token from the token file |
| 154 | +func ReadRefreshToken() (string, error) { |
| 155 | + tokenFilePath, err := xdg.DataFile("cloudquery/token") |
| 156 | + if err != nil { |
| 157 | + return "", fmt.Errorf("failed to get token file path: %w", err) |
| 158 | + } |
| 159 | + b, err := os.ReadFile(tokenFilePath) |
| 160 | + if err != nil { |
| 161 | + return "", fmt.Errorf("failed to read token file: %w", err) |
| 162 | + } |
| 163 | + return strings.TrimSpace(string(b)), nil |
| 164 | +} |
| 165 | + |
| 166 | +// RemoveRefreshToken removes the token file |
| 167 | +func RemoveRefreshToken() error { |
| 168 | + tokenFilePath, err := xdg.DataFile("cloudquery/token") |
| 169 | + if err != nil { |
| 170 | + return fmt.Errorf("failed to get token file path: %w", err) |
| 171 | + } |
| 172 | + if err := os.RemoveAll(tokenFilePath); err != nil { |
| 173 | + return fmt.Errorf("failed to remove token file %q: %w", tokenFilePath, err) |
| 174 | + } |
| 175 | + return nil |
| 176 | +} |
0 commit comments