GitLabgitlab-org
cli
main
1//go:build !integration
3package config
5import (
6 "errors"
7 "fmt"
8 "os"
9 "path/filepath"
10 "runtime"
11 "strconv"
12 "strings"
13 "testing"
14 "time"
16 "github.com/MakeNowJust/heredoc/v2"
17 "github.com/stretchr/testify/assert"
18 "github.com/stretchr/testify/require"
19 "github.com/zalando/go-keyring"
20 "go.yaml.in/yaml/v3"
21)
23// persistedFile returns the contents of a config file written into dir by a
24// dir-backed Config, for tests that assert on what was persisted.
25func persistedFile(t *testing.T, dir, name string) string {
26 t.Helper()
27 data, err := os.ReadFile(filepath.Join(dir, name))
28 require.NoError(t, err)
29 return string(data)
30}
32func Test_BlankConfig_RoundTripsAndExposesSchemaKeys(t *testing.T) {
33 root := NewBlankRoot()
34 cfg := NewConfig(root)
36 // The blank config must marshal to valid YAML that parses back to an
37 // equivalent tree.
38 out, err := yaml.Marshal(root)
39 require.NoError(t, err)
40 reparsed, err := parseConfigData(out)
41 require.NoError(t, err)
42 roundTripped, err := yaml.Marshal(reparsed)
43 require.NoError(t, err)
44 assert.Equal(t, string(out), string(roundTripped))
46 // Hosts and aliases sections must be reachable.
47 hosts, err := cfg.Hosts()
48 require.NoError(t, err)
49 assert.NotEmpty(t, hosts, "blank config should seed at least one host")
51 aliases, err := cfg.Aliases()
52 require.NoError(t, err)
53 assert.NotEmpty(t, aliases.All(), "blank config should seed default aliases")
55 // Defaults declared in KeySchema must surface through Get.
56 gitProto, err := cfg.Get("", "git_protocol")
57 require.NoError(t, err)
58 assert.Equal(t, "ssh", gitProto)
59}
61func Test_fileConfig_Set(t *testing.T) {
62 dir := t.TempDir()
63 seedFile(t, dir, "config.yml", `---
64git_protocol: ssh
65editor: vim
66hosts:
67 gitlab.com:
68 token:
69 git_protocol: https
70 username: user
71`)
73 c, err := ParseConfig(filepath.Join(dir, "config.yml"))
74 require.NoError(t, err)
76 assert.NoError(t, c.Set("", "editor", "nano"))
77 assert.NoError(t, c.Set("gitlab.com", "git_protocol", "ssh"))
78 assert.NoError(t, c.Set("example.com", "username", "testUser"))
79 assert.NoError(t, c.Set("gitlab.com", "username", "hubot"))
80 assert.NoError(t, c.WriteAll())
82 expected := heredoc.Doc(`
83git_protocol: ssh
84editor: nano
85hosts:
86 gitlab.com:
87 token:
88 git_protocol: ssh
89 username: hubot
90 example.com:
91 username: testUser
92`)
93 assert.Equal(t, expected, persistedFile(t, dir, "config.yml"))
94}
96func Test_fileConfig_Set_WritesAliasToCanonicalKey(t *testing.T) {
97 dir := t.TempDir()
98 seedFile(t, dir, "config.yml", `---
99editor: vim
100`)
102 c, err := ParseConfig(filepath.Join(dir, "config.yml"))
103 require.NoError(t, err)
105 require.NoError(t, c.Set("", "visual", "nano"))
106 require.NoError(t, c.WriteAll())
108 assert.Equal(t, "editor: nano\n", persistedFile(t, dir, "config.yml"))
109}
111func Test_fileConfig_Set_Empty_Removes(t *testing.T) {
112 dir := t.TempDir()
113 seedFile(t, dir, "config.yml", `---
114git_protocol: ssh
115editor: vim
116hosts:
117 gitlab.com:
118 token: foobar
119 git_protocol: https
120 username: user
121`)
123 c, err := ParseConfig(filepath.Join(dir, "config.yml"))
124 require.NoError(t, err)
126 assert.NoError(t, c.Set("", "editor", ""))
127 assert.NoError(t, c.Set("gitlab.com", "token", ""))
128 assert.NoError(t, c.WriteAll())
130 expected := heredoc.Doc(`
131git_protocol: ssh
132hosts:
133 gitlab.com:
134 git_protocol: https
135 username: user
136`)
137 assert.Equal(t, expected, persistedFile(t, dir, "config.yml"))
138}
140func Test_defaultConfig(t *testing.T) {
141 dir := t.TempDir()
142 cfg := NewBlankConfigInDir(dir)
143 require.NoError(t, cfg.Write())
144 _, statErr := os.Stat(filepath.Join(dir, "aliases.yml"))
145 assert.True(t, os.IsNotExist(statErr), "Write() must not persist the aliases file")
147 proto, err := cfg.Get("", "git_protocol")
148 require.NoError(t, err)
149 assert.Equal(t, "ssh", proto)
151 editor, err := cfg.Get("", "editor")
152 require.NoError(t, err)
153 assert.Equal(t, os.Getenv("EDITOR"), editor)
155 aliases, err := cfg.Aliases()
156 require.NoError(t, err)
157 assert.Len(t, aliases.All(), 2)
158 expansion, _ := aliases.Get("co")
159 assert.Equal(t, "mr checkout", expansion)
160}
162func Test_getFromKeyring(t *testing.T) {
163 c := NewBlankConfig()
165 // Ensure host exists and its token is empty
166 err := c.Set("gitlab.com", "token", "")
167 require.NoError(t, err)
168 err = c.Write()
169 require.NoError(t, err)
171 keyring.MockInit()
172 token, _, err := c.GetWithSource("gitlab.com", "token", false)
173 require.NoError(t, err)
174 assert.Empty(t, token)
176 err = keyring.Set("glab:gitlab.com", "", "glpat-1234")
177 require.NoError(t, err)
179 token, _, err = c.GetWithSource("gitlab.com", "token", false)
181 require.NoError(t, err)
182 assert.Equal(t, "glpat-1234", token)
183}
185func Test_KeyringAvailable(t *testing.T) {
186 t.Run("returns true when a keyring backend works", func(t *testing.T) {
187 keyring.MockInit()
188 assert.True(t, KeyringAvailable())
189 })
191 t.Run("returns false when the keyring backend errors", func(t *testing.T) {
192 keyring.MockInitWithError(errors.New("no keyring"))
193 t.Cleanup(keyring.MockInit)
194 assert.False(t, KeyringAvailable())
195 })
196}
198func Test_Set_SwitchingKeyringToFileRemovesStaleEntry(t *testing.T) {
199 // Clear CI vars so the file-mode keyring cleanup is exercised (it is skipped
200 // in CI, and the suite itself may run there).
201 t.Setenv("GITLAB_CI", "")
202 t.Setenv("CI", "")
203 keyring.MockInit()
205 c := NewBlankConfig()
207 // Start in keyring mode with a token stored in the keyring.
208 require.NoError(t, c.Set("gitlab.com", "use_keyring", "true"))
209 require.NoError(t, c.Set("gitlab.com", "token", "glpat-keyring"))
210 got, err := keyring.Get("glab:gitlab.com:token", "")
211 require.NoError(t, err)
212 require.Equal(t, "glpat-keyring", got)
214 // Switch to file storage and write a new token.
215 require.NoError(t, c.Set("gitlab.com", "use_keyring", "false"))
216 require.NoError(t, c.Set("gitlab.com", "token", "glpat-file"))
218 // The stale keyring entry must be gone (no orphaned secret).
219 _, err = keyring.Get("glab:gitlab.com:token", "")
220 require.Error(t, err)
222 // The token now resolves from the file.
223 v, _ := c.Get("gitlab.com", "token")
224 assert.Equal(t, "glpat-file", v)
225}
227func Test_Set_ClearRemovesKeyringEntry(t *testing.T) {
228 t.Setenv("GITLAB_CI", "")
229 t.Setenv("CI", "")
230 keyring.MockInit()
232 c := NewBlankConfig()
233 require.NoError(t, c.Set("gitlab.com", "use_keyring", "true"))
234 require.NoError(t, c.Set("gitlab.com", "token", "glpat-x"))
236 // Clearing the value deletes the keyring entry.
237 require.NoError(t, c.Set("gitlab.com", "token", ""))
238 _, err := keyring.Get("glab:gitlab.com:token", "")
239 require.Error(t, err)
240}
242func Test_InCI(t *testing.T) {
243 t.Run("false or unparseable values", func(t *testing.T) {
244 // strconv.ParseBool rejects "yes"/"on"/"2", which we treat as not-CI.
245 for _, v := range []string{"", "false", "0", "FALSE", "f", "yes", "on", "2"} {
246 t.Setenv("GITLAB_CI", "")
247 t.Setenv("CI", v)
248 assert.Falsef(t, InCI(), "CI=%q should not count as CI", v)
249 }
250 })
252 t.Run("truthy values", func(t *testing.T) {
253 for _, v := range []string{"true", "True", "TRUE", "1", "t", "T"} {
254 t.Setenv("GITLAB_CI", "")
255 t.Setenv("CI", v)
256 assert.Truef(t, InCI(), "CI=%q should count as CI", v)
257 }
258 })
260 t.Run("GITLAB_CI is honored independently", func(t *testing.T) {
261 t.Setenv("CI", "")
262 t.Setenv("GITLAB_CI", "true")
263 assert.True(t, InCI())
264 })
265}
267func Test_SetStringValue_ResetsNullTagOnBlankEntry(t *testing.T) {
268 // A key written with no value parses as a null-tagged scalar.
269 var root yaml.Node
270 require.NoError(t, yaml.Unmarshal([]byte("token:\n"), &root))
271 cm := ConfigMap{Root: root.Content[0]}
273 require.NoError(t, cm.SetStringValue("token", "secret-value"))
275 out, err := yaml.Marshal(root.Content[0])
276 require.NoError(t, err)
277 // The value must not be written as a null-tagged scalar (which would leave
278 // it in the file yet decode as empty).
279 assert.NotContains(t, string(out), "!!null")
280 assert.Contains(t, string(out), "secret-value")
282 // It decodes as a proper string after a round-trip through disk.
283 var reloaded yaml.Node
284 require.NoError(t, yaml.Unmarshal(out, &reloaded))
285 var s string
286 require.NoError(t, reloaded.Content[0].Content[1].Decode(&s))
287 assert.Equal(t, "secret-value", s)
288}
290func Test_GetWithSource_SurfacesKeyringReadError(t *testing.T) {
291 cause := errors.New("access denied")
292 keyring.MockInitWithError(cause)
293 t.Cleanup(keyring.MockInit)
295 c := NewBlankConfig()
296 require.NoError(t, c.Set("gitlab.com", "use_keyring", "true"))
298 _, _, err := c.GetWithSource("gitlab.com", "token", false)
299 require.ErrorIs(t, err, ErrKeyringUnavailable)
300 require.ErrorIs(t, err, cause)
301 assert.EqualError(t, err, `failed to read "token" from the operating system keyring for host "gitlab.com": access denied`)
302}
304// Test_GetWithSource_CredentialEnvVarsRequireTrustedHost pins the fix for
305// https://gitlab.com/gitlab-org/cli/-/work_items/8545: this pins the gate in
306// GetWithSource; which hosts count as trusted is covered by TestIsTrustedHost.
307func Test_GetWithSource_CredentialEnvVarsRequireTrustedHost(t *testing.T) {
308 // Neutralize every environment variable that maps to a key under test or
309 // that toggles CI auto-login.
310 for _, e := range []string{
311 "GITLAB_TOKEN", "GITLAB_ACCESS_TOKEN", "OAUTH_TOKEN", "GLAB_IS_OAUTH2",
312 "GITLAB_HOST", "GITLAB_URI", "GL_HOST",
313 "GITLAB_API_HOST", "GLAB_GIT_PROTOCOL", "GIT_PROTOCOL",
314 "GLAB_ENABLE_CI_AUTOLOGIN", "GITLAB_CI", "CI_SERVER_FQDN", "CI_JOB_TOKEN",
315 } {
316 t.Setenv(e, "")
317 }
319 t.Run("resolves for gitlab.com when nothing is configured", func(t *testing.T) {
320 t.Setenv("GITLAB_TOKEN", "env-token")
321 cfg := NewFromString("hosts: {}\n")
323 token, source, err := cfg.GetWithSource("gitlab.com", "token", true)
324 require.NoError(t, err)
325 assert.Equal(t, "env-token", token)
326 assert.Equal(t, "GITLAB_TOKEN", source)
327 })
329 t.Run("withheld from a host that is neither default nor configured", func(t *testing.T) {
330 t.Setenv("GITLAB_TOKEN", "env-token")
331 cfg := NewFromString("hosts: {}\n")
333 token, source, err := cfg.GetWithSource("attacker.example.com", "token", true)
334 require.NoError(t, err)
335 assert.Empty(t, token)
336 assert.NotEqual(t, "GITLAB_TOKEN", source)
337 })
339 t.Run("aliases of the token key are scoped too", func(t *testing.T) {
340 t.Setenv("GITLAB_TOKEN", "env-token")
341 cfg := NewFromString("hosts: {}\n")
343 token, _, err := cfg.GetWithSource("attacker.example.com", "oauth_token", true)
344 require.NoError(t, err)
345 assert.Empty(t, token)
346 })
348 t.Run("the OAuth scheme flag is scoped too", func(t *testing.T) {
349 t.Setenv("GLAB_IS_OAUTH2", "true")
350 cfg := NewFromString("hosts: {}\n")
352 value, _, err := cfg.GetWithSource("attacker.example.com", "is_oauth2", true)
353 require.NoError(t, err)
354 assert.Empty(t, value)
355 })
357 t.Run("non-credential per-host keys keep resolving globally", func(t *testing.T) {
358 // api_host is not a secret, and flows like `glab auth login` read such
359 // keys for a host that is not configured yet (for example
360 // GITLAB_CLIENT_ID for a self-managed instance's OAuth login).
361 t.Setenv("GITLAB_API_HOST", "api.example.com")
362 cfg := NewFromString("hosts: {}\n")
364 value, _, err := cfg.GetWithSource("attacker.example.com", "api_host", true)
365 require.NoError(t, err)
366 assert.Equal(t, "api.example.com", value)
367 })
369 t.Run("global keys resolve regardless of the host", func(t *testing.T) {
370 t.Setenv("GIT_PROTOCOL", "https")
371 cfg := NewFromString("hosts: {}\n")
373 value, _, err := cfg.GetWithSource("attacker.example.com", "git_protocol", true)
374 require.NoError(t, err)
375 assert.Equal(t, "https", value)
376 })
378 t.Run("an empty hostname still resolves from the environment", func(t *testing.T) {
379 t.Setenv("GITLAB_TOKEN", "env-token")
380 cfg := NewFromString("hosts: {}\n")
382 token, _, err := cfg.GetWithSource("", "token", true)
383 require.NoError(t, err)
384 assert.Equal(t, "env-token", token)
385 })
387 t.Run("a withheld environment token falls through to host configuration", func(t *testing.T) {
388 t.Setenv("GITLAB_TOKEN", "env-token")
389 cfg := NewFromString("hosts:\n gitlab.example.com:\n token: stored-token\n")
391 // For a configured host the environment wins, as before.
392 token, _, err := cfg.GetWithSource("gitlab.example.com", "token", true)
393 require.NoError(t, err)
394 assert.Equal(t, "env-token", token)
396 // For an unconfigured host the environment token is withheld and there
397 // is no stored credential to fall back to.
398 token, _, err = cfg.GetWithSource("attacker.example.com", "token", true)
399 require.NoError(t, err)
400 assert.Empty(t, token)
401 })
403 t.Run("CI auto-login job token resolves for the CI server host only", func(t *testing.T) {
404 t.Setenv("GLAB_ENABLE_CI_AUTOLOGIN", "true")
405 t.Setenv("GITLAB_CI", "true")
406 t.Setenv("CI_SERVER_FQDN", "ci.example.com")
407 t.Setenv("CI_JOB_TOKEN", "ci-job-token")
408 cfg := NewFromString("hosts: {}\n")
410 token, source, err := cfg.GetWithSource("ci.example.com", "job_token", true)
411 require.NoError(t, err)
412 assert.Equal(t, "ci-job-token", token)
413 assert.Equal(t, "CI_JOB_TOKEN", source)
415 token, _, err = cfg.GetWithSource("attacker.example.com", "job_token", true)
416 require.NoError(t, err)
417 assert.Empty(t, token)
418 })
419}
421func TestIsTrustedHost(t *testing.T) {
422 for _, e := range []string{"GITLAB_HOST", "GITLAB_URI", "GL_HOST", "GITLAB_REPO", "GLAB_ENABLE_CI_AUTOLOGIN", "GITLAB_CI", "CI_SERVER_FQDN"} {
423 t.Setenv(e, "")
424 }
426 tests := []struct {
427 name string
428 gitlabHost string
429 gitlabRepo string
430 config string
431 hostname string
432 want bool
433 }{
434 {name: "gitlab.com is trusted by default", hostname: "gitlab.com", want: true},
435 {name: "unconfigured host is not trusted", hostname: "attacker.example.com", want: false},
436 {name: "configured host is trusted", config: "hosts:\n gitlab.example.com:\n user: someone\n", hostname: "gitlab.example.com", want: true},
437 {name: "configured host with port is trusted", config: "hosts:\n gitlab.example.com:8443:\n user: someone\n", hostname: "gitlab.example.com:8443", want: true},
438 {name: "configured host matches case-insensitively", config: "hosts:\n GitLab.Example.COM:\n user: someone\n", hostname: "gitlab.example.com", want: true},
439 {name: "host only similar to a configured host is not trusted", config: "hosts:\n gitlab.example.com:\n user: someone\n", hostname: "notgitlab.example.com", want: false},
440 {name: "hosts key saved with a scheme", config: "hosts:\n https://gl.test:\n user: someone\n", hostname: "gl.test", want: true},
441 {name: "hosts key saved with a subfolder", config: "hosts:\n gl.test/gitlab:\n user: someone\n", hostname: "gl.test", want: true},
442 {name: "default host from the configuration file is trusted", config: "host: gitlab.example.com\nhosts: {}\n", hostname: "gitlab.example.com", want: true},
443 {name: "default host from the configuration file matches case-insensitively", config: "host: GitLab.Example.COM\nhosts: {}\n", hostname: "gitlab.example.com", want: true},
444 {name: "default host with a subfolder from the configuration file", config: "host: gitlab.example.com/gitlab/\nhosts: {}\n", hostname: "gitlab.example.com/gitlab", want: true},
445 {name: "GITLAB_HOST with a protocol prefix", gitlabHost: "https://gitlab.example.com", hostname: "gitlab.example.com", want: true},
446 {name: "GITLAB_HOST matches case-insensitively", gitlabHost: "GitLab.Example.COM", hostname: "gitlab.example.com", want: true},
447 {name: "GITLAB_HOST with a subfolder, as NewFactory passes it", gitlabHost: "http://127.0.0.1:8099/gitlab", hostname: "127.0.0.1:8099/gitlab", want: true},
448 {name: "GITLAB_HOST with a subfolder, bare host", gitlabHost: "http://127.0.0.1:8099/gitlab", hostname: "127.0.0.1:8099", want: true},
449 {name: "GITLAB_HOST with a subfolder does not trust another port", gitlabHost: "http://127.0.0.1:8099/gitlab", hostname: "127.0.0.1", want: false},
450 {name: "GITLAB_HOST with a trailing slash and no scheme", gitlabHost: "127.0.0.1:8099/", hostname: "127.0.0.1:8099/", want: true},
451 {name: "GITLAB_HOST starting with https but without a scheme", gitlabHost: "httpsgit.corp.test", hostname: "httpsgit.corp.test", want: true},
452 {name: "GITLAB_HOST starting with https but without a scheme does not trust its suffix", gitlabHost: "httpsgit.corp.test", hostname: "git.corp.test", want: false},
453 {name: "candidate with a scheme, as auth dpop-gen --hostname passes it", hostname: "https://gitlab.com", want: true},
454 {name: "candidate with a scheme for an unconfigured host", hostname: "https://attacker.example.com/gitlab", want: false},
455 {name: "GITLAB_REPO HTTPS URL trusts its host", gitlabRepo: "https://gitlab.example.com/group/project", hostname: "gitlab.example.com", want: true},
456 {name: "GITLAB_REPO HTTPS URL keeps its port", gitlabRepo: "https://gitlab.example.com:8443/group/project", hostname: "gitlab.example.com:8443", want: true},
457 {name: "GITLAB_REPO SSH URL trusts its host without the SSH port", gitlabRepo: "ssh://git@gitlab.example.com:2222/group/project.git", hostname: "gitlab.example.com", want: true},
458 {name: "GITLAB_REPO scp-like Git URL trusts its host", gitlabRepo: "git@gitlab.example.com:group/project.git", hostname: "gitlab.example.com", want: true},
459 {name: "GITLAB_REPO URL does not trust other hosts", gitlabRepo: "https://gitlab.example.com/group/project", hostname: "attacker.example.com", want: false},
460 {name: "GITLAB_REPO HOST/OWNER/REPO form adds no trusted host", gitlabRepo: "gitlab.example.com/group/project", hostname: "gitlab.example.com", want: false},
461 }
463 for _, tt := range tests {
464 t.Run(tt.name, func(t *testing.T) {
465 t.Setenv("GITLAB_HOST", tt.gitlabHost)
466 t.Setenv("GITLAB_REPO", tt.gitlabRepo)
467 config := tt.config
468 if config == "" {
469 config = "hosts: {}\n"
470 }
471 assert.Equal(t, tt.want, IsTrustedHost(NewFromString(config), tt.hostname))
472 })
473 }
474}
476func Test_Set_SurfacesKeyringWriteError(t *testing.T) {
477 keyring.MockInitWithError(errors.New("exit status 161"))
478 t.Cleanup(keyring.MockInit)
480 c := NewBlankConfig()
481 require.NoError(t, c.Set("gitlab.com", "use_keyring", "true"))
483 err := c.Set("gitlab.com", "token", "secret-value")
484 require.ErrorIs(t, err, ErrKeyringUnavailable)
485 require.EqualError(t, err, `failed to store "token" in the operating system's keyring for host "gitlab.com": exit status 161`)
486 assert.Contains(t, err.Error(), "keyring", "error must name the keyring as the failing subsystem")
487 assert.Contains(t, err.Error(), "gitlab.com", "error must name the host")
488 assert.Contains(t, err.Error(), "token", "error must name the key")
489 assert.Contains(t, err.Error(), "exit status 161", "underlying cause must be preserved")
490 assert.NotContains(t, err.Error(), "secret-value", "credential must not be echoed into the error")
491}
493func Test_GetWithSource_KeyringNotFoundIsNotAnError(t *testing.T) {
494 keyring.MockInit()
496 c := NewBlankConfig()
497 require.NoError(t, c.Set("gitlab.com", "use_keyring", "true"))
499 val, _, err := c.GetWithSource("gitlab.com", "token", false)
500 require.NoError(t, err)
501 assert.Empty(t, val)
502}
504func Test_config_Get_NotFoundError(t *testing.T) {
505 cfg := NewBlankConfig()
507 local, err := cfg.Local()
508 require.NoError(t, err)
509 require.NotNil(t, local)
511 _, err = local.FindEntry("git_protocol")
512 require.Error(t, err)
513 assert.True(t, isNotFoundError(err))
514}
516func TestCustomHeader_ResolvedValue_MissingEnvVar(t *testing.T) {
517 // Ensure the environment variable doesn't exist
518 os.Unsetenv("NONEXISTENT_VAR")
520 header := CustomHeader{
521 Name: "X-Test-Header",
522 ValueFromEnv: "NONEXISTENT_VAR",
523 }
525 value, err := header.ResolvedValue()
526 require.Error(t, err)
527 require.Empty(t, value)
528 require.Contains(t, err.Error(), "environment variable \"NONEXISTENT_VAR\" for header \"X-Test-Header\" is not set or empty")
529}
531func TestCustomHeader_ResolvedValue_EmptyEnvVar(t *testing.T) {
532 // Set environment variable to empty string
533 t.Setenv("EMPTY_VAR", "")
535 header := CustomHeader{
536 Name: "X-Test-Header",
537 ValueFromEnv: "EMPTY_VAR",
538 }
540 value, err := header.ResolvedValue()
541 require.Error(t, err)
542 require.Empty(t, value)
543 require.Contains(t, err.Error(), "environment variable \"EMPTY_VAR\" for header \"X-Test-Header\" is not set or empty")
544}
546func TestResolveCustomHeaders_MissingEnvVar(t *testing.T) {
547 // Ensure the environment variable doesn't exist
548 os.Unsetenv("MISSING_SECRET")
550 configYAML := `
551hosts:
552 gitlab.com:
553 custom_headers:
554 - name: Cf-Access-Client-Secret
555 valueFromEnv: MISSING_SECRET
556`
558 cfg := NewFromString(configYAML)
559 headers, err := ResolveCustomHeaders(cfg, "gitlab.com")
561 require.Error(t, err)
562 require.Nil(t, headers)
563 require.Contains(t, err.Error(), "failed to resolve header \"Cf-Access-Client-Secret\"")
564 require.Contains(t, err.Error(), "environment variable \"MISSING_SECRET\" for header \"Cf-Access-Client-Secret\" is not set or empty")
565}
567func TestCustomHeader_ResolvedValue_Command(t *testing.T) {
568 t.Setenv("GLAB_CUSTOM_HEADER_HELPER", "1")
569 t.Setenv("GLAB_CUSTOM_HEADER_HELPER_OUTPUT", " Bearer generated-token\n")
571 header := CustomHeader{
572 Name: "Proxy-Authorization",
573 ValueFromCommand: customHeaderHelperCommand(),
574 }
576 value, err := header.ResolvedValue()
577 require.NoError(t, err)
578 assert.Equal(t, "Bearer generated-token", value)
579}
581func TestCustomHeader_ResolvedValue_CommandErrorIncludesStderr(t *testing.T) {
582 t.Setenv("GLAB_CUSTOM_HEADER_HELPER", "1")
583 t.Setenv("GLAB_CUSTOM_HEADER_HELPER_ERROR", "no active credentials")
585 header := CustomHeader{
586 Name: "Proxy-Authorization",
587 ValueFromCommand: customHeaderHelperCommand(),
588 }
590 value, err := header.ResolvedValue()
591 require.Error(t, err)
592 assert.Empty(t, value)
593 assert.Contains(t, err.Error(), "no active credentials")
594}
596func TestCustomHeader_ResolvedValue_CommandTimesOut(t *testing.T) {
597 t.Setenv("GLAB_CUSTOM_HEADER_HELPER", "1")
598 t.Setenv("GLAB_CUSTOM_HEADER_HELPER_SLEEP", "1s")
600 value, err := resolveCustomHeaderCommandWithTimeout(customHeaderHelperCommand(), 10*time.Millisecond)
601 require.Error(t, err)
602 assert.Empty(t, value)
603 assert.Contains(t, err.Error(), "command timed out after 10ms")
604}
606func TestCustomHeader_ResolvedValue_CommandTimeoutKillsGrandchild(t *testing.T) {
607 if runtime.GOOS == "windows" {
608 t.Skip("sh -c wrapping is a Unix-specific pattern")
609 }
611 marker := filepath.Join(t.TempDir(), "ran-to-completion")
612 t.Setenv("GLAB_CUSTOM_HEADER_HELPER", "1")
613 t.Setenv("GLAB_CUSTOM_HEADER_HELPER_SLEEP", "500ms")
614 t.Setenv("GLAB_CUSTOM_HEADER_HELPER_MARKER_AFTER_SLEEP", marker)
616 // Mirrors the README's documented pattern for pipelines: the process
617 // glab spawns directly is `sh`, and the real work happens in a child
618 // of that shell.
619 command := "sh -c " + strconv.Quote(customHeaderHelperCommand())
621 value, err := resolveCustomHeaderCommandWithTimeout(command, 50*time.Millisecond)
622 require.Error(t, err)
623 assert.Empty(t, value)
624 assert.Contains(t, err.Error(), "command timed out after 50ms")
626 // Give the grandchild long enough to have finished its sleep and
627 // written the marker, if it survived the timeout.
628 time.Sleep(1 * time.Second)
629 _, err = os.Stat(marker)
630 assert.True(t, os.IsNotExist(err), "grandchild process should have been killed along with its parent shell")
631}
633func TestResolveCustomHeaders_CachesCommandValue(t *testing.T) {
634 marker := filepath.Join(t.TempDir(), "calls")
635 t.Setenv("GLAB_CUSTOM_HEADER_HELPER", "1")
636 t.Setenv("GLAB_CUSTOM_HEADER_HELPER_OUTPUT", "Bearer generated-token")
637 t.Setenv("GLAB_CUSTOM_HEADER_HELPER_MARKER", marker)
639 cfg := NewFromString(fmt.Sprintf(`
640hosts:
641 gitlab.com:
642 custom_headers:
643 - name: Proxy-Authorization
644 valueFromCommand: %s
645`, strconv.Quote(customHeaderHelperCommand())))
647 first, err := ResolveCustomHeaders(cfg, "gitlab.com")
648 require.NoError(t, err)
649 second, err := ResolveCustomHeaders(cfg, "gitlab.com")
650 require.NoError(t, err)
652 assert.Equal(t, "Bearer generated-token", first["Proxy-Authorization"])
653 assert.Equal(t, first, second)
654 calls, err := os.ReadFile(marker)
655 require.NoError(t, err)
656 assert.Equal(t, "x", string(calls), "the configured command should run once")
657}
659func TestGetCustomHeaders_RequiresExactlyOneValueSource(t *testing.T) {
660 tests := []struct {
661 name string
662 fields string
663 }{
664 {name: "no value source", fields: ""},
665 {name: "value and environment", fields: " value: direct\n valueFromEnv: TOKEN"},
666 {name: "environment and command", fields: " valueFromEnv: TOKEN\n valueFromCommand: token-helper"},
667 {name: "value and command", fields: " value: direct\n valueFromCommand: token-helper"},
668 }
670 for _, tc := range tests {
671 t.Run(tc.name, func(t *testing.T) {
672 cfg := NewFromString("hosts:\n gitlab.com:\n custom_headers:\n - name: X-Test\n" + tc.fields + "\n")
674 _, err := ResolveCustomHeaders(cfg, "gitlab.com")
675 require.Error(t, err)
676 assert.Contains(t, err.Error(), "exactly one of 'value', 'valueFromEnv', or 'valueFromCommand'")
677 })
678 }
679}
681func customHeaderHelperCommand() string {
682 return strconv.Quote(os.Args[0]) + " -test.run=^TestCustomHeaderCommandHelper$"
683}
685func TestCustomHeaderCommandHelper(t *testing.T) {
686 if os.Getenv("GLAB_CUSTOM_HEADER_HELPER") != "1" {
687 return
688 }
690 if marker := os.Getenv("GLAB_CUSTOM_HEADER_HELPER_MARKER"); marker != "" {
691 file, err := os.OpenFile(marker, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o600)
692 if err != nil {
693 os.Exit(2)
694 }
695 if _, err := file.WriteString("x"); err != nil {
696 os.Exit(2)
697 }
698 if err := file.Close(); err != nil {
699 os.Exit(2)
700 }
701 }
702 if message := os.Getenv("GLAB_CUSTOM_HEADER_HELPER_ERROR"); message != "" {
703 if _, err := fmt.Fprint(os.Stderr, message); err != nil {
704 os.Exit(2)
705 }
706 os.Exit(1)
707 }
708 if delay := os.Getenv("GLAB_CUSTOM_HEADER_HELPER_SLEEP"); delay != "" {
709 duration, err := time.ParseDuration(delay)
710 if err != nil {
711 os.Exit(2)
712 }
713 time.Sleep(duration)
714 }
716 if marker := os.Getenv("GLAB_CUSTOM_HEADER_HELPER_MARKER_AFTER_SLEEP"); marker != "" {
717 if err := os.WriteFile(marker, []byte("x"), 0o600); err != nil {
718 os.Exit(2)
719 }
720 }
722 if _, err := fmt.Fprint(os.Stdout, os.Getenv("GLAB_CUSTOM_HEADER_HELPER_OUTPUT")); err != nil {
723 os.Exit(2)
724 }
725 os.Exit(0)
726}
728func TestConfig_parseHosts_NoHosts(t *testing.T) {
729 t.Parallel()
731 cfg := &fileConfig{}
732 // Create empty hosts node
733 emptyHostsNode := &yaml.Node{Kind: yaml.MappingNode}
735 _, err := cfg.parseHosts(emptyHostsNode)
737 assert.True(t, isNotFoundError(err))
738}
740func TestConfig_parseHosts_YAMLAnchor(t *testing.T) {
741 t.Parallel()
743 configYAML := heredoc.Doc(`
744 hosts:
745 gitlab.com: &gl
746 token: glpat-secret
747 user: testuser
748 gitlab.com:443: *gl
749 `)
751 var root yaml.Node
752 require.NoError(t, yaml.Unmarshal([]byte(configYAML), &root))
754 cfg := &fileConfig{ConfigMap: ConfigMap{Root: root.Content[0]}}
756 // The anchored host must resolve its values.
757 anchoredToken, err := cfg.Get("gitlab.com", "token")
758 require.NoError(t, err)
759 assert.Equal(t, "glpat-secret", anchoredToken)
761 anchoredUser, err := cfg.Get("gitlab.com", "user")
762 require.NoError(t, err)
763 assert.Equal(t, "testuser", anchoredUser)
765 // The aliased host must resolve the same values as the anchored one.
766 aliasedToken, err := cfg.Get("gitlab.com:443", "token")
767 require.NoError(t, err)
768 assert.Equal(t, anchoredToken, aliasedToken)
769}
771func Test_SetKeyring_StoresTokenInKeyringAndSetsIndicator(t *testing.T) {
772 dir := t.TempDir()
773 keyring.MockInit()
774 cfg := NewBlankConfigInDir(dir)
776 // Enable keyring mode
777 err := cfg.Set("gitlab.com", "use_keyring", "true")
778 require.NoError(t, err)
780 // Set a token - should go to keyring
781 err = cfg.Set("gitlab.com", "token", "glpat-secret-token")
782 require.NoError(t, err)
784 // Verify token is stored in keyring with new key format
785 storedToken, err := keyring.Get("glab:gitlab.com:token", "")
786 require.NoError(t, err)
787 assert.Equal(t, "glpat-secret-token", storedToken)
789 // Verify use_keyring indicator is set in config
790 useKeyring, err := cfg.Get("gitlab.com", "use_keyring")
791 require.NoError(t, err)
792 assert.Equal(t, "true", useKeyring)
794 // Verify token is NOT in config (removed/empty)
795 err = cfg.Write()
796 require.NoError(t, err)
797 configContent := persistedFile(t, dir, "config.yml")
798 assert.NotContains(t, configContent, "glpat-secret-token", "Token should not be in plaintext config")
799 assert.Contains(t, configContent, "use_keyring: true")
800}
802func Test_SetKeyring_OAuth2RefreshToken(t *testing.T) {
803 dir := t.TempDir()
804 keyring.MockInit()
805 cfg := NewBlankConfigInDir(dir)
807 // Enable keyring mode
808 err := cfg.Set("gitlab.com", "use_keyring", "true")
809 require.NoError(t, err)
811 // Set a refresh token - should go to keyring
812 err = cfg.Set("gitlab.com", "oauth2_refresh_token", "refresh-secret-token")
813 require.NoError(t, err)
815 // Verify refresh token is stored in keyring with new key format
816 storedToken, err := keyring.Get("glab:gitlab.com:oauth2_refresh_token", "")
817 require.NoError(t, err)
818 assert.Equal(t, "refresh-secret-token", storedToken)
820 // Verify use_keyring indicator is set in config
821 useKeyring, err := cfg.Get("gitlab.com", "use_keyring")
822 require.NoError(t, err)
823 assert.Equal(t, "true", useKeyring)
825 // Verify refresh token is NOT in config
826 err = cfg.Write()
827 require.NoError(t, err)
828 configContent := persistedFile(t, dir, "config.yml")
829 assert.NotContains(t, configContent, "refresh-secret-token", "Refresh token should not be in plaintext config")
830}
832func Test_ClientCertPassword_StoredInKeyring(t *testing.T) {
833 dir := t.TempDir()
834 keyring.MockInit()
835 cfg := NewBlankConfigInDir(dir)
836 require.NoError(t, cfg.Set("git.example.com", "use_keyring", "true"))
838 require.NoError(t, cfg.Set("git.example.com", "client_cert_password", "p12-secret"))
840 stored, err := keyring.Get("glab:git.example.com:client_cert_password", "")
841 require.NoError(t, err)
842 assert.Equal(t, "p12-secret", stored)
843 value, source, err := cfg.GetWithSource("git.example.com", "client_cert_password", false)
844 require.NoError(t, err)
845 assert.Equal(t, "p12-secret", value)
846 assert.Equal(t, "keyring", source)
847 require.NoError(t, cfg.Write())
848 assert.NotContains(t, persistedFile(t, dir, "config.yml"), "p12-secret")
849}
851func Test_ClientCertPassword_RoundTripsThroughConfigFile(t *testing.T) {
852 dir := t.TempDir()
853 cfg := NewBlankConfigInDir(dir)
854 require.NoError(t, cfg.Set("git.example.com", "client_cert_password", "p12-secret"))
855 require.NoError(t, cfg.Write())
857 reloaded, err := cfg.Reload()
858 require.NoError(t, err)
859 value, err := reloaded.Get("git.example.com", "client_cert_password")
860 require.NoError(t, err)
861 assert.Equal(t, "p12-secret", value)
862}
864func Test_ClientCertPassword_ReadsEnvironmentVariable(t *testing.T) {
865 t.Setenv("GLAB_CLIENT_CERT_PASSWORD", "from-env")
866 cfg := NewBlankConfig()
867 require.NoError(t, cfg.Set("git.example.com", "client_cert_password", "from-file"))
869 value, source, err := cfg.GetWithSource("git.example.com", "client_cert_password", true)
870 require.NoError(t, err)
871 assert.Equal(t, "from-env", value)
872 assert.Equal(t, "GLAB_CLIENT_CERT_PASSWORD", source)
873}
875func Test_GetWithSource_RetrievesFromKeyringWhenUseKeyringSet(t *testing.T) {
876 dir := t.TempDir()
877 seedFile(t, dir, "config.yml", heredoc.Doc(`
878 ---
879 hosts:
880 gitlab.com:
881 use_keyring: "true"
882 is_oauth2: true
883 `))
885 keyring.MockInit()
887 // Store token in keyring with new key format
888 err := keyring.Set("glab:gitlab.com:token", "", "glpat-from-keyring")
889 require.NoError(t, err)
891 // Store refresh token in keyring with new key format
892 err = keyring.Set("glab:gitlab.com:oauth2_refresh_token", "", "refresh-from-keyring")
893 require.NoError(t, err)
895 cfg, err := ParseConfig(filepath.Join(dir, "config.yml"))
896 require.NoError(t, err)
898 // Retrieve token - should come from keyring, not config
899 token, source, err := cfg.GetWithSource("gitlab.com", "token", false)
900 require.NoError(t, err)
901 assert.Equal(t, "glpat-from-keyring", token)
902 assert.Equal(t, "keyring", source)
904 // Retrieve refresh token - should come from keyring
905 refreshToken, source, err := cfg.GetWithSource("gitlab.com", "oauth2_refresh_token", false)
906 require.NoError(t, err)
907 assert.Equal(t, "refresh-from-keyring", refreshToken)
908 assert.Equal(t, "keyring", source)
909}
911func Test_GetWithSource_KeyringEnabledButTokenMissingReturnsEmpty(t *testing.T) {
912 dir := t.TempDir()
913 seedFile(t, dir, "config.yml", `---
914hosts:
915 gitlab.com:
916 use_keyring: "true"
917`)
919 keyring.MockInit()
920 // Don't store any token in keyring
922 cfg, err := ParseConfig(filepath.Join(dir, "config.yml"))
923 require.NoError(t, err)
925 // A genuinely missing keyring entry is not an error: it is treated like an
926 // unset value so callers can fall back to re-authentication rather than
927 // failing with a confusing keyring error. (Real keyring failures, such as a
928 // denied or locked keyring, are surfaced instead — see
929 // Test_GetWithSource_SurfacesKeyringReadError.)
930 token, _, err := cfg.GetWithSource("gitlab.com", "token", false)
931 require.NoError(t, err)
932 assert.Empty(t, token)
933}
935func Test_SetKeyring_JobToken(t *testing.T) {
936 keyring.MockInit()
937 cfg := NewBlankConfig()
939 // Enable keyring mode
940 err := cfg.Set("gitlab.com", "use_keyring", "true")
941 require.NoError(t, err)
943 // Set a job token - should go to keyring
944 err = cfg.Set("gitlab.com", "job_token", "job-token-value")
945 require.NoError(t, err)
947 // Verify job token is stored in keyring with new key format
948 storedToken, err := keyring.Get("glab:gitlab.com:job_token", "")
949 require.NoError(t, err)
950 assert.Equal(t, "job-token-value", storedToken)
952 // Verify use_keyring indicator is set
953 useKeyring, err := cfg.Get("gitlab.com", "use_keyring")
954 require.NoError(t, err)
955 assert.Equal(t, "true", useKeyring)
956}
958func Test_SetKeyring_CleansUpExistingPlaintextToken(t *testing.T) {
959 dir := t.TempDir()
960 seedFile(t, dir, "config.yml", `---
961hosts:
962 gitlab.com:
963 token: glpat-old-plaintext-token
964`)
966 keyring.MockInit()
967 cfg, err := ParseConfig(filepath.Join(dir, "config.yml"))
968 require.NoError(t, err)
970 // Enable keyring mode
971 err = cfg.Set("gitlab.com", "use_keyring", "true")
972 require.NoError(t, err)
974 // Set token - should go to keyring and remove plaintext token from config
975 err = cfg.Set("gitlab.com", "token", "glpat-new-keyring-token")
976 require.NoError(t, err)
978 err = cfg.Write()
979 require.NoError(t, err)
981 // Verify old plaintext token is removed from config
982 configContent := persistedFile(t, dir, "config.yml")
983 assert.NotContains(t, configContent, "glpat-old-plaintext-token")
984 assert.NotContains(t, configContent, "glpat-new-keyring-token")
985 assert.Contains(t, configContent, "use_keyring: \"true\"")
987 // Verify new token is in keyring with new key format
988 storedToken, err := keyring.Get("glab:gitlab.com:token", "")
989 require.NoError(t, err)
990 assert.Equal(t, "glpat-new-keyring-token", storedToken)
991}
993func Test_extractSubfolderFromURL(t *testing.T) {
994 tests := []struct {
995 name string
996 url string
997 expected string
998 }{
999 {
1000 name: "URL with subfolder",
1001 url: "https://example.com/gitlab",
1002 expected: "gitlab",
1003 },
1004 {
1005 name: "URL with nested subfolder",
1006 url: "https://example.com/tools/gitlab",
1007 expected: "tools/gitlab",
1008 },
1009 {
1010 name: "URL without subfolder",
1011 url: "https://example.com",
1012 expected: "",
1013 },
1014 {
1015 name: "URL with only slash",
1016 url: "https://example.com/",
1017 expected: "",
1018 },
1019 {
1020 name: "URL with trailing slash",
1021 url: "https://example.com/gitlab/",
1022 expected: "gitlab",
1023 },
1024 {
1025 name: "URL with port and subfolder",
1026 url: "https://example.com:3000/gitlab",
1027 expected: "gitlab",
1028 },
1029 }
1031 for _, tt := range tests {
1032 t.Run(tt.name, func(t *testing.T) {
1033 result := extractSubfolderFromURL(tt.url)
1034 assert.Equal(t, tt.expected, result)
1035 })
1036 }
1037}
1039func Test_GetFromEnvWithSource_CI_Subfolder(t *testing.T) {
1040 t.Run("subfolder from GITLAB_SUBFOLDER", func(t *testing.T) {
1041 t.Setenv("GITLAB_SUBFOLDER", "mysubfolder")
1042 t.Setenv("GLAB_ENABLE_CI_AUTOLOGIN", "")
1043 t.Setenv("GITLAB_CI", "")
1045 value, source := GetFromEnvWithSource("subfolder")
1046 assert.Equal(t, "mysubfolder", value)
1047 assert.Equal(t, "GITLAB_SUBFOLDER", source)
1048 })
1050 t.Run("subfolder from CI_SERVER_URL with path", func(t *testing.T) {
1051 t.Setenv("GITLAB_SUBFOLDER", "")
1052 t.Setenv("CI_SERVER_URL", "https://example.com/gitlab")
1053 t.Setenv("GLAB_ENABLE_CI_AUTOLOGIN", "true")
1054 t.Setenv("GITLAB_CI", "true")
1056 value, source := GetFromEnvWithSource("subfolder")
1057 assert.Equal(t, "gitlab", value)
1058 assert.Equal(t, "CI_SERVER_URL", source)
1059 })
1061 t.Run("subfolder from CI_SERVER_URL without path", func(t *testing.T) {
1062 t.Setenv("GITLAB_SUBFOLDER", "")
1063 t.Setenv("CI_SERVER_URL", "https://example.com")
1064 t.Setenv("GLAB_ENABLE_CI_AUTOLOGIN", "true")
1065 t.Setenv("GITLAB_CI", "true")
1067 value, source := GetFromEnvWithSource("subfolder")
1068 assert.Empty(t, value)
1069 assert.Empty(t, source)
1070 })
1072 t.Run("GITLAB_SUBFOLDER takes precedence over CI_SERVER_URL", func(t *testing.T) {
1073 t.Setenv("GITLAB_SUBFOLDER", "explicit")
1074 t.Setenv("CI_SERVER_URL", "https://example.com/gitlab")
1075 t.Setenv("GLAB_ENABLE_CI_AUTOLOGIN", "true")
1076 t.Setenv("GITLAB_CI", "true")
1078 value, source := GetFromEnvWithSource("subfolder")
1079 assert.Equal(t, "explicit", value)
1080 assert.Equal(t, "GITLAB_SUBFOLDER", source)
1081 })
1082}
1084func Test_GetFromEnvWithSource_CI_SSHHost(t *testing.T) {
1085 t.Run("ssh_host from GITLAB_SSH_HOST", func(t *testing.T) {
1086 t.Setenv("GITLAB_SSH_HOST", "ssh.example.com")
1087 t.Setenv("GLAB_ENABLE_CI_AUTOLOGIN", "")
1088 t.Setenv("GITLAB_CI", "")
1090 value, source := GetFromEnvWithSource("ssh_host")
1091 assert.Equal(t, "ssh.example.com", value)
1092 assert.Equal(t, "GITLAB_SSH_HOST", source)
1093 })
1095 t.Run("ssh_host from CI_SERVER_SHELL_SSH_HOST without port", func(t *testing.T) {
1096 t.Setenv("GITLAB_SSH_HOST", "")
1097 t.Setenv("CI_SERVER_SHELL_SSH_HOST", "git.example.com")
1098 t.Setenv("CI_SERVER_SHELL_SSH_PORT", "")
1099 t.Setenv("GLAB_ENABLE_CI_AUTOLOGIN", "true")
1100 t.Setenv("GITLAB_CI", "true")
1102 value, source := GetFromEnvWithSource("ssh_host")
1103 assert.Equal(t, "git.example.com", value)
1104 assert.Equal(t, "CI_SERVER_SHELL_SSH_HOST", source)
1105 })
1107 t.Run("ssh_host from CI_SERVER_SHELL_SSH_HOST with custom port", func(t *testing.T) {
1108 t.Setenv("GITLAB_SSH_HOST", "")
1109 t.Setenv("CI_SERVER_SHELL_SSH_HOST", "git.example.com")
1110 t.Setenv("CI_SERVER_SHELL_SSH_PORT", "2222")
1111 t.Setenv("GLAB_ENABLE_CI_AUTOLOGIN", "true")
1112 t.Setenv("GITLAB_CI", "true")
1114 value, source := GetFromEnvWithSource("ssh_host")
1115 assert.Equal(t, "git.example.com:2222", value)
1116 assert.Equal(t, "CI_SERVER_SHELL_SSH_HOST", source)
1117 })
1119 t.Run("ssh_host from CI_SERVER_SHELL_SSH_HOST with default port 22", func(t *testing.T) {
1120 t.Setenv("GITLAB_SSH_HOST", "")
1121 t.Setenv("CI_SERVER_SHELL_SSH_HOST", "git.example.com")
1122 t.Setenv("CI_SERVER_SHELL_SSH_PORT", "22")
1123 t.Setenv("GLAB_ENABLE_CI_AUTOLOGIN", "true")
1124 t.Setenv("GITLAB_CI", "true")
1126 value, source := GetFromEnvWithSource("ssh_host")
1127 assert.Equal(t, "git.example.com", value)
1128 assert.Equal(t, "CI_SERVER_SHELL_SSH_HOST", source)
1129 })
1131 t.Run("GITLAB_SSH_HOST takes precedence over CI_SERVER_SHELL_SSH_HOST", func(t *testing.T) {
1132 t.Setenv("GITLAB_SSH_HOST", "ssh.example.com:3000")
1133 t.Setenv("CI_SERVER_SHELL_SSH_HOST", "git.example.com")
1134 t.Setenv("CI_SERVER_SHELL_SSH_PORT", "2222")
1135 t.Setenv("GLAB_ENABLE_CI_AUTOLOGIN", "true")
1136 t.Setenv("GITLAB_CI", "true")
1138 value, source := GetFromEnvWithSource("ssh_host")
1139 assert.Equal(t, "ssh.example.com:3000", value)
1140 assert.Equal(t, "GITLAB_SSH_HOST", source)
1141 })
1142}
1144func Test_IsGlobalOnlyKey(t *testing.T) {
1145 // Drift guards against the schema rather than a hand-kept list, so a new
1146 // glab-managed key cannot slip in without IsGlobalOnlyKey covering it.
1147 for _, def := range KeySchema {
1148 if strings.Contains(def.Description, "(automatically set)") {
1149 assert.Truef(t, def.GlobalOnly,
1150 "%s is described as automatically set, so it must be GlobalOnly", def.Name)
1151 }
1153 if !def.GlobalOnly {
1154 continue
1155 }
1157 assert.Equalf(t, ScopeGlobal, def.Scope, "a GlobalOnly key is not per host: %s", def.Name)
1159 // The name and every alias resolve as glab-managed state.
1160 assert.Truef(t, IsGlobalOnlyKey(def.Name), "%s is state glab maintains for itself", def.Name)
1161 for _, alias := range def.Aliases {
1162 assert.Truef(t, IsGlobalOnlyKey(alias), "alias %s of %s is glab-managed state", alias, def.Name)
1163 }
1164 }
1166 // Ordinary ScopeGlobal keys are still meant to be set per repository.
1167 for _, key := range []string{"git_protocol", "branch_prefix", "editor", "remote_alias"} {
1168 assert.Falsef(t, IsGlobalOnlyKey(key), "%s is a user setting, not glab-managed state", key)
1169 }
1170}
1172// A value for a glab-managed key sitting in a repository's local file used to
1173// win every read, while every write went to the global file. `glab duo cli
1174// update` then re-downloaded the same version on each run.
1175func Test_GetWithSource_GlobalOnlyKeySkipsLocalConfig(t *testing.T) {
1176 cfg := NewBlankConfig()
1178 local, err := cfg.Local()
1179 require.NoError(t, err)
1180 require.NoError(t, local.SetStringValue("duo_cli_binary_version", "9.5.0"))
1181 require.NoError(t, cfg.Set("", "duo_cli_binary_version", "9.26.0"))
1183 value, source, err := cfg.GetWithSource("", "duo_cli_binary_version", false)
1184 require.NoError(t, err)
1185 assert.Equal(t, "9.26.0", value, "the global value is the one glab writes and must be the one it reads")
1186 assert.Equal(t, ConfigFile(), source)
1187}
1189// A user setting keeps its existing precedence: local wins over global.
1190func Test_GetWithSource_OrdinaryKeyStillPrefersLocalConfig(t *testing.T) {
1191 cfg := NewBlankConfig()
1193 local, err := cfg.Local()
1194 require.NoError(t, err)
1195 require.NoError(t, local.SetStringValue("git_protocol", "https"))
1196 require.NoError(t, cfg.Set("", "git_protocol", "ssh"))
1198 value, source, err := cfg.GetWithSource("", "git_protocol", false)
1199 require.NoError(t, err)
1200 assert.Equal(t, "https", value)
1201 assert.Equal(t, LocalConfigFile(), source)
1202}
Diagnostics6 git calls · 46 ms
CallStatusSizeTime046 ms
discover200185 B2 ms
git.upload-pack discover http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=ls-refs git.upstream.dur_ms=2 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 KiB2 ms
git.upload-pack ls-refs http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=ls-refs git.upstream.dur_ms=2 git.response.bytes=59849 git.response.cache=UPDATING git.response.duration_ms=2 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
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=44Open pack map
fetchcombine:blob:none+tree:2 · deepen 12004.2 KiB · hit4 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=4 git.response.bytes=4273 git.response.cache=HIT git.response.duration_ms=4 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:02001.4 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=1391 git.response.cache=HIT git.response.duration_ms=3 git.fetch.filter=tree:0 git.fetch.wants=e9da9edfdcf44933ee5fa121d411de326220161c 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=1391 git.pkt.payload.max=1364 git.sideband.band1.bytes=1364 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0 git.pack.objects=1 git.pack.bytes=1364 git.pack.trailer=bf750bd385ed98d15e1fea1289d3b00caa61d64cOpen pack map
fetch2008.5 KiB · hit37 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=36 git.response.bytes=8713 git.response.cache=HIT git.response.duration_ms=37 git.fetch.wants=da8256307b4d6733f9f6d58644b55ed8e8b34327 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=8713 git.pkt.payload.max=8686 git.sideband.band1.bytes=8686 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
- a5e280043ee50555
- Request
- 8e296875…
- 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