Skip to content

Commit

Permalink
feat: deduplicate rotation requests
Browse files Browse the repository at this point in the history
  • Loading branch information
OpenSrcerer committed Apr 16, 2024
1 parent 986dc9b commit 1e36556
Showing 1 changed file with 21 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ import online.danielstefani.paddy.mqtt.RxMqttClient
import online.danielstefani.paddy.security.dto.AuthenticationRequestDto
import online.danielstefani.paddy.security.dto.AuthenticationResultDto
import org.jboss.resteasy.reactive.RestResponse
import reactor.core.publisher.Mono
import java.time.Duration
import java.time.Instant

@Path("/")
Expand All @@ -26,6 +28,8 @@ class MqttAuthorizationController(

companion object {
const val SECONDS_WEEK = 604800

val rotationDeduplicationSet = mutableSetOf<String>()
}

@POST
Expand All @@ -40,10 +44,21 @@ class MqttAuthorizationController(
val exp = jwt.getJsonObject("payload").getString("exp")

// If JWT on the device is expiring in one week, rotate it
if (exp.toLong() <= Instant.now().epochSecond + SECONDS_WEEK) {
if (shouldRotateKey(sub, exp)) {
rotationDeduplicationSet.add(sub) // Prevent duplicates

val newJwt = jwtService.makeJwt(sub, JwtType.DAEMON, null).jwt

mqttClient.publish(sub, "rotate", newJwt, qos = MqttQos.EXACTLY_ONCE)
?.doOnSubscribe { Log.info("[JWT-ROTATOR] Rotating JWT for <$sub>...") }
?.subscribe()

// Remove element from deduplication set after 60s
Mono.just(true)
.doOnSubscribe { Log.info("[JWT-ROTATOR] Removing <$sub> from deduplication set.") }
.delayElement(Duration.ofSeconds(60))
.doOnSuccess { rotationDeduplicationSet.remove(sub) }
.subscribe()
}

// Special case: Check if the token is for the backend
Expand All @@ -57,6 +72,11 @@ class MqttAuthorizationController(
allow(sub, authDto.topic) else forbid(sub, authDto.topic)
}

private fun shouldRotateKey(sub: String, exp: String): Boolean {
return !rotationDeduplicationSet.contains(sub)
&& exp.toLong() <= Instant.now().epochSecond + SECONDS_WEEK
}

/*
Topics are expected to be in the format daemon/SUB-XXXX/...
This function makes sure that the first part is in that format.
Expand Down

0 comments on commit 1e36556

Please sign in to comment.