mirror of
https://github.com/hanzoai/team.git
synced 2026-11-01 07:55:31 +00:00
* MM-69561: Add ability to rotate (regenerate) Personal Access Tokens - Add UpdateTokenRotate to UserAccessTokenStore interface and implement in sqlstore: deletes sessions on the old secret, then updates the token row with the new secret and expiry in one transaction - Regenerate store retrylayer, timerlayer, and mocks - Add RotateUserAccessToken app method: validates expiry (bot-exempt), captures old session for cache eviction, generates new secret, and sends a notification email - Register POST /api/v4/users/tokens/rotate handler with full permission checks (create_user_access_token + edit_other_users + manage_system for sysadmin targets); rejects OAuth sessions and disabled tokens - Add RotateUserAccessToken to the Go client (client4.go) - Add storetest covering secret rotation and old-session cleanup - Add API4 tests: happy path, permission denials, OAuth rejection, and max-lifetime enforcement * MM-69561: Add dedicated rotate email and i18n strings - Add SendUserAccessTokenRotatedEmail (subject/body distinct from the 'added' email so users aren't confused by a rotation event) - Add SendUserAccessTokenRotatedEmail to ServiceInterface + mock - Add en.json strings for the rotate email and the two new error ids (rotate.app_error, disabled_token.app_error) - Switch RotateUserAccessToken to call SendUserAccessTokenRotatedEmail * MM-69561: Add mmctl token rotate subcommand - Add RotateUserAccessToken to the mmctl Client interface and mock - Add 'mmctl token rotate <token-id> [--expires-in <duration>]' command reusing the existing resolveTokenExpiry/parseExpiresIn helpers from 'generate'; prints the new secret once on success - Add unit tests: happy path, --expires-in passed through, server error, invalid --expires-in * MM-69561: Regenerate mmctl docs for token rotate * MM-69561: Add API docs for POST /users/tokens/rotate * MM-69561: Fix i18n string ordering after extract * MM-69561: Add missing API4 test cases for token rotate Cover the three untested access-control branches flagged by the test analysis bot: - Rotating a disabled token returns 400 - Non-system-admin rotating a sysadmin's token returns 403 - Rotating a remote user's token returns 403 * MM-69561: Address review comments - Fix handler authorization order: check SessionHasPermissionToUserOrBot and manage_system before IsRemote/IsActive to avoid leaking token state to unauthorized callers; matches revokeUserAccessToken/disableUserAccessToken - Fix API docs minimum server version: 10.8 -> 10.10 * MM-69561: Restore i18n strings accidentally deleted by extract The earlier i18n-extract run stripped ~164 unrelated translation keys (mostly enterprise-only strings like app.pap.* and api.ldap.*) because the enterprise codebase isn't present in this checkout, so the extractor treated them as unused. Restore them while keeping the 5 new keys added for token rotation. * comment * [MM-69561] Add webapp Regenerate option for Personal Access Tokens Adds a "Regenerate" link to Account Settings > Security > Personal Access Tokens that calls the POST /users/tokens/rotate endpoint added in the server-side rotate PAT work. Regenerating shows a confirmation modal naming the token, then reveals the new secret via the existing one-time-copy flow used for token creation. - webapp Client4.rotateUserAccessToken - mattermost-redux rotateUserAccessToken action - Regenerate link/confirm modal/reveal flow in user_access_token_section - i18n strings - Playwright e2e coverage * Fix regenerate PAT e2e test: confirm modal is not nested in the Profile dialog ConfirmModal renders via react-bootstrap's Modal, which portals to document.body as a sibling of the Profile dialog rather than a descendant, so it must be located via #confirmModal on the page instead of scoped to the Profile dialog locator. * Let users pick a new expiry when regenerating a Personal Access Token Previously, regenerating a token always called rotateUserAccessToken with no expiresAt, so the rotated secret never expired even if the original token did. The Regenerate confirmation modal now includes the same expiry picker used by token creation (extracted into a shared renderExpiryPicker helper), enforces MaximumPersonalAccessTokenLifetimeDays the same way, and disables the confirm button until a valid expiry is selected. * Scope the red background in the Regenerate modal to the warning text only The confirmation question, expiry picker, and its hints were sitting inside the same alert-danger box as the warning, making the whole modal read as an error. Only the warning paragraph keeps the red background now. * Move the regenerate confirmation question below the expiry picker * Align rotate-token wording with UI: use 'regenerate/regenerated' * [MM-69561] rename pat_expiry_notify job to notify_expiring_access_tokens Unifies naming with the sibling cleanup_expired_access_tokens job and fixes the "expiry" vs "expiring" ambiguity: this job warns about tokens approaching expiry, not ones that have already expired. Safe to rename outright since the job hasn't shipped yet. * [MM-69561] remove dead session lookup from EnableUserAccessToken The GetSessionContext call and its result were never used: both branches returned nil regardless. Leftover from mirroring DisableUserAccessToken's shape, which does use its session (to revoke it) unlike Enable. * [MM-69561] rename remaining PAT identifiers to match AccessToken convention The job-level rename (pat_expiry_notify -> notify_expiring_access_tokens) left the app-layer function and its helpers using the old PAT/ PersonalAccessToken naming. Rename them to match: - NotifyPersonalAccessTokensExpiring -> NotifyExpiringAccessTokens - patExpiryBucket -> accessTokenExpiryBucket - sendPATExpiryNotification -> sendAccessTokenExpiryNotification - patExpiryNotifyBatchLimit -> expiringAccessTokenBatchLimit - patExpiryThresholds -> expiringAccessTokenThresholds - maxPersonalAccessTokenExpiry -> maxUserAccessTokenExpiry Also reword the package doc on notify_expiring_access_tokens, which no longer needs to explain a PAT/UserAccessToken naming split now that the app-layer method matches the job name. Pure rename, no behavior change. --------- Co-authored-by: Hanzo Dev <[email protected]>
160 lines
5.5 KiB
Go
160 lines
5.5 KiB
Go
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
|
|
// See LICENSE.txt for license information.
|
|
|
|
package app
|
|
|
|
import (
|
|
"net/http"
|
|
|
|
"github.com/mattermost/mattermost/server/public/model"
|
|
"github.com/mattermost/mattermost/server/public/shared/i18n"
|
|
"github.com/mattermost/mattermost/server/public/shared/mlog"
|
|
"github.com/mattermost/mattermost/server/public/shared/request"
|
|
)
|
|
|
|
// expiringAccessTokenBatchLimit bounds the number of tokens processed per run.
|
|
// GetExpiringTokens returns only actionable rows (most urgent first), so this
|
|
// caps work per run while a backlog larger than the limit drains across
|
|
// subsequent hourly runs without starving the least-urgent tokens.
|
|
const expiringAccessTokenBatchLimit = 1000
|
|
|
|
// expiringAccessTokenThresholds is the pre-expiry warning cascade, in days,
|
|
// ordered from most to least urgent. A token owner is warned once as the
|
|
// token crosses into each bucket.
|
|
var expiringAccessTokenThresholds = []int{1, 3, 7}
|
|
|
|
// NotifyExpiringAccessTokens warns the owners of personal access tokens that
|
|
// are approaching expiry, on a fixed 7 / 3 / 1 day cascade. It is invoked
|
|
// hourly by the notify_expiring_access_tokens job.
|
|
//
|
|
// Bot tokens and tokens owned by deactivated users are excluded by the store
|
|
// query. For each remaining token this computes the current warning bucket,
|
|
// sends a single system-bot DM, and records the per-token LastNotifiedAt marker
|
|
// so the same (or a less urgent) warning is never re-sent. Because only
|
|
// the most urgent applicable bucket is ever sent, a token that first becomes
|
|
// visible already inside the window (e.g. created with a short lifetime, or owned
|
|
// by a just-reactivated user) gets a single warning rather than a catch-up burst
|
|
// of every threshold it has already passed.
|
|
func (a *App) NotifyExpiringAccessTokens() error {
|
|
if !*a.Config().ServiceSettings.EnableUserAccessTokens {
|
|
return nil
|
|
}
|
|
|
|
rctx := request.EmptyContext(a.Log().With(mlog.String("component", "notify_expiring_access_tokens")))
|
|
|
|
now := model.GetMillis()
|
|
|
|
tokens, err := a.Srv().Store().UserAccessToken().GetExpiringTokens(now, expiringAccessTokenThresholds, expiringAccessTokenBatchLimit)
|
|
if err != nil {
|
|
return model.NewAppError("NotifyExpiringAccessTokens", "app.user_access_token.get_expiring.app_error", nil, "", http.StatusInternalServerError).Wrap(err)
|
|
}
|
|
if len(tokens) == 0 {
|
|
return nil
|
|
}
|
|
|
|
systemBot, appErr := a.GetSystemBot(rctx)
|
|
if appErr != nil {
|
|
return appErr
|
|
}
|
|
|
|
for _, token := range tokens {
|
|
bucket := accessTokenExpiryBucket(token.ExpiresAt, now)
|
|
if bucket == 0 {
|
|
// Already expired or outside the cascade; the store window should
|
|
// prevent this, but guard against clock skew between runs.
|
|
continue
|
|
}
|
|
|
|
// Skip if the owner has already been warned at this bucket or a more
|
|
// urgent (smaller) one. A prior warning covers the current bucket when it
|
|
// was sent while no more time remained than the bucket spans, i.e.
|
|
// LastNotifiedAt >= ExpiresAt - bucket. nil means no warning sent yet.
|
|
if token.LastNotifiedAt != nil && *token.LastNotifiedAt >= token.ExpiresAt-int64(bucket)*model.DayInMilliseconds {
|
|
continue
|
|
}
|
|
|
|
if appErr := a.sendAccessTokenExpiryNotification(rctx, systemBot, token, bucket); appErr != nil {
|
|
rctx.Logger().Error("Failed to send personal access token expiry notification",
|
|
mlog.String("token_id", token.Id),
|
|
mlog.String("user_id", token.UserId),
|
|
mlog.Err(appErr),
|
|
)
|
|
continue
|
|
}
|
|
|
|
if err := a.Srv().Store().UserAccessToken().UpdateLastNotifiedAt(token.Id, now); err != nil {
|
|
rctx.Logger().Error("Failed to update LastNotifiedAt for personal access token",
|
|
mlog.String("token_id", token.Id),
|
|
mlog.Err(err),
|
|
)
|
|
}
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
// accessTokenExpiryBucket returns the most urgent warning threshold (in days)
|
|
// that the token currently qualifies for, or 0 if it is already expired or
|
|
// further out than the largest threshold. A token with N days remaining maps
|
|
// to the smallest threshold T such that N <= T (e.g. 2 days remaining -> the
|
|
// 3-day bucket).
|
|
func accessTokenExpiryBucket(expiresAt int64, now int64) int {
|
|
remaining := expiresAt - now
|
|
if remaining <= 0 {
|
|
return 0
|
|
}
|
|
for _, threshold := range expiringAccessTokenThresholds {
|
|
if remaining <= int64(threshold)*model.DayInMilliseconds {
|
|
return threshold
|
|
}
|
|
}
|
|
return 0
|
|
}
|
|
|
|
func (a *App) sendAccessTokenExpiryNotification(rctx request.CTX, systemBot *model.Bot, token *model.UserAccessToken, bucket int) *model.AppError {
|
|
channel, appErr := a.GetOrCreateDirectChannel(rctx, token.UserId, systemBot.UserId)
|
|
if appErr != nil {
|
|
return appErr
|
|
}
|
|
|
|
user, appErr := a.GetUser(token.UserId)
|
|
if appErr != nil {
|
|
return appErr
|
|
}
|
|
|
|
T := i18n.GetUserTranslations(user.Locale)
|
|
|
|
description := token.Description
|
|
if description == "" {
|
|
description = T("app.notify_expiring_access_tokens.unnamed_token")
|
|
}
|
|
|
|
// The cascade is 7/3/1; the multi-day message is only ever rendered with a
|
|
// plural day count (7 or 3), and the 1-day bucket uses a dedicated "24 hours"
|
|
// message, so neither string needs an awkward "day(s)" plural.
|
|
var message string
|
|
if bucket <= 1 {
|
|
message = T("app.notify_expiring_access_tokens.dm_final", map[string]any{
|
|
"Description": description,
|
|
})
|
|
} else {
|
|
message = T("app.notify_expiring_access_tokens.dm", map[string]any{
|
|
"Description": description,
|
|
"Days": bucket,
|
|
})
|
|
}
|
|
|
|
post := &model.Post{
|
|
ChannelId: channel.Id,
|
|
Message: message,
|
|
Type: model.PostTypeDefault,
|
|
UserId: systemBot.UserId,
|
|
}
|
|
|
|
if _, _, err := a.CreatePost(rctx, post, channel, model.CreatePostFlags{SetOnline: false}); err != nil {
|
|
return err
|
|
}
|
|
|
|
return nil
|
|
}
|