Validate APP_KEY at startup

This commit is contained in:
grimsi
2025-05-27 17:58:19 +02:00
parent 123e888923
commit c2c6a891b9
2 changed files with 32 additions and 8 deletions
@@ -0,0 +1,31 @@
package de.grimsi.gameyfin.core.security
import io.github.oshai.kotlinlogging.KotlinLogging
import org.springframework.boot.CommandLineRunner
import org.springframework.stereotype.Component
import java.util.*
import kotlin.system.exitProcess
@Component
class AppKeyValidator : CommandLineRunner {
companion object {
val log = KotlinLogging.logger {}
}
override fun run(vararg args: String?) {
val base64Key = System.getenv("APP_KEY")
if (base64Key.isNullOrBlank()) {
log.error { "APP_KEY environment variable is not set or empty" }
exitProcess(1)
}
val decodedKey = Base64.getDecoder().decode(base64Key)
// Ensure the key length is valid for AES (128, 192, or 256 bits)
if (decodedKey.size !in listOf(16, 24, 32)) {
log.error { "Invalid AES key length in APP_KEY. Key must be 128, 192, or 256 bits." }
exitProcess(1)
}
}
}
@@ -1,6 +1,6 @@
package de.grimsi.gameyfin.core.security
import java.util.Base64
import java.util.*
import javax.crypto.Cipher
import javax.crypto.spec.SecretKeySpec
@@ -12,14 +12,7 @@ class EncryptionUtils {
init {
val base64Key = System.getenv("APP_KEY")
?: throw IllegalStateException("APP_KEY environment variable is not set or empty")
val decodedKey = Base64.getDecoder().decode(base64Key)
// Ensure the key length is valid for AES (128, 192, or 256 bits)
if (decodedKey.size !in listOf(16, 24, 32)) {
throw IllegalArgumentException("Invalid AES key length. Key must be 128, 192, or 256 bits.")
}
SECRET_KEY = SecretKeySpec(decodedKey, ALGORITHM)
}