package rotate import ( "context" "errors" "fmt" "slices" "strconv" "time" "github.com/MakeNowJust/heredoc/v2" "github.com/spf13/cobra" gitlab "gitlab.com/gitlab-org/api/client-go/v3" "gitlab.com/gitlab-org/cli/internal/api" "gitlab.com/gitlab-org/cli/internal/cmdutils" "gitlab.com/gitlab-org/cli/internal/cmdutils/tokenduration" "gitlab.com/gitlab-org/cli/internal/commands/token/expirationdate" "gitlab.com/gitlab-org/cli/internal/commands/token/filter" "gitlab.com/gitlab-org/cli/internal/commands/token/tokenutils" "gitlab.com/gitlab-org/cli/internal/config" "gitlab.com/gitlab-org/cli/internal/glrepo" "gitlab.com/gitlab-org/cli/internal/iostreams" "gitlab.com/gitlab-org/cli/internal/mcpannotations" ) type options struct { apiClient func(repoHost string) (*api.Client, error) config func() config.Config io *iostreams.IOStreams baseRepo func() (glrepo.Interface, error) defaultHostname func() string user string group string self bool name any duration tokenduration.TokenDuration expireAt expirationdate.ExpirationDate outputFormat string } func NewCmdRotate(f cmdutils.Factory) *cobra.Command { opts := &options{ io: f.IO(), apiClient: f.ApiClient, config: f.Config, baseRepo: f.BaseRepo, defaultHostname: f.DefaultHostname, duration: tokenduration.TokenDuration(30 * 24 * time.Hour), // Default: 30 days } cmd := &cobra.Command{ Use: "rotate []", Short: "Rotate user, group, or project access tokens.", Aliases: []string{"rot"}, Args: cobra.MaximumNArgs(1), ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]cobra.Completion, cobra.ShellCompDirective) { if self, err := cmd.Flags().GetBool("self"); err == nil && self { return nil, cobra.ShellCompDirectiveNoFileComp } return tokenutils.NameOrIDCompletions(cmd.Context(), f, cmd, args, toComplete) }, Long: heredoc.Docf(` Rotating a token revokes the existing token and creates a new one with a new secret value and expiration date. The old token stops working immediately, so you must update any client that uses it with the new value that this command returns. If multiple tokens share the same name, specify the token ID to select the correct one. The token expires at 00:00 UTC on a date calculated by adding the duration to today's date. The default duration is 30 days. You can specify a different duration in days (%[1]sd%[1]s), weeks (%[1]sw%[1]s), or hours (%[1]sh%[1]s). The %[1]s--duration%[1]s and %[1]s--expires-at%[1]s flags are mutually exclusive. Administrators can rotate personal access tokens that belong to other users. Use %[1]s--self%[1]s to rotate the token currently used for authentication. This command requires GitLab 17.9 or later. 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. `, "`"), Example: heredoc.Doc(` # Rotate project access token of current project (default 30 days) glab token rotate my-project-token # Rotate project access token with explicit expiration date glab token rotate --repo user/repo my-project-token --expires-at 2025-08-08 # Rotate group access token with 7 day lifetime glab token rotate --group group/sub-group my-group-token --duration 7d # Rotate personal access token with 2 week lifetime glab token rotate --user @me my-personal-token --duration 2w # Rotate a personal access token of another user (administrator only) glab token rotate --user johndoe johns-personal-token --duration 90d # Rotate the current authentication token glab token rotate --self --duration 90d`), Annotations: map[string]string{ mcpannotations.Exclude: "true", }, RunE: func(cmd *cobra.Command, args []string) error { if err := opts.complete(cmd, args); err != nil { return err } if err := opts.validate(); err != nil { return err } return opts.run(cmd.Context()) }, } cmdutils.EnableRepoOverride(cmd, f) fl := cmd.Flags() fl.StringVarP(&opts.group, "group", "g", "", "Rotate group access token. Ignored if a user or repository argument is set.") cobra.CheckErr(cmd.RegisterFlagCompletionFunc("group", tokenutils.GroupCompletions)) fl.StringVarP(&opts.user, "user", "U", "", "Rotate personal access token. Use @me for the current user.") cobra.CheckErr(cmd.RegisterFlagCompletionFunc("user", tokenutils.UserCompletions)) fl.BoolVar(&opts.self, "self", false, "Rotate the access token currently used for authentication.") 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.") cobra.CheckErr(cmd.RegisterFlagCompletionFunc("duration", cobra.NoFileCompletions)) 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.") cobra.CheckErr(cmd.RegisterFlagCompletionFunc("expires-at", cobra.NoFileCompletions)) cmdutils.EnableJSONOutput(cmd, opts.io, &opts.outputFormat, "Format output as: text, json. 'text' provides the new token value; 'json' outputs the token with metadata.") cmd.MarkFlagsMutuallyExclusive("duration", "expires-at") cmd.MarkFlagsMutuallyExclusive("self", "user") cmd.MarkFlagsMutuallyExclusive("self", "group") return cmd } func (o *options) complete(cmd *cobra.Command, args []string) error { if len(args) > 0 { if name, err := strconv.ParseInt(args[0], 10, 64); err != nil { o.name = args[0] } else { o.name = name } } if group, err := cmdutils.GroupOverride(cmd); err != nil { return err } else { o.group = group } if time.Time(o.expireAt).IsZero() { o.expireAt = expirationdate.ExpirationDate(o.duration.CalculateExpirationDate()) } return nil } func (o *options) nameKind() string { if _, ok := o.name.(int64); ok { return "ID" } return "name" } func (o *options) validate() error { if o.group != "" && o.user != "" { return cmdutils.FlagError{Err: errors.New("'--group' and '--user' are mutually exclusive")} } if o.self && o.name != nil { return cmdutils.FlagError{Err: errors.New("'--self' does not accept a positional argument")} } if !o.self && o.name == nil { return cmdutils.FlagError{Err: errors.New("requires either '--self' or a token name/ID argument")} } return nil } func (o *options) run(ctx context.Context) error { // NOTE: this command can not only be used for projects, // so we have to manually check for the base repo, if it doesn't exist, // we bootstrap the client with the default hostname. var repoHost string if baseRepo, err := o.baseRepo(); err == nil { repoHost = baseRepo.RepoHost() } configHost := repoHost if configHost == "" { configHost = o.defaultHostname() } apiClient, err := o.apiClient(repoHost) if err != nil { return err } client := apiClient.Lab() expirationDate := gitlab.ISOTime(o.expireAt) var outputToken any var outputTokenValue string switch { case o.self: rotateOptions := &gitlab.RotatePersonalAccessTokenOptions{ ExpiresAt: &expirationDate, } token, _, err := client.PersonalAccessTokens.RotatePersonalAccessTokenSelf(rotateOptions, gitlab.WithContext(ctx)) if err != nil { return err } outputToken = token outputTokenValue = token.Token case o.user != "": user, err := api.UserByName(client, o.user) if err != nil { return cmdutils.FlagError{Err: err} } options := &gitlab.ListPersonalAccessTokensOptions{ ListOptions: gitlab.ListOptions{PerPage: 100}, UserID: &user.ID, } tokens, err := gitlab.ScanAndCollect(func(p gitlab.PaginationOptionFunc) ([]*gitlab.PersonalAccessToken, *gitlab.Response, error) { return client.PersonalAccessTokens.ListPersonalAccessTokens(options, p, gitlab.WithContext(ctx)) }) if err != nil { return err } var token *gitlab.PersonalAccessToken tokens = filter.Filter(tokens, func(t *gitlab.PersonalAccessToken) bool { return t.Active && (t.Name == o.name || t.ID == o.name) }) switch len(tokens) { case 1: token = tokens[0] case 0: return cmdutils.FlagError{Err: fmt.Errorf("no active token found with the %s '%v'", o.nameKind(), o.name)} default: return cmdutils.FlagError{Err: fmt.Errorf("multiple tokens found with the name %q; use the ID instead", o.name)} } rotateOptions := &gitlab.RotatePersonalAccessTokenOptions{ ExpiresAt: &expirationDate, } token, _, err = client.PersonalAccessTokens.RotatePersonalAccessToken(token.ID, rotateOptions, gitlab.WithContext(ctx)) if err != nil { return err } outputToken = token outputTokenValue = token.Token case o.group != "": options := &gitlab.ListGroupAccessTokensOptions{ListOptions: gitlab.ListOptions{PerPage: 100}} tokens, err := gitlab.ScanAndCollect(func(p gitlab.PaginationOptionFunc) ([]*gitlab.GroupAccessToken, *gitlab.Response, error) { return client.GroupAccessTokens.ListGroupAccessTokens(o.group, options, p, gitlab.WithContext(ctx)) }) if err != nil { return err } var token *gitlab.GroupAccessToken tokens = filter.Filter(tokens, func(t *gitlab.GroupAccessToken) bool { return t.Active && (t.Name == o.name || t.ID == o.name) }) switch len(tokens) { case 1: token = tokens[0] case 0: return cmdutils.FlagError{Err: fmt.Errorf("no active token found with the %s '%v'", o.nameKind(), o.name)} default: return cmdutils.FlagError{Err: fmt.Errorf("multiple tokens found with the name '%v', use the ID instead", o.name)} } rotateOptions := &gitlab.RotateGroupAccessTokenOptions{ ExpiresAt: &expirationDate, } token, _, err = client.GroupAccessTokens.RotateGroupAccessToken(o.group, token.ID, rotateOptions, gitlab.WithContext(ctx)) if err != nil { return err } outputToken = token outputTokenValue = token.Token default: repo, err := o.baseRepo() if err != nil { return err } options := &gitlab.ListProjectAccessTokensOptions{ListOptions: gitlab.ListOptions{PerPage: 100}} tokens, err := gitlab.ScanAndCollect(func(p gitlab.PaginationOptionFunc) ([]*gitlab.ProjectAccessToken, *gitlab.Response, error) { return client.ProjectAccessTokens.ListProjectAccessTokens(repo.FullName(), options, p, gitlab.WithContext(ctx)) }) if err != nil { return err } tokens = filter.Filter(tokens, func(t *gitlab.ProjectAccessToken) bool { return t.Active && (t.Name == o.name || t.ID == o.name) }) var token *gitlab.ProjectAccessToken switch len(tokens) { case 1: token = tokens[0] case 0: return cmdutils.FlagError{Err: fmt.Errorf("no active token found with the %s '%v'", o.nameKind(), o.name)} default: return cmdutils.FlagError{Err: fmt.Errorf("multiple tokens found with the name '%v', use the ID instead", o.name)} } rotateOptions := &gitlab.RotateProjectAccessTokenOptions{ ExpiresAt: &expirationDate, } token, _, err = client.ProjectAccessTokens.RotateProjectAccessToken(repo.FullName(), token.ID, rotateOptions, gitlab.WithContext(ctx)) if err != nil { return err } outputToken = token outputTokenValue = token.Token } if o.outputFormat == "json" { if err := o.io.PrintJSON(outputToken); err != nil { return err } } else if _, err := fmt.Fprintln(o.io.StdOut, outputTokenValue); err != nil { //nolint:forbidigo // write error must propagate to the caller return err } if o.self { return o.storeRotatedToken(configHost, outputTokenValue) } return nil } // storeRotatedToken replaces the stored copy of the token that --self just // revoked, so the next command doesn't authenticate with it. It runs after the // new token is printed: a failed write must not lose the only copy. func (o *options) storeRotatedToken(host, newToken string) error { cfg := o.config() stored, source, err := cfg.GetWithSource(host, "token", true) if err != nil { return fmt.Errorf("could not store the new token for %s: %w; it was printed above", host, err) } if stored == "" { return nil } if slices.Contains(config.EnvKeyEquivalence("token"), source) { 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) return nil } if err := cfg.Set(host, "token", newToken); err != nil { return fmt.Errorf("could not store the new token for %s: %w; it was printed above", host, err) } if err := cfg.Write(); err != nil { return fmt.Errorf("could not store the new token for %s: %w; it was printed above", host, err) } where := "config file" if useKeyring, _ := cfg.Get(host, "use_keyring"); useKeyring == "true" { where = "keyring" } o.io.LogErrorf("%s Updated the stored token for %s (%s).\n", o.io.Color().GreenCheck(), host, where) return nil }