Throttle relay token mints per account (todo 507)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1
2026-11-13 19:13:50 -05:00
co-authored by Claude Opus 5.5
parent ec75ee3f75
commit dd664b1a03
4 changed files with 86 additions and 2 deletions
+16 -2
View File
@@ -26,6 +26,8 @@ struct AuthThrottle {
/// does — but it turns a script into a trickle, which is most of the value
/// for a fraction of the cost of anything else.
let perAddressRegistration: RateLimiter.Limit
/// Relay token mints per account (todo 507).
let perAccountRelayMint: RateLimiter.Limit
static func fromEnvironment() -> AuthThrottle {
let window = Double(Environment.get("ENCLAVE_AUTH_WINDOW_SECONDS").flatMap(Int.init) ?? 300)
@@ -39,7 +41,10 @@ struct AuthThrottle {
return AuthThrottle(
perHandle: .init(attempts: handleAttempts, window: window),
perAddress: .init(attempts: addressAttempts, window: window),
perAddressRegistration: .init(attempts: signupAttempts, window: signupWindow)
perAddressRegistration: .init(attempts: signupAttempts, window: signupWindow),
perAccountRelayMint: RelayMintPolicy.limit(
attempts: Environment.get("ENCLAVE_RELAY_MINTS_PER_ACCOUNT").flatMap(Int.init),
window: Environment.get("ENCLAVE_RELAY_MINT_WINDOW_SECONDS").flatMap(Double.init))
)
}
@@ -59,6 +64,14 @@ struct AuthThrottle {
}
}
/// Consume one relay mint for this account, or throw 429.
func checkRelayMint(subject: String, request: Request) async throws {
let limiter = PostgresRateLimiter(sql: try request.throttleStore, limit: perAccountRelayMint)
guard try await limiter.allow(RelayMintPolicy.key(subject: subject)) else {
throw Abort(.tooManyRequests, reason: "Too many relay tokens requested. Wait a few minutes and try again.")
}
}
/// Consume budget for one attempt, or throw 429.
///
/// Checked before the handle is looked up, so throttling itself cannot be
@@ -104,7 +117,8 @@ struct AuthThrottle {
/// would delete registration attempts that are still inside their hour and
/// hand back exactly the budget this table exists to remember.
func startSweeping(on application: Application) {
let keep = max(perHandle.window, max(perAddress.window, perAddressRegistration.window))
let keep = max(max(perHandle.window, perAccountRelayMint.window),
max(perAddress.window, perAddressRegistration.window))
application.eventLoopGroup.next().scheduleRepeatedTask(
initialDelay: .minutes(5), delay: .minutes(5)
) { _ in
@@ -57,6 +57,8 @@ struct AccountController: RouteCollection {
/// that send a session token straight to a relay keep working.
func relaySession(request: Request) async throws -> RelaySessionResponse {
let session = try await request.jwt.verify(as: EnclaveToken.self)
try await request.application.authThrottle.checkRelayMint(
subject: session.subject.value, request: request)
let input = try request.content.decode(RelaySessionRequest.self)
let audience = input.audience.trimmingCharacters(in: .whitespacesAndNewlines)
guard !audience.isEmpty, audience.count <= 256 else {
@@ -0,0 +1,27 @@
import Foundation
/// The budget for POST /sessions/relay (todo 507).
///
/// A valid session token can ask for a relay token as often as it likes, so
/// without a cap one stolen or scripted session mints thousands of signed
/// tokens a minute and keeps the signer busy. The limit is counted per account
/// (the session's `sub`), so new sessions for the same account share it.
///
/// A client asks for one token per relay per sign-in and again after about
/// five minutes, when the last one expires. 30 in five minutes covers several
/// relays and devices with room to spare.
public enum RelayMintPolicy {
public static let defaultAttempts = 30
public static let defaultWindow: TimeInterval = 300
public static func limit(attempts: Int? = nil, window: TimeInterval? = nil) -> RateLimiter.Limit {
RateLimiter.Limit(attempts: max(1, attempts ?? defaultAttempts),
window: max(1, window ?? defaultWindow))
}
/// The counter key. Prefixed so it can never collide with the sign-in
/// keys ("ip:", "handle:", "signup:") in the same table.
public static func key(subject: String) -> String {
"relay:\(subject)"
}
}
@@ -0,0 +1,41 @@
import XCTest
@testable import EnclaveAccountsKit
/// Pins the relay mint budget the SQL limiter enforces in production.
final class RelayMintPolicyTests: XCTestCase {
final class Clock: @unchecked Sendable { var t: TimeInterval = 1_000 }
func testDefaultBudgetIs30PerFiveMinutes() {
let limit = RelayMintPolicy.limit()
XCTAssertEqual(limit.attempts, 30)
XCTAssertEqual(limit.window, 300)
}
func testOverridesAreClampedToAtLeastOne() {
let limit = RelayMintPolicy.limit(attempts: 0, window: -5)
XCTAssertEqual(limit.attempts, 1)
XCTAssertEqual(limit.window, 1)
}
func testKeyIsPrefixedAndPerSubject() {
XCTAssertEqual(RelayMintPolicy.key(subject: "u1"), "relay:u1")
XCTAssertNotEqual(RelayMintPolicy.key(subject: "u1"), RelayMintPolicy.key(subject: "u2"))
}
func testThirtyFirstMintInWindowIsRefusedAndOtherUsersAreNot() async {
let clock = Clock()
let limiter = RateLimiter(limit: RelayMintPolicy.limit(), now: { clock.t })
let alice = RelayMintPolicy.key(subject: "alice")
for i in 0..<30 {
let ok = await limiter.allow(alice)
XCTAssertTrue(ok, "mint \(i + 1) should pass")
}
let blocked = await limiter.allow(alice)
XCTAssertFalse(blocked)
let bob = await limiter.allow(RelayMintPolicy.key(subject: "bob"))
XCTAssertTrue(bob)
clock.t += 301
let afterWindow = await limiter.allow(alice)
XCTAssertTrue(afterWindow)
}
}