Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -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<Long> = mutableListOf(),
var lockedUntil: Long = 0L,
var expiresAt: Long = 0L,
)

private val lock = Any()
private val states = LinkedHashMap<String, State>(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
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
package top.foxball.nekomainsite.authentication

import org.springframework.stereotype.Component

/**
* 成员写入限流器(进程内,无外部依赖)。
*
* 以「用户 + 资源类型」为键,在滑动时间窗口内限制提交次数,
* 防止单个账号刷申请、建议、报名、反馈或点赞淹没后台审核队列。
* 阈值对正常使用足够宽松,仅在真实滥用时触发 429。
*/
@Component
class SubmissionRateLimiter {
private class Window(
val times: MutableList<Long> = mutableListOf(),
var expiresAt: Long = 0L,
)

private val lock = Any()
private val windows = LinkedHashMap<String, Window>(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
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,10 @@ class AdminContentController(
fun updateApplication(authentication: Authentication?, @PathVariable id: Long, @Valid @RequestBody request: ModerationRequest): ResponseEntity<ApiResponse> =
builder.ok().data(adminContentService.updateApplication(authentication.operatorId(), id, request.status, request.note)).build()

@DeleteMapping("/applications/{id}")
fun deleteApplication(authentication: Authentication?, @PathVariable id: Long): ResponseEntity<ApiResponse> =
builder.ok().data(adminContentService.deleteApplication(authentication.operatorId(), id)).build()

@PatchMapping("/feedback/{id}")
fun updateFeedback(authentication: Authentication?, @PathVariable id: Long, @Valid @RequestBody request: FeedbackModerationRequest): ResponseEntity<ApiResponse> =
builder.ok().data(adminContentService.updateFeedback(authentication.operatorId(), id, request.status, request.note)).build()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand All @@ -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<ApiResponse> {
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")
Expand Down Expand Up @@ -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()

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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")
Expand Down Expand Up @@ -71,23 +74,30 @@ class PublicContentController(
@GetMapping("/applications")
fun applications(): ResponseEntity<ApiResponse> = builder.ok().data(mapOf("submissionRequiresLogin" to true)).build()

@GetMapping("/applications/mine")
fun myApplications(authentication: Authentication?): ResponseEntity<ApiResponse> =
builder.ok().data(siteContentService.memberApplications(authentication.userId())).build()

@PostMapping("/applications")
fun submitApplication(
authentication: Authentication?,
@Valid @RequestBody request: ApplicationRequest,
): ResponseEntity<ApiResponse> {
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<ApiResponse> {
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<ApiResponse> {
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()
}
Expand All @@ -98,18 +108,34 @@ class PublicContentController(
@PathVariable slug: String,
@Valid @RequestBody request: RegistrationRequest,
): ResponseEntity<ApiResponse> {
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<ApiResponse> {
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,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,10 @@ class UserController(
private val userService: UserService,
private val builder: ResponseBuilder,
) {
@GetMapping
fun listUsers(): ResponseEntity<ApiResponse> =
builder.ok().data(userService.listUsers()).build()

@PostMapping("/Register")
fun createUser(@Valid @RequestBody request: CreateUserRequest): ResponseEntity<ApiResponse> =
builder.ok().data(userService.createUser(request.toCommand())).build()
Expand All @@ -51,12 +55,20 @@ class UserController(
}

@PutMapping("/{id}")
fun updateUser(@PathVariable id: Long, @Valid @RequestBody request: UpdateUserRequest): ResponseEntity<ApiResponse> =
builder.ok().data(userService.updateUser(request.toCommand(id))).build()
fun updateUser(
authentication: Authentication?,
@PathVariable id: Long,
@Valid @RequestBody request: UpdateUserRequest,
): ResponseEntity<ApiResponse> {
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<BatchUpdateUserRequest>): ResponseEntity<ApiResponse> {
fun updateUsers(authentication: Authentication?, @Valid @RequestBody requests: List<BatchUpdateUserRequest>): ResponseEntity<ApiResponse> {
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()
}

Expand Down Expand Up @@ -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 {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Loading