GitLabgitlab-org
cli
main
1package api
3import (
4 "errors"
5 "fmt"
6 "net/http"
7 "testing"
8 "time"
10 "github.com/stretchr/testify/assert"
11 "github.com/stretchr/testify/require"
12 xoauth2 "golang.org/x/oauth2"
14 gitlab "gitlab.com/gitlab-org/api/client-go/v3"
15)
17type staticTokenSource struct {
18 token *xoauth2.Token
19}
21func (s staticTokenSource) Token() (*xoauth2.Token, error) {
22 return s.token, nil
23}
25// Credential is the single place that maps an auth source onto a credential
26// kind, so pin every source NewClientFromConfig can produce.
27func TestClient_Credential(t *testing.T) {
28 expiry := time.Now().Add(time.Hour).Truncate(time.Second)
30 tests := []struct {
31 name string
32 authSource gitlab.AuthSource
33 expected Credential
34 }{
35 {
36 name: "personal access token",
37 authSource: gitlab.AccessTokenAuthSource{Token: "a-pat"},
38 expected: Credential{Kind: CredentialPAT, Token: "a-pat"},
39 },
40 {
41 name: "job token",
42 authSource: gitlab.JobTokenAuthSource{Token: "a-job-token"},
43 expected: Credential{Kind: CredentialJobToken, Token: "a-job-token"},
44 },
45 {
46 // A refreshable session reports both the expiry and the refresh token,
47 // which the Git credential protocol passes on to Git.
48 name: "refreshable OAuth2 session",
49 authSource: gitlab.OAuthTokenSource{TokenSource: staticTokenSource{token: &xoauth2.Token{
50 AccessToken: "an-access-token",
51 RefreshToken: "a-refresh-token",
52 Expiry: expiry,
53 }}},
54 expected: Credential{
55 Kind: CredentialOAuth2,
56 Token: "an-access-token",
57 Expiry: expiry,
58 RefreshToken: "a-refresh-token",
59 },
60 },
61 {
62 // Reported as OAuth2 even though it cannot be renewed: the kind names
63 // the scheme the caller must use, not whether a refresh is possible.
64 name: "OAuth2 access token with no refresh token",
65 authSource: oauth2AccessTokenOnlyAuthSource{token: "an-access-token"},
66 expected: Credential{Kind: CredentialOAuth2, Token: "an-access-token"},
67 },
68 }
70 for _, tt := range tests {
71 t.Run(tt.name, func(t *testing.T) {
72 client := clientWithAuthSource(t, tt.authSource)
74 cred, err := client.Credential(t.Context())
75 require.NoError(t, err)
76 assert.Equal(t, tt.expected, cred)
77 })
78 }
79}
81// NewConfigTokenSource hands back an x/oauth2 reuseTokenSource, so exercise
82// that concrete type rather than only a hand-written TokenSource.
83func TestClient_Credential_reuseTokenSource(t *testing.T) {
84 tests := []struct {
85 name string
86 expiresIn time.Duration
87 expectedToken string
88 }{
89 {
90 name: "valid cached token is reused",
91 expiresIn: 30 * time.Minute,
92 expectedToken: "cached-token",
93 },
94 {
95 name: "expired cached token is renewed",
96 expiresIn: -time.Minute,
97 expectedToken: "fresh-token",
98 },
99 }
101 for _, tt := range tests {
102 t.Run(tt.name, func(t *testing.T) {
103 reusable := xoauth2.ReuseTokenSource(
104 &xoauth2.Token{AccessToken: "cached-token", Expiry: time.Now().Add(tt.expiresIn)},
105 staticTokenSource{token: &xoauth2.Token{
106 AccessToken: "fresh-token",
107 Expiry: time.Now().Add(time.Hour),
108 }},
109 )
110 client := clientWithAuthSource(t, gitlab.OAuthTokenSource{TokenSource: reusable})
112 cred, err := client.Credential(t.Context())
113 require.NoError(t, err)
114 assert.Equal(t, tt.expectedToken, cred.Token)
115 })
116 }
117}
119// CredentialKind must agree with Credential on every source, since a caller
120// that refuses on kind alone never reaches Credential to find out otherwise.
121func TestClient_CredentialKind_matchesCredential(t *testing.T) {
122 sources := []gitlab.AuthSource{
123 gitlab.AccessTokenAuthSource{Token: "a-pat"},
124 gitlab.JobTokenAuthSource{Token: "a-job-token"},
125 oauth2AccessTokenOnlyAuthSource{token: "an-access-token"},
126 gitlab.OAuthTokenSource{TokenSource: staticTokenSource{token: &xoauth2.Token{
127 AccessToken: "an-access-token",
128 Expiry: time.Now().Add(time.Hour),
129 }}},
130 }
132 for _, as := range sources {
133 t.Run(fmt.Sprintf("%T", as), func(t *testing.T) {
134 client := clientWithAuthSource(t, as)
136 kind, err := client.CredentialKind()
137 require.NoError(t, err)
139 cred, err := client.Credential(t.Context())
140 require.NoError(t, err)
141 assert.Equal(t, cred.Kind, kind)
142 })
143 }
144}
146func TestClient_CredentialKind_errors(t *testing.T) {
147 _, err := clientWithAuthSource(t, gitlab.Unauthenticated{}).CredentialKind()
148 require.ErrorIs(t, err, ErrUnauthenticated)
150 _, err = clientWithAuthSource(t, &gitlab.PasswordCredentialsAuthSource{Password: "p"}).CredentialKind()
151 require.ErrorIs(t, err, ErrUnsupportedAuthSource)
152}
154func TestClient_Credential_unauthenticated(t *testing.T) {
155 client := clientWithAuthSource(t, gitlab.Unauthenticated{})
157 _, err := client.Credential(t.Context())
158 assert.ErrorIs(t, err, ErrUnauthenticated)
159}
161func TestClient_Credential_unsupportedAuthSource(t *testing.T) {
162 client := clientWithAuthSource(t, &gitlab.PasswordCredentialsAuthSource{Password: "a-password"})
164 _, err := client.Credential(t.Context())
165 require.ErrorIs(t, err, ErrUnsupportedAuthSource)
166 // The Go type stays in the message for whoever has to debug it.
167 assert.ErrorContains(t, err, "*gitlab.PasswordCredentialsAuthSource")
168}
170type failingTokenSource struct {
171 err error
172}
174func (f failingTokenSource) Token() (*xoauth2.Token, error) {
175 return nil, f.err
176}
178func TestClient_Credential_refreshFailed(t *testing.T) {
179 cause := errors.New("invalid_grant")
180 client := clientWithAuthSource(t, gitlab.OAuthTokenSource{TokenSource: failingTokenSource{err: cause}})
182 _, err := client.Credential(t.Context())
183 require.ErrorIs(t, err, ErrRefreshFailed)
184 require.ErrorIs(t, err, cause)
185 assert.EqualError(t, err, "failed to refresh the OAuth2 token: invalid_grant")
186}
188func clientWithAuthSource(t *testing.T, as gitlab.AuthSource) *Client {
189 t.Helper()
191 client, err := NewClient(
192 func(*http.Client) (gitlab.AuthSource, error) { return as, nil },
193 WithBaseURL("https://example.com/api/v4/"),
194 )
195 require.NoError(t, err)
196 return client
197}
199// A host whose refresh token was forgotten must not hand its dead access token
200// to the credential helper: the Duo CLI keys its "session expired" message on
201// this prefix.
202func TestClient_Credential_expiredAccessTokenOnly(t *testing.T) {
203 client := clientWithAuthSource(t, oauth2AccessTokenOnlyAuthSource{
204 token: "access-expired",
205 host: "gitlab.example.com",
206 expiry: time.Now().Add(-time.Minute),
207 })
209 _, err := client.Credential(t.Context())
210 require.Error(t, err)
211 require.ErrorIs(t, err, ErrRefreshFailed)
212 require.ErrorContains(t, err, "failed to refresh the OAuth2 token")
213 assert.ErrorContains(t, err, "glab auth login --hostname gitlab.example.com")
214}
Diagnostics6 git calls · 230 ms
CallStatusSizeTime0230 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 · 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:0 · deepen 1020032 KiB · hit4 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=4 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.1 KiB · 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=1165 git.response.cache=HIT git.response.duration_ms=4 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
fetch2001.9 KiB221 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=221 git.response.bytes=1926 git.response.cache=MISS git.response.duration_ms=221 git.fetch.wants=c3bf7146b976ef7e995a6586e89318162b9abcb4 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=1926 git.pkt.payload.max=1899 git.sideband.band1.bytes=1899 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
- a5e1342f0d1b18aa
- Request
- 5d337bfd…
- 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