feat(login): log in with a saved token instead of storing the password (#120)

This commit is contained in:
Fiereu authored and GitHub committed 2026-08-08 23:35:13 +02:00
1 parent 457f21c17f
commit a1453b8db2
19 files changed
+706 -45

No files matched your search

@@ -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))
@@ -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))
@@ -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<IllegalArgumentException> { RememberMeTokenIssuer(ByteArray(0)) }
shouldThrow<IllegalArgumentException> { RememberMeTokenVerifier(ByteArray(0), thirtyDays) }
shouldThrow<IllegalArgumentException> { RememberMeTokenVerifier(secret, Duration.ZERO) }
}
})
@@ -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<IllegalArgumentException> { SessionTokenIssuer(ByteArray(0)) }
shouldThrow<IllegalArgumentException> { 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<IllegalArgumentException> { SessionTokenVerifier(secret, Duration.ZERO) }
shouldThrow<IllegalArgumentException> {
SessionTokenVerifier(secret, Duration.ofMinutes(-1))
}
}
})