Commit Graph

96 Commits

Author SHA1 Message Date
d4ec8a13e4 security(auth): raise Argon2id calibration minimums to OWASP thresholds (SEC-ARGON2)
- Increase minimum iterations from 2 to 3 (OWASP minimum)
- Increase minimum memory from 16MB to 19MB (19456KB, OWASP minimum)
- Update comments to document the OWASP rationale

Fixes: SEC-ARGON2
2026-05-08 10:24:10 +08:00
2a18a6fb47 fix(n+1): 批量查询替代循环单查
- IsAdminBootstrapRequired: userRepo.GetByID 循环 → GetByIDs 批量
- AssignRoles: roleRepo.GetByID 循环 → GetByIDs 批量
- 在 userRepositoryInterface 补充 GetByIDs 方法签名
2026-05-08 08:05:26 +08:00
9b1cea246e feat: permissions CRUD browser integration + E2E enhancements
Backend:
- permission_handler: 完善权限 CRUD 接口(列表/创建/更新/删除)
- auth_handler: 修复认证处理逻辑
- router: 新增权限管理路由
- handler_test: 新增权限 handler 测试覆盖

Frontend:
- permissions.ts/test.ts: 权限服务层完整实现
- profile/settings/service_tests: 服务适配器修正
- client.ts: HTTP 客户端健壮性增强
- vite.config.js: 构建配置优化
- E2E 脚本: run-playwright-cdp-e2e 大幅增强(权限流程覆盖)

Docs:
- REAL_PROJECT_STATUS: 状态更新
- PRODUCTION_CHECKLIST/QUALITY_STANDARD/TECHNICAL_GUIDE/PROJECT_EXPERIENCE_SUMMARY: 团队规范完善
- plans/2026-04-23: 权限浏览器 CRUD 设计方案

验证: go build 0错误
2026-04-24 07:30:18 +08:00
3f3bb82f1d fix: v6 code review P0 auth/IDOR fixes + frontend regression patches
Backend fixes:
- auth_handler: P0 认证逻辑修复
- ratelimit: 限速中间件增强 + 新增单元测试
- auth_service: 认证服务逻辑完善 + 新增测试
- server: server 配置增强 + 新增测试
- handler_test: 新增 handler 层集成测试
- auth_bootstrap_test: bootstrap 路径测试

Frontend patches:
- LoginPage/RegisterPage: CSRF + 表单交互修复
- BootstrapAdminPage: 引导流程修复
- DevicesPage: 设备管理页修复
- auth/social-accounts/users/webhooks services: 类型修正
- csrf.ts: CSRF token 处理修正
- E2E 脚本: CDP smoke + auth e2e 增强

Docs:
- FULL_CODE_REVIEW_REPORT_2026-04-20
- report-v6 执行计划
- REAL_PROJECT_STATUS 更新
- .gitignore: 新增 .gocache-*/config.yaml 排除

验证: go build/vet 0错误, go test 42/42 PASS, 0 FAIL
2026-04-23 07:14:12 +08:00
82109ec216 Merge branch 'fix/status-review-sync-20260409' 2026-04-19 09:11:10 +08:00
8d9f157eb8 feat: add UMS CLI for binary packaging and system initialization
- Add Cobra-based CLI with ums init, ums serve, ums version commands
- ums init supports interactive prompts and non-interactive flags
- Generates secure JWT secrets and config.yaml automatically
- Extract server.Serve() function for reuse
- Add cross-platform build targets to Makefile
- Update README with CLI installation and usage instructions

