|
| 1 | +// Package authutil provides shared constants and functions for handling authentication |
| 2 | +// credentials, including storage in the system keyring and OAuth2 token management. |
| 3 | +package authutil |
| 4 | + |
| 5 | +import ( |
| 6 | + "context" |
| 7 | + "crypto/rsa" |
| 8 | + "crypto/x509" |
| 9 | + "encoding/json" |
| 10 | + "encoding/pem" |
| 11 | + "fmt" |
| 12 | + "io" |
| 13 | + "net/http" |
| 14 | + "net/url" |
| 15 | + "strings" |
| 16 | + "sync" |
| 17 | + "time" |
| 18 | + |
| 19 | + jose "github.com/go-jose/go-jose/v4" |
| 20 | + josejwt "github.com/go-jose/go-jose/v4/jwt" |
| 21 | + "github.com/google/uuid" |
| 22 | + customerrors "go.datum.net/datumctl/internal/errors" |
| 23 | + "go.datum.net/datumctl/internal/keyring" |
| 24 | + "golang.org/x/oauth2" |
| 25 | +) |
| 26 | + |
| 27 | +// MachineAccountCredentials is the on-disk JSON format downloaded from the Datum Cloud portal. |
| 28 | +type MachineAccountCredentials struct { |
| 29 | + Type string `json:"type"` // "datum_machine_account" |
| 30 | + APIEndpoint string `json:"api_endpoint"` // "https://api.datum.net" |
| 31 | + TokenURI string `json:"token_uri"` // "https://auth.datum.net/oauth/v2/token" |
| 32 | + Scope string `json:"scope"` // OAuth2 scope string, e.g. "openid profile email urn:zitadel:..." |
| 33 | + ProjectID string `json:"project_id"` |
| 34 | + ClientEmail string `json:"client_email"` // identity e-mail, used as display name |
| 35 | + ClientID string `json:"client_id"` // numeric Zitadel user ID (iss / sub) |
| 36 | + PrivateKeyID string `json:"private_key_id"` // kid header |
| 37 | + PrivateKey string `json:"private_key"` // PEM-encoded RSA private key |
| 38 | +} |
| 39 | + |
| 40 | +// tokenResponse is a minimal struct for parsing token endpoint responses in the |
| 41 | +// JWT bearer exchange. It mirrors the fields we care about from deviceTokenResponse |
| 42 | +// without creating a circular import with the auth command package. |
| 43 | +type tokenResponse struct { |
| 44 | + AccessToken string `json:"access_token"` |
| 45 | + TokenType string `json:"token_type"` |
| 46 | + ExpiresIn int64 `json:"expires_in"` |
| 47 | + Error string `json:"error"` |
| 48 | + ErrorDesc string `json:"error_description"` |
| 49 | +} |
| 50 | + |
| 51 | +// MintJWT mints a signed RS256 JWT suitable for the jwt-bearer grant. |
| 52 | +// Claims: iss=clientID, sub=clientID, aud=issuer (scheme+host of tokenURI), |
| 53 | +// kid=privateKeyID, jti=random UUID, iat=now, exp=now+60s. |
| 54 | +func MintJWT(clientID, privateKeyID, privateKeyPEM, tokenURI string) (string, error) { |
| 55 | + block, _ := pem.Decode([]byte(privateKeyPEM)) |
| 56 | + if block == nil { |
| 57 | + return "", fmt.Errorf("failed to decode PEM block from private key") |
| 58 | + } |
| 59 | + |
| 60 | + var rsaKey *rsa.PrivateKey |
| 61 | + // Try PKCS#1 first, fall back to PKCS#8. |
| 62 | + if key, err := x509.ParsePKCS1PrivateKey(block.Bytes); err == nil { |
| 63 | + rsaKey = key |
| 64 | + } else { |
| 65 | + key8, err := x509.ParsePKCS8PrivateKey(block.Bytes) |
| 66 | + if err != nil { |
| 67 | + return "", fmt.Errorf("failed to parse private key (tried PKCS#1 and PKCS#8): %w", err) |
| 68 | + } |
| 69 | + var ok bool |
| 70 | + rsaKey, ok = key8.(*rsa.PrivateKey) |
| 71 | + if !ok { |
| 72 | + return "", fmt.Errorf("private key is not an RSA key") |
| 73 | + } |
| 74 | + } |
| 75 | + |
| 76 | + // aud must be the issuer (scheme+host), not the full token endpoint URL. |
| 77 | + u, err := url.Parse(tokenURI) |
| 78 | + if err != nil { |
| 79 | + return "", fmt.Errorf("failed to parse token URI: %w", err) |
| 80 | + } |
| 81 | + issuer := u.Scheme + "://" + u.Host |
| 82 | + |
| 83 | + jwk := jose.JSONWebKey{Key: rsaKey, KeyID: privateKeyID} |
| 84 | + |
| 85 | + sig, err := jose.NewSigner( |
| 86 | + jose.SigningKey{Algorithm: jose.RS256, Key: jwk}, |
| 87 | + (&jose.SignerOptions{}).WithType("JWT"), |
| 88 | + ) |
| 89 | + if err != nil { |
| 90 | + return "", fmt.Errorf("failed to create JWT signer: %w", err) |
| 91 | + } |
| 92 | + |
| 93 | + now := time.Now() |
| 94 | + signed, err := josejwt.Signed(sig). |
| 95 | + Claims(josejwt.Claims{ |
| 96 | + Issuer: clientID, |
| 97 | + Subject: clientID, |
| 98 | + Audience: josejwt.Audience{issuer}, |
| 99 | + IssuedAt: josejwt.NewNumericDate(now), |
| 100 | + Expiry: josejwt.NewNumericDate(now.Add(60 * time.Second)), |
| 101 | + ID: uuid.NewString(), |
| 102 | + }). |
| 103 | + Serialize() |
| 104 | + if err != nil { |
| 105 | + return "", fmt.Errorf("failed to serialize JWT: %w", err) |
| 106 | + } |
| 107 | + |
| 108 | + return signed, nil |
| 109 | +} |
| 110 | + |
| 111 | +// tokenHTTPClient is used for all JWT bearer token exchanges. |
| 112 | +// A dedicated client with a timeout prevents indefinite hangs on slow endpoints. |
| 113 | +var tokenHTTPClient = &http.Client{Timeout: 30 * time.Second} |
| 114 | + |
| 115 | +// ExchangeJWT POSTs a signed JWT to tokenURI using the jwt-bearer grant and |
| 116 | +// returns the resulting oauth2.Token. The token will have no RefreshToken. |
| 117 | +// If scope is empty, "openid profile email" is used as the default. |
| 118 | +func ExchangeJWT(ctx context.Context, tokenURI, signedJWT, scope string) (*oauth2.Token, error) { |
| 119 | + u, err := url.Parse(tokenURI) |
| 120 | + if err != nil { |
| 121 | + return nil, fmt.Errorf("failed to parse token URI: %w", err) |
| 122 | + } |
| 123 | + if u.Scheme != "https" { |
| 124 | + return nil, fmt.Errorf("token_uri must use HTTPS, got %q", u.Scheme) |
| 125 | + } |
| 126 | + |
| 127 | + if scope == "" { |
| 128 | + scope = "openid profile email" |
| 129 | + } |
| 130 | + form := url.Values{} |
| 131 | + form.Set("grant_type", "urn:ietf:params:oauth:grant-type:jwt-bearer") |
| 132 | + form.Set("assertion", signedJWT) |
| 133 | + form.Set("scope", scope) |
| 134 | + |
| 135 | + req, err := http.NewRequestWithContext(ctx, http.MethodPost, tokenURI, strings.NewReader(form.Encode())) |
| 136 | + if err != nil { |
| 137 | + return nil, fmt.Errorf("failed to create JWT bearer request: %w", err) |
| 138 | + } |
| 139 | + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") |
| 140 | + |
| 141 | + resp, err := tokenHTTPClient.Do(req) |
| 142 | + if err != nil { |
| 143 | + return nil, fmt.Errorf("JWT bearer token request failed: %w", err) |
| 144 | + } |
| 145 | + defer resp.Body.Close() |
| 146 | + |
| 147 | + body, err := io.ReadAll(io.LimitReader(resp.Body, 1<<20)) // 1 MB cap |
| 148 | + if err != nil { |
| 149 | + return nil, fmt.Errorf("failed to read JWT bearer response: %w", err) |
| 150 | + } |
| 151 | + |
| 152 | + var tr tokenResponse |
| 153 | + if err := json.Unmarshal(body, &tr); err != nil { |
| 154 | + return nil, fmt.Errorf("failed to parse JWT bearer response: %w", err) |
| 155 | + } |
| 156 | + |
| 157 | + if resp.StatusCode != http.StatusOK { |
| 158 | + if tr.Error != "" { |
| 159 | + return nil, fmt.Errorf("JWT bearer exchange failed: %s (%s)", tr.Error, tr.ErrorDesc) |
| 160 | + } |
| 161 | + return nil, fmt.Errorf("JWT bearer exchange failed with status %s", resp.Status) |
| 162 | + } |
| 163 | + |
| 164 | + token := &oauth2.Token{ |
| 165 | + AccessToken: tr.AccessToken, |
| 166 | + TokenType: tr.TokenType, |
| 167 | + } |
| 168 | + if tr.ExpiresIn > 0 { |
| 169 | + token.Expiry = time.Now().Add(time.Duration(tr.ExpiresIn) * time.Second) |
| 170 | + } |
| 171 | + |
| 172 | + return token, nil |
| 173 | +} |
| 174 | + |
| 175 | +// machineAccountTokenSource implements oauth2.TokenSource for machine account sessions. |
| 176 | +// It re-mints a JWT and re-exchanges it whenever the stored access token has expired, |
| 177 | +// since machine account sessions have no refresh token. |
| 178 | +type machineAccountTokenSource struct { |
| 179 | + ctx context.Context |
| 180 | + creds *StoredCredentials |
| 181 | + userKey string |
| 182 | + mu sync.Mutex |
| 183 | +} |
| 184 | + |
| 185 | +// Token implements oauth2.TokenSource. If the cached token is still valid it is |
| 186 | +// returned immediately. Otherwise a new JWT is minted, exchanged for an access |
| 187 | +// token, and the updated credentials are persisted to the keyring. |
| 188 | +func (m *machineAccountTokenSource) Token() (*oauth2.Token, error) { |
| 189 | + m.mu.Lock() |
| 190 | + defer m.mu.Unlock() |
| 191 | + |
| 192 | + if m.creds.Token != nil && m.creds.Token.Valid() { |
| 193 | + return m.creds.Token, nil |
| 194 | + } |
| 195 | + |
| 196 | + ma := m.creds.MachineAccount |
| 197 | + signedJWT, err := MintJWT(ma.ClientID, ma.PrivateKeyID, ma.PrivateKey, ma.TokenURI) |
| 198 | + if err != nil { |
| 199 | + return nil, customerrors.WrapUserErrorWithHint( |
| 200 | + "Failed to mint JWT for machine account authentication.", |
| 201 | + "Please re-authenticate using: `datumctl auth login --credentials <file>`", |
| 202 | + err, |
| 203 | + ) |
| 204 | + } |
| 205 | + |
| 206 | + token, err := ExchangeJWT(m.ctx, ma.TokenURI, signedJWT, ma.Scope) |
| 207 | + if err != nil { |
| 208 | + return nil, customerrors.WrapUserErrorWithHint( |
| 209 | + "Failed to exchange JWT for access token.", |
| 210 | + "Please re-authenticate using: `datumctl auth login --credentials <file>`", |
| 211 | + err, |
| 212 | + ) |
| 213 | + } |
| 214 | + |
| 215 | + m.creds.Token = token |
| 216 | + |
| 217 | + credsJSON, err := json.Marshal(m.creds) |
| 218 | + if err != nil { |
| 219 | + // Return token even if persistence fails — the caller can still proceed. |
| 220 | + return token, fmt.Errorf("failed to marshal updated machine account credentials: %w", err) |
| 221 | + } |
| 222 | + |
| 223 | + if err := keyring.Set(ServiceName, m.userKey, string(credsJSON)); err != nil { |
| 224 | + return token, fmt.Errorf("failed to persist refreshed machine account token to keyring: %w", err) |
| 225 | + } |
| 226 | + |
| 227 | + return token, nil |
| 228 | +} |
0 commit comments