Commit Graph

113 Commits

Author SHA1 Message Date
f91b5d1cef feat: improve auth form UX 2026-05-12 20:34:30 +08:00
fc3adfac82 Ignore local report artifacts 2026-05-12 07:14:33 +08:00
77d096cdc9 Fix prelaunch navigation and log scale regressions 2026-05-12 00:28:38 +08:00
7c2f073cbf chore: 归档已完成的中介层测试补全计划文档 2026-05-10 13:48:14 +08:00
b77412b47f test: 增强 handler/middleware 测试覆盖并优化错误分类
测试增强:
- handler_test.go: 大幅增强 handler 集成测试(+1284/-98 行)
- theme_handler_test.go: 增强主题管理测试(+174/-22 行)
- auth_bootstrap_test.go: 新增 bootstrap 认证测试(+329 行)
- ratelimit_test.go: 新增限流中间件测试(+153 行)
- runtime_test.go: 新增运行时中间件测试(+351 行)

错误处理:
- auth_handler.go: classifyErrorMessage 增加 TOTP 错误码和 2FA 状态字分类

清理:
- 删除覆盖率报告残留文件(coverage_issue, handler, middleware 等)
- 归档 docs/superpowers/plans/2026-05-09-middleware-test-backfill-phase1.md
2026-05-10 13:46:29 +08:00
f050c60a09 docs: 新增运维和使用指南文档
新增文档:
- guides/ADMIN_GUIDE.md — 管理员操作手册(用户/角色/设备/日志管理)
- guides/USER_GUIDE.md — 普通用户操作手册(注册/登录/TOTP/设备管理)
- guides/CONFIG_REFERENCE.md — 配置文件参考手册(含全部配置项说明)
- guides/MONITORING.md — 健康检查、Prometheus 指标和告警规则

同步更新:
- docs/README.md 文档索引,加入新增文档链接
2026-05-10 13:22:51 +08:00
bb7588b7c0 docs: 更新 REAL_PROJECT_STATUS 并追加 Sprint 17 完成报告
- 在 REAL_PROJECT_STATUS.md 开头追加 2026-05-10 最新验证快照
- 将 /uploads 路径遍历标记为  已修复
- 创建 docs/sprints/SPRINT_17_COMPLETION_REPORT.md
2026-05-10 13:05:07 +08:00
28012140cb test: 补齐 handler/repository/domain 层单元测试 2026-05-10 12:54:13 +08:00
b8e9af001f refactor: 提取公共分页解析函数 parsePageAndSize
- 新增 internal/api/handler/common.go 存放 handler 层公共辅助函数
- parsePageAndSize: 统一提取 page/page_size 参数解析、默认值设置、ClampPageSize 调用
- device/log/webhook handler: 替换重复的分页解析代码为 parsePageAndSize 调用
- 清理不再需要的 strconv/pagination 导入
2026-05-08 12:48:03 +08:00
b3374dccf4 refactor: 使用 pagination.ClampPageSize 简化 handler 分页代码
- device/log/webhook handler: 替换 if/else 分页限制为 ClampPageSize
- 统一添加 page < 1 检查(device/log handler 缺失)
2026-05-08 12:45:56 +08:00
2ecd1fef1e refactor: 提取 service 层 best-effort 超时常量
- 新增 defaultBETimeout = 5 * time.Second
- 替换 auth/auth_runtime/password_reset/user_service/webhook 中 6 处硬编码 5*time.Second
2026-05-08 12:44:05 +08:00
9ad7b5c0df refactor: 提取 avatar handler 魔法数字为具名常量
- maxAvatarSize = 5 * 1024 * 1024 (5MB)
- magicBytesBufSize = 512
- avatarTokenLen = 8
- dirPerm = 0o755
- filePerm = 0o644
2026-05-08 12:42:35 +08:00
1f7a223768 refactor: 提取分页魔法数字为 pagination 常量
- handler 层: device/log/webhook/user handler 使用 pagination.DefaultPageSize/MaxPageSize
- service 层: device/login_log/operation_log service 使用 pagination.DefaultPageSize
- repository 层: user repository 使用 pagination.DefaultPageSize/MaxPageSize
- 消除 8 处硬编码的 20/100 分页魔法数字
2026-05-08 12:40:36 +08:00
202b3963f8 docs: 更新生产就绪评审报告 — 安全项全部修复
- SEC-UPLOAD: 已修复 (61692e4)
- SEC-OAUTH-VAL: 已修复 — 5秒超时 + userinfo端点验证
- SEC-RECOVERY/SEC-IP-SPOOF/SEC-ARGON2: 已修复
- 评分从 8.1 提升至 8.3
- 仅剩 SMTP 告警验证一项阻塞
2026-05-08 12:31:22 +08:00
61692e4c1a fix(security): /uploads 目录路径遍历防护
- 替换 Static 为受控文件服务 handler (serveUploads)
- 添加 filepath.Clean 路径清理 + .. 检测
- 使用 Abs + HasPrefix 限制访问范围在上传目录内
- 添加安全响应头(CSP default-src 'none', X-Content-Type-Options nosniff)
2026-05-08 12:28:03 +08:00
e49865df11 docs: 更新生产就绪评审报告 — P2 修复完成
- SEC-RECOVERY/TOTP 恢复码加密: 已修复
- SEC-IP-SPOOF/X-Forwarded-For 伪造: 已修复
- SEC-ARGON2/Argon2id 参数: 已修复
- PERF-01/03/07 性能问题: 已修复
- RES-01/02/03 资源管理: 已修复
- 全量测试 43 个包 PASS
- 评分从 7.7 提升至 8.1
2026-05-08 10:58:38 +08:00
8665c97d0d fix(security): X-Forwarded-For IP 伪造防护
- isTrustedProxy: 空可信代理列表时默认不信任(安全优先)
- realIP: 修正 XFF 遍历逻辑,从右到左跳过可信代理,返回第一个不可信的客户端 IP
- GetClientIP: 优先读取 IPFilterMiddleware 已验证的 client_ip,避免直接信任转发头
2026-05-08 10:35:20 +08:00
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