diff --git a/go.mod b/go.mod index 0138cc3414..24cf02f36c 100644 --- a/go.mod +++ b/go.mod @@ -3,7 +3,7 @@ module github.com/GoogleContainerTools/config-sync go 1.26.0 require ( - cloud.google.com/go/auth v0.20.0 + cloud.google.com/go/auth v0.21.0 cloud.google.com/go/compute/metadata v0.9.0 cloud.google.com/go/logging v1.18.0 cloud.google.com/go/monitoring v1.29.0 @@ -41,7 +41,7 @@ require ( go.uber.org/zap v1.28.0 golang.org/x/exp v0.0.0-20241217172543-b2144cdd0a67 golang.org/x/mod v0.38.0 - google.golang.org/api v0.286.0 + google.golang.org/api v0.287.1 gopkg.in/yaml.v3 v3.0.1 k8s.io/api v0.35.6 k8s.io/apiextensions-apiserver v0.35.6 @@ -105,8 +105,8 @@ require ( github.com/google/btree v1.1.3 // indirect github.com/google/licenseclassifier/v2 v2.0.0 // indirect github.com/google/s2a-go v0.1.9 // indirect - github.com/googleapis/enterprise-certificate-proxy v0.3.16 // indirect - github.com/googleapis/gax-go/v2 v2.22.0 // indirect + github.com/googleapis/enterprise-certificate-proxy v0.3.17 // indirect + github.com/googleapis/gax-go/v2 v2.23.0 // indirect github.com/gregjones/httpcache v0.0.0-20190611155906-901d90724c79 // indirect github.com/grpc-ecosystem/grpc-gateway/v2 v2.29.0 // indirect github.com/inconshreveable/mousetrap v1.1.0 // indirect @@ -162,9 +162,9 @@ require ( golang.org/x/tools v0.47.0 // indirect gomodules.xyz/jsonpatch/v2 v2.4.0 // indirect google.golang.org/genproto v0.0.0-20260319201613-d00831a3d3e7 // indirect - google.golang.org/genproto/googleapis/api v0.0.0-20260526163538-3dc84a4a5aaa // indirect - google.golang.org/genproto/googleapis/rpc v0.0.0-20260610212136-7ab31c22f7ad // indirect - google.golang.org/grpc v1.81.1 // indirect + google.golang.org/genproto/googleapis/api v0.0.0-20260630182238-925bb5da69e7 // indirect + google.golang.org/genproto/googleapis/rpc v0.0.0-20260630182238-925bb5da69e7 // indirect + google.golang.org/grpc v1.82.0 // indirect google.golang.org/protobuf v1.36.12-0.20260120151049-f2248ac996af // indirect gopkg.in/evanphx/json-patch.v4 v4.13.0 // indirect gopkg.in/inf.v0 v0.9.1 // indirect diff --git a/go.sum b/go.sum index e9e3d2f043..2d4137a0e0 100644 --- a/go.sum +++ b/go.sum @@ -5,8 +5,8 @@ cel.dev/expr v0.25.1/go.mod h1:hrXvqGP6G6gyx8UAHSHJ5RGk//1Oj5nXQ2NI02Nrsg4= cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= cloud.google.com/go v0.123.0 h1:2NAUJwPR47q+E35uaJeYoNhuNEM9kM8SjgRgdeOJUSE= cloud.google.com/go v0.123.0/go.mod h1:xBoMV08QcqUGuPW65Qfm1o9Y4zKZBpGS+7bImXLTAZU= -cloud.google.com/go/auth v0.20.0 h1:kXTssoVb4azsVDoUiF8KvxAqrsQcQtB53DcSgta74CA= -cloud.google.com/go/auth v0.20.0/go.mod h1:942/yi/itH1SsmpyrbnTMDgGfdy2BUqIKyd0cyYLc5Q= +cloud.google.com/go/auth v0.21.0 h1:g/QwYfYb2Ai6HH8oomAOyBaIHLbscZ4+T/F/f5JZHkE= +cloud.google.com/go/auth v0.21.0/go.mod h1:M9o2Oz+YI2jAfxewJgb1vyI3vceHF+eohmxyzmrl+9s= 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= @@ -28,8 +28,8 @@ github.com/Azure/go-ansiterm v0.0.0-20230124172434-306776ec8161/go.mod h1:xomTg6 github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= github.com/BurntSushi/toml v1.4.0 h1:kuoIxZQy2WRRk1pttg9asf+WVv6tWQuBNVmK8+nqPr0= github.com/BurntSushi/toml v1.4.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho= -github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.31.0 h1:DHa2U07rk8syqvCge0QIGMCE1WxGj9njT44GH7zNJLQ= -github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.31.0/go.mod h1:P4WPRUkOhJC13W//jWpyfJNDAIpvRbAUIYLX/4jtlE0= +github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.32.0 h1:rIkQfkCOVKc1OiRCNcSDD8ml5RJlZbH/Xsq7lbpynwc= +github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.32.0/go.mod h1:RD2SsorTmYhF6HkTmDw7KmPYQk8OBYwTkuasChwv7R4= github.com/GoogleCloudPlatform/opentelemetry-operations-go/exporter/metric v0.55.0 h1:UnDZ/zFfG1JhH/DqxIZYU/1CUAlTUScoXD/LcM2Ykk8= github.com/GoogleCloudPlatform/opentelemetry-operations-go/exporter/metric v0.55.0/go.mod h1:IA1C1U7jO/ENqm/vhi7V9YYpBsp+IMyqNrEN94N7tVc= github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/resourcemapping v0.55.0 h1:0s6TxfCu2KHkkZPnBfsQ2y5qia0jl3MMrmBhu3nCOYk= @@ -182,10 +182,10 @@ github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510/go.mod h1:pupxD2MaaD3 github.com/google/uuid v1.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= -github.com/googleapis/enterprise-certificate-proxy v0.3.16 h1:F/VPrx0YPBdksZJQdCAp0WUsqnNmZpUZszzfYt0M5Dw= -github.com/googleapis/enterprise-certificate-proxy v0.3.16/go.mod h1:9Yb0eAkH/Xqhvv3zbeKf/+wMJqCeocWc6KIhDvEAuYE= -github.com/googleapis/gax-go/v2 v2.22.0 h1:PjIWBpgGIVKGoCXuiCoP64altEJCj3/Ei+kSU5vlZD4= -github.com/googleapis/gax-go/v2 v2.22.0/go.mod h1:irWBbALSr0Sk3qlqb9SyJ1h68WjgeFuiOzI4Rqw5+aY= +github.com/googleapis/enterprise-certificate-proxy v0.3.17 h1:73NfMHdiqo9JFU9+7a5ExpVa10/R29pXfZIaW559nrg= +github.com/googleapis/enterprise-certificate-proxy v0.3.17/go.mod h1:rSEsBUemEBZEexP2y6jPp16LUmUbjmSbcPMQizR0o4k= +github.com/googleapis/gax-go/v2 v2.23.0 h1:Tchl7qkvE7Ip3y+ztvNufYFvkfqTe7NfLTYGIdJRLuE= +github.com/googleapis/gax-go/v2 v2.23.0/go.mod h1:rBQKOVJCdb8IFEzg+FCwlt1LP/xMDGuqUXhUG+XMXEg= github.com/gregjones/httpcache v0.0.0-20190611155906-901d90724c79 h1:+ngKgrYPPJrOjhax5N+uePQ0Fh1Z7PheYoUI/0nzkPA= github.com/gregjones/httpcache v0.0.0-20190611155906-901d90724c79/go.mod h1:FecbI9+v66THATjSRHfNgh1IVFe/9kFxbXtjV0ctIMA= github.com/grpc-ecosystem/grpc-gateway/v2 v2.29.0 h1:5VipnvEpbqr2gA2VbM+nYVbkIF28c5ZQfqCBQ5g2xfk= @@ -324,8 +324,8 @@ go.opencensus.io v0.24.0 h1:y73uSU6J157QMP2kn2r30vwW1A2W2WFwSCGnAVxeaD0= go.opencensus.io v0.24.0/go.mod h1:vNK8G9p7aAivkbmorf4v+7Hgx+Zs0yY+0fOtgBfjQKo= go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64= go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y= -go.opentelemetry.io/contrib/detectors/gcp v1.42.0 h1:kpt2PEJuOuqYkPcktfJqWWDjTEd/FNgrxcniL7kQrXQ= -go.opentelemetry.io/contrib/detectors/gcp v1.42.0/go.mod h1:W9zQ439utxymRrXsUOzZbFX4JhLxXU4+ZnCt8GG7yA8= +go.opentelemetry.io/contrib/detectors/gcp v1.43.0 h1:62yY3dT7/ShwOxzA0RsKRgshBmfElKI4d/Myu2OxDFU= +go.opentelemetry.io/contrib/detectors/gcp v1.43.0/go.mod h1:RyaZMFY7yi1kAs45S6mbFGz8O8rqB0dTY14uzvG4LCs= go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.67.0 h1:yI1/OhfEPy7J9eoa6Sj051C7n5dvpj0QX8g4sRchg04= go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.67.0/go.mod h1:NoUCKYWK+3ecatC4HjkRktREheMeEtrXoQxrqYFeHSc= go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.67.0 h1:OyrsyzuttWTSur2qN/Lm0m2a8yqyIjUVBZcxFPuXq2o= @@ -420,8 +420,8 @@ gomodules.xyz/jsonpatch/v2 v2.4.0 h1:Ci3iUJyx9UeRx7CeFN8ARgGbkESwJK+KB9lLcWxY/Zw gomodules.xyz/jsonpatch/v2 v2.4.0/go.mod h1:AH3dM2RI6uoBZxn3LVrfvJ3E0/9dG4cSrbuBJT4moAY= gonum.org/v1/gonum v0.17.0 h1:VbpOemQlsSMrYmn7T2OUvQ4dqxQXU+ouZFQsZOx50z4= gonum.org/v1/gonum v0.17.0/go.mod h1:El3tOrEuMpv2UdMrbNlKEh9vd86bmQ6vqIcDwxEOc1E= -google.golang.org/api v0.286.0 h1:TdTXMvzYKnWV1/lPbCdbXRqBrkDqjPto22H2xeZZ8LI= -google.golang.org/api v0.286.0/go.mod h1:NlOlUIr8MPoIhT9Bb/oUnRuHbJOLwxb6JSYJM8Yz+jQ= +google.golang.org/api v0.287.1 h1:LiyJx32VU3cwQfLchn/513qKhc25hq0pEANYJoWNnnI= +google.golang.org/api v0.287.1/go.mod h1:lM2kYRzYUCBY91P9h6VF1PYmvhxii3O5hji37qRvIcY= google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= @@ -429,17 +429,17 @@ google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55/go.mod h1:DMBHOl98 google.golang.org/genproto v0.0.0-20200526211855-cb27e3aa2013/go.mod h1:NbSheEEYHJ7i3ixzK3sjbqSGDJWnxyFXZblF3eUsNvo= google.golang.org/genproto v0.0.0-20260319201613-d00831a3d3e7 h1:XzmzkmB14QhVhgnawEVsOn6OFsnpyxNPRY9QV01dNB0= google.golang.org/genproto v0.0.0-20260319201613-d00831a3d3e7/go.mod h1:L43LFes82YgSonw6iTXTxXUX1OlULt4AQtkik4ULL/I= -google.golang.org/genproto/googleapis/api v0.0.0-20260526163538-3dc84a4a5aaa h1:Kjn0N0tCrDgiAFW+lGO4JZ3ck44CehvJQMAwj9QF0G8= -google.golang.org/genproto/googleapis/api v0.0.0-20260526163538-3dc84a4a5aaa/go.mod h1:q4lMZS6kskjT5HvCPrnnypcDPVJqT/f4nfxmkE7gryY= -google.golang.org/genproto/googleapis/rpc v0.0.0-20260610212136-7ab31c22f7ad h1:45WmJvIV6C2+O/jjLkPUH+F3aOj/1miDoU2DD0+NWbg= -google.golang.org/genproto/googleapis/rpc v0.0.0-20260610212136-7ab31c22f7ad/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8= +google.golang.org/genproto/googleapis/api v0.0.0-20260630182238-925bb5da69e7 h1:jQ9p21COKWjP3VwuFrNRiiOTMh3mPpN45R7SLrH/HUU= +google.golang.org/genproto/googleapis/api v0.0.0-20260630182238-925bb5da69e7/go.mod h1:KqHwBx2upmfa1XSi1WuRvC+2VGCLtooKkfmyvRbUmqA= +google.golang.org/genproto/googleapis/rpc v0.0.0-20260630182238-925bb5da69e7 h1:eM/YSd5bBFagF51o1E745Ta7RwzpW0h+z+QDNZOgmQ8= +google.golang.org/genproto/googleapis/rpc v0.0.0-20260630182238-925bb5da69e7/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8= google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= google.golang.org/grpc v1.23.0/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg= google.golang.org/grpc v1.25.1/go.mod h1:c3i+UQWmh7LiEpx4sFZnkU36qjEYZ0imhYfXVyQciAY= google.golang.org/grpc v1.27.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= google.golang.org/grpc v1.33.2/go.mod h1:JMHMWHQWaTccqQQlmk3MJZS+GWXOdAesneDmEnv2fbc= -google.golang.org/grpc v1.81.1 h1:VnnIIZ88UzOOKLukQi+ImGz8O1Wdp8nAGGnvOfEIWQQ= -google.golang.org/grpc v1.81.1/go.mod h1:xGH9GfzOyMTGIOXBJmXt+BX/V0kcdQbdcuwQ/zNw42I= +google.golang.org/grpc v1.82.0 h1:vguDnZUPjE26w09A63VoxZPnvPjB5Riyc0mkXPFmAIU= +google.golang.org/grpc v1.82.0/go.mod h1:yzTZ1TB1Z3SG+LIYaI+WiE8D5+PZ3ArnrSp8zF3+/ZA= google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0= google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM= diff --git a/vendor/cloud.google.com/go/auth/CHANGES.md b/vendor/cloud.google.com/go/auth/CHANGES.md index 2c1f6ff8fa..a51c653fd5 100644 --- a/vendor/cloud.google.com/go/auth/CHANGES.md +++ b/vendor/cloud.google.com/go/auth/CHANGES.md @@ -1,5 +1,18 @@ # Changes +## [0.21.0](https://github.com/googleapis/google-cloud-go/compare/auth/v0.20.0...auth/v0.21.0) (2026-07-07) + + +### Features + +* **auth:** Implement updated design for regional access boundary ([#13417](https://github.com/googleapis/google-cloud-go/issues/13417)) ([fadb6c7](https://github.com/googleapis/google-cloud-go/commit/fadb6c764dbe869fca736d9f0446b5010f21d2f2)) + + +### Bug Fixes + +* **auth:** Avoid double impersonation in idtoken and clarify docs ([#14474](https://github.com/googleapis/google-cloud-go/issues/14474)) ([995bfc3](https://github.com/googleapis/google-cloud-go/commit/995bfc36199ba6ae1c88803c71f39a0b19fc8c0f)), closes [#11105](https://github.com/googleapis/google-cloud-go/issues/11105) +* **auth:** Correct go min version ([#20094](https://github.com/googleapis/google-cloud-go/issues/20094)) ([6bb4358](https://github.com/googleapis/google-cloud-go/commit/6bb4358dca69b803e52eb2af882fa5afc24d54e2)) + ## [0.20.0](https://github.com/googleapis/google-cloud-go/releases/tag/auth%2Fv0.20.0) (2026-04-06) ## [0.19.0](https://github.com/googleapis/google-cloud-go/releases/tag/auth%2Fv0.19.0) (2026-03-23) diff --git a/vendor/cloud.google.com/go/auth/credentials/detect.go b/vendor/cloud.google.com/go/auth/credentials/detect.go index c9d7600e03..9ce369d79f 100644 --- a/vendor/cloud.google.com/go/auth/credentials/detect.go +++ b/vendor/cloud.google.com/go/auth/credentials/detect.go @@ -27,7 +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/auth/internal/regionalaccessboundary" "cloud.google.com/go/compute/metadata" "github.com/googleapis/gax-go/v2/internallog" ) @@ -138,11 +138,15 @@ func OnGCE() bool { // Google APIs can compromise the security of your systems and data. For // more information, refer to [Validate credential configurations from // external sources](https://cloud.google.com/docs/authentication/external/externally-sourced-credentials). +// +// Note: If the detected credential configuration file contains a +// `service_account_impersonation_url` field, the returned credentials will +// yield tokens that are already impersonated to that target service account. func DetectDefault(opts *DetectOptions) (*auth.Credentials, error) { if err := opts.validate(); err != nil { return nil, err } - trustBoundaryEnabled, err := trustboundary.IsEnabled() + regionalAccessBoundaryEnabled, err := regionalaccessboundary.IsEnabled() if err != nil { return nil, err } @@ -175,12 +179,12 @@ func DetectDefault(opts *DetectOptions) (*auth.Credentials, error) { } tp := computeTokenProvider(opts, metadataClient) - if trustBoundaryEnabled { - gceConfigProvider := trustboundary.NewGCEConfigProvider(gceUniverseDomainProvider) + if regionalAccessBoundaryEnabled { + gceConfigProvider := regionalaccessboundary.NewGCEConfigProvider(gceUniverseDomainProvider) var err error - tp, err = trustboundary.NewProvider(opts.client(), gceConfigProvider, opts.logger(), tp) + tp, err = regionalaccessboundary.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 nil, fmt.Errorf("credentials: failed to initialize GCE Regional Access Boundary provider: %w", err) } } diff --git a/vendor/cloud.google.com/go/auth/credentials/filetypes.go b/vendor/cloud.google.com/go/auth/credentials/filetypes.go index f3737a5e8c..a82995582c 100644 --- a/vendor/cloud.google.com/go/auth/credentials/filetypes.go +++ b/vendor/cloud.google.com/go/auth/credentials/filetypes.go @@ -25,7 +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" + "cloud.google.com/go/auth/internal/regionalaccessboundary" ) const cloudPlatformScope = "https://www.googleapis.com/auth/cloud-platform" @@ -159,15 +159,15 @@ func handleServiceAccount(f *credsfile.ServiceAccountFile, opts *DetectOptions) return nil, err } - trustBoundaryEnabled, err := trustboundary.IsEnabled() + regionalAccessBoundaryEnabled, err := regionalaccessboundary.IsEnabled() if err != nil { return nil, err } - if !trustBoundaryEnabled { + if !regionalAccessBoundaryEnabled { return tp, nil } - saConfig := trustboundary.NewServiceAccountConfigProvider(opts2LO.Email, opts2LO.UniverseDomain) - return trustboundary.NewProvider(opts.client(), saConfig, opts.logger(), tp) + saConfig := regionalaccessboundary.NewServiceAccountConfigProvider(opts2LO.Email, opts2LO.UniverseDomain) + return regionalaccessboundary.NewProvider(opts.client(), saConfig, opts.logger(), tp) } func handleUserCredential(f *credsfile.UserCredentialsFile, opts *DetectOptions) (auth.TokenProvider, error) { @@ -210,35 +210,35 @@ func handleExternalAccount(f *credsfile.ExternalAccountFile, opts *DetectOptions if err != nil { return nil, err } - trustBoundaryEnabled, err := trustboundary.IsEnabled() + regionalAccessBoundaryEnabled, err := regionalaccessboundary.IsEnabled() if err != nil { return nil, err } - if !trustBoundaryEnabled { + if !regionalAccessBoundaryEnabled { return tp, nil } ud := resolveUniverseDomain(opts.UniverseDomain, f.UniverseDomain) - var configProvider trustboundary.ConfigProvider + var configProvider regionalaccessboundary.ConfigProvider if f.ServiceAccountImpersonationURL == "" { // No impersonation, this is a direct external account credential. - // The trust boundary is based on the workload/workforce pool. + // The Regional Access Boundary is based on the workload/workforce pool. var err error - configProvider, err = trustboundary.NewExternalAccountConfigProvider(f.Audience, ud) + configProvider, err = regionalaccessboundary.NewExternalAccountConfigProvider(f.Audience, ud) if err != nil { return nil, err } } else { - // Impersonation is used. The trust boundary is based on the target service account. + // Impersonation is used. The Regional Access 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) + return nil, fmt.Errorf("credentials: could not extract target service account email for Regional Access Boundary: %w", err) } - configProvider = trustboundary.NewServiceAccountConfigProvider(targetSAEmail, ud) + configProvider = regionalaccessboundary.NewServiceAccountConfigProvider(targetSAEmail, ud) } - return trustboundary.NewProvider(opts.client(), configProvider, opts.logger(), tp) + return regionalaccessboundary.NewProvider(opts.client(), configProvider, opts.logger(), tp) } func handleExternalAccountAuthorizedUser(f *credsfile.ExternalAccountAuthorizedUserFile, opts *DetectOptions) (auth.TokenProvider, error) { @@ -257,20 +257,20 @@ func handleExternalAccountAuthorizedUser(f *credsfile.ExternalAccountAuthorizedU if err != nil { return nil, err } - trustBoundaryEnabled, err := trustboundary.IsEnabled() + regionalAccessBoundaryEnabled, err := regionalaccessboundary.IsEnabled() if err != nil { return nil, err } - if !trustBoundaryEnabled { + if !regionalAccessBoundaryEnabled { return tp, nil } ud := resolveUniverseDomain(opts.UniverseDomain, f.UniverseDomain) - configProvider, err := trustboundary.NewExternalAccountConfigProvider(f.Audience, ud) + configProvider, err := regionalaccessboundary.NewExternalAccountConfigProvider(f.Audience, ud) if err != nil { return nil, err } - return trustboundary.NewProvider(opts.client(), configProvider, opts.logger(), tp) + return regionalaccessboundary.NewProvider(opts.client(), configProvider, opts.logger(), tp) } func handleImpersonatedServiceAccount(f *credsfile.ImpersonatedServiceAccountFile, opts *DetectOptions) (auth.TokenProvider, error) { @@ -306,19 +306,19 @@ func handleImpersonatedServiceAccount(f *credsfile.ImpersonatedServiceAccountFil if err != nil { return nil, err } - trustBoundaryEnabled, err := trustboundary.IsEnabled() + regionalAccessBoundaryEnabled, err := regionalaccessboundary.IsEnabled() if err != nil { return nil, err } - if !trustBoundaryEnabled { + if !regionalAccessBoundaryEnabled { 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) + return nil, fmt.Errorf("credentials: could not extract target service account email for Regional Access Boundary: %w", err) } - targetSAConfig := trustboundary.NewServiceAccountConfigProvider(targetSAEmail, ud) - return trustboundary.NewProvider(opts.client(), targetSAConfig, opts.logger(), tp) + targetSAConfig := regionalaccessboundary.NewServiceAccountConfigProvider(targetSAEmail, ud) + return regionalaccessboundary.NewProvider(opts.client(), targetSAConfig, opts.logger(), tp) } func handleGDCHServiceAccount(f *credsfile.GDCHServiceAccountFile, opts *DetectOptions) (auth.TokenProvider, error) { return gdch.NewTokenProvider(f, &gdch.Options{ diff --git a/vendor/cloud.google.com/go/auth/grpctransport/directpath.go b/vendor/cloud.google.com/go/auth/grpctransport/directpath.go index 69d6d0034e..c405e9f8ec 100644 --- a/vendor/cloud.google.com/go/auth/grpctransport/directpath.go +++ b/vendor/cloud.google.com/go/auth/grpctransport/directpath.go @@ -120,7 +120,7 @@ func configureDirectPath(grpcOpts []grpc.DialOption, opts *Options, endpoint str }) if isDirectPathEnabled(endpoint, opts) && compute.OnComputeEngine() && isTokenProviderDirectPathCompatible(creds, opts) { // Overwrite all of the previously specific DialOptions, DirectPath uses its own set of credentials and certificates. - defaultCredetialsOptions := grpcgoogle.DefaultCredentialsOptions{PerRPCCreds: &grpcCredentialsProvider{creds: creds}} + defaultCredetialsOptions := grpcgoogle.DefaultCredentialsOptions{PerRPCCreds: &grpcCredentialsProvider{creds: creds, endpoint: endpoint}} if isDirectPathBoundTokenEnabled(opts.InternalOptions) && isTokenProviderComputeEngine(creds) { optsClone := opts.resolveDetectOptions() optsClone.TokenBindingType = credentials.ALTSHardBinding @@ -128,7 +128,7 @@ func configureDirectPath(grpcOpts []grpc.DialOption, opts *Options, endpoint str if err != nil { return nil, "", err } - defaultCredetialsOptions.ALTSPerRPCCreds = &grpcCredentialsProvider{creds: altsCreds} + defaultCredetialsOptions.ALTSPerRPCCreds = &grpcCredentialsProvider{creds: altsCreds, endpoint: endpoint} } grpcOpts = []grpc.DialOption{ grpc.WithCredentialsBundle(grpcgoogle.NewDefaultCredentialsWithOptions(defaultCredetialsOptions))} diff --git a/vendor/cloud.google.com/go/auth/grpctransport/grpctransport.go b/vendor/cloud.google.com/go/auth/grpctransport/grpctransport.go index f77f6423c4..f76091b634 100644 --- a/vendor/cloud.google.com/go/auth/grpctransport/grpctransport.go +++ b/vendor/cloud.google.com/go/auth/grpctransport/grpctransport.go @@ -358,6 +358,7 @@ func dial(ctx context.Context, secure bool, opts *Options) (*grpc.ClientConn, er creds: creds, metadata: metadata, clientUniverseDomain: opts.UniverseDomain, + endpoint: transportCreds.Endpoint, }), ) // Attempt Direct Path @@ -405,6 +406,7 @@ type grpcCredentialsProvider struct { // Additional metadata attached as headers. metadata map[string]string clientUniverseDomain string + endpoint string } // getClientUniverseDomain returns the default service domain for a given Cloud @@ -447,7 +449,7 @@ func (c *grpcCredentialsProvider) GetRequestMetadata(ctx context.Context, uri .. } } metadata := make(map[string]string, len(c.metadata)+1) - headers.SetAuthMetadata(token, metadata) + headers.SetAuthMetadata(ctx, token, c.endpoint, metadata) for k, v := range c.metadata { metadata[k] = v } diff --git a/vendor/cloud.google.com/go/auth/internal/internal.go b/vendor/cloud.google.com/go/auth/internal/internal.go index 48e9bd9ece..d79e0ffbe5 100644 --- a/vendor/cloud.google.com/go/auth/internal/internal.go +++ b/vendor/cloud.google.com/go/auth/internal/internal.go @@ -48,11 +48,8 @@ const ( // 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" + // RegionalAccessBoundaryDataKey is the key used to store regional access boundary data in a token's metadata. + RegionalAccessBoundaryDataKey = "google.auth.regional_access_boundary_data" ) type clonableTransport interface { @@ -231,55 +228,35 @@ func FormatIAMServiceAccountResource(name string) string { return fmt.Sprintf("projects/-/serviceAccounts/%s", name) } -// TrustBoundaryData represents the trust boundary data associated with a token. +// RegionalAccessBoundaryData represents the regional access boundary data associated with a token. // It contains information about the regions or environments where the token is valid. -type TrustBoundaryData struct { +type RegionalAccessBoundaryData 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 { +// NewRegionalAccessBoundaryData returns a new RegionalAccessBoundaryData with the specified locations and encoded locations. +func NewRegionalAccessBoundaryData(locations []string, encodedLocations string) *RegionalAccessBoundaryData { // 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{ + return &RegionalAccessBoundaryData{ 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) { +// RegionalAccessBoundaryHeader returns the value for the x-allowed-locations header and a bool +// indicating if the header should be set. If EncodedLocations is empty, the header +// should not be present. Otherwise, it should be present with the value of EncodedLocations. +func (t RegionalAccessBoundaryData) RegionalAccessBoundaryHeader() (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 + return t.EncodedLocations, true } diff --git a/vendor/cloud.google.com/go/auth/internal/trustboundary/external_accounts_config_providers.go b/vendor/cloud.google.com/go/auth/internal/regionalaccessboundary/external_accounts_config_providers.go similarity index 60% rename from vendor/cloud.google.com/go/auth/internal/trustboundary/external_accounts_config_providers.go rename to vendor/cloud.google.com/go/auth/internal/regionalaccessboundary/external_accounts_config_providers.go index 8fa5600bdc..2c1189017f 100644 --- a/vendor/cloud.google.com/go/auth/internal/trustboundary/external_accounts_config_providers.go +++ b/vendor/cloud.google.com/go/auth/internal/regionalaccessboundary/external_accounts_config_providers.go @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -package trustboundary +package regionalaccessboundary import ( "context" @@ -21,13 +21,13 @@ import ( ) const ( - workloadAllowedLocationsEndpoint = "https://iamcredentials.%s/v1/projects/%s/locations/global/workloadIdentityPools/%s/allowedLocations" - workforceAllowedLocationsEndpoint = "https://iamcredentials.%s/v1/locations/global/workforcePools/%s/allowedLocations" + workloadAllowedLocationsEndpoint = "https://iamcredentials.googleapis.com/v1/projects/%s/locations/global/workloadIdentityPools/%s/allowedLocations" + workforceAllowedLocationsEndpoint = "https://iamcredentials.googleapis.com/v1/locations/global/workforcePools/%s/allowedLocations" ) var ( - workforceAudiencePattern = regexp.MustCompile(`//iam\.([^/]+)/locations/global/workforcePools/([^/]+)`) - workloadAudiencePattern = regexp.MustCompile(`//iam\.([^/]+)/projects/([^/]+)/locations/global/workloadIdentityPools/([^/]+)`) + workforceAudiencePattern = regexp.MustCompile(`^//iam\.([^/]+)/locations/([^/]+)/workforcePools/([^/]+)/providers/[^/]+$`) + workloadAudiencePattern = regexp.MustCompile(`^//iam\.([^/]+)/projects/([^/]+)/locations/([^/]+)/workloadIdentityPools/([^/]+)/providers/[^/]+$`) ) // NewExternalAccountConfigProvider creates a new ConfigProvider for external accounts. @@ -36,19 +36,19 @@ func NewExternalAccountConfigProvider(audience, inputUniverseDomain string) (Con var isWorkload bool matches := workloadAudiencePattern.FindStringSubmatch(audience) - if len(matches) == 4 { // Expecting full match, domain, projectNumber, poolID + if len(matches) == 5 { // Expecting full match, domain, projectNumber, location, poolID audienceDomain = matches[1] projectNumber = matches[2] - poolID = matches[3] + poolID = matches[4] isWorkload = true } else { matches = workforceAudiencePattern.FindStringSubmatch(audience) - if len(matches) == 3 { // Expecting full match, domain, poolID + if len(matches) == 4 { // Expecting full match, domain, location, poolID audienceDomain = matches[1] - poolID = matches[2] + poolID = matches[3] isWorkload = false } else { - return nil, fmt.Errorf("trustboundary: unknown audience format: %q", audience) + return nil, fmt.Errorf("regionalaccessboundary: unknown audience format: %q", audience) } } @@ -56,7 +56,7 @@ func NewExternalAccountConfigProvider(audience, inputUniverseDomain string) (Con 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) + return nil, fmt.Errorf("regionalaccessboundary: provided universe domain (%q) does not match domain in audience (%q)", inputUniverseDomain, audienceDomain) } if isWorkload { @@ -77,8 +77,8 @@ type workforcePoolConfigProvider struct { universeDomain string } -func (p *workforcePoolConfigProvider) GetTrustBoundaryEndpoint(ctx context.Context) (string, error) { - return fmt.Sprintf(workforceAllowedLocationsEndpoint, p.universeDomain, p.poolID), nil +func (p *workforcePoolConfigProvider) GetRegionalAccessBoundaryEndpoint(ctx context.Context) (string, error) { + return fmt.Sprintf(workforceAllowedLocationsEndpoint, p.poolID), nil } func (p *workforcePoolConfigProvider) GetUniverseDomain(ctx context.Context) (string, error) { @@ -91,8 +91,8 @@ type workloadIdentityPoolConfigProvider struct { 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) GetRegionalAccessBoundaryEndpoint(ctx context.Context) (string, error) { + return fmt.Sprintf(workloadAllowedLocationsEndpoint, p.projectNumber, p.poolID), nil } func (p *workloadIdentityPoolConfigProvider) GetUniverseDomain(ctx context.Context) (string, error) { diff --git a/vendor/cloud.google.com/go/auth/internal/regionalaccessboundary/regional_access_boundary.go b/vendor/cloud.google.com/go/auth/internal/regionalaccessboundary/regional_access_boundary.go new file mode 100644 index 0000000000..a94d25ee03 --- /dev/null +++ b/vendor/cloud.google.com/go/auth/internal/regionalaccessboundary/regional_access_boundary.go @@ -0,0 +1,503 @@ +// Copyright 2026 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 regionalaccessboundary + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "io" + "log/slog" + "maps" + "math/rand" + "net" + "net/http" + "net/url" + "os" + "strings" + "sync" + "time" + + "cloud.google.com/go/auth" + "cloud.google.com/go/auth/internal" + "cloud.google.com/go/auth/internal/retry" + "github.com/googleapis/gax-go/v2/internallog" +) + +// ProviderKey is the key to fetch the DataProvider from Token Metadata. +const ProviderKey = "regionalaccessboundary.ProviderKey" + +const ( + // serviceAccountAllowedLocationsEndpoint is the URL for fetching allowed locations for a given service account email. + serviceAccountAllowedLocationsEndpoint = "https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/%s/allowedLocations" + + // cacheTTL is the duration cached RAB data remains valid before hard expiry. + cacheTTL = 6 * time.Hour + // cacheSoftExpiry is the threshold before hard expiry where a background refresh is triggered. + cacheSoftExpiry = 1 * time.Hour + // baseCooldownDuration is the initial delay after a failed background fetch. + baseCooldownDuration = 15 * time.Minute +) + +var ( + // retryOptions configures the retry behavior for Regional Access Boundary lookups. + retryOptions = &retry.Options{ + Initial: 1 * time.Second, + Max: 60 * time.Second, + Multiplier: 2.0, + MaxAttempts: 6, + } +) + +// isEnabled wraps isRegionalAccessBoundaryEnabled with sync.OnceValues to ensure it's +// called only once. +var isEnabled = sync.OnceValues(isRegionalAccessBoundaryEnabled) + +// IsEnabled returns if the Regional Access 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() +} + +// isRegionalAccessBoundaryEnabled checks if the Regional Access Boundary feature +// is enabled via the GOOGLE_AUTH_TRUST_BOUNDARY_ENABLED environment variable. +// +// If the environment variable is not set or empty, it is considered false. +// +// The environment variable is interpreted as a boolean with the following +// (case-insensitive) rules: +// - "true", "1" are considered true. +// - All other values (including "false", "0", or invalid strings) are considered false. +func isRegionalAccessBoundaryEnabled() (bool, error) { + val := strings.ToLower(os.Getenv("GOOGLE_AUTH_TRUST_BOUNDARY_ENABLED")) + return val == "true" || val == "1", nil +} + +// ConfigProvider provides specific configuration for Regional Access Boundary lookups. +type ConfigProvider interface { + // GetRegionalAccessBoundaryEndpoint returns the endpoint URL for the Regional Access Boundary lookup. + GetRegionalAccessBoundaryEndpoint(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 Regional Access 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"` +} + +// fetchRegionalAccessBoundaryData fetches the Regional Access Boundary data from the API. +func fetchRegionalAccessBoundaryData(ctx context.Context, client *http.Client, url string, token *auth.Token, logger *slog.Logger) (*internal.RegionalAccessBoundaryData, error) { + if logger == nil { + logger = slog.New(slog.NewTextHandler(io.Discard, nil)) + } + if client == nil { + return nil, errors.New("regionalaccessboundary: HTTP client is required") + } + + if url == "" { + return nil, errors.New("regionalaccessboundary: URL cannot be empty") + } + + req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil) + if err != nil { + return nil, fmt.Errorf("regionalaccessboundary: failed to create Regional Access Boundary request: %w", err) + } + + if token == nil || token.Value == "" { + return nil, errors.New("regionalaccessboundary: access token required for lookup API authentication") + } + typ := token.Type + if typ == "" { + typ = internal.TokenTypeBearer + } + req.Header.Set("Authorization", typ+" "+token.Value) + logger.DebugContext(ctx, "Regional Access Boundary request", "request", internallog.HTTPRequest(req, nil)) + + retryer := retry.NewWithOptions(retryOptions) + startTime := time.Now() + 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) + + // Enforce a maximum 1 minute retry window for specific server errors. + if shouldRetry && (statusCode == 500 || statusCode == 502 || statusCode == 503 || statusCode == 504) { + if time.Since(startTime)+pause > 1*time.Minute { + shouldRetry = false + } + } + + 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("regionalaccessboundary: failed to fetch Regional Access Boundary: %w", err) + } + defer response.Body.Close() + + body, err := io.ReadAll(response.Body) + if err != nil { + return nil, fmt.Errorf("regionalaccessboundary: failed to read Regional Access Boundary response: %w", err) + } + + logger.DebugContext(ctx, "Regional Access Boundary response", "response", internallog.HTTPResponse(response, body)) + + if response.StatusCode != http.StatusOK { + return nil, fmt.Errorf("regionalaccessboundary: Regional Access 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("regionalaccessboundary: failed to unmarshal Regional Access Boundary response: %w", err) + } + + if apiResponse.EncodedLocations == "" { + return nil, errors.New("regionalaccessboundary: invalid API response: encodedLocations is empty") + } + + return internal.NewRegionalAccessBoundaryData(apiResponse.Locations, apiResponse.EncodedLocations), nil +} + +// DataProvider fetches and caches Regional Access Boundary Data. +// It implements the auth.TokenProvider interface and uses a ConfigProvider +// to get type-specific details for the lookup. +type DataProvider struct { + client *http.Client + configProvider ConfigProvider + logger *slog.Logger + base auth.TokenProvider + + mu sync.RWMutex + data *internal.RegionalAccessBoundaryData + dataExpiry time.Time + isFetching bool + cooldownExpiry time.Time + cooldownDuration time.Duration // tracks the current cooldown duration for exponential backoff +} + +// NewProvider wraps the provided base [auth.TokenProvider] and returns a new +// provider that fetches and caches the Regional Access Boundary data. It uses +// the provided HTTP client and configProvider. +func NewProvider(client *http.Client, configProvider ConfigProvider, logger *slog.Logger, base auth.TokenProvider) (*DataProvider, error) { + if client == nil { + return nil, errors.New("regionalaccessboundary: HTTP client cannot be nil for DataProvider") + } + if configProvider == nil { + return nil, errors.New("regionalaccessboundary: ConfigProvider cannot be nil for DataProvider") + } + p := &DataProvider{ + client: client, + configProvider: configProvider, + logger: internallog.New(logger), + base: base, + cooldownDuration: 15 * time.Minute, + } + return p, nil +} + +// Token retrieves a token from the base provider and injects the DataProvider +// instance into its metadata. +func (p *DataProvider) Token(ctx context.Context) (*auth.Token, error) { + token, err := p.base.Token(ctx) + if err != nil { + return nil, err + } + + // Clone the token and its metadata to avoid mutating shared/cached state. + newToken := *token + newToken.Metadata = maps.Clone(token.Metadata) + if newToken.Metadata == nil { + newToken.Metadata = make(map[string]interface{}) + } + newToken.Metadata[ProviderKey] = p + + return &newToken, nil +} + +// GetHeaderValue immediately returns a valid header if it's cached, or kicks off a background fetch +// if it is unpopulated or expired. +func (p *DataProvider) GetHeaderValue(ctx context.Context, reqURL string, accessToken *auth.Token) string { + if !strings.Contains(reqURL, "://") { + reqURL = "https://" + reqURL + } + if u, err := url.Parse(reqURL); err == nil { + host := u.Host + if host == "" && strings.HasPrefix(u.Path, "/") { + host = strings.TrimPrefix(u.Path, "/") + } + if h, _, err := net.SplitHostPort(host); err == nil { + host = h + } + // Skip lookup for regional endpoints. + if host == "rep.googleapis.com" || strings.HasSuffix(host, ".rep.googleapis.com") || + host == "rep.sandbox.googleapis.com" || strings.HasSuffix(host, ".rep.sandbox.googleapis.com") { + return "" + } + // Skip lookup for IAM and STS endpoints as they do not require RAB headers. + if host == "iam.googleapis.com" || host == "iamcredentials.googleapis.com" || + host == "sts.googleapis.com" { + return "" + } + } + + // Skip lookup for non-default universe domains. + uniDomain, err := p.configProvider.GetUniverseDomain(ctx) + if err != nil { + p.logger.WarnContext(ctx, "regionalaccessboundary: error getting universe domain", "error", err) + return "" + } + if uniDomain != "" && uniDomain != internal.DefaultUniverseDomain { + return "" + } + + // Return the cached data if present and not expired. + p.mu.RLock() + data := p.data + dataExpiry := p.dataExpiry + p.mu.RUnlock() + + now := time.Now() + if data != nil && now.Before(dataExpiry) { + val, _ := data.RegionalAccessBoundaryHeader() + + // Soft Expiry: if the cached data is within the soft expiration window, + // initiate a non-blocking background refresh to proactively fetch new data + // while continuing to serve the current valid cache block. + if now.After(dataExpiry.Add(-cacheSoftExpiry)) { + p.mu.Lock() + if !p.isFetching && now.After(p.cooldownExpiry) { + p.isFetching = true + go p.fetchAsync(context.Background(), accessToken) + } + p.mu.Unlock() + } + + return val + } + + p.mu.Lock() + defer p.mu.Unlock() + + // Skip lookup if in cooldown or another process is already fetching. + if p.isFetching || time.Now().Before(p.cooldownExpiry) { + return "" + } + + // Start async RAB lookup and return empty header. + p.isFetching = true + go p.fetchAsync(context.Background(), accessToken) + return "" +} + +// fetchAsync performs the background lookup for Regional Access Boundary data. +// It updates the provider's state based on the result (success or failure). +func (p *DataProvider) fetchAsync(ctx context.Context, accessToken *auth.Token) { + defer func() { + p.mu.Lock() + p.isFetching = false + p.mu.Unlock() + }() + + url, err := p.configProvider.GetRegionalAccessBoundaryEndpoint(ctx) + if err != nil { + p.logger.WarnContext(ctx, "regionalaccessboundary: error getting the lookup endpoint", "error", err) + p.handleFetchFailure(ctx) + return + } + + newData, fetchErr := fetchRegionalAccessBoundaryData(ctx, p.client, url, accessToken, p.logger) + + if fetchErr != nil { + p.logger.WarnContext(ctx, "regionalaccessboundary: async fetch failed", "error", fetchErr) + p.handleFetchFailure(ctx) + return + } + + p.handleFetchSuccess(newData) +} + +// handleFetchSuccess updates the cache with new data and clears any existing cooldown. +func (p *DataProvider) handleFetchSuccess(newData *internal.RegionalAccessBoundaryData) { + p.mu.Lock() + defer p.mu.Unlock() + p.data = newData + p.dataExpiry = time.Now().Add(cacheTTL) + p.cooldownExpiry = time.Time{} + p.cooldownDuration = baseCooldownDuration +} + +// handleFetchFailure triggers the cooldown period using exponential backoff. +func (p *DataProvider) handleFetchFailure(ctx context.Context) { + p.mu.Lock() + defer p.mu.Unlock() + + // Add random bounded jitter (between half of the base and the full base) to prevent thundering herds + jitter := p.cooldownDuration/2 + time.Duration(rand.Int63n(int64(p.cooldownDuration/2))) + p.cooldownExpiry = time.Now().Add(jitter) + + // Exponential backoff for the NEXT attempt, up to cacheTTL max (6 hours) + nextCooldown := p.cooldownDuration * 2 + if nextCooldown > cacheTTL { + nextCooldown = cacheTTL + } + p.cooldownDuration = nextCooldown +} + +// serviceAccountConfig holds configuration for SA Regional Access 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, + } +} + +// GetRegionalAccessBoundaryEndpoint returns the formatted URL for fetching allowed locations +// for the configured service account. +func (sac *serviceAccountConfig) GetRegionalAccessBoundaryEndpoint(ctx context.Context) (url string, err error) { + if sac.ServiceAccountEmail == "" { + return "", errors.New("regionalaccessboundary: service account email cannot be empty for config") + } + return fmt.Sprintf(serviceAccountAllowedLocationsEndpoint, 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 +} + +// GCEConfigProvider implements ConfigProvider for GCE environments. +// It lazily fetches and caches the necessary metadata (service account email, universe domain) +type GCEConfigProvider struct { + // universeDomainProvider provides the universe domain and underlying metadata client. + universeDomainProvider *internal.ComputeUniverseDomainProvider + + // Caching for service account email + saMu sync.Mutex + saEmail string + + // 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 GetRegionalAccessBoundaryEndpoint and GetUniverseDomain methods. + return &GCEConfigProvider{ + universeDomainProvider: gceUDP, + } +} + +func (g *GCEConfigProvider) fetchSA(ctx context.Context) (string, error) { + if g.universeDomainProvider == nil || g.universeDomainProvider.MetadataClient == nil { + return "", errors.New("regionalaccessboundary: GCEConfigProvider not properly initialized (missing ComputeUniverseDomainProvider or MetadataClient)") + } + mdClient := g.universeDomainProvider.MetadataClient + saEmail, err := mdClient.EmailWithContext(ctx, "default") + if err != nil { + return "", fmt.Errorf("regionalaccessboundary: GCE config: failed to get service account email: %w", err) + } + return saEmail, nil +} + +func (g *GCEConfigProvider) fetchUD(ctx context.Context) { + if g.universeDomainProvider == nil || g.universeDomainProvider.MetadataClient == nil { + g.udErr = errors.New("regionalaccessboundary: GCEConfigProvider not properly initialized (missing ComputeUniverseDomainProvider or MetadataClient)") + return + } + ud, err := g.universeDomainProvider.GetProperty(ctx) + if err != nil { + g.udErr = fmt.Errorf("regionalaccessboundary: GCE config: failed to get universe domain: %w", err) + return + } + if ud == "" { + ud = internal.DefaultUniverseDomain + } + g.ud = ud +} + +// GetRegionalAccessBoundaryEndpoint constructs the Regional Access Boundary lookup URL for a GCE environment. +// It uses cached service account email after the first call. +func (g *GCEConfigProvider) GetRegionalAccessBoundaryEndpoint(ctx context.Context) (string, error) { + // Check if we already have a cached service account email. + g.saMu.Lock() + if g.saEmail != "" { + email := g.saEmail + g.saMu.Unlock() + return fmt.Sprintf(serviceAccountAllowedLocationsEndpoint, email), nil + } + g.saMu.Unlock() + + // Fetch the email from the metadata server. We do not hold the lock + // during this I/O operation to avoid blocking other goroutines. + email, err := g.fetchSA(ctx) + if err != nil { + return "", err + } + + // Cache the successful result. + g.saMu.Lock() + g.saEmail = email + g.saMu.Unlock() + + return fmt.Sprintf(serviceAccountAllowedLocationsEndpoint, email), 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 +} diff --git a/vendor/cloud.google.com/go/auth/internal/retry/retry.go b/vendor/cloud.google.com/go/auth/internal/retry/retry.go index 276cc4a3e2..7cbd06a763 100644 --- a/vendor/cloud.google.com/go/auth/internal/retry/retry.go +++ b/vendor/cloud.google.com/go/auth/internal/retry/retry.go @@ -22,10 +22,6 @@ import ( "time" ) -const ( - maxRetryAttempts = 5 -) - var ( syscallRetryable = func(error) bool { return false } ) @@ -61,21 +57,69 @@ func Sleep(ctx context.Context, d time.Duration) error { // 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, - }} + return NewWithOptions(&Options{ + Initial: 100 * time.Millisecond, + Max: 30 * time.Second, + Multiplier: 2, + MaxAttempts: 5, + }) +} + +// Options defines the configuration for the Retryer. +type Options struct { + // Initial is the initial backoff duration. + Initial time.Duration + // Max is the maximum backoff duration for a single retry attempt. + // It does not limit the total time of all retries. + Max time.Duration + // Multiplier is the factor by which the backoff duration is multiplied after each attempt. + Multiplier float64 + // MaxAttempts is the maximum number of attempts before giving up. + MaxAttempts int +} + +// NewWithOptions returns a new Retryer with the specified backoff strategy. +// If any option is not set (zero value), it defaults to the values used in New(). +func NewWithOptions(opts *Options) *Retryer { + initial := opts.Initial + if initial <= 0 { + initial = 100 * time.Millisecond + } + + max := opts.Max + if max <= 0 { + max = 30 * time.Second + } + + multiplier := opts.Multiplier + if multiplier < 1.0 { + multiplier = 2.0 + } + + maxAttempts := opts.MaxAttempts + if maxAttempts <= 0 { + maxAttempts = 5 + } + + return &Retryer{ + bo: &defaultBackoff{ + cur: initial, + max: max, + mul: multiplier, + }, + maxAttempts: maxAttempts, + } } type backoff interface { Pause() time.Duration } -// Retryer is a retryer for HTTP requests. +// Retryer handles retry logic for HTTP requests using a configurable backoff strategy. type Retryer struct { - bo backoff - attempts int + bo backoff + attempts int + maxAttempts int } // Retry determines if a request should be retried. @@ -87,7 +131,7 @@ func (r *Retryer) Retry(status int, err error) (time.Duration, bool) { if !retryOk { return 0, false } - if r.attempts == maxRetryAttempts { + if r.attempts == r.maxAttempts { return 0, false } r.attempts++ diff --git a/vendor/cloud.google.com/go/auth/internal/retry/retry_linux.go b/vendor/cloud.google.com/go/auth/internal/retry/retry_linux.go new file mode 100644 index 0000000000..8f0a78c577 --- /dev/null +++ b/vendor/cloud.google.com/go/auth/internal/retry/retry_linux.go @@ -0,0 +1,31 @@ +// Copyright 2026 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. + +//go:build linux +// +build linux + +package retry + +import ( + "errors" + "syscall" +) + +func init() { + // Initialize syscallRetryable to return true on transient socket-level + // errors. These errors are specific to Linux. + syscallRetryable = func(err error) bool { + return errors.Is(err, syscall.ECONNRESET) || errors.Is(err, syscall.ECONNREFUSED) + } +} diff --git a/vendor/cloud.google.com/go/auth/internal/transport/headers/headers.go b/vendor/cloud.google.com/go/auth/internal/transport/headers/headers.go index 5483a763c4..01c06e272a 100644 --- a/vendor/cloud.google.com/go/auth/internal/transport/headers/headers.go +++ b/vendor/cloud.google.com/go/auth/internal/transport/headers/headers.go @@ -15,14 +15,20 @@ package headers import ( + "context" "net/http" "cloud.google.com/go/auth" "cloud.google.com/go/auth/internal" + "cloud.google.com/go/auth/internal/regionalaccessboundary" ) -// 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 +type regionalAccessBoundaryProvider interface { + GetHeaderValue(ctx context.Context, reqURL string, token *auth.Token) string +} + +// SetAuthHeader uses the provided token to set the Authorization and regional +// access 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 @@ -31,31 +37,26 @@ func SetAuthHeader(token *auth.Token, req *http.Request) { } req.Header.Set("Authorization", typ+" "+token.Value) - if headerVal, setHeader := getTrustBoundaryHeader(token); setHeader { - req.Header.Set("x-allowed-locations", headerVal) + if provider, ok := token.Metadata[regionalaccessboundary.ProviderKey].(regionalAccessBoundaryProvider); ok { + if headerVal := provider.GetHeaderValue(req.Context(), req.URL.String(), token); headerVal != "" { + 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 +// SetAuthMetadata uses the provided token to set the Authorization and regional +// access boundary metadata. If the token.Type is empty, the type is assumed to be // Bearer. -func SetAuthMetadata(token *auth.Token, m map[string]string) { +func SetAuthMetadata(ctx context.Context, token *auth.Token, reqURL string, 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() + if provider, ok := token.Metadata[regionalaccessboundary.ProviderKey].(regionalAccessBoundaryProvider); ok { + if headerVal := provider.GetHeaderValue(ctx, reqURL, token); headerVal != "" { + m["x-allowed-locations"] = headerVal } } - return "", false } diff --git a/vendor/cloud.google.com/go/auth/internal/trustboundary/trust_boundary.go b/vendor/cloud.google.com/go/auth/internal/trustboundary/trust_boundary.go deleted file mode 100644 index bf898fffd6..0000000000 --- a/vendor/cloud.google.com/go/auth/internal/trustboundary/trust_boundary.go +++ /dev/null @@ -1,392 +0,0 @@ -// 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 -} diff --git a/vendor/cloud.google.com/go/auth/internal/version.go b/vendor/cloud.google.com/go/auth/internal/version.go index d627069b57..3ece8f50f1 100644 --- a/vendor/cloud.google.com/go/auth/internal/version.go +++ b/vendor/cloud.google.com/go/auth/internal/version.go @@ -17,4 +17,4 @@ package internal // Version is the current tagged release of the library. -const Version = "0.20.0" +const Version = "0.21.0" diff --git a/vendor/github.com/googleapis/gax-go/v2/.release-please-manifest.json b/vendor/github.com/googleapis/gax-go/v2/.release-please-manifest.json index 2fcff6e273..90b5af3c47 100644 --- a/vendor/github.com/googleapis/gax-go/v2/.release-please-manifest.json +++ b/vendor/github.com/googleapis/gax-go/v2/.release-please-manifest.json @@ -1,3 +1,3 @@ { - "v2": "2.15.0" + "v2": "2.23.0" } diff --git a/vendor/github.com/googleapis/gax-go/v2/CHANGES.md b/vendor/github.com/googleapis/gax-go/v2/CHANGES.md index ed27c5ee71..d7559b7532 100644 --- a/vendor/github.com/googleapis/gax-go/v2/CHANGES.md +++ b/vendor/github.com/googleapis/gax-go/v2/CHANGES.md @@ -1,5 +1,17 @@ # Changes +## [2.23.0](https://github.com/googleapis/gax-go/compare/v2.22.0...v2.23.0) (2026-07-07) + + +### Features + +* **v2:** add http.response.status_code to TransportTelemetryData ([#513](https://github.com/googleapis/gax-go/issues/513)) ([7d5554f](https://github.com/googleapis/gax-go/commit/7d5554f433f669fba3db5c5b64ed67a30813c568)) + + +### Bug Fixes + +* correct min go version ([#517](https://github.com/googleapis/gax-go/issues/517)) ([fc62896](https://github.com/googleapis/gax-go/commit/fc62896b04d04db85c48585b9311ec4bbee1d9bc)) + ## [2.22.0](https://github.com/googleapis/google-cloud-go/releases/tag/v2.22.0) (2026-04-14) ## [2.21.0](https://github.com/googleapis/google-cloud-go/releases/tag/v2.21.0) (2026-04-01) diff --git a/vendor/github.com/googleapis/gax-go/v2/internal/version.go b/vendor/github.com/googleapis/gax-go/v2/internal/version.go index f324d1ab82..d35188c502 100644 --- a/vendor/github.com/googleapis/gax-go/v2/internal/version.go +++ b/vendor/github.com/googleapis/gax-go/v2/internal/version.go @@ -17,4 +17,4 @@ package internal // Version is the current tagged release of the library. -const Version = "2.22.0" +const Version = "2.23.0" diff --git a/vendor/github.com/googleapis/gax-go/v2/release-please-config.json b/vendor/github.com/googleapis/gax-go/v2/release-please-config.json index 61ee266a15..80724af03f 100644 --- a/vendor/github.com/googleapis/gax-go/v2/release-please-config.json +++ b/vendor/github.com/googleapis/gax-go/v2/release-please-config.json @@ -1,5 +1,5 @@ { - "release-type": "go-yoshi", + "release-type": "go-librarian", "separate-pull-requests": true, "include-component-in-tag": false, "packages": { diff --git a/vendor/github.com/googleapis/gax-go/v2/telemetry.go b/vendor/github.com/googleapis/gax-go/v2/telemetry.go index b849b36919..2490c3690e 100644 --- a/vendor/github.com/googleapis/gax-go/v2/telemetry.go +++ b/vendor/github.com/googleapis/gax-go/v2/telemetry.go @@ -54,8 +54,9 @@ import ( // regardless of any other documented package stability guarantees. // It should not be used by external consumers. type TransportTelemetryData struct { - serverAddress string - serverPort int + serverAddress string + serverPort int + httpStatusCode int } // SetServerAddress sets the server address. @@ -78,6 +79,16 @@ func (d *TransportTelemetryData) SetServerPort(port int) { d.serverPort = port } // regardless of any other documented package stability guarantees. func (d *TransportTelemetryData) ServerPort() int { return d.serverPort } +// SetHTTPStatusCode sets the HTTP status code. +// Experimental: This function is experimental and may be modified or removed in future versions, +// regardless of any other documented package stability guarantees. +func (d *TransportTelemetryData) SetHTTPStatusCode(code int) { d.httpStatusCode = code } + +// HTTPStatusCode returns the HTTP status code. +// Experimental: This function is experimental and may be modified or removed in future versions, +// regardless of any other documented package stability guarantees. +func (d *TransportTelemetryData) HTTPStatusCode() int { return d.httpStatusCode } + // transportTelemetryKey is the private context key used to inject TransportTelemetryData type transportTelemetryKey struct{} @@ -450,6 +461,9 @@ func recordMetric(ctx context.Context, settings CallSettings, d time.Duration, e if td.ServerPort() != 0 { attrs = append(attrs, attribute.Int("server.port", td.ServerPort())) } + if td.HTTPStatusCode() != 0 { + attrs = append(attrs, attribute.Int("http.response.status_code", td.HTTPStatusCode())) + } } if errInfo.ErrorType != "" { diff --git a/vendor/google.golang.org/api/internal/version.go b/vendor/google.golang.org/api/internal/version.go index a91cdbad05..146ea7c16f 100644 --- a/vendor/google.golang.org/api/internal/version.go +++ b/vendor/google.golang.org/api/internal/version.go @@ -5,4 +5,4 @@ package internal // Version is the current tagged release of the library. -const Version = "0.286.0" +const Version = "0.287.1" diff --git a/vendor/google.golang.org/grpc/balancer/balancer.go b/vendor/google.golang.org/grpc/balancer/balancer.go index 326888ae35..7e3dbaad26 100644 --- a/vendor/google.golang.org/grpc/balancer/balancer.go +++ b/vendor/google.golang.org/grpc/balancer/balancer.go @@ -60,7 +60,7 @@ func Register(b Builder) { if !envconfig.CaseSensitiveBalancerRegistries { name = strings.ToLower(name) if name != b.Name() { - logger.Warningf("Balancer registered with name %q. grpc-go will be switching to case sensitive balancer registries soon. After 2 releases, we will enable the env var by default.", b.Name()) + logger.Warningf("Balancer registered with name %q. grpc-go has switched to case sensitive balancer registries. GRPC_GO_EXPERIMENTAL_CASE_SENSITIVE_BALANCER_REGISTRIES env variable will be removed in release v1.82.0", b.Name()) } } m[name] = b @@ -85,7 +85,7 @@ func Get(name string) Builder { if !envconfig.CaseSensitiveBalancerRegistries { lowerName := strings.ToLower(name) if lowerName != name { - logger.Warningf("Balancer retrieved for name %q. grpc-go will be switching to case sensitive balancer registries soon. After 2 releases, we will enable the env var by default.", name) + logger.Warningf("Balancer retrieved for name %q. grpc-go has switched to case sensitive balancer registries. GRPC_GO_EXPERIMENTAL_CASE_SENSITIVE_BALANCER_REGISTRIES env variable will be removed in release v1.82.0", name) } name = lowerName } diff --git a/vendor/google.golang.org/grpc/balancer/grpclb/grpc_lb_v1/load_balancer_grpc.pb.go b/vendor/google.golang.org/grpc/balancer/grpclb/grpc_lb_v1/load_balancer_grpc.pb.go index 942b7e9676..6aeb81981a 100644 --- a/vendor/google.golang.org/grpc/balancer/grpclb/grpc_lb_v1/load_balancer_grpc.pb.go +++ b/vendor/google.golang.org/grpc/balancer/grpclb/grpc_lb_v1/load_balancer_grpc.pb.go @@ -19,7 +19,7 @@ // Code generated by protoc-gen-go-grpc. DO NOT EDIT. // versions: -// - protoc-gen-go-grpc v1.6.1 +// - protoc-gen-go-grpc v1.6.2 // - protoc v5.27.1 // source: grpc/lb/v1/load_balancer.proto diff --git a/vendor/google.golang.org/grpc/balancer/pickfirst/pickfirst.go b/vendor/google.golang.org/grpc/balancer/pickfirst/pickfirst.go index 518a69d573..d48bc304c2 100644 --- a/vendor/google.golang.org/grpc/balancer/pickfirst/pickfirst.go +++ b/vendor/google.golang.org/grpc/balancer/pickfirst/pickfirst.go @@ -35,9 +35,9 @@ import ( "google.golang.org/grpc/balancer" "google.golang.org/grpc/balancer/pickfirst/internal" "google.golang.org/grpc/connectivity" + "google.golang.org/grpc/experimental/balancer/weight" expstats "google.golang.org/grpc/experimental/stats" "google.golang.org/grpc/grpclog" - "google.golang.org/grpc/internal/balancer/weight" "google.golang.org/grpc/internal/envconfig" internalgrpclog "google.golang.org/grpc/internal/grpclog" "google.golang.org/grpc/internal/pretty" diff --git a/vendor/google.golang.org/grpc/credentials/alts/alts.go b/vendor/google.golang.org/grpc/credentials/alts/alts.go index 35539eb1ad..b8afa917ce 100644 --- a/vendor/google.golang.org/grpc/credentials/alts/alts.go +++ b/vendor/google.golang.org/grpc/credentials/alts/alts.go @@ -181,16 +181,9 @@ func (g *altsTC) ClientHandshake(ctx context.Context, addr string, rawConn net.C } // Do not close hsConn since it is shared with other handshakes. - // Possible context leak: - // The cancel function for the child context we create will only be - // called a non-nil error is returned. var cancel context.CancelFunc ctx, cancel = context.WithCancel(ctx) - defer func() { - if err != nil { - cancel() - } - }() + defer cancel() opts := handshaker.DefaultClientHandshakerOptions() opts.TargetName = addr @@ -204,11 +197,8 @@ func (g *altsTC) ClientHandshake(ctx context.Context, addr string, rawConn net.C if err != nil { return nil, nil, err } - defer func() { - if err != nil { - chs.Close() - } - }() + // Close the handshaker since we have obtained a connection. + defer chs.Close() secConn, authInfo, err := chs.ClientHandshake(ctx) if err != nil { return nil, nil, err @@ -247,15 +237,12 @@ func (g *altsTC) ServerHandshake(rawConn net.Conn) (_ net.Conn, _ credentials.Au if err != nil { return nil, nil, err } - defer func() { - if err != nil { - shs.Close() - } - }() secConn, authInfo, err := shs.ServerHandshake(ctx) if err != nil { return nil, nil, err } + // Close the handshaker since we have obtained a connection. + defer shs.Close() altsAuthInfo, ok := authInfo.(AuthInfo) if !ok { return nil, nil, errors.New("server-side auth info is not of type alts.AuthInfo") diff --git a/vendor/google.golang.org/grpc/credentials/alts/internal/proto/grpc_gcp/handshaker_grpc.pb.go b/vendor/google.golang.org/grpc/credentials/alts/internal/proto/grpc_gcp/handshaker_grpc.pb.go index 2dee74f16f..96a40fc359 100644 --- a/vendor/google.golang.org/grpc/credentials/alts/internal/proto/grpc_gcp/handshaker_grpc.pb.go +++ b/vendor/google.golang.org/grpc/credentials/alts/internal/proto/grpc_gcp/handshaker_grpc.pb.go @@ -17,7 +17,7 @@ // Code generated by protoc-gen-go-grpc. DO NOT EDIT. // versions: -// - protoc-gen-go-grpc v1.6.1 +// - protoc-gen-go-grpc v1.6.2 // - protoc v5.27.1 // source: grpc/gcp/handshaker.proto diff --git a/vendor/google.golang.org/grpc/dialoptions.go b/vendor/google.golang.org/grpc/dialoptions.go index 4ec5f9cd09..3af08e1ab9 100644 --- a/vendor/google.golang.org/grpc/dialoptions.go +++ b/vendor/google.golang.org/grpc/dialoptions.go @@ -173,10 +173,8 @@ func newJoinDialOption(opts ...DialOption) DialOption { // If this option is set to true every connection will release the buffer after // flushing the data on the wire. // -// # Experimental -// -// Notice: This API is EXPERIMENTAL and may be changed or removed in a -// later release. +// Deprecated: shared write buffer is enabled by default. WithSharedWriteBuffer +// will be removed in a future release. func WithSharedWriteBuffer(val bool) DialOption { return newFuncDialOption(func(o *dialOptions) { o.copts.SharedWriteBuffer = val @@ -229,6 +227,14 @@ func WithInitialConnWindowSize(s int32) DialOption { // WithStaticStreamWindowSize returns a DialOption which sets the initial // stream window size to the value provided and disables dynamic flow control. +// +// Note that this also disables dynamic flow control for the connection, +// falling back to a default static connection-level window of 64KB. To +// use a larger connection-level window, you must also use the +// [WithStaticConnWindowSize] DialOption. +// +// Most users should not configure static flow control windows unless +// operating in a memory-constrained environment. func WithStaticStreamWindowSize(s int32) DialOption { return newFuncDialOption(func(o *dialOptions) { o.copts.InitialWindowSize = s @@ -239,6 +245,14 @@ func WithStaticStreamWindowSize(s int32) DialOption { // WithStaticConnWindowSize returns a DialOption which sets the initial // connection window size to the value provided and disables dynamic flow // control. +// +// Note that this also disables dynamic flow control for individual streams, +// falling back to a default static connection-level window of 64KB. To +// explicitly configure the stream-level window size, you must also use the +// [WithStaticStreamWindowSize] DialOption. +// +// Most users should not configure static flow control windows unless +// operating in a memory-constrained environment. func WithStaticConnWindowSize(s int32) DialOption { return newFuncDialOption(func(o *dialOptions) { o.copts.InitialConnWindowSize = s diff --git a/vendor/google.golang.org/grpc/encoding/encoding.go b/vendor/google.golang.org/grpc/encoding/encoding.go index 296f38c3a8..bfa8b268fe 100644 --- a/vendor/google.golang.org/grpc/encoding/encoding.go +++ b/vendor/google.golang.org/grpc/encoding/encoding.go @@ -66,6 +66,9 @@ type Compressor interface { // Decompress reads data from r, decompresses it, and provides the // uncompressed data via the returned io.Reader. If an error occurs while // initializing the decompressor, that error is returned instead. + // + // The returned io.Reader may optionally implement io.ReadCloser, and if it + // does, gRPC will call Close() exactly once. Decompress(r io.Reader) (io.Reader, error) // Name is the name of the compression codec and is used to set the content // coding header. The result must be static; the result cannot change diff --git a/vendor/google.golang.org/grpc/encoding/gzip/gzip.go b/vendor/google.golang.org/grpc/encoding/gzip/gzip.go index 153e4dbfbf..65908d9a2c 100644 --- a/vendor/google.golang.org/grpc/encoding/gzip/gzip.go +++ b/vendor/google.golang.org/grpc/encoding/gzip/gzip.go @@ -81,6 +81,8 @@ func (z *writer) Close() error { return z.Writer.Close() } +var _ io.Closer = &reader{} + type reader struct { *gzip.Reader pool *sync.Pool @@ -102,14 +104,16 @@ func (c *compressor) Decompress(r io.Reader) (io.Reader, error) { return z, nil } -func (z *reader) Read(p []byte) (n int, err error) { - n, err = z.Reader.Read(p) - if err == io.EOF { - z.pool.Put(z) - } +func (r *reader) Read(p []byte) (n int, err error) { + n, err = r.Reader.Read(p) return n, err } +func (r *reader) Close() error { + defer r.pool.Put(r) + return r.Reader.Close() +} + func (c *compressor) Name() string { return Name } diff --git a/vendor/google.golang.org/grpc/internal/balancer/weight/weight.go b/vendor/google.golang.org/grpc/experimental/balancer/weight/weight.go similarity index 71% rename from vendor/google.golang.org/grpc/internal/balancer/weight/weight.go rename to vendor/google.golang.org/grpc/experimental/balancer/weight/weight.go index 11beb07d14..beab9e07c9 100644 --- a/vendor/google.golang.org/grpc/internal/balancer/weight/weight.go +++ b/vendor/google.golang.org/grpc/experimental/balancer/weight/weight.go @@ -16,23 +16,23 @@ * */ -// Package weight contains utilities to manage endpoint weights. Weights are -// used by LB policies such as ringhash to distribute load across multiple -// endpoints. +// Package weight contains utilities to manage endpoint weights. +// Weights may be used by LB policies to distribute load across +// multiple endpoints. +// +// # Experimental +// +// Notice: All APIs in this package are EXPERIMENTAL and may be changed +// or removed in a later release. package weight -import ( - "fmt" - - "google.golang.org/grpc/resolver" -) +import "google.golang.org/grpc/resolver" // attributeKey is the type used as the key to store EndpointInfo in the // Attributes field of resolver.Endpoint. type attributeKey struct{} -// EndpointInfo will be stored in the Attributes field of Endpoints in order to -// use the ringhash balancer. +// EndpointInfo will be stored in the Attributes field of Endpoints. type EndpointInfo struct { Weight uint32 } @@ -43,22 +43,16 @@ func (a EndpointInfo) Equal(o any) bool { return ok && oa.Weight == a.Weight } -// Set returns a copy of endpoint in which the Attributes field is updated with -// EndpointInfo. +// Set returns a copy of endpoint in which the Attributes field is +// updated with EndpointInfo. func Set(endpoint resolver.Endpoint, epInfo EndpointInfo) resolver.Endpoint { endpoint.Attributes = endpoint.Attributes.WithValue(attributeKey{}, epInfo) return endpoint } -// String returns a human-readable representation of EndpointInfo. -// This method is intended for logging, testing, and debugging purposes only. -// Do not rely on the output format, as it is not guaranteed to remain stable. -func (a EndpointInfo) String() string { - return fmt.Sprintf("Weight: %d", a.Weight) -} - -// FromEndpoint returns the EndpointInfo stored in the Attributes field of an -// endpoint. It returns an empty EndpointInfo if attribute is not found. +// FromEndpoint returns the EndpointInfo stored in the Attributes +// field of an endpoint. It returns an empty EndpointInfo if attribute +// is not found. func FromEndpoint(endpoint resolver.Endpoint) EndpointInfo { v := endpoint.Attributes.Value(attributeKey{}) ei, _ := v.(EndpointInfo) diff --git a/vendor/google.golang.org/grpc/health/grpc_health_v1/health_grpc.pb.go b/vendor/google.golang.org/grpc/health/grpc_health_v1/health_grpc.pb.go index 9e10fdd2eb..537ba0571c 100644 --- a/vendor/google.golang.org/grpc/health/grpc_health_v1/health_grpc.pb.go +++ b/vendor/google.golang.org/grpc/health/grpc_health_v1/health_grpc.pb.go @@ -17,7 +17,7 @@ // Code generated by protoc-gen-go-grpc. DO NOT EDIT. // versions: -// - protoc-gen-go-grpc v1.6.1 +// - protoc-gen-go-grpc v1.6.2 // - protoc v5.27.1 // source: grpc/health/v1/health.proto diff --git a/vendor/google.golang.org/grpc/internal/envconfig/envconfig.go b/vendor/google.golang.org/grpc/internal/envconfig/envconfig.go index 8ca87a57a2..ba05b65d5b 100644 --- a/vendor/google.golang.org/grpc/internal/envconfig/envconfig.go +++ b/vendor/google.golang.org/grpc/internal/envconfig/envconfig.go @@ -59,6 +59,15 @@ var ( // unconditionally. XDSEndpointHashKeyBackwardCompat = boolFromEnv("GRPC_XDS_ENDPOINT_HASH_KEY_BACKWARD_COMPAT", false) + // LabelServerGoroutines controls setting [runtime/pprof.Labels] on the + // goroutines spawned by [grpc.Server] type. + // For now, this is limited to the goroutines spawned to handle incoming + // requests on the server. + // Set "GRPC_GO_SERVER_GOROUTINE_LABELS" to "grpc.method=true" to + // enable this grpc.method label, or "all" to enable all valid labels. + // This variable is a bit-field. + LabelServerGoroutines = goroutineLabelsFromEnv("GRPC_GO_SERVER_GOROUTINE_LABELS", 0) + // RingHashSetRequestHashKey is set if the ring hash balancer can get the // request hash header by setting the "requestHashHeader" field, according // to gRFC A76. It can be disabled by setting the environment variable @@ -78,12 +87,12 @@ var ( EnableDefaultPortForProxyTarget = boolFromEnv("GRPC_EXPERIMENTAL_ENABLE_DEFAULT_PORT_FOR_PROXY_TARGET", true) // CaseSensitiveBalancerRegistries is set if the balancer registry should be - // case-sensitive. This is disabled by default, but can be enabled by setting + // case-sensitive. This is enabled by default, but can be disabled by setting // the env variable "GRPC_GO_EXPERIMENTAL_CASE_SENSITIVE_BALANCER_REGISTRIES" - // to "true". + // to "false". // - // TODO: After 2 releases, we will enable the env var by default. - CaseSensitiveBalancerRegistries = boolFromEnv("GRPC_GO_EXPERIMENTAL_CASE_SENSITIVE_BALANCER_REGISTRIES", false) + // This env varible will be removed in release v1.82.0. + CaseSensitiveBalancerRegistries = boolFromEnv("GRPC_GO_EXPERIMENTAL_CASE_SENSITIVE_BALANCER_REGISTRIES", true) // XDSAuthorityRewrite indicates whether xDS authority rewriting is enabled. // This feature is defined in gRFC A81 and is enabled by setting the @@ -104,22 +113,6 @@ var ( // to "false". XDSRecoverPanicInResourceParsing = boolFromEnv("GRPC_GO_EXPERIMENTAL_XDS_RESOURCE_PANIC_RECOVERY", true) - // DisableStrictPathChecking indicates whether strict path checking is - // disabled. This feature can be disabled by setting the environment - // variable GRPC_GO_EXPERIMENTAL_DISABLE_STRICT_PATH_CHECKING to "true". - // - // When strict path checking is enabled, gRPC will reject requests with - // paths that do not conform to the gRPC over HTTP/2 specification found at - // https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md. - // - // When disabled, gRPC will allow paths that do not contain a leading slash. - // Enabling strict path checking is recommended for security reasons, as it - // prevents potential path traversal vulnerabilities. - // - // A future release will remove this environment variable, enabling strict - // path checking behavior unconditionally. - DisableStrictPathChecking = boolFromEnv("GRPC_GO_EXPERIMENTAL_DISABLE_STRICT_PATH_CHECKING", false) - // EnablePriorityLBChildPolicyCache controls whether the priority balancer // should cache child balancers that are removed from the LB policy config, // for a period of 15 minutes. This is disabled by default, but can be @@ -127,6 +120,18 @@ var ( // GRPC_EXPERIMENTAL_ENABLE_PRIORITY_LB_CHILD_POLICY_CACHE to true. EnablePriorityLBChildPolicyCache = boolFromEnv("GRPC_EXPERIMENTAL_ENABLE_PRIORITY_LB_CHILD_POLICY_CACHE", false) + // Enable8KBDefaultHeaderListSize indicates that default maximum header list + // size is restricted to 8KB. This is disabled by default, but can be enabled + // by setting the environment variable + // "GRPC_GO_EXPERIMENTAL_ENABLE_8KB_DEFAULT_HEADER_LIST_SIZE" to "true". + // When disabled, the default maximum header list size of 16MB is used. + // + // When enabled, RPCs with a total size of headers exceeding 8KB will fail + // unless explicitly configured otherwise by the user. + // + // TODO: In release v1.82.0, env var will be enabled by default. + Enable8KBDefaultHeaderListSize = boolFromEnv("GRPC_GO_EXPERIMENTAL_ENABLE_8KB_DEFAULT_HEADER_LIST_SIZE", false) + // EnableHTTPFramerReadBufferPooling enables the use of the // readyreader.Reader interface to perform non-memory-pinning reads, // provided the underlying net.Conn supports it. This reduces memory usage @@ -160,3 +165,52 @@ func uint64FromEnv(envVar string, def, min, max uint64) uint64 { } return v } + +// GoroutineLabels is a bitfield indicating which goroutine labels are enabled. +type GoroutineLabels uint16 + +func goroutineLabelsFromEnv(envVar string, def GoroutineLabels) GoroutineLabels { + val := def + v := os.Getenv(envVar) + if strings.EqualFold(v, "all") { + return AllGoroutineLabels + } else if strings.EqualFold(v, "none") { + return 0 + } + for s := range strings.SplitSeq(v, ",") { + s = strings.TrimSpace(s) + if len(s) == 0 { + continue + } + pre, post, ok := strings.Cut(s, "=") + if !ok { + // no equals sign + continue + } + post = strings.TrimSpace(post) + pre = strings.TrimSpace(pre) + bitDesignator := GoroutineLabels(0) + switch { + case strings.EqualFold(pre, "grpc.method"): + bitDesignator = GoroutineLabelServerMethod + default: + continue + } + if strings.EqualFold(post, "true") { + val |= bitDesignator + } else if strings.EqualFold(post, "false") { + val &^= bitDesignator + } + } + return val +} + +const ( + // GoroutineLabelServerMethod sets the grpc.method label on new + // server-side gRPC streams. + GoroutineLabelServerMethod GoroutineLabels = 1 << iota +) + +// AllGoroutineLabels is an or'd together bitfield of all valid GoroutineLabels +// constant values (above). +const AllGoroutineLabels = GoroutineLabelServerMethod diff --git a/vendor/google.golang.org/grpc/internal/envconfig/xds.go b/vendor/google.golang.org/grpc/internal/envconfig/xds.go index 333d8a0b06..a2312f8eac 100644 --- a/vendor/google.golang.org/grpc/internal/envconfig/xds.go +++ b/vendor/google.golang.org/grpc/internal/envconfig/xds.go @@ -89,4 +89,14 @@ var ( // filtered and prefix-propagated to the LRS server. For more details, see: // https://github.com/grpc/proposal/blob/master/A85-lrs-custom-metrics-changes.md XDSORCAToLRSPropEnabled = boolFromEnv("GRPC_EXPERIMENTAL_XDS_ORCA_LRS_PROPAGATION", false) + + // XDSClientExtProcEnabled indicates whether ExtProc filter is enabled on + // the client side. For more details, see: + // https://github.com/grpc/proposal/blob/master/A93-xds-ext-proc.md + XDSClientExtProcEnabled = boolFromEnv("GRPC_EXPERIMENTAL_XDS_EXT_PROC_ON_CLIENT", false) + + // GCPAuthenticationFilterEnabled enables the xDS GCP Authentication + // filter. For more details, see: + // https://github.com/grpc/proposal/blob/master/A83-xds-gcp-authn-filter.md + GCPAuthenticationFilterEnabled = boolFromEnv("GRPC_EXPERIMENTAL_XDS_GCP_AUTHENTICATION_FILTER", false) ) diff --git a/vendor/google.golang.org/grpc/internal/grpcutil/encode_duration.go b/vendor/google.golang.org/grpc/internal/grpcutil/encode_duration.go index b25b0baec3..1cc43fc6b8 100644 --- a/vendor/google.golang.org/grpc/internal/grpcutil/encode_duration.go +++ b/vendor/google.golang.org/grpc/internal/grpcutil/encode_duration.go @@ -39,7 +39,6 @@ func div(d, r time.Duration) int64 { // // https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md#requests func EncodeDuration(t time.Duration) string { - // TODO: This is simplistic and not bandwidth efficient. Improve it. if t <= 0 { return "0n" } diff --git a/vendor/google.golang.org/grpc/internal/resolver/config_selector.go b/vendor/google.golang.org/grpc/internal/resolver/config_selector.go index 3db62ccad2..6320e9b576 100644 --- a/vendor/google.golang.org/grpc/internal/resolver/config_selector.go +++ b/vendor/google.golang.org/grpc/internal/resolver/config_selector.go @@ -106,14 +106,24 @@ type ClientStream interface { // ClientInterceptor is an interceptor for gRPC client streams. type ClientInterceptor interface { - // NewStream produces a ClientStream for an RPC which may optionally use - // the provided function to produce a stream for delegation. Note: - // RPCInfo.Context should not be used (will be nil). + // NewStream creates a ClientStream for an RPC. // - // done is invoked when the RPC is finished using its connection, or could - // not be assigned a connection. RPC operations may still occur on - // ClientStream after done is called, since the interceptor is invoked by - // application-layer operations. done must never be nil when called. + // Implementations must delegate stream creation to the provided newStream + // function. To intercept or override stream behavior, implementations + // may wrap the ClientStream returned by the delegate. + // + // Note: RPCInfo.Context is currently unused and will be nil. + // + // The done function is invoked when the RPC has finished using its + // underlying connection or if a connection could not be assigned. Because + // interceptors operate at the application layer, RPC operations may + // continue on the ClientStream even after done has been called. The + // caller must ensure done is non-nil. + // + // To ensure RPC completion notifications propagate through the entire + // interceptor chain, implementations must ensure that the done function + // passed to the delegate newStream invokes the done function passed to + // NewStream. NewStream(ctx context.Context, ri RPCInfo, done func(), newStream func(ctx context.Context, done func()) (ClientStream, error)) (ClientStream, error) // Close closes the interceptor. Once called, no new calls to NewStream are // accepted. Ongoing calls to NewStream are allowed to complete. diff --git a/vendor/google.golang.org/grpc/internal/stats/labels.go b/vendor/google.golang.org/grpc/internal/stats/labels.go index fd33af51ae..5ea898cb53 100644 --- a/vendor/google.golang.org/grpc/internal/stats/labels.go +++ b/vendor/google.golang.org/grpc/internal/stats/labels.go @@ -19,24 +19,56 @@ // Package stats provides internal stats related functionality. package stats -import "context" +import ( + "context" + "maps" +) -// Labels are the labels for metrics. -type Labels struct { - // TelemetryLabels are the telemetry labels to record. - TelemetryLabels map[string]string +// LabelCallback is a function that is executed when telemetry +// label keys are updated. +type LabelCallback func(map[string]string) +type telemetryLabelCallbackKey struct{} + +// UpdateLabels executes registered telemetry callbacks with the update labels. Labels +// are copied before being processed by any callbacks to ensure mutations are not +// shared among derived contexts. +// +// It is the responsibility of the registrant to handle conflicts or label resets. +func UpdateLabels(ctx context.Context, update map[string]string) { + executeTelemetryLabelCallbacks(ctx, update) } -type labelsKey struct{} +// RegisterTelemetryLabelCallback registers a callback function that is executed whenever +// telemetry labels are updated. +func RegisterTelemetryLabelCallback(ctx context.Context, callback LabelCallback) context.Context { + if callback == nil { + return ctx + } + + callbacks, ok := ctx.Value(telemetryLabelCallbackKey{}).([]LabelCallback) + if !ok { + return context.WithValue(ctx, telemetryLabelCallbackKey{}, []LabelCallback{callback}) + } + return context.WithValue(ctx, telemetryLabelCallbackKey{}, append(append([]LabelCallback(nil), callbacks...), callback)) -// GetLabels returns the Labels stored in the context, or nil if there is one. -func GetLabels(ctx context.Context) *Labels { - labels, _ := ctx.Value(labelsKey{}).(*Labels) - return labels } -// SetLabels sets the Labels in the context. -func SetLabels(ctx context.Context, labels *Labels) context.Context { - // could also append - return context.WithValue(ctx, labelsKey{}, labels) +// executeTelemetryLabelCallback runs the registered callbacks in the order they were +// registered on the context with the provided labels. If no callbacks are registered +// it does nothing. +// +// To ensure callbacks do not mutate the state of the provided label map it is copied +// before execution. +func executeTelemetryLabelCallbacks(ctx context.Context, labels map[string]string) { + callbacks, ok := ctx.Value(telemetryLabelCallbackKey{}).([]LabelCallback) + if !ok { + return + } + + labelsCopy := map[string]string{} + maps.Copy(labelsCopy, labels) + for _, callback := range callbacks { + callback(labelsCopy) + } + } diff --git a/vendor/google.golang.org/grpc/internal/transport/client_stream.go b/vendor/google.golang.org/grpc/internal/transport/client_stream.go index cd8152ef13..ad382b0fda 100644 --- a/vendor/google.golang.org/grpc/internal/transport/client_stream.go +++ b/vendor/google.golang.org/grpc/internal/transport/client_stream.go @@ -19,6 +19,7 @@ package transport import ( + "fmt" "sync/atomic" "golang.org/x/net/http2" @@ -28,6 +29,12 @@ import ( "google.golang.org/grpc/status" ) +// nonGRPCDataMaxLen is the maximum length of nonGRPCDataBuf. +// +// NOTE: If changed this value, you MUST update the corresponding test in: +// - /test/end2end_test.go:TestHTTPServerSendsNonGRPCHeaderSurfaceFurtherData +const nonGRPCDataMaxLen = 1024 + // ClientStream implements streaming functionality for a gRPC client. type ClientStream struct { Stream // Embed for common stream functionality. @@ -46,7 +53,11 @@ type ClientStream struct { // headerValid indicates whether a valid header was received. Only // meaningful after headerChan is closed (always call waitOnHeader() before // reading its value). - headerValid bool + headerValid bool + + nonGRPCStatus *status.Status // the initial status from the non-gRPC response header, finalized with collected data before closing. + nonGRPCDataBuf []byte // stores the data of a non-gRPC response. + noHeaders bool // set if the client never received headers (set only after the stream is done). headerChanClosed uint32 // set when headerChan is closed. Used to avoid closing headerChan multiple times. bytesReceived atomic.Bool // indicates whether any bytes have been received on this stream @@ -54,6 +65,29 @@ type ClientStream struct { statsHandler stats.Handler // nil for internal streams (e.g., health check, ORCA) where telemetry is not supported. } +func (s *ClientStream) startNonGRPCDataCollection(st *status.Status) { + s.nonGRPCStatus = st + s.nonGRPCDataBuf = make([]byte, 0, nonGRPCDataMaxLen) +} + +// finalizeNonGRPCStatus builds the terminal status by appending the collected +// response body to the original non-gRPC status message. +func (s *ClientStream) finalizeNonGRPCStatus() *status.Status { + msg := fmt.Sprintf("%s\ndata: %q", s.nonGRPCStatus.Message(), s.nonGRPCDataBuf) + return status.New(s.nonGRPCStatus.Code(), msg) +} + +// handleNonGRPCData collects non-gRPC body from the given data frame. +// It returns non-nil value when the stream should be closed with it. +func (s *ClientStream) handleNonGRPCData(f *parsedDataFrame) *status.Status { + n := min(f.data.Len(), nonGRPCDataMaxLen-len(s.nonGRPCDataBuf)) + s.nonGRPCDataBuf = append(s.nonGRPCDataBuf, f.data.ReadOnlyData()[0:n]...) + if len(s.nonGRPCDataBuf) >= nonGRPCDataMaxLen || f.StreamEnded() { + return s.finalizeNonGRPCStatus() + } + return nil +} + // Read reads an n byte message from the input stream. func (s *ClientStream) Read(n int) (mem.BufferSlice, error) { b, err := s.Stream.read(n) diff --git a/vendor/google.golang.org/grpc/internal/transport/controlbuf.go b/vendor/google.golang.org/grpc/internal/transport/controlbuf.go index 7efa524785..c5a76b70ad 100644 --- a/vendor/google.golang.org/grpc/internal/transport/controlbuf.go +++ b/vendor/google.golang.org/grpc/internal/transport/controlbuf.go @@ -956,39 +956,16 @@ func (l *loopyWriter) processData() (bool, error) { // from data is copied to h to make as big as the maximum possible HTTP2 frame // size. - if len(dataItem.h) == 0 && reader.Remaining() == 0 { // Empty data frame - // Client sends out empty data frame with endStream = true - if err := l.framer.writeData(dataItem.streamID, dataItem.endStream, nil); err != nil { - return false, err - } - str.itl.dequeue() // remove the empty data item from stream - reader.Close() - if str.itl.isEmpty() { - str.state = empty - } else if trailer, ok := str.itl.peek().(*headerFrame); ok { // the next item is trailers. - if err := l.writeHeader(trailer.streamID, trailer.endStream, trailer.hf, trailer.onWrite); err != nil { - return false, err - } - if err := l.cleanupStreamHandler(trailer.cleanup); err != nil { - return false, err - } - } else { - l.activeStreams.enqueue(str) - } - return false, nil - } - + isEmpty := len(dataItem.h) == 0 && reader.Remaining() == 0 // Figure out the maximum size we can send maxSize := http2MaxFrameLen - if strQuota := int(l.oiws) - str.bytesOutStanding; strQuota <= 0 { // stream-level flow control. + strQuota := int(l.oiws) - str.bytesOutStanding + if strQuota <= 0 && !isEmpty { // stream-level flow control. str.state = waitingOnStreamQuota return false, nil - } else if maxSize > strQuota { - maxSize = strQuota - } - if maxSize > int(l.sendQuota) { // connection-level flow control. - maxSize = int(l.sendQuota) } + maxSize = min(maxSize, max(strQuota, 0)) + maxSize = min(maxSize, int(l.sendQuota)) // connection-level flow control. // Compute how much of the header and data we can send within quota and max frame length hSize := min(maxSize, len(dataItem.h)) dSize := min(maxSize-hSize, reader.Remaining()) @@ -1039,19 +1016,23 @@ func (l *loopyWriter) processData() (bool, error) { reader.Close() str.itl.dequeue() } + return false, l.updateStreamAfterWrite(str) +} + +func (l *loopyWriter) updateStreamAfterWrite(str *outStream) error { if str.itl.isEmpty() { str.state = empty - } else if trailer, ok := str.itl.peek().(*headerFrame); ok { // The next item is trailers. + } else if trailer, ok := str.itl.peek().(*headerFrame); ok { // the next item is trailers. if err := l.writeHeader(trailer.streamID, trailer.endStream, trailer.hf, trailer.onWrite); err != nil { - return false, err + return err } if err := l.cleanupStreamHandler(trailer.cleanup); err != nil { - return false, err + return err } } else if int(l.oiws)-str.bytesOutStanding <= 0 { // Ran out of stream quota. str.state = waitingOnStreamQuota } else { // Otherwise add it back to the list of active streams. l.activeStreams.enqueue(str) } - return false, nil + return nil } diff --git a/vendor/google.golang.org/grpc/internal/transport/flowcontrol.go b/vendor/google.golang.org/grpc/internal/transport/flowcontrol.go index 7cfbc9637b..98cef9ec2b 100644 --- a/vendor/google.golang.org/grpc/internal/transport/flowcontrol.go +++ b/vendor/google.golang.org/grpc/internal/transport/flowcontrol.go @@ -115,7 +115,6 @@ func (f *trInFlow) getSize() uint32 { return atomic.LoadUint32(&f.effectiveWindowSize) } -// TODO(mmukhi): Simplify this code. // inFlow deals with inbound flow control type inFlow struct { mu sync.Mutex @@ -174,14 +173,14 @@ func (f *inFlow) maybeAdjust(n uint32) uint32 { // onData is invoked when some data frame is received. It updates pendingData. func (f *inFlow) onData(n uint32) error { f.mu.Lock() + defer f.mu.Unlock() + f.pendingData += n if f.pendingData+f.pendingUpdate > f.limit+f.delta { limit := f.limit rcvd := f.pendingData + f.pendingUpdate - f.mu.Unlock() return fmt.Errorf("received %d-bytes data exceeding the limit %d bytes", rcvd, limit) } - f.mu.Unlock() return nil } @@ -189,8 +188,9 @@ func (f *inFlow) onData(n uint32) error { // to be sent to the peer. func (f *inFlow) onRead(n uint32) uint32 { f.mu.Lock() + defer f.mu.Unlock() + if f.pendingData == 0 { - f.mu.Unlock() return 0 } f.pendingData -= n @@ -205,9 +205,7 @@ func (f *inFlow) onRead(n uint32) uint32 { if f.pendingUpdate >= f.limit/4 { wu := f.pendingUpdate f.pendingUpdate = 0 - f.mu.Unlock() return wu } - f.mu.Unlock() return 0 } diff --git a/vendor/google.golang.org/grpc/internal/transport/handler_server.go b/vendor/google.golang.org/grpc/internal/transport/handler_server.go index 7ab3422b8a..a8356c9adb 100644 --- a/vendor/google.golang.org/grpc/internal/transport/handler_server.go +++ b/vendor/google.golang.org/grpc/internal/transport/handler_server.go @@ -479,8 +479,8 @@ func (ht *serverHandlerTransport) runStream() { func (ht *serverHandlerTransport) incrMsgRecv() {} -func (ht *serverHandlerTransport) Drain(string) { - panic("Drain() is not implemented") +func (ht *serverHandlerTransport) Drain(s string) { + ht.Close(errors.New(s)) } // mapRecvMsgError returns the non-nil err into the appropriate diff --git a/vendor/google.golang.org/grpc/internal/transport/http2_client.go b/vendor/google.golang.org/grpc/internal/transport/http2_client.go index d6bc6a6cc7..133f5d7065 100644 --- a/vendor/google.golang.org/grpc/internal/transport/http2_client.go +++ b/vendor/google.golang.org/grpc/internal/transport/http2_client.go @@ -39,6 +39,7 @@ import ( "google.golang.org/grpc/internal" "google.golang.org/grpc/internal/channelz" icredentials "google.golang.org/grpc/internal/credentials" + "google.golang.org/grpc/internal/envconfig" "google.golang.org/grpc/internal/grpclog" "google.golang.org/grpc/internal/grpcsync" "google.golang.org/grpc/internal/grpcutil" @@ -318,7 +319,13 @@ func NewHTTP2Client(connectCtx, ctx context.Context, addr resolver.Address, opts } writeBufSize := opts.WriteBufferSize readBufSize := opts.ReadBufferSize + // The default header list size is moving from 16MB to 8KB. The 8KB limit + // is only used if Enable8KBDefaultHeaderListSize is true; otherwise, the + // old 16MB default is used. User-specified options always take precedence. maxHeaderListSize := defaultClientMaxHeaderListSize + if envconfig.Enable8KBDefaultHeaderListSize { + maxHeaderListSize = upcomingDefaultHeaderListSize + } if opts.MaxHeaderListSize != nil { maxHeaderListSize = *opts.MaxHeaderListSize } @@ -879,8 +886,8 @@ func (t *http2Client) NewStream(ctx context.Context, callHdr *CallHdr, handler s return false } } - if sz > int64(upcomingDefaultHeaderListSize) { - t.logger.Warningf("Header list size to send (%d bytes) is larger than the upcoming default limit (%d bytes). In a future release, this will be restricted to %d bytes.", sz, upcomingDefaultHeaderListSize, upcomingDefaultHeaderListSize) + if !envconfig.Enable8KBDefaultHeaderListSize && sz > int64(upcomingDefaultHeaderListSize) { + t.logger.Warningf("Header list size to send (%d bytes) is larger than the upcoming default limit (%d bytes). In release v1.82.0, GRPC_GO_EXPERIMENTAL_ENABLE_8KB_DEFAULT_HEADER_LIST_SIZE will be enabled by default, enforcing this limit.", sz, upcomingDefaultHeaderListSize) } return true } @@ -1224,6 +1231,23 @@ func (t *http2Client) handleData(f *parsedDataFrame) { t.closeStream(s, io.EOF, true, http2.ErrCodeFlowControl, status.New(codes.Internal, err.Error()), nil, false) return } + + if s.nonGRPCStatus != nil { + // The frame should be handled as a non-gRPC response body + st := s.handleNonGRPCData(f) + if st != nil { + t.closeStream(s, st.Err(), true, http2.ErrCodeProtocol, st, nil, true) + return + } + if w := s.fc.onRead(size); w > 0 { + t.controlBuf.put(&outgoingWindowUpdate{ + streamID: s.id, + increment: w, + }) + } + return + } + dataLen := f.data.Len() if f.Header().Flags.Has(http2.FlagDataPadded) { if w := s.fc.onRead(size - uint32(dataLen)); w > 0 { @@ -1468,6 +1492,17 @@ func (t *http2Client) operateHeaders(frame *http2.MetaHeadersFrame) { return } + // If we are collecting non-gRPC response data and receive a trailing + // HEADERS frame with END_STREAM, finalize the buffered data and close + // the stream. + if s.nonGRPCStatus != nil { + if endStream { + st := s.finalizeNonGRPCStatus() + t.closeStream(s, st.Err(), true, http2.ErrCodeProtocol, st, nil, true) + } + return + } + var ( // If a gRPC Response-Headers has already been received, then it means // that the peer is speaking gRPC and we are in gRPC mode. @@ -1568,7 +1603,12 @@ func (t *http2Client) operateHeaders(frame *http2.MetaHeadersFrame) { } se := status.New(grpcErrorCode, strings.Join(errs, "; ")) - t.closeStream(s, se.Err(), true, http2.ErrCodeProtocol, se, nil, endStream) + if endStream { + t.closeStream(s, se.Err(), true, http2.ErrCodeProtocol, se, nil, true) + return + } + + s.startNonGRPCDataCollection(se) return } diff --git a/vendor/google.golang.org/grpc/internal/transport/http2_server.go b/vendor/google.golang.org/grpc/internal/transport/http2_server.go index 3a8c36e4f9..1acd44be4b 100644 --- a/vendor/google.golang.org/grpc/internal/transport/http2_server.go +++ b/vendor/google.golang.org/grpc/internal/transport/http2_server.go @@ -38,11 +38,13 @@ import ( "google.golang.org/protobuf/proto" "google.golang.org/grpc/internal" + "google.golang.org/grpc/internal/envconfig" "google.golang.org/grpc/internal/grpclog" "google.golang.org/grpc/internal/grpcutil" "google.golang.org/grpc/internal/pretty" istatus "google.golang.org/grpc/internal/status" "google.golang.org/grpc/internal/syscall" + transportinternal "google.golang.org/grpc/internal/transport/internal" "google.golang.org/grpc/mem" "google.golang.org/grpc/codes" @@ -165,7 +167,13 @@ func NewServerTransport(conn net.Conn, config *ServerConfig) (_ ServerTransport, } writeBufSize := config.WriteBufferSize readBufSize := config.ReadBufferSize + // The default header list size is moving from 16MB to 8KB. The 8KB limit + // is only used if Enable8KBDefaultHeaderListSize is true; otherwise, the + // old 16MB default is used. User-specified options always take precedence. maxHeaderListSize := defaultServerMaxHeaderListSize + if envconfig.Enable8KBDefaultHeaderListSize { + maxHeaderListSize = upcomingDefaultHeaderListSize + } if config.MaxHeaderListSize != nil { maxHeaderListSize = *config.MaxHeaderListSize } @@ -948,8 +956,8 @@ func (t *http2Server) checkForHeaderListSize(hf []hpack.HeaderField) bool { return false } } - if sz > int64(upcomingDefaultHeaderListSize) { - t.logger.Warningf("Header list size to send (%d bytes) is larger than the upcoming default limit (%d bytes). In a future release, this will be restricted to %d bytes.", sz, upcomingDefaultHeaderListSize, upcomingDefaultHeaderListSize) + if !envconfig.Enable8KBDefaultHeaderListSize && sz > int64(upcomingDefaultHeaderListSize) { + t.logger.Warningf("Header list size to send (%d bytes) is larger than the upcoming default limit (%d bytes). In release v1.82.0, GRPC_GO_EXPERIMENTAL_ENABLE_8KB_DEFAULT_HEADER_LIST_SIZE will be enabled by default, enforcing this limit.", sz, upcomingDefaultHeaderListSize) } return true } @@ -1441,14 +1449,14 @@ func (t *http2Server) socketMetrics() *channelz.EphemeralSocketMetrics { func (t *http2Server) incrMsgSent() { if channelz.IsOn() { t.channelz.SocketMetrics.MessagesSent.Add(1) - t.channelz.SocketMetrics.LastMessageSentTimestamp.Add(1) + t.channelz.SocketMetrics.LastMessageSentTimestamp.Store(transportinternal.TimeNowFunc()) } } func (t *http2Server) incrMsgRecv() { if channelz.IsOn() { t.channelz.SocketMetrics.MessagesReceived.Add(1) - t.channelz.SocketMetrics.LastMessageReceivedTimestamp.Add(1) + t.channelz.SocketMetrics.LastMessageReceivedTimestamp.Store(transportinternal.TimeNowFunc()) } } diff --git a/vendor/google.golang.org/grpc/internal/grpcutil/regex.go b/vendor/google.golang.org/grpc/internal/transport/internal/internal.go similarity index 59% rename from vendor/google.golang.org/grpc/internal/grpcutil/regex.go rename to vendor/google.golang.org/grpc/internal/transport/internal/internal.go index 7a092b2b80..a7c7c7d5a8 100644 --- a/vendor/google.golang.org/grpc/internal/grpcutil/regex.go +++ b/vendor/google.golang.org/grpc/internal/transport/internal/internal.go @@ -1,6 +1,6 @@ /* * - * Copyright 2021 gRPC authors. + * Copyright 2026 gRPC authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,16 +16,10 @@ * */ -package grpcutil +// Package internal contains functionality internal to the transport package. +package internal -import "regexp" - -// FullMatchWithRegex returns whether the full text matches the regex provided. -func FullMatchWithRegex(re *regexp.Regexp, text string) bool { - if len(text) == 0 { - return re.MatchString(text) - } - re.Longest() - rem := re.FindString(text) - return len(rem) == len(text) -} +// TimeNowFunc is a variable that can be set to override the default behavior of +// getting the current time in nanoseconds. It is used in transport code to set +// channelz timestamps, and is exposed here for testing purposes. +var TimeNowFunc func() int64 diff --git a/vendor/google.golang.org/grpc/internal/transport/transport.go b/vendor/google.golang.org/grpc/internal/transport/transport.go index 1e224576e8..6dfae39849 100644 --- a/vendor/google.golang.org/grpc/internal/transport/transport.go +++ b/vendor/google.golang.org/grpc/internal/transport/transport.go @@ -35,6 +35,7 @@ import ( "google.golang.org/grpc/codes" "google.golang.org/grpc/credentials" "google.golang.org/grpc/internal/channelz" + "google.golang.org/grpc/internal/transport/internal" "google.golang.org/grpc/keepalive" "google.golang.org/grpc/mem" "google.golang.org/grpc/metadata" @@ -46,6 +47,10 @@ import ( const logLevel = 2 +func init() { + internal.TimeNowFunc = func() int64 { return time.Now().UnixNano() } +} + // recvMsg represents the received msg from the transport. All transport // protocol specific info has been removed. type recvMsg struct { diff --git a/vendor/google.golang.org/grpc/rpc_util.go b/vendor/google.golang.org/grpc/rpc_util.go index ee7f7dead1..52f4ea513d 100644 --- a/vendor/google.golang.org/grpc/rpc_util.go +++ b/vendor/google.golang.org/grpc/rpc_util.go @@ -128,6 +128,16 @@ func NewGZIPDecompressor() Decompressor { } func (d *gzipDecompressor) Do(r io.Reader) ([]byte, error) { + return d.doWithMaxSize(r, math.MaxInt64) +} + +// doWithMaxSize behaves like Do but caps the size of the decompressed +// payload at maxMessageSize+1 bytes. The Decompressor interface does not +// allow extra parameters, so callers inside the package type-assert to +// *gzipDecompressor to invoke this method directly. The +1 byte makes it +// possible for the caller to detect that the limit was exceeded and +// return ResourceExhausted instead of materializing an unbounded payload. +func (d *gzipDecompressor) doWithMaxSize(r io.Reader, maxMessageSize int64) ([]byte, error) { var z *gzip.Reader switch maybeZ := d.pool.Get().(type) { case nil: @@ -148,7 +158,11 @@ func (d *gzipDecompressor) Do(r io.Reader) ([]byte, error) { z.Close() d.pool.Put(z) }() - return io.ReadAll(z) + var src io.Reader = z + if maxMessageSize < math.MaxInt64 { + src = io.LimitReader(z, maxMessageSize+1) + } + return io.ReadAll(src) } func (d *gzipDecompressor) Type() string { @@ -830,15 +844,15 @@ func compress(in mem.BufferSlice, cp Compressor, compressor encoding.Compressor, if compressor != nil { z, err := compressor.Compress(w) if err != nil { - return nil, 0, wrapErr(err) + return nil, compressionNone, wrapErr(err) } for _, b := range in { if _, err := z.Write(b.ReadOnlyData()); err != nil { - return nil, 0, wrapErr(err) + return nil, compressionNone, wrapErr(err) } } if err := z.Close(); err != nil { - return nil, 0, wrapErr(err) + return nil, compressionNone, wrapErr(err) } } else { // This is obviously really inefficient since it fully materializes the data, but @@ -848,7 +862,7 @@ func compress(in mem.BufferSlice, cp Compressor, compressor encoding.Compressor, buf := in.MaterializeToBuffer(pool) defer buf.Free() if err := cp.Do(w, buf.ReadOnlyData()); err != nil { - return nil, 0, wrapErr(err) + return nil, compressionNone, wrapErr(err) } } return out, compressionMade, nil @@ -971,7 +985,20 @@ func recvAndDecompress(p *parser, s recvCompressor, dc Decompressor, maxReceiveM func decompress(compressor encoding.Compressor, d mem.BufferSlice, dc Decompressor, maxReceiveMessageSize int, pool mem.BufferPool) (mem.BufferSlice, error) { if dc != nil { r := d.Reader() - uncompressed, err := dc.Do(r) + // For the built-in gzip decompressor, bound the decompressed output + // at maxReceiveMessageSize+1 so that a small but highly compressed + // payload (a "zip bomb") cannot expand to gigabytes in memory before + // the post-decompression size check below has a chance to fire. The + // Decompressor interface does not accept an extra size parameter, + // so we type-assert to invoke a size-aware helper. Third-party + // Decompressor implementations keep the original Do behavior. + var uncompressed []byte + var err error + if gd, ok := dc.(*gzipDecompressor); ok { + uncompressed, err = gd.doWithMaxSize(r, int64(maxReceiveMessageSize)) + } else { + uncompressed, err = dc.Do(r) + } if err != nil { r.Close() // ensure buffers are reused return nil, status.Errorf(codes.Internal, "grpc: failed to decompress the received message: %v", err) @@ -989,6 +1016,9 @@ func decompress(compressor encoding.Compressor, d mem.BufferSlice, dc Decompress r.Close() // ensure buffers are reused return nil, status.Errorf(codes.Internal, "grpc: failed to decompress the message: %v", err) } + if closer, ok := dcReader.(io.Closer); ok { + defer closer.Close() + } // Read at most one byte more than the limit from the decompressor. // Unless the limit is MaxInt64, in which case, that's impossible, so diff --git a/vendor/google.golang.org/grpc/server.go b/vendor/google.golang.org/grpc/server.go index 5229adf711..cf0a206719 100644 --- a/vendor/google.golang.org/grpc/server.go +++ b/vendor/google.golang.org/grpc/server.go @@ -28,6 +28,7 @@ import ( "net/http" "reflect" "runtime" + "runtime/pprof" "strings" "sync" "sync/atomic" @@ -150,8 +151,6 @@ type Server struct { serverWorkerChannel chan func() serverWorkerChannelClose func() - - strictPathCheckingLogEmitted atomic.Bool } type serverOptions struct { @@ -250,10 +249,8 @@ func newJoinServerOption(opts ...ServerOption) ServerOption { // If this option is set to true every connection will release the buffer after // flushing the data on the wire. // -// # Experimental -// -// Notice: This API is EXPERIMENTAL and may be changed or removed in a -// later release. +// Deprecated: shared write buffer is enabled by default. SharedWriteBuffer +// will be removed in a future release. func SharedWriteBuffer(val bool) ServerOption { return newFuncServerOption(func(o *serverOptions) { o.sharedWriteBuffer = val @@ -302,6 +299,14 @@ func InitialConnWindowSize(s int32) ServerOption { // window size to the value provided and disables dynamic flow control. // The lower bound for window size is 64K and any value smaller than that // will be ignored. +// +// Note that this also disables dynamic flow control for the connection, +// falling back to a default static connection-level window of 64KB. To +// use a larger connection-level window, you must also use the +// [StaticConnWindowSize] ServerOption. +// +// Most users should not configure static flow control windows unless +// operating in a memory-constrained environment. func StaticStreamWindowSize(s int32) ServerOption { return newFuncServerOption(func(o *serverOptions) { o.initialWindowSize = s @@ -313,6 +318,14 @@ func StaticStreamWindowSize(s int32) ServerOption { // window size to the value provided and disables dynamic flow control. // The lower bound for window size is 64K and any value smaller than that // will be ignored. +// +// Note that this also disables dynamic flow control for individual streams, +// falling back to a default static connection-level window of 64KB. To +// explicitly configure the stream-level window size, you must also use the +// [StaticStreamWindowSize] ServerOption. +// +// Most users should not configure static flow control windows unless +// operating in a memory-constrained environment. func StaticConnWindowSize(s int32) ServerOption { return newFuncServerOption(func(o *serverOptions) { o.initialConnWindowSize = s @@ -1787,6 +1800,12 @@ func (s *Server) handleMalformedMethodName(stream *transport.ServerStream, ti *t func (s *Server) handleStream(t transport.ServerTransport, stream *transport.ServerStream) { ctx := stream.Context() ctx = contextWithServer(ctx, s) + if envconfig.LabelServerGoroutines&envconfig.GoroutineLabelServerMethod != 0 { + // This method always runs in its own goroutine, so we can set a + // goroutine label without needing to restore a previous context. + ctx = pprof.WithLabels(ctx, pprof.Labels("grpc.method", stream.Method())) + pprof.SetGoroutineLabels(ctx) + } var ti *traceInfo if EnableTracing { tr := newTrace("grpc.Recv."+methodFamily(stream.Method()), stream.Method()) @@ -1803,28 +1822,11 @@ func (s *Server) handleStream(t transport.ServerTransport, stream *transport.Ser } } - sm := stream.Method() - if sm == "" { + sm, found := strings.CutPrefix(stream.Method(), "/") + if !found { s.handleMalformedMethodName(stream, ti) return } - if sm[0] != '/' { - // TODO(easwars): Add a link to the CVE in the below log messages once - // published. - if envconfig.DisableStrictPathChecking { - if old := s.strictPathCheckingLogEmitted.Swap(true); !old { - channelz.Warningf(logger, s.channelz, "grpc: Server.handleStream received malformed method name %q. Allowing it because the environment variable GRPC_GO_EXPERIMENTAL_DISABLE_STRICT_PATH_CHECKING is set to true, but this option will be removed in a future release.", sm) - } - } else { - if old := s.strictPathCheckingLogEmitted.Swap(true); !old { - channelz.Warningf(logger, s.channelz, "grpc: Server.handleStream rejected malformed method name %q. To temporarily allow such requests, set the environment variable GRPC_GO_EXPERIMENTAL_DISABLE_STRICT_PATH_CHECKING to true. Note that this is not recommended as it may allow requests to bypass security policies.", sm) - } - s.handleMalformedMethodName(stream, ti) - return - } - } else { - sm = sm[1:] - } pos := strings.LastIndex(sm, "/") if pos == -1 { s.handleMalformedMethodName(stream, ti) diff --git a/vendor/google.golang.org/grpc/version.go b/vendor/google.golang.org/grpc/version.go index 3ccfe515f7..cf114ef4bc 100644 --- a/vendor/google.golang.org/grpc/version.go +++ b/vendor/google.golang.org/grpc/version.go @@ -19,4 +19,4 @@ package grpc // Version is the current grpc version. -const Version = "1.81.1" +const Version = "1.82.0" diff --git a/vendor/modules.txt b/vendor/modules.txt index 7ac249e645..1cf67c022d 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -4,7 +4,7 @@ al.essio.dev/pkg/shellescape # cloud.google.com/go v0.123.0 ## explicit; go 1.24.0 cloud.google.com/go -# cloud.google.com/go/auth v0.20.0 +# cloud.google.com/go/auth v0.21.0 ## explicit; go 1.25.0 cloud.google.com/go/auth cloud.google.com/go/auth/credentials @@ -19,11 +19,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/regionalaccessboundary 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 @@ -288,11 +288,11 @@ github.com/google/s2a-go/stream # github.com/google/uuid v1.6.0 ## explicit github.com/google/uuid -# github.com/googleapis/enterprise-certificate-proxy v0.3.16 -## explicit; go 1.25.8 +# github.com/googleapis/enterprise-certificate-proxy v0.3.17 +## explicit; go 1.25.0 github.com/googleapis/enterprise-certificate-proxy/client github.com/googleapis/enterprise-certificate-proxy/client/util -# github.com/googleapis/gax-go/v2 v2.22.0 +# github.com/googleapis/gax-go/v2 v2.23.0 ## explicit; go 1.25.0 github.com/googleapis/gax-go/v2 github.com/googleapis/gax-go/v2/apierror @@ -686,8 +686,8 @@ golang.org/x/tools/internal/versions # gomodules.xyz/jsonpatch/v2 v2.4.0 ## explicit; go 1.20 gomodules.xyz/jsonpatch/v2 -# google.golang.org/api v0.286.0 -## explicit; go 1.25.8 +# google.golang.org/api v0.287.1 +## explicit; go 1.25.0 google.golang.org/api/googleapi google.golang.org/api/googleapi/transport google.golang.org/api/internal @@ -710,7 +710,7 @@ google.golang.org/genproto/googleapis/logging/type google.golang.org/genproto/googleapis/type/calendarperiod google.golang.org/genproto/googleapis/type/expr google.golang.org/genproto/googleapis/type/timeofday -# google.golang.org/genproto/googleapis/api v0.0.0-20260526163538-3dc84a4a5aaa +# google.golang.org/genproto/googleapis/api v0.0.0-20260630182238-925bb5da69e7 ## explicit; go 1.25.0 google.golang.org/genproto/googleapis/api google.golang.org/genproto/googleapis/api/annotations @@ -719,13 +719,13 @@ google.golang.org/genproto/googleapis/api/httpbody google.golang.org/genproto/googleapis/api/label google.golang.org/genproto/googleapis/api/metric google.golang.org/genproto/googleapis/api/monitoredres -# google.golang.org/genproto/googleapis/rpc v0.0.0-20260610212136-7ab31c22f7ad +# google.golang.org/genproto/googleapis/rpc v0.0.0-20260630182238-925bb5da69e7 ## explicit; go 1.25.0 google.golang.org/genproto/googleapis/rpc/code google.golang.org/genproto/googleapis/rpc/context/attribute_context google.golang.org/genproto/googleapis/rpc/errdetails google.golang.org/genproto/googleapis/rpc/status -# google.golang.org/grpc v1.81.1 +# google.golang.org/grpc v1.82.0 ## explicit; go 1.25.0 google.golang.org/grpc google.golang.org/grpc/attributes @@ -758,6 +758,7 @@ google.golang.org/grpc/encoding google.golang.org/grpc/encoding/gzip google.golang.org/grpc/encoding/internal google.golang.org/grpc/encoding/proto +google.golang.org/grpc/experimental/balancer/weight google.golang.org/grpc/experimental/stats google.golang.org/grpc/grpclog google.golang.org/grpc/grpclog/internal @@ -765,7 +766,6 @@ google.golang.org/grpc/health/grpc_health_v1 google.golang.org/grpc/internal google.golang.org/grpc/internal/backoff google.golang.org/grpc/internal/balancer/gracefulswitch -google.golang.org/grpc/internal/balancer/weight google.golang.org/grpc/internal/balancerload google.golang.org/grpc/internal/binarylog google.golang.org/grpc/internal/buffer @@ -792,6 +792,7 @@ google.golang.org/grpc/internal/stats google.golang.org/grpc/internal/status google.golang.org/grpc/internal/syscall google.golang.org/grpc/internal/transport +google.golang.org/grpc/internal/transport/internal google.golang.org/grpc/internal/transport/networktype google.golang.org/grpc/internal/transport/readyreader google.golang.org/grpc/internal/xds