GitLabgitlab-org

cli

main
ply8 git calls337 ms99 KiB6 cachedprotocol v2
187 lines5.4 KiBRaw
1package add
3import (
4 "context"
5 "errors"
6 "fmt"
7 "io"
8 "os"
10 "github.com/MakeNowJust/heredoc/v2"
11 "github.com/spf13/cobra"
12 "golang.org/x/crypto/ssh"
14 gitlab "gitlab.com/gitlab-org/api/client-go/v3"
16 "gitlab.com/gitlab-org/cli/internal/api"
17 "gitlab.com/gitlab-org/cli/internal/cmdutils"
18 "gitlab.com/gitlab-org/cli/internal/iostreams"
19 "gitlab.com/gitlab-org/cli/internal/mcpannotations"
22type options struct {
23 apiClient func(repoHost string) (*api.Client, error)
24 io *iostreams.IOStreams
26 title string
27 key string
28 expiresAt string
29 usageType string
31 expiresAtTime *gitlab.ISOTime
32 replace bool
34 keyFile string
37func NewCmdAdd(f cmdutils.Factory) *cobra.Command {
38 opts := &options{
39 io: f.IO(),
40 apiClient: f.ApiClient,
41 }
42 cmd := &cobra.Command{
43 Use: "add [key-file]",
44 Short: "Add an SSH key to your GitLab account.",
45 Long: heredoc.Doc(`
46 Creates a new SSH key owned by the currently authenticated user.
48 Requires the '--title' flag.
50 GitLab rejects a key whose fingerprint is already registered on your account, even when that key has expired. Use '--replace' to delete the existing key with the same SHA256 fingerprint and add it again with the new title, usage type, and expiration date.
51 `),
52 Example: heredoc.Doc(`
53 # Read ssh key from stdin and upload.
54 glab ssh-key add -t "my title"
56 # Read ssh key from specified key file, upload and set the ssh key type to "authentication".
57 glab ssh-key add ~/.ssh/id_ed25519.pub -t "my title" --usage-type "auth"
59 # Re-register an expired key with a new expiration date.
60 glab ssh-key add ~/.ssh/id_ed25519.pub -t "my title" --expires-at 2027-01-01 --replace`),
61 Args: cobra.MaximumNArgs(1),
62 ValidArgsFunction: func(_ *cobra.Command, args []string, _ string) ([]cobra.Completion, cobra.ShellCompDirective) {
63 if len(args) != 0 {
64 return nil, cobra.ShellCompDirectiveNoFileComp
65 }
66 // .pub filenames would be desirable, but FilterFileExt breaks bash completion when a command has required flags
67 return nil, cobra.ShellCompDirectiveDefault
68 },
69 Annotations: map[string]string{
70 mcpannotations.Destructive: "true",
71 },
72 RunE: func(cmd *cobra.Command, args []string) error {
73 if err := opts.complete(args); err != nil {
74 return err
75 }
77 return opts.run(cmd.Context())
78 },
79 }
81 fl := cmd.Flags()
82 fl.StringVarP(&opts.title, "title", "t", "", "New SSH key's title.")
83 fl.VarP(cmdutils.NewEnumValue([]string{"auth", "signing", "auth_and_signing"}, "auth_and_signing", &opts.usageType), "usage-type", "u", "Usage scope for the key. Possible values: 'auth', 'signing' or 'auth_and_signing'. Default value: 'auth_and_signing'.")
84 fl.StringVarP(&opts.expiresAt, "expires-at", "e", "", "The expiration date of the SSH key. Uses ISO 8601 format: YYYY-MM-DDTHH:MM:SSZ.")
85 fl.BoolVar(&opts.replace, "replace", false, "Delete an existing key with the same fingerprint, such as an expired key, before adding this one.")
87 _ = cmd.MarkFlagRequired("title")
89 return cmd
92func (o *options) complete(args []string) error {
93 if len(args) == 0 {
94 if o.io.IsInteractive() {
95 return &cmdutils.FlagError{Err: errors.New("missing key file")}
96 }
97 o.keyFile = "-"
98 } else {
99 o.keyFile = args[0]
100 }
102 if o.expiresAt != "" {
103 expiresAt, err := parseExpiresAt(o.expiresAt)
104 if err != nil {
105 return &cmdutils.FlagError{Err: fmt.Errorf("invalid --expires-at value %q: %w", o.expiresAt, err)}
106 }
107 o.expiresAtTime = expiresAt
108 }
110 return nil
113func (o *options) run(ctx context.Context) error {
114 c, err := o.apiClient("")
115 if err != nil {
116 return err
117 }
118 client := c.Lab()
120 var keyFileReader io.Reader
121 if o.keyFile == "-" {
122 keyFileReader = o.io.In
123 defer o.io.In.Close()
124 } else {
125 f, err := os.Open(o.keyFile)
126 if err != nil {
127 return err
128 }
129 defer f.Close()
131 keyFileReader = f
132 }
134 keyInBytes, err := io.ReadAll(keyFileReader)
135 if err != nil {
136 return cmdutils.WrapError(err, "failed to read SSH key file.")
137 }
139 o.key = string(keyInBytes)
141 var replacedKeyID int64
142 if o.replace {
143 replacedKeyID, err = o.deleteKeyWithSameFingerprint(ctx, client)
144 if err != nil {
145 return err
146 }
147 }
149 err = UploadSSHKey(ctx, client, o.title, o.key, o.usageType, o.expiresAtTime)
150 if err != nil {
151 if replacedKeyID != 0 {
152 return cmdutils.WrapError(err, fmt.Sprintf("failed to add new SSH public key. The existing key with ID %d was already deleted.", replacedKeyID))
153 }
154 return cmdutils.WrapError(err, "failed to add new SSH public key.")
155 }
157 if o.io.IsOutputTTY() {
158 cs := o.io.Color()
159 o.io.LogInfof("%s New SSH public key added to your account.\n", cs.GreenCheck())
160 } else {
161 o.io.LogInfo("New SSH public key added to your account.\n")
162 }
164 return nil
167func (o *options) deleteKeyWithSameFingerprint(ctx context.Context, client *gitlab.Client) (int64, error) {
168 pub, _, _, _, err := ssh.ParseAuthorizedKey([]byte(o.key))
169 if err != nil {
170 return 0, cmdutils.WrapError(err, "failed to parse SSH public key.")
171 }
173 existing, err := findSSHKeyByFingerprint(ctx, client, ssh.FingerprintSHA256(pub))
174 if err != nil {
175 return 0, cmdutils.WrapError(err, "failed to list existing SSH keys.")
176 }
177 if existing == nil {
178 return 0, nil
179 }
181 if _, err := client.Users.DeleteSSHKey(existing.ID, gitlab.WithContext(ctx)); err != nil {
182 return 0, cmdutils.WrapError(err, fmt.Sprintf("failed to delete existing SSH key with ID %d.", existing.ID))
183 }
184 o.io.LogInfof("Deleted existing SSH key %q (ID %d) with the same fingerprint.\n", existing.Title, existing.ID)
186 return existing.ID, nil
Diagnostics8 git calls · 337 ms
CallStatusSizeTime0337 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 · 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=4273
git.response.cache=HIT
git.response.duration_ms=3
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: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 · 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=199
git.response.cache=HIT
git.response.duration_ms=2
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.2 KiB323 ms
git.upload-pack fetch
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=fetch
git.upstream.dur_ms=323
git.response.bytes=2211
git.response.cache=MISS
git.response.duration_ms=323
git.fetch.wants=a67161f7bec3dcb7a4ec3268db7ef8810571e870
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=2211
git.pkt.payload.max=2184
git.sideband.band1.bytes=2184
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
a5e2c1561bcc89da
Request
5f7251b4…
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