GitLabgitlab-org

cli

main
ply8 git calls259 ms109 KiB5 cachedprotocol v2
1337 lines51 KiBRaw
1//go:build !integration
3package login
5import (
6 "encoding/json"
7 "errors"
8 "net/http"
9 "net/http/httptest"
10 "net/url"
11 "os"
12 "path/filepath"
13 "strings"
14 "sync/atomic"
15 "testing"
16 "time"
18 "github.com/golang-jwt/jwt/v5"
19 "github.com/stretchr/testify/assert"
20 "github.com/stretchr/testify/require"
22 gitlab "gitlab.com/gitlab-org/api/client-go/v3"
24 "gitlab.com/gitlab-org/cli/internal/api"
25 "gitlab.com/gitlab-org/cli/internal/api/artifactregistry"
26 "gitlab.com/gitlab-org/cli/internal/config"
27 "gitlab.com/gitlab-org/cli/internal/glinstance"
28 "gitlab.com/gitlab-org/cli/internal/testing/cmdtest"
29 "gitlab.com/gitlab-org/cli/internal/testing/tokenexchangetest"
32// apiHost returns srv's host:port, since the api_host config key takes a bare
33// host:port rather than a full URL.
34func apiHost(t *testing.T, srv *httptest.Server) string {
35 t.Helper()
37 u, err := url.Parse(srv.URL)
38 require.NoError(t, err)
39 return u.Host
42// mustURL parses raw the way validate does, so a writer test hands its writer
43// the same *url.URL the command would.
44func mustURL(t *testing.T, raw string) *url.URL {
45 t.Helper()
47 u, err := url.Parse(raw)
48 require.NoError(t, err)
49 return u
52// storedToken is the credential newServerConfig puts in the configuration file,
53// named so a test can tell it apart from one set in the environment.
54const storedToken = "config-token"
56// newServerConfig builds a config that routes each of hostnames' API traffic to
57// srv and gives each a stored token.
58//
59// The token goes in the configuration file rather than GITLAB_TOKEN because the
60// --docker path builds its client with api.WithoutTokenFromEnvironment, the same
61// way the Docker credential helper builds its own, so an environment token would
62// be ignored here exactly as it is at `docker pull` time.
63func newServerConfig(t *testing.T, srv *httptest.Server, hostnames ...string) config.Config {
64 t.Helper()
66 var yaml strings.Builder
67 yaml.WriteString("---\nhosts:\n")
68 for _, hostname := range hostnames {
69 yaml.WriteString(" " + hostname + ":\n" +
70 " token: " + storedToken + "\n" +
71 " api_host: " + apiHost(t, srv) + "\n" +
72 " api_protocol: http\n")
73 }
75 return config.NewFromString(yaml.String())
78// clearAmbientTokens empties every environment variable the token and job_token
79// config keys resolve through, so a developer's shell or a CI job cannot decide
80// whether a test's host counts as having a credential. GLAB_ENABLE_CI_AUTOLOGIN
81// is in the list because it is what maps job_token onto CI_JOB_TOKEN.
82func clearAmbientTokens(t *testing.T) {
83 t.Helper()
85 for _, name := range []string{"GITLAB_TOKEN", "GITLAB_ACCESS_TOKEN", "OAUTH_TOKEN", "JOB_TOKEN", "GLAB_ENABLE_CI_AUTOLOGIN"} {
86 t.Setenv(name, "")
87 }
90// newTestExec wires NewCmd to cfg, which is where the --docker path finds
91// everything it needs: the API endpoint and credential for the verification
92// exchange, and the artifact_registry_domains it reads and writes.
93func newTestExec(t *testing.T, cfg config.Config) cmdtest.CmdExecFunc {
94 t.Helper()
96 return cmdtest.SetupCmdForTest(t, NewCmd, false, cmdtest.WithConfig(cfg))
99// newWriterTestExec wires NewCmd to an api.Client pointed at srv. Every writer
100// path (--maven, --gradle, --npm, --sbt, --yarn) exchanges through
101// options.apiClient, which is f.ApiClient, so unlike newTestExec it needs no
102// config: nothing on those paths reads one. Only --docker does.
103func newWriterTestExec(t *testing.T, srv *httptest.Server) cmdtest.CmdExecFunc {
104 t.Helper()
106 return tokenexchangetest.NewTestExec(t, srv, NewCmd)
109// wireRequest mirrors the JSON body `glab artifact-registry login` sends to
110// POST /api/v4/token_exchange for the non-docker writers.
111type wireRequest = tokenexchangetest.WireRequest
113// tokenServer starts a fake token_exchange endpoint that always returns
114// wantToken, decoding each request body into gotBody.
115func tokenServer(t *testing.T, wantToken string, gotBody *wireRequest) (*httptest.Server, *atomic.Int32) {
116 t.Helper()
118 return tokenexchangetest.NewTokenExchangeServer(t, wantToken, gotBody)
121// supportedOS stands in for dockercredhelper.Supported in tests that build
122// options directly, so they exercise validate on the supported-platform path
123// whatever the test host is.
124func supportedOS() error { return nil }
126// dockerTokenServer starts a token_exchange endpoint that succeeds, for the
127// --docker path's pre-write verification exchange.
128func dockerTokenServer(t *testing.T) *httptest.Server {
129 t.Helper()
131 token := tokenexchangetest.MakeJWT(t, jwt.RegisteredClaims{
132 Issuer: "https://gitlab.example.com",
133 Subject: "gid://gitlab/User/1",
134 ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Hour).Truncate(time.Second)),
135 })
137 srv, _ := tokenexchangetest.NewTestServer(t, func(w http.ResponseWriter, r *http.Request) {
138 w.Header().Set("Content-Type", "application/json")
139 w.WriteHeader(http.StatusOK)
140 _, _ = w.Write([]byte(`{"token":"` + token + `"}`))
141 })
142 return srv
145func TestLogin_NoToolFlag(t *testing.T) {
146 exec := cmdtest.SetupCmdForTest(t, NewCmd, false)
148 _, err := exec("--registry registry.example.com")
149 require.Error(t, err)
150 assert.Contains(t, err.Error(), "at least one of the flags")
153// TestLogin_TwoToolFlags pins that every pair of tool flags is refused, not
154// just the two the group started with. Each tool writes its own credential
155// file, so a pair that slipped through the group would write two of them from
156// one exchange.
157func TestLogin_TwoToolFlags(t *testing.T) {
158 tools := []string{"--docker", "--maven", "--gradle", "--npm", "--sbt", "--yarn"}
160 for i, first := range tools {
161 for _, second := range tools[i+1:] {
162 t.Run(first+" "+second, func(t *testing.T) {
163 exec := cmdtest.SetupCmdForTest(t, NewCmd, false)
165 _, err := exec(first + " " + second + " --registry registry.example.com")
166 require.Error(t, err)
167 assert.Contains(t, err.Error(), "none of the others can be")
168 })
169 }
170 }
173func TestLogin_ToolFlagFalseLeavesNoneSelected(t *testing.T) {
174 exec := cmdtest.SetupCmdForTest(t, NewCmd, false)
176 // MarkFlagsOneRequired only checks that a flag in the group was passed,
177 // so --docker=false alone satisfies it and reaches validate() with no
178 // tool actually selected.
179 _, err := exec("--docker=false --registry registry.example.com")
180 require.Error(t, err)
181 assert.Contains(t, err.Error(), "invalid --docker, --maven, --gradle, --npm, --sbt, and --yarn: all false leaves no tool selected")
184func TestLogin_MissingRegistry(t *testing.T) {
185 exec := cmdtest.SetupCmdForTest(t, NewCmd, false)
187 _, err := exec("--docker")
188 require.Error(t, err)
189 assert.Contains(t, err.Error(), "required flag")
192func TestLogin_RegistryMustBeBareHostname(t *testing.T) {
193 exec := cmdtest.SetupCmdForTest(t, NewCmd, false)
195 _, err := exec("--docker --registry https://has-a-scheme.example.com")
196 require.Error(t, err)
197 assert.Contains(t, err.Error(), "bare hostname")
200func TestLogin_RegistryMustNotContainComma(t *testing.T) {
201 exec := cmdtest.SetupCmdForTest(t, NewCmd, false)
203 _, err := exec("--docker --registry registry.example.com,other.example.com")
204 require.Error(t, err)
205 assert.Contains(t, err.Error(), "comma")
208func TestLogin_RegistryMustNotBeEmpty(t *testing.T) {
209 exec := cmdtest.SetupCmdForTest(t, NewCmd, false)
211 // cobra's MarkFlagRequired only checks that the flag was passed, so an
212 // explicitly empty value reaches validate().
213 _, err := exec(`--docker --registry ""`)
214 require.Error(t, err)
215 assert.Contains(t, err.Error(), "invalid --registry: must not be empty")
218// TestLogin_RegistryMustNotContainControlCharacters exercises validate()
219// directly: shlex-parsing a CLI string can't produce an embedded literal
220// newline in --registry, so this goes through options.validate() rather
221// than exec().
222func TestLogin_RegistryMustNotContainControlCharacters(t *testing.T) {
223 for name, o := range map[string]*options{
224 "maven": {registry: "https://ar.example.com/\nEvil=1", writer: writerForFlag("maven")},
225 "gradle": {registry: "https://ar.example.com/\nEvil=1", writer: writerForFlag("gradle")},
226 "npm": {registry: "https://ar.example.com/\nEvil=1", writer: writerForFlag("npm")},
227 "sbt": {registry: "https://ar.example.com/\nEvil=1", writer: writerForFlag("sbt")},
228 "yarn": {registry: "https://ar.example.com/\nEvil=1", writer: writerForFlag("yarn")},
229 "docker": {registry: "ar.example.com\nEvil=1", docker: true, supportedOS: supportedOS},
230 } {
231 t.Run(name, func(t *testing.T) {
232 err := o.validate()
233 require.Error(t, err)
234 assert.Contains(t, err.Error(), "control characters")
235 })
236 }
239func TestLogin_RegistryAliasMustBeSafeCharacters(t *testing.T) {
240 exec := cmdtest.SetupCmdForTest(t, NewCmd, false)
242 _, err := exec(`--maven --registry https://ar.example.com --registry-alias "bad<id>"`)
243 require.Error(t, err)
244 assert.Contains(t, err.Error(), "--registry-alias")
247func TestLogin_RegistryAliasIgnoredOutsideMavenGradleWarning(t *testing.T) {
248 binDir := t.TempDir()
249 writeFakeGlab(t, binDir)
250 setPath(t, binDir)
251 setHome(t, t.TempDir())
253 srv := dockerTokenServer(t)
254 exec := newTestExec(t, newServerConfig(t, srv, glinstance.DefaultHostname))
256 out, err := exec("--docker --registry registry.example.com --registry-alias my-alias")
257 require.NoError(t, err)
258 assert.Contains(t, out.ErrBuf.String(), "--registry-alias is ignored")
261func TestLogin_ConfigFileIgnoredOutsideMavenSbtWarning(t *testing.T) {
262 binDir := t.TempDir()
263 writeFakeGlab(t, binDir)
264 setPath(t, binDir)
265 setHome(t, t.TempDir())
267 srv := dockerTokenServer(t)
268 exec := newTestExec(t, newServerConfig(t, srv, glinstance.DefaultHostname))
270 out, err := exec("--docker --registry registry.example.com --config-file settings.xml")
271 require.NoError(t, err)
272 assert.Contains(t, out.ErrBuf.String(), "--config-file is ignored")
275func TestLogin_ConfigFileMustNotBeDirectory(t *testing.T) {
276 for _, tool := range []string{"--maven", "--sbt"} {
277 t.Run(tool, func(t *testing.T) {
278 exec := cmdtest.SetupCmdForTest(t, NewCmd, false)
280 _, err := exec(tool + " --registry https://ar.example.com --config-file " + t.TempDir())
281 require.Error(t, err)
282 assert.Contains(t, err.Error(), "invalid --config-file")
283 })
285 t.Run(tool+" trailing separator on a missing directory", func(t *testing.T) {
286 setHome(t, t.TempDir())
287 srv, count := tokenexchangetest.NewTestServer(t, func(w http.ResponseWriter, r *http.Request) {
288 t.Errorf("unexpected request to fake server: %s %s", r.Method, r.URL.Path)
289 w.WriteHeader(http.StatusInternalServerError)
290 })
291 exec := newWriterTestExec(t, srv)
292 dir := filepath.Join(t.TempDir(), "newdir")
294 _, err := exec(tool + " --registry https://ar.example.com --config-file " + dir + string(os.PathSeparator))
295 require.Error(t, err)
296 assert.Contains(t, err.Error(), "is a directory")
297 assert.EqualValues(t, 0, count.Load(), "a directory path must be rejected before the token exchange")
298 assert.NoDirExists(t, dir)
299 })
300 }
303// TestLogin_Sbt_ConfigFileMustBeSbtFile pins that --sbt refuses a file sbt
304// would not load as Scala, such as the ~/.sbt/.credentials properties file,
305// before the token exchange and without touching the file.
306func TestLogin_Sbt_ConfigFileMustBeSbtFile(t *testing.T) {
307 setHome(t, t.TempDir())
308 srv, count := tokenexchangetest.NewTestServer(t, func(w http.ResponseWriter, r *http.Request) {
309 t.Errorf("unexpected request to fake server: %s %s", r.Method, r.URL.Path)
310 w.WriteHeader(http.StatusInternalServerError)
311 })
312 exec := newWriterTestExec(t, srv)
313 path := filepath.Join(t.TempDir(), ".credentials")
314 const fixture = "realm=Sonatype Nexus Repository Manager\nhost=example.com\n"
315 require.NoError(t, os.WriteFile(path, []byte(fixture), 0o600))
317 _, err := exec("--sbt --registry https://ar.example.com --config-file " + path)
318 require.Error(t, err)
319 assert.Contains(t, err.Error(), "is not a .sbt file")
320 assert.EqualValues(t, 0, count.Load(), "a non-.sbt path must be rejected before the token exchange")
322 got, err := os.ReadFile(path)
323 require.NoError(t, err)
324 assert.Equal(t, fixture, string(got))
327func TestLogin_Npm_RegistryMustHaveSchemeAndHost(t *testing.T) {
328 exec := cmdtest.SetupCmdForTest(t, NewCmd, false)
330 _, err := exec("--npm --registry registry.example.com:8080")
331 require.Error(t, err)
332 assert.Contains(t, err.Error(), "scheme and host")
335// TestLogin_Gradle_RegistryMustHaveSchemeAndHost pins that --gradle is held to
336// the same URL shape as --npm and --sbt. It writes the registry into
337// {alias}Url, so a value that is not a URL only fails later, at build time.
338// --maven is the exception and has its own test below.
339func TestLogin_Gradle_RegistryMustHaveSchemeAndHost(t *testing.T) {
340 exec := cmdtest.SetupCmdForTest(t, NewCmd, false)
342 _, err := exec("--gradle --registry registry.example.com:8080")
343 require.Error(t, err)
344 assert.Contains(t, err.Error(), "scheme and host")
347// TestLogin_Maven_RegistryNeedsNoURLShape pins the deliberate exception: a
348// <server> block carries only the alias and the credentials, and the URL lives
349// in the caller's pom.xml, so --maven accepts a bare host.
350func TestLogin_Maven_RegistryNeedsNoURLShape(t *testing.T) {
351 setHome(t, t.TempDir())
353 wantToken := tokenexchangetest.MakeJWT(t, jwt.RegisteredClaims{
354 Issuer: "https://gitlab.example.com",
355 Subject: "gid://gitlab/User/1",
356 ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Hour).Truncate(time.Second)),
357 })
358 var gotBody wireRequest
359 srv, count := tokenServer(t, wantToken, &gotBody)
360 exec := newWriterTestExec(t, srv)
362 _, err := exec("--maven --registry registry.example.com")
363 require.NoError(t, err)
364 assert.EqualValues(t, 1, count.Load())
367func TestLogin_Sbt_RegistryMustHaveSchemeAndHost(t *testing.T) {
368 exec := cmdtest.SetupCmdForTest(t, NewCmd, false)
370 _, err := exec("--sbt --registry registry.example.com:8080")
371 require.Error(t, err)
372 assert.Contains(t, err.Error(), "scheme and host")
375func TestLogin_Yarn_RegistryMustHaveSchemeAndHost(t *testing.T) {
376 exec := cmdtest.SetupCmdForTest(t, NewCmd, false)
378 _, err := exec("--yarn --registry registry.example.com:8080")
379 require.Error(t, err)
380 assert.Contains(t, err.Error(), "scheme and host")
383// TestLogin_Sbt_SuccessMessageNamesEachFileAndItsVersion pins that the message
384// says which file each sbt version reads. sbt picks one from the sbt.version a
385// project declares, so a message naming only one file leaves a user on the
386// other version unable to tell where the token went.
387func TestLogin_Sbt_SuccessMessageNamesEachFileAndItsVersion(t *testing.T) {
388 home := t.TempDir()
389 setHome(t, home)
391 token := tokenexchangetest.MakeJWT(t, jwt.RegisteredClaims{
392 Issuer: "https://gitlab.example.com",
393 Subject: "gid://gitlab/User/1",
394 ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Hour).Truncate(time.Second)),
395 })
396 var gotBody wireRequest
397 srv, _ := tokenServer(t, token, &gotBody)
398 exec := newWriterTestExec(t, srv)
400 out, err := exec("--sbt --registry https://ar.example.com")
401 require.NoError(t, err)
402 assert.Contains(t, out.OutBuf.String(), "Configured sbt for https://ar.example.com. Wrote "+
403 sbtCredentialsPath(home)+" for sbt 1.x and "+sbt2CredentialsPath(home)+" for sbt 2.x.")
404 assert.Empty(t, out.ErrBuf.String())
407// TestLogin_Sbt_SuccessMessageSaysARunningSbtKeepsItsCredentials pins the
408// reload hint. sbt compiles credentials.sbt when it loads the build, and sbt 2.x
409// keeps a server running for days by default, so without the hint a refreshed
410// login looks done while the next build still sends the expired token.
411func TestLogin_Sbt_SuccessMessageSaysARunningSbtKeepsItsCredentials(t *testing.T) {
412 setHome(t, t.TempDir())
414 token := tokenexchangetest.MakeJWT(t, jwt.RegisteredClaims{
415 Issuer: "https://gitlab.example.com",
416 Subject: "gid://gitlab/User/1",
417 ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Hour).Truncate(time.Second)),
418 })
419 var gotBody wireRequest
420 srv, _ := tokenServer(t, token, &gotBody)
421 exec := newWriterTestExec(t, srv)
423 out, err := exec("--sbt --registry https://ar.example.com")
424 require.NoError(t, err)
425 assert.Contains(t, out.OutBuf.String(), "An sbt shell or sbt 2.x server that is already running keeps the credentials it loaded: run `reload` in it, or `sbt shutdown`.")
428// TestLogin_Sbt_WarnsAboutASkippedVariable pins the warning for a relative
429// SBT_CONFIG_HOME. sbt 2.x resolves it against the build directory, so the
430// sbt 2.x file the success line names is one that build never reads.
431func TestLogin_Sbt_WarnsAboutASkippedVariable(t *testing.T) {
432 setHome(t, t.TempDir())
433 t.Setenv("SBT_CONFIG_HOME", "relative")
435 token := tokenexchangetest.MakeJWT(t, jwt.RegisteredClaims{
436 Issuer: "https://gitlab.example.com",
437 Subject: "gid://gitlab/User/1",
438 ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Hour).Truncate(time.Second)),
439 })
440 var gotBody wireRequest
441 srv, _ := tokenServer(t, token, &gotBody)
442 exec := newWriterTestExec(t, srv)
444 out, err := exec("--sbt --registry https://ar.example.com")
445 require.NoError(t, err)
446 assert.Contains(t, out.ErrBuf.String(), "SBT_CONFIG_HOME is blank or a relative path, so glab skipped it.")
449// TestLogin_Yarn_SuccessMessageClaimsOnlyTheToken pins that the message says a
450// token was written, not that Yarn was configured: Yarn keeps fetching from
451// its default registry until npmRegistryServer names this one.
452func TestLogin_Yarn_SuccessMessageClaimsOnlyTheToken(t *testing.T) {
453 setHome(t, t.TempDir())
455 token := tokenexchangetest.MakeJWT(t, jwt.RegisteredClaims{
456 Issuer: "https://gitlab.example.com",
457 Subject: "gid://gitlab/User/1",
458 ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Hour).Truncate(time.Second)),
459 })
460 var gotBody wireRequest
461 srv, _ := tokenServer(t, token, &gotBody)
462 exec := newWriterTestExec(t, srv)
464 out, err := exec("--yarn --registry https://ar.example.com")
465 require.NoError(t, err)
466 assert.Contains(t, out.OutBuf.String(), "Wrote a Yarn auth token for https://ar.example.com.")
467 assert.Contains(t, out.OutBuf.String(), "npmRegistryServer")
468 assert.NotContains(t, out.OutBuf.String(), "Configured")
469 assert.Empty(t, out.ErrBuf.String())
472// TestLogin_Yarn_WarnsAboutAScopeWithItsOwnToken pins the warning for a scope
473// whose own npmAuthToken Yarn sends instead of the token this command wrote.
474func TestLogin_Yarn_WarnsAboutAScopeWithItsOwnToken(t *testing.T) {
475 home := t.TempDir()
476 setHome(t, home)
477 fixture := "npmScopes:\n acme:\n npmRegistryServer: \"https://ar.example.com\"\n npmAuthToken: old\n"
478 require.NoError(t, os.WriteFile(filepath.Join(home, ".yarnrc.yml"), []byte(fixture), 0o600))
480 token := tokenexchangetest.MakeJWT(t, jwt.RegisteredClaims{
481 Issuer: "https://gitlab.example.com",
482 Subject: "gid://gitlab/User/1",
483 ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Hour).Truncate(time.Second)),
484 })
485 var gotBody wireRequest
486 srv, _ := tokenServer(t, token, &gotBody)
487 exec := newWriterTestExec(t, srv)
489 out, err := exec("--yarn --registry https://ar.example.com")
490 require.NoError(t, err)
491 assert.Contains(t, out.OutBuf.String(), "Wrote a Yarn auth token for https://ar.example.com.")
492 assert.Contains(t, out.ErrBuf.String(), `The npmScopes entry "acme" in ~/.yarnrc.yml has its own npmAuthToken or npmAuthIdent, and Yarn sends that for @acme packages instead of this token.`)
495// TestLogin_RegistryWithoutASchemeIsRejected pins the "scheme" half of the
496// message the four URL-shaped writers share. url.Parse gives a
497// scheme-relative "//ar.example.com" a host and no scheme, so a host-only
498// check would accept it, and --gradle would write it verbatim into {alias}Url
499// for Gradle to reject at build time.
500func TestLogin_RegistryWithoutASchemeIsRejected(t *testing.T) {
501 for _, flag := range []string{"--gradle", "--npm", "--sbt", "--yarn"} {
502 t.Run(flag, func(t *testing.T) {
503 exec := cmdtest.SetupCmdForTest(t, NewCmd, false)
505 _, err := exec(flag + " --registry //ar.example.com")
506 require.Error(t, err)
507 assert.Contains(t, err.Error(), "scheme and host")
508 })
509 }
512// TestLogin_RegistryHostMustLookLikeAHost pins that a host carrying anything
513// but host-name characters is refused before a writer sees it. url.Parse
514// accepts '"', '(' and ')' in a host, and credentials.sbt is compiled as
515// Scala: one '"' closes the string literal, so the rest of the host would land
516// in the file as code that sbt runs on every build.
517// Exercised through options.validate() rather than exec(), since shlex cannot
518// carry an unbalanced quote through a command line.
519func TestLogin_RegistryHostMustLookLikeAHost(t *testing.T) {
520 for name, registry := range map[string]string{
521 "scala injection": `https://x")+sys.error("boom")+Credentials("z/`,
522 "single quote": `https://ar.example.com"/`,
523 "unicode host": `https://münchen.example.com/`,
524 } {
525 for _, o := range []*options{
526 {registry: registry, writer: writerForFlag("gradle")},
527 {registry: registry, writer: writerForFlag("npm")},
528 {registry: registry, writer: writerForFlag("sbt")},
529 {registry: registry, writer: writerForFlag("yarn")},
530 } {
531 t.Run(name, func(t *testing.T) {
532 err := o.validate()
534 require.Error(t, err)
535 assert.Contains(t, err.Error(), "its host must be")
536 })
537 }
538 }
541// TestLogin_RegistryHostAcceptsAnIPAddress guards the other side of that
542// check: an IP literal is a legitimate registry host, and an IPv6 one arrives
543// from url.Parse without its brackets.
544func TestLogin_RegistryHostAcceptsAnIPAddress(t *testing.T) {
545 for _, registry := range []string{"https://192.0.2.10:8443/", "https://[2001:db8::1]:8443/"} {
546 t.Run(registry, func(t *testing.T) {
547 setHome(t, t.TempDir())
549 token := tokenexchangetest.MakeJWT(t, jwt.RegisteredClaims{
550 Issuer: "https://gitlab.example.com",
551 Subject: "gid://gitlab/User/1",
552 ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Hour).Truncate(time.Second)),
553 })
554 var gotBody wireRequest
555 srv, count := tokenServer(t, token, &gotBody)
556 exec := newWriterTestExec(t, srv)
558 _, err := exec("--npm --registry " + registry)
560 require.NoError(t, err)
561 assert.EqualValues(t, 1, count.Load())
562 })
563 }
566// TestLogin_UnresolvableHomeDirectoryIsReported pins the shared homeDir
567// helper's contract: every writer roots its target path in the home
568// directory, and each one reports the same failure, in the same words, when
569// it cannot be resolved.
570func TestLogin_UnresolvableHomeDirectoryIsReported(t *testing.T) {
571 for _, flag := range []string{"--gradle", "--npm", "--sbt", "--yarn"} {
572 t.Run(flag, func(t *testing.T) {
573 setHome(t, "")
575 token := tokenexchangetest.MakeJWT(t, jwt.RegisteredClaims{
576 Issuer: "https://gitlab.example.com",
577 Subject: "gid://gitlab/User/1",
578 ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Hour).Truncate(time.Second)),
579 })
580 var gotBody wireRequest
581 srv, _ := tokenServer(t, token, &gotBody)
582 exec := newWriterTestExec(t, srv)
584 _, err := exec(flag + " --registry https://ar.example.com")
585 require.Error(t, err)
586 assert.Contains(t, err.Error(), "resolving home directory")
587 })
588 }
591// writerPaths maps each token-writing tool flag to the file it writes, keyed by
592// flag so a new writer that forgets to register here fails the "every tool flag
593// is covered" check in TestLogin_DispatchesToTheSelectedWriter.
594var writerPaths = map[string]func(home string) string{
595 "--maven": settingsPath,
596 "--gradle": gradlePropertiesPath,
597 "--npm": npmrcPath,
598 "--sbt": sbtCredentialsPath,
599 "--yarn": yarnrcPath,
602// TestLogin_DispatchesToTheSelectedWriter pins which writer each tool flag
603// reaches. Asserting the exchange happened is not enough on its own: every arm
604// exchanges a token, so a flag wired to the wrong writer would satisfy a
605// request-count assertion. Each case therefore also checks that the token
606// landed in that tool's file and that no other tool's file was created.
607func TestLogin_DispatchesToTheSelectedWriter(t *testing.T) {
608 paths := writerPaths
610 for flag, wantPath := range paths {
611 t.Run(flag, func(t *testing.T) {
612 home := t.TempDir()
613 setHome(t, home)
615 wantToken := tokenexchangetest.MakeJWT(t, jwt.RegisteredClaims{
616 Issuer: "https://gitlab.example.com",
617 Subject: "gid://gitlab/User/1",
618 ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Hour).Truncate(time.Second)),
619 })
620 var gotBody wireRequest
621 srv, count := tokenServer(t, wantToken, &gotBody)
622 exec := newWriterTestExec(t, srv)
624 _, err := exec(flag + " --registry https://ar.example.com")
625 require.NoError(t, err)
626 assert.EqualValues(t, 1, count.Load())
628 got, err := os.ReadFile(wantPath(home))
629 require.NoError(t, err, "%s must write its own file", flag)
630 assert.Contains(t, string(got), wantToken, "%s must write the exchanged token", flag)
632 for otherFlag, otherPath := range paths {
633 if otherFlag == flag {
634 continue
635 }
636 _, err := os.Stat(otherPath(home))
637 assert.ErrorIs(t, err, os.ErrNotExist, "%s must not write %s's file", flag, otherFlag)
638 }
639 })
640 }
642 // Guards the map above against drifting from the command's actual flag set,
643 // in the direction that matters: a writer added without a writerPaths entry
644 // is one this test and TestLogin_TokenWithALineBreakReachesNoWriter would
645 // silently stop covering. Walking the map instead would only catch a flag
646 // that was removed.
647 //
648 // --docker is the one tool flag with no writerPaths entry: it registers a
649 // credential helper rather than writing a credential file of its own.
650 for _, w := range writers {
651 _, ok := paths["--"+w.flag]
652 assert.True(t, ok, "--%s writes a credential file but has no writerPaths entry", w.flag)
653 }
654 assert.Len(t, paths, len(writers), "writers table and writerPaths must have the same number of entries")
657// TestLogin_TokenWithALineBreakReachesNoWriter pins that a token carrying a line
658// break is refused before any credential file is touched.
659//
660// Every writer interpolates the token into a file it does not re-parse, so a
661// line break in it becomes a line of that file: a bare entry in .npmrc or
662// gradle.properties, and in credentials.sbt a syntax error in a file sbt
663// compiles as Scala, which breaks every later build.
664//
665// The break survives the claims decode, which is why the shape check in
666// artifactregistry.exchange is load-bearing rather than belt-and-braces: Go's
667// base64 decoder treats "\r" and "\n" as insignificant whitespace, so a token
668// whose signature segment carries one decodes cleanly, claims and all. Bytes
669// like "=", ":" and '"' cannot get this far, the base64 decode rejects those
670// already; the line breaks were the gap.
671func TestLogin_TokenWithALineBreakReachesNoWriter(t *testing.T) {
672 for flag, path := range writerPaths {
673 t.Run(flag, func(t *testing.T) {
674 home := t.TempDir()
675 setHome(t, home)
677 valid := tokenexchangetest.MakeJWT(t, jwt.RegisteredClaims{
678 Issuer: "https://gitlab.example.com",
679 Subject: "gid://gitlab/User/1",
680 ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Hour).Truncate(time.Second)),
681 })
682 // Spliced into the signature segment, so what follows the break would
683 // land on its own line in the written file.
684 cut := strings.LastIndex(valid, ".") + 3
685 require.Less(t, cut, len(valid), "the signature segment must be long enough to split")
686 crafted := valid[:cut] + "\n" + valid[cut:]
688 var gotBody wireRequest
689 srv, count := tokenServer(t, crafted, &gotBody)
690 exec := newWriterTestExec(t, srv)
692 _, err := exec(flag + " --registry https://ar.example.com")
694 require.Error(t, err, "%s must refuse a token carrying a line break", flag)
695 assert.EqualValues(t, 1, count.Load(), "the refusal must come after the exchange, not instead of it")
697 _, statErr := os.Stat(path(home))
698 assert.ErrorIs(t, statErr, os.ErrNotExist, "%s must write nothing when the token is refused", flag)
699 })
700 }
703func TestLogin_Maven_DurationOutOfRange(t *testing.T) {
704 srv, count := tokenexchangetest.NewTestServer(t, func(w http.ResponseWriter, r *http.Request) {
705 t.Errorf("unexpected request to fake server: %s %s", r.Method, r.URL.Path)
706 w.WriteHeader(http.StatusInternalServerError)
707 })
708 exec := newWriterTestExec(t, srv)
710 _, err := exec("--maven --registry https://ar.example.com --duration 13h")
711 require.Error(t, err)
712 assert.EqualValues(t, 0, count.Load(), "an out-of-range duration must be rejected before making an HTTP call")
715func TestLogin_Maven_DispatchesToWriterAfterExchangingToken(t *testing.T) {
716 setHome(t, t.TempDir())
718 exp := time.Now().Add(time.Hour).Truncate(time.Second)
719 wantToken := tokenexchangetest.MakeJWT(t, jwt.RegisteredClaims{
720 Issuer: "https://gitlab.example.com",
721 Subject: "gid://gitlab/User/1",
722 ExpiresAt: jwt.NewNumericDate(exp),
723 })
725 var gotBody wireRequest
726 srv, count := tokenServer(t, wantToken, &gotBody)
727 exec := newWriterTestExec(t, srv)
729 _, err := exec("--maven --registry https://ar.example.com")
730 require.NoError(t, err)
731 assert.EqualValues(t, 1, count.Load())
734func TestLogin_ConfigFile_WritesNamedFileOnly(t *testing.T) {
735 for _, tc := range []struct {
736 tool, file, wantMessage string
737 }{
738 {tool: "--maven", file: "ci-settings.xml", wantMessage: "Configured Maven server"},
739 {tool: "--sbt", file: "credentials.sbt", wantMessage: "Configured sbt"},
740 } {
741 t.Run(tc.tool, func(t *testing.T) {
742 home := t.TempDir()
743 setHome(t, home)
744 configFile := filepath.Join(t.TempDir(), tc.file)
746 wantToken := tokenexchangetest.MakeJWT(t, jwt.RegisteredClaims{
747 Issuer: "https://gitlab.example.com",
748 Subject: "gid://gitlab/User/1",
749 ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Hour)),
750 })
751 srv, _ := tokenServer(t, wantToken, &wireRequest{})
752 exec := newWriterTestExec(t, srv)
754 out, err := exec(tc.tool + " --registry https://ar.example.com --config-file " + configFile)
755 require.NoError(t, err)
757 content, err := os.ReadFile(configFile)
758 require.NoError(t, err)
759 assert.Contains(t, string(content), wantToken)
760 assert.Contains(t, out.OutBuf.String(), tc.wantMessage)
761 assert.Contains(t, out.OutBuf.String(), configFile, "the success message must name --config-file so a mistyped path is visible")
763 entries, err := os.ReadDir(home)
764 require.NoError(t, err)
765 assert.Empty(t, entries, "nothing may be written under HOME when --config-file is set")
766 })
767 }
770// TestLogin_Maven_ForwardsDurationToExchange pins the --duration value the
771// --maven path puts on the wire, in both directions: an explicit value must
772// reach token_exchange instead of the flag's default, and an omitted flag must
773// send DefaultDuration rather than whatever a previous run asked for.
774func TestLogin_Maven_ForwardsDurationToExchange(t *testing.T) {
775 tests := []struct {
776 name string
777 args string
778 wantExpiresIn time.Duration
779 }{
780 {
781 name: "explicit duration is forwarded",
782 args: "--maven --registry https://ar.example.com --duration 42m",
783 wantExpiresIn: 42 * time.Minute,
784 },
785 {
786 name: "omitted duration sends the default",
787 args: "--maven --registry https://ar.example.com",
788 wantExpiresIn: artifactregistry.DefaultDuration,
789 },
790 }
792 for _, tc := range tests {
793 t.Run(tc.name, func(t *testing.T) {
794 setHome(t, t.TempDir())
796 wantToken := tokenexchangetest.MakeJWT(t, jwt.RegisteredClaims{
797 Issuer: "https://gitlab.example.com",
798 Subject: "gid://gitlab/User/1",
799 ExpiresAt: jwt.NewNumericDate(time.Now().Add(tc.wantExpiresIn).Truncate(time.Second)),
800 })
802 var gotBody wireRequest
803 srv, count := tokenServer(t, wantToken, &gotBody)
804 exec := newWriterTestExec(t, srv)
806 _, err := exec(tc.args)
807 require.NoError(t, err)
809 assert.EqualValues(t, 1, count.Load())
810 assert.Equal(t, wireRequest{
811 Audience: "gitlab-artifact-registry",
812 ExpiresIn: int(tc.wantExpiresIn.Seconds()),
813 }, gotBody)
814 })
815 }
818// TestLogin_Maven_DefaultRegistryAliasIsDerivedFromRegistry pins that a
819// --maven login with no --registry-alias writes a <server> block keyed by an
820// alias derived from --registry, not a literal or empty id.
821func TestLogin_Maven_DefaultRegistryAliasIsDerivedFromRegistry(t *testing.T) {
822 home := t.TempDir()
823 setHome(t, home)
825 wantToken := tokenexchangetest.MakeJWT(t, jwt.RegisteredClaims{
826 Issuer: "https://gitlab.example.com",
827 Subject: "gid://gitlab/User/1",
828 ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Hour).Truncate(time.Second)),
829 })
830 var gotBody wireRequest
831 srv, _ := tokenServer(t, wantToken, &gotBody)
832 exec := newWriterTestExec(t, srv)
834 _, err := exec("--maven --registry https://ar.example.com")
835 require.NoError(t, err)
837 content, readErr := os.ReadFile(settingsPath(home))
838 require.NoError(t, readErr)
839 assert.Contains(t, string(content), "<id>artifact-registry-ar-example-com</id>")
842// TestLogin_RegistryMustNotContainWhitespace covers the value that would
843// otherwise be written verbatim into artifact_registry_domains and read back
844// trimmed by config.ParseDomains: the credHelpers key Docker looks up would
845// never match, and each login would append another entry to the domain list.
846func TestLogin_RegistryMustNotContainWhitespace(t *testing.T) {
847 tests := []struct {
848 name string
849 registry string
850 }{
851 {name: "leading space", registry: " registry.example.com"},
852 {name: "trailing space", registry: "registry.example.com "},
853 {name: "inner tab", registry: "registry.example.com\tother.example.com"},
854 }
856 for _, tc := range tests {
857 t.Run(tc.name, func(t *testing.T) {
858 exec := cmdtest.SetupCmdForTest(t, NewCmd, false)
860 _, err := exec(`--docker --registry "` + tc.registry + `"`)
861 require.Error(t, err)
862 assert.Contains(t, err.Error(), "invalid --registry: must not contain whitespace or control characters")
863 })
864 }
867func TestLogin_InvalidHostname(t *testing.T) {
868 tests := []struct {
869 name string
870 hostname string
871 }{
872 {name: "URL rather than hostname", hostname: "https://gitlab.example.com"},
873 {name: "hostname with a port", hostname: "gitlab.example.com:8080"},
874 {name: "hostname with a path", hostname: "gitlab.example.com/foo"},
875 }
877 for _, tc := range tests {
878 t.Run(tc.name, func(t *testing.T) {
879 exec := cmdtest.SetupCmdForTest(t, NewCmd, false)
881 _, err := exec("--docker --registry registry.example.com --hostname " + tc.hostname)
882 require.Error(t, err)
883 assert.Contains(t, err.Error(), "error parsing --hostname")
884 })
885 }
888// TestLogin_HostnameMustNotContainWhitespace covers what
889// glinstance.HostnameValidator lets through: it rejects only "/" and ":", so
890// without this check a hostname with a space reaches glinstance.APIEndpoint and
891// fails with a net/url parse error instead of a FlagError naming the flag.
892func TestLogin_HostnameMustNotContainWhitespace(t *testing.T) {
893 exec := cmdtest.SetupCmdForTest(t, NewCmd, false)
895 _, err := exec(`--docker --registry registry.example.com --hostname "gitlab example.com"`)
896 require.Error(t, err)
897 assert.Contains(t, err.Error(), "invalid --hostname: must not contain whitespace or control characters")
900func TestLogin_Docker_ExchangeFailureWritesNothing(t *testing.T) {
901 binDir := t.TempDir()
902 home := t.TempDir()
903 // glab is on PATH here on purpose: with it missing, the shim assertion
904 // below would pass because Install could never have run, rather than
905 // because the failed exchange stopped it.
906 writeFakeGlab(t, binDir)
907 setPath(t, binDir)
908 setHome(t, home)
910 srv, _ := tokenexchangetest.NewTestServer(t, func(w http.ResponseWriter, r *http.Request) {
911 w.Header().Set("Content-Type", "application/json")
912 w.WriteHeader(http.StatusForbidden)
913 _, _ = w.Write([]byte(`{"message":"artifact registry is disabled for this project"}`))
914 })
915 cfg := newServerConfig(t, srv, glinstance.DefaultHostname)
916 exec := newTestExec(t, cfg)
918 _, err := exec("--docker --registry registry.example.com")
919 require.Error(t, err)
920 assert.Contains(t, err.Error(), "artifact registry is disabled for this project")
922 domains, getErr := cfg.Get(glinstance.DefaultHostname, "artifact_registry_domains")
923 require.NoError(t, getErr)
924 assert.Empty(t, domains, "a failed exchange must leave no config behind")
926 _, statErr := os.Stat(filepath.Join(binDir, "docker-credential-glab"))
927 assert.True(t, os.IsNotExist(statErr), "a failed exchange must leave no shim behind")
929 _, statErr = os.Stat(filepath.Join(home, ".docker", "config.json"))
930 assert.True(t, os.IsNotExist(statErr), "a failed exchange must leave no credHelpers entry behind")
933// TestLogin_Docker_UnsupportedOSFailsBeforeTheExchange pins that an
934// unsupported platform is rejected in validate, not by
935// dockercredhelper.Install after run has already exchanged a token. A user on
936// Windows must not mint a live credential to be told Docker can never use it.
937func TestLogin_Docker_UnsupportedOSFailsBeforeTheExchange(t *testing.T) {
938 o := &options{
939 supportedOS: func() error { return errors.New(`operating system "windows" is not supported`) },
940 registry: "registry.example.com",
941 docker: true,
942 }
944 err := o.validate()
945 require.Error(t, err)
946 assert.Contains(t, err.Error(), "is not supported")
949func TestLogin_RegistryMustNotContainPath(t *testing.T) {
950 exec := cmdtest.SetupCmdForTest(t, NewCmd, false)
952 _, err := exec("--docker --registry registry.example.com/some/path")
953 require.Error(t, err)
954 assert.Contains(t, err.Error(), "must not contain a path")
957// TestLogin_Docker_VerificationTokenUsesMinDuration pins the lifetime of the
958// token this command exchanges and throws away. Nothing sends it, so it asks
959// for the shortest lifetime the server issues rather than the server default.
960func TestLogin_Docker_VerificationTokenUsesMinDuration(t *testing.T) {
961 binDir := t.TempDir()
962 writeFakeGlab(t, binDir)
963 setPath(t, binDir)
964 setHome(t, t.TempDir())
966 token := tokenexchangetest.MakeJWT(t, jwt.RegisteredClaims{
967 Issuer: "https://gitlab.example.com",
968 Subject: "gid://gitlab/User/1",
969 ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Hour).Truncate(time.Second)),
970 })
972 var gotBody struct {
973 ExpiresIn *int `json:"expires_in"`
974 }
975 var decodeErr error
976 srv, _ := tokenexchangetest.NewTestServer(t, func(w http.ResponseWriter, r *http.Request) {
977 // Recorded rather than asserted: a failed assertion inside a handler
978 // runs on the server's goroutine, where it cannot fail the test.
979 decodeErr = json.NewDecoder(r.Body).Decode(&gotBody)
980 w.Header().Set("Content-Type", "application/json")
981 w.WriteHeader(http.StatusOK)
982 _, _ = w.Write([]byte(`{"token":"` + token + `"}`))
983 })
984 exec := newTestExec(t, newServerConfig(t, srv, glinstance.DefaultHostname))
986 _, err := exec("--docker --registry registry.example.com")
987 require.NoError(t, err)
989 require.NoError(t, decodeErr)
990 require.NotNil(t, gotBody.ExpiresIn, "expires_in must be sent, so the server does not apply its own default")
991 assert.Equal(t, int(artifactregistry.MinDuration.Seconds()), *gotBody.ExpiresIn)
994// TestLogin_Docker_VerificationUsesTheStoredCredential pins that the
995// verification exchange authenticates as the identity the Docker credential
996// helper will use. The helper ignores GITLAB_TOKEN, so verifying with it would
997// check an identity Docker never uses: a valid GITLAB_TOKEN over a dead stored
998// token would report a successful login whose every `docker pull` then 401s.
999func TestLogin_Docker_VerificationUsesTheStoredCredential(t *testing.T) {
1000 binDir := t.TempDir()
1001 writeFakeGlab(t, binDir)
1002 setPath(t, binDir)
1003 setHome(t, t.TempDir())
1004 clearAmbientTokens(t)
1005 t.Setenv("GITLAB_TOKEN", "environment-token")
1007 token := tokenexchangetest.MakeJWT(t, jwt.RegisteredClaims{
1008 Issuer: "https://gitlab.example.com",
1009 Subject: "gid://gitlab/User/1",
1010 ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Hour).Truncate(time.Second)),
1011 })
1013 // Recorded rather than asserted: a failed assertion inside a handler runs on
1014 // the server's goroutine, where it cannot fail the test.
1015 var gotToken string
1016 srv, _ := tokenexchangetest.NewTestServer(t, func(w http.ResponseWriter, r *http.Request) {
1017 gotToken = r.Header.Get(gitlab.AccessTokenHeaderName)
1018 w.Header().Set("Content-Type", "application/json")
1019 w.WriteHeader(http.StatusOK)
1020 _, _ = w.Write([]byte(`{"token":"` + token + `"}`))
1021 })
1022 exec := newTestExec(t, newServerConfig(t, srv, glinstance.DefaultHostname))
1024 _, err := exec("--docker --registry registry.example.com")
1025 require.NoError(t, err)
1027 assert.Equal(t, storedToken, gotToken)
1030// TestLogin_Docker_VerificationFailsWhenOnlyTheEnvironmentHasAToken is the
1031// other half: with nothing stored for the host, the exchange goes out
1032// unauthenticated and the login fails, even though GITLAB_TOKEN would have made
1033// it succeed. That is the point, since `docker pull` has the same nothing to
1034// authenticate with, so the error has to name the environment token the user is
1035// about to blame for working everywhere else.
1036func TestLogin_Docker_VerificationFailsWhenOnlyTheEnvironmentHasAToken(t *testing.T) {
1037 binDir := t.TempDir()
1038 home := t.TempDir()
1039 writeFakeGlab(t, binDir)
1040 setPath(t, binDir)
1041 setHome(t, home)
1042 clearAmbientTokens(t)
1043 t.Setenv("GITLAB_TOKEN", "environment-token")
1045 srv, _ := tokenexchangetest.NewTestServer(t, func(w http.ResponseWriter, r *http.Request) {
1046 if r.Header.Get(gitlab.AccessTokenHeaderName) == "" {
1047 w.Header().Set("Content-Type", "application/json")
1048 w.WriteHeader(http.StatusUnauthorized)
1049 _, _ = w.Write([]byte(`{"message":"401 Unauthorized"}`))
1050 return
1052 w.Header().Set("Content-Type", "application/json")
1053 w.WriteHeader(http.StatusOK)
1054 _, _ = w.Write([]byte(`{"token":"should not be reached"}`))
1055 })
1057 cfg := config.NewFromString("---\nhosts:\n " + glinstance.DefaultHostname + ":\n" +
1058 " user: someone\n" +
1059 " api_host: " + apiHost(t, srv) + "\n" +
1060 " api_protocol: http\n")
1061 exec := newTestExec(t, cfg)
1063 _, err := exec("--docker --registry registry.example.com")
1064 require.Error(t, err)
1065 assert.Contains(t, err.Error(), "401")
1066 assert.Contains(t, err.Error(), "GITLAB_TOKEN is set, but nothing is stored for "+glinstance.DefaultHostname)
1067 assert.Contains(t, err.Error(), "glab auth login --hostname "+glinstance.DefaultHostname)
1069 _, statErr := os.Stat(filepath.Join(home, ".docker", "config.json"))
1070 assert.True(t, os.IsNotExist(statErr), "a failed verification must leave no credHelpers entry behind")
1073// TestLogin_Docker_ExchangeFailureHintsAtTheMissingToken covers the same
1074// unauthenticated exchange with no environment token either. "401 Unauthorized"
1075// alone would not tell the user that `glab auth login` is what writes the file
1076// the Docker credential helper reads.
1077func TestLogin_Docker_ExchangeFailureHintsAtTheMissingToken(t *testing.T) {
1078 binDir := t.TempDir()
1079 writeFakeGlab(t, binDir)
1080 setPath(t, binDir)
1081 setHome(t, t.TempDir())
1082 clearAmbientTokens(t)
1084 srv, _ := tokenexchangetest.NewTestServer(t, func(w http.ResponseWriter, r *http.Request) {
1085 w.Header().Set("Content-Type", "application/json")
1086 w.WriteHeader(http.StatusUnauthorized)
1087 _, _ = w.Write([]byte(`{"message":"401 Unauthorized"}`))
1088 })
1090 cfg := config.NewFromString("---\nhosts:\n " + glinstance.DefaultHostname + ":\n" +
1091 " user: someone\n" +
1092 " api_host: " + apiHost(t, srv) + "\n" +
1093 " api_protocol: http\n")
1094 exec := newTestExec(t, cfg)
1096 _, err := exec("--docker --registry registry.example.com")
1097 require.Error(t, err)
1098 assert.Contains(t, err.Error(), "No token is stored for "+glinstance.DefaultHostname)
1099 assert.Contains(t, err.Error(), "glab auth login --hostname "+glinstance.DefaultHostname)
1102// TestLogin_Docker_ExchangeFailureWithAJobTokenAddsNoHint covers the CI case: a
1103// host whose only credential is a job token is configured, since that is what
1104// the Docker credential helper authenticates with inside a CI job, so telling
1105// the user to run `glab auth login` would be wrong.
1106func TestLogin_Docker_ExchangeFailureWithAJobTokenAddsNoHint(t *testing.T) {
1107 binDir := t.TempDir()
1108 writeFakeGlab(t, binDir)
1109 setPath(t, binDir)
1110 setHome(t, t.TempDir())
1111 clearAmbientTokens(t)
1113 srv, _ := tokenexchangetest.NewTestServer(t, func(w http.ResponseWriter, r *http.Request) {
1114 w.Header().Set("Content-Type", "application/json")
1115 w.WriteHeader(http.StatusForbidden)
1116 _, _ = w.Write([]byte(`{"message":"403 Forbidden"}`))
1117 })
1119 cfg := config.NewFromString("---\nhosts:\n " + glinstance.DefaultHostname + ":\n" +
1120 " job_token: ci-job-token\n" +
1121 " api_host: " + apiHost(t, srv) + "\n" +
1122 " api_protocol: http\n")
1123 exec := newTestExec(t, cfg)
1125 _, err := exec("--docker --registry registry.example.com")
1126 require.Error(t, err)
1127 assert.Contains(t, err.Error(), "403 Forbidden")
1128 assert.NotContains(t, err.Error(), "glab auth login")
1129 assert.NotContains(t, err.Error(), "No token is stored")
1132// TestLogin_Docker_ExchangeFailureWithAStoredTokenAddsNoHint keeps the hint
1133// honest: a host that does have a stored token failed the exchange for some
1134// other reason, and telling the user to log in again would send them the wrong
1135// way.
1136func TestLogin_Docker_ExchangeFailureWithAStoredTokenAddsNoHint(t *testing.T) {
1137 binDir := t.TempDir()
1138 writeFakeGlab(t, binDir)
1139 setPath(t, binDir)
1140 setHome(t, t.TempDir())
1142 srv, _ := tokenexchangetest.NewTestServer(t, func(w http.ResponseWriter, r *http.Request) {
1143 w.Header().Set("Content-Type", "application/json")
1144 w.WriteHeader(http.StatusForbidden)
1145 _, _ = w.Write([]byte(`{"message":"artifact registry is disabled for this project"}`))
1146 })
1147 exec := newTestExec(t, newServerConfig(t, srv, glinstance.DefaultHostname))
1149 _, err := exec("--docker --registry registry.example.com")
1150 require.Error(t, err)
1151 assert.Contains(t, err.Error(), "artifact registry is disabled for this project")
1152 assert.NotContains(t, err.Error(), "glab auth login")
1155func TestLogin_Docker_DefaultsHostnameWhenNotProvided(t *testing.T) {
1156 binDir := t.TempDir()
1157 writeFakeGlab(t, binDir)
1158 setPath(t, binDir)
1159 setHome(t, t.TempDir())
1161 srv := dockerTokenServer(t)
1162 cfg := newServerConfig(t, srv, glinstance.DefaultHostname)
1163 exec := newTestExec(t, cfg)
1165 _, err := exec("--docker --registry registry.example.com")
1166 require.NoError(t, err)
1168 domains, err := cfg.Get(glinstance.DefaultHostname, "artifact_registry_domains")
1169 require.NoError(t, err)
1170 assert.Contains(t, domains, "registry.example.com")
1173func TestLogin_Docker_UsesExplicitHostnameWhenProvided(t *testing.T) {
1174 binDir := t.TempDir()
1175 writeFakeGlab(t, binDir)
1176 setPath(t, binDir)
1177 setHome(t, t.TempDir())
1179 srv := dockerTokenServer(t)
1180 cfg := newServerConfig(t, srv, glinstance.DefaultHostname, "gitlab.other-instance.example.com")
1181 exec := newTestExec(t, cfg)
1183 _, err := exec("--docker --registry registry.example.com --hostname gitlab.other-instance.example.com")
1184 require.NoError(t, err)
1186 // The explicit hostname must be used as-is, not overridden by the
1187 // default-hostname fallback.
1188 domains, err := cfg.Get("gitlab.other-instance.example.com", "artifact_registry_domains")
1189 require.NoError(t, err)
1190 assert.Contains(t, domains, "registry.example.com")
1192 defaultDomains, err := cfg.Get(glinstance.DefaultHostname, "artifact_registry_domains")
1193 require.NoError(t, err)
1194 assert.NotContains(t, defaultDomains, "registry.example.com")
1197// TestLogin_Docker_ExchangeUsesResolvedHostname pins that the API client is
1198// built from the same hostname the domain is recorded under. The two are
1199// resolved from one variable, so an exchange can never verify access against a
1200// different host than the one being configured.
1201func TestLogin_Docker_ExchangeUsesResolvedHostname(t *testing.T) {
1202 tests := []struct {
1203 name string
1204 hostname string
1205 want string
1206 }{
1207 {name: "empty hostname resolves to the default", hostname: "", want: "gitlab.default.example.com"},
1208 {name: "explicit hostname is used as given", hostname: "gitlab.other.example.com", want: "gitlab.other.example.com"},
1211 for _, tc := range tests {
1212 t.Run(tc.name, func(t *testing.T) {
1213 var got string
1214 o := &options{
1215 credHelperApiClient: func(repoHost string) (*api.Client, error) {
1216 got = repoHost
1217 // Stop before the exchange: the host the client is built
1218 // for is all this test is about.
1219 return nil, errors.New("no API client in this test")
1220 },
1221 defaultHostname: "gitlab.default.example.com",
1222 hostname: tc.hostname,
1223 registry: "registry.example.com",
1224 docker: true,
1227 require.Error(t, o.run(t.Context()))
1228 assert.Equal(t, tc.want, got)
1229 })
1233func TestLogin_Docker_DurationIgnoredWarning(t *testing.T) {
1234 binDir := t.TempDir()
1235 writeFakeGlab(t, binDir)
1236 setPath(t, binDir)
1237 setHome(t, t.TempDir())
1239 srv := dockerTokenServer(t)
1240 exec := newTestExec(t, newServerConfig(t, srv, glinstance.DefaultHostname))
1242 out, err := exec("--docker --registry registry.example.com --duration 30m")
1243 require.NoError(t, err)
1244 assert.Contains(t, out.ErrBuf.String(), "--duration is ignored")
1247func TestLogin_Docker_NoDurationWarningWhenFlagNotPassed(t *testing.T) {
1248 binDir := t.TempDir()
1249 writeFakeGlab(t, binDir)
1250 setPath(t, binDir)
1251 setHome(t, t.TempDir())
1253 srv := dockerTokenServer(t)
1254 exec := newTestExec(t, newServerConfig(t, srv, glinstance.DefaultHostname))
1256 out, err := exec("--docker --registry registry.example.com")
1257 require.NoError(t, err)
1259 // The warning keys off cmd.Flags().Changed("duration"), not off the value,
1260 // so `--duration 0` still warns even though it matches the flag's default.
1261 assert.NotContains(t, out.ErrBuf.String(), "--duration is ignored")
1264// TestLogin_Docker_ExplicitZeroDurationStillWarns pins that the warning
1265// follows Changed, not the value. The flag defaults to zero because nothing
1266// reads it yet, so a value test would have gone quiet on `--duration 0`.
1267func TestLogin_Docker_ExplicitZeroDurationStillWarns(t *testing.T) {
1268 binDir := t.TempDir()
1269 writeFakeGlab(t, binDir)
1270 setPath(t, binDir)
1271 setHome(t, t.TempDir())
1273 srv := dockerTokenServer(t)
1274 exec := newTestExec(t, newServerConfig(t, srv, glinstance.DefaultHostname))
1276 out, err := exec("--docker --registry registry.example.com --duration 0")
1277 require.NoError(t, err)
1278 assert.Contains(t, out.ErrBuf.String(), "--duration is ignored")
1281// TestLogin_Docker_DurationOutOfRangeIsStillIgnored pins that the value is not
1282// range-checked on this path. --duration is never sent anywhere here, so
1283// rejecting a value the command has already said it ignores would contradict
1284// the warning. Step 5 adds the check with the first path that spends the value.
1285func TestLogin_Docker_DurationOutOfRangeIsStillIgnored(t *testing.T) {
1286 binDir := t.TempDir()
1287 writeFakeGlab(t, binDir)
1288 setPath(t, binDir)
1289 setHome(t, t.TempDir())
1291 srv := dockerTokenServer(t)
1292 exec := newTestExec(t, newServerConfig(t, srv, glinstance.DefaultHostname))
1294 out, err := exec("--docker --registry registry.example.com --duration 100h")
1295 require.NoError(t, err)
1296 assert.Contains(t, out.ErrBuf.String(), "--duration is ignored")
1299// TestLogin_Docker_GlabNotOnPathFailsBeforeTheExchange pins that a glab PATH
1300// cannot resolve is rejected in validate, not by dockercredhelper.Install
1301// after run has already exchanged a token. The shim is written next to glab
1302// and shells out to it, so this login can never work, and it must not mint a
1303// live credential to find that out.
1305// The request counter is the assertion that matters: the error alone would
1306// also pass if Install were still the one raising it. loginDocker's own PATH
1307// failure, for callers that reach it without validate, is exercised in
1308// docker_test.go's TestLoginDocker_GlabNotOnPath.
1309func TestLogin_Docker_GlabNotOnPathFailsBeforeTheExchange(t *testing.T) {
1310 setPath(t, t.TempDir())
1311 setHome(t, t.TempDir())
1313 srv, requests := tokenexchangetest.NewTestServer(t, func(w http.ResponseWriter, _ *http.Request) {
1314 w.WriteHeader(http.StatusOK)
1315 })
1316 exec := newTestExec(t, newServerConfig(t, srv, glinstance.DefaultHostname))
1318 _, err := exec("--docker --registry registry.example.com")
1319 require.Error(t, err)
1320 assert.Contains(t, err.Error(), "glab")
1321 assert.Zero(t, requests.Load(), "a login that can never work must not exchange a token")
1324// TestLogin_Docker_BadRegistryIsReportedAheadOfThePlatform pins the order
1325// inside validate: the environment checks run last, so a user who typed a
1326// registry they can fix hears about the flag rather than about their platform.
1327func TestLogin_Docker_BadRegistryIsReportedAheadOfThePlatform(t *testing.T) {
1328 o := &options{
1329 supportedOS: func() error { return errors.New(`operating system "windows" is not supported`) },
1330 registry: "registry.example.com/some/path",
1331 docker: true,
1334 err := o.validate()
1335 require.Error(t, err)
1336 assert.Contains(t, err.Error(), "must not contain a path")
Diagnostics8 git calls · 259 ms
CallStatusSizeTime0259 ms
discover200185 B3 ms
git.upload-pack discover
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=ls-refs
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=3
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=2
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 · hit1 ms
git.upload-pack fetch
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=fetch
git.upstream.dur_ms=1
git.response.bytes=1857
git.response.cache=HIT
git.response.duration_ms=1
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 · 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=242
git.response.cache=HIT
git.response.duration_ms=2
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 · 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=494
git.response.cache=HIT
git.response.duration_ms=3
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
fetch20011 KiB248 ms
git.upload-pack fetch
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=fetch
git.upstream.dur_ms=246
git.response.bytes=11556
git.response.cache=MISS
git.response.duration_ms=248
git.fetch.wants=04cc1b5376f33dc61ae9eb7f54937a39b242ac6f
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=11556
git.pkt.payload.max=11529
git.sideband.band1.bytes=11529
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
a5e2f9c039eb90c0
Request
fdb6e85f…
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