GitLabgitlab-org
cli
main
1//go:build !integration
3package config
5import (
6 "bytes"
7 "fmt"
8 "os"
9 "path/filepath"
10 "reflect"
11 "runtime"
12 "testing"
14 "github.com/adrg/xdg"
15 "github.com/stretchr/testify/assert"
16 "github.com/stretchr/testify/require"
17 "go.yaml.in/yaml/v3"
19 "gitlab.com/gitlab-org/cli/test"
20)
22func eq(t *testing.T, got any, expected any) {
23 t.Helper()
24 if !reflect.DeepEqual(got, expected) {
25 t.Errorf("expected: %v, got: %v", expected, got)
26 }
27}
29// setupTestHome creates a temporary home directory and sets up environment
30// variables for cross-platform testing (HOME for Unix/macOS, USERPROFILE for Windows).
31// It also reloads the XDG paths to pick up the new environment.
32func setupTestHome(t *testing.T) string {
33 t.Helper()
34 test.ClearEnvironmentVariables(t)
36 homeDir := t.TempDir()
37 // Set both HOME (Unix/macOS) and USERPROFILE (Windows) for cross-platform compatibility
38 t.Setenv("HOME", homeDir)
39 t.Setenv("USERPROFILE", homeDir)
41 return homeDir
42}
44// setupXDGHome creates a temporary XDG config directory and sets XDG_CONFIG_HOME.
45// It reloads XDG paths after setting the environment variable.
46func setupXDGHome(t *testing.T) string {
47 t.Helper()
49 xdgConfigHome := t.TempDir()
50 t.Setenv("XDG_CONFIG_HOME", xdgConfigHome)
51 xdg.Reload()
53 return xdgConfigHome
54}
56func Test_parseConfig(t *testing.T) {
57 test.ClearEnvironmentVariables(t)
58 dir := t.TempDir()
59 seedFile(t, dir, "config.yml", `---
60hosts:
61 gitlab.com:
62 username: monalisa
63 token: OTOKEN
64aliases:
65`)
67 config, err := ParseConfig(filepath.Join(dir, "config.yml"))
68 eq(t, err, nil)
69 username, err := config.Get("gitlab.com", "username")
70 eq(t, err, nil)
71 eq(t, username, "monalisa")
72 token, err := config.Get("gitlab.com", "token")
73 eq(t, err, nil)
74 eq(t, token, "OTOKEN")
75}
77func Test_parseConfig_multipleHosts(t *testing.T) {
78 test.ClearEnvironmentVariables(t)
79 dir := t.TempDir()
80 seedFile(t, dir, "config.yml", `---
81hosts:
82 gitlab.example.com:
83 username: wrongusername
84 token: NOTTHIS
85 gitlab.com:
86 username: monalisa
87 token: OTOKEN
88`)
90 config, err := ParseConfig(filepath.Join(dir, "config.yml"))
91 eq(t, err, nil)
92 username, err := config.Get("gitlab.com", "username")
93 eq(t, err, nil)
94 eq(t, username, "monalisa")
95 token, err := config.Get("gitlab.com", "token")
96 eq(t, err, nil)
97 eq(t, token, "OTOKEN")
98}
100func Test_parseConfig_Hosts(t *testing.T) {
101 test.ClearEnvironmentVariables(t)
102 dir := t.TempDir()
103 seedFile(t, dir, "config.yml", `---
104hosts:
105 gitlab.com:
106 username: monalisa
107 token: OTOKEN
108`)
110 config, err := ParseConfig(filepath.Join(dir, "config.yml"))
111 eq(t, err, nil)
112 username, err := config.Get("gitlab.com", "username")
113 eq(t, err, nil)
114 eq(t, username, "monalisa")
115 token, err := config.Get("gitlab.com", "token")
116 eq(t, err, nil)
117 eq(t, token, "OTOKEN")
118}
120func Test_parseConfig_Local(t *testing.T) {
121 test.ClearEnvironmentVariables(t)
122 dir := t.TempDir()
123 seedFile(t, dir, "config.yml", `---
124git_protocol: ssh
125editor: vim
126local:
127 git_protocol: https
128 editor: nano
129`)
131 config, err := ParseConfig(filepath.Join(dir, "config.yml"))
132 eq(t, err, nil)
133 gitProtocol, err := config.Get("", "git_protocol")
134 eq(t, err, nil)
135 eq(t, gitProtocol, "https")
136 editor, err := config.Get("", "editor")
137 eq(t, err, nil)
138 eq(t, editor, "nano")
139}
141func Test_Get_configReadSequence(t *testing.T) {
142 test.ClearEnvironmentVariables(t)
144 dir := t.TempDir()
145 seedFile(t, dir, "config.yml", `---
146git_protocol: ssh
147editor: vim
148browser: mozilla
149local:
150 git_protocol: https
151 editor:
152 browser: chrome
153`)
154 t.Setenv("BROWSER", "opera")
156 config, err := ParseConfig(filepath.Join(dir, "config.yml"))
157 eq(t, err, nil)
158 gitProtocol, err := config.Get("", "git_protocol")
159 eq(t, err, nil)
160 eq(t, gitProtocol, "https")
161 token, err := config.Get("", "editor")
162 eq(t, err, nil)
163 eq(t, token, "vim")
164 browser, err := config.Get("", "browser")
165 eq(t, err, nil)
166 eq(t, browser, "opera")
167 l, _ := config.Local()
168 t.Log(l.All())
169}
171func Test_parseConfig_AliasesFile(t *testing.T) {
172 dir := t.TempDir()
173 seedFile(t, dir, "config.yml", "")
174 seedFile(t, dir, "aliases.yml", `---
175ci: pipeline ci
176co: mr checkout
177`)
178 config, err := ParseConfig(filepath.Join(dir, "config.yml"))
179 eq(t, err, nil)
180 aliases, err := config.Aliases()
181 eq(t, err, nil)
182 a, isAlias := aliases.Get("ci")
183 eq(t, isAlias, true)
184 eq(t, a, "pipeline ci")
185 b, isAlias := aliases.Get("co")
186 eq(t, isAlias, true)
187 eq(t, b, "mr checkout")
188 eq(t, len(aliases.All()), 2)
189}
191func Test_parseConfig_hostFallback(t *testing.T) {
192 dir := t.TempDir()
193 seedFile(t, dir, "config.yml", `---
194git_protocol: ssh
195hosts:
196 gitlab.com:
197 username: monalisa
198 token: OTOKEN
199 gitlab.example.com:
200 username: wrongusername
201 token: NOTTHIS
202 git_protocol: https
203`)
204 config, err := ParseConfig(filepath.Join(dir, "config.yml"))
205 eq(t, err, nil)
206 val, err := config.Get("gitlab.example.com", "git_protocol")
207 eq(t, err, nil)
208 eq(t, val, "https")
209 val, err = config.Get("gitlab.com", "git_protocol")
210 eq(t, err, nil)
211 eq(t, val, "ssh")
212 val, err = config.Get("nonexist.io", "git_protocol")
213 eq(t, err, nil)
214 eq(t, val, "ssh")
215}
217func Test_parseConfigFile(t *testing.T) {
218 tests := []struct {
219 contents string
220 wantsErr bool
221 }{
222 {
223 contents: "",
224 wantsErr: true,
225 },
226 {
227 contents: " ",
228 wantsErr: false,
229 },
230 {
231 contents: "\n",
232 wantsErr: false,
233 },
234 }
236 for _, tt := range tests {
237 t.Run(fmt.Sprintf("contents: %q", tt.contents), func(t *testing.T) {
238 dir := t.TempDir()
239 // Empty contents models a missing file (which must error), so only
240 // write the file when there is actual content.
241 if tt.contents != "" {
242 seedFile(t, dir, "config.yml", tt.contents)
243 }
244 _, yamlRoot, err := ParseConfigFile(filepath.Join(dir, "config.yml"))
245 if tt.wantsErr != (err != nil) {
246 t.Fatalf("got error: %v", err)
247 }
248 if tt.wantsErr {
249 return
250 }
251 assert.Equal(t, yaml.MappingNode, yamlRoot.Content[0].Kind)
252 assert.Empty(t, yamlRoot.Content[0].Content)
253 })
254 }
255}
257func Test_ParseConfigFilePermissions(t *testing.T) {
258 tests := map[string]struct {
259 permissions int
260 wantErr bool
261 }{
262 "bad permissions": {
263 permissions: 0o755,
264 wantErr: true,
265 },
266 "normal permissions": {
267 permissions: 0o600,
268 },
269 }
271 for name, tt := range tests {
272 t.Run(name, func(t *testing.T) {
273 tempDir := t.TempDir()
274 configFile := filepath.Join(tempDir, "config.yml")
276 err := os.WriteFile(
277 configFile,
278 []byte("---\nhost: https://gitlab.mycompany.global"),
279 os.FileMode(tt.permissions),
280 )
281 require.NoError(t, err)
283 _, err = ParseConfig(configFile)
285 if tt.wantErr {
286 require.Error(t, err)
287 } else {
288 require.NoError(t, err)
289 }
290 })
291 }
292}
294func Test_parseConfigHostEnv(t *testing.T) {
295 t.Setenv("GITLAB_URI", "https://gitlab.mycompany.env")
297 dir := t.TempDir()
298 seedFile(t, dir, "config.yml", `---
299host: https://gitlab.mycompany.global
300local:
301 host: https://gitlab.mycompany.local
302`)
303 config, err := ParseConfig(filepath.Join(dir, "config.yml"))
304 eq(t, err, nil)
306 val, err := config.Get("", "host")
307 eq(t, err, nil)
308 eq(t, val, "https://gitlab.mycompany.env")
309}
311func Test_parseConfigHostLocal(t *testing.T) {
312 t.Parallel()
314 dir := t.TempDir()
315 seedFile(t, dir, "config.yml", `---
316host: https://gitlab.mycompany.global
317local:
318 host: https://gitlab.mycompany.local
319`)
320 config, err := ParseConfig(filepath.Join(dir, "config.yml"))
321 eq(t, err, nil)
323 val, err := config.Get("", "host")
324 eq(t, err, nil)
325 eq(t, val, "https://gitlab.mycompany.local")
326}
328func Test_parseConfigHostGlobal(t *testing.T) {
329 t.Parallel()
331 dir := t.TempDir()
332 seedFile(t, dir, "config.yml", `---
333host: https://gitlab.mycompany.org
334`)
335 config, err := ParseConfig(filepath.Join(dir, "config.yml"))
336 eq(t, err, nil)
338 val, err := config.Get("", "host")
339 eq(t, err, nil)
340 eq(t, val, "https://gitlab.mycompany.org")
341}
343func Test_SearchConfigFile_UserConfig(t *testing.T) {
344 _ = setupTestHome(t)
346 // Create a temporary user config directory
347 userConfigDir := t.TempDir()
348 userConfigFile := filepath.Join(userConfigDir, "glab-cli", "config.yml")
350 // Create config file
351 err := os.MkdirAll(filepath.Dir(userConfigFile), 0o750)
352 require.NoError(t, err)
353 err = os.WriteFile(userConfigFile, []byte("test: user"), 0o600)
354 require.NoError(t, err)
356 // Set XDG_CONFIG_HOME to temp directory
357 t.Setenv("XDG_CONFIG_HOME", userConfigDir)
358 xdg.Reload()
360 // SearchConfigFile should find the user config
361 foundPath, err := SearchConfigFile()
362 require.NoError(t, err)
363 assert.Equal(t, userConfigFile, foundPath)
364}
366func Test_SearchConfigFile_SystemConfig(t *testing.T) {
367 _ = setupTestHome(t)
369 // Create temporary directories for system and user configs
370 userConfigDir := t.TempDir()
371 systemConfigDir := t.TempDir()
372 systemConfigFile := filepath.Join(systemConfigDir, "glab-cli", "config.yml")
374 // Create ONLY system config (no user config)
375 err := os.MkdirAll(filepath.Dir(systemConfigFile), 0o750)
376 require.NoError(t, err)
377 err = os.WriteFile(systemConfigFile, []byte("test: system"), 0o600)
378 require.NoError(t, err)
380 // Set XDG environment variables
381 t.Setenv("XDG_CONFIG_HOME", userConfigDir)
382 t.Setenv("XDG_CONFIG_DIRS", systemConfigDir)
383 xdg.Reload()
385 // SearchConfigFile should find the system config
386 foundPath, err := SearchConfigFile()
387 require.NoError(t, err)
388 assert.Equal(t, systemConfigFile, foundPath)
389}
391func Test_SearchConfigFile_Precedence(t *testing.T) {
392 _ = setupTestHome(t)
394 // Create temporary directories
395 userConfigDir := t.TempDir()
396 systemConfigDir := t.TempDir()
397 userConfigFile := filepath.Join(userConfigDir, "glab-cli", "config.yml")
398 systemConfigFile := filepath.Join(systemConfigDir, "glab-cli", "config.yml")
400 // Create both user and system configs
401 err := os.MkdirAll(filepath.Dir(userConfigFile), 0o750)
402 require.NoError(t, err)
403 err = os.WriteFile(userConfigFile, []byte("test: user"), 0o600)
404 require.NoError(t, err)
406 err = os.MkdirAll(filepath.Dir(systemConfigFile), 0o750)
407 require.NoError(t, err)
408 err = os.WriteFile(systemConfigFile, []byte("test: system"), 0o600)
409 require.NoError(t, err)
411 // Set XDG environment variables
412 t.Setenv("XDG_CONFIG_HOME", userConfigDir)
413 t.Setenv("XDG_CONFIG_DIRS", systemConfigDir)
414 xdg.Reload()
416 // SearchConfigFile should prefer user config over system config
417 foundPath, err := SearchConfigFile()
418 require.NoError(t, err)
419 assert.Equal(t, userConfigFile, foundPath)
420}
422func Test_SearchConfigFile_NotFound(t *testing.T) {
423 _ = setupTestHome(t)
425 // Use empty temp directories (no config files)
426 userConfigDir := t.TempDir()
427 systemConfigDir := t.TempDir()
429 t.Setenv("XDG_CONFIG_HOME", userConfigDir)
430 t.Setenv("XDG_CONFIG_DIRS", systemConfigDir)
431 xdg.Reload()
433 // SearchConfigFile should return an error
434 _, err := SearchConfigFile()
435 require.Error(t, err)
436}
438func Test_SearchConfigFile_GLABConfigDirOverride(t *testing.T) {
439 test.ClearEnvironmentVariables(t)
441 // Create temp directories
442 glabConfigDir := t.TempDir()
443 userConfigDir := t.TempDir()
444 glabConfigFile := filepath.Join(glabConfigDir, "config.yml")
445 userConfigFile := filepath.Join(userConfigDir, "glab-cli", "config.yml")
447 // Create both GLAB_CONFIG_DIR and user configs
448 err := os.WriteFile(glabConfigFile, []byte("test: glab"), 0o600)
449 require.NoError(t, err)
451 err = os.MkdirAll(filepath.Dir(userConfigFile), 0o750)
452 require.NoError(t, err)
453 err = os.WriteFile(userConfigFile, []byte("test: user"), 0o600)
454 require.NoError(t, err)
456 // Set both environment variables
457 t.Setenv("GLAB_CONFIG_DIR", glabConfigDir)
458 t.Setenv("XDG_CONFIG_HOME", userConfigDir)
460 // GLAB_CONFIG_DIR should take precedence
461 foundPath, err := SearchConfigFile()
462 require.NoError(t, err)
463 assert.Equal(t, glabConfigFile, foundPath)
464}
466func Test_SearchConfigFile_GLABConfigDirNotFound(t *testing.T) {
467 test.ClearEnvironmentVariables(t)
469 // Use empty GLAB_CONFIG_DIR
470 glabConfigDir := t.TempDir()
471 t.Setenv("GLAB_CONFIG_DIR", glabConfigDir)
473 // Should return os.ErrNotExist, not search XDG paths
474 _, err := SearchConfigFile()
475 require.ErrorIs(t, err, os.ErrNotExist)
476}
478func Test_ConfigFile_XDGCompliance(t *testing.T) {
479 _ = setupTestHome(t)
481 userConfigDir := setupXDGHome(t)
483 configFile := ConfigFile()
484 expectedPath := filepath.Join(userConfigDir, "glab-cli", "config.yml")
486 assert.Equal(t, expectedPath, configFile)
487}
489func Test_ConfigDir_XDGCompliance(t *testing.T) {
490 _ = setupTestHome(t)
492 userConfigDir := setupXDGHome(t)
494 configDir := ConfigDir()
495 expectedPath := filepath.Join(userConfigDir, "glab-cli")
497 assert.Equal(t, expectedPath, configDir)
498}
500func Test_ConfigFile_PureFunction(t *testing.T) {
501 _ = setupTestHome(t)
502 _ = setupXDGHome(t)
504 configFile := ConfigFile()
506 // Should always return a path without side effects
507 assert.NotEmpty(t, configFile)
508 assert.Contains(t, configFile, "glab-cli")
509 assert.Contains(t, configFile, "config.yml")
510 assert.True(t, filepath.IsAbs(configFile), "ConfigFile should return an absolute path")
512 // The directory should NOT be created (pure function)
513 configDir := filepath.Dir(configFile)
514 _, err := os.Stat(configDir)
515 assert.True(t, os.IsNotExist(err), "ConfigFile should not create directories")
516}
518func Test_ConfigDir_LegacyBackwardCompatibility(t *testing.T) {
519 homeDir := setupTestHome(t)
521 // Create legacy config directory and file
522 legacyDir := filepath.Join(homeDir, ".config", "glab-cli")
523 err := os.MkdirAll(legacyDir, 0o750)
524 require.NoError(t, err)
526 legacyConfigFile := filepath.Join(legacyDir, "config.yml")
527 err = os.WriteFile(legacyConfigFile, []byte("test: legacy"), 0o600)
528 require.NoError(t, err)
530 // Even though XDG_CONFIG_HOME might point elsewhere, if legacy config exists,
531 // ConfigDir should return the legacy location
532 _ = setupXDGHome(t)
534 configDir := ConfigDir()
536 // Should use legacy location since the config file exists there
537 assert.Equal(t, legacyDir, configDir)
538}
540func Test_ConfigDir_NewInstallation(t *testing.T) {
541 _ = setupTestHome(t)
543 // Set XDG_CONFIG_HOME to a new location (no legacy config exists)
544 xdgConfigHome := setupXDGHome(t)
546 configDir := ConfigDir()
548 // Should use XDG location since no legacy config exists
549 expectedDir := filepath.Join(xdgConfigHome, "glab-cli")
550 assert.Equal(t, expectedDir, configDir)
551}
553func Test_SearchConfigFile_LegacyLocation(t *testing.T) {
554 homeDir := setupTestHome(t)
556 // Create legacy config
557 legacyDir := filepath.Join(homeDir, ".config", "glab-cli")
558 err := os.MkdirAll(legacyDir, 0o750)
559 require.NoError(t, err)
561 legacyConfigFile := filepath.Join(legacyDir, "config.yml")
562 err = os.WriteFile(legacyConfigFile, []byte("test: legacy"), 0o600)
563 require.NoError(t, err)
565 // Set XDG_CONFIG_HOME to a different location
566 _ = setupXDGHome(t)
568 // SearchConfigFile should find the legacy config first
569 foundPath, err := SearchConfigFile()
570 require.NoError(t, err)
571 assert.Equal(t, legacyConfigFile, foundPath)
572}
574func Test_checkForDuplicateConfigs_SymlinkSameFile(t *testing.T) {
575 // This test simulates Fedora Silverblue where /home is a symlink to /var/home.
576 // Both paths point to the same file, so no duplicate warning should be printed.
577 test.ClearEnvironmentVariables(t)
579 // Create a base directory structure: baseDir/var/home/testuser
580 baseDir := t.TempDir()
581 realHome := filepath.Join(baseDir, "var", "home", "testuser")
582 err := os.MkdirAll(realHome, 0o750)
583 require.NoError(t, err)
585 // Create a symlink: baseDir/home -> baseDir/var/home
586 symlinkHome := filepath.Join(baseDir, "home")
587 err = os.Symlink(filepath.Join(baseDir, "var", "home"), symlinkHome)
588 require.NoError(t, err)
590 // Create config file via the real path
591 realConfigDir := filepath.Join(realHome, ".config", "glab-cli")
592 err = os.MkdirAll(realConfigDir, 0o750)
593 require.NoError(t, err)
594 err = os.WriteFile(filepath.Join(realConfigDir, "config.yml"), []byte("test: value"), 0o600)
595 require.NoError(t, err)
597 // Set HOME to the real path (simulating what os.UserHomeDir returns on Silverblue)
598 t.Setenv("HOME", realHome)
599 t.Setenv("USERPROFILE", realHome)
601 // Set XDG_CONFIG_HOME to the symlinked path (simulating XDG resolution)
602 t.Setenv("XDG_CONFIG_HOME", filepath.Join(symlinkHome, "testuser", ".config"))
603 xdg.Reload()
605 // Both paths resolve to the same file, just accessed via different paths
606 var buf bytes.Buffer
607 checkForDuplicateConfigs(&buf)
609 assert.NotContains(t, buf.String(), "Multiple config files found",
610 "Should not warn about duplicates when paths are symlinks to the same file")
611}
613func Test_checkForDuplicateConfigs_RealDuplicates(t *testing.T) {
614 // This test verifies that we still warn when there are genuinely different config files
615 test.ClearEnvironmentVariables(t)
617 homeDir := t.TempDir()
618 xdgDir := t.TempDir()
620 // Create legacy config
621 legacyConfigDir := filepath.Join(homeDir, ".config", "glab-cli")
622 err := os.MkdirAll(legacyConfigDir, 0o750)
623 require.NoError(t, err)
624 err = os.WriteFile(filepath.Join(legacyConfigDir, "config.yml"), []byte("test: legacy"), 0o600)
625 require.NoError(t, err)
627 // Create XDG config (different file)
628 xdgConfigDir := filepath.Join(xdgDir, "glab-cli")
629 err = os.MkdirAll(xdgConfigDir, 0o750)
630 require.NoError(t, err)
631 err = os.WriteFile(filepath.Join(xdgConfigDir, "config.yml"), []byte("test: xdg"), 0o600)
632 require.NoError(t, err)
634 t.Setenv("HOME", homeDir)
635 t.Setenv("USERPROFILE", homeDir)
636 t.Setenv("XDG_CONFIG_HOME", xdgDir)
637 xdg.Reload()
639 var buf bytes.Buffer
640 checkForDuplicateConfigs(&buf)
642 assert.Contains(t, buf.String(), "Multiple config files found",
643 "Should warn about duplicates when config files are genuinely different")
644}
646// sharedConfigEnv points glab at a shared configuration directory outside the
647// test HOME, with the user's own XDG directory inside it, which is how a real
648// machine is laid out. It returns (sharedDir, userDir).
649//
650// xdg.Reload is undone on cleanup: t.Setenv restores the environment but not
651// the paths adrg/xdg already parsed from it, so without this a later test in
652// the same binary inherits these directories.
653func sharedConfigEnv(t *testing.T) (string, string) {
654 t.Helper()
655 home := setupTestHome(t)
657 sharedDir := t.TempDir() // outside HOME, like /etc/xdg
658 userDir := filepath.Join(home, ".config-xdg")
659 require.NoError(t, os.MkdirAll(userDir, 0o750))
661 t.Setenv("GLAB_CONFIG_DIR", "")
662 t.Setenv("XDG_CONFIG_HOME", userDir)
663 t.Setenv("XDG_CONFIG_DIRS", sharedDir)
664 xdg.Reload()
665 t.Cleanup(func() { xdg.Reload() })
667 return sharedDir, userDir
668}
670// writeConfigAt writes contents to <dir>/glab-cli/<name> with exactly perm.
671func writeConfigAt(t *testing.T, dir, name, contents string, perm os.FileMode) string {
672 t.Helper()
673 path := filepath.Join(dir, "glab-cli", name)
674 require.NoError(t, os.MkdirAll(filepath.Dir(path), 0o755))
675 require.NoError(t, os.WriteFile(path, []byte(contents), perm))
676 // WriteFile is subject to the umask, so set the mode explicitly.
677 require.NoError(t, os.Chmod(path, perm))
678 return path
679}
681func TestHasSafeSharedPerms(t *testing.T) {
682 if runtime.GOOS == "windows" {
683 t.Skip("permission bits are not enforced on Windows")
684 }
686 assert.True(t, HasSafeSharedPerms(0o644))
687 assert.True(t, HasSafeSharedPerms(0o600))
688 assert.False(t, HasSafeSharedPerms(0o664))
689 assert.False(t, HasSafeSharedPerms(0o666))
690}
692func TestParseConfigFile_Permissions(t *testing.T) {
693 if runtime.GOOS == "windows" {
694 t.Skip("permission bits are not enforced on Windows")
695 }
697 // A shared file has to be readable by every user, so the read mode is not
698 // checked. The write bits still are: a config can run a command through
699 // custom_headers.valueFromCommand, so one another account can write is
700 // code execution.
701 for _, tc := range []struct {
702 mode os.FileMode
703 accepted bool
704 }{
705 {0o644, true},
706 {0o600, true},
707 {0o664, false},
708 {0o666, false},
709 {0o646, false},
710 } {
711 t.Run(fmt.Sprintf("shared mode %o", tc.mode), func(t *testing.T) {
712 shared, _ := sharedConfigEnv(t)
713 path := writeConfigAt(t, shared, "config.yml", "editor: vim\n", tc.mode)
715 _, root, err := ParseConfigFile(path)
716 if tc.accepted {
717 require.NoError(t, err)
718 assert.NotNil(t, root)
719 return
720 }
721 require.Error(t, err)
722 assert.Contains(t, err.Error(), "not to be writable by group or others")
723 })
724 }
726 t.Run("a credential in a world-readable shared file is read", func(t *testing.T) {
727 shared, _ := sharedConfigEnv(t)
728 path := writeConfigAt(t, shared, "config.yml", "hosts:\n gitlab.com:\n token: glpat-xxx\n", 0o644)
730 _, root, err := ParseConfigFile(path)
731 require.NoError(t, err)
732 assert.NotNil(t, root)
733 })
735 t.Run("a shared aliases.yml does not fail the whole CLI", func(t *testing.T) {
736 // parseConfig propagates a non-ErrNotExist error from aliases.yml, so
737 // holding it to the user rule fails every glab command, not just aliases.
738 shared, _ := sharedConfigEnv(t)
739 writeConfigAt(t, shared, "config.yml", "editor: vim\n", 0o644)
740 writeConfigAt(t, shared, "aliases.yml", "token: personal-access-token list\n", 0o644)
742 _, err := ParseDefaultConfig()
743 require.NoError(t, err)
744 })
746 t.Run("a shared config is readable with HOME unset", func(t *testing.T) {
747 // Containers, systemd units and cron jobs scrub the environment, and
748 // they are the setups that rely on a system-wide config.
749 shared, _ := sharedConfigEnv(t)
750 path := writeConfigAt(t, shared, "config.yml", "editor: vim\n", 0o644)
751 t.Setenv("HOME", "")
753 _, _, err := ParseConfigFile(path)
754 require.NoError(t, err)
755 })
757 t.Run("GLAB_CONFIG_DIR pointing at a shared directory stays shared", func(t *testing.T) {
758 // Pointing a fleet at a provisioned config must not reimpose 600.
759 shared, _ := sharedConfigEnv(t)
760 path := writeConfigAt(t, shared, "config.yml", "editor: vim\n", 0o644)
761 t.Setenv("GLAB_CONFIG_DIR", filepath.Join(shared, "glab-cli"))
763 _, _, err := ParseConfigFile(path)
764 require.NoError(t, err)
765 })
767 t.Run("a symlinked shared directory is still shared", func(t *testing.T) {
768 // filepath.Abs alone would compare the link unequal to its target and
769 // fall back to the 600 rule.
770 shared, _ := sharedConfigEnv(t)
771 writeConfigAt(t, shared, "config.yml", "editor: vim\n", 0o644)
773 link := filepath.Join(t.TempDir(), "link")
774 require.NoError(t, os.Symlink(shared, link))
776 _, _, err := ParseConfigFile(filepath.Join(link, "glab-cli", "config.yml"))
777 require.NoError(t, err)
778 })
780 t.Run("a user config is still held to 600", func(t *testing.T) {
781 _, user := sharedConfigEnv(t)
782 path := writeConfigAt(t, user, "config.yml", "editor: vim\n", 0o644)
784 _, _, err := ParseConfigFile(path)
785 require.Error(t, err)
786 assert.Contains(t, err.Error(), "glab requires 600")
787 })
789 t.Run("an unreadable user config keeps the actionable error", func(t *testing.T) {
790 // Statting the open handle instead would report "permission denied"
791 // rather than the chmod advice.
792 _, user := sharedConfigEnv(t)
793 path := writeConfigAt(t, user, "config.yml", "editor: vim\n", 0o200)
795 _, _, err := ParseConfigFile(path)
796 require.Error(t, err)
797 assert.Contains(t, err.Error(), "chmod 600")
798 })
800 t.Run("the legacy directory is a user config even when listed in ConfigDirs", func(t *testing.T) {
801 // On macOS adrg/xdg puts $HOME/.config in ConfigDirs, and that is glab's
802 // own legacy user directory, so membership alone would drop the 600 rule
803 // for exactly the file it protects.
804 home := setupTestHome(t)
805 legacy := filepath.Join(home, ".config")
806 require.NoError(t, os.MkdirAll(legacy, 0o750))
808 t.Setenv("GLAB_CONFIG_DIR", "")
809 t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, ".config-xdg"))
810 t.Setenv("XDG_CONFIG_DIRS", legacy)
811 xdg.Reload()
812 t.Cleanup(func() { xdg.Reload() })
814 require.Contains(t, xdg.ConfigDirs, legacy, "precondition: the legacy dir is in ConfigDirs")
816 path := writeConfigAt(t, legacy, "config.yml", "editor: vim\n", 0o644)
818 _, _, err := ParseConfigFile(path)
819 require.Error(t, err, "a user's own config must keep the 600 rule")
820 assert.Contains(t, err.Error(), "glab requires 600")
821 })
822}
Diagnostics6 git calls · 41 ms
CallStatusSizeTime041 ms
discover200185 B4 ms
git.upload-pack discover http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=3 git.response.bytes=185 git.server.agent=git/2.56.g1891de4-Linux git.server.object_format=sha1 git.server.caps=agent ls-refs fetch server-option object-format git.server.fetch=shallow wait-for-done filter git.protocol.version=2 git.pkt.frames=9 git.pkt.data=7 git.pkt.flush=2 git.pkt.delim=0 git.pkt.bytes=185 git.pkt.payload.max=35
ls-refs20058 KiB3 ms
git.upload-pack ls-refs http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=ls-refs git.upstream.dur_ms=3 git.response.bytes=59849 git.response.cache=UPDATING git.response.duration_ms=3 git.protocol.version=2 git.pkt.frames=731 git.pkt.data=730 git.pkt.flush=1 git.pkt.delim=0 git.pkt.bytes=59849 git.pkt.payload.max=143 git.ls_refs.count=730 git.ls_refs.head=refs/heads/main
fetchcombine:blob:none+tree:2 · deepen 12004.2 KiB · 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=4273 git.response.cache=HIT git.response.duration_ms=3 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 · hit5 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=5 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
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=31 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
fetch2005.0 KiB · hit31 ms
git.upload-pack fetch http.response.status_code=200 git.response.bytes=5151 git.response.cache=HIT git.response.duration_ms=31 git.fetch.wants=cbfc18660cdf9a0a4a3f9136bf5222e5e53c6b03 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=5151 git.pkt.payload.max=5124 git.sideband.band1.bytes=5124 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
- a5e29f11ecec1293
- Request
- 7b99eee1…
- 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