Yokan / rebuild
Course 1 8624561

VerifiedRecipeCatalogTest.kt

composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/extensions/recipe/VerifiedRecipeCatalogTest.kt

test / fixture205 lines
1package eu.friedcutlet.yokan.services.extensions.recipe23import dev.whyoleg.cryptography.CryptographyProvider4import dev.whyoleg.cryptography.CryptographyProviderApi5import dev.whyoleg.cryptography.algorithms.EdDSA6import dev.whyoleg.cryptography.algorithms.SHA2567import kotlinx.coroutines.test.runTest8import kotlin.test.Test9import kotlin.test.assertEquals10import kotlin.test.assertIs1112@OptIn(CryptographyProviderApi::class)13class VerifiedRecipeCatalogTest {14    private val provider = CryptographyProvider.Default15    private val now = 1_700_000_000L16    private val catalogId = "catalog.primary"1718    @Test19    fun verifiesManualSignedEnvelopeAndIntegrityOnlyArtifactMatch() = runTest {20        val material = signingMaterial()21        val signed = signedCatalog(material)2223        val accepted = assertIs<RecipeCatalogVerificationResult.Accepted>(verify(signed))24        assertEquals(false, accepted.idempotent)25        assertEquals(catalogId, accepted.acceptanceState.catalogId)26        assertEquals(RecipeArtifactEligibility.Eligible, VerifiedRecipeCatalogVerifier.artifactEligibility(accepted.catalog.artifacts.single(), signed.artifactBytes))27    }2829    @Test30    fun manualProtocolVectorBindsDomainIdentityByteOrderLengthsAndSignature() = runTest {31        val material = signingMaterial(keyId = "signing-key")32        val payload = catalogPayload("recipe".encodeToByteArray())33        val hash = sha256(payload)34        val revision = 0x0102030405060708L35        val frame = manualSigningFrame(material.key.catalogId, material.key.keyId, revision, now - 60, now + 60, payload.size, hash)3637        assertEquals(38            "796f6b616e2e7265636970652d636174616c6f672e656432353531392e763200000f636174616c6f672e7072696d617279000b7369676e696e672d6b65790102030405060708",39            frame.take(70).toByteArray().toHexString(),40        )41        val signature = material.sign(frame)42        val envelope = manualEnvelope(material.key.catalogId, material.key.keyId, revision, now - 60, now + 60, hash, signature, payload)43        val signed = SignedCatalog(envelope, payload, "recipe".encodeToByteArray(), material, signature)4445        assertIs<RecipeCatalogVerificationResult.Accepted>(verify(signed))46    }4748    @Test49    fun rejectsPayloadAndSignatureTamperingIncludingRehashedUnsignedPayload() = runTest {50        val material = signingMaterial()51        val signed = signedCatalog(material)52        assertError(signed.envelope.copyOf().also { it[it.lastIndex] = (it[it.lastIndex] + 1).toByte() }, policy(material), RecipeCatalogVerificationErrorCode.InvalidPayloadDigest)5354        val alteredPayload = signed.payload.decodeToString().replace("1.0.0", "2.0.0").encodeToByteArray()55        val rehashedUnsigned = manualEnvelope(catalogId, material.key.keyId, 10, now - 60, now + 60, sha256(alteredPayload), signed.signature, alteredPayload)56        assertError(rehashedUnsigned, policy(material), RecipeCatalogVerificationErrorCode.InvalidSignature)5758        val headerTampered = signed.envelope.copyOf().also { it[revisionOffset(material.key)] = (it[revisionOffset(material.key)] + 1).toByte() }59        assertError(headerTampered, policy(material), RecipeCatalogVerificationErrorCode.InvalidSignature)60        assertError(signed.envelope.copyOf().also { it[signatureOffset(material.key)] = (it[signatureOffset(material.key)] + 1).toByte() }, policy(material), RecipeCatalogVerificationErrorCode.InvalidSignature)61    }6263    @Test64    fun authenticatedPayloadUsesSharedBoundedStrictJsonPreflight() = runTest {65        val material = signingMaterial()66        val normal = catalogPayload("recipe".encodeToByteArray()).decodeToString()67        val payloads = listOf(68            normal.replace("\"formatVersion\":\"1\"", "\"formatVersion\":\"1\",\"\\u0066ormatVersion\":\"1\""),69            normal.replace("\"releaseVersion\":\"1.0.0\"", "\"releaseVersion\":\"${"a".repeat(RecipeBundleLimits.maxStringCharacters + 1)}\""),70            "[".repeat(RecipeBundleLimits.maxJsonDepth + 1) + "0" + "]".repeat(RecipeBundleLimits.maxJsonDepth + 1),71            "[" + List(RecipeBundleLimits.maxCollectionEntries + 1) { "0" }.joinToString(",") + "]",72            "{\"formatVersion\":",73            normal.replace("\"artifacts\":", "\"unknown\":true,\"artifacts\":"),74            normal.replace("\"formatVersion\":\"1\"", "\"formatVersion\":\"2\""),75        )76        payloads.forEach { payload ->77            val signed = signedCatalog(material, payload = payload.encodeToByteArray())78            assertError(signed.envelope, policy(material), RecipeCatalogVerificationErrorCode.InvalidCatalogPayload)79        }80    }8182    @Test83    fun scopesKeysAndStateToExpectedStableCatalogIdentity() = runTest {84        val primary = signingMaterial()85        val other = signingMaterial(catalog = "catalog.other")86        val primaryPolicy = policy(primary)8788        assertError(signedCatalog(other).envelope, primaryPolicy, RecipeCatalogVerificationErrorCode.CatalogIdentityMismatch)89        assertError(signedCatalog(primary).envelope, CatalogTrustPolicy(catalogId, listOf(other.key)), RecipeCatalogVerificationErrorCode.InvalidTrustPolicy)9091        val signed = signedCatalog(primary)92        val otherKeyUnderExpectedId = other.key.copy(catalogId = catalogId, keyId = primary.key.keyId)93        assertError(signed.envelope, CatalogTrustPolicy(catalogId, listOf(otherKeyUnderExpectedId)), RecipeCatalogVerificationErrorCode.InvalidSignature)94        assertError(signed.envelope, CatalogTrustPolicy(catalogId, listOf(primary.key, otherKeyUnderExpectedId)), RecipeCatalogVerificationErrorCode.InvalidKey)9596        val accepted = assertIs<RecipeCatalogVerificationResult.Accepted>(verify(signed))97        assertError(signed.envelope, primaryPolicy, RecipeCatalogVerificationErrorCode.InvalidAcceptanceState, CatalogAcceptanceState("catalog.other", 10, accepted.acceptanceState.payloadHash))98        assertError(signed.envelope, primaryPolicy, RecipeCatalogVerificationErrorCode.InvalidAcceptanceState, CatalogAcceptanceState(catalogId, -1, accepted.acceptanceState.payloadHash))99    }100101    @Test102    fun rejectsUnknownRevokedMalformedAndOutOfWindowKeys() = runTest {103        val material = signingMaterial()104        val signed = signedCatalog(material)105        assertError(signed.envelope, CatalogTrustPolicy(catalogId, listOf(material.key.copy(keyId = "unknown"))), RecipeCatalogVerificationErrorCode.UnknownKey)106        assertError(signed.envelope, policy(material, material.key.copy(state = TrustedCatalogKeyState.Revoked)), RecipeCatalogVerificationErrorCode.RevokedKey)107        assertError(signed.envelope, policy(material, material.key.copy(rawEd25519PublicKey = ByteArray(31))), RecipeCatalogVerificationErrorCode.InvalidKey)108        assertError(signed.envelope, policy(material, material.key.copy(validUntilEpochSeconds = now - 1)), RecipeCatalogVerificationErrorCode.KeyOutsideValidity)109    }110111    @Test112    fun authenticSignaturesCoverTimeLifetimeAndWireBoundaries() = runTest {113        val material = signingMaterial()114        assertError(signedCatalog(material, issued = now - 20, expires = now).envelope, policy(material), RecipeCatalogVerificationErrorCode.Expired)115        assertError(signedCatalog(material, issued = now + 301, expires = now + 600).envelope, policy(material), RecipeCatalogVerificationErrorCode.IssuedInFuture)116        assertError(signedCatalog(material, issued = now, expires = now + 14L * 24 * 60 * 60 + 1).envelope, policy(material), RecipeCatalogVerificationErrorCode.InvalidLifetime)117118        val signed = signedCatalog(material)119        assertError(signed.envelope + byteArrayOf(0), policy(material), RecipeCatalogVerificationErrorCode.MalformedEnvelope)120        assertError(signed.envelope.copyOf().also { it[4] = 3 }, policy(material), RecipeCatalogVerificationErrorCode.UnsupportedEnvelopeVersion)121        assertError(signed.envelope.copyOf().also { it[5] = 0x80.toByte(); it[6] = 0 }, policy(material), RecipeCatalogVerificationErrorCode.MalformedEnvelope)122        assertError(signed.envelope.copyOf().also { it[payloadLengthOffset(material.key)] = 0x80.toByte() }, policy(material), RecipeCatalogVerificationErrorCode.MalformedEnvelope)123    }124125    @Test126    fun acceptsHigherRevisionAndSamePayloadFreshnessRenewalButRejectsRollbackAndConflict() = runTest {127        val material = signingMaterial()128        val first = signedCatalog(material, revision = 10)129        val state = assertIs<RecipeCatalogVerificationResult.Accepted>(verify(first)).acceptanceState130        assertError(signedCatalog(material, revision = 9).envelope, policy(material), RecipeCatalogVerificationErrorCode.Rollback, state)131        assertError(signedCatalog(material, revision = 10, artifactBytes = "changed".encodeToByteArray()).envelope, policy(material), RecipeCatalogVerificationErrorCode.RevisionConflict, state)132        assertEquals(true, assertIs<RecipeCatalogVerificationResult.Accepted>(verify(signedCatalog(material, revision = 10, issued = now - 30, expires = now + 120), state)).idempotent)133        val higher = assertIs<RecipeCatalogVerificationResult.Accepted>(verify(signedCatalog(material, revision = 11, artifactBytes = "changed".encodeToByteArray()), state))134        assertEquals(false, higher.idempotent)135        assertEquals(11, higher.acceptanceState.highestRevision)136    }137138    @Test139    fun rejectsUnsafeArtifactMetadataAndIntegrityMismatches() = runTest {140        val material = signingMaterial()141        assertError(signedCatalog(material, url = "http://example.test/recipe.json").envelope, policy(material), RecipeCatalogVerificationErrorCode.InvalidArtifactMetadata)142        val signed = signedCatalog(material)143        val artifact = assertIs<RecipeCatalogVerificationResult.Accepted>(verify(signed)).catalog.artifacts.single()144        assertEquals(RecipeArtifactEligibilityError.SizeMismatch, assertIs<RecipeArtifactEligibility.Rejected>(VerifiedRecipeCatalogVerifier.artifactEligibility(artifact, ByteArray(1))).error)145        assertEquals(RecipeArtifactEligibilityError.DigestMismatch, assertIs<RecipeArtifactEligibility.Rejected>(VerifiedRecipeCatalogVerifier.artifactEligibility(artifact, signed.artifactBytes.copyOf().also { it[0] = (it[0] + 1).toByte() })).error)146    }147148    private suspend fun verify(signed: SignedCatalog, previous: CatalogAcceptanceState? = null): RecipeCatalogVerificationResult =149        VerifiedRecipeCatalogVerifier.verify(signed.envelope, policy(signed.signing), previous, now)150151    private suspend fun assertError(envelope: ByteArray, trustPolicy: CatalogTrustPolicy, expected: RecipeCatalogVerificationErrorCode, previous: CatalogAcceptanceState? = null) {152        val rejected = assertIs<RecipeCatalogVerificationResult.Rejected>(VerifiedRecipeCatalogVerifier.verify(envelope, trustPolicy, previous, now))153        assertEquals(expected, rejected.error.code)154    }155156    private suspend fun signingMaterial(catalog: String = catalogId, keyId: String = "catalog-key"): CatalogSigningMaterial {157        val pair = provider.get(EdDSA).keyPairGenerator(EdDSA.Curve.Ed25519).generateKey()158        return CatalogSigningMaterial(159            TrustedCatalogKey(catalog, keyId, pair.publicKey.encodeToByteArray(EdDSA.PublicKey.Format.RAW), TrustedCatalogKeyState.Active),160            sign = { frame -> pair.privateKey.signatureGenerator().generateSignature(frame) },161        )162    }163164    private fun policy(material: CatalogSigningMaterial, key: TrustedCatalogKey = material.key): CatalogTrustPolicy = CatalogTrustPolicy(material.key.catalogId, listOf(key))165166    private suspend fun signedCatalog(167        signing: CatalogSigningMaterial,168        revision: Long = 10,169        issued: Long = now - 60,170        expires: Long = now + 60,171        artifactBytes: ByteArray = "recipe".encodeToByteArray(),172        url: String = "https://example.test/recipe.json",173        payload: ByteArray? = null,174    ): SignedCatalog {175        val actualPayload = payload ?: catalogPayload(artifactBytes, url)176        val hash = sha256(actualPayload)177        val frame = manualSigningFrame(signing.key.catalogId, signing.key.keyId, revision, issued, expires, actualPayload.size, hash)178        val signature = signing.sign(frame)179        return SignedCatalog(manualEnvelope(signing.key.catalogId, signing.key.keyId, revision, issued, expires, hash, signature, actualPayload), actualPayload, artifactBytes, signing, signature)180    }181182    private suspend fun sha256(bytes: ByteArray): ByteArray = provider.get(SHA256).hasher().hash(bytes)183    private suspend fun catalogPayload(artifactBytes: ByteArray, url: String = "https://example.test/recipe.json"): ByteArray {184        val digest = sha256(artifactBytes).toHexString()185        return """{"formatVersion":"1","artifacts":[{"stableId":"example.recipe","releaseVersion":"1.0.0","sha256":"$digest","sizeBytes":${artifactBytes.size},"url":"$url"}]}""".encodeToByteArray()186    }187188    private fun manualSigningFrame(catalog: String, keyId: String, revision: Long, issued: Long, expires: Long, payloadLength: Int, hash: ByteArray): ByteArray =189        "yokan.recipe-catalog.ed25519.v2\u0000".encodeToByteArray() + u16(catalog.encodeToByteArray().size) + catalog.encodeToByteArray() +190            u16(keyId.encodeToByteArray().size) + keyId.encodeToByteArray() + i64(revision) + i64(issued) + i64(expires) + u32(payloadLength) + hash191192    private fun manualEnvelope(catalog: String, keyId: String, revision: Long, issued: Long, expires: Long, hash: ByteArray, signature: ByteArray, payload: ByteArray): ByteArray =193        byteArrayOf('Y'.code.toByte(), 'R'.code.toByte(), 'C'.code.toByte(), '2'.code.toByte(), 2) + u16(catalog.encodeToByteArray().size) + catalog.encodeToByteArray() +194            u16(keyId.encodeToByteArray().size) + keyId.encodeToByteArray() + i64(revision) + i64(issued) + i64(expires) + u32(payload.size) + hash + signature + payload195196    private fun revisionOffset(key: TrustedCatalogKey): Int = 4 + 1 + 2 + key.catalogId.encodeToByteArray().size + 2 + key.keyId.encodeToByteArray().size197    private fun payloadLengthOffset(key: TrustedCatalogKey): Int = revisionOffset(key) + 8 + 8 + 8198    private fun signatureOffset(key: TrustedCatalogKey): Int = payloadLengthOffset(key) + 4 + 32199    private fun u16(value: Int): ByteArray = byteArrayOf((value ushr 8).toByte(), value.toByte())200    private fun u32(value: Int): ByteArray = byteArrayOf((value ushr 24).toByte(), (value ushr 16).toByte(), (value ushr 8).toByte(), value.toByte())201    private fun i64(value: Long): ByteArray = ByteArray(8) { index -> (value ushr (56 - index * 8)).toByte() }202    private data class SignedCatalog(val envelope: ByteArray, val payload: ByteArray, val artifactBytes: ByteArray, val signing: CatalogSigningMaterial, val signature: ByteArray)203    private data class CatalogSigningMaterial(val key: TrustedCatalogKey, val sign: suspend (ByteArray) -> ByteArray)204    private fun ByteArray.toHexString(): String = joinToString("") { (it.toInt() and 0xff).toString(16).padStart(2, '0') }205}206

Search chapters, reference and source filenames.