feat(android): Kotlin-vaulten — vault v2 lest og skrevet fra telefonen
no.zyon.shade.vault: samme format som @shade/vault 4.14.1 (deflate-raw- entries, biter à 4 MiB, SVM2-manifester, indeks, edit med retry på SEQ_CONFLICT). CanonicalJson for signaturene; BlobKdf bruker BouncyCastle for Ed25519-public. Vektortester mot test-vectors/vault-v2.json og et live kryss-sjekkskript (scripts/vault-live-kotlin.ts) mot TS-klienten. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,280 @@
|
||||
package no.zyon.shade
|
||||
|
||||
import com.sun.net.httpserver.HttpServer
|
||||
import no.zyon.shade.crypto.CryptoProvider
|
||||
import no.zyon.shade.crypto.TinkProvider
|
||||
import no.zyon.shade.serialization.canonicalJson
|
||||
import no.zyon.shade.vault.VaultClient
|
||||
import no.zyon.shade.vault.VaultEdit
|
||||
import no.zyon.shade.vault.VaultException
|
||||
import no.zyon.shade.vault.VaultFile
|
||||
import no.zyon.shade.vault.VaultFormatException
|
||||
import no.zyon.shade.vault.VaultHttpTransport
|
||||
import no.zyon.shade.vault.VaultKeys
|
||||
import no.zyon.shade.vault.VaultLog
|
||||
import no.zyon.shade.vault.VaultLogEntry
|
||||
import no.zyon.shade.vault.VaultManifest
|
||||
import no.zyon.shade.vault.VaultPruneResult
|
||||
import no.zyon.shade.vault.VaultTransport
|
||||
import no.zyon.shade.vault.deriveVaultKeys
|
||||
import no.zyon.shade.vault.entryObjectHashes
|
||||
import no.zyon.shade.vault.objectHash
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import org.junit.Assert.assertArrayEquals
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertThrows
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
import java.net.InetSocketAddress
|
||||
import java.util.Base64
|
||||
|
||||
/**
|
||||
* [VaultClient.edit] and friends against an in-memory relay that enforces
|
||||
* what the real routes enforce: hash-checked uploads, TOFU Ed25519 over the
|
||||
* canonical body, `seq == head + 1`, and every referenced object present.
|
||||
* A signature or hash the TS relay would refuse fails here too.
|
||||
*/
|
||||
class VaultClientTest {
|
||||
|
||||
private val crypto = TinkProvider()
|
||||
private val master = ByteArray(32) { (it * 7 + 3).toByte() }
|
||||
private val keys = deriveVaultKeys(crypto, master, "prism-queue-test")
|
||||
private val at = 1_786_600_000_000L
|
||||
|
||||
/** The relay, minus HTTP. */
|
||||
private class MemoryRelay(private val crypto: CryptoProvider) : VaultTransport {
|
||||
val objects = HashMap<String, ByteArray>()
|
||||
val log = ArrayList<VaultLogEntry>()
|
||||
val committedHashes = HashMap<Long, List<String>>()
|
||||
var pinned: ByteArray? = null
|
||||
var puts = 0
|
||||
/** Runs just before a commit is checked — the "other device" hook. */
|
||||
var beforeCommit: (() -> Unit)? = null
|
||||
|
||||
private fun authorize(body: JSONObject) {
|
||||
val sig = Base64.getDecoder().decode(body.getString("signature"))
|
||||
val fields = LinkedHashMap<String, Any>()
|
||||
for (k in body.keys()) if (k != "signature") fields[k] = plain(body.get(k))
|
||||
val canonical = canonicalJson(fields).toByteArray()
|
||||
val key = pinned ?: Base64.getDecoder().decode(body.getString("publicKey")).also { pinned = it }
|
||||
if (!crypto.verify(key, canonical, sig)) throw VaultException("UNAUTHORIZED", 401, "bad signature")
|
||||
}
|
||||
|
||||
private fun plain(v: Any): Any = when (v) {
|
||||
is JSONArray -> List(v.length()) { plain(v.get(it)) }
|
||||
is Int -> v.toLong()
|
||||
else -> v
|
||||
}
|
||||
|
||||
private fun head() = log.lastOrNull()?.seq ?: 0L
|
||||
|
||||
override fun has(vaultId: String, hash: String) = hash in objects
|
||||
|
||||
override fun put(vaultId: String, hash: String, signedBody: String) {
|
||||
val body = JSONObject(signedBody)
|
||||
authorize(body)
|
||||
val data = Base64.getDecoder().decode(body.getString("data"))
|
||||
if (objectHash(data) != hash) throw VaultException("BAD_REQUEST", 400, "hash mismatch")
|
||||
objects[hash] = data
|
||||
puts++
|
||||
}
|
||||
|
||||
override fun get(vaultId: String, hash: String) =
|
||||
objects[hash] ?: throw VaultException("NOT_FOUND", 404, "no such object")
|
||||
|
||||
override fun log(vaultId: String, limit: Int?) =
|
||||
VaultLog(if (limit == null) log.toList() else log.takeLast(limit), head())
|
||||
|
||||
override fun commit(vaultId: String, signedBody: String): Long {
|
||||
beforeCommit?.let { beforeCommit = null; it() }
|
||||
val body = JSONObject(signedBody)
|
||||
authorize(body)
|
||||
val seq = body.getLong("seq")
|
||||
if (seq != head() + 1) throw VaultException("SEQ_CONFLICT", 409, "expected seq ${head() + 1}, got $seq", head = head())
|
||||
val hashes = List(body.getJSONArray("hashes").length()) { body.getJSONArray("hashes").getString(it) }
|
||||
val manifest = body.getString("manifest")
|
||||
if (manifest !in objects || hashes.any { it !in objects }) throw VaultException("MISSING_OBJECTS", 409, "missing")
|
||||
log.add(VaultLogEntry(seq, manifest, body.getLong("at"), 0))
|
||||
committedHashes[seq] = hashes
|
||||
return seq
|
||||
}
|
||||
|
||||
override fun prune(vaultId: String, signedBody: String) = VaultPruneResult(0, 0, 0)
|
||||
}
|
||||
|
||||
private fun text(s: String) = s.toByteArray()
|
||||
|
||||
@Test
|
||||
fun emptyVaultAndNoOpEditsCommitNothing() {
|
||||
val relay = MemoryRelay(crypto)
|
||||
val client = VaultClient(crypto, keys, relay)
|
||||
assertNull(client.headManifest())
|
||||
assertThrows(VaultException::class.java) { client.manifest() }
|
||||
|
||||
var seen: VaultManifest? = VaultManifest(2, 99, 0, null, emptyList())
|
||||
assertEquals(0L, client.edit(at) { seen = it; null }.seq)
|
||||
assertNull(seen)
|
||||
val noop = client.edit(at) { VaultEdit(remove = listOf("not-there")) }
|
||||
assertFalse(noop.committed)
|
||||
assertEquals(0, relay.puts)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun appendThenEditKeepsUntouchedEntriesByteForByte() {
|
||||
val relay = MemoryRelay(crypto)
|
||||
val client = VaultClient(crypto, keys, relay, chunkSize = 64)
|
||||
val big = ByteArray(1000).also { java.util.Random(1).nextBytes(it) } // 16 parts, incompressible
|
||||
val note = text("# Plan\n" + "- [ ] gjør noe\n".repeat(40))
|
||||
val r1 = client.append(
|
||||
listOf(VaultFile("big.bin", big), VaultFile("plan.md", note, mode = "644"), VaultFile("empty", ByteArray(0))),
|
||||
at,
|
||||
)
|
||||
assertEquals(1L, r1.seq)
|
||||
assertTrue(r1.committed)
|
||||
|
||||
val m1 = client.manifest()
|
||||
assertEquals(2, m1.version)
|
||||
val bigEntry = m1.entries.single { it.path == "big.bin" }
|
||||
assertEquals(16, bigEntry.parts!!.size)
|
||||
assertEquals(bigEntry.parts!![0], bigEntry.hash)
|
||||
assertNull(bigEntry.enc)
|
||||
val planEntry = m1.entries.single { it.path == "plan.md" }
|
||||
assertEquals("deflate-raw", planEntry.enc)
|
||||
assertEquals("644", planEntry.mode)
|
||||
assertArrayEquals(big, client.readEntry(bigEntry))
|
||||
assertArrayEquals(note, client.readEntry(planEntry))
|
||||
assertArrayEquals(ByteArray(0), client.readEntry(m1.entries.single { it.path == "empty" }))
|
||||
// Commit lists every part of every entry.
|
||||
assertEquals(m1.entries.flatMap { entryObjectHashes(it) }.toSet(), relay.committedHashes[1L]!!.toSet())
|
||||
|
||||
val putsBefore = relay.puts
|
||||
val r2 = client.edit(at + 1) { head ->
|
||||
assertEquals(1L, head!!.seq)
|
||||
VaultEdit(put = listOf(VaultFile("queue/001.json", text("""{"op":"check"}"""))), remove = listOf("empty"))
|
||||
}
|
||||
assertEquals(2L, r2.seq)
|
||||
assertEquals(2, relay.puts - putsBefore) // one new object + the manifest; nothing re-sealed
|
||||
|
||||
val m2 = client.manifest()
|
||||
assertEquals(listOf("big.bin", "plan.md", "queue/001.json"), m2.entries.map { it.path })
|
||||
assertEquals(bigEntry, m2.entries[0])
|
||||
assertEquals(planEntry, m2.entries[1])
|
||||
assertEquals(m2.entries.flatMap { entryObjectHashes(it) }.toSet(), relay.committedHashes[2L]!!.toSet())
|
||||
|
||||
// Old versions stay readable; pull decrypts everything.
|
||||
assertEquals(3, client.manifest(1).entries.size)
|
||||
val pulled = client.pull()
|
||||
assertArrayEquals(text("""{"op":"check"}"""), pulled.files["queue/001.json"])
|
||||
assertEquals(2L, client.log().head)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun seqConflictRereadsTheHeadAndRetries() {
|
||||
val relay = MemoryRelay(crypto)
|
||||
val phone = VaultClient(crypto, keys, relay)
|
||||
val pc = VaultClient(crypto, keys, relay)
|
||||
phone.append(listOf(VaultFile("a.txt", text("a"))), at)
|
||||
|
||||
// The PC drains the queue between the phone's read and its commit.
|
||||
relay.beforeCommit = { pc.edit(at) { VaultEdit(remove = listOf("a.txt"), put = listOf(VaultFile("pc.txt", text("pc")))) } }
|
||||
|
||||
val heads = ArrayList<Long?>()
|
||||
val putsBefore = relay.puts
|
||||
val r = phone.edit(at + 5) { head ->
|
||||
heads.add(head?.seq)
|
||||
VaultEdit(put = listOf(VaultFile("b.txt", text("b"))))
|
||||
}
|
||||
assertEquals(listOf<Long?>(1L, 2L), heads) // change() saw the new head on the retry
|
||||
assertEquals(3L, r.seq)
|
||||
assertTrue(r.committed)
|
||||
val m = phone.manifest()
|
||||
assertEquals(setOf("pc.txt", "b.txt"), m.entries.map { it.path }.toSet()) // the PC's edit survived
|
||||
assertArrayEquals(text("b"), phone.readEntry(m.entries.single { it.path == "b.txt" }))
|
||||
// Phone: b.txt sealed once + two manifests. PC: pc.txt + its manifest.
|
||||
assertEquals(5, relay.puts - putsBefore)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun givesUpAfterMaxAttemptsAndPassesOtherErrorsThrough() {
|
||||
val relay = MemoryRelay(crypto)
|
||||
val client = VaultClient(crypto, keys, relay)
|
||||
val other = VaultClient(crypto, keys, relay)
|
||||
var calls = 0
|
||||
val loseEveryRace = object : VaultTransport by relay {
|
||||
override fun commit(vaultId: String, signedBody: String): Long {
|
||||
other.append(listOf(VaultFile("x${calls++}", text("x"))), at)
|
||||
return relay.commit(vaultId, signedBody)
|
||||
}
|
||||
}
|
||||
val e = assertThrows(VaultException::class.java) {
|
||||
VaultClient(crypto, keys, loseEveryRace).edit(at, maxAttempts = 3) { VaultEdit(put = listOf(VaultFile("p", text("p")))) }
|
||||
}
|
||||
assertTrue(e.isSeqConflict)
|
||||
assertEquals(3, calls)
|
||||
|
||||
val refusing = object : VaultTransport by relay {
|
||||
override fun commit(vaultId: String, signedBody: String): Long =
|
||||
throw VaultException("MISSING_OBJECTS", 409, "missing")
|
||||
}
|
||||
var attempts = 0
|
||||
val e2 = assertThrows(VaultException::class.java) {
|
||||
VaultClient(crypto, keys, refusing).edit(at) { attempts++; VaultEdit(put = listOf(VaultFile("q", text("q")))) }
|
||||
}
|
||||
assertEquals("MISSING_OBJECTS", e2.code)
|
||||
assertEquals(1, attempts)
|
||||
assertTrue(client.headManifest() != null)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun refusesToEditOnTopOfAnUnreadableHead() {
|
||||
val relay = MemoryRelay(crypto)
|
||||
VaultClient(crypto, keys, relay).append(listOf(VaultFile("a", text("a"))), at)
|
||||
val wrongKey = VaultKeys(keys.vaultId, ByteArray(32) { 9 }, keys.signingSeed, keys.publicKey)
|
||||
assertThrows(VaultFormatException::class.java) {
|
||||
VaultClient(crypto, wrongKey, relay).edit(at) { VaultEdit(put = listOf(VaultFile("b", text("b")))) }
|
||||
}
|
||||
assertEquals(1L, relay.log.size.toLong())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun httpTransportMapsRelayErrors() {
|
||||
val server = HttpServer.create(InetSocketAddress("127.0.0.1", 0), 0)
|
||||
server.createContext("/") { ex ->
|
||||
val path = ex.requestURI.path
|
||||
val (status, body) = when {
|
||||
path.endsWith("/commit") -> 409 to """{"error":{"code":"SEQ_CONFLICT","message":"expected seq 4, got 3"},"head":3}"""
|
||||
path.endsWith("/log") -> 200 to """{"entries":[{"seq":3,"manifest":"${"a".repeat(64)}","at":5,"bytes":10}],"head":3}"""
|
||||
ex.requestMethod == "HEAD" -> 404 to ""
|
||||
ex.requestMethod == "GET" -> 200 to "raw-bytes"
|
||||
else -> 502 to "<html>bad gateway</html>"
|
||||
}
|
||||
val bytes = body.toByteArray()
|
||||
ex.sendResponseHeaders(status, if (ex.requestMethod == "HEAD" || bytes.isEmpty()) -1 else bytes.size.toLong())
|
||||
if (bytes.isNotEmpty() && ex.requestMethod != "HEAD") ex.responseBody.use { it.write(bytes) }
|
||||
ex.close()
|
||||
}
|
||||
server.start()
|
||||
try {
|
||||
val t = VaultHttpTransport("http://127.0.0.1:${server.address.port}/")
|
||||
val id = keys.vaultId
|
||||
val hash = "b".repeat(64)
|
||||
assertEquals(3L, t.log(id, 1).head)
|
||||
assertEquals(10L, t.log(id).entries.single().bytes)
|
||||
assertFalse(t.has(id, hash))
|
||||
assertArrayEquals("raw-bytes".toByteArray(), t.get(id, hash))
|
||||
val e = assertThrows(VaultException::class.java) { t.commit(id, "{}") }
|
||||
assertTrue(e.isSeqConflict)
|
||||
assertEquals(409, e.statusCode)
|
||||
assertEquals(3L, e.head)
|
||||
val e2 = assertThrows(VaultException::class.java) { t.put(id, hash, "{}") }
|
||||
assertEquals(VaultException.CODE_NETWORK, e2.code)
|
||||
assertEquals(502, e2.statusCode)
|
||||
assertThrows(IllegalArgumentException::class.java) { t.get(id, "../../etc/passwd") }
|
||||
} finally {
|
||||
server.stop(0)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
package no.zyon.shade
|
||||
|
||||
import no.zyon.shade.crypto.TinkProvider
|
||||
import no.zyon.shade.vault.VaultClient
|
||||
import no.zyon.shade.vault.VaultEdit
|
||||
import no.zyon.shade.vault.VaultFile
|
||||
import no.zyon.shade.vault.VaultHttpTransport
|
||||
import no.zyon.shade.vault.deriveVaultKeys
|
||||
import no.zyon.shade.vault.toHex
|
||||
import org.json.JSONObject
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Assume.assumeTrue
|
||||
import org.junit.Test
|
||||
import java.io.File
|
||||
import java.security.MessageDigest
|
||||
|
||||
/**
|
||||
* Live cross-check against the real TS vault routes — skipped unless
|
||||
* `SHADE_VAULT_LIVE_SPEC` points at the spec file a TS driver wrote.
|
||||
*
|
||||
* Run it via `bun run scripts/vault-live-kotlin.ts`: the driver serves `createVaultRoutes`
|
||||
* on a local port, pushes files with the TS client and writes
|
||||
* `{ url, masterKey, app, files: {path: sha256}, kotlinOut }`. This test reads
|
||||
* every file back, then edits the vault from Kotlin and records what it wrote
|
||||
* in `kotlinOut`; the driver then reads that back with the TS client.
|
||||
*/
|
||||
class VaultLiveTest {
|
||||
|
||||
private fun sha256(b: ByteArray) = toHex(MessageDigest.getInstance("SHA-256").digest(b))
|
||||
|
||||
private fun fromHex(s: String) =
|
||||
ByteArray(s.length / 2) { ((Character.digit(s[it * 2], 16) shl 4) + Character.digit(s[it * 2 + 1], 16)).toByte() }
|
||||
|
||||
@Test
|
||||
fun readsTsWritesAndAppendsForTs() {
|
||||
val specPath = System.getenv("SHADE_VAULT_LIVE_SPEC")
|
||||
assumeTrue("SHADE_VAULT_LIVE_SPEC not set — live cross-check skipped", !specPath.isNullOrEmpty())
|
||||
val spec = JSONObject(File(specPath!!).readText())
|
||||
val crypto = TinkProvider()
|
||||
val keys = deriveVaultKeys(crypto, fromHex(spec.getString("masterKey")), spec.getString("app"))
|
||||
val client = VaultClient(crypto, keys, VaultHttpTransport(spec.getString("url")))
|
||||
|
||||
// Read what TS pushed.
|
||||
val head = client.manifest()
|
||||
val want = spec.getJSONObject("files")
|
||||
assertEquals(want.keySet(), head.entries.map { it.path }.toSet())
|
||||
for (entry in head.entries) {
|
||||
assertEquals(entry.path, want.getString(entry.path), sha256(client.readEntry(entry)))
|
||||
}
|
||||
assertTrue("TS pushed a multi-part file", head.entries.any { (it.parts?.size ?: 0) > 1 })
|
||||
assertTrue("TS pushed a compressed file", head.entries.any { it.enc == "deflate-raw" })
|
||||
|
||||
// Append from Kotlin: a compressible note, a 2-part binary, a removal.
|
||||
val note = ("# Fra telefonen\n" + "- [x] lest workspace mens PC-en var av\n".repeat(200)).toByteArray()
|
||||
val big = ByteArray(5 * 1024 * 1024).also { java.util.Random(42).nextBytes(it) }
|
||||
val result = client.edit(System.currentTimeMillis()) { h ->
|
||||
assertEquals(head.seq, h!!.seq)
|
||||
VaultEdit(
|
||||
put = listOf(VaultFile("from-kotlin/note.md", note, mode = "644"), VaultFile("from-kotlin/big.bin", big)),
|
||||
remove = listOf("hello.txt"),
|
||||
)
|
||||
}
|
||||
assertTrue(result.committed)
|
||||
assertEquals(head.seq + 1, result.seq)
|
||||
|
||||
val out = JSONObject()
|
||||
.put("seq", result.seq)
|
||||
.put("removed", "hello.txt")
|
||||
.put("files", JSONObject().put("from-kotlin/note.md", sha256(note)).put("from-kotlin/big.bin", sha256(big)))
|
||||
File(spec.getString("kotlinOut")).writeText(out.toString())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,333 @@
|
||||
package no.zyon.shade
|
||||
|
||||
import no.zyon.shade.crypto.TinkProvider
|
||||
import no.zyon.shade.vault.VAULT_CHUNK_SIZE
|
||||
import no.zyon.shade.vault.VaultEntry
|
||||
import no.zyon.shade.vault.VaultFormatException
|
||||
import no.zyon.shade.vault.VaultKeys
|
||||
import no.zyon.shade.vault.VaultManifest
|
||||
import no.zyon.shade.vault.decodeManifest
|
||||
import no.zyon.shade.vault.deflateRaw
|
||||
import no.zyon.shade.vault.deriveVaultKeys
|
||||
import no.zyon.shade.vault.encodeManifest
|
||||
import no.zyon.shade.vault.entryLocator
|
||||
import no.zyon.shade.vault.entryObjectHashes
|
||||
import no.zyon.shade.vault.inflateRaw
|
||||
import no.zyon.shade.vault.looksCompressed
|
||||
import no.zyon.shade.vault.openEntryBytes
|
||||
import no.zyon.shade.vault.openManifest
|
||||
import no.zyon.shade.vault.openObject
|
||||
import no.zyon.shade.vault.packEntry
|
||||
import no.zyon.shade.vault.sealObject
|
||||
import no.zyon.shade.vault.sealObjectWithNonce
|
||||
import no.zyon.shade.vault.signPayload
|
||||
import no.zyon.shade.vault.signVaultBody
|
||||
import no.zyon.shade.vault.toHex
|
||||
import no.zyon.shade.vault.vaultObjectAad
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import org.junit.Assert.assertArrayEquals
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertThrows
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
import java.io.File
|
||||
import java.util.Base64
|
||||
|
||||
/**
|
||||
* `@shade/vault` v2 against `test-vectors/vault-v2.json` — the cross-language
|
||||
* contract in `docs/vault.md`. Every byte a reader or signer depends on is
|
||||
* compared exactly; generated by `scripts/generate-vectors.ts vault-v2.json`.
|
||||
*/
|
||||
class VaultVectorTest {
|
||||
|
||||
private val crypto = TinkProvider()
|
||||
private val vectors: JSONArray = run {
|
||||
val obj = JSONObject(File("../../test-vectors/vault-v2.json").readText())
|
||||
assertEquals("vault-v2.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 fromHex(s: String): ByteArray =
|
||||
ByteArray(s.length / 2) { ((Character.digit(s[it * 2], 16) shl 4) + Character.digit(s[it * 2 + 1], 16)).toByte() }
|
||||
|
||||
private val keyVector = byPrefix("vault-v2 keys").single()
|
||||
private val keys: VaultKeys = deriveVaultKeys(crypto, fromHex(keyVector.getString("masterKey")), keyVector.getString("app"))
|
||||
|
||||
private fun entryFrom(o: JSONObject): VaultEntry = VaultEntry(
|
||||
path = o.getString("path"),
|
||||
hash = o.getString("hash"),
|
||||
size = o.getLong("size"),
|
||||
mode = if (o.has("mode")) o.getString("mode") else null,
|
||||
enc = if (o.has("enc") && !o.isNull("enc")) o.getString("enc") else null,
|
||||
parts = o.optJSONArray("parts")?.let { a -> List(a.length()) { a.getString(it) } },
|
||||
)
|
||||
|
||||
private fun manifestFrom(o: JSONObject): VaultManifest {
|
||||
val a = o.getJSONArray("entries")
|
||||
return VaultManifest(
|
||||
version = o.getInt("version"),
|
||||
seq = o.getLong("seq"),
|
||||
at = o.getLong("at"),
|
||||
message = if (o.has("message")) o.getString("message") else null,
|
||||
entries = List(a.length()) { entryFrom(a.getJSONObject(it)) },
|
||||
)
|
||||
}
|
||||
|
||||
/** Vector JSON → plain Kotlin values, keeping key order (org.json does not, but only top-level is sorted anyway). */
|
||||
private fun toKotlin(v: Any?): Any = when (v) {
|
||||
is JSONObject -> LinkedHashMap<String, Any>().apply { for (k in v.keys()) put(k, toKotlin(v.get(k))) }
|
||||
is JSONArray -> List(v.length()) { toKotlin(v.get(it)) }
|
||||
is Int -> v.toLong()
|
||||
is Long, is String, is Boolean -> v
|
||||
else -> error("unexpected vector value ${v?.javaClass}")
|
||||
}
|
||||
|
||||
// ─── Keys ────────────────────────────────────────────────
|
||||
|
||||
@Test
|
||||
fun keysMatchVector() {
|
||||
assertEquals(keyVector.getString("vaultId"), keys.vaultId)
|
||||
assertEquals(keyVector.getString("contentKey"), toHex(keys.contentKey))
|
||||
assertEquals(keyVector.getString("signingSeed"), toHex(keys.signingSeed))
|
||||
assertEquals(keyVector.getString("publicKey"), toHex(keys.publicKey))
|
||||
assertEquals(keyVector.getString("objectAad"), toHex(vaultObjectAad(keys.vaultId)))
|
||||
assertEquals(keyVector.getString("objectAadUtf8"), String(vaultObjectAad(keys.vaultId), Charsets.UTF_8))
|
||||
}
|
||||
|
||||
// ─── Entries ─────────────────────────────────────────────
|
||||
|
||||
@Test
|
||||
fun entryPackingMatchesVectors() {
|
||||
for (v in byPrefix("vault-v2 entry")) {
|
||||
val what = v.getString("description")
|
||||
val plaintext = fromHex(v.getString("plaintext"))
|
||||
val chunkSize = v.getInt("chunkSize")
|
||||
val packed = packEntry(plaintext, chunkSize)
|
||||
val wantEnc = if (v.isNull("enc")) null else v.getString("enc")
|
||||
assertEquals("$what: enc", wantEnc, packed.enc)
|
||||
// Compressed bytes need not match zlib-for-zlib (readers never
|
||||
// depend on them; the JDK's zlib and Bun's diverge on longer
|
||||
// inputs) — but ours must inflate back, and the vector's must too.
|
||||
if (packed.enc != null) {
|
||||
assertArrayEquals("$what: own stored inflates", plaintext, inflateRaw(packed.stored, plaintext.size.toLong()))
|
||||
assertArrayEquals("$what: vector stored inflates", plaintext, inflateRaw(fromHex(v.getString("stored")), plaintext.size.toLong()))
|
||||
} else {
|
||||
assertEquals("$what: stored", v.getString("stored"), toHex(packed.stored))
|
||||
}
|
||||
|
||||
// Splitting and sealing are exact: chunk the vector's stored bytes
|
||||
// the way packEntry does and seal each slice under the pinned nonce.
|
||||
val stored = fromHex(v.getString("stored"))
|
||||
val chunks = stored.toList().chunked(chunkSize).map { it.toByteArray() }.ifEmpty { listOf(ByteArray(0)) }
|
||||
val parts = v.getJSONArray("parts")
|
||||
assertEquals("$what: part count", parts.length(), chunks.size)
|
||||
val sealed = (0 until parts.length()).map { i ->
|
||||
val p = parts.getJSONObject(i)
|
||||
assertEquals("$what: part $i plaintext", p.getString("plaintext"), toHex(chunks[i]))
|
||||
val obj = sealObjectWithNonce(keys.contentKey, keys.vaultId, chunks[i], fromHex(p.getString("nonce")))
|
||||
assertEquals("$what: part $i wire", p.getString("wire"), toHex(obj.bytes))
|
||||
assertEquals("$what: part $i hash", p.getString("hash"), obj.hash)
|
||||
obj
|
||||
}
|
||||
val vectorPacked = no.zyon.shade.vault.PackedEntry(wantEnc, stored, chunks)
|
||||
|
||||
val want = entryFrom(v.getJSONObject("entry"))
|
||||
val loc = entryLocator(vectorPacked, sealed)
|
||||
assertEquals("$what: hash", want.hash, loc.hash)
|
||||
assertEquals("$what: parts", want.parts, loc.parts)
|
||||
assertEquals("$what: locator enc", want.enc, loc.enc)
|
||||
assertEquals("$what: object hashes", sealed.map { it.hash }, entryObjectHashes(want))
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun entryReadsBackFromWire() {
|
||||
for (v in byPrefix("vault-v2 entry")) {
|
||||
val entry = entryFrom(v.getJSONObject("entry"))
|
||||
val parts = v.getJSONArray("parts")
|
||||
val wires = List(parts.length()) { fromHex(parts.getJSONObject(it).getString("wire")) }
|
||||
val plain = openEntryBytes(crypto, keys.contentKey, keys.vaultId, entry, wires)
|
||||
assertEquals(v.getString("description"), v.getString("plaintext"), toHex(plain))
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun entryReadRefusesWhatDoesNotAddUp() {
|
||||
val v = byPrefix("vault-v2 entry: multi-part").single()
|
||||
val entry = entryFrom(v.getJSONObject("entry"))
|
||||
val parts = v.getJSONArray("parts")
|
||||
val wires = List(parts.length()) { fromHex(parts.getJSONObject(it).getString("wire")) }
|
||||
|
||||
// Parts swapped: each fetched object must hash to its slot.
|
||||
assertThrows(VaultFormatException::class.java) {
|
||||
openEntryBytes(crypto, keys.contentKey, keys.vaultId, entry, listOf(wires[1], wires[0]) + wires.drop(2))
|
||||
}
|
||||
// A part dropped from the list (consistently, so every hash checks out).
|
||||
val shorter = entry.copy(parts = entry.parts!!.dropLast(1))
|
||||
assertThrows(VaultFormatException::class.java) {
|
||||
openEntryBytes(crypto, keys.contentKey, keys.vaultId, shorter, wires.dropLast(1))
|
||||
}
|
||||
// Size lies.
|
||||
assertThrows(VaultFormatException::class.java) {
|
||||
openEntryBytes(crypto, keys.contentKey, keys.vaultId, entry.copy(size = entry.size + 1), wires)
|
||||
}
|
||||
// An encoding this reader does not know is refused, not guessed.
|
||||
assertThrows(VaultFormatException::class.java) {
|
||||
openEntryBytes(crypto, keys.contentKey, keys.vaultId, entry.copy(enc = "zstd"), wires)
|
||||
}
|
||||
// hash must equal parts[0].
|
||||
assertThrows(VaultFormatException::class.java) {
|
||||
openEntryBytes(crypto, keys.contentKey, keys.vaultId, entry.copy(hash = entry.parts!![1]), wires)
|
||||
}
|
||||
// A flipped ciphertext bit no longer matches its name.
|
||||
val tampered = wires[0].copyOf().also { it[20] = (it[20].toInt() xor 1).toByte() }
|
||||
assertThrows(VaultFormatException::class.java) {
|
||||
openObject(crypto, keys.contentKey, keys.vaultId, entry.parts!![0], tampered)
|
||||
}
|
||||
// Right name, wrong vault: the AAD binds the vaultId.
|
||||
assertThrows(VaultFormatException::class.java) {
|
||||
openObject(crypto, keys.contentKey, "0".repeat(64), entry.parts!![0], wires[0])
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Manifests ───────────────────────────────────────────
|
||||
|
||||
@Test
|
||||
fun manifestsDecodeFromWire() {
|
||||
for (prefix in listOf("vault-v2 manifest v2", "vault-v2 manifest v1")) {
|
||||
val v = byPrefix(prefix).single()
|
||||
val want = manifestFrom(v.getJSONObject("manifest"))
|
||||
val got = openManifest(crypto, keys.contentKey, keys.vaultId, v.getString("hash"), fromHex(v.getString("wire")))
|
||||
assertEquals(prefix, want, got)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun manifestsEncodeLikeTypeScript() {
|
||||
for (prefix in listOf("vault-v2 manifest v2", "vault-v2 manifest v1")) {
|
||||
val v = byPrefix(prefix).single()
|
||||
val m = manifestFrom(v.getJSONObject("manifest"))
|
||||
val plain = encodeManifest(m)
|
||||
// Key order is not contract, but writing it in TS order makes the
|
||||
// JSON identical; v1 is that JSON, so its whole plaintext matches.
|
||||
val ownJson = if (m.version == 2) String(inflateRaw(plain.copyOfRange(4, plain.size), 1L shl 20)) else String(plain)
|
||||
assertEquals("$prefix: json", v.getString("json"), ownJson)
|
||||
assertArrayEquals("$prefix: magic", if (m.version == 2) "SVM2".toByteArray() else "{\"v".toByteArray(), plain.copyOf(if (m.version == 2) 4 else 3))
|
||||
if (m.version == 1) assertEquals("$prefix: plaintext", v.getString("plaintext"), toHex(plain))
|
||||
val sealed = sealObjectWithNonce(keys.contentKey, keys.vaultId, fromHex(v.getString("plaintext")), fromHex(v.getString("nonce")))
|
||||
assertEquals("$prefix: wire", v.getString("wire"), toHex(sealed.bytes))
|
||||
assertEquals("$prefix: hash", v.getString("hash"), sealed.hash)
|
||||
assertEquals("$prefix: round trip", m, decodeManifest(plain))
|
||||
}
|
||||
val v2 = byPrefix("vault-v2 manifest v2").single()
|
||||
val json = String(inflateRaw(fromHex(v2.getString("plaintext")).copyOfRange(4, fromHex(v2.getString("plaintext")).size), 1 shl 20))
|
||||
assertEquals(v2.getString("json"), json)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun manifestRefusesUnknownVersion() {
|
||||
for (bad in listOf("""{"version":3,"seq":1,"at":1,"entries":[]}""", """{"version":"2","seq":1,"at":1,"entries":[]}""", """{"seq":1,"at":1,"entries":[]}""")) {
|
||||
assertThrows(bad, VaultFormatException::class.java) { decodeManifest(bad.toByteArray()) }
|
||||
}
|
||||
val v3 = byteArrayOf(0x53, 0x56, 0x4d, 0x32) + deflateRaw("""{"version":3,"seq":1,"at":1,"entries":[]}""".toByteArray())
|
||||
assertThrows(VaultFormatException::class.java) { decodeManifest(v3) }
|
||||
}
|
||||
|
||||
@Test
|
||||
fun freshSealOpensAndRoundTripsAManifest() {
|
||||
val m = manifestFrom(byPrefix("vault-v2 manifest v2").single().getJSONObject("manifest"))
|
||||
val a = sealObject(crypto, keys.contentKey, keys.vaultId, encodeManifest(m))
|
||||
val b = sealObject(crypto, keys.contentKey, keys.vaultId, encodeManifest(m))
|
||||
// Fresh nonce: same plaintext, different names — why unchanged entries are reused, not re-sealed.
|
||||
assertFalse(a.hash == b.hash)
|
||||
assertEquals(m, openManifest(crypto, keys.contentKey, keys.vaultId, a.hash, a.bytes))
|
||||
}
|
||||
|
||||
// ─── Signing ─────────────────────────────────────────────
|
||||
|
||||
@Test
|
||||
fun signedBodiesMatchVectors() {
|
||||
for (v in byPrefix("vault-v2 signed")) {
|
||||
val what = v.getString("description")
|
||||
@Suppress("UNCHECKED_CAST")
|
||||
val body = toKotlin(v.getJSONObject("body")) as Map<String, Any>
|
||||
val signed = signPayload(crypto, keys.signingSeed, body, v.getLong("signedAt"))
|
||||
assertEquals("$what: canonical", v.getString("canonical"), String(signed.canonical, Charsets.UTF_8))
|
||||
assertEquals("$what: canonicalHex", v.getString("canonicalHex"), toHex(signed.canonical))
|
||||
assertEquals("$what: signature", v.getString("signature"), toHex(signed.signature))
|
||||
|
||||
val wire = JSONObject(signed.json)
|
||||
assertEquals(v.getString("signatureBase64"), wire.getString("signature"))
|
||||
assertEquals(v.getLong("signedAt"), wire.getLong("signedAt"))
|
||||
assertTrue(crypto.verify(keys.publicKey, signed.canonical, Base64.getDecoder().decode(wire.getString("signature"))))
|
||||
|
||||
// The vault helper adds publicKey itself and must land on the same bytes.
|
||||
val withoutKey = body.filterKeys { it != "publicKey" }
|
||||
val viaKeys = signVaultBody(crypto, keys, withoutKey, v.getLong("signedAt"))
|
||||
assertArrayEquals("$what: signVaultBody", signed.canonical, viaKeys.canonical)
|
||||
assertArrayEquals(signed.signature, viaKeys.signature)
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Packing rules ───────────────────────────────────────
|
||||
|
||||
@Test
|
||||
fun packingRules() {
|
||||
// Empty file: one empty part, never compressed.
|
||||
val empty = packEntry(ByteArray(0))
|
||||
assertNull(empty.enc)
|
||||
assertEquals(1, empty.chunks.size)
|
||||
assertEquals(0, empty.chunks[0].size)
|
||||
|
||||
// Random bytes do not shrink ≥5 %: stored as-is.
|
||||
val random = ByteArray(10_000).also { java.util.Random(7).nextBytes(it) }
|
||||
assertNull(packEntry(random).enc)
|
||||
|
||||
// Exactly at a chunk boundary: no trailing empty part.
|
||||
val twoChunks = packEntry(random, chunkSize = 5_000)
|
||||
assertEquals(2, twoChunks.chunks.size)
|
||||
assertEquals(VAULT_CHUNK_SIZE, 4 * 1024 * 1024)
|
||||
|
||||
// Compressible text compresses and inflates back.
|
||||
val text = "hei hei hei hei\n".repeat(500).toByteArray()
|
||||
val p = packEntry(text)
|
||||
assertEquals("deflate-raw", p.enc)
|
||||
assertArrayEquals(text, inflateRaw(p.stored, text.size.toLong()))
|
||||
|
||||
val magics = listOf(
|
||||
byteArrayOf(0x89.toByte(), 0x50, 0x4e, 0x47),
|
||||
byteArrayOf(0xff.toByte(), 0xd8.toByte(), 0xff.toByte()),
|
||||
"RIFF\u0000\u0000\u0000\u0000WEBP".toByteArray(),
|
||||
"\u0000\u0000\u0000\u0018ftypmp42".toByteArray(),
|
||||
"GIF89a".toByteArray(),
|
||||
byteArrayOf(0x1f, 0x8b.toByte()),
|
||||
"PK\u0003\u0004".toByteArray(),
|
||||
)
|
||||
for (m in magics) {
|
||||
assertTrue(toHex(m), looksCompressed(m))
|
||||
assertNull(packEntry(m + ByteArray(4000)).enc)
|
||||
}
|
||||
assertFalse(looksCompressed("RIFF\u0000\u0000\u0000\u0000WAVE".toByteArray()))
|
||||
assertFalse(looksCompressed("P".toByteArray()))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun inflateIsStrictAboutTheStreamEnd() {
|
||||
val text = "abcabcabc-".repeat(1000).toByteArray()
|
||||
val d = deflateRaw(text)
|
||||
assertArrayEquals(text, inflateRaw(d, text.size.toLong()))
|
||||
assertThrows(VaultFormatException::class.java) { inflateRaw(d.copyOf(d.size - 3), text.size.toLong()) }
|
||||
assertThrows(VaultFormatException::class.java) { inflateRaw(d + byteArrayOf(1, 2, 3), text.size.toLong()) }
|
||||
assertThrows(VaultFormatException::class.java) { inflateRaw(d, text.size.toLong() - 1) }
|
||||
assertThrows(VaultFormatException::class.java) { inflateRaw(byteArrayOf(0xff.toByte(), 0xff.toByte(), 0xff.toByte()), 100) }
|
||||
assertArrayEquals(ByteArray(0), inflateRaw(deflateRaw(ByteArray(0)), 0))
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user