|
| 1 | +package googlechat |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "crypto" |
| 6 | + "crypto/rand" |
| 7 | + "crypto/rsa" |
| 8 | + "crypto/sha256" |
| 9 | + "crypto/x509" |
| 10 | + "encoding/base64" |
| 11 | + "encoding/json" |
| 12 | + "encoding/pem" |
| 13 | + "fmt" |
| 14 | + "io" |
| 15 | + "net/http" |
| 16 | + "net/url" |
| 17 | + "os" |
| 18 | + "strings" |
| 19 | + "sync" |
| 20 | + "time" |
| 21 | +) |
| 22 | + |
| 23 | +type ServiceAccountAuth struct { |
| 24 | + email string |
| 25 | + privateKey *rsa.PrivateKey |
| 26 | + scopes []string |
| 27 | + token string |
| 28 | + expiresAt time.Time |
| 29 | + mu sync.Mutex |
| 30 | + tokenEndpoint string |
| 31 | + httpClient *http.Client |
| 32 | +} |
| 33 | + |
| 34 | +type serviceAccountFile struct { |
| 35 | + Type string `json:"type"` |
| 36 | + ClientEmail string `json:"client_email"` |
| 37 | + PrivateKey string `json:"private_key"` |
| 38 | + TokenURI string `json:"token_uri"` |
| 39 | +} |
| 40 | + |
| 41 | +func NewServiceAccountAuth(saFilePath string, scopes []string) (*ServiceAccountAuth, error) { |
| 42 | + data, err := os.ReadFile(saFilePath) |
| 43 | + if err != nil { |
| 44 | + return nil, fmt.Errorf("read service account file: %w", err) |
| 45 | + } |
| 46 | + |
| 47 | + var sa serviceAccountFile |
| 48 | + if err := json.Unmarshal(data, &sa); err != nil { |
| 49 | + return nil, fmt.Errorf("parse service account file: %w", err) |
| 50 | + } |
| 51 | + if sa.ClientEmail == "" { |
| 52 | + return nil, fmt.Errorf("service account file missing client_email") |
| 53 | + } |
| 54 | + if sa.PrivateKey == "" { |
| 55 | + return nil, fmt.Errorf("service account file missing private_key") |
| 56 | + } |
| 57 | + |
| 58 | + block, _ := pem.Decode([]byte(sa.PrivateKey)) |
| 59 | + if block == nil { |
| 60 | + return nil, fmt.Errorf("failed to decode PEM block from private_key") |
| 61 | + } |
| 62 | + |
| 63 | + key, err := x509.ParsePKCS8PrivateKey(block.Bytes) |
| 64 | + if err != nil { |
| 65 | + rsaKey, err2 := x509.ParsePKCS1PrivateKey(block.Bytes) |
| 66 | + if err2 != nil { |
| 67 | + return nil, fmt.Errorf("parse private key: %w (pkcs1: %w)", err, err2) |
| 68 | + } |
| 69 | + key = rsaKey |
| 70 | + } |
| 71 | + |
| 72 | + rsaKey, ok := key.(*rsa.PrivateKey) |
| 73 | + if !ok { |
| 74 | + return nil, fmt.Errorf("private key is not RSA") |
| 75 | + } |
| 76 | + |
| 77 | + ep := sa.TokenURI |
| 78 | + if ep == "" { |
| 79 | + ep = tokenEndpoint |
| 80 | + } |
| 81 | + |
| 82 | + return &ServiceAccountAuth{ |
| 83 | + email: sa.ClientEmail, |
| 84 | + privateKey: rsaKey, |
| 85 | + scopes: scopes, |
| 86 | + tokenEndpoint: ep, |
| 87 | + httpClient: &http.Client{Timeout: 10 * time.Second}, |
| 88 | + }, nil |
| 89 | +} |
| 90 | + |
| 91 | +func (a *ServiceAccountAuth) Token(ctx context.Context) (string, error) { |
| 92 | + a.mu.Lock() |
| 93 | + defer a.mu.Unlock() |
| 94 | + |
| 95 | + if a.token != "" && time.Now().Add(60*time.Second).Before(a.expiresAt) { |
| 96 | + return a.token, nil |
| 97 | + } |
| 98 | + |
| 99 | + now := time.Now() |
| 100 | + claims := map[string]any{ |
| 101 | + "iss": a.email, |
| 102 | + "scope": strings.Join(a.scopes, " "), |
| 103 | + "aud": tokenEndpoint, |
| 104 | + "iat": now.Unix(), |
| 105 | + "exp": now.Add(time.Hour).Unix(), |
| 106 | + } |
| 107 | + |
| 108 | + signedJWT, err := signJWT(a.privateKey, claims) |
| 109 | + if err != nil { |
| 110 | + return "", fmt.Errorf("sign JWT: %w", err) |
| 111 | + } |
| 112 | + |
| 113 | + form := url.Values{ |
| 114 | + "grant_type": {"urn:ietf:params:oauth:grant-type:jwt-bearer"}, |
| 115 | + "assertion": {signedJWT}, |
| 116 | + } |
| 117 | + |
| 118 | + req, err := http.NewRequestWithContext(ctx, "POST", a.tokenEndpoint, strings.NewReader(form.Encode())) |
| 119 | + if err != nil { |
| 120 | + return "", err |
| 121 | + } |
| 122 | + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") |
| 123 | + |
| 124 | + resp, err := a.httpClient.Do(req) |
| 125 | + if err != nil { |
| 126 | + return "", fmt.Errorf("token exchange request: %w", err) |
| 127 | + } |
| 128 | + defer resp.Body.Close() |
| 129 | + |
| 130 | + body, _ := io.ReadAll(resp.Body) |
| 131 | + if resp.StatusCode != http.StatusOK { |
| 132 | + return "", fmt.Errorf("token exchange failed (%d): %s", resp.StatusCode, string(body)) |
| 133 | + } |
| 134 | + |
| 135 | + var tokenResp struct { |
| 136 | + AccessToken string `json:"access_token"` |
| 137 | + ExpiresIn int `json:"expires_in"` |
| 138 | + TokenType string `json:"token_type"` |
| 139 | + } |
| 140 | + if err := json.Unmarshal(body, &tokenResp); err != nil { |
| 141 | + return "", fmt.Errorf("parse token response: %w", err) |
| 142 | + } |
| 143 | + |
| 144 | + a.token = tokenResp.AccessToken |
| 145 | + a.expiresAt = now.Add(time.Duration(tokenResp.ExpiresIn) * time.Second) |
| 146 | + |
| 147 | + return a.token, nil |
| 148 | +} |
| 149 | + |
| 150 | +func signJWT(key *rsa.PrivateKey, claims map[string]any) (string, error) { |
| 151 | + header := base64URLEncode([]byte(`{"alg":"RS256","typ":"JWT"}`)) |
| 152 | + payload, err := json.Marshal(claims) |
| 153 | + if err != nil { |
| 154 | + return "", err |
| 155 | + } |
| 156 | + payloadEnc := base64URLEncode(payload) |
| 157 | + signingInput := header + "." + payloadEnc |
| 158 | + |
| 159 | + hash := sha256.Sum256([]byte(signingInput)) |
| 160 | + sig, err := rsa.SignPKCS1v15(rand.Reader, key, crypto.SHA256, hash[:]) |
| 161 | + if err != nil { |
| 162 | + return "", err |
| 163 | + } |
| 164 | + |
| 165 | + return signingInput + "." + base64URLEncode(sig), nil |
| 166 | +} |
| 167 | + |
| 168 | +func base64URLEncode(data []byte) string { |
| 169 | + return base64.RawURLEncoding.EncodeToString(data) |
| 170 | +} |
0 commit comments