GitLabgitlab-org

cli

main
ply9 git calls317 ms100 KiB7 cachedprotocol v2
331 lines10 KiBRaw
1//go:build !integration
3package create
5import (
6 "encoding/json"
7 "errors"
8 "testing"
9 "time"
11 "github.com/MakeNowJust/heredoc/v2"
12 "github.com/stretchr/testify/assert"
13 "github.com/stretchr/testify/require"
14 "go.uber.org/mock/gomock"
16 gitlab "gitlab.com/gitlab-org/api/client-go/v3"
17 gitlabtesting "gitlab.com/gitlab-org/api/client-go/v3/testing"
19 "gitlab.com/gitlab-org/cli/internal/api"
20 "gitlab.com/gitlab-org/cli/internal/cmdutils"
21 "gitlab.com/gitlab-org/cli/internal/cmdutils/tokenduration"
22 "gitlab.com/gitlab-org/cli/internal/testing/cmdtest"
25func setupExec(t *testing.T, tc *gitlabtesting.TestClient, opts ...cmdtest.FactoryOption) cmdtest.CmdExecFunc {
26 t.Helper()
28 opts = append(
29 []cmdtest.FactoryOption{
30 cmdtest.WithApiClient(cmdtest.NewTestApiClient(t, nil, "", "", api.WithGitLabClient(tc.Client))),
31 },
32 opts...,
33 )
35 return cmdtest.SetupCmdForTest(t, NewCmd, false, opts...)
38func noMorePages() *gitlab.Response {
39 return &gitlab.Response{NextPage: 0}
42func createdToken() *gitlab.PersonalAccessToken {
43 expiresAt := gitlab.ISOTime(time.Date(2027, 1, 31, 0, 0, 0, 0, time.UTC))
44 return &gitlab.PersonalAccessToken{
45 ID: 7,
46 Name: "ci",
47 Scopes: []string{"api"},
48 Active: true,
49 ExpiresAt: &expiresAt,
50 Token: "glpat-secret",
51 }
54// expectProjectCreate returns an accessor for the options the command sent, so
55// the tests can assert on the request and not only on what is printed.
56func expectProjectCreate(tc *gitlabtesting.TestClient) func() *gitlab.CreateProjectServiceAccountPersonalAccessTokenOptions {
57 var sent *gitlab.CreateProjectServiceAccountPersonalAccessTokenOptions
58 tc.MockProjects.EXPECT().
59 CreateProjectServiceAccountPersonalAccessToken("OWNER/REPO", int64(51), gomock.Any(), gomock.Any()).
60 DoAndReturn(func(_ any, _ int64, opt *gitlab.CreateProjectServiceAccountPersonalAccessTokenOptions, _ ...gitlab.RequestOptionFunc) (*gitlab.PersonalAccessToken, *gitlab.Response, error) {
61 sent = opt
62 return createdToken(), nil, nil
63 })
65 return func() *gitlab.CreateProjectServiceAccountPersonalAccessTokenOptions { return sent }
68// No account list expectation is set: an ID goes straight to the create.
69func TestTokenCreate_Project(t *testing.T) {
70 t.Parallel()
72 tc := gitlabtesting.NewTestClient(t)
73 sent := expectProjectCreate(tc)
75 out, err := setupExec(t, tc)("51 ci --scope api")
76 require.NoError(t, err)
78 assert.Equal(t, "ci", *sent().Name)
79 assert.Equal(t, []string{"api"}, *sent().Scopes)
80 assert.Nil(t, sent().Description)
82 assert.Equal(t, "glpat-secret\n", out.OutBuf.String())
83 expected := heredoc.Doc(`
84 ID 7
85 Name ci
86 Description -
87 Scopes api
88 Expires At 2027-01-31
89 ! Created token 7 for service account 51 in project OWNER/REPO. Store the token value now. It is not shown again.
90 `)
91 assert.Equal(t, expected, out.ErrBuf.String())
94func TestTokenCreate_DefaultExpiryIs30Days(t *testing.T) {
95 t.Parallel()
97 tc := gitlabtesting.NewTestClient(t)
98 sent := expectProjectCreate(tc)
100 _, err := setupExec(t, tc)("51 ci --scope api")
101 require.NoError(t, err)
103 want := tokenduration.TokenDuration(30 * 24 * time.Hour).CalculateExpirationDate().Format(time.DateOnly)
104 require.NotNil(t, sent().ExpiresAt)
105 assert.Equal(t, want, sent().ExpiresAt.String())
108func TestTokenCreate_Duration(t *testing.T) {
109 t.Parallel()
111 tc := gitlabtesting.NewTestClient(t)
112 sent := expectProjectCreate(tc)
114 _, err := setupExec(t, tc)("51 ci --scope api --duration 7d")
115 require.NoError(t, err)
117 want := tokenduration.TokenDuration(7 * 24 * time.Hour).CalculateExpirationDate().Format(time.DateOnly)
118 assert.Equal(t, want, sent().ExpiresAt.String())
121func TestTokenCreate_ExpiresAt(t *testing.T) {
122 t.Parallel()
124 tc := gitlabtesting.NewTestClient(t)
125 sent := expectProjectCreate(tc)
127 _, err := setupExec(t, tc)("51 ci --scope api --expires-at 2027-12-31")
128 require.NoError(t, err)
130 assert.Equal(t, "2027-12-31", sent().ExpiresAt.String())
133func TestTokenCreate_ScopesAndDescription(t *testing.T) {
134 t.Parallel()
136 tc := gitlabtesting.NewTestClient(t)
137 sent := expectProjectCreate(tc)
139 _, err := setupExec(t, tc)(`51 ci --scope read_api,read_repository --scope read_registry --description "CI reader"`)
140 require.NoError(t, err)
142 assert.Equal(t, []string{"read_api", "read_repository", "read_registry"}, *sent().Scopes)
143 require.NotNil(t, sent().Description)
144 assert.Equal(t, "CI reader", *sent().Description)
147func TestTokenCreate_Group(t *testing.T) {
148 t.Parallel()
150 var sent *gitlab.CreateServiceAccountPersonalAccessTokenOptions
151 tc := gitlabtesting.NewTestClient(t)
152 tc.MockGroups.EXPECT().
153 CreateServiceAccountPersonalAccessToken("group/sub-group", int64(41), gomock.Any(), gomock.Any()).
154 DoAndReturn(func(_ any, _ int64, opt *gitlab.CreateServiceAccountPersonalAccessTokenOptions, _ ...gitlab.RequestOptionFunc) (*gitlab.PersonalAccessToken, *gitlab.Response, error) {
155 sent = opt
156 return createdToken(), nil, nil
157 })
159 out, err := setupExec(t, tc)("41 ci --scope api --expires-at 2027-12-31 --group group/sub-group")
160 require.NoError(t, err)
162 assert.Equal(t, "ci", *sent.Name)
163 assert.Equal(t, []string{"api"}, *sent.Scopes)
164 assert.Equal(t, "2027-12-31", sent.ExpiresAt.String())
165 assert.Contains(t, out.ErrBuf.String(), "! Created token 7 for service account 41 in group group/sub-group. Store the token value now. It is not shown again.\n")
168func TestTokenCreate_ByUsername(t *testing.T) {
169 t.Parallel()
171 tc := gitlabtesting.NewTestClient(t)
172 gomock.InOrder(
173 tc.MockProjects.EXPECT().
174 ListProjectServiceAccounts("OWNER/REPO", gomock.Any(), gomock.Any(), gomock.Any()).
175 Return([]*gitlab.ProjectServiceAccount{{ID: 52, Username: "release-bot"}}, noMorePages(), nil),
176 tc.MockProjects.EXPECT().
177 CreateProjectServiceAccountPersonalAccessToken("OWNER/REPO", int64(52), gomock.Any(), gomock.Any()).
178 Return(createdToken(), nil, nil),
179 )
181 out, err := setupExec(t, tc)("release-bot ci --scope api")
182 require.NoError(t, err)
184 assert.Contains(t, out.ErrBuf.String(), "for service account 52 in project OWNER/REPO")
187// Unlike token list, create prints the token value, because this is the only
188// time GitLab returns it.
189func TestTokenCreate_JSONKeepsTokenValue(t *testing.T) {
190 t.Parallel()
192 tc := gitlabtesting.NewTestClient(t)
193 expectProjectCreate(tc)
195 out, err := setupExec(t, tc)("51 ci --scope api --output json")
196 require.NoError(t, err)
198 var result gitlab.PersonalAccessToken
199 require.NoError(t, json.Unmarshal(out.OutBuf.Bytes(), &result))
200 assert.Equal(t, int64(7), result.ID)
201 assert.Equal(t, "ci", result.Name)
202 assert.Equal(t, "glpat-secret", result.Token)
203 assert.Empty(t, out.ErrBuf.String())
206func TestTokenCreate_ScopeIsRequired(t *testing.T) {
207 t.Parallel()
209 tc := gitlabtesting.NewTestClient(t)
211 _, err := setupExec(t, tc)("51 ci")
212 require.Error(t, err)
213 assert.Contains(t, err.Error(), `required flag(s) "scope" not set`)
216func TestTokenCreate_DurationAndExpiresAtAreMutuallyExclusive(t *testing.T) {
217 t.Parallel()
219 tc := gitlabtesting.NewTestClient(t)
221 _, err := setupExec(t, tc)("51 ci --scope api --duration 7d --expires-at 2027-12-31")
222 require.Error(t, err)
223 assert.Contains(t, err.Error(), "none of the others can be")
226func TestTokenCreate_InvalidDuration(t *testing.T) {
227 t.Parallel()
229 tc := gitlabtesting.NewTestClient(t)
231 _, err := setupExec(t, tc)("51 ci --scope api --duration 400d")
232 require.Error(t, err)
233 assert.Contains(t, err.Error(), "duration must be between 1 and 365 days")
236func TestTokenCreate_InvalidExpiresAt(t *testing.T) {
237 t.Parallel()
239 tc := gitlabtesting.NewTestClient(t)
241 _, err := setupExec(t, tc)("51 ci --scope api --expires-at 31.12.2027")
242 require.Error(t, err)
243 assert.Contains(t, err.Error(), `invalid argument "31.12.2027" for "-E, --expires-at"`)
246func TestTokenCreate_InvalidAccountID(t *testing.T) {
247 t.Parallel()
249 tc := gitlabtesting.NewTestClient(t)
251 _, err := setupExec(t, tc)("0 ci --scope api")
252 require.Error(t, err)
253 assert.Contains(t, err.Error(), `invalid service account ID "0"`)
256func TestTokenCreate_APIError(t *testing.T) {
257 t.Parallel()
259 tc := gitlabtesting.NewTestClient(t)
260 tc.MockProjects.EXPECT().
261 CreateProjectServiceAccountPersonalAccessToken("OWNER/REPO", int64(51), gomock.Any(), gomock.Any()).
262 Return(nil, nil, errors.New("400 Bad Request"))
264 _, err := setupExec(t, tc)("51 ci --scope api")
265 require.Error(t, err)
267 var exitErr *cmdutils.ExitError
268 require.ErrorAs(t, err, &exitErr)
269 assert.Equal(t, "failed to create service account token", exitErr.Details)
270 assert.Contains(t, err.Error(), "400 Bad Request")
273func TestTokenCreate_RequiresArguments(t *testing.T) {
274 t.Parallel()
276 tc := gitlabtesting.NewTestClient(t)
278 _, err := setupExec(t, tc)("51 --scope api")
279 require.Error(t, err)
280 assert.Contains(t, err.Error(), "accepts 2 arg(s), received 1")
283func TestTokenCreate_RepoAndGroupAreMutuallyExclusive(t *testing.T) {
284 t.Parallel()
286 tc := gitlabtesting.NewTestClient(t)
288 _, err := setupExec(t, tc)("51 ci --scope api --repo OWNER/REPO --group my-group")
289 require.Error(t, err)
290 assert.Contains(t, err.Error(), "none of the others can be")
293func TestTokenCreate_OutsideRepositoryWithoutGroup(t *testing.T) {
294 t.Parallel()
296 tc := gitlabtesting.NewTestClient(t)
298 _, err := setupExec(t, tc, cmdtest.WithBaseRepoError(errors.New("not a git repository")))("51 ci --scope api")
299 require.Error(t, err)
300 assert.Contains(t, err.Error(), "not a git repository")
303func TestTokenCreate_OutsideRepositoryWithGroup(t *testing.T) {
304 t.Parallel()
306 tc := gitlabtesting.NewTestClient(t)
307 tc.MockGroups.EXPECT().
308 CreateServiceAccountPersonalAccessToken("my-group", int64(41), gomock.Any(), gomock.Any()).
309 Return(createdToken(), nil, nil)
311 out, err := setupExec(t, tc, cmdtest.WithBaseRepoError(errors.New("not a git repository")))("41 ci --scope api --group my-group")
312 require.NoError(t, err)
314 assert.Contains(t, out.OutBuf.String(), "glpat-secret")
317// GITLAB_GROUP redirects the command with no flag passed. t.Setenv rules out
318// t.Parallel.
319func TestTokenCreate_GroupFromEnvironment(t *testing.T) {
320 t.Setenv("GITLAB_GROUP", "env-group")
322 tc := gitlabtesting.NewTestClient(t)
323 tc.MockGroups.EXPECT().
324 CreateServiceAccountPersonalAccessToken("env-group", int64(41), gomock.Any(), gomock.Any()).
325 Return(createdToken(), nil, nil)
327 out, err := setupExec(t, tc)("41 ci --scope api")
328 require.NoError(t, err)
330 assert.Contains(t, out.ErrBuf.String(), "in group env-group.")
Diagnostics9 git calls · 317 ms
CallStatusSizeTime0317 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
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=44
Open pack map
fetchcombine:blob:none+tree:2 · deepen 12004.2 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=4273
git.response.cache=HIT
git.response.duration_ms=4
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 · 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=1857
git.response.cache=HIT
git.response.duration_ms=4
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:0200322 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=322
git.response.cache=HIT
git.response.duration_ms=3
git.fetch.filter=tree:0
git.fetch.wants=ba2caccf6c55211c6b29b98f40c2358479d91b1f
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=322
git.pkt.payload.max=295
git.sideband.band1.bytes=295
git.sideband.band2.bytes=0
git.sideband.band3.bytes=0
git.pack.objects=1
git.pack.bytes=295
git.pack.trailer=3488e558d4708096e879feba968e084c249dbe22
Open pack map
fetchtree:0200223 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=223
git.response.cache=HIT
git.response.duration_ms=3
git.fetch.filter=tree:0
git.fetch.wants=41d72d07155f99e3acc572f8fe5ad26c802e4ddc
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=223
git.pkt.payload.max=196
git.sideband.band1.bytes=196
git.sideband.band2.bytes=0
git.sideband.band3.bytes=0
git.pack.objects=1
git.pack.bytes=196
git.pack.trailer=d9c58aac50f427eb21501a81fe28c81c7c49ae44
Open pack map
fetchtree:0200138 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=138
git.response.cache=HIT
git.response.duration_ms=3
git.fetch.filter=tree:0
git.fetch.wants=17f358c7e70526844540138db141fe75ab4e5547
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=4d47b7526a382df069b0f8eed3c03e424e930f30
Open pack map
fetch2002.3 KiB297 ms
git.upload-pack fetch
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=fetch
git.upstream.dur_ms=297
git.response.bytes=2403
git.response.cache=MISS
git.response.duration_ms=297
git.fetch.wants=c0acf368fb49fbeeae492b691a341791447b704e
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=2403
git.pkt.payload.max=2376
git.sideband.band1.bytes=2376
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
a5e2f04eacf3fda9
Request
f2df47c7…
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