lib

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

commit d5e023b3fc97764a7821b347756eb8987dc78739
parent 7cbbb170ce4a9ef51b744b7c5bce4a11c3786b96
Author: triesap <tyson@radroots.org>
Date:   Sun, 18 Oct 2026 21:56:22 +0000

secrets: Persist explicitly bound browser wrapping keys

- Keep nonextractable origin keys behind an opt-in browser provider.
- Commit first key bindings atomically and refuse missing-key replacement.
- Bound owned setup, wrapping and close work across cancelled observations.
- Verify persistence, failure cases and restart in three browser engines.

Diffstat:
MCargo.lock | 5+++++
Acontracts/api_baselines/radroots_secrets.wasm32_browser.txt | 496+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acontracts/architecture/decisions/browser_secret_provider.v1.json | 71+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcrates/secrets/Cargo.toml | 8++++++++
Mcrates/secrets/README.md | 25++++++++++++++++++++++++-
Acrates/secrets/src/browser/crypto.rs | 218+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acrates/secrets/src/browser/idb.rs | 289++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acrates/secrets/src/browser/mod.rs | 477+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcrates/secrets/src/lib.rs | 2++
Mcrates/secrets/tests/package_boundary.rs | 24+++++++++++++++++++++---
Mcrates/secrets/tests/security_contract.rs | 47+++++++++++++++++++++++++++++++++++++++++++----
Mcrates/storage_indexeddb/tests/browser/Cargo.lock | 6++++++
Mcrates/storage_indexeddb/tests/browser/Cargo.toml | 3++-
Mcrates/storage_indexeddb/tests/browser/run.mjs | 119++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---
Mcrates/storage_indexeddb/tests/browser/src/lib.rs | 2++
Acrates/storage_indexeddb/tests/browser/src/persistent.rs | 259+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
16 files changed, 2038 insertions(+), 13 deletions(-)

