-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgcred.go
409 lines (373 loc) · 13.1 KB
/
gcred.go
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
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
package gcreds4aws
import (
"context"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
"log/slog"
"net"
"net/http"
"os"
"strconv"
"strings"
"sync"
"time"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/aws/arn"
"github.com/aws/aws-sdk-go-v2/config"
"github.com/aws/aws-sdk-go-v2/service/ssm"
"google.golang.org/api/option"
)
var DefaultCredentialsManager = &CredentialsManager{}
func WithCredentials(ctx context.Context) option.ClientOption {
return DefaultCredentialsManager.WithCredentials(ctx)
}
func NewCredentials(ctx context.Context) (option.ClientOption, error) {
return DefaultCredentialsManager.NewCredentialsOption(ctx)
}
func SetSSMClient(client GetParameterAPIClient) {
DefaultCredentialsManager.SetSSMClient(client)
}
func SetLogger(logger *slog.Logger) {
DefaultCredentialsManager.SetLogger(logger)
}
func Close() error {
return DefaultCredentialsManager.Close()
}
type CredentialsManager struct {
logger *slog.Logger
mu sync.Mutex
awsCfg *aws.Config
ssmClient GetParameterAPIClient
cacheCredentialsExpiresAt time.Time
cacheCredentialsJSON []byte
cacheCredentials *credentials
proxyServer *http.Server
proxyListener net.Listener
proxyRegion string
proxyWaitGroup sync.WaitGroup
}
const (
CacheLifetimeSeconds = 4 * 60
ServiceAccountImpersonationLifetimeSeconds = 5 * 60
SubjectTokenTypeForAWS = "urn:ietf:params:aws:token-type:aws4_request"
)
func (mgr *CredentialsManager) Close() error {
mgr.mu.Lock()
defer mgr.mu.Unlock()
if mgr.proxyServer == nil {
return nil
}
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
if err := mgr.proxyServer.Shutdown(ctx); err != nil {
return fmt.Errorf("failed to shutdown proxy server: %w", err)
}
mgr.proxyServer = nil
if err := mgr.proxyListener.Close(); err != nil {
mgr.proxyListener = nil
return fmt.Errorf("failed to close proxy listener: %w", err)
}
mgr.proxyListener = nil
mgr.proxyWaitGroup.Wait()
mgr.cacheCredentialsExpiresAt = time.Time{}
mgr.cacheCredentialsJSON = nil
mgr.cacheCredentials = nil
return nil
}
type GetParameterAPIClient interface {
GetParameter(ctx context.Context, input *ssm.GetParameterInput, optFns ...func(*ssm.Options)) (*ssm.GetParameterOutput, error)
}
func (mgr *CredentialsManager) SetSSMClient(client GetParameterAPIClient) {
mgr.mu.Lock()
defer mgr.mu.Unlock()
mgr.ssmClient = client
}
func (mgr *CredentialsManager) SetLogger(logger *slog.Logger) {
mgr.mu.Lock()
defer mgr.mu.Unlock()
mgr.logger = logger
}
func (mgr *CredentialsManager) getLogger() *slog.Logger {
mgr.mu.Lock()
defer mgr.mu.Unlock()
if mgr.logger == nil {
mgr.logger = slog.New(slog.NewTextHandler(io.Discard, &slog.HandlerOptions{}))
}
return mgr.logger.With("module", "gcred4aws")
}
func (mgr *CredentialsManager) WithCredentials(ctx context.Context) option.ClientOption {
opt, err := mgr.NewCredentialsOption(ctx)
if err != nil {
panic(err)
}
return opt
}
func (mgr *CredentialsManager) NewCredentialsOption(ctx context.Context) (option.ClientOption, error) {
logger := mgr.getLogger()
if opt, ok := mgr.newCredentialsOptionFromCache(); ok {
logger.DebugContext(ctx, "use cached credentials")
return opt, nil
}
if path := os.Getenv("GOOGLE_APPLICATION_CREDENTIALS"); path != "" {
return mgr.newCredentialsOptionFromPath(ctx, path)
}
projectNumberStr := os.Getenv("GOOGLE_CLOUD_PROJECT_NUMBER")
poolID := os.Getenv("GOOGLE_CLOUD_POOL_ID")
providerID := os.Getenv("GOOGLE_CLOUD_PROVIDER_ID")
serviceAccountEmail := os.Getenv("GOOGLE_CLOUD_SERVICE_ACCOUNT_EMAIL")
if projectNumberStr == "" || poolID == "" || providerID == "" || serviceAccountEmail == "" {
return nil, errors.New("GOOGLE_APPLICATION_CREDENTIALS or Workload Identity Environment Variables(GOOGLE_CLOUD_PROJECT_NUMBER, GOOGLE_CLOUD_POOL_ID, GOOGLE_CLOUD_PROVIDER_ID, GOOGLE_CLOUD_SERVICE_ACCOUNT_EMAIL) is required")
}
projectNumber, err := strconv.Atoi(projectNumberStr)
if err != nil {
return nil, fmt.Errorf("failed to convert GOOGLE_CLOUD_PROJECT_NUMBER to int: %w", err)
}
cred := &credentials{
Type: "external_account",
Audience: fmt.Sprintf("//iam.googleapis.com/projects/%d/locations/global/workloadIdentityPools/%s/providers/%s", projectNumber, poolID, providerID),
SubjectTokenType: SubjectTokenTypeForAWS,
ServiceAccountImpersonationURL: fmt.Sprintf("https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/%s:generateAccessToken", serviceAccountEmail),
TokenURL: "https://sts.googleapis.com/v1/token",
}
bs, err := json.Marshal(cred)
if err != nil {
return nil, fmt.Errorf("failed to marshal credentials: %w", err)
}
return mgr.newCredentialsOptionFromBytes(ctx, bs)
}
func (mgr *CredentialsManager) newCredentialsOptionFromPath(ctx context.Context, path string) (option.ClientOption, error) {
if strings.HasPrefix(path, "arn:") {
return mgr.newCredentialsOptionFromArn(ctx, path)
}
bs, err := os.ReadFile(path)
if err != nil {
return nil, fmt.Errorf("failed to read credentials file: %w", err)
}
return mgr.newCredentialsOptionFromBytes(ctx, bs)
}
func (mgr *CredentialsManager) newCredentialsOptionFromArn(ctx context.Context, rawARN string) (option.ClientOption, error) {
arnObj, err := arn.Parse(rawARN)
if err != nil {
return nil, fmt.Errorf("failed to parse ARN: %w", err)
}
switch arnObj.Service {
case "ssm":
return mgr.newCredentialsOptionFromSSM(ctx, arnObj)
default:
return nil, fmt.Errorf("unsupported service: %s", arnObj.Service)
}
}
func (mgr *CredentialsManager) loadConfig(ctx context.Context) (aws.Config, error) {
if mgr.awsCfg != nil {
return *mgr.awsCfg, nil
}
cfg, err := config.LoadDefaultConfig(ctx)
if err != nil {
return aws.Config{}, fmt.Errorf("failed to load AWS config: %w", err)
}
mgr.awsCfg = &cfg
return cfg, nil
}
func (mgr *CredentialsManager) getSSMClient(ctx context.Context) (GetParameterAPIClient, error) {
mgr.mu.Lock()
defer mgr.mu.Unlock()
if mgr.ssmClient != nil {
return mgr.ssmClient, nil
}
cfg, err := mgr.loadConfig(ctx)
if err != nil {
return nil, err
}
client := ssm.NewFromConfig(cfg)
mgr.ssmClient = client
return client, nil
}
func (mgr *CredentialsManager) newCredentialsOptionFromCache() (option.ClientOption, bool) {
if bs, _, ok := mgr.getCachedCredentials(); ok {
return option.WithCredentialsJSON(bs), true
}
return nil, false
}
func (mgr *CredentialsManager) newCredentialsOptionFromSSM(ctx context.Context, arnObj arn.ARN) (option.ClientOption, error) {
client, err := mgr.getSSMClient(ctx)
if err != nil {
return nil, err
}
input := &ssm.GetParameterInput{
Name: aws.String(arnObj.Resource),
WithDecryption: aws.Bool(true),
}
output, err := client.GetParameter(ctx, input)
if err != nil {
return nil, fmt.Errorf("failed to get parameter: %w", err)
}
return mgr.newCredentialsOptionFromBytes(ctx, []byte(*output.Parameter.Value))
}
type credentials struct {
Type string `json:"type"`
Audience string `json:"audience"`
SubjectTokenType string `json:"subject_token_type"`
ServiceAccountImpersonationURL string `json:"service_account_impersonation_url"`
TokenURL string `json:"token_url"`
CredentialSource *credentialSource `json:"credential_source,omitempty"`
}
type credentialSource struct {
File string `json:"file,omitempty"`
URL string `json:"url,omitempty"`
EnvironmentID string `json:"environment_id,omitempty"`
RegionURL string `json:"region_url,omitempty"`
RegionalCredVerificationURL string `json:"regional_cred_verification_url,omitempty"`
}
func (cred *credentials) notTemporary() bool {
return cred.Type != "external_account"
}
func (mgr *CredentialsManager) newCredentialsOptionFromBytes(_ context.Context, bs []byte) (option.ClientOption, error) {
if len(bs) == 0 {
return nil, errors.New("empty credentials")
}
if decoded, err := base64.StdEncoding.DecodeString(string(bs)); err == nil {
bs = decoded
}
if !json.Valid(bs) {
return nil, errors.New("invalid credentials: not JSON")
}
var creds credentials
if err := json.Unmarshal(bs, &creds); err != nil {
return nil, fmt.Errorf("failed to unmarshal credentials: %w", err)
}
if creds.notTemporary() {
mgr.setCredentialsCache(bs, &creds)
return option.WithCredentialsJSON(bs), nil
}
rewrited, err := mgr.rewriteCredentialSource(&creds)
if err != nil {
return nil, fmt.Errorf("failed to rewrite credential source: %w", err)
}
bs, err = json.Marshal(rewrited)
if err != nil {
return nil, fmt.Errorf("failed to marshal credentials: %w", err)
}
mgr.setCredentialsCache(bs, rewrited)
return option.WithCredentialsJSON(bs), nil
}
func (mgr *CredentialsManager) rewriteCredentialSource(cred *credentials) (*credentials, error) {
// check from AWS Credential Source
if cred.SubjectTokenType != SubjectTokenTypeForAWS {
return cred, nil
}
if cred.CredentialSource != nil && cred.CredentialSource.File != "" {
return cred, nil
}
addr, err := mgr.getProxyServerAddress()
if err != nil {
return nil, fmt.Errorf("failed to get proxy server address: %w", err)
}
if cred.CredentialSource == nil {
cred.CredentialSource = &credentialSource{
EnvironmentID: "aws1",
}
}
cred.CredentialSource.URL = fmt.Sprintf("http://%s%s", addr, credentialsPath)
cred.CredentialSource.RegionURL = fmt.Sprintf("http://%s%s", addr, regionPath)
cred.CredentialSource.RegionalCredVerificationURL = "https://sts.{region}.amazonaws.com?Action=GetCallerIdentity&Version=2011-06-15"
return cred, nil
}
const (
regionPath = "/latest/meta-data/placement/availability-zone"
credentialsPath = "/latest/meta-data/iam/security-credentials"
)
func (mgr *CredentialsManager) getProxyServerAddress() (string, error) {
mgr.mu.Lock()
defer mgr.mu.Unlock()
if mgr.proxyServer == nil {
listener, err := net.Listen("tcp", ":0")
if err != nil {
return "", fmt.Errorf("failed to listen: %w", err)
}
mgr.proxyListener = listener
if region := os.Getenv("AWS_REGION"); region != "" {
mgr.proxyRegion = region
} else if region := os.Getenv("AWS_DEFAULT_REGION"); region != "" {
mgr.proxyRegion = region
} else {
mgr.proxyRegion = "us-east-1"
}
m := http.NewServeMux()
m.HandleFunc(regionPath, func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
w.Write([]byte(mgr.proxyRegion))
})
m.HandleFunc(credentialsPath, func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
w.Write([]byte("default"))
})
m.HandleFunc(credentialsPath+"/default", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
mgr.mu.Lock()
defer mgr.mu.Unlock()
awsCfg, err := mgr.loadConfig(r.Context())
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte(fmt.Sprintf(`{"Code": "Failed", "Message": "%s"}`, err.Error())))
return
}
cloned := awsCfg.Copy()
cloned.Region = mgr.proxyRegion
cred, err := cloned.Credentials.Retrieve(r.Context())
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte(fmt.Sprintf(`{"Code": "Failed", "Message": "%s"}`, err.Error())))
return
}
w.WriteHeader(http.StatusOK)
w.Write([]byte(fmt.Sprintf(
`{"Code": "Success", "LastUpdated":"%s", "Type": "AWS-HMAC", "AccessKeyId": "%s", "SecretAccessKey": "%s", "Token": "%s", "Expiration": "%s"}`,
time.Now().Format(time.RFC3339),
cred.AccessKeyID,
cred.SecretAccessKey,
cred.SessionToken,
cred.Expires.Format(time.RFC3339),
)))
})
mgr.proxyServer = &http.Server{
Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
logger := mgr.getLogger()
logger.Debug("receive request on credentials proxy server", "method", r.Method, "url", r.URL, "remote_addr", r.RemoteAddr)
m.ServeHTTP(w, r)
}),
}
mgr.proxyWaitGroup = sync.WaitGroup{}
mgr.proxyWaitGroup.Add(1)
go func() {
logger := mgr.getLogger()
logger.Info("start credentials proxy server", "addr", listener.Addr())
if err := mgr.proxyServer.Serve(listener); err != nil && !errors.Is(err, http.ErrServerClosed) {
logger.Error("failed to serve credentials proxy server", "error", err)
}
mgr.proxyWaitGroup.Done()
}()
}
port := mgr.proxyListener.Addr().(*net.TCPAddr).Port
return fmt.Sprintf("127.0.0.1:%d", port), nil
}
func (mgr *CredentialsManager) setCredentialsCache(bs []byte, cred *credentials) {
mgr.mu.Lock()
defer mgr.mu.Unlock()
mgr.cacheCredentialsJSON = bs
mgr.cacheCredentials = cred
mgr.cacheCredentialsExpiresAt = time.Now().Add(CacheLifetimeSeconds * time.Second)
}
func (mgr *CredentialsManager) getCachedCredentials() ([]byte, *credentials, bool) {
mgr.mu.Lock()
defer mgr.mu.Unlock()
if mgr.cacheCredentials == nil {
return nil, nil, false
}
if mgr.cacheCredentialsExpiresAt.Before(time.Now()) {
return nil, nil, false
}
return mgr.cacheCredentialsJSON, mgr.cacheCredentials, true
}