lib

Core libraries for Radroots
git clone https://radroots.dev/git/lib.git
Log | Files | Refs | README

commit 7cbbb170ce4a9ef51b744b7c5bce4a11c3786b96
parent 8b54f12ee947fdb6e86e622afdd74a48a0ca83c9
Author: triesap <tyson@radroots.org>
Date:   Sun, 18 Oct 2026 20:57:40 +0000

secrets: support target-local wrapping providers

- Preserve native thread bounds through one explicit wrapping host marker.
- Permit local browser provider futures and scoped migration validators.
- Prove native and embedded guarantees with reviewed public API boundaries.
- Execute protected IndexedDB and local callback workflows in three browsers.

Diffstat:
Mcontracts/api_baselines/radroots_secrets.txt | 14++++++++------
Mcrates/secrets/README.md | 8++++++++
Mcrates/secrets/src/envelope.rs | 2+-
Mcrates/secrets/src/provider.rs | 2+-
Mcrates/secrets/src/wrapping.rs | 21+++++++++++++++++++--
Mcrates/secrets/tests/package_boundary.rs | 2+-
Mcrates/secrets/tests/provider_contract.rs | 16++++++++++++++++
Mcrates/storage_indexeddb/tests/browser/Cargo.lock | 98+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----
Mcrates/storage_indexeddb/tests/browser/Cargo.toml | 2++
Mcrates/storage_indexeddb/tests/browser/run.mjs | 7++++---
Mcrates/storage_indexeddb/tests/browser/src/lib.rs | 3+++
Acrates/storage_indexeddb/tests/browser/src/protected.rs | 223+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
12 files changed, 380 insertions(+), 18 deletions(-)

