GitLabgitlab-org
cli
main
1// Package tokenexchange exchanges a GitLab session token for a short-lived
2// token scoped to one GitLab service through the POST /api/v4/token_exchange
3// endpoint.
4package tokenexchange
6import (
7 "context"
8 "encoding/json"
9 "errors"
10 "fmt"
11 "net/http"
12 "regexp"
13 "strings"
14 "time"
16 "github.com/golang-jwt/jwt/v5"
18 gitlab "gitlab.com/gitlab-org/api/client-go/v3"
20 "gitlab.com/gitlab-org/cli/internal/api"
21)
23const path = "token_exchange"
25// request is the JSON body sent to path. ExpiresIn is a pointer so that a nil
26// value omits expires_in from the request body entirely, letting the server
27// apply its own default lifetime rather than sending a CLI-chosen one.
28type request struct {
29 Audience string `json:"audience"`
30 ExpiresIn *int `json:"expires_in,omitempty"`
31}
33type response struct {
34 Token string `json:"token"`
35}
37// jwtCompactRe matches the JWS compact serialization: three base64url segments,
38// with a possibly-empty signature for alg=none. Nothing but [A-Za-z0-9_-] and
39// the two dots may appear.
40//
41// Enforced because callers write this token verbatim into line-oriented
42// credential files (~/.m2/settings.xml, .npmrc and friends) or request
43// metadata, and decodeUnverifiedClaims alone does not keep line breaks out
44// of it. Go's base64 decoder skips "\r" and "\n" as insignificant whitespace,
45// so a token whose signature or payload segment carries them decodes cleanly,
46// claims and all, and reaches the writer with the breaks intact. Bytes like
47// "=", ":", '"' and " " are rejected by the base64 decode already; the line
48// breaks are the gap.
49var jwtCompactRe = regexp.MustCompile(`^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]*$`)
51// Result is the decoded result of a successful token exchange. The
52// claim-derived fields are populated here so callers never have to decode the
53// token a second time.
54type Result struct {
55 // Token is the raw, encoded access token returned by the server. Nothing
56 // here verifies its signature; it is trustworthy because of the TLS
57 // connection to the issuing host. Treat it as a bearer credential for the
58 // requested audience and hand it to nothing else.
59 Token string `json:"token"`
60 // ExpiresAt is the token's expiry, taken from its exp claim.
61 ExpiresAt time.Time `json:"expires_at"`
62 // Issuer is the token's iss claim.
63 Issuer string `json:"issuer"`
64 // Subject is the token's sub claim.
65 Subject string `json:"subject"`
66 // Audience is the token's aud claim: what it is scoped to. Printing this
67 // is what distinguishes a service-scoped token from just "a token GitLab
68 // issued".
69 Audience string `json:"audience"`
70}
72// String redacts Token so logging or formatting a Result with %v or %+v never
73// leaks the bearer token.
74func (r Result) String() string {
75 return fmt.Sprintf("ExchangeResult{Token:REDACTED, ExpiresAt:%s, Issuer:%s, Subject:%s, Audience:%s}",
76 r.ExpiresAt, r.Issuer, r.Subject, r.Audience)
77}
79// MarshalJSON redacts Token so json.Marshal(Result) never leaks the bearer
80// token, protecting callers that marshal the whole struct instead of a
81// printer-local subset of its fields.
82func (r Result) MarshalJSON() ([]byte, error) {
83 type alias Result
84 //nolint:forbidigo // implementing MarshalJSON itself, not producing stdout output
85 return json.Marshal(struct {
86 alias
87 Token string `json:"token"`
88 }{
89 alias: alias(r),
90 Token: "REDACTED",
91 })
92}
94// Exchange exchanges the caller's GitLab credential for a short-lived token
95// for audience, valid for expiresIn. A zero expiresIn omits expires_in from
96// the request so the server applies its own default lifetime. Bounds on
97// expiresIn are the caller's to enforce; the server's 400 is the
98// authoritative answer.
99func Exchange(ctx context.Context, gl *gitlab.Client, audience string, expiresIn time.Duration) (*Result, error) {
100 body := request{Audience: audience}
101 if expiresIn != 0 {
102 // Rounded rather than truncated: the server's floor is one second, so
103 // truncating could silently discard up to just under a full second of
104 // a short, precisely-chosen request.
105 seconds := int(expiresIn.Round(time.Second).Seconds())
106 body.ExpiresIn = &seconds
107 }
109 req, err := gl.NewRequest(http.MethodPost, path, body, []gitlab.RequestOptionFunc{gitlab.WithContext(ctx), api.WithSafeRetries()})
110 if err != nil {
111 return nil, fmt.Errorf("failed to create token exchange request: %w", err)
112 }
114 var resp response
115 if _, err := gl.Do(req, &resp); err != nil {
116 if errors.Is(err, gitlab.ErrNotFound) {
117 return nil, fmt.Errorf("token exchange is not available on this instance (requires GitLab EE 19.4 or later): %w", err)
118 }
119 return nil, fmt.Errorf("failed to exchange token: %w", err)
120 }
122 if resp.Token == "" {
123 return nil, fmt.Errorf("server returned an empty token")
124 }
126 // Checked before the claims decode, so a token that cannot safely be
127 // written to a credential file is rejected on its shape rather than on
128 // whichever claim happens to be missing.
129 if !jwtCompactRe.MatchString(resp.Token) {
130 return nil, fmt.Errorf("server returned a token that is not in JWS compact form")
131 }
133 claims, err := decodeUnverifiedClaims(resp.Token)
134 if err != nil {
135 return nil, fmt.Errorf("failed to decode exchanged token: %w", err)
136 }
138 if claims.ExpiresAt == nil {
139 return nil, fmt.Errorf("exchanged token has no expiry claim")
140 }
141 if claims.Issuer == "" {
142 return nil, fmt.Errorf("exchanged token has no issuer claim")
143 }
144 if claims.Subject == "" {
145 return nil, fmt.Errorf("exchanged token has no subject claim")
146 }
148 return &Result{
149 Token: resp.Token,
150 ExpiresAt: claims.ExpiresAt.Time,
151 Issuer: claims.Issuer,
152 Subject: claims.Subject,
153 Audience: strings.Join(claims.Audience, ","),
154 }, nil
155}
157// decodeUnverifiedClaims decodes the registered claims of token without
158// verifying its signature: the trust boundary is the TLS connection to the
159// issuing GitLab host.
160func decodeUnverifiedClaims(token string) (*jwt.RegisteredClaims, error) {
161 claims := &jwt.RegisteredClaims{}
162 if _, _, err := jwt.NewParser().ParseUnverified(token, claims); err != nil {
163 return nil, fmt.Errorf("failed to decode token claims: %w", err)
164 }
165 return claims, nil
166}
Diagnostics7 git calls · 38 ms
CallStatusSizeTime038 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 KiB3 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=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=44Open 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.1 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=1165 git.response.cache=HIT git.response.duration_ms=3 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
fetchtree:0200145 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=145 git.response.cache=HIT git.response.duration_ms=2 git.fetch.filter=tree:0 git.fetch.wants=61a86c3cd09248644c3c2b7a4404d83963e3f410 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=145 git.pkt.payload.max=118 git.sideband.band1.bytes=118 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0 git.pack.objects=1 git.pack.bytes=118 git.pack.trailer=cb5fa2850a001f0015a161f432a87b299fd95ab9Open pack map
fetch2002.5 KiB · hit26 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=26 git.response.bytes=2587 git.response.cache=HIT git.response.duration_ms=26 git.fetch.wants=a0b58770899717d056da7b61e9ab78719d2b0e59 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=2587 git.pkt.payload.max=2560 git.sideband.band1.bytes=2560 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
- a5e267153c0cdf63
- Request
- 67441195…
- 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