Debian Codegraph @

registry/remote/credentials/internal/config/config.go

raw
1 /*
2 Copyright The ORAS Authors.
3 Licensed under the Apache License, Version 2.0 (the "License");
4 you may not use this file except in compliance with the License.
5 You may obtain a copy of the License at
6
7 http://www.apache.org/licenses/LICENSE-2.0
8
9 Unless required by applicable law or agreed to in writing, software
10 distributed under the License is distributed on an "AS IS" BASIS,
11 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 See the License for the specific language governing permissions and
13 limitations under the License.
14 */
15
16 package config
17
18 import (
19 "bytes"
20 "encoding/base64"
21 "encoding/json"
22 "errors"
23 "fmt"
24 "io"
25 "os"
26 "path/filepath"
27 "strings"
28 "sync"
29
30 "oras.land/oras-go/v2/registry/remote/auth"
31 "oras.land/oras-go/v2/registry/remote/credentials/internal/ioutil"
32 )
33
34 const (
35 // configFieldAuths is the "auths" field in the config file.
36 // Reference: https://github.com/docker/cli/blob/v24.0.0-beta.2/cli/config/configfile/file.go#L19
37 configFieldAuths = "auths"
38 // configFieldCredentialsStore is the "credsStore" field in the config file.
39 configFieldCredentialsStore = "credsStore"
40 // configFieldCredentialHelpers is the "credHelpers" field in the config file.
41 configFieldCredentialHelpers = "credHelpers"
42 )
43
44 // ErrInvalidConfigFormat is returned when the config format is invalid.
45 var ErrInvalidConfigFormat = errors.New("invalid config format")
46
47 // AuthConfig contains authorization information for connecting to a Registry.
48 // References:
49 // - https://github.com/docker/cli/blob/v24.0.0-beta.2/cli/config/configfile/file.go#L17-L45
50 // - https://github.com/docker/cli/blob/v24.0.0-beta.2/cli/config/types/authconfig.go#L3-L22
51 type AuthConfig struct {
52 // Auth is a base64-encoded string of "{username}:{password}".
53 Auth string `json:"auth,omitempty"`
54 // IdentityToken is used to authenticate the user and get an access token
55 // for the registry.
56 IdentityToken string `json:"identitytoken,omitempty"`
57 // RegistryToken is a bearer token to be sent to a registry.
58 RegistryToken string `json:"registrytoken,omitempty"`
59
60 Username string `json:"username,omitempty"` // legacy field for compatibility
61 Password string `json:"password,omitempty"` // legacy field for compatibility
62 }
63
64 // NewAuthConfig creates an authConfig based on cred.
65 func NewAuthConfig(cred auth.Credential) AuthConfig {
66 return AuthConfig{
67 Auth: encodeAuth(cred.Username, cred.Password),
68 IdentityToken: cred.RefreshToken,
69 RegistryToken: cred.AccessToken,
70 }
71 }
72
73 // Credential returns an auth.Credential based on ac.
74 func (ac AuthConfig) Credential() (auth.Credential, error) {
75 cred := auth.Credential{
76 Username: ac.Username,
77 Password: ac.Password,
78 RefreshToken: ac.IdentityToken,
79 AccessToken: ac.RegistryToken,
80 }
81 if ac.Auth != "" {
82 var err error
83 // override username and password
84 cred.Username, cred.Password, err = decodeAuth(ac.Auth)
85 if err != nil {
86 return auth.EmptyCredential, fmt.Errorf("failed to decode auth field: %w: %v", ErrInvalidConfigFormat, err)
87 }
88 }
89 return cred, nil
90 }
91
92 // Config represents a docker configuration file.
93 // References:
94 // - https://docs.docker.com/engine/reference/commandline/cli/#docker-cli-configuration-file-configjson-properties
95 // - https://github.com/docker/cli/blob/v24.0.0-beta.2/cli/config/configfile/file.go#L17-L44
96 type Config struct {
97 // path is the path to the config file.
98 path string
99 // rwLock is a read-write-lock for the file store.
100 rwLock sync.RWMutex
101 // content is the content of the config file.
102 // Reference: https://github.com/docker/cli/blob/v24.0.0-beta.2/cli/config/configfile/file.go#L17-L44
103 content map[string]json.RawMessage
104 // authsCache is a cache of the auths field of the config.
105 // Reference: https://github.com/docker/cli/blob/v24.0.0-beta.2/cli/config/configfile/file.go#L19
106 authsCache map[string]json.RawMessage
107 // credentialsStore is the credsStore field of the config.
108 // Reference: https://github.com/docker/cli/blob/v24.0.0-beta.2/cli/config/configfile/file.go#L28
109 credentialsStore string
110 // credentialHelpers is the credHelpers field of the config.
111 // Reference: https://github.com/docker/cli/blob/v24.0.0-beta.2/cli/config/configfile/file.go#L29
112 credentialHelpers map[string]string
113 }
114
115 // Load loads Config from the given config path.
116 func Load(configPath string) (*Config, error) {
117 cfg := &Config{path: configPath}
118 configFile, err := os.Open(configPath)
119 if err != nil {
120 if os.IsNotExist(err) {
121 // init content and caches if the content file does not exist
122 cfg.content = make(map[string]json.RawMessage)
123 cfg.authsCache = make(map[string]json.RawMessage)
124 return cfg, nil
125 }
126 return nil, fmt.Errorf("failed to open config file at %s: %w", configPath, err)
127 }
128 defer configFile.Close()
129
130 // decode config content if the config file exists
131 if err := json.NewDecoder(configFile).Decode(&cfg.content); err != nil {
132 if errors.Is(err, io.EOF) {
133 // empty or whitespace only file
134 cfg.content = make(map[string]json.RawMessage)
135 cfg.authsCache = make(map[string]json.RawMessage)
136 return cfg, nil
137 }
138 return nil, fmt.Errorf("failed to decode config file %s: %w: %v", configPath, ErrInvalidConfigFormat, err)
139 }
140
141 if credsStoreBytes, ok := cfg.content[configFieldCredentialsStore]; ok {
142 if err := json.Unmarshal(credsStoreBytes, &cfg.credentialsStore); err != nil {
143 return nil, fmt.Errorf("failed to unmarshal creds store field: %w: %v", ErrInvalidConfigFormat, err)
144 }
145 }
146
147 if credHelpersBytes, ok := cfg.content[configFieldCredentialHelpers]; ok {
148 if err := json.Unmarshal(credHelpersBytes, &cfg.credentialHelpers); err != nil {
149 return nil, fmt.Errorf("failed to unmarshal cred helpers field: %w: %v", ErrInvalidConfigFormat, err)
150 }
151 }
152
153 if authsBytes, ok := cfg.content[configFieldAuths]; ok {
154 if err := json.Unmarshal(authsBytes, &cfg.authsCache); err != nil {
155 return nil, fmt.Errorf("failed to unmarshal auths field: %w: %v", ErrInvalidConfigFormat, err)
156 }
157 }
158 if cfg.authsCache == nil {
159 cfg.authsCache = make(map[string]json.RawMessage)
160 }
161
162 return cfg, nil
163 }
164
165 // GetAuthConfig returns an auth.Credential for serverAddress.
166 func (cfg *Config) GetCredential(serverAddress string) (auth.Credential, error) {
167 cfg.rwLock.RLock()
168 defer cfg.rwLock.RUnlock()
169
170 authCfgBytes, ok := cfg.authsCache[serverAddress]
171 if !ok {
172 // NOTE: the auth key for the server address may have been stored with
173 // a http/https prefix in legacy config files, e.g. "registry.example.com"
174 // can be stored as "https://registry.example.com/".
175 var matched bool
176 for addr, auth := range cfg.authsCache {
177 if ToHostname(addr) == serverAddress {
178 matched = true
179 authCfgBytes = auth
180 break
181 }
182 }
183 if !matched {
184 return auth.EmptyCredential, nil
185 }
186 }
187 var authCfg AuthConfig
188 if err := json.Unmarshal(authCfgBytes, &authCfg); err != nil {
189 return auth.EmptyCredential, fmt.Errorf("failed to unmarshal auth field: %w: %v", ErrInvalidConfigFormat, err)
190 }
191 return authCfg.Credential()
192 }
193
194 // PutAuthConfig puts cred for serverAddress.
195 func (cfg *Config) PutCredential(serverAddress string, cred auth.Credential) error {
196 cfg.rwLock.Lock()
197 defer cfg.rwLock.Unlock()
198
199 authCfg := NewAuthConfig(cred)
200 authCfgBytes, err := json.Marshal(authCfg)
201 if err != nil {
202 return fmt.Errorf("failed to marshal auth field: %w", err)
203 }
204 cfg.authsCache[serverAddress] = authCfgBytes
205 return cfg.saveFile()
206 }
207
208 // DeleteAuthConfig deletes the corresponding credential for serverAddress.
209 func (cfg *Config) DeleteCredential(serverAddress string) error {
210 cfg.rwLock.Lock()
211 defer cfg.rwLock.Unlock()
212
213 if _, ok := cfg.authsCache[serverAddress]; !ok {
214 // no ops
215 return nil
216 }
217 delete(cfg.authsCache, serverAddress)
218 return cfg.saveFile()
219 }
220
221 // GetCredentialHelper returns the credential helpers for serverAddress.
222 func (cfg *Config) GetCredentialHelper(serverAddress string) string {
223 return cfg.credentialHelpers[serverAddress]
224 }
225
226 // CredentialsStore returns the configured credentials store.
227 func (cfg *Config) CredentialsStore() string {
228 cfg.rwLock.RLock()
229 defer cfg.rwLock.RUnlock()
230
231 return cfg.credentialsStore
232 }
233
234 // Path returns the path to the config file.
235 func (cfg *Config) Path() string {
236 return cfg.path
237 }
238
239 // SetCredentialsStore puts the configured credentials store.
240 func (cfg *Config) SetCredentialsStore(credsStore string) error {
241 cfg.rwLock.Lock()
242 defer cfg.rwLock.Unlock()
243
244 cfg.credentialsStore = credsStore
245 return cfg.saveFile()
246 }
247
248 // IsAuthConfigured returns whether there is authentication configured in this
249 // config file or not.
250 func (cfg *Config) IsAuthConfigured() bool {
251 return cfg.credentialsStore != "" ||
252 len(cfg.credentialHelpers) > 0 ||
253 len(cfg.authsCache) > 0
254 }
255
256 // saveFile saves Config into the file.
257 func (cfg *Config) saveFile() (returnErr error) {
258 // marshal content
259 // credentialHelpers is skipped as it's never set
260 if cfg.credentialsStore != "" {
261 credsStoreBytes, err := json.Marshal(cfg.credentialsStore)
262 if err != nil {
263 return fmt.Errorf("failed to marshal creds store: %w", err)
264 }
265 cfg.content[configFieldCredentialsStore] = credsStoreBytes
266 } else {
267 // omit empty
268 delete(cfg.content, configFieldCredentialsStore)
269 }
270 authsBytes, err := json.Marshal(cfg.authsCache)
271 if err != nil {
272 return fmt.Errorf("failed to marshal credentials: %w", err)
273 }
274 cfg.content[configFieldAuths] = authsBytes
275 jsonBytes, err := json.MarshalIndent(cfg.content, "", "\t")
276 if err != nil {
277 return fmt.Errorf("failed to marshal config: %w", err)
278 }
279
280 // write the content to a ingest file for atomicity
281 configDir := filepath.Dir(cfg.path)
282 if err := os.MkdirAll(configDir, 0700); err != nil {
283 return fmt.Errorf("failed to make directory %s: %w", configDir, err)
284 }
285 ingest, err := ioutil.Ingest(configDir, bytes.NewReader(jsonBytes))
286 if err != nil {
287 return fmt.Errorf("failed to save config file: %w", err)
288 }
289 defer func() {
290 if returnErr != nil {
291 // clean up the ingest file in case of error
292 os.Remove(ingest)
293 }
294 }()
295
296 // overwrite the config file
297 if err := os.Rename(ingest, cfg.path); err != nil {
298 return fmt.Errorf("failed to save config file: %w", err)
299 }
300 return nil
301 }
302
303 // encodeAuth base64-encodes username and password into base64(username:password).
304 func encodeAuth(username, password string) string {
305 if username == "" && password == "" {
306 return ""
307 }
308 return base64.StdEncoding.EncodeToString([]byte(username + ":" + password))
309 }
310
311 // decodeAuth decodes a base64 encoded string and returns username and password.
312 func decodeAuth(authStr string) (username string, password string, err error) {
313 if authStr == "" {
314 return "", "", nil
315 }
316
317 decoded, err := base64.StdEncoding.DecodeString(authStr)
318 if err != nil {
319 return "", "", err
320 }
321 decodedStr := string(decoded)
322 username, password, ok := strings.Cut(decodedStr, ":")
323 if !ok {
324 return "", "", fmt.Errorf("auth '%s' does not conform the base64(username:password) format", decodedStr)
325 }
326 return username, password, nil
327 }
328
329 // ToHostname normalizes a server address to just its hostname, removing
330 // the scheme and the path parts.
331 // It is used to match keys in the auths map, which may be either stored as
332 // hostname or as hostname including scheme (in legacy docker config files).
333 // Reference: https://github.com/docker/cli/blob/v24.0.6/cli/config/credentials/file_store.go#L71
334 func ToHostname(addr string) string {
335 addr = strings.TrimPrefix(addr, "http://")
336 addr = strings.TrimPrefix(addr, "https://")
337 addr, _, _ = strings.Cut(addr, "/")
338 return addr
339 }