GitLabgitlab-org
cli
main
1package generate
3import (
4 "crypto"
5 "crypto/rsa"
6 "crypto/sha256"
7 "encoding/base64"
8 "errors"
9 "fmt"
10 "log"
11 "os"
12 "time"
14 "github.com/MakeNowJust/heredoc/v2"
15 "github.com/golang-jwt/jwt/v5"
16 "github.com/google/uuid"
17 "github.com/spf13/cobra"
18 "golang.org/x/crypto/ed25519"
19 "golang.org/x/crypto/ssh"
20 "golang.org/x/term"
22 "gitlab.com/gitlab-org/cli/internal/cmdutils"
23 "gitlab.com/gitlab-org/cli/internal/commands/auth/generate/dpop"
24 "gitlab.com/gitlab-org/cli/internal/config"
25 "gitlab.com/gitlab-org/cli/internal/iostreams"
26 "gitlab.com/gitlab-org/cli/internal/mcpannotations"
27 "gitlab.com/gitlab-org/cli/internal/text"
28)
30type options struct {
31 io *iostreams.IOStreams
32 config func() config.Config
33 privateKeyLocation string
34 personalAccessToken string
35 hostname string
36}
38type PasswordReader interface {
39 Read() ([]byte, error)
40}
42type ConsolePasswordReader struct{}
44func (pr ConsolePasswordReader) Read() ([]byte, error) {
45 return term.ReadPassword(int(os.Stdin.Fd()))
46}
48func NewCmdGenerate(f cmdutils.Factory) *cobra.Command {
49 opts := &options{
50 io: f.IO(),
51 config: f.Config,
52 }
53 cmd := &cobra.Command{
54 Use: "dpop-gen",
55 Short: "Generate a DPoP (demonstrating-proof-of-possession) proof JWT. (EXPERIMENTAL)",
56 Long: heredoc.Docf(`
57 Generates a demonstrating-proof-of-possession (DPoP) proof JSON Web Token (JWT).
58 DPoP cryptographically binds personal access tokens to their owners.
60 Use the JWT with a personal access token (PAT) to authenticate to the GitLab API.
61 glab signs the JWT with your SSH private key. The JWT remains valid for five
62 minutes. After it expires, generate another one.
64 Prerequisites:
66 - An SSH key pair in RSA, ed25519, or ECDSA format.
67 - [Enabled DPoP for your account](https://docs.gitlab.com/user/profile/personal_access_tokens/#use-dpop-with-personal-access-tokens).
68 %s`, text.ExperimentalString),
69 Example: heredoc.Doc(`
70 # Generate a DPoP JWT using an SSH private key and a personal access token
71 glab auth dpop-gen --private-key "~/.ssh/id_rsa" --pat "glpat-xxxxxxxxxxxxxxxxxxxx"
73 # Generate a DPoP JWT without a PAT (uses the token from 'glab auth login')
74 glab auth dpop-gen --private-key "~/.ssh/id_rsa"
76 # Generate a DPoP JWT for a different GitLab instance
77 glab auth dpop-gen --private-key "~/.ssh/id_rsa" --hostname "https://gitlab.com"
78 `),
79 Args: cobra.NoArgs,
80 ValidArgsFunction: cobra.NoFileCompletions,
81 Annotations: map[string]string{
82 mcpannotations.Destructive: "true",
83 },
84 RunE: func(cmd *cobra.Command, args []string) error {
85 if err := opts.complete(); err != nil {
86 return err
87 }
89 return opts.run()
90 },
91 }
93 cmd.Flags().StringVarP(&opts.privateKeyLocation, "private-key", "p", "", "Location of the private SSH key on the local system.")
94 cmd.Flags().StringVar(&opts.personalAccessToken, "pat", "", "Personal access token (PAT) to generate a DPoP proof for. Defaults to the token set with 'glab auth login'.")
95 cmd.Flags().StringVarP(&opts.hostname, "hostname", "", "gitlab.com", "The hostname of the GitLab instance to authenticate with.")
96 cobra.CheckErr(cmd.MarkFlagRequired("private-key"))
98 return cmd
99}
101func (o *options) complete() error {
102 if o.personalAccessToken == "" {
103 cfg := o.config()
105 token, err := cfg.Get(o.hostname, "token")
106 if err != nil {
107 return err
108 }
110 if token != "" {
111 o.personalAccessToken = token
112 } else {
113 return fmt.Errorf("personal access token is required")
114 }
115 }
117 return nil
118}
120func (o *options) run() error {
121 privateKey, err := loadPrivateKey(o.privateKeyLocation, ConsolePasswordReader{})
122 if err != nil {
123 return err
124 }
126 proofString, err := generateDPoPProof(privateKey, o.personalAccessToken)
127 if err != nil {
128 return err
129 }
131 log.Println("DPoP Proof:", proofString)
132 return nil
133}
135func generateDPoPProof(key crypto.PrivateKey, accessToken string) (string, error) {
136 signingMethod, err := getSigningMethod(key)
137 if err != nil {
138 return "", err
139 }
141 hashedToken := sha256.Sum256([]byte(accessToken))
142 base64UrlEncodedHash := base64.RawURLEncoding.EncodeToString(hashedToken[:])
144 uuidObj, err := uuid.NewRandom()
145 if err != nil {
146 return "", err
147 }
149 publicKey, err := getPublicKey(key)
150 if err != nil {
151 return "", err
152 }
154 sshPubKey, err := ssh.NewPublicKey(publicKey)
155 if err != nil {
156 return "", err
157 }
159 fingerprint := ssh.FingerprintSHA256(sshPubKey)
161 now := time.Now()
162 claims := &dpop.ProofTokenClaims{
163 RegisteredClaims: &jwt.RegisteredClaims{
164 IssuedAt: jwt.NewNumericDate(now),
165 ExpiresAt: jwt.NewNumericDate(now.Add(time.Minute * 5)),
166 ID: uuidObj.String(),
167 },
168 AccessTokenHash: base64UrlEncodedHash,
169 }
171 signer, ok := key.(crypto.Signer)
172 if !ok {
173 return "", fmt.Errorf("key type does not implement crypto.Signer")
174 }
176 jwk, err := dpop.Reflect(publicKey)
177 if err != nil {
178 return "", err
179 }
180 token := &jwt.Token{
181 Header: map[string]any{
182 "typ": "dpop+jwt",
183 "alg": signingMethod.Alg(),
184 "jwk": jwk,
185 "kid": fingerprint,
186 },
187 Claims: claims,
188 Method: signingMethod,
189 }
191 signedToken, err := token.SignedString(signer)
192 if err != nil {
193 return "", err
194 }
196 return signedToken, nil
197}
199func getSigningMethod(key crypto.PrivateKey) (jwt.SigningMethod, error) {
200 var signingMethod jwt.SigningMethod
201 switch key := key.(type) {
202 case *rsa.PrivateKey:
203 if key.N.BitLen() < 2048 {
204 // Minimum should be 2048 as per https://www.rfc-editor.org/rfc/rfc7518.html#section-3.3
205 return nil, fmt.Errorf("RSA key size must be greater than 2048 bits")
206 }
207 if key.N.BitLen() > 8192 {
208 // Maximum should be 8192 as per https://docs.gitlab.com/user/ssh/#rsa-ssh-keys
209 return nil, fmt.Errorf("RSA key size must be less than 8192 bits")
210 }
211 signingMethod = jwt.SigningMethodRS512
212 case *ed25519.PrivateKey:
213 signingMethod = jwt.SigningMethodEdDSA
214 default:
215 return nil, fmt.Errorf("unsupported key type")
216 }
217 return signingMethod, nil
218}
220func getPublicKey(key crypto.PrivateKey) (crypto.PublicKey, error) {
221 switch key := key.(type) {
222 case *rsa.PrivateKey:
223 return key.Public(), nil
224 case *ed25519.PrivateKey:
225 publicKey, ok := key.Public().(ed25519.PublicKey)
226 if !ok {
227 return nil, fmt.Errorf("ed25519 private key did not return an ed25519 public key")
228 }
229 return publicKey, nil
230 default:
231 return nil, fmt.Errorf("unsupported key type")
232 }
233}
235func loadPrivateKey(path string, passwordReader PasswordReader) (crypto.PrivateKey, error) {
236 keyBytes, err := os.ReadFile(path)
237 if err != nil {
238 return nil, err
239 }
241 privateKey, err := ssh.ParseRawPrivateKey(keyBytes)
242 if err != nil {
243 var passphraseMissingErr *ssh.PassphraseMissingError
244 if errors.As(err, &passphraseMissingErr) {
245 fmt.Println("SSH private key is encrypted. Enter your key's passphrase: ")
246 passphrase, err := passwordReader.Read()
247 if err != nil {
248 return nil, err
249 }
251 privateKey, err = ssh.ParseRawPrivateKeyWithPassphrase(keyBytes, passphrase)
252 if err != nil {
253 return nil, err
254 }
255 } else {
256 return nil, err
257 }
258 }
260 pk, ok := privateKey.(crypto.PrivateKey)
261 if !ok {
262 return nil, fmt.Errorf("parsed key %T does not satisfy crypto.PrivateKey", privateKey)
263 }
264 return pk, nil
265}
Diagnostics8 git calls · 252 ms
CallStatusSizeTime0252 ms
discover200185 B4 ms
git.upload-pack discover http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=ls-refs git.upstream.dur_ms=4 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 KiB216 ms
git.upload-pack ls-refs http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=ls-refs git.upstream.dur_ms=203 git.response.bytes=59849 git.response.cache=EXPIRED git.response.duration_ms=216 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 · 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: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
fetchtree:02001.8 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=1857 git.response.cache=HIT git.response.duration_ms=2 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=fb03183b7909876778f740d196d7516811003517Open pack map
fetchtree:0200358 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=358 git.response.cache=HIT git.response.duration_ms=3 git.fetch.filter=tree:0 git.fetch.wants=5d783fac547a70b19ca138c47d067b44febb52da 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=358 git.pkt.payload.max=331 git.sideband.band1.bytes=331 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0 git.pack.objects=1 git.pack.bytes=331 git.pack.trailer=22a484e5ecad6d6e62b224e8a7f90cf5ff085938Open pack map
fetchtree:0200204 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=204 git.response.cache=HIT git.response.duration_ms=4 git.fetch.filter=tree:0 git.fetch.wants=7f57e69c1796ef0dd4d7877c582d94d8a96a5369 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=204 git.pkt.payload.max=177 git.sideband.band1.bytes=177 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0 git.pack.objects=1 git.pack.bytes=177 git.pack.trailer=abcd288a8924fff99397ff5cd51aa278233a24e2Open pack map
fetch2002.6 KiB · hit24 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=24 git.response.bytes=2627 git.response.cache=HIT git.response.duration_ms=24 git.fetch.wants=0a4dc6da8be0f4ec02fb1a950fef3c9354682f15 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=2627 git.pkt.payload.max=2600 git.sideband.band1.bytes=2600 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
- a5e1fd1fd882a9c0
- Request
- ad3f3f75…
- 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