WeKnora/internal/application/service/user_admin_create_test.go

302 lines
11 KiB
Go
Raw Normal View History

feat(system-admin): add endpoint for creating users (#2722) * feat(types): add AdminCreateUserRequest for system-admin user creation Password un-tagged so an empty value reaches the service and triggers OIDC-style random-password generation. * feat(system-admin): scaffold POST /system/admin/users/create endpoint - Handler skeleton under the SystemAdmin()-guarded group - Binding and validation live (400); happy path 501 until the service logic lands - Response type declares the once-only generated_password contract * test(system-admin): contract tests for user creation - Create/audit/generated-password cases assert the final contract and are intentionally red against the 501 stub - Binding and trim validation cases already pass - Adds the system.user_created audit action as the audit contract * feat(frontend): add createSystemUser API wrapper Mirrors promote/revoke/reset-password conventions, including the once-only generated_password contract on the response type. * fix(system-admin): never rewrite password; re-check trimmed username - Handler no longer trims the password: whitespace is part of the credential, hashed byte-for-byte (mirrors auth.go Register) - Trimmed username re-checked to 2-50 runes (binding ran on the raw JSON) * feat(service): implement AdminCreateUser with random-password fallback - Empty password: OIDC-style crypto/rand generation, returned once - Explicit password: must satisfy the 8-32 letter-and-number policy - Delegates to Register: duplicate checks, tenant provisioning and Owner membership bootstrap match public registration * feat(system-admin): implement create-user handler - Resolves tenant mode from the shared auth.default_tenant_mode policy (single source for registration and admin creation) - Emits system.user_created audit without the plaintext password - 201 + once-only generated password; 400 for policy/duplicate, 500 for internal failures * test(service): whitespace-only password must be rejected - All-whitespace password: ErrPasswordPolicy, nothing persisted (matches AdminResetPassword); only truly empty triggers generation - Red against the current TrimSpace-empty check - Handler test drops the whitespace-only 201 expectation, keeps byte-for-byte pass-through for spacey valid passwords * fix(service): treat only a truly empty password as generate-request Generation now triggers only on the empty string; whitespace-only input is rejected by the 8-32 policy like AdminResetPassword. * fix(service): regenerate until the generated password passes policy A 32-char base64url draw misses digits ~0.4% of the time and could 400 a creation nobody picked a password for; regenerate until the policy passes (expected ~1.004 draws). * refactor(system-admin): drop TenantProvisioning from create payload The value lived both on the request and as the service argument; keep it only as the argument, mirroring LoginWithOIDC. * test(system-admin): pin password_generated audit value; cover dupes - Audit assertions check the exact password_generated boolean (true generated, false caller-supplied) - Duplicate mapping table-driven over email and username errors * feat(system-admin): explicit provide-and-validate password semantics - Password pointer-typed: absence (or null) triggers random generation; any provided value, empty string included, is policy-checked and rejected otherwise - Service: generation on nil only, all provided values hashed byte-for-byte - Tests: empty string -> 400, absent -> generate, nil pass-through at the handler boundary - Frontend: document that any provided value is policy-checked * test(system-admin): merge duplicate rejection tests Whitespace-only and weak-password rejection tests were structurally identical, differing only in inputs. Merged into one table-driven test covering weak, empty, whitespace and whitespace-only values. * feat(system-admin): idempotent create on duplicate identity - Register returns typed sentinels ErrUser{Email,Username}Exists - AdminCreateUser re-queries the existing row, lookup targeted at the sentinel-named identity (email or username) - Handler: duplicate sentinels -> 200 + UserInfo with idempotent=true audit, policy errors stay 400; drops the substring-matched branch * fix(system-admin): reject partial identity conflicts on user create Idempotent 200 now requires both email and username to match the existing row; partial collisions return 409. Align handler identity sanitization and password docs with nil-or-null generation semantics. --------- Co-authored-by: wizardchen <wizardchen@tencent.com>
2026-08-20 11:51:10 +00:00
package service
import (
"context"
"errors"
"strings"
"testing"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
"golang.org/x/crypto/bcrypt"
)
// adminCreateUserRepo records the Register call so tests can verify both
// the persisted user and the exact password bytes handed to bcrypt.
type adminCreateUserRepo struct {
interfaces.UserRepository
existingByEmail *types.User
existingByUsername *types.User
created *types.User
}
func (r *adminCreateUserRepo) GetUserByEmail(context.Context, string) (*types.User, error) {
if r.existingByEmail != nil {
return r.existingByEmail, nil
}
return nil, nil
}
func (r *adminCreateUserRepo) GetUserByUsername(context.Context, string) (*types.User, error) {
if r.existingByUsername != nil {
return r.existingByUsername, nil
}
return nil, nil
}
func (r *adminCreateUserRepo) CreateUser(_ context.Context, user *types.User) error {
copied := *user
r.created = &copied
return nil
}
func newAdminCreateUserService(repo *adminCreateUserRepo) *userService {
return &userService{userRepo: repo, tenantService: nil, memberService: nil}
}
func TestAdminCreateUserGeneratesPolicyCompliantPasswordWhenEmpty(t *testing.T) {
repo := &adminCreateUserRepo{}
svc := newAdminCreateUserService(repo)
user, generated, err := svc.AdminCreateUser(context.Background(), &types.AdminCreateUserRequest{
Username: "alice", Email: "alice@example.com",
}, types.TenantProvisioningTenantless)
if err != nil {
t.Fatalf("AdminCreateUser: %v", err)
}
if generated == "" {
t.Fatal("expected a generated password")
}
if user == nil || repo.created == nil {
t.Fatalf("user was not persisted: %v", repo.created)
}
if err := ValidatePasswordPolicy(generated); err != nil {
t.Fatalf("generated password violates the policy: %v", err)
}
if bcrypt.CompareHashAndPassword([]byte(repo.created.PasswordHash), []byte(generated)) != nil {
t.Fatal("persisted hash does not match the generated password")
}
}
func TestAdminCreateUserUsesExplicitPassword(t *testing.T) {
repo := &adminCreateUserRepo{}
svc := newAdminCreateUserService(repo)
user, generated, err := svc.AdminCreateUser(context.Background(), &types.AdminCreateUserRequest{
Username: "alice", Email: "alice@example.com", Password: new("PlainPass9"),
}, types.TenantProvisioningTenantless)
if err != nil {
t.Fatalf("AdminCreateUser: %v", err)
}
if generated != "" {
t.Fatalf("generated password must be empty for a caller-supplied password, got %q", generated)
}
if user == nil {
t.Fatal("user is nil")
}
if bcrypt.CompareHashAndPassword([]byte(repo.created.PasswordHash), []byte("PlainPass9")) != nil {
t.Fatal("persisted hash does not match the explicit password")
}
}
func TestAdminCreateUserHashesUntrimmedPasswordByteForByte(t *testing.T) {
// Leading/trailing whitespace is part of the credential.
repo := &adminCreateUserRepo{}
svc := newAdminCreateUserService(repo)
raw := " PlainPass9 "
if _, _, err := svc.AdminCreateUser(context.Background(), &types.AdminCreateUserRequest{
Username: "alice", Email: "alice@example.com", Password: &raw,
}, types.TenantProvisioningTenantless); err != nil {
t.Fatalf("AdminCreateUser: %v", err)
}
if bcrypt.CompareHashAndPassword([]byte(repo.created.PasswordHash), []byte(raw)) != nil {
t.Fatal("hash does not match the raw password bytes")
}
if bcrypt.CompareHashAndPassword([]byte(repo.created.PasswordHash), []byte(strings.TrimSpace(raw))) == nil {
t.Fatal("hash matches the trimmed password, the credential was rewritten")
}
}
func TestAdminCreateUserRejectsPolicyViolatingPassword(t *testing.T) {
// Registration accepts whitespace as literal password characters, but
// admin-create policy-checks any provided value.
// Only an absent password triggers generation.
repo := &adminCreateUserRepo{}
svc := newAdminCreateUserService(repo)
for _, pw := range []string{"password", "", " ", "\t\n", " \u00a0\u00a0 "} {
_, generated, err := svc.AdminCreateUser(context.Background(), &types.AdminCreateUserRequest{
Username: "alice", Email: "alice@example.com", Password: &pw,
}, types.TenantProvisioningTenantless)
if !errors.Is(err, ErrPasswordPolicy) {
t.Fatalf("password=%q err=%v, want ErrPasswordPolicy", pw, err)
}
if generated != "" {
t.Fatalf("password=%q generated=%q, want no generated password", pw, generated)
}
if repo.created != nil {
t.Fatalf("password=%q reached persistence", pw)
}
}
}
func TestGeneratePolicyCompliantPasswordAlwaysComplies(t *testing.T) {
// ~0.4% of base64url draws have no digit. Regenerating until the
// policy passes makes compliance certain for every draw.
for i := range 2000 {
pw, err := generatePolicyCompliantPassword()
if err != nil {
t.Fatalf("iteration %d: generate: %v", i, err)
}
if err := ValidatePasswordPolicy(pw); err != nil {
t.Fatalf("iteration %d: generated password %q violates the policy: %v", i, pw, err)
}
}
}
func TestAdminCreateUserRejectsWeakPasswordBeforePersisting(t *testing.T) {
// Providing the password key with any value subjects it to the
// policy; the explicit empty string is rejected like any other
// policy-violating value and never reaches persistence.
repo := &adminCreateUserRepo{}
svc := newAdminCreateUserService(repo)
for _, pw := range []string{"password", ""} {
_, _, err := svc.AdminCreateUser(context.Background(), &types.AdminCreateUserRequest{
Username: "alice", Email: "alice@example.com", Password: &pw,
}, types.TenantProvisioningTenantless)
if !errors.Is(err, ErrPasswordPolicy) {
t.Fatalf("password=%q err=%v, want ErrPasswordPolicy", pw, err)
}
if repo.created != nil {
t.Fatalf("password=%q reached persistence", pw)
}
}
}
func TestAdminCreateUserDuplicateReturnsExistingUserWithSentinel(t *testing.T) {
existing := &types.User{ID: "existing", Username: "alice", Email: "alice@example.com"}
repo := &adminCreateUserRepo{existingByEmail: existing}
svc := newAdminCreateUserService(repo)
user, generated, err := svc.AdminCreateUser(context.Background(), &types.AdminCreateUserRequest{
Username: "alice", Email: "alice@example.com", Password: new("PlainPass9"),
}, types.TenantProvisioningTenantless)
if !errors.Is(err, ErrUserEmailExists) {
t.Fatalf("err=%v, want ErrUserEmailExists", err)
}
if user == nil || user.ID != existing.ID {
t.Fatalf("user=%v, want the existing user %q", user, existing.ID)
}
if generated != "" {
t.Fatalf("generated=%q, want no generated password for an existing user", generated)
}
if repo.created != nil {
t.Fatal("existing user was overwritten")
}
}
func TestAdminCreateUserDuplicateUsernameReturnsExistingUserWithSentinel(t *testing.T) {
existing := &types.User{ID: "existing", Username: "alice", Email: "alice@example.com"}
repo := &adminCreateUserRepo{existingByUsername: existing}
svc := newAdminCreateUserService(repo)
user, _, err := svc.AdminCreateUser(context.Background(), &types.AdminCreateUserRequest{
Username: "alice", Email: "alice@example.com", Password: new("PlainPass9"),
}, types.TenantProvisioningTenantless)
if !errors.Is(err, ErrUserUsernameExists) {
t.Fatalf("err=%v, want ErrUserUsernameExists", err)
}
if user == nil || user.ID != existing.ID {
t.Fatalf("user=%v, want the existing user %q", user, existing.ID)
}
}
func TestAdminCreateUserDuplicateLookupTargetsSentinelIdentity(t *testing.T) {
// Register reports a username collision (email free at check time).
// A user owning the request email appears before the duplicate lookup,
// as if created concurrently. The lookup must return the user named by
// the sentinel, not the email owner a fallback would have picked.
repo := &racyIdentityRepo{
byUsername: &types.User{ID: "username-owner", Username: "alice", Email: "alice@example.com"},
byEmail: &types.User{ID: "email-owner", Email: "alice@example.com"},
}
svc := &userService{userRepo: repo}
user, _, err := svc.AdminCreateUser(context.Background(), &types.AdminCreateUserRequest{
Username: "alice", Email: "alice@example.com", Password: new("PlainPass9"),
}, types.TenantProvisioningTenantless)
if !errors.Is(err, ErrUserUsernameExists) {
t.Fatalf("err=%v, want ErrUserUsernameExists", err)
}
if user == nil || user.ID != repo.byUsername.ID {
t.Fatalf("user=%v, want the username-collision owner %q", user, repo.byUsername.ID)
}
if repo.emailLookups != 1 {
t.Fatalf("emailLookups=%d, want 1 (Register's check only, the duplicate lookup must not query email)", repo.emailLookups)
}
}
// racyIdentityRepo simulates a concurrent create between Register's
// duplicate check and AdminCreateUser's duplicate-path lookup: the email
// becomes occupied only on the second query.
type racyIdentityRepo struct {
interfaces.UserRepository
byUsername *types.User
byEmail *types.User
emailLookups int
}
func (r *racyIdentityRepo) GetUserByEmail(_ context.Context, _ string) (*types.User, error) {
r.emailLookups++
if r.emailLookups > 1 {
return r.byEmail, nil
}
return nil, nil
}
func (r *racyIdentityRepo) GetUserByUsername(_ context.Context, _ string) (*types.User, error) {
return r.byUsername, nil
}
func TestAdminCreateUserRejectsPartialEmailConflict(t *testing.T) {
existing := &types.User{ID: "existing", Username: "alice", Email: "alice@example.com"}
repo := &adminCreateUserRepo{existingByEmail: existing}
svc := newAdminCreateUserService(repo)
_, generated, err := svc.AdminCreateUser(context.Background(), &types.AdminCreateUserRequest{
Username: "bob", Email: "alice@example.com", Password: new("PlainPass9"),
}, types.TenantProvisioningTenantless)
if !errors.Is(err, ErrUserIdentityConflict) {
t.Fatalf("err=%v, want ErrUserIdentityConflict", err)
}
if generated != "" {
t.Fatalf("generated=%q, want empty", generated)
}
if repo.created != nil {
t.Fatal("conflicting request reached persistence")
}
}
func TestAdminCreateUserRejectsPartialUsernameConflict(t *testing.T) {
existing := &types.User{ID: "existing", Username: "alice", Email: "alice@example.com"}
repo := &adminCreateUserRepo{existingByUsername: existing}
svc := newAdminCreateUserService(repo)
_, _, err := svc.AdminCreateUser(context.Background(), &types.AdminCreateUserRequest{
Username: "alice", Email: "bob@example.com", Password: new("PlainPass9"),
}, types.TenantProvisioningTenantless)
if !errors.Is(err, ErrUserIdentityConflict) {
t.Fatalf("err=%v, want ErrUserIdentityConflict", err)
}
if repo.created != nil {
t.Fatal("conflicting request reached persistence")
}
}
func TestAdminCreateUserRejectsMissingIdentity(t *testing.T) {
repo := &adminCreateUserRepo{}
svc := newAdminCreateUserService(repo)
_, _, err := svc.AdminCreateUser(context.Background(), &types.AdminCreateUserRequest{
Username: "", Email: "alice@example.com",
}, types.TenantProvisioningTenantless)
if err == nil {
t.Fatal("expected an error for an empty username")
}
if repo.created != nil {
t.Fatal("invalid request reached persistence")
}
}