-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathstore.go
More file actions
219 lines (189 loc) · 5.8 KB
/
store.go
File metadata and controls
219 lines (189 loc) · 5.8 KB
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
// Copyright 2025-2026 Docker, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package credentialhelper
import (
"context"
"encoding/json"
"fmt"
"io"
"net"
"os"
"os/user"
"path"
"runtime"
"strings"
"time"
"github.com/docker/docker-credential-helpers/client"
"github.com/docker/secrets-engine/plugin"
)
// KeyRewriter provides a credential-helper credential username and ID (a server URL).
// The server URL can consist of an http or https prefix and may end with
// a trailing forward-slash.
//
// For example:
//
// {
// "ServerURL": "http://127.0.0.1/test",
// "Username": "bob"
// }
//
// Errors returned by a KeyRewriter will simply log and the current credential
// will be skipped when [GetSecrets] is called.
//
// It is recommended to use [DefaultKeyRewriter] for credential-helper
// credentials when writing custom rules in your [KeyRewriter].
type KeyRewriter func(serverURL, username string) (plugin.ID, error)
type credentialHelperStore struct {
client.ProgramFunc
plugin.Logger
rewriter KeyRewriter
}
// DefaultKeyRewriter can be used to remove the "https://", "http://" prefix
// and any trailing forward-slash "/". Additionally it will replace colons ":"
// in an IP address with "-port-".
//
// Example:
//
// https://mydomain.com/key -> mydomain.com/key
// http://182.31.42.33:8455/key -> 182.31.42.33-port-8455/key
// https://io.docker.com/access-token/ -> io.docker.com/access-token
func DefaultKeyRewriter(serverURL string) string {
replacer := strings.NewReplacer("https://", "", "http://", "")
o := strings.TrimSuffix(replacer.Replace(serverURL), "/")
parts := strings.Split(o, "/")
_, _, err := net.SplitHostPort(parts[0])
if err == nil {
return strings.ReplaceAll(o, ":", "-port-")
}
return o
}
func (s *credentialHelperStore) GetSecrets(_ context.Context, pattern plugin.Pattern) ([]plugin.Envelope, error) {
credentials, err := client.List(s.ProgramFunc)
if err != nil {
return nil, err
}
result := []plugin.Envelope{}
resolvedAt := time.Now()
for serverURL, username := range credentials {
var p plugin.ID
var err error
if s.rewriter != nil {
p, err = s.rewriter(serverURL, username)
} else {
p, err = plugin.ParseID(DefaultKeyRewriter(serverURL))
}
if err != nil {
s.Warnf("could not parse key '%s' as secrets.ID: %s", serverURL, err)
continue
}
if pattern.Match(p) {
cred, err := client.Get(s.ProgramFunc, serverURL)
// ignore the error if we could not fetch it from credential-helper
if err != nil {
s.Warnf("could not get matched secret key '%s' from the credential-helper: %s", serverURL, err)
continue
}
result = append(result, plugin.Envelope{
ID: p,
Value: []byte(cred.Secret),
Metadata: map[string]string{
"ServerURL": cred.ServerURL,
"Username": cred.Username,
},
Provider: "docker-credential-helper",
Version: "0.0.1",
ResolvedAt: resolvedAt,
})
}
}
if len(result) == 0 {
return nil, plugin.ErrNotFound
}
return result, nil
}
func (s *credentialHelperStore) Run(ctx context.Context) error {
<-ctx.Done()
return ctx.Err()
}
var _ plugin.Plugin = &credentialHelperStore{}
// only the CLI owns the config file
// unfortunately it also specifies the credential helper in use
// to support the credential-helper for legacy credentials
// we need to support this env.
// https://github.com/docker/cli/blob/master/cli/config/config.go#L24
const envOverrideConfigDir = "DOCKER_CONFIG"
func getConfigPath() (string,error) {
configDir := os.Getenv(envOverrideConfigDir)
if configDir != "" {
return configDir,nil
}
// continue with normal config resolution
// https://github.com/docker/cli/blob/1c572a10de5b9645045e3868b72f0863b920bd13/cli/config/config.go#L61-L69
home, _ := os.UserHomeDir()
if home == "" && runtime.GOOS != "windows" {
if u, err := user.Current(); err == nil {
home = u.HomeDir
}
}
if home == "" {
return "", fmt.Errorf("cannot determine home directory")
}
// there might be a case here where a system does not report a home
// directory based on the above steps taken from the CLI.
// We will error when we try to open a non-exiting file.
return path.Join(home, ".docker", "config.json")
}
type Options func(*credentialHelperStore)
func WithKeyRewriter(rewriter KeyRewriter) Options {
return func(chs *credentialHelperStore) {
chs.rewriter = rewriter
}
}
func WithShellProgramFunc(f client.ProgramFunc) Options {
return func(chs *credentialHelperStore) {
chs.ProgramFunc = f
}
}
func New(logger plugin.Logger, opts ...Options) (plugin.Plugin, error) {
c := &credentialHelperStore{
Logger: logger,
}
for _, opt := range opts {
opt(c)
}
if c.ProgramFunc == nil {
configPath := getConfigPath()
f, err := os.Open(configPath)
if err != nil {
return nil, err
}
defer f.Close()
// limit the size of the file we are reading.
// Don't want the plugin to get taken down by a really large file.
config, err := io.ReadAll(io.LimitReader(f, 1024*1024))
if err != nil {
return nil, err
}
var v map[string]any
if err := json.Unmarshal(config, &v); err != nil {
return nil, err
}
suffix, ok := v["credsStore"].(string)
if !ok || suffix == "" {
return nil, fmt.Errorf("credential-helper not specified in '%s'", configPath)
}
c.ProgramFunc = client.NewShellProgramFunc("docker-credential-" + suffix)
}
return c, nil
}