diff --git a/common/src/main/kotlin/de/fiereu/openmmo/common/auth/RememberMeToken.kt b/common/src/main/kotlin/de/fiereu/openmmo/common/auth/RememberMeToken.kt new file mode 100644 index 0000000..a807dfa --- /dev/null +++ b/common/src/main/kotlin/de/fiereu/openmmo/common/auth/RememberMeToken.kt @@ -0,0 +1,105 @@ +package de.fiereu.openmmo.common.auth + +import java.nio.ByteBuffer +import java.security.MessageDigest +import java.time.Clock +import java.time.Duration +import java.time.Instant +import javax.crypto.Mac +import javax.crypto.spec.SecretKeySpec + +/** + * Long lived credential the client stores in place of a password. The epoch is the user's current + * token generation, so raising it in the database invalidates every token already issued to them. + */ +data class RememberMeToken( + val userId: Int, + val epoch: Int, + val issuedAt: Instant, + val bytes: ByteArray, +) { + override fun equals(other: Any?): Boolean = + other is RememberMeToken && + userId == other.userId && + epoch == other.epoch && + issuedAt == other.issuedAt && + bytes.contentEquals(other.bytes) + + override fun hashCode(): Int { + var h = userId + h = h * 31 + epoch + h = h * 31 + issuedAt.hashCode() + h = h * 31 + bytes.contentHashCode() + return h + } +} + +class RememberMeTokenIssuer(secret: ByteArray, private val clock: Clock = Clock.systemUTC()) { + init { + require(secret.isNotEmpty()) { "remember me token secret must not be empty" } + } + + private val secretKey = SecretKeySpec(secret, REMEMBER_ME_MAC_ALGORITHM) + + fun issue(userId: Int, epoch: Int): RememberMeToken { + val issuedAt = clock.instant() + val bytes = ByteArray(REMEMBER_ME_TOKEN_SIZE) + ByteBuffer.wrap(bytes, 0, REMEMBER_ME_PREFIX_SIZE) + .putInt(userId) + .putInt(epoch) + .putLong(issuedAt.epochSecond) + signRememberMe(bytes, secretKey) + return RememberMeToken(userId, epoch, issuedAt, bytes) + } +} + +class RememberMeTokenVerifier( + secret: ByteArray, + private val maxAge: Duration, + private val clock: Clock = Clock.systemUTC(), +) { + init { + require(secret.isNotEmpty()) { "remember me token secret must not be empty" } + require(!maxAge.isNegative && !maxAge.isZero) { "remember me maxAge must be positive" } + } + + private val secretKey = SecretKeySpec(secret, REMEMBER_ME_MAC_ALGORITHM) + + /** Checks the mac and the age. The caller still has to match [RememberMeToken.epoch]. */ + fun verify(bytes: ByteArray): RememberMeToken? { + if (bytes.size != REMEMBER_ME_TOKEN_SIZE) return null + if (!isAuthenticRememberMe(bytes, secretKey)) return null + val buf = ByteBuffer.wrap(bytes) + val userId = buf.int + val epoch = buf.int + val issuedAt = Instant.ofEpochSecond(buf.long) + val now = clock.instant() + if (issuedAt.isAfter(now.plus(REMEMBER_ME_SKEW_LEEWAY))) return null + if (issuedAt.isBefore(now.minus(maxAge))) return null + return RememberMeToken(userId, epoch, issuedAt, bytes) + } +} + +private const val REMEMBER_ME_MAC_ALGORITHM = "HmacSHA256" +private const val REMEMBER_ME_PREFIX_SIZE = 16 +private const val REMEMBER_ME_MAC_SIZE = 16 +private const val REMEMBER_ME_TOKEN_SIZE = REMEMBER_ME_PREFIX_SIZE + REMEMBER_ME_MAC_SIZE + +private val REMEMBER_ME_SKEW_LEEWAY: Duration = Duration.ofSeconds(30) + +private fun rememberMeTagOf(token: ByteArray, key: SecretKeySpec): ByteArray { + val mac = Mac.getInstance(REMEMBER_ME_MAC_ALGORITHM) + mac.init(key) + mac.update(token, 0, REMEMBER_ME_PREFIX_SIZE) + return mac.doFinal().copyOf(REMEMBER_ME_MAC_SIZE) +} + +private fun signRememberMe(token: ByteArray, key: SecretKeySpec) { + System.arraycopy( + rememberMeTagOf(token, key), 0, token, REMEMBER_ME_PREFIX_SIZE, REMEMBER_ME_MAC_SIZE) +} + +private fun isAuthenticRememberMe(token: ByteArray, key: SecretKeySpec): Boolean = + MessageDigest.isEqual( + rememberMeTagOf(token, key), + token.copyOfRange(REMEMBER_ME_PREFIX_SIZE, REMEMBER_ME_TOKEN_SIZE)) diff --git a/common/src/main/kotlin/de/fiereu/openmmo/common/auth/SessionToken.kt b/common/src/main/kotlin/de/fiereu/openmmo/common/auth/SessionToken.kt index 1a7d4ef..f21b65b 100644 --- a/common/src/main/kotlin/de/fiereu/openmmo/common/auth/SessionToken.kt +++ b/common/src/main/kotlin/de/fiereu/openmmo/common/auth/SessionToken.kt @@ -3,6 +3,7 @@ package de.fiereu.openmmo.common.auth import java.nio.ByteBuffer import java.security.MessageDigest import java.time.Clock +import java.time.Duration import java.time.Instant import javax.crypto.Mac import javax.crypto.spec.SecretKeySpec @@ -32,28 +33,42 @@ class SessionTokenIssuer(secret: ByteArray, private val clock: Clock = Clock.sys fun issue(userId: Long): SessionToken { val issuedAt = clock.instant() - val bytes = build(userId, issuedAt, secretKey) + val bytes = ByteArray(TOKEN_SIZE) + ByteBuffer.wrap(bytes, 0, PREFIX_SIZE).putLong(userId).putLong(issuedAt.epochSecond) + sign(bytes, secretKey) return SessionToken(userId, issuedAt, bytes) } } -class SessionTokenVerifier(secret: ByteArray) { +class SessionTokenVerifier( + secret: ByteArray, + private val maxAge: Duration = DEFAULT_MAX_AGE, + private val clock: Clock = Clock.systemUTC(), +) { init { require(secret.isNotEmpty()) { "session token secret must not be empty" } + require(!maxAge.isNegative && !maxAge.isZero) { "session token maxAge must be positive" } } private val secretKey = SecretKeySpec(secret, MAC_ALGORITHM) + // Reads the fields only once the mac says they are ours, so a forged timestamp cannot reach + // Instant.ofEpochSecond, which throws on an out of range value. fun verify(bytes: ByteArray): SessionToken? { if (bytes.size != TOKEN_SIZE) return null + if (!isAuthentic(bytes, secretKey)) return null val buf = ByteBuffer.wrap(bytes) val userId = buf.long - val epochSeconds = buf.long - val issuedAt = Instant.ofEpochSecond(epochSeconds) - val expected = build(userId, issuedAt, secretKey) - if (!MessageDigest.isEqual(bytes, expected)) return null + val issuedAt = Instant.ofEpochSecond(buf.long) + if (isExpired(issuedAt)) return null return SessionToken(userId, issuedAt, bytes) } + + private fun isExpired(issuedAt: Instant): Boolean { + val now = clock.instant() + if (issuedAt.isAfter(now.plus(CLOCK_SKEW_LEEWAY))) return true + return issuedAt.isBefore(now.minus(maxAge)) + } } private const val MAC_ALGORITHM = "HmacSHA256" @@ -61,15 +76,22 @@ private const val PREFIX_SIZE = 16 private const val MAC_SIZE = 16 private const val TOKEN_SIZE = PREFIX_SIZE + MAC_SIZE -private fun build(userId: Long, issuedAt: Instant, key: SecretKeySpec): ByteArray { - val out = ByteArray(TOKEN_SIZE) - val prefix = ByteBuffer.wrap(out, 0, PREFIX_SIZE) - prefix.putLong(userId) - prefix.putLong(issuedAt.epochSecond) +private val DEFAULT_MAX_AGE: Duration = Duration.ofMinutes(5) + +// Tolerates drift between the two servers' clocks. A token dated further ahead than this would +// outlive maxAge by the difference. +private val CLOCK_SKEW_LEEWAY: Duration = Duration.ofSeconds(30) + +private fun tagOf(token: ByteArray, key: SecretKeySpec): ByteArray { val mac = Mac.getInstance(MAC_ALGORITHM) mac.init(key) - mac.update(out, 0, PREFIX_SIZE) - val tag = mac.doFinal() - System.arraycopy(tag, 0, out, PREFIX_SIZE, MAC_SIZE) - return out + mac.update(token, 0, PREFIX_SIZE) + return mac.doFinal().copyOf(MAC_SIZE) } + +private fun sign(token: ByteArray, key: SecretKeySpec) { + System.arraycopy(tagOf(token, key), 0, token, PREFIX_SIZE, MAC_SIZE) +} + +private fun isAuthentic(token: ByteArray, key: SecretKeySpec): Boolean = + MessageDigest.isEqual(tagOf(token, key), token.copyOfRange(PREFIX_SIZE, TOKEN_SIZE)) diff --git a/common/src/test/kotlin/de/fiereu/openmmo/common/auth/RememberMeTokenTest.kt b/common/src/test/kotlin/de/fiereu/openmmo/common/auth/RememberMeTokenTest.kt new file mode 100644 index 0000000..5c78f99 --- /dev/null +++ b/common/src/test/kotlin/de/fiereu/openmmo/common/auth/RememberMeTokenTest.kt @@ -0,0 +1,85 @@ +package de.fiereu.openmmo.common.auth + +import io.kotest.assertions.throwables.shouldThrow +import io.kotest.core.spec.style.FunSpec +import io.kotest.matchers.nulls.shouldNotBeNull +import io.kotest.matchers.shouldBe +import java.time.Clock +import java.time.Duration +import java.time.Instant +import java.time.ZoneOffset + +class RememberMeTokenTest : + FunSpec({ + val secret = ByteArray(32) { it.toByte() } + val issuedAt = Instant.ofEpochSecond(1_700_000_000) + val at = { i: Instant -> Clock.fixed(i, ZoneOffset.UTC) } + val thirtyDays = Duration.ofDays(30) + + test("a token round-trips its user, epoch and issue time") { + val token = RememberMeTokenIssuer(secret, at(issuedAt)).issue(userId = 42, epoch = 7) + + val verified = RememberMeTokenVerifier(secret, thirtyDays, at(issuedAt)).verify(token.bytes) + + verified.shouldNotBeNull() + verified.userId shouldBe 42 + verified.epoch shouldBe 7 + verified.issuedAt shouldBe issuedAt + } + + test("the token is the 32 bytes the client stores") { + RememberMeTokenIssuer(secret, at(issuedAt)).issue(1, 0).bytes.size shouldBe 32 + } + + test("tampered bytes fail verification") { + val token = RememberMeTokenIssuer(secret, at(issuedAt)).issue(1, 0) + val mutated = token.bytes.copyOf() + mutated[0] = (mutated[0] + 1).toByte() + + RememberMeTokenVerifier(secret, thirtyDays, at(issuedAt)).verify(mutated) shouldBe null + } + + test("a different secret fails verification") { + val token = RememberMeTokenIssuer(secret, at(issuedAt)).issue(1, 0) + val other = ByteArray(32) { (it + 1).toByte() } + + RememberMeTokenVerifier(other, thirtyDays, at(issuedAt)).verify(token.bytes) shouldBe null + } + + test("the epoch is covered by the mac, so it cannot be edited in place") { + val token = RememberMeTokenIssuer(secret, at(issuedAt)).issue(userId = 42, epoch = 7) + val bumped = token.bytes.copyOf() + // The epoch is the second int of the prefix. + bumped[7] = (bumped[7] + 1).toByte() + + RememberMeTokenVerifier(secret, thirtyDays, at(issuedAt)).verify(bumped) shouldBe null + } + + test("a token is accepted right up to the idle window and rejected past it") { + val token = RememberMeTokenIssuer(secret, at(issuedAt)).issue(1, 0) + val atLimit = at(issuedAt.plus(thirtyDays)) + val pastLimit = at(issuedAt.plus(thirtyDays).plusSeconds(1)) + + RememberMeTokenVerifier(secret, thirtyDays, atLimit).verify(token.bytes).shouldNotBeNull() + RememberMeTokenVerifier(secret, thirtyDays, pastLimit).verify(token.bytes) shouldBe null + } + + test("a token dated beyond the skew leeway is rejected") { + val ahead = RememberMeTokenIssuer(secret, at(issuedAt.plusSeconds(31))).issue(1, 0) + + RememberMeTokenVerifier(secret, thirtyDays, at(issuedAt)).verify(ahead.bytes) shouldBe null + } + + test("an unauthentic token with an out of range timestamp is rejected, not thrown") { + val bytes = ByteArray(32) + java.nio.ByteBuffer.wrap(bytes).putInt(1).putInt(0).putLong(Long.MAX_VALUE) + + RememberMeTokenVerifier(secret, thirtyDays, at(issuedAt)).verify(bytes) shouldBe null + } + + test("empty secret and non-positive max age are rejected") { + shouldThrow { RememberMeTokenIssuer(ByteArray(0)) } + shouldThrow { RememberMeTokenVerifier(ByteArray(0), thirtyDays) } + shouldThrow { RememberMeTokenVerifier(secret, Duration.ZERO) } + } + }) diff --git a/common/src/test/kotlin/de/fiereu/openmmo/common/auth/SessionTokenTest.kt b/common/src/test/kotlin/de/fiereu/openmmo/common/auth/SessionTokenTest.kt index ca33401..3f39713 100644 --- a/common/src/test/kotlin/de/fiereu/openmmo/common/auth/SessionTokenTest.kt +++ b/common/src/test/kotlin/de/fiereu/openmmo/common/auth/SessionTokenTest.kt @@ -5,6 +5,7 @@ import io.kotest.core.spec.style.FunSpec import io.kotest.matchers.nulls.shouldNotBeNull import io.kotest.matchers.shouldBe import java.time.Clock +import java.time.Duration import java.time.Instant import java.time.ZoneOffset @@ -16,7 +17,7 @@ class SessionTokenTest : val fixed = Clock.fixed(Instant.ofEpochSecond(1_700_000_000), ZoneOffset.UTC) val issuer = SessionTokenIssuer(secret, fixed) val token = issuer.issue(userId = 42L) - val verified = SessionTokenVerifier(secret).verify(token.bytes) + val verified = SessionTokenVerifier(secret, clock = fixed).verify(token.bytes) verified.shouldNotBeNull() verified.userId shouldBe 42L verified.issuedAt shouldBe Instant.ofEpochSecond(1_700_000_000) @@ -45,4 +46,83 @@ class SessionTokenTest : shouldThrow { SessionTokenIssuer(ByteArray(0)) } shouldThrow { SessionTokenVerifier(ByteArray(0)) } } + + test("token is accepted right up to its max age") { + val issuedAt = Instant.ofEpochSecond(1_700_000_000) + val token = SessionTokenIssuer(secret, Clock.fixed(issuedAt, ZoneOffset.UTC)).issue(7L) + val atLimit = Clock.fixed(issuedAt.plus(Duration.ofMinutes(5)), ZoneOffset.UTC) + + val verified = + SessionTokenVerifier(secret, Duration.ofMinutes(5), atLimit).verify(token.bytes) + + verified.shouldNotBeNull() + verified.userId shouldBe 7L + } + + test("token past its max age is rejected") { + val issuedAt = Instant.ofEpochSecond(1_700_000_000) + val token = SessionTokenIssuer(secret, Clock.fixed(issuedAt, ZoneOffset.UTC)).issue(7L) + val tooLate = Clock.fixed(issuedAt.plusSeconds(301), ZoneOffset.UTC) + + SessionTokenVerifier(secret, Duration.ofMinutes(5), tooLate).verify(token.bytes) shouldBe + null + } + + test("max age is configurable independently of the default") { + val issuedAt = Instant.ofEpochSecond(1_700_000_000) + val token = SessionTokenIssuer(secret, Clock.fixed(issuedAt, ZoneOffset.UTC)).issue(7L) + val later = Clock.fixed(issuedAt.plusSeconds(60), ZoneOffset.UTC) + + SessionTokenVerifier(secret, Duration.ofSeconds(30), later).verify(token.bytes) shouldBe + null + SessionTokenVerifier(secret, Duration.ofHours(1), later) + .verify(token.bytes) + .shouldNotBeNull() + } + + test("token dated beyond the skew leeway is rejected") { + val now = Instant.ofEpochSecond(1_700_000_000) + val future = Clock.fixed(now.plusSeconds(120), ZoneOffset.UTC) + val token = SessionTokenIssuer(secret, future).issue(7L) + + SessionTokenVerifier(secret, Duration.ofMinutes(5), Clock.fixed(now, ZoneOffset.UTC)) + .verify(token.bytes) shouldBe null + } + + test("token inside the skew leeway is accepted") { + val now = Instant.ofEpochSecond(1_700_000_000) + val slightlyAhead = Clock.fixed(now.plusSeconds(10), ZoneOffset.UTC) + val token = SessionTokenIssuer(secret, slightlyAhead).issue(7L) + + SessionTokenVerifier(secret, Duration.ofMinutes(5), Clock.fixed(now, ZoneOffset.UTC)) + .verify(token.bytes) + .shouldNotBeNull() + } + + test("an unauthentic token with an out of range timestamp is rejected, not thrown") { + val bytes = ByteArray(32) + java.nio.ByteBuffer.wrap(bytes).putLong(1L).putLong(Long.MAX_VALUE) + + SessionTokenVerifier(secret).verify(bytes) shouldBe null + } + + test("the skew leeway is thirty seconds") { + val now = Instant.ofEpochSecond(1_700_000_000) + val verifier = + SessionTokenVerifier(secret, Duration.ofMinutes(5), Clock.fixed(now, ZoneOffset.UTC)) + fun issuedAhead(seconds: Long) = + SessionTokenIssuer(secret, Clock.fixed(now.plusSeconds(seconds), ZoneOffset.UTC)) + .issue(7L) + .bytes + + verifier.verify(issuedAhead(30)).shouldNotBeNull() + verifier.verify(issuedAhead(31)) shouldBe null + } + + test("non-positive max age rejected") { + shouldThrow { SessionTokenVerifier(secret, Duration.ZERO) } + shouldThrow { + SessionTokenVerifier(secret, Duration.ofMinutes(-1)) + } + } }) diff --git a/server.game/build.gradle.kts b/server.game/build.gradle.kts index 6894028..90861d4 100644 --- a/server.game/build.gradle.kts +++ b/server.game/build.gradle.kts @@ -35,6 +35,7 @@ dependencies { tasks.named("run") { listOf( "OPENMMO_SESSION_SECRET", + "OPENMMO_SESSION_TOKEN_MAX_AGE", "GAME_DB_HOST", "GAME_DB_PORT", "GAME_DB_NAME", diff --git a/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/config/ConfigLoader.kt b/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/config/ConfigLoader.kt index 961350f..9265ec6 100644 --- a/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/config/ConfigLoader.kt +++ b/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/config/ConfigLoader.kt @@ -11,6 +11,10 @@ object ConfigLoader { val config = ConfigFactory.load() val secret = config.getString("server.sessionSecret") require(secret.isNotEmpty()) { "server.sessionSecret must not be empty" } + val tokenMaxAge = config.getDuration("server.sessionTokenMaxAge") + require(!tokenMaxAge.isNegative && !tokenMaxAge.isZero) { + "server.sessionTokenMaxAge must be positive" + } return GameServerConfig( host = config.getString("server.host"), port = config.getInt("server.port"), @@ -19,6 +23,7 @@ object ConfigLoader { rootKey = config.stringOrNull("server.rootKey"), rootKeyFile = config.stringOrNull("server.rootKeyFile"), sessionSecret = secret.toByteArray(Charsets.UTF_8), + sessionTokenMaxAge = tokenMaxAge, db = DbConfig( host = config.getString("db.host"), diff --git a/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/config/GameServerConfig.kt b/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/config/GameServerConfig.kt index a3894e7..fe021c8 100644 --- a/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/config/GameServerConfig.kt +++ b/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/config/GameServerConfig.kt @@ -1,11 +1,14 @@ package de.fiereu.openmmo.server.game.config +import java.time.Duration + data class GameServerConfig( val host: String, val port: Int, val checksumSize: Int, val rootKeyResource: String, val sessionSecret: ByteArray, + val sessionTokenMaxAge: Duration = Duration.ofMinutes(5), val db: DbConfig = DbConfig(), val rootKey: String? = null, val rootKeyFile: String? = null, @@ -19,6 +22,7 @@ data class GameServerConfig( rootKey == other.rootKey && rootKeyFile == other.rootKeyFile && sessionSecret.contentEquals(other.sessionSecret) && + sessionTokenMaxAge == other.sessionTokenMaxAge && db == other.db override fun hashCode(): Int { @@ -29,6 +33,7 @@ data class GameServerConfig( h = h * 31 + rootKey.hashCode() h = h * 31 + rootKeyFile.hashCode() h = h * 31 + sessionSecret.contentHashCode() + h = h * 31 + sessionTokenMaxAge.hashCode() h = h * 31 + db.hashCode() return h } diff --git a/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/di/GameServerModule.kt b/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/di/GameServerModule.kt index cd7cc6a..b426fdb 100644 --- a/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/di/GameServerModule.kt +++ b/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/di/GameServerModule.kt @@ -40,7 +40,7 @@ object GameServerModule { @Provides @Singleton fun tokenVerifier(config: GameServerConfig): SessionTokenVerifier = - SessionTokenVerifier(config.sessionSecret) + SessionTokenVerifier(config.sessionSecret, config.sessionTokenMaxAge) @Provides @Singleton diff --git a/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/services/LoginService.kt b/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/services/LoginService.kt index f657864..57a1512 100644 --- a/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/services/LoginService.kt +++ b/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/services/LoginService.kt @@ -3,6 +3,7 @@ package de.fiereu.openmmo.server.game.services import de.fiereu.network.PacketEvent import de.fiereu.network.SessionContext import de.fiereu.openmmo.common.CharacterInfo +import de.fiereu.openmmo.common.auth.SessionTokenVerifier import de.fiereu.openmmo.common.enums.CharacterGender import de.fiereu.openmmo.common.enums.ChatType import de.fiereu.openmmo.common.enums.Language @@ -75,29 +76,51 @@ constructor( private val characterStore: CharacterStore, private val presenceService: PresenceService, private val mapScriptService: MapScriptService, + private val tokenVerifier: SessionTokenVerifier, ) { fun onJoinGame(event: PacketEvent) { val ctx = event.session - val join = event.packet - log.info { "Player joined the game." } + val authData = event.packet.authData - val authData = join.authData - var userId = 0 - if (authData is NewAuthData) { - userId = authData.userId - log.info { "User $userId joined with session key (${authData.sessionKey.size} bytes)" } + if (authData !is NewAuthData) { + log.warn { "Rejected join with unsupported auth data ${authData::class.simpleName}" } + rejectJoin(ctx) + return } - if (userId > 0) { - ctx.attributes[PLAYER_STATE] = PlayerState(userId = userId) - sessionRegistry.register(ctx) - log.info { "Session created for user $userId" } + val token = tokenVerifier.verify(authData.sessionKey) + if (token == null) { + log.warn { + "Rejected join for claimed userId=${authData.userId}, " + + "session token invalid or expired (${authData.sessionKey.size} bytes)" + } + rejectJoin(ctx) + return } + // The claim in the packet is the client's, the token is the login server's. Compare before + // narrowing, so a value that does not fit an Int cannot match by truncation. + if (token.userId != authData.userId.toLong() || token.userId <= 0) { + log.warn { "Join claimed userId=${authData.userId} but its token says ${token.userId}" } + rejectJoin(ctx) + return + } + val userId = token.userId.toInt() + + ctx.attributes[PLAYER_STATE] = PlayerState(userId = userId) + sessionRegistry.register(ctx) + log.info { "Session created for user $userId" } + ctx.send(JoinResponsePacket.acceptNow(playtime = 1337, rewardPoints = 420, balance = 187)) } + // Closing is what keeps a refused peer from going on to send packets the handlers would + // otherwise answer without a PlayerState. Close only once the refusal itself has been written. + private fun rejectJoin(ctx: SessionContext) { + ctx.send(JoinResponsePacket.reject()).addListener { ctx.close { "join rejected" } } + } + suspend fun onCreateCharacter(event: PacketEvent) { val ctx = event.session val state = ctx.attributes[PLAYER_STATE] @@ -173,14 +196,18 @@ constructor( suspend fun onCharacterSelected(event: PacketEvent) { val ctx = event.session val charId = event.packet.characterId + val state = ctx.attributes[PLAYER_STATE] + if (state == null) { + log.warn { "No session for channel" } + return + } val stored = characterStore.getOrLoadCharacter(charId) if (stored == null) { log.warn { "Character $charId not found" } return } - val state = ctx.attributes[PLAYER_STATE] - if (state == null) { - log.warn { "No session for channel" } + if (stored.info.userId != state.userId) { + log.warn { "User ${state.userId} tried to select character $charId owned by another account" } return } diff --git a/server.game/src/main/resources/application.conf b/server.game/src/main/resources/application.conf index 129d055..ff16e70 100644 --- a/server.game/src/main/resources/application.conf +++ b/server.game/src/main/resources/application.conf @@ -7,6 +7,8 @@ server { rootKeyFile = ${?OPENMMO_GAME_PRIVATE_KEY_FILE} sessionSecret = "dev-only-secret-do-not-use-in-production" sessionSecret = ${?OPENMMO_SESSION_SECRET} + sessionTokenMaxAge = 5m + sessionTokenMaxAge = ${?OPENMMO_SESSION_TOKEN_MAX_AGE} } db { diff --git a/server.login/src/main/kotlin/de/fiereu/openmmo/server/login/auth/JooqUserStore.kt b/server.login/src/main/kotlin/de/fiereu/openmmo/server/login/auth/JooqUserStore.kt index 2b59c90..80e676e 100644 --- a/server.login/src/main/kotlin/de/fiereu/openmmo/server/login/auth/JooqUserStore.kt +++ b/server.login/src/main/kotlin/de/fiereu/openmmo/server/login/auth/JooqUserStore.kt @@ -23,7 +23,14 @@ constructor( if (user == null || user.passwordHash != password) { UserService.AuthResult(LoginState.INVALID_PASSWORD) } else { - UserService.AuthResult(LoginState.AUTHED, user.id) + UserService.AuthResult(LoginState.AUTHED, user.id, user.tokenEpoch ?: 0) + } + } + + override suspend fun findForToken(userId: Int): UserService.TokenUser? = + withContext(dispatcher) { + dsl.selectFrom(USERS).where(USERS.ID.eq(userId)).fetchOne()?.let { + UserService.TokenUser(it.id!!, it.username, it.displayName, it.tokenEpoch ?: 0) } } diff --git a/server.login/src/main/kotlin/de/fiereu/openmmo/server/login/auth/UserService.kt b/server.login/src/main/kotlin/de/fiereu/openmmo/server/login/auth/UserService.kt index cd5398d..5aff717 100644 --- a/server.login/src/main/kotlin/de/fiereu/openmmo/server/login/auth/UserService.kt +++ b/server.login/src/main/kotlin/de/fiereu/openmmo/server/login/auth/UserService.kt @@ -9,11 +9,21 @@ import javax.inject.Inject import javax.inject.Singleton interface UserService { - data class AuthResult(val state: LoginState, val userId: Int? = null) + data class AuthResult(val state: LoginState, val userId: Int? = null, val tokenEpoch: Int = 0) + + /** Identity a remember me token resolves to, with the epoch that token has to still match. */ + data class TokenUser( + val id: Int, + val username: String, + val displayName: String, + val tokenEpoch: Int, + ) suspend fun authenticate(username: String, password: String): AuthResult suspend fun getUserId(username: String): Int? + + suspend fun findForToken(userId: Int): TokenUser? } @Suppress("kotlin:S4790") @@ -23,7 +33,12 @@ internal fun sha1Hex(value: String): String = @Singleton class InMemoryUserStore @Inject constructor() : UserService { - private data class UserInfo(val id: Int, val passwordHash: String, val username: String) + private data class UserInfo( + val id: Int, + val passwordHash: String, + val username: String, + val tokenEpoch: Int = 0, + ) private val users = ConcurrentHashMap() private val nextId = AtomicInteger(1) @@ -45,8 +60,15 @@ class InMemoryUserStore @Inject constructor() : UserService { if (user.passwordHash != password) { return UserService.AuthResult(LoginState.INVALID_PASSWORD) } - return UserService.AuthResult(LoginState.AUTHED, user.id) + return UserService.AuthResult(LoginState.AUTHED, user.id, user.tokenEpoch) } override suspend fun getUserId(username: String): Int? = users[username.lowercase()]?.id + + override suspend fun findForToken(userId: Int): UserService.TokenUser? = + users.values + .firstOrNull { it.id == userId } + ?.let { + UserService.TokenUser(it.id, it.username.lowercase(), it.username, it.tokenEpoch) + } } diff --git a/server.login/src/main/kotlin/de/fiereu/openmmo/server/login/config/ConfigLoader.kt b/server.login/src/main/kotlin/de/fiereu/openmmo/server/login/config/ConfigLoader.kt index 9087bf9..fd30cb4 100644 --- a/server.login/src/main/kotlin/de/fiereu/openmmo/server/login/config/ConfigLoader.kt +++ b/server.login/src/main/kotlin/de/fiereu/openmmo/server/login/config/ConfigLoader.kt @@ -11,6 +11,10 @@ object ConfigLoader { val config = ConfigFactory.load() val secret = config.getString("server.sessionSecret") require(secret.isNotEmpty()) { "server.sessionSecret must not be empty" } + val rememberMeMaxAge = config.getDuration("server.rememberMeMaxAge") + require(!rememberMeMaxAge.isNegative && !rememberMeMaxAge.isZero) { + "server.rememberMeMaxAge must be positive" + } return LoginServerConfig( host = config.getString("server.host"), port = config.getInt("server.port"), @@ -19,6 +23,7 @@ object ConfigLoader { rootKey = config.stringOrNull("server.rootKey"), rootKeyFile = config.stringOrNull("server.rootKeyFile"), sessionSecret = secret.toByteArray(Charsets.UTF_8), + rememberMeMaxAge = rememberMeMaxAge, db = DbConfig( host = config.getString("db.host"), diff --git a/server.login/src/main/kotlin/de/fiereu/openmmo/server/login/config/LoginServerConfig.kt b/server.login/src/main/kotlin/de/fiereu/openmmo/server/login/config/LoginServerConfig.kt index 7a25fb1..62fae5b 100644 --- a/server.login/src/main/kotlin/de/fiereu/openmmo/server/login/config/LoginServerConfig.kt +++ b/server.login/src/main/kotlin/de/fiereu/openmmo/server/login/config/LoginServerConfig.kt @@ -1,11 +1,14 @@ package de.fiereu.openmmo.server.login.config +import java.time.Duration + data class LoginServerConfig( val host: String, val port: Int, val checksumSize: Int, val rootKeyResource: String, val sessionSecret: ByteArray, + val rememberMeMaxAge: Duration = Duration.ofDays(30), val db: DbConfig = DbConfig(), val rootKey: String? = null, val rootKeyFile: String? = null, @@ -19,6 +22,7 @@ data class LoginServerConfig( rootKey == other.rootKey && rootKeyFile == other.rootKeyFile && sessionSecret.contentEquals(other.sessionSecret) && + rememberMeMaxAge == other.rememberMeMaxAge && db == other.db override fun hashCode(): Int { @@ -29,6 +33,7 @@ data class LoginServerConfig( h = h * 31 + rootKey.hashCode() h = h * 31 + rootKeyFile.hashCode() h = h * 31 + sessionSecret.contentHashCode() + h = h * 31 + rememberMeMaxAge.hashCode() h = h * 31 + db.hashCode() return h } diff --git a/server.login/src/main/kotlin/de/fiereu/openmmo/server/login/di/LoginServerModule.kt b/server.login/src/main/kotlin/de/fiereu/openmmo/server/login/di/LoginServerModule.kt index f4ec777..abac563 100644 --- a/server.login/src/main/kotlin/de/fiereu/openmmo/server/login/di/LoginServerModule.kt +++ b/server.login/src/main/kotlin/de/fiereu/openmmo/server/login/di/LoginServerModule.kt @@ -5,6 +5,8 @@ import com.zaxxer.hikari.HikariDataSource import dagger.Binds import dagger.Module import dagger.Provides +import de.fiereu.openmmo.common.auth.RememberMeTokenIssuer +import de.fiereu.openmmo.common.auth.RememberMeTokenVerifier import de.fiereu.openmmo.common.auth.SessionTokenIssuer import de.fiereu.openmmo.common.io.PemKeyLoader import de.fiereu.openmmo.common.io.pemStream @@ -43,6 +45,16 @@ abstract class LoginServerModule { fun tokenIssuer(config: LoginServerConfig): SessionTokenIssuer = SessionTokenIssuer(config.sessionSecret) + @Provides + @Singleton + fun rememberMeIssuer(config: LoginServerConfig): RememberMeTokenIssuer = + RememberMeTokenIssuer(config.sessionSecret) + + @Provides + @Singleton + fun rememberMeVerifier(config: LoginServerConfig): RememberMeTokenVerifier = + RememberMeTokenVerifier(config.sessionSecret, config.rememberMeMaxAge) + @Provides @Singleton @Named("boss") diff --git a/server.login/src/main/kotlin/de/fiereu/openmmo/server/login/handler/LoginAppHandler.kt b/server.login/src/main/kotlin/de/fiereu/openmmo/server/login/handler/LoginAppHandler.kt index d045c88..deec05b 100644 --- a/server.login/src/main/kotlin/de/fiereu/openmmo/server/login/handler/LoginAppHandler.kt +++ b/server.login/src/main/kotlin/de/fiereu/openmmo/server/login/handler/LoginAppHandler.kt @@ -3,6 +3,8 @@ package de.fiereu.openmmo.server.login.handler import de.fiereu.network.PacketEvent import de.fiereu.network.Side import de.fiereu.network.coroutines.CoroutineProtocolHandler +import de.fiereu.openmmo.common.auth.RememberMeTokenIssuer +import de.fiereu.openmmo.common.auth.RememberMeTokenVerifier import de.fiereu.openmmo.common.auth.SessionTokenIssuer import de.fiereu.openmmo.common.enums.LoginState import de.fiereu.openmmo.net.login.LoginProtocol @@ -14,6 +16,8 @@ import de.fiereu.openmmo.net.login.packets.LoginRequestPacket import de.fiereu.openmmo.net.login.packets.LoginResponsePacket import de.fiereu.openmmo.net.login.packets.PasswordLogin import de.fiereu.openmmo.net.login.packets.RequestGameServerListPacket +import de.fiereu.openmmo.net.login.packets.SentCredentialsPacket +import de.fiereu.openmmo.net.login.packets.TokenLogin import de.fiereu.openmmo.server.login.auth.UserService import de.fiereu.openmmo.server.login.catalog.GameServerCatalog import de.fiereu.openmmo.server.login.session.AUTHED_USER_ID @@ -29,6 +33,8 @@ constructor( private val users: UserService, private val catalog: GameServerCatalog, private val tokenIssuer: SessionTokenIssuer, + private val rememberMeIssuer: RememberMeTokenIssuer, + private val rememberMeVerifier: RememberMeTokenVerifier, scope: CoroutineScope, ) : CoroutineProtocolHandler(LoginProtocol, Side.SERVER, scope) { @@ -38,22 +44,60 @@ constructor( onSuspend { event -> onJoinGameServer(event) } } - private suspend fun onLoginRequest(event: PacketEvent) { - val packet = event.packet - val method = packet.method - if (method !is PasswordLogin) { - log.warn { "Unsupported login method ${method::class.simpleName} for ${packet.username}" } - event.session.send(LoginResponsePacket(LoginState.INVALID_PASSWORD)) + internal suspend fun onLoginRequest(event: PacketEvent) { + when (val method = event.packet.method) { + is PasswordLogin -> onPasswordLogin(event, method) + is TokenLogin -> onTokenLogin(event, method) + } + } + + private suspend fun onPasswordLogin( + event: PacketEvent, + method: PasswordLogin, + ) { + val username = event.packet.username + val result = users.authenticate(username, method.password) + log.info { "Login attempt for $username: ${result.state}" } + if (result.state != LoginState.AUTHED || result.userId == null) { + event.session.send(LoginResponsePacket(result.state)) return } - val result = users.authenticate(packet.username, method.password) - log.info { "Login attempt for ${packet.username}: ${result.state}" } - if (result.state == LoginState.AUTHED && result.userId != null) { - event.session.attributes[AUTHED_USER_ID] = result.userId + event.session.attributes[AUTHED_USER_ID] = result.userId + if (method.stayLoggedIn) { + sendRememberMeToken(event, result.userId, result.tokenEpoch, username) } event.session.send(LoginResponsePacket(result.state)) } + private suspend fun onTokenLogin(event: PacketEvent, method: TokenLogin) { + val username = event.packet.username + val token = rememberMeVerifier.verify(method.token) + val user = token?.let { users.findForToken(it.userId) } + if (token == null || + user == null || + user.tokenEpoch != token.epoch || + !user.username.equals(username, ignoreCase = true)) { + log.warn { "Rejected token login for $username" } + event.session.send(LoginResponsePacket(LoginState.INVALID_SAVED_CREDENTIALS)) + return + } + log.info { "Token login for ${user.displayName}: AUTHED" } + event.session.attributes[AUTHED_USER_ID] = user.id + // Sliding expiry, so a player who keeps logging in never has to type a password again. + sendRememberMeToken(event, user.id, user.tokenEpoch, user.displayName) + event.session.send(LoginResponsePacket(LoginState.AUTHED)) + } + + private fun sendRememberMeToken( + event: PacketEvent, + userId: Int, + epoch: Int, + displayName: String, + ) { + val issued = rememberMeIssuer.issue(userId, epoch) + event.session.send(SentCredentialsPacket(displayName, issued.bytes)) + } + private fun onServerListRequest(event: PacketEvent) { event.session.send(GameServerListPacket(catalog.list())) } diff --git a/server.login/src/main/resources/application.conf b/server.login/src/main/resources/application.conf index 01b05f7..254cd1f 100644 --- a/server.login/src/main/resources/application.conf +++ b/server.login/src/main/resources/application.conf @@ -7,6 +7,9 @@ server { rootKeyFile = ${?OPENMMO_GAME_PRIVATE_KEY_FILE} sessionSecret = "dev-only-secret-do-not-use-in-production" sessionSecret = ${?OPENMMO_SESSION_SECRET} + # Idle window for a remember me token. Every token login issues a fresh one. + rememberMeMaxAge = 30d + rememberMeMaxAge = ${?OPENMMO_REMEMBER_ME_MAX_AGE} } db { diff --git a/server.login/src/main/resources/db/migration/V2__add_user_token_epoch.sql b/server.login/src/main/resources/db/migration/V2__add_user_token_epoch.sql new file mode 100644 index 0000000..1b7ac44 --- /dev/null +++ b/server.login/src/main/resources/db/migration/V2__add_user_token_epoch.sql @@ -0,0 +1,3 @@ +-- Raising a user's epoch invalidates every remember me token already issued to them. +ALTER TABLE users + ADD COLUMN token_epoch INT NOT NULL DEFAULT 0; diff --git a/server.login/src/test/kotlin/de/fiereu/openmmo/server/login/handler/LoginAppHandlerTest.kt b/server.login/src/test/kotlin/de/fiereu/openmmo/server/login/handler/LoginAppHandlerTest.kt index 2dcbd39..bd5d714 100644 --- a/server.login/src/test/kotlin/de/fiereu/openmmo/server/login/handler/LoginAppHandlerTest.kt +++ b/server.login/src/test/kotlin/de/fiereu/openmmo/server/login/handler/LoginAppHandlerTest.kt @@ -1,15 +1,124 @@ package de.fiereu.openmmo.server.login.handler +import de.fiereu.network.PacketEvent +import de.fiereu.network.SessionAttribute +import de.fiereu.network.SessionAttributes +import de.fiereu.network.SessionContext +import de.fiereu.network.SessionPhase +import de.fiereu.network.Side +import de.fiereu.openmmo.common.auth.RememberMeTokenIssuer +import de.fiereu.openmmo.common.auth.RememberMeTokenVerifier +import de.fiereu.openmmo.common.auth.SessionTokenIssuer +import de.fiereu.openmmo.common.enums.Language +import de.fiereu.openmmo.common.enums.LoginState import de.fiereu.openmmo.net.login.packets.JoinGameServerPacket import de.fiereu.openmmo.net.login.packets.LoginRequestPacket +import de.fiereu.openmmo.net.login.packets.LoginResponsePacket +import de.fiereu.openmmo.net.login.packets.PasswordLogin import de.fiereu.openmmo.net.login.packets.RequestGameServerListPacket +import de.fiereu.openmmo.net.login.packets.SentCredentialsPacket +import de.fiereu.openmmo.net.login.packets.TokenLogin +import de.fiereu.openmmo.server.login.auth.InMemoryUserStore +import de.fiereu.openmmo.server.login.auth.sha1Hex +import de.fiereu.openmmo.server.login.catalog.GameServerCatalog import de.fiereu.openmmo.server.login.config.LoginServerConfig import de.fiereu.openmmo.server.login.di.DaggerLoginServerComponent +import de.fiereu.openmmo.server.login.session.AUTHED_USER_ID import io.kotest.core.spec.style.FunSpec +import io.kotest.matchers.nulls.shouldNotBeNull import io.kotest.matchers.shouldBe +import io.netty.channel.ChannelFuture +import io.netty.channel.embedded.EmbeddedChannel +import java.net.SocketAddress +import java.time.Clock +import java.time.Duration +import java.time.Instant +import java.time.ZoneOffset +import java.util.Base64 +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Job +import kotlinx.coroutines.runBlocking + +private class RecordingSession : SessionContext { + val sent = mutableListOf() + private val backing = EmbeddedChannel() + + override val side: Side = Side.SERVER + override val channel = backing + override val remoteAddress: SocketAddress + get() = backing.remoteAddress() ?: java.net.InetSocketAddress(0) + + override val phase: SessionPhase = SessionPhase.ESTABLISHED + override val handshakeCompletedAt: Instant? = Instant.now() + + override val attributes: SessionAttributes = + object : SessionAttributes { + private val map = HashMap, Any>() + + @Suppress("UNCHECKED_CAST") + override fun get(key: SessionAttribute): T? = map[key] as T? + + override fun set(key: SessionAttribute, value: T) { + map[key] = value + } + + @Suppress("UNCHECKED_CAST") + override fun remove(key: SessionAttribute): T? = map.remove(key) as T? + + @Suppress("UNCHECKED_CAST") + override fun getOrPut(key: SessionAttribute, default: () -> T): T = + map.getOrPut(key) { default() } as T + + override fun contains(key: SessionAttribute<*>): Boolean = map.containsKey(key) + } + + override fun send(packet: Any): ChannelFuture { + sent += packet + return backing.newSucceededFuture() + } + + override fun close(reason: () -> String) { + backing.close() + } + + override fun onPhase(phase: SessionPhase, listener: () -> Unit) = listener() +} + +private fun loginRequest( + username: String, + method: de.fiereu.openmmo.net.login.packets.LoginMethod +) = + LoginRequestPacket( + username = username, + manualLogin = true, + hwid = ByteArray(0), + method = method, + language = Language.EN, + clientRevision = 0, + installationRevision = 0, + os = 0u, + hardwareInfoCache = ByteArray(0), + ) class LoginAppHandlerTest : FunSpec({ + val secret = ByteArray(32) { it.toByte() } + + val maxAge: Duration = Duration.ofDays(30) + + fun newHandler( + users: InMemoryUserStore, + clock: Clock = Clock.systemUTC(), + ): LoginAppHandler = + LoginAppHandler( + users = users, + catalog = GameServerCatalog(), + tokenIssuer = SessionTokenIssuer(secret, clock), + rememberMeIssuer = RememberMeTokenIssuer(secret, clock), + rememberMeVerifier = RememberMeTokenVerifier(secret, maxAge, clock), + scope = CoroutineScope(Job()), + ) + test("dagger component constructs the handler with all three packet types registered") { val config = LoginServerConfig( @@ -25,4 +134,123 @@ class LoginAppHandlerTest : handler.isRegistered(RequestGameServerListPacket::class) shouldBe true handler.isRegistered(JoinGameServerPacket::class) shouldBe true } + + test("password login without stay-logged-in sends only the AUTHED response") { + val users = InMemoryUserStore() + users.addUser("test", "test") + val handler = newHandler(users) + val session = RecordingSession() + runBlocking { + handler.onLoginRequest( + PacketEvent(loginRequest("test", PasswordLogin(sha1Hex("test"), false)), session)) + } + session.sent.map { it::class } shouldBe listOf(LoginResponsePacket::class) + (session.sent.single() as LoginResponsePacket).state shouldBe LoginState.AUTHED + } + + test("password login with stay-logged-in sends a token that verifies to the user id") { + val users = InMemoryUserStore() + val userId = users.addUser("stay", "secret") + val handler = newHandler(users) + val session = RecordingSession() + runBlocking { + handler.onLoginRequest( + PacketEvent(loginRequest("stay", PasswordLogin(sha1Hex("secret"), true)), session)) + } + session.sent.map { it::class } shouldBe + listOf(SentCredentialsPacket::class, LoginResponsePacket::class) + val credentials = session.sent[0] as SentCredentialsPacket + credentials.key.isNotBlank() shouldBe true + val tokenBytes = Base64.getDecoder().decode(credentials.key) + tokenBytes.size shouldBe 32 + val decoded = RememberMeTokenVerifier(secret, maxAge).verify(tokenBytes) + decoded.shouldNotBeNull() + decoded.userId shouldBe userId + (session.sent[1] as LoginResponsePacket).state shouldBe LoginState.AUTHED + session.attributes[AUTHED_USER_ID] shouldBe userId + } + + test("token login with a matching token authenticates the user and refreshes the token") { + val users = InMemoryUserStore() + val userId = users.addUser("tokenuser", "secret") + val handler = newHandler(users) + val token = RememberMeTokenIssuer(secret).issue(userId, 0) + val session = RecordingSession() + runBlocking { + handler.onLoginRequest( + PacketEvent(loginRequest("tokenuser", TokenLogin(token.bytes)), session)) + } + session.sent.map { it::class } shouldBe + listOf(SentCredentialsPacket::class, LoginResponsePacket::class) + val refreshed = session.sent[0] as SentCredentialsPacket + val refreshedBytes = Base64.getDecoder().decode(refreshed.key) + RememberMeTokenVerifier(secret, maxAge) + .verify(refreshedBytes) + .shouldNotBeNull() + .userId shouldBe userId + (session.sent[1] as LoginResponsePacket).state shouldBe LoginState.AUTHED + session.attributes[AUTHED_USER_ID] shouldBe userId + } + + test("token login with an expired token is rejected") { + val users = InMemoryUserStore() + val userId = users.addUser("tokenuser", "secret") + val issuedAt = Instant.ofEpochSecond(1_700_000_000) + val token = + RememberMeTokenIssuer(secret, Clock.fixed(issuedAt, ZoneOffset.UTC)).issue(userId, 0) + val laterClock = Clock.fixed(issuedAt.plus(Duration.ofDays(31)), ZoneOffset.UTC) + val handler = newHandler(users, clock = laterClock) + val session = RecordingSession() + runBlocking { + handler.onLoginRequest( + PacketEvent(loginRequest("tokenuser", TokenLogin(token.bytes)), session)) + } + (session.sent.single() as LoginResponsePacket).state shouldBe + LoginState.INVALID_SAVED_CREDENTIALS + session.attributes.contains(AUTHED_USER_ID) shouldBe false + } + + test("token login with invalid bytes is rejected") { + val users = InMemoryUserStore() + users.addUser("tokenuser", "secret") + val handler = newHandler(users) + val session = RecordingSession() + runBlocking { + handler.onLoginRequest( + PacketEvent(loginRequest("tokenuser", TokenLogin(ByteArray(24) { 1 })), session)) + } + (session.sent.single() as LoginResponsePacket).state shouldBe + LoginState.INVALID_SAVED_CREDENTIALS + session.attributes.contains(AUTHED_USER_ID) shouldBe false + } + + test("token login for a username that does not exist is rejected") { + val users = InMemoryUserStore() + val token = RememberMeTokenIssuer(secret).issue(999, 0) + val handler = newHandler(users) + val session = RecordingSession() + runBlocking { + handler.onLoginRequest( + PacketEvent(loginRequest("ghost", TokenLogin(token.bytes)), session)) + } + (session.sent.single() as LoginResponsePacket).state shouldBe + LoginState.INVALID_SAVED_CREDENTIALS + session.attributes.contains(AUTHED_USER_ID) shouldBe false + } + + test("token login for a user id that does not match the username is rejected") { + val users = InMemoryUserStore() + val otherId = users.addUser("other", "secret") + users.addUser("victim", "secret") + val handler = newHandler(users) + val token = RememberMeTokenIssuer(secret).issue(otherId, 0) + val session = RecordingSession() + runBlocking { + handler.onLoginRequest( + PacketEvent(loginRequest("victim", TokenLogin(token.bytes)), session)) + } + (session.sent.single() as LoginResponsePacket).state shouldBe + LoginState.INVALID_SAVED_CREDENTIALS + session.attributes.contains(AUTHED_USER_ID) shouldBe false + } })