newKMSClient returns a GCP KMS client configured with the tokenSource or credentialJSON, and/or grpcConn, falling back to environmental defaults. It returns an error if the ResourceID is invalid, or if the setup of the client fails.
(ctx context.Context)
| 288 | // It returns an error if the ResourceID is invalid, or if the setup of the |
| 289 | // client fails. |
| 290 | func (key *MasterKey) newKMSClient(ctx context.Context) (*kms.KeyManagementClient, error) { |
| 291 | re := regexp.MustCompile(`^projects/[^/]+/locations/[^/]+/keyRings/[^/]+/cryptoKeys/[^/]+$`) |
| 292 | matches := re.FindStringSubmatch(key.ResourceID) |
| 293 | if matches == nil { |
| 294 | return nil, fmt.Errorf("no valid resource ID found in %q", key.ResourceID) |
| 295 | } |
| 296 | |
| 297 | var opts []option.ClientOption |
| 298 | switch { |
| 299 | case key.tokenSource != nil: |
| 300 | opts = append(opts, option.WithTokenSource(key.tokenSource)) |
| 301 | case key.credentialJSON != nil: |
| 302 | opts = append(opts, option.WithCredentialsJSON(key.credentialJSON)) |
| 303 | default: |
| 304 | credentials, err := getGoogleCredentials() |
| 305 | if err != nil { |
| 306 | return nil, fmt.Errorf("credentials: failed to obtain credentials from %q: %w", SopsGoogleCredentialsEnv, err) |
| 307 | } |
| 308 | if credentials != nil { |
| 309 | opts = append(opts, option.WithCredentialsJSON(credentials)) |
| 310 | break |
| 311 | } |
| 312 | |
| 313 | if atCredentials := getGoogleOAuthTokenFromEnv(); atCredentials != nil { |
| 314 | opts = append(opts, option.WithTokenSource(atCredentials)) |
| 315 | break |
| 316 | } |
| 317 | } |
| 318 | |
| 319 | switch { |
| 320 | case key.grpcConn != nil: |
| 321 | opts = append(opts, option.WithGRPCConn(key.grpcConn)) |
| 322 | case len(key.grpcDialOpts) > 0: |
| 323 | for _, opt := range key.grpcDialOpts { |
| 324 | opts = append(opts, option.WithGRPCDialOption(opt)) |
| 325 | } |
| 326 | } |
| 327 | |
| 328 | // Add extra options. |
| 329 | opts = append(opts, key.clientOpts...) |
| 330 | |
| 331 | if endpoint := os.Getenv(SopsGCPKMSEndpointEnv); endpoint != "" { |
| 332 | opts = append(opts, option.WithEndpoint(endpoint)) |
| 333 | } else if ud := os.Getenv(SopsGCPKMSUniverseDomainEnv); ud != "" { |
| 334 | opts = append(opts, option.WithUniverseDomain(ud)) |
| 335 | } |
| 336 | |
| 337 | // Select client type based on inputs. |
| 338 | clientType := strings.ToLower(os.Getenv(SopsGCPKMSClientTypeEnv)) |
| 339 | var client *kms.KeyManagementClient |
| 340 | var err error |
| 341 | switch { |
| 342 | case clientType == "rest", key.useRESTClient: |
| 343 | client, err = kms.NewKeyManagementRESTClient(ctx, opts...) |
| 344 | default: |
| 345 | client, err = kms.NewKeyManagementClient(ctx, opts...) |
| 346 | } |
| 347 | if err != nil { |