-
Notifications
You must be signed in to change notification settings - Fork 2.4k
/
Copy pathecr.go
76 lines (67 loc) · 2.08 KB
/
ecr.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
package ecr
import (
"context"
"encoding/base64"
"strings"
"github.com/aquasecurity/trivy/pkg/fanal/types"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/credentials"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/ecr"
"github.com/aws/aws-sdk-go/service/ecr/ecriface"
"golang.org/x/xerrors"
)
const ecrURL = "amazonaws.com"
type ECR struct {
Client ecriface.ECRAPI
}
func getSession(option types.DockerOption) (*session.Session, error) {
// create custom credential information if option is valid
if option.AwsSecretKey != "" && option.AwsAccessKey != "" && option.AwsRegion != "" {
return session.NewSessionWithOptions(
session.Options{
Config: aws.Config{
Region: aws.String(option.AwsRegion),
Credentials: credentials.NewStaticCredentialsFromCreds(
credentials.Value{
AccessKeyID: option.AwsAccessKey,
SecretAccessKey: option.AwsSecretKey,
SessionToken: option.AwsSessionToken,
},
),
},
})
}
// use shared configuration normally
return session.NewSessionWithOptions(session.Options{
SharedConfigState: session.SharedConfigEnable,
})
}
func (e *ECR) CheckOptions(domain string, option types.DockerOption) error {
if !strings.HasSuffix(domain, ecrURL) {
return xerrors.Errorf("ECR : %w", types.InvalidURLPattern)
}
sess := session.Must(getSession(option))
svc := ecr.New(sess)
e.Client = svc
return nil
}
func (e *ECR) GetCredential(ctx context.Context) (username, password string, err error) {
input := &ecr.GetAuthorizationTokenInput{}
result, err := e.Client.GetAuthorizationTokenWithContext(ctx, input)
if err != nil {
return "", "", xerrors.Errorf("failed to get authorization token: %w", err)
}
for _, data := range result.AuthorizationData {
b, err := base64.StdEncoding.DecodeString(*data.AuthorizationToken)
if err != nil {
return "", "", xerrors.Errorf("base64 decode failed: %w", err)
}
// e.g. AWS:eyJwYXlsb2...
split := strings.SplitN(string(b), ":", 2)
if len(split) == 2 {
return split[0], split[1], nil
}
}
return "", "", nil
}