Debian Codegraph @

launcher/registryauth/auth.go

raw
1 // Package registryauth contains functionalities to authenticate docker repo.
2 package registryauth
3
4 import (
5 "context"
6 "encoding/json"
7 "fmt"
8 "strings"
9
10 "cloud.google.com/go/compute/metadata"
11 "github.com/containerd/containerd/remotes"
12 "github.com/containerd/containerd/remotes/docker"
13 "golang.org/x/oauth2"
14 )
15
16 // RetrieveAuthToken takes in a metadata server client, and uses it to read the
17 // default service account token from a GCE VM and returns the token.
18 func RetrieveAuthToken(ctx context.Context, client *metadata.Client) (oauth2.Token, error) {
19 data, err := client.GetWithContext(ctx, "instance/service-accounts/default/token")
20 if err != nil {
21 return oauth2.Token{}, err
22 }
23
24 var token oauth2.Token
25 if err := json.Unmarshal([]byte(data), &token); err != nil {
26 return oauth2.Token{}, err
27 }
28
29 return token, nil
30 }
31
32 // Resolver returns a custom resolver that can use the token to authenticate with
33 // the repo.
34 func Resolver(token string) remotes.Resolver {
35 options := docker.ResolverOptions{}
36
37 credentials := func(host string) (string, string, error) {
38 // append the token if is talking to Artifact Registry or GCR Registry
39 if strings.HasSuffix(host, "docker.pkg.dev") || strings.HasSuffix(host, "gcr.io") {
40 return "_token", token, nil
41 }
42 return "", "", nil
43 }
44 authOpts := []docker.AuthorizerOpt{docker.WithAuthCreds(credentials)}
45 //nolint:staticcheck
46 options.Authorizer = docker.NewDockerAuthorizer(authOpts...)
47
48 return docker.NewResolver(options)
49 }
50
51 // RefreshResolver takes in a metadata server client, uses it to refresh the default service
52 // account token, and returns a custom resolver that can use the token to authenticate with
53 // the repo.
54 func RefreshResolver(ctx context.Context, client *metadata.Client) (remotes.Resolver, error) {
55 token, err := RetrieveAuthToken(ctx, client)
56 if err != nil {
57 return nil, fmt.Errorf("failed to retrieve auth token from metadata server: %v", err)
58 }
59
60 if token.Valid() {
61 return Resolver(token.AccessToken), nil
62 }
63
64 return nil, fmt.Errorf("invalid token from metadata server: %v", token)
65 }