compute.go 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. // Copyright 2023 Google LLC
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package credentials
  15. import (
  16. "context"
  17. "encoding/json"
  18. "errors"
  19. "fmt"
  20. "net/url"
  21. "strings"
  22. "time"
  23. "cloud.google.com/go/auth"
  24. "cloud.google.com/go/compute/metadata"
  25. )
  26. var (
  27. computeTokenMetadata = map[string]interface{}{
  28. "auth.google.tokenSource": "compute-metadata",
  29. "auth.google.serviceAccount": "default",
  30. }
  31. computeTokenURI = "instance/service-accounts/default/token"
  32. )
  33. // computeTokenProvider creates a [cloud.google.com/go/auth.TokenProvider] that
  34. // uses the metadata service to retrieve tokens.
  35. func computeTokenProvider(opts *DetectOptions) auth.TokenProvider {
  36. return auth.NewCachedTokenProvider(computeProvider{scopes: opts.Scopes}, &auth.CachedTokenProviderOptions{
  37. ExpireEarly: opts.EarlyTokenRefresh,
  38. DisableAsyncRefresh: opts.DisableAsyncRefresh,
  39. })
  40. }
  41. // computeProvider fetches tokens from the google cloud metadata service.
  42. type computeProvider struct {
  43. scopes []string
  44. }
  45. type metadataTokenResp struct {
  46. AccessToken string `json:"access_token"`
  47. ExpiresInSec int `json:"expires_in"`
  48. TokenType string `json:"token_type"`
  49. }
  50. func (cs computeProvider) Token(ctx context.Context) (*auth.Token, error) {
  51. tokenURI, err := url.Parse(computeTokenURI)
  52. if err != nil {
  53. return nil, err
  54. }
  55. if len(cs.scopes) > 0 {
  56. v := url.Values{}
  57. v.Set("scopes", strings.Join(cs.scopes, ","))
  58. tokenURI.RawQuery = v.Encode()
  59. }
  60. tokenJSON, err := metadata.GetWithContext(ctx, tokenURI.String())
  61. if err != nil {
  62. return nil, fmt.Errorf("credentials: cannot fetch token: %w", err)
  63. }
  64. var res metadataTokenResp
  65. if err := json.NewDecoder(strings.NewReader(tokenJSON)).Decode(&res); err != nil {
  66. return nil, fmt.Errorf("credentials: invalid token JSON from metadata: %w", err)
  67. }
  68. if res.ExpiresInSec == 0 || res.AccessToken == "" {
  69. return nil, errors.New("credentials: incomplete token received from metadata")
  70. }
  71. return &auth.Token{
  72. Value: res.AccessToken,
  73. Type: res.TokenType,
  74. Expiry: time.Now().Add(time.Duration(res.ExpiresInSec) * time.Second),
  75. Metadata: computeTokenMetadata,
  76. }, nil
  77. }