GitLabgitlab-org

cli

main
ply8 git calls362 ms100 KiB6 cachedprotocol v2
267 lines8.9 KiBRaw
1//go:build !integration
3package gettoken
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/api/artifactregistry"
18 "gitlab.com/gitlab-org/cli/internal/testing/cmdtest"
19 "gitlab.com/gitlab-org/cli/internal/testing/tokenexchangetest"
22// wireRequest mirrors the JSON body `glab artifact-registry get-token` is expected to send
23// to POST /api/v4/token_exchange, via artifactregistry.
24type wireRequest = tokenexchangetest.WireRequest
26// newTestServer starts a fake token_exchange endpoint and returns it along
27// with a counter of how many requests it received, so tests can assert that
28// invalid input (e.g. an out-of-range --duration) never reaches the network.
29func newTestServer(t *testing.T, handler http.HandlerFunc) (*httptest.Server, *atomic.Int32) {
30 t.Helper()
31 return tokenexchangetest.NewTestServer(t, handler)
34// newTestExec wires NewCmd to an api.Client pointed at srv, mirroring how
35// f.ApiClient(hostname).Lab() resolves in production.
36func newTestExec(t *testing.T, srv *httptest.Server) cmdtest.CmdExecFunc {
37 t.Helper()
38 return tokenexchangetest.NewTestExec(t, srv, NewCmd)
41// makeJWT mints a JWT carrying claims. The command never verifies token
42// signatures, so any signing key works here.
43func makeJWT(t *testing.T, claims jwt.RegisteredClaims) string {
44 t.Helper()
45 return tokenexchangetest.MakeJWT(t, claims)
48// tokenServer starts a fake token_exchange endpoint that always returns
49// wantToken, decoding each request body into gotBody.
50func tokenServer(t *testing.T, wantToken string, gotBody *wireRequest) (*httptest.Server, *atomic.Int32) {
51 t.Helper()
52 return tokenexchangetest.NewTokenExchangeServer(t, wantToken, gotBody)
55func TestGetToken_DefaultDuration(t *testing.T) {
56 exp := time.Now().Add(artifactregistry.DefaultDuration).Truncate(time.Second)
57 wantToken := makeJWT(t, jwt.RegisteredClaims{
58 Issuer: "https://gitlab.example.com",
59 Subject: "gid://gitlab/User/1",
60 ExpiresAt: jwt.NewNumericDate(exp),
61 })
63 var gotBody wireRequest
64 srv, count := tokenServer(t, wantToken, &gotBody)
65 exec := newTestExec(t, srv)
67 out, err := exec("")
68 require.NoError(t, err)
70 assert.EqualValues(t, 1, count.Load())
71 assert.Equal(t, wireRequest{Audience: "gitlab-artifact-registry", ExpiresIn: int(artifactregistry.DefaultDuration.Seconds())}, gotBody)
72 assert.Equal(t, wantToken+"\n", out.OutBuf.String())
73 assert.Empty(t, out.ErrBuf.String())
76func TestGetToken_CustomDuration(t *testing.T) {
77 exp := time.Now().Add(time.Hour).Truncate(time.Second)
78 wantToken := makeJWT(t, jwt.RegisteredClaims{
79 Issuer: "https://gitlab.example.com",
80 Subject: "gid://gitlab/User/1",
81 ExpiresAt: jwt.NewNumericDate(exp),
82 })
84 var gotBody wireRequest
85 srv, count := tokenServer(t, wantToken, &gotBody)
86 exec := newTestExec(t, srv)
88 out, err := exec("--duration 1h")
89 require.NoError(t, err)
91 assert.EqualValues(t, 1, count.Load())
92 assert.Equal(t, 3600, gotBody.ExpiresIn)
93 assert.Equal(t, wantToken+"\n", out.OutBuf.String())
96func TestGetToken_DurationOutOfRange(t *testing.T) {
97 tests := []struct {
98 name string
99 args string
100 }{
101 {name: "below the 1-second floor", args: "--duration 500ms"},
102 {name: "negative duration", args: "--duration=-1s"},
103 {name: "above the 12-hour ceiling", args: "--duration 13h"},
104 }
106 for _, tc := range tests {
107 t.Run(tc.name, func(t *testing.T) {
108 srv, count := newTestServer(t, func(w http.ResponseWriter, r *http.Request) {
109 t.Errorf("unexpected request to fake server: %s %s", r.Method, r.URL.Path)
110 w.WriteHeader(http.StatusInternalServerError)
111 })
112 exec := newTestExec(t, srv)
114 out, err := exec(tc.args)
115 require.Error(t, err)
116 assert.Contains(t, err.Error(), "error parsing --duration")
117 assert.EqualValues(t, 0, count.Load(), "an out-of-range duration must be rejected before making an HTTP call")
118 assert.Empty(t, out.OutBuf.String())
119 })
120 }
123func TestGetToken_JSONOutput(t *testing.T) {
124 exp := time.Now().Add(artifactregistry.DefaultDuration).Truncate(time.Second)
125 wantToken := makeJWT(t, jwt.RegisteredClaims{
126 Issuer: "https://gitlab.example.com",
127 Subject: "gid://gitlab/User/1",
128 ExpiresAt: jwt.NewNumericDate(exp),
129 })
131 var gotBody wireRequest
132 srv, _ := tokenServer(t, wantToken, &gotBody)
133 exec := newTestExec(t, srv)
135 out, err := exec("--output json")
136 require.NoError(t, err)
138 var result struct {
139 Token string `json:"token"`
140 ExpiresAt time.Time `json:"expires_at"`
141 }
142 require.NoError(t, json.Unmarshal(out.OutBuf.Bytes(), &result))
143 assert.Equal(t, wantToken, result.Token)
144 assert.WithinDuration(t, exp, result.ExpiresAt, 0)
147func TestGetToken_ServerError(t *testing.T) {
148 // 400 is the real non-2xx surface for a bad request (the other
149 // documented codes are 401, 404, and 429).
150 srv, _ := newTestServer(t, func(w http.ResponseWriter, r *http.Request) {
151 w.Header().Set("Content-Type", "application/json")
152 w.WriteHeader(http.StatusBadRequest)
153 _, _ = w.Write([]byte(`{"message":"audience is not a valid value"}`))
154 })
155 exec := newTestExec(t, srv)
157 out, err := exec("")
158 require.Error(t, err)
159 assert.Contains(t, err.Error(), "audience is not a valid value")
160 assert.Empty(t, out.OutBuf.String())
163func TestGetToken_TokenExchangeNotAvailable(t *testing.T) {
164 // An instance that does not serve token exchange responds 404 rather
165 // than a feature-specific error: a Community Edition instance, a
166 // release before 19.1, or 19.1 to 19.3 with the
167 // gate_token_exchange_endpoint feature flag disabled.
168 srv, _ := newTestServer(t, func(w http.ResponseWriter, r *http.Request) {
169 w.WriteHeader(http.StatusNotFound)
170 })
171 exec := newTestExec(t, srv)
173 out, err := exec("")
174 require.Error(t, err)
175 assert.Contains(t, err.Error(), "token exchange is not available on this instance (requires GitLab EE 19.4 or later)")
176 assert.Empty(t, out.OutBuf.String())
179func TestGetToken_HelpNamesNoRemovedFeatureFlag(t *testing.T) {
180 ios, _, _, _ := cmdtest.TestIOStreams()
181 cmd := NewCmd(cmdtest.NewTestFactory(ios))
183 assert.Contains(t, cmd.Long, "GitLab 19.4 or later")
184 assert.NotContains(t, cmd.Long, "gate_token_exchange_endpoint")
187func TestGetToken_InvalidHostname(t *testing.T) {
188 tests := []struct {
189 name string
190 hostname string
191 }{
192 {name: "URL rather than hostname", hostname: "https://gitlab.example.com"},
193 {name: "hostname with a port", hostname: "gitlab.example.com:8080"},
194 {name: "hostname with a path", hostname: "gitlab.example.com/foo"},
195 }
197 for _, tc := range tests {
198 t.Run(tc.name, func(t *testing.T) {
199 srv, count := newTestServer(t, func(w http.ResponseWriter, r *http.Request) {
200 t.Errorf("unexpected request to fake server: %s %s", r.Method, r.URL.Path)
201 w.WriteHeader(http.StatusInternalServerError)
202 })
203 exec := newTestExec(t, srv)
205 out, err := exec("--hostname " + tc.hostname)
206 require.Error(t, err)
207 assert.Contains(t, err.Error(), "error parsing --hostname")
208 // The credential must not leave the machine before the host it would
209 // be sent to has been checked.
210 assert.EqualValues(t, 0, count.Load(), "an invalid --hostname must be rejected before any HTTP call")
211 assert.Empty(t, out.OutBuf.String())
212 })
213 }
216func TestGetToken_ValidHostnameReachesTheExchange(t *testing.T) {
217 tests := []struct {
218 name string
219 args string
220 }{
221 {name: "bare hostname", args: "--hostname gitlab.example.com"},
222 // Empty means "use the configured instance", so it is a valid value even
223 // when passed explicitly.
224 {name: "explicitly empty", args: "--hostname ''"},
225 {name: "not passed at all", args: ""},
226 }
228 for _, tc := range tests {
229 t.Run(tc.name, func(t *testing.T) {
230 wantToken := makeJWT(t, jwt.RegisteredClaims{
231 Issuer: "https://gitlab.example.com",
232 Subject: "gid://gitlab/User/1",
233 ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Hour)),
234 })
236 srv, count := newTestServer(t, func(w http.ResponseWriter, r *http.Request) {
237 w.Header().Set("Content-Type", "application/json")
238 w.WriteHeader(http.StatusOK)
239 _, _ = w.Write([]byte(`{"token":"` + wantToken + `"}`))
240 })
241 exec := newTestExec(t, srv)
243 _, err := exec(tc.args)
244 require.NoError(t, err)
245 assert.EqualValues(t, 1, count.Load())
246 })
247 }
250// TestGetToken_StdoutCarriesOnlyTheToken asserts the negative half of the
251// capture contract: a failed exchange must not leave a partial or empty line
252// on stdout for `TOKEN=$(glab artifact-registry get-token)` to capture. The
253// happy path is covered by TestGetToken_DefaultDuration.
254func TestGetToken_StdoutCarriesOnlyTheToken(t *testing.T) {
255 // 400, not 500: a 5xx triggers the API client's retry/backoff, which
256 // would make this test slow for no benefit — any failed exchange, whatever
257 // the status, must leave stdout empty.
258 srv, _ := newTestServer(t, func(w http.ResponseWriter, r *http.Request) {
259 w.WriteHeader(http.StatusBadRequest)
260 })
261 exec := newTestExec(t, srv)
263 out, err := exec("")
264 require.Error(t, err)
266 assert.Empty(t, out.OutBuf.String())
Diagnostics8 git calls · 362 ms
CallStatusSizeTime0362 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=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 KiB · hit2 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=HIT
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 · 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=32926
git.response.cache=HIT
git.response.duration_ms=2
git.fetch.filter=tree:0
git.fetch.wants=0dd7574dce9e385c5c30540e6c15657adc6bdce9
git.fetch.haves.count=0
git.fetch.deepen=10
git.fetch.thin_pack=false
git.fetch.ofs_delta=true
git.protocol.version=2
git.pkt.frames=22
git.pkt.data=20
git.pkt.flush=1
git.pkt.delim=1
git.pkt.bytes=32926
git.pkt.payload.max=32046
git.sideband.band1.bytes=32046
git.sideband.band2.bytes=0
git.sideband.band3.bytes=0
git.pack.objects=80
git.pack.bytes=32046
git.pack.ofs_delta=36
git.pack.ref_delta=0
git.pack.chain.max=2
git.pack.trailer=cb0bad5d7ffc514895d8b21c4dd470327f90bc91
git.pack.full=44
Open pack map
fetchcombine:blob:none+tree:2 · deepen 12004.2 KiB · hit2 ms
git.upload-pack fetch
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=fetch
git.upstream.dur_ms=3
git.response.bytes=4273
git.response.cache=HIT
git.response.duration_ms=2
git.fetch.filter=combine:blob:none+tree:2
git.fetch.wants=0dd7574dce9e385c5c30540e6c15657adc6bdce9
git.fetch.haves.count=0
git.fetch.deepen=1
git.fetch.thin_pack=false
git.fetch.ofs_delta=true
git.protocol.version=2
git.pkt.frames=7
git.pkt.data=5
git.pkt.flush=1
git.pkt.delim=1
git.pkt.bytes=4273
git.pkt.payload.max=4173
git.sideband.band1.bytes=4173
git.sideband.band2.bytes=0
git.sideband.band3.bytes=0
git.pack.objects=11
git.pack.bytes=4173
git.fetch.wide.objects=11
git.fetch.wide.extra_bytes=3930
git.fetch.wide.blobs=0
fetchtree:02001.8 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=1857
git.response.cache=HIT
git.response.duration_ms=3
git.fetch.filter=tree:0
git.fetch.wants=dce174ff8c632a19d17eea99c8a9b7c37fb2b592
git.fetch.haves.count=0
git.fetch.deepen=0
git.fetch.thin_pack=false
git.fetch.ofs_delta=true
git.protocol.version=2
git.pkt.frames=4
git.pkt.data=3
git.pkt.flush=1
git.pkt.delim=0
git.pkt.bytes=1857
git.pkt.payload.max=1830
git.sideband.band1.bytes=1830
git.sideband.band2.bytes=0
git.sideband.band3.bytes=0
git.pack.objects=1
git.pack.bytes=1830
git.pack.trailer=fb03183b7909876778f740d196d7516811003517
Open pack map
fetchtree:0200242 B · 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=242
git.response.cache=HIT
git.response.duration_ms=3
git.fetch.filter=tree:0
git.fetch.wants=5da85e254ab77f5f6e7e1419be57d524a9f8208e
git.fetch.haves.count=0
git.fetch.deepen=0
git.fetch.thin_pack=false
git.fetch.ofs_delta=true
git.protocol.version=2
git.pkt.frames=4
git.pkt.data=3
git.pkt.flush=1
git.pkt.delim=0
git.pkt.bytes=242
git.pkt.payload.max=215
git.sideband.band1.bytes=215
git.sideband.band2.bytes=0
git.sideband.band3.bytes=0
git.pack.objects=1
git.pack.bytes=215
git.pack.trailer=bd426fb1ae09d9fdcf755902c6903cd2eea819b2
Open pack map
fetchtree:0200140 B · hit3 ms
git.upload-pack fetch
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=fetch
git.upstream.dur_ms=348
git.response.bytes=140
git.response.cache=HIT
git.response.duration_ms=3
git.fetch.filter=tree:0
git.fetch.wants=eb7fc31ecec841eb8546c913f46e8a8530fe755b
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=140
git.pkt.payload.max=113
git.sideband.band1.bytes=113
git.sideband.band2.bytes=0
git.sideband.band3.bytes=0
git.pack.objects=1
git.pack.bytes=113
git.pack.trailer=12eb4bffd5426cf02b3756055be2d3b0d6b78a1a
Open pack map
fetch2002.7 KiB348 ms
git.upload-pack fetch
http.response.status_code=200
git.response.bytes=2727
git.response.cache=MISS
git.response.duration_ms=348
git.fetch.wants=ffd5759c927e1f3f429bbbf0da377c061cc64326
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=2727
git.pkt.payload.max=2700
git.sideband.band1.bytes=2700
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
a5e2d688a863689d
Request
ce14c12b…
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