diff --git a/contracts/api_baselines/radroots_secrets.txt b/contracts/api_baselines/radroots_secrets.txt @@ -60,7 +60,7 @@ pub const fn radroots_secrets::envelope::EncryptedEnvelope::key_source(&self) -> pub async fn radroots_secrets::envelope::EncryptedEnvelope::open(&self, &dyn radroots_secrets::wrapping::KeyWrapping, &radroots_secrets::context::EnvelopeContext) -> core::result::Result<radroots_secrets::wrapping::SecretMaterial, radroots_secrets::error::Error> pub async fn radroots_secrets::envelope::EncryptedEnvelope::open_legacy_v1(&self, &dyn radroots_secrets::wrapping::KeyWrapping, &radroots_secrets::envelope::LegacyV1ResealAuthority, &radroots_secrets::id::SecretRef, &radroots_secrets::context::EnvelopeContext) -> core::result::Result<radroots_secrets::wrapping::SecretMaterial, radroots_secrets::error::Error> pub const fn radroots_secrets::envelope::EncryptedEnvelope::reference(&self) -> &radroots_secrets::id::SecretRef -pub async fn radroots_secrets::envelope::EncryptedEnvelope::reseal_legacy_v1<V>(&self, &dyn radroots_secrets::wrapping::KeyWrapping, &radroots_secrets::envelope::LegacyV1ResealAuthority, &radroots_secrets::id::SecretRef, radroots_secrets::id::SecretRef, radroots_secrets::context::EnvelopeContext, &V, radroots_secrets::envelope::SealMaterial) -> core::result::Result<radroots_secrets::envelope::LegacyV1ResealResult, radroots_secrets::error::Error> where V: core::ops::function::Fn(&[u8]) -> bool + core::marker::Send + core::marker::Sync +pub async fn radroots_secrets::envelope::EncryptedEnvelope::reseal_legacy_v1<V>(&self, &dyn radroots_secrets::wrapping::KeyWrapping, &radroots_secrets::envelope::LegacyV1ResealAuthority, &radroots_secrets::id::SecretRef, radroots_secrets::id::SecretRef, radroots_secrets::context::EnvelopeContext, &V, radroots_secrets::envelope::SealMaterial) -> core::result::Result<radroots_secrets::envelope::LegacyV1ResealResult, radroots_secrets::error::Error> where V: core::ops::function::Fn(&[u8]) -> bool + radroots_secrets::wrapping::HostBound pub async fn radroots_secrets::envelope::EncryptedEnvelope::seal(&dyn radroots_secrets::wrapping::KeyWrapping, radroots_secrets::envelope::SealRequest<'_>) -> core::result::Result<Self, radroots_secrets::error::Error> pub const fn radroots_secrets::envelope::EncryptedEnvelope::version(&self) -> u16 impl core::fmt::Debug for radroots_secrets::envelope::EncryptedEnvelope @@ -316,7 +316,7 @@ pub struct radroots_secrets::provider::SelectionPolicy impl radroots_secrets::provider::SelectionPolicy pub const fn radroots_secrets::provider::SelectionPolicy::new(radroots_secrets::id::BackendKind, radroots_secrets::provider::AccessPolicy) -> Self pub fn radroots_secrets::provider::SelectionPolicy::select<'a>(self, &'a [&'a dyn radroots_secrets::provider::SecretProvider]) -> core::result::Result<&'a dyn radroots_secrets::provider::SecretProvider, radroots_secrets::error::Error> -pub trait radroots_secrets::provider::SecretProvider: radroots_secrets::wrapping::KeyWrapping + core::marker::Send + core::marker::Sync +pub trait radroots_secrets::provider::SecretProvider: radroots_secrets::wrapping::KeyWrapping pub fn radroots_secrets::provider::SecretProvider::backend_kind(&self) -> radroots_secrets::id::BackendKind pub fn radroots_secrets::provider::SecretProvider::capabilities(&self) -> radroots_secrets::provider::SecretCapabilities impl radroots_secrets::provider::SecretProvider for radroots_secrets::file::FileProvider @@ -363,7 +363,9 @@ impl core::fmt::Debug for radroots_secrets::wrapping::WrappedSecret pub fn radroots_secrets::wrapping::WrappedSecret::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result pub const radroots_secrets::wrapping::SECRET_MATERIAL_MAX_BYTES: usize pub const radroots_secrets::wrapping::WRAPPED_SECRET_MAX_BYTES: usize -pub trait radroots_secrets::wrapping::KeyWrapping: core::marker::Send + core::marker::Sync +pub trait radroots_secrets::wrapping::HostBound: core::marker::Send + core::marker::Sync +impl<T: core::marker::Send + core::marker::Sync + ?core::marker::Sized> radroots_secrets::wrapping::HostBound for T +pub trait radroots_secrets::wrapping::KeyWrapping: radroots_secrets::wrapping::HostBound pub fn radroots_secrets::wrapping::KeyWrapping::unwrap<'a>(&'a self, radroots_secrets::wrapping::UnwrapRequest<'a>) -> radroots_secrets::wrapping::BoxFuture<'a, core::result::Result<radroots_secrets::wrapping::SecretMaterial, radroots_secrets::error::Error>> pub fn radroots_secrets::wrapping::KeyWrapping::unwrap_legacy_v1<'a>(&'a self, radroots_secrets::wrapping::LegacyV1UnwrapRequest<'a>) -> radroots_secrets::wrapping::BoxFuture<'a, core::result::Result<radroots_secrets::wrapping::SecretMaterial, radroots_secrets::error::Error>> pub fn radroots_secrets::wrapping::KeyWrapping::wrap<'a>(&'a self, radroots_secrets::wrapping::WrapRequest<'a>) -> radroots_secrets::wrapping::BoxFuture<'a, core::result::Result<radroots_secrets::wrapping::WrappedSecret, radroots_secrets::error::Error>> @@ -449,7 +451,7 @@ pub const fn radroots_secrets::envelope::EncryptedEnvelope::key_source(&self) -> pub async fn radroots_secrets::envelope::EncryptedEnvelope::open(&self, &dyn radroots_secrets::wrapping::KeyWrapping, &radroots_secrets::context::EnvelopeContext) -> core::result::Result<radroots_secrets::wrapping::SecretMaterial, radroots_secrets::error::Error> pub async fn radroots_secrets::envelope::EncryptedEnvelope::open_legacy_v1(&self, &dyn radroots_secrets::wrapping::KeyWrapping, &radroots_secrets::envelope::LegacyV1ResealAuthority, &radroots_secrets::id::SecretRef, &radroots_secrets::context::EnvelopeContext) -> core::result::Result<radroots_secrets::wrapping::SecretMaterial, radroots_secrets::error::Error> pub const fn radroots_secrets::envelope::EncryptedEnvelope::reference(&self) -> &radroots_secrets::id::SecretRef -pub async fn radroots_secrets::envelope::EncryptedEnvelope::reseal_legacy_v1<V>(&self, &dyn radroots_secrets::wrapping::KeyWrapping, &radroots_secrets::envelope::LegacyV1ResealAuthority, &radroots_secrets::id::SecretRef, radroots_secrets::id::SecretRef, radroots_secrets::context::EnvelopeContext, &V, radroots_secrets::envelope::SealMaterial) -> core::result::Result<radroots_secrets::envelope::LegacyV1ResealResult, radroots_secrets::error::Error> where V: core::ops::function::Fn(&[u8]) -> bool + core::marker::Send + core::marker::Sync +pub async fn radroots_secrets::envelope::EncryptedEnvelope::reseal_legacy_v1<V>(&self, &dyn radroots_secrets::wrapping::KeyWrapping, &radroots_secrets::envelope::LegacyV1ResealAuthority, &radroots_secrets::id::SecretRef, radroots_secrets::id::SecretRef, radroots_secrets::context::EnvelopeContext, &V, radroots_secrets::envelope::SealMaterial) -> core::result::Result<radroots_secrets::envelope::LegacyV1ResealResult, radroots_secrets::error::Error> where V: core::ops::function::Fn(&[u8]) -> bool + radroots_secrets::wrapping::HostBound pub async fn radroots_secrets::envelope::EncryptedEnvelope::seal(&dyn radroots_secrets::wrapping::KeyWrapping, radroots_secrets::envelope::SealRequest<'_>) -> core::result::Result<Self, radroots_secrets::error::Error> pub const fn radroots_secrets::envelope::EncryptedEnvelope::version(&self) -> u16 impl core::fmt::Debug for radroots_secrets::envelope::EncryptedEnvelope @@ -481,7 +483,7 @@ pub const fn radroots_secrets::id::SecretRef::key_version(&self) -> radroots_sec pub const fn radroots_secrets::id::SecretRef::new(radroots_secrets::id::SecretId, radroots_secrets::id::BackendKind, radroots_secrets::id::KeyVersion) -> Self impl core::fmt::Debug for radroots_secrets::id::SecretRef pub fn radroots_secrets::id::SecretRef::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result -pub trait radroots_secrets::KeyWrapping: core::marker::Send + core::marker::Sync +pub trait radroots_secrets::KeyWrapping: radroots_secrets::wrapping::HostBound pub fn radroots_secrets::KeyWrapping::unwrap<'a>(&'a self, radroots_secrets::wrapping::UnwrapRequest<'a>) -> radroots_secrets::wrapping::BoxFuture<'a, core::result::Result<radroots_secrets::wrapping::SecretMaterial, radroots_secrets::error::Error>> pub fn radroots_secrets::KeyWrapping::unwrap_legacy_v1<'a>(&'a self, radroots_secrets::wrapping::LegacyV1UnwrapRequest<'a>) -> radroots_secrets::wrapping::BoxFuture<'a, core::result::Result<radroots_secrets::wrapping::SecretMaterial, radroots_secrets::error::Error>> pub fn radroots_secrets::KeyWrapping::wrap<'a>(&'a self, radroots_secrets::wrapping::WrapRequest<'a>) -> radroots_secrets::wrapping::BoxFuture<'a, core::result::Result<radroots_secrets::wrapping::WrappedSecret, radroots_secrets::error::Error>> @@ -497,7 +499,7 @@ impl radroots_secrets::wrapping::KeyWrapping for radroots_secrets::memory::Memor pub fn radroots_secrets::memory::MemoryProvider::unwrap<'a>(&'a self, radroots_secrets::wrapping::UnwrapRequest<'a>) -> radroots_secrets::wrapping::BoxFuture<'a, core::result::Result<radroots_secrets::wrapping::SecretMaterial, radroots_secrets::error::Error>> pub fn radroots_secrets::memory::MemoryProvider::unwrap_legacy_v1<'a>(&'a self, radroots_secrets::wrapping::LegacyV1UnwrapRequest<'a>) -> radroots_secrets::wrapping::BoxFuture<'a, core::result::Result<radroots_secrets::wrapping::SecretMaterial, radroots_secrets::error::Error>> pub fn radroots_secrets::memory::MemoryProvider::wrap<'a>(&'a self, radroots_secrets::wrapping::WrapRequest<'a>) -> radroots_secrets::wrapping::BoxFuture<'a, core::result::Result<radroots_secrets::wrapping::WrappedSecret, radroots_secrets::error::Error>> -pub trait radroots_secrets::SecretProvider: radroots_secrets::wrapping::KeyWrapping + core::marker::Send + core::marker::Sync +pub trait radroots_secrets::SecretProvider: radroots_secrets::wrapping::KeyWrapping pub fn radroots_secrets::SecretProvider::backend_kind(&self) -> radroots_secrets::id::BackendKind pub fn radroots_secrets::SecretProvider::capabilities(&self) -> radroots_secrets::provider::SecretCapabilities impl radroots_secrets::provider::SecretProvider for radroots_secrets::file::FileProvider diff --git a/crates/secrets/README.md b/crates/secrets/README.md @@ -104,6 +104,14 @@ are native host adapters; `memory` is available on standard-library targets. No feature installs a global provider, starts a runtime, generates key material, selects a fallback, opens storage, or performs a credential prompt. +Provider and wrapping ownership is target-aware through +`wrapping::HostBound`: native hosts retain `Send + Sync` and sendable futures; +WASM hosts may retain local objects and local futures, including scoped +`Rc`/`RefCell` callbacks. This changes no residency, presence or hardware claim. +Envelope migration validators follow the same host boundary. Hosts still own +accepted work and callback lifetimes; the SPI starts no executor or background +task and supplies no unsafe thread bridge. + ## Security and serialization contract `SecretMaterial` is bounded, single-owner, zeroizing plaintext. It implements diff --git a/crates/secrets/src/envelope.rs b/crates/secrets/src/envelope.rs @@ -349,7 +349,7 @@ impl EncryptedEnvelope { material: SealMaterial, ) -> Result<LegacyV1ResealResult, Error> where - V: Fn(&[u8]) -> bool + Send + Sync, + V: Fn(&[u8]) -> bool + crate::wrapping::HostBound, { if material.nonce == self.nonce { return Err(Error::LegacyEntropyReuse); diff --git a/crates/secrets/src/provider.rs b/crates/secrets/src/provider.rs @@ -185,7 +185,7 @@ impl SecretCapabilities { } /// A wrapping provider selected and owned by the host. -pub trait SecretProvider: KeyWrapping + Send + Sync { +pub trait SecretProvider: KeyWrapping { /// Returns the adapter family implemented by this provider. fn backend_kind(&self) -> BackendKind; diff --git a/crates/secrets/src/wrapping.rs b/crates/secrets/src/wrapping.rs @@ -16,8 +16,25 @@ pub const SECRET_MATERIAL_MAX_BYTES: usize = 64 * 1024; /// Maximum protected value accepted by the generic wrapping boundary. pub const WRAPPED_SECRET_MAX_BYTES: usize = 128 * 1024; -/// A sendable provider future that does not prescribe an executor. +/// Native providers retain thread-safe ownership; browser providers may retain +/// local objects. This marker grants no residency or security capability. +#[cfg(not(target_arch = "wasm32"))] +pub trait HostBound: Send + Sync {} +#[cfg(not(target_arch = "wasm32"))] +impl<T: Send + Sync + ?Sized> HostBound for T {} +/// Native providers retain thread-safe ownership; browser providers may retain +/// local objects. This marker grants no residency or security capability. +#[cfg(target_arch = "wasm32")] +pub trait HostBound {} +#[cfg(target_arch = "wasm32")] +impl<T: ?Sized> HostBound for T {} + +/// Native provider future without a prescribed executor. +#[cfg(not(target_arch = "wasm32"))] pub type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>; +/// Browser-local provider future without a prescribed executor. +#[cfg(target_arch = "wasm32")] +pub type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + 'a>>; /// Opaque, single-owner plaintext material that zeroizes on drop. /// @@ -237,7 +254,7 @@ impl<'a> UnwrapRequest<'a> { } /// Executor-neutral, dyn-compatible data-key wrapping. -pub trait KeyWrapping: Send + Sync { +pub trait KeyWrapping: HostBound { /// Wraps explicit caller-owned plaintext for the selected reference. fn wrap<'a>(&'a self, request: WrapRequest<'a>) -> BoxFuture<'a, Result<WrappedSecret, Error>>; diff --git a/crates/secrets/tests/package_boundary.rs b/crates/secrets/tests/package_boundary.rs @@ -77,7 +77,7 @@ fn production_sources_publish_only_the_approved_traits() { assert_eq!( public_traits, - ["KeyWrapping", "SecretProvider"] + ["HostBound", "KeyWrapping", "SecretProvider"] .into_iter() .map(str::to_owned) .collect() diff --git a/crates/secrets/tests/provider_contract.rs b/crates/secrets/tests/provider_contract.rs @@ -143,6 +143,22 @@ fn provider_traits_are_dyn_compatible_and_round_trip_opaque_material() { assert_eq!(format!("{wrapped:?}"), "WrappedSecret(<redacted>)"); } +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn native_provider_objects_and_borrowed_futures_retain_thread_bounds() { + fn thread_safe<T: Send + Sync + ?Sized>() {} + fn send<T: Send>(_: T) {} + thread_safe::<dyn KeyWrapping>(); + thread_safe::<dyn SecretProvider>(); + let provider = provider(BackendKind::Memory, SecretCapabilities::unavailable()); + let reference = reference(BackendKind::Memory); + let context = context(); + let plaintext = SecretMaterial::from_slice(&[1; 32]).unwrap(); + let wrapped = WrappedSecret::from_bytes(vec![1; 32]).unwrap(); + send(provider.wrap(WrapRequest::new(&reference, &context, &plaintext))); + send(provider.unwrap(UnwrapRequest::new(&reference, &context, &wrapped))); +} + #[test] fn exact_selection_never_falls_back_to_another_backend() { let memory = provider( diff --git a/crates/storage_indexeddb/tests/browser/Cargo.lock b/crates/storage_indexeddb/tests/browser/Cargo.lock @@ -3,6 +3,16 @@ version = 4 [[package]] +name = "aead" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d122413f284cf2d62fb1b7db97e02edb8cda96d769b16e443a4f6195e35662b0" +dependencies = [ + "crypto-common", + "generic-array", +] + +[[package]] name = "arrayvec" version = "0.7.6" source = "registry+https://github.com/rust-lang/crates.io-index" @@ -52,6 +62,41 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" [[package]] +name = "chacha20" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3613f74bd2eac03dad61bd53dbe620703d4371614fe0bc3b9f04dd36fe4e818" +dependencies = [ + "cfg-if", + "cipher", + "cpufeatures", +] + +[[package]] +name = "chacha20poly1305" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10cd79432192d1c0f4e1a0fef9527696cc039165d729fb41b3f4f4f354c2dc35" +dependencies = [ + "aead", + "chacha20", + "cipher", + "poly1305", + "zeroize", +] + +[[package]] +name = "cipher" +version = "0.4.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad" +dependencies = [ + "crypto-common", + "inout", + "zeroize", +] + +[[package]] name = "const-oid" version = "0.9.6" source = "registry+https://github.com/rust-lang/crates.io-index" @@ -380,6 +425,15 @@ dependencies = [ ] [[package]] +name = "inout" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01" +dependencies = [ + "generic-array", +] + +[[package]] name = "itoa" version = "1.0.18" source = "registry+https://github.com/rust-lang/crates.io-index" @@ -451,6 +505,12 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" [[package]] +name = "opaque-debug" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c08d65885ee38876c4f86fa503fb49d7b507c2b62552df7c70b2fce627e06381" + +[[package]] name = "percent-encoding" version = "2.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" @@ -463,6 +523,17 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" [[package]] +name = "poly1305" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8159bd90725d2df49889a078b54f4f79e87f1f8a8444194cdca81d38f5393abf" +dependencies = [ + "cpufeatures", + "opaque-debug", + "universal-hash", +] + +[[package]] name = "potential_utf" version = "0.1.4" source = "registry+https://github.com/rust-lang/crates.io-index" @@ -563,7 +634,9 @@ name = "radroots_indexeddb_browser_fixture" version = "0.0.0" dependencies = [ "futures", + "hex", "js-sys", + "radroots_secrets", "radroots_storage", "radroots_storage_indexeddb", "wasm-bindgen", @@ -581,6 +654,17 @@ dependencies = [ ] [[package]] +name = "radroots_secrets" +version = "0.1.0-alpha" +dependencies = [ + "chacha20poly1305", + "serde", + "sha2", + "subtle", + "zeroize", +] + +[[package]] name = "radroots_storage" version = "0.1.0-alpha" dependencies = [ @@ -837,6 +921,16 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" [[package]] +name = "universal-hash" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc1de2c688dc15305988b563c3854064043356019f97a4b46276fe734c4f07ea" +dependencies = [ + "crypto-common", + "subtle", +] + +[[package]] name = "url" version = "2.5.8" source = "registry+https://github.com/rust-lang/crates.io-index" @@ -1036,10 +1130,6 @@ name = "radroots_nostr_connect" version = "0.1.0-alpha" [[patch.unused]] -name = "radroots_secrets" -version = "0.1.0-alpha" - -[[patch.unused]] name = "radroots_signing" version = "0.1.0-alpha" diff --git a/crates/storage_indexeddb/tests/browser/Cargo.toml b/crates/storage_indexeddb/tests/browser/Cargo.toml @@ -13,7 +13,9 @@ crate-type = ["cdylib"] [dependencies] radroots_storage_indexeddb = { path = "../.." } radroots_storage = { path = "../../../storage" } +radroots_secrets = { path = "../../../secrets", features = ["memory"] } futures = "=0.3.32" +hex = "=0.4.3" js-sys = "=0.3.91" wasm-bindgen = "=0.2.114" wasm-bindgen-futures = "=0.4.64" diff --git a/crates/storage_indexeddb/tests/browser/run.mjs b/crates/storage_indexeddb/tests/browser/run.mjs @@ -20,9 +20,9 @@ const server = createServer(async (req,res) => { } if (path.endsWith('/worker.js')) { res.setHeader('content-type','text/javascript'); - res.end(`import init, {Fixture} from './fixture.js'; + res.end(`import init, {Fixture,protected_round_trip} from './fixture.js'; await init(); - self.onmessage=async()=>{try{const db=await Fixture.open(77,true);await db.write(1,undefined,new Uint8Array([77]));await db.close();const again=await Fixture.open(77,false);const value=await again.read(1);await again.close();self.postMessage({value:Array.from(value)});}catch(error){self.postMessage({error:String(error)});}}; + self.onmessage=async()=>{try{await protected_round_trip(79);const db=await Fixture.open(77,true);await db.write(1,undefined,new Uint8Array([77]));await db.close();const again=await Fixture.open(77,false);const value=await again.read(1);await again.close();self.postMessage({value:Array.from(value)});}catch(error){self.postMessage({error:String(error)});}}; self.postMessage({ready:true});`); return; } res.setHeader('content-type',path.endsWith('.wasm') ? 'application/wasm' : 'text/javascript'); @@ -40,7 +40,7 @@ try { page.on('console',message=>{if(message.type()==='log')console.log(message.text());}); await page.goto(`http://127.0.0.1:${server.address().port}/index.html`); const result=await page.evaluate(async()=>{ - const {default:init,Fixture}=await import('./fixture.js'); await init(); + const {default:init,Fixture,protected_round_trip}=await import('./fixture.js'); await init(); console.log('STEP wasm_initialized'); const events=[]; const nativeTransaction=IDBDatabase.prototype.transaction; @@ -56,6 +56,7 @@ try { const tests=[]; const passed=name=>{tests.push(name);console.log('PASS '+name);}; try { + await protected_round_trip(78);passed('local provider and migration validator across real protected IndexedDB reopen'); await rejects(()=>Fixture.open(12,false),'missing_namespace'); console.log('STEP missing_existing_refused'); const db=await Fixture.open(12,true); diff --git a/crates/storage_indexeddb/tests/browser/src/lib.rs b/crates/storage_indexeddb/tests/browser/src/lib.rs @@ -5,6 +5,9 @@ use radroots_storage_indexeddb::{ }; use wasm_bindgen::prelude::*; +mod protected; +pub use protected::protected_round_trip; + fn failure(error: Error) -> JsValue { JsValue::from_str(error.code()) } diff --git a/crates/storage_indexeddb/tests/browser/src/protected.rs b/crates/storage_indexeddb/tests/browser/src/protected.rs @@ -0,0 +1,223 @@ +//! Volatile fixture provider. No persistent custody or hardware claim. +use radroots_secrets::context::{ + EnvelopeContext, EnvelopePurpose, EnvelopeSubject, PayloadSchemaId, +}; +use radroots_secrets::envelope::{LegacyV1ResealAuthority, Nonce, SealMaterial, SealRequest}; +use radroots_secrets::id::{BackendKind, KeyVersion}; +use radroots_secrets::memory::MemoryProvider; +use radroots_secrets::provider::SecretCapabilities; +use radroots_secrets::wrapping::{ + BoxFuture, LegacyV1UnwrapRequest, SecretMaterial, UnwrapRequest, WrapRequest, WrappedSecret, +}; +use radroots_secrets::{ + EncryptedEnvelope, Error, KeyWrapping, SecretId, SecretProvider, SecretRef, +}; +use radroots_storage::event::SourceGeneration; +use radroots_storage_indexeddb::{Batch, Database, Mutation, Namespace, OpenMode, RecordKey}; +use std::{cell::RefCell, rc::Rc}; +use wasm_bindgen::prelude::*; +use wasm_bindgen_futures::JsFuture; + +#[derive(Default)] +struct Calls { + wraps: usize, + unwraps: usize, + legacy: usize, +} +struct LocalProvider { + inner: MemoryProvider, + calls: Rc<RefCell<Calls>>, +} +async fn pause() { + JsFuture::from(js_sys::Promise::resolve(&JsValue::UNDEFINED)) + .await + .expect("fixture microtask"); +} +impl KeyWrapping for LocalProvider { + fn wrap<'a>(&'a self, request: WrapRequest<'a>) -> BoxFuture<'a, Result<WrappedSecret, Error>> { + let calls = self.calls.clone(); + Box::pin(async move { + pause().await; + calls.borrow_mut().wraps += 1; + self.inner.wrap(request).await + }) + } + fn unwrap<'a>( + &'a self, + request: UnwrapRequest<'a>, + ) -> BoxFuture<'a, Result<SecretMaterial, Error>> { + let calls = self.calls.clone(); + Box::pin(async move { + pause().await; + calls.borrow_mut().unwraps += 1; + self.inner.unwrap(request).await + }) + } + fn unwrap_legacy_v1<'a>( + &'a self, + request: LegacyV1UnwrapRequest<'a>, + ) -> BoxFuture<'a, Result<SecretMaterial, Error>> { + let calls = self.calls.clone(); + Box::pin(async move { + pause().await; + calls.borrow_mut().legacy += 1; + // Exact frozen envelope_contract.rs vector, never a runtime key. + if request.reference().id().as_str() != "envelope-key" + || request.reference().backend() != BackendKind::Memory + || request.reference().key_version().get() != 7 + || request.wrapped().as_bytes() != [0x4b; 32] + { + return Err(Error::LegacyEnvelopeDenied); + } + SecretMaterial::from_slice(&[0x11; 32]) + }) + } +} +impl SecretProvider for LocalProvider { + fn backend_kind(&self) -> BackendKind { + self.inner.backend_kind() + } + fn capabilities(&self) -> SecretCapabilities { + self.inner.capabilities() + } +} +fn reference() -> SecretRef { + SecretRef::new( + SecretId::parse("local-fixture-key").unwrap(), + BackendKind::Memory, + KeyVersion::new(1).unwrap(), + ) +} +fn context(subject: &str) -> EnvelopeContext { + EnvelopeContext::new( + EnvelopePurpose::parse("radroots.browser_fixture").unwrap(), + EnvelopeSubject::parse("fixture", subject).unwrap(), + PayloadSchemaId::parse("radroots.browser_fixture.v1").unwrap(), + ) +} +fn secret_error(_: Error) -> JsValue { + JsValue::from_str("protected_fixture_failure") +} + +#[wasm_bindgen] +pub async fn protected_round_trip(n: u8) -> Result<(), JsValue> { + let calls = Rc::new(RefCell::new(Calls::default())); + let provider = LocalProvider { + inner: MemoryProvider::new(), + calls: calls.clone(), + }; + provider + .inner + .provision( + &reference(), + SecretMaterial::from_slice(&[0x41; 32]).map_err(secret_error)?, + ) + .map_err(secret_error)?; + let plaintext = + SecretMaterial::from_slice(b"browser protected fixture").map_err(secret_error)?; + let expected = context(&n.to_string()); + let encoded = EncryptedEnvelope::seal( + &provider, + SealRequest::new( + reference(), + expected.clone(), + &plaintext, + SealMaterial::new( + SecretMaterial::from_slice(&[0x41; 32]).map_err(secret_error)?, + Nonce::new([0x24; 24]), + ), + ), + ) + .await + .map_err(secret_error)? + .encode() + .map_err(secret_error)?; + assert!( + !encoded + .windows(plaintext.len()) + .any(|value| plaintext.expose_secret(|plain| plain == value)) + ); + let namespace = Namespace::new(SourceGeneration::new([n; 32]).unwrap()); + let record = RecordKey::new([1; 32]); + let db = Database::open(namespace, OpenMode::CreateNew) + .await + .map_err(super::failure)?; + db.compare_exchange( + Batch::new(vec![ + Mutation::new(record, None, Some(encoded)).map_err(super::failure)?, + ]) + .map_err(super::failure)?, + ) + .await + .map_err(super::failure)?; + db.close().await.map_err(super::failure)?; + let reopened = Database::open(namespace, OpenMode::Existing) + .await + .map_err(super::failure)?; + let mut stored = reopened + .get(record) + .await + .map_err(super::failure)? + .ok_or_else(|| JsValue::from_str("missing_protected_fixture"))?; + let envelope = EncryptedEnvelope::decode(&stored).map_err(secret_error)?; + let opened = envelope + .open(&provider, &expected) + .await + .map_err(secret_error)?; + opened.expose_secret(|bytes| assert_eq!(bytes, b"browser protected fixture")); + assert_eq!( + envelope.open(&provider, &context("foreign")).await.err(), + Some(Error::ContextMismatch) + ); + *stored.last_mut().unwrap() ^= 1; + let tampered = EncryptedEnvelope::decode(&stored).map_err(secret_error)?; + assert_eq!( + tampered.open(&provider, &expected).await.err(), + Some(Error::DecryptFailed) + ); + reopened.close().await.map_err(super::failure)?; + + // Existing independently frozen v1 ciphertext and its public fixture key. + let legacy=hex::decode("52525331000101010100000007000c656e76656c6f70652d6b6579222222222222222222222222222222222222222222222222000000204b4b4b4b4b4b4b4b4b4b4b4b4b4b4b4b4b4b4b4b4b4b4b4b4b4b4b4b4b4b4b4b00000028f106837e33d690e7c5287abdd815ce9257b7b5b176ea9596abf3b7fe745aec5a8c2487a553d4659d").unwrap(); + let legacy = EncryptedEnvelope::decode(&legacy).map_err(secret_error)?; + assert_eq!( + legacy.open(&provider, &expected).await.err(), + Some(Error::LegacyEnvelopeDenied) + ); + let authority = LegacyV1ResealAuthority::new(); + let original = SecretRef::new( + SecretId::parse("envelope-key").unwrap(), + BackendKind::Memory, + KeyVersion::new(7).unwrap(), + ); + let validations = Rc::new(RefCell::new(0)); + let validator = |bytes: &[u8]| { + *validations.borrow_mut() += 1; + bytes == b"radroots envelope vector" + }; + let resealed = legacy + .reseal_legacy_v1( + &provider, + &authority, + &original, + reference(), + expected.clone(), + &validator, + SealMaterial::new( + SecretMaterial::from_slice(&[0x41; 32]).map_err(secret_error)?, + Nonce::new([0x55; 24]), + ), + ) + .await + .map_err(secret_error)? + .into_envelope(); + assert_eq!(*validations.borrow(), 1); + resealed + .open(&provider, &expected) + .await + .map_err(secret_error)? + .expose_secret(|bytes| assert_eq!(bytes, b"radroots envelope vector")); + let calls = calls.borrow(); + assert_eq!((calls.wraps, calls.unwraps, calls.legacy), (2, 3, 1)); + Ok(()) +}