GitLabgitlab-org

cli

main
ply8 git calls274 ms108 KiB5 cachedprotocol v2
675 lines32 KiBRaw
1// Package login implements `glab artifact-registry login`, which
2// authenticates a package manager against the GitLab Artifact Registry.
3package login
5import (
6 "context"
7 "fmt"
8 "net"
9 "net/url"
10 "os"
11 "regexp"
12 "strings"
13 "time"
14 "unicode"
16 "github.com/MakeNowJust/heredoc/v2"
17 "github.com/spf13/cobra"
19 "gitlab.com/gitlab-org/cli/internal/api"
20 "gitlab.com/gitlab-org/cli/internal/api/artifactregistry"
21 "gitlab.com/gitlab-org/cli/internal/cmdutils"
22 "gitlab.com/gitlab-org/cli/internal/config"
23 "gitlab.com/gitlab-org/cli/internal/dockercredhelper"
24 "gitlab.com/gitlab-org/cli/internal/glinstance"
25 "gitlab.com/gitlab-org/cli/internal/iostreams"
26 "gitlab.com/gitlab-org/cli/internal/mcpannotations"
27 "gitlab.com/gitlab-org/cli/internal/text"
30// aliasInvalidCharsRe matches runs of characters that cannot appear in a
31// registry alias, so they can be collapsed into a single "-".
32var aliasInvalidCharsRe = regexp.MustCompile(`[^a-z0-9]+`)
34// registryAliasRe restricts an explicit --registry-alias to characters that
35// are always safe as Maven <id> XML text content and as a Gradle property
36// key prefix. Unlike defaultRegistryAlias's derived value, a user-supplied
37// alias is never sanitized before being written, so it must be validated
38// instead.
39var registryAliasRe = regexp.MustCompile(`^[a-zA-Z0-9._-]+$`)
41// registryHostRe restricts a --registry host to what a host name can hold.
42// url.Parse is far looser: it accepts '"', '(' and ')' there, and every writer
43// interpolates the host into a file its tool parses. credentials.sbt is the
44// sharpest case, since sbt compiles it as Scala: one '"' closes the string
45// literal and the rest of the host lands in the file as code, so a registry
46// like `https://x")+sys.error("boom")+Credentials("z/` becomes something sbt
47// runs. The others fail more quietly, on a key their tool never looks up.
48//
49// An internationalized host has to be given in punycode. That is what the
50// tools look for anyway: npm builds its .npmrc key with the WHATWG URL parser,
51// which converts the host to punycode, so a UTF-8 host here would write a key
52// npm never reads.
53var registryHostRe = regexp.MustCompile(`^[A-Za-z0-9._-]+$`)
55type writer struct {
56 flag string
57 usage string
58 needsAlias bool
59 needsURL bool
60 // acceptsConfigFile is set for writers whose target file --config-file
61 // can replace.
62 acceptsConfigFile bool
63 login func(o *options, alias string, result *artifactregistry.ExchangeResult) error
66var writers = []writer{
67 {
68 flag: "maven",
69 usage: "Configure Maven to authenticate against the registry. Writes to ~/.m2/settings.xml.",
70 needsAlias: true,
71 needsURL: false,
72 acceptsConfigFile: true,
73 login: func(o *options, alias string, result *artifactregistry.ExchangeResult) error {
74 if err := loginMaven(o.configFile, alias, result.Token); err != nil {
75 return err
76 }
77 o.io.LogInfof("%s Configured Maven server %q for %s%s. Token expires at %s.\n", o.io.Color().GreenCheck(), alias, o.registry, o.configFileSuffix(), result.ExpiresAt.Format(time.RFC3339))
78 return nil
79 },
80 },
81 {
82 flag: "gradle",
83 usage: "Configure Gradle to authenticate against the registry. Writes to ~/.gradle/gradle.properties.",
84 needsAlias: true,
85 needsURL: true,
86 login: func(o *options, alias string, result *artifactregistry.ExchangeResult) error {
87 if err := loginGradle(o.registry, alias, result.Token); err != nil {
88 return err
89 }
90 // Names the three property keys, not just the file: the alias is what the
91 // user has to type into build.gradle, and it is the one writer whose
92 // output is unusable without knowing it.
93 o.io.LogInfof("%s Configured Gradle properties %sUrl, %sUsername and %sPassword for %s. Token expires at %s.\n",
94 o.io.Color().GreenCheck(), alias, alias, alias, o.registry, result.ExpiresAt.Format(time.RFC3339))
95 return nil
96 },
97 },
98 {
99 flag: "npm",
100 usage: "Configure npm to authenticate against the registry. Writes to ~/.npmrc.",
101 needsAlias: false,
102 needsURL: true,
103 login: func(o *options, alias string, result *artifactregistry.ExchangeResult) error {
104 if err := loginNpm(o.registryURL, result.Token); err != nil {
105 return err
106 }
107 // Says "auth token", not "configured npm": all this writes is the
108 // credential. npm still resolves packages from its default registry
109 // until the user points it at this one, so a message claiming npm was
110 // configured would be describing a step the user still has to take.
111 o.io.LogInfof("%s Wrote an npm auth token for %s. Point npm at that registry with a `registry=` or `@scope:registry=` line if you have not already. Token expires at %s.\n",
112 o.io.Color().GreenCheck(), o.registry, result.ExpiresAt.Format(time.RFC3339))
113 return nil
114 },
115 },
116 {
117 flag: "sbt",
118 usage: "Configure sbt to authenticate against the registry. Writes credentials.sbt to the sbt 1.x and 2.x global bases.",
119 needsAlias: false,
120 needsURL: true,
121 acceptsConfigFile: true,
122 login: func(o *options, alias string, result *artifactregistry.ExchangeResult) error {
123 written, skipped, err := loginSbt(o.configFile, o.registryURL, result.Token)
124 if err != nil {
125 return err
126 }
127 // sbt compiles credentials.sbt once, when it loads the build, and does
128 // not watch the global base, so a refreshed token never reaches an sbt
129 // that is already running. sbt 2.x keeps a server running by default.
130 o.io.LogInfof("%s Configured sbt for %s. Wrote %s. Token expires at %s. An sbt shell or sbt 2.x server that is already running keeps the credentials it loaded: run `reload` in it, or `sbt shutdown`.\n",
131 o.io.Color().GreenCheck(), o.registry, describeSbtCredentialsFiles(written), result.ExpiresAt.Format(time.RFC3339))
132 if skipped != "" {
133 o.io.LogErrorf("%s %s is blank or a relative path, so glab skipped it. sbt 2.x resolves it against the directory the build runs in, and does not read the sbt 2.x file above. Set it to an absolute path, or unset it.\n",
134 o.io.Color().WarnIcon(), skipped)
135 }
136 return nil
137 },
138 },
139 {
140 flag: "yarn",
141 usage: "Configure Yarn 2 or later to authenticate against the registry. Writes to ~/.yarnrc.yml. For Yarn 1, use --npm.",
142 needsAlias: false,
143 needsURL: true,
144 login: func(o *options, alias string, result *artifactregistry.ExchangeResult) error {
145 shadowed, err := loginYarn(o.registryURL, result.Token)
146 if err != nil {
147 return err
148 }
149 // Like --npm, says only what was written: Yarn keeps fetching from its
150 // default registry until npmRegistryServer names this one.
151 o.io.LogInfof("%s Wrote a Yarn auth token for %s. Point Yarn at that registry with `npmRegistryServer`, at the top level or under `npmScopes`, if you have not already. Token expires at %s.\n",
152 o.io.Color().GreenCheck(), o.registry, result.ExpiresAt.Format(time.RFC3339))
153 for _, scope := range shadowed {
154 o.io.LogErrorf("%s The npmScopes entry %q in ~/.yarnrc.yml has its own npmAuthToken or npmAuthIdent, and Yarn sends that for @%s packages instead of this token. Remove it from the scope to use this login.\n",
155 o.io.Color().WarnIcon(), scope, scope)
156 }
157 return nil
158 },
159 },
162func writerForFlag(flag string) *writer {
163 for i := range writers {
164 if writers[i].flag == flag {
165 return &writers[i]
166 }
167 }
168 return nil
171type options struct {
172 io *iostreams.IOStreams
173 // apiClient builds the client for an exchange whose token this command
174 // writes into a package manager's own configuration, so far only --maven.
175 // f.ApiClient, unlike credHelperApiClient: nothing re-resolves the
176 // credential afterwards, so every credential glab accepts, GITLAB_TOKEN
177 // included, works here.
178 apiClient func(repoHost string) (*api.Client, error)
179 // credHelperApiClient builds the client for the --docker verification
180 // exchange, resolving the same identity the Docker credential helper will.
181 // Deliberately not f.ApiClient: see its wiring in NewCmd. A field rather
182 // than an inline call so a test can assert which host it is built for.
183 credHelperApiClient func(repoHost string) (*api.Client, error)
184 cfg config.Config
185 defaultHostname string
186 // supportedOS reports whether this platform can run the Docker credential
187 // helper shim. A field rather than a direct call so a test can exercise the
188 // unsupported path on a supported platform.
189 supportedOS func() error
191 hostname string
192 duration time.Duration
193 // durationChanged is set from cmd.Flags().Changed("duration") before
194 // validate/run are called, since a duration flag's zero value can't
195 // distinguish "not passed" from "passed as 0s".
196 durationChanged bool
198 registry string
199 // registryURL is registry parsed, set by validate on the --gradle/--npm/
200 // --sbt/--yarn paths and nil elsewhere. It travels from the check that
201 // rejects a bad URL to the writers that key their entries on one, so no
202 // writer has to parse the same string again and handle a failure that
203 // cannot happen.
204 registryURL *url.URL
205 registryAlias string
206 configFile string
208 docker bool
209 writer *writer
212// NewCmd returns the `glab artifact-registry login` command.
213func NewCmd(f cmdutils.Factory) *cobra.Command {
214 opts := &options{
215 io: f.IO(),
216 apiClient: f.ApiClient,
217 // WithoutTokenFromEnvironment, so this client resolves the same identity
218 // the Docker credential helper will
219 // (internal/commands/auth/docker.Helper.getArtifactRegistryToken builds
220 // its client the same way). f.ApiClient reads GITLAB_TOKEN, which the
221 // helper ignores, so verifying with it would check an identity Docker
222 // never uses: a valid GITLAB_TOKEN over a dead stored token reports
223 // success and then 401s on every pull, and the reverse fails a login
224 // that would have worked.
225 credHelperApiClient: func(repoHost string) (*api.Client, error) {
226 return api.NewClientFromConfig(repoHost, f.Config(), false, f.BuildInfo().UserAgent(), api.WithoutTokenFromEnvironment())
227 },
228 cfg: f.Config(),
229 defaultHostname: f.DefaultHostname(),
230 supportedOS: dockercredhelper.Supported,
231 }
233 toolFlags := make([]bool, len(writers))
234 cmd := &cobra.Command{
235 Use: "login",
236 Short: "Authenticate a package manager against the GitLab Artifact Registry. (EXPERIMENTAL)",
237 Long: heredoc.Docf(`
238 Configure a package manager to authenticate against the GitLab Artifact
239 Registry, using a short-lived access token exchanged from your GitLab
240 session.
242 Use the flag for your package manager:
244 - %[1]s--docker%[1]s: registers %[1]sglab%[1]s as a Docker credential
245 helper for the registry.
246 - %[1]s--maven%[1]s: writes a %[1]s<server>%[1]s block in
247 %[1]s~/.m2/settings.xml%[1]s, or %[1]s--config-file%[1]s, keyed by
248 %[1]s--registry-alias%[1]s.
249 Reference it from a %[1]s<repository>%[1]s carrying the same
250 %[1]s<id>%[1]s. The token is written in plain text, so keep a
251 %[1]s--config-file%[1]s out of version control.
252 - %[1]s--gradle%[1]s: writes %[1]s{alias}Url%[1]s,
253 %[1]s{alias}Username%[1]s, and %[1]s{alias}Password%[1]s in
254 %[1]s~/.gradle/gradle.properties%[1]s, where %[1]s{alias}%[1]s is
255 %[1]s--registry-alias%[1]s.
256 - %[1]s--npm%[1]s: writes a %[1]s//{host}{path}/:_authToken%[1]s entry
257 in %[1]s~/.npmrc%[1]s. You still need to point npm at the registry, with a
258 %[1]sregistry=%[1]s or %[1]s@scope:registry=%[1]s line.
259 - %[1]s--yarn%[1]s: writes an %[1]snpmRegistries%[1]s entry with %[1]snpmAuthToken%[1]s
260 and %[1]snpmAlwaysAuth%[1]s in %[1]s~/.yarnrc.yml%[1]s, for Yarn 2 and later. Set
261 an %[1]snpmRegistryServer%[1]s that matches %[1]s--registry%[1]s. Rewriting the
262 file can change its formatting, like indentation, blank lines, and line endings.
263 - %[1]s--sbt%[1]s: writes a %[1]scredentials +=%[1]s line in
264 %[1]s~/.sbt/1.0/credentials.sbt%[1]s, which sbt 1.x reads, and the
265 same line in %[1]s2/credentials.sbt%[1]s in the sbt 2.x global base,
266 which sbt 2.x reads. That base is %[1]s~/.config/sbt%[1]s, or
267 %[1]s%%LOCALAPPDATA%%\sbt%[1]s on Windows, unless
268 %[1]sSBT_CONFIG_HOME%[1]s or %[1]sXDG_CONFIG_HOME%[1]s moves it.
269 On Windows it also writes
270 %[1]s%%LOCALAPPDATA%%\sbt\credentials.sbt%[1]s. The %[1]ssbt.bat%[1]s
271 of sbt 2.x points every build it starts, on either version, at
272 that file only, even when %[1]sSBT_CONFIG_HOME%[1]s is set.
273 The %[1]ssbt.version%[1]s in a project's
274 %[1]sproject/build.properties%[1]s decides which file its build
275 reads. An sbt started with any other %[1]s-Dsbt.global.base%[1]s
276 reads none of them. An sbt shell or sbt 2.x server that is
277 already running keeps the credentials it loaded, so run
278 %[1]sreload%[1]s in it, or %[1]ssbt shutdown%[1]s, after you log in.
279 To write a different file, pass it with %[1]s--config-file%[1]s. It
280 must be a %[1]s.sbt%[1]s file that sbt loads, not a properties file
281 such as %[1]s~/.sbt/.credentials%[1]s.
283 Token lifetime:
285 - %[1]s--docker%[1]s exchanges a fresh token on every pull or push,
286 so %[1]s--duration%[1]s does not apply.
287 - Every other flag writes one token, and nothing refreshes it. Run
288 the command again before %[1]s--duration%[1]s elapses. The default
289 is 15 minutes and the maximum is 12 hours.
291 Credential resolution:
293 - Docker runs the credential helper as its own subprocess, which
294 reads your credentials from the configuration file and ignores
295 %[1]sGITLAB_TOKEN%[1]s. This command verifies the login the same
296 way, so run %[1]sglab auth login%[1]s first if no token is stored
297 for the host.
298 - Every other flag does read %[1]sGITLAB_TOKEN%[1]s. %[1]sglab%[1]s
299 writes the token into each file itself, so the tool can read it
300 without fetching credentials itself.
302 Registry and alias selection:
304 - Use %[1]s--registry%[1]s only for a registry the Artifact Registry
305 actually backs. If you name a container registry here, it receives the
306 wrong token and the error only surfaces on the next pull.
307 - %[1]s--registry-alias%[1]s applies to %[1]s--maven%[1]s and
308 %[1]s--gradle%[1]s only, because %[1]s--npm%[1]s, %[1]s--sbt%[1]s,
309 and %[1]s--yarn%[1]s key their entries on %[1]s--registry%[1]s
310 itself.
311 For %[1]s--gradle%[1]s, use an alias that is a valid identifier
312 in your build script: the default is derived from the registry
313 host and contains hyphens, which Groovy cannot interpolate as
314 %[1]s${...}%[1]s.
315 `, "`") + text.ExperimentalString,
316 Example: heredoc.Doc(`
317 # Configure Docker to authenticate against a registry
318 glab artifact-registry login --docker --registry registry.example.com
320 # Configure Maven to authenticate against a registry for two hours
321 glab artifact-registry login --maven --registry https://ar.example.com --duration 2h
323 # Configure Gradle to authenticate against a registry for two hours
324 glab artifact-registry login --gradle --registry https://ar.example.com --duration 2h
326 # Configure npm to authenticate against a registry for two hours
327 glab artifact-registry login --npm --registry https://ar.example.com --duration 2h
329 # Configure Yarn 2 or later to authenticate against a registry for two hours
330 glab artifact-registry login --yarn --registry https://ar.example.com --duration 2h
332 # Configure sbt to authenticate against a registry for two hours
333 glab artifact-registry login --sbt --registry https://ar.example.com --duration 2h
335 # Configure Maven through a settings.xml passed to mvn with -s
336 glab artifact-registry login --maven --registry https://ar.example.com --config-file ~/.m2/ci-settings.xml
337 `),
338 Args: cobra.NoArgs,
339 ValidArgsFunction: cobra.NoFileCompletions,
340 Annotations: map[string]string{
341 mcpannotations.Destructive: "true",
342 "help:environment": heredoc.Doc(`
343 DOCKER_CONFIG: the directory holding Docker's config.json, written by --docker. Defaults to ~/.docker.
344 GRADLE_USER_HOME: the directory holding gradle.properties, written by --gradle. Defaults to ~/.gradle.
345 npm_config_userconfig: the .npmrc written by --npm. Defaults to ~/.npmrc.
346 SBT_CONFIG_HOME: the sbt 2.x global base; --sbt writes 2/credentials.sbt in it. Defaults to $XDG_CONFIG_HOME/sbt, else ~/.config/sbt. On Windows, the sbt.bat of sbt 2.x overrides it with %LOCALAPPDATA%\sbt. --sbt skips a blank or relative value of this variable and the next two.
347 XDG_CONFIG_HOME: used by --sbt for the sbt 2.x base when SBT_CONFIG_HOME is unset. Not read on Windows.
348 LOCALAPPDATA: on Windows, used by --sbt in place of XDG_CONFIG_HOME, and for the base the sbt.bat of sbt 2.x passes.
349 `),
350 },
351 RunE: func(cmd *cobra.Command, _ []string) error {
352 opts.complete(cmd, toolFlags)
354 if err := opts.validate(); err != nil {
355 return err
356 }
357 return opts.run(cmd.Context())
358 },
359 }
361 flagNames := make([]string, 0, len(writers)+1)
362 flagNames = append(flagNames, "docker")
363 cmd.Flags().BoolVar(&opts.docker, "docker", false, "Configure Docker to authenticate against the registry. Writes to $DOCKER_CONFIG, or ~/.docker when it is unset.")
364 for i := range writers {
365 flagNames = append(flagNames, writers[i].flag)
366 cmd.Flags().BoolVar(&toolFlags[i], writers[i].flag, false, writers[i].usage)
367 }
368 cmd.MarkFlagsMutuallyExclusive(flagNames...)
369 cmd.MarkFlagsOneRequired(flagNames...)
371 cmd.Flags().StringVar(&opts.registry, "registry", "", "Registry to authenticate against. For --docker, a bare hostname; for others, typically a URL.")
372 cobra.CheckErr(cmd.MarkFlagRequired("registry"))
373 cmd.Flags().StringVar(&opts.registryAlias, "registry-alias", "", "Alias/ID to register the registry under (Maven/Gradle only). Defaults to a name derived from --registry.")
374 cmd.Flags().StringVar(&opts.configFile, "config-file", "", "File to write (Maven/sbt only). Defaults to ~/.m2/settings.xml for --maven and the sbt 1.x and 2.x global bases for --sbt, where it replaces every file --sbt writes.")
375 // --duration is accepted and ignored on the --docker path, deliberately:
376 // that credential helper exchanges its own token for every request, with its
377 // own lifetime (artifactregistry.DockerHelperDuration), so there is no token
378 // there whose validity a user could choose. Rejecting the flag instead would
379 // break the uniform flag set the other tools use, and silently accepting it
380 // would let a user believe they had shortened a token's life. So it is
381 // accepted, and run() says it did nothing.
382 cmd.Flags().DurationVar(&opts.duration, "duration", artifactregistry.DefaultDuration, "How long the exchanged token should remain valid. Ignored for --docker.")
383 cmd.Flags().StringVar(&opts.hostname, "hostname", "", "GitLab hostname to request the token from. Defaults to the configured GitLab instance.")
385 return cmd
388// complete reads the state that lives on the parsed command rather than in a
389// flag variable.
390func (o *options) complete(cmd *cobra.Command, toolFlags []bool) {
391 o.durationChanged = cmd.Flags().Changed("duration")
392 for i := range writers {
393 if i < len(toolFlags) && toolFlags[i] {
394 o.writer = &writers[i]
395 break
396 }
397 }
400// validate rejects everything that makes the login impossible, before any
401// network call or write. The --registry rules split by tool: --docker needs a
402// bare hostname because that is what a credential helper is handed, while
403// --gradle, --npm, --sbt and --yarn need a URL with a host because they write
404// it, or a key derived from it, into their own files.
405//
406// Two kinds of error come out of it. A bad flag value is a
407// *cmdutils.FlagError, naming the flag whose value the user has to change. The
408// --docker environment checks below (platform, glab on PATH) return whatever
409// dockercredhelper hands back, deliberately not a FlagError: no flag the user
410// could retype fixes either one, so pointing at a flag would misdirect.
411//
412// No FlagError starts with the flag name, also deliberately. fang's error
413// handler title-cases the first word of whatever it renders, which turns a
414// leading "--docker=false" into "--Docker=False": a flag spelling that does not
415// exist. Leading with "invalid" keeps the flag as the user typed it.
416func (o *options) validate() error {
417 // MarkFlagsOneRequired only checks that one of the tool flags was passed, so
418 // --docker=false alone (all others left at their false default) reaches here
419 // with no tool actually selected.
420 if !o.docker && o.writer == nil {
421 return &cmdutils.FlagError{Err: fmt.Errorf("invalid --docker, --maven, --gradle, --npm, --sbt, and --yarn: all false leaves no tool selected; pass one of them as true")}
422 }
424 if o.registryAlias != "" && o.writer != nil && o.writer.needsAlias && !registryAliasRe.MatchString(o.registryAlias) {
425 return &cmdutils.FlagError{Err: fmt.Errorf("invalid --registry-alias: must contain only letters, digits, '.', '_', and '-' (got %q)", o.registryAlias)}
426 }
428 if o.configFile != "" && o.writer != nil && o.writer.acceptsConfigFile {
429 // A trailing separator names a directory even when it does not exist
430 // yet; the writer would create it and then fail to rename onto it.
431 info, err := os.Stat(o.configFile)
432 if os.IsPathSeparator(o.configFile[len(o.configFile)-1]) || (err == nil && info.IsDir()) {
433 return &cmdutils.FlagError{Err: fmt.Errorf("invalid --config-file: %q is a directory; pass the path of the file to write", o.configFile)}
434 }
435 // sbt loads only .sbt files from its global base, and the Scala line
436 // this writes would corrupt a properties file like ~/.sbt/.credentials.
437 if o.writer.flag == "sbt" && !strings.HasSuffix(o.configFile, ".sbt") {
438 return &cmdutils.FlagError{Err: fmt.Errorf("invalid --config-file: %q is not a .sbt file; --sbt writes a Scala credentials line, which sbt loads only from a .sbt file", o.configFile)}
439 }
440 }
442 if o.hostname != "" {
443 // Checked before HostnameValidator, which only rejects "/" and ":": a
444 // hostname with a space otherwise reaches glinstance.APIEndpoint and dies
445 // with a net/url parse error rather than a FlagError naming the flag.
446 if hasWhitespaceOrControl(o.hostname) {
447 return &cmdutils.FlagError{Err: fmt.Errorf("invalid --hostname: must not contain whitespace or control characters (got %q)", o.hostname)}
448 }
449 if err := glinstance.HostnameValidator(o.hostname); err != nil {
450 return &cmdutils.FlagError{Err: fmt.Errorf("error parsing --hostname: %w", err)}
451 }
452 }
454 if o.registry == "" {
455 return &cmdutils.FlagError{Err: fmt.Errorf("invalid --registry: must not be empty")}
456 }
457 // Rejected rather than trimmed: loginDocker writes the value verbatim into
458 // artifact_registry_domains but config.ParseDomains reads it back trimmed,
459 // so " registry.example.com" would never match the credHelpers key Docker
460 // looks up, and every login would append another entry to the domain list.
461 if hasWhitespaceOrControl(o.registry) {
462 return &cmdutils.FlagError{Err: fmt.Errorf("invalid --registry: must not contain whitespace or control characters (got %q)", o.registry)}
463 }
465 if o.docker {
466 if strings.Contains(o.registry, "://") {
467 return &cmdutils.FlagError{Err: fmt.Errorf("invalid --registry: must be a bare hostname when using --docker (got %q); Docker credential helpers receive bare hostnames, not URLs", o.registry)}
468 }
469 if strings.Contains(o.registry, "/") {
470 return &cmdutils.FlagError{Err: fmt.Errorf("invalid --registry: must not contain a path (got %q); Docker matches credHelpers entries on the host, optionally with a port, so a path would never match", o.registry)}
471 }
472 if strings.Contains(o.registry, ",") {
473 return &cmdutils.FlagError{Err: fmt.Errorf("invalid --registry: must not contain a comma (got %q); artifact_registry_domains stores registries as a comma-separated list", o.registry)}
474 }
476 // Last, after the flag rules: a user who typed a bad --registry should
477 // hear about the flag they can fix, not about their platform.
478 //
479 // Both are checked here rather than left to dockercredhelper.Install,
480 // because run exchanges a token before it writes anything: without them, a
481 // login that can never work mints a live credential on the server and only
482 // then reports that Docker can never use it.
483 //
484 // They are not everything Install can reject: it can still find no
485 // writable directory for the shim. That is not preflighted here because
486 // the only honest check is attempting the write, which would leave a shim
487 // behind on a login whose token exchange then fails. Install tries every
488 // directory on PATH and then ~/.local/bin, so reaching that failure takes
489 // a filesystem where none of them will accept a file.
490 if err := o.supportedOS(); err != nil {
491 return err
492 }
493 // The shim shells out to glab, so a glab that PATH cannot resolve is as
494 // fatal as an unsupported platform. Install repeats the lookup, which is
495 // cheap and keeps it safe for callers that skip this check.
496 if _, err := dockercredhelper.Locate(); err != nil {
497 return err
498 }
500 // --duration is not range-checked: nothing on this path sends it, so
501 // rejecting a value run() has already said it ignores would contradict
502 // the warning.
503 return nil
504 }
506 // --gradle joins --npm, --sbt and --yarn: all four put the registry URL, or
507 // a key derived from it, into the file they write, so a value that is not a
508 // URL only fails later at build time. --maven is the exception, and
509 // deliberately so: its <server> block carries just the alias and the
510 // credentials, and the URL itself lives in the caller's pom.xml keyed by
511 // that alias.
512 //
513 // The scheme is required as well as the host, and not just because the
514 // message says so: url.Parse gives "//ar.example.com" a host and no scheme,
515 // and --gradle writes that value verbatim into {alias}Url, where Gradle
516 // rejects it as a repository URL at build time.
517 if o.writer != nil && o.writer.needsURL {
518 u, err := url.Parse(o.registry)
519 if err != nil || u.Scheme == "" || u.Host == "" {
520 return &cmdutils.FlagError{Err: fmt.Errorf("invalid --registry: must be a URL with a scheme and host, for example https://registry.example.com (got %q)", o.registry)}
521 }
522 // Hostname(), so an IPv6 literal arrives without its brackets and the
523 // port stays out of the check: url.Parse has already refused a port
524 // that is not numeric.
525 host := u.Hostname()
526 if net.ParseIP(host) == nil && !registryHostRe.MatchString(host) {
527 return &cmdutils.FlagError{Err: fmt.Errorf("invalid --registry: its host must be an IP address, or contain only letters, digits, '.', '_' and '-' (got %q); an internationalized host must be given in punycode", host)}
528 }
530 // Kept, not thrown away: loginNpm, loginSbt and loginYarn need the
531 // parsed URL, and parsing it a second time there would give them an
532 // error branch that this check has already ruled out.
533 o.registryURL = u
534 }
536 return artifactregistry.ValidateDuration(o.duration)
539// hasWhitespaceOrControl reports whether s holds whitespace or a control
540// character. Neither belongs in a hostname, and both survive a write only to
541// break the read that follows it.
542func hasWhitespaceOrControl(s string) bool {
543 return strings.ContainsFunc(s, func(r rune) bool {
544 return unicode.IsSpace(r) || unicode.IsControl(r)
545 })
548func (o *options) run(ctx context.Context) error {
549 if o.registryAlias != "" && (o.writer == nil || !o.writer.needsAlias) {
550 o.io.LogErrorf("%s --registry-alias is ignored outside --maven/--gradle logins.\n", o.io.Color().WarnIcon())
551 }
552 if o.configFile != "" && (o.writer == nil || !o.writer.acceptsConfigFile) {
553 o.io.LogErrorf("%s --config-file is ignored outside --maven/--sbt logins.\n", o.io.Color().WarnIcon())
554 }
556 // Resolved once, then used everywhere: the token exchange must run against
557 // the same host the domain is recorded under. Load-bearing rather than
558 // belt-and-braces on the --docker path, since credHelperApiClient comes
559 // from api.NewClientFromConfig, which builds a client for whatever host it
560 // is handed and does not substitute the default for an empty one the way
561 // f.ApiClient does.
562 hostname := o.hostname
563 if hostname == "" {
564 hostname = o.defaultHostname
565 }
567 if o.docker {
568 // Warned before the exchange, so the user still learns the flag did
569 // nothing on a run that then fails.
570 if o.durationChanged {
571 o.io.LogErrorf("%s --duration is ignored for --docker logins: the Docker credential helper exchanges a fresh token for every request.\n", o.io.Color().WarnIcon())
572 }
574 apiClient, err := o.credHelperApiClient(hostname)
575 if err != nil {
576 return err
577 }
579 // The token is exchanged only to confirm the exchange itself works,
580 // then discarded: the Docker credential helper mints a fresh one on
581 // every request. Without this, a login with no working credential
582 // would still install the shim and write config, and the first sign
583 // of trouble would be an unrelated-looking `docker pull` failure.
584 //
585 // MinDuration, not the server default: nothing ever sends this token, so
586 // the shortest lifetime the server will issue verifies just as much while
587 // leaving a live credential valid for a second instead of five minutes.
588 if _, err := artifactregistry.NewClient(apiClient.Lab()).ExchangeToken(ctx, artifactregistry.MinDuration); err != nil {
589 return o.exchangeError(hostname, err)
590 }
592 return loginDocker(o.io, o.cfg, hostname, o.registry)
593 }
595 alias := o.registryAlias
596 if alias == "" {
597 alias = defaultRegistryAlias(o.registry)
598 }
600 apiClient, err := o.apiClient(hostname)
601 if err != nil {
602 return err
603 }
605 result, err := artifactregistry.NewClient(apiClient.Lab()).ExchangeToken(ctx, o.duration)
606 if err != nil {
607 return fmt.Errorf("failed to get artifact registry token: %w", err)
608 }
610 return o.writer.login(o, alias, result)
613// configFileSuffix names --config-file in a success message, so a mistyped
614// path shows up at login rather than as a build with no credentials.
615func (o *options) configFileSuffix() string {
616 if o.configFile == "" {
617 return ""
618 }
619 return fmt.Sprintf(" in %q", o.configFile)
622// defaultRegistryAlias derives a default alias/ID from registry, which may
623// be a bare hostname or a full URL. The result is always prefixed with
624// "artifact-registry-" and contains only lowercase alphanumerics and single
625// hyphens between runs of other characters.
626func defaultRegistryAlias(registry string) string {
627 host := registry
628 if u, err := url.Parse(registry); err == nil && u.Host != "" {
629 host = u.Host
630 }
632 host = strings.ToLower(host)
633 host = aliasInvalidCharsRe.ReplaceAllString(host, "-")
634 host = strings.Trim(host, "-")
636 return "artifact-registry-" + host
639// exchangeError reports a failed verification exchange, naming an absent stored
640// credential as the cause when that is what it is.
641//
642// Worth two config reads on a path that is already failing: the exchange
643// resolves credentials from the configuration file only (see
644// credHelperApiClient's wiring in NewCmd), so a bare "401 Unauthorized" is
645// baffling to a user holding a GITLAB_TOKEN every other glab command accepts.
646// The remedy is also not guessable from the status code, since
647// `glab auth login` is what writes the file the Docker credential helper reads.
648//
649// Read failures add no hint: api.NewClientFromConfig would have failed on the
650// same unreadable token before the exchange ran, so it cannot be the cause here.
651func (o *options) exchangeError(hostname string, err error) error {
652 wrapped := fmt.Errorf("failed to exchange an artifact registry token from %s; docker pull would hit the same failure: %w", hostname, err)
654 // The environment is excluded, matching how the exchange's own client
655 // resolved its credential: a token only the environment holds is not one
656 // `docker pull` can ever use, so it must not silence the hint.
657 stored, _, storedErr := o.cfg.GetWithSource(hostname, "token", false)
658 if storedErr != nil || stored != "" {
659 return wrapped
660 }
662 // job_token is read with the environment included, on purpose: CI_JOB_TOKEN
663 // is how the Docker credential helper authenticates inside a CI job, so a
664 // host holding only that one is configured, not unconfigured.
665 jobToken, jobTokenErr := o.cfg.Get(hostname, "job_token")
666 if jobTokenErr != nil || jobToken != "" {
667 return wrapped
668 }
670 // No trailing period on either message: the CLI's error renderer appends one.
671 if environment, source := config.GetFromEnvWithSource("token"); environment != "" {
672 return fmt.Errorf("%w. %s is set, but nothing is stored for %s and neither this command nor the Docker credential helper reads the environment; run `glab auth login --hostname %s` to store a token", wrapped, source, hostname, hostname)
673 }
674 return fmt.Errorf("%w. No token is stored for %s; run `glab auth login --hostname %s` to store one", wrapped, hostname, hostname)
Diagnostics8 git calls · 274 ms
CallStatusSizeTime0274 ms
discover200185 B4 ms
git.upload-pack discover
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=fetch
git.upstream.dur_ms=3
git.response.bytes=185
git.server.agent=git/2.56.g1891de4-Linux
git.server.object_format=sha1
git.server.caps=agent ls-refs fetch server-option object-format
git.server.fetch=shallow wait-for-done filter
git.protocol.version=2
git.pkt.frames=9
git.pkt.data=7
git.pkt.flush=2
git.pkt.delim=0
git.pkt.bytes=185
git.pkt.payload.max=35
ls-refs20058 KiB3 ms
git.upload-pack ls-refs
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=ls-refs
git.upstream.dur_ms=3
git.response.bytes=59849
git.response.cache=UPDATING
git.response.duration_ms=3
git.protocol.version=2
git.pkt.frames=731
git.pkt.data=730
git.pkt.flush=1
git.pkt.delim=0
git.pkt.bytes=59849
git.pkt.payload.max=143
git.ls_refs.count=730
git.ls_refs.head=refs/heads/main
fetchcombine:blob:none+tree:2 · deepen 12004.2 KiB · hit2 ms
git.upload-pack fetch
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=fetch
git.upstream.dur_ms=2
git.response.bytes=4273
git.response.cache=HIT
git.response.duration_ms=2
git.fetch.filter=combine:blob:none+tree:2
git.fetch.wants=0dd7574dce9e385c5c30540e6c15657adc6bdce9
git.fetch.haves.count=0
git.fetch.deepen=1
git.fetch.thin_pack=false
git.fetch.ofs_delta=true
git.protocol.version=2
git.pkt.frames=7
git.pkt.data=5
git.pkt.flush=1
git.pkt.delim=1
git.pkt.bytes=4273
git.pkt.payload.max=4173
git.sideband.band1.bytes=4173
git.sideband.band2.bytes=0
git.sideband.band3.bytes=0
git.pack.objects=11
git.pack.bytes=4173
git.fetch.wide.objects=11
git.fetch.wide.extra_bytes=3930
git.fetch.wide.blobs=0
fetchtree:0 · deepen 1020032 KiB · hit3 ms
git.upload-pack fetch
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=fetch
git.upstream.dur_ms=3
git.response.bytes=32926
git.response.cache=HIT
git.response.duration_ms=3
git.fetch.filter=tree:0
git.fetch.wants=0dd7574dce9e385c5c30540e6c15657adc6bdce9
git.fetch.haves.count=0
git.fetch.deepen=10
git.fetch.thin_pack=false
git.fetch.ofs_delta=true
git.protocol.version=2
git.pkt.frames=22
git.pkt.data=20
git.pkt.flush=1
git.pkt.delim=1
git.pkt.bytes=32926
git.pkt.payload.max=32046
git.sideband.band1.bytes=32046
git.sideband.band2.bytes=0
git.sideband.band3.bytes=0
git.pack.objects=80
git.pack.bytes=32046
git.pack.ofs_delta=36
git.pack.ref_delta=0
git.pack.chain.max=2
git.pack.trailer=cb0bad5d7ffc514895d8b21c4dd470327f90bc91
git.pack.full=44
Open pack map
fetchtree:02001.8 KiB · hit3 ms
git.upload-pack fetch
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=fetch
git.upstream.dur_ms=3
git.response.bytes=1857
git.response.cache=HIT
git.response.duration_ms=3
git.fetch.filter=tree:0
git.fetch.wants=dce174ff8c632a19d17eea99c8a9b7c37fb2b592
git.fetch.haves.count=0
git.fetch.deepen=0
git.fetch.thin_pack=false
git.fetch.ofs_delta=true
git.protocol.version=2
git.pkt.frames=4
git.pkt.data=3
git.pkt.flush=1
git.pkt.delim=0
git.pkt.bytes=1857
git.pkt.payload.max=1830
git.sideband.band1.bytes=1830
git.sideband.band2.bytes=0
git.sideband.band3.bytes=0
git.pack.objects=1
git.pack.bytes=1830
git.pack.trailer=fb03183b7909876778f740d196d7516811003517
Open pack map
fetchtree:0200242 B · hit3 ms
git.upload-pack fetch
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=fetch
git.upstream.dur_ms=2
git.response.bytes=242
git.response.cache=HIT
git.response.duration_ms=3
git.fetch.filter=tree:0
git.fetch.wants=5da85e254ab77f5f6e7e1419be57d524a9f8208e
git.fetch.haves.count=0
git.fetch.deepen=0
git.fetch.thin_pack=false
git.fetch.ofs_delta=true
git.protocol.version=2
git.pkt.frames=4
git.pkt.data=3
git.pkt.flush=1
git.pkt.delim=0
git.pkt.bytes=242
git.pkt.payload.max=215
git.sideband.band1.bytes=215
git.sideband.band2.bytes=0
git.sideband.band3.bytes=0
git.pack.objects=1
git.pack.bytes=215
git.pack.trailer=bd426fb1ae09d9fdcf755902c6903cd2eea819b2
Open pack map
fetchtree:0200494 B · hit2 ms
git.upload-pack fetch
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=fetch
git.upstream.dur_ms=260
git.response.bytes=494
git.response.cache=HIT
git.response.duration_ms=2
git.fetch.filter=tree:0
git.fetch.wants=400358373377bb8e4922d8b821520ebdf8130c4d
git.fetch.haves.count=0
git.fetch.deepen=0
git.fetch.thin_pack=false
git.fetch.ofs_delta=true
git.protocol.version=2
git.pkt.frames=4
git.pkt.data=3
git.pkt.flush=1
git.pkt.delim=0
git.pkt.bytes=494
git.pkt.payload.max=467
git.sideband.band1.bytes=467
git.sideband.band2.bytes=0
git.sideband.band3.bytes=0
git.pack.objects=1
git.pack.bytes=467
git.pack.trailer=363b27e4d94209a9331c11b44fe1ce6e5f4e6e81
Open pack map
fetch20010 KiB260 ms
git.upload-pack fetch
http.response.status_code=200
git.response.bytes=10665
git.response.cache=MISS
git.response.duration_ms=260
git.fetch.wants=49b048061c03023f06ac40c324a8e5514e91066b
git.fetch.haves.count=0
git.fetch.deepen=0
git.fetch.thin_pack=false
git.fetch.ofs_delta=true
git.protocol.version=2
git.pkt.frames=4
git.pkt.data=3
git.pkt.flush=1
git.pkt.delim=0
git.pkt.bytes=10665
git.pkt.payload.max=10638
git.sideband.band1.bytes=10638
git.sideband.band2.bytes=0
git.sideband.band3.bytes=0

Each row is one HTTP round trip ply made to the git server for this page, on one timeline. discover asks what the server speaks, ls-refs lists branch tips, fetch brings objects by id. A hit was served by Workers Cache. Tap a row for its wire details.

Remote
https://gitlab.com/gitlab-org/cli
Ref
refs/heads/main
Commit
0dd7574dce9e385c5c30540e6c15657adc6bdce9
cf-ray
a5e2f841bdac90c0
Request
e6fd4fba…
Protocol
v2 · sha1
Agent
git/2.56.g1891de4-Linux
Filter
advertised
Fetch
shallow wait-for-done filter
Capabilities
agent ls-refs fetch server-option object-format