New files:
- cmd/ums/main.go - CLI entry point
- cmd/ums/cmd/root.go - Root command
- cmd/ums/cmd/init.go - Interactive/non-interactive init
- cmd/ums/cmd/serve.go - Server command
- cmd/ums/cmd/version.go - Version command
- internal/server/server.go - Extracted Serve function
2026-04-19 08:59:00 +08:00
0cfb0f8afd Merge pull request 'fix/status-review-sync-20260409' (#1) from fix/status-review-sync-20260409 into main
Reviewed-on: #1
2026-04-18 15:05:51 +00:00
7b047e2f11 perf: Sprint 19 P0/P1 性能优化落地
P0(高优先级):
- P0-1: 确认数据库复合索引已存在(GORM tag),composite_index_test 验证通过
- P0-2: 连接池调优 MaxIdleConns 5→10, ConnMaxLifetime 30min→5min
- P0-3: Redis 智能探测(ProbeRedis),无 Redis 自动降级到纯内存模式

P1(中优先级):
- P1-1: GZIP 压缩中间件(compress/gzip 标准库,零新依赖)
- P1-2: 权限缓存 TTL 30min→5min
- P1-3: Argon2id 启动自适应校准(CalibrateArgon2id)

历史优化(含本次提交):
- L1Cache O(n)→O(1) LRU 重构
- Auth 中间件 DB 查询合并 + 5s L1 缓存
- Logger 异步化(4096 缓冲通道)

验证: go build/vet/test 41/41 PASS, govulncheck 无漏洞
2026-04-18 22:57:44 +08:00
85285c16d1 docs: update project documentation with P0/P1/P2 fix status
- Add security features section to README
- Add security architecture section 12.1 and 12.2 to ARCHITECTURE
- Add validation commands section to DEPLOYMENT
- Update PRD with fix completion status
2026-04-18 21:30:14 +08:00
509c5ca2fd docs: 更新项目状态文档,记录 P0/P1/P2 修复完成状态
- 更新 REAL_PROJECT_STATUS.md 添加 2026-04-18 验证快照
- 添加 P0/P1/P2 修复完成状态表
- 更新 FULL_CODE_REVIEW_REPORT_2026-04-17.md 添加修复完成附录
- 记录 API 变更历史和验证结果
2026-04-18 21:23:55 +08:00
adb251e4ad fix: P2 security and correctness issues
P2-10: Change ActivateEmail from GET to POST - token now passed in
request body instead of URL query parameter for better security

P2-11: Change ValidateResetToken from GET to POST - token now passed
in request body instead of URL query parameter to prevent log leakage

P2-12: Note - /uploads static exposure remains (requires architectural
decision about file serving)

P2-13: cursor.Encode() now checks and returns empty string on JSON
marshaling error instead of silently ignoring

P2-14: initDefaultData and ensurePermissions now properly check and
propagate errors from RolePermission creation, and createDefaultPermissions
aggregates errors instead of silently continuing

P2-15: NewJWT now returns (nil, error) on initialization failure
instead of a partially initialized object. All callers updated to handle
the error return.

Backend routes updated:
- POST /auth/activate-email (was GET /activate)
- POST /auth/password/validate (was GET /reset-password)

Frontend updated to match new API endpoints.
2026-04-18 20:48:11 +08:00
a754545072 fix: add missing PCE parameter to GenerateTokenPair calls in test files
The JWT GenerateTokenPair functions were updated to require a PCE (Password
Changed Epoch) parameter for token invalidation. This commit updates test files
in concurrent and performance packages to include this parameter.

- internal/concurrent/concurrent_test.go: 2 call sites fixed
- internal/performance/benchmark_test.go: 3 call sites fixed
- internal/performance/performance_test.go: 4 call sites fixed
2026-04-18 20:16:45 +08:00
61c19e54ac fix: P1-02 OAuth context propagation and P1-16 AuthProvider double-check
P1-02: OAuth ExchangeCode and GetUserInfo now accept context parameter
       to properly propagate request context to HTTP calls
P1-16: AuthProvider isAuthenticated now uses single source of truth
       (effectiveUser !== null) instead of double-checking both
       React state and module-level function
2026-04-18 19:40:54 +08:00
e1e423008e chore: update coverage report 2026-04-18 18:43:29 +08:00
8095307d82 fix: P0/P1 security and quality fixes
P0-01: Add ESCAPE clause to LIKE queries in operation_log.go and device.go
P0-02: Add atomic Increment to L1Cache and L2Cache interfaces
P0-07: Add TOTP verification step after password login
P1-01: Sanitize error messages in error.go middleware
P1-03: Remove err.Error() from export error messages
P1-04: Add error return to CountByResultSince in login_log.go
P1-05: Add transactional DeleteCascade to RoleRepository
P1-06: Add PasswordChangedAt tracking for JWT token invalidation
P1-07: Wrap theme SetDefault in database transaction
P1-08: Use config values for database pool parameters
P1-09: Add rows.Err() checks in social_account_repo.go
P1-10: Validate sortOrder with map in user.go ORDER BY
P1-11: Add GORM tags to Announcement struct
P1-15: Add pageSize upper limit (100) to device and log handlers
2026-04-18 15:33:12 +08:00
9d7abb8a46 fix: P0-07 complete frontend TOTP login flow
Backend changes:
- Add VerifyTOTPAfterPasswordLogin handler in auth_handler.go
- Add route /auth/login/totp-verify in router.go

Frontend changes:
- Update TokenBundle type to include requires_totp and user_id fields
- Add TOTPVerifyRequest type for TOTP verification
- Add verifyTOTPAfterPasswordLogin() API function

New login flow when user has TOTP enabled:
1. loginByPassword returns {requires_totp: true, user_id: <id>}
2. Frontend prompts user for TOTP code
3. Frontend calls verifyTOTPAfterPasswordLogin({user_id, code})
4. If TOTP valid, full TokenBundle with tokens is returned
2026-04-18 14:50:25 +08:00
4acd19f420 fix: P0-07 prevent login bypassing TOTP verification
- Add RequiresTOTP, TempToken, UserID fields to LoginResponse
- Add isTOTPRequiredForLogin() to check if TOTP is needed after password
- Add VerifyTOTPAfterPasswordLogin() for completing login with TOTP
- Login() now checks if TOTP is required after password verification

When user has TOTP enabled and device is not trusted:
- Login returns {requires_totp: true, user_id: <id>} instead of token
- Frontend should prompt for TOTP code
- Frontend calls VerifyTOTPAfterPasswordLogin to complete login

Note: Frontend changes are required to handle the new login flow.
The TempToken field is reserved for future use.
2026-04-18 14:19:15 +08:00
ca7ba5ccdf fix: P0-02 prevent login attempt counter race condition
Add atomic Increment method to cache layers:
- L2Cache interface: add Increment method signature
- RedisCache: implement using Redis INCRBY
- L1Cache: implement with mutex-protected counter
- CacheManager: add Increment that updates both L1 and L2

Update incrementFailAttempts to use atomic Increment instead
of Get-Increment-Set pattern, preventing TOCTOU race.
2026-04-18 13:45:09 +08:00
32a3d4c9e0 fix: P0-01 prevent LIKE injection in operation_log and device repos
- operation_log.go Search(): add escapeLikePattern + ESCAPE clause
- device.go ListAllCursor(): add escapeLikePattern + ESCAPE clause

The ESCAPE clause is required for SQLite to properly interpret
backslash as an escape character.
2026-04-18 13:06:44 +08:00
b6f330fe7d docs: add 2026-04-18 optimization baseline to governance documents
- Add optimization baseline appendix to QUALITY_STANDARD.md defining
  current baseline gates for all future optimization work
- Update REAL_PROJECT_STATUS.md with latest project status
- Add experience summary to PROJECT_EXPERIENCE_SUMMARY.md
- Add technical guide updates to TECHNICAL_GUIDE.md
- Add FULL_CODE_REVIEW_REPORT_2026-04-17.md as reference document
2026-04-18 12:24:36 +08:00
bba44e820a fix: P0-04 prevent password reset code replay attack
ResetPasswordByPhone and ResetPassword now immediately consume
(delete) the verification code/token after successful validation,
before proceeding with password reset. This prevents replay attacks
where the same code could be used multiple times.

Security fix:验证码/Token验证通过后立即删除,防止Replay攻击
2026-04-18 10:26:36 +08:00
bb7c5e7fe2 fix: P0-08 cursor pagination sort consistency
Cursor pagination now only applies when sorting by created_at.
Other sort fields (username, last_login_time, updated_at) will
not use cursor pagination to prevent data inconsistency.

Fixes: UserRepository.ListCursor() allowing sort fields that
don't match the cursor predicate.
2026-04-18 10:13:37 +08:00
0795e126cc fix: resolve P0 security issues per governance baseline
P0-01: LIKE injection fix in device.go (2 locations)
- Added escapeLikePattern() to prevent LIKE pattern manipulation

P0-03: Token refresh blacklist fail-closed
- RefreshToken() now returns error if cache.Set fails
- Prevents token double-spend on cache failures

P0-05: CORS dangerous default configuration
- Default changed to empty origins, credentials off
- init() panics if default config is dangerous

P0-06: UpdateUser IDOR vulnerability fix
- Added authorization check (self-or-admin)
- Prevents unauthorized user profile modification

Also: Fixed frontend lint errors in device-fingerprint.test.ts and http/index.test.ts

All 518 frontend tests pass, all backend tests pass.
2026-04-18 09:32:54 +08:00
7849c3c3ed docs: update TEST_PLAN.md with completed status 2026-04-18 07:48:19 +08:00
8b8c05bb60 test: add Stage 3-5 component and layout test coverage
Add tests for:
- PageLayout components: ContentCard, FilterCard, TableCard, TreeCard, PageLayout
- AuthLayout layout component
- LoginLogDetailDrawer and OperationLogDetailDrawer page components

All 518 tests pass across 82 test files.
2026-04-18 07:46:42 +08:00
40d146b6aa test: add Stage 1 lib and Stage 2 services test coverage
Add comprehensive unit tests for:
- lib layer: config, device-fingerprint, errors, storage, hooks/useBreadcrumbs, http
- services layer: devices, login-logs, operation-logs, permissions, profile, roles, settings, stats, import-export

All 491 tests pass across 74 test files.
2026-04-17 23:59:15 +08:00
582ad7a069 test: add comprehensive test coverage and improve code quality
- Add new test files for auth, service, and handler modules
- Improve test organization and coverage
- Refactor code for better maintainability
- Add captcha, settings, stats, and theme handler tests
- Add auth module tests (CAS, OAuth, password, SSO, state)
- Add service layer tests for auth, export, permissions, roles
- All Go tests pass (exit code 0)
- All frontend tests pass (325 tests in 59 files)
2026-04-17 20:43:50 +08:00
0d66aa0423 docs: add systematic test optimization review 2026-04-12 17:20:49 +08:00
e77f3a6391 docs: add expert invitation for test, performance, and UI optimization 2026-04-12 17:13:19 +08:00
09beb173cc feat: complete production readiness improvements
- Fix DIP violations in service layer (device, stats, auth middleware)
- Add ReplaceUserRoles interface method for transaction safety
- Implement Magic Bytes validation for avatar uploads
- Standardize OAuth error handling with ErrOAuthProviderNotSupported
- Use crypto/rand for JWT secret generation instead of weak fixed key
- Apply code formatting with gofumpt and goimports
- Fix staticcheck issues (S1024, S1008, ST1005)
- Add comprehensive quality and functional test reports
- Achieve 36.3% test coverage (up from 16.3%)
- All E2E, integration, and business logic tests passing
2026-04-12 16:15:32 +08:00
861736cf4d fix: exclude test files from tsconfig.app.json to resolve TS2304 build error
P0 F-01: Frontend build was failing with "Cannot find name 'beforeEach'"
because test files were being compiled by tsconfig.app.json which lacked
vitest globals. Added exclude patterns to tsconfig.app.json.

Updated PROJECT_REAL_COMPLETION_REVIEW_2026-04-10.md to reflect fix.
2026-04-11 23:45:43 +08:00
779b432f52 docs: update completion review with false completion prevention status 2026-04-11 23:39:17 +08:00
4193b46b5f docs: add false completion prevention rules and fix swagger gaps
Changes:
- Add FALSE_COMPLETION_PREVENTION.md documenting false completion patterns
- Add integrity check script (scripts/check-integrity.sh) for automated verification
- Fix swagger annotation gaps in 3 handlers (+10 annotations):
  - password_reset_handler.go: +4 annotations
  - totp_handler.go: +4 annotations
  - log_handler.go: +2 annotations
- Define IntegrationRedisSuite type for Redis integration tests
- Update QUALITY_STANDARD.md with swagger completeness and response format requirements
- Update PROJECT_EXPERIENCE_SUMMARY.md with new learnings on false completion

Integrity check now validates:
- Swagger annotation completeness per handler
- Response format uniformity (with OAuth whitelist)
- Test infrastructure type definitions
- Repository test coverage
2026-04-11 23:38:43 +08:00
339c740365 test: update playwright script and fix jsdom alert mock 2026-04-11 23:03:04 +08:00
47b7205916 chore: update .gitignore and add review document
- Add SQLite temp files (sub2api*) to .gitignore
- Add .codex-tmp/ to .gitignore
- Add .workbuddy memory files to .gitignore
- Add frontend/admin/coverage/ to .gitignore
- Add SENIOR_DEV_REVIEW_2026-04-10.md review document
2026-04-11 23:02:13 +08:00
bc17db352e docs: remove duplicate English-named runbook files 2026-04-11 23:01:06 +08:00
2824855be6 docs: update completion review with runbooks and K8s status 2026-04-11 22:58:11 +08:00
54a73e66f4 docs: add runbooks and Kubernetes Helm Chart
Add 6 runbook documents:
- 服务启动 (Service Startup)
- 服务停止 (Service Shutdown)
- 配置更新 (Configuration Update)
- 日志分析 (Log Analysis)
- 备份恢复 (Backup & Recovery)
- 安全事件 (Security Incident)

Add Kubernetes Helm Chart:
- Chart.yaml, values.yaml
- Deployment with health checks
- Ingress with TLS support
- PVC for data persistence
- PDB for high availability
- HPA for autoscaling
- ServiceAccount configuration

Add cron-backup.conf for automated backup scheduling.
2026-04-11 22:57:31 +08:00
84d9ed28af docs: add Swagger annotations to 5 handlers
Add comprehensive Swagger/Swagger comments to:
- export_handler.go (ExportUsers, ImportUsers, GetImportTemplate)
- sms_handler.go (SendCode, LoginByCode)
- sso_handler.go (Authorize, Token, Introspect, Revoke, UserInfo)
- theme_handler.go (8 endpoints)
- webhook_handler.go (5 endpoints)

All 18 handlers now have Swagger annotations.
2026-04-11 22:49:13 +08:00
1929c42e35 test: add comprehensive ListCursor tests with keyword, time range, and role filters 2026-04-11 22:26:18 +08:00
8257897bf5 test: add tests for GetPermissionsByIDs, GetUserRolesAndPermissions, ListCursor
Repository test coverage improved to 80.4%

- role_permission_repository_test.go: GetPermissionsByIDs test
- user_role_repository_test.go: GetUserRolesAndPermissions test
- user_repository_test.go: ListCursor test
2026-04-11 22:19:44 +08:00
5389d2bcf5 fix: replace MySQL NOW() with SQLite-compatible datetime('now')
- Set function: use GORM clause.OnConflict for cross-database upsert
- BatchSet function: replace NOW() with datetime('now')
- Add tests for Set and BatchSet (both now 100%/85.7% covered)
2026-04-11 22:13:00 +08:00
8f5a315bdf test: add ListLogsForExportBatch test to improve coverage 2026-04-11 22:01:43 +08:00
289aab2930 test: add repository tests to improve coverage from 46.6% to 74%
New test files:
- custom_field_repository_test.go: 10 tests for CustomFieldRepository & UserCustomFieldValueRepository
- login_log_repository_test.go: 3 tests for ListCursor, ListByUserIDCursor, ListAllForExport
- operation_log_repository_test.go: 1 test for ListCursor
- role_repository_test.go: 2 tests for GetAncestorIDs, GetAncestors
- social_account_repository_test.go: 8 CRUD tests
- theme_repository_test.go: 10 tests for ThemeConfigRepository
- user_role_repository_test.go: 1 test for DeleteByUserAndRole

Modified test files:
- device_repository_test.go: Added ListAllCursor tests
- user_repository_test.go: Added AdvancedSearch tests
- webhook_repository_test.go: Added ListByCreatorPaginated test

Updated documentation with new coverage status.
2026-04-11 21:58:28 +08:00
b1311ea144 docs: update completion review with Swagger and test coverage progress
- Added Swagger annotations summary (86 annotations, 13 handlers)
- Added Device Repository tests summary (15 test cases)
- Coverage: 46.6% -> 49.0% (+2.4%)

From PRODUCTION_GAP_ANALYSIS_2026-04-08:
- P2: Swagger annotations - substantially addressed
- P1: Repository coverage - improved from 46.6% to 49.0%
2026-04-11 21:33:45 +08:00
4764814de1 test: add device repository tests for full CRUD coverage
Added 15 test cases covering:
- Create, GetByID, GetByDeviceID
- Update, Delete
- List, ListByUserID, ListByStatus
- UpdateStatus, Exists
- DeleteByUserID, DeleteAllByUserIDExcept
- GetActiveDevices, TrustDevice, UntrustDevice
- GetTrustedDevices, ListAll

Coverage: 46.6% -> 49.0% (+2.4%)
Addresses P1: repository layer test coverage
2026-04-11 21:32:06 +08:00
0564bfd9ad docs: add Swagger annotations to 13 API handlers
Added @Summary, @Description, @Tags, @Param, @Success, @Failure,
@Router annotations to all major handler endpoints for OpenAPI/Swagger
auto-generation. Covers 86 annotations across:

- auth_handler.go (25): all auth endpoints
- user_handler.go (14): CRUD + roles + admin management
- device_handler.go (13): device CRUD + trust management
- role_handler.go (8): role CRUD + permissions
- custom_field_handler.go (7): field CRUD + user values
- permission_handler.go (7): permission CRUD + tree
- log_handler.go (3): login/operation logs
- captcha_handler.go (3): generate/verify
- stats_handler.go (2): dashboard + user stats
- avatar_handler.go (1): upload avatar
- totp_handler.go (1): totp status
- password_reset_handler.go (1): forgot password

Partially addresses P2: missing Swagger annotations
(PRODUCTION_GAP_ANALYSIS_2026-04-08)
2026-04-11 21:23:52 +08:00
27a8dd91a2 test: add AvatarHandler tests for upload validation
Add unit tests for avatar upload including:
- Unauthorized access (no token)
- Non-admin cannot update other user avatar
- User not found or forbidden case
2026-04-11 20:05:40 +08:00
fd1161b867 docs: update completion review - all P2 handler format issues resolved
Mark all P2 handler response format unification as complete.
Update honest assessment to "可声称完全闭环: 是".
2026-04-11 13:38:23 +08:00
c39796b70d fix: unify auth_handler.go response format
Standardize all JSON responses to {code: 0, message: "success", data: ...} for success
and {code: XXX, message: "..."} for errors.
2026-04-11 13:37:39 +08:00