-
Notifications
You must be signed in to change notification settings - Fork 637
Expand file tree
/
Copy pathauth.go
More file actions
315 lines (274 loc) · 8.44 KB
/
auth.go
File metadata and controls
315 lines (274 loc) · 8.44 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
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
// Copyright 2020 Google LLC All Rights Reserved.
//
// 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 cmd
import (
"encoding/json"
"errors"
"fmt"
"io"
"log"
"os"
"strings"
"github.com/docker/cli/cli/config"
"github.com/docker/cli/cli/config/types"
"github.com/google/go-containerregistry/pkg/authn"
"github.com/google/go-containerregistry/pkg/crane"
"github.com/google/go-containerregistry/pkg/name"
"github.com/google/go-containerregistry/pkg/v1/remote/transport"
"github.com/spf13/cobra"
)
// NewCmdAuth creates a new cobra.Command for the auth subcommand.
func NewCmdAuth(options []crane.Option, argv ...string) *cobra.Command {
cmd := &cobra.Command{
Use: "auth",
Short: "Log in or access credentials",
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, _ []string) error { return cmd.Usage() },
}
cmd.AddCommand(NewCmdAuthGet(options, argv...), NewCmdAuthLogin(argv...), NewCmdAuthLogout(argv...), NewCmdAuthToken(options))
return cmd
}
func NewCmdAuthToken(options []crane.Option) *cobra.Command {
var (
header bool
push bool
mounts []string
)
cmd := &cobra.Command{
Use: "token REPO",
Short: "Retrieves a token for a remote repo",
Example: `# If you wanted to mount a blob from debian to ubuntu.
$ curl -H "$(crane auth token -H --push --mount debian ubuntu)" ...
# To get the raw list tags response
$ curl -H "$(crane auth token -H ubuntu)" https://index.docker.io/v2/library/ubuntu/tags/list
`,
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
repo, err := name.NewRepository(args[0])
if err != nil {
return err
}
o := crane.GetOptions(options...)
t := transport.NewLogger(o.Transport)
pr, err := transport.Ping(cmd.Context(), repo.Registry, t)
if err != nil {
return err
}
auth, err := authn.Resolve(cmd.Context(), o.Keychain, repo)
if err != nil {
return err
}
scopes := []string{repo.Scope(transport.PullScope)}
if push {
scopes[0] = repo.Scope(transport.PushScope)
}
for _, m := range mounts {
mr, err := name.NewRepository(m)
if err != nil {
return err
}
scopes = append(scopes, mr.Scope(transport.PullScope))
}
tr, err := transport.Exchange(cmd.Context(), repo.Registry, auth, t, scopes, pr)
if err != nil {
return err
}
if header {
fmt.Fprintf(cmd.OutOrStdout(), "Authorization: Bearer %s", tr.Token)
return nil
}
if err := json.NewEncoder(os.Stdout).Encode(tr); err != nil {
return err
}
return nil
},
}
cmd.Flags().StringSliceVarP(&mounts, "mount", "m", []string{}, "Scopes to mount from")
cmd.Flags().BoolVarP(&header, "header", "H", false, "Output in header format")
cmd.Flags().BoolVar(&push, "push", false, "Request push scopes")
return cmd
}
type credentials struct {
Username string `json:"Username,omitempty"`
Secret string `json:"Secret,omitempty"`
}
// https://github.com/docker/cli/blob/2291f610ae73533e6e0749d4ef1e360149b1e46b/cli/config/credentials/native_store.go#L100-L109
func toCreds(config *authn.AuthConfig) credentials {
creds := credentials{
Username: config.Username,
Secret: config.Password,
}
if config.IdentityToken != "" {
creds.Username = "<token>"
creds.Secret = config.IdentityToken
}
return creds
}
// NewCmdAuthGet creates a new `crane auth get` command.
func NewCmdAuthGet(options []crane.Option, argv ...string) *cobra.Command {
if len(argv) == 0 {
argv = []string{os.Args[0]}
}
baseCmd := strings.Join(argv, " ")
eg := fmt.Sprintf(` # Read configured credentials for reg.example.com
$ echo "reg.example.com" | %s get
{"Username":"AzureDiamond","Secret":"hunter2"}
# or
$ %s get reg.example.com
{"Username":"AzureDiamond","Secret":"hunter2"}`, baseCmd, baseCmd)
return &cobra.Command{
Use: "get [REGISTRY_ADDR]",
Short: "Implements a credential helper",
Example: eg,
Args: cobra.MaximumNArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
registryAddr := ""
if len(args) == 1 {
registryAddr = args[0]
} else {
b, err := io.ReadAll(os.Stdin)
if err != nil {
return err
}
registryAddr = strings.TrimSpace(string(b))
}
reg, err := name.NewRegistry(registryAddr)
if err != nil {
return err
}
authorizer, err := authn.Resolve(cmd.Context(), crane.GetOptions(options...).Keychain, reg)
if err != nil {
return err
}
// If we don't find any credentials, there's a magic error to return:
//
// https://github.com/docker/docker-credential-helpers/blob/f78081d1f7fef6ad74ad6b79368de6348386e591/credentials/error.go#L4-L6
// https://github.com/docker/docker-credential-helpers/blob/f78081d1f7fef6ad74ad6b79368de6348386e591/credentials/credentials.go#L61-L63
if authorizer == authn.Anonymous {
fmt.Fprint(os.Stdout, "credentials not found in native keychain\n")
os.Exit(1)
}
auth, err := authn.Authorization(cmd.Context(), authorizer)
if err != nil {
return err
}
// Convert back to a form that credential helpers can parse so that this
// can act as a meta credential helper.
creds := toCreds(auth)
return json.NewEncoder(os.Stdout).Encode(creds)
},
}
}
// NewCmdAuthLogin creates a new `crane auth login` command.
func NewCmdAuthLogin(argv ...string) *cobra.Command {
var opts loginOptions
if len(argv) == 0 {
argv = []string{os.Args[0]}
}
eg := fmt.Sprintf(` # Log in to reg.example.com
%s login reg.example.com -u AzureDiamond -p hunter2`, strings.Join(argv, " "))
cmd := &cobra.Command{
Use: "login [OPTIONS] [SERVER]",
Short: "Log in to a registry",
Example: eg,
Args: cobra.ExactArgs(1),
RunE: func(_ *cobra.Command, args []string) error {
reg, err := name.NewRegistry(args[0])
if err != nil {
return err
}
opts.serverAddress = reg.Name()
return login(opts)
},
}
flags := cmd.Flags()
flags.StringVarP(&opts.user, "username", "u", "", "Username")
flags.StringVarP(&opts.password, "password", "p", "", "Password")
flags.BoolVarP(&opts.passwordStdin, "password-stdin", "", false, "Take the password from stdin")
return cmd
}
type loginOptions struct {
serverAddress string
user string
password string
passwordStdin bool
}
func login(opts loginOptions) error {
if opts.passwordStdin {
contents, err := io.ReadAll(os.Stdin)
if err != nil {
return err
}
opts.password = strings.TrimSuffix(string(contents), "\n")
opts.password = strings.TrimSuffix(opts.password, "\r")
}
if opts.user == "" && opts.password == "" {
return errors.New("username and password required")
}
cf, err := config.Load(os.Getenv("DOCKER_CONFIG"))
if err != nil {
return err
}
creds := cf.GetCredentialsStore(opts.serverAddress)
if opts.serverAddress == name.DefaultRegistry {
opts.serverAddress = authn.DefaultAuthKey
}
if err := creds.Store(types.AuthConfig{
ServerAddress: opts.serverAddress,
Username: opts.user,
Password: opts.password,
}); err != nil {
return err
}
if err := cf.Save(); err != nil {
return err
}
log.Printf("logged in via %s", cf.Filename)
return nil
}
// NewCmdAuthLogout creates a new `crane auth logout` command.
func NewCmdAuthLogout(argv ...string) *cobra.Command {
eg := fmt.Sprintf(` # Log out of reg.example.com
%s logout reg.example.com`, strings.Join(argv, " "))
cmd := &cobra.Command{
Use: "logout [SERVER]",
Short: "Log out of a registry",
Example: eg,
Args: cobra.ExactArgs(1),
RunE: func(_ *cobra.Command, args []string) error {
reg, err := name.NewRegistry(args[0])
if err != nil {
return err
}
serverAddress := reg.Name()
cf, err := config.Load(os.Getenv("DOCKER_CONFIG"))
if err != nil {
return err
}
creds := cf.GetCredentialsStore(serverAddress)
if serverAddress == name.DefaultRegistry {
serverAddress = authn.DefaultAuthKey
}
if err := creds.Erase(serverAddress); err != nil {
return err
}
if err := cf.Save(); err != nil {
return err
}
log.Printf("logged out via %s", cf.Filename)
return nil
},
}
return cmd
}