diff --git a/src/main/kotlin/top/foxball/nekomainsite/authentication/LoginAttemptLimiter.kt b/src/main/kotlin/top/foxball/nekomainsite/authentication/LoginAttemptLimiter.kt new file mode 100644 index 0000000..0c627b8 --- /dev/null +++ b/src/main/kotlin/top/foxball/nekomainsite/authentication/LoginAttemptLimiter.kt @@ -0,0 +1,97 @@ +package top.foxball.nekomainsite.authentication + +import org.springframework.stereotype.Component + +/** + * 登录尝试限流器(进程内,无外部依赖)。 + * + * 以「用户名 + 客户端 IP」为键,记录最近一次登录窗口内的失败次数; + * 连续失败达到 [MAX_FAILURES] 次后锁定 [LOCK_DURATION_MS],期间登录直接返回 429。 + * 登录成功会清空该键的计数与锁定。仅用于防护在线口令猜测,不替代后端认证与审计。 + */ +@Component +class LoginAttemptLimiter { + private class State( + val failureTimes: MutableList = mutableListOf(), + var lockedUntil: Long = 0L, + var expiresAt: Long = 0L, + ) + + private val lock = Any() + private val states = LinkedHashMap(16, 0.75f, true) + private var nextCleanupAt = 0L + + /** 该键当前是否处于锁定状态;锁定到期后自动清除并视为未锁定。 */ + fun isLocked(key: String, now: Long = System.currentTimeMillis()): Boolean = synchronized(lock) { + cleanupIfDue(now) + val state = states[key] ?: return@synchronized false + if (now < state.lockedUntil) return@synchronized true + state.failureTimes.removeAll { it < now - FAILURE_WINDOW_MS } + if (state.failureTimes.isEmpty()) { + states.remove(key) + } else { + state.lockedUntil = 0L + state.expiresAt = state.failureTimes.last() + FAILURE_WINDOW_MS + } + false + } + + /** 记录一次失败;达到阈值后进入锁定。 */ + fun recordFailure(key: String, now: Long = System.currentTimeMillis()) = synchronized(lock) { + cleanupIfDue(now) + if (key !in states && states.size >= MAX_TRACKED_KEYS && !removeOldestUnlocked(now)) return@synchronized + val state = states.getOrPut(key) { State() } + if (now < state.lockedUntil) return@synchronized + state.failureTimes.removeAll { it < now - FAILURE_WINDOW_MS } + state.failureTimes.add(now) + if (state.failureTimes.size >= MAX_FAILURES) { + state.lockedUntil = now + LOCK_DURATION_MS + state.expiresAt = state.lockedUntil + state.failureTimes.clear() + } else { + state.lockedUntil = 0L + state.expiresAt = now + FAILURE_WINDOW_MS + } + } + + /** 登录成功:清空该键的失败记录与锁定。 */ + fun recordSuccess(key: String) { + synchronized(lock) { states.remove(key) } + } + + /** 清空全部状态(仅测试使用)。 */ + fun clear() { + synchronized(lock) { + states.clear() + nextCleanupAt = 0L + } + } + + internal fun trackedKeyCount(): Int = synchronized(lock) { states.size } + + private fun cleanupIfDue(now: Long) { + if (now < nextCleanupAt) return + states.entries.removeIf { it.value.expiresAt <= now } + nextCleanupAt = now + CLEANUP_INTERVAL_MS + } + + private fun removeOldestUnlocked(now: Long): Boolean { + val iterator = states.entries.iterator() + while (iterator.hasNext()) { + val entry = iterator.next() + if (entry.value.lockedUntil <= now) { + iterator.remove() + return true + } + } + return false + } + + companion object { + const val MAX_FAILURES = 5 + const val FAILURE_WINDOW_MS = 10 * 60 * 1000L + const val LOCK_DURATION_MS = 5 * 60 * 1000L + const val MAX_TRACKED_KEYS = 4_096 + private const val CLEANUP_INTERVAL_MS = 60 * 1000L + } +} diff --git a/src/main/kotlin/top/foxball/nekomainsite/authentication/SubmissionRateLimiter.kt b/src/main/kotlin/top/foxball/nekomainsite/authentication/SubmissionRateLimiter.kt new file mode 100644 index 0000000..1c1f928 --- /dev/null +++ b/src/main/kotlin/top/foxball/nekomainsite/authentication/SubmissionRateLimiter.kt @@ -0,0 +1,63 @@ +package top.foxball.nekomainsite.authentication + +import org.springframework.stereotype.Component + +/** + * 成员写入限流器(进程内,无外部依赖)。 + * + * 以「用户 + 资源类型」为键,在滑动时间窗口内限制提交次数, + * 防止单个账号刷申请、建议、报名、反馈或点赞淹没后台审核队列。 + * 阈值对正常使用足够宽松,仅在真实滥用时触发 429。 + */ +@Component +class SubmissionRateLimiter { + private class Window( + val times: MutableList = mutableListOf(), + var expiresAt: Long = 0L, + ) + + private val lock = Any() + private val windows = LinkedHashMap(16, 0.75f, true) + private var nextCleanupAt = 0L + + /** 当前键在窗口内是否允许下一次提交;允许时记录本次时间。 */ + fun allow(key: String, limit: Int, windowMs: Long, now: Long = System.currentTimeMillis()): Boolean = synchronized(lock) { + cleanupIfDue(now) + if (key !in windows && windows.size >= MAX_TRACKED_KEYS) removeOldest() + val window = windows.getOrPut(key) { Window() } + window.times.removeAll { it < now - windowMs } + if (window.times.size >= limit) return@synchronized false + window.times.add(now) + window.expiresAt = now + windowMs + true + } + + /** 清空全部状态(仅测试使用)。 */ + fun clear() { + synchronized(lock) { + windows.clear() + nextCleanupAt = 0L + } + } + + internal fun trackedKeyCount(): Int = synchronized(lock) { windows.size } + + private fun cleanupIfDue(now: Long) { + if (now < nextCleanupAt) return + windows.entries.removeIf { it.value.expiresAt <= now } + nextCleanupAt = now + CLEANUP_INTERVAL_MS + } + + private fun removeOldest() { + val iterator = windows.entries.iterator() + if (iterator.hasNext()) { + iterator.next() + iterator.remove() + } + } + + companion object { + const val MAX_TRACKED_KEYS = 4_096 + private const val CLEANUP_INTERVAL_MS = 60 * 1000L + } +} diff --git a/src/main/kotlin/top/foxball/nekomainsite/controller/AdminContentController.kt b/src/main/kotlin/top/foxball/nekomainsite/controller/AdminContentController.kt index bfee675..75c47c6 100644 --- a/src/main/kotlin/top/foxball/nekomainsite/controller/AdminContentController.kt +++ b/src/main/kotlin/top/foxball/nekomainsite/controller/AdminContentController.kt @@ -52,6 +52,10 @@ class AdminContentController( fun updateApplication(authentication: Authentication?, @PathVariable id: Long, @Valid @RequestBody request: ModerationRequest): ResponseEntity = builder.ok().data(adminContentService.updateApplication(authentication.operatorId(), id, request.status, request.note)).build() + @DeleteMapping("/applications/{id}") + fun deleteApplication(authentication: Authentication?, @PathVariable id: Long): ResponseEntity = + builder.ok().data(adminContentService.deleteApplication(authentication.operatorId(), id)).build() + @PatchMapping("/feedback/{id}") fun updateFeedback(authentication: Authentication?, @PathVariable id: Long, @Valid @RequestBody request: FeedbackModerationRequest): ResponseEntity = builder.ok().data(adminContentService.updateFeedback(authentication.operatorId(), id, request.status, request.note)).build() diff --git a/src/main/kotlin/top/foxball/nekomainsite/controller/AuthController.kt b/src/main/kotlin/top/foxball/nekomainsite/controller/AuthController.kt index df3d8c6..547e722 100644 --- a/src/main/kotlin/top/foxball/nekomainsite/controller/AuthController.kt +++ b/src/main/kotlin/top/foxball/nekomainsite/controller/AuthController.kt @@ -5,6 +5,7 @@ import jakarta.validation.Valid import jakarta.validation.constraints.NotBlank import jakarta.validation.constraints.Size import org.springframework.http.HttpHeaders +import org.springframework.http.HttpStatus import org.springframework.http.ResponseCookie import org.springframework.http.ResponseEntity import org.springframework.security.core.Authentication @@ -14,8 +15,11 @@ import org.springframework.web.bind.annotation.RequestBody import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RequestParam import org.springframework.web.bind.annotation.RestController +import top.foxball.nekomainsite.authentication.LoginAttemptLimiter import top.foxball.nekomainsite.authentication.LoginTokenAuthentication import top.foxball.nekomainsite.config.JwtProperties +import top.foxball.nekomainsite.handlder.UserDisabledException +import top.foxball.nekomainsite.handlder.UsernameOrPasswordErrorException import top.foxball.nekomainsite.service.AuthService import top.foxball.nekomainsite.service.BlessingSkinAuthService import top.foxball.nekomainsite.shared.ResponseBuilder @@ -28,12 +32,28 @@ class AuthController( private val loginTokenAuthentication: LoginTokenAuthentication, private val blessingSkinAuthService: BlessingSkinAuthService, private val jwtProperties: JwtProperties, + private val loginAttemptLimiter: LoginAttemptLimiter, private val builder: ResponseBuilder, ) { @PostMapping("/login") fun login(@Valid @RequestBody request: LoginRequest, http: HttpServletRequest): ResponseEntity { - val result = authService.login(request.username.trim(), request.password, http.getHeader("User-Agent").orEmpty()) - return authenticatedResponse(result, "登录失败") + val key = "${request.username.trim().lowercase()}|${clientIp(http)}" + if (loginAttemptLimiter.isLocked(key)) { + return builder.status(HttpStatus.TOO_MANY_REQUESTS) + .message("尝试次数过多,请稍后再试") + .build() + } + return try { + val result = authService.login(request.username.trim(), request.password, http.getHeader("User-Agent").orEmpty()) + loginAttemptLimiter.recordSuccess(key) + authenticatedResponse(result, "登录失败") + } catch (ex: UsernameOrPasswordErrorException) { + loginAttemptLimiter.recordFailure(key) + throw ex + } catch (ex: UserDisabledException) { + loginAttemptLimiter.recordFailure(key) + throw ex + } } @GetMapping("/me") @@ -83,6 +103,17 @@ class AuthController( return request.cookies?.firstOrNull { it.name == "neko_auth" }?.value } + private fun clientIp(request: HttpServletRequest): String { + return normalizeIp(request.remoteAddr) ?: "unknown" + } + + private fun normalizeIp(value: String?): String? { + val candidate = value?.trim()?.lowercase()?.takeIf { it.length in 2..64 } ?: return null + return candidate.takeIf { address -> + address.any { it == '.' || it == ':' } && address.all { it.isDigit() || it in 'a'..'f' || it == '.' || it == ':' } + } + } + private fun authCookie(token: String): ResponseCookie = ResponseCookie.from("neko_auth", token) .httpOnly(true).secure(jwtProperties.cookieSecure).path("/").sameSite("Strict").maxAge(jwtProperties.ttlSeconds).build() diff --git a/src/main/kotlin/top/foxball/nekomainsite/controller/PublicContentController.kt b/src/main/kotlin/top/foxball/nekomainsite/controller/PublicContentController.kt index c98e148..c1872c0 100644 --- a/src/main/kotlin/top/foxball/nekomainsite/controller/PublicContentController.kt +++ b/src/main/kotlin/top/foxball/nekomainsite/controller/PublicContentController.kt @@ -12,8 +12,10 @@ import org.springframework.web.bind.annotation.PostMapping import org.springframework.web.bind.annotation.RequestBody import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RestController +import top.foxball.nekomainsite.authentication.SubmissionRateLimiter import top.foxball.nekomainsite.entity.jdbc.ApplicationKind import top.foxball.nekomainsite.handlder.ParamErrorException +import top.foxball.nekomainsite.handlder.TooManyRequestsException import top.foxball.nekomainsite.service.ActivityView import top.foxball.nekomainsite.service.ApplicationCommand import top.foxball.nekomainsite.service.FeedbackCommand @@ -27,6 +29,7 @@ import top.foxball.nekomainsite.shared.Response as ApiResponse @RequestMapping("/api/public") class PublicContentController( private val siteContentService: SiteContentService, + private val submissionRateLimiter: SubmissionRateLimiter, private val builder: ResponseBuilder, ) { @GetMapping("/home") @@ -71,23 +74,30 @@ class PublicContentController( @GetMapping("/applications") fun applications(): ResponseEntity = builder.ok().data(mapOf("submissionRequiresLogin" to true)).build() + @GetMapping("/applications/mine") + fun myApplications(authentication: Authentication?): ResponseEntity = + builder.ok().data(siteContentService.memberApplications(authentication.userId())).build() + @PostMapping("/applications") fun submitApplication( authentication: Authentication?, @Valid @RequestBody request: ApplicationRequest, ): ResponseEntity { + ensureAllowed(authentication, "applications") val id = siteContentService.submitApplication(authentication.userId(), request.toCommand()) return builder.ok().data(mapOf("id" to id, "status" to "PENDING")).build() } @PostMapping("/ideas") fun submitIdea(authentication: Authentication?, @Valid @RequestBody request: IdeaRequest): ResponseEntity { + ensureAllowed(authentication, "ideas") val id = siteContentService.submitIdea(authentication.userId(), IdeaCommand(request.title, request.category, request.description)) return builder.ok().data(mapOf("id" to id, "status" to "PENDING")).build() } @PostMapping("/ideas/{id}/like") fun likeIdea(authentication: Authentication?, @PathVariable id: Long): ResponseEntity { + ensureAllowed(authentication, "likes", limit = LIKE_LIMIT) val likes = siteContentService.likeIdea(authentication.userId(), id) return builder.ok().data(mapOf("id" to id, "likes" to likes)).build() } @@ -98,18 +108,34 @@ class PublicContentController( @PathVariable slug: String, @Valid @RequestBody request: RegistrationRequest, ): ResponseEntity { + ensureAllowed(authentication, "registrations") val id = siteContentService.registerActivity(authentication.userId(), slug, RegistrationCommand(request.minecraftId, request.qq)) return builder.ok().data(mapOf("id" to id, "status" to "PENDING")).build() } @PostMapping("/feedback") fun submitFeedback(authentication: Authentication?, @Valid @RequestBody request: FeedbackRequest): ResponseEntity { + ensureAllowed(authentication, "feedback") val id = siteContentService.submitFeedback(authentication.userId(), FeedbackCommand(request.body)) return builder.ok().data(mapOf("id" to id, "status" to "OPEN")).build() } + private fun ensureAllowed(authentication: Authentication?, resource: String, limit: Int = SUBMISSION_LIMIT) { + val userId = authentication?.principal as? Long ?: return + val key = "$userId|$resource" + if (!submissionRateLimiter.allow(key, limit, WINDOW_MS)) { + throw TooManyRequestsException("操作过于频繁,请稍后再试") + } + } + private fun Authentication?.userId(): Long? = (this?.principal as? Long) + private companion object { + const val SUBMISSION_LIMIT = 5 + const val LIKE_LIMIT = 30 + const val WINDOW_MS = 10 * 60 * 1000L + } + data class ApplicationRequest( @field:NotBlank @field:Size(max = 30) val kind: String, @field:NotBlank @field:Size(max = 80) val name: String, diff --git a/src/main/kotlin/top/foxball/nekomainsite/controller/UserController.kt b/src/main/kotlin/top/foxball/nekomainsite/controller/UserController.kt index 872b8b5..5546998 100644 --- a/src/main/kotlin/top/foxball/nekomainsite/controller/UserController.kt +++ b/src/main/kotlin/top/foxball/nekomainsite/controller/UserController.kt @@ -30,6 +30,10 @@ class UserController( private val userService: UserService, private val builder: ResponseBuilder, ) { + @GetMapping + fun listUsers(): ResponseEntity = + builder.ok().data(userService.listUsers()).build() + @PostMapping("/Register") fun createUser(@Valid @RequestBody request: CreateUserRequest): ResponseEntity = builder.ok().data(userService.createUser(request.toCommand())).build() @@ -51,12 +55,20 @@ class UserController( } @PutMapping("/{id}") - fun updateUser(@PathVariable id: Long, @Valid @RequestBody request: UpdateUserRequest): ResponseEntity = - builder.ok().data(userService.updateUser(request.toCommand(id))).build() + fun updateUser( + authentication: Authentication?, + @PathVariable id: Long, + @Valid @RequestBody request: UpdateUserRequest, + ): ResponseEntity { + preventSelfLockout(authentication.userId(), id, request.role, request.enabled) + return builder.ok().data(userService.updateUser(request.toCommand(id))).build() + } @PutMapping("/Batch") - fun updateUsers(@Valid @RequestBody requests: List): ResponseEntity { + fun updateUsers(authentication: Authentication?, @Valid @RequestBody requests: List): ResponseEntity { validateBatchSize(requests.size) + val currentUserId = authentication.userId() + requests.forEach { preventSelfLockout(currentUserId, it.id, it.role, it.enabled) } return builder.ok().data(userService.updateUsers(requests.map(BatchUpdateUserRequest::toCommand))).build() } @@ -113,6 +125,12 @@ class UserController( if (size !in 1..MAX_BATCH_SIZE) throw ParamErrorException("批量操作每次只允许 1 到 $MAX_BATCH_SIZE 条记录") } + private fun preventSelfLockout(currentUserId: Long?, targetId: Long, targetRole: String, targetEnabled: Boolean) { + if (currentUserId == targetId && (!targetEnabled || !targetRole.equals("ADMIN", ignoreCase = true))) { + throw ConflictException("不能停用当前登录账号或移除自己的管理员权限") + } + } + private fun Authentication?.userId(): Long? = this?.principal as? Long private companion object { diff --git a/src/main/kotlin/top/foxball/nekomainsite/handlder/BusinessException.kt b/src/main/kotlin/top/foxball/nekomainsite/handlder/BusinessException.kt index 3aae38d..1084c62 100644 --- a/src/main/kotlin/top/foxball/nekomainsite/handlder/BusinessException.kt +++ b/src/main/kotlin/top/foxball/nekomainsite/handlder/BusinessException.kt @@ -41,3 +41,7 @@ class ResourceNotFoundException( class ParamErrorException( message: String = "参数错误" ) : BusinessException(HttpStatus.BAD_REQUEST, message) + +class TooManyRequestsException( + message: String = "操作过于频繁,请稍后再试" +) : BusinessException(HttpStatus.TOO_MANY_REQUESTS, message) diff --git a/src/main/kotlin/top/foxball/nekomainsite/handlder/GlobalExceptionHandler.kt b/src/main/kotlin/top/foxball/nekomainsite/handlder/GlobalExceptionHandler.kt index a2506b4..59a17a7 100644 --- a/src/main/kotlin/top/foxball/nekomainsite/handlder/GlobalExceptionHandler.kt +++ b/src/main/kotlin/top/foxball/nekomainsite/handlder/GlobalExceptionHandler.kt @@ -9,6 +9,7 @@ import org.springframework.http.HttpStatus import org.springframework.http.ResponseEntity import org.springframework.http.converter.HttpMessageNotReadableException import org.springframework.security.access.AccessDeniedException +import org.springframework.web.HttpMediaTypeNotSupportedException import org.springframework.web.HttpRequestMethodNotSupportedException import org.springframework.web.bind.MethodArgumentNotValidException import org.springframework.web.bind.MissingRequestHeaderException @@ -52,6 +53,13 @@ class GlobalExceptionHandler( .build() } + @ExceptionHandler(HttpMediaTypeNotSupportedException::class) + fun onHttpMediaTypeNotSupportedException(ex: HttpMediaTypeNotSupportedException): ResponseEntity { + return builder.status(HttpStatus.UNSUPPORTED_MEDIA_TYPE) + .message("请求的 Content-Type 不受支持,请使用 application/json") + .build() + } + @ExceptionHandler(NoResourceFoundException::class, NoHandlerFoundException::class) fun onNoResourceOrHandlerFoundException(): ResponseEntity { return builder.notFound().build() diff --git a/src/main/kotlin/top/foxball/nekomainsite/repository/SiteRepositories.kt b/src/main/kotlin/top/foxball/nekomainsite/repository/SiteRepositories.kt index 37b426e..da2dbd1 100644 --- a/src/main/kotlin/top/foxball/nekomainsite/repository/SiteRepositories.kt +++ b/src/main/kotlin/top/foxball/nekomainsite/repository/SiteRepositories.kt @@ -57,6 +57,7 @@ interface HistoryItemRepository : JpaRepository { interface ApplicationRepository : JpaRepository { fun findByStatusOrderByCreatedAtDesc(status: ModerationStatus): List fun countByStatus(status: ModerationStatus): Long + fun findAllByUserIdOrderByCreatedAtDesc(userId: Long): List fun findAllByOrderByCreatedAtDesc(): List } @@ -88,6 +89,7 @@ interface PrivateFeedbackRepository : JpaRepository { interface AuditLogRepository : JpaRepository { fun findAllByOrderByCreatedAtDesc(): List + fun findTop200ByOrderByCreatedAtDesc(): List } interface ContentDraftRepository : JpaRepository { diff --git a/src/main/kotlin/top/foxball/nekomainsite/repository/UserRepository.kt b/src/main/kotlin/top/foxball/nekomainsite/repository/UserRepository.kt index e28f36d..dfc4c08 100644 --- a/src/main/kotlin/top/foxball/nekomainsite/repository/UserRepository.kt +++ b/src/main/kotlin/top/foxball/nekomainsite/repository/UserRepository.kt @@ -10,4 +10,5 @@ interface UserRepository : JpaRepository { fun findByEmail(email: String): User? fun findByExternalUserId(externalUserId: String): User? fun countByRoleAndEnabledTrue(role: String): Long + fun findAllByOrderByCreatedAtDesc(): List } diff --git a/src/main/kotlin/top/foxball/nekomainsite/service/AdminContentService.kt b/src/main/kotlin/top/foxball/nekomainsite/service/AdminContentService.kt index 3489dc9..9de4ff5 100644 --- a/src/main/kotlin/top/foxball/nekomainsite/service/AdminContentService.kt +++ b/src/main/kotlin/top/foxball/nekomainsite/service/AdminContentService.kt @@ -73,6 +73,7 @@ data class AdminServerStatusView( ) data class AdminPublicationView(val id: Long, val published: Boolean) +data class AdminDeletionView(val id: Long, val deleted: Boolean) @Service @Transactional(readOnly = true) @@ -117,6 +118,14 @@ class AdminContentService( return result } + @Transactional + fun deleteApplication(operatorId: Long?, id: Long): AdminDeletionView { + val application = applicationRepository.findById(id).orElseThrow { ResourceNotFoundException("申请不存在") } + applicationRepository.delete(application) + audit(operatorId, "APPLICATION", id.toString(), "DELETE") + return AdminDeletionView(id, true) + } + @Transactional fun updateFeedback(operatorId: Long?, id: Long, status: FeedbackStatus, note: String?): AdminFeedbackView { val result = siteContentService.updateFeedbackStatus(id, status, note) @@ -192,7 +201,7 @@ class AdminContentService( return AdminPublicationView(id, false) } - fun auditLogs(): List = auditLogRepository.findAllByOrderByCreatedAtDesc().map { + fun auditLogs(): List = auditLogRepository.findTop200ByOrderByCreatedAtDesc().map { AdminAuditLogView( id = it.id.requirePresent("AuditLog.id"), operatorUserId = it.operatorUserId, diff --git a/src/main/kotlin/top/foxball/nekomainsite/service/SiteContentService.kt b/src/main/kotlin/top/foxball/nekomainsite/service/SiteContentService.kt index 53376a2..a852f1e 100644 --- a/src/main/kotlin/top/foxball/nekomainsite/service/SiteContentService.kt +++ b/src/main/kotlin/top/foxball/nekomainsite/service/SiteContentService.kt @@ -106,6 +106,11 @@ data class AdminApplicationView( val skill: String?, val status: String, val adminNote: String?, val createdAt: String, val updatedAt: String, ) +data class MemberApplicationView( + val id: Long, val kind: String, val name: String, val status: String, + val adminNote: String?, val createdAt: String, val updatedAt: String, +) + data class AdminIdeaView( val id: Long, val userId: Long?, val nickname: String, val title: String, val category: String, val description: String, val status: String, val publicReply: String?, val relatedSlug: String?, @@ -248,6 +253,9 @@ class SiteContentService( } fun adminApplications(): List = applicationRepository.findAllByOrderByCreatedAtDesc().map(::adminApplicationView) + fun memberApplications(userId: Long?): List = + applicationRepository.findAllByUserIdOrderByCreatedAtDesc(requiredUser(userId).id.requirePresent("User.id")) + .map(::memberApplicationView) fun adminIdeas(): List = ideaRepository.findAllByOrderByCreatedAtDesc().map(::adminIdeaView) fun adminRegistrations(): List = registrationRepository.findAllByOrderByCreatedAtDesc().map(::adminRegistrationView) fun adminFeedback(): List = feedbackRepository.findAllByOrderByCreatedAtDesc().map(::adminFeedbackView) @@ -389,6 +397,11 @@ class SiteContentService( item.availableTime, item.skill, item.status.name, item.adminNote, item.createdAt.toString(), item.updatedAt.toString(), ) + private fun memberApplicationView(item: Application) = MemberApplicationView( + item.id.requirePresent("Application.id"), item.kind.name, item.name, item.status.name, + item.adminNote, item.createdAt.toString(), item.updatedAt.toString(), + ) + private fun adminIdeaView(item: Idea) = AdminIdeaView( item.id.requirePresent("Idea.id"), item.userId, item.nickname, item.title, item.category, item.description, item.status.name, item.publicReply, item.relatedSlug, item.createdAt.toString(), item.updatedAt.toString(), diff --git a/src/main/kotlin/top/foxball/nekomainsite/service/UserService.kt b/src/main/kotlin/top/foxball/nekomainsite/service/UserService.kt index c44a88f..d09d4a5 100644 --- a/src/main/kotlin/top/foxball/nekomainsite/service/UserService.kt +++ b/src/main/kotlin/top/foxball/nekomainsite/service/UserService.kt @@ -32,6 +32,7 @@ data class UserAdminView( ) interface UserService { + fun listUsers(): List fun createUser(command: CreateUserCommand): UserAdminView fun createUsers(commands: List): List fun getUserById(id: Long): UserAdminView? diff --git a/src/main/kotlin/top/foxball/nekomainsite/service/impl/UserServiceImpl.kt b/src/main/kotlin/top/foxball/nekomainsite/service/impl/UserServiceImpl.kt index 537960e..6e579f6 100644 --- a/src/main/kotlin/top/foxball/nekomainsite/service/impl/UserServiceImpl.kt +++ b/src/main/kotlin/top/foxball/nekomainsite/service/impl/UserServiceImpl.kt @@ -21,6 +21,8 @@ class UserServiceImpl( private val passwordEncoder: PasswordEncoder, ) : UserService { + override fun listUsers(): List = userRepository.findAllByOrderByCreatedAtDesc().map(::view) + @Transactional override fun createUser(command: CreateUserCommand): UserAdminView { val normalized = normalize(command) diff --git a/src/main/resources/application.yaml b/src/main/resources/application.yaml index 52c1adb..b0b45f7 100644 --- a/src/main/resources/application.yaml +++ b/src/main/resources/application.yaml @@ -26,7 +26,7 @@ spring: server: port: ${SERVER_PORT:8080} - forward-headers-strategy: framework + forward-headers-strategy: native management: endpoints: diff --git a/src/test/kotlin/top/foxball/nekomainsite/authentication/LoginAttemptLimiterTest.kt b/src/test/kotlin/top/foxball/nekomainsite/authentication/LoginAttemptLimiterTest.kt new file mode 100644 index 0000000..8cb9c5c --- /dev/null +++ b/src/test/kotlin/top/foxball/nekomainsite/authentication/LoginAttemptLimiterTest.kt @@ -0,0 +1,95 @@ +package top.foxball.nekomainsite.authentication + +import org.junit.jupiter.api.Assertions.assertFalse +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertTrue +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test + +class LoginAttemptLimiterTest { + private lateinit var limiter: LoginAttemptLimiter + + @BeforeEach + fun setUp() { + limiter = LoginAttemptLimiter() + } + + @Test + fun `unknown key is not locked`() { + assertFalse(limiter.isLocked("admin|127.0.0.1", now = 1_000L)) + } + + @Test + fun `five failures lock the key`() { + repeat(LoginAttemptLimiter.MAX_FAILURES) { limiter.recordFailure("admin|127.0.0.1", now = 1_000L + it) } + assertTrue(limiter.isLocked("admin|127.0.0.1", now = 10_000L)) + } + + @Test + fun `four failures do not lock the key`() { + repeat(LoginAttemptLimiter.MAX_FAILURES - 1) { limiter.recordFailure("admin|127.0.0.1", now = 1_000L + it) } + assertFalse(limiter.isLocked("admin|127.0.0.1", now = 10_000L)) + } + + @Test + fun `lock expires after the lock duration`() { + repeat(LoginAttemptLimiter.MAX_FAILURES) { limiter.recordFailure("admin|127.0.0.1", now = 1_000L + it) } + assertTrue(limiter.isLocked("admin|127.0.0.1", now = 10_000L)) + assertFalse(limiter.isLocked("admin|127.0.0.1", now = 10_000L + LoginAttemptLimiter.LOCK_DURATION_MS + 1)) + } + + @Test + fun `success clears failures and lock`() { + repeat(LoginAttemptLimiter.MAX_FAILURES) { limiter.recordFailure("admin|127.0.0.1", now = 1_000L + it) } + assertTrue(limiter.isLocked("admin|127.0.0.1", now = 10_000L)) + limiter.recordSuccess("admin|127.0.0.1") + assertFalse(limiter.isLocked("admin|127.0.0.1", now = 10_000L)) + } + + @Test + fun `different keys are independent`() { + repeat(LoginAttemptLimiter.MAX_FAILURES) { limiter.recordFailure("admin|127.0.0.1", now = 1_000L + it) } + assertTrue(limiter.isLocked("admin|127.0.0.1", now = 10_000L)) + assertFalse(limiter.isLocked("admin|10.0.0.1", now = 10_000L)) + assertFalse(limiter.isLocked("other|127.0.0.1", now = 10_000L)) + } + + @Test + fun `old failures outside the window do not count`() { + repeat(LoginAttemptLimiter.MAX_FAILURES - 1) { limiter.recordFailure("admin|127.0.0.1", now = 1_000L + it) } + // 过期失败不累计;窗口外再失败 1 次仍不锁定 + limiter.recordFailure("admin|127.0.0.1", now = 1_000L + LoginAttemptLimiter.FAILURE_WINDOW_MS + 60_000L) + assertFalse(limiter.isLocked("admin|127.0.0.1", now = 1_000L + LoginAttemptLimiter.FAILURE_WINDOW_MS + 120_000L)) + } + + @Test + fun `expired keys are removed during later traffic`() { + limiter.recordFailure("old|127.0.0.1", now = 1_000L) + + limiter.recordFailure("new|127.0.0.1", now = 1_000L + LoginAttemptLimiter.FAILURE_WINDOW_MS + 1L) + + assertEquals(1, limiter.trackedKeyCount()) + } + + @Test + fun `tracked keys stay within the hard limit`() { + repeat(LoginAttemptLimiter.MAX_TRACKED_KEYS + 100) { index -> + limiter.recordFailure("user-$index|192.0.2.1", now = 1_000L) + } + + assertTrue(limiter.trackedKeyCount() <= LoginAttemptLimiter.MAX_TRACKED_KEYS) + } + + @Test + fun `capacity pressure never evicts an active lock`() { + val lockedKey = "admin|192.0.2.1" + repeat(LoginAttemptLimiter.MAX_FAILURES) { limiter.recordFailure(lockedKey, now = 1_000L + it) } + + repeat(LoginAttemptLimiter.MAX_TRACKED_KEYS + 100) { index -> + limiter.recordFailure("user-$index|192.0.2.1", now = 10_000L) + } + + assertTrue(limiter.isLocked(lockedKey, now = 10_001L)) + assertTrue(limiter.trackedKeyCount() <= LoginAttemptLimiter.MAX_TRACKED_KEYS) + } +} diff --git a/src/test/kotlin/top/foxball/nekomainsite/authentication/SubmissionRateLimiterTest.kt b/src/test/kotlin/top/foxball/nekomainsite/authentication/SubmissionRateLimiterTest.kt new file mode 100644 index 0000000..4c74d8b --- /dev/null +++ b/src/test/kotlin/top/foxball/nekomainsite/authentication/SubmissionRateLimiterTest.kt @@ -0,0 +1,70 @@ +package top.foxball.nekomainsite.authentication + +import org.junit.jupiter.api.Assertions.assertFalse +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertTrue +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test + +class SubmissionRateLimiterTest { + private lateinit var limiter: SubmissionRateLimiter + + @BeforeEach + fun setUp() { + limiter = SubmissionRateLimiter() + } + + @Test + fun `allows up to the limit within the window`() { + repeat(5) { assertTrue(limiter.allow("1|ideas", 5, 600_000L, now = 1_000L + it)) } + assertFalse(limiter.allow("1|ideas", 5, 600_000L, now = 10_000L)) + } + + @Test + fun `requests outside the window are allowed again`() { + repeat(5) { limiter.allow("1|ideas", 5, 600_000L, now = 1_000L + it) } + assertFalse(limiter.allow("1|ideas", 5, 600_000L, now = 100_000L)) + // 窗口滑过 600s 后旧记录失效,可以再次提交 + assertTrue(limiter.allow("1|ideas", 5, 600_000L, now = 1_000L + 600_000L + 60_000L)) + } + + @Test + fun `different keys are independent`() { + repeat(5) { limiter.allow("1|ideas", 5, 600_000L, now = 1_000L + it) } + assertFalse(limiter.allow("1|ideas", 5, 600_000L, now = 10_000L)) + assertTrue(limiter.allow("1|applications", 5, 600_000L, now = 10_000L)) + assertTrue(limiter.allow("2|ideas", 5, 600_000L, now = 10_000L)) + } + + @Test + fun `like limit uses its own threshold`() { + repeat(30) { assertTrue(limiter.allow("1|likes", 30, 600_000L, now = 1_000L + it)) } + assertFalse(limiter.allow("1|likes", 30, 600_000L, now = 100_000L)) + } + + @Test + fun `clear resets all state`() { + repeat(5) { limiter.allow("1|ideas", 5, 600_000L, now = 1_000L + it) } + assertFalse(limiter.allow("1|ideas", 5, 600_000L, now = 10_000L)) + limiter.clear() + assertTrue(limiter.allow("1|ideas", 5, 600_000L, now = 10_000L)) + } + + @Test + fun `expired keys are removed during later traffic`() { + limiter.allow("1|ideas", 5, 600_000L, now = 1_000L) + + limiter.allow("2|ideas", 5, 600_000L, now = 601_001L) + + assertEquals(1, limiter.trackedKeyCount()) + } + + @Test + fun `tracked keys stay within the hard limit`() { + repeat(SubmissionRateLimiter.MAX_TRACKED_KEYS + 100) { index -> + limiter.allow("$index|ideas", 5, 600_000L, now = 1_000L) + } + + assertTrue(limiter.trackedKeyCount() <= SubmissionRateLimiter.MAX_TRACKED_KEYS) + } +} diff --git a/src/test/kotlin/top/foxball/nekomainsite/controller/AdminApplicationDeletionTest.kt b/src/test/kotlin/top/foxball/nekomainsite/controller/AdminApplicationDeletionTest.kt new file mode 100644 index 0000000..64868c3 --- /dev/null +++ b/src/test/kotlin/top/foxball/nekomainsite/controller/AdminApplicationDeletionTest.kt @@ -0,0 +1,112 @@ +package top.foxball.nekomainsite.controller + +import jakarta.servlet.Filter +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Assertions.assertFalse +import org.junit.jupiter.api.Assertions.assertTrue +import org.junit.jupiter.api.Test +import org.springframework.beans.factory.annotation.Autowired +import org.springframework.boot.test.context.SpringBootTest +import org.springframework.test.web.servlet.MockMvc +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete +import org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath +import org.springframework.test.web.servlet.result.MockMvcResultMatchers.status +import org.springframework.test.web.servlet.setup.DefaultMockMvcBuilder +import org.springframework.test.web.servlet.setup.MockMvcBuilders +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken +import org.springframework.security.core.authority.SimpleGrantedAuthority +import org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.authentication +import org.springframework.transaction.annotation.Transactional +import org.springframework.web.context.WebApplicationContext +import top.foxball.nekomainsite.entity.jdbc.Application +import top.foxball.nekomainsite.repository.ApplicationRepository +import top.foxball.nekomainsite.repository.AuditLogRepository +import top.foxball.nekomainsite.repository.UserRepository + +@SpringBootTest +@Transactional +class AdminApplicationDeletionTest @Autowired constructor( + private val controller: AdminContentController, + private val applications: ApplicationRepository, + private val audits: AuditLogRepository, + private val users: UserRepository, + private val context: WebApplicationContext, +) { + private lateinit var mockMvc: MockMvc + + @BeforeEach + fun setUpMockMvc() { + val securityFilter = context.getBean("springSecurityFilterChain", Filter::class.java) + mockMvc = MockMvcBuilders.webAppContextSetup(context) + .addFilters(securityFilter) + .build() + } + + @Test + fun `administrator can permanently delete an application with audit record`() { + val admin = users.findByUsername("admin") ?: error("local admin missing") + val authentication = UsernamePasswordAuthenticationToken( + requireNotNull(admin.id), + null, + listOf(SimpleGrantedAuthority("ROLE_ADMIN")), + ) + val saved = applications.save(Application(name = "待删除申请", qq = "10000")) + val id = requireNotNull(saved.id) + + controller.deleteApplication(authentication, id) + + assertFalse(applications.existsById(id)) + assertTrue( + audits.findAllByOrderByCreatedAtDesc().any { + it.resourceType == "APPLICATION" && it.resourceId == id.toString() && it.action == "DELETE" + }, + ) + } + + @Test + fun `anonymous and ordinary members cannot delete applications`() { + val saved = applications.save(Application(name = "受保护申请", qq = "10001")) + val id = requireNotNull(saved.id) + + mockMvc.perform(delete("/api/admin/applications/{id}", id)) + .andExpect(status().isUnauthorized) + .andExpect(jsonPath("$.status").value(401)) + + val memberAuthentication = UsernamePasswordAuthenticationToken( + 999L, + null, + listOf(SimpleGrantedAuthority("ROLE_USER")), + ) + mockMvc.perform(delete("/api/admin/applications/{id}", id).with(authentication(memberAuthentication))) + .andExpect(status().isForbidden) + .andExpect(jsonPath("$.status").value(403)) + + assertTrue(applications.existsById(id)) + } + + @Test + fun `deleting an application twice returns not found without a second audit`() { + val admin = users.findByUsername("admin") ?: error("local admin missing") + val adminId = requireNotNull(admin.id) + val adminAuthentication = UsernamePasswordAuthenticationToken( + adminId, + null, + listOf(SimpleGrantedAuthority("ROLE_ADMIN")), + ) + val saved = applications.save(Application(name = "重复删除申请", qq = "10002")) + val id = requireNotNull(saved.id) + + mockMvc.perform(delete("/api/admin/applications/{id}", id).with(authentication(adminAuthentication))) + .andExpect(status().isOk) + .andExpect(jsonPath("$.data.deleted").value(true)) + + mockMvc.perform(delete("/api/admin/applications/{id}", id).with(authentication(adminAuthentication))) + .andExpect(status().isNotFound) + .andExpect(jsonPath("$.status").value(404)) + + val deletionAudits = audits.findAllByOrderByCreatedAtDesc().count { + it.resourceType == "APPLICATION" && it.resourceId == id.toString() && it.action == "DELETE" + } + assertTrue(deletionAudits == 1) + } +} diff --git a/src/test/kotlin/top/foxball/nekomainsite/controller/AuthControllerSecurityTest.kt b/src/test/kotlin/top/foxball/nekomainsite/controller/AuthControllerSecurityTest.kt index 599f096..e0e66ba 100644 --- a/src/test/kotlin/top/foxball/nekomainsite/controller/AuthControllerSecurityTest.kt +++ b/src/test/kotlin/top/foxball/nekomainsite/controller/AuthControllerSecurityTest.kt @@ -1,6 +1,7 @@ package top.foxball.nekomainsite.controller import jakarta.servlet.Filter +import jakarta.servlet.http.Cookie import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertFalse import org.junit.jupiter.api.Assertions.assertInstanceOf @@ -14,23 +15,30 @@ import org.springframework.http.HttpHeaders import org.springframework.http.MediaType import org.springframework.mock.web.MockHttpServletRequest import org.springframework.test.web.servlet.MockMvc +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get import org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post import org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath import org.springframework.test.web.servlet.result.MockMvcResultMatchers.status import org.springframework.test.web.servlet.setup.DefaultMockMvcBuilder import org.springframework.test.web.servlet.setup.MockMvcBuilders import org.springframework.web.context.WebApplicationContext +import top.foxball.nekomainsite.authentication.LoginAttemptLimiter +import top.foxball.nekomainsite.authentication.SubmissionRateLimiter import top.foxball.nekomainsite.service.AuthUserView @SpringBootTest class AuthControllerSecurityTest @Autowired constructor( private val controller: AuthController, private val context: WebApplicationContext, + private val loginAttemptLimiter: LoginAttemptLimiter, + private val submissionRateLimiter: SubmissionRateLimiter, ) { private lateinit var mockMvc: MockMvc @BeforeEach fun setUpMockMvc() { + loginAttemptLimiter.clear() + submissionRateLimiter.clear() val securityFilter = context.getBean("springSecurityFilterChain", Filter::class.java) mockMvc = MockMvcBuilders.webAppContextSetup(context) .addFilters(securityFilter) @@ -63,4 +71,78 @@ class AuthControllerSecurityTest @Autowired constructor( .andExpect(status().isUnauthorized) .andExpect(jsonPath("$.status").value(401)) } + + @Test + fun `proxy appended client address cannot be bypassed with a spoofed prefix`() { + repeat(LoginAttemptLimiter.MAX_FAILURES) { attempt -> + mockMvc.perform( + post("/api/auth/login") + .header("X-Forwarded-For", "198.51.100.$attempt, 203.0.113.8") + .header("User-Agent", "auth-controller-test") + .contentType(MediaType.APPLICATION_JSON) + .content("""{"username":"admin","password":"wrong-password"}"""), + ).andExpect(status().isUnauthorized) + } + + mockMvc.perform( + post("/api/auth/login") + .header("X-Forwarded-For", "198.51.100.99, 203.0.113.8") + .header("User-Agent", "auth-controller-test") + .contentType(MediaType.APPLICATION_JSON) + .content("""{"username":"admin","password":"wrong-password"}"""), + ) + .andExpect(status().isTooManyRequests) + .andExpect(jsonPath("$.status").value(429)) + } + + @Test + fun `authenticated member writes return 429 after the configured limit`() { + val cookie = adminCookie() + repeat(5) { attempt -> + mockMvc.perform( + post("/api/public/feedback") + .cookie(cookie) + .header("User-Agent", TEST_USER_AGENT) + .contentType(MediaType.APPLICATION_JSON) + .content("""{"body":"限流控制器测试 $attempt"}"""), + ).andExpect(status().isOk) + } + + mockMvc.perform( + post("/api/public/feedback") + .cookie(cookie) + .header("User-Agent", TEST_USER_AGENT) + .contentType(MediaType.APPLICATION_JSON) + .content("""{"body":"第六次提交"}"""), + ) + .andExpect(status().isTooManyRequests) + .andExpect(jsonPath("$.status").value(429)) + } + + @Test + fun `admin user list is protected and never exposes passwords`() { + mockMvc.perform(get("/api/users")) + .andExpect(status().isUnauthorized) + + mockMvc.perform( + get("/api/users") + .cookie(adminCookie()) + .header("User-Agent", TEST_USER_AGENT), + ) + .andExpect(status().isOk) + .andExpect(jsonPath("$.data[0].username").value("admin")) + .andExpect(jsonPath("$.data[0].password").doesNotExist()) + } + + private fun adminCookie(): Cookie { + val request = MockHttpServletRequest().apply { addHeader("User-Agent", TEST_USER_AGENT) } + val response = controller.login(AuthController.LoginRequest("admin", "admin12345"), request) + val setCookie = requireNotNull(response.headers.getFirst(HttpHeaders.SET_COOKIE)) + val token = setCookie.substringAfter("neko_auth=").substringBefore(';') + return Cookie("neko_auth", token) + } + + private companion object { + const val TEST_USER_AGENT = "auth-controller-test" + } } diff --git a/src/test/kotlin/top/foxball/nekomainsite/service/MemberApplicationHistoryTest.kt b/src/test/kotlin/top/foxball/nekomainsite/service/MemberApplicationHistoryTest.kt new file mode 100644 index 0000000..3f626a6 --- /dev/null +++ b/src/test/kotlin/top/foxball/nekomainsite/service/MemberApplicationHistoryTest.kt @@ -0,0 +1,46 @@ +package top.foxball.nekomainsite.service + +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertThrows +import org.junit.jupiter.api.Test +import org.springframework.beans.factory.annotation.Autowired +import org.springframework.boot.test.context.SpringBootTest +import org.springframework.transaction.annotation.Transactional +import top.foxball.nekomainsite.entity.jdbc.Application +import top.foxball.nekomainsite.entity.jdbc.ModerationStatus +import top.foxball.nekomainsite.entity.jdbc.User +import top.foxball.nekomainsite.handlder.UnauthorizedException +import top.foxball.nekomainsite.repository.ApplicationRepository +import top.foxball.nekomainsite.repository.UserRepository + +@SpringBootTest +@Transactional +class MemberApplicationHistoryTest @Autowired constructor( + private val service: SiteContentService, + private val applications: ApplicationRepository, + private val users: UserRepository, +) { + @Test + fun `members only see their own application status and admin reply`() { + val firstUser = users.save(User(username = "history-user-1", email = "history-1@example.test", password = "test")) + val secondUser = users.save(User(username = "history-user-2", email = "history-2@example.test", password = "test")) + applications.save( + Application( + userId = requireNotNull(firstUser.id), + name = "第一个成员", + qq = "10001", + status = ModerationStatus.ADOPTED, + adminNote = "申请已通过,请查看群内开服安排。", + ), + ) + applications.save(Application(userId = requireNotNull(secondUser.id), name = "其他成员", qq = "10002")) + + val result = service.memberApplications(firstUser.id) + + assertEquals(1, result.size) + assertEquals("第一个成员", result.single().name) + assertEquals("ADOPTED", result.single().status) + assertEquals("申请已通过,请查看群内开服安排。", result.single().adminNote) + assertThrows(UnauthorizedException::class.java) { service.memberApplications(null) } + } +} diff --git a/src/test/kotlin/top/foxball/nekomainsite/service/UserServiceTest.kt b/src/test/kotlin/top/foxball/nekomainsite/service/UserServiceTest.kt index 1e66237..c686654 100644 --- a/src/test/kotlin/top/foxball/nekomainsite/service/UserServiceTest.kt +++ b/src/test/kotlin/top/foxball/nekomainsite/service/UserServiceTest.kt @@ -45,4 +45,20 @@ class UserServiceTest @Autowired constructor( assertThrows(ConflictException::class.java) { service.disableUserById(adminId) } assertTrue(users.findById(adminId).orElseThrow().enabled) } + + @Test + fun `listUsers returns created accounts without password fields`() { + val created = service.createUser(CreateUserCommand( + username = "list-target", + email = "list-target@example.com", + password = "a-secure-test-password", + role = "USER", + displayName = "列表成员", + enabled = true, + )) + val listed = service.listUsers() + val view = listed.firstOrNull { it.id == created.id } ?: error("created user missing from list") + assertEquals("list-target", view.username) + assertTrue(view.toString().contains("list-target")) + } }