feat(system): add admin password reset with session revocation

Let system administrators reset another user's local password from the settings UI, revoke all active sessions, and record the action in the audit log.
This commit is contained in:
wizardchen
2026-07-13 20:05:08 +08:00
committed by lyingbug
parent 8554c422dc
commit 8ec65941a5
17 changed files with 1340 additions and 59 deletions
+58
View File
@@ -14,6 +14,7 @@ import (
"strings"
"sync"
"time"
"unicode/utf8"
"github.com/golang-jwt/jwt/v5"
"github.com/google/uuid"
@@ -30,8 +31,38 @@ import (
var (
jwtSecretOnce sync.Once
jwtSecret string
// ErrPasswordPolicy is returned when a newly chosen password does not
// meet the product's public 8-32 character, letter-and-number contract.
// It is exported so HTTP handlers can translate the failure to a 400
// without exposing bcrypt or persistence errors.
ErrPasswordPolicy = errors.New("password must be 8-32 characters and contain at least one letter and one number")
)
// ValidatePasswordPolicy keeps administrative password resets aligned with
// the registration form's documented policy. Password bytes are never logged
// or included in the returned error.
func ValidatePasswordPolicy(password string) error {
length := utf8.RuneCountInString(password)
if length < 8 || length > 32 {
return ErrPasswordPolicy
}
hasLetter := false
hasNumber := false
for _, r := range password {
switch {
case r >= 'a' && r <= 'z', r >= 'A' && r <= 'Z':
hasLetter = true
case r >= '0' && r <= '9':
hasNumber = true
}
}
if !hasLetter || !hasNumber {
return ErrPasswordPolicy
}
return nil
}
// getJwtSecret retrieves the JWT secret from the environment, falling back to a securely generated random secret.
func getJwtSecret() string {
jwtSecretOnce.Do(func() {
@@ -630,6 +661,33 @@ func (s *userService) ChangePassword(ctx context.Context, userID string, oldPass
return s.tokenRepo.RevokeTokensByUserID(ctx, userID)
}
// AdminResetPassword replaces a user's password without checking the previous
// credential. Authorization and the cannot-reset-self rule live at the system
// admin HTTP boundary; this service owns the security-critical persistence and
// session invalidation so no caller can accidentally update only one of them.
func (s *userService) AdminResetPassword(ctx context.Context, userID string, newPassword string) error {
if err := ValidatePasswordPolicy(newPassword); err != nil {
return err
}
user, err := s.userRepo.GetUserByID(ctx, userID)
if err != nil {
return err
}
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(newPassword), bcrypt.DefaultCost)
if err != nil {
return err
}
user.PasswordHash = string(hashedPassword)
user.UpdatedAt = time.Now()
if err := s.userRepo.UpdateUser(ctx, user); err != nil {
return err
}
return s.tokenRepo.RevokeTokensByUserID(ctx, userID)
}
// ValidatePassword validates user password
func (s *userService) ValidatePassword(ctx context.Context, userID string, password string) error {
user, err := s.userRepo.GetUserByID(ctx, userID)
@@ -8,6 +8,7 @@ import (
"time"
"github.com/golang-jwt/jwt/v5"
"golang.org/x/crypto/bcrypt"
"github.com/Tencent/WeKnora/internal/types"
)
@@ -41,7 +42,8 @@ func (s *stubAuthTokenRepo) RevokeTokensByUserID(_ context.Context, userID strin
}
type stubUserRepoForAuth struct {
users map[string]*types.User
users map[string]*types.User
updateCalls int
}
func (s *stubUserRepoForAuth) CreateUser(context.Context, *types.User) error { return nil }
@@ -64,8 +66,11 @@ func (s *stubUserRepoForAuth) GetUserByUsername(context.Context, string) (*types
func (s *stubUserRepoForAuth) GetUserByTenantID(context.Context, uint64) (*types.User, error) {
return nil, nil
}
func (s *stubUserRepoForAuth) UpdateUser(context.Context, *types.User) error { return nil }
func (s *stubUserRepoForAuth) DeleteUser(context.Context, string) error { return nil }
func (s *stubUserRepoForAuth) UpdateUser(context.Context, *types.User) error {
s.updateCalls++
return nil
}
func (s *stubUserRepoForAuth) DeleteUser(context.Context, string) error { return nil }
func (s *stubUserRepoForAuth) ListUsers(context.Context, int, int) ([]*types.User, error) {
return nil, nil
}
@@ -177,6 +182,44 @@ func TestLogoutRevokesAllUserTokens(t *testing.T) {
}
}
func TestAdminResetPasswordHashesPasswordAndRevokesSessions(t *testing.T) {
ctx := context.Background()
tokenRepo := &stubAuthTokenRepo{tokens: map[string]*types.AuthToken{}}
svc := newAuthTestUserService(tokenRepo)
repo := svc.userRepo.(*stubUserRepoForAuth)
if err := svc.AdminResetPassword(ctx, "user-1", "NewSecure9"); err != nil {
t.Fatalf("AdminResetPassword() err = %v", err)
}
if repo.updateCalls != 1 {
t.Fatalf("UpdateUser calls = %d, want 1", repo.updateCalls)
}
user := repo.users["user-1"]
if user.PasswordHash == "NewSecure9" || user.PasswordHash == "" {
t.Fatalf("password was not stored as a hash")
}
if err := bcrypt.CompareHashAndPassword([]byte(user.PasswordHash), []byte("NewSecure9")); err != nil {
t.Fatalf("stored hash does not match new password: %v", err)
}
if len(tokenRepo.revokedUserIDs) != 1 || tokenRepo.revokedUserIDs[0] != "user-1" {
t.Fatalf("RevokeTokensByUserID calls = %v, want [user-1]", tokenRepo.revokedUserIDs)
}
}
func TestAdminResetPasswordRejectsWeakPasswordBeforeWrite(t *testing.T) {
tokenRepo := &stubAuthTokenRepo{tokens: map[string]*types.AuthToken{}}
svc := newAuthTestUserService(tokenRepo)
repo := svc.userRepo.(*stubUserRepoForAuth)
err := svc.AdminResetPassword(context.Background(), "user-1", "password")
if !errors.Is(err, ErrPasswordPolicy) {
t.Fatalf("AdminResetPassword() err = %v, want ErrPasswordPolicy", err)
}
if repo.updateCalls != 0 || len(tokenRepo.revokedUserIDs) != 0 {
t.Fatalf("weak password caused side effects: updates=%d revocations=%v", repo.updateCalls, tokenRepo.revokedUserIDs)
}
}
func TestUserIDFromSignedTokenAcceptsExpiredToken(t *testing.T) {
expired := signTestJWT(jwt.MapClaims{
"user_id": "user-1",
+66
View File
@@ -1362,6 +1362,72 @@ func (h *SystemHandler) ListSystemAdmins(c *gin.Context) {
})
}
// ResetUserPasswordRequest defines the system-administrator password-reset
// payload. Email is intentionally the only user-facing identifier: the UI is
// an operator tool and emails are easier to verify than UUIDs. The password is
// never written to logs or audit details.
type ResetUserPasswordRequest struct {
Email string `json:"email" binding:"required,email"`
NewPassword string `json:"new_password" binding:"required"`
}
// ResetUserPassword godoc
// @Summary Reset another user's password
// @Description Replace another user's local password and revoke all of their existing sessions (SystemAdmin only).
// @Description A system administrator cannot reset their own password through this endpoint; self-service password change still requires the old password.
// @Tags System Admin
// @Accept json
// @Produce json
// @Param request body ResetUserPasswordRequest true "Password reset request"
// @Success 200 {object} map[string]interface{} "Password reset successfully"
// @Failure 400 {object} map[string]interface{} "Invalid request, weak password, or self reset"
// @Failure 403 {object} map[string]interface{} "Forbidden: not a system admin"
// @Failure 404 {object} map[string]interface{} "User not found"
// @Router /system/admin/users/reset-password [post]
func (h *SystemHandler) ResetUserPassword(c *gin.Context) {
ctx := logger.CloneContext(c.Request.Context())
var req ResetUserPasswordRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid password reset request"})
return
}
req.Email = strings.TrimSpace(req.Email)
if err := service.ValidatePasswordPolicy(req.NewPassword); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
user, err := h.userSvc.GetUserByEmail(ctx, req.Email)
if err != nil || user == nil {
c.JSON(http.StatusNotFound, gin.H{"error": "User not found"})
return
}
callerID, _ := types.UserIDFromContext(ctx)
if callerID == user.ID {
c.JSON(http.StatusBadRequest, gin.H{"error": "Cannot reset your own password here"})
return
}
if err := h.userSvc.AdminResetPassword(ctx, user.ID, req.NewPassword); err != nil {
if errors.Is(err, service.ErrPasswordPolicy) {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
logger.Errorf(ctx, "Failed to reset password for user %s: %v", user.ID, err)
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to reset user password"})
return
}
logger.Infof(ctx, "Password reset by system administrator for user ID: %s", user.ID)
h.emitAdminAudit(ctx, types.AuditActionSystemUserPasswordReset, user, map[string]any{
"target_email": user.Email,
"target_username": user.Username,
"sessions_revoked": true,
})
c.JSON(http.StatusOK, gin.H{"message": "Password reset successfully"})
}
// ============================================================================
// System Settings (P1)
// ----------------------------------------------------------------------------
@@ -0,0 +1,115 @@
package handler
import (
"bytes"
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
"github.com/gin-gonic/gin"
)
type resetPasswordUserService struct {
interfaces.UserService
target *types.User
lookupCalls int
resetCalls int
resetUserID string
}
func (s *resetPasswordUserService) GetUserByEmail(context.Context, string) (*types.User, error) {
s.lookupCalls++
return s.target, nil
}
func (s *resetPasswordUserService) AdminResetPassword(_ context.Context, userID, _ string) error {
s.resetCalls++
s.resetUserID = userID
return nil
}
func passwordResetRouter(h *SystemHandler, actorID string) *gin.Engine {
gin.SetMode(gin.TestMode)
r := gin.New()
r.Use(func(c *gin.Context) {
ctx := context.WithValue(c.Request.Context(), types.UserIDContextKey, actorID)
c.Request = c.Request.WithContext(ctx)
c.Next()
})
r.POST("/system/admin/users/reset-password", h.ResetUserPassword)
return r
}
func performPasswordReset(t *testing.T, r *gin.Engine, body map[string]string) *httptest.ResponseRecorder {
t.Helper()
payload, err := json.Marshal(body)
if err != nil {
t.Fatal(err)
}
req := httptest.NewRequest(http.MethodPost, "/system/admin/users/reset-password", bytes.NewReader(payload))
req.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
return w
}
func TestResetUserPasswordResetsOtherUserAndAuditsWithoutSecret(t *testing.T) {
users := &resetPasswordUserService{target: &types.User{
ID: "target-user", Username: "alice", Email: "alice@example.com",
}}
audits := &capturingAuditService{}
h := &SystemHandler{userSvc: users, auditSvc: audits}
w := performPasswordReset(t, passwordResetRouter(h, "admin-user"), map[string]string{
"email": "alice@example.com", "new_password": "FreshPass9",
})
if w.Code != http.StatusOK {
t.Fatalf("status=%d body=%s", w.Code, w.Body.String())
}
if users.resetCalls != 1 || users.resetUserID != "target-user" {
t.Fatalf("reset calls=%d user=%q", users.resetCalls, users.resetUserID)
}
if len(audits.entries) != 1 || audits.entries[0].Action != types.AuditActionSystemUserPasswordReset {
t.Fatalf("unexpected audit entries: %+v", audits.entries)
}
if strings.Contains(string(audits.entries[0].Details), "FreshPass9") {
t.Fatal("audit details leaked the new password")
}
}
func TestResetUserPasswordRejectsSelfReset(t *testing.T) {
users := &resetPasswordUserService{target: &types.User{
ID: "admin-user", Username: "admin", Email: "admin@example.com",
}}
h := &SystemHandler{userSvc: users}
w := performPasswordReset(t, passwordResetRouter(h, "admin-user"), map[string]string{
"email": "admin@example.com", "new_password": "FreshPass9",
})
if w.Code != http.StatusBadRequest {
t.Fatalf("status=%d body=%s", w.Code, w.Body.String())
}
if users.resetCalls != 0 {
t.Fatalf("self reset reached service %d times", users.resetCalls)
}
}
func TestResetUserPasswordRejectsWeakPasswordBeforeUserLookup(t *testing.T) {
users := &resetPasswordUserService{target: &types.User{ID: "target-user"}}
h := &SystemHandler{userSvc: users}
w := performPasswordReset(t, passwordResetRouter(h, "admin-user"), map[string]string{
"email": "alice@example.com", "new_password": "password",
})
if w.Code != http.StatusBadRequest {
t.Fatalf("status=%d body=%s", w.Code, w.Body.String())
}
if users.lookupCalls != 0 || users.resetCalls != 0 {
t.Fatalf("weak password caused side effects: lookups=%d resets=%d", users.lookupCalls, users.resetCalls)
}
}
+1
View File
@@ -875,6 +875,7 @@ func RegisterSystemAdminRoutes(
adminRoutes.POST("/promote", handler.PromoteUserToSystemAdmin)
adminRoutes.POST("/revoke", handler.RevokeSystemAdmin)
adminRoutes.GET("/list", handler.ListSystemAdmins)
adminRoutes.POST("/users/reset-password", handler.ResetUserPassword)
// P1: platform-wide system settings (DB-backed runtime tunables).
// Reads return raw model rows / arrays (no `gin.H{"data":...}`
+5
View File
@@ -116,6 +116,11 @@ const (
// reader can distinguish a real revoke from a noop attempt.
// TenantID=0 because the change is system-scope.
AuditActionSystemAdminRevoked AuditAction = "system.admin_revoked"
// AuditActionSystemUserPasswordReset fires when a SystemAdmin replaces
// another user's local password. Details identify the target and record
// session revocation, but never contain the old or new password.
AuditActionSystemUserPasswordReset AuditAction = "system.user_password_reset"
)
// AuditOutcome distinguishes successful mutations from middleware-level
+6 -2
View File
@@ -37,6 +37,7 @@ func TestAuditAction_DotNamespaceConvention(t *testing.T) {
AuditActionSystemSettingChanged,
AuditActionSystemAdminPromoted,
AuditActionSystemAdminRevoked,
AuditActionSystemUserPasswordReset,
}
for _, a := range all {
s := string(a)
@@ -118,9 +119,10 @@ func TestAuditAction_NoCollisionsAcrossNamespaces(t *testing.T) {
register("AuditActionSystemSettingChanged", AuditActionSystemSettingChanged)
register("AuditActionSystemAdminPromoted", AuditActionSystemAdminPromoted)
register("AuditActionSystemAdminRevoked", AuditActionSystemAdminRevoked)
register("AuditActionSystemUserPasswordReset", AuditActionSystemUserPasswordReset)
}
// TestAuditAction_SystemNamespacePrefix pins the three system.* actions
// TestAuditAction_SystemNamespacePrefix pins the system.* actions
// added in this PR to their shared area prefix. The prefix is the
// contract by which the platform audit log endpoint
// (GET /system/admin/audit-log) filters out per-tenant rbac.* rows —
@@ -131,6 +133,7 @@ func TestAuditAction_SystemNamespacePrefix(t *testing.T) {
AuditActionSystemSettingChanged,
AuditActionSystemAdminPromoted,
AuditActionSystemAdminRevoked,
AuditActionSystemUserPasswordReset,
}
for _, a := range cases {
assert.True(t,
@@ -141,7 +144,7 @@ func TestAuditAction_SystemNamespacePrefix(t *testing.T) {
}
// TestAuditAction_SystemWireValues pins the exact wire strings for
// the three system.* actions. Audit-log consumers (Langfuse exporters,
// the system.* actions. Audit-log consumers (Langfuse exporters,
// the new frontend platform audit drawer, future SIEM integrations)
// match on these strings; changing them is a breaking change.
func TestAuditAction_SystemWireValues(t *testing.T) {
@@ -152,6 +155,7 @@ func TestAuditAction_SystemWireValues(t *testing.T) {
{AuditActionSystemSettingChanged, "system.setting_changed"},
{AuditActionSystemAdminPromoted, "system.admin_promoted"},
{AuditActionSystemAdminRevoked, "system.admin_revoked"},
{AuditActionSystemUserPasswordReset, "system.user_password_reset"},
}
for _, c := range cases {
assert.Equal(t, c.wire, string(c.constant))
+4
View File
@@ -37,6 +37,10 @@ type UserService interface {
DeleteUser(ctx context.Context, id string) error
// ChangePassword changes user password
ChangePassword(ctx context.Context, userID string, oldPassword, newPassword string) error
// AdminResetPassword replaces a user's password without requiring the old
// password and revokes all of that user's existing sessions. Callers must
// enforce the system-admin and cannot-reset-self guards before invoking it.
AdminResetPassword(ctx context.Context, userID string, newPassword string) error
// ValidatePassword validates user password
ValidatePassword(ctx context.Context, userID string, password string) error
// GenerateTokens generates access and refresh tokens for user