-
Notifications
You must be signed in to change notification settings - Fork 2
/
env.go
190 lines (160 loc) · 4.48 KB
/
env.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
package main
import (
"bytes"
"context"
"encoding/base64"
"fmt"
"net/url"
"os"
"regexp"
"strings"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/config"
"github.com/aws/aws-sdk-go-v2/credentials/stscreds"
"github.com/aws/aws-sdk-go-v2/service/ecr"
"github.com/aws/aws-sdk-go-v2/service/sts"
docker_credentials "github.com/docker/docker-credential-helpers/credentials"
)
var ecrHostname = regexp.MustCompile(`^[0-9]+\.dkr\.ecr\.[-a-z0-9]+\.amazonaws\.com$`)
var ghcrHostname = regexp.MustCompile(`^ghcr\.io$`)
const (
defaultScheme = "https://"
envPrefix = "DOCKER"
envUsernameSuffix = "USR"
envPasswordSuffix = "PSW"
envSeparator = "_"
envIgnoreLogin = "IGNORE_DOCKER_LOGIN"
)
type NotSupportedError struct{}
func (m *NotSupportedError) Error() string {
return "not supported"
}
// Env implements the Docker credentials Helper interface.
type Env struct{}
// Add implements the set verb
func (*Env) Add(*docker_credentials.Credentials) error {
switch {
case os.Getenv(envIgnoreLogin) != "":
return nil
default:
return fmt.Errorf("add: %w", &NotSupportedError{})
}
}
// Delete implements the erase verb
func (*Env) Delete(string) error {
switch {
case os.Getenv(envIgnoreLogin) != "":
return nil
default:
return fmt.Errorf("delete: %w", &NotSupportedError{})
}
}
// List implements the list verb
func (*Env) List() (map[string]string, error) {
return nil, fmt.Errorf("list: %w", &NotSupportedError{})
}
// Get implements the get verb
func (e *Env) Get(serverURL string) (username string, password string, err error) {
var (
hostname string
ok bool
)
hostname, err = getHostname(serverURL)
if err != nil {
return
}
if username, password, ok = getEnvCredentials(hostname); ok {
return
}
if ecrHostname.MatchString(hostname) {
// This is an AWS ECR Docker Registry: <account-id>.dkr.ecr.<region>.amazonaws.com
username, password, err = getEcrToken()
return
}
if ghcrHostname.MatchString(hostname) {
// This is a GitHub Container Registry: ghcr.io
if token, found := os.LookupEnv("GITHUB_TOKEN"); found {
username = "github"
password = token
}
return
}
return
}
func getHostname(serverURL string) (hostname string, err error) {
var server *url.URL
server, err = url.Parse(defaultScheme + strings.TrimPrefix(serverURL, defaultScheme))
if err != nil {
return
}
hostname = server.Hostname()
return
}
func getEnvVariables(labels []string, offset int) (envUsername, envPassword string) {
if offset < 0 {
offset = 0
} else if offset > len(labels) {
offset = len(labels)
}
envHostname := strings.Join(labels[offset:], envSeparator)
envUsername = strings.Join([]string{envPrefix, envHostname, envUsernameSuffix}, envSeparator)
envPassword = strings.Join([]string{envPrefix, envHostname, envPasswordSuffix}, envSeparator)
return
}
func getEnvCredentials(hostname string) (username, password string, found bool) {
hostname = strings.ReplaceAll(hostname, "-", "_")
labels := strings.Split(hostname, ".")
for i := 0; i <= len(labels); i++ {
envUsername, envPassword := getEnvVariables(labels, i)
if username, found = os.LookupEnv(envUsername); found {
if password, found = os.LookupEnv(envPassword); found {
break
}
}
}
return
}
func getEcrToken() (username, password string, err error) {
ctx := context.TODO()
cfg, err := config.LoadDefaultConfig(ctx)
if err != nil {
return
}
if roleArn := getRoleArn(cfg.ConfigSources...); roleArn != "" {
stsSvc := sts.NewFromConfig(cfg)
creds := stscreds.NewAssumeRoleProvider(stsSvc, roleArn)
cfg.Credentials = aws.NewCredentialsCache(creds)
}
client := ecr.NewFromConfig(cfg)
output, err := client.GetAuthorizationToken(ctx, nil)
if err != nil {
return
}
for _, authData := range output.AuthorizationData {
// authData.AuthorizationToken is a base64-encoded username:password string,
// where the username is always expected to be "AWS".
var tokenBytes []byte
tokenBytes, err = base64.StdEncoding.DecodeString(*authData.AuthorizationToken)
if err != nil {
return
}
token := bytes.SplitN(tokenBytes, []byte{':'}, 2)
username, password = string(token[0]), string(token[1])
}
return
}
func getRoleArn(configSources ...interface{}) (roleARN string) {
for _, x := range configSources {
switch impl := x.(type) {
case config.EnvConfig:
if impl.RoleARN != "" {
return strings.TrimSpace(impl.RoleARN)
}
case config.SharedConfig:
if impl.RoleARN != "" {
return strings.TrimSpace(impl.RoleARN)
}
}
}
return
}