Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.
Go agentagenticaichatbotdsh-pluginembeddingsevaluationgenerative-aigolangknowledge-basellmmulti-tenantollamaopenaiquestion-answeringragrerankingsemantic-searchvector-searchwiki
feat: support complex password (#2929)
cainbita55f4b78341f
diff --git a/.env.example b/.env.exampleindex 903eb4d68..75842ffe2 100644--- a/.env.example+++ b/.env.example@@ -534,6 +534,8 @@ SYSTEM_AES_KEY=weknora-system-aes-key-32bytes!!# ========== F2. 注册与空间策略 ==========# 禁止新用户注册(生产建议 true)。# DISABLE_REGISTRATION=false+# 开启后密码必须包含大小写字母、数字和特殊字符,特殊字符包含:!@#$%^&*()_+-=[]{}|;:,.<>?+# WEKNORA_AUTH_COMPLEX_PASSWORD_ENABLED=false# 公开注册后的默认空间策略:create_personal(默认,自动创建个人空间)/ tenantless。# WEKNORA_AUTH_DEFAULT_TENANT_MODE=create_personal# 是否允许普通用户登录后主动创建空间(默认 true;false 仅能邀请加入,超管不受影响)。diff --git a/client/auth.go b/client/auth.goindex c22f6178a..ef32a1409 100644--- a/client/auth.go+++ b/client/auth.go@@ -199,3 +199,26 @@ func (c *Client) ChangePassword(ctx context.Context, req ChangePasswordRequest)}return &out, nil}++// AuthConfigResponse is returned by GET /api/v1/auth/config.+// The endpoint is unauthenticated so the SPA can decide whether to show+// the register tab and which password complexity rules to apply.+type AuthConfigResponse struct {+ Success bool `json:"success"`+ RegistrationMode string `json:"registration_mode"`+ ComplexPasswordEnabled bool `json:"complex_password_enabled"`+}++// GetAuthConfig fetches public authentication settings.+// Maps to GET /api/v1/auth/config.+func (c *Client) GetAuthConfig(ctx context.Context) (*AuthConfigResponse, error) {+ resp, err := c.doRequest(ctx, http.MethodGet, "/api/v1/auth/config", nil, nil)+ if err != nil {+ return nil, fmt.Errorf("get auth config: %w", err)+ }+ var out AuthConfigResponse+ if err := parseResponse(resp, &out); err != nil {+ return nil, err+ }+ return &out, nil+}diff --git a/docker-compose.yml b/docker-compose.ymlindex 33cf583f4..4e8d1bfb5 100644--- a/docker-compose.yml+++ b/docker-compose.yml@@ -107,6 +107,8 @@ services:# 认证 / 空间 / RBAC / 审计# 禁止新用户注册(生产建议 true)- DISABLE_REGISTRATION=${DISABLE_REGISTRATION:-false}+ # 开启后密码必须包含大小写字母、数字和特殊字符,特殊字符包含:!@#$%^&*()_+-=[]{}|;:,.<>?+ - WEKNORA_AUTH_COMPLEX_PASSWORD_ENABLED=${WEKNORA_AUTH_COMPLEX_PASSWORD_ENABLED:-false}# 公开注册后的默认空间策略:create_personal(默认,自动创建个人空间)/ tenantless- WEKNORA_AUTH_DEFAULT_TENANT_MODE=${WEKNORA_AUTH_DEFAULT_TENANT_MODE:-create_personal}# 是否允许普通用户登录后主动创建空间(默认 true;false 仅能邀请加入,超管不受影响)diff --git a/docs/api/auth.md b/docs/api/auth.mdindex 8999914ed..79f9e54b2 100644--- a/docs/api/auth.md+++ b/docs/api/auth.md@@ -10,17 +10,18 @@ WeKnora 的 `/auth/*` 端点本身**不需要 X-API-Key**,但部分端点需| 端点 | 鉴权方式 || --- | --- |-| `/auth/register` `/auth/login` | 无 |+| `/auth/register` `/auth/login` `/auth/config` | 无 || `/auth/oidc/config` `/auth/oidc/url` `/auth/oidc/callback` | 无 || `/auth/refresh` | refresh_token(请求体携带) || `/auth/validate` `/auth/me` `/auth/logout` `/auth/change-password` | Bearer JWT |-注册接口可通过环境变量 `DISABLE_REGISTRATION=true` 关闭。+注册接口可通过环境变量 `DISABLE_REGISTRATION=true` 关闭。密码策略默认 8–32 位且同时包含字母与数字;部署可通过环境变量 `WEKNORA_AUTH_COMPLEX_PASSWORD_ENABLED` 或系统设置 `auth.complex_password_enabled` 要求额外包含大小写字母与特殊字符。当前策略见 `GET /auth/config`。## 端点一览| 方法 | 路径 | 描述 || ---- | -------------------------- | ------------------------------------------ |+| GET | `/auth/config` | 公开认证配置(注册模式、密码复杂度) || POST | `/auth/register` | 用户注册 || POST | `/auth/login` | 用户登录 || GET | `/auth/oidc/config` | 获取 OIDC 配置元数据 |@@ -34,6 +35,27 @@ WeKnora 的 `/auth/*` 端点本身**不需要 X-API-Key**,但部分端点需---+## GET `/auth/config` - 公开认证配置++无需登录。前端用它决定是否展示注册入口,以及注册/改密表单应使用哪套密码规则。++**响应**:++```json+{+ "success": true,+ "registration_mode": "self_serve",+ "complex_password_enabled": false+}+```++| 字段 | 说明 |+| ---- | ---- |+| `registration_mode` | `self_serve` 允许公开注册;`invite_only` 仅邀请 |+| `complex_password_enabled` | `true` 时新密码须含大小写字母、数字和特殊字符 `!@#$%^&*()_+-=[]{}|;:,.<>?` |++---+## POST `/auth/register` - 用户注册**参数说明(请求体)**:@@ -42,7 +64,7 @@ WeKnora 的 `/auth/*` 端点本身**不需要 X-API-Key**,但部分端点需| -------- | ------ | ---- | -------------------------- | --------- || username | string | 是 | 长度 2-50 | 用户名 || email | string | 是 | 邮箱格式 | 邮箱 |-| password | string | 是 | 最少 6 位 | 密码 |+| password | string | 是 | 8–32 位,须含字母与数字;若 `complex_password_enabled` 则还须含大小写与特殊字符 | 密码 |**请求**:@@ -336,14 +358,14 @@ curl --location 'http://localhost:8080/api/v1/auth/me' \## POST `/auth/change-password` - 修改密码-修改当前用户的登录密码。新密码须满足 **8–32 位**且**同时包含字母与数字**;不能与当前密码相同。成功后**所有会话被撤销**,需使用新密码重新登录。+修改当前用户的登录密码。新密码须满足 **8–32 位**且**同时包含字母与数字**;当 `GET /auth/config` 的 `complex_password_enabled` 为 true 时,还须包含大小写字母与特殊字符。不能与当前密码相同。成功后**所有会话被撤销**,需使用新密码重新登录。**参数说明(请求体)**:| 字段 | 类型 | 必填 | 校验 | 说明 || ------------- | ------ | ---- | ------- | --------- || old_password | string | 是 | | 当前密码 |-| new_password | string | 是 | 8–32 位,须含字母与数字,且不同于旧密码 | 新密码 |+| new_password | string | 是 | 8–32 位,须含字母与数字(复杂模式另需大小写与特殊字符),且不同于旧密码 | 新密码 |**请求**:diff --git a/docs/docs.go b/docs/docs.goindex 799153fed..acc16b183 100644--- a/docs/docs.go+++ b/docs/docs.go@@ -825,7 +825,7 @@ const docTemplate = `{"Bearer": []}],- "description": "修改当前用户的登录密码。新密码须满足 8–32 位且同时包含字母与数字;成功后所有会话被撤销,需重新登录。",+ "description": "修改当前用户的登录密码。新密码须满足 8–32 位且同时包含字母与数字;开启复杂密码后还需包含大小写与特殊字符。成功后所有会话被撤销,需重新登录。","consumes": ["application/json"],@@ -874,7 +874,7 @@ const docTemplate = `{},"/auth/config": {"get": {- "description": "返回当前部署的注册模式等公开认证配置,供前端决定是否展示注册入口",+ "description": "返回当前部署的注册模式与密码复杂度开关,供前端决定是否展示注册入口以及密码校验规则","consumes": ["application/json"],diff --git a/docs/swagger.json b/docs/swagger.jsonindex 90c634165..46ee83e64 100644--- a/docs/swagger.json+++ b/docs/swagger.json@@ -818,7 +818,7 @@"Bearer": []}],- "description": "修改当前用户的登录密码。新密码须满足 8–32 位且同时包含字母与数字;成功后所有会话被撤销,需重新登录。",+ "description": "修改当前用户的登录密码。新密码须满足 8–32 位且同时包含字母与数字;开启复杂密码后还需包含大小写与特殊字符。成功后所有会话被撤销,需重新登录。","consumes": ["application/json"],@@ -867,7 +867,7 @@},"/auth/config": {"get": {- "description": "返回当前部署的注册模式等公开认证配置,供前端决定是否展示注册入口",+ "description": "返回当前部署的注册模式与密码复杂度开关,供前端决定是否展示注册入口以及密码校验规则","consumes": ["application/json"],diff --git a/docs/swagger.yaml b/docs/swagger.yamlindex af472bbd2..bee859abf 100644--- a/docs/swagger.yaml+++ b/docs/swagger.yaml@@ -6810,7 +6810,7 @@ paths:post:consumes:- application/json- description: 修改当前用户的登录密码。新密码须满足 8–32 位且同时包含字母与数字;成功后所有会话被撤销,需重新登录。+ description: 修改当前用户的登录密码。新密码须满足 8–32 位且同时包含字母与数字;开启复杂密码后还需包含大小写与特殊字符。成功后所有会话被撤销,需重新登录。parameters:- description: 密码修改请求in: body@@ -6844,7 +6844,7 @@ paths:get:consumes:- application/json- description: 返回当前部署的注册模式等公开认证配置,供前端决定是否展示注册入口+ description: 返回当前部署的注册模式与密码复杂度开关,供前端决定是否展示注册入口以及密码校验规则produces:- application/jsonresponses:diff --git a/frontend/src/api/auth/index.ts b/frontend/src/api/auth/index.tsindex ab730caa4..6d57d3087 100644--- a/frontend/src/api/auth/index.ts+++ b/frontend/src/api/auth/index.ts@@ -262,6 +262,7 @@ export async function getOIDCConfig(): Promise<OIDCConfigResponse> {export interface AuthConfigResponse {success: booleanregistration_mode: 'self_serve' | 'invite_only' | string+ complex_password_enabled: boolean}export async function getAuthConfig(): Promise<AuthConfigResponse> {@@ -269,7 +270,7 @@ export async function getAuthConfig(): Promise<AuthConfigResponse> {const response = await get('/api/v1/auth/config')return response as unknown as AuthConfigResponse} catch {- return { success: false, registration_mode: 'self_serve' }+ return { success: false, registration_mode: 'self_serve', complex_password_enabled: false }}}diff --git a/frontend/src/i18n/locales/en-US.ts b/frontend/src/i18n/locales/en-US.tsindex 93df18799..8b7bfaa97 100755--- a/frontend/src/i18n/locales/en-US.ts+++ b/frontend/src/i18n/locales/en-US.ts@@ -2124,7 +2124,7 @@ export default {subtitle: 'RAG Q&A, ReAct Agent and Wiki — an LLM-powered enterprise knowledge framework',registerSubtitle: 'Create your account and start using WeKnora',emailPlaceholder: 'Enter email address',- passwordPlaceholder: 'Enter password (8-32 characters, including letters and numbers)',+ passwordPlaceholder: 'Enter password',confirmPasswordPlaceholder: 'Enter password again',usernamePlaceholder: 'Enter username',emailRequired: 'Enter email address',@@ -2133,7 +2133,10 @@ export default {passwordMinLength: 'Password must be at least 8 characters',passwordMaxLength: 'Password cannot exceed 32 characters',passwordMustContainLetter: 'Password must contain letters',+ passwordMustContainLowercaseLetter: 'Password must contain lowercase letters',+ passwordMustContainUppercaseLetter: 'Password must contain uppercase letters',passwordMustContainNumber: 'Password must contain numbers',+ passwordMustContainSpecialChar: 'Password must contain special characters: {specialChars}',usernameRequired: 'Enter username',usernameMinLength: 'Username must be at least 2 characters',usernameMaxLength: 'Username cannot exceed 20 characters',@@ -3852,7 +3855,8 @@ export default {keyLabels: {auth: {registration_mode: 'Self-service registration mode',- default_tenant_mode: 'Default workspace provisioning'+ default_tenant_mode: 'Default workspace provisioning',+ complex_password_enabled: 'Require complex password'},ssrf: {whitelist: 'SSRF protection allowlist'@@ -3878,7 +3882,8 @@ export default {keyDescriptions: {auth: {registration_mode: 'Self-service registration mode. self_serve = anyone can register an account; invite_only = public registration is disabled and only Owners/Admins can invite. Takes effect immediately after saving, but use self_serve with care (the public internet will send spam sign-ups).',- default_tenant_mode: 'Workspace provisioning after public registration. create_personal creates an Owner workspace; tenantless creates only the account until the user accepts an invitation or creates a workspace. Applies to new users only.'+ default_tenant_mode: 'Workspace provisioning after public registration. create_personal creates an Owner workspace; tenantless creates only the account until the user accepts an invitation or creates a workspace. Applies to new users only.',+ complex_password_enabled: 'Whether to require complex passwords. When enabled, passwords must contain uppercase and lowercase letters, numbers, and special characters. Changes take effect immediately and only apply to newly registered users or new password changes/resets. Special characters include {specialChars}'},ssrf: {whitelist: 'SSRF protection allowlist. Accepts entries such as example.com / *.foo.com / 10.0.0.0/8 / 2001:db8::1. Takes effect immediately after saving. The SSRF_WHITELIST_EXTRA environment variable is still maintained by the deployer and is not overridden here.'@@ -3977,22 +3982,12 @@ export default {emailLabel: 'User email',emailPlaceholder: 'Enter the email of the user to reset',newPasswordLabel: 'New password',- newPasswordPlaceholder: '8-32 characters, including letters and numbers',+ newPasswordPlaceholder: 'Enter new password',confirmPasswordLabel: 'Confirm new password',confirmPasswordPlaceholder: 'Enter the new password again',confirmBtn: 'Confirm reset',success: 'Password reset; the user\'s existing sessions were revoked',failed: 'Failed to reset password',- validation: {- emailRequired: 'Enter the user email',- emailInvalid: 'Enter a valid email address',- passwordRequired: 'Enter a new password',- passwordLength: 'Password must be 8-32 characters',- passwordLetter: 'Password must contain a letter',- passwordNumber: 'Password must contain a number',- confirmRequired: 'Enter the new password again',- passwordMismatch: 'The passwords do not match'- }},bulkApply: {label: 'Apply to all existing workspaces',@@ -6422,7 +6417,7 @@ export default {currentPlaceholder: 'Enter your current password',currentRequired: 'Enter your current password',newLabel: 'New password',- newPlaceholder: '8-32 characters, include letters and numbers',+ newPlaceholder: 'Enter new password',confirmLabel: 'Confirm new password',confirmPlaceholder: 'Enter the new password again',submit: 'Update password',diff --git a/frontend/src/i18n/locales/ko-KR.ts b/frontend/src/i18n/locales/ko-KR.tsindex a2a5e0acf..c9d44dbbe 100755--- a/frontend/src/i18n/locales/ko-KR.ts+++ b/frontend/src/i18n/locales/ko-KR.ts@@ -234,7 +234,7 @@ export default {currentPlaceholder: '현재 비밀번호를 입력하세요',currentRequired: '현재 비밀번호를 입력하세요',newLabel: '새 비밀번호',- newPlaceholder: '8-32자, 문자와 숫자 포함',+ newPlaceholder: '새 비밀번호 입력',confirmLabel: '새 비밀번호 확인',confirmPlaceholder: '새 비밀번호를 다시 입력하세요',submit: '비밀번호 업데이트',@@ -2722,22 +2722,12 @@ export default {emailLabel: '사용자 이메일',emailPlaceholder: '비밀번호를 재설정할 사용자의 이메일 입력',newPasswordLabel: '새 비밀번호',- newPasswordPlaceholder: '8~32자, 문자와 숫자 포함',+ newPasswordPlaceholder: '새 비밀번호 입력',confirmPasswordLabel: '새 비밀번호 확인',confirmPasswordPlaceholder: '새 비밀번호를 다시 입력',confirmBtn: '재설정 확인',success: '비밀번호가 재설정되고 기존 세션이 만료되었습니다',failed: '비밀번호 재설정 실패',- validation: {- emailRequired: '사용자 이메일을 입력하세요',- emailInvalid: '올바른 이메일 주소를 입력하세요',- passwordRequired: '새 비밀번호를 입력하세요',- passwordLength: '비밀번호는 8~32자여야 합니다',- passwordLetter: '비밀번호에 문자가 포함되어야 합니다',- passwordNumber: '비밀번호에 숫자가 포함되어야 합니다',- confirmRequired: '새 비밀번호를 다시 입력하세요',- passwordMismatch: '비밀번호가 일치하지 않습니다'- }},admins: {label: '시스템 관리자',@@ -2829,7 +2819,8 @@ export default {},auth: {registration_mode: '셀프 가입 모드입니다. self_serve = 누구나 계정을 만들 수 있음; invite_only = 공개 가입을 끄고 Owner/Admin만 초대 가능. 저장 즉시 적용되며, self_serve는 스팸 가입이 들어올 수 있으니 신중히 사용하세요.',- default_tenant_mode: '공개 가입 후 공간 초기화 정책입니다. create_personal은 개인 공간을 만들고 Owner를 부여하며, tenantless는 초대 수락 또는 직접 공간 생성 전까지 계정만 만듭니다.'+ default_tenant_mode: '공개 가입 후 공간 초기화 정책입니다. create_personal은 개인 공간을 만들고 Owner를 부여하며, tenantless는 초대 수락 또는 직접 공간 생성 전까지 계정만 만듭니다.',+ complex_password_enabled: '복잡한 비밀번호를 사용할지 여부입니다. 활성화하면 비밀번호에 대문자, 소문자, 숫자 및 특수 문자가 포함되어야 합니다. 변경 사항은 즉시 적용되며, 새로 가입하는 사용자 또는 비밀번호를 새로 변경하거나 재설정하는 경우에만 적용됩니다. 특수 문자는 다음을 포함합니다: {specialChars}'}},keyLabels: {@@ -2855,7 +2846,8 @@ export default {},auth: {registration_mode: '셀프 가입 모드',- default_tenant_mode: '기본 공간 프로비저닝'+ default_tenant_mode: '기본 공간 프로비저닝',+ complex_password_enabled: '복잡한 비밀번호 사용'}},runtime: {@@ -4527,7 +4519,7 @@ export default {subtitle: 'RAG Q&A, ReAct 에이전트, Wiki 지식베이스 — 대규모 언어 모델 기반 엔터프라이즈 지식 프레임워크',registerSubtitle: '계정을 만들고 WeKnora를 시작하세요',emailPlaceholder: '이메일 주소 입력',- passwordPlaceholder: '비밀번호 입력 (8-32자, 문자와 숫자 포함)',+ passwordPlaceholder: '비밀번호 입력',confirmPasswordPlaceholder: '비밀번호 다시 입력',usernamePlaceholder: '사용자명 입력',emailRequired: '이메일 주소를 입력해주세요',@@ -4536,7 +4528,10 @@ export default {passwordMinLength: '비밀번호는 최소 8자여야 합니다',passwordMaxLength: '비밀번호는 32자를 초과할 수 없습니다',passwordMustContainLetter: '비밀번호에 문자가 포함되어야 합니다',+ passwordMustContainLowercaseLetter: '비밀번호에는 소문자가 포함되어야 합니다',+ passwordMustContainUppercaseLetter: '비밀번호에는 대문자가 포함되어야 합니다',passwordMustContainNumber: '비밀번호에 숫자가 포함되어야 합니다',+ passwordMustContainSpecialChar: '비밀번호에는 특수문자가 포함되어야 합니다: {specialChars}',usernameRequired: '사용자명을 입력해주세요',usernameMinLength: '사용자명은 최소 2자여야 합니다',usernameMaxLength: '사용자명은 20자를 초과할 수 없습니다',diff --git a/frontend/src/i18n/locales/ru-RU.ts b/frontend/src/i18n/locales/ru-RU.tsindex 50d4aeb39..a31edb83d 100755--- a/frontend/src/i18n/locales/ru-RU.ts+++ b/frontend/src/i18n/locales/ru-RU.ts@@ -234,7 +234,7 @@ export default {currentPlaceholder: 'Введите текущий пароль',currentRequired: 'Введите текущий пароль',newLabel: 'Новый пароль',- newPlaceholder: '8–32 символа, буквы и цифры',+ newPlaceholder: 'Введите новый пароль',confirmLabel: 'Подтвердите новый пароль',confirmPlaceholder: 'Введите новый пароль ещё раз',submit: 'Обновить пароль',@@ -2722,22 +2722,12 @@ export default {emailLabel: 'Email пользователя',emailPlaceholder: 'Введите email пользователя',newPasswordLabel: 'Новый пароль',- newPasswordPlaceholder: '8–32 символа, включая буквы и цифры',+ newPasswordPlaceholder: 'Введите новый пароль',confirmPasswordLabel: 'Подтвердите новый пароль',confirmPasswordPlaceholder: 'Введите новый пароль ещё раз',confirmBtn: 'Подтвердить сброс',success: 'Пароль сброшен, существующие сеансы пользователя завершены',failed: 'Не удалось сбросить пароль',- validation: {- emailRequired: 'Введите email пользователя',- emailInvalid: 'Введите корректный email',- passwordRequired: 'Введите новый пароль',- passwordLength: 'Пароль должен содержать от 8 до 32 символов',- passwordLetter: 'Пароль должен содержать букву',- passwordNumber: 'Пароль должен содержать цифру',- confirmRequired: 'Введите новый пароль ещё раз',- passwordMismatch: 'Пароли не совпадают'- }},admins: {label: 'Системные администраторы',@@ -2829,7 +2819,8 @@ export default {},auth: {registration_mode: 'Режим самостоятельной регистрации. self_serve = любой может создать аккаунт; invite_only = открытая регистрация отключена, приглашать могут только Owner/Admin. Вступает в силу сразу после сохранения; используйте self_serve осторожно (в публичном интернете появятся спам-регистрации).',- default_tenant_mode: 'Политика пространства после открытой регистрации. create_personal создаёт личное пространство с ролью Owner; tenantless создаёт только аккаунт до принятия приглашения или самостоятельного создания пространства.'+ default_tenant_mode: 'Политика пространства после открытой регистрации. create_personal создаёт личное пространство с ролью Owner; tenantless создаёт только аккаунт до принятия приглашения или самостоятельного создания пространства.',+ complex_password_enabled: 'Определяет, требуется ли сложный пароль. При включении пароль должен содержать прописные и строчные буквы, цифры и специальные символы. Изменение вступает в силу немедленно и применяется только к новым пользователям при регистрации, а также при изменении или сбросе пароля. Специальные символы включают: {specialChars}'}},keyLabels: {@@ -2855,7 +2846,8 @@ export default {},auth: {registration_mode: 'Режим самостоятельной регистрации',- default_tenant_mode: 'Создание пространства по умолчанию'+ default_tenant_mode: 'Создание пространства по умолчанию',+ complex_password_enabled: 'Включить сложные пароли'}},runtime: {@@ -4527,7 +4519,7 @@ export default {subtitle: 'RAG, ReAct-агент и Wiki — корпоративный фреймворк знаний на основе больших моделей',registerSubtitle: 'Создайте аккаунт и начните работу с WeKnora',emailPlaceholder: 'Введите адрес электронной почты',- passwordPlaceholder: 'Введите пароль (8-32 символа, включая буквы и цифры)',+ passwordPlaceholder: 'Введите пароль',confirmPasswordPlaceholder: 'Введите пароль ещё раз',usernamePlaceholder: 'Введите имя пользователя',emailRequired: 'Введите адрес электронной почты',@@ -4536,7 +4528,10 @@ export default {passwordMinLength: 'Пароль должен быть не менее 8 символов',passwordMaxLength: 'Пароль не может превышать 32 символа',passwordMustContainLetter: 'Пароль должен содержать буквы',+ passwordMustContainLowercaseLetter: 'Пароль должен содержать строчные буквы',+ passwordMustContainUppercaseLetter: 'Пароль должен содержать прописные буквы',passwordMustContainNumber: 'Пароль должен содержать цифры',+ passwordMustContainSpecialChar: 'Пароль должен содержать специальные символы: {specialChars}',usernameRequired: 'Введите имя пользователя',usernameMinLength: 'Имя пользователя должно быть не менее 2 символов',usernameMaxLength: 'Имя пользователя не может превышать 20 символов',diff --git a/frontend/src/i18n/locales/zh-CN.ts b/frontend/src/i18n/locales/zh-CN.tsindex 44963edd3..c849ecd27 100755--- a/frontend/src/i18n/locales/zh-CN.ts+++ b/frontend/src/i18n/locales/zh-CN.ts@@ -234,7 +234,7 @@ export default {currentPlaceholder: '请输入当前密码',currentRequired: '请输入当前密码',newLabel: '新密码',- newPlaceholder: '8-32 个字符,需包含字母和数字',+ newPlaceholder: '请输入新密码',confirmLabel: '确认新密码',confirmPlaceholder: '再次输入新密码',submit: '更新密码',@@ -2724,22 +2724,12 @@ export default {emailLabel: '用户邮箱',emailPlaceholder: '输入需要重置密码的用户邮箱',newPasswordLabel: '新密码',- newPasswordPlaceholder: '8-32 个字符,包含字母和数字',+ newPasswordPlaceholder: '请输入新密码',confirmPasswordLabel: '确认新密码',confirmPasswordPlaceholder: '再次输入新密码',confirmBtn: '确认重置',success: '密码已重置,该用户的现有会话已失效',failed: '重置密码失败',- validation: {- emailRequired: '请输入用户邮箱',- emailInvalid: '请输入有效的邮箱地址',- passwordRequired: '请输入新密码',- passwordLength: '密码长度必须为 8-32 个字符',- passwordLetter: '密码必须包含字母',- passwordNumber: '密码必须包含数字',- confirmRequired: '请再次输入新密码',- passwordMismatch: '两次输入的密码不一致'- }},admins: {label: '系统管理员',@@ -2831,7 +2821,8 @@ export default {},auth: {registration_mode: '自助注册模式。self_serve = 任何人可注册账号;invite_only = 关闭公网注册,仅 Owner/Admin 可邀请。修改后立即生效,但谨慎对待 self_serve(公网会接受 spam)。',- default_tenant_mode: '公开注册后的空间初始化策略。create_personal 会自动创建个人空间并授予 Owner;tenantless 仅创建账户,用户需要接受邀请或主动创建空间。只影响之后注册的用户。'+ default_tenant_mode: '公开注册后的空间初始化策略。create_personal 会自动创建个人空间并授予 Owner;tenantless 仅创建账户,用户需要接受邀请或主动创建空间。只影响之后注册的用户。',+ complex_password_enabled: '是否启用复杂密码。开启后密码必须包含大小写字母、数字和特殊字符。修改后立即生效,只影响新注册用户或新密码修改/重置操作。特殊字符包含:{specialChars}'}},keyLabels: {@@ -2857,7 +2848,8 @@ export default {},auth: {registration_mode: '自助注册模式',- default_tenant_mode: '注册默认空间策略'+ default_tenant_mode: '注册默认空间策略',+ complex_password_enabled: '启用复杂密码'}},runtime: {@@ -4529,7 +4521,7 @@ export default {subtitle: 'RAG 问答、ReAct 智能体与 Wiki 知识库,大模型驱动的企业级知识框架',registerSubtitle: '创建账户并开始使用 WeKnora',emailPlaceholder: '输入邮箱地址',- passwordPlaceholder: '输入密码(8-32个字符,包含字母和数字)',+ passwordPlaceholder: '输入密码',confirmPasswordPlaceholder: '再次输入密码',usernamePlaceholder: '输入用户名',emailRequired: '请输入邮箱地址',@@ -4538,7 +4530,10 @@ export default {passwordMinLength: '密码至少8个字符',passwordMaxLength: '密码不能超过32个字符',passwordMustContainLetter: '密码必须包含字母',+ passwordMustContainLowercaseLetter: '密码必须包含小写字母',+ passwordMustContainUppercaseLetter: '密码必须包含大写字母',passwordMustContainNumber: '密码必须包含数字',+ passwordMustContainSpecialChar: '密码必须包含特殊字符:{specialChars}',usernameRequired: '请输入用户名',usernameMinLength: '用户名至少2个字符',usernameMaxLength: '用户名不能超过20个字符',diff --git a/frontend/src/utils/passwordPolicy.ts b/frontend/src/utils/passwordPolicy.tsnew file mode 100644index 000000000..8e00de5de--- /dev/null+++ b/frontend/src/utils/passwordPolicy.ts@@ -0,0 +1,38 @@+import type { FormRule } from 'tdesign-vue-next'++export const PASSWORD_SPECIAL_CHARS = '!@#$%^&*()_+-=[]{}|;:,.<>?'+export const PASSWORD_SPECIAL_CHAR_REGEX = /[!@#$%^&*()_+\-=\[\]{}|;:,.<>?]/++type Translate = (key: string, params?: Record<string, unknown>) => string++export function newPasswordRules(+ t: Translate,+ complexEnabled: boolean,+ extra: FormRule[] = [],+): FormRule[] {+ const common: FormRule[] = [+ { required: true, message: t('auth.passwordRequired'), type: 'error' },+ { min: 8, message: t('auth.passwordMinLength'), type: 'error' },+ { max: 32, message: t('auth.passwordMaxLength'), type: 'error' },+ ]+ if (complexEnabled) {+ return [+ ...common,+ { pattern: /[a-z]/, message: t('auth.passwordMustContainLowercaseLetter'), type: 'error' },+ { pattern: /[A-Z]/, message: t('auth.passwordMustContainUppercaseLetter'), type: 'error' },+ { pattern: /\d/, message: t('auth.passwordMustContainNumber'), type: 'error' },+ {+ pattern: PASSWORD_SPECIAL_CHAR_REGEX,+ message: t('auth.passwordMustContainSpecialChar', { specialChars: PASSWORD_SPECIAL_CHARS }),+ type: 'error',+ },+ ...extra,+ ]+ }+ return [+ ...common,+ { pattern: /[a-zA-Z]/, message: t('auth.passwordMustContainLetter'), type: 'error' },+ { pattern: /\d/, message: t('auth.passwordMustContainNumber'), type: 'error' },+ ...extra,+ ]+}diff --git a/frontend/src/views/auth/Login.vue b/frontend/src/views/auth/Login.vueindex edd29b1e2..c88ae7a28 100755--- a/frontend/src/views/auth/Login.vue+++ b/frontend/src/views/auth/Login.vue@@ -344,6 +344,7 @@ import { useRoute, useRouter } from 'vue-router'import { MessagePlugin } from 'tdesign-vue-next'import { useRoleLabel } from '@/composables/useRoleLabel'import { notifyLoginSuccess } from '@/utils/loginNotify'+import { newPasswordRules } from '@/utils/passwordPolicy'import { Swiper, SwiperSlide } from 'swiper/vue'import { Autoplay, EffectFade, Pagination } from 'swiper/modules'import 'swiper/css'@@ -418,6 +419,7 @@ const oidcProviderName = ref('')// link is visible; the actual mode is fetched from /auth/config in onMounted.// In invite_only mode the link/card are hidden.const registrationEnabled = ref(true)+const complexPasswordEnabled = ref(false)// invite-link state. When the URL carries ?token=xxx we resolve it to// the originating tenant + role and switch the form into a "register@@ -470,10 +472,8 @@ const formRules = computed(() => ({password: [{ required: true, message: t('auth.passwordRequired'), type: 'error' },{ min: 8, message: t('auth.passwordMinLength'), type: 'error' },- { max: 32, message: t('auth.passwordMaxLength'), type: 'error' },- { pattern: /[a-zA-Z]/, message: t('auth.passwordMustContainLetter'), type: 'error' },- { pattern: /\d/, message: t('auth.passwordMustContainNumber'), type: 'error' }- ]+ { max: 32, message: t('auth.passwordMaxLength'), type: 'error' }+ ],}))// Register form validation rules@@ -492,13 +492,7 @@ const registerRules = computed(() => ({{ required: true, message: t('auth.emailRequired'), type: 'error' },{ email: true, message: t('auth.emailInvalid'), type: 'error' }],- password: [- { required: true, message: t('auth.passwordRequired'), type: 'error' },- { min: 8, message: t('auth.passwordMinLength'), type: 'error' },- { max: 32, message: t('auth.passwordMaxLength'), type: 'error' },- { pattern: /[a-zA-Z]/, message: t('auth.passwordMustContainLetter'), type: 'error' },- { pattern: /\d/, message: t('auth.passwordMustContainNumber'), type: 'error' }- ],+ password: newPasswordRules(t, complexPasswordEnabled.value),confirmPassword: [{ required: true, message: t('auth.confirmPasswordRequired'), type: 'error' },{@@ -623,8 +617,10 @@ const loadAuthConfig = async () => {try {const response = await getAuthConfig()registrationEnabled.value = response.registration_mode !== 'invite_only'+ complexPasswordEnabled.value = response.complex_password_enabled} catch {registrationEnabled.value = true+ complexPasswordEnabled.value = false}}diff --git a/frontend/src/views/settings/UserProfile.vue b/frontend/src/views/settings/UserProfile.vueindex cabc49bc9..d7e88507a 100644--- a/frontend/src/views/settings/UserProfile.vue+++ b/frontend/src/views/settings/UserProfile.vue@@ -176,18 +176,21 @@ import { MessagePlugin } from 'tdesign-vue-next'import type { FormInstanceFunctions, FormRule } from 'tdesign-vue-next'import {getCurrentUser,+ getAuthConfig,changePassword,logout as logoutApi,type UserInfo,} from '@/api/auth'import { useAuthStore } from '@/stores/auth'import { useI18n } from 'vue-i18n'+import { newPasswordRules } from '@/utils/passwordPolicy'const { t, locale } = useI18n()const router = useRouter()const authStore = useAuthStore()const userInfo = ref<UserInfo | null>(null)+const complexPasswordEnabled = ref(false)const loading = ref(true)const error = ref('')@@ -200,32 +203,39 @@ const passwordForm = reactive({confirmPassword: '',})+const loadPasswordPolicy = async () => {+ try {+ const resp = await getAuthConfig()+ complexPasswordEnabled.value = !!resp.complex_password_enabled+ } catch {+ complexPasswordEnabled.value = false+ }+}+const oidcOnlyLogin = computed(() => userInfo.value?.preferences?.oidc_only_login === true,)watch(passwordPopupVisible, (open) => {- if (open) {+ if (!open) {resetPasswordForm()+ return}+ resetPasswordForm()+ void loadPasswordPolicy()})const passwordRules = computed<Record<string, FormRule[]>>(() => ({oldPassword: [{ required: true, message: t('userProfile.changePassword.currentRequired'), type: 'error' },],- newPassword: [- { required: true, message: t('auth.passwordRequired'), type: 'error' },- { min: 8, message: t('auth.passwordMinLength'), type: 'error' },- { max: 32, message: t('auth.passwordMaxLength'), type: 'error' },- { pattern: /[a-zA-Z]/, message: t('auth.passwordMustContainLetter'), type: 'error' },- { pattern: /\d/, message: t('auth.passwordMustContainNumber'), type: 'error' },+ newPassword: newPasswordRules(t, complexPasswordEnabled.value, [{validator: (val: string) => val !== passwordForm.oldPassword,message: t('userProfile.changePassword.sameAsCurrent'),type: 'error',},- ],+ ]),confirmPassword: [{ required: true, message: t('auth.confirmPasswordRequired'), type: 'error' },{diff --git a/frontend/src/views/system/SystemSettings.vue b/frontend/src/views/system/SystemSettings.vueindex ad56acdcd..ea00aacee 100644--- a/frontend/src/views/system/SystemSettings.vue+++ b/frontend/src/views/system/SystemSettings.vue@@ -495,7 +495,11 @@ import {resetUserPassword,type SystemSettingItem,} from '@/api/system'+import {+ getAuthConfig,+} from '@/api/auth'import { useAuthStore } from '@/stores/auth'+import { newPasswordRules, PASSWORD_SPECIAL_CHARS } from '@/utils/passwordPolicy'import { isSettingValueDirty, resolveCurrentSetting } from './systemSettingsEdit'const authStore = useAuthStore()@@ -516,7 +520,12 @@ function keyLabel(k: string): string {// user-facing copy lives in i18n (system.globalSettings.keyDescriptions.*).function settingDescription(item: { key: string; description?: string }): string {const path = `system.globalSettings.keyDescriptions.${item.key}`- if (te(path)) return t(path) as string+ if (te(path)) {+ if (path === 'system.globalSettings.keyDescriptions.auth.complex_password_enabled') {+ return t(path, { specialChars: PASSWORD_SPECIAL_CHARS }) as string+ }+ return t(path) as string+ }return item.description ?? ''}@@ -621,6 +630,7 @@ type SettingsSection = 'access' | 'tenant' | 'runtime' | 'security' | 'other'const SETTINGS_SECTION_KEYS: Record<Exclude<SettingsSection, 'other'>, readonly string[]> = {access: ['auth.registration_mode',+ 'auth.complex_password_enabled','auth.default_tenant_mode','tenant.self_service_creation_enabled','tenant.max_owned_per_user',@@ -708,26 +718,33 @@ const passwordResetForm = reactive({newPassword: '',confirmPassword: '',})-const passwordResetRules: Record<string, FormRule[]> = {+const passwordResetRules = computed(() => ({email: [- { required: true, message: t('system.globalSettings.passwordReset.validation.emailRequired'), trigger: 'blur' },- { email: true, message: t('system.globalSettings.passwordReset.validation.emailInvalid'), trigger: 'blur' },- ],- newPassword: [- { required: true, message: t('system.globalSettings.passwordReset.validation.passwordRequired'), trigger: 'blur' },- { min: 8, message: t('system.globalSettings.passwordReset.validation.passwordLength'), trigger: 'blur' },- { max: 32, message: t('system.globalSettings.passwordReset.validation.passwordLength'), trigger: 'blur' },- { pattern: /[a-zA-Z]/, message: t('system.globalSettings.passwordReset.validation.passwordLetter'), trigger: 'blur' },- { pattern: /\d/, message: t('system.globalSettings.passwordReset.validation.passwordNumber'), trigger: 'blur' },+ { required: true, message: t('auth.emailRequired'), type: 'error' },+ { email: true, message: t('auth.emailInvalid'), type: 'error' }],+ newPassword: newPasswordRules(t, complexPasswordEnabled.value),confirmPassword: [- { required: true, message: t('system.globalSettings.passwordReset.validation.confirmRequired'), trigger: 'blur' },+ { required: true, message: t('auth.confirmPasswordRequired'), trigger: 'blur' },{validator: (value: string) => value === passwordResetForm.newPassword,- message: t('system.globalSettings.passwordReset.validation.passwordMismatch'),+ message: t('auth.passwordMismatch'),trigger: 'blur',},],+}))++const complexPasswordEnabled = ref(false)++const loadAuthConfig = async () => {+ try {+ const resp = await getAuthConfig()+ complexPasswordEnabled.value = !!resp.complex_password_enabled+ } catch (err: any) {+ const msg = err?.message || t('system.globalSettings.messages.loadFailed')+ MessagePlugin.error(msg)+ complexPasswordEnabled.value = false+ }}function resetPasswordResetForm() {@@ -738,6 +755,7 @@ function resetPasswordResetForm() {}async function openPasswordResetDialog() {+ await loadAuthConfig()resetPasswordResetForm()passwordResetVisible.value = trueawait nextTick()diff --git a/internal/application/service/password_policy.go b/internal/application/service/password_policy.gonew file mode 100644index 000000000..d7216ead0--- /dev/null+++ b/internal/application/service/password_policy.go@@ -0,0 +1,95 @@+package service++import (+ "context"+ "errors"+ "strings"+ "unicode/utf8"++ "github.com/Tencent/WeKnora/internal/config"+ "github.com/Tencent/WeKnora/internal/types/interfaces"+)++const (+ authComplexPasswordEnabledSettingKey = "auth.complex_password_enabled"+ authComplexPasswordEnabledEnvName = "WEKNORA_AUTH_COMPLEX_PASSWORD_ENABLED"++ upperChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"+ lowerChars = "abcdefghijklmnopqrstuvwxyz"+ digitChars = "0123456789"+ passwordSpecialChars = "!@#$%^&*()_+-=[]{}|;:,.<>?"+ allChars = upperChars + lowerChars + digitChars + passwordSpecialChars+)++// ResolveComplexPasswordEnabled is the shared runtime resolver for the+// complex-password switch. Priority matches other auth tunables:+// DB system_settings > ENV > cfg.Auth (startup YAML/env) > false.+func ResolveComplexPasswordEnabled(+ ctx context.Context,+ cfg *config.Config,+ settings interfaces.SystemSettingService,+) bool {+ enabled := false+ if cfg != nil && cfg.Auth != nil {+ enabled = cfg.Auth.ComplexPasswordEnabled+ }+ if settings == nil {+ return enabled+ }+ return settings.GetBool(+ ctx,+ authComplexPasswordEnabledSettingKey,+ authComplexPasswordEnabledEnvName,+ enabled,+ )+}++// IsPasswordPolicyError reports whether err is a documented password-policy+// failure. Handlers map both the simple and complex sentinels to the same+// machine-readable details token so the SPA can localize them.+func IsPasswordPolicyError(err error) bool {+ return errors.Is(err, ErrPasswordPolicy) || errors.Is(err, ErrComplexPasswordPolicy)+}++// ValidatePasswordPolicy keeps registration, self-service rotation and+// administrative password resets aligned with the SPA form. Letter and+// digit classes are ASCII so they match the frontend regexes; special+// characters are the documented whitelist. Password bytes are never+// logged or included in the returned error.+func ValidatePasswordPolicy(password string, complexPasswordEnabled bool) error {+ length := utf8.RuneCountInString(password)+ if length < 8 || length > 32 {+ return ErrPasswordPolicy+ }++ var (+ hasUpper bool+ hasLower bool+ hasDigit bool+ hasSpecial bool+ )++ for _, r := range password {+ switch {+ case r >= 'A' && r <= 'Z':+ hasUpper = true+ case r >= 'a' && r <= 'z':+ hasLower = true+ case r >= '0' && r <= '9':+ hasDigit = true+ case strings.ContainsRune(passwordSpecialChars, r):+ hasSpecial = true+ }+ }++ if complexPasswordEnabled {+ if !hasUpper || !hasLower || !hasDigit || !hasSpecial {+ return ErrComplexPasswordPolicy+ }+ return nil+ }+ if (!hasUpper && !hasLower) || !hasDigit {+ return ErrPasswordPolicy+ }+ return nil+}diff --git a/internal/application/service/password_policy_test.go b/internal/application/service/password_policy_test.gonew file mode 100644index 000000000..e1b036ba1--- /dev/null+++ b/internal/application/service/password_policy_test.go@@ -0,0 +1,93 @@+package service++import (+ "context"+ "errors"+ "testing"++ "github.com/Tencent/WeKnora/internal/config"+ "github.com/Tencent/WeKnora/internal/types/interfaces"+)++type stubComplexPasswordSettings struct {+ interfaces.SystemSettingService+ enabled bool+}++func (s *stubComplexPasswordSettings) GetBool(context.Context, string, string, bool) bool {+ return s.enabled+}++func TestValidatePasswordPolicy(t *testing.T) {+ t.Parallel()++ cases := []struct {+ name string+ password string+ complex bool+ want error+ }{+ {name: "simple missing digit", password: "password", want: ErrPasswordPolicy},+ {name: "simple too short", password: "Ab1defg", want: ErrPasswordPolicy},+ {name: "simple too long", password: "Abcdefg1" + "xxxxxxxxxxxxxxxxxxxxxxxxx", want: ErrPasswordPolicy},+ {name: "simple ok", password: "password1"},+ {name: "simple unicode letter is not ASCII", password: "Ä1234567", want: ErrPasswordPolicy},+ {name: "complex missing special", password: "NewSecure9", complex: true, want: ErrComplexPasswordPolicy},+ {name: "complex missing upper", password: "newsecure9!", complex: true, want: ErrComplexPasswordPolicy},+ {name: "complex missing lower", password: "NEWSECURE9!", complex: true, want: ErrComplexPasswordPolicy},+ {name: "complex ok", password: "NewSecure9!", complex: true},+ {+ name: "complex unicode digit is not ASCII",+ password: "Password١!",+ complex: true,+ want: ErrComplexPasswordPolicy,+ },+ }++ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ err := ValidatePasswordPolicy(tc.password, tc.complex)+ if !errors.Is(err, tc.want) {+ t.Fatalf("ValidatePasswordPolicy(%q, %v) err = %v, want %v", tc.password, tc.complex, err, tc.want)+ }+ })+ }+}++func TestResolveComplexPasswordEnabled(t *testing.T) {+ t.Parallel()++ ctx := context.Background()++ if got := ResolveComplexPasswordEnabled(ctx, nil, nil); got {+ t.Fatal("nil cfg and settings should default to false")+ }++ // The previous copy-paste checked cfg.Tenant; Auth-only configs must still work.+ cfgAuthOnly := &config.Config{Auth: &config.AuthConfig{ComplexPasswordEnabled: true}}+ if !ResolveComplexPasswordEnabled(ctx, cfgAuthOnly, nil) {+ t.Fatal("Auth.ComplexPasswordEnabled should be honoured when Tenant is nil")+ }++ cfgTenantOnly := &config.Config{Tenant: &config.TenantConfig{}}+ if got := ResolveComplexPasswordEnabled(ctx, cfgTenantOnly, nil); got {+ t.Fatal("Tenant-only cfg must not panic or enable the switch")+ }++ if !ResolveComplexPasswordEnabled(ctx, cfgAuthOnly, &stubComplexPasswordSettings{enabled: true}) {+ t.Fatal("settings override true")+ }+ if ResolveComplexPasswordEnabled(ctx, cfgAuthOnly, &stubComplexPasswordSettings{enabled: false}) {+ t.Fatal("settings override false should win over cfg")+ }+}++func TestIsPasswordPolicyError(t *testing.T) {+ t.Parallel()+ if !IsPasswordPolicyError(ErrPasswordPolicy) || !IsPasswordPolicyError(ErrComplexPasswordPolicy) {+ t.Fatal("policy sentinels should match")+ }+ if IsPasswordPolicyError(ErrSamePassword) {+ t.Fatal("unrelated sentinel must not match")+ }+}diff --git a/internal/application/service/system_setting.go b/internal/application/service/system_setting.goindex c40696a68..cd4541e8f 100644--- a/internal/application/service/system_setting.go+++ b/internal/application/service/system_setting.go@@ -144,6 +144,14 @@ var registry = map[string]settingSpec{Description: "公开注册成功后的默认空间策略。create_personal = 自动创建个人空间并设为 Owner;" +"tenantless = 仅创建用户,等待接受邀请或主动创建空间。修改后只影响新注册用户。",},+ "auth.complex_password_enabled": {+ Type: "bool",+ EnvName: "WEKNORA_AUTH_COMPLEX_PASSWORD_ENABLED",+ Default: false,+ Category: "auth",+ Description: "是否启用复杂密码。开启后密码必须包含大小写字母、数字和特殊字符。" ++ "修改后立即生效,只影响新注册用户或新密码修改/重置操作。特殊字符包含:!@#$%^&*()_+-=[]{}|;:,.<>?",+ },// tenant.max_owned_per_user caps how many tenants a single non-superuser// can create (and Own) via self-service POST /tenants. Read on every// request — UI edits take effect immediately, no restart required. Thediff --git a/internal/application/service/user.go b/internal/application/service/user.goindex 9dc86c34d..8696d4c58 100644--- a/internal/application/service/user.go+++ b/internal/application/service/user.go@@ -16,7 +16,6 @@ import ("strings""sync""time"- "unicode/utf8""github.com/golang-jwt/jwt/v5""github.com/google/uuid"@@ -51,7 +50,13 @@ var (// 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")+ ErrPasswordPolicy = errors.New(+ "password must be 8-32 characters and contain at least one letter and one number")+ // ErrComplexPasswordPolicy is returned when the runtime complex-password+ // switch is on and the new password is missing a required character class.+ ErrComplexPasswordPolicy = errors.New(+ "password must be 8-32 characters and must contain uppercase and lowercase " ++ "letters, numbers, and special characters")// ErrInvalidOldPassword is returned by ChangePassword when the supplied// current password does not match the stored hash. Handlers map this to@@ -71,30 +76,6 @@ const (DetailSamePassword = "same_password")-// 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() {@@ -115,11 +96,12 @@ func getJwtSecret() string {// userService implements the UserService interfacetype userService struct {- userRepo interfaces.UserRepository- tokenRepo interfaces.AuthTokenRepository- tenantService interfaces.TenantService- memberService interfaces.TenantMemberService- config *config.Config+ userRepo interfaces.UserRepository+ tokenRepo interfaces.AuthTokenRepository+ tenantService interfaces.TenantService+ memberService interfaces.TenantMemberService+ config *config.Config+ systemSettingSvc interfaces.SystemSettingService}// NewUserService creates a new user service instance@@ -129,16 +111,22 @@ func NewUserService(tokenRepo interfaces.AuthTokenRepository,tenantService interfaces.TenantService,memberService interfaces.TenantMemberService,+ systemSettingSvc interfaces.SystemSettingService,) interfaces.UserService {return &userService{- userRepo: userRepo,- tokenRepo: tokenRepo,- tenantService: tenantService,- memberService: memberService,- config: configInfo,+ userRepo: userRepo,+ tokenRepo: tokenRepo,+ tenantService: tenantService,+ memberService: memberService,+ config: configInfo,+ systemSettingSvc: systemSettingSvc,}}+func (s *userService) complexPasswordEnabled(ctx context.Context) bool {+ return ResolveComplexPasswordEnabled(ctx, s.config, s.systemSettingSvc)+}+// Register creates a new user accountfunc (s *userService) Register(ctx context.Context, req *types.RegisterRequest) (*types.User, error) {logger.Info(ctx, "Start user registration")@@ -669,7 +657,7 @@ func (s *userService) DeleteUser(ctx context.Context, id string) error {// self-service rotation cannot introduce weaker passwords than// registration / admin reset allow. On success every outstanding session// is revoked so a stolen token cannot survive the rotation.-func (s *userService) ChangePassword(ctx context.Context, userID string, oldPassword, newPassword string) error {+func (s *userService) ChangePassword(ctx context.Context, userID, oldPassword, newPassword string) error {user, err := s.userRepo.GetUserByID(ctx, userID)if err != nil {return err@@ -685,7 +673,7 @@ func (s *userService) ChangePassword(ctx context.Context, userID string, oldPassreturn ErrSamePassword}- if err := ValidatePasswordPolicy(newPassword); err != nil {+ if err := ValidatePasswordPolicy(newPassword, s.complexPasswordEnabled(ctx)); err != nil {return err}@@ -715,8 +703,8 @@ func (s *userService) ChangePassword(ctx context.Context, userID string, oldPass// 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 {+func (s *userService) AdminResetPassword(ctx context.Context, userID, newPassword string) error {+ if err := ValidatePasswordPolicy(newPassword, s.complexPasswordEnabled(ctx)); err != nil {return err}@@ -756,8 +744,10 @@ func (s *userService) AdminCreateUser(password := ""generated := false+ complexPasswordEnabled := s.complexPasswordEnabled(ctx)+if req.Password == nil {- randomPassword, err := generatePolicyCompliantPassword()+ randomPassword, err := generatePolicyCompliantPassword(complexPasswordEnabled)if err != nil {return nil, "", fmt.Errorf("failed to generate password: %w", err)}@@ -769,7 +759,7 @@ func (s *userService) AdminCreateUser(// 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 {+ if err := ValidatePasswordPolicy(password, complexPasswordEnabled); err != nil {return nil, "", err}@@ -1703,17 +1693,88 @@ func generateRandomString(length int) (string, error) {return base64.RawURLEncoding.EncodeToString(buffer), nil}+func getRandomChar(charset string) (byte, error) {+ n, err := rand.Int(rand.Reader, big.NewInt(int64(len(charset))))+ if err != nil {+ return 0, err+ }+ return charset[n.Int64()], nil+}++func generateComplexPassword(length int) (string, error) {+ if length < 4 {+ return "", fmt.Errorf("password length must be at least 4")+ }++ password := make([]byte, 0, length)++ c, err := getRandomChar(upperChars)+ if err != nil {+ return "", err+ }+ password = append(password, c)++ c, err = getRandomChar(lowerChars)+ if err != nil {+ return "", err+ }+ password = append(password, c)++ c, err = getRandomChar(digitChars)+ if err != nil {+ return "", err+ }+ password = append(password, c)++ c, err = getRandomChar(passwordSpecialChars)+ if err != nil {+ return "", err+ }+ password = append(password, c)++ for len(password) < length {+ c, err = getRandomChar(allChars)+ if err != nil {+ return "", err+ }+ password = append(password, c)+ }++ // Fisher-Yates shuffle+ for i := len(password) - 1; i > 0; i-- {+ n, err := rand.Int(rand.Reader, big.NewInt(int64(i+1)))+ if err != nil {+ return "", err+ }++ j := int(n.Int64())+ password[i], password[j] = password[j], password[i]+ }++ return string(password), 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) {+// password that satisfies ValidatePasswordPolicy.+//+// Simple policies may require regeneration (a single 32-char base64url+// draw misses digits ~0.4% of the time). Complex policies are satisfied+// in a single pass.+func generatePolicyCompliantPassword(complexPasswordEnabled bool) (string, error) {+ var password string+ var err errorfor {- password, err := generateRandomString(24)+ if complexPasswordEnabled {+ password, err = generateComplexPassword(16)+ } else {+ password, err = generateRandomString(24)+ }+if err != nil {return "", err}- if ValidatePasswordPolicy(password) == nil {++ if ValidatePasswordPolicy(password, complexPasswordEnabled) == nil {return password, nil}}diff --git a/internal/application/service/user_admin_create_test.go b/internal/application/service/user_admin_create_test.goindex a10bdbd79..d5b28e111 100644--- a/internal/application/service/user_admin_create_test.go+++ b/internal/application/service/user_admin_create_test.go@@ -60,7 +60,13 @@ func TestAdminCreateUserGeneratesPolicyCompliantPasswordWhenEmpty(t *testing.T)if user == nil || repo.created == nil {t.Fatalf("user was not persisted: %v", repo.created)}- if err := ValidatePasswordPolicy(generated); err != nil {++ complexPasswordEnabled := false+ if svc.config != nil && svc.config.Auth != nil {+ complexPasswordEnabled = svc.config.Auth.ComplexPasswordEnabled+ }++ if err := ValidatePasswordPolicy(generated, complexPasswordEnabled); err != nil {t.Fatalf("generated password violates the policy: %v", err)}if bcrypt.CompareHashAndPassword([]byte(repo.created.PasswordHash), []byte(generated)) != nil {@@ -135,12 +141,24 @@ 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()+ pw, err := generatePolicyCompliantPassword(false)+ if err != nil {+ t.Fatalf("iteration %d: failed to generate simple password: %v", i, err)+ }+ if err := ValidatePasswordPolicy(pw, false); err != nil {+ t.Fatalf("iteration %d: generated simple password %q violates the policy: %v", i, pw, err)+ }+ }++ // Complex policies are constructed to comply in a single pass; still+ // sample many draws so a shuffle regression cannot hide.+ for i := range 200 {+ pw, err := generatePolicyCompliantPassword(true)if err != nil {- t.Fatalf("iteration %d: generate: %v", i, err)+ t.Fatalf("iteration %d: failed to generate complex password: %v", i, err)}- if err := ValidatePasswordPolicy(pw); err != nil {- t.Fatalf("iteration %d: generated password %q violates the policy: %v", i, pw, err)+ if err := ValidatePasswordPolicy(pw, true); err != nil {+ t.Fatalf("iteration %d: generated complex password %q violates the policy: %v", i, pw, err)}}}@@ -165,6 +183,35 @@ func TestAdminCreateUserRejectsWeakPasswordBeforePersisting(t *testing.T) {}}+func TestAdminCreateUserHonoursRuntimeComplexPolicy(t *testing.T) {+ repo := &adminCreateUserRepo{}+ svc := &userService{+ userRepo: repo,+ systemSettingSvc: &stubComplexPasswordSettings{enabled: true},+ }++ user, generated, err := svc.AdminCreateUser(context.Background(), &types.AdminCreateUserRequest{+ Username: "alice", Email: "[email protected]",+ }, types.TenantProvisioningTenantless)+ if err != nil {+ t.Fatalf("AdminCreateUser generate: %v", err)+ }+ if user == nil || generated == "" {+ t.Fatal("expected a generated complex password")+ }+ if err := ValidatePasswordPolicy(generated, true); err != nil {+ t.Fatalf("generated password %q violates complex policy: %v", generated, err)+ }++ simple := "PlainPass9"+ _, _, err = svc.AdminCreateUser(context.Background(), &types.AdminCreateUserRequest{+ Username: "bob", Email: "[email protected]", Password: &simple,+ }, types.TenantProvisioningTenantless)+ if !errors.Is(err, ErrComplexPasswordPolicy) {+ t.Fatalf("explicit simple password err=%v, want ErrComplexPasswordPolicy", err)+ }+}+func TestAdminCreateUserDuplicateReturnsExistingUserWithSentinel(t *testing.T) {existing := &types.User{ID: "existing", Username: "alice", Email: "[email protected]"}repo := &adminCreateUserRepo{existingByEmail: existing}diff --git a/internal/application/service/user_auth_token_test.go b/internal/application/service/user_auth_token_test.goindex 70f92729e..471a12445 100644--- a/internal/application/service/user_auth_token_test.go+++ b/internal/application/service/user_auth_token_test.go@@ -216,7 +216,8 @@ func TestAdminResetPasswordRejectsWeakPasswordBeforeWrite(t *testing.T) {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)+ t.Fatalf("weak password caused side effects: updates=%d revocations=%v",+ repo.updateCalls, tokenRepo.revokedUserIDs)}}@@ -236,7 +237,8 @@ func TestChangePasswordRequiresPolicyAndRevokesSessions(t *testing.T) {t.Fatalf("ChangePassword(weak) 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)+ t.Fatalf("weak password caused side effects: updates=%d revocations=%v",+ repo.updateCalls, tokenRepo.revokedUserIDs)}if err := svc.ChangePassword(ctx, "user-1", "wrong-pass", "NewSecure9"); !errors.Is(err, ErrInvalidOldPassword) {@@ -274,6 +276,34 @@ func TestChangePasswordRejectsSamePassword(t *testing.T) {}}+func TestChangePasswordHonoursRuntimeComplexPolicy(t *testing.T) {+ ctx := context.Background()+ tokenRepo := &stubAuthTokenRepo{tokens: map[string]*types.AuthToken{}}+ svc := newAuthTestUserService(tokenRepo)+ svc.systemSettingSvc = &stubComplexPasswordSettings{enabled: true}+ repo := svc.userRepo.(*stubUserRepoForAuth)++ hashed, err := bcrypt.GenerateFromPassword([]byte("OldSecure9"), bcrypt.DefaultCost)+ if err != nil {+ t.Fatalf("hash old password: %v", err)+ }+ repo.users["user-1"].PasswordHash = string(hashed)++ if err := svc.ChangePassword(ctx, "user-1", "wrong-pass", "weak"); !errors.Is(err, ErrInvalidOldPassword) {+ t.Fatalf("ChangePassword(wrong old, weak new) err = %v, want ErrInvalidOldPassword", err)+ }+ if err := svc.ChangePassword(ctx, "user-1", "OldSecure9", "NewSecure9"); !errors.Is(err, ErrComplexPasswordPolicy) {+ t.Fatalf("ChangePassword(simple new) err = %v, want ErrComplexPasswordPolicy", err)+ }+ if repo.updateCalls != 0 || len(tokenRepo.revokedUserIDs) != 0 {+ t.Fatalf("complex-policy reject caused side effects: updates=%d revocations=%v",+ repo.updateCalls, tokenRepo.revokedUserIDs)+ }+ if err := svc.ChangePassword(ctx, "user-1", "OldSecure9", "NewSecure9!"); err != nil {+ t.Fatalf("ChangePassword(complex new) err = %v", err)+ }+}+func TestUserIDFromSignedTokenAcceptsExpiredToken(t *testing.T) {expired := signTestJWT(jwt.MapClaims{"user_id": "user-1",diff --git a/internal/config/auth_legacy_env_test.go b/internal/config/auth_legacy_env_test.goindex fcf6d0662..a6bd8dc47 100644--- a/internal/config/auth_legacy_env_test.go+++ b/internal/config/auth_legacy_env_test.go@@ -154,3 +154,30 @@ func TestApplyAuthAndTenantDefaults_CrossTenantAccess(t *testing.T) {}})}++func TestApplyAuthAndTenantDefaults_ComplexPasswordEnabledEnv(t *testing.T) {+ t.Run("1 enables via ParseBool", func(t *testing.T) {+ t.Setenv("WEKNORA_AUTH_COMPLEX_PASSWORD_ENABLED", "1")+ cfg := &Config{Auth: &AuthConfig{}}+ applyAuthAndTenantDefaults(cfg)+ if !cfg.Auth.ComplexPasswordEnabled {+ t.Fatal("WEKNORA_AUTH_COMPLEX_PASSWORD_ENABLED=1 should enable complex passwords")+ }+ })+ t.Run("false disables", func(t *testing.T) {+ t.Setenv("WEKNORA_AUTH_COMPLEX_PASSWORD_ENABLED", "false")+ cfg := &Config{Auth: &AuthConfig{ComplexPasswordEnabled: true}}+ applyAuthAndTenantDefaults(cfg)+ if cfg.Auth.ComplexPasswordEnabled {+ t.Fatal("WEKNORA_AUTH_COMPLEX_PASSWORD_ENABLED=false should disable complex passwords")+ }+ })+ t.Run("unset leaves yaml", func(t *testing.T) {+ t.Setenv("WEKNORA_AUTH_COMPLEX_PASSWORD_ENABLED", "")+ cfg := &Config{Auth: &AuthConfig{ComplexPasswordEnabled: true}}+ applyAuthAndTenantDefaults(cfg)+ if !cfg.Auth.ComplexPasswordEnabled {+ t.Fatal("empty env should leave YAML complex-password flag untouched")+ }+ })+}diff --git a/internal/config/config.go b/internal/config/config.goindex c5dd55c1d..6f02d4c83 100644--- a/internal/config/config.go+++ b/internal/config/config.go@@ -279,7 +279,8 @@ type AuthConfig struct {// create_personal preserves the historical one-user-one-workspace default;// tenantless creates only the identity and waits for an invitation or an// explicit self-service tenant creation.- DefaultTenantMode string `yaml:"default_tenant_mode" json:"default_tenant_mode"`+ DefaultTenantMode string `yaml:"default_tenant_mode" json:"default_tenant_mode"`+ ComplexPasswordEnabled bool `yaml:"complex_password_enabled" json:"complex_password_enabled"`}// AuthRegistrationMode constants used by handlers and middleware.@@ -633,6 +634,7 @@ func ValidateConfig(cfg *Config) error {errs = append(errs, fmt.Sprintf("auth.registration_mode must be %q or %q, got %q",AuthRegistrationModeSelfServe, AuthRegistrationModeInviteOnly, mode))}+tenantMode := strings.TrimSpace(cfg.Auth.DefaultTenantMode)if tenantMode != "" && tenantMode != AuthDefaultTenantModeCreatePersonal && tenantMode != AuthDefaultTenantModeTenantless {errs = append(errs, fmt.Sprintf("auth.default_tenant_mode must be %q or %q, got %q",@@ -810,6 +812,7 @@ func applyAgentEnvOverrides(cfg *Config) {//// Env overrides (when set and non-empty):// - WEKNORA_AUTH_DEFAULT_TENANT_MODE ("create_personal"/"tenantless")+// - WEKNORA_AUTH_COMPLEX_PASSWORD_ENABLED (boolean)// - WEKNORA_TENANT_SELF_SERVICE_CREATION_ENABLED (boolean)// - WEKNORA_TENANT_ENABLE_RBAC ("true"/"false", case-insensitive)// - WEKNORA_TENANT_ENABLE_CROSS_TENANT_ACCESS ("true"/"false", case-insensitive).@@ -848,6 +851,13 @@ func applyAuthAndTenantDefaults(cfg *Config) {if strings.TrimSpace(cfg.Auth.RegistrationMode) == "" {cfg.Auth.RegistrationMode = AuthRegistrationModeSelfServe}++ if value := strings.TrimSpace(os.Getenv("WEKNORA_AUTH_COMPLEX_PASSWORD_ENABLED")); value != "" {+ if parsed, err := strconv.ParseBool(value); err == nil {+ cfg.Auth.ComplexPasswordEnabled = parsed+ }+ }+if value := strings.TrimSpace(os.Getenv("WEKNORA_AUTH_DEFAULT_TENANT_MODE")); value != "" {cfg.Auth.DefaultTenantMode = value}diff --git a/internal/handler/auth.go b/internal/handler/auth.goindex 0384fcb38..38c52b309 100644--- a/internal/handler/auth.go+++ b/internal/handler/auth.go@@ -148,6 +148,14 @@ func (h *SystemHandler) resolveDefaultTenantMode(ctx context.Context) types.Tenareturn resolveDefaultTenantMode(ctx, h.cfg, h.systemSettingSvc)}+func (h *AuthHandler) complexPasswordEnabled(ctx context.Context) bool {+ return service.ResolveComplexPasswordEnabled(ctx, h.configInfo, h.systemSettingSvc)+}++func (h *SystemHandler) complexPasswordEnabled(ctx context.Context) bool {+ return service.ResolveComplexPasswordEnabled(ctx, h.cfg, h.systemSettingSvc)+}+// Register godoc// @Summary 用户注册// @Description 注册新用户账号@@ -200,6 +208,17 @@ func (h *AuthHandler) Register(c *gin.Context) {c.Error(appErr)return}++ // Validate password against the runtime policy (DB system_settings+ // first). Register itself does not enforce this because OIDC+ // auto-provision uses an untyped random secret the user never types.+ if err := service.ValidatePasswordPolicy(req.Password, h.complexPasswordEnabled(ctx)); err != nil {+ logger.Error(ctx, "Invalid password policy")+ appErr := errors.NewValidationError(err.Error())+ _ = c.Error(appErr)+ return+ }+req.Username = secutils.SanitizeForLog(req.Username)req.Email = secutils.SanitizeForLog(req.Email)req.TenantProvisioning = h.resolveDefaultTenantMode(ctx)@@ -710,7 +729,7 @@ func (h *AuthHandler) UpdateMyPreferences(c *gin.Context) {// ChangePassword godoc// @Summary 修改密码-// @Description 修改当前用户的登录密码。新密码须满足 8–32 位且同时包含字母与数字;成功后所有会话被撤销,需重新登录。+// @Description 修改当前用户的登录密码。新密码须满足 8–32 位且同时包含字母与数字;开启复杂密码后还需包含大小写与特殊字符。成功后所有会话被撤销,需重新登录。// @Tags 认证// @Accept json// @Produce json@@ -745,14 +764,16 @@ func (h *AuthHandler) ChangePassword(c *gin.Context) {return}- // Change password+ // Change password. Policy is enforced in the service after the old+ // password is verified so a wrong current credential is not masked+ // by a complexity error.err = h.userService.ChangePassword(ctx, user.ID, req.OldPassword, req.NewPassword)if err != nil {switch {- case stderrors.Is(err, service.ErrPasswordPolicy):+ case service.IsPasswordPolicyError(err):appErr := errors.NewValidationError("Password policy violation").WithDetails(service.DetailPasswordPolicy)- c.Error(appErr)+ _ = c.Error(appErr)returncase stderrors.Is(err, service.ErrInvalidOldPassword):appErr := errors.NewBadRequestError("Current password is incorrect").@@ -781,7 +802,7 @@ func (h *AuthHandler) ChangePassword(c *gin.Context) {// GetAuthConfig godoc// @Summary 获取认证配置-// @Description 返回当前部署的注册模式等公开认证配置,供前端决定是否展示注册入口+// @Description 返回当前部署的注册模式与密码复杂度开关,供前端决定是否展示注册入口以及密码校验规则// @Tags 认证// @Accept json// @Produce json@@ -789,16 +810,23 @@ func (h *AuthHandler) ChangePassword(c *gin.Context) {// @Router /auth/config [get]//// GetAuthConfig is intentionally a no-auth endpoint: the frontend reads-// it on app load to decide whether to show the Register tab. We expose-// only what the UI strictly needs (registration_mode); other config-// stays internal.+// it on app load to decide whether to show the Register tab and which+// password complexity rules to apply. We expose only what the UI+// strictly needs; other config stays internal.func (h *AuthHandler) GetAuthConfig(c *gin.Context) {// Same source-of-truth as Register's gate, so the UI hide-the-button// signal can never disagree with the API enforcement signal.mode := h.resolveRegistrationMode(c.Request.Context())++ complexPasswordEnabled := service.ResolveComplexPasswordEnabled(+ c.Request.Context(),+ h.configInfo,+ h.systemSettingSvc,+ )c.JSON(http.StatusOK, gin.H{- "success": true,- "registration_mode": mode,+ "success": true,+ "registration_mode": mode,+ "complex_password_enabled": complexPasswordEnabled,})}diff --git a/internal/handler/auth_change_password_test.go b/internal/handler/auth_change_password_test.goindex 137696b13..ab04b5a78 100644--- a/internal/handler/auth_change_password_test.go+++ b/internal/handler/auth_change_password_test.go@@ -138,3 +138,36 @@ func TestChangePassword_MapsSamePasswordDetail(t *testing.T) {t.Fatalf("details = %q, want %q", resp.Error.Details, service.DetailSamePassword)}}++func TestChangePassword_MapsPasswordPolicyDetail(t *testing.T) {+ h := &AuthHandler{+ userService: &stubChangePasswordUserService{+ getCurrentUser: func(_ context.Context) (*types.User, error) {+ return &types.User{ID: "user-1", Email: "[email protected]"}, nil+ },+ changePassword: func(_ context.Context, _, _, _ string) error {+ return service.ErrComplexPasswordPolicy+ },+ },+ }++ w := doChangePassword(t, newChangePasswordTestRouter(h), map[string]string{+ "old_password": "OldSecure9",+ "new_password": "NewSecure9",+ })+ if w.Code != http.StatusBadRequest {+ t.Fatalf("status = %d, want %d body=%s", w.Code, http.StatusBadRequest, w.Body.String())+ }++ var resp struct {+ Error struct {+ Details string `json:"details"`+ } `json:"error"`+ }+ if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {+ t.Fatalf("unmarshal: %v", err)+ }+ if resp.Error.Details != service.DetailPasswordPolicy {+ t.Fatalf("details = %q, want %q", resp.Error.Details, service.DetailPasswordPolicy)+ }+}diff --git a/internal/handler/auth_register_by_invite.go b/internal/handler/auth_register_by_invite.goindex f3160e753..2c20860de 100644--- a/internal/handler/auth_register_by_invite.go+++ b/internal/handler/auth_register_by_invite.go@@ -6,6 +6,7 @@ import ("github.com/gin-gonic/gin"+ "github.com/Tencent/WeKnora/internal/application/service"apperrors "github.com/Tencent/WeKnora/internal/errors""github.com/Tencent/WeKnora/internal/handler/dto""github.com/Tencent/WeKnora/internal/logger"@@ -169,6 +170,12 @@ func (h *AuthHandler) RegisterByInvite(c *gin.Context) {return}+ if err := service.ValidatePasswordPolicy(req.Password, h.complexPasswordEnabled(ctx)); err != nil {+ logger.Error(ctx, "Invalid password policy")+ _ = c.Error(apperrors.NewValidationError(err.Error()))+ return+ }+user, err := h.userService.Register(ctx, &types.RegisterRequest{Username: req.Username,Email: req.Email,diff --git a/internal/handler/auth_register_by_invite_tenant_test.go b/internal/handler/auth_register_by_invite_tenant_test.goindex f02d1a8ef..f961aa840 100644--- a/internal/handler/auth_register_by_invite_tenant_test.go+++ b/internal/handler/auth_register_by_invite_tenant_test.go@@ -71,7 +71,7 @@ func TestRegisterByInviteRestoresTenantlessAccountWhenInviteExpiresDuringRegistrr.Use(errorCapture())r.POST("/auth/register-by-invite", h.RegisterByInvite)- body := []byte(`{"token":"invite-token","email":"[email protected]","username":"alice","password":"supersecret"}`)+ body := []byte(`{"token":"invite-token","email":"[email protected]","username":"alice","password":"supersecret1"}`)req := httptest.NewRequest(http.MethodPost, "/auth/register-by-invite", bytes.NewReader(body))req.Header.Set("Content-Type", "application/json")w := httptest.NewRecorder()@@ -104,7 +104,7 @@ func TestRegisterByInviteUsesInvitedTenantWithoutPersonalTenant(t *testing.T) {r.Use(errorCapture())r.POST("/auth/register-by-invite", h.RegisterByInvite)- body := []byte(`{"token":"invite-token","email":"[email protected]","username":"alice","password":"supersecret"}`)+ body := []byte(`{"token":"invite-token","email":"[email protected]","username":"alice","password":"supersecret1"}`)req := httptest.NewRequest(http.MethodPost, "/auth/register-by-invite", bytes.NewReader(body))req.Header.Set("Content-Type", "application/json")w := httptest.NewRecorder()@@ -120,3 +120,30 @@ func TestRegisterByInviteUsesInvitedTenantWithoutPersonalTenant(t *testing.T) {t.Fatalf("updated tenant=%d, want 42", users.updatedTenant)}}++func TestRegisterByInviteRejectsSimplePasswordWhenComplexEnabled(t *testing.T) {+ gin.SetMode(gin.TestMode)+ users := &invitedRegistrationUserService{}+ h := &AuthHandler{+ userService: users,+ tenantService: &invitedRegistrationTenantService{},+ invitationSvc: &invitedRegistrationInvitationService{},+ systemSettingSvc: &tenantPolicySettingService{enabled: true},+ }+ r := gin.New()+ r.Use(errorCapture())+ r.POST("/auth/register-by-invite", h.RegisterByInvite)++ body := []byte(`{"token":"invite-token","email":"[email protected]","username":"alice","password":"supersecret1"}`)+ req := httptest.NewRequest(http.MethodPost, "/auth/register-by-invite", bytes.NewReader(body))+ 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, want 400", w.Code, w.Body.String())+ }+ if users.registeredMode != "" {+ t.Fatalf("Register was called with mode=%q", users.registeredMode)+ }+}diff --git a/internal/handler/auth_register_invite_only_test.go b/internal/handler/auth_register_invite_only_test.goindex 891c9c915..02c55f987 100644--- a/internal/handler/auth_register_invite_only_test.go+++ b/internal/handler/auth_register_invite_only_test.go@@ -6,6 +6,7 @@ import ("encoding/json""net/http""net/http/httptest"+ "strings""testing""github.com/Tencent/WeKnora/internal/config"@@ -71,7 +72,7 @@ func validRegisterBody() map[string]string {return map[string]string{"username": "alice","email": "[email protected]",- "password": "supersecret",+ "password": "supersecret1",}}@@ -150,6 +151,27 @@ func TestRegister_TenantlessProvisioningFromConfig(t *testing.T) {}}+func TestGetAuthConfigExposesComplexPassword(t *testing.T) {+ gin.SetMode(gin.TestMode)+ h := &AuthHandler{+ configInfo: &config.Config{Auth: &config.AuthConfig{+ RegistrationMode: config.AuthRegistrationModeSelfServe,+ }},+ systemSettingSvc: &tenantPolicySettingService{enabled: true},+ }+ r := gin.New()+ r.GET("/auth/config", h.GetAuthConfig)+ req := httptest.NewRequest(http.MethodGet, "/auth/config", nil)+ w := httptest.NewRecorder()+ r.ServeHTTP(w, req)+ if w.Code != http.StatusOK {+ t.Fatalf("status=%d body=%s", w.Code, w.Body.String())+ }+ if !strings.Contains(w.Body.String(), `"complex_password_enabled":true`) {+ t.Fatalf("body=%s, want complex_password_enabled true", w.Body.String())+ }+}+func TestRegister_NilAuthConfigDoesNotPanic(t *testing.T) {// Defensive: a nil Auth section means the operator hasn't set the// registration mode at all, which must not crash and must keep thediff --git a/internal/handler/system.go b/internal/handler/system.goindex 3f9add9ca..cee7f54d8 100644--- a/internal/handler/system.go+++ b/internal/handler/system.go@@ -1551,7 +1551,8 @@ func (h *SystemHandler) ResetUserPassword(c *gin.Context) {return}req.Email = strings.TrimSpace(req.Email)- if err := service.ValidatePasswordPolicy(req.NewPassword); err != nil {++ if err := service.ValidatePasswordPolicy(req.NewPassword, h.complexPasswordEnabled(ctx)); err != nil {c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})return}@@ -1568,7 +1569,7 @@ func (h *SystemHandler) ResetUserPassword(c *gin.Context) {}if err := h.userSvc.AdminResetPassword(ctx, user.ID, req.NewPassword); err != nil {- if errors.Is(err, service.ErrPasswordPolicy) {+ if service.IsPasswordPolicyError(err) {c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})return}diff --git a/internal/handler/tenant_self_service_policy_test.go b/internal/handler/tenant_self_service_policy_test.goindex 18d7811bc..52c5d00fb 100644--- a/internal/handler/tenant_self_service_policy_test.go+++ b/internal/handler/tenant_self_service_policy_test.go@@ -36,6 +36,10 @@ func (s *tenantPolicySettingService) GetBool(context.Context, string, string, boreturn s.enabled}+func (s *tenantPolicySettingService) GetString(_ context.Context, _ string, _ string, def string) string {+ return def+}+func (s *tenantPolicySettingService) GetInt(_ context.Context, _ string, _ string, def int64) int64 {return def}