GitLabgitlab-org

cli

main
ply8 git calls231 ms100 KiB5 cachedprotocol v2
303 lines10 KiBRaw
1//go:build !integration
3package add
5import (
6 "errors"
7 "testing"
8 "time"
10 "github.com/stretchr/testify/assert"
11 "github.com/stretchr/testify/require"
12 "go.uber.org/mock/gomock"
14 gitlab "gitlab.com/gitlab-org/api/client-go/v3"
15 gitlabtesting "gitlab.com/gitlab-org/api/client-go/v3/testing"
17 "gitlab.com/gitlab-org/cli/internal/api"
18 "gitlab.com/gitlab-org/cli/internal/cmdutils"
19 "gitlab.com/gitlab-org/cli/internal/testing/cmdtest"
22func Test_AddSSHKey(t *testing.T) {
23 type testCase struct {
24 Name string
25 ExpectedMsg []string
26 wantErr bool
27 cli string
28 stdin string
29 wantStderr string
30 setupMock func(tc *gitlabtesting.TestClient)
31 }
33 validSSHKey := &gitlab.SSHKey{
34 ID: 1,
35 Key: "ssh-ed25519 example",
36 Title: "mysshkey",
37 CreatedAt: new(time.Time{}),
38 }
40 testCases := []testCase{
41 // Success cases
42 {
43 Name: "Add SSH key from file",
44 ExpectedMsg: []string{"New SSH public key added to your account.\n"},
45 cli: "testdata/testkey.key --title mysshkey --usage-type 'auth'",
46 setupMock: func(tc *gitlabtesting.TestClient) {
47 tc.MockUsers.EXPECT().AddSSHKey(gomock.Any(), gomock.Any()).Return(validSSHKey, nil, nil)
48 },
49 },
50 {
51 Name: "Add SSH key from stdin",
52 ExpectedMsg: []string{"New SSH public key added to your account.\n\n"},
53 cli: "--title mysshkey",
54 stdin: "ssh-ed25519 example",
55 setupMock: func(tc *gitlabtesting.TestClient) {
56 tc.MockUsers.EXPECT().AddSSHKey(gomock.Any(), gomock.Any()).Return(validSSHKey, nil, nil)
57 },
58 },
60 // // File errors
61 {
62 Name: "Add SSH key with missing file",
63 cli: "nonexistent.key --title somekey",
64 wantErr: true,
65 wantStderr: "nonexistent.key",
66 setupMock: func(tc *gitlabtesting.TestClient) {},
67 },
68 {
69 Name: "Add SSH key with long invalid expiry",
70 cli: "testdata/testkey.key --title somekey --expires-at not-a-valid-timestamp-that-is-long",
71 wantErr: true,
72 wantStderr: "cannot parse",
73 setupMock: func(tc *gitlabtesting.TestClient) {},
74 },
76 // // API errors
77 {
78 Name: "Add SSH key with invalid key format",
79 cli: "testdata/testkey.key --title somekey",
80 wantErr: true,
81 wantStderr: "Key is invalid",
82 setupMock: func(tc *gitlabtesting.TestClient) {
83 tc.MockUsers.EXPECT().AddSSHKey(gomock.Any(), gomock.Any()).Return(nil, nil, errors.New("Key is invalid"))
84 },
85 },
86 {
87 Name: "Add SSH key with duplicate key error",
88 cli: "testdata/testkey.key --title somekey",
89 wantErr: true,
90 wantStderr: "Key has already been taken",
91 setupMock: func(tc *gitlabtesting.TestClient) {
92 tc.MockUsers.EXPECT().AddSSHKey(gomock.Any(), gomock.Any()).Return(nil, nil, errors.New("Key has already been taken"))
93 },
94 },
95 {
96 Name: "Add SSH key with unauthorized error",
97 cli: "testdata/testkey.key --title somekey",
98 wantErr: true,
99 wantStderr: "401",
100 setupMock: func(tc *gitlabtesting.TestClient) {
101 tc.MockUsers.EXPECT().AddSSHKey(gomock.Any(), gomock.Any()).Return(nil, nil, errors.New("401 Unauthorized"))
102 },
103 },
104 {
105 Name: "Add SSH key with server error",
106 cli: "testdata/testkey.key --title somekey",
107 wantErr: true,
108 wantStderr: "",
109 setupMock: func(tc *gitlabtesting.TestClient) {
110 tc.MockUsers.EXPECT().AddSSHKey(gomock.Any(), gomock.Any()).Return(nil, nil, errors.New("500 Internal Server Error"))
111 },
112 },
113 }
115 for _, tc := range testCases {
116 t.Run(tc.Name, func(t *testing.T) {
117 // GIVEN
118 testClient := gitlabtesting.NewTestClient(t)
119 tc.setupMock(testClient)
120 exec := cmdtest.SetupCmdForTest(
121 t,
122 NewCmdAdd,
123 false,
124 cmdtest.WithApiClient(cmdtest.NewTestApiClient(t, nil, "", "", api.WithGitLabClient(testClient.Client))),
125 )
127 // WHEN
128 out, err := exec(tc.cli)
130 // THEN
131 if tc.wantErr {
132 require.Error(t, err)
133 assert.Contains(t, err.Error(), tc.wantStderr)
134 return
135 }
136 require.NoError(t, err)
137 for _, msg := range tc.ExpectedMsg {
138 assert.Contains(t, out.OutBuf.String(), msg)
139 }
140 })
141 }
144func Test_AddSSHKey_Replace(t *testing.T) {
145 const (
146 otherKey = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIC/7QmKq64NnEioQCTCeMaf6qdoqCmba2K0/Fi7P2kPf other"
147 sameKey = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIPxBTowwahEEmAu2wxFivSEyic4mIM/dJnC622v0/txu old-comment"
148 )
150 existingKeys := []*gitlab.SSHKey{
151 {ID: 10, Title: "other", Key: otherKey},
152 {ID: 11, Title: "expired", Key: sameKey},
153 }
154 addedKey := &gitlab.SSHKey{ID: 12, Title: "renewed", Key: sameKey}
156 type testCase struct {
157 name string
158 cli string
159 setupMock func(tc *gitlabtesting.TestClient)
160 wantErr string
161 wantFlagErr string
162 wantOut []string
163 notInOut string
164 }
166 testCases := []testCase{
167 {
168 name: "deletes the key with the same fingerprint even when its comment differs",
169 cli: "testdata/ed25519.pub --title renewed --expires-at 2027-01-01 --replace",
170 setupMock: func(tc *gitlabtesting.TestClient) {
171 gomock.InOrder(
172 tc.MockUsers.EXPECT().ListSSHKeys(gomock.Any(), gomock.Any()).Return(existingKeys, &gitlab.Response{}, nil),
173 tc.MockUsers.EXPECT().DeleteSSHKey(int64(11), gomock.Any()).Return(nil, nil),
174 tc.MockUsers.EXPECT().AddSSHKey(gomock.Any(), gomock.Any()).DoAndReturn(
175 func(opt *gitlab.AddSSHKeyOptions, _ ...gitlab.RequestOptionFunc) (*gitlab.SSHKey, *gitlab.Response, error) {
176 assert.Equal(t, "renewed", *opt.Title)
177 assert.Equal(t, "2027-01-01", opt.ExpiresAt.String())
178 return addedKey, nil, nil
179 }),
180 )
181 },
182 wantOut: []string{
183 `Deleted existing SSH key "expired" (ID 11) with the same fingerprint.`,
184 "New SSH public key added to your account.",
185 },
186 },
187 {
188 name: "adds the key when no existing key matches",
189 cli: "testdata/ed25519.pub --title renewed --replace",
190 setupMock: func(tc *gitlabtesting.TestClient) {
191 gomock.InOrder(
192 tc.MockUsers.EXPECT().ListSSHKeys(gomock.Any(), gomock.Any()).Return(existingKeys[:1], &gitlab.Response{}, nil),
193 tc.MockUsers.EXPECT().AddSSHKey(gomock.Any(), gomock.Any()).Return(addedKey, nil, nil),
194 )
195 },
196 wantOut: []string{"New SSH public key added to your account."},
197 notInOut: "Deleted existing SSH key",
198 },
199 {
200 name: "searches every page of existing keys",
201 cli: "testdata/ed25519.pub --title renewed --replace",
202 setupMock: func(tc *gitlabtesting.TestClient) {
203 gomock.InOrder(
204 tc.MockUsers.EXPECT().ListSSHKeys(gomock.Any(), gomock.Any()).Return(existingKeys[:1], &gitlab.Response{NextPage: 2}, nil),
205 tc.MockUsers.EXPECT().ListSSHKeys(gomock.Any(), gomock.Any(), gomock.Any()).Return(existingKeys[1:], &gitlab.Response{}, nil),
206 tc.MockUsers.EXPECT().DeleteSSHKey(int64(11), gomock.Any()).Return(nil, nil),
207 tc.MockUsers.EXPECT().AddSSHKey(gomock.Any(), gomock.Any()).Return(addedKey, nil, nil),
208 )
209 },
210 wantOut: []string{"(ID 11)", "New SSH public key added to your account."},
211 },
212 {
213 name: "does not delete the existing key when the expiration date is invalid",
214 cli: "testdata/ed25519.pub --title renewed --expires-at 2027-13-45 --replace",
215 setupMock: func(tc *gitlabtesting.TestClient) {},
216 wantFlagErr: `invalid --expires-at value "2027-13-45"`,
217 },
218 {
219 name: "does not delete the existing key when the usage type is invalid",
220 cli: "testdata/ed25519.pub --title renewed --usage-type everything --replace",
221 setupMock: func(tc *gitlabtesting.TestClient) {},
222 wantFlagErr: "must be one of",
223 },
224 {
225 name: "fails on a key that cannot be parsed",
226 cli: "testdata/testkey.key --title renewed --replace",
227 setupMock: func(tc *gitlabtesting.TestClient) {},
228 wantErr: "failed to parse SSH public key",
229 },
230 {
231 name: "fails without adding when listing keys fails",
232 cli: "testdata/ed25519.pub --title renewed --replace",
233 setupMock: func(tc *gitlabtesting.TestClient) {
234 tc.MockUsers.EXPECT().ListSSHKeys(gomock.Any(), gomock.Any()).Return(nil, nil, errors.New("500 Internal Server Error"))
235 },
236 wantErr: "failed to list existing SSH keys",
237 },
238 {
239 name: "fails without adding when deleting the existing key fails",
240 cli: "testdata/ed25519.pub --title renewed --replace",
241 setupMock: func(tc *gitlabtesting.TestClient) {
242 gomock.InOrder(
243 tc.MockUsers.EXPECT().ListSSHKeys(gomock.Any(), gomock.Any()).Return(existingKeys, &gitlab.Response{}, nil),
244 tc.MockUsers.EXPECT().DeleteSSHKey(int64(11), gomock.Any()).Return(nil, errors.New("403 Forbidden")),
245 )
246 },
247 wantErr: "failed to delete existing SSH key with ID 11",
248 },
249 {
250 name: "reports the deleted key when adding fails",
251 cli: "testdata/ed25519.pub --title renewed --replace",
252 setupMock: func(tc *gitlabtesting.TestClient) {
253 gomock.InOrder(
254 tc.MockUsers.EXPECT().ListSSHKeys(gomock.Any(), gomock.Any()).Return(existingKeys, &gitlab.Response{}, nil),
255 tc.MockUsers.EXPECT().DeleteSSHKey(int64(11), gomock.Any()).Return(nil, nil),
256 tc.MockUsers.EXPECT().AddSSHKey(gomock.Any(), gomock.Any()).Return(nil, nil, errors.New("400 Bad Request")),
257 )
258 },
259 wantErr: "The existing key with ID 11 was already deleted",
260 },
261 {
262 name: "does not look up existing keys without the flag",
263 cli: "testdata/ed25519.pub --title renewed",
264 setupMock: func(tc *gitlabtesting.TestClient) {
265 tc.MockUsers.EXPECT().AddSSHKey(gomock.Any(), gomock.Any()).Return(nil, nil, errors.New("fingerprint_sha256: [has already been taken]"))
266 },
267 wantErr: "failed to add new SSH public key.",
268 },
269 }
271 for _, tc := range testCases {
272 t.Run(tc.name, func(t *testing.T) {
273 testClient := gitlabtesting.NewTestClient(t)
274 tc.setupMock(testClient)
275 exec := cmdtest.SetupCmdForTest(
276 t,
277 NewCmdAdd,
278 false,
279 cmdtest.WithApiClient(cmdtest.NewTestApiClient(t, nil, "", "", api.WithGitLabClient(testClient.Client))),
280 )
282 out, err := exec(tc.cli)
284 if tc.wantFlagErr != "" {
285 require.ErrorContains(t, err, tc.wantFlagErr)
286 return
287 }
288 if tc.wantErr != "" {
289 var exitErr *cmdutils.ExitError
290 require.ErrorAs(t, err, &exitErr)
291 assert.Contains(t, exitErr.Details, tc.wantErr)
292 return
293 }
294 require.NoError(t, err)
295 for _, msg := range tc.wantOut {
296 assert.Contains(t, out.OutBuf.String(), msg)
297 }
298 if tc.notInOut != "" {
299 assert.NotContains(t, out.OutBuf.String(), tc.notInOut)
300 }
301 })
302 }
Diagnostics8 git calls · 231 ms
CallStatusSizeTime0231 ms
discover200185 B2 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 KiB2 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=UPDATING
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
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=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
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:0200289 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=289
git.response.cache=HIT
git.response.duration_ms=3
git.fetch.filter=tree:0
git.fetch.wants=1dd4ebf804b44e69b594244d57246af8b61f1ed3
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=289
git.pkt.payload.max=262
git.sideband.band1.bytes=262
git.sideband.band2.bytes=0
git.sideband.band3.bytes=0
git.pack.objects=1
git.pack.bytes=262
git.pack.trailer=d2a3ec46393f5a5492eae3096186e74c059a8aaf
Open pack map
fetchtree:0200199 B · hit3 ms
git.upload-pack fetch
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=fetch
git.upstream.dur_ms=218
git.response.bytes=199
git.response.cache=HIT
git.response.duration_ms=3
git.fetch.filter=tree:0
git.fetch.wants=37f4e04d7d2121449fd7bf4ba03a057405653a0d
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=199
git.pkt.payload.max=172
git.sideband.band1.bytes=172
git.sideband.band2.bytes=0
git.sideband.band3.bytes=0
git.pack.objects=1
git.pack.bytes=172
git.pack.trailer=22339d6a56272356818583e03d5e52f3bf953d0d
Open pack map
fetch2002.3 KiB218 ms
git.upload-pack fetch
http.response.status_code=200
git.response.bytes=2310
git.response.cache=MISS
git.response.duration_ms=218
git.fetch.wants=76569c83e1e25c5b97ff5102052862b248e2538a
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=2310
git.pkt.payload.max=2283
git.sideband.band1.bytes=2283
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
a5e2cb8e795a7929
Request
dfbb4aad…
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