GitLabgitlab-org
cli
main
1// Package dockercredhelper wires glab into Docker as a credential helper: it
2// installs the docker-credential-glab shim that Docker executes, and points
3// Docker's config.json at that shim for a set of registry domains.
4package dockercredhelper
6import (
7 "fmt"
8 "maps"
9 "os"
10 "os/exec"
11 "path/filepath"
12 "slices"
13 "strings"
15 dockerconfig "github.com/docker/cli/cli/config"
16)
18const (
19 // FullName is the shim's file name, and is what Docker looks for in the
20 // user's PATH.
21 FullName = "docker-credential-glab"
22 // ShortName is the short name of the credential helper, and is what a
23 // Docker config's credHelpers object lists for a registry.
24 ShortName = "glab"
25)
27// script is the shim Docker executes. It delegates straight to
28// `glab auth docker-helper`, which reads the requested registry on stdin.
29var script = []byte("#!/bin/sh -eu\nexec glab auth docker-helper \"$@\"\n")
31// Installation reports where Install put the shim.
32type Installation struct {
33 Path string
34 // OnPath is false when Path's directory is absent from PATH, which happens
35 // only when no directory on PATH would accept the write. Docker resolves
36 // the shim by name through PATH, so until the user adds the directory the
37 // shim is inert and the caller has to say so.
38 OnPath bool
39}
41// PathWarning is what to tell the user when OnPath is false. It lives next to
42// the field rather than in each caller so the commands that install the shim
43// (`glab auth configure-docker` and `glab artifact-registry login --docker`)
44// cannot drift apart on the remedy they name.
45//
46// No leading icon and no trailing newline: those belong to how the caller
47// formats a warning line.
48func (i Installation) PathWarning() string {
49 return fmt.Sprintf(
50 "%s was installed to %s, which is not on your PATH. Docker looks %s up by name, so add that directory to PATH before pulling from a GitLab registry.",
51 FullName, filepath.Dir(i.Path), FullName)
52}
54// Locate resolves the glab binary on PATH. The shim shells out to it, and
55// Install prefers to write the shim into the same directory, so a glab that
56// PATH cannot resolve means the install can never work.
57//
58// Exported separately from Install so a caller that does other work first,
59// such as a token exchange, can fail on a missing glab before spending that
60// work rather than after. Install calls it too, so a caller that skips the
61// check is not left unguarded.
62func Locate() (string, error) {
63 path, err := exec.LookPath("glab")
64 if err != nil {
65 return "", fmt.Errorf("looking up the glab binary on PATH: %w", err)
66 }
67 return path, nil
68}
70// Registration reports the outcome of pointing Docker at glab for one domain.
71type Registration struct {
72 Domain string
73 // ShadowedLogin is true when Docker's config.json already held a
74 // credential for Domain, which `docker login` writes. Docker consults
75 // credHelpers ahead of that entry, so the stored credential is now unused
76 // and the caller should say so.
77 ShadowedLogin bool
78}
80// ShadowedLoginWarning is what to tell the user when ShadowedLogin is set. It
81// lives next to the field rather than in each caller so the commands that
82// register domains (`glab auth configure-docker` and `glab artifact-registry
83// login --docker`) cannot drift apart on the remedy they name.
84//
85// No leading icon and no trailing newline: those belong to how the caller
86// formats a warning line.
87func (r Registration) ShadowedLoginWarning() string {
88 return fmt.Sprintf(
89 "%s already had credentials from `docker login`. Docker asks %s first, so those are no longer used; run `docker logout %s` to remove them.",
90 r.Domain, ShortName, r.Domain)
91}
93// ConflictError reports domains that a different credential helper already
94// claims. Register returns it having written nothing.
95type ConflictError struct {
96 // Helpers maps a domain to the credential helper already configured for it.
97 Helpers map[string]string
98 // ConfigPath is the config.json holding those entries.
99 ConfigPath string
100}
102func (e *ConflictError) Error() string {
103 domains := slices.Sorted(maps.Keys(e.Helpers))
105 claims := make([]string, 0, len(domains))
106 for _, domain := range domains {
107 claims = append(claims, fmt.Sprintf("%s is handled by %q", domain, e.Helpers[domain]))
108 }
110 // No trailing period: the CLI's error renderer appends one.
111 return fmt.Sprintf(
112 "refusing to replace another Docker credential helper: %s. "+
113 "Remove the matching credHelpers entries from %s if you want %s to manage these registries",
114 strings.Join(claims, "; "), e.ConfigPath, ShortName)
115}
117// Register points Docker at the glab credential helper for each of domains,
118// by writing credHelpers in dir's config.json. Callers resolve dir via
119// ConfigDir unless they have a reason to use a different directory.
120//
121// Every domain is checked before anything is written, and a domain already
122// claimed by a different helper fails the whole call with a *ConflictError.
123// Docker resolves credHelpers ahead of every other credential source and
124// credHelpers holds one helper per domain, so overwriting an entry silently
125// takes a registry away from whichever tool owns it — ecr-login, gcloud, a
126// per-registry osxkeychain — and Save discards the old value irrecoverably.
127func Register(dir string, domains ...string) ([]Registration, error) {
128 cfg, err := dockerconfig.Load(dir)
129 if err != nil {
130 return nil, fmt.Errorf("reading current docker config: %w", err)
131 }
133 conflicts := make(map[string]string)
134 for _, domain := range domains {
135 if existing, ok := cfg.CredentialHelpers[domain]; ok && existing != ShortName {
136 conflicts[domain] = existing
137 }
138 }
139 if len(conflicts) > 0 {
140 return nil, &ConflictError{Helpers: conflicts, ConfigPath: filepath.Join(dir, "config.json")}
141 }
143 // WARNING: This must be added to avoid accessing an uninitialized
144 // map. This happens when someone hasn't used a cred helper already
145 // and isn't handled by the Docker configuration module.
146 // See https://gitlab.com/gitlab-org/cli/-/issues/7921
147 if cfg.CredentialHelpers == nil {
148 cfg.CredentialHelpers = make(map[string]string)
149 }
151 registrations := make([]Registration, 0, len(domains))
152 for _, domain := range domains {
153 // Check whether AuthConfigs holds the key, not what it holds: under a
154 // configured credsStore, `docker login` leaves an empty marker entry
155 // here and stores the actual secret in the OS keychain, while
156 // `docker logout` removes the key outright.
157 _, shadowed := cfg.AuthConfigs[domain]
159 cfg.CredentialHelpers[domain] = ShortName
160 registrations = append(registrations, Registration{Domain: domain, ShadowedLogin: shadowed})
161 }
163 if err := cfg.Save(); err != nil {
164 return nil, fmt.Errorf("registering %s as a docker credential helper: %w", ShortName, err)
165 }
167 return registrations, nil
168}
170// ConfigDir resolves the directory Docker reads config.json from, mirroring
171// dockerconfig.Dir(): $DOCKER_CONFIG when set, otherwise ~/.docker. Honoring
172// $DOCKER_CONFIG matters because writing to the wrong directory fails
173// silently: the command reports success, but Docker reads a config.json with
174// no credHelpers entry for the registry.
175//
176// This is not dockerconfig.Dir() itself, because that function memoizes its
177// result in a process-wide sync.Once the first time it's called: the first
178// caller in the process would lock in a directory that later callers (for
179// example, tests overriding $HOME) can't change.
180func ConfigDir() (string, error) {
181 if dir := os.Getenv("DOCKER_CONFIG"); dir != "" {
182 return dir, nil
183 }
185 home, err := os.UserHomeDir()
186 if err != nil {
187 return "", fmt.Errorf("resolving home directory: %w", err)
188 }
190 return filepath.Join(home, ".docker"), nil
191}
Diagnostics6 git calls · 28 ms
CallStatusSizeTime028 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 KiB · hit3 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=HIT 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 · 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
fetchtree:0200245 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=245 git.response.cache=HIT git.response.duration_ms=2 git.fetch.filter=tree:0 git.fetch.wants=aba319365668a8024052e17001ff1ccb32f32ad1 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=245 git.pkt.payload.max=218 git.sideband.band1.bytes=218 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0 git.pack.objects=1 git.pack.bytes=218 git.pack.trailer=a79e8c6a1fa5857567b424874e4f19628bc00ab3Open pack map
fetch2002.9 KiB · hit20 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=20 git.response.bytes=3019 git.response.cache=HIT git.response.duration_ms=20 git.fetch.wants=be14718e70c99c3e19c4058c96e0dac19f599fbc 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=3019 git.pkt.payload.max=2992 git.sideband.band1.bytes=2992 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
- a5e2cb800d4a7929
- Request
- 75e34c00…
- 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