-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
176 lines (149 loc) · 5.26 KB
/
main.go
File metadata and controls
176 lines (149 loc) · 5.26 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
/*
Implements the kubelet image credential provider request flow by taking in a
service account token and exchanging it for a Google cloud token via OIDC,
which can be used to pull images from GAR.
https://kubernetes.io/docs/tasks/administer-cluster/kubelet-credential-provider/
Takes from stdin a json string like this:
{
"apiVersion": "credentialprovider.kubelet.k8s.io/v1",
"kind": "CredentialProviderRequest",
"image": "REGION-docker.pkg.dev/GOOGLE_PROJECT_ID/GAR_REPO/alpine:latest",
"serviceAccountToken": "SERVICE_ACCOUNT_TOKEN",
"serviceAccountAnnotations": {}
}
Returns to stdout a json string like this:
{
"apiVersion": "credentialprovider.kubelet.k8s.io/v1",
"kind": "CredentialProviderResponse",
"cacheTypeKey": "Image",
"cacheDuration": "1h0m0s",
"auth": {
"REGION-docker.pkg.dev": {
"username": "oauth2accesstoken",
"password": "GCP_ACCESS_TOKEN"
}
}
}
The credential provider config must be set up with requireServiceAccount set to
true and both a GCP_AUDIENCE env mapping and serviceAccountTokenAudience set to
the full resource name of the Workload Identity Pool provider being used in GCP
for the token exchange. The Workload Identity Pool provider can be configured
with uploaded jwks to avoid needing to expose a public URL from the cluster for
token verification.
*/
package main
import (
"context"
"encoding/json"
"fmt"
"io"
"log"
"os"
"time"
containername "github.com/google/go-containerregistry/pkg/name"
"google.golang.org/api/option"
stsv1 "google.golang.org/api/sts/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
credentialproviderapi "k8s.io/kubelet/pkg/apis/credentialprovider/v1"
)
type Provider struct {
stsService *stsv1.Service
}
func NewProvider(ctx context.Context) (*Provider, error) {
stsService, err := stsv1.NewService(ctx, option.WithoutAuthentication())
if err != nil {
return nil, fmt.Errorf("failed to create sts service: %w", err)
}
return &Provider{stsService: stsService}, nil
}
func main() {
ctx := context.Background()
p, err := NewProvider(ctx)
if err != nil {
log.Fatalf("ERROR: %s", err)
}
if err := p.run(os.Stdin, os.Stdout); err != nil {
log.Fatalf("ERROR: %s", err)
}
}
func (p *Provider) run(r io.Reader, w io.Writer) error {
stdinBytes, err := io.ReadAll(r)
if err != nil {
return fmt.Errorf("reading input: %w", err)
}
var req credentialproviderapi.CredentialProviderRequest
err = json.Unmarshal(stdinBytes, &req)
if err != nil {
return fmt.Errorf("unmarshaling auth credential request: %w", err)
}
if req.ServiceAccountToken == "" {
return fmt.Errorf("must provide service account token in request")
}
containerref, err := containername.ParseReference(req.Image)
if err != nil {
return fmt.Errorf("parsing image: %w", err)
}
host := containerref.Context().RegistryStr()
token, err := p.exchangeToken(req.ServiceAccountToken)
if err != nil {
return fmt.Errorf("exchanging token: %w", err)
}
resp := &credentialproviderapi.CredentialProviderResponse{
TypeMeta: metav1.TypeMeta{
APIVersion: "credentialprovider.kubelet.k8s.io/v1",
Kind: "CredentialProviderResponse",
},
Auth: map[string]credentialproviderapi.AuthConfig{
host: {
Username: "oauth2accesstoken",
Password: token.AccessToken,
},
},
}
cacheDurationBuffer := 60 * time.Second
cacheDuration := max((time.Duration(token.ExpiresIn)*time.Second)-cacheDurationBuffer, 0)
resp.CacheDuration = &metav1.Duration{Duration: cacheDuration}
cacheKey, err := getCacheKeyType()
if err != nil {
return fmt.Errorf("getting cacheKey: %w", err)
}
resp.CacheKeyType = cacheKey
return json.NewEncoder(w).Encode(resp)
}
func (p *Provider) exchangeToken(subjectToken string) (*stsv1.GoogleIdentityStsV1ExchangeTokenResponse, error) {
audience := os.Getenv("GCP_AUDIENCE")
if audience == "" {
return nil, fmt.Errorf("GCP_AUDIENCE environment variable was not set")
}
stsTokenResp, err := p.stsService.V1.Token(&stsv1.GoogleIdentityStsV1ExchangeTokenRequest{
SubjectToken: subjectToken,
SubjectTokenType: "urn:ietf:params:oauth:token-type:jwt",
RequestedTokenType: "urn:ietf:params:oauth:token-type:access_token",
GrantType: "urn:ietf:params:oauth:grant-type:token-exchange",
Scope: "https://www.googleapis.com/auth/cloud-platform",
Audience: audience,
}).Do()
if err != nil {
return nil, fmt.Errorf("failed to exchange k8s service account token for google federated token: %w", err)
}
if stsTokenResp == nil || stsTokenResp.AccessToken == "" {
return nil, fmt.Errorf("empty token response when exchanging k8s service account token for google federated token")
}
return stsTokenResp, nil
}
// https://github.com/kubernetes/cloud-provider-gcp/blob/0a7773256f8929150cd4ef12b6e2ffa485eb9cd2/cmd/auth-provider-gcp/provider/provider.go#L93
func getCacheKeyType() (credentialproviderapi.PluginCacheKeyType, error) {
keyType := os.Getenv("KUBE_SIDECAR_CACHE_TYPE")
switch keyType {
case "":
return credentialproviderapi.ImagePluginCacheKeyType, nil
case "image":
return credentialproviderapi.ImagePluginCacheKeyType, nil
case "registry":
return credentialproviderapi.RegistryPluginCacheKeyType, nil
case "global":
return credentialproviderapi.GlobalPluginCacheKeyType, nil
default:
return "", fmt.Errorf("unknown cache key %q", keyType)
}
}