Commit Graph

94 Commits

Author SHA1 Message Date
Your Name
23113fedf3 test: add timezone package tests
Add comprehensive tests for timezone functionality:
- Init (valid/invalid timezones, default)
- getUTCOffset
- Now (with/without location)
- Location (with/without location)
- Name (with/without name)
- StartOfDay, Today, EndOfDay
- StartOfWeek (Monday-based)
- StartOfMonth
- ParseInLocation
- ParseInUserLocation (valid/empty/invalid TZ)
- NowInUserLocation
- StartOfDayInUserLocation

Coverage: timezone 45.2% → 93.5%
2026-05-29 21:20:30 +08:00
Your Name
7014936a75 test: add antigravity OAuth tests
Add tests for OAuth functionality:
- GetUserAgent
- BaseURLs and ForwardBaseURLs
- URLAvailability (mark/unavailable, mark/success, expired)
- SessionStore (set/get/delete, expired sessions)
- Generate functions (random bytes, state, session ID, verifier, challenge)
- base64URLEncode
- BuildAuthorizationURL
- Constants

Coverage: antigravity 19.6% → 27.1%
2026-05-29 21:08:28 +08:00
Your Name
e5da23cea2 test: add CORS middleware tests
Add tests for CORS functionality:
- validateCORSConfig (valid and invalid configs)
- SetCORSConfig (update and validation)
- resolveAllowedOrigin (exact match, wildcard, case insensitive)
- CORS middleware (allow/forbid origins, OPTIONS handling)

Coverage: middleware 36.4% → 37.4%
2026-05-29 21:06:43 +08:00
Your Name
e735f74c23 test: add domain constants tests
Add tests for domain constant values:
- Status constants (active, disabled, error, etc.)
- Role constants (admin, user)
- Platform constants (anthropic, openai, gemini, etc.)
- Account type constants (oauth, apikey, bedrock, etc.)
- Redeem type constants
- PromoCode status constants
- Adjustment type constants
- Subscription type/status constants
- Model mapping verification
2026-05-29 21:04:33 +08:00
Your Name
dfca5e2272 test: expand httpclient pool tests
Add tests for:
- buildClientKey (consistent hashing)
- buildClientKeyTrimsSpaces
- isValidatedHost (cache hit/miss/expire)
- isValidatedHostNilTransport
- newValidatedTransport
- buildClient (valid options and error cases)
- buildTransport (default and custom values)

Coverage: httpclient 36.5% → 69.8%
2026-05-29 20:52:04 +08:00
Your Name
65309b95e7 test: add oauth package tests
Add tests for OAuth helper functions:
- GenerateRandomBytes
- GenerateState
- GenerateSessionID
- GenerateCodeVerifier
- GenerateCodeChallenge
- base64URLEncode
- BuildAuthorizationURL
- Constants and types

Coverage: oauth 15.9% → 47.6%
2026-05-29 20:50:16 +08:00
Your Name
abcbc4e58d test: add antigravity model functions tests
Add tests for model-related functions:
- DefaultModels
- DefaultGeminiModels
- FallbackGeminiModelsList
- FallbackGeminiModel
- ClaudeModels/GeminiModels verification

Coverage: antigravity 18.8% → 19.6%
2026-05-29 20:48:12 +08:00
Your Name
23bfed3b61 test: add domain LoginType constants test
Add test for LoginType enum constants:
- LoginTypePassword (1)
- LoginTypeEmailCode (2)
- LoginTypeSMSCode (3)
- LoginTypeOAuth (4)
2026-05-29 20:29:08 +08:00
Your Name
e267bb8400 test: add openai request helper tests
Add tests for Codex client detection functions:
- IsCodexCLIRequest
- IsCodexOfficialClientRequest
- IsCodexOfficialClientOriginator
- IsCodexOfficialClientByHeaders
- normalizeCodexClientHeader
- matchCodexClientHeaderPrefixes

Coverage: openai 34.2% → 34.9%
2026-05-29 20:26:44 +08:00
Your Name
de329286c9 test: add sms_handler tests for SendCode endpoint
Add tests for SMS handler:
- SendCode with valid phone number
- SendCode with invalid phone (returns 400)
- SendCode with missing phone (validation error)
- SendCode when service not configured (returns 503)

