Debian Codegraph @

registry/remote/credentials/memory_store.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 credentials
17
18 import (
19 "context"
20 "encoding/json"
21 "fmt"
22 "sync"
23
24 "oras.land/oras-go/v2/registry/remote/auth"
25 "oras.land/oras-go/v2/registry/remote/credentials/internal/config"
26 )
27
28 // memoryStore is a store that keeps credentials in memory.
29 type memoryStore struct {
30 store sync.Map
31 }
32
33 // NewMemoryStore creates a new in-memory credentials store.
34 func NewMemoryStore() Store {
35 return &memoryStore{}
36 }
37
38 // NewMemoryStoreFromDockerConfig creates a new in-memory credentials store from the given configuration.
39 //
40 // Reference: https://docs.docker.com/engine/reference/commandline/cli/#docker-cli-configuration-file-configjson-properties
41 func NewMemoryStoreFromDockerConfig(c []byte) (Store, error) {
42 cfg := struct {
43 Auths map[string]config.AuthConfig `json:"auths"`
44 }{}
45 if err := json.Unmarshal(c, &cfg); err != nil {
46 return nil, fmt.Errorf("failed to unmarshal auth field: %w: %v", config.ErrInvalidConfigFormat, err)
47 }
48
49 s := &memoryStore{}
50 for addr, auth := range cfg.Auths {
51 // Normalize the auth key to hostname.
52 hostname := config.ToHostname(addr)
53 cred, err := auth.Credential()
54 if err != nil {
55 return nil, err
56 }
57 _, _ = s.store.LoadOrStore(hostname, cred)
58 }
59 return s, nil
60 }
61
62 // Get retrieves credentials from the store for the given server address.
63 func (ms *memoryStore) Get(_ context.Context, serverAddress string) (auth.Credential, error) {
64 cred, found := ms.store.Load(serverAddress)
65 if !found {
66 return auth.EmptyCredential, nil
67 }
68 return cred.(auth.Credential), nil
69 }
70
71 // Put saves credentials into the store for the given server address.
72 func (ms *memoryStore) Put(_ context.Context, serverAddress string, cred auth.Credential) error {
73 ms.store.Store(serverAddress, cred)
74 return nil
75 }
76
77 // Delete removes credentials from the store for the given server address.
78 func (ms *memoryStore) Delete(_ context.Context, serverAddress string) error {
79 ms.store.Delete(serverAddress)
80 return nil
81 }