From fb7f2e55c0a7cbfca8100af40e0a9e33da315c50 Mon Sep 17 00:00:00 2001 From: Sterister Date: Fri, 16 Oct 2026 13:18:01 +0200 Subject: [PATCH] =?UTF-8?q?feat(android):=20Kotlin-vaulten=20=E2=80=94=20v?= =?UTF-8?q?ault=20v2=20lest=20og=20skrevet=20fra=20telefonen?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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) --- ...ault-v2-og-kotlin-vaulten-4-14-0-4-14-1.md | 20 + android/shade-android/build.gradle.kts | 3 + .../kotlin/no/zyon/shade/blob/BlobClient.kt | 57 +-- .../main/kotlin/no/zyon/shade/blob/BlobKdf.kt | 17 +- .../zyon/shade/serialization/CanonicalJson.kt | 112 ++++++ .../kotlin/no/zyon/shade/vault/VaultClient.kt | 223 +++++++++++ .../kotlin/no/zyon/shade/vault/VaultCrypto.kt | 364 ++++++++++++++++++ .../kotlin/no/zyon/shade/vault/VaultErrors.kt | 44 +++ .../kotlin/no/zyon/shade/vault/VaultKeys.kt | 80 ++++ .../kotlin/no/zyon/shade/vault/VaultModels.kt | 183 +++++++++ .../no/zyon/shade/vault/VaultSigning.kt | 67 ++++ .../no/zyon/shade/vault/VaultTransport.kt | 167 ++++++++ .../kotlin/no/zyon/shade/VaultClientTest.kt | 280 ++++++++++++++ .../kotlin/no/zyon/shade/VaultLiveTest.kt | 73 ++++ .../kotlin/no/zyon/shade/VaultVectorTest.kt | 333 ++++++++++++++++ scripts/vault-live-kotlin.ts | 107 +++++ 16 files changed, 2069 insertions(+), 61 deletions(-) create mode 100644 .scaffold/logs/2026-10-16-vault-v2-og-kotlin-vaulten-4-14-0-4-14-1.md create mode 100644 android/shade-android/src/main/kotlin/no/zyon/shade/serialization/CanonicalJson.kt create mode 100644 android/shade-android/src/main/kotlin/no/zyon/shade/vault/VaultClient.kt create mode 100644 android/shade-android/src/main/kotlin/no/zyon/shade/vault/VaultCrypto.kt create mode 100644 android/shade-android/src/main/kotlin/no/zyon/shade/vault/VaultErrors.kt create mode 100644 android/shade-android/src/main/kotlin/no/zyon/shade/vault/VaultKeys.kt create mode 100644 android/shade-android/src/main/kotlin/no/zyon/shade/vault/VaultModels.kt create mode 100644 android/shade-android/src/main/kotlin/no/zyon/shade/vault/VaultSigning.kt create mode 100644 android/shade-android/src/main/kotlin/no/zyon/shade/vault/VaultTransport.kt create mode 100644 android/shade-android/src/test/kotlin/no/zyon/shade/VaultClientTest.kt create mode 100644 android/shade-android/src/test/kotlin/no/zyon/shade/VaultLiveTest.kt create mode 100644 android/shade-android/src/test/kotlin/no/zyon/shade/VaultVectorTest.kt create mode 100644 scripts/vault-live-kotlin.ts diff --git a/.scaffold/logs/2026-10-16-vault-v2-og-kotlin-vaulten-4-14-0-4-14-1.md b/.scaffold/logs/2026-10-16-vault-v2-og-kotlin-vaulten-4-14-0-4-14-1.md new file mode 100644 index 0000000..46381f2 --- /dev/null +++ b/.scaffold/logs/2026-10-16-vault-v2-og-kotlin-vaulten-4-14-0-4-14-1.md @@ -0,0 +1,20 @@ +--- +title: "Vault v2 og Kotlin-vaulten (4.14.0/4.14.1)" +date: 2026-10-16 +author: "Claude" +--- + +Shade fikk det Scaffold-vaulten trengte for å bli telefonens kilde når PC-en er av, uten at serveren fylles opp. + +- **4.14.0 — vault v2:** + - Filer komprimeres med deflate-raw når det lønner seg, og deles i forseglede biter på 4 MiB. Manifestene komprimeres også (`SVM2`). + - Push bruker en lokal indeks og laster ikke ned forrige versjon. En push uten endringer committer ingenting. + - Ny lat lesing med `manifest` og `readEntry`. + - Relayet registrerer hvilke objekter hver versjon refererer til, og har fått en signert `prune`-rute. SQLite-lageret migrerer seg selv. + - Kryss-språk-vektorene ligger i `test-vectors/vault-v2.json`. +- **4.14.1 — `edit`:** endrer noen få filer mot hodet som faktisk ble lest, og prøver igjen ved `SEQ_CONFLICT`. Dette er det en kø med to skrivere trenger. `push` publiserer hele samlingen, og ville mistet en fil som en annen enhet la til i mellomtiden. +- **Kotlin, `no.zyon.shade.vault`:** en full port av v2 (lese, forsegle, signere, `edit`). + - 71 Android-tester er grønne. + - Live kryss-sjekk TS↔Kotlin mot ekte vault-ruter (`scripts/vault-live-kotlin.ts`). + +Verifisert: shade-vault 61, storage-sqlite 47 og shade-server 55 grønne, og typecheck er ren for alle 26 pakkene. Publisert til Gitea-registeret. Commitet lokalt og tagget (`v4.14.0`, `v4.14.1`), men ikke pushet til remote. Kotlin-filene i `android/` er ennå ikke commitet. diff --git a/android/shade-android/build.gradle.kts b/android/shade-android/build.gradle.kts index f06b70b..1834761 100644 --- a/android/shade-android/build.gradle.kts +++ b/android/shade-android/build.gradle.kts @@ -49,6 +49,9 @@ dependencies { tasks.withType().configureEach { useJUnit() + // VaultLiveTest is gated on this; as an input, a new spec (a new live + // relay) reruns the tests instead of reporting a stale UP-TO-DATE. + inputs.property("shadeVaultLiveSpec", System.getenv("SHADE_VAULT_LIVE_SPEC") ?: "") testLogging { events("passed", "failed", "skipped") showStandardStreams = false diff --git a/android/shade-android/src/main/kotlin/no/zyon/shade/blob/BlobClient.kt b/android/shade-android/src/main/kotlin/no/zyon/shade/blob/BlobClient.kt index f79aa4d..0e11d7a 100644 --- a/android/shade-android/src/main/kotlin/no/zyon/shade/blob/BlobClient.kt +++ b/android/shade-android/src/main/kotlin/no/zyon/shade/blob/BlobClient.kt @@ -1,6 +1,7 @@ package no.zyon.shade.blob import no.zyon.shade.crypto.CryptoProvider +import no.zyon.shade.serialization.canonicalJson import org.json.JSONObject import java.net.URI import java.net.http.HttpClient @@ -187,62 +188,6 @@ class BlobClient( } } -/** - * Mirror of TS `signPayload`'s canonicalization: sorted keys, compact - * JSON, signature field absent. Only handles the subset of types we - * need (strings + longs + base64 strings) — keeping the implementation - * narrow so it can't accidentally diverge from `JSON.stringify` on - * structurally-different inputs. - */ -internal fun canonicalJson(map: Map): String { - val sb = StringBuilder() - sb.append('{') - var first = true - for ((key, value) in map.toSortedMap()) { - if (!first) sb.append(',') - first = false - appendJsonString(sb, key) - sb.append(':') - appendJsonValue(sb, value) - } - sb.append('}') - return sb.toString() -} - -private fun appendJsonValue(sb: StringBuilder, value: Any) { - when (value) { - is String -> appendJsonString(sb, value) - is Long, is Int -> sb.append(value.toString()) - is Boolean -> sb.append(value.toString()) - else -> throw IllegalArgumentException( - "canonicalJson: unsupported value type ${value::class.java}", - ) - } -} - -private fun appendJsonString(sb: StringBuilder, s: String) { - sb.append('"') - for (c in s) { - when (c) { - '\\' -> sb.append("\\\\") - '"' -> sb.append("\\\"") - '\b' -> sb.append("\\b") - '\u000C' -> sb.append("\\f") - '\n' -> sb.append("\\n") - '\r' -> sb.append("\\r") - '\t' -> sb.append("\\t") - else -> { - if (c.code < 0x20) { - sb.append("\\u").append("%04x".format(c.code)) - } else { - sb.append(c) - } - } - } - } - sb.append('"') -} - class BlobClientException( val code: String, val statusCode: Int, diff --git a/android/shade-android/src/main/kotlin/no/zyon/shade/blob/BlobKdf.kt b/android/shade-android/src/main/kotlin/no/zyon/shade/blob/BlobKdf.kt index b43ffed..d401eb5 100644 --- a/android/shade-android/src/main/kotlin/no/zyon/shade/blob/BlobKdf.kt +++ b/android/shade-android/src/main/kotlin/no/zyon/shade/blob/BlobKdf.kt @@ -1,6 +1,6 @@ package no.zyon.shade.blob -import com.google.crypto.tink.subtle.Ed25519Sign +import org.bouncycastle.crypto.params.Ed25519PrivateKeyParameters import no.zyon.shade.crypto.CryptoProvider /** @@ -72,13 +72,20 @@ fun deriveBlobSigningSeed(crypto: CryptoProvider, masterKey: ByteArray, app: Str /** * Recover the Ed25519 public key from a 32-byte seed. Mirrors - * `@shade/crypto-web`'s `ed25519PublicKeyFromSeed`. Tink's - * `Ed25519Sign.KeyPair.newKeyPairFromSeed(seed)` exposes both halves; - * we discard the private half here. + * `@shade/crypto-web`'s `ed25519PublicKeyFromSeed`. + * + * BouncyCastle rather than Tink, although the rest of the module signs with + * Tink: this is the one primitive the vault and blob code use OUTSIDE the + * injected [CryptoProvider], so whatever it calls is a hard dependency of + * every app that reads a vault. An Android app cannot take JVM Tink (it + * drags in full `protobuf-java`, which collides with Firebase's + * `protobuf-javalite`), while BouncyCastle is already here for scrypt and + * already in every app that embeds this module. RFC 8032 fixes the result, + * so the two produce the same bytes — the blob and vault vectors pin it. */ fun ed25519PublicKeyFromSeed(seed: ByteArray): ByteArray { require(seed.size == 32) { "Ed25519 seed must be 32 bytes" } - return Ed25519Sign.KeyPair.newKeyPairFromSeed(seed).publicKey + return Ed25519PrivateKeyParameters(seed, 0).generatePublicKey().encoded } /** Convert a 32-byte slotId into the lowercase-hex wire form (64 chars). */ diff --git a/android/shade-android/src/main/kotlin/no/zyon/shade/serialization/CanonicalJson.kt b/android/shade-android/src/main/kotlin/no/zyon/shade/serialization/CanonicalJson.kt new file mode 100644 index 0000000..9ffb846 --- /dev/null +++ b/android/shade-android/src/main/kotlin/no/zyon/shade/serialization/CanonicalJson.kt @@ -0,0 +1,112 @@ +package no.zyon.shade.serialization + +/** + * JSON written exactly the way JavaScript's `JSON.stringify` writes it — + * because signatures are computed over these bytes, and a TS relay verifies + * them over *its* re-serialisation of the parsed body. + * + * Two entry points: + * + * - [canonicalJson]: mirror of TS `canonicalizePayload` (`@shade/server`). + * Top-level keys sorted, nested values serialised as-is — `JSON.stringify` + * of an object built by inserting the sorted keys, so a nested object keeps + * its insertion order and is NOT sorted. The vault's signed bodies carry an + * array of hashes and an array of seqs, which is why arrays are supported. + * - [stringifyJson]: plain `JSON.stringify` of a value, insertion order kept. + * Used where key order is not part of any contract but reproducing the TS + * bytes keeps vector tests exact (vault manifests). + * + * Deliberately narrow: strings, integers, booleans, null, lists and string- + * keyed maps. Floating-point numbers are refused rather than formatted — + * JavaScript's shortest-round-trip number printing is not something to + * approximate in a signature path, and no Shade payload needs it. + */ +internal fun canonicalJson(map: Map): String { + val sb = StringBuilder() + sb.append('{') + var first = true + for ((key, value) in map.toSortedMap()) { + if (!first) sb.append(',') + first = false + appendJsonString(sb, key) + sb.append(':') + appendJsonValue(sb, value) + } + sb.append('}') + return sb.toString() +} + +/** `JSON.stringify(value)` — maps keep their iteration (insertion) order. */ +internal fun stringifyJson(value: Any?): String { + val sb = StringBuilder() + appendJsonValue(sb, value) + return sb.toString() +} + +private fun appendJsonValue(sb: StringBuilder, value: Any?) { + when (value) { + null -> sb.append("null") + is String -> appendJsonString(sb, value) + is Long, is Int, is Short, is Byte -> sb.append(value.toString()) + is Boolean -> sb.append(value.toString()) + is Map<*, *> -> { + sb.append('{') + var first = true + for ((k, v) in value) { + require(k is String) { "stringifyJson: map keys must be strings, got ${k?.javaClass}" } + if (!first) sb.append(',') + first = false + appendJsonString(sb, k) + sb.append(':') + appendJsonValue(sb, v) + } + sb.append('}') + } + is Iterable<*> -> { + sb.append('[') + var first = true + for (v in value) { + if (!first) sb.append(',') + first = false + appendJsonValue(sb, v) + } + sb.append(']') + } + is Array<*> -> appendJsonValue(sb, value.asList()) + else -> throw IllegalArgumentException( + "canonicalJson: unsupported value type ${value::class.java}", + ) + } +} + +/** + * `JSON.stringify` string escaping (ES2019 "well-formed"): the two-character + * escapes for `" \ \b \f \n \r \t`, `\u00XX` (lowercase) for other control + * characters and for lone surrogates, everything else — including non-ASCII + * — emitted literally and left to UTF-8. + */ +private fun appendJsonString(sb: StringBuilder, s: String) { + sb.append('"') + var i = 0 + while (i < s.length) { + val c = s[i] + when { + c == '\\' -> sb.append("\\\\") + c == '"' -> sb.append("\\\"") + c == '\b' -> sb.append("\\b") + c == '\u000C' -> sb.append("\\f") + c == '\n' -> sb.append("\\n") + c == '\r' -> sb.append("\\r") + c == '\t' -> sb.append("\\t") + c.code < 0x20 -> sb.append("\\u").append("%04x".format(c.code)) + c.isHighSurrogate() && i + 1 < s.length && s[i + 1].isLowSurrogate() -> { + sb.append(c).append(s[i + 1]) + i++ + } + c.isSurrogate() -> sb.append("\\u").append("%04x".format(c.code)) + else -> sb.append(c) + } + i++ + } + sb.append('"') +} diff --git a/android/shade-android/src/main/kotlin/no/zyon/shade/vault/VaultClient.kt b/android/shade-android/src/main/kotlin/no/zyon/shade/vault/VaultClient.kt new file mode 100644 index 0000000..61d8493 --- /dev/null +++ b/android/shade-android/src/main/kotlin/no/zyon/shade/vault/VaultClient.kt @@ -0,0 +1,223 @@ +package no.zyon.shade.vault + +import no.zyon.shade.crypto.CryptoProvider +import java.security.MessageDigest +import java.util.Base64 + +/** A file as the app sees it, before encryption. */ +class VaultFile(val path: String, val bytes: ByteArray, val mode: String? = null) + +/** + * A few files changed, for [VaultClient.edit] — mirror of TS `VaultEdit`. + */ +class VaultEdit( + /** Files to add, or to replace at the same path. Paths must be distinct. */ + val put: List = emptyList(), + /** Paths to drop. A path that is not there is ignored. */ + val remove: List = emptyList(), +) + +/** What [VaultClient.edit] did. */ +data class VaultEditResult( + /** The head after the edit: the new version, or the unchanged head. */ + val seq: Long, + /** False when the edit changed nothing and no version was committed. */ + val committed: Boolean, +) + +/** A whole version, decrypted. */ +class VaultPull(val manifest: VaultManifest, val files: Map) + +/** + * The client half of `@shade/vault` v2 for a phone: read a vault whose writer + * (the PC) may be switched off, and edit a vault several devices write to — + * such as a queue of changes the phone appends to and the PC drains. + * + * What it deliberately does not port is TS `push` (publish a whole + * collection from local files, with an index): a phone is not the source of + * truth for a workspace, and a whole-collection push from a stale view is + * exactly how another device's latest file gets lost. [edit] is the write + * primitive here. + * + * Blocking, like the transport: call from a background dispatcher. + * + * @param clock wall clock for `signedAt` — the relay rejects signatures older + * than five minutes, so this must be real time outside tests. + * @param chunkSize part size; tests only. Real writers use [VAULT_CHUNK_SIZE] + * so every implementation splits identically. + */ +class VaultClient( + private val crypto: CryptoProvider, + private val keys: VaultKeys, + private val transport: VaultTransport, + private val chunkSize: Int = VAULT_CHUNK_SIZE, + private val clock: () -> Long = System::currentTimeMillis, +) { + val vaultId: String get() = keys.vaultId + + /** Version history, newest last. [limit] counts back from the head. */ + fun log(limit: Int? = null): VaultLog = transport.log(keys.vaultId, limit) + + /** + * Fetch and open just a version's manifest; defaults to the head. The + * cheap way to list a thousand-file workspace: one download, then + * [readEntry] only what the user opens. + * + * @throws VaultException `NOT_FOUND` when there is no such version + * (including the head of an empty vault — see [headManifest]). + */ + fun manifest(seq: Long? = null): VaultManifest { + // The head needs only the newest row; an older version needs the log + // to find its row, since `limit` counts back from the head. + val log = transport.log(keys.vaultId, if (seq == null) 1 else null) + val wanted = seq ?: log.head + val row = log.entries.firstOrNull { it.seq == wanted } + ?: throw VaultException(VaultException.CODE_NOT_FOUND, 0, "vault has no version $wanted") + return openRow(row) + } + + /** The head manifest, or null when nothing has ever been committed. */ + fun headManifest(): VaultManifest? { + val log = transport.log(keys.vaultId, 1) + val row = log.entries.firstOrNull { it.seq == log.head } ?: return null + return openRow(row) + } + + /** Fetch, verify, decrypt and reassemble one file of a manifest. */ + fun readEntry(entry: VaultEntry): ByteArray { + val objects = entryObjectHashes(entry).map { transport.get(keys.vaultId, it) } + return openEntryBytes(crypto, keys.contentKey, keys.vaultId, entry, objects) + } + + /** Fetch a version and decrypt all of it; defaults to the head. */ + fun pull(seq: Long? = null): VaultPull { + val manifest = manifest(seq) + val files = LinkedHashMap() + for (entry in manifest.entries) files[entry.path] = readEntry(entry) + return VaultPull(manifest, files) + } + + /** + * Change a few files against the head that was actually read, and only it + * — mirror of TS `VaultClient.edit`. + * + * Reads the head, lets [change] decide from exactly that manifest (null + * for an empty vault), keeps every entry it did not touch as-is — same + * hash, same parts, never re-sealed — and commits `head + 1`. If another + * device committed in between, the relay answers SEQ_CONFLICT and this + * starts over from the new head, calling [change] again: it must be a + * pure decision about the manifest it is given. + * + * Returning null, or an edit with no puts that removes nothing present, + * commits nothing. + * + * One deliberate difference from TS: a file sealed in a lost attempt is + * not sealed again on the retry. Its objects are already on the relay + * (covered by the prune grace period), and on a phone the upload is the + * expensive part. The committed manifest is the same either way. + * + * @throws VaultException SEQ_CONFLICT after [maxAttempts] lost races, or + * any other relay refusal at once. + * @throws VaultFormatException when the head cannot be read — editing on + * top of a manifest this client cannot parse would drop its files. + */ + fun edit(at: Long, maxAttempts: Int = 5, change: (VaultManifest?) -> VaultEdit?): VaultEditResult { + val attempts = maxOf(1, maxAttempts) + // Plaintext digest + path → the entry its upload produced, across attempts. + val sealedThisEdit = HashMap() + var attempt = 1 + while (true) { + val log = transport.log(keys.vaultId, 1) + val head = log.head + val row = log.entries.firstOrNull { it.seq == head } + val manifest = row?.let { openRow(it) } + val edit = change(manifest) + val put = edit?.put.orEmpty() + val remove = edit?.remove.orEmpty().toSet() + val current = manifest?.entries.orEmpty() + val replaced = put.map { it.path }.toSet() + require(replaced.size == put.size) { "VaultEdit.put lists the same path more than once" } + if (put.isEmpty() && current.none { it.path in remove }) { + return VaultEditResult(seq = head, committed = false) + } + + val entries = current.filterTo(ArrayList()) { it.path !in remove && it.path !in replaced } + for (file in put) { + val key = sha256Hex(file.bytes) + "\u0000" + file.path + val located = sealedThisEdit.getOrPut(key) { upload(file) } + entries.add(located.copy(mode = file.mode)) + } + + try { + val seq = commitManifest(entries, head + 1, at) + return VaultEditResult(seq = seq, committed = true) + } catch (e: VaultException) { + // Only a lost race is worth another go; the manifest object + // just uploaded is an orphan the relay's GC will collect. + if (attempt >= attempts || !e.isSeqConflict) throw e + } + attempt++ + } + } + + /** Add or replace [files], keeping everything else — [edit] with only puts. */ + fun append(files: List, at: Long, maxAttempts: Int = 5): VaultEditResult = + edit(at, maxAttempts) { VaultEdit(put = files) } + + /** + * Drop every version not in [keep] and let the relay delete objects only + * those versions used. [keep] must include the current head. + */ + fun prune(keep: List): VaultPruneResult = + transport.prune(keys.vaultId, sign(mapOf("keep" to keep))) + + // ─── Internals ─────────────────────────────────────────── + + /** Seal one file into fresh objects and PUT them; the entry, without mode. */ + private fun upload(file: VaultFile): VaultEntry { + val sealed = sealEntry(crypto, keys.contentKey, keys.vaultId, file.bytes, chunkSize) + // No have-check: every object was just sealed under a fresh nonce, + // so its name is new by construction. + for (obj in sealed.objects) { + transport.put(keys.vaultId, obj.hash, sign(mapOf("data" to Base64.getEncoder().encodeToString(obj.bytes)))) + } + return VaultEntry( + path = file.path, + hash = sealed.locator.hash, + size = file.bytes.size.toLong(), + enc = sealed.locator.enc, + parts = sealed.locator.parts, + ) + } + + /** + * Seal and upload a v2 manifest naming [entries], then commit it as [seq]. + * Every entry's objects must already be on the relay. `hashes` lists every + * part of every entry: the relay checks they exist, and records them as + * what the version references — a part left out may be pruned. + */ + private fun commitManifest(entries: List, seq: Long, at: Long): Long { + val manifest = VaultManifest(version = 2, seq = seq, at = at, entries = entries) + val sealed = sealManifest(crypto, keys.contentKey, keys.vaultId, manifest) + transport.put(keys.vaultId, sealed.hash, sign(mapOf("data" to Base64.getEncoder().encodeToString(sealed.bytes)))) + val hashes = LinkedHashSet().apply { entries.forEach { addAll(entryObjectHashes(it)) } } + return transport.commit( + keys.vaultId, + sign( + linkedMapOf( + "manifest" to sealed.hash, + "seq" to seq, + "at" to at, + "hashes" to hashes.toList(), + ), + ), + ) + } + + private fun sign(body: Map): String = signVaultBody(crypto, keys, body, clock()).json + + private fun openRow(row: VaultLogEntry): VaultManifest = + openManifest(crypto, keys.contentKey, keys.vaultId, row.manifest, transport.get(keys.vaultId, row.manifest)) + + private fun sha256Hex(bytes: ByteArray): String = toHex(MessageDigest.getInstance("SHA-256").digest(bytes)) +} diff --git a/android/shade-android/src/main/kotlin/no/zyon/shade/vault/VaultCrypto.kt b/android/shade-android/src/main/kotlin/no/zyon/shade/vault/VaultCrypto.kt new file mode 100644 index 0000000..985a576 --- /dev/null +++ b/android/shade-android/src/main/kotlin/no/zyon/shade/vault/VaultCrypto.kt @@ -0,0 +1,364 @@ +package no.zyon.shade.vault + +import no.zyon.shade.blob.aeadSeal +import no.zyon.shade.crypto.CryptoProvider +import no.zyon.shade.serialization.stringifyJson +import java.io.ByteArrayOutputStream +import java.security.GeneralSecurityException +import java.security.MessageDigest +import java.util.zip.DataFormatException +import java.util.zip.Deflater +import java.util.zip.Inflater + +/** + * Sealing, naming, packing and manifest encoding — mirror of + * `@shade/vault/src/crypto.ts`. The cross-language contract is the + * "Format (v2)" section of `docs/vault.md`; vectors in + * `test-vectors/vault-v2.json`. + * + * Every object on the relay is `nonce(12) || ciphertext || tag(16)`, named by + * the lowercase hex SHA-256 of those bytes. Hashing the *ciphertext* is what + * lets the relay check an upload without holding a key; the price is that + * identical plaintext gets a new name on every seal (fresh nonce), so + * unchanged files must reuse their old entry instead of being re-sealed. + */ + +private const val NONCE_LEN = 12 +private const val TAG_LEN = 16 + +/** + * Largest stored (post-compression) slice sealed as one object: 4 MiB. + * Part of the wire contract — every writer splits at the same boundary. + */ +const val VAULT_CHUNK_SIZE = 4 * 1024 * 1024 + +/** + * Ceiling on an inflated manifest. Manifests are sealed under our own key, so + * a decompression bomb could only come from a device that holds it — but a + * corrupted write should fail with a message, not by exhausting the heap. + */ +private const val MAX_MANIFEST_BYTES = 256L * 1024 * 1024 + +/** ASCII "SVM2" — marks a compressed v2 manifest. */ +private val MANIFEST_V2_MAGIC = byteArrayOf(0x53, 0x56, 0x4d, 0x32) + +/** One sealed object: its relay name and its bytes. */ +class SealedObject(val hash: String, val bytes: ByteArray) + +/** Lowercase hex SHA-256 — the name of an object. */ +fun objectHash(sealed: ByteArray): String = + toHex(MessageDigest.getInstance("SHA-256").digest(sealed)) + +/** + * AAD for an object: binds the vault, so a ciphertext lifted from one vault + * cannot be planted in another even by someone who can write to both. The + * content hash is deliberately not in it — it is derived from the very bytes + * being sealed. + */ +fun vaultObjectAad(vaultId: String): ByteArray = + "shade-vault-object-v1|$vaultId".toByteArray(Charsets.UTF_8) + +/** Encrypt one object under a fresh random nonce and give it its name. */ +fun sealObject(crypto: CryptoProvider, contentKey: ByteArray, vaultId: String, plaintext: ByteArray): SealedObject { + val (ciphertext, nonce) = crypto.aesGcmEncrypt(contentKey, plaintext, vaultObjectAad(vaultId)) + val bytes = ByteArray(NONCE_LEN + ciphertext.size) + System.arraycopy(nonce, 0, bytes, 0, NONCE_LEN) + System.arraycopy(ciphertext, 0, bytes, NONCE_LEN, ciphertext.size) + return SealedObject(objectHash(bytes), bytes) +} + +/** + * [sealObject] with a caller-chosen nonce — for cross-language vectors ONLY. + * Mirror of `@shade/vault/testing`'s `sealObjectWithNonce`. `internal` so it + * is reachable from this module's tests and from nowhere else: a nonce reused + * under one content key breaks AES-GCM outright. + */ +internal fun sealObjectWithNonce(contentKey: ByteArray, vaultId: String, plaintext: ByteArray, nonce: ByteArray): SealedObject { + val bytes = aeadSeal(contentKey, nonce, plaintext, vaultObjectAad(vaultId)) + return SealedObject(objectHash(bytes), bytes) +} + +/** + * Decrypt one object, verifying its name first: a relay that returned the + * wrong object would otherwise surface as an AEAD failure, which reads like + * key corruption and sends the user looking in the wrong place. + */ +fun openObject( + crypto: CryptoProvider, + contentKey: ByteArray, + vaultId: String, + expectedHash: String, + bytes: ByteArray, +): ByteArray { + if (bytes.size < NONCE_LEN + TAG_LEN) { + throw VaultFormatException("vault object too short to be a sealed object") + } + val actual = objectHash(bytes) + if (actual != expectedHash) { + throw VaultFormatException("vault object hash mismatch: expected $expectedHash, got $actual") + } + return try { + crypto.aesGcmDecrypt( + contentKey, + bytes.copyOfRange(NONCE_LEN, bytes.size), + bytes.copyOfRange(0, NONCE_LEN), + vaultObjectAad(vaultId), + ) + } catch (e: GeneralSecurityException) { + // The hash matched, so the relay returned what was asked for; a tag + // failure now means a wrong key or an object from another vault. + throw VaultFormatException("vault object $expectedHash failed authentication (wrong key or vault?)", e) + } +} + +// ─── Compression ───────────────────────────────────────────── + +/** + * Raw DEFLATE (RFC 1951) at zlib's default level — what the TS side's + * `CompressionStream('deflate-raw')` produces. Readers never depend on the + * exact bytes, only on the stream inflating to the original. + */ +fun deflateRaw(bytes: ByteArray): ByteArray { + val deflater = Deflater(Deflater.DEFAULT_COMPRESSION, true) + try { + deflater.setInput(bytes) + deflater.finish() + val out = ByteArrayOutputStream(maxOf(64, bytes.size / 2)) + val buf = ByteArray(64 * 1024) + while (!deflater.finished()) { + val n = deflater.deflate(buf) + out.write(buf, 0, n) + } + return out.toByteArray() + } finally { + deflater.end() + } +} + +/** + * Inverse of [deflateRaw], refusing to produce more than [limit] bytes. + * + * Strict about the stream's end, like the TS `DecompressionStream`: a stream + * that stops before its final block is "truncated", and bytes after the final + * block are "trailing data" — both are corruption, not something to paper + * over by returning whatever inflated so far. + */ +fun inflateRaw(bytes: ByteArray, limit: Long): ByteArray { + val inflater = Inflater(true) + try { + // With `nowrap`, zlib may need one byte past the end of the stream + // before it reports `finished()` (documented on Inflater's + // constructor). Feed a dummy byte so a valid stream always finishes; + // it is never consumed, which is how trailing data is recognised below. + inflater.setInput(bytes.copyOf(bytes.size + 1)) + val out = ByteArrayOutputStream() + val buf = ByteArray(64 * 1024) + var stalls = 0 + while (!inflater.finished()) { + val n = try { + inflater.inflate(buf) + } catch (e: DataFormatException) { + throw VaultFormatException("vault inflate failed: ${e.message ?: "corrupt deflate stream"}", e) + } + if (n == 0) { + if (inflater.finished()) break + if (inflater.needsDictionary()) throw VaultFormatException("vault inflate failed: stream wants a preset dictionary") + if (inflater.needsInput()) throw VaultFormatException("vault inflate failed: truncated deflate stream") + // Neither progress nor a reason: never spin forever on it. + if (++stalls > 2) throw VaultFormatException("vault inflate failed: no progress") + continue + } + stalls = 0 + if (out.size().toLong() + n > limit) throw VaultFormatException("vault inflate exceeded $limit bytes") + out.write(buf, 0, n) + } + if (inflater.remaining > 1) { + throw VaultFormatException("vault inflate failed: ${inflater.remaining - 1} byte(s) of trailing data") + } + return out.toByteArray() + } finally { + inflater.end() + } +} + +/** + * Does this file start with the signature of an already-compressed format? + * Part of the contract so ports make the same `enc` choice: PNG, JPEG, WebP + * ("RIFF"…"WEBP"), MP4 family ("ftyp" at offset 4), GIF, gzip, zip ("PK", + * which also covers docx/xlsx/jar/apk). + */ +fun looksCompressed(b: ByteArray): Boolean { + fun at(offset: Int, vararg sig: Int): Boolean = + b.size >= offset + sig.size && sig.indices.all { (b[offset + it].toInt() and 0xff) == sig[it] } + return at(0, 0x89, 0x50, 0x4e, 0x47) || // PNG + at(0, 0xff, 0xd8, 0xff) || // JPEG + (at(0, 0x52, 0x49, 0x46, 0x46) && at(8, 0x57, 0x45, 0x42, 0x50)) || // RIFF....WEBP + at(4, 0x66, 0x74, 0x79, 0x70) || // ....ftyp + at(0, 0x47, 0x49, 0x46, 0x38) || // GIF8 + at(0, 0x1f, 0x8b) || // gzip + at(0, 0x50, 0x4b) // PK +} + +// ─── Entries ───────────────────────────────────────────────── + +/** A file's bytes as they will be stored, before sealing. */ +class PackedEntry( + /** [VAULT_ENC_DEFLATE_RAW] when the stored bytes are compressed, else null. */ + val enc: String?, + /** The plaintext, or its deflate-raw. */ + val stored: ByteArray, + /** [stored] in slices of at most the chunk size. Never empty. */ + val chunks: List, +) + +/** + * Turn a file's plaintext into the slices that get sealed. + * + * Compression is kept only when it saves at least 5 %, as the integer test + * `compressed * 20 <= plain * 19` so no port disagrees over rounding. The + * whole file is compressed first and THEN split: a reader concatenates the + * opened parts and inflates once, so parts carry no framing of their own. + * + * [chunkSize] exists for tests and vectors; real writers use the default. + */ +fun packEntry(plaintext: ByteArray, chunkSize: Int = VAULT_CHUNK_SIZE): PackedEntry { + require(chunkSize >= 1) { "vault chunk size must be a positive integer, got $chunkSize" } + var stored = plaintext + var enc: String? = null + if (plaintext.isNotEmpty() && !looksCompressed(plaintext)) { + val deflated = deflateRaw(plaintext) + if (deflated.size.toLong() * 20 <= plaintext.size.toLong() * 19) { + stored = deflated + enc = VAULT_ENC_DEFLATE_RAW + } + } + // An empty file is still one (empty) object: an entry always names + // something the relay holds, so a reader never special-cases. + val chunks = ArrayList() + var i = 0 + while (i < stored.size || chunks.isEmpty()) { + chunks.add(stored.copyOfRange(i, minOf(stored.size, i + chunkSize))) + i += chunkSize + } + return PackedEntry(enc, stored, chunks) +} + +/** The manifest fields that locate a file's ciphertext. */ +data class EntryLocator(val hash: String, val parts: List? = null, val enc: String? = null) + +/** Shape an entry's locator from its sealed parts (one part → no `parts`). */ +fun entryLocator(packed: PackedEntry, sealed: List): EntryLocator { + require(sealed.isNotEmpty()) { "an entry has at least one object" } + return EntryLocator( + hash = sealed[0].hash, + parts = if (sealed.size > 1) sealed.map { it.hash } else null, + enc = packed.enc, + ) +} + +/** The locator for a file's manifest entry, and the objects to upload. */ +class SealedEntry(val locator: EntryLocator, val objects: List) + +/** Pack and seal one file. */ +fun sealEntry( + crypto: CryptoProvider, + contentKey: ByteArray, + vaultId: String, + plaintext: ByteArray, + chunkSize: Int = VAULT_CHUNK_SIZE, +): SealedEntry { + val packed = packEntry(plaintext, chunkSize) + val objects = packed.chunks.map { sealObject(crypto, contentKey, vaultId, it) } + return SealedEntry(entryLocator(packed, objects), objects) +} + +/** + * Every object an entry needs, in read order — also exactly what a commit's + * signed `hashes` must list, or a part may be collected by the next prune. + */ +fun entryObjectHashes(entry: VaultEntry): List = + if (!entry.parts.isNullOrEmpty()) entry.parts else listOf(entry.hash) + +/** + * Reassemble a file from its fetched objects, in [entryObjectHashes] order: + * verify and open each part, concatenate, inflate if `enc`, check the size. + * + * The size check is what catches a part list that lost or gained an element + * — every part authenticates on its own, so such an entry would otherwise + * open cleanly into a truncated or padded file. + */ +fun openEntryBytes( + crypto: CryptoProvider, + contentKey: ByteArray, + vaultId: String, + entry: VaultEntry, + objects: List, +): ByteArray { + val hashes = entryObjectHashes(entry) + if (!entry.parts.isNullOrEmpty() && entry.parts[0] != entry.hash) { + throw VaultFormatException("vault entry ${entry.path}: hash must equal parts[0]") + } + if (objects.size != hashes.size) { + throw VaultFormatException("vault entry ${entry.path}: expected ${hashes.size} object(s), got ${objects.size}") + } + if (entry.size < 0 || entry.size > Int.MAX_VALUE - 8) { + throw VaultFormatException("vault entry ${entry.path}: size ${entry.size} cannot be held in memory") + } + + val stored = ByteArrayOutputStream() + for (i in hashes.indices) { + stored.write(openObject(crypto, contentKey, vaultId, hashes[i], objects[i])) + } + + val plaintext = when (entry.enc) { + null -> stored.toByteArray() + VAULT_ENC_DEFLATE_RAW -> inflateRaw(stored.toByteArray(), entry.size) + // Guessing would hand back bytes that look like the file and are not. + else -> throw VaultFormatException("vault entry ${entry.path}: unsupported encoding ${entry.enc}") + } + if (plaintext.size.toLong() != entry.size) { + throw VaultFormatException( + "vault entry ${entry.path}: size mismatch, manifest says ${entry.size}, got ${plaintext.size}", + ) + } + return plaintext +} + +// ─── Manifests ─────────────────────────────────────────────── + +/** + * A manifest's plaintext before sealing: v1 is bare UTF-8 JSON, v2 is "SVM2" + * + deflate-raw of it. The version field decides the container. + */ +fun encodeManifest(manifest: VaultManifest): ByteArray { + require(manifest.version == 1 || manifest.version == 2) { + "unsupported vault manifest version: ${manifest.version}" + } + val json = stringifyJson(manifest.toJsonMap()).toByteArray(Charsets.UTF_8) + if (manifest.version == 1) return json + return MANIFEST_V2_MAGIC + deflateRaw(json) +} + +/** Parse a manifest's plaintext, v1 or v2, refusing any other version. */ +fun decodeManifest(plain: ByteArray): VaultManifest { + val isV2 = plain.size >= MANIFEST_V2_MAGIC.size && + MANIFEST_V2_MAGIC.indices.all { plain[it] == MANIFEST_V2_MAGIC[it] } + val json = if (isV2) { + inflateRaw(plain.copyOfRange(MANIFEST_V2_MAGIC.size, plain.size), MAX_MANIFEST_BYTES) + } else { + plain + } + return parseManifestJson(String(json, Charsets.UTF_8)) +} + +/** A manifest is stored as an ordinary object; this is the encoding step around it. */ +fun sealManifest(crypto: CryptoProvider, contentKey: ByteArray, vaultId: String, manifest: VaultManifest): SealedObject = + sealObject(crypto, contentKey, vaultId, encodeManifest(manifest)) + +fun openManifest( + crypto: CryptoProvider, + contentKey: ByteArray, + vaultId: String, + expectedHash: String, + bytes: ByteArray, +): VaultManifest = decodeManifest(openObject(crypto, contentKey, vaultId, expectedHash, bytes)) diff --git a/android/shade-android/src/main/kotlin/no/zyon/shade/vault/VaultErrors.kt b/android/shade-android/src/main/kotlin/no/zyon/shade/vault/VaultErrors.kt new file mode 100644 index 0000000..32928ae --- /dev/null +++ b/android/shade-android/src/main/kotlin/no/zyon/shade/vault/VaultErrors.kt @@ -0,0 +1,44 @@ +package no.zyon.shade.vault + +/** + * The relay refused a request. [code] is the relay's own error code + * (`BAD_REQUEST`, `UNAUTHORIZED`, `NOT_FOUND`, `SEQ_CONFLICT`, `TOO_LARGE`, + * `MISSING_OBJECTS`), or `SHADE_NETWORK` when the response carried none. + * + * Kept apart from [VaultFormatException] because the reactions differ: a + * relay refusal may be retried or shown as "offline / rejected", while a + * format failure means the bytes themselves are wrong and retrying is futile. + */ +class VaultException( + val code: String, + /** HTTP status, or 0 when the failure is local (e.g. a missing version). */ + val statusCode: Int, + message: String, + /** The relay's head, sent along with `SEQ_CONFLICT`. */ + val head: Long? = null, + /** Up to 20 hashes the relay reported missing with `MISSING_OBJECTS`. */ + val missing: List = emptyList(), + cause: Throwable? = null, +) : RuntimeException("[$code @ $statusCode] $message", cause) { + + /** + * Two devices committed from the same head and this one lost. The answer + * is to re-read the head and rebuild the edit on top of it — never to + * resend the same commit, which would just lose again. + */ + val isSeqConflict: Boolean get() = code == CODE_SEQ_CONFLICT + + companion object { + const val CODE_SEQ_CONFLICT = "SEQ_CONFLICT" + const val CODE_NOT_FOUND = "NOT_FOUND" + const val CODE_MISSING_OBJECTS = "MISSING_OBJECTS" + const val CODE_NETWORK = "SHADE_NETWORK" + } +} + +/** + * Bytes that do not decode to what the vault format promises: a hash + * mismatch, a failed AEAD tag, corrupt or oversized deflate, an unknown + * manifest version or entry encoding, a size that does not add up. + */ +class VaultFormatException(message: String, cause: Throwable? = null) : RuntimeException(message, cause) diff --git a/android/shade-android/src/main/kotlin/no/zyon/shade/vault/VaultKeys.kt b/android/shade-android/src/main/kotlin/no/zyon/shade/vault/VaultKeys.kt new file mode 100644 index 0000000..23eacb4 --- /dev/null +++ b/android/shade-android/src/main/kotlin/no/zyon/shade/vault/VaultKeys.kt @@ -0,0 +1,80 @@ +package no.zyon.shade.vault + +import no.zyon.shade.blob.ed25519PublicKeyFromSeed +import no.zyon.shade.crypto.CryptoProvider + +/** + * Everything a vault needs, derived from the account master key. + * + * Mirror of `@shade/vault`'s `VaultKeys` / `deriveVaultKeys`, and of the three + * `deriveVault*` functions in `@shade/storage-encrypted/crypto/kdf.ts`: + * + * vaultId = hex(HKDF(masterKey, info=`shade-vault-id-v1:`)) // relay-visible opaque id + * contentKey = HKDF(masterKey, info=`shade-vault-content-v1:`) // AES-256-GCM key for every object + * signingSeed = HKDF(masterKey, info=`shade-vault-sig-v1:`) // Ed25519 seed, TOFU-pinned by the relay + * publicKey = Ed25519 public key of signingSeed + * + * This is what makes recovery "username and password": a phone that can + * derive the profile master can derive these too, and read a vault whose + * writer — the PC — is switched off. + * + * Its own HKDF branch rather than a reuse of `shade-blob-*-v1`: whoever holds + * a vault key reads every file, so it must not be derivable from the profile + * blob's key or vice versa. Reference vectors: `test-vectors/vault-v2.json` + * ("vault-v2 keys"). + */ +class VaultKeys( + /** Lowercase hex (64 chars) — the id in every relay URL. */ + val vaultId: String, + val contentKey: ByteArray, + val signingSeed: ByteArray, + val publicKey: ByteArray, +) + +private const val VAULT_ID_INFO_PREFIX = "shade-vault-id-v1:" +private const val VAULT_CONTENT_INFO_PREFIX = "shade-vault-content-v1:" +private const val VAULT_SIG_INFO_PREFIX = "shade-vault-sig-v1:" + +private const val DERIVED_LEN = 32 + +/** + * Derive a vault's keys for namespace [app] (e.g. `"scaffold"`). Distinct + * collections under one master MUST use distinct `app` strings — the phone's + * outgoing change queue is a second vault with its own `app`, not a path + * prefix inside the first, so the two never contend for one `seq`. + * + * No HKDF salt: the TS side passes `undefined`, which RFC 5869 (and + * `@noble/hashes`) turn into 32 zero bytes — exactly what Tink does with an + * empty salt. The vectors pin it. + */ +fun deriveVaultKeys(crypto: CryptoProvider, masterKey: ByteArray, app: String): VaultKeys { + require(masterKey.size == 32) { "masterKey must be 32 bytes" } + require(app.isNotEmpty()) { "app namespace must be non-empty" } + fun derive(prefix: String): ByteArray = + crypto.hkdf(masterKey, ByteArray(0), (prefix + app).toByteArray(Charsets.UTF_8), DERIVED_LEN) + + val signingSeed = derive(VAULT_SIG_INFO_PREFIX) + return VaultKeys( + vaultId = toHex(derive(VAULT_ID_INFO_PREFIX)), + contentKey = derive(VAULT_CONTENT_INFO_PREFIX), + signingSeed = signingSeed, + publicKey = ed25519PublicKeyFromSeed(signingSeed), + ) +} + +/** Lowercase hex — the encoding of vault ids and object names on the wire. */ +fun toHex(bytes: ByteArray): String { + val out = CharArray(bytes.size * 2) + val digits = "0123456789abcdef" + for (i in bytes.indices) { + val v = bytes[i].toInt() and 0xff + out[i * 2] = digits[v ushr 4] + out[i * 2 + 1] = digits[v and 0x0f] + } + return String(out) +} + +private val HEX64 = Regex("^[0-9a-f]{64}$") + +/** True for a 64-char lowercase hex string — a vault id or an object name. */ +internal fun isHex64(s: String): Boolean = HEX64.matches(s) diff --git a/android/shade-android/src/main/kotlin/no/zyon/shade/vault/VaultModels.kt b/android/shade-android/src/main/kotlin/no/zyon/shade/vault/VaultModels.kt new file mode 100644 index 0000000..11dc044 --- /dev/null +++ b/android/shade-android/src/main/kotlin/no/zyon/shade/vault/VaultModels.kt @@ -0,0 +1,183 @@ +package no.zyon.shade.vault + +import org.json.JSONArray +import org.json.JSONException +import org.json.JSONObject + +/** + * The vault's data model — mirror of `@shade/vault/src/types.ts`. + * + * Objects are content-addressed (named by the SHA-256 of their ciphertext), a + * manifest names the collection (paths live only inside it, encrypted), and + * the log is append-only. See `docs/vault.md` for why. + */ + +/** The only entry encoding v2 defines: RFC 1951 raw DEFLATE, no zlib/gzip header. */ +const val VAULT_ENC_DEFLATE_RAW = "deflate-raw" + +/** + * One file in a manifest. + * + * [enc] is kept as a raw string rather than an enum on purpose: a manifest + * written by a newer client may name an encoding this one does not know, and + * the right reaction is to refuse *reading that file* (see [openEntryBytes]), + * not to refuse the whole manifest — every other file is still readable. + */ +data class VaultEntry( + /** Path within the collection, as the app understands it. */ + val path: String, + /** Lowercase hex SHA-256 of the (first) ciphertext object. */ + val hash: String, + /** PLAINTEXT byte length — before compression, whatever [enc] says. */ + val size: Long, + /** Optional app-defined mode/metadata, opaque to the vault. */ + val mode: String? = null, + /** Present only when the stored bytes are compressed. */ + val enc: String? = null, + /** Present only when there is more than one object; `parts[0] == hash`. */ + val parts: List? = null, +) + +/** The full contents of a collection at one point in time. */ +data class VaultManifest( + /** 1: bare JSON. 2: "SVM2" + deflate-raw(JSON). Writers emit 2; readers accept both. */ + val version: Int, + /** Monotonic, assigned by the client and checked by the relay. */ + val seq: Long, + /** Epoch millis when the commit was made. */ + val at: Long, + /** Optional human note, e.g. "nattlig backup". */ + val message: String? = null, + val entries: List, +) + +/** One row of the append-only log. */ +data class VaultLogEntry( + val seq: Long, + /** Hash of the encrypted manifest object. */ + val manifest: String, + val at: Long, + /** Total bytes of all objects the manifest references, for quota display. */ + val bytes: Long, +) + +/** What `GET /v1/vault/:id/log` returns. */ +data class VaultLog( + val entries: List, + /** Highest seq the relay holds; `0` when the vault is empty. */ + val head: Long, +) + +/** What `POST /v1/vault/:id/prune` returns. */ +data class VaultPruneResult( + val removedVersions: Long, + val removedObjects: Long, + val freedBytes: Long, +) + +// ─── JSON ──────────────────────────────────────────────────── + +/** + * The entry as an insertion-ordered map, in the order TS builds it + * (`{ path, ...locator, size }`, then `mode`), so `JSON.stringify` on either + * side yields the same bytes. Key order is not part of the contract — readers + * never depend on it — but matching it keeps the manifest vector exact. + * Absent optionals are left out, as `JSON.stringify` drops `undefined`. + */ +internal fun VaultEntry.toJsonMap(): Map { + val m = LinkedHashMap() + m["path"] = path + m["hash"] = hash + if (parts != null) m["parts"] = parts + if (enc != null) m["enc"] = enc + m["size"] = size + if (mode != null) m["mode"] = mode + return m +} + +internal fun VaultManifest.toJsonMap(): Map { + val m = LinkedHashMap() + m["version"] = version + m["seq"] = seq + m["at"] = at + m["entries"] = entries.map { it.toJsonMap() } + if (message != null) m["message"] = message + return m +} + +/** + * Parse a manifest's JSON. Malformed structure surfaces as + * [VaultFormatException], never as a raw `JSONException` — a caller showing + * "the backup could not be read" should not have to know which parser ran. + */ +internal fun parseManifestJson(text: String): VaultManifest { + try { + val o = JSONObject(text) + // Strict like TS `version !== 1 && version !== 2`: "2" or 2.5 are refused. + val version = when ((o.opt("version") as? Number)?.toDouble()) { + 1.0 -> 1 + 2.0 -> 2 + else -> -1 + } + if (version != 1 && version != 2) { + // Refusing beats guessing: a future manifest may describe a file + // this reader cannot represent, and committing on top of a + // half-understood head would drop it. + throw VaultFormatException( + "unsupported vault manifest version: ${if (o.has("version")) o.get("version") else "undefined"}", + ) + } + val arr = o.getJSONArray("entries") + val entries = ArrayList(arr.length()) + for (i in 0 until arr.length()) entries.add(parseEntryJson(arr.getJSONObject(i))) + return VaultManifest( + version = version, + seq = o.getLong("seq"), + at = o.getLong("at"), + message = optString(o, "message"), + entries = entries, + ) + } catch (e: JSONException) { + throw VaultFormatException("vault manifest is not valid JSON: ${e.message}", e) + } +} + +private fun parseEntryJson(o: JSONObject): VaultEntry { + val parts = if (o.has("parts") && !o.isNull("parts")) { + val a = o.getJSONArray("parts") + List(a.length()) { a.getString(it) } + } else { + null + } + return VaultEntry( + path = o.getString("path"), + hash = o.getString("hash"), + size = o.getLong("size"), + mode = optString(o, "mode"), + enc = optString(o, "enc"), + parts = parts, + ) +} + +/** `org.json`'s `optString` turns null into "null" and numbers into strings; this does not. */ +private fun optString(o: JSONObject, key: String): String? = + if (o.has(key) && !o.isNull(key)) o.getString(key) else null + +internal fun parseLogJson(text: String): VaultLog { + try { + val o = JSONObject(text) + val arr: JSONArray = o.getJSONArray("entries") + val entries = List(arr.length()) { i -> + val e = arr.getJSONObject(i) + VaultLogEntry( + seq = e.getLong("seq"), + manifest = e.getString("manifest"), + at = e.getLong("at"), + bytes = e.optLong("bytes", 0L), + ) + } + return VaultLog(entries = entries, head = o.getLong("head")) + } catch (e: JSONException) { + throw VaultFormatException("vault log response is malformed: ${e.message}", e) + } +} diff --git a/android/shade-android/src/main/kotlin/no/zyon/shade/vault/VaultSigning.kt b/android/shade-android/src/main/kotlin/no/zyon/shade/vault/VaultSigning.kt new file mode 100644 index 0000000..59ce145 --- /dev/null +++ b/android/shade-android/src/main/kotlin/no/zyon/shade/vault/VaultSigning.kt @@ -0,0 +1,67 @@ +package no.zyon.shade.vault + +import no.zyon.shade.crypto.CryptoProvider +import no.zyon.shade.serialization.canonicalJson +import no.zyon.shade.serialization.stringifyJson +import java.util.Base64 + +/** + * A request body signed the way the relay verifies it. + * + * [canonical] is kept alongside the wire JSON so tests can compare it with + * the TS bytes directly instead of reverse-engineering a failing signature. + */ +class SignedPayload( + /** The JSON to send: the payload fields + `signedAt` + `signature`. */ + val json: String, + /** The exact bytes the signature covers. */ + val canonical: ByteArray, + val signedAt: Long, + val signature: ByteArray, +) + +/** + * Mirror of `@shade/server`'s `signPayload`: Ed25519 over `JSON.stringify` of + * every field except `signature` (with `signedAt` added), top-level keys + * sorted, nested values as-is; the wire body then carries `signedAt` and the + * signature in standard base64. + * + * [signedAt] is a parameter so the vectors can pin it; the relay rejects a + * value more than five minutes old or one minute in the future, so real + * callers pass the current wall clock. + */ +fun signPayload( + crypto: CryptoProvider, + signingSeed: ByteArray, + payload: Map, + signedAt: Long, +): SignedPayload { + require(signingSeed.size == 32) { "signingSeed must be 32 bytes (Ed25519)" } + require("signature" !in payload && "signedAt" !in payload) { + "payload must not carry signature/signedAt — they are added here" + } + val withTime = LinkedHashMap(payload).apply { put("signedAt", signedAt) } + val canonical = canonicalJson(withTime).toByteArray(Charsets.UTF_8) + val signature = crypto.sign(signingSeed, canonical) + val wire = LinkedHashMap(withTime).apply { + put("signature", Base64.getEncoder().encodeToString(signature)) + } + return SignedPayload(stringifyJson(wire), canonical, signedAt, signature) +} + +/** + * Sign a vault request body with the vault's key, the pubkey INSIDE the + * signed payload — appended afterwards it would not be covered, and could be + * swapped in transit on the first (TOFU-pinning) write. + */ +fun signVaultBody( + crypto: CryptoProvider, + keys: VaultKeys, + body: Map, + signedAt: Long, +): SignedPayload { + val withKey = LinkedHashMap(body).apply { + put("publicKey", Base64.getEncoder().encodeToString(keys.publicKey)) + } + return signPayload(crypto, keys.signingSeed, withKey, signedAt) +} diff --git a/android/shade-android/src/main/kotlin/no/zyon/shade/vault/VaultTransport.kt b/android/shade-android/src/main/kotlin/no/zyon/shade/vault/VaultTransport.kt new file mode 100644 index 0000000..6da58e3 --- /dev/null +++ b/android/shade-android/src/main/kotlin/no/zyon/shade/vault/VaultTransport.kt @@ -0,0 +1,167 @@ +package no.zyon.shade.vault + +import org.json.JSONException +import org.json.JSONObject +import java.io.IOException +import java.io.InputStream +import java.net.HttpURLConnection +import java.net.URL + +/** + * How a [VaultClient] reaches the relay — mirror of `@shade/vault`'s + * `VaultTransport`. Bodies arrive already signed (as JSON text): the + * transport moves bytes and maps errors, it never holds a key. + * + * Blocking by design, like [no.zyon.shade.blob.BlobClient]: call it from a + * background dispatcher (`Dispatchers.IO`), never from the main thread. + */ +interface VaultTransport { + /** Does the relay already hold this object? */ + fun has(vaultId: String, hash: String): Boolean + + fun put(vaultId: String, hash: String, signedBody: String) + + /** The raw sealed object. */ + fun get(vaultId: String, hash: String): ByteArray + + fun log(vaultId: String, limit: Int? = null): VaultLog + + /** Returns the committed seq. Throws [VaultException] with `SEQ_CONFLICT` when beaten to it. */ + fun commit(vaultId: String, signedBody: String): Long + + fun prune(vaultId: String, signedBody: String): VaultPruneResult +} + +/** + * Plain HTTP against a relay running `createVaultRoutes`. + * + * Built on `HttpURLConnection` rather than `java.net.http.HttpClient` (which + * [no.zyon.shade.blob.BlobClient] uses): `java.net.http` does not exist on + * Android at any API level, and this client exists for a phone. OkHttp would + * also work but would add a dependency to a library that has none for HTTP; + * `HttpURLConnection` is on both the JVM (tests) and Android. + */ +class VaultHttpTransport( + baseUrl: String, + private val connectTimeoutMs: Int = 15_000, + /** Generous: one object is up to 4 MiB, and phones sit on slow uplinks. */ + private val readTimeoutMs: Int = 60_000, +) : VaultTransport { + + private val base = baseUrl.trimEnd('/') + + override fun has(vaultId: String, hash: String): Boolean { + val res = request("HEAD", objectPath(vaultId, hash), null) + return when (res.status) { + 200 -> true + 404 -> false + else -> fail(res, "have-check") + } + } + + override fun put(vaultId: String, hash: String, signedBody: String) { + val res = request("PUT", objectPath(vaultId, hash), signedBody) + if (res.status !in 200..299) fail(res, "upload") + } + + override fun get(vaultId: String, hash: String): ByteArray { + val res = request("GET", objectPath(vaultId, hash), null) + if (res.status !in 200..299) fail(res, "download") + return res.body + } + + override fun log(vaultId: String, limit: Int?): VaultLog { + val q = if (limit == null) "" else "?limit=$limit" + val res = request("GET", "${vaultPath(vaultId)}/log$q", null) + if (res.status !in 200..299) fail(res, "log") + return parseLogJson(res.body.toString(Charsets.UTF_8)) + } + + override fun commit(vaultId: String, signedBody: String): Long { + val res = request("POST", "${vaultPath(vaultId)}/commit", signedBody) + if (res.status !in 200..299) fail(res, "commit") + return jsonBody(res, "commit").getLong("seq") + } + + override fun prune(vaultId: String, signedBody: String): VaultPruneResult { + val res = request("POST", "${vaultPath(vaultId)}/prune", signedBody) + if (res.status !in 200..299) fail(res, "prune") + val o = jsonBody(res, "prune") + return VaultPruneResult( + removedVersions = o.getLong("removedVersions"), + removedObjects = o.getLong("removedObjects"), + freedBytes = o.getLong("freedBytes"), + ) + } + + // ─── Plumbing ──────────────────────────────────────────── + + private class Response(val status: Int, val body: ByteArray) + + /** Ids are validated before they reach a URL, so nothing can smuggle a path. */ + private fun vaultPath(vaultId: String): String { + require(isHex64(vaultId)) { "vaultId must be 64 lowercase hex chars" } + return "/v1/vault/$vaultId" + } + + private fun objectPath(vaultId: String, hash: String): String { + require(isHex64(hash)) { "object hash must be 64 lowercase hex chars" } + return "${vaultPath(vaultId)}/object/$hash" + } + + private fun request(method: String, path: String, jsonBody: String?): Response { + val conn = try { + URL(base + path).openConnection() as HttpURLConnection + } catch (e: IOException) { + throw VaultException(VaultException.CODE_NETWORK, 0, "vault $method $path: ${e.message}", cause = e) + } + try { + conn.requestMethod = method + conn.connectTimeout = connectTimeoutMs + conn.readTimeout = readTimeoutMs + conn.useCaches = false + if (jsonBody != null) { + val bytes = jsonBody.toByteArray(Charsets.UTF_8) + conn.doOutput = true + conn.setRequestProperty("content-type", "application/json") + conn.setFixedLengthStreamingMode(bytes.size) + conn.outputStream.use { it.write(bytes) } + } + val status = conn.responseCode + // A non-2xx body is on the error stream; HEAD has neither. + val stream: InputStream? = if (status >= 400) conn.errorStream else if (method == "HEAD") null else conn.inputStream + val body = stream?.use { it.readBytes() } ?: ByteArray(0) + return Response(status, body) + } catch (e: IOException) { + throw VaultException(VaultException.CODE_NETWORK, 0, "vault $method $path: ${e.message}", cause = e) + } finally { + conn.disconnect() + } + } + + private fun jsonBody(res: Response, what: String): JSONObject = try { + JSONObject(res.body.toString(Charsets.UTF_8)) + } catch (e: JSONException) { + throw VaultException(VaultException.CODE_NETWORK, res.status, "vault $what response not JSON", cause = e) + } + + /** Turn a non-2xx into a [VaultException] that carries the relay's own code. */ + private fun fail(res: Response, what: String): Nothing { + var code = VaultException.CODE_NETWORK + var detail = "HTTP ${res.status}" + var head: Long? = null + var missing = emptyList() + try { + val o = JSONObject(res.body.toString(Charsets.UTF_8)) + o.optJSONObject("error")?.let { err -> + code = err.optString("code", code) + detail = err.optString("message", detail) + } + if (o.has("head") && !o.isNull("head")) head = o.getLong("head") + o.optJSONArray("missing")?.let { a -> missing = List(a.length()) { a.getString(it) } } + } catch (_: JSONException) { + // Non-JSON error body (a proxy's HTML page): the status is all we have. + } + throw VaultException(code, res.status, "vault $what failed — $detail", head = head, missing = missing) + } +} diff --git a/android/shade-android/src/test/kotlin/no/zyon/shade/VaultClientTest.kt b/android/shade-android/src/test/kotlin/no/zyon/shade/VaultClientTest.kt new file mode 100644 index 0000000..42305bc --- /dev/null +++ b/android/shade-android/src/test/kotlin/no/zyon/shade/VaultClientTest.kt @@ -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() + val log = ArrayList() + val committedHashes = HashMap>() + 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() + 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() + 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(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 "bad gateway" + } + 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) + } + } +} diff --git a/android/shade-android/src/test/kotlin/no/zyon/shade/VaultLiveTest.kt b/android/shade-android/src/test/kotlin/no/zyon/shade/VaultLiveTest.kt new file mode 100644 index 0000000..0a41df4 --- /dev/null +++ b/android/shade-android/src/test/kotlin/no/zyon/shade/VaultLiveTest.kt @@ -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()) + } +} diff --git a/android/shade-android/src/test/kotlin/no/zyon/shade/VaultVectorTest.kt b/android/shade-android/src/test/kotlin/no/zyon/shade/VaultVectorTest.kt new file mode 100644 index 0000000..4d24ece --- /dev/null +++ b/android/shade-android/src/test/kotlin/no/zyon/shade/VaultVectorTest.kt @@ -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 = + (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().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 + 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)) + } +} diff --git a/scripts/vault-live-kotlin.ts b/scripts/vault-live-kotlin.ts new file mode 100644 index 0000000..8f9742b --- /dev/null +++ b/scripts/vault-live-kotlin.ts @@ -0,0 +1,107 @@ +/** + * Live cross-check of the Kotlin vault client against the real TS routes. + * + * bun run scripts/vault-live-kotlin.ts + * + * Serves `createVaultRoutes` (memory store) on a free local port, pushes a + * few files with the TS client — one compressed, one multi-part, one PNG — + * then runs the gated `VaultLiveTest` in android/ with `SHADE_VAULT_LIVE_SPEC` + * set. That test reads every file back from Kotlin and edits the vault + * (adds two files, removes one). This script then reads the Kotlin-written + * version back with the TS client, checks every byte and that untouched + * entries kept their objects, and finally edits on top of it from TS. + * + * Vectors pin the format byte for byte; this pins the conversation — real + * HTTP, real signature checks, real SEQ handling — which no vector can. + */ +import { createHash, randomBytes } from 'node:crypto'; +import { mkdtemp, readFile, writeFile } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join, resolve } from 'node:path'; +import { SubtleCryptoProvider } from '../packages/shade-crypto-web/src/index.js'; +import { createVaultRoutes, MemoryVaultStore } from '../packages/shade-vault/src/server.js'; +import { HttpVaultTransport } from '../packages/shade-vault/src/http-transport.js'; +import { VaultClient, deriveVaultKeys } from '../packages/shade-vault/src/client.js'; + +const sha256 = (b: Uint8Array) => createHash('sha256').update(b).digest('hex'); +const enc = (s: string) => new TextEncoder().encode(s); +function check(cond: unknown, what: string): asserts cond { + if (!cond) throw new Error(`live cross-check failed: ${what}`); +} + +const crypto = new SubtleCryptoProvider(); +const routes = createVaultRoutes(new MemoryVaultStore(), crypto); +const server = Bun.serve({ port: 0, hostname: '127.0.0.1', fetch: (req) => routes.fetch(req) }); +const url = `http://127.0.0.1:${server.port}`; + +try { + const masterKey = new Uint8Array(randomBytes(32)); + const app = 'kotlin-live'; + const keys = await deriveVaultKeys(masterKey, app); + const client = new VaultClient(crypto, keys, new HttpVaultTransport(url)); + + const files = [ + { path: 'hello.txt', bytes: enc('hei fra TS\n') }, + { path: '.scaffold/plan.md', bytes: enc('# Plan\n' + '- [ ] noe å gjøre\n'.repeat(300)), mode: '644' }, + { path: 'big.bin', bytes: new Uint8Array(randomBytes(9 * 1024 * 1024)) }, // 3 parts at 4 MiB + { path: 'pic.png', bytes: new Uint8Array([0x89, 0x50, 0x4e, 0x47, ...randomBytes(2000)]) }, + ]; + const pushed = await client.push(files, Date.now(), 'from TS'); + console.log(`TS pushed seq ${pushed.seq} (${pushed.uploaded} objects) to ${url}`); + const before = await client.manifest(); + + const dir = await mkdtemp(join(tmpdir(), 'shade-vault-live-')); + const specPath = join(dir, 'spec.json'); + const kotlinOut = join(dir, 'kotlin-out.json'); + await writeFile( + specPath, + JSON.stringify({ + url, + masterKey: Buffer.from(masterKey).toString('hex'), + app, + files: Object.fromEntries(files.map((f) => [f.path, sha256(f.bytes)])), + kotlinOut, + }), + ); + + const androidDir = resolve(import.meta.dir, '../android'); + const gradle = Bun.spawn( + ['./gradlew', ':shade-android:test', '--tests', 'no.zyon.shade.VaultLiveTest', '--console=plain'], + { cwd: androidDir, env: { ...process.env, SHADE_VAULT_LIVE_SPEC: specPath }, stdout: 'inherit', stderr: 'inherit' }, + ); + check((await gradle.exited) === 0, 'Kotlin VaultLiveTest failed'); + + const out = JSON.parse(await readFile(kotlinOut, 'utf8')) as { + seq: number; + removed: string; + files: Record; + }; + const after = await client.pull(); + check(after.manifest.seq === out.seq, `head is ${after.manifest.seq}, Kotlin committed ${out.seq}`); + check(!after.files.has(out.removed), `${out.removed} should be gone`); + for (const [path, digest] of Object.entries(out.files)) { + check(after.files.has(path), `${path} missing`); + check(sha256(after.files.get(path)!) === digest, `${path} bytes differ`); + } + for (const f of files.filter((f) => f.path !== out.removed)) { + check(sha256(after.files.get(f.path)!) === sha256(f.bytes), `${f.path} changed`); + const was = before.entries.find((e) => e.path === f.path)!; + const now = after.manifest.entries.find((e) => e.path === f.path)!; + check(JSON.stringify(was) === JSON.stringify(now), `${f.path} entry was rewritten`); + } + const kotlinBig = after.manifest.entries.find((e) => e.path === 'from-kotlin/big.bin')!; + check((kotlinBig.parts?.length ?? 0) === 2, 'Kotlin big.bin should be 2 parts'); + check( + after.manifest.entries.find((e) => e.path === 'from-kotlin/note.md')?.enc === 'deflate-raw', + 'Kotlin note.md should be compressed', + ); + + // And TS can keep editing on top of a Kotlin-written head. + const ts = await client.edit(() => ({ put: [{ path: 'from-ts.txt', bytes: enc('ok') }] }), Date.now()); + check(ts.committed && ts.seq === out.seq + 1, 'TS edit on top of Kotlin head'); + console.log( + `LIVE OK — TS→Kotlin read ${files.length} files; Kotlin edit seq ${out.seq} read back by TS; TS edit seq ${ts.seq}`, + ); +} finally { + server.stop(true); +}