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>
main
parent
f51a139480
commit
ba03be775f
|
|
@ -376,6 +376,40 @@ export async function resetUserPassword(req: ResetUserPasswordRequest): Promise<
|
|||
return response as unknown as { message: string }
|
||||
}
|
||||
|
||||
export interface CreateSystemUserRequest {
|
||||
/** 2-50 characters. */
|
||||
username: string
|
||||
/** Must be a valid email address. */
|
||||
email: string
|
||||
/**
|
||||
* Optional. Omit the key (or send null) to have the server generate a
|
||||
* random password, returned exactly once in `generated_password`.
|
||||
* Any provided value (including empty string) is subject to the
|
||||
* password policy and can be rejected.
|
||||
*/
|
||||
password?: string
|
||||
}
|
||||
|
||||
export interface CreateSystemUserResponse {
|
||||
user: SystemAdminUser
|
||||
/**
|
||||
* Present only when the request omitted `password` (or sent null): the
|
||||
* server-minted plaintext password, returned exactly once and could not
|
||||
* be fetched again.
|
||||
*/
|
||||
generated_password?: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Provision a new local user account (SystemAdmin only).
|
||||
* Backend returns the unwrapped CreateSystemUserResponse body.
|
||||
* Responses 201 on success.
|
||||
*/
|
||||
export async function createSystemUser(req: CreateSystemUserRequest): Promise<CreateSystemUserResponse> {
|
||||
const response = await post('/api/v1/system/admin/users/create', req)
|
||||
return response as unknown as CreateSystemUserResponse
|
||||
}
|
||||
|
||||
// ---- System Settings (P1) ----
|
||||
|
||||
/**
|
||||
|
|
|
|||
|
|
@ -32,6 +32,19 @@ var (
|
|||
jwtSecretOnce sync.Once
|
||||
jwtSecret string
|
||||
|
||||
// ErrUserEmailExists is returned by Register when the target entity's
|
||||
// email already exists.
|
||||
ErrUserEmailExists = errors.New("user with this email already exists")
|
||||
|
||||
// ErrUserUsernameExists is returned by Register when the target entity's
|
||||
// username already exists.
|
||||
ErrUserUsernameExists = errors.New("user with this username already exists")
|
||||
|
||||
// ErrUserIdentityConflict is returned by AdminCreateUser when only part
|
||||
// of the requested identity (email or username) collides with an existing
|
||||
// user, so a blind idempotent retry would return the wrong account.
|
||||
ErrUserIdentityConflict = errors.New("email and username refer to conflicting existing identities")
|
||||
|
||||
// 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
|
||||
|
|
@ -136,12 +149,12 @@ func (s *userService) Register(ctx context.Context, req *types.RegisterRequest)
|
|||
// Check if user already exists
|
||||
existingUser, _ := s.userRepo.GetUserByEmail(ctx, req.Email)
|
||||
if existingUser != nil {
|
||||
return nil, errors.New("user with this email already exists")
|
||||
return nil, ErrUserEmailExists
|
||||
}
|
||||
|
||||
existingUser, _ = s.userRepo.GetUserByUsername(ctx, req.Username)
|
||||
if existingUser != nil {
|
||||
return nil, errors.New("user with this username already exists")
|
||||
return nil, ErrUserUsernameExists
|
||||
}
|
||||
|
||||
// Hash password
|
||||
|
|
@ -723,6 +736,105 @@ func (s *userService) AdminResetPassword(ctx context.Context, userID string, new
|
|||
return s.tokenRepo.RevokeTokensByUserID(ctx, userID)
|
||||
}
|
||||
|
||||
// AdminCreateUser provisions a new local user on behalf of a SystemAdmin.
|
||||
//
|
||||
// An absent password generates a random one, returned exactly once.
|
||||
// Any provided password, must satisfy ValidatePasswordPolicy.
|
||||
//
|
||||
// Delegates to Register, so duplicate checks, tenant provisioning and Owner
|
||||
// membership bootstrapping match public registration.
|
||||
func (s *userService) AdminCreateUser(
|
||||
ctx context.Context,
|
||||
req *types.AdminCreateUserRequest,
|
||||
provisioning types.TenantProvisioningMode,
|
||||
) (*types.User, string, error) {
|
||||
if req == nil || strings.TrimSpace(req.Username) == "" || strings.TrimSpace(req.Email) == "" {
|
||||
return nil, "", errors.New("username and email are required")
|
||||
}
|
||||
|
||||
password := ""
|
||||
generated := false
|
||||
if req.Password == nil {
|
||||
randomPassword, err := generatePolicyCompliantPassword()
|
||||
if err != nil {
|
||||
return nil, "", fmt.Errorf("failed to generate password: %w", err)
|
||||
}
|
||||
password = randomPassword
|
||||
generated = true
|
||||
} else {
|
||||
password = *req.Password
|
||||
}
|
||||
// Generation triggers only on an absent password. Any provided
|
||||
// value, empty or whitespace-only, is hashed byte-for-byte and must
|
||||
// satisfy the password policy.
|
||||
if err := ValidatePasswordPolicy(password); err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
|
||||
user, err := s.Register(ctx, &types.RegisterRequest{
|
||||
Username: strings.TrimSpace(req.Username),
|
||||
Email: strings.TrimSpace(req.Email),
|
||||
Password: password,
|
||||
TenantProvisioning: provisioning,
|
||||
})
|
||||
// WARN: idempotency is sequential only. Two concurrent creates of the
|
||||
// same identity can race past Register's check; the loser gets a 500,
|
||||
// and a retry resolves idempotently.
|
||||
if err != nil {
|
||||
// Register owns duplicate detection; on a duplicate we surface
|
||||
// the existing row so the caller can respond idempotently. The
|
||||
// sentinel names the colliding identity, so the lookup is
|
||||
// targeted at exactly that key.
|
||||
switch {
|
||||
case errors.Is(err, ErrUserEmailExists):
|
||||
return s.adminCreateUserOnDuplicate(
|
||||
ctx, req, err,
|
||||
func(ctx context.Context) (*types.User, error) {
|
||||
return s.userRepo.GetUserByEmail(ctx, strings.TrimSpace(req.Email))
|
||||
},
|
||||
)
|
||||
case errors.Is(err, ErrUserUsernameExists):
|
||||
return s.adminCreateUserOnDuplicate(
|
||||
ctx, req, err,
|
||||
func(ctx context.Context) (*types.User, error) {
|
||||
return s.userRepo.GetUserByUsername(ctx, strings.TrimSpace(req.Username))
|
||||
},
|
||||
)
|
||||
}
|
||||
return nil, "", err
|
||||
}
|
||||
if generated {
|
||||
return user, password, nil
|
||||
}
|
||||
return user, "", nil
|
||||
}
|
||||
|
||||
func (s *userService) adminCreateUserOnDuplicate(
|
||||
ctx context.Context,
|
||||
req *types.AdminCreateUserRequest,
|
||||
dupErr error,
|
||||
lookup func(context.Context) (*types.User, error),
|
||||
) (*types.User, string, error) {
|
||||
existing, lookupErr := lookup(ctx)
|
||||
if lookupErr != nil || existing == nil {
|
||||
return nil, "", dupErr
|
||||
}
|
||||
if adminCreateIdentityMatches(existing, req.Username, req.Email) {
|
||||
return existing, "", dupErr
|
||||
}
|
||||
return nil, "", ErrUserIdentityConflict
|
||||
}
|
||||
|
||||
// adminCreateIdentityMatches reports whether an existing row is the exact
|
||||
// identity an admin create is idempotently retrying (both email and username).
|
||||
func adminCreateIdentityMatches(existing *types.User, username, email string) bool {
|
||||
if existing == nil {
|
||||
return false
|
||||
}
|
||||
return existing.Username == strings.TrimSpace(username) &&
|
||||
existing.Email == strings.TrimSpace(email)
|
||||
}
|
||||
|
||||
// ValidatePassword validates user password
|
||||
func (s *userService) ValidatePassword(ctx context.Context, userID string, password string) error {
|
||||
user, err := s.userRepo.GetUserByID(ctx, userID)
|
||||
|
|
@ -1549,6 +1661,22 @@ func generateRandomString(length int) (string, error) {
|
|||
return base64.RawURLEncoding.EncodeToString(buffer), nil
|
||||
}
|
||||
|
||||
// generatePolicyCompliantPassword returns a cryptographically random
|
||||
// password that satisfies ValidatePasswordPolicy, regenerating until
|
||||
// it does (a single 32-char base64url draw misses digits ~0.4% of the
|
||||
// time).
|
||||
func generatePolicyCompliantPassword() (string, error) {
|
||||
for {
|
||||
password, err := generateRandomString(24)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if ValidatePasswordPolicy(password) == nil {
|
||||
return password, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func decodeJWTClaims(token string) (map[string]interface{}, error) {
|
||||
parts := strings.Split(token, ".")
|
||||
if len(parts) < 2 {
|
||||
|
|
|
|||
|
|
@ -0,0 +1,301 @@
|
|||
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")
|
||||
}
|
||||
}
|
||||
|
|
@ -103,19 +103,27 @@ func (h *AuthHandler) resolveRegistrationMode(ctx context.Context) string {
|
|||
return h.systemSettingSvc.GetString(ctx, "auth.registration_mode", "", def)
|
||||
}
|
||||
|
||||
// resolveDefaultTenantMode returns the provisioning policy for ordinary
|
||||
// public password registrations. Invitation registration never uses this
|
||||
// value: the invitation itself supplies the target tenant.
|
||||
func (h *AuthHandler) resolveDefaultTenantMode(ctx context.Context) types.TenantProvisioningMode {
|
||||
// resolveDefaultTenantMode returns the provisioning policy for a new
|
||||
// local user account.
|
||||
// Priority: DB system_settings > cfg.Auth > hard default (create_personal).
|
||||
// Shared by public registration and the SystemAdmin create-user endpoint.
|
||||
//
|
||||
// Invitation registration never uses this value: the invitation itself
|
||||
// supplies the target tenant.
|
||||
func resolveDefaultTenantMode(
|
||||
ctx context.Context,
|
||||
configInfo *config.Config,
|
||||
systemSettingSvc interfaces.SystemSettingService,
|
||||
) types.TenantProvisioningMode {
|
||||
def := config.AuthDefaultTenantModeCreatePersonal
|
||||
if h.configInfo != nil && h.configInfo.Auth != nil {
|
||||
if mode := strings.TrimSpace(h.configInfo.Auth.DefaultTenantMode); mode != "" {
|
||||
if configInfo != nil && configInfo.Auth != nil {
|
||||
if mode := strings.TrimSpace(configInfo.Auth.DefaultTenantMode); mode != "" {
|
||||
def = mode
|
||||
}
|
||||
}
|
||||
mode := def
|
||||
if h.systemSettingSvc != nil {
|
||||
mode = h.systemSettingSvc.GetString(
|
||||
if systemSettingSvc != nil {
|
||||
mode = systemSettingSvc.GetString(
|
||||
ctx,
|
||||
"auth.default_tenant_mode",
|
||||
"WEKNORA_AUTH_DEFAULT_TENANT_MODE",
|
||||
|
|
@ -128,6 +136,18 @@ func (h *AuthHandler) resolveDefaultTenantMode(ctx context.Context) types.Tenant
|
|||
return types.TenantProvisioningCreatePersonal
|
||||
}
|
||||
|
||||
// resolveDefaultTenantMode returns the provisioning policy for ordinary
|
||||
// public password registrations.
|
||||
func (h *AuthHandler) resolveDefaultTenantMode(ctx context.Context) types.TenantProvisioningMode {
|
||||
return resolveDefaultTenantMode(ctx, h.configInfo, h.systemSettingSvc)
|
||||
}
|
||||
|
||||
// resolveDefaultTenantMode resolves the same policy for users provisioned
|
||||
// by a SystemAdmin via POST /api/v1/system/admin/users/create.
|
||||
func (h *SystemHandler) resolveDefaultTenantMode(ctx context.Context) types.TenantProvisioningMode {
|
||||
return resolveDefaultTenantMode(ctx, h.cfg, h.systemSettingSvc)
|
||||
}
|
||||
|
||||
// Register godoc
|
||||
// @Summary 用户注册
|
||||
// @Description 注册新用户账号
|
||||
|
|
|
|||
|
|
@ -13,6 +13,7 @@ import (
|
|||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/application/repository"
|
||||
"github.com/Tencent/WeKnora/internal/application/service"
|
||||
|
|
@ -1585,6 +1586,98 @@ func (h *SystemHandler) ResetUserPassword(c *gin.Context) {
|
|||
c.JSON(http.StatusOK, gin.H{"message": "Password reset successfully"})
|
||||
}
|
||||
|
||||
// CreateSystemUserResponse is the payload returned by
|
||||
// POST /api/v1/system/admin/users/create. GeneratedPassword is populated
|
||||
// exactly once, only when the server minted a random password (`password`
|
||||
// omitted or null), and is never logged, audited, or retrievable again.
|
||||
type CreateSystemUserResponse struct {
|
||||
User *types.UserInfo `json:"user"`
|
||||
// GeneratedPassword is the plaintext password when the server
|
||||
// auto-generated one. Absent when the caller supplied the password.
|
||||
GeneratedPassword string `json:"generated_password,omitempty"`
|
||||
}
|
||||
|
||||
// CreateSystemUser godoc
|
||||
// @Summary Create a new user (SystemAdmin)
|
||||
// @Description Provision a new local user account (SystemAdmin only).
|
||||
// @Description When `password` is omitted or null, a cryptographically random
|
||||
// @Description password is generated (OIDC-style crypto/rand + base64url)
|
||||
// @Description and returned once in the response body. Any provided value,
|
||||
// @Description including empty string, is policy-checked. Tenant provisioning
|
||||
// @Description follows the shared auth.default_tenant_mode policy.
|
||||
// @Tags System Admin
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param request body types.AdminCreateUserRequest true "User creation request"
|
||||
// @Success 201 {object} CreateSystemUserResponse "User created successfully"
|
||||
// @Success 200 {object} CreateSystemUserResponse "Identity already exists, returns the existing user"
|
||||
// @Failure 400 {object} map[string]interface{} "Invalid request or weak password"
|
||||
// @Failure 403 {object} map[string]interface{} "Forbidden: not a system admin"
|
||||
// @Failure 409 {object} map[string]interface{} "Email and username refer to conflicting identities"
|
||||
// @Failure 500 {object} map[string]interface{} "Internal error"
|
||||
// @Router /system/admin/users/create [post]
|
||||
func (h *SystemHandler) CreateSystemUser(c *gin.Context) {
|
||||
ctx := logger.CloneContext(c.Request.Context())
|
||||
|
||||
var req types.AdminCreateUserRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid user creation request"})
|
||||
return
|
||||
}
|
||||
req.Username = secutils.SanitizeForLog(strings.TrimSpace(req.Username))
|
||||
req.Email = secutils.SanitizeForLog(strings.TrimSpace(req.Email))
|
||||
// Password is intentionally NOT trimmed or sanitized.
|
||||
if req.Username == "" || req.Email == "" {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "Username and email are required"})
|
||||
return
|
||||
}
|
||||
// Binding's min=2/max=50 ran on the raw JSON, re-check the trimmed value.
|
||||
if n := utf8.RuneCountInString(req.Username); n < 2 || n > 50 {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "Username must be 2-50 characters"})
|
||||
return
|
||||
}
|
||||
|
||||
user, generatedPassword, err := h.userSvc.AdminCreateUser(ctx, &req, h.resolveDefaultTenantMode(ctx))
|
||||
if err != nil {
|
||||
switch {
|
||||
case errors.Is(err, service.ErrUserEmailExists) || errors.Is(err, service.ErrUserUsernameExists):
|
||||
if user == nil {
|
||||
logger.Errorf(ctx, "Duplicate identity error without a resolved user: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to create user"})
|
||||
return
|
||||
}
|
||||
logger.Infof(ctx, "Create user noop (identity already exists, ID: %s)", user.ID)
|
||||
h.emitAdminAudit(ctx, types.AuditActionSystemUserCreated, user, map[string]any{
|
||||
"target_email": user.Email,
|
||||
"target_username": user.Username,
|
||||
"password_generated": false,
|
||||
"idempotent": true,
|
||||
})
|
||||
c.JSON(http.StatusOK, CreateSystemUserResponse{User: user.ToUserInfo()})
|
||||
case errors.Is(err, service.ErrPasswordPolicy):
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
case errors.Is(err, service.ErrUserIdentityConflict):
|
||||
c.JSON(http.StatusConflict, gin.H{"error": err.Error()})
|
||||
default:
|
||||
logger.Errorf(ctx, "Failed to create user: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to create user"})
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "System admin created user %s (ID: %s)", user.Username, user.ID)
|
||||
h.emitAdminAudit(ctx, types.AuditActionSystemUserCreated, user, map[string]any{
|
||||
"target_email": user.Email,
|
||||
"target_username": user.Username,
|
||||
"password_generated": generatedPassword != "",
|
||||
"idempotent": false,
|
||||
})
|
||||
c.JSON(http.StatusCreated, CreateSystemUserResponse{
|
||||
User: user.ToUserInfo(),
|
||||
GeneratedPassword: generatedPassword,
|
||||
})
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// System Settings (P1)
|
||||
// ----------------------------------------------------------------------------
|
||||
|
|
|
|||
|
|
@ -0,0 +1,337 @@
|
|||
package handler
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/application/service"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// createUserService records the request handed to AdminCreateUser so
|
||||
// tests can pin byte-for-byte password pass-through and the resolved
|
||||
// tenant provisioning mode.
|
||||
type createUserService struct {
|
||||
interfaces.UserService
|
||||
createdUser *types.User
|
||||
generated string
|
||||
err error
|
||||
gotReq *types.AdminCreateUserRequest
|
||||
gotProvisioning types.TenantProvisioningMode
|
||||
}
|
||||
|
||||
func (s *createUserService) AdminCreateUser(
|
||||
_ context.Context,
|
||||
req *types.AdminCreateUserRequest,
|
||||
provisioning types.TenantProvisioningMode,
|
||||
) (*types.User, string, error) {
|
||||
record := *req
|
||||
s.gotReq = &record
|
||||
s.gotProvisioning = provisioning
|
||||
return s.createdUser, s.generated, s.err
|
||||
}
|
||||
|
||||
func createSystemUserRouter(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/create", h.CreateSystemUser)
|
||||
return r
|
||||
}
|
||||
|
||||
func performCreateSystemUser(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/create", bytes.NewReader(payload))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
w := httptest.NewRecorder()
|
||||
r.ServeHTTP(w, req)
|
||||
return w
|
||||
}
|
||||
|
||||
func TestCreateSystemUserCreatesUserWithExplicitPassword(t *testing.T) {
|
||||
users := &createUserService{createdUser: &types.User{
|
||||
ID: "u1", Username: "alice", Email: "alice@example.com",
|
||||
}}
|
||||
audits := &capturingAuditService{}
|
||||
h := &SystemHandler{userSvc: users, auditSvc: audits}
|
||||
r := createSystemUserRouter(h, "admin-user")
|
||||
|
||||
w := performCreateSystemUser(t, r, map[string]string{
|
||||
"username": "alice", "email": "alice@example.com", "password": "PlainPass9",
|
||||
})
|
||||
if w.Code != http.StatusCreated {
|
||||
t.Fatalf("status=%d body=%s", w.Code, w.Body.String())
|
||||
}
|
||||
var resp CreateSystemUserResponse
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
|
||||
t.Fatalf("unmarshal: %v", err)
|
||||
}
|
||||
if resp.User == nil || resp.User.Username != "alice" || resp.User.Email != "alice@example.com" {
|
||||
t.Fatalf("unexpected user: %+v", resp.User)
|
||||
}
|
||||
if resp.GeneratedPassword != "" {
|
||||
t.Fatalf(
|
||||
"generated_password must be absent when the caller supplied a password, got %q",
|
||||
resp.GeneratedPassword,
|
||||
)
|
||||
}
|
||||
if users.gotReq == nil || users.gotReq.Password == nil || *users.gotReq.Password != "PlainPass9" {
|
||||
t.Fatalf("service received unexpected request: %+v", users.gotReq)
|
||||
}
|
||||
if len(audits.entries) != 1 || audits.entries[0].Action != types.AuditActionSystemUserCreated {
|
||||
t.Fatalf("expected one %s audit entry, got %+v", types.AuditActionSystemUserCreated, audits.entries)
|
||||
}
|
||||
if strings.Contains(string(audits.entries[0].Details), "PlainPass9") {
|
||||
t.Fatal("audit details leaked the password")
|
||||
}
|
||||
if !strings.Contains(string(audits.entries[0].Details), `"password_generated":false`) {
|
||||
t.Fatalf("audit details must mark password_generated=false, got %s", audits.entries[0].Details)
|
||||
}
|
||||
if !strings.Contains(string(audits.entries[0].Details), `"idempotent":false`) {
|
||||
t.Fatalf("audit details must mark idempotent=false, got %s", audits.entries[0].Details)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateSystemUserAutoGeneratesPasswordWhenEmpty(t *testing.T) {
|
||||
users := &createUserService{
|
||||
createdUser: &types.User{ID: "u2", Username: "bob", Email: "bob@example.com"},
|
||||
generated: "G3n3r4t3dP4ssw0rd",
|
||||
}
|
||||
audits := &capturingAuditService{}
|
||||
h := &SystemHandler{userSvc: users, auditSvc: audits}
|
||||
r := createSystemUserRouter(h, "admin-user")
|
||||
|
||||
w := performCreateSystemUser(t, r, map[string]string{
|
||||
"username": "bob", "email": "bob@example.com",
|
||||
})
|
||||
if w.Code != http.StatusCreated {
|
||||
t.Fatalf("status=%d body=%s", w.Code, w.Body.String())
|
||||
}
|
||||
var resp CreateSystemUserResponse
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
|
||||
t.Fatalf("unmarshal: %v", err)
|
||||
}
|
||||
if resp.User == nil || resp.User.Username != "bob" {
|
||||
t.Fatalf("unexpected user: %+v", resp.User)
|
||||
}
|
||||
if resp.GeneratedPassword != "G3n3r4t3dP4ssw0rd" {
|
||||
t.Fatalf("generated_password=%q, want the once-only generated password", resp.GeneratedPassword)
|
||||
}
|
||||
if users.gotReq == nil || users.gotReq.Password != nil {
|
||||
t.Fatalf("absent password must reach the service as nil, got %+v", users.gotReq)
|
||||
}
|
||||
if len(audits.entries) != 1 || audits.entries[0].Action != types.AuditActionSystemUserCreated {
|
||||
t.Fatalf("expected one %s audit entry, got %+v", types.AuditActionSystemUserCreated, audits.entries)
|
||||
}
|
||||
if !strings.Contains(string(audits.entries[0].Details), "password_generated") {
|
||||
t.Fatal("audit details must carry the password_generated flag")
|
||||
}
|
||||
if strings.Contains(string(audits.entries[0].Details), "G3n3r4t3dP4ssw0rd") {
|
||||
t.Fatal("audit details leaked the generated password")
|
||||
}
|
||||
if !strings.Contains(string(audits.entries[0].Details), `"password_generated":true`) {
|
||||
t.Fatalf("audit details must mark password_generated=true, got %s", audits.entries[0].Details)
|
||||
}
|
||||
if !strings.Contains(string(audits.entries[0].Details), `"idempotent":false`) {
|
||||
t.Fatalf("audit details must mark idempotent=false, got %s", audits.entries[0].Details)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateSystemUserDoesNotRewritePassword(t *testing.T) {
|
||||
// Password bytes must reach the service unmodified for valid credentials.
|
||||
users := &createUserService{createdUser: &types.User{ID: "u3", Username: "carol", Email: "carol@example.com"}}
|
||||
h := &SystemHandler{userSvc: users}
|
||||
r := createSystemUserRouter(h, "admin-user")
|
||||
|
||||
for _, pw := range []string{" PlainPass9 ", "\tPlainPass9\n"} {
|
||||
w := performCreateSystemUser(t, r, map[string]string{
|
||||
"username": "carol", "email": "carol@example.com", "password": pw,
|
||||
})
|
||||
if w.Code != http.StatusCreated {
|
||||
t.Fatalf("password=%q status=%d body=%s", pw, w.Code, w.Body.String())
|
||||
}
|
||||
if users.gotReq == nil || users.gotReq.Password == nil || *users.gotReq.Password != pw {
|
||||
t.Fatalf("password=%q service received %+v", pw, users.gotReq)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateSystemUserMapsEmptyPasswordTo400(t *testing.T) {
|
||||
users := &createUserService{err: service.ErrPasswordPolicy}
|
||||
h := &SystemHandler{userSvc: users}
|
||||
r := createSystemUserRouter(h, "admin-user")
|
||||
|
||||
w := performCreateSystemUser(t, r, map[string]string{
|
||||
"username": "carol", "email": "carol@example.com", "password": "",
|
||||
})
|
||||
if w.Code != http.StatusBadRequest {
|
||||
t.Fatalf("status=%d body=%s", w.Code, w.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateSystemUserMapsIdentityConflictTo409(t *testing.T) {
|
||||
users := &createUserService{err: service.ErrUserIdentityConflict}
|
||||
audits := &capturingAuditService{}
|
||||
h := &SystemHandler{userSvc: users, auditSvc: audits}
|
||||
r := createSystemUserRouter(h, "admin-user")
|
||||
|
||||
w := performCreateSystemUser(t, r, map[string]string{
|
||||
"username": "alice", "email": "bob@example.com",
|
||||
})
|
||||
if w.Code != http.StatusConflict {
|
||||
t.Fatalf("status=%d body=%s", w.Code, w.Body.String())
|
||||
}
|
||||
if len(audits.entries) != 0 {
|
||||
t.Fatalf("conflict emitted audit entries: %+v", audits.entries)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateSystemUserResolvesDefaultTenantMode(t *testing.T) {
|
||||
users := &createUserService{createdUser: &types.User{ID: "u4", Username: "dave", Email: "dave@example.com"}}
|
||||
h := &SystemHandler{userSvc: users}
|
||||
r := createSystemUserRouter(h, "admin-user")
|
||||
|
||||
w := performCreateSystemUser(t, r, map[string]string{
|
||||
"username": "dave", "email": "dave@example.com",
|
||||
})
|
||||
if w.Code != http.StatusCreated {
|
||||
t.Fatalf("status=%d body=%s", w.Code, w.Body.String())
|
||||
}
|
||||
if users.gotProvisioning != types.TenantProvisioningCreatePersonal {
|
||||
t.Fatalf("provisioning=%v, want create_personal default", users.gotProvisioning)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateSystemUserMapsPasswordPolicyTo400(t *testing.T) {
|
||||
users := &createUserService{err: service.ErrPasswordPolicy}
|
||||
h := &SystemHandler{userSvc: users}
|
||||
r := createSystemUserRouter(h, "admin-user")
|
||||
|
||||
w := performCreateSystemUser(t, r, map[string]string{
|
||||
"username": "alice", "email": "alice@example.com", "password": "password",
|
||||
})
|
||||
if w.Code != http.StatusBadRequest {
|
||||
t.Fatalf("status=%d body=%s", w.Code, w.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateSystemUserDuplicateIdentityReturnsExistingUser(t *testing.T) {
|
||||
// Idempotent contract: when the identity already exists the service
|
||||
// returns the existing user with ErrUserEmailExists/ErrUserUsernameExists,
|
||||
// and the handler answers 200 with the existing UserInfo, an empty
|
||||
// generated_password and an audit row marked idempotent.
|
||||
users := &createUserService{
|
||||
createdUser: &types.User{ID: "existing", Username: "alice", Email: "alice@example.com"},
|
||||
err: service.ErrUserUsernameExists,
|
||||
}
|
||||
audits := &capturingAuditService{}
|
||||
h := &SystemHandler{userSvc: users, auditSvc: audits}
|
||||
r := createSystemUserRouter(h, "admin-user")
|
||||
|
||||
w := performCreateSystemUser(t, r, map[string]string{
|
||||
"username": "alice", "email": "alice@example.com",
|
||||
})
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("status=%d body=%s", w.Code, w.Body.String())
|
||||
}
|
||||
var resp CreateSystemUserResponse
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
|
||||
t.Fatalf("unmarshal: %v", err)
|
||||
}
|
||||
if resp.User == nil || resp.User.ID != "existing" {
|
||||
t.Fatalf("unexpected user: %+v", resp.User)
|
||||
}
|
||||
if resp.GeneratedPassword != "" {
|
||||
t.Fatalf("generated_password=%q, want empty for an existing user", resp.GeneratedPassword)
|
||||
}
|
||||
if len(audits.entries) != 1 || audits.entries[0].Action != types.AuditActionSystemUserCreated {
|
||||
t.Fatalf("expected one %s audit entry, got %+v", types.AuditActionSystemUserCreated, audits.entries)
|
||||
}
|
||||
if !strings.Contains(string(audits.entries[0].Details), `"idempotent":true`) {
|
||||
t.Fatalf("audit details must mark idempotent=true, got %s", audits.entries[0].Details)
|
||||
}
|
||||
if !strings.Contains(string(audits.entries[0].Details), `"password_generated":false`) {
|
||||
t.Fatalf("audit details must mark password_generated=false, got %s", audits.entries[0].Details)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateSystemUserMapsInternalErrorTo500(t *testing.T) {
|
||||
users := &createUserService{err: errors.New("transient db hiccup")}
|
||||
audits := &capturingAuditService{}
|
||||
h := &SystemHandler{userSvc: users, auditSvc: audits}
|
||||
r := createSystemUserRouter(h, "admin-user")
|
||||
|
||||
w := performCreateSystemUser(t, r, map[string]string{
|
||||
"username": "alice", "email": "alice@example.com",
|
||||
})
|
||||
if w.Code != http.StatusInternalServerError {
|
||||
t.Fatalf("status=%d body=%s", w.Code, w.Body.String())
|
||||
}
|
||||
if len(audits.entries) != 0 {
|
||||
t.Fatalf("failed creation emitted audit entries: %+v", audits.entries)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateSystemUserRejectsMissingFields(t *testing.T) {
|
||||
h := &SystemHandler{}
|
||||
r := createSystemUserRouter(h, "admin-user")
|
||||
|
||||
cases := []map[string]string{
|
||||
{"email": "alice@example.com"},
|
||||
{"username": "alice"},
|
||||
{"username": "", "email": "alice@example.com"},
|
||||
{"username": "alice", "email": ""},
|
||||
{"username": " ", "email": "alice@example.com"},
|
||||
// Binding's min=2 ran on the raw JSON; the trimmed value "a" (1
|
||||
// rune) must be rejected by the post-trim re-check.
|
||||
{"username": " a ", "email": "alice@example.com"},
|
||||
}
|
||||
for _, body := range cases {
|
||||
w := performCreateSystemUser(t, r, body)
|
||||
if w.Code != http.StatusBadRequest {
|
||||
t.Fatalf("body=%v status=%d body=%s", body, w.Code, w.Body.String())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateSystemUserRejectsInvalidEmail(t *testing.T) {
|
||||
h := &SystemHandler{}
|
||||
r := createSystemUserRouter(h, "admin-user")
|
||||
|
||||
w := performCreateSystemUser(t, r, map[string]string{
|
||||
"username": "alice", "email": "not-an-email",
|
||||
})
|
||||
if w.Code != http.StatusBadRequest {
|
||||
t.Fatalf("status=%d body=%s", w.Code, w.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateSystemUserRejectsMalformedJSON(t *testing.T) {
|
||||
h := &SystemHandler{}
|
||||
r := createSystemUserRouter(h, "admin-user")
|
||||
|
||||
req := httptest.NewRequest(http.MethodPost, "/system/admin/users/create",
|
||||
bytes.NewReader([]byte(`{"username": "alice"`)))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
w := httptest.NewRecorder()
|
||||
r.ServeHTTP(w, req)
|
||||
if w.Code != http.StatusBadRequest {
|
||||
t.Fatalf("status=%d body=%s", w.Code, w.Body.String())
|
||||
}
|
||||
}
|
||||
|
|
@ -263,6 +263,7 @@ func RegisterSystemAdminRoutes(
|
|||
adminRoutes.POST("/revoke", handler.RevokeSystemAdmin)
|
||||
adminRoutes.GET("/list", handler.ListSystemAdmins)
|
||||
adminRoutes.POST("/users/reset-password", handler.ResetUserPassword)
|
||||
adminRoutes.POST("/users/create", handler.CreateSystemUser)
|
||||
adminRoutes.GET("/api-keys", handler.ListPlatformAPIKeys)
|
||||
adminRoutes.POST("/api-keys", handler.CreatePlatformAPIKey)
|
||||
adminRoutes.DELETE("/api-keys/:key_id", handler.DeletePlatformAPIKey)
|
||||
|
|
|
|||
|
|
@ -121,8 +121,16 @@ const (
|
|||
// 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"
|
||||
AuditActionSystemAPIKeyCreated AuditAction = "system.api_key_created"
|
||||
AuditActionSystemAPIKeyRevoked AuditAction = "system.api_key_revoked"
|
||||
|
||||
// AuditActionSystemUserCreated fires when a SystemAdmin provisions a
|
||||
// new local user via POST /api/v1/system/admin/users/create. Details
|
||||
// carry {target_email, target_username, password_generated, idempotent}
|
||||
// password_generated=true only on the create path, idempotent=true
|
||||
// marks a no-op hit on an already-existing identity.
|
||||
// TenantID=0 (system-scope).
|
||||
AuditActionSystemUserCreated AuditAction = "system.user_created"
|
||||
AuditActionSystemAPIKeyCreated AuditAction = "system.api_key_created"
|
||||
AuditActionSystemAPIKeyRevoked AuditAction = "system.api_key_revoked"
|
||||
|
||||
// Runtime queue mutations are privileged SystemAdmin actions. Retrying an
|
||||
// archived task can repeat its original side effects; deleting one removes
|
||||
|
|
|
|||
|
|
@ -125,6 +125,7 @@ func TestAuditAction_NoCollisionsAcrossNamespaces(t *testing.T) {
|
|||
register("AuditActionSystemAdminPromoted", AuditActionSystemAdminPromoted)
|
||||
register("AuditActionSystemAdminRevoked", AuditActionSystemAdminRevoked)
|
||||
register("AuditActionSystemUserPasswordReset", AuditActionSystemUserPasswordReset)
|
||||
register("AuditActionSystemUserCreated", AuditActionSystemUserCreated)
|
||||
register("AuditActionSystemQueueTaskRetried", AuditActionSystemQueueTaskRetried)
|
||||
register("AuditActionSystemQueueTaskDeleted", AuditActionSystemQueueTaskDeleted)
|
||||
register("AuditActionSystemQueueTaskRunNow", AuditActionSystemQueueTaskRunNow)
|
||||
|
|
@ -144,6 +145,7 @@ func TestAuditAction_SystemNamespacePrefix(t *testing.T) {
|
|||
AuditActionSystemAdminPromoted,
|
||||
AuditActionSystemAdminRevoked,
|
||||
AuditActionSystemUserPasswordReset,
|
||||
AuditActionSystemUserCreated,
|
||||
AuditActionSystemQueueTaskRetried,
|
||||
AuditActionSystemQueueTaskDeleted,
|
||||
AuditActionSystemQueueTaskRunNow,
|
||||
|
|
@ -171,6 +173,7 @@ func TestAuditAction_SystemWireValues(t *testing.T) {
|
|||
{AuditActionSystemAdminPromoted, "system.admin_promoted"},
|
||||
{AuditActionSystemAdminRevoked, "system.admin_revoked"},
|
||||
{AuditActionSystemUserPasswordReset, "system.user_password_reset"},
|
||||
{AuditActionSystemUserCreated, "system.user_created"},
|
||||
{AuditActionSystemQueueTaskRetried, "system.queue_task_retried"},
|
||||
{AuditActionSystemQueueTaskDeleted, "system.queue_task_deleted"},
|
||||
{AuditActionSystemQueueTaskRunNow, "system.queue_task_run_now"},
|
||||
|
|
|
|||
|
|
@ -79,6 +79,13 @@ type UserService interface {
|
|||
// callers pass offset/limit to page through results. Used by the
|
||||
// /api/v1/system/admin/list endpoint, gated to SystemAdmin callers.
|
||||
ListSystemAdmins(ctx context.Context, offset, limit int) ([]*types.User, int64, error)
|
||||
// AdminCreateUser provisions a new local user on behalf of a
|
||||
// SystemAdmin. When req.Password is nil, a random password is generated
|
||||
// and returned exactly once as the second result. provisioning is
|
||||
// resolved by the caller from the shared auth.default_tenant_mode policy.
|
||||
AdminCreateUser(
|
||||
ctx context.Context, req *types.AdminCreateUserRequest, provisioning types.TenantProvisioningMode,
|
||||
) (*types.User, string, error)
|
||||
// RevokeSystemAdmin removes system-admin privileges with the
|
||||
// last-admin/self-revoke checks performed atomically.
|
||||
RevokeSystemAdmin(ctx context.Context, userID, actorID string) (*types.User, error)
|
||||
|
|
|
|||
|
|
@ -194,6 +194,18 @@ type RegisterRequest struct {
|
|||
TenantProvisioning TenantProvisioningMode `json:"-"`
|
||||
}
|
||||
|
||||
// AdminCreateUserRequest is the payload for a SystemAdmin provisioning a
|
||||
// new local user via POST /api/v1/system/admin/users/create.
|
||||
//
|
||||
// Password is optional: when absent (or null), the service generates a
|
||||
// random one and returns it exactly once. Any provided value, the
|
||||
// empty string included, is subject to the password policy.
|
||||
type AdminCreateUserRequest struct {
|
||||
Username string `json:"username" binding:"required,min=2,max=50"`
|
||||
Email string `json:"email" binding:"required,email"`
|
||||
Password *string `json:"password"`
|
||||
}
|
||||
|
||||
// TenantProvisioningMode controls what UserService.Register does after it
|
||||
// has validated the identity fields. Joining an existing tenant is
|
||||
// orchestrated by the invitation handler because the invitation token is the
|
||||
|
|
|
|||
Loading…
Reference in New Issue