diff --git a/Cargo.lock b/Cargo.lock @@ -3482,14 +3482,19 @@ name = "radroots_secrets" version = "0.1.0-alpha" dependencies = [ "chacha20poly1305", + "futures", "futures-executor", "hex", + "js-sys", "keyring", "serde", "serde_json", "sha2", "subtle", "tempfile", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", "zeroize", ] diff --git a/contracts/api_baselines/radroots_secrets.wasm32_browser.txt b/contracts/api_baselines/radroots_secrets.wasm32_browser.txt @@ -0,0 +1,496 @@ +pub mod radroots_secrets +pub mod radroots_secrets::browser +#[non_exhaustive] pub enum radroots_secrets::browser::BrowserError +pub radroots_secrets::browser::BrowserError::Aborted +pub radroots_secrets::browser::BrowserError::Capacity +pub radroots_secrets::browser::BrowserError::Closed +pub radroots_secrets::browser::BrowserError::CommitUnknown +pub radroots_secrets::browser::BrowserError::IncompatibleSchema +pub radroots_secrets::browser::BrowserError::KeyMismatch +pub radroots_secrets::browser::BrowserError::MissingKey +pub radroots_secrets::browser::BrowserError::MissingNamespace +pub radroots_secrets::browser::BrowserError::NamespaceExists +pub radroots_secrets::browser::BrowserError::Provider(radroots_secrets::error::Error) +pub radroots_secrets::browser::BrowserError::Unavailable +impl radroots_secrets::browser::BrowserError +pub const fn radroots_secrets::browser::BrowserError::code(self) -> &'static str +impl core::error::Error for radroots_secrets::browser::BrowserError +impl core::fmt::Display for radroots_secrets::browser::BrowserError +pub fn radroots_secrets::browser::BrowserError::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +pub struct radroots_secrets::browser::BrowserProvider +impl radroots_secrets::browser::BrowserProvider +pub async fn radroots_secrets::browser::BrowserProvider::close(&self) -> core::result::Result<(), radroots_secrets::browser::BrowserError> +pub async fn radroots_secrets::browser::BrowserProvider::create(radroots_secrets::id::SecretId, radroots_secrets::id::SecretRef) -> core::result::Result<Self, radroots_secrets::browser::BrowserError> +pub fn radroots_secrets::browser::BrowserProvider::fingerprint(&self) -> [u8; 32] +pub async fn radroots_secrets::browser::BrowserProvider::open(radroots_secrets::id::SecretId, radroots_secrets::id::SecretRef, [u8; 32]) -> core::result::Result<Self, radroots_secrets::browser::BrowserError> +impl core::fmt::Debug for radroots_secrets::browser::BrowserProvider +pub fn radroots_secrets::browser::BrowserProvider::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +impl radroots_secrets::provider::SecretProvider for radroots_secrets::browser::BrowserProvider +pub fn radroots_secrets::browser::BrowserProvider::backend_kind(&self) -> radroots_secrets::id::BackendKind +pub fn radroots_secrets::browser::BrowserProvider::capabilities(&self) -> radroots_secrets::provider::SecretCapabilities +impl radroots_secrets::wrapping::KeyWrapping for radroots_secrets::browser::BrowserProvider +pub fn radroots_secrets::browser::BrowserProvider::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::browser::BrowserProvider::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::browser::BrowserProvider::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 mod radroots_secrets::context +pub struct radroots_secrets::context::EnvelopeContext +impl radroots_secrets::context::EnvelopeContext +pub fn radroots_secrets::context::EnvelopeContext::authentication_digest(&self) -> [u8; 32] +pub const fn radroots_secrets::context::EnvelopeContext::new(radroots_secrets::context::EnvelopePurpose, radroots_secrets::context::EnvelopeSubject, radroots_secrets::context::PayloadSchemaId) -> Self +pub const fn radroots_secrets::context::EnvelopeContext::payload_schema(&self) -> &radroots_secrets::context::PayloadSchemaId +pub const fn radroots_secrets::context::EnvelopeContext::purpose(&self) -> &radroots_secrets::context::EnvelopePurpose +pub const fn radroots_secrets::context::EnvelopeContext::subject(&self) -> &radroots_secrets::context::EnvelopeSubject +pub fn radroots_secrets::context::EnvelopeContext::to_canonical_bytes(&self) -> alloc::vec::Vec<u8> +impl core::fmt::Debug for radroots_secrets::context::EnvelopeContext +pub fn radroots_secrets::context::EnvelopeContext::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +impl serde_core::ser::Serialize for radroots_secrets::context::EnvelopeContext +pub fn radroots_secrets::context::EnvelopeContext::serialize<S>(&self, S) -> core::result::Result<<S as serde_core::ser::Serializer>::Ok, <S as serde_core::ser::Serializer>::Error> where S: serde_core::ser::Serializer +impl<'de> serde_core::de::Deserialize<'de> for radroots_secrets::context::EnvelopeContext +pub fn radroots_secrets::context::EnvelopeContext::deserialize<D>(D) -> core::result::Result<Self, <D as serde_core::de::Deserializer>::Error> where D: serde_core::de::Deserializer<'de> +pub struct radroots_secrets::context::EnvelopePurpose(_) +impl radroots_secrets::context::EnvelopePurpose +pub fn radroots_secrets::context::EnvelopePurpose::as_str(&self) -> &str +pub fn radroots_secrets::context::EnvelopePurpose::parse(impl core::convert::Into<alloc::string::String>) -> core::result::Result<Self, radroots_secrets::error::Error> +impl core::fmt::Debug for radroots_secrets::context::EnvelopePurpose +pub fn radroots_secrets::context::EnvelopePurpose::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +impl core::fmt::Display for radroots_secrets::context::EnvelopePurpose +pub fn radroots_secrets::context::EnvelopePurpose::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +pub struct radroots_secrets::context::EnvelopeSubject +impl radroots_secrets::context::EnvelopeSubject +pub fn radroots_secrets::context::EnvelopeSubject::parse(impl core::convert::Into<alloc::string::String>, impl core::convert::Into<alloc::string::String>) -> core::result::Result<Self, radroots_secrets::error::Error> +pub fn radroots_secrets::context::EnvelopeSubject::subject_type(&self) -> &str +pub fn radroots_secrets::context::EnvelopeSubject::value(&self) -> &str +impl core::fmt::Debug for radroots_secrets::context::EnvelopeSubject +pub fn radroots_secrets::context::EnvelopeSubject::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +impl core::fmt::Display for radroots_secrets::context::EnvelopeSubject +pub fn radroots_secrets::context::EnvelopeSubject::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +pub struct radroots_secrets::context::PayloadSchemaId(_) +impl radroots_secrets::context::PayloadSchemaId +pub fn radroots_secrets::context::PayloadSchemaId::as_str(&self) -> &str +pub fn radroots_secrets::context::PayloadSchemaId::parse(impl core::convert::Into<alloc::string::String>) -> core::result::Result<Self, radroots_secrets::error::Error> +impl core::fmt::Debug for radroots_secrets::context::PayloadSchemaId +pub fn radroots_secrets::context::PayloadSchemaId::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +impl core::fmt::Display for radroots_secrets::context::PayloadSchemaId +pub fn radroots_secrets::context::PayloadSchemaId::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +pub const radroots_secrets::context::ENVELOPE_CONTEXT_DOMAIN: &[u8] +pub const radroots_secrets::context::ENVELOPE_CONTEXT_VERSION: u16 +pub const radroots_secrets::context::ENVELOPE_PURPOSE_MAX_BYTES: usize +pub const radroots_secrets::context::ENVELOPE_SUBJECT_TYPE_MAX_BYTES: usize +pub const radroots_secrets::context::ENVELOPE_SUBJECT_VALUE_MAX_BYTES: usize +pub const radroots_secrets::context::PAYLOAD_SCHEMA_MAX_BYTES: usize +pub mod radroots_secrets::envelope +#[non_exhaustive] pub enum radroots_secrets::envelope::Cipher +pub radroots_secrets::envelope::Cipher::XChaCha20Poly1305 +#[non_exhaustive] pub enum radroots_secrets::envelope::KeySource +pub radroots_secrets::envelope::KeySource::ProviderWrapped +pub struct radroots_secrets::envelope::EncryptedEnvelope +impl radroots_secrets::envelope::EncryptedEnvelope +pub const fn radroots_secrets::envelope::EncryptedEnvelope::cipher(&self) -> radroots_secrets::envelope::Cipher +pub const fn radroots_secrets::envelope::EncryptedEnvelope::context(&self) -> core::option::Option<&radroots_secrets::context::EnvelopeContext> +pub fn radroots_secrets::envelope::EncryptedEnvelope::decode(&[u8]) -> core::result::Result<Self, radroots_secrets::error::Error> +pub fn radroots_secrets::envelope::EncryptedEnvelope::encode(&self) -> core::result::Result<alloc::vec::Vec<u8>, radroots_secrets::error::Error> +pub const fn radroots_secrets::envelope::EncryptedEnvelope::key_source(&self) -> radroots_secrets::envelope::KeySource +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 + 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 +pub fn radroots_secrets::envelope::EncryptedEnvelope::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +impl serde_core::ser::Serialize for radroots_secrets::envelope::EncryptedEnvelope +pub fn radroots_secrets::envelope::EncryptedEnvelope::serialize<S>(&self, S) -> core::result::Result<<S as serde_core::ser::Serializer>::Ok, <S as serde_core::ser::Serializer>::Error> where S: serde_core::ser::Serializer +impl<'de> serde_core::de::Deserialize<'de> for radroots_secrets::envelope::EncryptedEnvelope +pub fn radroots_secrets::envelope::EncryptedEnvelope::deserialize<D>(D) -> core::result::Result<Self, <D as serde_core::de::Deserializer>::Error> where D: serde_core::de::Deserializer<'de> +pub struct radroots_secrets::envelope::LegacyV1ResealAuthority +impl radroots_secrets::envelope::LegacyV1ResealAuthority +pub const fn radroots_secrets::envelope::LegacyV1ResealAuthority::new() -> Self +impl core::fmt::Debug for radroots_secrets::envelope::LegacyV1ResealAuthority +pub fn radroots_secrets::envelope::LegacyV1ResealAuthority::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +pub struct radroots_secrets::envelope::LegacyV1ResealResult +impl radroots_secrets::envelope::LegacyV1ResealResult +pub const fn radroots_secrets::envelope::LegacyV1ResealResult::envelope(&self) -> &radroots_secrets::envelope::EncryptedEnvelope +pub fn radroots_secrets::envelope::LegacyV1ResealResult::into_envelope(self) -> radroots_secrets::envelope::EncryptedEnvelope +pub const fn radroots_secrets::envelope::LegacyV1ResealResult::plaintext_commitment(&self) -> &[u8; 32] +impl core::fmt::Debug for radroots_secrets::envelope::LegacyV1ResealResult +pub fn radroots_secrets::envelope::LegacyV1ResealResult::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +pub struct radroots_secrets::envelope::Nonce(_) +impl radroots_secrets::envelope::Nonce +pub const fn radroots_secrets::envelope::Nonce::as_bytes(&self) -> &[u8; 24] +pub const fn radroots_secrets::envelope::Nonce::new([u8; 24]) -> Self +impl core::fmt::Debug for radroots_secrets::envelope::Nonce +pub fn radroots_secrets::envelope::Nonce::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +pub struct radroots_secrets::envelope::SealMaterial +impl radroots_secrets::envelope::SealMaterial +pub const fn radroots_secrets::envelope::SealMaterial::new(radroots_secrets::wrapping::SecretMaterial, radroots_secrets::envelope::Nonce) -> Self +impl core::fmt::Debug for radroots_secrets::envelope::SealMaterial +pub fn radroots_secrets::envelope::SealMaterial::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +pub struct radroots_secrets::envelope::SealRequest<'a> +impl<'a> radroots_secrets::envelope::SealRequest<'a> +pub const fn radroots_secrets::envelope::SealRequest<'a>::new(radroots_secrets::id::SecretRef, radroots_secrets::context::EnvelopeContext, &'a radroots_secrets::wrapping::SecretMaterial, radroots_secrets::envelope::SealMaterial) -> Self +impl core::fmt::Debug for radroots_secrets::envelope::SealRequest<'_> +pub fn radroots_secrets::envelope::SealRequest<'_>::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +pub const radroots_secrets::envelope::ENVELOPE_MAX_BYTES: usize +pub const radroots_secrets::envelope::ENVELOPE_VERSION: u16 +pub const radroots_secrets::envelope::LEGACY_ENVELOPE_VERSION: u16 +pub mod radroots_secrets::error +#[non_exhaustive] pub enum radroots_secrets::error::ContextField +pub radroots_secrets::error::ContextField::PayloadSchema +pub radroots_secrets::error::ContextField::Purpose +pub radroots_secrets::error::ContextField::SubjectType +pub radroots_secrets::error::ContextField::SubjectValue +#[non_exhaustive] pub enum radroots_secrets::error::ContextValueError +pub radroots_secrets::error::ContextValueError::Empty +pub radroots_secrets::error::ContextValueError::NonCanonical +pub radroots_secrets::error::ContextValueError::TooLong +pub radroots_secrets::error::ContextValueError::TooLong::actual_bytes: usize +pub radroots_secrets::error::ContextValueError::TooLong::max_bytes: usize +impl core::fmt::Display for radroots_secrets::error::ContextValueError +pub fn radroots_secrets::error::ContextValueError::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +#[non_exhaustive] pub enum radroots_secrets::error::Error +pub radroots_secrets::error::Error::BackendFailure +pub radroots_secrets::error::Error::BackendFailure::backend: radroots_secrets::id::BackendKind +pub radroots_secrets::error::Error::BackendFailure::operation: radroots_secrets::error::Operation +pub radroots_secrets::error::Error::BackendMismatch +pub radroots_secrets::error::Error::BackendMismatch::provider: radroots_secrets::id::BackendKind +pub radroots_secrets::error::Error::BackendMismatch::reference: radroots_secrets::id::BackendKind +pub radroots_secrets::error::Error::BackendUnavailable +pub radroots_secrets::error::Error::BackendUnavailable::backend: radroots_secrets::id::BackendKind +pub radroots_secrets::error::Error::ContextMismatch +pub radroots_secrets::error::Error::DecryptFailed +pub radroots_secrets::error::Error::EncryptFailed +pub radroots_secrets::error::Error::EnvelopeMalformed +pub radroots_secrets::error::Error::EnvelopeTooLarge +pub radroots_secrets::error::Error::EnvelopeTooLarge::actual_bytes: usize +pub radroots_secrets::error::Error::EnvelopeTooLarge::max_bytes: usize +pub radroots_secrets::error::Error::InsecurePermissions +pub radroots_secrets::error::Error::InvalidContextValue +pub radroots_secrets::error::Error::InvalidContextValue::field: radroots_secrets::error::ContextField +pub radroots_secrets::error::Error::InvalidContextValue::reason: radroots_secrets::error::ContextValueError +pub radroots_secrets::error::Error::InvalidDataKeyLength +pub radroots_secrets::error::Error::InvalidDataKeyLength::actual_bytes: usize +pub radroots_secrets::error::Error::InvalidKeyVersion +pub radroots_secrets::error::Error::InvalidRotation +pub radroots_secrets::error::Error::InvalidSecretId(radroots_secrets::error::SecretIdError) +pub radroots_secrets::error::Error::InvalidSecretLength +pub radroots_secrets::error::Error::InvalidSecretLength::actual_bytes: usize +pub radroots_secrets::error::Error::InvalidSecretLength::max_bytes: usize +pub radroots_secrets::error::Error::InvalidServiceName +pub radroots_secrets::error::Error::InvalidWrappedLength +pub radroots_secrets::error::Error::InvalidWrappedLength::actual_bytes: usize +pub radroots_secrets::error::Error::InvalidWrappedLength::max_bytes: usize +pub radroots_secrets::error::Error::LegacyEntropyReuse +pub radroots_secrets::error::Error::LegacyEnvelopeDenied +pub radroots_secrets::error::Error::LegacyPayloadValidationFailed +pub radroots_secrets::error::Error::PolicyUnsupported +pub radroots_secrets::error::Error::PolicyUnsupported::backend: radroots_secrets::id::BackendKind +pub radroots_secrets::error::Error::PolicyUnsupported::requirement: radroots_secrets::error::PolicyRequirement +pub radroots_secrets::error::Error::ProviderReferenceMismatch +pub radroots_secrets::error::Error::SecretAlreadyExists +pub radroots_secrets::error::Error::SecretAlreadyExists::backend: radroots_secrets::id::BackendKind +pub radroots_secrets::error::Error::SecretAlreadyExists::key_version: u32 +pub radroots_secrets::error::Error::SecretNotFound +pub radroots_secrets::error::Error::SecretNotFound::backend: radroots_secrets::id::BackendKind +pub radroots_secrets::error::Error::SecretNotFound::key_version: u32 +pub radroots_secrets::error::Error::UnsafePath +pub radroots_secrets::error::Error::UnsupportedBackend +pub radroots_secrets::error::Error::UnsupportedBackend::backend: u8 +pub radroots_secrets::error::Error::UnsupportedCipher +pub radroots_secrets::error::Error::UnsupportedCipher::cipher: u8 +pub radroots_secrets::error::Error::UnsupportedContextVersion +pub radroots_secrets::error::Error::UnsupportedContextVersion::version: u16 +pub radroots_secrets::error::Error::UnsupportedEnvelopeVersion +pub radroots_secrets::error::Error::UnsupportedEnvelopeVersion::version: u16 +pub radroots_secrets::error::Error::UnsupportedKeySource +pub radroots_secrets::error::Error::UnsupportedKeySource::key_source: u8 +impl core::error::Error for radroots_secrets::error::Error +impl core::fmt::Display for radroots_secrets::error::Error +pub fn radroots_secrets::error::Error::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +#[non_exhaustive] pub enum radroots_secrets::error::Operation +pub radroots_secrets::error::Operation::Open +pub radroots_secrets::error::Operation::Provision +pub radroots_secrets::error::Operation::Read +pub radroots_secrets::error::Operation::Remove +pub radroots_secrets::error::Operation::Rotate +pub radroots_secrets::error::Operation::Unwrap +pub radroots_secrets::error::Operation::Wrap +pub radroots_secrets::error::Operation::Write +#[non_exhaustive] pub enum radroots_secrets::error::PolicyRequirement +pub radroots_secrets::error::PolicyRequirement::DeviceLocal +pub radroots_secrets::error::PolicyRequirement::HardwareBacked +pub radroots_secrets::error::PolicyRequirement::UserPresence +#[non_exhaustive] pub enum radroots_secrets::error::SecretIdError +pub radroots_secrets::error::SecretIdError::Empty +pub radroots_secrets::error::SecretIdError::InvalidCharacter +pub radroots_secrets::error::SecretIdError::InvalidCharacter::byte_offset: usize +pub radroots_secrets::error::SecretIdError::TooLong +pub radroots_secrets::error::SecretIdError::TooLong::actual_bytes: usize +pub radroots_secrets::error::SecretIdError::TooLong::max_bytes: usize +impl core::fmt::Display for radroots_secrets::error::SecretIdError +pub fn radroots_secrets::error::SecretIdError::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +pub mod radroots_secrets::id +#[non_exhaustive] pub enum radroots_secrets::id::BackendKind +pub radroots_secrets::id::BackendKind::External +pub radroots_secrets::id::BackendKind::File +pub radroots_secrets::id::BackendKind::Keyring +pub radroots_secrets::id::BackendKind::Memory +pub struct radroots_secrets::id::KeyVersion(_) +impl radroots_secrets::id::KeyVersion +pub const fn radroots_secrets::id::KeyVersion::get(self) -> u32 +pub const fn radroots_secrets::id::KeyVersion::new(u32) -> core::result::Result<Self, radroots_secrets::error::Error> +pub struct radroots_secrets::id::SecretId(_) +impl radroots_secrets::id::SecretId +pub fn radroots_secrets::id::SecretId::as_str(&self) -> &str +pub fn radroots_secrets::id::SecretId::parse(impl core::convert::AsRef<str>) -> core::result::Result<Self, radroots_secrets::error::Error> +impl core::fmt::Debug for radroots_secrets::id::SecretId +pub fn radroots_secrets::id::SecretId::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +impl core::fmt::Display for radroots_secrets::id::SecretId +pub fn radroots_secrets::id::SecretId::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +impl core::str::traits::FromStr for radroots_secrets::id::SecretId +pub type radroots_secrets::id::SecretId::Err = radroots_secrets::error::Error +pub fn radroots_secrets::id::SecretId::from_str(&str) -> core::result::Result<Self, Self::Err> +impl serde_core::ser::Serialize for radroots_secrets::id::SecretId +pub fn radroots_secrets::id::SecretId::serialize<S>(&self, S) -> core::result::Result<<S as serde_core::ser::Serializer>::Ok, <S as serde_core::ser::Serializer>::Error> where S: serde_core::ser::Serializer +impl<'de> serde_core::de::Deserialize<'de> for radroots_secrets::id::SecretId +pub fn radroots_secrets::id::SecretId::deserialize<D>(D) -> core::result::Result<Self, <D as serde_core::de::Deserializer>::Error> where D: serde_core::de::Deserializer<'de> +pub struct radroots_secrets::id::SecretRef +impl radroots_secrets::id::SecretRef +pub const fn radroots_secrets::id::SecretRef::backend(&self) -> radroots_secrets::id::BackendKind +pub const fn radroots_secrets::id::SecretRef::id(&self) -> &radroots_secrets::id::SecretId +pub const fn radroots_secrets::id::SecretRef::key_version(&self) -> radroots_secrets::id::KeyVersion +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 const radroots_secrets::id::SECRET_ID_MAX_BYTES: usize +pub mod radroots_secrets::memory +pub struct radroots_secrets::memory::MemoryProvider +impl radroots_secrets::memory::MemoryProvider +pub fn radroots_secrets::memory::MemoryProvider::contains(&self, &radroots_secrets::id::SecretRef) -> core::result::Result<bool, radroots_secrets::error::Error> +pub fn radroots_secrets::memory::MemoryProvider::new() -> Self +pub fn radroots_secrets::memory::MemoryProvider::provision(&self, &radroots_secrets::id::SecretRef, radroots_secrets::wrapping::SecretMaterial) -> core::result::Result<(), radroots_secrets::error::Error> +pub fn radroots_secrets::memory::MemoryProvider::remove(&self, &radroots_secrets::id::SecretRef) -> core::result::Result<bool, radroots_secrets::error::Error> +pub fn radroots_secrets::memory::MemoryProvider::rotate(&self, &radroots_secrets::id::SecretRef, &radroots_secrets::id::SecretRef, radroots_secrets::wrapping::SecretMaterial) -> core::result::Result<(), radroots_secrets::error::Error> +impl core::fmt::Debug for radroots_secrets::memory::MemoryProvider +pub fn radroots_secrets::memory::MemoryProvider::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +impl radroots_secrets::provider::SecretProvider for radroots_secrets::memory::MemoryProvider +pub fn radroots_secrets::memory::MemoryProvider::backend_kind(&self) -> radroots_secrets::id::BackendKind +pub fn radroots_secrets::memory::MemoryProvider::capabilities(&self) -> radroots_secrets::provider::SecretCapabilities +impl radroots_secrets::wrapping::KeyWrapping for radroots_secrets::memory::MemoryProvider +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 mod radroots_secrets::provider +#[non_exhaustive] pub enum radroots_secrets::provider::CapabilitySupport +pub radroots_secrets::provider::CapabilitySupport::Supported +pub radroots_secrets::provider::CapabilitySupport::Unavailable +#[non_exhaustive] pub enum radroots_secrets::provider::HardwarePolicy +pub radroots_secrets::provider::HardwarePolicy::Any +pub radroots_secrets::provider::HardwarePolicy::PreferHardwareBacked +pub radroots_secrets::provider::HardwarePolicy::RequireHardwareBacked +#[non_exhaustive] pub enum radroots_secrets::provider::ResidencyPolicy +pub radroots_secrets::provider::ResidencyPolicy::Any +pub radroots_secrets::provider::ResidencyPolicy::DeviceLocal +#[non_exhaustive] pub enum radroots_secrets::provider::ResidencySupport +pub radroots_secrets::provider::ResidencySupport::DeviceLocal +pub radroots_secrets::provider::ResidencySupport::UserProfile +pub radroots_secrets::provider::ResidencySupport::Volatile +#[non_exhaustive] pub enum radroots_secrets::provider::UserPresencePolicy +pub radroots_secrets::provider::UserPresencePolicy::NotRequired +pub radroots_secrets::provider::UserPresencePolicy::Required +pub struct radroots_secrets::provider::AccessPolicy +impl radroots_secrets::provider::AccessPolicy +pub const fn radroots_secrets::provider::AccessPolicy::new(radroots_secrets::provider::ResidencyPolicy, radroots_secrets::provider::UserPresencePolicy, radroots_secrets::provider::HardwarePolicy) -> Self +pub const fn radroots_secrets::provider::AccessPolicy::standard() -> Self +pub struct radroots_secrets::provider::SecretCapabilities +impl radroots_secrets::provider::SecretCapabilities +pub const fn radroots_secrets::provider::SecretCapabilities::available(radroots_secrets::provider::ResidencySupport, radroots_secrets::provider::CapabilitySupport, radroots_secrets::provider::CapabilitySupport) -> Self +pub const fn radroots_secrets::provider::SecretCapabilities::hardware_backed(self) -> radroots_secrets::provider::CapabilitySupport +pub const fn radroots_secrets::provider::SecretCapabilities::is_available(self) -> bool +pub const fn radroots_secrets::provider::SecretCapabilities::residency(self) -> radroots_secrets::provider::ResidencySupport +pub const fn radroots_secrets::provider::SecretCapabilities::unavailable() -> Self +pub const fn radroots_secrets::provider::SecretCapabilities::user_presence(self) -> radroots_secrets::provider::CapabilitySupport +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 +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::browser::BrowserProvider +pub fn radroots_secrets::browser::BrowserProvider::backend_kind(&self) -> radroots_secrets::id::BackendKind +pub fn radroots_secrets::browser::BrowserProvider::capabilities(&self) -> radroots_secrets::provider::SecretCapabilities +impl radroots_secrets::provider::SecretProvider for radroots_secrets::memory::MemoryProvider +pub fn radroots_secrets::memory::MemoryProvider::backend_kind(&self) -> radroots_secrets::id::BackendKind +pub fn radroots_secrets::memory::MemoryProvider::capabilities(&self) -> radroots_secrets::provider::SecretCapabilities +pub mod radroots_secrets::wrapping +pub struct radroots_secrets::wrapping::LegacyV1UnwrapRequest<'a> +impl<'a> radroots_secrets::wrapping::LegacyV1UnwrapRequest<'a> +pub const fn radroots_secrets::wrapping::LegacyV1UnwrapRequest<'a>::reference(&self) -> &'a radroots_secrets::id::SecretRef +pub const fn radroots_secrets::wrapping::LegacyV1UnwrapRequest<'a>::wrapped(&self) -> &'a radroots_secrets::wrapping::WrappedSecret +impl core::fmt::Debug for radroots_secrets::wrapping::LegacyV1UnwrapRequest<'_> +pub fn radroots_secrets::wrapping::LegacyV1UnwrapRequest<'_>::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +pub struct radroots_secrets::wrapping::SecretMaterial(_) +impl radroots_secrets::wrapping::SecretMaterial +pub fn radroots_secrets::wrapping::SecretMaterial::expose_secret<T>(&self, impl core::ops::function::FnOnce(&[u8]) -> T) -> T +pub fn radroots_secrets::wrapping::SecretMaterial::from_slice(&[u8]) -> core::result::Result<Self, radroots_secrets::error::Error> +pub fn radroots_secrets::wrapping::SecretMaterial::is_empty(&self) -> bool +pub fn radroots_secrets::wrapping::SecretMaterial::len(&self) -> usize +impl core::fmt::Debug for radroots_secrets::wrapping::SecretMaterial +pub fn radroots_secrets::wrapping::SecretMaterial::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +pub struct radroots_secrets::wrapping::UnwrapRequest<'a> +impl<'a> radroots_secrets::wrapping::UnwrapRequest<'a> +pub const fn radroots_secrets::wrapping::UnwrapRequest<'a>::context(&self) -> &'a radroots_secrets::context::EnvelopeContext +pub const fn radroots_secrets::wrapping::UnwrapRequest<'a>::new(&'a radroots_secrets::id::SecretRef, &'a radroots_secrets::context::EnvelopeContext, &'a radroots_secrets::wrapping::WrappedSecret) -> Self +pub const fn radroots_secrets::wrapping::UnwrapRequest<'a>::reference(&self) -> &'a radroots_secrets::id::SecretRef +pub const fn radroots_secrets::wrapping::UnwrapRequest<'a>::wrapped(&self) -> &'a radroots_secrets::wrapping::WrappedSecret +pub struct radroots_secrets::wrapping::WrapRequest<'a> +impl<'a> radroots_secrets::wrapping::WrapRequest<'a> +pub const fn radroots_secrets::wrapping::WrapRequest<'a>::context(&self) -> &'a radroots_secrets::context::EnvelopeContext +pub const fn radroots_secrets::wrapping::WrapRequest<'a>::new(&'a radroots_secrets::id::SecretRef, &'a radroots_secrets::context::EnvelopeContext, &'a radroots_secrets::wrapping::SecretMaterial) -> Self +pub const fn radroots_secrets::wrapping::WrapRequest<'a>::plaintext(&self) -> &'a radroots_secrets::wrapping::SecretMaterial +pub const fn radroots_secrets::wrapping::WrapRequest<'a>::reference(&self) -> &'a radroots_secrets::id::SecretRef +pub struct radroots_secrets::wrapping::WrappedSecret(_) +impl radroots_secrets::wrapping::WrappedSecret +pub fn radroots_secrets::wrapping::WrappedSecret::as_bytes(&self) -> &[u8] +pub fn radroots_secrets::wrapping::WrappedSecret::from_bytes(impl core::convert::Into<alloc::vec::Vec<u8>>) -> core::result::Result<Self, radroots_secrets::error::Error> +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::HostBound +impl<T: ?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>> +impl radroots_secrets::wrapping::KeyWrapping for radroots_secrets::browser::BrowserProvider +pub fn radroots_secrets::browser::BrowserProvider::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::browser::BrowserProvider::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::browser::BrowserProvider::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>> +impl radroots_secrets::wrapping::KeyWrapping for radroots_secrets::memory::MemoryProvider +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 type radroots_secrets::wrapping::BoxFuture<'a, T> = core::pin::Pin<alloc::boxed::Box<(dyn core::future::future::Future<Output = T> + 'a)>> +#[non_exhaustive] pub enum radroots_secrets::Error +pub radroots_secrets::Error::BackendFailure +pub radroots_secrets::Error::BackendFailure::backend: radroots_secrets::id::BackendKind +pub radroots_secrets::Error::BackendFailure::operation: radroots_secrets::error::Operation +pub radroots_secrets::Error::BackendMismatch +pub radroots_secrets::Error::BackendMismatch::provider: radroots_secrets::id::BackendKind +pub radroots_secrets::Error::BackendMismatch::reference: radroots_secrets::id::BackendKind +pub radroots_secrets::Error::BackendUnavailable +pub radroots_secrets::Error::BackendUnavailable::backend: radroots_secrets::id::BackendKind +pub radroots_secrets::Error::ContextMismatch +pub radroots_secrets::Error::DecryptFailed +pub radroots_secrets::Error::EncryptFailed +pub radroots_secrets::Error::EnvelopeMalformed +pub radroots_secrets::Error::EnvelopeTooLarge +pub radroots_secrets::Error::EnvelopeTooLarge::actual_bytes: usize +pub radroots_secrets::Error::EnvelopeTooLarge::max_bytes: usize +pub radroots_secrets::Error::InsecurePermissions +pub radroots_secrets::Error::InvalidContextValue +pub radroots_secrets::Error::InvalidContextValue::field: radroots_secrets::error::ContextField +pub radroots_secrets::Error::InvalidContextValue::reason: radroots_secrets::error::ContextValueError +pub radroots_secrets::Error::InvalidDataKeyLength +pub radroots_secrets::Error::InvalidDataKeyLength::actual_bytes: usize +pub radroots_secrets::Error::InvalidKeyVersion +pub radroots_secrets::Error::InvalidRotation +pub radroots_secrets::Error::InvalidSecretId(radroots_secrets::error::SecretIdError) +pub radroots_secrets::Error::InvalidSecretLength +pub radroots_secrets::Error::InvalidSecretLength::actual_bytes: usize +pub radroots_secrets::Error::InvalidSecretLength::max_bytes: usize +pub radroots_secrets::Error::InvalidServiceName +pub radroots_secrets::Error::InvalidWrappedLength +pub radroots_secrets::Error::InvalidWrappedLength::actual_bytes: usize +pub radroots_secrets::Error::InvalidWrappedLength::max_bytes: usize +pub radroots_secrets::Error::LegacyEntropyReuse +pub radroots_secrets::Error::LegacyEnvelopeDenied +pub radroots_secrets::Error::LegacyPayloadValidationFailed +pub radroots_secrets::Error::PolicyUnsupported +pub radroots_secrets::Error::PolicyUnsupported::backend: radroots_secrets::id::BackendKind +pub radroots_secrets::Error::PolicyUnsupported::requirement: radroots_secrets::error::PolicyRequirement +pub radroots_secrets::Error::ProviderReferenceMismatch +pub radroots_secrets::Error::SecretAlreadyExists +pub radroots_secrets::Error::SecretAlreadyExists::backend: radroots_secrets::id::BackendKind +pub radroots_secrets::Error::SecretAlreadyExists::key_version: u32 +pub radroots_secrets::Error::SecretNotFound +pub radroots_secrets::Error::SecretNotFound::backend: radroots_secrets::id::BackendKind +pub radroots_secrets::Error::SecretNotFound::key_version: u32 +pub radroots_secrets::Error::UnsafePath +pub radroots_secrets::Error::UnsupportedBackend +pub radroots_secrets::Error::UnsupportedBackend::backend: u8 +pub radroots_secrets::Error::UnsupportedCipher +pub radroots_secrets::Error::UnsupportedCipher::cipher: u8 +pub radroots_secrets::Error::UnsupportedContextVersion +pub radroots_secrets::Error::UnsupportedContextVersion::version: u16 +pub radroots_secrets::Error::UnsupportedEnvelopeVersion +pub radroots_secrets::Error::UnsupportedEnvelopeVersion::version: u16 +pub radroots_secrets::Error::UnsupportedKeySource +pub radroots_secrets::Error::UnsupportedKeySource::key_source: u8 +impl core::error::Error for radroots_secrets::error::Error +impl core::fmt::Display for radroots_secrets::error::Error +pub fn radroots_secrets::error::Error::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +pub struct radroots_secrets::EncryptedEnvelope +impl radroots_secrets::envelope::EncryptedEnvelope +pub const fn radroots_secrets::envelope::EncryptedEnvelope::cipher(&self) -> radroots_secrets::envelope::Cipher +pub const fn radroots_secrets::envelope::EncryptedEnvelope::context(&self) -> core::option::Option<&radroots_secrets::context::EnvelopeContext> +pub fn radroots_secrets::envelope::EncryptedEnvelope::decode(&[u8]) -> core::result::Result<Self, radroots_secrets::error::Error> +pub fn radroots_secrets::envelope::EncryptedEnvelope::encode(&self) -> core::result::Result<alloc::vec::Vec<u8>, radroots_secrets::error::Error> +pub const fn radroots_secrets::envelope::EncryptedEnvelope::key_source(&self) -> radroots_secrets::envelope::KeySource +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 + 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 +pub fn radroots_secrets::envelope::EncryptedEnvelope::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +impl serde_core::ser::Serialize for radroots_secrets::envelope::EncryptedEnvelope +pub fn radroots_secrets::envelope::EncryptedEnvelope::serialize<S>(&self, S) -> core::result::Result<<S as serde_core::ser::Serializer>::Ok, <S as serde_core::ser::Serializer>::Error> where S: serde_core::ser::Serializer +impl<'de> serde_core::de::Deserialize<'de> for radroots_secrets::envelope::EncryptedEnvelope +pub fn radroots_secrets::envelope::EncryptedEnvelope::deserialize<D>(D) -> core::result::Result<Self, <D as serde_core::de::Deserializer>::Error> where D: serde_core::de::Deserializer<'de> +pub struct radroots_secrets::SecretId(_) +impl radroots_secrets::id::SecretId +pub fn radroots_secrets::id::SecretId::as_str(&self) -> &str +pub fn radroots_secrets::id::SecretId::parse(impl core::convert::AsRef<str>) -> core::result::Result<Self, radroots_secrets::error::Error> +impl core::fmt::Debug for radroots_secrets::id::SecretId +pub fn radroots_secrets::id::SecretId::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +impl core::fmt::Display for radroots_secrets::id::SecretId +pub fn radroots_secrets::id::SecretId::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +impl core::str::traits::FromStr for radroots_secrets::id::SecretId +pub type radroots_secrets::id::SecretId::Err = radroots_secrets::error::Error +pub fn radroots_secrets::id::SecretId::from_str(&str) -> core::result::Result<Self, Self::Err> +impl serde_core::ser::Serialize for radroots_secrets::id::SecretId +pub fn radroots_secrets::id::SecretId::serialize<S>(&self, S) -> core::result::Result<<S as serde_core::ser::Serializer>::Ok, <S as serde_core::ser::Serializer>::Error> where S: serde_core::ser::Serializer +impl<'de> serde_core::de::Deserialize<'de> for radroots_secrets::id::SecretId +pub fn radroots_secrets::id::SecretId::deserialize<D>(D) -> core::result::Result<Self, <D as serde_core::de::Deserializer>::Error> where D: serde_core::de::Deserializer<'de> +pub struct radroots_secrets::SecretRef +impl radroots_secrets::id::SecretRef +pub const fn radroots_secrets::id::SecretRef::backend(&self) -> radroots_secrets::id::BackendKind +pub const fn radroots_secrets::id::SecretRef::id(&self) -> &radroots_secrets::id::SecretId +pub const fn radroots_secrets::id::SecretRef::key_version(&self) -> radroots_secrets::id::KeyVersion +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: 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>> +impl radroots_secrets::wrapping::KeyWrapping for radroots_secrets::browser::BrowserProvider +pub fn radroots_secrets::browser::BrowserProvider::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::browser::BrowserProvider::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::browser::BrowserProvider::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>> +impl radroots_secrets::wrapping::KeyWrapping for radroots_secrets::memory::MemoryProvider +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 +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::browser::BrowserProvider +pub fn radroots_secrets::browser::BrowserProvider::backend_kind(&self) -> radroots_secrets::id::BackendKind +pub fn radroots_secrets::browser::BrowserProvider::capabilities(&self) -> radroots_secrets::provider::SecretCapabilities +impl radroots_secrets::provider::SecretProvider for radroots_secrets::memory::MemoryProvider +pub fn radroots_secrets::memory::MemoryProvider::backend_kind(&self) -> radroots_secrets::id::BackendKind +pub fn radroots_secrets::memory::MemoryProvider::capabilities(&self) -> radroots_secrets::provider::SecretCapabilities diff --git a/contracts/architecture/decisions/browser_secret_provider.v1.json b/contracts/architecture/decisions/browser_secret_provider.v1.json @@ -0,0 +1,71 @@ +{ + "schema_version": 1, + "contract_id": "radroots.secrets.browser_provider.v1", + "state": "implemented_browser_host_component", + "owner": "radroots_secrets", + "feature": "browser", + "target": "wasm32-unknown-unknown", + "radroots_dependencies_allowed": false, + "residency": "user_profile_origin_storage", + "device_local_claim": false, + "user_presence_claim": false, + "hardware_backed_claim": false, + "participant_signer_authority": false, + "stock_authority": false, + "provider_backend": "external", + "master": { + "material_bytes": 32, + "entropy": "browser_crypto_get_random_values", + "algorithm": "HKDF", + "extractable": false, + "usages": ["deriveKey"], + "persistence": "indexeddb_structured_clone", + "raw_export_allowed": false + }, + "wrapping": { + "version": 1, + "magic_ascii": "RRBW", + "data_key_bytes": 32, + "wrapped_key_bytes": 40, + "encoded_bytes": 45, + "derivation": "HKDF-SHA-256", + "key_algorithm": "AES-KW", + "key_bits": 256, + "binding": ["namespace", "secret_id", "key_version", "expected_envelope_context_digest"], + "probe_domain_separate": true, + "generic_envelope_v2_unchanged": true, + "legacy_unwrap_default_denied": true + }, + "storage": { + "namespace_prefix": "radroots.secrets.browser.v1.", + "version": 1, + "store": "provider", + "records": ["binding", "key"], + "one_immutable_key_per_namespace": true, + "create_and_open_separate": true, + "creation_key_and_binding_atomic": true, + "acknowledgement": "actual_upgrade_transaction_completion", + "existing_open_requires_expected_fingerprint": true, + "missing_key_replacement_allowed": false, + "implicit_creation_allowed": false, + "implicit_migration_allowed": false, + "old_namespaces_retained": true + }, + "resources": { + "jobs_max": 32, + "setup_jobs_max_per_host_thread": 32, + "setup_create_and_open_share_admission": true, + "retained_bytes_max": 4194304, + "close_waiters_max": 32, + "accepted_work_rust_owned": true, + "callbacks_retained_until_terminal_event": true, + "close_drains_accepted_work": true + }, + "qualification": { + "contexts": ["main_thread", "dedicated_worker"], + "browsers": ["chromium", "firefox", "webkit"], + "page_and_worker_restart_required": true, + "public_fingerprint_is_not_authority": true, + "authenticated_journal_or_full_client_claim": false + } +} diff --git a/crates/secrets/Cargo.toml b/crates/secrets/Cargo.toml @@ -39,6 +39,7 @@ serde = ["dep:serde"] memory = ["std"] file = ["std", "dep:tempfile"] keyring = ["std", "dep:keyring"] +browser = ["std", "dep:futures", "dep:js-sys", "dep:wasm-bindgen", "dep:wasm-bindgen-futures", "dep:web-sys"] [dependencies] chacha20poly1305 = { workspace = true } @@ -52,6 +53,13 @@ subtle = { workspace = true, default-features = false } tempfile = { workspace = true, optional = true } zeroize = { workspace = true, default-features = true } +[target.'cfg(target_arch = "wasm32")'.dependencies] +futures = { workspace = true, optional = true } +js-sys = { workspace = true, optional = true } +wasm-bindgen = { workspace = true, optional = true } +wasm-bindgen-futures = { workspace = true, optional = true } +web-sys = { workspace = true, optional = true, features = ["AesKeyGenParams", "Crypto", "CryptoKey", "DomException", "DomStringList", "Event", "EventTarget", "HkdfParams", "IdbDatabase", "IdbFactory", "IdbObjectStore", "IdbOpenDbRequest", "IdbRequest", "IdbTransaction", "IdbTransactionMode", "SubtleCrypto"] } + [dev-dependencies] futures-executor = { workspace = true } hex = { workspace = true } diff --git a/crates/secrets/README.md b/crates/secrets/README.md @@ -3,7 +3,7 @@ `radroots_secrets` defines the bounded secret-provider, key-wrapping, and authenticated-envelope contracts for Radroots. Hosts choose and configure a provider explicitly; this crate does not own application authorization, -credential UI, account policy, runtime execution, or global provider state. +credential UI, account policy, application command execution, or global provider state. The crate is pre-release and publication remains disabled. Its Cargo version is frozen at `0.1.0-alpha` until the coordinated release contract explicitly @@ -20,6 +20,7 @@ changes it. | `memory` | Opt-in, process-local adapter for development and deterministic tests. | | `file` | Opt-in encrypted file adapter with secure path, permission, and durable-write rules. | | `keyring` | Opt-in operating-system credential-store adapter with lazy native access. | +| `browser` | Opt-in WASM origin-storage provider with independently pinned nonextractable keys. | | `error` | Normalized errors that do not expose provider-native messages or secret values. | The curated root exports only `EncryptedEnvelope`, `Error`, `SecretId`, @@ -98,6 +99,7 @@ every encryption under the same data key. | `memory` | no | Enables the explicit process-local adapter; requires `std`. | | `file` | no | Enables encrypted file persistence; requires `std`. | | `keyring` | no | Enables lazy operating-system credential-store access; requires `std`. | +| `browser` | no | Enables the explicit WASM Web Crypto/IndexedDB adapter; requires `std`. | The core contracts compile without the standard library. `file` and `keyring` are native host adapters; `memory` is available on standard-library targets. @@ -112,6 +114,27 @@ 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. +`browser::BrowserProvider::create` explicitly creates one immutable selected +key/version in a new origin namespace. `open` requires the caller's retained +public fingerprint. Missing or changed keys never trigger generation or +replacement; retain old namespaces for their protected data. Native targets do +not compile this adapter. Its capability report is user-profile storage with +presence, device-local and hardware requirements unavailable. + +The provider keeps a nonextractable HKDF master CryptoKey in IndexedDB, derives +AES-256-KW keys from the exact namespace/reference/context and wraps 32-byte +data keys. Generic envelope v2 retains its XChaCha20-Poly1305 format and nonce +requirements. Provider keys never leave the adapter; controllable transient +plaintext arrays are cleared. The browser and OS own their internal key memory. +See the [Web Crypto key serialization contract](https://www.w3.org/TR/webcrypto/#cryptokey-interface-clone). + +The adapter exposes a provider only after the key and binding commit together. +Its accepted mechanical jobs and event callbacks stay Rust-owned through lost +observation. Close stops admission and drains those jobs. Version change and +unexpected database closure stop admission. Storage eviction remains possible; +exact opening then fails without creating an empty replacement. A fingerprint +is a provider identity check and grants no participant or stock authority. + ## Security and serialization contract `SecretMaterial` is bounded, single-owner, zeroizing plaintext. It implements diff --git a/crates/secrets/src/browser/crypto.rs b/crates/secrets/src/browser/crypto.rs @@ -0,0 +1,218 @@ +use super::BrowserError; +use crate::{ + SecretId, SecretRef, + context::EnvelopeContext, + wrapping::{SecretMaterial, WrappedSecret}, +}; +use js_sys::{Array, ArrayBuffer, Reflect, Uint8Array}; +use sha2::{Digest, Sha256}; +use wasm_bindgen::{JsCast, JsValue}; +use wasm_bindgen_futures::JsFuture; +use web_sys::{AesKeyGenParams, Crypto, CryptoKey, HkdfParams, SubtleCrypto}; + +const HEADER: &[u8; 5] = b"RRBW\x01"; +const ENCODED_BYTES: usize = 45; + +struct PlainBytes(Uint8Array); +impl Drop for PlainBytes { + fn drop(&mut self) { + self.0.fill(0, 0, self.0.length()); + } +} +fn usages(names: &[&str]) -> Array { + names.iter().map(|name| JsValue::from_str(name)).collect() +} +pub(super) fn host() -> Result<(Crypto, SubtleCrypto), BrowserError> { + let crypto = Reflect::get(&js_sys::global(), &JsValue::from_str("crypto")) + .map_err(|_| BrowserError::Unavailable)? + .dyn_into::<Crypto>() + .map_err(|_| BrowserError::Unavailable)?; + let subtle = Reflect::get(crypto.as_ref(), &JsValue::from_str("subtle")) + .map_err(|_| BrowserError::Unavailable)? + .dyn_into::<SubtleCrypto>() + .map_err(|_| BrowserError::Unavailable)?; + Ok((crypto, subtle)) +} +pub(super) async fn generate( + crypto: &Crypto, + subtle: &SubtleCrypto, +) -> Result<CryptoKey, BrowserError> { + let seed = PlainBytes(Uint8Array::new_with_length(32)); + crypto + .get_random_values_with_js_u8_array(&seed.0) + .map_err(|_| BrowserError::Unavailable)?; + let promise = subtle + .import_key_with_str("raw", &seed.0, "HKDF", false, &usages(&["deriveKey"])) + .map_err(|_| BrowserError::Unavailable)?; + let key = JsFuture::from(promise) + .await + .map_err(|_| BrowserError::Unavailable)? + .dyn_into::<CryptoKey>() + .map_err(|_| BrowserError::KeyMismatch)?; + validate(&key)?; + Ok(key) +} +pub(super) fn validate(key: &CryptoKey) -> Result<(), BrowserError> { + let algorithm = key.algorithm().map_err(|_| BrowserError::KeyMismatch)?; + if key.type_() != "secret" + || key.extractable() + || key.usages().length() != 1 + || key.usages().get(0).as_string().as_deref() != Some("deriveKey") + || Reflect::get(&algorithm, &JsValue::from_str("name")) + .ok() + .and_then(|v| v.as_string()) + .as_deref() + != Some("HKDF") + { + return Err(BrowserError::KeyMismatch); + } + Ok(()) +} +fn scope(namespace: &SecretId, reference: &SecretRef) -> [u8; 32] { + let mut hash = Sha256::new(); + hash.update(b"radroots.browser.key_scope.v1\0"); + for value in [namespace.as_str(), reference.id().as_str()] { + hash.update((value.len() as u16).to_be_bytes()); + hash.update(value.as_bytes()); + } + hash.update(reference.key_version().get().to_be_bytes()); + hash.finalize().into() +} +async fn derive( + subtle: &SubtleCrypto, + key: &CryptoKey, + namespace: &SecretId, + reference: &SecretRef, + context: Option<&EnvelopeContext>, +) -> Result<CryptoKey, BrowserError> { + validate(key)?; + let salt = Uint8Array::from(scope(namespace, reference).as_slice()); + let mut info = Vec::from(if context.is_some() { + b"radroots.browser.key_wrap.v1\0".as_slice() + } else { + b"radroots.browser.key_probe.v1\0".as_slice() + }); + if let Some(context) = context { + info.extend_from_slice(&context.authentication_digest()); + } + let params = + HkdfParams::new_with_str("HKDF", "SHA-256", &Uint8Array::from(info.as_slice()), &salt); + let algorithm = AesKeyGenParams::new("AES-KW", 256); + let promise = subtle + .derive_key_with_object_and_object( + &params, + key, + &algorithm, + false, + &usages(&["wrapKey", "unwrapKey"]), + ) + .map_err(|_| BrowserError::Unavailable)?; + JsFuture::from(promise) + .await + .map_err(|_| BrowserError::Unavailable)? + .dyn_into::<CryptoKey>() + .map_err(|_| BrowserError::KeyMismatch) +} +async fn encode( + subtle: &SubtleCrypto, + wrapping: &CryptoKey, + bytes: &[u8], +) -> Result<Vec<u8>, BrowserError> { + if bytes.len() != 32 { + return Err(BrowserError::Provider(crate::Error::InvalidDataKeyLength { + actual_bytes: bytes.len(), + })); + } + let raw = PlainBytes(Uint8Array::from(bytes)); + let promise = subtle + .import_key_with_str("raw", &raw.0, "AES-GCM", true, &usages(&["encrypt"])) + .map_err(|_| BrowserError::Unavailable)?; + let data_key = JsFuture::from(promise) + .await + .map_err(|_| BrowserError::Unavailable)? + .dyn_into::<CryptoKey>() + .map_err(|_| BrowserError::KeyMismatch)?; + let promise = subtle + .wrap_key_with_str("raw", &data_key, wrapping, "AES-KW") + .map_err(|_| BrowserError::Unavailable)?; + let buffer = JsFuture::from(promise) + .await + .map_err(|_| BrowserError::Unavailable)? + .dyn_into::<ArrayBuffer>() + .map_err(|_| BrowserError::KeyMismatch)?; + if buffer.byte_length() != 40 { + return Err(BrowserError::KeyMismatch); + } + Ok(Uint8Array::new(&buffer).to_vec()) +} +pub(super) async fn fingerprint( + subtle: &SubtleCrypto, + key: &CryptoKey, + namespace: &SecretId, + reference: &SecretRef, +) -> Result<[u8; 32], BrowserError> { + let derived = derive(subtle, key, namespace, reference, None).await?; + // Public fixed probe in its own KDF domain; no payload or provider key is exposed. + Ok(Sha256::digest(encode(subtle, &derived, &[0xa5; 32]).await?).into()) +} +pub(super) async fn wrap( + subtle: &SubtleCrypto, + key: &CryptoKey, + namespace: &SecretId, + reference: &SecretRef, + context: &EnvelopeContext, + plaintext: &SecretMaterial, +) -> Result<WrappedSecret, BrowserError> { + let derived = derive(subtle, key, namespace, reference, Some(context)).await?; + let raw = plaintext.expose_secret(|bytes| zeroize::Zeroizing::new(bytes.to_vec())); + let mut encoded = Vec::from(HEADER.as_slice()); + encoded.extend_from_slice(&encode(subtle, &derived, raw.as_slice()).await?); + WrappedSecret::from_bytes(encoded).map_err(BrowserError::Provider) +} +pub(super) fn validate_wrapped(wrapped: &WrappedSecret) -> Result<(), BrowserError> { + if wrapped.as_bytes().len() != ENCODED_BYTES || !wrapped.as_bytes().starts_with(HEADER) { + return Err(BrowserError::KeyMismatch); + } + Ok(()) +} +pub(super) async fn unwrap( + subtle: &SubtleCrypto, + key: &CryptoKey, + namespace: &SecretId, + reference: &SecretRef, + context: &EnvelopeContext, + wrapped: &WrappedSecret, +) -> Result<SecretMaterial, BrowserError> { + validate_wrapped(wrapped)?; + let derived = derive(subtle, key, namespace, reference, Some(context)).await?; + let ciphertext = Uint8Array::from(&wrapped.as_bytes()[HEADER.len()..]); + let promise = subtle + .unwrap_key_with_buffer_source_and_str_and_str( + "raw", + &ciphertext, + &derived, + "AES-KW", + "AES-GCM", + true, + &usages(&["encrypt"]), + ) + .map_err(|_| BrowserError::KeyMismatch)?; + let data_key = JsFuture::from(promise) + .await + .map_err(|_| BrowserError::KeyMismatch)? + .dyn_into::<CryptoKey>() + .map_err(|_| BrowserError::KeyMismatch)?; + let promise = subtle + .export_key("raw", &data_key) + .map_err(|_| BrowserError::KeyMismatch)?; + let buffer = JsFuture::from(promise) + .await + .map_err(|_| BrowserError::KeyMismatch)? + .dyn_into::<ArrayBuffer>() + .map_err(|_| BrowserError::KeyMismatch)?; + let plaintext = PlainBytes(Uint8Array::new(&buffer)); + if plaintext.0.length() != 32 { + return Err(BrowserError::KeyMismatch); + } + SecretMaterial::from_owned(plaintext.0.to_vec()).map_err(BrowserError::Provider) +} diff --git a/crates/secrets/src/browser/idb.rs b/crates/secrets/src/browser/idb.rs @@ -0,0 +1,289 @@ +//! Browser event roots follow the qualified local transaction ownership pattern. +use super::BrowserError; +use futures::channel::oneshot; +use js_sys::Uint8Array; +use std::{ + cell::{Cell, RefCell}, + rc::Rc, +}; +use wasm_bindgen::{JsCast, JsValue, closure::Closure}; +use web_sys::{ + CryptoKey, Event, IdbDatabase, IdbFactory, IdbOpenDbRequest, IdbRequest, IdbTransaction, +}; + +const STORE: &str = "provider"; +type Callback = Closure<dyn FnMut(Event)>; + +pub(super) struct Seed { + pub key: CryptoKey, + pub binding: Vec<u8>, +} +struct OpenRoots { + request: IdbOpenDbRequest, + _upgrade: Callback, + _success: Callback, + _error: Callback, +} +impl Drop for OpenRoots { + fn drop(&mut self) { + self.request.set_onupgradeneeded(None); + self.request.set_onsuccess(None); + self.request.set_onerror(None); + } +} +pub(super) async fn open( + factory: &IdbFactory, + name: &str, + seed: Option<Seed>, +) -> Result<IdbDatabase, BrowserError> { + let request = factory + .open_with_u32(name, 1) + .map_err(|_| BrowserError::Unavailable)?; + let create = seed.is_some(); + let created = Rc::new(Cell::new(false)); + let failure = Rc::new(Cell::new(None)); + let (send, observe) = oneshot::channel(); + let reply = Rc::new(RefCell::new(Some(send))); + let upgrade = { + let request = request.clone(); + let created = created.clone(); + let failure = failure.clone(); + Closure::new(move |_: Event| { + let result = (|| { + let seed = seed.as_ref().ok_or(BrowserError::MissingNamespace)?; + let db = request + .result() + .map_err(|_| BrowserError::Unavailable)? + .dyn_into::<IdbDatabase>() + .map_err(|_| BrowserError::IncompatibleSchema)?; + let store = db + .create_object_store(STORE) + .map_err(|_| BrowserError::Aborted)?; + store + .add_with_key(seed.key.as_ref(), &JsValue::from_str("key")) + .map_err(|_| BrowserError::Aborted)?; + store + .add_with_key( + &Uint8Array::from(seed.binding.as_slice()), + &JsValue::from_str("binding"), + ) + .map_err(|_| BrowserError::Aborted)?; + created.set(true); + Ok(()) + })(); + if let Err(error) = result { + failure.set(Some(error)); + if let Some(tx) = request.transaction() { + let _ = tx.abort(); + } + } + }) + }; + let success = { + let request = request.clone(); + let failure = failure.clone(); + let created = created.clone(); + let reply = reply.clone(); + Closure::new(move |_: Event| { + let result = (|| { + let db = request + .result() + .map_err(|_| BrowserError::Unavailable)? + .dyn_into::<IdbDatabase>() + .map_err(|_| BrowserError::IncompatibleSchema)?; + let checked = if let Some(error) = failure.get() { + Err(error) + } else if create && !created.get() { + Err(BrowserError::NamespaceExists) + } else { + schema(&db) + }; + if let Err(error) = checked { + db.close(); + return Err(error); + } + Ok(db) + })(); + if let Some(send) = reply.borrow_mut().take() { + let _ = send.send(result); + } + }) + }; + let error = { + let request = request.clone(); + let failure = failure.clone(); + let reply = reply.clone(); + Closure::new(move |_: Event| { + let error = failure.get().unwrap_or_else(|| { + if request + .error() + .ok() + .flatten() + .is_some_and(|e| e.name() == "VersionError") + { + BrowserError::IncompatibleSchema + } else { + BrowserError::Aborted + } + }); + if let Some(send) = reply.borrow_mut().take() { + let _ = send.send(Err(error)); + } + }) + }; + request.set_onupgradeneeded(Some(upgrade.as_ref().unchecked_ref())); + request.set_onsuccess(Some(success.as_ref().unchecked_ref())); + request.set_onerror(Some(error.as_ref().unchecked_ref())); + let _roots = OpenRoots { + request, + _upgrade: upgrade, + _success: success, + _error: error, + }; + observe.await.unwrap_or(Err(BrowserError::CommitUnknown)) +} +fn schema(db: &IdbDatabase) -> Result<(), BrowserError> { + if db.version() != 1.0 + || db.object_store_names().length() != 1 + || !db.object_store_names().contains(STORE) + { + return Err(BrowserError::IncompatibleSchema); + } + let tx = db + .transaction_with_str(STORE) + .map_err(|_| BrowserError::Unavailable)?; + let store = tx + .object_store(STORE) + .map_err(|_| BrowserError::IncompatibleSchema)?; + if store.auto_increment() + || !store + .key_path() + .map_err(|_| BrowserError::IncompatibleSchema)? + .is_null() + || store.index_names().length() != 0 + { + return Err(BrowserError::IncompatibleSchema); + } + Ok(()) +} +struct Terminal { + tx: IdbTransaction, + observe: oneshot::Receiver<Result<(), BrowserError>>, + _complete: Callback, + _abort: Callback, +} +impl Terminal { + fn new(tx: IdbTransaction) -> Self { + let (send, observe) = oneshot::channel(); + let reply = Rc::new(RefCell::new(Some(send))); + let complete = { + let reply = reply.clone(); + Closure::new(move |_: Event| { + if let Some(send) = reply.borrow_mut().take() { + let _ = send.send(Ok(())); + } + }) + }; + let abort = Closure::new(move |_: Event| { + if let Some(send) = reply.borrow_mut().take() { + let _ = send.send(Err(BrowserError::Aborted)); + } + }); + tx.set_oncomplete(Some(complete.as_ref().unchecked_ref())); + tx.set_onabort(Some(abort.as_ref().unchecked_ref())); + Self { + tx, + observe, + _complete: complete, + _abort: abort, + } + } + async fn wait(&mut self) -> Result<(), BrowserError> { + (&mut self.observe) + .await + .unwrap_or(Err(BrowserError::CommitUnknown)) + } +} +impl Drop for Terminal { + fn drop(&mut self) { + self.tx.set_oncomplete(None); + self.tx.set_onabort(None); + } +} +struct ReadRoot { + request: IdbRequest, + _success: Callback, +} +impl Drop for ReadRoot { + fn drop(&mut self) { + self.request.set_onsuccess(None); + } +} +pub(super) async fn load(db: &IdbDatabase) -> Result<(CryptoKey, Vec<u8>), BrowserError> { + let tx = db + .transaction_with_str(STORE) + .map_err(|_| BrowserError::Closed)?; + let mut terminal = Terminal::new(tx.clone()); + let store = match tx.object_store(STORE) { + Ok(store) => store, + Err(_) => { + let _ = tx.abort(); + terminal.wait().await?; + return Err(BrowserError::IncompatibleSchema); + } + }; + let values = Rc::new(RefCell::new([None, None, None])); + let mut roots = Vec::with_capacity(3); + for index in 0..3 { + let request = match index { + 0 => store.get(&JsValue::from_str("key")), + 1 => store.get(&JsValue::from_str("binding")), + _ => store.count(), + }; + let request = match request { + Ok(request) => request, + Err(_) => { + let _ = tx.abort(); + terminal.wait().await?; + return Err(BrowserError::IncompatibleSchema); + } + }; + let success = { + let request = request.clone(); + let values = values.clone(); + let tx = tx.clone(); + Closure::new(move |_: Event| match request.result() { + Ok(value) => values.borrow_mut()[index] = Some(value), + Err(_) => { + let _ = tx.abort(); + } + }) + }; + request.set_onsuccess(Some(success.as_ref().unchecked_ref())); + roots.push(ReadRoot { + request, + _success: success, + }); + } + terminal.wait().await?; + let mut values = values.borrow_mut(); + let key = values[0].take().ok_or(BrowserError::CommitUnknown)?; + if key.is_undefined() { + return Err(BrowserError::MissingKey); + } + let key = key + .dyn_into::<CryptoKey>() + .map_err(|_| BrowserError::KeyMismatch)?; + let binding = values[1] + .take() + .ok_or(BrowserError::CommitUnknown)? + .dyn_into::<Uint8Array>() + .map_err(|_| BrowserError::KeyMismatch)?; + if binding.length() > 170 + || binding.length() < 42 + || values[2].take().and_then(|v| v.as_f64()) != Some(2.0) + { + return Err(BrowserError::IncompatibleSchema); + } + Ok((key, binding.to_vec())) +} diff --git a/crates/secrets/src/browser/mod.rs b/crates/secrets/src/browser/mod.rs @@ -0,0 +1,477 @@ +//! Explicit browser-origin data-key wrapping with pinned nonextractable keys. +//! No participant signer, hardware/presence claim, fallback or stock authority. +use crate::{ + Error, KeyWrapping, SecretId, SecretProvider, SecretRef, + error::Operation, + id::BackendKind, + provider::{CapabilitySupport, ResidencySupport, SecretCapabilities}, + wrapping::{BoxFuture, SecretMaterial, UnwrapRequest, WrapRequest, WrappedSecret}, +}; +use futures::channel::oneshot; +use js_sys::Reflect; +use std::{ + cell::{Cell, RefCell}, + fmt, + future::{Future, poll_fn}, + rc::{Rc, Weak}, + task::{Poll, Waker}, +}; +use subtle::ConstantTimeEq; +use wasm_bindgen::{JsCast, JsValue, closure::Closure}; +use wasm_bindgen_futures::spawn_local; +use web_sys::{CryptoKey, Event, IdbDatabase, IdbFactory, SubtleCrypto}; + +mod crypto; +mod idb; + +const JOBS_MAX: usize = 32; +const LIVE_BYTES_MAX: usize = 4 * 1024 * 1024; +type Callback = Closure<dyn FnMut(Event)>; +type CloseSignal = RefCell<Option<Waker>>; + +// Setup has no provider instance yet. Keep its accepted jobs bounded per host +// thread, independently of whether the caller retains the observation. +thread_local! { + static SETUP_JOBS: Cell<usize> = const { Cell::new(0) }; +} +struct Setup; +impl Setup { + fn admit() -> Result<Self, BrowserError> { + SETUP_JOBS.with(|jobs| { + if jobs.get() >= JOBS_MAX { + return Err(BrowserError::Capacity); + } + jobs.set(jobs.get() + 1); + Ok(Self) + }) + } +} +impl Drop for Setup { + fn drop(&mut self) { + SETUP_JOBS.with(|jobs| jobs.set(jobs.get() - 1)); + } +} + +/// Fixed source-redacted browser setup/storage outcomes. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +#[non_exhaustive] +pub enum BrowserError { + Unavailable, + MissingNamespace, + NamespaceExists, + IncompatibleSchema, + MissingKey, + KeyMismatch, + Closed, + Capacity, + Aborted, + CommitUnknown, + Provider(Error), +} +impl BrowserError { + /// Returns a stable code without native exception messages or identifiers. + pub const fn code(self) -> &'static str { + match self { + Self::Unavailable => "browser_provider_unavailable", + Self::MissingNamespace => "missing_namespace", + Self::NamespaceExists => "namespace_exists", + Self::IncompatibleSchema => "incompatible_schema", + Self::MissingKey => "missing_key", + Self::KeyMismatch => "provider_key_mismatch", + Self::Closed => "closed", + Self::Capacity => "capacity_exhausted", + Self::Aborted => "transaction_aborted", + Self::CommitUnknown => "commit_unknown", + Self::Provider(_) => "provider_failure", + } + } +} +impl fmt::Display for BrowserError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(self.code()) + } +} +impl std::error::Error for BrowserError {} + +struct State { + db: IdbDatabase, + subtle: SubtleCrypto, + namespace: SecretId, + reference: SecretRef, + fingerprint: [u8; 32], + closing: Cell<bool>, + jobs: Cell<usize>, + bytes: Cell<usize>, + waiters: RefCell<Vec<Weak<CloseSignal>>>, + version_change: RefCell<Option<Callback>>, +} +impl State { + fn wake(&self) { + self.waiters.borrow_mut().retain(|weak| { + if let Some(signal) = weak.upgrade() { + if let Some(waker) = signal.borrow_mut().take() { + waker.wake(); + } + true + } else { + false + } + }); + } + fn stop(&self) { + self.closing.set(true); + if self.jobs.get() == 0 { + self.db.close(); + } + self.wake(); + } + fn admit(self: &Rc<Self>, bytes: usize) -> Result<Work, BrowserError> { + if self.closing.get() { + return Err(BrowserError::Closed); + } + let retained = self + .bytes + .get() + .checked_add(bytes) + .ok_or(BrowserError::Capacity)?; + if self.jobs.get() >= JOBS_MAX || retained > LIVE_BYTES_MAX { + return Err(BrowserError::Capacity); + } + self.jobs.set(self.jobs.get() + 1); + self.bytes.set(retained); + Ok(Work { + state: self.clone(), + bytes, + }) + } + async fn key(&self) -> Result<CryptoKey, BrowserError> { + let (key, binding) = idb::load(&self.db).await?; + let expected = binding_bytes(&self.reference, &self.fingerprint); + if !bool::from(binding.as_slice().ct_eq(expected.as_slice())) { + return Err(BrowserError::KeyMismatch); + } + let actual = + crypto::fingerprint(&self.subtle, &key, &self.namespace, &self.reference).await?; + if !bool::from(actual.ct_eq(&self.fingerprint)) { + return Err(BrowserError::KeyMismatch); + } + Ok(key) + } +} +impl Drop for State { + fn drop(&mut self) { + self.db.set_onversionchange(None); + self.db.set_onclose(None); + self.db.close(); + } +} +struct Work { + state: Rc<State>, + bytes: usize, +} +impl Drop for Work { + fn drop(&mut self) { + self.state.jobs.set(self.state.jobs.get() - 1); + self.state.bytes.set(self.state.bytes.get() - self.bytes); + if self.state.closing.get() && self.state.jobs.get() == 0 { + self.state.db.close(); + } + self.state.wake(); + } +} +async fn owned<T: 'static>( + work: Work, + future: impl Future<Output = Result<T, BrowserError>> + 'static, +) -> Result<T, BrowserError> { + let (send, observe) = oneshot::channel(); + spawn_local(async move { + let _work = work; + let _ = send.send(future.await); + }); + observe.await.unwrap_or(Err(BrowserError::CommitUnknown)) +} +fn factory() -> Result<IdbFactory, BrowserError> { + Reflect::get(&js_sys::global(), &JsValue::from_str("indexedDB")) + .map_err(|_| BrowserError::Unavailable)? + .dyn_into::<IdbFactory>() + .map_err(|_| BrowserError::Unavailable) +} +fn name(namespace: &SecretId) -> String { + format!("radroots.secrets.browser.v1.{}", namespace.as_str()) +} +fn binding_bytes(reference: &SecretRef, fingerprint: &[u8; 32]) -> Vec<u8> { + let mut bytes = Vec::from(b"RRSB\x01".as_slice()); + bytes.push(reference.id().as_str().len() as u8); + bytes.extend_from_slice(reference.id().as_str().as_bytes()); + bytes.extend_from_slice(&reference.key_version().get().to_be_bytes()); + bytes.extend_from_slice(fingerprint); + bytes +} +fn selected(reference: &SecretRef) -> Result<(), BrowserError> { + if reference.backend() != BackendKind::External { + return Err(BrowserError::Provider(Error::BackendMismatch { + provider: BackendKind::External, + reference: reference.backend(), + })); + } + Ok(()) +} +fn normalize(error: BrowserError, operation: Operation, version: u32) -> Error { + match error { + BrowserError::Provider(error) => error, + BrowserError::MissingKey => Error::SecretNotFound { + backend: BackendKind::External, + key_version: version, + }, + BrowserError::Closed | BrowserError::Unavailable => Error::BackendUnavailable { + backend: BackendKind::External, + }, + _ => Error::BackendFailure { + backend: BackendKind::External, + operation, + }, + } +} + +/// One immutable selected provider key in explicit origin storage. The public +/// fingerprint is an independently pinned identity, never signing/stock authority. +/// Native targets do not compile this adapter. Imports and capabilities do no IO. +pub struct BrowserProvider { + state: Rc<State>, +} +impl BrowserProvider { + /// Explicitly provisions a new namespace. The generated key is never used + /// for private payloads or exposed before its binding commits atomically. + /// Existing, including damaged, namespaces are never replaced. + pub async fn create(namespace: SecretId, reference: SecretRef) -> Result<Self, BrowserError> { + selected(&reference)?; + let setup = Setup::admit()?; + let factory = factory()?; + let (crypto, subtle) = crypto::host()?; + let (send, observe) = oneshot::channel(); + spawn_local(async move { + let _setup = setup; + let result = async { + match idb::open(&factory, &name(&namespace), None).await { + Ok(db) => { + db.close(); + return Err(BrowserError::NamespaceExists); + } + Err(BrowserError::MissingNamespace) => {} + Err(error) => return Err(error), + } + let key = crypto::generate(&crypto, &subtle).await?; + let fingerprint = + crypto::fingerprint(&subtle, &key, &namespace, &reference).await?; + let seed = idb::Seed { + key, + binding: binding_bytes(&reference, &fingerprint), + }; + let db = idb::open(&factory, &name(&namespace), Some(seed)).await?; + Ok(Self::assemble( + db, + subtle, + namespace, + reference, + fingerprint, + )) + } + .await; + let _ = send.send(result); + }); + observe.await.unwrap_or(Err(BrowserError::CommitUnknown)) + } + /// Opens an existing namespace only with the caller's independently pinned + /// fingerprint. Missing or changed keys never authorize fresh generation. + pub async fn open( + namespace: SecretId, + reference: SecretRef, + expected_fingerprint: [u8; 32], + ) -> Result<Self, BrowserError> { + selected(&reference)?; + let setup = Setup::admit()?; + let factory = factory()?; + let (_, subtle) = crypto::host()?; + let (send, observe) = oneshot::channel(); + spawn_local(async move { + let _setup = setup; + let result = async { + let db = idb::open(&factory, &name(&namespace), None).await?; + let provider = + Self::assemble(db, subtle, namespace, reference, expected_fingerprint); + provider.state.key().await?; + Ok(provider) + } + .await; + let _ = send.send(result); + }); + observe.await.unwrap_or(Err(BrowserError::CommitUnknown)) + } + fn assemble( + db: IdbDatabase, + subtle: SubtleCrypto, + namespace: SecretId, + reference: SecretRef, + fingerprint: [u8; 32], + ) -> Self { + let state = Rc::new(State { + db, + subtle, + namespace, + reference, + fingerprint, + closing: Cell::new(false), + jobs: Cell::new(0), + bytes: Cell::new(0), + waiters: RefCell::new(Vec::new()), + version_change: RefCell::new(None), + }); + let weak = Rc::downgrade(&state); + let changed = Closure::new(move |_: Event| { + if let Some(state) = weak.upgrade() { + state.stop(); + state.db.close(); + } + }); + state + .db + .set_onversionchange(Some(changed.as_ref().unchecked_ref())); + state.db.set_onclose(Some(changed.as_ref().unchecked_ref())); + *state.version_change.borrow_mut() = Some(changed); + Self { state } + } + /// Returns the public fingerprint that must be retained independently + /// for exact subsequent opening. It reveals no provider key material. + pub fn fingerprint(&self) -> [u8; 32] { + self.state.fingerprint + } + /// Stops admission, drains accepted jobs and closes the actual connection. + /// Cancellation of this observation does not cancel accepted jobs. + pub async fn close(&self) -> Result<(), BrowserError> { + self.state.stop(); + if self.state.jobs.get() == 0 { + return Ok(()); + } + let signal = Rc::new(RefCell::new(None)); + { + let mut waiters = self.state.waiters.borrow_mut(); + waiters.retain(|weak| weak.strong_count() > 0); + if waiters.len() >= JOBS_MAX { + return Err(BrowserError::Capacity); + } + waiters.push(Rc::downgrade(&signal)); + } + poll_fn(|cx| { + if self.state.jobs.get() == 0 { + Poll::Ready(()) + } else { + *signal.borrow_mut() = Some(cx.waker().clone()); + Poll::Pending + } + }) + .await; + Ok(()) + } + fn check(&self, reference: &SecretRef) -> Result<(), Error> { + selected(reference) + .map_err(|e| normalize(e, Operation::Read, reference.key_version().get()))?; + if reference.id() != self.state.reference.id() + || reference.key_version() != self.state.reference.key_version() + { + return Err(Error::SecretNotFound { + backend: BackendKind::External, + key_version: reference.key_version().get(), + }); + } + Ok(()) + } +} +impl fmt::Debug for BrowserProvider { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("BrowserProvider(<redacted>)") + } +} +impl SecretProvider for BrowserProvider { + fn backend_kind(&self) -> BackendKind { + BackendKind::External + } + fn capabilities(&self) -> SecretCapabilities { + if self.state.closing.get() { + SecretCapabilities::unavailable() + } else { + SecretCapabilities::available( + ResidencySupport::UserProfile, + CapabilitySupport::Unavailable, + CapabilitySupport::Unavailable, + ) + } + } +} +impl KeyWrapping for BrowserProvider { + fn wrap<'a>(&'a self, request: WrapRequest<'a>) -> BoxFuture<'a, Result<WrappedSecret, Error>> { + Box::pin(async move { + self.check(request.reference())?; + if request.plaintext().len() != 32 { + return Err(Error::InvalidDataKeyLength { + actual_bytes: request.plaintext().len(), + }); + } + let version = request.reference().key_version().get(); + let work = self + .state + .admit(16 * 1024) + .map_err(|e| normalize(e, Operation::Wrap, version))?; + let plaintext = request + .plaintext() + .expose_secret(SecretMaterial::from_slice)?; + let context = request.context().clone(); + let state = self.state.clone(); + owned(work, async move { + let key = state.key().await?; + crypto::wrap( + &state.subtle, + &key, + &state.namespace, + &state.reference, + &context, + &plaintext, + ) + .await + }) + .await + .map_err(|e| normalize(e, Operation::Wrap, version)) + }) + } + fn unwrap<'a>( + &'a self, + request: UnwrapRequest<'a>, + ) -> BoxFuture<'a, Result<SecretMaterial, Error>> { + Box::pin(async move { + self.check(request.reference())?; + let version = request.reference().key_version().get(); + crypto::validate_wrapped(request.wrapped()) + .map_err(|e| normalize(e, Operation::Unwrap, version))?; + let work = self + .state + .admit(16 * 1024) + .map_err(|e| normalize(e, Operation::Unwrap, version))?; + let wrapped = request.wrapped().clone(); + let context = request.context().clone(); + let state = self.state.clone(); + owned(work, async move { + let key = state.key().await?; + crypto::unwrap( + &state.subtle, + &key, + &state.namespace, + &state.reference, + &context, + &wrapped, + ) + .await + }) + .await + .map_err(|e| normalize(e, Operation::Unwrap, version)) + }) + } +} diff --git a/crates/secrets/src/lib.rs b/crates/secrets/src/lib.rs @@ -6,6 +6,8 @@ extern crate alloc; +#[cfg(all(feature = "browser", target_arch = "wasm32"))] +pub mod browser; pub mod context; pub mod envelope; pub mod error; diff --git a/crates/secrets/tests/package_boundary.rs b/crates/secrets/tests/package_boundary.rs @@ -28,7 +28,9 @@ fn manifest_has_final_identity_features_and_no_radroots_dependencies() { assert_eq!( table_keys(MANIFEST, "[features]"), - BTreeSet::from(["default", "file", "keyring", "memory", "serde", "std"]) + BTreeSet::from([ + "browser", "default", "file", "keyring", "memory", "serde", "std" + ]) ); assert!( table_keys(MANIFEST, "[dependencies]") @@ -52,6 +54,22 @@ fn manifest_has_final_identity_features_and_no_radroots_dependencies() { table_keys(MANIFEST, "[dev-dependencies]"), BTreeSet::from(["futures-executor", "hex", "serde_json"]) ); + assert_eq!( + table_keys( + MANIFEST, + "[target.'cfg(target_arch = \"wasm32\")'.dependencies]" + ), + BTreeSet::from([ + "futures", + "js-sys", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys" + ]) + ); + assert!(ROOT.contains( + "#[cfg(all(feature = \"browser\", target_arch = \"wasm32\"))]\npub mod browser;" + )); } #[test] @@ -90,8 +108,8 @@ fn crate_root_contains_only_the_approved_module_skeleton() { assert_eq!( declarations(ROOT, "pub mod "), BTreeSet::from([ - "context", "envelope", "error", "file", "id", "keyring", "memory", "provider", - "wrapping", + "browser", "context", "envelope", "error", "file", "id", "keyring", "memory", + "provider", "wrapping", ]) ); assert_eq!( diff --git a/crates/secrets/tests/security_contract.rs b/crates/secrets/tests/security_contract.rs @@ -10,9 +10,48 @@ use std::fs; use std::path::{Path, PathBuf}; const PUBLIC_API: &str = include_str!("../../../contracts/api_baselines/radroots_secrets.txt"); +const BROWSER_PUBLIC_API: &str = + include_str!("../../../contracts/api_baselines/radroots_secrets.wasm32_browser.txt"); #[test] fn reviewed_api_forbids_secret_bearing_clone_serialize_and_byte_access() { + for public_api in [PUBLIC_API, BROWSER_PUBLIC_API] { + assert_reviewed_api(public_api); + } +} + +#[test] +fn browser_api_has_only_opaque_provider_ownership_and_typed_setup() { + assert!(!PUBLIC_API.contains("pub mod radroots_secrets::browser")); + for required in [ + "pub struct radroots_secrets::browser::BrowserProvider", + "pub async fn radroots_secrets::browser::BrowserProvider::create(", + "pub async fn radroots_secrets::browser::BrowserProvider::open(", + "pub async fn radroots_secrets::browser::BrowserProvider::close(", + "pub fn radroots_secrets::browser::BrowserProvider::fingerprint(&self) -> [u8; 32]", + ] { + assert!(BROWSER_PUBLIC_API.contains(required)); + } + for dependency in [ + "web_sys", + "js_sys", + "wasm_bindgen", + "wasm_bindgen_futures", + "futures", + ] { + assert!(!exposes_crate_path(BROWSER_PUBLIC_API, dependency)); + } + for forbidden in [ + "CryptoKey", + "JsValue", + "BrowserProvider::export", + "BrowserProvider::key", + ] { + assert!(!BROWSER_PUBLIC_API.contains(forbidden)); + } +} + +fn assert_reviewed_api(public_api: &str) { for required in [ "pub mod radroots_secrets::context", "pub mod radroots_secrets::envelope", @@ -26,7 +65,7 @@ fn reviewed_api_forbids_secret_bearing_clone_serialize_and_byte_access() { "pub trait radroots_secrets::wrapping::KeyWrapping", ] { assert!( - PUBLIC_API.contains(required), + public_api.contains(required), "reviewed public API is missing `{required}`" ); } @@ -42,7 +81,7 @@ fn reviewed_api_forbids_secret_bearing_clone_serialize_and_byte_access() { for forbidden_trait in ["core::clone::Clone", "serde_core::ser::Serialize"] { let forbidden = format!("impl {forbidden_trait} for {secret_bearing_type}"); assert!( - !PUBLIC_API.contains(&forbidden), + !public_api.contains(&forbidden), "secret-bearing public type exposes forbidden trait: {forbidden}" ); } @@ -58,7 +97,7 @@ fn reviewed_api_forbids_secret_bearing_clone_serialize_and_byte_access() { "SealRequest<'a>::new(radroots_secrets::id::SecretRef, &'a radroots_secrets::wrapping::SecretMaterial", ] { assert!( - !PUBLIC_API.contains(forbidden), + !public_api.contains(forbidden), "reviewed API exposes forbidden plaintext or duplication surface `{forbidden}`" ); } @@ -72,7 +111,7 @@ fn reviewed_api_forbids_secret_bearing_clone_serialize_and_byte_access() { "zeroize", ] { assert!( - !exposes_crate_path(PUBLIC_API, forbidden_dependency), + !exposes_crate_path(public_api, forbidden_dependency), "reviewed API leaks implementation dependency `{forbidden_dependency}`" ); } diff --git a/crates/storage_indexeddb/tests/browser/Cargo.lock b/crates/storage_indexeddb/tests/browser/Cargo.lock @@ -641,6 +641,7 @@ dependencies = [ "radroots_storage_indexeddb", "wasm-bindgen", "wasm-bindgen-futures", + "web-sys", ] [[package]] @@ -658,9 +659,14 @@ name = "radroots_secrets" version = "0.1.0-alpha" dependencies = [ "chacha20poly1305", + "futures", + "js-sys", "serde", "sha2", "subtle", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", "zeroize", ] diff --git a/crates/storage_indexeddb/tests/browser/Cargo.toml b/crates/storage_indexeddb/tests/browser/Cargo.toml @@ -13,9 +13,10 @@ crate-type = ["cdylib"] [dependencies] radroots_storage_indexeddb = { path = "../.." } radroots_storage = { path = "../../../storage" } -radroots_secrets = { path = "../../../secrets", features = ["memory"] } +radroots_secrets = { path = "../../../secrets", features = ["memory", "browser"] } futures = "=0.3.32" hex = "=0.4.3" js-sys = "=0.3.91" wasm-bindgen = "=0.2.114" wasm-bindgen-futures = "=0.4.64" +web-sys = { version = "=0.3.91", features = ["Crypto"] } diff --git a/crates/storage_indexeddb/tests/browser/run.mjs b/crates/storage_indexeddb/tests/browser/run.mjs @@ -20,9 +20,12 @@ const server = createServer(async (req,res) => { } if (path.endsWith('/worker.js')) { res.setHeader('content-type','text/javascript'); - res.end(`import init, {Fixture,protected_round_trip} from './fixture.js'; + res.end(`import init, {Fixture,Persistent,protected_round_trip} from './fixture.js'; await init(); - 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.onmessage=async(event)=>{try{ + if(event.data?.kind==='persistent_create'){const provider=await Persistent.create(90);const fingerprint=provider.fingerprint();const encoded=await provider.protect(new Uint8Array([90,91,92]));await provider.close();self.postMessage({fingerprint:Array.from(fingerprint),encoded:Array.from(encoded)});return;} + if(event.data?.kind==='persistent_open'){const provider=await Persistent.open(90,new Uint8Array(event.data.fingerprint));const plain=await provider.reveal(new Uint8Array(event.data.encoded));await provider.close();self.postMessage({plain:Array.from(plain)});return;} + 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 +43,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,protected_round_trip}=await import('./fixture.js'); await init(); + const {default:init,Fixture,Persistent,protected_round_trip}=await import('./fixture.js'); await init(); console.log('STEP wasm_initialized'); const events=[]; const nativeTransaction=IDBDatabase.prototype.transaction; @@ -57,6 +60,26 @@ try { 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'); + const persistent=await Persistent.create(80); + same(persistent.truthful_capabilities(),true); + same(await persistent.context_and_reference_refusal(),true); + const fingerprint=Array.from(persistent.fingerprint()); + const encoded=Array.from(await persistent.protect(new Uint8Array([80,81,82]))); + same(Array.from(await persistent.reveal(new Uint8Array(encoded))),[80,81,82]); + const changedEnvelope=new Uint8Array(encoded);changedEnvelope[changedEnvelope.length-1]^=1; + await rejects(()=>persistent.reveal(changedEnvelope),'persistent_crypto_refused'); + await persistent.close(); + const reopenedProvider=await Persistent.open(80,new Uint8Array(fingerprint)); + same(Array.from(await reopenedProvider.reveal(new Uint8Array(encoded))),[80,81,82]); + await rejects(()=>Persistent.open(80,new Uint8Array(32)),'provider_key_mismatch'); + await rejects(()=>Persistent.create(80),'namespace_exists'); + await reopenedProvider.close(); + const different=await Persistent.create(81); + if(JSON.stringify(Array.from(different.fingerprint()))===JSON.stringify(fingerprint))throw Error('independent master keys aliased'); + await different.close(); + passed('persistent key creation, exact reopen, context, reference, capabilities and key independence'); + const dataStore=await Fixture.open(80,true); + await dataStore.write(4,undefined,new Uint8Array(encoded));await dataStore.close(); await rejects(()=>Fixture.open(12,false),'missing_namespace'); console.log('STEP missing_existing_refused'); const db=await Fixture.open(12,true); @@ -106,6 +129,80 @@ try { request.onupgradeneeded=()=>upgrade?.(request.result); request.onsuccess=()=>resolve(request.result);request.onerror=()=>reject(Error('raw fixture open failed')); }); + const providerName=n=>'radroots.secrets.browser.v1.persistent_fixture_'+n; + const providerRaw=n=>new Promise((resolve,reject)=>{ + const request=indexedDB.open(providerName(n),1); + request.onupgradeneeded=()=>request.transaction.abort(); + request.onsuccess=()=>resolve(request.result);request.onerror=()=>reject(Error('missing provider fixture')); + }); + const providerRead=async n=>{ + const raw=await providerRaw(n); + try{return await new Promise((resolve,reject)=>{ + const tx=raw.transaction('provider','readonly');const store=tx.objectStore('provider');let key,binding; + store.get('key').onsuccess=e=>key=e.target.result;store.get('binding').onsuccess=e=>binding=e.target.result; + tx.oncomplete=()=>resolve({key,binding});tx.onabort=reject; + });}finally{raw.close();} + }; + const providerMutate=async(n,change)=>{ + const raw=await providerRaw(n); + try{await new Promise((resolve,reject)=>{const tx=raw.transaction('provider','readwrite');change(tx.objectStore('provider'));tx.oncomplete=resolve;tx.onabort=reject;});} + finally{raw.close();} + }; + const storedProvider=await providerRead(80); + same(storedProvider.key.type,'secret');same(storedProvider.key.algorithm.name,'HKDF');same(storedProvider.key.extractable,false);same(storedProvider.key.usages,['deriveKey']); + let exportRefused=false;try{await crypto.subtle.exportKey('raw',storedProvider.key);}catch{exportRefused=true;}same(exportRefused,true); + passed('actual persisted master CryptoKey is nonextractable and raw export is refused'); + const copied=await Persistent.create(82);await copied.close(); + await providerMutate(82,store=>{store.put(storedProvider.key,'key');store.put(storedProvider.binding,'binding');}); + await rejects(()=>Persistent.open(82,new Uint8Array(fingerprint)),'provider_key_mismatch'); + passed('copied key and metadata cannot cross namespace binding'); + const lostKey=await Persistent.create(86);const lostFingerprint=lostKey.fingerprint(); + const lostNamespace=await Persistent.create(87);const lostNamespaceFingerprint=lostNamespace.fingerprint(); + const originalImport=SubtleCrypto.prototype.importKey;let masterImports=0; + SubtleCrypto.prototype.importKey=function(format,data,algorithm,...args){if((typeof algorithm==='string'?algorithm:algorithm.name)==='HKDF')masterImports++;return originalImport.call(this,format,data,algorithm,...args);}; + try{ + await providerMutate(86,store=>store.delete('key')); + await rejects(()=>lostKey.protect(new Uint8Array([1])),'persistent_crypto_refused'); + await rejects(()=>Persistent.open(86,lostFingerprint),'missing_key'); + await rejects(()=>Persistent.create(86),'namespace_exists');await lostKey.close(); + await new Promise((resolve,reject)=>{const request=indexedDB.deleteDatabase(providerName(87));request.onsuccess=resolve;request.onerror=reject;}); + await rejects(()=>lostNamespace.protect(new Uint8Array([1])),'persistent_crypto_refused'); + await rejects(()=>Persistent.open(87,lostNamespaceFingerprint),'missing_namespace');await lostNamespace.close(); + same(masterImports,0); + }finally{SubtleCrypto.prototype.importKey=originalImport;} + passed('actual key and namespace loss refuse without master-key regeneration'); + const wrongKey=await Persistent.create(91);const wrongFingerprint=wrongKey.fingerprint(); + await providerMutate(91,store=>store.put({algorithm:'HKDF'},'key')); + await rejects(()=>wrongKey.protect(new Uint8Array([1])),'persistent_crypto_refused'); + await rejects(()=>Persistent.open(91,wrongFingerprint),'provider_key_mismatch');await wrongKey.close(); + const foreignProvider=n=>new Promise((resolve,reject)=>{const request=indexedDB.open(providerName(n),n===89?2:1);request.onupgradeneeded=()=>request.result.createObjectStore('provider',{autoIncrement:true});request.onsuccess=()=>{request.result.close();resolve();};request.onerror=reject;}); + for(const n of [88,89]){await foreignProvider(n);await rejects(()=>Persistent.open(n,new Uint8Array(32)),'incompatible_schema');} + passed('foreign key representation and provider schema/version are refused'); + const originalAdd=IDBObjectStore.prototype.add;let keyWriteSucceeded=false; + IDBObjectStore.prototype.add=function(...args){const request=originalAdd.apply(this,args);if(this.name==='provider'){request.addEventListener('success',()=>{if(args[1]==='key')keyWriteSucceeded=true;if(args[1]==='binding')this.transaction.abort();},{once:true});}return request;}; + try{await rejects(()=>Persistent.create(92),'transaction_aborted');}finally{IDBObjectStore.prototype.add=originalAdd;} + same(keyWriteSucceeded,true);await rejects(()=>Persistent.open(92,new Uint8Array(32)),'missing_namespace'); + passed('actual creation abort after key-write success returns no provider and retains no empty namespace'); + const originalOpen=IDBFactory.prototype.open;let createdResolve; + const createdUnobserved=new Promise(resolve=>createdResolve=resolve); + IDBFactory.prototype.open=function(...args){const request=originalOpen.apply(this,args);if(args[0]===providerName(93))request.addEventListener('success',()=>createdResolve(),{once:true});return request;}; + try{Persistent.abandon_create(93);await createdUnobserved;}finally{IDBFactory.prototype.open=originalOpen;} + const unobserved=await providerRead(93);const unobservedFingerprint=unobserved.binding.slice(unobserved.binding.length-32); + const retained=await Persistent.open(93,unobservedFingerprint);const retainedBytes=await retained.protect(new Uint8Array([93]));same(Array.from(await retained.reveal(retainedBytes)),[93]);await retained.close(); + passed('accepted creation remains Rust-owned after its observer is dropped'); + const completedSetups=new Set();let setupsResolve; + const allSetups=new Promise(resolve=>setupsResolve=resolve); + IDBFactory.prototype.open=function(...args){const request=originalOpen.apply(this,args);for(let n=100;n<132;n++)if(args[0]===providerName(n))request.addEventListener('success',()=>{completedSetups.add(n);if(completedSetups.size===32)setupsResolve();},{once:true});return request;}; + try{Persistent.abandon_setup_batch(100);await allSetups;}finally{IDBFactory.prototype.open=originalOpen;} + const setupBinding=(await providerRead(100)).binding; + const setupReopened=await Persistent.open(100,setupBinding.slice(-32)); + await setupReopened.close();setupReopened.free(); + passed('create and open share bounded setup admission and release it after unobserved completion'); + const busy=await Persistent.create(94);const busyFingerprint=busy.fingerprint(); + same(busy.abandon_wraps(33),32);for(let n=0;n<64;n++)busy.abandon_close();await busy.close(); + await rejects(()=>busy.protect(new Uint8Array([1])),'persistent_crypto_refused'); + const busyReopened=await Persistent.open(94,busyFingerprint);await busyReopened.close(); + passed('bounded wrapping survives dropped observers and cancelled close, then reopens'); const foreign=await rawOpen(14,1,db=>db.createObjectStore('records',{autoIncrement:true}));foreign.close(); await rejects(()=>Fixture.open(14,false),'incompatible_schema'); const future=await rawOpen(15,2,db=>db.createObjectStore('records'));future.close(); @@ -127,9 +224,23 @@ try { await rejects(()=>Fixture.open(18,false),'missing_namespace');passed('actual namespace deletion cannot silently recreate'); const workerResult=await new Promise((resolve,reject)=>{const worker=new Worker('./worker.js',{type:'module'});worker.onmessage=e=>{if(e.data.ready){worker.postMessage('run');return;}worker.terminate();resolve(e.data);};worker.onerror=e=>{worker.terminate();reject(Error(e.message));};}); same(workerResult,{value:[77]});passed('dedicated worker actual WASM and IndexedDB reopen'); - return {tests,events:events.reduce((all,event)=>(all[event]=(all[event]??0)+1,all),{})}; + const workerCall=message=>new Promise((resolve,reject)=>{const worker=new Worker('./worker.js',{type:'module'});worker.onmessage=e=>{if(e.data.ready){worker.postMessage(message);return;}worker.terminate();if(e.data.error)reject(Error(e.data.error));else resolve(e.data);};worker.onerror=e=>{worker.terminate();reject(Error(e.message));};}); + const workerCreated=await workerCall({kind:'persistent_create'}); + same(await workerCall({kind:'persistent_open',...workerCreated}),{plain:[90,91,92]}); + passed('persistent provider survives actual worker termination and new worker instance'); + return {tests,events:events.reduce((all,event)=>(all[event]=(all[event]??0)+1,all),{}),persistent:{fingerprint,encoded}}; } finally {IDBDatabase.prototype.transaction=nativeTransaction;} }); + await page.reload(); + const restarted=await page.evaluate(async receipt=>{ + const {default:init,Persistent,Fixture}=await import('./fixture.js');await init(); + const provider=await Persistent.open(80,new Uint8Array(receipt.fingerprint)); + const store=await Fixture.open(80,false);const encoded=await store.read(4); + const plain=await provider.reveal(encoded);await provider.close();await store.close();return Array.from(plain); + },result.persistent); + assert.deepEqual(restarted,[80,81,82]); + result.tests.push('persistent provider and encrypted data survive actual page and WASM restart'); + delete result.persistent; console.log(JSON.stringify({engine,version:browser.version(),...result})); } finally { clearTimeout(deadline); diff --git a/crates/storage_indexeddb/tests/browser/src/lib.rs b/crates/storage_indexeddb/tests/browser/src/lib.rs @@ -7,6 +7,8 @@ use wasm_bindgen::prelude::*; mod protected; pub use protected::protected_round_trip; +mod persistent; +pub use persistent::Persistent; fn failure(error: Error) -> JsValue { JsValue::from_str(error.code()) diff --git a/crates/storage_indexeddb/tests/browser/src/persistent.rs b/crates/storage_indexeddb/tests/browser/src/persistent.rs @@ -0,0 +1,259 @@ +use futures::FutureExt; +use radroots_secrets::{ + EncryptedEnvelope, KeyWrapping, SecretId, SecretProvider, SecretRef, + browser::BrowserProvider, + context::{EnvelopeContext, EnvelopePurpose, EnvelopeSubject, PayloadSchemaId}, + envelope::{Nonce, SealMaterial, SealRequest}, + id::{BackendKind, KeyVersion}, + provider::{ + AccessPolicy, CapabilitySupport, HardwarePolicy, ResidencyPolicy, ResidencySupport, + SelectionPolicy, UserPresencePolicy, + }, + wrapping::{SecretMaterial, UnwrapRequest, WrapRequest}, +}; +use wasm_bindgen::JsCast; +use wasm_bindgen::prelude::*; + +fn reference() -> SecretRef { + SecretRef::new( + SecretId::parse("persistent_fixture_key").unwrap(), + BackendKind::External, + KeyVersion::new(1).unwrap(), + ) +} +fn namespace(n: u8) -> SecretId { + SecretId::parse(format!("persistent_fixture_{n}")).unwrap() +} +fn context(n: u8) -> EnvelopeContext { + EnvelopeContext::new( + EnvelopePurpose::parse("radroots.persistent_fixture").unwrap(), + EnvelopeSubject::parse("fixture", n.to_string()).unwrap(), + PayloadSchemaId::parse("radroots.persistent_fixture.v1").unwrap(), + ) +} +fn fail(_: radroots_secrets::Error) -> JsValue { + JsValue::from_str("persistent_crypto_refused") +} +fn rng() -> web_sys::Crypto { + js_sys::Reflect::get(&js_sys::global(), &JsValue::from_str("crypto")) + .unwrap() + .dyn_into() + .unwrap() +} + +#[wasm_bindgen] +pub struct Persistent { + provider: BrowserProvider, + n: u8, +} +#[wasm_bindgen] +impl Persistent { + pub fn abandon_setup_batch(first: u8) -> Result<(), JsValue> { + for n in first..first + 32 { + Self::abandon_create(n)?; + } + if !matches!( + BrowserProvider::create(namespace(first + 32), reference()).now_or_never(), + Some(Err(radroots_secrets::browser::BrowserError::Capacity)) + ) { + return Err(JsValue::from_str("setup_admission_was_not_bounded")); + } + if !matches!( + BrowserProvider::open(namespace(first), reference(), [0; 32]).now_or_never(), + Some(Err(radroots_secrets::browser::BrowserError::Capacity)) + ) { + return Err(JsValue::from_str("setup_open_admission_was_not_bounded")); + } + Ok(()) + } + pub fn abandon_create(n: u8) -> Result<(), JsValue> { + if BrowserProvider::create(namespace(n), reference()) + .now_or_never() + .is_some() + { + return Err(JsValue::from_str("unexpected_immediate_create")); + } + Ok(()) + } + pub async fn create(n: u8) -> Result<Persistent, JsValue> { + Ok(Self { + provider: BrowserProvider::create(namespace(n), reference()) + .await + .map_err(|e| JsValue::from_str(e.code()))?, + n, + }) + } + pub async fn open(n: u8, fingerprint: Vec<u8>) -> Result<Persistent, JsValue> { + let fingerprint = fingerprint + .as_slice() + .try_into() + .map_err(|_| JsValue::from_str("invalid_fingerprint"))?; + Ok(Self { + provider: BrowserProvider::open(namespace(n), reference(), fingerprint) + .await + .map_err(|e| JsValue::from_str(e.code()))?, + n, + }) + } + pub fn fingerprint(&self) -> Vec<u8> { + self.provider.fingerprint().to_vec() + } + pub fn truthful_capabilities(&self) -> bool { + let capabilities = self.provider.capabilities(); + assert_eq!(capabilities.residency(), ResidencySupport::UserProfile); + assert_eq!( + capabilities.hardware_backed(), + CapabilitySupport::Unavailable + ); + assert_eq!(capabilities.user_presence(), CapabilitySupport::Unavailable); + let candidates: [&dyn SecretProvider; 1] = [&self.provider]; + assert!( + SelectionPolicy::new(BackendKind::External, AccessPolicy::standard()) + .select(&candidates) + .is_ok() + ); + for policy in [ + AccessPolicy::new( + ResidencyPolicy::DeviceLocal, + UserPresencePolicy::NotRequired, + HardwarePolicy::Any, + ), + AccessPolicy::new( + ResidencyPolicy::Any, + UserPresencePolicy::Required, + HardwarePolicy::Any, + ), + AccessPolicy::new( + ResidencyPolicy::Any, + UserPresencePolicy::NotRequired, + HardwarePolicy::RequireHardwareBacked, + ), + ] { + assert!( + SelectionPolicy::new(BackendKind::External, policy) + .select(&candidates) + .is_err() + ); + } + true + } + pub async fn protect(&self, bytes: Vec<u8>) -> Result<Vec<u8>, JsValue> { + let mut key = [0; 32]; + let mut nonce = [0; 24]; + rng().get_random_values_with_u8_array(&mut key).unwrap(); + rng().get_random_values_with_u8_array(&mut nonce).unwrap(); + let material = SecretMaterial::from_slice(&key).map_err(fail)?; + key.fill(0); + let plaintext = SecretMaterial::from_slice(&bytes).map_err(fail)?; + EncryptedEnvelope::seal( + &self.provider, + SealRequest::new( + reference(), + context(self.n), + &plaintext, + SealMaterial::new(material, Nonce::new(nonce)), + ), + ) + .await + .map_err(fail)? + .encode() + .map_err(fail) + } + pub async fn reveal(&self, encoded: Vec<u8>) -> Result<Vec<u8>, JsValue> { + let envelope = EncryptedEnvelope::decode(&encoded).map_err(fail)?; + envelope + .open(&self.provider, &context(self.n)) + .await + .map_err(fail) + .map(|plain| plain.expose_secret(|bytes| bytes.to_vec())) + } + pub async fn context_and_reference_refusal(&self) -> Result<bool, JsValue> { + let reference = reference(); + let expected = context(self.n); + let wrong = context(self.n.wrapping_add(1)); + let plaintext = SecretMaterial::from_slice(&[0x31; 32]).map_err(fail)?; + let wrapped = self + .provider + .wrap(WrapRequest::new(&reference, &expected, &plaintext)) + .await + .map_err(fail)?; + assert!( + self.provider + .unwrap(UnwrapRequest::new(&reference, &wrong, &wrapped)) + .await + .is_err() + ); + let foreign = SecretRef::new( + SecretId::parse("foreign_key").unwrap(), + BackendKind::External, + KeyVersion::new(1).unwrap(), + ); + assert!( + self.provider + .wrap(WrapRequest::new(&foreign, &expected, &plaintext)) + .await + .is_err() + ); + let version = SecretRef::new( + SecretId::parse("persistent_fixture_key").unwrap(), + BackendKind::External, + KeyVersion::new(2).unwrap(), + ); + assert!( + self.provider + .unwrap(UnwrapRequest::new(&version, &expected, &wrapped)) + .await + .is_err() + ); + let memory = SecretRef::new( + SecretId::parse("persistent_fixture_key").unwrap(), + BackendKind::Memory, + KeyVersion::new(1).unwrap(), + ); + assert!( + self.provider + .wrap(WrapRequest::new(&memory, &expected, &plaintext)) + .await + .is_err() + ); + let short = SecretMaterial::from_slice(&[1; 31]).map_err(fail)?; + assert!( + self.provider + .wrap(WrapRequest::new(&reference, &expected, &short)) + .await + .is_err() + ); + Ok(true) + } + pub fn abandon_wraps(&self, count: usize) -> Result<usize, JsValue> { + let reference = reference(); + let context = context(self.n); + let plaintext = SecretMaterial::from_slice(&[1; 32]).map_err(fail)?; + for index in 0..count { + if let Some(result) = self + .provider + .wrap(WrapRequest::new(&reference, &context, &plaintext)) + .now_or_never() + { + return if result.is_err() { + Ok(index) + } else { + Err(JsValue::from_str("unexpected_immediate_wrap")) + }; + } + } + Ok(count) + } + pub fn abandon_close(&self) -> Result<(), JsValue> { + if self.provider.close().now_or_never().is_some() { + return Err(JsValue::from_str("unexpected_immediate_close")); + } + Ok(()) + } + pub async fn close(&self) -> Result<(), JsValue> { + self.provider + .close() + .await + .map_err(|e| JsValue::from_str(e.code())) + } +}