feat(media,android): Kotlin SMF1 reader/sealer and live channel, cross-language vectors
test-vectors/media.json pins SMF1 files (empty, partial, exact boundary, multi-segment with full metadata) and SLF1 live frames in link mode across a rotation. Kotlin reads them and reproduces every sealed file and every signed frame byte for byte; TS locks the same file. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,179 @@
|
||||
package no.zyon.shade
|
||||
|
||||
import no.zyon.shade.media.ByteArraySource
|
||||
import no.zyon.shade.media.FOOTER_BYTES
|
||||
import no.zyon.shade.media.Grants
|
||||
import no.zyon.shade.media.LiveContent
|
||||
import no.zyon.shade.media.LiveGrant
|
||||
import no.zyon.shade.media.LiveKeyException
|
||||
import no.zyon.shade.media.LivePublisher
|
||||
import no.zyon.shade.media.LiveSubscriber
|
||||
import no.zyon.shade.media.MediaGrant
|
||||
import no.zyon.shade.media.MediaIntegrityException
|
||||
import no.zyon.shade.media.MediaKeys
|
||||
import no.zyon.shade.media.MediaMeta
|
||||
import no.zyon.shade.media.MediaReader
|
||||
import no.zyon.shade.media.MediaSealer
|
||||
import no.zyon.shade.media.chainStep
|
||||
import no.zyon.shade.media.decodeFrame
|
||||
import no.zyon.shade.media.deriveMediaSubkeys
|
||||
import no.zyon.shade.media.epochKeys
|
||||
import no.zyon.shade.media.linkEpochSeed
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import org.junit.Assert.assertArrayEquals
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertNotNull
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertThrows
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
import java.io.File
|
||||
|
||||
/**
|
||||
* `@shade/media` against `test-vectors/media.json` — SMF1 sealed files and
|
||||
* SLF1 live frames, byte for byte. Generated by
|
||||
* `bun run scripts/generate-vectors.ts media.json`.
|
||||
*/
|
||||
class MediaVectorTest {
|
||||
|
||||
private val vectors: JSONArray = run {
|
||||
val obj = JSONObject(File("../../test-vectors/media.json").readText())
|
||||
assertEquals("media.json schema version", 2, obj.getInt("version"))
|
||||
obj.getJSONArray("vectors")
|
||||
}
|
||||
|
||||
private fun byPrefix(prefix: String): List<JSONObject> =
|
||||
(0 until vectors.length()).map { vectors.getJSONObject(it) }
|
||||
.filter { it.getString("description").startsWith(prefix) }
|
||||
.also { assertTrue("no vectors for '$prefix'", it.isNotEmpty()) }
|
||||
|
||||
private fun hex(s: String): ByteArray =
|
||||
ByteArray(s.length / 2) { ((Character.digit(s[it * 2], 16) shl 4) + Character.digit(s[it * 2 + 1], 16)).toByte() }
|
||||
|
||||
private fun toHex(b: ByteArray) = b.joinToString("") { "%02x".format(it) }
|
||||
|
||||
private val keys = byPrefix("smf1 keys").single()
|
||||
private val mediaId = hex(keys.getString("mediaId"))
|
||||
private val mediaKey = hex(keys.getString("mediaKey"))
|
||||
|
||||
@Test
|
||||
fun subkeys() {
|
||||
val k = deriveMediaSubkeys(mediaKey, mediaId)
|
||||
assertEquals(keys.getString("segmentKey"), toHex(k.segmentKey))
|
||||
assertEquals(keys.getString("metaKey"), toHex(k.metaKey))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun sealedFilesReadAndResealByteForByte() {
|
||||
for (v in byPrefix("smf1 file")) {
|
||||
val sealed = hex(v.getString("sealed"))
|
||||
val plain = hex(v.getString("plaintext"))
|
||||
val reader = MediaReader.open(ByteArraySource(sealed), MediaKeys(mediaId, mediaKey, hex(v.getString("rootDigest"))))
|
||||
assertArrayEquals(v.getString("description"), plain, reader.read(0, plain.size))
|
||||
val meta = MediaMeta.fromJson(v.getString("metaJson"))
|
||||
assertEquals(meta, reader.meta)
|
||||
|
||||
// Writer parity: the same key, id and input give the same bytes.
|
||||
val (resealed, result) = MediaSealer.withPinnedKeys(mediaId, mediaKey, meta, v.getInt("segmentSize")).sealAll(plain)
|
||||
assertEquals(v.getString("description"), v.getString("sealed"), toHex(resealed))
|
||||
assertEquals(v.getString("rootDigest"), toHex(result.rootDigest))
|
||||
assertEquals(v.getLong("segmentCount"), result.segmentCount)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun randomAccessAndStreaming() {
|
||||
val v = byPrefix("smf1 file: three segments").single()
|
||||
val plain = hex(v.getString("plaintext"))
|
||||
val reader = MediaReader.open(ByteArraySource(hex(v.getString("sealed"))), MediaKeys(mediaId, mediaKey), cacheSegments = 0)
|
||||
for (off in listOf(0, 1, 4095, 4096, 4097, 8191, 8192, plain.size - 1)) {
|
||||
for (len in listOf(1, 100, 4096, 9000)) {
|
||||
assertArrayEquals("at $off+$len", plain.copyOfRange(off, minOf(plain.size, off + len)), reader.read(off.toLong(), len))
|
||||
}
|
||||
}
|
||||
assertArrayEquals(plain, reader.inputStream().readBytes())
|
||||
assertArrayEquals(plain.copyOfRange(5000, 9000), reader.inputStream(5000, 9000).readBytes())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun tamperedSegmentAndTrailerAreRefused() {
|
||||
val v = byPrefix("smf1 file: three segments").single()
|
||||
val sealed = hex(v.getString("sealed"))
|
||||
val root = hex(v.getString("rootDigest"))
|
||||
val bad = sealed.copyOf().also { it[5000] = (it[5000].toInt() xor 1).toByte() }
|
||||
val r = MediaReader.open(ByteArraySource(bad), MediaKeys(mediaId, mediaKey, root))
|
||||
assertThrows(MediaIntegrityException::class.java) { r.read(4096, 10) }
|
||||
val badTable = sealed.copyOf().also { it[it.size - FOOTER_BYTES - 1] = (it[it.size - FOOTER_BYTES - 1].toInt() xor 1).toByte() }
|
||||
assertThrows(MediaIntegrityException::class.java) { MediaReader.open(ByteArraySource(badTable), MediaKeys(mediaId, mediaKey, root)) }
|
||||
}
|
||||
|
||||
@Test
|
||||
fun liveKeySchedule() {
|
||||
val k = byPrefix("live keys").single()
|
||||
val channelId = hex(k.getString("channelId"))
|
||||
val seed = linkEpochSeed(hex(k.getString("channelSecret")), channelId, 0)
|
||||
assertEquals(k.getString("epochSeed"), toHex(seed))
|
||||
assertEquals(k.getString("epochSeed1"), toHex(linkEpochSeed(hex(k.getString("channelSecret")), channelId, 1)))
|
||||
val ek = epochKeys(seed, channelId, 0)
|
||||
assertEquals(k.getString("chainKey0"), toHex(ek.chainKey))
|
||||
assertEquals(k.getString("stickyKey"), toHex(ek.stickyKey))
|
||||
val (mk0, ck1) = chainStep(ek.chainKey)
|
||||
assertEquals(k.getString("messageKey0"), toHex(mk0))
|
||||
assertEquals(k.getString("chainKey1"), toHex(ck1))
|
||||
assertEquals(k.getString("messageKey1"), toHex(chainStep(ck1).first))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun liveFramesOpenFromTheLinkGrantAcrossARotation() {
|
||||
val g = Grants.parse(byPrefix("live grant").single().getString("json")) as LiveGrant
|
||||
assertNotNull(g.channelSecret)
|
||||
val sub = LiveSubscriber(g)
|
||||
for (v in byPrefix("live frame")) {
|
||||
val f = sub.open(hex(v.getString("wire")))
|
||||
assertNotNull(v.getString("description"), f)
|
||||
assertEquals(v.getLong("seq"), f!!.seq)
|
||||
assertEquals(v.getString("payload"), toHex(f.content.encode()))
|
||||
// Replays are dropped quietly.
|
||||
assertNull(sub.open(hex(v.getString("wire"))))
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun livePublisherReproducesTheWireBytes() {
|
||||
val k = byPrefix("live keys").single()
|
||||
val pub = LivePublisher(hex(k.getString("channelId")), hex(k.getString("signingSecret")), hex(k.getString("channelSecret")))
|
||||
assertEquals(k.getString("signingKey"), toHex(pub.signingKey))
|
||||
val frames = byPrefix("live frame: seq")
|
||||
for ((i, v) in frames.withIndex()) {
|
||||
val content = LiveContent.decode(hex(v.getString("payload")))
|
||||
val sticky = v.getString("description").contains("sticky")
|
||||
val keyframe = decodeFrame(hex(v.getString("wire"))).header.flags and 0x02 != 0
|
||||
val wire = pub.frame(content, keyframe = keyframe, sticky = sticky, timestamp = 1_786_600_000_000L + i * 100)
|
||||
assertEquals(v.getString("description"), v.getString("wire"), toHex(wire))
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun forgedFramesAndForeignEpochsAreRefused() {
|
||||
val k = byPrefix("live keys").single()
|
||||
val channelId = hex(k.getString("channelId"))
|
||||
val pub = LivePublisher(channelId, ByteArray(32) { 7 }, null)
|
||||
val sub = LiveSubscriber(pub.grant(from = "now"))
|
||||
val good = pub.frame(LiveContent.Text("hei"))
|
||||
val mallory = LivePublisher(channelId, ByteArray(32) { 9 }, null)
|
||||
assertThrows(MediaIntegrityException::class.java) { sub.open(mallory.frame(LiveContent.Text("falsk"))) }
|
||||
assertEquals(LiveContent.Text("hei"), sub.open(good)!!.content)
|
||||
pub.rotate()
|
||||
assertThrows(LiveKeyException::class.java) { sub.open(pub.frame(LiveContent.Text("etter"))) }
|
||||
}
|
||||
|
||||
@Test
|
||||
fun mediaGrantParses() {
|
||||
val g = Grants.parse(
|
||||
"""{"kind":"shade.media-grant/v1","mediaId":"${java.util.Base64.getUrlEncoder().withoutPadding().encodeToString(mediaId)}","key":"${java.util.Base64.getUrlEncoder().withoutPadding().encodeToString(mediaKey)}","root":"${"ab".repeat(32)}","url":"https://relay.example/v1/media/x","token":"${"A".repeat(43)}"}""",
|
||||
) as MediaGrant
|
||||
assertArrayEquals(mediaId, g.mediaId)
|
||||
assertThrows(Exception::class.java) { Grants.parse("""{"kind":"shade.media-grant/v1","mediaId":"AA","key":"AA","root":"ab"}""") }
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user