Coverage: handler 27.7% → 28.6%
2026-05-29 20:21:07 +08:00
Your Name
36a497ed7b test: expand responseheaders test coverage to 97.2%
Add tests for:
- FilterHeaders with nil filter (uses default)
- CompileHeaderFilter with empty/whitespace strings
- WriteFilteredHeaders helper
- Multi-value header handling

Coverage: 77.8% → 97.2%
2026-05-29 20:13:56 +08:00
Your Name
707d35fb74 test: add middleware tests for cache_control, security_headers, trace_id
Add comprehensive tests for three middleware components:
- cache_control: NoStoreSensitiveResponses, shouldDisableCaching
- security_headers: SecurityHeaders, shouldAttachCSP, isHTTPSRequest
- trace_id: TraceID, GetTraceID, generateTraceID

Coverage: middleware 35.7% → 36.4%
2026-05-29 20:11:26 +08:00
Your Name
17a46c2770 test: add service header util tests
- Add resolveWireCasing tests
- Add setHeaderRaw/addHeaderRaw/getHeaderRaw tests
- Add sortHeadersByWireOrder tests
2026-05-29 18:37:52 +08:00
Your Name
7a20548204 test: add social account domain tests
- Add SocialAccountStatus constants tests
- Add ExtraData Value/Scan tests
- Add SocialAccount ToInfo and field tests
2026-05-29 17:52:16 +08:00
Your Name
e47dae6fc6 test: add geminicli codeassist types tests
- Add TierInfo UnmarshalJSON tests
- Add LoadCodeAssistResponse GetTier tests
- Add model field tests
2026-05-29 17:43:16 +08:00
Your Name
cd5dae4778 test: add sysutil and cache tests
- Add RestartService tests (pkg/sysutil)
- Add decodeRedisValue and normalizeRedisValue tests (cache/l2.go)
2026-05-29 17:38:48 +08:00
Your Name
281811e80b test: add security encryption tests
- Add AES-GCM encryption/decryption tests
- Add NewEncryption validation tests
- Add MaskEmail and MaskPhone tests

Coverage: internal/security improved
2026-05-29 17:28:57 +08:00
Your Name
48e31166bf test: add monitoring collector tests
- Add collector metrics tests (internal/monitoring/collector.go)
- Test SetMemoryUsage, SetGoroutines, and DB metrics handling
2026-05-29 17:23:44 +08:00
Your Name
871bc79598 test: add repository and domain tests
- Add pagination result tests (internal/repository/pagination.go)
- Add Gemini drive client factory test (internal/repository/gemini_drive_client.go)
- Add scanSingleRow contract tests (internal/repository/sql_scan.go)
- Add DefaultThemeConfig test (internal/domain/theme.go)

Coverage improvements:
- repository: 75.8%
- domain: 21.1%
2026-05-29 16:59:05 +08:00
Your Name
9cc4305395 test: add pkg tests for gemini, openai, geminicli packages
- Add sanitize tests (internal/pkg/geminicli): 55.3%
- Add constants/model tests (internal/pkg/openai): 34.2%
- Add models tests (internal/pkg/gemini): 100%
2026-05-29 16:36:54 +08:00
Your Name
0b17ab42c2 test: improve pkg coverage - pagination and ip packages
- Add PaginationParams tests (internal/pkg/pagination): 100%
- Add IP utility function tests (internal/pkg/ip): 80%

Total project coverage: 55.0% (+0.6%)
2026-05-29 16:33:54 +08:00
Your Name
ed399edb5f test: improve pkg package coverage
- Add HTTP status error functions tests (internal/pkg/errors)
- Add ReadRequestBodyWithPrealloc tests (internal/pkg/httputil)
- Add HTTPStatusToGoogleStatus tests (internal/pkg/googleapi)

