lib

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

README.md (10971B)


      1 # radroots_secrets
      2 
      3 `radroots_secrets` defines the bounded secret-provider, key-wrapping, and
      4 authenticated-envelope contracts for Radroots. Hosts choose and configure a
      5 provider explicitly; this crate does not own application authorization,
      6 credential UI, account policy, application command execution, or global provider state.
      7 
      8 The crate is pre-release and publication remains disabled. Its Cargo version
      9 is frozen at `0.1.0-alpha` until the coordinated release contract explicitly
     10 changes it.
     11 
     12 ## Canonical surface
     13 
     14 | Module | Responsibility |
     15 | --- | --- |
     16 | `id` | Validated, redacted identifiers, backend kinds, key versions, and single-owner references. |
     17 | `provider` | Provider capabilities, exact selection policy, and the executor-neutral provider SPI. |
     18 | `wrapping` | Bounded zeroizing plaintext, wrapped values, requests, and the key-wrapping SPI. |
     19 | `envelope` | Versioned XChaCha20-Poly1305 envelope encoding with authenticated provider metadata. |
     20 | `memory` | Opt-in, process-local adapter for development and deterministic tests. |
     21 | `file` | Opt-in encrypted file adapter with secure path, permission, and durable-write rules. |
     22 | `keyring` | Opt-in operating-system credential-store adapter with lazy native access. |
     23 | `browser` | Opt-in WASM origin-storage provider with independently pinned nonextractable keys. |
     24 | `error` | Normalized errors that do not expose provider-native messages or secret values. |
     25 
     26 The curated root exports only `EncryptedEnvelope`, `Error`, `SecretId`,
     27 `SecretRef`, `SecretProvider`, and `KeyWrapping`. Supporting request, policy,
     28 adapter, and value types remain in their owning modules so security boundaries
     29 stay explicit. The reviewed Rust surface is recorded in the
     30 [public API baseline](../../contracts/api_baselines/radroots_secrets.txt).
     31 
     32 ## Explicit provider and envelope flow
     33 
     34 The memory adapter is empty when constructed. This example provisions an
     35 explicit key, supplies a separate explicit data key and nonce, seals one value,
     36 serializes the envelope, and opens it again:
     37 
     38 ```rust
     39 # #[cfg(feature = "memory")]
     40 # fn main() -> Result<(), Box<dyn std::error::Error>> {
     41 use futures_executor::block_on;
     42 use radroots_secrets::EncryptedEnvelope;
     43 use radroots_secrets::context::{
     44     EnvelopeContext, EnvelopePurpose, EnvelopeSubject, PayloadSchemaId,
     45 };
     46 use radroots_secrets::envelope::{Nonce, SealMaterial, SealRequest};
     47 use radroots_secrets::id::{BackendKind, KeyVersion};
     48 use radroots_secrets::memory::MemoryProvider;
     49 use radroots_secrets::wrapping::SecretMaterial;
     50 use radroots_secrets::{SecretId, SecretRef};
     51 
     52 let reference = SecretRef::new(
     53     SecretId::parse("example-profile-key")?,
     54     BackendKind::Memory,
     55     KeyVersion::new(1)?,
     56 );
     57 let provider = MemoryProvider::new();
     58 provider.provision(
     59     &reference,
     60     SecretMaterial::from_slice(&[0x41; 32])?,
     61 )?;
     62 
     63 let plaintext = SecretMaterial::from_slice(b"private profile value")?;
     64 let data_key = SecretMaterial::from_slice(&[0x41; 32])?;
     65 let context = EnvelopeContext::new(
     66     EnvelopePurpose::parse("radroots.private_profile")?,
     67     EnvelopeSubject::parse("profile", "example-profile")?,
     68     PayloadSchemaId::parse("radroots.private_profile.v1")?,
     69 );
     70 let request = SealRequest::new(
     71     reference,
     72     context.clone(),
     73     &plaintext,
     74     SealMaterial::new(data_key, Nonce::new([0x24; 24])),
     75 );
     76 let encoded = block_on(EncryptedEnvelope::seal(&provider, request))?.encode()?;
     77 let decoded = EncryptedEnvelope::decode(&encoded)?;
     78 let opened = block_on(decoded.open(&provider, &context))?;
     79 
     80 opened.expose_secret(|bytes| assert_eq!(bytes, b"private profile value"));
     81 # Ok(())
     82 # }
     83 # #[cfg(not(feature = "memory"))]
     84 # fn main() {}
     85 ```
     86 
     87 A runnable version is available at
     88 [`examples/explicit_memory_provider.rs`](examples/explicit_memory_provider.rs).
     89 Its fixed key and nonce exist only to make the example deterministic. Production
     90 hosts must supply cryptographically strong key material and a unique nonce for
     91 every encryption under the same data key.
     92 
     93 ## Features and supported targets
     94 
     95 | Feature | Default | Effect |
     96 | --- | --- | --- |
     97 | `std` | yes | Enables standard-library integration; it performs no I/O by itself. |
     98 | `serde` | yes | Serializes validated identifiers and encoded envelopes, never plaintext material or capability references. |
     99 | `memory` | no | Enables the explicit process-local adapter; requires `std`. |
    100 | `file` | no | Enables encrypted file persistence; requires `std`. |
    101 | `keyring` | no | Enables lazy operating-system credential-store access; requires `std`. |
    102 | `browser` | no | Enables the explicit WASM Web Crypto/IndexedDB adapter; requires `std`. |
    103 
    104 The core contracts compile without the standard library. `file` and `keyring`
    105 are native host adapters; `memory` is available on standard-library targets.
    106 No feature installs a global provider, starts a runtime, generates key
    107 material, selects a fallback, opens storage, or performs a credential prompt.
    108 
    109 Provider and wrapping ownership is target-aware through
    110 `wrapping::HostBound`: native hosts retain `Send + Sync` and sendable futures;
    111 WASM hosts may retain local objects and local futures, including scoped
    112 `Rc`/`RefCell` callbacks. This changes no residency, presence or hardware claim.
    113 Envelope migration validators follow the same host boundary. Hosts still own
    114 accepted work and callback lifetimes; the SPI starts no executor or background
    115 task and supplies no unsafe thread bridge.
    116 
    117 `browser::BrowserProvider::create` explicitly creates one immutable selected
    118 key/version in a new origin namespace. `open` requires the caller's retained
    119 public fingerprint. Missing or changed keys never trigger generation or
    120 replacement; retain old namespaces for their protected data. Native targets do
    121 not compile this adapter. Its capability report is user-profile storage with
    122 presence, device-local and hardware requirements unavailable.
    123 
    124 The provider keeps a nonextractable HKDF master CryptoKey in IndexedDB, derives
    125 AES-256-KW keys from the exact namespace/reference/context and wraps 32-byte
    126 data keys. Generic envelope v2 retains its XChaCha20-Poly1305 format and nonce
    127 requirements. Provider keys never leave the adapter; controllable transient
    128 plaintext arrays are cleared. The browser and OS own their internal key memory.
    129 See the [Web Crypto key serialization contract](https://www.w3.org/TR/webcrypto/#cryptokey-interface-clone).
    130 
    131 The adapter exposes a provider only after the key and binding commit together.
    132 Its accepted mechanical jobs and event callbacks stay Rust-owned through lost
    133 observation. Close stops admission and drains those jobs. Version change and
    134 unexpected database closure stop admission. Storage eviction remains possible;
    135 exact opening then fails without creating an empty replacement. A fingerprint
    136 is a provider identity check and grants no participant or stock authority.
    137 
    138 ## Security and serialization contract
    139 
    140 `SecretMaterial` is bounded, single-owner, zeroizing plaintext. It implements
    141 neither `Clone` nor serialization and exposes bytes only inside an explicit
    142 closure. `SecretRef`, seal requests, and seal material are likewise not
    143 cloneable or serializable. Secret identifiers are serialized only where a
    144 documented wire or storage format requires them; their ordinary diagnostics
    145 remain redacted.
    146 
    147 `EncryptedEnvelope` v2 authenticates its format version, cipher, key source,
    148 backend, key version, secret identifier, purpose, typed subject, payload
    149 schema, nonce, wrapped data key, and ciphertext length. Normal open requires an
    150 independently derived expected context and rejects legacy v1. Decode validates
    151 all lengths and enum values before provider access. Envelope serialization is
    152 a persistence contract; Rust layout and debug output are not. Unknown versions,
    153 ciphers, key sources, malformed lengths, context mismatches, backend mismatches,
    154 and authentication failures fail closed.
    155 
    156 Legacy v1 bytes remain decodeable for migration inventory, but normal open
    157 always rejects them. An authorized host migration boundary must explicitly
    158 construct `LegacyV1ResealAuthority`, supply the independently derived v2
    159 context and expected provider reference, validate the owning payload schema,
    160 and provide a fresh data key and nonce. The migration primitive rejects key or
    161 nonce reuse and returns only a new v2 envelope plus a plaintext commitment;
    162 transient plaintext and key material remain single-owner zeroizing values.
    163 
    164 Provider-native error strings are normalized before crossing the public
    165 boundary. Callers must still avoid logging plaintext, serialized identifiers,
    166 encoded envelopes, or provider configuration.
    167 
    168 ## Side effects, cancellation, and commit points
    169 
    170 Constructing `MemoryProvider` and `KeyringProvider`, querying capabilities,
    171 validating identifiers, selecting a provider, and encoding or decoding an
    172 already-built envelope do not access secret storage. `KeyringProvider` creates
    173 native credential entries lazily when an explicit operation begins.
    174 
    175 Memory provisioning commits when the in-process map accepts the value. File
    176 provisioning commits when the no-clobber entry is durably renamed and its
    177 directory is synchronized. File rotation commits the new version before
    178 removing the old version and can resume that boundary. Keyring provisioning
    179 commits when the native store accepts the credential. Removal is idempotent;
    180 rotation requires a higher version of the same identifier.
    181 
    182 The SPIs return executor-neutral futures and do not create cancellation tokens
    183 or background work. Dropping a future before its provider commit point cancels
    184 only work the provider has not committed. After a durable or native commit,
    185 the host must inspect or retry the exact operation; it must not assume that
    186 dropping the future rolled the operation back. The built-in adapters perform no
    187 implicit retry or fallback.
    188 
    189 ## Intended consumers
    190 
    191 Direct consumers are storage adapters, SDK signing hosts, Myc custody hosts,
    192 and other first-party runtimes that own provider selection and authorization.
    193 Applications should normally consume these contracts through `radroots_sdk`.
    194 External provider implementations may implement `SecretProvider` and
    195 `KeyWrapping` without depending on a built-in adapter.
    196 
    197 This package must not acquire actor authorization, signing policy, account
    198 management, application database ownership, UI prompts, executor ownership,
    199 global sessions, network transport, or provider fallback. Those responsibilities
    200 remain with their dedicated packages and hosts.
    201 
    202 ## Package charter
    203 
    204 The authoritative responsibility, dependency, feature, module, root-export,
    205 and forbidden-scope contract is the
    206 [Radroots crates Release V1 specification](../../contracts/crates/release_v1/radroots_crates_release_v1.toml).
    207 The reviewed surface is the
    208 [`radroots_secrets` API baseline](../../contracts/api_baselines/radroots_secrets.txt).
    209 
    210 ## Copyright
    211 
    212 Except as otherwise noted, all files in the `radroots_secrets` distribution
    213 are copyright (c) 2025 Tyson Lupul. See `LICENSE` for usage, redistribution,
    214 and warranty terms.