compute.go

 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
15package credentials
16
17import (
18	"context"
19	"encoding/json"
20	"errors"
21	"fmt"
22	"net/url"
23	"strings"
24	"time"
25
26	"cloud.google.com/go/auth"
27	"cloud.google.com/go/compute/metadata"
28)
29
30var (
31	computeTokenMetadata = map[string]interface{}{
32		"auth.google.tokenSource":    "compute-metadata",
33		"auth.google.serviceAccount": "default",
34	}
35	computeTokenURI = "instance/service-accounts/default/token"
36)
37
38// computeTokenProvider creates a [cloud.google.com/go/auth.TokenProvider] that
39// uses the metadata service to retrieve tokens.
40func computeTokenProvider(opts *DetectOptions, client *metadata.Client) auth.TokenProvider {
41	return auth.NewCachedTokenProvider(&computeProvider{
42		scopes: opts.Scopes,
43		client: client,
44	}, &auth.CachedTokenProviderOptions{
45		ExpireEarly:         opts.EarlyTokenRefresh,
46		DisableAsyncRefresh: opts.DisableAsyncRefresh,
47	})
48}
49
50// computeProvider fetches tokens from the google cloud metadata service.
51type computeProvider struct {
52	scopes []string
53	client *metadata.Client
54}
55
56type metadataTokenResp struct {
57	AccessToken  string `json:"access_token"`
58	ExpiresInSec int    `json:"expires_in"`
59	TokenType    string `json:"token_type"`
60}
61
62func (cs *computeProvider) Token(ctx context.Context) (*auth.Token, error) {
63	tokenURI, err := url.Parse(computeTokenURI)
64	if err != nil {
65		return nil, err
66	}
67	if len(cs.scopes) > 0 {
68		v := url.Values{}
69		v.Set("scopes", strings.Join(cs.scopes, ","))
70		tokenURI.RawQuery = v.Encode()
71	}
72	tokenJSON, err := cs.client.GetWithContext(ctx, tokenURI.String())
73	if err != nil {
74		return nil, fmt.Errorf("credentials: cannot fetch token: %w", err)
75	}
76	var res metadataTokenResp
77	if err := json.NewDecoder(strings.NewReader(tokenJSON)).Decode(&res); err != nil {
78		return nil, fmt.Errorf("credentials: invalid token JSON from metadata: %w", err)
79	}
80	if res.ExpiresInSec == 0 || res.AccessToken == "" {
81		return nil, errors.New("credentials: incomplete token received from metadata")
82	}
83	return &auth.Token{
84		Value:    res.AccessToken,
85		Type:     res.TokenType,
86		Expiry:   time.Now().Add(time.Duration(res.ExpiresInSec) * time.Second),
87		Metadata: computeTokenMetadata,
88	}, nil
89
90}