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:
@@ -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",
|
||||
|
||||
Reference in New Issue
Block a user