GitLabgitlab-org
cli
main
1//go:build !integration
3package artifactregistry
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/tokenexchangetest"
18)
20// wireRequest mirrors the JSON body artifactregistry is expected to send to
21// POST /api/v4/token_exchange.
22type wireRequest = tokenexchangetest.WireRequest
24// newTestServer starts a fake token_exchange endpoint and returns it along
25// with a counter of how many requests it received, so tests can assert that
26// invalid input never reaches the network.
27func newTestServer(t *testing.T, handler http.HandlerFunc) (*httptest.Server, *atomic.Int32) {
28 t.Helper()
29 return tokenexchangetest.NewTestServer(t, handler)
30}
32func newTestClient(t *testing.T, baseURL string) *Client {
33 t.Helper()
34 return NewClient(tokenexchangetest.NewTestClient(t, baseURL))
35}
37// makeJWT mints a JWT carrying claims. artifactregistry never verifies token
38// signatures (it trusts the TLS connection to the GitLab host that issued
39// the token), so any signing key works.
40func makeJWT(t *testing.T, claims jwt.RegisteredClaims) string {
41 t.Helper()
42 return tokenexchangetest.MakeJWT(t, claims)
43}
45func TestExchangeToken_Success(t *testing.T) {
46 exp := time.Now().Add(15 * time.Minute).Truncate(time.Second)
47 wantToken := makeJWT(t, jwt.RegisteredClaims{
48 Issuer: "https://gitlab.example.com",
49 Subject: "gid://gitlab/User/1",
50 Audience: jwt.ClaimStrings{"gitlab-artifact-registry", "gitlab-iam-data-access"},
51 ExpiresAt: jwt.NewNumericDate(exp),
52 })
54 var gotBody wireRequest
55 srv, count := newTestServer(t, func(w http.ResponseWriter, r *http.Request) {
56 assert.Equal(t, http.MethodPost, r.Method)
57 assert.Equal(t, "/api/v4/token_exchange", r.URL.Path)
58 assert.NoError(t, json.NewDecoder(r.Body).Decode(&gotBody))
60 w.Header().Set("Content-Type", "application/json")
61 w.WriteHeader(http.StatusOK)
62 _, _ = w.Write([]byte(`{"token":"` + wantToken + `"}`))
63 })
65 client := newTestClient(t, srv.URL)
67 result, err := client.ExchangeToken(t.Context(), 15*time.Minute)
68 require.NoError(t, err)
69 require.NotNil(t, result)
71 assert.EqualValues(t, 1, count.Load())
72 assert.Equal(t, wireRequest{Audience: "gitlab-artifact-registry", ExpiresIn: 900}, gotBody)
73 assert.Equal(t, wantToken, result.Token)
74 assert.WithinDuration(t, exp, result.ExpiresAt, 0)
76 // Issuer, Subject, and Audience come off the same decode as ExpiresAt, so
77 // callers never re-parse the token.
78 assert.Equal(t, "https://gitlab.example.com", result.Issuer)
79 assert.Equal(t, "gid://gitlab/User/1", result.Subject)
80 assert.Equal(t, "gitlab-artifact-registry,gitlab-iam-data-access", result.Audience)
81}
83func TestExchangeDefaultToken_OmitsExpiresIn(t *testing.T) {
84 exp := time.Now().Add(5 * time.Minute).Truncate(time.Second)
85 wantToken := makeJWT(t, jwt.RegisteredClaims{
86 Issuer: "https://gitlab.example.com",
87 Subject: "gid://gitlab/User/1",
88 Audience: jwt.ClaimStrings{"gitlab-artifact-registry"},
89 ExpiresAt: jwt.NewNumericDate(exp),
90 })
92 var gotBody map[string]any
93 srv, count := newTestServer(t, func(w http.ResponseWriter, r *http.Request) {
94 assert.NoError(t, json.NewDecoder(r.Body).Decode(&gotBody))
96 w.Header().Set("Content-Type", "application/json")
97 w.WriteHeader(http.StatusCreated)
98 _, _ = w.Write([]byte(`{"token":"` + wantToken + `"}`))
99 })
101 client := newTestClient(t, srv.URL)
103 result, err := client.ExchangeDefaultToken(t.Context())
104 require.NoError(t, err)
105 require.NotNil(t, result)
107 assert.EqualValues(t, 1, count.Load())
108 _, hasExpiresIn := gotBody["expires_in"]
109 assert.False(t, hasExpiresIn, "ExchangeDefaultToken must omit expires_in so the server applies its own default")
110 assert.WithinDuration(t, exp, result.ExpiresAt, 0)
111}
113func TestExchangeToken_DurationOutOfRange(t *testing.T) {
114 tests := []struct {
115 name string
116 duration time.Duration
117 }{
118 {
119 name: "below MinDuration",
120 duration: 999 * time.Millisecond,
121 },
122 {
123 name: "above MaxDuration",
124 duration: 13 * time.Hour,
125 },
126 }
128 for _, tc := range tests {
129 t.Run(tc.name, func(t *testing.T) {
130 srv, count := newTestServer(t, func(w http.ResponseWriter, r *http.Request) {
131 t.Errorf("unexpected request to fake server: %s %s", r.Method, r.URL.Path)
132 w.WriteHeader(http.StatusInternalServerError)
133 })
135 client := newTestClient(t, srv.URL)
137 result, err := client.ExchangeToken(t.Context(), tc.duration)
138 require.Error(t, err)
139 assert.Nil(t, result)
140 assert.EqualValues(t, 0, count.Load(), "client must reject an invalid duration before making an HTTP call")
141 })
142 }
143}
145func TestValidateDuration(t *testing.T) {
146 tests := []struct {
147 name string
148 d time.Duration
149 wantErr bool
150 }{
151 {name: "exactly MinDuration is valid", d: MinDuration, wantErr: false},
152 {name: "exactly MaxDuration is valid", d: MaxDuration, wantErr: false},
153 {name: "one nanosecond below MinDuration is invalid", d: MinDuration - time.Nanosecond, wantErr: true},
154 {name: "one nanosecond above MaxDuration is invalid", d: MaxDuration + time.Nanosecond, wantErr: true},
155 {name: "zero duration is invalid", d: 0, wantErr: true},
156 {name: "negative duration is invalid", d: -1 * time.Hour, wantErr: true},
157 {name: "well above MaxDuration is invalid", d: 13 * time.Hour, wantErr: true},
158 {name: "within range is valid", d: time.Hour, wantErr: false},
159 }
161 for _, tc := range tests {
162 t.Run(tc.name, func(t *testing.T) {
163 err := ValidateDuration(tc.d)
164 if tc.wantErr {
165 require.Error(t, err)
166 // The error names the bounds, so a CLI error message needs no
167 // extra context.
168 assert.Contains(t, err.Error(), MinDuration.String())
169 assert.Contains(t, err.Error(), MaxDuration.String())
170 } else {
171 require.NoError(t, err)
172 }
173 })
174 }
175}
Diagnostics7 git calls · 381 ms
CallStatusSizeTime0381 ms
discover200185 B5 ms
git.upload-pack discover http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=ls-refs git.upstream.dur_ms=5 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 KiB171 ms
git.upload-pack ls-refs http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=ls-refs git.upstream.dur_ms=171 git.response.bytes=59849 git.response.cache=EXPIRED git.response.duration_ms=171 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 · hit5 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=5 git.response.bytes=4273 git.response.cache=HIT git.response.duration_ms=5 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.1 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=1165 git.response.cache=HIT git.response.duration_ms=2 git.fetch.filter=tree:0 git.fetch.wants=71c8407e0ff0e0af10f6a041ae330f754b68e7eb 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=1165 git.pkt.payload.max=1138 git.sideband.band1.bytes=1138 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0 git.pack.objects=1 git.pack.bytes=1138 git.pack.trailer=61886367c69619d8db2b2cf2d7d24dca2016141cOpen pack map
fetchtree:0200148 B · 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=148 git.response.cache=HIT git.response.duration_ms=4 git.fetch.filter=tree:0 git.fetch.wants=f193dbf7c81afce45df7f6e0e0227e5abc78bf3a 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=148 git.pkt.payload.max=121 git.sideband.band1.bytes=121 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0 git.pack.objects=1 git.pack.bytes=121 git.pack.trailer=2125fef90ae9a520d4b5d8ceee3c23653a798ba8Open pack map
fetch2001.9 KiB199 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=199 git.response.bytes=1953 git.response.cache=MISS git.response.duration_ms=199 git.fetch.wants=f4e1479caffb5c47987d96c38e48720283206650 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=1953 git.pkt.payload.max=1926 git.sideband.band1.bytes=1926 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
- a5e1727bd9806102
- Request
- b7bc8fb6…
- 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