GitLabgitlab-org
cli
main
1//go:build !integration
3package status
5import (
6 "encoding/json"
7 "net/http"
8 "net/http/httptest"
9 "sync/atomic"
10 "testing"
11 "time"
13 "github.com/golang-jwt/jwt/v5"
14 "github.com/stretchr/testify/assert"
15 "github.com/stretchr/testify/require"
17 "gitlab.com/gitlab-org/cli/internal/testing/cmdtest"
18 "gitlab.com/gitlab-org/cli/internal/testing/tokenexchangetest"
19)
21// wireRequest mirrors the JSON body `glab artifact-registry status` is expected to send to
22// POST /api/v4/token_exchange, via artifactregistry.
23type wireRequest = tokenexchangetest.WireRequest
25// newTestServer starts a fake token_exchange endpoint and returns it along
26// with a counter of how many requests it received.
27func newTestServer(t *testing.T, handler http.HandlerFunc) (*httptest.Server, *atomic.Int32) {
28 t.Helper()
29 return tokenexchangetest.NewTestServer(t, handler)
30}
32// newTestExec wires NewCmd to an api.Client pointed at srv, mirroring how
33// f.ApiClient(hostname).Lab() resolves in production.
34func newTestExec(t *testing.T, srv *httptest.Server) cmdtest.CmdExecFunc {
35 t.Helper()
36 return tokenexchangetest.NewTestExec(t, srv, NewCmd)
37}
39// makeJWT mints a JWT carrying claims. The command never verifies token
40// signatures, so any signing key works here.
41func makeJWT(t *testing.T, claims jwt.RegisteredClaims) string {
42 t.Helper()
43 return tokenexchangetest.MakeJWT(t, claims)
44}
46func TestStatus_Success(t *testing.T) {
47 exp := time.Now().Add(time.Hour).Truncate(time.Second)
48 wantToken := makeJWT(t, jwt.RegisteredClaims{
49 Issuer: "https://gitlab.example.com",
50 Subject: "gid://gitlab/User/42",
51 Audience: jwt.ClaimStrings{"gitlab-artifact-registry"},
52 ExpiresAt: jwt.NewNumericDate(exp),
53 })
55 var gotBody wireRequest
56 srv, count := newTestServer(t, func(w http.ResponseWriter, r *http.Request) {
57 assert.Equal(t, http.MethodPost, r.Method)
58 assert.Equal(t, "/api/v4/token_exchange", r.URL.Path)
59 assert.NoError(t, json.NewDecoder(r.Body).Decode(&gotBody))
61 w.Header().Set("Content-Type", "application/json")
62 w.WriteHeader(http.StatusCreated)
63 _, _ = w.Write([]byte(`{"token":"` + wantToken + `"}`))
64 })
65 exec := newTestExec(t, srv)
67 out, err := exec("")
68 require.NoError(t, err)
70 assert.EqualValues(t, 1, count.Load())
71 // status reads the token for its claims and discards it, so it must not
72 // send expires_in: the server's own default lifetime applies.
73 assert.Equal(t, wireRequest{Audience: "gitlab-artifact-registry"}, gotBody)
75 output := out.OutBuf.String()
76 assert.Contains(t, output, "https://gitlab.example.com")
77 assert.Contains(t, output, "gid://gitlab/User/42")
78 assert.Contains(t, output, "gitlab-artifact-registry")
79 assert.Contains(t, output, exp.Format(time.RFC3339))
80 assert.NotContains(t, output, wantToken, "the raw bearer token must never reach stdout")
81}
83func TestStatus_JSONOutput(t *testing.T) {
84 exp := time.Now().Add(time.Hour).Truncate(time.Second)
85 wantToken := makeJWT(t, jwt.RegisteredClaims{
86 Issuer: "https://gitlab.example.com",
87 Subject: "gid://gitlab/User/42",
88 Audience: jwt.ClaimStrings{"gitlab-artifact-registry"},
89 ExpiresAt: jwt.NewNumericDate(exp),
90 })
92 srv, _ := newTestServer(t, func(w http.ResponseWriter, r *http.Request) {
93 w.Header().Set("Content-Type", "application/json")
94 w.WriteHeader(http.StatusCreated)
95 _, _ = w.Write([]byte(`{"token":"` + wantToken + `"}`))
96 })
97 exec := newTestExec(t, srv)
99 out, err := exec("--output json")
100 require.NoError(t, err)
102 var result struct {
103 Issuer string `json:"issuer"`
104 Subject string `json:"subject"`
105 Audience string `json:"audience"`
106 ExpiresAt time.Time `json:"expires_at"`
107 }
108 require.NoError(t, json.Unmarshal(out.OutBuf.Bytes(), &result))
109 assert.Equal(t, "https://gitlab.example.com", result.Issuer)
110 assert.Equal(t, "gid://gitlab/User/42", result.Subject)
111 assert.Equal(t, "gitlab-artifact-registry", result.Audience)
112 assert.WithinDuration(t, exp, result.ExpiresAt, 0)
113 assert.NotContains(t, out.OutBuf.String(), wantToken, "the raw bearer token must never reach stdout")
114}
116func TestStatus_ValidHostnameReachesTheExchange(t *testing.T) {
117 // The counterpart to TestStatus_InvalidHostname: a stricter validator must
118 // not start rejecting legitimate hosts unnoticed.
119 tests := []struct {
120 name string
121 args string
122 }{
123 {name: "bare hostname", args: "--hostname gitlab.example.com"},
124 // Empty means "use the configured instance", so it is a valid value even
125 // when passed explicitly.
126 {name: "explicitly empty", args: "--hostname ''"},
127 {name: "not passed at all", args: ""},
128 }
130 for _, tc := range tests {
131 t.Run(tc.name, func(t *testing.T) {
132 wantToken := makeJWT(t, jwt.RegisteredClaims{
133 Issuer: "https://gitlab.example.com",
134 Subject: "gid://gitlab/User/42",
135 ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Hour)),
136 })
138 srv, count := newTestServer(t, func(w http.ResponseWriter, r *http.Request) {
139 w.Header().Set("Content-Type", "application/json")
140 w.WriteHeader(http.StatusOK)
141 _, _ = w.Write([]byte(`{"token":"` + wantToken + `"}`))
142 })
143 exec := newTestExec(t, srv)
145 _, err := exec(tc.args)
146 require.NoError(t, err)
147 assert.EqualValues(t, 1, count.Load())
148 })
149 }
150}
152func TestStatus_InvalidHostname(t *testing.T) {
153 tests := []struct {
154 name string
155 hostname string
156 }{
157 {name: "URL rather than hostname", hostname: "https://gitlab.example.com"},
158 {name: "hostname with a port", hostname: "gitlab.example.com:8080"},
159 {name: "hostname with a path", hostname: "gitlab.example.com/foo"},
160 }
162 for _, tc := range tests {
163 t.Run(tc.name, func(t *testing.T) {
164 srv, count := newTestServer(t, func(w http.ResponseWriter, r *http.Request) {
165 t.Errorf("unexpected request to fake server: %s %s", r.Method, r.URL.Path)
166 w.WriteHeader(http.StatusInternalServerError)
167 })
168 exec := newTestExec(t, srv)
170 _, err := exec("--hostname " + tc.hostname)
171 require.Error(t, err)
172 assert.Contains(t, err.Error(), "error parsing --hostname")
173 // The credential must not leave the machine before the host it would
174 // be sent to has been checked.
175 assert.EqualValues(t, 0, count.Load(), "an invalid --hostname must be rejected before any HTTP call")
176 })
177 }
178}
180func TestStatus_ServerError(t *testing.T) {
181 // 400 is the real non-2xx surface for a bad request (the other
182 // documented codes are 401, 404, and 429).
183 srv, _ := newTestServer(t, func(w http.ResponseWriter, r *http.Request) {
184 w.Header().Set("Content-Type", "application/json")
185 w.WriteHeader(http.StatusBadRequest)
186 _, _ = w.Write([]byte(`{"message":"audience is not a valid value"}`))
187 })
188 exec := newTestExec(t, srv)
190 _, err := exec("")
191 require.Error(t, err)
192 assert.Contains(t, err.Error(), "audience is not a valid value")
193}
195func TestStatus_TokenExchangeNotAvailable(t *testing.T) {
196 // An instance that does not serve token exchange responds 404 rather
197 // than a feature-specific error: a Community Edition instance, a
198 // release before 19.1, or 19.1 to 19.3 with the
199 // gate_token_exchange_endpoint feature flag disabled.
200 srv, _ := newTestServer(t, func(w http.ResponseWriter, r *http.Request) {
201 w.WriteHeader(http.StatusNotFound)
202 })
203 exec := newTestExec(t, srv)
205 _, err := exec("")
206 require.Error(t, err)
207 assert.Contains(t, err.Error(), "token exchange is not available on this instance (requires GitLab EE 19.4 or later)")
208}
210func TestStatus_HelpNamesNoRemovedFeatureFlag(t *testing.T) {
211 ios, _, _, _ := cmdtest.TestIOStreams()
212 cmd := NewCmd(cmdtest.NewTestFactory(ios))
214 assert.Contains(t, cmd.Long, "GitLab 19.4 or later")
215 assert.NotContains(t, cmd.Long, "gate_token_exchange_endpoint")
216}
Diagnostics8 git calls · 236 ms
CallStatusSizeTime0236 ms
discover200185 B3 ms
git.upload-pack discover http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=3 git.response.bytes=185 git.server.agent=git/2.56.g1891de4-Linux git.server.object_format=sha1 git.server.caps=agent ls-refs fetch server-option object-format git.server.fetch=shallow wait-for-done filter git.protocol.version=2 git.pkt.frames=9 git.pkt.data=7 git.pkt.flush=2 git.pkt.delim=0 git.pkt.bytes=185 git.pkt.payload.max=35
ls-refs20058 KiB3 ms
git.upload-pack ls-refs http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=ls-refs git.upstream.dur_ms=3 git.response.bytes=59849 git.response.cache=UPDATING git.response.duration_ms=3 git.protocol.version=2 git.pkt.frames=731 git.pkt.data=730 git.pkt.flush=1 git.pkt.delim=0 git.pkt.bytes=59849 git.pkt.payload.max=143 git.ls_refs.count=730 git.ls_refs.head=refs/heads/main
fetchcombine:blob:none+tree:2 · deepen 12004.2 KiB · hit2 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=2 git.response.bytes=4273 git.response.cache=HIT git.response.duration_ms=2 git.fetch.filter=combine:blob:none+tree:2 git.fetch.wants=0dd7574dce9e385c5c30540e6c15657adc6bdce9 git.fetch.haves.count=0 git.fetch.deepen=1 git.fetch.thin_pack=false git.fetch.ofs_delta=true git.protocol.version=2 git.pkt.frames=7 git.pkt.data=5 git.pkt.flush=1 git.pkt.delim=1 git.pkt.bytes=4273 git.pkt.payload.max=4173 git.sideband.band1.bytes=4173 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0 git.pack.objects=11 git.pack.bytes=4173 git.fetch.wide.objects=11 git.fetch.wide.extra_bytes=3930 git.fetch.wide.blobs=0
fetchtree:0 · deepen 1020032 KiB · hit3 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=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=44Open pack map
fetchtree:02001.8 KiB · hit2 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=2 git.response.bytes=1857 git.response.cache=HIT git.response.duration_ms=2 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=fb03183b7909876778f740d196d7516811003517Open 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=bd426fb1ae09d9fdcf755902c6903cd2eea819b2Open pack map
fetchtree:0200138 B · hit2 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=225 git.response.bytes=138 git.response.cache=HIT git.response.duration_ms=2 git.fetch.filter=tree:0 git.fetch.wants=b0826c05487ddcb0a998bd4b65170b76913da918 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=138 git.pkt.payload.max=111 git.sideband.band1.bytes=111 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0 git.pack.objects=1 git.pack.bytes=111 git.pack.trailer=a9c5cadae9ab881146a570ac590a9ff8a03cfd03Open pack map
fetch2002.4 KiB225 ms
git.upload-pack fetch http.response.status_code=200 git.response.bytes=2444 git.response.cache=MISS git.response.duration_ms=225 git.fetch.wants=1a0d99f3886b44f856afb32b0985410cafa24da6 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=2444 git.pkt.payload.max=2417 git.sideband.band1.bytes=2417 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
- a5e2e7800cb6ecfa
- Request
- cf0cd7f3…
- 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