VerifiedRecipeCatalog.kt
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/extensions/recipe/VerifiedRecipeCatalog.kt
1package eu.friedcutlet.yokan.services.extensions.recipe23import dev.whyoleg.cryptography.CryptographyProviderApi4import dev.whyoleg.cryptography.algorithms.EdDSA5import dev.whyoleg.cryptography.algorithms.SHA2566import eu.friedcutlet.yokan.services.catchingNonCancellation7import kotlinx.serialization.SerialName8import kotlinx.serialization.Serializable9import kotlinx.serialization.decodeFromString10import kotlinx.serialization.json.Json1112/** Host-owned trust material. It is intentionally not serializable recipe/catalog data. */13data class TrustedCatalogKey(14 val catalogId: String,15 val keyId: String,16 val rawEd25519PublicKey: ByteArray,17 val state: TrustedCatalogKeyState,18 val validFromEpochSeconds: Long? = null,19 val validUntilEpochSeconds: Long? = null,20)2122/** Host-owned key scope; keys enrolled for another catalog are never valid here. */23data class CatalogTrustPolicy(24 val catalogId: String,25 val trustedKeys: List<TrustedCatalogKey>,26)2728enum class TrustedCatalogKeyState { Active, Revoked }2930/** Host-owned replay state. Persisting it belongs to a later integration phase. */31class CatalogAcceptanceState(32 val catalogId: String,33 val highestRevision: Long,34 payloadHash: ByteArray,35) {36 val payloadHash: ByteArray = payloadHash.copyOf()37}3839@Serializable40data class VerifiedRecipeCatalog(41 val formatVersion: RecipeCatalogFormatVersion,42 val artifacts: List<RecipeArtifactMetadata>,43)4445@Serializable46enum class RecipeCatalogFormatVersion {47 @SerialName("1")48 V1,49}5051/** Signed transport metadata only; recipe parsing and execution deliberately remain out of scope. */52@Serializable53data class RecipeArtifactMetadata(54 val stableId: String,55 val releaseVersion: String,56 val sha256: String,57 val sizeBytes: Long,58 val url: String,59)6061enum class RecipeCatalogVerificationErrorCode {62 EnvelopeTooLarge,63 MalformedEnvelope,64 UnsupportedEnvelopeVersion,65 UnknownKey,66 RevokedKey,67 InvalidKey,68 KeyOutsideValidity,69 InvalidSignature,70 InvalidPayloadDigest,71 Expired,72 IssuedInFuture,73 InvalidLifetime,74 CatalogIdentityMismatch,75 InvalidTrustPolicy,76 Rollback,77 RevisionConflict,78 InvalidAcceptanceState,79 InvalidCatalogPayload,80 InvalidArtifactMetadata,81}8283data class RecipeCatalogVerificationError(84 val code: RecipeCatalogVerificationErrorCode,85 val detail: String = "catalog verification failed",86)8788sealed interface RecipeCatalogVerificationResult {89 data class Accepted(90 val catalog: VerifiedRecipeCatalog,91 val acceptanceState: CatalogAcceptanceState,92 val idempotent: Boolean,93 ) : RecipeCatalogVerificationResult9495 data class Rejected(val error: RecipeCatalogVerificationError) : RecipeCatalogVerificationResult96}9798sealed interface RecipeArtifactEligibility {99 data object Eligible : RecipeArtifactEligibility100 data class Rejected(val error: RecipeArtifactEligibilityError) : RecipeArtifactEligibility101}102103enum class RecipeArtifactEligibilityError { InvalidMetadata, SizeMismatch, DigestMismatch }104105object VerifiedRecipeCatalogVerifier {106 private const val maxCatalogArtifacts = 64107 private const val maxArtifactBytes = 32 * 1024 * 1024108 private const val maxCatalogLifetimeSeconds = 14L * 24 * 60 * 60109 private const val maxFutureIssueSkewSeconds = 5L * 60110 private const val publicKeyBytes = 32111 private const val sha256Bytes = 32112 private val provider = dev.whyoleg.cryptography.CryptographyProvider.Default113 private val catalogJson = Json {114 ignoreUnknownKeys = false115 isLenient = false116 coerceInputValues = false117 explicitNulls = false118 useAlternativeNames = false119 }120121 @OptIn(CryptographyProviderApi::class)122 suspend fun verify(123 envelopeBytes: ByteArray,124 trustPolicy: CatalogTrustPolicy,125 previousAcceptance: CatalogAcceptanceState?,126 nowEpochSeconds: Long,127 ): RecipeCatalogVerificationResult {128 val envelope = when (val parsed = RecipeCatalogEnvelopeWire.parse(envelopeBytes, RecipeCatalogLimits.maxEnvelopeBytes, RecipeCatalogLimits.maxPayloadBytes, RecipeCatalogLimits.maxKeyIdBytes)) {129 is RecipeCatalogEnvelopeParseResult.Parsed -> parsed.envelope130 RecipeCatalogEnvelopeParseResult.UnsupportedVersion -> return rejected(RecipeCatalogVerificationErrorCode.UnsupportedEnvelopeVersion)131 RecipeCatalogEnvelopeParseResult.Malformed -> return rejected(RecipeCatalogVerificationErrorCode.MalformedEnvelope)132 }133 if (!validCatalogId(trustPolicy.catalogId) || trustPolicy.trustedKeys.any { it.catalogId != trustPolicy.catalogId }) {134 return rejected(RecipeCatalogVerificationErrorCode.InvalidTrustPolicy)135 }136 if (envelope.catalogId != trustPolicy.catalogId) return rejected(RecipeCatalogVerificationErrorCode.CatalogIdentityMismatch)137 val matchingKeys = trustPolicy.trustedKeys.filter { it.keyId == envelope.keyId }138 if (matchingKeys.isEmpty()) return rejected(RecipeCatalogVerificationErrorCode.UnknownKey)139 if (matchingKeys.size != 1) return rejected(RecipeCatalogVerificationErrorCode.InvalidKey)140 val key = matchingKeys.single()141 if (key.state == TrustedCatalogKeyState.Revoked) return rejected(RecipeCatalogVerificationErrorCode.RevokedKey)142 if (key.rawEd25519PublicKey.size != publicKeyBytes || !validKeyId(key.keyId) || !validCatalogId(key.catalogId)) {143 return rejected(RecipeCatalogVerificationErrorCode.InvalidKey)144 }145 if ((key.validFromEpochSeconds != null && nowEpochSeconds < key.validFromEpochSeconds) ||146 (key.validUntilEpochSeconds != null && nowEpochSeconds > key.validUntilEpochSeconds)147 ) return rejected(RecipeCatalogVerificationErrorCode.KeyOutsideValidity)148 if (envelope.expiresAtEpochSeconds <= envelope.issuedAtEpochSeconds ||149 envelope.issuedAtEpochSeconds > Long.MAX_VALUE - maxCatalogLifetimeSeconds ||150 envelope.expiresAtEpochSeconds > envelope.issuedAtEpochSeconds + maxCatalogLifetimeSeconds151 ) return rejected(RecipeCatalogVerificationErrorCode.InvalidLifetime)152 val latestAllowedIssue = if (nowEpochSeconds > Long.MAX_VALUE - maxFutureIssueSkewSeconds) {153 Long.MAX_VALUE154 } else {155 nowEpochSeconds + maxFutureIssueSkewSeconds156 }157 if (envelope.issuedAtEpochSeconds > latestAllowedIssue) {158 return rejected(RecipeCatalogVerificationErrorCode.IssuedInFuture)159 }160 if (envelope.expiresAtEpochSeconds <= nowEpochSeconds) return rejected(RecipeCatalogVerificationErrorCode.Expired)161162 val payloadHash = catchingNonCancellation { provider.get(SHA256).hasher().hash(envelope.payload) }163 .getOrElse { return rejected(RecipeCatalogVerificationErrorCode.InvalidPayloadDigest) }164 if (!constantTimeEquals(payloadHash, envelope.payloadHash)) return rejected(RecipeCatalogVerificationErrorCode.InvalidPayloadDigest)165166 val publicKey = catchingNonCancellation {167 provider.get(EdDSA).publicKeyDecoder(EdDSA.Curve.Ed25519)168 .decodeFromByteArray(EdDSA.PublicKey.Format.RAW, key.rawEd25519PublicKey)169 }.getOrElse { return rejected(RecipeCatalogVerificationErrorCode.InvalidKey) }170 val signatureValid = catchingNonCancellation {171 publicKey.signatureVerifier().tryVerifySignature(RecipeCatalogEnvelopeWire.signingFrame(envelope), envelope.signature)172 }.getOrDefault(false)173 if (!signatureValid) return rejected(RecipeCatalogVerificationErrorCode.InvalidSignature)174175 val idempotent = when (previousAcceptance) {176 null -> false177 else -> when {178 previousAcceptance.catalogId != envelope.catalogId || previousAcceptance.highestRevision < 0 || previousAcceptance.payloadHash.size != sha256Bytes ->179 return rejected(RecipeCatalogVerificationErrorCode.InvalidAcceptanceState)180 envelope.revision < previousAcceptance.highestRevision -> return rejected(RecipeCatalogVerificationErrorCode.Rollback)181 envelope.revision == previousAcceptance.highestRevision && !constantTimeEquals(envelope.payloadHash, previousAcceptance.payloadHash) ->182 return rejected(RecipeCatalogVerificationErrorCode.RevisionConflict)183 else -> envelope.revision == previousAcceptance.highestRevision184 }185 }186 if (StrictRecipeBundleDecoder.boundedJsonPreflight(envelope.payload, RecipeCatalogLimits.maxPayloadBytes) != null) {187 return rejected(RecipeCatalogVerificationErrorCode.InvalidCatalogPayload)188 }189 val catalog = decodeCatalog(envelope.payload) ?: return rejected(RecipeCatalogVerificationErrorCode.InvalidCatalogPayload)190 if (!validCatalog(catalog)) return rejected(RecipeCatalogVerificationErrorCode.InvalidArtifactMetadata)191 return RecipeCatalogVerificationResult.Accepted(192 catalog = catalog,193 acceptanceState = CatalogAcceptanceState(envelope.catalogId, envelope.revision, envelope.payloadHash),194 idempotent = idempotent,195 )196 }197198 @OptIn(CryptographyProviderApi::class)199 /** Integrity matching only; download and installation authorization remain host policy decisions. */200 suspend fun artifactEligibility(metadata: RecipeArtifactMetadata, bytes: ByteArray): RecipeArtifactEligibility {201 if (!validArtifact(metadata)) return RecipeArtifactEligibility.Rejected(RecipeArtifactEligibilityError.InvalidMetadata)202 if (bytes.size.toLong() != metadata.sizeBytes) return RecipeArtifactEligibility.Rejected(RecipeArtifactEligibilityError.SizeMismatch)203 val digest = catchingNonCancellation { provider.get(SHA256).hasher().hash(bytes) }204 .getOrElse { return RecipeArtifactEligibility.Rejected(RecipeArtifactEligibilityError.DigestMismatch) }205 return if (constantTimeEquals(digest, hexToBytes(metadata.sha256) ?: ByteArray(0))) {206 RecipeArtifactEligibility.Eligible207 } else {208 RecipeArtifactEligibility.Rejected(RecipeArtifactEligibilityError.DigestMismatch)209 }210 }211212 private fun decodeCatalog(payload: ByteArray): VerifiedRecipeCatalog? {213 val text = try {214 payload.decodeToString(throwOnInvalidSequence = true)215 } catch (_: CharacterCodingException) {216 return null217 }218 // SerializationException is an IllegalArgumentException.219 return try {220 catalogJson.decodeFromString<VerifiedRecipeCatalog>(text)221 } catch (_: IllegalArgumentException) {222 null223 }224 }225226 private fun validCatalog(catalog: VerifiedRecipeCatalog): Boolean = catalog.artifacts.size in 1..maxCatalogArtifacts &&227 catalog.artifacts.all(::validArtifact) && catalog.artifacts.map(RecipeArtifactMetadata::stableId).toSet().size == catalog.artifacts.size228229 private fun validArtifact(artifact: RecipeArtifactMetadata): Boolean =230 validIdentifier(artifact.stableId) && validReleaseVersion(artifact.releaseVersion) &&231 artifact.sizeBytes in 1..maxArtifactBytes.toLong() && hexToBytes(artifact.sha256)?.size == sha256Bytes && safeHttpsUrl(artifact.url)232233 private fun safeHttpsUrl(value: String): Boolean {234 if (value.length !in 9..2_048 || value.any { it.code <= 0x20 || it == '\\' || it == '#' }) return false235 if (loopbackCatalogOrigin(value) != null) return true236 if (!value.startsWith("https://")) return false237 val pathStart = value.indexOf('/', startIndex = 8)238 val queryStart = value.indexOf('?', startIndex = 8)239 val authorityEnd = listOf(pathStart, queryStart).filter { it >= 0 }.minOrNull() ?: value.length240 val authority = value.substring(8, authorityEnd)241 if (authority.isEmpty() || '@' in authority) return false242 val pieces = authority.split(':')243 if (pieces.size !in 1..2 || !RecipeSyntax.isHost(pieces.first())) return false244 if (pieces.size == 2) {245 val port = pieces[1].toIntOrNull() ?: return false246 if (port !in 1..65535 || pieces[1] != port.toString()) return false247 }248 return true249 }250251 private fun validIdentifier(value: String): Boolean = RecipeSyntax.isIdentifier(value)252 private fun validCatalogId(value: String): Boolean = RecipeSyntax.isIdentifier(value)253 private fun validReleaseVersion(value: String): Boolean = RecipeSyntax.isIdentifier(value, allowPlus = true)254 private fun validKeyId(value: String): Boolean = RecipeSyntax.isIdentifier(value, RecipeCatalogLimits.maxKeyIdBytes)255 private fun hexToBytes(value: String): ByteArray? {256 if (value.length != 64 || value.any { !it.isHex() }) return null257 return ByteArray(32) { index -> ((value[index * 2].hexValue() shl 4) or value[index * 2 + 1].hexValue()).toByte() }258 }259 private fun Char.isHex(): Boolean = this in '0'..'9' || this in 'a'..'f'260 private fun Char.hexValue(): Int = if (this in '0'..'9') this - '0' else this - 'a' + 10261 private fun constantTimeEquals(left: ByteArray, right: ByteArray): Boolean {262 var difference = left.size xor right.size263 val maximum = maxOf(left.size, right.size)264 for (index in 0 until maximum) difference = difference or ((left.getOrElse(index) { 0 }.toInt() xor right.getOrElse(index) { 0 }.toInt()))265 return difference == 0266 }267}268269private fun rejected(code: RecipeCatalogVerificationErrorCode): RecipeCatalogVerificationResult.Rejected =270 RecipeCatalogVerificationResult.Rejected(RecipeCatalogVerificationError(code))271272internal data class RecipeCatalogEnvelope(273 val catalogId: String,274 val keyId: String,275 val revision: Long,276 val issuedAtEpochSeconds: Long,277 val expiresAtEpochSeconds: Long,278 val payloadHash: ByteArray,279 val signature: ByteArray,280 val payload: ByteArray,281)282283internal sealed interface RecipeCatalogEnvelopeParseResult {284 data class Parsed(val envelope: RecipeCatalogEnvelope) : RecipeCatalogEnvelopeParseResult285 data object UnsupportedVersion : RecipeCatalogEnvelopeParseResult286 data object Malformed : RecipeCatalogEnvelopeParseResult287}288289/** Fixed binary envelope and its domain-separated signing frame. */290internal object RecipeCatalogEnvelopeWire {291 private val magic = byteArrayOf('Y'.code.toByte(), 'R'.code.toByte(), 'C'.code.toByte(), '2'.code.toByte())292 private const val version = 2293 private val domain = "yokan.recipe-catalog.ed25519.v2\u0000".encodeToByteArray()294 private const val signatureBytes = 64295 private const val hashBytes = 32296297 internal fun parse(bytes: ByteArray, maxEnvelopeBytes: Int, maxPayloadBytes: Int, maxKeyIdBytes: Int): RecipeCatalogEnvelopeParseResult {298 if (bytes.size > maxEnvelopeBytes || bytes.size < magic.size + 1 + 2 + 2 + 8 + 8 + 8 + 4 + hashBytes + signatureBytes) {299 return RecipeCatalogEnvelopeParseResult.Malformed300 }301 var offset = 0302 fun read(count: Int): ByteArray? = if (count > bytes.size - offset) null else bytes.copyOfRange(offset, offset + count).also { offset += count }303 if (read(magic.size)?.contentEquals(magic) != true) return RecipeCatalogEnvelopeParseResult.Malformed304 if (read(1)?.firstOrNull()?.toInt()?.and(0xff) != version) return RecipeCatalogEnvelopeParseResult.UnsupportedVersion305 val catalogLength = readU16(read(2) ?: return RecipeCatalogEnvelopeParseResult.Malformed)306 if (catalogLength !in 1..maxKeyIdBytes) return RecipeCatalogEnvelopeParseResult.Malformed307 val catalogBytes = read(catalogLength) ?: return RecipeCatalogEnvelopeParseResult.Malformed308 val catalogId = try { catalogBytes.decodeToString(throwOnInvalidSequence = true) } catch (_: CharacterCodingException) {309 return RecipeCatalogEnvelopeParseResult.Malformed310 }311 if (catalogId.encodeToByteArray().size != catalogLength) return RecipeCatalogEnvelopeParseResult.Malformed312 val keyLength = readU16(read(2) ?: return RecipeCatalogEnvelopeParseResult.Malformed)313 if (keyLength !in 1..maxKeyIdBytes) return RecipeCatalogEnvelopeParseResult.Malformed314 val keyBytes = read(keyLength) ?: return RecipeCatalogEnvelopeParseResult.Malformed315 val keyId = try { keyBytes.decodeToString(throwOnInvalidSequence = true) } catch (_: CharacterCodingException) {316 return RecipeCatalogEnvelopeParseResult.Malformed317 }318 if (keyId.encodeToByteArray().size != keyLength) return RecipeCatalogEnvelopeParseResult.Malformed319 val revision = readI64(read(8) ?: return RecipeCatalogEnvelopeParseResult.Malformed)320 if (revision < 0) return RecipeCatalogEnvelopeParseResult.Malformed321 val issued = readI64(read(8) ?: return RecipeCatalogEnvelopeParseResult.Malformed)322 val expires = readI64(read(8) ?: return RecipeCatalogEnvelopeParseResult.Malformed)323 val payloadLength = readU32(read(4) ?: return RecipeCatalogEnvelopeParseResult.Malformed) ?: return RecipeCatalogEnvelopeParseResult.Malformed324 if (payloadLength > maxPayloadBytes || payloadLength > bytes.size - offset - hashBytes - signatureBytes) return RecipeCatalogEnvelopeParseResult.Malformed325 val hash = read(hashBytes) ?: return RecipeCatalogEnvelopeParseResult.Malformed326 val signature = read(signatureBytes) ?: return RecipeCatalogEnvelopeParseResult.Malformed327 val payload = read(payloadLength) ?: return RecipeCatalogEnvelopeParseResult.Malformed328 if (offset != bytes.size) return RecipeCatalogEnvelopeParseResult.Malformed329 return RecipeCatalogEnvelopeParseResult.Parsed(RecipeCatalogEnvelope(catalogId, keyId, revision, issued, expires, hash, signature, payload))330 }331332 internal fun signingFrame(envelope: RecipeCatalogEnvelope): ByteArray = signingFrame(333 envelope.catalogId.encodeToByteArray(), envelope.keyId.encodeToByteArray(), envelope.revision, envelope.issuedAtEpochSeconds, envelope.expiresAtEpochSeconds, envelope.payload.size, envelope.payloadHash,334 )335336 internal fun signingFrame(337 catalogId: ByteArray,338 keyId: ByteArray,339 revision: Long,340 issuedAtEpochSeconds: Long,341 expiresAtEpochSeconds: Long,342 payloadLength: Int,343 payloadHash: ByteArray,344 ): ByteArray = domain + writeU16(catalogId.size) + catalogId + writeU16(keyId.size) + keyId + writeI64(revision) + writeI64(issuedAtEpochSeconds) + writeI64(expiresAtEpochSeconds) + writeU32(payloadLength) + payloadHash345346 internal fun encodeForTesting(347 catalogId: String,348 keyId: String,349 revision: Long,350 issuedAtEpochSeconds: Long,351 expiresAtEpochSeconds: Long,352 payloadHash: ByteArray,353 signature: ByteArray,354 payload: ByteArray,355 ): ByteArray {356 val catalog = catalogId.encodeToByteArray()357 val key = keyId.encodeToByteArray()358 return magic + byteArrayOf(version.toByte()) + writeU16(catalog.size) + catalog + writeU16(key.size) + key + writeI64(revision) + writeI64(issuedAtEpochSeconds) +359 writeI64(expiresAtEpochSeconds) + writeU32(payload.size) + payloadHash + signature + payload360 }361362 private fun readU16(bytes: ByteArray): Int = ((bytes[0].toInt() and 0xff) shl 8) or (bytes[1].toInt() and 0xff)363 private fun readU32(bytes: ByteArray): Int? {364 val value = ((bytes[0].toLong() and 0xff) shl 24) or ((bytes[1].toLong() and 0xff) shl 16) or ((bytes[2].toLong() and 0xff) shl 8) or (bytes[3].toLong() and 0xff)365 return if (value > Int.MAX_VALUE) null else value.toInt()366 }367 private fun readI64(bytes: ByteArray): Long = bytes.fold(0L) { value, byte -> (value shl 8) or (byte.toLong() and 0xff) }368 private fun writeU16(value: Int): ByteArray = byteArrayOf((value ushr 8).toByte(), value.toByte())369 private fun writeU32(value: Int): ByteArray = byteArrayOf((value ushr 24).toByte(), (value ushr 16).toByte(), (value ushr 8).toByte(), value.toByte())370 private fun writeI64(value: Long): ByteArray = ByteArray(8) { index -> (value ushr (56 - index * 8)).toByte() }371}372