vendor: cloud.google.com/go/auth v0.17.0

full diff: https://github.com/googleapis/google-cloud-go/compare/auth/v0.16.5...auth/v0.17.0

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
This commit is contained in:
Sebastiaan van Stijn
2026-01-15 13:35:58 +01:00
parent 2cd55b272c
commit c7d9ac59c3
18 changed files with 929 additions and 66 deletions

2
go.mod
View File

@@ -123,7 +123,7 @@ require (
require (
cloud.google.com/go v0.121.6 // indirect
cloud.google.com/go/auth v0.16.5 // indirect
cloud.google.com/go/auth v0.17.0 // indirect
cloud.google.com/go/auth/oauth2adapt v0.2.8 // indirect
cloud.google.com/go/longrunning v0.6.7 // indirect
cyphar.com/go-pathrs v0.2.1 // indirect

4
go.sum
View File

@@ -2,8 +2,8 @@ cloud.google.com/go v0.16.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMT
cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw=
cloud.google.com/go v0.121.6 h1:waZiuajrI28iAf40cWgycWNgaXPO06dupuS+sgibK6c=
cloud.google.com/go v0.121.6/go.mod h1:coChdst4Ea5vUpiALcYKXEpR1S9ZgXbhEzzMcMR66vI=
cloud.google.com/go/auth v0.16.5 h1:mFWNQ2FEVWAliEQWpAdH80omXFokmrnbDhUS9cBywsI=
cloud.google.com/go/auth v0.16.5/go.mod h1:utzRfHMP+Vv0mpOkTRQoWD2q3BatTOoWbA7gCc2dUhQ=
cloud.google.com/go/auth v0.17.0 h1:74yCm7hCj2rUyyAocqnFzsAYXgJhrG26XCFimrc/Kz4=
cloud.google.com/go/auth v0.17.0/go.mod h1:6wv/t5/6rOPAX4fJiRjKkJCvswLwdet7G8+UGXt7nCQ=
cloud.google.com/go/auth/oauth2adapt v0.2.8 h1:keo8NaayQZ6wimpNSmW5OPc283g65QNIiLpZnkHRbnc=
cloud.google.com/go/auth/oauth2adapt v0.2.8/go.mod h1:XQ9y31RkqZCcwJWNSx2Xvric3RrU88hAYYbjDWYDL+c=
cloud.google.com/go/compute/metadata v0.9.0 h1:pDUj4QMoPejqq20dK0Pg2N4yG9zIkYGdBtwLoEkH9Zs=

View File

@@ -1,3 +1,10 @@
## [0.17.0](https://github.com/googleapis/google-cloud-go/releases/tag/auth%2Fv0.17.0) (2025-10-02)
### Features
* Add trust boundary support for service accounts and impersonation (HTTP/gRPC) (#11870) ([5c2b665](https://github.com/googleapis/google-cloud-go/commit/5c2b665f392e6dd90192f107188720aa1357e7da))
* add trust boundary support for external accounts (#12864) ([a67a146](https://github.com/googleapis/google-cloud-go/commit/a67a146a6a88a6f1ba10c409dfce8015ecd60a64))
# Changelog
## [0.16.5](https://github.com/googleapis/google-cloud-go/compare/auth/v0.16.4...auth/v0.16.5) (2025-08-14)

View File

@@ -483,6 +483,8 @@ type Options2LO struct {
Audience string
// PrivateClaims allows specifying any custom claims for the JWT. Optional.
PrivateClaims map[string]interface{}
// UniverseDomain is the default service domain for a given Cloud universe.
UniverseDomain string
// Client is the client to be used to make the underlying token requests.
// Optional.

View File

@@ -92,11 +92,11 @@ func (cs *computeProvider) Token(ctx context.Context) (*auth.Token, error) {
if res.ExpiresInSec == 0 || res.AccessToken == "" {
return nil, errors.New("credentials: incomplete token received from metadata")
}
return &auth.Token{
token := &auth.Token{
Value: res.AccessToken,
Type: res.TokenType,
Expiry: time.Now().Add(time.Duration(res.ExpiresInSec) * time.Second),
Metadata: computeTokenMetadata,
}, nil
}
return token, nil
}

View File

@@ -27,6 +27,7 @@ import (
"cloud.google.com/go/auth"
"cloud.google.com/go/auth/internal"
"cloud.google.com/go/auth/internal/credsfile"
"cloud.google.com/go/auth/internal/trustboundary"
"cloud.google.com/go/compute/metadata"
"github.com/googleapis/gax-go/v2/internallog"
)
@@ -95,6 +96,10 @@ func DetectDefault(opts *DetectOptions) (*auth.Credentials, error) {
if err := opts.validate(); err != nil {
return nil, err
}
trustBoundaryEnabled, err := trustboundary.IsEnabled()
if err != nil {
return nil, err
}
if len(opts.CredentialsJSON) > 0 {
return readCredentialsFileJSON(opts.CredentialsJSON, opts)
}
@@ -119,14 +124,26 @@ func DetectDefault(opts *DetectOptions) (*auth.Credentials, error) {
Logger: opts.logger(),
UseDefaultClient: true,
})
gceUniverseDomainProvider := &internal.ComputeUniverseDomainProvider{
MetadataClient: metadataClient,
}
tp := computeTokenProvider(opts, metadataClient)
if trustBoundaryEnabled {
gceConfigProvider := trustboundary.NewGCEConfigProvider(gceUniverseDomainProvider)
var err error
tp, err = trustboundary.NewProvider(opts.client(), gceConfigProvider, opts.logger(), tp)
if err != nil {
return nil, fmt.Errorf("credentials: failed to initialize GCE trust boundary provider: %w", err)
}
}
return auth.NewCredentials(&auth.CredentialsOptions{
TokenProvider: computeTokenProvider(opts, metadataClient),
TokenProvider: tp,
ProjectIDProvider: auth.CredentialsPropertyFunc(func(ctx context.Context) (string, error) {
return metadataClient.ProjectIDWithContext(ctx)
}),
UniverseDomainProvider: &internal.ComputeUniverseDomainProvider{
MetadataClient: metadataClient,
},
UniverseDomainProvider: gceUniverseDomainProvider,
}), nil
}

View File

@@ -25,6 +25,7 @@ import (
"cloud.google.com/go/auth/credentials/internal/impersonate"
internalauth "cloud.google.com/go/auth/internal"
"cloud.google.com/go/auth/internal/credsfile"
"cloud.google.com/go/auth/internal/trustboundary"
)
func fileCredentials(b []byte, opts *DetectOptions) (*auth.Credentials, error) {
@@ -136,19 +137,34 @@ func handleServiceAccount(f *credsfile.ServiceAccountFile, opts *DetectOptions)
return configureSelfSignedJWT(f, opts)
}
opts2LO := &auth.Options2LO{
Email: f.ClientEmail,
PrivateKey: []byte(f.PrivateKey),
PrivateKeyID: f.PrivateKeyID,
Scopes: opts.scopes(),
TokenURL: f.TokenURL,
Subject: opts.Subject,
Client: opts.client(),
Logger: opts.logger(),
Email: f.ClientEmail,
PrivateKey: []byte(f.PrivateKey),
PrivateKeyID: f.PrivateKeyID,
Scopes: opts.scopes(),
TokenURL: f.TokenURL,
Subject: opts.Subject,
Client: opts.client(),
Logger: opts.logger(),
UniverseDomain: ud,
}
if opts2LO.TokenURL == "" {
opts2LO.TokenURL = jwtTokenURL
}
return auth.New2LOTokenProvider(opts2LO)
tp, err := auth.New2LOTokenProvider(opts2LO)
if err != nil {
return nil, err
}
trustBoundaryEnabled, err := trustboundary.IsEnabled()
if err != nil {
return nil, err
}
if !trustBoundaryEnabled {
return tp, nil
}
saConfig := trustboundary.NewServiceAccountConfigProvider(opts2LO.Email, opts2LO.UniverseDomain)
return trustboundary.NewProvider(opts.client(), saConfig, opts.logger(), tp)
}
func handleUserCredential(f *credsfile.UserCredentialsFile, opts *DetectOptions) (auth.TokenProvider, error) {
@@ -187,7 +203,39 @@ func handleExternalAccount(f *credsfile.ExternalAccountFile, opts *DetectOptions
if f.ServiceAccountImpersonation != nil {
externalOpts.ServiceAccountImpersonationLifetimeSeconds = f.ServiceAccountImpersonation.TokenLifetimeSeconds
}
return externalaccount.NewTokenProvider(externalOpts)
tp, err := externalaccount.NewTokenProvider(externalOpts)
if err != nil {
return nil, err
}
trustBoundaryEnabled, err := trustboundary.IsEnabled()
if err != nil {
return nil, err
}
if !trustBoundaryEnabled {
return tp, nil
}
ud := resolveUniverseDomain(opts.UniverseDomain, f.UniverseDomain)
var configProvider trustboundary.ConfigProvider
if f.ServiceAccountImpersonationURL == "" {
// No impersonation, this is a direct external account credential.
// The trust boundary is based on the workload/workforce pool.
var err error
configProvider, err = trustboundary.NewExternalAccountConfigProvider(f.Audience, ud)
if err != nil {
return nil, err
}
} else {
// Impersonation is used. The trust boundary is based on the target service account.
targetSAEmail, err := impersonate.ExtractServiceAccountEmail(f.ServiceAccountImpersonationURL)
if err != nil {
return nil, fmt.Errorf("credentials: could not extract target service account email for trust boundary: %w", err)
}
configProvider = trustboundary.NewServiceAccountConfigProvider(targetSAEmail, ud)
}
return trustboundary.NewProvider(opts.client(), configProvider, opts.logger(), tp)
}
func handleExternalAccountAuthorizedUser(f *credsfile.ExternalAccountAuthorizedUserFile, opts *DetectOptions) (auth.TokenProvider, error) {
@@ -202,7 +250,24 @@ func handleExternalAccountAuthorizedUser(f *credsfile.ExternalAccountAuthorizedU
Client: opts.client(),
Logger: opts.logger(),
}
return externalaccountuser.NewTokenProvider(externalOpts)
tp, err := externalaccountuser.NewTokenProvider(externalOpts)
if err != nil {
return nil, err
}
trustBoundaryEnabled, err := trustboundary.IsEnabled()
if err != nil {
return nil, err
}
if !trustBoundaryEnabled {
return tp, nil
}
ud := resolveUniverseDomain(opts.UniverseDomain, f.UniverseDomain)
configProvider, err := trustboundary.NewExternalAccountConfigProvider(f.Audience, ud)
if err != nil {
return nil, err
}
return trustboundary.NewProvider(opts.client(), configProvider, opts.logger(), tp)
}
func handleImpersonatedServiceAccount(f *credsfile.ImpersonatedServiceAccountFile, opts *DetectOptions) (auth.TokenProvider, error) {
@@ -210,20 +275,38 @@ func handleImpersonatedServiceAccount(f *credsfile.ImpersonatedServiceAccountFil
return nil, errors.New("missing 'source_credentials' field or 'service_account_impersonation_url' in credentials")
}
tp, err := fileCredentials(f.CredSource, opts)
sourceTP, err := fileCredentials(f.CredSource, opts)
if err != nil {
return nil, err
}
return impersonate.NewTokenProvider(&impersonate.Options{
URL: f.ServiceAccountImpersonationURL,
Scopes: opts.scopes(),
Tp: tp,
Delegates: f.Delegates,
Client: opts.client(),
Logger: opts.logger(),
})
ud := resolveUniverseDomain(opts.UniverseDomain, f.UniverseDomain)
impOpts := &impersonate.Options{
URL: f.ServiceAccountImpersonationURL,
Scopes: opts.scopes(),
Tp: sourceTP,
Delegates: f.Delegates,
Client: opts.client(),
Logger: opts.logger(),
UniverseDomain: ud,
}
tp, err := impersonate.NewTokenProvider(impOpts)
if err != nil {
return nil, err
}
trustBoundaryEnabled, err := trustboundary.IsEnabled()
if err != nil {
return nil, err
}
if !trustBoundaryEnabled {
return tp, nil
}
targetSAEmail, err := impersonate.ExtractServiceAccountEmail(f.ServiceAccountImpersonationURL)
if err != nil {
return nil, fmt.Errorf("credentials: could not extract target service account email for trust boundary: %w", err)
}
targetSAConfig := trustboundary.NewServiceAccountConfigProvider(targetSAEmail, ud)
return trustboundary.NewProvider(opts.client(), targetSAConfig, opts.logger(), tp)
}
func handleGDCHServiceAccount(f *credsfile.GDCHServiceAccountFile, opts *DetectOptions) (auth.TokenProvider, error) {
return gdch.NewTokenProvider(f, &gdch.Options{
STSAudience: opts.STSAudience,

View File

@@ -22,10 +22,12 @@ import (
"fmt"
"log/slog"
"net/http"
"regexp"
"time"
"cloud.google.com/go/auth"
"cloud.google.com/go/auth/internal"
"cloud.google.com/go/auth/internal/transport/headers"
"github.com/googleapis/gax-go/v2/internallog"
)
@@ -34,6 +36,8 @@ const (
authHeaderKey = "Authorization"
)
var serviceAccountEmailRegex = regexp.MustCompile(`serviceAccounts/(.+?):generateAccessToken`)
// generateAccesstokenReq is used for service account impersonation
type generateAccessTokenReq struct {
Delegates []string `json:"delegates,omitempty"`
@@ -81,6 +85,8 @@ type Options struct {
// enabled by setting GOOGLE_SDK_GO_LOGGING_LEVEL in which case a default
// logger will be used. Optional.
Logger *slog.Logger
// UniverseDomain is the default service domain for a given Cloud universe.
UniverseDomain string
}
func (o *Options) validate() error {
@@ -114,9 +120,11 @@ func (o *Options) Token(ctx context.Context) (*auth.Token, error) {
return nil, fmt.Errorf("credentials: unable to create impersonation request: %w", err)
}
req.Header.Set("Content-Type", "application/json")
if err := setAuthHeader(ctx, o.Tp, req); err != nil {
sourceToken, err := o.Tp.Token(ctx)
if err != nil {
return nil, err
}
headers.SetAuthHeader(sourceToken, req)
logger.DebugContext(ctx, "impersonated token request", "request", internallog.HTTPRequest(req, b))
resp, body, err := internal.DoRequest(o.Client, req)
if err != nil {
@@ -135,22 +143,26 @@ func (o *Options) Token(ctx context.Context) (*auth.Token, error) {
if err != nil {
return nil, fmt.Errorf("credentials: unable to parse expiry: %w", err)
}
return &auth.Token{
token := &auth.Token{
Value: accessTokenResp.AccessToken,
Expiry: expiry,
Type: internal.TokenTypeBearer,
}, nil
}
return token, nil
}
func setAuthHeader(ctx context.Context, tp auth.TokenProvider, r *http.Request) error {
t, err := tp.Token(ctx)
if err != nil {
return err
// ExtractServiceAccountEmail extracts the service account email from the impersonation URL.
// The impersonation URL is expected to be in the format:
// https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/{SERVICE_ACCOUNT_EMAIL}:generateAccessToken
// or
// https://iamcredentials.googleapis.com/v1/projects/{PROJECT_ID}/serviceAccounts/{SERVICE_ACCOUNT_EMAIL}:generateAccessToken
// Returns an error if the email cannot be extracted.
func ExtractServiceAccountEmail(impersonationURL string) (string, error) {
matches := serviceAccountEmailRegex.FindStringSubmatch(impersonationURL)
if len(matches) < 2 {
return "", fmt.Errorf("credentials: invalid impersonation URL format: %s", impersonationURL)
}
typ := t.Type
if typ == "" {
typ = internal.TokenTypeBearer
}
r.Header.Set(authHeaderKey, typ+" "+t.Value)
return nil
return matches[1], nil
}

View File

@@ -30,6 +30,7 @@ import (
"cloud.google.com/go/auth/credentials"
"cloud.google.com/go/auth/internal"
"cloud.google.com/go/auth/internal/transport"
"cloud.google.com/go/auth/internal/transport/headers"
"github.com/googleapis/gax-go/v2/internallog"
"go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc"
"google.golang.org/grpc"
@@ -428,23 +429,13 @@ func (c *grpcCredentialsProvider) GetRequestMetadata(ctx context.Context, uri ..
}
}
metadata := make(map[string]string, len(c.metadata)+1)
setAuthMetadata(token, metadata)
headers.SetAuthMetadata(token, metadata)
for k, v := range c.metadata {
metadata[k] = v
}
return metadata, nil
}
// setAuthMetadata uses the provided token to set the Authorization metadata.
// If the token.Type is empty, the type is assumed to be Bearer.
func setAuthMetadata(token *auth.Token, m map[string]string) {
typ := token.Type
if typ == "" {
typ = internal.TokenTypeBearer
}
m["authorization"] = typ + " " + token.Value
}
func (c *grpcCredentialsProvider) RequireTransportSecurity() bool {
return c.secure
}

View File

@@ -25,8 +25,8 @@ import (
"cloud.google.com/go/auth"
detect "cloud.google.com/go/auth/credentials"
"cloud.google.com/go/auth/internal"
"cloud.google.com/go/auth/internal/transport"
"cloud.google.com/go/auth/internal/transport/headers"
"github.com/googleapis/gax-go/v2/internallog"
)
@@ -236,12 +236,10 @@ func NewClient(opts *Options) (*http.Client, error) {
}, nil
}
// SetAuthHeader uses the provided token to set the Authorization header on a
// request. If the token.Type is empty, the type is assumed to be Bearer.
// SetAuthHeader uses the provided token to set the Authorization and trust
// boundary headers on an http.Request. If the token.Type is empty, the type is
// assumed to be Bearer. This is the recommended way to set authorization
// headers on a custom http.Request.
func SetAuthHeader(token *auth.Token, req *http.Request) {
typ := token.Type
if typ == "" {
typ = internal.TokenTypeBearer
}
req.Header.Set("Authorization", typ+" "+token.Value)
headers.SetAuthHeader(token, req)
}

View File

@@ -27,6 +27,7 @@ import (
"cloud.google.com/go/auth/internal"
"cloud.google.com/go/auth/internal/transport"
"cloud.google.com/go/auth/internal/transport/cert"
"cloud.google.com/go/auth/internal/transport/headers"
"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"
"golang.org/x/net/http2"
)
@@ -228,7 +229,7 @@ func (t *authTransport) RoundTrip(req *http.Request) (*http.Response, error) {
}
}
req2 := req.Clone(req.Context())
SetAuthHeader(token, req2)
headers.SetAuthHeader(token, req2)
reqBodyClosed = true
return t.base.RoundTrip(req2)
}

View File

@@ -47,6 +47,12 @@ const (
// DefaultUniverseDomain is the default value for universe domain.
// Universe domain is the default service domain for a given Cloud universe.
DefaultUniverseDomain = "googleapis.com"
// TrustBoundaryNoOp is a constant indicating no trust boundary is enforced.
TrustBoundaryNoOp = "0x0"
// TrustBoundaryDataKey is the key used to store trust boundary data in a token's metadata.
TrustBoundaryDataKey = "google.auth.trust_boundary_data"
)
type clonableTransport interface {
@@ -223,3 +229,56 @@ func getMetadataUniverseDomain(ctx context.Context, client *metadata.Client) (st
func FormatIAMServiceAccountResource(name string) string {
return fmt.Sprintf("projects/-/serviceAccounts/%s", name)
}
// TrustBoundaryData represents the trust boundary data associated with a token.
// It contains information about the regions or environments where the token is valid.
type TrustBoundaryData struct {
// Locations is the list of locations that the token is allowed to be used in.
Locations []string
// EncodedLocations represents the locations in an encoded format.
EncodedLocations string
}
// NewTrustBoundaryData returns a new TrustBoundaryData with the specified locations and encoded locations.
func NewTrustBoundaryData(locations []string, encodedLocations string) *TrustBoundaryData {
// Ensure consistency by treating a nil slice as an empty slice.
if locations == nil {
locations = []string{}
}
locationsCopy := make([]string, len(locations))
copy(locationsCopy, locations)
return &TrustBoundaryData{
Locations: locationsCopy,
EncodedLocations: encodedLocations,
}
}
// NewNoOpTrustBoundaryData returns a new TrustBoundaryData with no restrictions.
func NewNoOpTrustBoundaryData() *TrustBoundaryData {
return &TrustBoundaryData{
Locations: []string{},
EncodedLocations: TrustBoundaryNoOp,
}
}
// TrustBoundaryHeader returns the value for the x-allowed-locations header and a bool
// indicating if the header should be set. The return values are structured to
// handle three distinct states required by the backend:
// 1. Header not set: (value="", present=false) -> data is empty.
// 2. Header set to an empty string: (value="", present=true) -> data is a no-op.
// 3. Header set to a value: (value="...", present=true) -> data has locations.
func (t TrustBoundaryData) TrustBoundaryHeader() (value string, present bool) {
if t.EncodedLocations == "" {
// If the data is empty, the header should not be present.
return "", false
}
// If data is not empty, the header should always be present.
present = true
value = ""
if t.EncodedLocations != TrustBoundaryNoOp {
value = t.EncodedLocations
}
// For a no-op, the backend requires an empty string.
return value, present
}

117
vendor/cloud.google.com/go/auth/internal/retry/retry.go generated vendored Normal file
View File

@@ -0,0 +1,117 @@
// Copyright 2025 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package retry
import (
"context"
"io"
"math/rand"
"net/http"
"time"
)
const (
maxRetryAttempts = 5
)
var (
syscallRetryable = func(error) bool { return false }
)
// defaultBackoff is basically equivalent to gax.Backoff without the need for
// the dependency.
type defaultBackoff struct {
max time.Duration
mul float64
cur time.Duration
}
func (b *defaultBackoff) Pause() time.Duration {
d := time.Duration(1 + rand.Int63n(int64(b.cur)))
b.cur = time.Duration(float64(b.cur) * b.mul)
if b.cur > b.max {
b.cur = b.max
}
return d
}
// Sleep is the equivalent of gax.Sleep without the need for the dependency.
func Sleep(ctx context.Context, d time.Duration) error {
t := time.NewTimer(d)
select {
case <-ctx.Done():
t.Stop()
return ctx.Err()
case <-t.C:
return nil
}
}
// New returns a new Retryer with the default backoff strategy.
func New() *Retryer {
return &Retryer{bo: &defaultBackoff{
cur: 100 * time.Millisecond,
max: 30 * time.Second,
mul: 2,
}}
}
type backoff interface {
Pause() time.Duration
}
// Retryer is a retryer for HTTP requests.
type Retryer struct {
bo backoff
attempts int
}
// Retry determines if a request should be retried.
func (r *Retryer) Retry(status int, err error) (time.Duration, bool) {
if status == http.StatusOK {
return 0, false
}
retryOk := shouldRetry(status, err)
if !retryOk {
return 0, false
}
if r.attempts == maxRetryAttempts {
return 0, false
}
r.attempts++
return r.bo.Pause(), true
}
func shouldRetry(status int, err error) bool {
if 500 <= status && status <= 599 {
return true
}
if err == io.ErrUnexpectedEOF {
return true
}
// Transient network errors should be retried.
if syscallRetryable(err) {
return true
}
if err, ok := err.(interface{ Temporary() bool }); ok {
if err.Temporary() {
return true
}
}
if err, ok := err.(interface{ Unwrap() error }); ok {
return shouldRetry(status, err.Unwrap())
}
return false
}

View File

@@ -0,0 +1,61 @@
// Copyright 2025 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package headers
import (
"net/http"
"cloud.google.com/go/auth"
"cloud.google.com/go/auth/internal"
)
// SetAuthHeader uses the provided token to set the Authorization and trust
// boundary headers on a request. If the token.Type is empty, the type is
// assumed to be Bearer.
func SetAuthHeader(token *auth.Token, req *http.Request) {
typ := token.Type
if typ == "" {
typ = internal.TokenTypeBearer
}
req.Header.Set("Authorization", typ+" "+token.Value)
if headerVal, setHeader := getTrustBoundaryHeader(token); setHeader {
req.Header.Set("x-allowed-locations", headerVal)
}
}
// SetAuthMetadata uses the provided token to set the Authorization and trust
// boundary metadata. If the token.Type is empty, the type is assumed to be
// Bearer.
func SetAuthMetadata(token *auth.Token, m map[string]string) {
typ := token.Type
if typ == "" {
typ = internal.TokenTypeBearer
}
m["authorization"] = typ + " " + token.Value
if headerVal, setHeader := getTrustBoundaryHeader(token); setHeader {
m["x-allowed-locations"] = headerVal
}
}
func getTrustBoundaryHeader(token *auth.Token) (val string, present bool) {
if data, ok := token.Metadata[internal.TrustBoundaryDataKey]; ok {
if tbd, ok := data.(internal.TrustBoundaryData); ok {
return tbd.TrustBoundaryHeader()
}
}
return "", false
}

View File

@@ -0,0 +1,100 @@
// Copyright 2025 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package trustboundary
import (
"context"
"fmt"
"regexp"
)
const (
workloadAllowedLocationsEndpoint = "https://iamcredentials.%s/v1/projects/%s/locations/global/workloadIdentityPools/%s/allowedLocations"
workforceAllowedLocationsEndpoint = "https://iamcredentials.%s/v1/locations/global/workforcePools/%s/allowedLocations"
)
var (
workforceAudiencePattern = regexp.MustCompile(`//iam\.([^/]+)/locations/global/workforcePools/([^/]+)`)
workloadAudiencePattern = regexp.MustCompile(`//iam\.([^/]+)/projects/([^/]+)/locations/global/workloadIdentityPools/([^/]+)`)
)
// NewExternalAccountConfigProvider creates a new ConfigProvider for external accounts.
func NewExternalAccountConfigProvider(audience, inputUniverseDomain string) (ConfigProvider, error) {
var audienceDomain, projectNumber, poolID string
var isWorkload bool
matches := workloadAudiencePattern.FindStringSubmatch(audience)
if len(matches) == 4 { // Expecting full match, domain, projectNumber, poolID
audienceDomain = matches[1]
projectNumber = matches[2]
poolID = matches[3]
isWorkload = true
} else {
matches = workforceAudiencePattern.FindStringSubmatch(audience)
if len(matches) == 3 { // Expecting full match, domain, poolID
audienceDomain = matches[1]
poolID = matches[2]
isWorkload = false
} else {
return nil, fmt.Errorf("trustboundary: unknown audience format: %q", audience)
}
}
effectiveUniverseDomain := inputUniverseDomain
if effectiveUniverseDomain == "" {
effectiveUniverseDomain = audienceDomain
} else if audienceDomain != "" && effectiveUniverseDomain != audienceDomain {
return nil, fmt.Errorf("trustboundary: provided universe domain (%q) does not match domain in audience (%q)", inputUniverseDomain, audienceDomain)
}
if isWorkload {
return &workloadIdentityPoolConfigProvider{
projectNumber: projectNumber,
poolID: poolID,
universeDomain: effectiveUniverseDomain,
}, nil
}
return &workforcePoolConfigProvider{
poolID: poolID,
universeDomain: effectiveUniverseDomain,
}, nil
}
type workforcePoolConfigProvider struct {
poolID string
universeDomain string
}
func (p *workforcePoolConfigProvider) GetTrustBoundaryEndpoint(ctx context.Context) (string, error) {
return fmt.Sprintf(workforceAllowedLocationsEndpoint, p.universeDomain, p.poolID), nil
}
func (p *workforcePoolConfigProvider) GetUniverseDomain(ctx context.Context) (string, error) {
return p.universeDomain, nil
}
type workloadIdentityPoolConfigProvider struct {
projectNumber string
poolID string
universeDomain string
}
func (p *workloadIdentityPoolConfigProvider) GetTrustBoundaryEndpoint(ctx context.Context) (string, error) {
return fmt.Sprintf(workloadAllowedLocationsEndpoint, p.universeDomain, p.projectNumber, p.poolID), nil
}
func (p *workloadIdentityPoolConfigProvider) GetUniverseDomain(ctx context.Context) (string, error) {
return p.universeDomain, nil
}

View File

@@ -0,0 +1,392 @@
// Copyright 2025 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package trustboundary
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"log/slog"
"net/http"
"os"
"strings"
"sync"
"cloud.google.com/go/auth"
"cloud.google.com/go/auth/internal"
"cloud.google.com/go/auth/internal/retry"
"cloud.google.com/go/auth/internal/transport/headers"
"github.com/googleapis/gax-go/v2/internallog"
)
const (
// serviceAccountAllowedLocationsEndpoint is the URL for fetching allowed locations for a given service account email.
serviceAccountAllowedLocationsEndpoint = "https://iamcredentials.%s/v1/projects/-/serviceAccounts/%s/allowedLocations"
)
// isEnabled wraps isTrustBoundaryEnabled with sync.OnceValues to ensure it's
// called only once.
var isEnabled = sync.OnceValues(isTrustBoundaryEnabled)
// IsEnabled returns if the trust boundary feature is enabled and an error if
// the configuration is invalid. The underlying check is performed only once.
func IsEnabled() (bool, error) {
return isEnabled()
}
// isTrustBoundaryEnabled checks if the trust boundary feature is enabled via
// GOOGLE_AUTH_TRUST_BOUNDARY_ENABLED environment variable.
//
// If the environment variable is not set, it is considered false.
//
// The environment variable is interpreted as a boolean with the following
// (case-insensitive) rules:
// - "true", "1" are considered true.
// - "false", "0" are considered false.
//
// Any other values will return an error.
func isTrustBoundaryEnabled() (bool, error) {
const envVar = "GOOGLE_AUTH_TRUST_BOUNDARY_ENABLED"
val, ok := os.LookupEnv(envVar)
if !ok {
return false, nil
}
val = strings.ToLower(val)
switch val {
case "true", "1":
return true, nil
case "false", "0":
return false, nil
default:
return false, fmt.Errorf(`invalid value for %s: %q. Must be one of "true", "false", "1", or "0"`, envVar, val)
}
}
// ConfigProvider provides specific configuration for trust boundary lookups.
type ConfigProvider interface {
// GetTrustBoundaryEndpoint returns the endpoint URL for the trust boundary lookup.
GetTrustBoundaryEndpoint(ctx context.Context) (url string, err error)
// GetUniverseDomain returns the universe domain associated with the credential.
// It may return an error if the universe domain cannot be determined.
GetUniverseDomain(ctx context.Context) (string, error)
}
// AllowedLocationsResponse is the structure of the response from the Trust Boundary API.
type AllowedLocationsResponse struct {
// Locations is the list of allowed locations.
Locations []string `json:"locations"`
// EncodedLocations is the encoded representation of the allowed locations.
EncodedLocations string `json:"encodedLocations"`
}
// fetchTrustBoundaryData fetches the trust boundary data from the API.
func fetchTrustBoundaryData(ctx context.Context, client *http.Client, url string, token *auth.Token, logger *slog.Logger) (*internal.TrustBoundaryData, error) {
if logger == nil {
logger = slog.New(slog.NewTextHandler(io.Discard, nil))
}
if client == nil {
return nil, errors.New("trustboundary: HTTP client is required")
}
if url == "" {
return nil, errors.New("trustboundary: URL cannot be empty")
}
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
if err != nil {
return nil, fmt.Errorf("trustboundary: failed to create trust boundary request: %w", err)
}
if token == nil || token.Value == "" {
return nil, errors.New("trustboundary: access token required for lookup API authentication")
}
headers.SetAuthHeader(token, req)
logger.DebugContext(ctx, "trust boundary request", "request", internallog.HTTPRequest(req, nil))
retryer := retry.New()
var response *http.Response
for {
response, err = client.Do(req)
var statusCode int
if response != nil {
statusCode = response.StatusCode
}
pause, shouldRetry := retryer.Retry(statusCode, err)
if !shouldRetry {
break
}
if response != nil {
// Drain and close the body to reuse the connection
io.Copy(io.Discard, response.Body)
response.Body.Close()
}
if err := retry.Sleep(ctx, pause); err != nil {
return nil, err
}
}
if err != nil {
return nil, fmt.Errorf("trustboundary: failed to fetch trust boundary: %w", err)
}
defer response.Body.Close()
body, err := io.ReadAll(response.Body)
if err != nil {
return nil, fmt.Errorf("trustboundary: failed to read trust boundary response: %w", err)
}
logger.DebugContext(ctx, "trust boundary response", "response", internallog.HTTPResponse(response, body))
if response.StatusCode != http.StatusOK {
return nil, fmt.Errorf("trustboundary: trust boundary request failed with status: %s, body: %s", response.Status, string(body))
}
apiResponse := AllowedLocationsResponse{}
if err := json.Unmarshal(body, &apiResponse); err != nil {
return nil, fmt.Errorf("trustboundary: failed to unmarshal trust boundary response: %w", err)
}
if apiResponse.EncodedLocations == "" {
return nil, errors.New("trustboundary: invalid API response: encodedLocations is empty")
}
return internal.NewTrustBoundaryData(apiResponse.Locations, apiResponse.EncodedLocations), nil
}
// serviceAccountConfig holds configuration for SA trust boundary lookups.
// It implements the ConfigProvider interface.
type serviceAccountConfig struct {
ServiceAccountEmail string
UniverseDomain string
}
// NewServiceAccountConfigProvider creates a new config for service accounts.
func NewServiceAccountConfigProvider(saEmail, universeDomain string) ConfigProvider {
return &serviceAccountConfig{
ServiceAccountEmail: saEmail,
UniverseDomain: universeDomain,
}
}
// GetTrustBoundaryEndpoint returns the formatted URL for fetching allowed locations
// for the configured service account and universe domain.
func (sac *serviceAccountConfig) GetTrustBoundaryEndpoint(ctx context.Context) (url string, err error) {
if sac.ServiceAccountEmail == "" {
return "", errors.New("trustboundary: service account email cannot be empty for config")
}
ud := sac.UniverseDomain
if ud == "" {
ud = internal.DefaultUniverseDomain
}
return fmt.Sprintf(serviceAccountAllowedLocationsEndpoint, ud, sac.ServiceAccountEmail), nil
}
// GetUniverseDomain returns the configured universe domain, defaulting to
// [internal.DefaultUniverseDomain] if not explicitly set.
func (sac *serviceAccountConfig) GetUniverseDomain(ctx context.Context) (string, error) {
if sac.UniverseDomain == "" {
return internal.DefaultUniverseDomain, nil
}
return sac.UniverseDomain, nil
}
// DataProvider fetches and caches trust boundary Data.
// It implements the DataProvider interface and uses a ConfigProvider
// to get type-specific details for the lookup.
type DataProvider struct {
client *http.Client
configProvider ConfigProvider
data *internal.TrustBoundaryData
logger *slog.Logger
base auth.TokenProvider
}
// NewProvider wraps the provided base [auth.TokenProvider] to create a new
// provider that injects tokens with trust boundary data. It uses the provided
// HTTP client and configProvider to fetch the data and attach it to the token's
// metadata.
func NewProvider(client *http.Client, configProvider ConfigProvider, logger *slog.Logger, base auth.TokenProvider) (*DataProvider, error) {
if client == nil {
return nil, errors.New("trustboundary: HTTP client cannot be nil for DataProvider")
}
if configProvider == nil {
return nil, errors.New("trustboundary: ConfigProvider cannot be nil for DataProvider")
}
p := &DataProvider{
client: client,
configProvider: configProvider,
logger: internallog.New(logger),
base: base,
}
return p, nil
}
// Token retrieves a token from the base provider and injects it with trust
// boundary data.
func (p *DataProvider) Token(ctx context.Context) (*auth.Token, error) {
// Get the original token.
token, err := p.base.Token(ctx)
if err != nil {
return nil, err
}
tbData, err := p.GetTrustBoundaryData(ctx, token)
if err != nil {
return nil, fmt.Errorf("trustboundary: error fetching the trust boundary data: %w", err)
}
if tbData != nil {
if token.Metadata == nil {
token.Metadata = make(map[string]interface{})
}
token.Metadata[internal.TrustBoundaryDataKey] = *tbData
}
return token, nil
}
// GetTrustBoundaryData retrieves the trust boundary data.
// It first checks the universe domain: if it's non-default, a NoOp is returned.
// Otherwise, it checks a local cache. If the data is not cached as NoOp,
// it fetches new data from the endpoint provided by its ConfigProvider,
// using the given accessToken for authentication. Results are cached.
// If fetching fails, it returns previously cached data if available, otherwise the fetch error.
func (p *DataProvider) GetTrustBoundaryData(ctx context.Context, token *auth.Token) (*internal.TrustBoundaryData, error) {
// Check the universe domain.
uniDomain, err := p.configProvider.GetUniverseDomain(ctx)
if err != nil {
return nil, fmt.Errorf("trustboundary: error getting universe domain: %w", err)
}
if uniDomain != "" && uniDomain != internal.DefaultUniverseDomain {
if p.data == nil || p.data.EncodedLocations != internal.TrustBoundaryNoOp {
p.data = internal.NewNoOpTrustBoundaryData()
}
return p.data, nil
}
// Check cache for a no-op result from a previous API call.
cachedData := p.data
if cachedData != nil && cachedData.EncodedLocations == internal.TrustBoundaryNoOp {
return cachedData, nil
}
// Get the endpoint
url, err := p.configProvider.GetTrustBoundaryEndpoint(ctx)
if err != nil {
return nil, fmt.Errorf("trustboundary: error getting the lookup endpoint: %w", err)
}
// Proceed to fetch new data.
newData, fetchErr := fetchTrustBoundaryData(ctx, p.client, url, token, p.logger)
if fetchErr != nil {
// Fetch failed. Fallback to cachedData if available.
if cachedData != nil {
return cachedData, nil // Successful fallback
}
// No cache to fallback to.
return nil, fmt.Errorf("trustboundary: failed to fetch trust boundary data for endpoint %s and no cache available: %w", url, fetchErr)
}
// Fetch successful. Update cache.
p.data = newData
return newData, nil
}
// GCEConfigProvider implements ConfigProvider for GCE environments.
// It lazily fetches and caches the necessary metadata (service account email, universe domain)
// from the GCE metadata server.
type GCEConfigProvider struct {
// universeDomainProvider provides the universe domain and underlying metadata client.
universeDomainProvider *internal.ComputeUniverseDomainProvider
// Caching for service account email
saOnce sync.Once
saEmail string
saEmailErr error
// Caching for universe domain
udOnce sync.Once
ud string
udErr error
}
// NewGCEConfigProvider creates a new GCEConfigProvider
// which uses the provided gceUDP to interact with the GCE metadata server.
func NewGCEConfigProvider(gceUDP *internal.ComputeUniverseDomainProvider) *GCEConfigProvider {
// The validity of gceUDP and its internal MetadataClient will be checked
// within the GetTrustBoundaryEndpoint and GetUniverseDomain methods.
return &GCEConfigProvider{
universeDomainProvider: gceUDP,
}
}
func (g *GCEConfigProvider) fetchSA(ctx context.Context) {
if g.universeDomainProvider == nil || g.universeDomainProvider.MetadataClient == nil {
g.saEmailErr = errors.New("trustboundary: GCEConfigProvider not properly initialized (missing ComputeUniverseDomainProvider or MetadataClient)")
return
}
mdClient := g.universeDomainProvider.MetadataClient
saEmail, err := mdClient.EmailWithContext(ctx, "default")
if err != nil {
g.saEmailErr = fmt.Errorf("trustboundary: GCE config: failed to get service account email: %w", err)
return
}
g.saEmail = saEmail
}
func (g *GCEConfigProvider) fetchUD(ctx context.Context) {
if g.universeDomainProvider == nil || g.universeDomainProvider.MetadataClient == nil {
g.udErr = errors.New("trustboundary: GCEConfigProvider not properly initialized (missing ComputeUniverseDomainProvider or MetadataClient)")
return
}
ud, err := g.universeDomainProvider.GetProperty(ctx)
if err != nil {
g.udErr = fmt.Errorf("trustboundary: GCE config: failed to get universe domain: %w", err)
return
}
if ud == "" {
ud = internal.DefaultUniverseDomain
}
g.ud = ud
}
// GetTrustBoundaryEndpoint constructs the trust boundary lookup URL for a GCE environment.
// It uses cached metadata (service account email, universe domain) after the first call.
func (g *GCEConfigProvider) GetTrustBoundaryEndpoint(ctx context.Context) (string, error) {
g.saOnce.Do(func() { g.fetchSA(ctx) })
if g.saEmailErr != nil {
return "", g.saEmailErr
}
g.udOnce.Do(func() { g.fetchUD(ctx) })
if g.udErr != nil {
return "", g.udErr
}
return fmt.Sprintf(serviceAccountAllowedLocationsEndpoint, g.ud, g.saEmail), nil
}
// GetUniverseDomain retrieves the universe domain from the GCE metadata server.
// It uses a cached value after the first call.
func (g *GCEConfigProvider) GetUniverseDomain(ctx context.Context) (string, error) {
g.udOnce.Do(func() { g.fetchUD(ctx) })
if g.udErr != nil {
return "", g.udErr
}
return g.ud, nil
}

20
vendor/cloud.google.com/go/auth/internal/version.go generated vendored Normal file
View File

@@ -0,0 +1,20 @@
// Copyright 2025 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Code generated by gapicgen. DO NOT EDIT.
package internal
// Version is the current tagged release of the library.
const Version = "0.17.0"

7
vendor/modules.txt vendored
View File

@@ -1,8 +1,8 @@
# cloud.google.com/go v0.121.6
## explicit; go 1.23.0
cloud.google.com/go
# cloud.google.com/go/auth v0.16.5
## explicit; go 1.23.0
# cloud.google.com/go/auth v0.17.0
## explicit; go 1.24.0
cloud.google.com/go/auth
cloud.google.com/go/auth/credentials
cloud.google.com/go/auth/credentials/internal/externalaccount
@@ -16,8 +16,11 @@ cloud.google.com/go/auth/internal
cloud.google.com/go/auth/internal/compute
cloud.google.com/go/auth/internal/credsfile
cloud.google.com/go/auth/internal/jwt
cloud.google.com/go/auth/internal/retry
cloud.google.com/go/auth/internal/transport
cloud.google.com/go/auth/internal/transport/cert
cloud.google.com/go/auth/internal/transport/headers
cloud.google.com/go/auth/internal/trustboundary
# cloud.google.com/go/auth/oauth2adapt v0.2.8
## explicit; go 1.23.0
cloud.google.com/go/auth/oauth2adapt