Coverage improvements:
- pkg/errors: 77.6%
- pkg/httputil: 91.7%
- pkg/googleapi: 79.5%
2026-05-29 16:24:23 +08:00
Your Name
6351271f2d test: add server package tests
- Add resolveGinMode tests (debug, test, release, default modes)
- Add case sensitivity tests for mode resolution
- Server package coverage: 0% -> 3.2%
- Overall coverage: 54.2% -> 54.3%
2026-05-29 16:04:40 +08:00
Your Name
ffcd820fed test: add domain model tests
- Add Announcement.IsActiveAt tests (nil, status, time range)
- Add TableName tests for all domain models
- Domain package coverage: 9.2% -> 16.3%
- Overall coverage: 54.1% -> 54.2%
2026-05-29 15:35:03 +08:00
Your Name
4fa63dca43 test: add security validator tests
- Add comprehensive Validator tests (email, phone, username, password)
- Add URL and IP validation tests (IPv4/IPv6)
- Add SQL injection sanitization tests
- Add XSS sanitization tests
- Security package coverage: 34.9% -> 69.4%
- Overall coverage: 53.5% -> 54.1%
2026-05-29 15:10:57 +08:00
Your Name
9f0eefd2f5 test: improve coverage for pagination and domain packages
- Add comprehensive cursor pagination tests (95.7% coverage)
- Add domain helper functions tests (StrPtr, DerefStr)
- Add Gender and UserStatus constants tests
- Add User model tests (TableName, default values)
- Overall coverage improved from 53.2% to 53.5%
2026-05-29 14:57:49 +08:00
Your Name
f0930489f1 test: add auth handler error classification tests
- Add handleError tests for ApplicationError types
- Add classifyErrorMessage tests for error message classification
- Add contains helper function tests
- Add getUserIDFromContext/getUsernameFromContext tests
- Cover error classification for both EN and CN error messages
2026-05-29 14:38:08 +08:00
Your Name
5d767abe72 test(docs): P2 optimization - add router tests and update README
- Add router package tests to improve coverage
- Update README status date to 2026-05-29
- Mark all P0/P1 review blockers as resolved
- Update project readiness rating to B (conditional ready)
2026-05-29 14:00:21 +08:00
Your Name
363c77d020 feat: atomic TOTP verification for DisableTOTP
- Add atomicTOTPVerifier interface for atomic TOTP/recovery code verification
- Implement VerifyTOTPOrRecoveryCode in UserRepository with transaction
- Update DisableTOTP to prefer atomic verification path
- Add unit tests for atomic verification success/failure paths
- Maintain backward compatibility with non-atomic fallback

Refs: TOTP verification atomicity completion
2026-05-29 12:47:05 +08:00
Your Name
8a45548ed8 refactor: migrate SocialAccountRepository to GORM for consistency
- Replace raw SQL with GORM chain calls in Create/Update/Delete/List
- Maintain backward compatibility for *sql.DB construction (wrapped via GORM)
- Update only permitted fields in Update to prevent accidental overwrite of binding keys
- Add repository-level tests for new implementation

Refs: UNFIXED_ISSUES_20260329 social_account_repo GORM refactor
2026-05-29 12:31:48 +08:00
Your Name
878ca731f4 fix: atomic TOTP recovery code consumption with repository-level transaction
- Add ConsumeTOTPRecoveryCode to UserRepository for atomic read-verify-update
- Update TOTPService.VerifyTOTP to prefer atomic consumption when available
- Update AuthService.verifyTOTPCodeOrRecoveryCode with same pattern
- Fix critical bug: ConsumeTOTPRecoveryCode now correctly returns consumed=false on mismatch
- Maintain backward compatibility: falls back to non-atomic path if repo doesn't implement interface
- Add comprehensive unit tests for atomic consumption path

Refs: review-fix-closure-2026-05-28 TOTP recovery code atomicity
2026-05-29 12:31:36 +08:00
Your Name
80c59e2c2c fix: harden avatar upload path and sync review truth 2026-05-29 07:33:19 +08:00
Your Name
9cc5892565 fix: tighten password and surface persistence errors 2026-05-28 20:38:34 +08:00
Your Name
caad1aba0c fix: harden handler context and rate limit isolation 2026-05-28 20:30:24 +08:00
Your Name
e46567678f fix(auth): restore self role lookup and lock regression coverage 2026-05-28 18:39:56 +08:00
Your Name
11232177d9 fix: enforce resource ownership checks 2026-05-28 17:28:08 +08:00
Your Name
7eb5f9c7d4 fix: fail closed on invalid cors config 2026-05-28 16:53:33 +08:00
Your Name
547fdab0b2 fix: require permission for user role queries 2026-05-28 16:20:20 +08:00
Your Name
260046a581 test: realign verification baseline and supporting tests 2026-05-28 15:19:34 +08:00
Your Name
6be90ddff8 fix: close auth, permission, contract and e2e review blockers 2026-05-28 15:19:13 +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
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
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
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