|
| 1 | +package googlechat |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "crypto" |
| 6 | + "crypto/rsa" |
| 7 | + "encoding/base64" |
| 8 | + "encoding/json" |
| 9 | + "fmt" |
| 10 | + "math/big" |
| 11 | + "net/http" |
| 12 | + "strings" |
| 13 | + "sync" |
| 14 | + "time" |
| 15 | +) |
| 16 | + |
| 17 | +const ( |
| 18 | + // chatJWKURL is the JWK endpoint for Google Chat's signing keys. |
| 19 | + // Standard idtoken.Validate() uses googleapis.com/oauth2/v3/certs which does NOT |
| 20 | + // include Chat's signing keys, causing "could not find matching cert keyId" errors. |
| 21 | + chatJWKURL = "https://www.googleapis.com/service_accounts/v1/jwk/[email protected]" |
| 22 | + |
| 23 | + // chatIssuer is the expected issuer claim in Google Chat JWT tokens. |
| 24 | + |
| 25 | + |
| 26 | + // jwkCacheTTL is how long to cache fetched JWKs before refreshing. |
| 27 | + jwkCacheTTL = 1 * time.Hour |
| 28 | + |
| 29 | + // clockSkewLeeway allows for minor clock differences between servers. |
| 30 | + clockSkewLeeway = 5 * time.Minute |
| 31 | +) |
| 32 | + |
| 33 | +// chatCertCache stores fetched Google Chat JWKs with a TTL. |
| 34 | +var chatCertCache = &jwkCache{keys: make(map[string]*rsa.PublicKey)} |
| 35 | + |
| 36 | +type jwkCache struct { |
| 37 | + mu sync.RWMutex |
| 38 | + keys map[string]*rsa.PublicKey // kid → public key |
| 39 | + fetched time.Time |
| 40 | +} |
| 41 | + |
| 42 | +// jwkSet is the JSON structure from Google's JWK endpoint. |
| 43 | +type jwkSet struct { |
| 44 | + Keys []jwkKey `json:"keys"` |
| 45 | +} |
| 46 | + |
| 47 | +type jwkKey struct { |
| 48 | + Kid string `json:"kid"` |
| 49 | + Kty string `json:"kty"` |
| 50 | + N string `json:"n"` |
| 51 | + E string `json:"e"` |
| 52 | +} |
| 53 | + |
| 54 | +// verifyChatToken verifies a Google Chat JWT token against the Chat-specific JWK endpoint. |
| 55 | +// audiences is a list of acceptable audience values (webhook URL, project number, etc.). |
| 56 | +func verifyChatToken(ctx context.Context, token string, audiences []string) error { |
| 57 | + parts := strings.Split(token, ".") |
| 58 | + if len(parts) != 3 { |
| 59 | + return fmt.Errorf("invalid JWT format") |
| 60 | + } |
| 61 | + |
| 62 | + // 1. Parse header to get kid |
| 63 | + headerJSON, err := base64.RawURLEncoding.DecodeString(parts[0]) |
| 64 | + if err != nil { |
| 65 | + return fmt.Errorf("decode header: %w", err) |
| 66 | + } |
| 67 | + var header struct { |
| 68 | + Kid string `json:"kid"` |
| 69 | + Alg string `json:"alg"` |
| 70 | + } |
| 71 | + if err := json.Unmarshal(headerJSON, &header); err != nil { |
| 72 | + return fmt.Errorf("parse header: %w", err) |
| 73 | + } |
| 74 | + if header.Alg != "RS256" { |
| 75 | + return fmt.Errorf("unsupported algorithm: %s", header.Alg) |
| 76 | + } |
| 77 | + |
| 78 | + // 2. Get signing key (fetch + cache, force-refresh on miss) |
| 79 | + pubKey, err := getChatSigningKey(ctx, header.Kid) |
| 80 | + if err != nil { |
| 81 | + return err |
| 82 | + } |
| 83 | + |
| 84 | + // 3. Verify RS256 signature |
| 85 | + signed := []byte(parts[0] + "." + parts[1]) |
| 86 | + sig, err := base64.RawURLEncoding.DecodeString(parts[2]) |
| 87 | + if err != nil { |
| 88 | + return fmt.Errorf("decode signature: %w", err) |
| 89 | + } |
| 90 | + h := crypto.SHA256.New() |
| 91 | + h.Write(signed) |
| 92 | + if err := rsa.VerifyPKCS1v15(pubKey, crypto.SHA256, h.Sum(nil), sig); err != nil { |
| 93 | + return fmt.Errorf("invalid signature: %w", err) |
| 94 | + } |
| 95 | + |
| 96 | + // 4. Validate claims |
| 97 | + claimsJSON, err := base64.RawURLEncoding.DecodeString(parts[1]) |
| 98 | + if err != nil { |
| 99 | + return fmt.Errorf("decode claims: %w", err) |
| 100 | + } |
| 101 | + var claims struct { |
| 102 | + Iss string `json:"iss"` |
| 103 | + Aud string `json:"aud"` |
| 104 | + Exp int64 `json:"exp"` |
| 105 | + } |
| 106 | + if err := json.Unmarshal(claimsJSON, &claims); err != nil { |
| 107 | + return fmt.Errorf("parse claims: %w", err) |
| 108 | + } |
| 109 | + |
| 110 | + if claims.Iss != chatIssuer { |
| 111 | + return fmt.Errorf("invalid issuer: %s", claims.Iss) |
| 112 | + } |
| 113 | + |
| 114 | + if time.Now().Unix() > claims.Exp+int64(clockSkewLeeway.Seconds()) { |
| 115 | + return fmt.Errorf("token expired") |
| 116 | + } |
| 117 | + |
| 118 | + for _, aud := range audiences { |
| 119 | + if claims.Aud == aud { |
| 120 | + return nil |
| 121 | + } |
| 122 | + } |
| 123 | + return fmt.Errorf("audience mismatch: got %s", claims.Aud) |
| 124 | +} |
| 125 | + |
| 126 | +// getChatSigningKey returns the RSA public key for the given kid. |
| 127 | +// Fetches from cache first; on miss, force-refreshes the cache and retries. |
| 128 | +func getChatSigningKey(ctx context.Context, kid string) (*rsa.PublicKey, error) { |
| 129 | + keys, err := fetchChatJWKs(ctx, false) |
| 130 | + if err != nil { |
| 131 | + return nil, fmt.Errorf("fetch certs: %w", err) |
| 132 | + } |
| 133 | + if key, ok := keys[kid]; ok { |
| 134 | + return key, nil |
| 135 | + } |
| 136 | + |
| 137 | + // Key not found — force refresh (Google may have rotated keys) |
| 138 | + keys, err = fetchChatJWKs(ctx, true) |
| 139 | + if err != nil { |
| 140 | + return nil, fmt.Errorf("refresh certs: %w", err) |
| 141 | + } |
| 142 | + if key, ok := keys[kid]; ok { |
| 143 | + return key, nil |
| 144 | + } |
| 145 | + return nil, fmt.Errorf("unknown signing key: %s", kid) |
| 146 | +} |
| 147 | + |
| 148 | +// fetchChatJWKs fetches Google Chat JWKs with caching. |
| 149 | +// forceRefresh bypasses the cache TTL. |
| 150 | +func fetchChatJWKs(ctx context.Context, forceRefresh bool) (map[string]*rsa.PublicKey, error) { |
| 151 | + chatCertCache.mu.RLock() |
| 152 | + if !forceRefresh && time.Since(chatCertCache.fetched) < jwkCacheTTL && len(chatCertCache.keys) > 0 { |
| 153 | + keys := chatCertCache.keys |
| 154 | + chatCertCache.mu.RUnlock() |
| 155 | + return keys, nil |
| 156 | + } |
| 157 | + chatCertCache.mu.RUnlock() |
| 158 | + |
| 159 | + chatCertCache.mu.Lock() |
| 160 | + defer chatCertCache.mu.Unlock() |
| 161 | + |
| 162 | + // Double-check after acquiring write lock |
| 163 | + if !forceRefresh && time.Since(chatCertCache.fetched) < jwkCacheTTL && len(chatCertCache.keys) > 0 { |
| 164 | + return chatCertCache.keys, nil |
| 165 | + } |
| 166 | + |
| 167 | + req, err := http.NewRequestWithContext(ctx, http.MethodGet, chatJWKURL, nil) |
| 168 | + if err != nil { |
| 169 | + return nil, err |
| 170 | + } |
| 171 | + resp, err := http.DefaultClient.Do(req) |
| 172 | + if err != nil { |
| 173 | + return nil, fmt.Errorf("fetch JWKs: %w", err) |
| 174 | + } |
| 175 | + defer resp.Body.Close() |
| 176 | + |
| 177 | + if resp.StatusCode != http.StatusOK { |
| 178 | + return nil, fmt.Errorf("JWK endpoint returned %d", resp.StatusCode) |
| 179 | + } |
| 180 | + |
| 181 | + var jwks jwkSet |
| 182 | + if err := json.NewDecoder(resp.Body).Decode(&jwks); err != nil { |
| 183 | + return nil, fmt.Errorf("decode JWKs: %w", err) |
| 184 | + } |
| 185 | + |
| 186 | + keys := make(map[string]*rsa.PublicKey, len(jwks.Keys)) |
| 187 | + for _, k := range jwks.Keys { |
| 188 | + if k.Kty != "RSA" { |
| 189 | + continue |
| 190 | + } |
| 191 | + pub, err := rsaPubFromJWK(k.N, k.E) |
| 192 | + if err != nil { |
| 193 | + continue |
| 194 | + } |
| 195 | + keys[k.Kid] = pub |
| 196 | + } |
| 197 | + |
| 198 | + chatCertCache.keys = keys |
| 199 | + chatCertCache.fetched = time.Now() |
| 200 | + return keys, nil |
| 201 | +} |
| 202 | + |
| 203 | +// rsaPubFromJWK converts base64url-encoded RSA modulus and exponent to an rsa.PublicKey. |
| 204 | +func rsaPubFromJWK(nB64, eB64 string) (*rsa.PublicKey, error) { |
| 205 | + nBytes, err := base64.RawURLEncoding.DecodeString(nB64) |
| 206 | + if err != nil { |
| 207 | + return nil, err |
| 208 | + } |
| 209 | + eBytes, err := base64.RawURLEncoding.DecodeString(eB64) |
| 210 | + if err != nil { |
| 211 | + return nil, err |
| 212 | + } |
| 213 | + |
| 214 | + e := 0 |
| 215 | + for _, b := range eBytes { |
| 216 | + e = e*256 + int(b) |
| 217 | + } |
| 218 | + |
| 219 | + return &rsa.PublicKey{ |
| 220 | + N: new(big.Int).SetBytes(nBytes), |
| 221 | + E: e, |
| 222 | + }, nil |
| 223 | +} |
0 commit comments