GitLabgitlab-org
cli
main
1package rotate
3import (
4 "context"
5 "errors"
6 "fmt"
7 "slices"
8 "strconv"
9 "time"
11 "github.com/MakeNowJust/heredoc/v2"
12 "github.com/spf13/cobra"
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/cmdutils/tokenduration"
19 "gitlab.com/gitlab-org/cli/internal/commands/token/expirationdate"
20 "gitlab.com/gitlab-org/cli/internal/commands/token/filter"
21 "gitlab.com/gitlab-org/cli/internal/commands/token/tokenutils"
22 "gitlab.com/gitlab-org/cli/internal/config"
23 "gitlab.com/gitlab-org/cli/internal/glrepo"
24 "gitlab.com/gitlab-org/cli/internal/iostreams"
25 "gitlab.com/gitlab-org/cli/internal/mcpannotations"
26)
28type options struct {
29 apiClient func(repoHost string) (*api.Client, error)
30 config func() config.Config
31 io *iostreams.IOStreams
32 baseRepo func() (glrepo.Interface, error)
33 defaultHostname func() string
35 user string
36 group string
37 self bool
38 name any
39 duration tokenduration.TokenDuration
40 expireAt expirationdate.ExpirationDate
41 outputFormat string
42}
44func NewCmdRotate(f cmdutils.Factory) *cobra.Command {
45 opts := &options{
46 io: f.IO(),
47 apiClient: f.ApiClient,
48 config: f.Config,
49 baseRepo: f.BaseRepo,
50 defaultHostname: f.DefaultHostname,
51 duration: tokenduration.TokenDuration(30 * 24 * time.Hour), // Default: 30 days
52 }
54 cmd := &cobra.Command{
55 Use: "rotate [<token-name|token-id>]",
56 Short: "Rotate user, group, or project access tokens.",
57 Aliases: []string{"rot"},
58 Args: cobra.MaximumNArgs(1),
59 ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]cobra.Completion, cobra.ShellCompDirective) {
60 if self, err := cmd.Flags().GetBool("self"); err == nil && self {
61 return nil, cobra.ShellCompDirectiveNoFileComp
62 }
63 return tokenutils.NameOrIDCompletions(cmd.Context(), f, cmd, args, toComplete)
64 },
65 Long: heredoc.Docf(`
66 Rotating a token revokes the existing token and creates a new one
67 with a new secret value and expiration date.
68 The old token stops working immediately, so you must update any client that uses
69 it with the new value that this command returns.
71 If multiple tokens share the same name, specify the token ID to select the correct one.
73 The token expires at 00:00 UTC on a date calculated by adding the duration to today's date.
74 The default duration is 30 days. You can specify a different duration in days (%[1]sd%[1]s),
75 weeks (%[1]sw%[1]s), or hours (%[1]sh%[1]s).
76 The %[1]s--duration%[1]s and %[1]s--expires-at%[1]s flags are mutually exclusive.
78 Administrators can rotate personal access tokens that belong to other users.
80 Use %[1]s--self%[1]s to rotate the token currently used for authentication. This command requires GitLab 17.9 or later.
81 glab replaces the stored copy of that token for the host, in the keyring or the config file, so your next command keeps working. A token from an environment variable can't be updated, so glab warns on stderr and you must export the new value.
82 `, "`"),
83 Example: heredoc.Doc(`
84 # Rotate project access token of current project (default 30 days)
85 glab token rotate my-project-token
87 # Rotate project access token with explicit expiration date
88 glab token rotate --repo user/repo my-project-token --expires-at 2025-08-08
90 # Rotate group access token with 7 day lifetime
91 glab token rotate --group group/sub-group my-group-token --duration 7d
93 # Rotate personal access token with 2 week lifetime
94 glab token rotate --user @me my-personal-token --duration 2w
96 # Rotate a personal access token of another user (administrator only)
97 glab token rotate --user johndoe johns-personal-token --duration 90d
99 # Rotate the current authentication token
100 glab token rotate --self --duration 90d`),
101 Annotations: map[string]string{
102 mcpannotations.Exclude: "true",
103 },
104 RunE: func(cmd *cobra.Command, args []string) error {
105 if err := opts.complete(cmd, args); err != nil {
106 return err
107 }
109 if err := opts.validate(); err != nil {
110 return err
111 }
113 return opts.run(cmd.Context())
114 },
115 }
117 cmdutils.EnableRepoOverride(cmd, f)
118 fl := cmd.Flags()
119 fl.StringVarP(&opts.group, "group", "g", "", "Rotate group access token. Ignored if a user or repository argument is set.")
120 cobra.CheckErr(cmd.RegisterFlagCompletionFunc("group", tokenutils.GroupCompletions))
121 fl.StringVarP(&opts.user, "user", "U", "", "Rotate personal access token. Use @me for the current user.")
122 cobra.CheckErr(cmd.RegisterFlagCompletionFunc("user", tokenutils.UserCompletions))
123 fl.BoolVar(&opts.self, "self", false, "Rotate the access token currently used for authentication.")
124 fl.VarP(&opts.duration, "duration", "D", "Sets the token lifetime in days. Accepts: days (30d), weeks (4w), or hours in multiples of 24 (24h, 168h, 720h). Maximum: 365d. The token expires at 00:00 UTC on the calculated date.")
125 cobra.CheckErr(cmd.RegisterFlagCompletionFunc("duration", cobra.NoFileCompletions))
126 fl.VarP(&opts.expireAt, "expires-at", "E", "Sets the token's expiration date and time, in YYYY-MM-DD format. If not specified, --duration is used.")
127 cobra.CheckErr(cmd.RegisterFlagCompletionFunc("expires-at", cobra.NoFileCompletions))
128 cmdutils.EnableJSONOutput(cmd, opts.io, &opts.outputFormat, "Format output as: text, json. 'text' provides the new token value; 'json' outputs the token with metadata.")
129 cmd.MarkFlagsMutuallyExclusive("duration", "expires-at")
130 cmd.MarkFlagsMutuallyExclusive("self", "user")
131 cmd.MarkFlagsMutuallyExclusive("self", "group")
132 return cmd
133}
135func (o *options) complete(cmd *cobra.Command, args []string) error {
136 if len(args) > 0 {
137 if name, err := strconv.ParseInt(args[0], 10, 64); err != nil {
138 o.name = args[0]
139 } else {
140 o.name = name
141 }
142 }
144 if group, err := cmdutils.GroupOverride(cmd); err != nil {
145 return err
146 } else {
147 o.group = group
148 }
150 if time.Time(o.expireAt).IsZero() {
151 o.expireAt = expirationdate.ExpirationDate(o.duration.CalculateExpirationDate())
152 }
154 return nil
155}
157func (o *options) nameKind() string {
158 if _, ok := o.name.(int64); ok {
159 return "ID"
160 }
161 return "name"
162}
164func (o *options) validate() error {
165 if o.group != "" && o.user != "" {
166 return cmdutils.FlagError{Err: errors.New("'--group' and '--user' are mutually exclusive")}
167 }
169 if o.self && o.name != nil {
170 return cmdutils.FlagError{Err: errors.New("'--self' does not accept a positional argument")}
171 }
173 if !o.self && o.name == nil {
174 return cmdutils.FlagError{Err: errors.New("requires either '--self' or a token name/ID argument")}
175 }
177 return nil
178}
180func (o *options) run(ctx context.Context) error {
181 // NOTE: this command can not only be used for projects,
182 // so we have to manually check for the base repo, if it doesn't exist,
183 // we bootstrap the client with the default hostname.
184 var repoHost string
185 if baseRepo, err := o.baseRepo(); err == nil {
186 repoHost = baseRepo.RepoHost()
187 }
188 configHost := repoHost
189 if configHost == "" {
190 configHost = o.defaultHostname()
191 }
192 apiClient, err := o.apiClient(repoHost)
193 if err != nil {
194 return err
195 }
196 client := apiClient.Lab()
198 expirationDate := gitlab.ISOTime(o.expireAt)
200 var outputToken any
201 var outputTokenValue string
203 switch {
204 case o.self:
205 rotateOptions := &gitlab.RotatePersonalAccessTokenOptions{
206 ExpiresAt: &expirationDate,
207 }
208 token, _, err := client.PersonalAccessTokens.RotatePersonalAccessTokenSelf(rotateOptions, gitlab.WithContext(ctx))
209 if err != nil {
210 return err
211 }
212 outputToken = token
213 outputTokenValue = token.Token
214 case o.user != "":
215 user, err := api.UserByName(client, o.user)
216 if err != nil {
217 return cmdutils.FlagError{Err: err}
218 }
220 options := &gitlab.ListPersonalAccessTokensOptions{
221 ListOptions: gitlab.ListOptions{PerPage: 100},
222 UserID: &user.ID,
223 }
224 tokens, err := gitlab.ScanAndCollect(func(p gitlab.PaginationOptionFunc) ([]*gitlab.PersonalAccessToken, *gitlab.Response, error) {
225 return client.PersonalAccessTokens.ListPersonalAccessTokens(options, p, gitlab.WithContext(ctx))
226 })
227 if err != nil {
228 return err
229 }
230 var token *gitlab.PersonalAccessToken
231 tokens = filter.Filter(tokens, func(t *gitlab.PersonalAccessToken) bool {
232 return t.Active && (t.Name == o.name || t.ID == o.name)
233 })
234 switch len(tokens) {
235 case 1:
236 token = tokens[0]
237 case 0:
238 return cmdutils.FlagError{Err: fmt.Errorf("no active token found with the %s '%v'", o.nameKind(), o.name)}
239 default:
240 return cmdutils.FlagError{Err: fmt.Errorf("multiple tokens found with the name %q; use the ID instead", o.name)}
241 }
242 rotateOptions := &gitlab.RotatePersonalAccessTokenOptions{
243 ExpiresAt: &expirationDate,
244 }
245 token, _, err = client.PersonalAccessTokens.RotatePersonalAccessToken(token.ID, rotateOptions, gitlab.WithContext(ctx))
246 if err != nil {
247 return err
248 }
249 outputToken = token
250 outputTokenValue = token.Token
251 case o.group != "":
252 options := &gitlab.ListGroupAccessTokensOptions{ListOptions: gitlab.ListOptions{PerPage: 100}}
253 tokens, err := gitlab.ScanAndCollect(func(p gitlab.PaginationOptionFunc) ([]*gitlab.GroupAccessToken, *gitlab.Response, error) {
254 return client.GroupAccessTokens.ListGroupAccessTokens(o.group, options, p, gitlab.WithContext(ctx))
255 })
256 if err != nil {
257 return err
258 }
259 var token *gitlab.GroupAccessToken
260 tokens = filter.Filter(tokens, func(t *gitlab.GroupAccessToken) bool {
261 return t.Active && (t.Name == o.name || t.ID == o.name)
262 })
263 switch len(tokens) {
264 case 1:
265 token = tokens[0]
266 case 0:
267 return cmdutils.FlagError{Err: fmt.Errorf("no active token found with the %s '%v'", o.nameKind(), o.name)}
268 default:
269 return cmdutils.FlagError{Err: fmt.Errorf("multiple tokens found with the name '%v', use the ID instead", o.name)}
270 }
272 rotateOptions := &gitlab.RotateGroupAccessTokenOptions{
273 ExpiresAt: &expirationDate,
274 }
275 token, _, err = client.GroupAccessTokens.RotateGroupAccessToken(o.group, token.ID, rotateOptions, gitlab.WithContext(ctx))
276 if err != nil {
277 return err
278 }
279 outputToken = token
280 outputTokenValue = token.Token
281 default:
282 repo, err := o.baseRepo()
283 if err != nil {
284 return err
285 }
286 options := &gitlab.ListProjectAccessTokensOptions{ListOptions: gitlab.ListOptions{PerPage: 100}}
287 tokens, err := gitlab.ScanAndCollect(func(p gitlab.PaginationOptionFunc) ([]*gitlab.ProjectAccessToken, *gitlab.Response, error) {
288 return client.ProjectAccessTokens.ListProjectAccessTokens(repo.FullName(), options, p, gitlab.WithContext(ctx))
289 })
290 if err != nil {
291 return err
292 }
293 tokens = filter.Filter(tokens, func(t *gitlab.ProjectAccessToken) bool {
294 return t.Active && (t.Name == o.name || t.ID == o.name)
295 })
296 var token *gitlab.ProjectAccessToken
297 switch len(tokens) {
298 case 1:
299 token = tokens[0]
300 case 0:
301 return cmdutils.FlagError{Err: fmt.Errorf("no active token found with the %s '%v'", o.nameKind(), o.name)}
302 default:
303 return cmdutils.FlagError{Err: fmt.Errorf("multiple tokens found with the name '%v', use the ID instead", o.name)}
304 }
306 rotateOptions := &gitlab.RotateProjectAccessTokenOptions{
307 ExpiresAt: &expirationDate,
308 }
309 token, _, err = client.ProjectAccessTokens.RotateProjectAccessToken(repo.FullName(), token.ID, rotateOptions, gitlab.WithContext(ctx))
310 if err != nil {
311 return err
312 }
313 outputToken = token
314 outputTokenValue = token.Token
315 }
317 if o.outputFormat == "json" {
318 if err := o.io.PrintJSON(outputToken); err != nil {
319 return err
320 }
321 } else if _, err := fmt.Fprintln(o.io.StdOut, outputTokenValue); err != nil { //nolint:forbidigo // write error must propagate to the caller
322 return err
323 }
325 if o.self {
326 return o.storeRotatedToken(configHost, outputTokenValue)
327 }
329 return nil
330}
332// storeRotatedToken replaces the stored copy of the token that --self just
333// revoked, so the next command doesn't authenticate with it. It runs after the
334// new token is printed: a failed write must not lose the only copy.
335func (o *options) storeRotatedToken(host, newToken string) error {
336 cfg := o.config()
337 stored, source, err := cfg.GetWithSource(host, "token", true)
338 if err != nil {
339 return fmt.Errorf("could not store the new token for %s: %w; it was printed above", host, err)
340 }
341 if stored == "" {
342 return nil
343 }
345 if slices.Contains(config.EnvKeyEquivalence("token"), source) {
346 o.io.LogErrorf("%s The token for %s came from %s, so glab can't update it. Export the new token before the next command.\n", o.io.Color().WarnIcon(), host, source)
347 return nil
348 }
350 if err := cfg.Set(host, "token", newToken); err != nil {
351 return fmt.Errorf("could not store the new token for %s: %w; it was printed above", host, err)
352 }
353 if err := cfg.Write(); err != nil {
354 return fmt.Errorf("could not store the new token for %s: %w; it was printed above", host, err)
355 }
357 where := "config file"
358 if useKeyring, _ := cfg.Get(host, "use_keyring"); useKeyring == "true" {
359 where = "keyring"
360 }
361 o.io.LogErrorf("%s Updated the stored token for %s (%s).\n", o.io.Color().GreenCheck(), host, where)
362 return nil
363}
Diagnostics8 git calls · 208 ms
CallStatusSizeTime0208 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 · hit4 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=4 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 · 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=32926 git.response.cache=HIT git.response.duration_ms=2 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 · 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=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=218b543e075f31e84c52193d193103408c52cb34 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=fbb77d44047cd3e1ee682eb9483227c59489e50fOpen 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=af225ea2432d7fff1c2afd415d9aa91b45507f7a 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=dfb59e832d53de2ef63e61029c585106e9af59ebOpen pack map
fetch2003.8 KiB192 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=192 git.response.bytes=3847 git.response.cache=MISS git.response.duration_ms=192 git.fetch.wants=b8ebcbd01057a013e49b5dbc41393b2bd1b55d03 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=3847 git.pkt.payload.max=3820 git.sideband.band1.bytes=3820 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
- a5e2ea3cc8534bc2
- Request
- e13d8ade…
- 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