mirror of
https://github.com/hanzoai/team.git
synced 2026-09-30 01:57:35 +00:00
* MM-68417, MM-68420: API support for PAT expiry and admin policy settings
POST /users/{id}/tokens now accepts a client-supplied expires_at
(previously stripped per the TODO in api4/user.go), and the create app
method enforces two new ServiceSettings:
- EnforcePersonalAccessTokenExpiry (bool, default false): when on,
rejects creates with expires_at == 0
- MaximumPersonalAccessTokenLifetimeDays (int, default 0 = unlimited):
caps how far in the future expires_at may be
Rejections return distinct app error ids so clients can disambiguate:
expires_at_required, expires_at_in_past, expires_at_too_far.
GET /users/{id}/tokens already serializes expires_at via the model's
JSON tag added in MM-68419; clients derive token status (active /
expired / inactive) from is_active + expires_at without a separate
server-side field, keeping the response shape minimal.
The Client4 helper CreateUserAccessToken gained an optional variadic
expiresAt parameter (and the mmctl Client interface + mock match)
rather than introducing a parallel WithExpiry method.
Refs: MM-68417, MM-68420
* MM-68417: exempt bot accounts from PAT expiry enforcement
Mirrors the existing EnableUserAccessTokens bypass at session.go:453,
where bot tokens are allowed even when human PATs are disabled. Bots
are programmatic clients that typically need long-lived credentials,
and integrations that provision them would otherwise break the moment
an admin enables EnforcePersonalAccessTokenExpiry — turning a settings
toggle into a footgun. The expiry policy now applies only to human
users; bots can still be given a future expires_at by callers that
want it, but the server won't require one.
Locked in by a new TestCreateUserAccessToken/bot_tokens_are_exempt
subtest that enables enforcement plus a 30-day cap, creates a bot,
and asserts a non-expiring token is accepted.
Refs: MM-68417
* MM-68420: bound MaximumPersonalAccessTokenLifetimeDays in isValid
Negative values silently meant "unlimited" (the runtime check is `> 0`),
and very large values overflow int64 when computing
`now + days*86_400_000` at token-creation time, producing a wrap-around
that either rejects all reasonable expiries or accepts past timestamps
as valid.
Bound the setting in ServiceSettings.isValid to [0, MaxPersonalAccess
TokenLifetimeDays] where the cap is 36500 (100 years) — past any
realistic operational use and well clear of int64 overflow. Surfaces
as a config validation error rather than a silently-broken runtime
check. New TestServiceSettingsIsValid cases lock in zero, negative,
upper-bound, and above-upper-bound behavior.
Refs: MM-68420
* MM-68417: reject multiple expiresAt values in Client4 helper
CodeRabbit caught that the variadic CreateUserAccessToken silently used
expiresAt[0] when callers passed more than one value, masking a
mis-call instead of failing fast. Return an error in that case so the
misuse is visible at the call site rather than producing a token with
the wrong (or right-but-coincidental) expiry.
Refs: MM-68417
* MM-68417: make expiresAt a required parameter on Client4.CreateUserAccessToken
Drop the variadic in favor of a regular int64 parameter. The variadic
form silently dropped extra values and made a misuse undetectable at
the call site (per CodeRabbit review on PR 36706); the previous fix
guarded against >1 values at runtime, but a required parameter is
strictly better — the compiler now refuses the misuse and every caller
is forced to make a deliberate decision about expiry. Existing callers
that want the old behavior pass 0 (== never expires).
Refs: MM-68417
* MM-68417: add --expires-in flag to mmctl user token generate
Adds an --expires-in duration flag so operators can create expiring
PATs via the CLI. Accepts the standard Go duration syntax plus a
trailing 'd' for days (the common case for token lifetimes), e.g.
--expires-in 90d, --expires-in 12h, --expires-in 1h30m. Empty (the
default) means no expiry — matching prior behavior. Without this
flag the command was unusable once an admin enables
EnforcePersonalAccessTokenExpiry, since every create would fail with
app.user_access_token.expires_at_required.app_error.
Flag parsing now happens before the user-lookup API call so the
command fails fast on invalid input. Regenerated mmctl docs reflect
the new flag.
Refs: MM-68417
* MM-68417: cap --expires-in day count to prevent time.Duration overflow
parseExpiresIn returns time.Duration(days) * 24 * time.Hour, which is
int64 nanoseconds and overflows past ~106751 days (CodeRabbit caught
this). Cap at model.MaxPersonalAccessTokenLifetimeDays (36500) so the
CLI rejects values the server would reject anyway, well below the
int64-overflow point. Adds two test cases (at-cap and beyond-cap) to
TestParseExpiresIn.
Refs: MM-68417
* MM-68420: collapse PAT expiry settings into a single max-lifetime setting
Remove ServiceSettings.EnforcePersonalAccessTokenExpiry and fold the
policy onto MaximumPersonalAccessTokenLifetimeDays: 0 means no policy
(never-expiring tokens allowed, no cap), while a value > 0 requires every
new token to expire within that many days. The two-setting design let an
admin set a maximum but leave enforcement off, silently allowing
never-expiring tokens to sidestep the cap; the only combination the
boolean added (require expiry, no upper bound) has little practical
value. The removed field was introduced on this branch and never
released, so this is not a breaking change.
---------
Co-authored-by: Hanzo Dev <[email protected]>
188 lines
5.9 KiB
Go
188 lines
5.9 KiB
Go
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
|
|
// See LICENSE.txt for license information.
|
|
|
|
package commands
|
|
|
|
import (
|
|
"context"
|
|
"net/http"
|
|
"strconv"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/mattermost/mattermost/server/public/model"
|
|
"github.com/mattermost/mattermost/server/v8/cmd/mmctl/client"
|
|
"github.com/mattermost/mattermost/server/v8/cmd/mmctl/printer"
|
|
|
|
"github.com/pkg/errors"
|
|
"github.com/spf13/cobra"
|
|
)
|
|
|
|
var TokenCmd = &cobra.Command{
|
|
Use: "token",
|
|
Short: "manage users' access tokens",
|
|
}
|
|
|
|
var GenerateUserTokenCmd = &cobra.Command{
|
|
Use: "generate [user] [description]",
|
|
Short: "Generate token for a user",
|
|
Long: "Generate token for a user. Use --expires-in to set an expiry, which may be required by " +
|
|
"the server's MaximumPersonalAccessTokenLifetimeDays setting.",
|
|
Example: ` generate testuser test-token
|
|
generate testuser ci-token --expires-in 90d
|
|
generate testuser short-lived --expires-in 12h`,
|
|
RunE: withClient(generateTokenForAUserCmdF),
|
|
Args: cobra.ExactArgs(2),
|
|
}
|
|
|
|
var RevokeUserTokenCmd = &cobra.Command{
|
|
Use: "revoke [token-ids]",
|
|
Short: "Revoke tokens for a user",
|
|
Long: "Revoke tokens for a user",
|
|
Example: " revoke testuser test-token-id",
|
|
RunE: withClient(revokeTokenForAUserCmdF),
|
|
Args: cobra.MinimumNArgs(1),
|
|
}
|
|
|
|
var ListUserTokensCmd = &cobra.Command{
|
|
Use: "list [user]",
|
|
Short: "List users tokens",
|
|
Long: "List the tokens of a user",
|
|
Example: " user tokens testuser",
|
|
RunE: withClient(listTokensOfAUserCmdF),
|
|
Args: cobra.ExactArgs(1),
|
|
}
|
|
|
|
func init() {
|
|
GenerateUserTokenCmd.Flags().String("expires-in", "", "Duration after which the token expires (e.g. 90d, 12h, 30m). Accepts the standard Go duration syntax plus a 'd' (days) suffix. If empty, the token does not expire.")
|
|
|
|
ListUserTokensCmd.Flags().Int("page", 0, "Page number to fetch for the list of users")
|
|
ListUserTokensCmd.Flags().Int("per-page", DefaultPageSize, "Number of users to be fetched")
|
|
ListUserTokensCmd.Flags().Bool("all", false, "Fetch all tokens. --page flag will be ignore if provided")
|
|
ListUserTokensCmd.Flags().Bool("active", true, "List only active tokens")
|
|
ListUserTokensCmd.Flags().Bool("inactive", false, "List only inactive tokens")
|
|
|
|
TokenCmd.AddCommand(
|
|
GenerateUserTokenCmd,
|
|
RevokeUserTokenCmd,
|
|
ListUserTokensCmd,
|
|
)
|
|
|
|
RootCmd.AddCommand(
|
|
TokenCmd,
|
|
)
|
|
}
|
|
|
|
func generateTokenForAUserCmdF(c client.Client, command *cobra.Command, args []string) error {
|
|
expiresAt, err := resolveTokenExpiry(command)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
userArg := args[0]
|
|
user := getUserFromUserArg(c, userArg)
|
|
if user == nil {
|
|
return errors.Errorf("could not retrieve user information of %q", userArg)
|
|
}
|
|
|
|
token, _, err := c.CreateUserAccessToken(context.TODO(), user.Id, args[1], expiresAt)
|
|
if err != nil {
|
|
return errors.Errorf("could not create token for %q: %s", userArg, err.Error())
|
|
}
|
|
printer.PrintT("{{.Token}}: {{.Description}}", token)
|
|
|
|
return nil
|
|
}
|
|
|
|
// resolveTokenExpiry converts the --expires-in flag into a Unix-millis timestamp
|
|
// suitable for UserAccessToken.ExpiresAt. Returns 0 when the flag is empty,
|
|
// meaning the token does not expire (subject to server policy).
|
|
func resolveTokenExpiry(command *cobra.Command) (int64, error) {
|
|
raw, _ := command.Flags().GetString("expires-in")
|
|
raw = strings.TrimSpace(raw)
|
|
if raw == "" {
|
|
return 0, nil
|
|
}
|
|
d, err := parseExpiresIn(raw)
|
|
if err != nil {
|
|
return 0, errors.Wrap(err, "invalid --expires-in value")
|
|
}
|
|
if d <= 0 {
|
|
return 0, errors.Errorf("--expires-in must be positive, got %q", raw)
|
|
}
|
|
return time.Now().Add(d).UnixMilli(), nil
|
|
}
|
|
|
|
// parseExpiresIn accepts a duration string. In addition to the standard Go
|
|
// duration syntax (e.g. "12h", "30m"), a trailing "d" is interpreted as days
|
|
// — the common case for token lifetimes which stdlib's time.ParseDuration
|
|
// does not support.
|
|
func parseExpiresIn(s string) (time.Duration, error) {
|
|
if prefix, ok := strings.CutSuffix(s, "d"); ok {
|
|
days, err := strconv.Atoi(prefix)
|
|
if err != nil {
|
|
return 0, errors.Errorf("%q is not a valid day count", s)
|
|
}
|
|
// time.Duration is int64 nanoseconds; days * 24h overflows past ~106751.
|
|
// Cap at the server-side bound so the CLI rejects values that the server
|
|
// would reject anyway, well below the int64-overflow point.
|
|
if days > model.MaxPersonalAccessTokenLifetimeDays {
|
|
return 0, errors.Errorf("%q exceeds maximum supported day count of %d", s, model.MaxPersonalAccessTokenLifetimeDays)
|
|
}
|
|
return time.Duration(days) * 24 * time.Hour, nil
|
|
}
|
|
return time.ParseDuration(s)
|
|
}
|
|
|
|
func listTokensOfAUserCmdF(c client.Client, command *cobra.Command, args []string) error {
|
|
page, _ := command.Flags().GetInt("page")
|
|
perPage, _ := command.Flags().GetInt("per-page")
|
|
showAll, _ := command.Flags().GetBool("all")
|
|
active, _ := command.Flags().GetBool("active")
|
|
inactive, _ := command.Flags().GetBool("inactive")
|
|
|
|
if showAll {
|
|
page = 0
|
|
perPage = 9999
|
|
}
|
|
|
|
userArg := args[0]
|
|
|
|
user := getUserFromUserArg(c, userArg)
|
|
if user == nil {
|
|
return errors.Errorf("could not retrieve user information of %q", userArg)
|
|
}
|
|
|
|
tokens, _, err := c.GetUserAccessTokensForUser(context.TODO(), user.Id, page, perPage)
|
|
if err != nil {
|
|
return errors.Errorf("could not retrieve tokens for user %q: %s", userArg, err.Error())
|
|
}
|
|
|
|
if len(tokens) == 0 {
|
|
return errors.Errorf("there are no tokens for the %q", userArg)
|
|
}
|
|
|
|
for _, t := range tokens {
|
|
if t.IsActive && !inactive {
|
|
printer.PrintT("{{.Id}}: {{.Description}}", t)
|
|
}
|
|
if !t.IsActive && !active {
|
|
printer.PrintT("{{.Id}}: {{.Description}}", t)
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func revokeTokenForAUserCmdF(c client.Client, command *cobra.Command, args []string) error {
|
|
for _, id := range args {
|
|
res, err := c.RevokeUserAccessToken(context.TODO(), id)
|
|
if err != nil {
|
|
return errors.Errorf("could not revoke token %q: %s", id, err.Error())
|
|
}
|
|
if res.StatusCode != http.StatusOK {
|
|
return errors.Errorf("could not revoke token %q", id)
|
|
}
|
|
}
|
|
return nil
|
|
}
|