Limit what one address can do, and close idle rooms
Release / build (push) Successful in 4m20s

Someone scripting the server could guess the 4-character room codes
without limit (one connection, thousands a second), open all 2000 rooms
in seconds, or flood it with connections and messages. Per IP address
now:

- 10 wrong room codes in a row, then one a minute; while cut off even a
  right code gets no answer. Coming back to your seat with a token is
  not limited, and answers the same whether the room or the seat is
  gone, so it tells nothing about which codes are in use.
- 10 new rooms in a row, then one every 3 minutes.
- 32 connections at a time; 40 messages in a burst, then 10 a second.

The address comes from X-Forwarded-For only when the connection is from
the local or Docker network (the TLS proxy); the server warns once if
such connections arrive without the header.

A room where no player did anything for 3 hours now closes even with
screens still connected (a forgotten tab), telling them why. Rooms
nobody is connected to already closed after 10 minutes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
TMCandClaude Opus 5.5 committed 2026-11-16 11:22:17 +01:00
1 parent ca87d53632
commit 59a37277f2
6 files changed
+375 -12

No files matched your search

+11
View File
@@ -82,6 +82,17 @@ Ponovno pokretanje servera (nova verzija, restart računala) ne prekida partije.
- Spremanje i učitavanje: `server/.../RoomStore.kt` (datoteka), `Rooms.kt` (kada), `Room.kt` (`snapshot`, `restore`). Partija se sprema kao sjeme i popis poteza (`GameRecord`, isti zapis kao spremljena lokalna igra) i ponovno odigra pri učitavanju.
- Ako se pravila u novoj verziji promijene tako da se stara partija ne može ponovno odigrati, soba ostaje, ali bez partije: igrači se vrate u čekaonicu i domaćin pokrene novu.
Soba nestaje kad je svi napuste, 10 minuta nakon što se posljednji igrač odspoji, ili nakon 3 sata u kojima nitko od igrača ništa nije odigrao ni kliknuo, čak i kad im je stranica otvorena (`Timing.idleClose`). Tada spojenim igračima javi da je soba zatvorena.
Zaštita od skripti (`server/.../Limits.kt`), po IP adresi:
- **Pogađanje kodova:** nakon 10 pogrešnih kodova adresa može pokušati još jedan kod u minuti. Dok je blokirana, ne dobiva odgovor ni za točan kod, pa joj pogađanje ne koristi. Povratak na svoje mjesto (token) nije ograničen. Taj povratak na nepostojeću sobu i povratak s krivim tokenom dobivaju isti odgovor, tako da ni preko toga ne može doznati koji su kodovi zauzeti.
- **Otvaranje soba:** 10 soba zaredom, zatim jedna svake 3 minute. Ukupno je dopušteno najviše 2000 otvorenih soba.
- **Veze:** najviše 32 istodobne veze s jedne adrese.
- **Poruke:** 40 poruka odjednom, zatim 10 u sekundi po vezi. Kad veza to prijeđe, server je prekine.
Server uzima adresu iz `X-Forwarded-For` samo kad veza dolazi s lokalne ili Docker mreže, odnosno od proxyja. Ako proxy ne šalje `X-Forwarded-For`, svi igrači izgledaju kao jedna adresa i dijele ograničenja. Server to jednom upozori u logu (`Connections come from … without X-Forwarded-For`).
## Server, Docker i Gitea Actions
Jedna Docker slika (`Dockerfile`) gradi web i server (uz testove) i pokreće server koji poslužuje web na `/`, igru na `/ws` i `/health`. Gitea Actions (`.gitea/workflows/release.yml`, isto kao Keep) na svaki push na `main` gradi sliku, skenira je Trivyjem i objavljuje kao `git.mariosem.es/msemes/bela:<sha>` i `:latest`. Za objavu repozitorij treba tajnu `REGISTRY_TOKEN` (osobni token s `write:package`).
@@ -0,0 +1,108 @@
package hr.bela.server
import java.net.Inet6Address
import java.net.InetAddress
/**
* How much one client may do, against someone scripting the server: guessing room codes, opening rooms by the
* hundred, or flooding it with connections and messages. Generous enough that people playing never notice.
* "Address" is the client's IP address ([clientAddress]).
*/
data class Limits(
/** Wrong room codes an address may try in a row; after that one more every [wrongCodeEvery] ms. */
val wrongCodes: Int = 10,
val wrongCodeEvery: Long = 60_000L,
/** Rooms an address may open in a row; after that one more every [newRoomEvery] ms. */
val newRooms: Int = 10,
val newRoomEvery: Long = 3 * 60_000L,
/** Connections open at the same time from one address (a whole office or family shares one). */
val connections: Int = 32,
/** Messages a connection may send in a burst; after that one more every [messageEvery] ms. */
val messageBurst: Int = 40,
val messageEvery: Long = 100L,
)
/**
* A token bucket per key: [capacity] tokens, one more every [every] ms. Full buckets are forgotten, so the map
* only holds the keys that used it lately.
*/
class RateLimiter(
private val capacity: Int,
private val every: Long,
private val clock: () -> Long = System::currentTimeMillis,
) {
private class Bucket(var tokens: Double, var at: Long)
private val buckets = HashMap<String, Bucket>()
private var calls = 0
/** Whether [key] has a token left, without taking it. */
@Synchronized
fun allows(key: String): Boolean = level(key, clock()) >= 1
/** Takes one of [key]'s tokens; false (and nothing taken) when it has none left. */
@Synchronized
fun take(key: String): Boolean {
val now = clock()
val tokens = level(key, now)
if (tokens < 1) return false
buckets[key] = Bucket(tokens - 1, now)
if (++calls % 1024 == 0) buckets.entries.removeAll { level(it.value, now) >= capacity }
return true
}
private fun level(key: String, now: Long): Double = buckets[key]?.let { level(it, now) } ?: capacity.toDouble()
private fun level(bucket: Bucket, now: Long): Double =
minOf(capacity.toDouble(), bucket.tokens + (now - bucket.at).toDouble() / every)
}
/** Open connections per address, at most [max] each. */
class ConnectionCounter(private val max: Int) {
private val open = HashMap<String, Int>()
/** Counts a new connection from [key]; false (and not counted) when [key] already has [max]. */
@Synchronized
fun open(key: String): Boolean {
val count = open[key] ?: 0
if (count >= max) return false
open[key] = count + 1
return true
}
@Synchronized
fun close(key: String) {
val count = open[key] ?: return
if (count <= 1) open.remove(key) else open[key] = count - 1
}
}
/**
* The client's IP address: the one the connection comes from, or, when that is a proxy on this machine or the local
* network (the TLS front end), the address the proxy saw, which it adds last to X-Forwarded-For. A client connecting
* from the internet straight to the port cannot choose its address by sending the header itself.
*/
fun clientAddress(peer: String, forwardedFor: String?): String {
val forwarded = forwardedFor?.substringAfterLast(',')?.trim()?.takeIf { it.isNotEmpty() } ?: return peer
return if (isLocal(peer)) forwarded else peer
}
/**
* A connection from another machine on the local network (or a Docker network) without X-Forwarded-For: most likely
* a proxy that does not send it, so every player looks like the proxy and they all share one address's [Limits].
*/
fun proxyWithoutForwardedFor(peer: String, forwardedFor: String?): Boolean =
forwardedFor.isNullOrBlank() && isLocal(peer) && peer != "localhost" &&
runCatching { !InetAddress.getByName(peer.substringBefore('%')).isLoopbackAddress }.getOrDefault(false)
private fun isLocal(address: String): Boolean {
if (address == "localhost") return true
val literal = address.substringBefore('%')
// A literal address only (IPv4, or IPv6 with its colons): a name would be looked up.
if (!literal.matches(IPV4) && !(':' in literal && literal.all { it.isLetterOrDigit() || it in ".:" })) return false
val ip = runCatching { InetAddress.getByName(literal) }.getOrNull() ?: return false
return ip.isLoopbackAddress || ip.isSiteLocalAddress || ip.isLinkLocalAddress ||
(ip is Inet6Address && (ip.address[0].toInt() and 0xfe) == 0xfc)
}
private val IPV4 = Regex("""\d{1,3}(\.\d{1,3}){3}""")
+73 -6
View File
@@ -21,13 +21,17 @@ import io.ktor.server.websocket.WebSockets
import io.ktor.server.websocket.pingPeriod
import io.ktor.server.websocket.timeout
import io.ktor.server.websocket.webSocket
import io.ktor.websocket.CloseReason
import io.ktor.websocket.DefaultWebSocketSession
import io.ktor.websocket.Frame
import io.ktor.websocket.close
import io.ktor.websocket.readText
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.withTimeoutOrNull
import org.slf4j.LoggerFactory
import org.slf4j.event.Level
import java.io.File
import java.util.concurrent.atomic.AtomicBoolean
import kotlin.time.Duration.Companion.seconds
/**
@@ -45,12 +49,18 @@ fun main() {
embeddedServer(Netty, port = port) { bela(webRoot, store = store) }.start(wait = true)
}
fun Application.bela(webRoot: File?, timing: Timing = Timing(), store: RoomStore? = null) {
fun Application.bela(webRoot: File?, timing: Timing = Timing(), store: RoomStore? = null, limits: Limits = Limits()) {
val log = LoggerFactory.getLogger("bela")
if (store == null) log.info("No DATA_DIR: open rooms will not survive a restart") else log.info("Open rooms are kept in {}", store.file)
// Loaded here, before the server takes connections, so returning players find their rooms.
val rooms = Rooms(this, timing, store = store)
monitor.subscribe(ApplicationStopping) { rooms.stop() }
val wrongCodes = RateLimiter(limits.wrongCodes, limits.wrongCodeEvery)
val newRooms = RateLimiter(limits.newRooms, limits.newRoomEvery)
val connections = ConnectionCounter(limits.connections)
val proxyWarned = AtomicBoolean(false)
// A warning about an address at most once a minute, so someone scripting the server cannot fill the log.
val warnings = RateLimiter(1, 60_000L)
install(CallLogging) {
level = Level.INFO
@@ -66,12 +76,35 @@ fun Application.bela(webRoot: File?, timing: Timing = Timing(), store: RoomStore
get("/health") { call.respondText("ok") }
webSocket("/ws") {
val peer = call.request.local.remoteAddress
val forwardedFor = call.request.headers["X-Forwarded-For"]
if (proxyWithoutForwardedFor(peer, forwardedFor) && proxyWarned.compareAndSet(false, true)) {
log.warn(
"Connections come from {} without X-Forwarded-For: all players count as one address for the " +
"limits on connections and room codes. Let the proxy in front send X-Forwarded-For.",
peer,
)
}
val address = clientAddress(peer, forwardedFor)
if (!connections.open(address)) {
if (warnings.take("connections $address")) log.warn("Too many connections from {}; refused", address)
sendNow(ServerMessage.Error(TOO_MANY_CONNECTIONS, fatal = true))
close(CloseReason(CloseReason.Codes.TRY_AGAIN_LATER, "Too many connections"))
return@webSocket
}
val connection = Connection(this)
val messages = RateLimiter(limits.messageBurst, limits.messageEvery)
var room: Room? = null
var member: Member? = null
try {
for (frame in incoming) {
if (frame !is Frame.Text) continue
if (!messages.take("")) {
if (warnings.take("messages $address")) log.warn("{} sends too many messages; disconnected", address)
// Straight away: the socket closes when this loop ends, before the queue would be sent.
sendNow(ServerMessage.Error("Previše poruka odjednom. Spoji se ponovno.", fatal = true))
break
}
val message = try {
Protocol.json.decodeFromString(ClientMessage.serializer(), frame.readText())
} catch (_: Exception) {
@@ -106,11 +139,38 @@ fun Application.bela(webRoot: File?, timing: Timing = Timing(), store: RoomStore
connection.send(ServerMessage.Error("Upiši svoje ime."))
continue
}
val target = if (entry.code == null) rooms.create() else rooms[entry.code]
if (target == null) {
val text = if (entry.code == null) "Poslužitelj je trenutno pun, pokušaj kasnije." else "Soba ${entry.code} ne postoji."
connection.send(ServerMessage.Error(text, fatal = true))
continue
val target = when {
entry.code == null -> {
if (!newRooms.take(address)) {
if (warnings.take("rooms $address")) log.warn("{} opens too many rooms", address)
connection.send(ServerMessage.Error("Otvorio si previše soba zaredom. Pričekaj par minuta.", fatal = true))
continue
}
rooms.create() ?: run {
connection.send(ServerMessage.Error("Poslužitelj je trenutno pun, pokušaj kasnije.", fatal = true))
continue
}
}
// Coming back with a token: one answer whether the room or the seat is gone, so a made-up
// token tells nothing about which codes are in use. Tokens cannot be guessed.
entry.token != null -> rooms[entry.code] ?: run {
connection.send(ServerMessage.Error("Tvoje mjesto u sobi ${entry.code} je isteklo.", fatal = true))
continue
}
// Joining by code: an address that keeps guessing codes is cut off for a while, and then even
// a right code gets no answer, so the guessing is no use.
!wrongCodes.allows(address) -> {
connection.send(ServerMessage.Error("Previše pogrešnih kodova. Pričekaj minutu pa pokušaj ponovno.", fatal = true))
continue
}
else -> rooms[entry.code] ?: run {
wrongCodes.take(address)
if (!wrongCodes.allows(address) && warnings.take("codes $address")) {
log.warn("{} tried too many wrong room codes; cut off for a while", address)
}
connection.send(ServerMessage.Error("Soba ${entry.code} ne postoji.", fatal = true))
continue
}
}
val reply = CompletableDeferred<Member?>()
val joined = target.post(Room.Event.Enter(connection, entry.name, entry.token, reply)) &&
@@ -126,6 +186,7 @@ fun Application.bela(webRoot: File?, timing: Timing = Timing(), store: RoomStore
val m = member
if (m != null) room?.post(Room.Event.Gone(m, connection))
connection.close()
connections.close(address)
}
}
@@ -157,6 +218,12 @@ fun Application.bela(webRoot: File?, timing: Timing = Timing(), store: RoomStore
}
}
/** Sends [message] now, not through the [Connection]'s queue. */
private suspend fun DefaultWebSocketSession.sendNow(message: ServerMessage) =
send(Frame.Text(Protocol.json.encodeToString(ServerMessage.serializer(), message)))
private const val TOO_MANY_CONNECTIONS = "Previše je veza s tvoje mreže. Pokušaj ponovno kasnije."
private const val OUTDATED = "Ova verzija Bele je zastarjela za igru online. Ažuriraj aplikaciju ili osvježi stranicu."
/** What a create, join or resume message asks for: [code] null creates a room; [token] set resumes a seat. */
+21 -1
View File
@@ -38,6 +38,11 @@ data class Timing(
val botTakeover: Long = 10_000L,
/** A player away for this long loses their seat (a bot keeps playing it meanwhile). */
val dropAfter: Long = 10 * 60_000L,
/**
* A room where none of the players did anything for this long closes, even with their screens still connected
* (a tab left open): a forgotten room should not live for days.
*/
val idleClose: Long = 3 * 3600_000L,
val sweepEvery: Long = 30_000L,
/** After a restart, players get this long to reconnect before bots play their seats. */
val restoreGrace: Long = 30_000L,
@@ -109,6 +114,9 @@ class Room(
private var plannedFor: GameState? = null
private var plannedAt = 0L
private var generation = 0
/** When a player last joined or did something here ([Timing.idleClose]); bots do not count. */
private var lastActive = clock()
private var closed = false
private val sweeper: Job
@@ -140,6 +148,7 @@ class Room(
when (event) {
is Event.Enter -> enter(event)
is Event.Message -> if (event.member.connection === event.connection && event.member in members) {
lastActive = clock()
message(event.member, event.message)
}
is Event.Gone -> gone(event.member, event.connection)
@@ -183,6 +192,7 @@ class Room(
}
}
member.connection = connection
lastActive = clock()
event.reply.complete(member)
connection.send(ServerMessage.Joined(code, member.token))
sendRoom()
@@ -217,9 +227,17 @@ class Room(
schedule()
}
/** Drops players who have been away too long; closes the room when nobody is left. */
/** Drops players who have been away too long; closes the room when nobody is left, or nobody plays any more. */
private fun sweep() {
val now = clock()
if (now - lastActive > timing.idleClose) {
log.info("Nothing happened for {} min", (now - lastActive) / 60_000)
for (member in members) {
member.connection?.send(ServerMessage.Error("Soba $code je zatvorena jer se u njoj dugo ništa nije događalo.", fatal = true))
}
members.clear()
return close()
}
members.filter { it.connection == null && now - it.awaySince > timing.dropAfter }.forEach(::leave)
if (members.isEmpty()) close()
}
@@ -367,6 +385,7 @@ class Room(
members = members.map { SavedMember(it.token, it.name, it.seat, if (it.connection == null) it.awaySince else 0) },
host = host?.token,
game = record?.encode(),
lastActive = lastActive,
)
private fun restore(saved: SavedRoom) {
@@ -383,6 +402,7 @@ class Room(
game = record?.let { runCatching { it.replay() }.onFailure { e -> log.warn("Game not restored: {}", e.message) }.getOrNull() }
this.record = record.takeIf { game != null }
graceUntil = now + timing.restoreGrace
if (saved.lastActive > 0) lastActive = saved.lastActive
log.info("Restored with {} player(s){}", members.size, if (game != null) ", game in progress" else "")
}
@@ -11,13 +11,17 @@ import java.nio.file.StandardCopyOption
@Serializable
data class SavedMember(val token: String, val name: String, val seat: Int, val awaySince: Long = 0)
/** A room as saved: its people, the host (by token) and the game so far ([hr.bela.engine.GameRecord.encode]). */
/**
* A room as saved: its people, the host (by token), the game so far ([hr.bela.engine.GameRecord.encode]) and when a
* player last did something (0: unknown, from an older save).
*/
@Serializable
data class SavedRoom(
val code: String,
val members: List<SavedMember>,
val host: String? = null,
val game: String? = null,
val lastActive: Long = 0,
)
@Serializable
@@ -32,11 +32,26 @@ import kotlin.test.assertTrue
class ServerTest {
private val fast = Timing(dealPause = 0, bidDelay = 1, playDelay = 1, trickPause = 0, trumpPause = 0)
private fun serverTest(block: suspend ApplicationTestBuilder.() -> Unit) = testApplication {
application { bela(webRoot = null, timing = fast) }
/** The test players play at machine speed, far more messages a second than a person sends. */
private val machineSpeed = Limits(messageEvery = 1)
private fun serverTest(
timing: Timing = fast,
limits: Limits = machineSpeed,
block: suspend ApplicationTestBuilder.() -> Unit,
) = testApplication {
application { bela(webRoot = null, timing = timing, limits = limits) }
block()
}
/** The next error, skipping everything else. */
private suspend fun DefaultClientWebSocketSession.expectError(): ServerMessage.Error {
while (true) {
val message = receive()
if (message is ServerMessage.Error) return message
}
}
private suspend fun DefaultClientWebSocketSession.send(message: ClientMessage) =
send(Frame.Text(Protocol.json.encodeToString(ClientMessage.serializer(), message)))
@@ -175,7 +190,7 @@ class ServerTest {
var token = ""
var before: TableView? = null
testApplication {
application { bela(webRoot = null, timing = fast, store = store) }
application { bela(webRoot = null, timing = fast, store = store, limits = machineSpeed) }
val ws = createClient { install(WebSockets) }
ws.webSocket("/ws") {
send(ClientMessage.CreateRoom("Ana"))
@@ -198,7 +213,7 @@ class ServerTest {
} // the server stops (a new release): the rooms are written to the store
assertTrue(store.file.exists())
testApplication {
application { bela(webRoot = null, timing = fast, store = store) }
application { bela(webRoot = null, timing = fast, store = store, limits = machineSpeed) }
val ws = createClient { install(WebSockets) }
ws.webSocket("/ws") {
send(ClientMessage.Resume(code, token))
@@ -211,6 +226,144 @@ class ServerTest {
}
}
@Test
fun guessingRoomCodesIsCutOff() = serverTest(limits = Limits(wrongCodes = 3, wrongCodeEvery = 3_600_000)) {
val ws = createClient { install(WebSockets) }
val joined = CompletableDeferred<ServerMessage.Joined>()
val guessed = CompletableDeferred<Unit>()
coroutineScope {
val host = async {
ws.webSocket("/ws") {
send(ClientMessage.CreateRoom("Ana"))
joined.complete(expect<ServerMessage.Joined>())
guessed.await()
}
}
val (code, token) = joined.await().let { it.code to it.token }
ws.webSocket("/ws") {
for (guess in listOf("AAAA", "BBBB", "CCCC", "DDDD").filter { it != code }.take(3)) {
send(ClientMessage.JoinRoom(guess, "Ivo"))
assertTrue("ne postoji" in assertIs<ServerMessage.Error>(receive()).message)
}
// Cut off: now even the right code gets no answer.
send(ClientMessage.JoinRoom(code, "Ivo"))
val error = assertIs<ServerMessage.Error>(receive())
assertTrue(error.fatal && "Previše pogrešnih kodova" in error.message, error.message)
// A player coming back to their own seat is not held up by it.
send(ClientMessage.Resume(code, token))
assertEquals(code, expect<ServerMessage.Joined>().code)
}
guessed.complete(Unit)
host.await()
}
}
@Test
fun openingRoomsIsLimited() = serverTest(limits = Limits(newRooms = 2, newRoomEvery = 3_600_000)) {
val ws = createClient { install(WebSockets) }
ws.webSocket("/ws") {
send(ClientMessage.CreateRoom("Ana"))
expect<ServerMessage.Joined>()
send(ClientMessage.CreateRoom("Ana"))
expect<ServerMessage.Joined>()
send(ClientMessage.CreateRoom("Ana"))
val error = expectError()
assertTrue(error.fatal && "previše soba" in error.message, error.message)
}
}
@Test
fun aComebackAfterTheRoomClosedSaysTheSeatExpired() = serverTest {
val ws = createClient { install(WebSockets) }
ws.webSocket("/ws") {
send(ClientMessage.Resume("ZZZZ", "not-a-token"))
val error = assertIs<ServerMessage.Error>(receive())
assertTrue(error.fatal && "isteklo" in error.message, error.message)
}
}
@Test
fun aRoomWhereNothingHappensCloses() = serverTest(timing = fast.copy(idleClose = 300, sweepEvery = 100)) {
val ws = createClient { install(WebSockets) }
ws.webSocket("/ws") {
send(ClientMessage.CreateRoom("Ana"))
val code = expect<ServerMessage.Joined>().code
val error = withTimeout(10_000) { expectError() }
assertTrue(error.fatal && "zatvorena" in error.message, error.message)
send(ClientMessage.JoinRoom(code, "Ana"))
assertTrue("ne postoji" in expectError().message, "the room is gone")
}
}
@Test
fun aClientFloodingMessagesIsDisconnected() = serverTest(limits = Limits(messageBurst = 5, messageEvery = 3_600_000)) {
val ws = createClient { install(WebSockets) }
ws.webSocket("/ws") {
send(ClientMessage.CreateRoom("Ana"))
expect<ServerMessage.Joined>()
repeat(10) { send(ClientMessage.TakeSeat(0)) }
val error = expectError()
assertTrue(error.fatal && "Previše poruka" in error.message, error.message)
}
}
@Test
fun tooManyConnectionsFromOneAddressAreRefused() = serverTest(limits = Limits(connections = 1)) {
val ws = createClient { install(WebSockets) }
val first = CompletableDeferred<Unit>()
val done = CompletableDeferred<Unit>()
coroutineScope {
val open = async {
ws.webSocket("/ws") {
send(ClientMessage.CreateRoom("Ana"))
expect<ServerMessage.Joined>()
first.complete(Unit)
done.await()
}
}
first.await()
ws.webSocket("/ws") {
val error = assertIs<ServerMessage.Error>(receive())
assertTrue(error.fatal && "Previše je veza" in error.message, error.message)
}
done.complete(Unit)
open.await()
}
// The first one closed, so there is room for another.
ws.webSocket("/ws") {
send(ClientMessage.CreateRoom("Ana"))
expect<ServerMessage.Joined>()
}
}
@Test
fun theProxysAddressIsTrustedOnlyFromTheLocalNetwork() {
assertEquals("203.0.113.7", clientAddress("203.0.113.7", null))
assertEquals("203.0.113.7", clientAddress("203.0.113.7", "198.51.100.1"), "straight from the internet: the header is ignored")
assertEquals("198.51.100.2", clientAddress("172.18.0.2", "10.0.0.5, 198.51.100.2"), "behind the proxy: the address it saw")
assertEquals("198.51.100.2", clientAddress("127.0.0.1", "198.51.100.2"))
assertEquals("198.51.100.2", clientAddress("::1", "198.51.100.2"))
assertEquals("example.com", clientAddress("example.com", "198.51.100.2"), "a name is never looked up")
assertTrue(proxyWithoutForwardedFor("172.17.0.1", null), "the Docker gateway without the header")
assertFalse(proxyWithoutForwardedFor("172.17.0.1", "198.51.100.2"))
assertFalse(proxyWithoutForwardedFor("127.0.0.1", null), "a local test run")
assertFalse(proxyWithoutForwardedFor("203.0.113.7", null), "a player straight from the internet")
}
@Test
fun rateLimiterRefills() {
var now = 0L
val limiter = RateLimiter(capacity = 2, every = 1_000, clock = { now })
assertTrue(limiter.take("a") && limiter.take("a"))
assertFalse(limiter.take("a"))
assertTrue(limiter.take("b"), "each key has its own bucket")
now = 999
assertFalse(limiter.allows("a"))
now = 1_000
assertTrue(limiter.take("a"))
assertFalse(limiter.take("a"))
}
@Test
fun anUnreadableStoreIsSetAside() {
val store = RoomStore(File(Files.createTempDirectory("bela").toFile(), "rooms.json"))