GitLabgitlab-org
cli
main
1package rotate
3import (
4 "context"
5 "time"
7 "github.com/MakeNowJust/heredoc/v2"
8 "github.com/spf13/cobra"
10 gitlab "gitlab.com/gitlab-org/api/client-go/v3"
12 "gitlab.com/gitlab-org/cli/internal/api"
13 "gitlab.com/gitlab-org/cli/internal/cmdutils"
14 "gitlab.com/gitlab-org/cli/internal/cmdutils/tokenduration"
15 "gitlab.com/gitlab-org/cli/internal/commands/service-account/serviceaccountutils"
16 "gitlab.com/gitlab-org/cli/internal/glrepo"
17 "gitlab.com/gitlab-org/cli/internal/iostreams"
18 "gitlab.com/gitlab-org/cli/internal/mcpannotations"
19)
21type options struct {
22 io *iostreams.IOStreams
23 apiClient func(repoHost string) (*api.Client, error)
24 baseRepo func() (glrepo.Interface, error)
26 account string
27 token string
28 duration tokenduration.TokenDuration
29 expiresAt time.Time
30 expiresAtSet bool
31 group string
32 outputFormat string
33}
35func NewCmd(f cmdutils.Factory) *cobra.Command {
36 opts := &options{
37 io: f.IO(),
38 apiClient: f.ApiClient,
39 baseRepo: f.BaseRepo,
40 duration: tokenduration.TokenDuration(30 * 24 * time.Hour),
41 }
43 cmd := &cobra.Command{
44 Use: "rotate <account-id | username> <token-id | name> [flags]",
45 Short: "Rotate a token of a service account.",
46 Args: cobra.ExactArgs(2),
47 ValidArgsFunction: cobra.NoFileCompletions,
48 Long: heredoc.Docf(`
49 Rotate a personal access token of a service account of a project or a group.
51 - Rotating revokes the token and creates a new one with the same name, description, and scopes. Anything using the old value stops working immediately.
52 - The new token value is printed only once and cannot be retrieved later. It is the only output on stdout, and the token details go to stderr.
53 - The new token expires after %[1]s--duration%[1]s, 30 days by default, at 00:00 UTC. Use %[1]s--expires-at%[1]s for a specific date instead.
54 - A token name matches active tokens only. If several active tokens share the name, use the token ID instead.
55 - Numeric arguments are always treated as IDs. Token IDs and names come from %[1]sglab service-account token list%[1]s.
57 Finding a token by name for a group service account requires GitLab 17.11 or later.
58 `, "`"),
59 Example: heredoc.Doc(`
60 # Rotate token 7 of service account 42 of the current project
61 glab service-account token rotate 42 7
63 # Rotate a token by its name for 90 days, finding the account by its username
64 glab service-account token rotate release-bot ci --duration 90d
66 # Rotate a token of a group's service account until the end of 2027
67 glab service-account token rotate 42 7 --expires-at 2027-12-31 --group my-group
69 # Rotate a token and store the new value in a variable
70 TOKEN=$(glab service-account token rotate 42 ci)`),
71 Annotations: map[string]string{
72 // Rotating a token prints a secret, so this command is kept out of MCP,
73 // as glab token rotate is.
74 mcpannotations.Exclude: "true",
75 },
76 RunE: func(cmd *cobra.Command, args []string) error {
77 if err := opts.complete(cmd, args); err != nil {
78 return err
79 }
81 return opts.run(cmd.Context())
82 },
83 }
85 cmdutils.EnableRepoOverride(cmd, f)
87 fl := cmd.Flags()
88 fl.StringVarP(&opts.group, "group", "g", "", "Rotate a token of a service account of a `group` instead of a project. Accepts a group ID or full path.")
89 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 midnight UTC on the calculated date.")
90 fl.TimeVarP(&opts.expiresAt, "expires-at", "E", time.Time{}, []string{time.DateOnly}, "Expiry date of the new token, as YYYY-MM-DD. The token expires at midnight UTC on that date.")
92 cmdutils.EnableJSONOutput(cmd, opts.io, &opts.outputFormat, "Format output as 'text' for the token value, 'json' for the token with its details.")
93 cmd.MarkFlagsMutuallyExclusive("duration", "expires-at")
94 cmd.MarkFlagsMutuallyExclusive("repo", "group")
96 return cmd
97}
99func (o *options) complete(cmd *cobra.Command, args []string) error {
100 o.account = args[0]
101 o.token = args[1]
102 o.expiresAtSet = cmd.Flags().Changed("expires-at")
104 group, err := cmdutils.GroupOverride(cmd)
105 if err != nil {
106 return err
107 }
108 o.group = group
110 return nil
111}
113func (o *options) run(ctx context.Context) error {
114 client, scope, err := serviceaccountutils.NewClient(o.baseRepo, o.apiClient, o.group)
115 if err != nil {
116 return err
117 }
119 accountID, err := serviceaccountutils.ResolveID(ctx, client, scope, o.account)
120 if err != nil {
121 return cmdutils.WrapError(err, "failed to rotate service account token")
122 }
124 tokenID, err := serviceaccountutils.ResolveTokenID(ctx, client, scope, accountID, o.token)
125 if err != nil {
126 return cmdutils.WrapError(err, "failed to rotate service account token")
127 }
129 expiry := o.duration.CalculateExpirationDate()
130 if o.expiresAtSet {
131 expiry = o.expiresAt
132 }
133 expiresAt := new(gitlab.ISOTime(expiry))
135 var token *gitlab.PersonalAccessToken
136 if scope.Group != "" {
137 token, _, err = client.Groups.RotateServiceAccountPersonalAccessToken(scope.Group, accountID, tokenID, &gitlab.RotateServiceAccountPersonalAccessTokenOptions{
138 ExpiresAt: expiresAt,
139 }, gitlab.WithContext(ctx))
140 } else {
141 token, _, err = client.Projects.RotateProjectServiceAccountPersonalAccessToken(scope.Project, accountID, tokenID, &gitlab.RotateProjectServiceAccountPersonalAccessTokenOptions{
142 ExpiresAt: expiresAt,
143 }, gitlab.WithContext(ctx))
144 }
145 if err != nil {
146 return cmdutils.WrapError(err, "failed to rotate service account token")
147 }
149 if o.outputFormat == "json" {
150 return o.io.PrintJSON(token)
151 }
153 if err := serviceaccountutils.PrintToken(o.io, token); err != nil {
154 return err
155 }
156 o.io.LogErrorf("%s Rotated token %d of service account %d in %s into token %d. Store the token value now. It is not shown again.\n", o.io.Color().WarnIcon(), tokenID, accountID, scope, token.ID)
158 return nil
159}
Diagnostics9 git calls · 219 ms
CallStatusSizeTime0219 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=3 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.8 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=1857 git.response.cache=HIT git.response.duration_ms=4 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:0200322 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=322 git.response.cache=HIT git.response.duration_ms=2 git.fetch.filter=tree:0 git.fetch.wants=ba2caccf6c55211c6b29b98f40c2358479d91b1f 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=322 git.pkt.payload.max=295 git.sideband.band1.bytes=295 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0 git.pack.objects=1 git.pack.bytes=295 git.pack.trailer=3488e558d4708096e879feba968e084c249dbe22Open pack map
fetchtree:0200223 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=223 git.response.cache=HIT git.response.duration_ms=3 git.fetch.filter=tree:0 git.fetch.wants=41d72d07155f99e3acc572f8fe5ad26c802e4ddc 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=223 git.pkt.payload.max=196 git.sideband.band1.bytes=196 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0 git.pack.objects=1 git.pack.bytes=196 git.pack.trailer=d9c58aac50f427eb21501a81fe28c81c7c49ae44Open 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=d264b3875ee1acf022000760e2b7fc444284f0af 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=ddb4ccc30fa55adee2cda1366700c19af506815fOpen pack map
fetch2002.2 KiB200 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=200 git.response.bytes=2287 git.response.cache=MISS git.response.duration_ms=200 git.fetch.wants=20c72d5d9d936ebc29c1aaf1f228c21bfd4033f2 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=2287 git.pkt.payload.max=2260 git.sideband.band1.bytes=2260 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
- a5e35e9d0ec35cd4
- Request
- e8924479…
- 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