diff --git a/.cargo/config.toml b/.cargo/config.toml index 60e1f61..af3bfde 100644 --- a/.cargo/config.toml +++ b/.cargo/config.toml @@ -1,2 +1,10 @@ [target.'cfg(target_arch = "aarch64")'] rustflags = ["--cfg", "aes_armv8"] + +# getrandom 0.3 (through turso_core) needs this cfg to pick its Web Crypto +# backend on wasm32-unknown-unknown. Only a backend selection, never a URL. +[target.wasm32-unknown-unknown] +rustflags = ["--cfg", 'getrandom_backend="wasm_js"'] + +[target.wasm32-wasip1] +runner = "wasmtime run --dir=." diff --git a/.github/workflows/cryptex.yml b/.github/workflows/cryptex.yml index b3400a2..b5ffc59 100644 --- a/.github/workflows/cryptex.yml +++ b/.github/workflows/cryptex.yml @@ -1,5 +1,8 @@ name: Cryptex CI +permissions: + contents: read + on: push: branches: main @@ -46,7 +49,7 @@ jobs: - name: Install native dependencies for encrypted-vfs and YubiHSM run: sudo apt-get install -y libclang-dev libusb-1.0-0-dev - run: cargo clippy --no-default-features --features encrypted-vfs -- -D warnings - - run: cargo clippy --all-targets --all-features -- -D warnings + - run: cargo clippy --all-targets --features "file,serde,encrypted-vfs,memory,turso,turso-encrypted-io,yubihsm-usb,yubihsm-http" -- -D warnings clippy-macos: runs-on: macos-latest @@ -82,6 +85,39 @@ jobs: - run: cargo clippy --no-default-features --features "windows-credentials,file" -- -D warnings - run: cargo clippy --no-default-features --features encrypted-vfs -- -D warnings + wasm: + runs-on: ubuntu-latest + env: + # The workflow-level RUSTFLAGS override the per-target flags in + # .cargo/config.toml, so the getrandom backend is repeated here. + RUSTFLAGS: '-D warnings --cfg getrandom_backend="wasm_js"' + steps: + - uses: actions/checkout@v4 + - uses: dtolnay/rust-toolchain@master + with: + toolchain: stable + components: clippy + targets: wasm32-unknown-unknown,wasm32-wasip1,wasm32-wasip2 + # WASI takes getrandom's WASI backend, so its checks drop the wasm_js cfg. + - name: Check browser and WASI backends + run: | + cargo clippy --target wasm32-unknown-unknown --no-default-features --features turso -- -D warnings + cargo clippy --target wasm32-unknown-unknown --no-default-features --features "turso,turso-encrypted-io" -- -D warnings + cargo clippy --target wasm32-unknown-unknown --no-default-features --features memory -- -D warnings + cargo clippy --target wasm32-unknown-unknown --no-default-features --features "turso,turso-opfs,indexeddb,web-storage,js" -- -D warnings + RUSTFLAGS="-D warnings" cargo check --target wasm32-wasip1 --no-default-features --features "turso,memory" + RUSTFLAGS="-D warnings" cargo check --target wasm32-wasip2 --no-default-features --features "turso,memory" + - name: Install wasm-pack + # Pinned and built from the registry: piping an unpinned installer + # script into a shell runs whatever that URL serves today. + run: cargo install wasm-pack --locked --version 0.13.1 + - name: Build the JavaScript package + run: wasm-pack build --target web --no-default-features --features js + # The runner image ships Chrome with a matching ChromeDriver; a separately + # installed driver tracks a newer Chrome and refuses the image's browser. + - name: Run the browser tests + run: wasm-pack test --headless --chrome --chromedriver "$CHROMEWEBDRIVER/chromedriver" --no-default-features --features js --test wasm + rustfmt-linux: runs-on: ubuntu-latest steps: @@ -123,7 +159,7 @@ jobs: - name: Install native dependencies for encrypted-vfs and YubiHSM run: sudo apt-get install -y libclang-dev libusb-1.0-0-dev - run: cargo doc --no-default-features --features encrypted-vfs - - run: cargo doc --no-deps --all-features + - run: cargo doc --no-deps --features "file,serde,encrypted-vfs,memory,turso,turso-encrypted-io,yubihsm-usb,yubihsm-http" doc-macos: runs-on: macos-latest @@ -191,7 +227,7 @@ jobs: run: cargo test --test default_argon2_params --no-default-features --features "file,encrypted-vfs" - name: Test all features if: matrix.cache-key == 'encrypted-vfs' - run: cargo test --all-features + run: cargo test --features "file,serde,encrypted-vfs,memory,turso,turso-encrypted-io,yubihsm-usb,yubihsm-http" macos: runs-on: macos-latest @@ -289,7 +325,8 @@ jobs: toolchain: nightly - uses: cargo-bins/cargo-binstall@main - run: cargo binstall --no-confirm cargo-outdated - - run: cargo outdated --root-deps-only --exit-code=1 + # bindgen must match sqlite-plugin's 0.72 to turn on its `runtime` feature. + - run: cargo outdated --root-deps-only --exit-code=1 --ignore bindgen pants: runs-on: ubuntu-latest diff --git a/Cargo.toml b/Cargo.toml index 973373e..bef4bbe 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -13,10 +13,22 @@ keywords = ["secrets", "vault", "keyring"] license = "MIT/Apache-2.0" repository = "https://github.com/mikelodder7/cryptex" readme = "README.md" -version = "2.4.0" +version = "2.5.0" +# `all-features` is not used: the browser-only features (web-storage, +# indexeddb, opfs, js) are rejected on non-wasm targets on purpose. [package.metadata.docs.rs] -all-features = true +no-default-features = true +features = [ + "serde", + "file", + "encrypted-vfs", + "memory", + "turso", + "turso-encrypted-io", + "yubihsm-usb", + "yubihsm-http", +] rustdoc-args = ["--cfg", "docsrs"] [package.metadata.cargo-udeps.ignore] @@ -31,8 +43,35 @@ name = "cryptex" [features] default = ["linux-secret-service", "macos-keychain", "windows-credentials"] file = ["dep:argon2", "dep:dirs", "dep:rusqlite", "rusqlite/bundled-sqlcipher-vendored-openssl"] +memory = ["dep:argon2", "dep:chacha20poly1305", "dep:aes-gcm", "dep:getrandom"] +web-storage = [ + "memory", + "dep:web-sys", + "dep:wasm-bindgen", + "dep:wasm-bindgen-futures", + "dep:js-sys", +] +indexeddb = ["memory", "dep:web-sys", "dep:wasm-bindgen", "dep:wasm-bindgen-futures", "dep:js-sys"] +turso-opfs = [ + "turso", + "dep:web-sys", + "dep:wasm-bindgen", + "dep:wasm-bindgen-futures", + "dep:js-sys", +] +js = [ + "memory", + "web-storage", + "indexeddb", + "turso-opfs", + "turso", + "dep:web-sys", + "dep:wasm-bindgen", + "dep:wasm-bindgen-futures", + "dep:js-sys", +] encrypted-vfs = ["dep:argon2", "dep:dirs", "dep:rusqlite", "rusqlite/bundled", "dep:chacha20poly1305", "dep:aes-gcm", "dep:sqlite-plugin", "dep:getrandom"] -turso = ["dep:argon2", "dep:dirs", "dep:turso", "dep:bindgen"] +turso = ["dep:argon2", "dep:dirs", "dep:turso", "dep:bindgen", "dep:js-sys", "dep:wasm-bindgen"] turso-encrypted-io = ["dep:argon2", "dep:dirs", "dep:turso", "dep:bindgen", "dep:chacha20poly1305", "dep:aes-gcm", "dep:getrandom"] linux-secret-service = ["secret-service", "uzers"] macos-keychain = ["security-framework", "security-framework-sys", "core-foundation", "core-foundation-sys", "uzers"] @@ -42,30 +81,75 @@ yubihsm-usb = ["dep:yubihsm", "yubihsm/usb", "yubihsm/passwords", "dep:aes-gcm", yubihsm-http = ["dep:yubihsm", "yubihsm/http", "yubihsm/passwords", "dep:aes-gcm", "dep:sha2", "dep:getrandom", "dep:dirs"] [dependencies] -aes-gcm = { version = "0.11", optional = true } -argon2 = { version = "0.5", optional = true } -chacha20poly1305 = { version = "0.11", optional = true } +aes-gcm = { version = "0.11", features = ["zeroize"], optional = true } +argon2 = { version = "0.6", optional = true } +chacha20poly1305 = { version = "0.11", features = ["zeroize"], optional = true } clap = "4.6.1" colored = "3.0" -dirs = { version = "6.0", optional = true } +dirs = { version = "7.0", optional = true } getrandom = { version = "0.4.3", optional = true } hex = "0.4" postcard = { version = "1", default-features = false, features = ["use-std"], optional = true } -rpassword = "7.5.4" -rusqlite = { version = "0.40.1", default-features = false, optional = true } +rusqlite = { version = "0.43", default-features = false, optional = true } serde = { version = "1", optional = true } sha2 = { version = "0.11", optional = true } -sqlite-plugin = { version = "0.10", optional = true } +sqlite-plugin = { version = "0.11", optional = true } subtle = "2" # Pre-release pinned exactly: page encryption and custom IO are only exposed here. -turso = { version = "=0.9.0-pre.1", default-features = false, optional = true } +turso = { version = "=0.9.0-pre.6", default-features = false, optional = true } whoami = "2.1.2" yubihsm = { version = "0.42", default-features = false, optional = true } zeroize = { version = "1.9.0", features = ["zeroize_derive"] } -[dev-dependencies] +[target.'cfg(not(target_family = "wasm"))'.dependencies] +rpassword = "7.5.4" + +# Criterion pulls in Rayon, which does not build for wasm. +[target.'cfg(not(target_family = "wasm"))'.dev-dependencies] criterion = { version = "0.8", features = ["html_reports"] } +[target.'cfg(all(target_arch = "wasm32", target_os = "unknown"))'.dependencies] +getrandom = { version = "0.4.3", features = ["wasm_js"], optional = true } +js-sys = { version = "0.3", optional = true } +wasm-bindgen = { version = "0.2.130", optional = true } +wasm-bindgen-futures = { version = "0.4", optional = true } +web-sys = { version = "0.3", optional = true, features = [ + "Window", + "Storage", + "Performance", + "WorkerGlobalScope", + "WorkerNavigator", + "StorageManager", + "LockManager", + "LockManagerSnapshot", + "Lock", + "IdbFactory", + "IdbDatabase", + "IdbOpenDbRequest", + "IdbObjectStore", + "IdbTransaction", + "IdbTransactionMode", + "DomException", + "IdbRequest", + "FileSystemDirectoryHandle", + "FileSystemGetDirectoryOptions", + "FileSystemFileHandle", + "FileSystemGetFileOptions", + "FileSystemSyncAccessHandle", + "FileSystemReadWriteOptions", +] } + +# Turso's native page encryption on wasm must use its pure-Rust ciphers; +# the native `aegis` build links C. +[target.'cfg(all(target_arch = "wasm32", target_os = "unknown"))'.dependencies.turso] +version = "=0.9.0-pre.6" +default-features = false +features = ["pure-rust-crypto"] +optional = true + +[target.'cfg(all(target_arch = "wasm32", target_os = "unknown"))'.dev-dependencies] +wasm-bindgen-test = "0.3" + [[bench]] name = "cipher_bench" harness = false diff --git a/README.md b/README.md index bee0fa2..cc989b3 100644 --- a/README.md +++ b/README.md @@ -100,6 +100,183 @@ CRYPTEX_ARGON2_MEMORY=32768 CRYPTEX_ARGON2_THREADS=3 CRYPTEX_ARGON2_PARALLEL=2 c The program can be compiled from any OS to run on any OS. Cryptex-CLI is the command line tool while Cryptex is the library. +### In-memory keyrings + +The `memory` feature adds `MemoryKeyring`, which keeps its secrets in RAM and +never writes a file. It builds for every target, including wasm. Secrets leave +memory only as a single AEAD-sealed blob: + +```rust +use cryptex::KeyRing; +use cryptex::memory::{ConnectionParams, MemoryKeyring}; + +let params: ConnectionParams = + "password= salt=".parse().unwrap(); +let mut keyring = MemoryKeyring::with_params(¶ms)?; +keyring.set_secret("token", b"secret value")?; + +// Persist this anywhere you like; it is sealed with a fresh nonce. +let blob = keyring.export()?; +// The salt, cipher and Argon2 parameters travel inside the blob. +let mut reopened = MemoryKeyring::import(&blob, b"")?; +# Ok::<(), cryptex::KeyRingError>(()) +``` + +A blob made from `key=` instead of a password needs that same raw key to +open. `rekey` re-derives the key without touching the secrets. + +--- + +## WebAssembly and WASI + +`cryptex` builds for `wasm32-unknown-unknown` and for `wasm32-wasip1` / +`wasm32-wasip2`. Which backends exist there: + +| Feature | `wasm32-unknown-unknown` | WASI | Notes | +|---------|--------------------------|------|-------| +| `memory` | yes | yes | encrypted in RAM, export/import | +| `turso` | yes | yes | Turso's native page encryption, including in-memory and OPFS keyrings | +| `turso-encrypted-io` | builds | yes | the page cipher needs a `PageStore`; the file-backed one is native only | +| `web-storage` | yes | no | a `MemoryKeyring` sealed into `localStorage` | +| `indexeddb` | yes | no | encrypted image snapshots, one per keyring | +| `turso-opfs` | yes | no | the database file itself in the origin private file system | +| `js` | yes | no | the `wasm-bindgen` `Keyring` class | +| `file`, `encrypted-vfs` | no | no | SQLCipher and the bundled C VFS are native only | +| OS keyrings, `yubihsm-*` | no | no | no OS keychain or USB device | + +Asking for an unsupported backend on wasm is a compile error that names the +problem, rather than a linker failure. + +`getrandom` needs its Web Crypto backend on `wasm32-unknown-unknown`. The +repository's `.cargo/config.toml` sets it, and a CI job that overrides +`RUSTFLAGS` must repeat it: + +```bash +RUSTFLAGS='--cfg getrandom_backend="wasm_js"' \ + cargo check --target wasm32-unknown-unknown --no-default-features --features turso +``` + +### Browser keyrings + +The `js` feature wraps the backends in a `Keyring` class for JavaScript: + +```bash +wasm-pack build --target web --no-default-features --features js +``` + +```js +import init, { Keyring, requestPersistentStorage } from "./pkg/cryptex.js"; + +await init(); + +// An encrypted Turso database, persisted in IndexedDB. These are the defaults. +const keyring = await Keyring.open("password=hunter2 salt=0okm9ijn8uhb7ygv", "settings"); +await keyring.set("api-token", new TextEncoder().encode("s3cret")); +const token = keyring.get("api-token"); // Uint8Array +await keyring.delete("api-token"); + +// Ask the browser not to evict the origin's storage. +await requestPersistentStorage(); +await keyring.close(); +``` + +`open(connection, name, options)` chooses where the keyring lives: + +| `backend` | `store` | What is persisted | +|-----------|---------|-------------------| +| `"turso"` (default) | `"indexeddb"` (default) | the encrypted database image, saved after every change | +| `"turso"` | `"opfs"` | the database file itself, in the origin private file system | +| `"turso"` | `"memory"` | nothing; `export()` the image yourself | +| `"memory"` | `"indexeddb"` | the sealed image, saved after every change | +| `"memory"` | `"localstorage"` | a sealed blob under `localStorage["cryptex:"]` | +| `"memory"` | `"memory"` | nothing | + +`import(connection, image, options)` reopens an image returned by `export()`, +and `rekey(connection)` changes its password. + +`keyring.keys()` lists the ids inside an open keyring, and +`storedKeyrings({ store })` lists the keyrings the origin already has in +`"indexeddb"` (the default), `"localstorage"` or `"opfs"`, without opening +anything. Listing OPFS works from a page; opening an OPFS keyring does not. + +Every store keeps the data encrypted; the key comes from the password (or raw +key) in the connection string, so a store with the wrong connection string +fails with `AccessDenied` instead of returning garbage. + +A `set` or `delete` that resolves has reached the store, and every call on a +closed keyring throws. An IndexedDB or localStorage keyring also holds a Web +Lock named after itself, so a second tab that opens the same name fails with +`AccessDenied` instead of overwriting the first tab's secrets; `close()` +releases the lock, and with OPFS the sync access handle, so close a keyring +before opening it again in the same context. The Rust-level +`WebStorageKeyring` does not take that lock: it is synchronous by design, and +taking a lock is not. + +OPFS needs `createSyncAccessHandle()`, which browsers expose only in a +dedicated worker, so `store: "opfs"` is refused on the main thread. A worker +can use IndexedDB too. `examples/web/` has a page that uses IndexedDB and a +worker that uses OPFS; serve it over HTTP (`python3 -m http.server`), because +wasm modules and OPFS are not available on `file://` URLs. + +Errors are `Error` objects whose message starts with the kind, so a caller can +switch on `ItemNotFound:`, `AccessDenied:`, `TypeError:` or `GeneralError:` +without parsing the rest. + +Two costs are worth planning for. Any script the origin loads can read +IndexedDB, OPFS and `localStorage`, so the encryption protects against other +origins and other users, not against a compromised page. +`requestPersistentStorage()` asks the browser to keep the data, but it may +refuse, and clearing site data always removes it. Key derivation runs Argon2, +which blocks the thread it runs on: with a large `memory=` value, open the +keyring in a worker or the page freezes until it finishes. + +What the encryption does not detect is a *stale* image. Code that can write +origin storage can put back an earlier one, or drop the `-wal` beside it, and +the keyring opens with the secrets it held then; a rotated secret can come +back that way. Keep a version or counter of your own outside the store if that +matters. + +The password reaches the library through the connection string, which is a +small DSL: `\` starts an escape, a leading `'` quotes a value, and whitespace +separates entries. A password containing those characters is not passed +through unchanged, so derive a key yourself or hex-encode the secret when the +password is user-supplied. A repeated keyword (`password=a password=b`) is an +error rather than a silent override. The examples use one fixed salt to stay +readable; an application should give each keyring a salt of its own. + +### Bringing your own storage + +`TursoKeyring` can adopt a connection you opened, or open through an IO you +supply, so one database can hold the keyring's `secrets` table and your own +tables under a single key: + +```rust +use cryptex::turso::TursoKeyring; + +// A connection opened by the caller, e.g. with a custom IO and encryption. +let keyring = TursoKeyring::from_connection(conn)?; + +// Or let cryptex build the database through your IO (such as OPFS). +let keyring = TursoKeyring::with_io(io, "keyring.db3", ¶ms)?; +# Ok::<(), cryptex::KeyRingError>(()) +``` + +In both cases cryptex creates and owns only its own tables, and `rekey` reports +an error because cryptex does not own that storage: copy the secrets into a +keyring that owns its file instead. `cryptex::turso` re-exports `Connection`, +`TursoBuilder` and `core` so callers construct matching types. + +Turso's synchronous API is driven on the current thread. Native builds park the +thread while a future is pending; wasm builds poll a bounded number of times +and return an error instead of spinning, so an IO backend must complete its +reads in place. + +On WASI there is no file locking: `try_lock` reports `Unsupported`, which the +keyring treats as success, and the default keyring directory is `./.cryptex` +because there is no home directory. Keep a single writer per database there. + +The CLI is native only: a wasm binary prints that and exits. + --- ## KMS/HSM Backends diff --git a/examples/web/index.html b/examples/web/index.html new file mode 100644 index 0000000..0cf20d3 --- /dev/null +++ b/examples/web/index.html @@ -0,0 +1,148 @@ + + + + + + cryptex in the browser + + + + +

cryptex in the browser

+

+ A keyring is a Turso database, either kept in IndexedDB (one image per + keyring) or in localStorage. Everything you store is encrypted with a key + derived from the password; any script on this origin can read the + ciphertext, so pick a password you would not reuse carelessly. +

+ +
+ Keyring + + + + + + + + +
+ +
+ Secret + + + + + + + + +
+ +
+ Keyrings in this browser +
    +
  • Loading…
  • +
+
+ +
+ Keys in the open keyring +
    +
  • Open a keyring to see its keys.
  • +
+
+ +

Not opened.

+ + + + diff --git a/examples/web/main.js b/examples/web/main.js new file mode 100644 index 0000000..842c25b --- /dev/null +++ b/examples/web/main.js @@ -0,0 +1,216 @@ +// A browser page that keeps cryptex keyrings in IndexedDB or localStorage. +// +// Build first: +// wasm-pack build --target web --out-dir examples/web/pkg --no-default-features --features js +// Then serve this directory over http (not file://): +// python3 -m http.server -d examples/web 8080 +// +// OPFS keyrings are listed too, but opening one needs a worker: see worker.js. + +import init, { + Keyring, + requestPersistentStorage, + storedKeyrings, +} from "./pkg/cryptex.js"; + +const $ = (id) => document.getElementById(id); +const decoder = new TextDecoder(); + +/** The stores this page can open. OPFS needs the worker in worker.js. */ +const STORES = ["indexeddb", "localstorage"]; +/** Every store the page lists, including the one it cannot open here. */ +const LISTED_STORES = [...STORES, "opfs"]; + +let keyring = null; +/** Where the open keyring lives, so the list can mark it. */ +let current = null; + +function show(message) { + $("status").textContent = message; +} + +function hint(message) { + const item = document.createElement("li"); + item.className = "hint"; + item.textContent = message; + return item; +} + +function render(list, rows) { + list.replaceChildren(...(rows.length ? rows : [hint("None stored.")])); +} + +/** One entry per keyring, tagged with the store it lives in. */ +function keyringRow(store, name) { + const item = document.createElement("li"); + + const tag = document.createElement("span"); + tag.className = "store"; + tag.textContent = store; + item.append(tag); + + const button = document.createElement("button"); + button.className = "link"; + button.textContent = name; + if (store === "opfs") { + // A sync access handle is worker-only, so the page cannot open this. + button.disabled = true; + const note = document.createElement("span"); + note.className = "hint"; + note.textContent = " opens in a worker"; + item.append(button, note); + return item; + } + button.addEventListener("click", () => + guarded(async () => { + $("name").value = name; + $("store").value = store; + await open(); + await refresh(); + const count = keyring.keys().length; + show(`Opened "${name}" from ${store}; it holds ${count} key${count === 1 ? "" : "s"}.`); + }), + ); + item.append(button); + + if (current && current.store === store && current.name === name) { + const open = document.createElement("span"); + open.className = "open"; + open.textContent = "(open)"; + item.append(open); + } + return item; +} + +/** One entry per key in the open keyring, with its value. */ +function keyRow(id) { + const item = document.createElement("li"); + const name = document.createElement("code"); + name.textContent = id; + const value = document.createElement("span"); + try { + value.textContent = ` = ${decoder.decode(keyring.get(id))}`; + } catch (error) { + value.textContent = ` (${error.message})`; + } + item.append(name, value); + return item; +} + +async function refreshKeyrings() { + const rows = []; + for (const store of LISTED_STORES) { + let names = []; + try { + names = await storedKeyrings({ store }); + } catch (error) { + rows.push(hint(`${store}: ${error.message}`)); + continue; + } + if (!names.length) rows.push(hint(`${store}: none`)); + for (const name of names) rows.push(keyringRow(store, name)); + } + render($("keyrings"), rows); +} + +async function refreshKeys() { + if (!keyring) { + render($("keys"), [hint("Open a keyring to see its keys.")]); + return; + } + render($("keys"), keyring.keys().map(keyRow)); +} + +async function refresh() { + await refreshKeyrings(); + await refreshKeys(); +} + +/** Connection strings are `password=... salt=...`. */ +function connection() { + const password = $("password").value; + if (!password) throw new Error("Enter a password first"); + // The connection string is whitespace-separated, so a value cannot contain + // one; say so rather than passing the parser's byte offset to the user. + if (/\s/.test(password)) { + throw new Error("The password cannot contain spaces; the connection string is `password= salt=`"); + } + return `password=${password} salt=cryptex-browser-example`; +} + +async function open() { + const name = $("name").value; + const store = $("store").value; + if (keyring) await keyring.close(); + keyring = await Keyring.open(connection(), name, { backend: "turso", store }); + current = { store, name }; + show(`Opened "${name}" from ${store}.`); +} + +async function guarded(action) { + try { + await action(); + } catch (error) { + show(`${error.message ?? error}`); + } +} + +$("open").addEventListener("click", () => + guarded(async () => { + await open(); + await refresh(); + const count = keyring.keys().length; + show(`Opened "${$("name").value}"; it holds ${count} key${count === 1 ? "" : "s"}.`); + }), +); + +$("persist").addEventListener("click", () => + guarded(async () => { + const granted = await requestPersistentStorage(); + show( + granted + ? "The browser will not evict this origin's storage under pressure." + : "The browser did not grant persistent storage; it may still evict the keyring.", + ); + }), +); + +$("set").addEventListener("click", () => + guarded(async () => { + if (!keyring) throw new Error("Open the keyring first"); + await keyring.set($("id").value, new TextEncoder().encode($("value").value)); + await refreshKeys(); + show(`Stored "${$("id").value}". It is in ${current.store}, encrypted, before this line ran.`); + }), +); + +$("get").addEventListener("click", () => + guarded(async () => { + if (!keyring) throw new Error("Open the keyring first"); + const bytes = keyring.get($("id").value); + show(`${$("id").value} is ${decoder.decode(bytes)}`); + }), +); + +$("delete").addEventListener("click", () => + guarded(async () => { + if (!keyring) throw new Error("Open the keyring first"); + await keyring.delete($("id").value); + await refreshKeys(); + show(`Deleted "${$("id").value}".`); + }), +); + +$("export").addEventListener("click", () => + guarded(async () => { + if (!keyring) throw new Error("Open the keyring first"); + const image = keyring.export(); + const text = Array.from(image, (b) => b.toString(16).padStart(2, "0")).join(""); + await navigator.clipboard.writeText(text); + show(`Copied ${image.length} encrypted bytes to the clipboard.`); + }), +); + +// Show what the origin already holds before anything is opened. +await init(); +await guarded(refresh); diff --git a/examples/web/worker.js b/examples/web/worker.js new file mode 100644 index 0000000..90d83ab --- /dev/null +++ b/examples/web/worker.js @@ -0,0 +1,69 @@ +// A dedicated worker that keeps a cryptex keyring in the origin private file +// system (OPFS). +// +// OPFS sync access handles only exist in a worker, and deriving the key with +// Argon2 blocks whichever thread it runs on, so this is where the keyring +// belongs. +// +// Build first: +// wasm-pack build --target web --out-dir examples/web/pkg -- --no-default-features --features js +// Then, from the page: +// const worker = new Worker("./worker.js", { type: "module" }); +// worker.postMessage({ id: 1, op: "open", password: "...", name: "example" }); + +import init, { Keyring } from "./pkg/cryptex.js"; + +let ready = null; +let keyring = null; + +async function open({ password, name }) { + // The connection string is whitespace-separated, so a password that holds a + // space, or a ` salt=` of its own, would change how it is parsed. + if (!password || /\s/.test(password)) { + throw new Error("the password must be non-empty and cannot contain spaces"); + } + ready ??= init(); + await ready; + if (keyring) await keyring.close(); + keyring = await Keyring.open( + `password=${password} salt=cryptex-browser-example`, + name, + { backend: "turso", store: "opfs" }, + ); +} + +self.addEventListener("message", async (event) => { + const { id, op, ...args } = event.data; + try { + switch (op) { + case "open": + await open(args); + postMessage({ id, ok: true }); + break; + case "set": + await keyring.set(args.key, new TextEncoder().encode(args.value)); + postMessage({ id, ok: true }); + break; + case "get": + postMessage({ + id, + ok: true, + value: new TextDecoder().decode(keyring.get(args.key)), + }); + break; + case "delete": + await keyring.delete(args.key); + postMessage({ id, ok: true }); + break; + case "close": + await keyring.close(); + keyring = null; + postMessage({ id, ok: true }); + break; + default: + throw new Error(`unknown operation ${op}`); + } + } catch (error) { + postMessage({ id, ok: false, error: String(error) }); + } +}); diff --git a/src/error.rs b/src/error.rs index 00735fa..dddd4bc 100644 --- a/src/error.rs +++ b/src/error.rs @@ -123,6 +123,26 @@ impl From for KeyRingError { } } +/// Browser APIs report failures as thrown JavaScript values. +#[cfg(any(feature = "indexeddb", feature = "turso-opfs", feature = "web-storage"))] +#[cfg_attr( + docsrs, + doc(cfg(any(feature = "indexeddb", feature = "turso-opfs", feature = "web-storage"))) +)] +impl From for KeyRingError { + fn from(value: wasm_bindgen::JsValue) -> Self { + let detail = value + .as_string() + .or_else(|| { + js_sys::Reflect::get(&value, &wasm_bindgen::JsValue::from_str("message")) + .ok() + .and_then(|message| message.as_string()) + }) + .unwrap_or_else(|| format!("{value:?}")); + KeyRingError::GeneralError { msg: detail } + } +} + #[cfg(any(feature = "turso", feature = "turso-encrypted-io"))] #[cfg_attr( docsrs, diff --git a/src/keyring.rs b/src/keyring.rs index a238a09..7ba529e 100644 --- a/src/keyring.rs +++ b/src/keyring.rs @@ -3,6 +3,13 @@ SPDX-License-Identifier: Apache-2.0 */ +#[cfg(any( + feature = "encrypted-vfs", + feature = "memory", + feature = "turso-encrypted-io" +))] +mod cipher; + mod keyringsecret; #[cfg(feature = "encrypted-vfs")] @@ -10,18 +17,32 @@ pub mod encrypted_vfs; #[cfg(any( feature = "file", feature = "encrypted-vfs", + feature = "memory", feature = "turso", feature = "turso-encrypted-io" ))] pub mod file_common; +#[cfg(feature = "indexeddb")] +pub mod indexeddb; #[cfg(any(feature = "yubihsm-usb", feature = "yubihsm-http"))] pub mod kms; #[cfg(all(target_os = "linux", feature = "linux-secret-service"))] pub mod linux; #[cfg(all(target_os = "macos", feature = "macos-keychain"))] pub mod macos; +#[cfg(feature = "memory")] +pub mod memory; +#[cfg(feature = "turso-opfs")] +pub mod opfs; #[cfg(any(feature = "encrypted-vfs", feature = "turso-encrypted-io"))] mod page_cipher; +#[cfg(any( + feature = "encrypted-vfs", + feature = "turso", + feature = "turso-encrypted-io", + feature = "turso-opfs" +))] +mod page_store; #[cfg(feature = "file")] pub mod sqlcipher; #[cfg(any(feature = "file", feature = "encrypted-vfs"))] @@ -32,6 +53,12 @@ pub mod turso; mod turso_common; #[cfg(feature = "turso-encrypted-io")] pub mod turso_encrypted_io; +#[cfg(feature = "turso")] +mod turso_web; +#[cfg(feature = "web-storage")] +pub mod web_storage; +#[cfg(any(feature = "turso-opfs", feature = "turso"))] +mod web_time; #[cfg(all(target_os = "windows", feature = "windows-credentials"))] pub mod windows; #[cfg(any(feature = "yubihsm-usb", feature = "yubihsm-http"))] @@ -99,6 +126,7 @@ pub fn get_os_keyring(service: &str) -> Result> { all(target_os = "linux", feature = "linux-secret-service"), feature = "file", feature = "encrypted-vfs", + feature = "memory", feature = "turso", feature = "turso-encrypted-io", feature = "yubihsm-usb", @@ -106,6 +134,40 @@ pub fn get_os_keyring(service: &str) -> Result> { )))] compile_error!("no keyring implementation is selected or available for this platform"); +// Backends that need native OS APIs, C libraries or USB devices. They are +// rejected on wasm targets so the build fails with a clear message instead of +// a wall of linker errors. +#[cfg(all( + target_family = "wasm", + any( + feature = "file", + feature = "encrypted-vfs", + feature = "yubihsm-usb", + feature = "yubihsm-http", + feature = "linux-secret-service", + feature = "macos-keychain", + feature = "windows-credentials", + ) +))] +compile_error!( + "the file, encrypted-vfs, yubihsm and OS keyring backends are not available on wasm; \ + use the memory, web-storage, indexeddb, turso-opfs or turso features instead" +); + +// Browser-only features asked for by a non-browser target. +#[cfg(all( + not(all(target_arch = "wasm32", target_os = "unknown")), + any( + feature = "web-storage", + feature = "indexeddb", + feature = "turso-opfs", + feature = "js" + ) +))] +compile_error!( + "the web-storage, indexeddb, turso-opfs and js features require wasm32-unknown-unknown" +); + #[cfg(any( all(target_os = "linux", feature = "linux-secret-service"), all(target_os = "macos", feature = "macos-keychain"), @@ -144,6 +206,7 @@ pub const fn allows_file() -> bool { any( feature = "file", feature = "encrypted-vfs", + feature = "memory", feature = "turso", feature = "turso-encrypted-io" ) @@ -158,6 +221,7 @@ pub const fn default_memory_cost() -> u32 { any( feature = "file", feature = "encrypted-vfs", + feature = "memory", feature = "turso", feature = "turso-encrypted-io" ) @@ -172,6 +236,7 @@ pub const fn default_memory_cost() -> u32 { any( feature = "file", feature = "encrypted-vfs", + feature = "memory", feature = "turso", feature = "turso-encrypted-io" ) @@ -186,6 +251,7 @@ pub const fn default_threads() -> u32 { any( feature = "file", feature = "encrypted-vfs", + feature = "memory", feature = "turso", feature = "turso-encrypted-io" ) @@ -200,6 +266,7 @@ pub const fn default_threads() -> u32 { any( feature = "file", feature = "encrypted-vfs", + feature = "memory", feature = "turso", feature = "turso-encrypted-io" ) @@ -214,6 +281,7 @@ pub const fn default_parallel() -> u32 { any( feature = "file", feature = "encrypted-vfs", + feature = "memory", feature = "turso", feature = "turso-encrypted-io" ) @@ -275,6 +343,7 @@ pub trait ListKeyRing { any( feature = "file", feature = "encrypted-vfs", + feature = "memory", feature = "turso", feature = "turso-encrypted-io" ) diff --git a/src/keyring/cipher.rs b/src/keyring/cipher.rs new file mode 100644 index 0000000..b9e7e9a --- /dev/null +++ b/src/keyring/cipher.rs @@ -0,0 +1,45 @@ +/* + Copyright Michael Lodder. All Rights Reserved. + SPDX-License-Identifier: Apache-2.0 +*/ +//! The AEAD algorithm choice shared by every encrypted keyring. + +use super::file_common; +use crate::Result; +use crate::error::KeyRingError; +use zeroize::Zeroize; + +/// Selects the AEAD algorithm used for page encryption. +/// +/// `Aes256Gcm` uses AES-NI hardware acceleration on x86/x86_64/AArch64 when +/// available; on hardware without AES-NI it falls back to a constant-time +/// software implementation that is slower than ChaCha20-Poly1305. +#[derive(Clone, Copy, Default, Debug, PartialEq, Eq)] +pub enum CipherAlgorithm { + /// ChaCha20-Poly1305 (default) + #[default] + ChaCha20Poly1305, + /// AES-256-GCM + Aes256Gcm, +} + +impl Zeroize for CipherAlgorithm { + fn zeroize(&mut self) { + *self = CipherAlgorithm::default(); + } +} + +impl file_common::CipherParam for CipherAlgorithm { + fn parse(value: &str) -> Result { + match value { + "chacha20poly1305" | "chacha20" => Ok(CipherAlgorithm::ChaCha20Poly1305), + "aes256gcm" | "aes" => Ok(CipherAlgorithm::Aes256Gcm), + other => Err(KeyRingError::GeneralError { + msg: format!( + "unknown cipher '{}'; use chacha20poly1305 or aes256gcm", + other + ), + }), + } + } +} diff --git a/src/keyring/encrypted_vfs.rs b/src/keyring/encrypted_vfs.rs index a5d9651..17dbc57 100644 --- a/src/keyring/encrypted_vfs.rs +++ b/src/keyring/encrypted_vfs.rs @@ -20,7 +20,7 @@ use super::page_cipher::{ActiveCipher, LOGICAL_PAGE_SIZE, logical_size, truncate use super::sqlite_common::{KEYRING_FILE, init_schema, lock_connection}; use crate::error::KeyRingError; -pub use super::page_cipher::CipherAlgorithm; +pub use super::cipher::CipherAlgorithm; /// Connection parameters for [`EncryptedVfsKeyring`]. /// @@ -142,7 +142,8 @@ impl Vfs for EncryptedVfs { } fn truncate(&self, handle: &mut Self::Handle, logical_size: usize) -> VfsResult<()> { - truncate(&handle.file, logical_size).map_err(|_| sqlite_plugin::vars::SQLITE_IOERR_TRUNCATE) + truncate(&mut handle.file, logical_size) + .map_err(|_| sqlite_plugin::vars::SQLITE_IOERR_TRUNCATE) } fn read(&self, handle: &mut Self::Handle, offset: usize, data: &mut [u8]) -> VfsResult { diff --git a/src/keyring/file_common.rs b/src/keyring/file_common.rs index 233adaa..3e3cc7f 100644 --- a/src/keyring/file_common.rs +++ b/src/keyring/file_common.rs @@ -9,27 +9,78 @@ use super::*; use argon2::{Algorithm, Argon2, Params as Argon2Params, Version}; use crate::error::KeyRingError; +#[cfg(any( + feature = "file", + feature = "encrypted-vfs", + feature = "turso", + feature = "turso-encrypted-io" +))] +use std::fs; #[cfg(any( feature = "encrypted-vfs", feature = "turso", feature = "turso-encrypted-io" ))] use std::fs::{File, OpenOptions, TryLockError}; +use std::iter; +#[cfg(any( + feature = "file", + feature = "encrypted-vfs", + feature = "turso", + feature = "turso-encrypted-io" +))] use std::path::{Path, PathBuf}; use std::str::FromStr; -use std::{fs, iter}; use zeroize::{Zeroize, Zeroizing}; +#[cfg(any( + feature = "file", + feature = "encrypted-vfs", + feature = "turso", + feature = "turso-encrypted-io" +))] // SQL shared by every file-backed keyring. Numbered parameters and // `excluded.value` work with both SQLite and Turso. pub(crate) const VERIFY_KEY_SQL: &str = "SELECT COUNT(*) FROM sqlite_master"; +#[cfg(any( + feature = "file", + feature = "encrypted-vfs", + feature = "turso", + feature = "turso-encrypted-io" +))] pub(crate) const CREATE_SECRETS_SQL: &str = "CREATE TABLE IF NOT EXISTS secrets (id TEXT UNIQUE NOT NULL, value TEXT NOT NULL)"; +#[cfg(any( + feature = "file", + feature = "encrypted-vfs", + feature = "turso", + feature = "turso-encrypted-io" +))] pub(crate) const SELECT_SECRET_SQL: &str = "SELECT value FROM secrets WHERE id = ?1"; +#[cfg(any( + feature = "file", + feature = "encrypted-vfs", + feature = "turso", + feature = "turso-encrypted-io" +))] pub(crate) const UPSERT_SECRET_SQL: &str = "INSERT INTO secrets(id, value) VALUES(?1, ?2) \ ON CONFLICT(id) DO UPDATE SET value = excluded.value"; +#[cfg(any( + feature = "file", + feature = "encrypted-vfs", + feature = "turso", + feature = "turso-encrypted-io" +))] pub(crate) const DELETE_SECRET_SQL: &str = "DELETE FROM secrets WHERE id = ?1"; +#[cfg(any(feature = "turso", feature = "turso-encrypted-io"))] +pub(crate) const SELECT_IDS_SQL: &str = "SELECT id FROM secrets ORDER BY id"; +#[cfg(any( + feature = "file", + feature = "encrypted-vfs", + feature = "turso", + feature = "turso-encrypted-io" +))] /// Storage behind a file-backed keyring. Secrets are stored hex-encoded. pub(crate) trait SecretStore { /// Fetch the secret stored under `id`. @@ -40,6 +91,12 @@ pub(crate) trait SecretStore { fn delete(&self, id: &str) -> Result<()>; } +#[cfg(any( + feature = "file", + feature = "encrypted-vfs", + feature = "turso", + feature = "turso-encrypted-io", +))] /// Decode a stored hex value, or report [`KeyRingError::ItemNotFound`]. pub(crate) fn decode_secret(value: Option>) -> Result { let value = value.ok_or(KeyRingError::ItemNotFound)?; @@ -50,6 +107,12 @@ pub(crate) fn decode_secret(value: Option>) -> Result KeyRingError { KeyRingError::AccessDenied { @@ -60,6 +123,7 @@ pub(crate) fn invalid_key() -> KeyRingError { /// Implements [`DynKeyRing`] by delegating to the [`SecretStore`] in field /// `$store`, and [`NewKeyRing`] by parsing the calling module's /// `ConnectionParams` and calling `with_params(¶ms, None)`. +#[allow(unused_macros)] macro_rules! file_keyring { ($keyring:ty, $store:ident) => { impl $crate::DynKeyRing for $keyring { @@ -84,6 +148,14 @@ macro_rules! file_keyring { } }; } +// Only the backends that own a `SecretStore` use the macro. +#[cfg(any( + feature = "file", + feature = "encrypted-vfs", + feature = "turso-encrypted-io", + feature = "yubihsm-usb", + feature = "yubihsm-http" +))] pub(crate) use file_keyring; /// A cipher choice that can be set with `cipher=` in a connection string. @@ -110,7 +182,7 @@ impl CipherParam for NoCipher { /// similar to postgres. /// /// ``` -/// use cryptex::sqlcipher::ConnectionParams; +/// use cryptex::file_common::ConnectionParams; /// /// let params = "password=1qaz2wsx3edc4rfv salt=0okm9ijn8uhb7ygv".parse::().unwrap(); /// ``` @@ -118,7 +190,7 @@ impl CipherParam for NoCipher { /// or with extra parameters. `memory` is Argon2's memory cost in KiB blocks. /// /// ``` -/// use cryptex::sqlcipher::ConnectionParams; +/// use cryptex::file_common::ConnectionParams; /// /// let params = "password=1qaz2wsx3edc4rfv salt=0okm9ijn8uhb7ygv memory=32768 threads=3 parallel=2".parse::().unwrap(); /// ``` @@ -302,6 +374,7 @@ pub(crate) fn derive_key( /// Derive a key with [`derive_key`] and require it to be exactly 32 bytes. #[cfg(any( feature = "encrypted-vfs", + feature = "memory", feature = "turso", feature = "turso-encrypted-io" ))] @@ -319,11 +392,22 @@ pub(crate) fn derive_key_32( Ok(out) } +#[cfg(any( + feature = "file", + feature = "encrypted-vfs", + feature = "turso", + feature = "turso-encrypted-io", +))] /// Resolve the keyring file `file_name` inside `in_path` (default /// `~/.cryptex`), creating and securing the directory. pub(crate) fn get_keyring_file(in_path: Option, file_name: &str) -> Result { let mut path = match in_path { None => { + // WASI has no home directory, and `CARGO_MANIFEST_DIR` is the + // build machine's path, so keep the keyring next to the program. + #[cfg(target_os = "wasi")] + let mut path = std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")); + #[cfg(not(target_os = "wasi"))] let mut path = dirs::home_dir().unwrap_or_else(|| { dirs::document_dir().unwrap_or_else(|| { dirs::data_local_dir() @@ -415,6 +499,12 @@ pub(crate) fn acquire_single_opener_lock(db_path: &Path) -> Result { Err(TryLockError::WouldBlock) => Err(KeyRingError::AccessDenied { msg: "keyring is already open by another process".to_string(), }), + // WASI does not implement locking at all, so a keyring there relies on + // the caller keeping a single writer. Everywhere else a filesystem + // that refuses to lock is an error: FUSE, NFS and SMB mounts report + // `Unsupported`, and opening unlocked would let two writers race. + #[cfg(target_os = "wasi")] + Err(TryLockError::Error(e)) if e.kind() == std::io::ErrorKind::Unsupported => Ok(file), Err(TryLockError::Error(e)) => Err(KeyRingError::GeneralError { msg: format!("unable to lock keyring: {}", e), }), @@ -433,7 +523,15 @@ pub(crate) fn sibling_path(path: &Path, suffix: &str) -> PathBuf { PathBuf::from(s) } -#[cfg(unix)] +#[cfg(all( + unix, + any( + feature = "file", + feature = "encrypted-vfs", + feature = "turso", + feature = "turso-encrypted-io" + ) +))] fn secure_dir(path: &Path) -> Result<()> { use std::os::unix::fs::PermissionsExt; @@ -444,7 +542,15 @@ fn secure_dir(path: &Path) -> Result<()> { }) } -#[cfg(not(unix))] +#[cfg(all( + not(unix), + any( + feature = "file", + feature = "encrypted-vfs", + feature = "turso", + feature = "turso-encrypted-io" + ) +))] fn secure_dir(_path: &Path) -> Result<()> { Ok(()) } @@ -467,7 +573,15 @@ pub(crate) fn secure_file(_path: &Path) -> Result<()> { Ok(()) } -#[cfg(target_os = "windows")] +#[cfg(all( + target_os = "windows", + any( + feature = "file", + feature = "encrypted-vfs", + feature = "turso", + feature = "turso-encrypted-io" + ) +))] fn make_hidden(path: &Path) { use std::ffi::OsStr; use std::os::windows::ffi::OsStrExt; @@ -491,7 +605,15 @@ fn make_hidden(path: &Path) { } } -#[cfg(not(target_os = "windows"))] +#[cfg(all( + not(target_os = "windows"), + any( + feature = "file", + feature = "encrypted-vfs", + feature = "turso", + feature = "turso-encrypted-io" + ) +))] fn make_hidden(_path: &Path) {} struct Parser<'a> { @@ -507,8 +629,18 @@ impl<'a> Parser<'a> { }; let mut connection_string = ConnectionParams::default(); + // A repeated keyword used to overwrite the first one, so a password + // that contained ` salt=...` could silently swap the salt or turn the + // password into a raw key. + let mut seen: Vec<&'a str> = Vec::new(); while let Some((key, value)) = parser.parameter()? { + if seen.contains(&key) { + return Err(KeyRingError::GeneralError { + msg: format!("duplicate parameter: {}", key), + }); + } + seen.push(key); connection_string.param(key, &value)?; } Ok(connection_string) @@ -644,7 +776,15 @@ impl<'a> Parser<'a> { } /// Helpers shared by the file-backed keyring tests. -#[cfg(test)] +#[cfg(all( + test, + any( + feature = "file", + feature = "encrypted-vfs", + feature = "turso", + feature = "turso-encrypted-io" + ) +))] pub(crate) mod test_support { use std::ops::Deref; use std::path::{Path, PathBuf}; @@ -655,6 +795,11 @@ pub(crate) mod test_support { impl TestDir { pub(crate) fn new(name: &str) -> Self { + // Under WASI only the preopened directory is reachable, so use a + // path relative to it. + #[cfg(target_os = "wasi")] + let path = PathBuf::from(name); + #[cfg(not(target_os = "wasi"))] let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join(name); let _ = std::fs::remove_dir_all(&path); Self(path) diff --git a/src/keyring/indexeddb.rs b/src/keyring/indexeddb.rs new file mode 100644 index 0000000..bcf3563 --- /dev/null +++ b/src/keyring/indexeddb.rs @@ -0,0 +1,377 @@ +/* + Copyright Michael Lodder. All Rights Reserved. + SPDX-License-Identifier: Apache-2.0 +*/ +//! Durable keyring images in IndexedDB, for browsers. +//! +//! A browser tab has no filesystem, so a keyring is persisted as one image: +//! the bytes [`TursoKeyring::export`](crate::turso::TursoKeyring::export) +//! produces. This module stores that image and takes an exclusive Web Lock +//! named after the keyring, so two tabs cannot open the same keyring at the +//! same time and overwrite each other. +//! +//! ```no_run +//! # use cryptex::indexeddb::SnapshotStore; +//! # async fn example() -> Result<(), Box> { +//! let store = SnapshotStore::open("settings").await?; +//! if let Some(image) = store.load().await? { +//! // pass the image to TursoKeyring::from_bytes +//! # let _ = image; +//! } +//! # Ok(()) +//! # } +//! ``` +//! +//! IndexedDB is per origin and readable by every script that runs on it, so +//! the image must stay encrypted: the key never leaves the password or raw +//! key the caller passes to the keyring. + +use js_sys::Reflect; +use wasm_bindgen::prelude::*; +use wasm_bindgen::{JsCast, JsValue}; +use wasm_bindgen_futures::JsFuture; +use web_sys::{IdbDatabase, IdbFactory, IdbRequest, IdbTransaction, IdbTransactionMode}; + +use crate::Result; +use crate::error::KeyRingError; + +/// Database holding every keyring image for this origin. +const DB_NAME: &str = "cryptex"; +/// Object store within [`DB_NAME`]. +const STORE_NAME: &str = "keyrings"; + +/// An IndexedDB-backed snapshot of one keyring. +/// +/// Opening takes the Web Lock `cryptex:`; it is held until the store is +/// dropped. If another tab holds it, [`open`](Self::open) fails with +/// `AccessDenied` instead of waiting. +pub struct SnapshotStore { + name: String, + db: IdbDatabase, + hold: LockHold, +} + +impl SnapshotStore { + /// Open the store for `name`, taking the single-opener lock. + pub async fn open(name: &str) -> Result { + let hold = LockHold::acquire(&format!("cryptex:{name}")).await?; + let db = open_db().await?; + Ok(Self { + name: name.to_string(), + db, + hold, + }) + } + + /// The name this store was opened under. + pub fn name(&self) -> &str { + &self.name + } + + /// Release the lock and wait until the browser has done so. + /// + /// Releasing is asynchronous: without this wait, opening the same name + /// again in the same page can still see the old lock and be refused. + pub async fn release(&mut self) { + self.hold.release_async().await; + } + + /// Read the stored image, if there is one. + pub async fn load(&self) -> Result>> { + let tx = self.transaction(IdbTransactionMode::Readonly)?; + let value = await_request( + &tx.object_store(STORE_NAME)? + .get(&JsValue::from_str(&self.name))?, + ) + .await?; + drop(tx); + if value.is_undefined() || value.is_null() { + Ok(None) + } else if value.is_instance_of::() { + Ok(Some(js_sys::Uint8Array::new(&value).to_vec())) + } else { + // `Uint8Array::new` would allocate whatever length the stored + // value claims; refuse anything that is not already an image. + Err(KeyRingError::AccessDenied { + msg: "the stored keyring is not an image".to_string(), + }) + } + } + + /// Write an image, replacing any previous one. Returns once the + /// transaction has committed. + pub async fn save(&self, image: &[u8]) -> Result<()> { + let tx = self.transaction(IdbTransactionMode::Readwrite)?; + let bytes = js_sys::Uint8Array::from(image); + tx.object_store(STORE_NAME)? + .put_with_key(&bytes, &JsValue::from_str(&self.name))?; + await_transaction(&tx).await + } + + /// Remove the stored image. + pub async fn delete(&self) -> Result<()> { + let tx = self.transaction(IdbTransactionMode::Readwrite)?; + tx.object_store(STORE_NAME)? + .delete(&JsValue::from_str(&self.name))?; + await_transaction(&tx).await + } + + /// Every keyring stored in this origin's IndexedDB, in name order. + /// + /// Reads without taking a lock, so it is safe to call while another tab + /// holds a keyring open. + pub async fn list_names() -> Result> { + let db = open_db().await?; + let tx = db + .transaction_with_str_and_mode(STORE_NAME, IdbTransactionMode::Readonly) + .map_err(js_error)?; + let store = tx.object_store(STORE_NAME)?; + let keys = await_request(&store.get_all_keys()?).await?; + drop(tx); + let mut names: Vec = js_sys::Array::from(&keys) + .iter() + .filter_map(|key| key.as_string()) + .collect(); + names.sort(); + Ok(names) + } + + fn transaction(&self, mode: IdbTransactionMode) -> Result { + self.db + .transaction_with_str_and_mode(STORE_NAME, mode) + .map_err(js_error) + } +} + +/// The exclusive lock held by a [`SnapshotStore`], released on drop. +/// +/// The lock lives as long as the promise the callback returns, so dropping +/// this resolves that promise and lets the next tab in. +pub(crate) struct LockHold { + /// Resolves the promise the lock callback returned. + release: std::rc::Rc>>, + /// The promise itself: the lock is held until it settles. + _held: js_sys::Promise, + /// Resolves once the lock has been released. + released: js_sys::Promise, + /// The callback, kept alive because the browser may still call it. + _callback: JsValue, +} + +impl LockHold { + pub(crate) async fn acquire(name: &str) -> Result { + let locks = Reflect::get(&navigator()?, &JsValue::from_str("locks")).map_err(js_error)?; + if locks.is_undefined() || locks.is_null() { + return Err(unsupported( + "this browser has no Web Locks API, so a keyring cannot be opened safely", + )); + } + let request: js_sys::Function = Reflect::get(&locks, &JsValue::from_str("request")) + .map_err(js_error)? + .dyn_into() + .map_err(|_| unsupported("the Web Locks API is not callable"))?; + + let options = js_sys::Object::new(); + Reflect::set(&options, &JsValue::from_str("ifAvailable"), &JsValue::TRUE) + .map_err(js_error)?; + + // `release` settles the promise the callback returns, ending the lock. + let release: std::rc::Rc>> = + std::rc::Rc::new(std::cell::RefCell::new(None)); + let held = js_sys::Promise::new(&mut { + let release = std::rc::Rc::clone(&release); + move |resolve, _reject| *release.borrow_mut() = Some(resolve) + }); + + // Resolved once the callback runs, whether or not it got the lock. + let signalled: std::rc::Rc>> = + std::rc::Rc::new(std::cell::RefCell::new(None)); + let signal = js_sys::Promise::new(&mut { + let signalled = std::rc::Rc::clone(&signalled); + move |resolve, _reject| *signalled.borrow_mut() = Some(resolve) + }); + + let denied = std::rc::Rc::new(std::cell::Cell::new(false)); + let callback = { + let denied = std::rc::Rc::clone(&denied); + let held = held.clone(); + let signalled = std::rc::Rc::clone(&signalled); + Closure:: JsValue>::once_into_js(move |lock: JsValue| { + if let Some(resolve) = signalled.borrow_mut().take() { + let _ = resolve.call0(&JsValue::NULL); + } + if lock.is_null() || lock.is_undefined() { + denied.set(true); + JsValue::UNDEFINED + } else { + JsValue::from(held.clone()) + } + }) + }; + + let request_promise: js_sys::Promise = request + .call3( + &locks, + &JsValue::from_str(name), + &options, + callback.unchecked_ref(), + ) + .map_err(js_error)? + .dyn_into() + .map_err(js_error)?; + + // Wait for whichever happens first: the callback runs, or the request + // itself fails. A granted lock keeps its request pending, so racing is + // what makes this usable at all. + let signals = js_sys::Array::of2(&signal, &request_promise); + JsFuture::from(js_sys::Promise::race(signals.as_ref())) + .await + .map_err(js_error)?; + + if denied.get() { + return Err(KeyRingError::AccessDenied { + msg: format!("the keyring '{name}' is open in another tab"), + }); + } + Ok(Self { + release, + _held: held, + released: request_promise, + _callback: callback, + }) + } +} + +impl LockHold { + /// Release the lock and wait for the browser to finish doing so. + pub(crate) async fn release_async(&mut self) { + if let Some(release) = self.release.borrow_mut().take() { + let _ = release.call0(&JsValue::NULL); + } + // The request settles only after the lock is gone, so awaiting it is + // what makes an immediate reopen of the same name work. + let _ = JsFuture::from(self.released.clone()).await; + } +} + +impl Drop for LockHold { + fn drop(&mut self) { + if let Some(release) = self.release.borrow_mut().take() { + let _ = release.call0(&JsValue::NULL); + } + } +} + +async fn open_db() -> Result { + // `indexedDB` hangs off the global object, not off `navigator`. + let factory: IdbFactory = Reflect::get(&js_sys::global(), &JsValue::from_str("indexedDB")) + .map_err(js_error)? + .dyn_into() + .map_err(|_| unsupported("this browser has no IndexedDB"))?; + let request = factory.open_with_u32(DB_NAME, 1).map_err(js_error)?; + + // Create the object store the first time the database is opened. + let upgrade_request = request.clone(); + let upgrade = Closure::::once_into_js(move |_event: JsValue| { + if let Some(db) = upgrade_request + .result() + .ok() + .and_then(|db| db.dyn_into::().ok()) + { + let _ = db.create_object_store(STORE_NAME); + } + }); + request.set_onupgradeneeded(Some(upgrade.unchecked_ref())); + + let db = await_request(&request).await?; + db.dyn_into::().map_err(js_error) +} + +/// The global object: `window` in a page, the worker scope in a worker. +fn navigator() -> Result { + let global = js_sys::global(); + // Workers expose `navigator` too, so this works in both contexts. + Reflect::get(&global, &JsValue::from_str("navigator")) + .map_err(js_error) + .and_then(|navigator| { + if navigator.is_undefined() { + Err(unsupported("no navigator: not a browser context")) + } else { + Ok(navigator) + } + }) +} + +/// Resolve a request's promise with `request.result`, rejecting on error. +async fn await_request(request: &IdbRequest) -> Result { + let promise = js_sys::Promise::new(&mut |resolve, reject| { + let on_success = { + let request = request.clone(); + let resolve = resolve.clone(); + Closure::::once_into_js(move |_event: JsValue| { + let value = request.result().unwrap_or(JsValue::NULL); + let _ = resolve.call1(&JsValue::NULL, &value); + }) + }; + let on_error = { + let request = request.clone(); + let reject = reject.clone(); + Closure::::once_into_js(move |_event: JsValue| { + let err = request + .error() + .ok() + .flatten() + .map(JsValue::from) + .unwrap_or(JsValue::NULL); + let _ = reject.call1(&JsValue::NULL, &err); + }) + }; + request.set_onsuccess(Some(on_success.unchecked_ref())); + request.set_onerror(Some(on_error.unchecked_ref())); + }); + JsFuture::from(promise).await.map_err(js_error) +} + +/// Wait for a transaction to commit. +async fn await_transaction(tx: &IdbTransaction) -> Result<()> { + let promise = js_sys::Promise::new(&mut |resolve, reject| { + let on_complete = { + let resolve = resolve.clone(); + Closure::::once_into_js(move |_event: JsValue| { + let _ = resolve.call0(&JsValue::NULL); + }) + }; + let on_error = { + let tx = tx.clone(); + let reject = reject.clone(); + Closure::::once_into_js(move |_event: JsValue| { + let err = tx.error().map(JsValue::from).unwrap_or(JsValue::NULL); + let _ = reject.call1(&JsValue::NULL, &err); + }) + }; + // A quota or abort failure fires neither event reliably in every + // browser, and an unsettled promise would make `set` hang forever. + let on_abort = { + let tx = tx.clone(); + let reject = reject.clone(); + Closure::::once_into_js(move |_event: JsValue| { + let err = tx.error().map(JsValue::from).unwrap_or(JsValue::NULL); + let _ = reject.call1(&JsValue::NULL, &err); + }) + }; + tx.set_oncomplete(Some(on_complete.unchecked_ref())); + tx.set_onerror(Some(on_error.unchecked_ref())); + tx.set_onabort(Some(on_abort.unchecked_ref())); + }); + JsFuture::from(promise).await.map(|_| ()).map_err(js_error) +} + +fn js_error(value: JsValue) -> KeyRingError { + KeyRingError::from(value) +} + +fn unsupported(msg: &str) -> KeyRingError { + KeyRingError::GeneralError { + msg: msg.to_string(), + } +} diff --git a/src/keyring/memory.rs b/src/keyring/memory.rs new file mode 100644 index 0000000..e3cac97 --- /dev/null +++ b/src/keyring/memory.rs @@ -0,0 +1,672 @@ +/* + Copyright Michael Lodder. All Rights Reserved. + SPDX-License-Identifier: Apache-2.0 +*/ +//! An encrypted, in-memory keyring. +//! +//! [`MemoryKeyring`] keeps every secret in a [`BTreeMap`] and never touches the +//! disk, so it builds for every target, including browsers and WASI. Secrets +//! only leave memory through [`MemoryKeyring::export`], which returns a single +//! AEAD-sealed blob, and return through [`MemoryKeyring::import`]. +//! +//! ``` +//! use cryptex::KeyRing; +//! use cryptex::memory::MemoryKeyring; +//! +//! let params: cryptex::memory::ConnectionParams = +//! "password=1qaz2wsx3edc4rfv salt=0okm9ijn8uhb7ygv".parse().unwrap(); +//! let mut keyring = MemoryKeyring::with_params(¶ms).unwrap(); +//! keyring.set_secret("token", b"secret value").unwrap(); +//! +//! // Persist the sealed blob wherever you like, then reopen it later. +//! let blob = keyring.export().unwrap(); +//! // Reopening needs the same password (or raw key); the salt, cipher and +//! // Argon2 parameters come from the blob itself. +//! let mut reopened = +//! MemoryKeyring::import(&blob, b"1qaz2wsx3edc4rfv").unwrap(); +//! assert_eq!(reopened.get_secret("token").unwrap().as_slice(), b"secret value"); +//! ``` + +use super::cipher::CipherAlgorithm; +use super::file_common::{self, derive_key_32}; +use super::*; +use crate::error::KeyRingError; +use aes_gcm::aead::{Aead, KeyInit}; +use std::collections::BTreeMap; +use zeroize::Zeroizing; + +/// Connection parameters for [`MemoryKeyring`]. +/// +/// Accepted format: +/// ```text +/// password=mysecret salt=0okm9ijn8uhb7ygv [cipher=chacha20poly1305|aes256gcm] +/// ``` +/// or, to supply the 32-byte key directly, `key=`. +pub type ConnectionParams = file_common::ConnectionParams; + +// Sealed blob layout. The whole header is the AEAD associated data, so the +// Argon2 parameters, salt and cipher travel with the blob and cannot be +// altered without failing the tag check. +// +// magic(8) | version(1) | kind(1) | cipher(1) | memory(4) | threads(4) | +// parallel(4) | salt_len(4) | salt(salt_len) | nonce(12) | ciphertext + tag +const BLOB_MAGIC: &[u8; 8] = b"CRYPTEX\0"; +const BLOB_VERSION: u8 = 1; +const HEADER_LEN: usize = 8 + 1 + 1 + 1 + 4 + 4 + 4 + 4; +const NONCE_SIZE: usize = 12; + +/// Highest Argon2 costs an imported blob may ask for. +/// +/// The costs sit in an unauthenticated header, so they are checked before +/// Argon2 runs: a crafted sixteen-byte blob would otherwise ask for terabytes +/// and minutes of work before the AEAD notices it is not authentic. +const MAX_IMPORT_MEMORY_KIB: u32 = 1024 * 1024; +const MAX_IMPORT_THREADS: u32 = 64; +const MAX_IMPORT_PARALLEL: u32 = 64; + +/// How the blob's key was produced. +mod kind { + /// Argon2id over password + salt. + pub(super) const PASSWORD: u8 = 1; + /// A caller-supplied 32-byte key. + pub(super) const RAW_KEY: u8 = 2; +} + +fn seal_cipher(cipher: CipherAlgorithm) -> u8 { + match cipher { + CipherAlgorithm::ChaCha20Poly1305 => 1, + CipherAlgorithm::Aes256Gcm => 2, + } +} + +fn open_cipher(tag: u8) -> Result { + match tag { + 1 => Ok(CipherAlgorithm::ChaCha20Poly1305), + 2 => Ok(CipherAlgorithm::Aes256Gcm), + other => Err(KeyRingError::GeneralError { + msg: format!("unsupported cipher in keyring blob: {}", other), + }), + } +} + +/// The error for a blob that will not open: wrong password or tampering. +fn invalid_blob() -> KeyRingError { + KeyRingError::AccessDenied { + msg: "Invalid key or corrupted keyring blob".to_string(), + } +} + +/// Authenticated encryption over a whole buffer, for either supported cipher. +enum Sealer { + ChaCha(Box), + Aes(Box), +} + +impl Sealer { + fn new(cipher: CipherAlgorithm, key: &[u8; 32]) -> Self { + match cipher { + CipherAlgorithm::ChaCha20Poly1305 => Self::ChaCha(Box::new( + chacha20poly1305::ChaCha20Poly1305::new_from_slice(key).expect("32-byte key"), + )), + CipherAlgorithm::Aes256Gcm => Self::Aes(Box::new( + aes_gcm::Aes256Gcm::new_from_slice(key).expect("32-byte key"), + )), + } + } + + fn nonce(bytes: &[u8]) -> Option { + chacha20poly1305::Nonce::try_from(bytes).ok() + } + + fn seal(&self, nonce: &[u8; NONCE_SIZE], aad: &[u8], plaintext: &[u8]) -> Option> { + let nonce = Self::nonce(nonce)?; + let payload = chacha20poly1305::aead::Payload { + msg: plaintext, + aad, + }; + match self { + Self::ChaCha(c) => c.encrypt(&nonce, payload).ok(), + Self::Aes(c) => c.encrypt(&nonce, payload).ok(), + } + } + + fn open(&self, nonce: &[u8], aad: &[u8], ciphertext: &[u8]) -> Option> { + let nonce = Self::nonce(nonce)?; + let payload = chacha20poly1305::aead::Payload { + msg: ciphertext, + aad, + }; + match self { + Self::ChaCha(c) => c.decrypt(&nonce, payload).ok(), + Self::Aes(c) => c.decrypt(&nonce, payload).ok(), + } + } +} + +/// Length-prefixed encoding of the secret table: +/// `count(u32) | [id_len(u32) id value_len(u32) value]*`. +fn encode_secrets(secrets: &BTreeMap>>) -> Result>> { + let too_long = |what: &str| KeyRingError::GeneralError { + msg: format!("{} is too large to export", what), + }; + // Size the buffer up front: a growing buffer copies the plaintext into + // freed allocations, which zeroizing afterwards cannot reach. + let mut len: usize = 4; + for (id, value) in secrets { + len = len + .checked_add(4 + id.len() + 4 + value.len()) + .ok_or_else(|| too_long("the secret table"))?; + } + let mut out = Zeroizing::new(Vec::with_capacity(len)); + out.extend_from_slice( + &u32::try_from(secrets.len()) + .map_err(|_| too_long("the secret count"))? + .to_le_bytes(), + ); + for (id, value) in secrets { + let id_len = u32::try_from(id.len()).map_err(|_| too_long("a secret id"))?; + let value_len = u32::try_from(value.len()).map_err(|_| too_long("a secret value"))?; + out.extend_from_slice(&id_len.to_le_bytes()); + out.extend_from_slice(id.as_bytes()); + out.extend_from_slice(&value_len.to_le_bytes()); + out.extend_from_slice(value); + } + Ok(out) +} + +/// Read a `u32` at `pos`, advancing past it. +fn read_u32(data: &[u8], pos: &mut usize) -> Option { + let mut raw = [0u8; 4]; + raw.copy_from_slice(data.get(*pos..*pos + 4)?); + *pos += 4; + Some(u32::from_le_bytes(raw)) +} + +/// Decode the plaintext table produced by [`encode_secrets`], rejecting any +/// trailing bytes. +fn decode_secrets(data: &[u8]) -> Option>>> { + let mut pos = 0usize; + let count = read_u32(data, &mut pos)? as usize; + let mut secrets = BTreeMap::new(); + for _ in 0..count { + let id_len = read_u32(data, &mut pos)? as usize; + let id = std::str::from_utf8(data.get(pos..pos.checked_add(id_len)?)?) + .ok()? + .to_string(); + pos += id_len; + let value_len = read_u32(data, &mut pos)? as usize; + let value = Zeroizing::new(data.get(pos..pos.checked_add(value_len)?)?.to_vec()); + pos += value_len; + secrets.insert(id, value); + } + (pos == data.len()).then_some(secrets) +} + +/// Header fields of a sealed blob. +struct Header<'a> { + kind: u8, + cipher: CipherAlgorithm, + memory: u32, + threads: u32, + parallel: u32, + salt: &'a [u8], +} + +/// A keyring that keeps its secrets in memory. +/// +/// The key is derived once from the connection parameters and zeroized on +/// drop; [`export`](Self::export) seals everything under a fresh nonce. +pub struct MemoryKeyring { + secrets: BTreeMap>>, + key: Zeroizing<[u8; 32]>, + cipher: CipherAlgorithm, + kind: u8, + salt: Vec, + memory: u32, + threads: u32, + parallel: u32, +} + +impl MemoryKeyring { + /// Open an empty keyring from the connection parameters. + pub fn with_params(params: &ConnectionParams) -> Result { + let kind = if params.key.is_empty() { + kind::PASSWORD + } else { + kind::RAW_KEY + }; + Ok(Self { + secrets: BTreeMap::new(), + key: derive_key_32(params)?, + cipher: params.cipher, + kind, + salt: params.salt.clone(), + memory: params.memory, + threads: params.threads, + parallel: params.parallel, + }) + } + + /// Reopen a keyring from a blob returned by [`export`](Self::export). + /// + /// A blob made from a password derives its key from the salt and Argon2 + /// parameters stored in the blob, so it needs only the same password. A + /// blob made from a raw key needs the same key. + /// + /// A wrong password or a modified blob returns + /// [`KeyRingError::AccessDenied`]. + pub fn import(blob: &[u8], password_or_key: &[u8]) -> Result { + let header = Self::parse_header(blob)?; + if header.memory > MAX_IMPORT_MEMORY_KIB + || header.threads > MAX_IMPORT_THREADS + || header.parallel > MAX_IMPORT_PARALLEL + { + return Err(KeyRingError::GeneralError { + msg: "the keyring blob asks for unreasonable Argon2 costs".to_string(), + }); + } + let params = ConnectionParams { + key: if header.kind == kind::RAW_KEY { + password_or_key.to_vec() + } else { + Vec::new() + }, + password: if header.kind == kind::RAW_KEY { + Vec::new() + } else { + password_or_key.to_vec() + }, + salt: header.salt.to_vec(), + memory: header.memory, + threads: header.threads, + parallel: header.parallel, + cipher: header.cipher, + }; + let key = derive_key_32(¶ms).map_err(|_| invalid_blob())?; + let aad_end = HEADER_LEN + header.salt.len(); + let body = &blob[aad_end..]; + let sealer = Sealer::new(header.cipher, &key); + let plaintext = Zeroizing::new( + sealer + .open(&body[..NONCE_SIZE], &blob[..aad_end], &body[NONCE_SIZE..]) + .ok_or_else(invalid_blob)?, + ); + let secrets = decode_secrets(&plaintext).ok_or_else(invalid_blob)?; + Ok(Self { + secrets, + key, + cipher: header.cipher, + kind: header.kind, + salt: header.salt.to_vec(), + memory: header.memory, + threads: header.threads, + parallel: header.parallel, + }) + } + + fn parse_header(blob: &[u8]) -> Result> { + if blob.len() < HEADER_LEN + NONCE_SIZE { + return Err(invalid_blob()); + } + if blob.get(..8) != Some(BLOB_MAGIC.as_slice()) { + return Err(invalid_blob()); + } + if blob[8] != BLOB_VERSION { + return Err(KeyRingError::GeneralError { + msg: format!("unsupported keyring blob version: {}", blob[8]), + }); + } + let blob_kind = blob[9]; + if blob_kind != kind::PASSWORD && blob_kind != kind::RAW_KEY { + return Err(invalid_blob()); + } + let mut pos = 11; + let memory = read_u32(blob, &mut pos).ok_or_else(invalid_blob)?; + let threads = read_u32(blob, &mut pos).ok_or_else(invalid_blob)?; + let parallel = read_u32(blob, &mut pos).ok_or_else(invalid_blob)?; + let salt_len = read_u32(blob, &mut pos).ok_or_else(invalid_blob)? as usize; + // `usize` is 32 bits on wasm32, so this addition can wrap before a + // bounds check would notice. + let salt_end = HEADER_LEN.checked_add(salt_len).ok_or_else(invalid_blob)?; + let salt = blob.get(HEADER_LEN..salt_end).ok_or_else(invalid_blob)?; + // The body must hold a nonce and at least the AEAD tag. + let body_start = salt_end + .checked_add(NONCE_SIZE + 16) + .ok_or_else(invalid_blob)?; + if body_start > blob.len() { + return Err(invalid_blob()); + } + Ok(Header { + kind: blob_kind, + cipher: open_cipher(blob[10]).map_err(|_| invalid_blob())?, + memory, + threads, + parallel, + salt, + }) + } + + /// Seal every secret into a single AEAD blob. + /// + /// The blob carries the salt, Argon2 parameters, cipher and key kind, so + /// [`import`](Self::import) needs only the same password (or raw key). + pub fn export(&self) -> Result> { + let mut nonce = [0u8; NONCE_SIZE]; + getrandom::fill(&mut nonce).map_err(|e| KeyRingError::GeneralError { + msg: format!("unable to generate a nonce: {}", e), + })?; + + let plaintext = encode_secrets(&self.secrets)?; + let salt_len = u32::try_from(self.salt.len()).map_err(|_| KeyRingError::GeneralError { + msg: "salt is too long to export".to_string(), + })?; + let mut header = Vec::with_capacity(HEADER_LEN + self.salt.len()); + header.extend_from_slice(BLOB_MAGIC); + header.push(BLOB_VERSION); + header.push(self.kind); + header.push(seal_cipher(self.cipher)); + header.extend_from_slice(&self.memory.to_le_bytes()); + header.extend_from_slice(&self.threads.to_le_bytes()); + header.extend_from_slice(&self.parallel.to_le_bytes()); + header.extend_from_slice(&salt_len.to_le_bytes()); + header.extend_from_slice(&self.salt); + + let ciphertext = Sealer::new(self.cipher, &self.key) + .seal(&nonce, &header, &plaintext) + .ok_or_else(|| KeyRingError::GeneralError { + msg: "unable to encrypt the keyring".to_string(), + })?; + let mut blob = header; + blob.extend_from_slice(&nonce); + blob.extend_from_slice(&ciphertext); + Ok(blob) + } + + /// Every id in the keyring, in order. + pub fn keys(&self) -> Vec { + self.secrets.keys().cloned().collect() + } + + /// Re-encrypt under new connection parameters, optionally with a new cipher. + /// + /// The secrets stay in memory; only the key, salt and cipher change, so + /// the next [`export`](Self::export) uses the new parameters. + pub fn rekey(&mut self, new_params: &ConnectionParams) -> Result<()> { + let key = derive_key_32(new_params)?; + self.kind = if new_params.key.is_empty() { + kind::PASSWORD + } else { + kind::RAW_KEY + }; + self.salt = new_params.salt.clone(); + self.memory = new_params.memory; + self.threads = new_params.threads; + self.parallel = new_params.parallel; + self.cipher = new_params.cipher; + self.key = key; + Ok(()) + } + + /// The cipher this keyring seals blobs with. + pub fn cipher(&self) -> CipherAlgorithm { + self.cipher + } +} + +impl NewKeyRing for MemoryKeyring { + fn new>(lock_key: S) -> Result { + let params = lock_key.as_ref().parse::()?; + Self::with_params(¶ms) + } +} + +impl DynKeyRing for MemoryKeyring { + fn get_secret(&mut self, id: &str) -> Result { + match self.secrets.get(id) { + Some(value) => Ok(KeyRingSecret(value.to_vec())), + None => Err(KeyRingError::ItemNotFound), + } + } + + fn set_secret(&mut self, id: &str, secret: &[u8]) -> Result<()> { + self.secrets + .insert(id.to_string(), Zeroizing::new(secret.to_vec())); + Ok(()) + } + + fn delete_secret(&mut self, id: &str) -> Result<()> { + match self.secrets.remove(id) { + Some(mut value) => { + zeroize::Zeroize::zeroize(&mut *value); + Ok(()) + } + None => Err(KeyRingError::ItemNotFound), + } + } +} + +#[cfg(test)] +mod tests { + // Only `DynKeyRing` is imported, so `kr.get_secret(..)` is unambiguous. + use super::super::DynKeyRing; + use super::{CipherAlgorithm, ConnectionParams, HEADER_LEN, MemoryKeyring}; + use crate::error::KeyRingError; + use argon2::Params as Argon2Params; + + const PASSWORD: &[u8] = b"1qaz2wsx3edc4rfv"; + + fn params(s: &str) -> ConnectionParams { + s.parse().unwrap() + } + + fn password_params(extra: &str) -> ConnectionParams { + params(&format!( + "password=1qaz2wsx3edc4rfv salt=0okm9ijn8uhb7ygv {extra}" + )) + } + + #[test] + fn round_trip_and_persistence() { + let mut kr = MemoryKeyring::with_params(&password_params("")).unwrap(); + kr.set_secret("a", b"one").unwrap(); + kr.set_secret("b", b"two").unwrap(); + kr.delete_secret("b").unwrap(); + assert_eq!(kr.get_secret("a").unwrap().as_slice(), b"one"); + assert!(matches!( + kr.get_secret("b"), + Err(KeyRingError::ItemNotFound) + )); + + let blob = kr.export().unwrap(); + let mut reopened = MemoryKeyring::import(&blob, PASSWORD).unwrap(); + assert_eq!(reopened.get_secret("a").unwrap().as_slice(), b"one"); + reopened.set_secret("c", b"three").unwrap(); + assert_eq!(reopened.get_secret("c").unwrap().as_slice(), b"three"); + } + + #[test] + fn keys_lists_the_ids_in_order() { + let mut kr = MemoryKeyring::with_params(&password_params("")).unwrap(); + assert!(kr.keys().is_empty()); + kr.set_secret("b", b"two").unwrap(); + kr.set_secret("a", b"one").unwrap(); + assert_eq!(kr.keys(), ["a", "b"]); + kr.delete_secret("a").unwrap(); + assert_eq!(kr.keys(), ["b"]); + } + + #[test] + fn empty_keyring_round_trips() { + let kr = MemoryKeyring::with_params(&password_params("")).unwrap(); + let blob = kr.export().unwrap(); + let mut reopened = MemoryKeyring::import(&blob, PASSWORD).unwrap(); + assert!(matches!( + reopened.get_secret("missing"), + Err(KeyRingError::ItemNotFound) + )); + } + + #[test] + fn wrong_password_is_denied() { + let mut kr = MemoryKeyring::with_params(&password_params("")).unwrap(); + kr.set_secret("a", b"one").unwrap(); + let blob = kr.export().unwrap(); + assert!(matches!( + MemoryKeyring::import(&blob, b"wrong"), + Err(KeyRingError::AccessDenied { .. }) + )); + } + + /// A blob header with whatever Argon2 costs a hostile image would ask for. + fn blob_with_costs(memory: u32, threads: u32, parallel: u32, salt_len: u32) -> Vec { + let mut blob = Vec::new(); + blob.extend_from_slice(b"CRYPTEX\0"); + blob.push(1); // version + blob.push(super::kind::PASSWORD); + blob.push(super::seal_cipher(CipherAlgorithm::default())); + blob.extend_from_slice(&memory.to_le_bytes()); + blob.extend_from_slice(&threads.to_le_bytes()); + blob.extend_from_slice(¶llel.to_le_bytes()); + blob.extend_from_slice(&salt_len.to_le_bytes()); + blob.extend_from_slice(b"saltsalt"); + blob.extend_from_slice(&[0u8; super::NONCE_SIZE + 16]); + blob + } + + #[test] + fn import_refuses_unreasonable_costs_before_deriving() { + // These sit in an unauthenticated header, so they must be bounded + // before Argon2 tries to honour them. + for (memory, threads, parallel) in [ + (u32::MAX, 1, 1), + (Argon2Params::DEFAULT_M_COST, u32::MAX, 1), + (Argon2Params::DEFAULT_M_COST, 1, u32::MAX), + ] { + let blob = blob_with_costs(memory, threads, parallel, 8); + assert!(matches!( + MemoryKeyring::import(&blob, PASSWORD), + Err(KeyRingError::GeneralError { .. }) + )); + } + } + + #[test] + fn import_refuses_a_salt_length_that_would_overflow() { + // `usize` is 32 bits on wasm32, where the old bounds check wrapped and + // a debug build then panicked slicing the blob. + let blob = blob_with_costs( + Argon2Params::DEFAULT_M_COST, + Argon2Params::DEFAULT_T_COST, + Argon2Params::DEFAULT_P_COST, + u32::MAX, + ); + assert!(matches!( + MemoryKeyring::import(&blob, PASSWORD), + Err(KeyRingError::AccessDenied { .. }) + )); + } + + #[test] + fn a_duplicate_parameter_is_refused() { + // A password containing ` salt=` used to silently replace the salt. + assert!( + "password=a salt=b salt=c" + .parse::() + .is_err() + ); + assert!("password=a password=b".parse::().is_err()); + } + + #[test] + fn tampering_is_detected() { + let mut kr = MemoryKeyring::with_params(&password_params("")).unwrap(); + kr.set_secret("a", b"one").unwrap(); + let blob = kr.export().unwrap(); + + // Header, salt and body are all authenticated. + for index in [9usize, 10, 12, HEADER_LEN + 1, blob.len() - 1] { + let mut flipped = blob.clone(); + flipped[index] ^= 0x80; + assert!( + MemoryKeyring::import(&flipped, PASSWORD).is_err(), + "flipping byte {} went undetected", + index + ); + } + + assert!(MemoryKeyring::import(&blob[..blob.len() - 1], PASSWORD).is_err()); + assert!(MemoryKeyring::import(b"", PASSWORD).is_err()); + } + + #[test] + fn both_ciphers_and_rekey() { + for (cipher, other) in [ + ("chacha20poly1305", "aes256gcm"), + ("aes256gcm", "chacha20poly1305"), + ] { + let mut kr = + MemoryKeyring::with_params(&password_params(&format!("cipher={cipher}"))).unwrap(); + kr.set_secret("a", b"one").unwrap(); + let mut reopened = MemoryKeyring::import(&kr.export().unwrap(), PASSWORD).unwrap(); + assert_eq!(reopened.get_secret("a").unwrap().as_slice(), b"one"); + + reopened + .rekey(¶ms(&format!( + "password=new_password salt=another_salt_value cipher={other}" + ))) + .unwrap(); + assert_eq!( + reopened.cipher(), + if other == "aes256gcm" { + CipherAlgorithm::Aes256Gcm + } else { + CipherAlgorithm::ChaCha20Poly1305 + } + ); + + let rekeyed = reopened.export().unwrap(); + assert!(MemoryKeyring::import(&rekeyed, PASSWORD).is_err()); + let mut again = MemoryKeyring::import(&rekeyed, b"new_password").unwrap(); + assert_eq!(again.get_secret("a").unwrap().as_slice(), b"one"); + } + } + + #[test] + fn raw_key_blobs_need_the_key() { + let key = "0f1e2d3c4b5a69788796a5b4c3d2e1f00f1e2d3c4b5a69788796a5b4c3d2e1f0"; + let mut kr = + MemoryKeyring::with_params(¶ms(&format!("key={} salt=ignored_salt_value", key))) + .unwrap(); + kr.set_secret("a", b"one").unwrap(); + let blob = kr.export().unwrap(); + + let key_bytes = hex::decode(key).unwrap(); + let mut reopened = MemoryKeyring::import(&blob, &key_bytes).unwrap(); + assert_eq!(reopened.get_secret("a").unwrap().as_slice(), b"one"); + assert!(MemoryKeyring::import(&blob, PASSWORD).is_err()); + + // A raw-key blob carries no password, so the password path must fail. + assert!(MemoryKeyring::import(&blob, b"anything").is_err()); + } + + #[test] + fn blobs_carry_no_plaintext() { + let mut kr = MemoryKeyring::with_params(&password_params("")).unwrap(); + kr.set_secret("account", b"super-secret-value").unwrap(); + let blob = kr.export().unwrap(); + assert!(!blob.windows(18).any(|w| w == b"super-secret-value")); + assert!(!blob.windows(7).any(|w| w == b"account")); + } + + #[test] + fn ids_and_values_survive_odd_characters() { + let mut kr = MemoryKeyring::with_params(&password_params("")).unwrap(); + kr.set_secret("ünïcode/ключ", b"\x00\x01\x02bytes").unwrap(); + let blob = kr.export().unwrap(); + let mut reopened = MemoryKeyring::import(&blob, PASSWORD).unwrap(); + assert_eq!( + reopened.get_secret("ünïcode/ключ").unwrap().as_slice(), + b"\x00\x01\x02bytes" + ); + } +} diff --git a/src/keyring/opfs.rs b/src/keyring/opfs.rs new file mode 100644 index 0000000..3d869b4 --- /dev/null +++ b/src/keyring/opfs.rs @@ -0,0 +1,468 @@ +/* + Copyright Michael Lodder. All Rights Reserved. + SPDX-License-Identifier: Apache-2.0 +*/ +//! Origin Private File System storage for a Turso keyring. +//! +//! OPFS is a real filesystem owned by the origin. Its synchronous access +//! handles are the only way to read and write files without awaiting every +//! call, and browsers only hand them out inside a worker — which is exactly +//! where a keyring belongs, since deriving a key with Argon2 would otherwise +//! freeze the page. +//! +//! ```no_run +//! # use cryptex::turso::TursoKeyring; +//! # use cryptex::KeyRing; +//! # async fn example() -> Result<(), Box> { +//! let params = "password=mysecret salt=0okm9ijn8uhb7ygv".parse()?; +//! let mut keyring = TursoKeyring::open_opfs(¶ms, "settings").await?; +//! keyring.set_secret("api-token", b"secret")?; +//! # Ok(()) +//! # } +//! ``` +//! +//! Files live under `cryptex/` in the origin's private filesystem, as +//! `.db3` plus the `.db3-wal` Turso keeps next to it. Holding the +//! sync access handle is itself exclusive: a second tab or worker that tries +//! to open the same keyring gets an error from the browser instead of +//! corrupting the file, so no separate lock file is needed. +//! +//! Like every browser store, OPFS is readable by any script on the origin, so +//! the pages stay encrypted and the key never leaves the password. + +use super::page_store::PageStore; +use super::web_time::WebClock; +use crate::Result; +use crate::error::KeyRingError; +use ::turso::core::io::FileId; +use ::turso::core::{ + Clock, File as TursoFileIo, LimboError, MonotonicInstant, WallClockInstant, io_error, +}; +use std::cell::{Cell, RefCell}; +use std::collections::HashMap; +use std::io; +use std::sync::{Arc, Mutex, MutexGuard}; +use wasm_bindgen::JsCast; +use wasm_bindgen_futures::JsFuture; +use web_sys::{ + FileSystemDirectoryHandle, FileSystemGetDirectoryOptions, FileSystemGetFileOptions, + FileSystemReadWriteOptions, FileSystemSyncAccessHandle, +}; + +/// Directory inside the origin's private filesystem. +const DIRECTORY: &str = "cryptex"; + +thread_local! { + /// Handles are `!Send`, so they live here and the store keeps only an id. + /// Wasm runs one thread, so a thread-local is the whole registry. + static HANDLES: RefCell> = + RefCell::new(HashMap::new()); + static NEXT_ID: Cell = const { Cell::new(1) }; +} + +/// A [`PageStore`] over one OPFS file's synchronous access handle. +pub(crate) struct OpfsPages { + id: u32, +} + +impl OpfsPages { + /// Open (creating if needed) `name` inside the cryptex directory. + async fn open(name: &str) -> Result { + let directory = open_directory().await?; + let options = FileSystemGetFileOptions::new(); + options.set_create(true); + let handle: web_sys::FileSystemFileHandle = + JsFuture::from(directory.get_file_handle_with_options(name, &options)) + .await + .map_err(js_error)? + .dyn_into() + .map_err(js_error)?; + + let access: FileSystemSyncAccessHandle = + JsFuture::from(handle.create_sync_access_handle()) + .await + .map_err(|e| { + KeyRingError::AccessDenied { + msg: format!( + "unable to take exclusive access to {name} in OPFS (is another tab or worker using it?): {}", + js_message(e) + ), + } + })? + .dyn_into() + .map_err(js_error)?; + + let id = NEXT_ID.with(|next| { + let id = next.get(); + next.set(id.wrapping_add(1)); + id + }); + HANDLES.with(|handles| handles.borrow_mut().insert(id, access)); + Ok(Self { id }) + } + + /// Release the handle, closing the file. + pub(crate) fn close(&self) { + if let Some(handle) = HANDLES.with(|handles| handles.borrow_mut().remove(&self.id)) { + handle.close(); + } + } + + fn with_handle( + &self, + op: &str, + f: impl FnOnce(&FileSystemSyncAccessHandle) -> std::result::Result, + ) -> io::Result { + HANDLES.with(|handles| { + let handles = handles.borrow(); + let handle = handles.get(&self.id).ok_or_else(|| { + io::Error::other(format!("the OPFS handle is closed, cannot {op}")) + })?; + f(handle).map_err(|e| io::Error::other(js_message(e))) + }) + } +} + +impl PageStore for OpfsPages { + fn len(&self) -> io::Result { + self.with_handle("size the file", |handle| handle.get_size()) + .map(|size| size as u64) + } + + fn read_exact_at(&mut self, offset: u64, buf: &mut [u8]) -> io::Result<()> { + let mut filled = 0; + while filled < buf.len() { + let options = FileSystemReadWriteOptions::new(); + options.set_at((offset as usize + filled) as f64); + let read = self.with_handle("read", |handle| { + handle.read_with_u8_array_and_options(&mut buf[filled..], &options) + })? as usize; + if read == 0 { + // Past the end of the file: zero-fill, like a sparse file. + buf[filled..].fill(0); + return Ok(()); + } + filled += read; + } + Ok(()) + } + + fn write_all_at(&mut self, offset: u64, buf: &[u8]) -> io::Result<()> { + let mut written = 0; + while written < buf.len() { + let options = FileSystemReadWriteOptions::new(); + options.set_at((offset as usize + written) as f64); + let n = self.with_handle("write", |handle| { + handle.write_with_u8_array_and_options(&buf[written..], &options) + })? as usize; + if n == 0 { + return Err(io::Error::other("OPFS accepted no bytes")); + } + written += n; + } + Ok(()) + } + + fn set_len(&mut self, len: u64) -> io::Result<()> { + self.with_handle("resize the file", |handle| { + handle.truncate_with_f64(len as f64) + }) + } + + fn sync(&mut self) -> io::Result<()> { + self.with_handle("flush the file", |handle| handle.flush()) + } +} + +/// The Turso [`IO`](::turso::core::IO) backed by OPFS. +/// +/// Both files Turso needs are opened up front, because a sync access handle is +/// obtained asynchronously: `open_file` itself cannot await. +pub(crate) struct OpfsIo { + files: HashMap>, + /// Distinguishes this IO in Turso's process-wide database registry, which + /// is keyed by `file_id`; see `WebIo::instance`. + instance: String, +} + +impl OpfsIo { + /// Open `.db3` and its WAL under `cryptex/`. + pub(crate) async fn open(name: &str) -> Result { + let db = format!("{name}.db3"); + let wal = format!("{db}-wal"); + let mut files = HashMap::new(); + for path in [db, wal] { + let pages = OpfsPages::open(&path).await?; + files.insert(path, Arc::new(OpfsFile::new(pages))); + } + Ok(Self { + files, + instance: super::turso_web::new_instance(), + }) + } + + /// Flush both files to disk and release their handles. + pub(crate) fn close(&mut self) { + for file in self.files.values() { + file.close(); + } + self.files.clear(); + } +} + +impl Drop for OpfsIo { + fn drop(&mut self) { + self.close(); + } +} + +impl Clock for OpfsIo { + fn current_time_monotonic(&self) -> MonotonicInstant { + WebClock.current_time_monotonic() + } + + fn current_time_wall_clock(&self) -> WallClockInstant { + WebClock.current_time_wall_clock() + } +} + +impl ::turso::core::IO for OpfsIo { + fn open_file( + &self, + path: &str, + _flags: ::turso::core::OpenFlags, + _direct: bool, + ) -> std::result::Result, LimboError> { + // Only the database and its WAL are ever opened: the handle for each + // had to exist before Turso asked, so an unknown path is a bug in the + // caller's configuration, not a file to create. + match self.files.get(path) { + Some(file) => { + let file: Arc = Arc::clone(file); + Ok(file) + } + None => Err(LimboError::InternalError(format!( + "the OPFS keyring did not prepare '{path}'; it opens only the database and its WAL" + ))), + } + } + + fn remove_file(&self, _path: &str) -> std::result::Result<(), LimboError> { + Err(LimboError::InternalError( + "an OPFS keyring is removed through the file system, not Turso".to_string(), + )) + } + + fn is_memory(&self) -> bool { + false + } + + fn file_id(&self, path: &str) -> std::result::Result { + Ok(FileId::from_path_hash(&format!( + "{}/{}", + self.instance, path + ))) + } +} + +/// The Turso file view of one prepared OPFS file. +struct OpfsFile { + store: Mutex, +} + +impl OpfsFile { + fn new(pages: OpfsPages) -> Self { + Self { + store: Mutex::new(pages), + } + } + + /// Flush and close the handle. The store stays usable but fails every call. + fn close(&self) { + if let Ok(mut store) = self.store.lock() { + let _ = store.sync(); + store.close(); + } + } + + fn store(&self) -> std::result::Result, LimboError> { + self.store + .lock() + .map_err(|_| LimboError::InternalError("OPFS file lock poisoned".to_string())) + } +} + +fn to_i32(n: usize) -> std::result::Result { + i32::try_from(n).map_err(|_| LimboError::InternalError("I/O length overflows i32".into())) +} + +impl TursoFileIo for OpfsFile { + // The sync access handle is already exclusive. + fn lock_file(&self, _exclusive: bool) -> std::result::Result<(), LimboError> { + Ok(()) + } + + fn unlock_file(&self) -> std::result::Result<(), LimboError> { + Ok(()) + } + + fn pread( + &self, + pos: u64, + c: ::turso::core::Completion, + ) -> std::result::Result<::turso::core::Completion, LimboError> { + let mut store = self.store()?; + let size = store.len().map_err(|e| io_error(e, "pread"))?; + let buf = c.as_read().buf().as_mut_slice(); + let n = (buf.len() as u64).min(size.saturating_sub(pos)) as usize; + store + .read_exact_at(pos, &mut buf[..n]) + .map_err(|e| io_error(e, "pread"))?; + c.complete(to_i32(n)?); + Ok(c) + } + + fn pwrite( + &self, + pos: u64, + buffer: Arc<::turso::core::Buffer>, + c: ::turso::core::Completion, + ) -> std::result::Result<::turso::core::Completion, LimboError> { + let mut store = self.store()?; + store + .write_all_at(pos, buffer.as_slice()) + .map_err(|e| io_error(e, "pwrite"))?; + c.complete(to_i32(buffer.as_slice().len())?); + Ok(c) + } + + fn sync( + &self, + c: ::turso::core::Completion, + _sync_type: ::turso::core::io::FileSyncType, + ) -> std::result::Result<::turso::core::Completion, LimboError> { + self.store()?.sync().map_err(|e| io_error(e, "sync"))?; + c.complete(0); + Ok(c) + } + + fn size(&self) -> std::result::Result { + self.store()?.len().map_err(|e| io_error(e, "size")) + } + + fn truncate( + &self, + len: u64, + c: ::turso::core::Completion, + ) -> std::result::Result<::turso::core::Completion, LimboError> { + self.store()? + .set_len(len) + .map_err(|e| io_error(e, "truncate"))?; + c.complete(0); + Ok(c) + } +} + +async fn open_directory() -> Result { + let navigator = js_sys::Reflect::get( + &js_sys::global(), + &wasm_bindgen::JsValue::from_str("navigator"), + ) + .map_err(js_error)?; + let storage = js_sys::Reflect::get(&navigator, &wasm_bindgen::JsValue::from_str("storage")) + .map_err(js_error)?; + if storage.is_undefined() { + return Err(unsupported( + "this browser has no Storage Manager API, so OPFS is unavailable", + )); + } + let get_directory = + js_sys::Reflect::get(&storage, &wasm_bindgen::JsValue::from_str("getDirectory")) + .map_err(js_error)? + .dyn_into::() + .map_err(js_error)?; + let root: FileSystemDirectoryHandle = JsFuture::from( + get_directory + .call0(&storage) + .map_err(js_error)? + .dyn_into::() + .map_err(js_error)?, + ) + .await + .map_err(js_error)? + .dyn_into() + .map_err(js_error)?; + + let options = FileSystemGetDirectoryOptions::new(); + options.set_create(true); + let directory = JsFuture::from(root.get_directory_handle_with_options(DIRECTORY, &options)) + .await + .map_err(js_error)? + .dyn_into() + .map_err(js_error)?; + Ok(directory) +} + +/// Names of every keyring stored under `cryptex/` in the origin's OPFS. +/// +/// Reads the directory listing only, so it works from a page even though +/// opening a keyring needs a worker (sync access handles are worker-only). +pub async fn list_names() -> Result> { + use wasm_bindgen::JsValue; + + let directory = open_directory().await?; + let keys: js_sys::Function = js_sys::Reflect::get(&directory, &JsValue::from_str("keys")) + .map_err(js_error)? + .dyn_into() + .map_err(|_| unsupported("this browser cannot list OPFS files"))?; + let iterator = keys.call0(&directory).map_err(js_error)?; + let next: js_sys::Function = js_sys::Reflect::get(&iterator, &JsValue::from_str("next")) + .map_err(js_error)? + .dyn_into() + .map_err(js_error)?; + + let mut names = Vec::new(); + loop { + // `keys()` is an async iterator: each step is a promise for + // `{ value, done }`. + let step = JsFuture::from( + next.call0(&iterator) + .map_err(js_error)? + .dyn_into::() + .map_err(js_error)?, + ) + .await + .map_err(js_error)?; + let done = js_sys::Reflect::get(&step, &JsValue::from_str("done")) + .map_err(js_error)? + .as_bool() + .unwrap_or(true); + if done { + break; + } + let value = js_sys::Reflect::get(&step, &JsValue::from_str("value")).map_err(js_error)?; + // Every keyring is `.db3`; the WAL next to it is not a keyring. + if let Some(name) = value + .as_string() + .and_then(|name| name.strip_suffix(".db3").map(str::to_string)) + { + names.push(name); + } + } + names.sort(); + Ok(names) +} + +fn js_error(value: wasm_bindgen::JsValue) -> KeyRingError { + KeyRingError::from(value) +} + +fn js_message(value: wasm_bindgen::JsValue) -> String { + KeyRingError::from(value).as_str() +} + +fn unsupported(msg: &str) -> KeyRingError { + KeyRingError::GeneralError { + msg: msg.to_string(), + } +} diff --git a/src/keyring/page_cipher.rs b/src/keyring/page_cipher.rs index 840971a..0e81dd0 100644 --- a/src/keyring/page_cipher.rs +++ b/src/keyring/page_cipher.rs @@ -2,25 +2,24 @@ Copyright Michael Lodder. All Rights Reserved. SPDX-License-Identifier: Apache-2.0 */ -//! Page-level AEAD encryption shared by the SQLite encrypted VFS and the -//! Turso encrypted IO backend. +//! Page-level AEAD encryption shared by the SQLite encrypted VFS, the Turso +//! encrypted IO backend and the browser page stores. //! -//! Every 4096-byte logical page is stored on disk as +//! Every 4096-byte logical page is stored as //! `[ciphertext(4096) | nonce(12) | tag(16)]`, with the page number bound as -//! associated data so pages cannot be swapped. +//! associated data so pages cannot be swapped. The byte layout is identical +//! for every [`PageStore`], so a file written natively opens unchanged from +//! OPFS and the other way round. -use super::*; +use super::cipher::CipherAlgorithm; +use super::page_store::PageStore; use aes_gcm::Aes256Gcm; use chacha20poly1305::{ ChaCha20Poly1305, aead::{Aead, KeyInit, Payload}, }; -use std::fs::File; -use std::io::{self, Read, Seek, SeekFrom, Write}; +use std::io; use std::iter; -use zeroize::Zeroize; - -use crate::error::KeyRingError; pub(crate) const LOGICAL_PAGE_SIZE: usize = 4096; const NONCE_SIZE: usize = 12; @@ -28,41 +27,6 @@ const TAG_SIZE: usize = 16; /// Physical block on disk = [ciphertext(4096) | nonce(12) | tag(16)] pub(crate) const PHYSICAL_PAGE_SIZE: usize = LOGICAL_PAGE_SIZE + NONCE_SIZE + TAG_SIZE; // 4124 -/// Selects the AEAD algorithm used for page encryption. -/// -/// `Aes256Gcm` uses AES-NI hardware acceleration on x86/x86_64/AArch64 when -/// available; on hardware without AES-NI it falls back to a constant-time -/// software implementation that is slower than ChaCha20-Poly1305. -#[derive(Clone, Copy, Default, Debug, PartialEq, Eq)] -pub enum CipherAlgorithm { - /// ChaCha20-Poly1305 (default) - #[default] - ChaCha20Poly1305, - /// AES-256-GCM - Aes256Gcm, -} - -impl Zeroize for CipherAlgorithm { - fn zeroize(&mut self) { - *self = CipherAlgorithm::default(); - } -} - -impl file_common::CipherParam for CipherAlgorithm { - fn parse(value: &str) -> Result { - match value { - "chacha20poly1305" | "chacha20" => Ok(CipherAlgorithm::ChaCha20Poly1305), - "aes256gcm" | "aes" => Ok(CipherAlgorithm::Aes256Gcm), - other => Err(KeyRingError::GeneralError { - msg: format!( - "unknown cipher '{}'; use chacha20poly1305 or aes256gcm", - other - ), - }), - } - } -} - // Internal dispatch — one variant per algorithm. Both use 12-byte nonces and // 16-byte tags so the physical page layout is identical regardless of choice. pub(crate) enum ActiveCipher { @@ -142,27 +106,30 @@ impl ActiveCipher { /// Read and decrypt physical page `page_no`, or return zeros if it lies /// past the end of the file. - fn load_page(&self, file: &mut File, page_no: usize) -> io::Result<[u8; LOGICAL_PAGE_SIZE]> { + fn load_page( + &self, + store: &mut S, + page_no: usize, + ) -> io::Result<[u8; LOGICAL_PAGE_SIZE]> { let physical_offset = (page_no * PHYSICAL_PAGE_SIZE) as u64; - if physical_offset >= file.metadata()?.len() { + if physical_offset >= store.len()? { return Ok([0u8; LOGICAL_PAGE_SIZE]); } let mut block = [0u8; PHYSICAL_PAGE_SIZE]; - file.seek(SeekFrom::Start(physical_offset))?; - file.read_exact(&mut block)?; + store.read_exact_at(physical_offset, &mut block)?; self.decrypt_page(page_no as u64, &block) } /// Read `data.len()` logical bytes starting at logical `offset`. /// Bytes past the end of the file read as zeros. - pub(crate) fn read_at( + pub(crate) fn read_at( &self, - file: &mut File, + store: &mut S, offset: usize, data: &mut [u8], ) -> io::Result { for chunk in page_chunks(offset, data.len()) { - let page = self.load_page(file, chunk.page_no)?; + let page = self.load_page(store, chunk.page_no)?; data[chunk.buf_pos..chunk.buf_pos + chunk.len] .copy_from_slice(&page[chunk.intra..chunk.intra + chunk.len]); } @@ -170,9 +137,9 @@ impl ActiveCipher { } /// Write `data` at logical `offset`, re-encrypting every touched page. - pub(crate) fn write_at( + pub(crate) fn write_at( &self, - file: &mut File, + store: &mut S, offset: usize, data: &[u8], ) -> io::Result { @@ -180,29 +147,32 @@ impl ActiveCipher { let mut page = if chunk.len == LOGICAL_PAGE_SIZE { [0u8; LOGICAL_PAGE_SIZE] } else { - self.load_page(file, chunk.page_no)? + self.load_page(store, chunk.page_no)? }; page[chunk.intra..chunk.intra + chunk.len] .copy_from_slice(&data[chunk.buf_pos..chunk.buf_pos + chunk.len]); let block = self.encrypt_page(chunk.page_no as u64, &page)?; - file.seek(SeekFrom::Start((chunk.page_no * PHYSICAL_PAGE_SIZE) as u64))?; - file.write_all(&block)?; + let physical_offset = (chunk.page_no * PHYSICAL_PAGE_SIZE) as u64; + store.write_all_at(physical_offset, &block)?; } Ok(data.len()) } } -/// Logical size of an encrypted file: whole physical pages × logical page size. -pub(crate) fn logical_size(file: &File) -> io::Result { - let phys = file.metadata()?.len(); +/// Logical size of an encrypted store: whole physical pages × logical page size. +pub(crate) fn logical_size(store: &S) -> io::Result { + let phys = store.len()?; Ok((phys / PHYSICAL_PAGE_SIZE as u64) * LOGICAL_PAGE_SIZE as u64) } -/// Truncate an encrypted file to hold `logical_size` bytes (rounded up to a page). -pub(crate) fn truncate(file: &File, logical_size: usize) -> io::Result<()> { +/// Truncate an encrypted store to hold `logical_size` bytes (rounded up to a page). +pub(crate) fn truncate( + store: &mut S, + logical_size: usize, +) -> io::Result<()> { let num_pages = logical_size.div_ceil(LOGICAL_PAGE_SIZE); - file.set_len((num_pages * PHYSICAL_PAGE_SIZE) as u64) + store.set_len((num_pages * PHYSICAL_PAGE_SIZE) as u64) } /// The part of one logical page touched by a byte-range access. @@ -240,6 +210,7 @@ fn page_chunks(offset: usize, len: usize) -> impl Iterator { mod tests { use super::*; use std::fs; + use std::fs::File; use std::path::PathBuf; fn temp_file(name: &str) -> (PathBuf, File) { @@ -295,9 +266,12 @@ mod tests { let wrong = ActiveCipher::from_key(alg, &[8u8; 32]); assert!(wrong.read_at(&mut f, 0, &mut out).is_err()); - truncate(&f, 1).unwrap(); + truncate(&mut f, 1).unwrap(); assert_eq!(logical_size(&f).unwrap(), LOGICAL_PAGE_SIZE as u64); + // Close the file before removing it, for Windows. + f.sync_all().unwrap(); + #[allow(clippy::drop_non_drop)] drop(f); let _ = fs::remove_file(path); } diff --git a/src/keyring/page_store.rs b/src/keyring/page_store.rs new file mode 100644 index 0000000..08304df --- /dev/null +++ b/src/keyring/page_store.rs @@ -0,0 +1,126 @@ +/* + Copyright Michael Lodder. All Rights Reserved. + SPDX-License-Identifier: Apache-2.0 +*/ +//! Byte-addressable storage behind an encrypted page file. +//! +//! The cipher in [`page_cipher`](super::page_cipher) works on pages; this +//! module supplies the bytes. Native keyrings use a file, browser keyrings a +//! buffer or an OPFS handle. + +#![allow(dead_code)] + +use std::fs::File; +use std::io::{self, Read, Seek, SeekFrom, Write}; + +/// Byte-addressable storage behind an encrypted page file. +/// +/// Implementations are a native file, an in-memory buffer and a browser OPFS +/// sync access handle. `len` and `set_len` work in physical bytes; the cipher +/// translates to logical pages. +pub(crate) trait PageStore { + /// Physical size in bytes. + fn len(&self) -> io::Result; + /// Read exactly `buf.len()` bytes at `offset`, zero-filling past the end. + fn read_exact_at(&mut self, offset: u64, buf: &mut [u8]) -> io::Result<()>; + /// Write all of `buf` at `offset`, growing the store if needed. + fn write_all_at(&mut self, offset: u64, buf: &[u8]) -> io::Result<()>; + /// Resize the store, zero-filling any gap. + fn set_len(&mut self, len: u64) -> io::Result<()>; + /// Flush writes to durable storage. Buffers have nothing to flush. + fn sync(&mut self) -> io::Result<()> { + Ok(()) + } +} + +impl PageStore for File { + fn len(&self) -> io::Result { + Ok(self.metadata()?.len()) + } + + fn read_exact_at(&mut self, offset: u64, buf: &mut [u8]) -> io::Result<()> { + self.seek(SeekFrom::Start(offset))?; + self.read_exact(buf) + } + + fn write_all_at(&mut self, offset: u64, buf: &[u8]) -> io::Result<()> { + self.seek(SeekFrom::Start(offset))?; + self.write_all(buf) + } + + fn set_len(&mut self, len: u64) -> io::Result<()> { + File::set_len(self, len) + } + + fn sync(&mut self) -> io::Result<()> { + self.sync_all() + } +} + +/// A [`PageStore`] held entirely in memory. +#[cfg(feature = "turso")] +#[derive(Default)] +pub(crate) struct MemPages(Vec); + +#[cfg(feature = "turso")] +impl MemPages { + pub(crate) fn new() -> Self { + Self(Vec::new()) + } + + pub(crate) fn from_vec(bytes: Vec) -> Self { + Self(bytes) + } + + pub(crate) fn as_slice(&self) -> &[u8] { + &self.0 + } +} + +#[cfg(feature = "turso")] +impl PageStore for MemPages { + fn len(&self) -> io::Result { + Ok(self.0.len() as u64) + } + + fn read_exact_at(&mut self, offset: u64, buf: &mut [u8]) -> io::Result<()> { + let start = + usize::try_from(offset).map_err(|_| io::Error::from(io::ErrorKind::InvalidInput))?; + let end = start + .checked_add(buf.len()) + .ok_or_else(|| io::Error::from(io::ErrorKind::InvalidInput))?; + if start >= self.0.len() { + buf.fill(0); + return Ok(()); + } + let available = self.0.len() - start; + let n = available.min(buf.len()); + buf[..n].copy_from_slice(&self.0[start..start + n]); + buf[n..].fill(0); + let _ = end; + Ok(()) + } + + fn write_all_at(&mut self, offset: u64, buf: &[u8]) -> io::Result<()> { + let start = + usize::try_from(offset).map_err(|_| io::Error::from(io::ErrorKind::InvalidInput))?; + let end = start + .checked_add(buf.len()) + .ok_or_else(|| io::Error::from(io::ErrorKind::InvalidInput))?; + if self.0.len() < end { + self.0.resize(end, 0); + } + self.0[start..end].copy_from_slice(buf); + Ok(()) + } + + fn set_len(&mut self, len: u64) -> io::Result<()> { + let len = usize::try_from(len).map_err(|_| io::Error::from(io::ErrorKind::InvalidInput))?; + self.0.resize(len, 0); + Ok(()) + } + + fn sync(&mut self) -> io::Result<()> { + Ok(()) + } +} diff --git a/src/keyring/turso.rs b/src/keyring/turso.rs index 7276a4e..9e3daaa 100644 --- a/src/keyring/turso.rs +++ b/src/keyring/turso.rs @@ -11,10 +11,14 @@ use super::*; use ::turso::{Builder, EncryptionOpts}; use std::path::PathBuf; +use std::sync::Arc; use zeroize::{Zeroize, Zeroizing}; -use super::file_common::{self, CipherParam, derive_key_32, file_keyring, secure_file}; +use super::file_common::{self, CipherParam, derive_key_32, secure_file}; +#[cfg(feature = "turso-opfs")] +use super::opfs::OpfsIo; use super::turso_common::TursoFile; +use super::turso_web::{WebIo, unique_db_path}; use crate::error::KeyRingError; /// The cipher Turso uses to encrypt database pages. @@ -62,23 +66,221 @@ impl CipherParam for TursoCipher { /// ``` pub type ConnectionParams = file_common::ConnectionParams; +/// Turso's builder, re-exported so callers construct matching types. +pub use ::turso::Builder as TursoBuilder; +/// The Turso connection type a keyring can adopt. +/// +/// Use the `turso` crate cryptex was built against (the same version as +/// [`Builder`]), or a type mismatch will result. +pub use ::turso::Connection; +/// Turso's low-level crate, for implementing a custom `IO` such as OPFS. +pub use ::turso::core; + /// A keyring stored in a Turso database encrypted with Turso's native page /// encryption. The default file is `~/.cryptex/keyring-turso.db3`. /// /// Turso keeps its own copy of the hex-encoded key for the life of the /// database; cryptex zeroizes only the copies it owns. +/// +/// Three ways to get one: +/// - [`with_params`](Self::with_params) opens the file itself, as before. +/// - [`from_connection`](Self::from_connection) adopts a connection the caller +/// already opened, so key storage and application tables can share one +/// database and one key. +/// - [`with_io`](Self::with_io) opens through a caller-supplied Turso `IO`, +/// such as the Origin Private File System in a browser worker. pub struct TursoKeyring { - file: TursoFile, + backing: Backing, +} + +/// Where a keyring's database lives. +enum Backing { + /// A file, or a connection the caller owns, that outlives the keyring. + Stored(TursoFile), + /// A database cryptex made in memory, so it can be copied out as an image. + InMemory { file: TursoFile, io: Arc }, } -file_keyring!(TursoKeyring, file); +impl Backing { + fn file(&self) -> &TursoFile { + match self { + Self::Stored(file) | Self::InMemory { file, .. } => file, + } + } + + fn into_file(self) -> TursoFile { + match self { + Self::Stored(file) | Self::InMemory { file, .. } => file, + } + } +} + +impl DynKeyRing for TursoKeyring { + fn get_secret(&mut self, id: &str) -> Result { + file_common::SecretStore::get(self.file(), id) + } + + fn set_secret(&mut self, id: &str, secret: &[u8]) -> Result<()> { + file_common::SecretStore::set(self.file(), id, secret) + } + + fn delete_secret(&mut self, id: &str) -> Result<()> { + file_common::SecretStore::delete(self.file(), id) + } +} + +impl NewKeyRing for TursoKeyring { + fn new>(lock_key: S) -> Result { + let params = lock_key.as_ref().parse::()?; + Self::with_params(¶ms, None) + } +} impl TursoKeyring { + fn file(&self) -> &TursoFile { + self.backing.file() + } + /// Open (or create) the keyring in `path` (default `~/.cryptex`). pub fn with_params(connection: &ConnectionParams, path: Option) -> Result { let file = TursoFile::open(path, builder(connection)?)?; - secure_file(file.db_path())?; - Ok(Self { file }) + if let Some(db_path) = file.db_path() { + secure_file(db_path)?; + } + Ok(Self { + backing: Backing::Stored(file), + }) + } + + /// Adopt an already-open Turso connection. + /// + /// The keyring creates and owns its `secrets` table and uses the + /// connection as given, so an application can keep its own tables in the + /// same database and share one key derivation. Nothing about the + /// connection is reconfigured: encryption, IO and the clock are the + /// caller's. + /// + /// The caller is responsible for opening the database with the right key + /// and, in a browser, for holding the single-writer storage handle. + /// + /// [`rekey`](Self::rekey) is not available on an adopted keyring because + /// cryptex does not own the storage; copy the secrets into a new keyring + /// instead. + /// + /// ```no_run + /// # use cryptex::turso::{TursoKeyring, TursoBuilder}; + /// # async fn example(conn: cryptex::turso::Connection) -> Result<(), Box> { + /// // The caller opened the database, e.g. with its own IO and encryption. + /// let mut keyring = TursoKeyring::from_connection(conn)?; + /// # Ok(()) + /// # } + /// ``` + pub fn from_connection(conn: Connection) -> Result { + Ok(Self { + backing: Backing::Stored(TursoFile::adopt(conn)?), + }) + } + + /// Open (or create) the keyring through a caller-supplied Turso `IO`. + /// + /// `io` supplies every page: for example an OPFS-backed `IO` in a browser + /// worker. `path` is the database path passed to that IO. The key is + /// derived from `params` and applied with Turso's native page encryption, + /// exactly as [`with_params`](Self::with_params) does. + /// + /// No lock file is created and [`rekey`](Self::rekey) is unavailable; the + /// caller owns single-writer access, which for OPFS means holding the one + /// sync access handle for the database. + pub fn with_io(io: Arc, path: &str, params: &ConnectionParams) -> Result { + Ok(Self { + backing: Backing::Stored(Self::open_through(io, path, params)?), + }) + } + + /// Open a keyring whose database lives in process memory. + /// + /// Nothing reaches the filesystem, so this works in a browser. Copy the + /// database out with [`export`](Self::export) to persist it and reopen + /// with [`from_bytes`](Self::from_bytes). + pub fn in_memory(params: &ConnectionParams) -> Result { + let io = WebIo::in_memory(); + let path = unique_db_path(); + Self::open_web(io, &path, params) + } + + /// Reopen a keyring from an image produced by [`export`](Self::export). + pub fn from_bytes(bytes: &[u8], params: &ConnectionParams) -> Result { + let io = WebIo::restore(bytes)?; + // The image remembers the path it was written under; Turso keys open + // databases by path, so it has to be opened as that path. + let path = io.db_path().ok_or_else(|| KeyRingError::AccessDenied { + msg: "Invalid key or corrupted keyring image".to_string(), + })?; + Self::open_web(io, &path, params) + } + + /// Open through an `IO` cryptex made, so the database can be copied out. + fn open_web(io: Arc, path: &str, params: &ConnectionParams) -> Result { + let handle = Arc::clone(&io); + // The image was already parsed, so the only thing left that can refuse + // the open is the key: an image written under another key looks like a + // corrupt one. Report both the way [`MemoryKeyring::import`] does. + let file = + Self::open_through(handle, path, params).map_err(|_| KeyRingError::AccessDenied { + msg: "Invalid key or corrupted keyring image".to_string(), + })?; + Ok(Self { + backing: Backing::InMemory { file, io }, + }) + } + + fn open_through( + io: Arc, + path: &str, + params: &ConnectionParams, + ) -> Result { + TursoFile::open_with(builder(params)?(path).with_io_impl(io)) + } + + /// Open (or create) the keyring in the origin private file system. + /// + /// Only available in a browser worker: OPFS sync access handles exist + /// nowhere else. The database and its WAL live under `cryptex/.db3`. + #[cfg(feature = "turso-opfs")] + pub async fn open_opfs(params: &ConnectionParams, name: &str) -> Result { + let io: Arc = Arc::new(OpfsIo::open(name).await?); + let keyring = Self::with_io(io, &format!("{name}.db3"), params)?; + Ok(keyring) + } + + /// Copy every secret into a new in-memory keyring under `params`. + /// + /// The caller's keyring is left untouched, so a failed rekey changes + /// nothing. This is how a keyring without a file of its own is rekeyed. + pub fn copy_under(&self, params: &ConnectionParams) -> Result { + let io = WebIo::in_memory(); + let path = unique_db_path(); + let copy = Self::open_web(io, &path, params)?; + self.file().copy_into(copy.file())?; + Ok(copy) + } + + /// Copy the whole in-memory database into one encrypted blob. + /// + /// Fails for a keyring opened from a path or from a caller's connection: + /// the caller owns that storage, so it owns copying it. + pub fn export(&self) -> Result> { + match &self.backing { + Backing::InMemory { io, .. } => io.snapshot(), + Backing::Stored(_) => Err(KeyRingError::GeneralError { + msg: "export is only available for an in-memory keyring".to_string(), + }), + } + } + + /// Every id in the keyring, in order. + pub fn keys(&self) -> Result> { + self.file().ids() } /// Re-encrypt the keyring with a new key (and optionally a different cipher). @@ -87,9 +289,13 @@ impl TursoKeyring { /// rekeying fails the original file is left intact and can be reopened /// with the old parameters. pub fn rekey(self, new_params: &ConnectionParams) -> Result { - let file = self.file.rekey(builder(new_params)?)?; - secure_file(file.db_path())?; - Ok(Self { file }) + let file = self.backing.into_file().rekey(builder(new_params)?)?; + if let Some(db_path) = file.db_path() { + secure_file(db_path)?; + } + Ok(Self { + backing: Backing::Stored(file), + }) } } @@ -113,12 +319,42 @@ mod tests { use crate::KeyRing; use crate::error::KeyRingError; use crate::file_common::test_support::TestDir; + use crate::keyring::turso_common::block_on; use std::fs; + use std::sync::Arc; fn params(s: &str) -> ConnectionParams { s.parse().unwrap() } + /// Rewrite a snapshot so its files sit under `base`, as two sessions do + /// when each names its first keyring the same thing. + fn with_paths(image: &[u8], base: &str) -> Vec { + let count = u32::from_le_bytes(image[11..15].try_into().unwrap()); + let mut rest = &image[15..]; + let mut out = image[..15].to_vec(); + for _ in 0..count { + let path_len = u32::from_le_bytes(rest[..4].try_into().unwrap()) as usize; + rest = &rest[4..]; + let path = std::str::from_utf8(&rest[..path_len]).unwrap(); + rest = &rest[path_len..]; + let data_len = u64::from_le_bytes(rest[..8].try_into().unwrap()) as usize; + let data = &rest[8..8 + data_len]; + rest = &rest[8 + data_len..]; + + let path = if path.ends_with("-wal") { + format!("{base}-wal") + } else { + base.to_string() + }; + out.extend_from_slice(&(path.len() as u32).to_le_bytes()); + out.extend_from_slice(path.as_bytes()); + out.extend_from_slice(&(data_len as u64).to_le_bytes()); + out.extend_from_slice(data); + } + out + } + #[test] fn cipher_param_parses() { assert_eq!(params("password=a").cipher, TursoCipher::Aegis256); @@ -158,6 +394,133 @@ mod tests { assert!(!raw.windows(13).any(|w| w == b"SQLite format")); } + #[test] + fn in_memory_round_trips_through_an_image() { + let p = params("password=in_memory salt=1qaz2wsx3edc4rfv5tgb"); + let wrong = params("password=nope salt=1qaz2wsx3edc4rfv5tgb"); + + let image = { + let mut kr = TursoKeyring::in_memory(&p).unwrap(); + kr.set_secret("k1", b"value1").unwrap(); + kr.set_secret("shared", b"kept").unwrap(); + let image = kr.export().unwrap(); + assert!(!image.windows(6).any(|w| w == b"value1")); + image + }; + + let mut restored = TursoKeyring::from_bytes(&image, &p).unwrap(); + assert_eq!(restored.get_secret("k1").unwrap().0, b"value1"); + assert_eq!(restored.get_secret("shared").unwrap().0, b"kept"); + assert_eq!(restored.keys().unwrap(), ["k1", "shared"]); + + assert!(matches!( + TursoKeyring::from_bytes(&image, &wrong), + Err(KeyRingError::AccessDenied { .. }) + )); + assert!(TursoKeyring::from_bytes(b"not a snapshot", &p).is_err()); + } + + #[test] + fn a_snapshot_claiming_huge_counts_is_refused() { + use crate::keyring::turso_web::WebIo; + + // Fifteen bytes used to size a HashMap from an unauthenticated count + // and abort the process on allocation failure. + let mut blob = b"CRYPTEX-IO".to_vec(); + blob.push(1); + blob.extend_from_slice(&u32::MAX.to_le_bytes()); + assert!(WebIo::restore(&blob).is_err()); + + // A count of two with no entries is malformed, not a panic. + let mut blob = b"CRYPTEX-IO".to_vec(); + blob.push(1); + blob.extend_from_slice(&2u32.to_le_bytes()); + assert!(WebIo::restore(&blob).is_err()); + } + + #[test] + fn two_ios_never_share_a_file_id() { + use crate::keyring::turso_web::WebIo; + use ::turso::core::IO; + + // Turso looks open databases up by `file_id`. Two IOs holding the same + // path - an OPFS keyring named `cryptex-1` and an in-memory image - must + // not resolve to one database, or one keyring writes into the other. + let a = WebIo::in_memory(); + let b = WebIo::in_memory(); + assert_ne!( + a.file_id("cryptex-1.db3").unwrap(), + b.file_id("cryptex-1.db3").unwrap() + ); + assert_eq!( + a.file_id("cryptex-1.db3").unwrap(), + a.file_id("cryptex-1.db3").unwrap() + ); + } + + #[test] + fn restored_images_do_not_reuse_the_recorded_path() { + // Turso keys its open databases by `file_id`, so two images recorded + // under one path used to share one open database: the second keyring + // read the first one's secrets and wrote into it. + let p = params("password=collide salt=1qaz2wsx3edc4rfv5tgb"); + + let mut first = TursoKeyring::in_memory(&p).unwrap(); + first.set_secret("first", b"one").unwrap(); + let image_a = first.export().unwrap(); + + let mut second = TursoKeyring::in_memory(&p).unwrap(); + second.set_secret("second", b"two").unwrap(); + let image_b = second.export().unwrap(); + + // Both images claim the same database path, as two page loads would + // when each named its first keyring the same thing. + let mut a = TursoKeyring::from_bytes(&with_paths(&image_a, "shared.db3"), &p).unwrap(); + let mut b = TursoKeyring::from_bytes(&with_paths(&image_b, "shared.db3"), &p).unwrap(); + + assert_eq!(a.get_secret("first").unwrap().0, b"one"); + assert_eq!(b.get_secret("second").unwrap().0, b"two"); + assert!(matches!( + b.get_secret("first"), + Err(KeyRingError::ItemNotFound) + )); + + // A write for one must not land in the other. + b.set_secret("later", b"kept").unwrap(); + assert!(matches!( + a.get_secret("later"), + Err(KeyRingError::ItemNotFound) + )); + } + + #[test] + fn copy_under_rekeys_without_touching_the_original() { + let a = params("password=first salt=1qaz2wsx3edc4rfv5tgb"); + let b = params("password=second salt=1qaz2wsx3edc4rfv5tgb"); + let wrong = params("password=third salt=1qaz2wsx3edc4rfv5tgb"); + + let mut original = TursoKeyring::in_memory(&a).unwrap(); + original.set_secret("k1", b"value1").unwrap(); + + let copy = original.copy_under(&b).unwrap(); + let image = copy.export().unwrap(); + + let mut reopened = TursoKeyring::from_bytes(&image, &b).unwrap(); + assert_eq!(reopened.get_secret("k1").unwrap().0, b"value1"); + assert!(TursoKeyring::from_bytes(&image, &wrong).is_err()); + + // The original still opens with its own key. + assert_eq!(original.get_secret("k1").unwrap().0, b"value1"); + } + + #[test] + fn export_needs_an_in_memory_keyring() { + let dir = TestDir::new(".test-turso-export"); + let p = params("password=export_test salt=1qaz2wsx3edc4rfv5tgb"); + let kr = TursoKeyring::with_params(&p, dir.keyring_dir()).unwrap(); + assert!(kr.export().is_err()); + } + #[test] fn wrong_key_and_concurrent_open_fail() { let dir = TestDir::new(".test-turso-wrongkey"); @@ -167,6 +530,9 @@ mod tests { { let mut kr = TursoKeyring::with_params(&correct, dir.keyring_dir()).unwrap(); kr.set_secret("x", b"secret").unwrap(); + // WASI has no file locking, so a second opener is not refused + // there; callers keep a single writer instead. + #[cfg(not(target_os = "wasi"))] assert!(matches!( TursoKeyring::with_params(&correct, dir.keyring_dir()), Err(KeyRingError::AccessDenied { .. }) @@ -207,4 +573,97 @@ mod tests { assert!(TursoKeyring::with_params(&old_params, dir.keyring_dir()).is_err()); } + + /// A connection opened by the caller, as a browser worker would. + fn caller_connection( + path: std::path::PathBuf, + params: &ConnectionParams, + ) -> ::turso::Connection { + let hexkey = hex::encode(*crate::file_common::derive_key_32(params).unwrap()); + let db = block_on::<_, _, KeyRingError>(async { + ::turso::Builder::new_local(path.to_str().unwrap()) + .experimental_encryption(true) + .with_encryption(::turso::EncryptionOpts { + cipher: params.cipher.as_turso_name().to_string(), + hexkey, + }) + .build() + .await + .map_err(|e| KeyRingError::GeneralError { msg: e.to_string() }) + }) + .unwrap(); + db.connect().unwrap() + } + + #[test] + fn adopts_an_existing_connection() { + let dir = TestDir::new(".test-turso-from-connection"); + let p = params("password=adopt_pass salt=1qaz2wsx3edc4rfv5tgb"); + fs::create_dir_all(&*dir).unwrap(); + let conn = caller_connection(dir.join("shared.db3"), &p); + + // The application owns its own table on the same connection. + block_on(conn.execute("CREATE TABLE audit (event TEXT NOT NULL)", ())).unwrap(); + + { + let mut kr = TursoKeyring::from_connection(conn.clone()).unwrap(); + kr.set_secret("k1", b"value1").unwrap(); + kr.set_secret("k2", b"value2").unwrap(); + assert_eq!(kr.get_secret("k1").unwrap().0, b"value1"); + kr.delete_secret("k2").unwrap(); + assert!(matches!( + kr.get_secret("k2"), + Err(KeyRingError::ItemNotFound) + )); + } + + // Reopening through another connection to the same file sees the data, + // and the application table survived. + let mut kr = + TursoKeyring::from_connection(caller_connection(dir.join("shared.db3"), &p)).unwrap(); + assert_eq!(kr.get_secret("k1").unwrap().0, b"value1"); + + let mut rows = block_on(conn.query( + "SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name", + (), + )) + .unwrap(); + let mut tables = Vec::new(); + while let Some(row) = block_on(rows.next()).unwrap() { + tables.push(row.get::(0).unwrap()); + } + assert_eq!(tables, vec!["audit", "secrets"]); + } + + #[test] + fn adopted_keyring_cannot_rekey() { + let dir = TestDir::new(".test-turso-adopt-rekey"); + let p = params("password=adopt_pass salt=1qaz2wsx3edc4rfv5tgb"); + fs::create_dir_all(&*dir).unwrap(); + let kr = + TursoKeyring::from_connection(caller_connection(dir.join("shared.db3"), &p)).unwrap(); + assert!(kr.rekey(&p).is_err()); + } + + #[test] + fn opens_through_a_custom_io() { + // A caller-supplied IO stands in for OPFS in a browser worker. + let io = Arc::new(::turso::core::MemoryIO::new()); + let p = params("password=io_pass salt=1qaz2wsx3edc4rfv5tgb"); + let db_name = "keyring.db3"; + + { + let mut kr = TursoKeyring::with_io(io.clone(), db_name, &p).unwrap(); + kr.set_secret("k1", b"value1").unwrap(); + } + + { + let mut kr = TursoKeyring::with_io(io.clone(), db_name, &p).unwrap(); + assert_eq!(kr.get_secret("k1").unwrap().0, b"value1"); + } + + // A different key on the same pages is refused. + let wrong = params("password=wrong_pass salt=1qaz2wsx3edc4rfv5tgb"); + assert!(TursoKeyring::with_io(io, db_name, &wrong).is_err()); + } } diff --git a/src/keyring/turso_common.rs b/src/keyring/turso_common.rs index 72f2610..55b61bd 100644 --- a/src/keyring/turso_common.rs +++ b/src/keyring/turso_common.rs @@ -9,18 +9,23 @@ use super::*; use ::turso::{Builder, Connection, Database}; -use std::fs::{self, File}; +use std::fs; +use std::fs::File; use std::future::Future; use std::path::{Path, PathBuf}; use std::pin::pin; +#[cfg(not(target_family = "wasm"))] use std::sync::Arc; -use std::task::{Context, Poll, Wake, Waker}; +#[cfg(not(target_family = "wasm"))] +use std::task::Wake; +use std::task::{Context, Poll, Waker}; +#[cfg(not(target_family = "wasm"))] use std::thread::{self, Thread}; use super::file_common::{ - CREATE_SECRETS_SQL, DELETE_SECRET_SQL, SELECT_SECRET_SQL, SecretStore, UPSERT_SECRET_SQL, - VERIFY_KEY_SQL, acquire_single_opener_lock, decode_secret, get_keyring_file, invalid_key, - sibling_path, + CREATE_SECRETS_SQL, DELETE_SECRET_SQL, SELECT_IDS_SQL, SELECT_SECRET_SQL, SecretStore, + UPSERT_SECRET_SQL, VERIFY_KEY_SQL, acquire_single_opener_lock, decode_secret, get_keyring_file, + invalid_key, sibling_path, }; use crate::error::KeyRingError; use zeroize::Zeroizing; @@ -29,8 +34,10 @@ use zeroize::Zeroizing; /// `keyring.db3` so the backends never try to open each other's files. pub(crate) const KEYRING_FILE: &str = "keyring-turso.db3"; +#[cfg(not(target_family = "wasm"))] struct ThreadWaker(Thread); +#[cfg(not(target_family = "wasm"))] impl Wake for ThreadWaker { fn wake(self: Arc) { self.0.unpark(); @@ -38,40 +45,90 @@ impl Wake for ThreadWaker { } /// Drive `fut` to completion on the current thread. -fn block_on(fut: F) -> F::Output { +/// +/// Turso's futures only return `Pending` when the IO is asynchronous. Native +/// builds can block, so they park the thread until woken. Wasm threads cannot +/// block, so a wasm build polls a bounded number of times and fails instead of +/// spinning forever when an IO backend never completes in place. +#[cfg(not(target_family = "wasm"))] +pub(crate) fn block_on(fut: F) -> Result +where + F: Future>, + E: Into, +{ let mut fut = pin!(fut); let waker = Waker::from(Arc::new(ThreadWaker(thread::current()))); let mut cx = Context::from_waker(&waker); loop { if let Poll::Ready(out) = fut.as_mut().poll(&mut cx) { - return out; + return out.map_err(Into::into); } thread::park(); } } +/// How many times a pending future is re-polled before giving up on wasm. +#[cfg(target_family = "wasm")] +const MAX_WASM_POLLS: usize = 1_000_000; + +#[cfg(target_family = "wasm")] +pub(crate) fn block_on(fut: F) -> Result +where + F: Future>, + E: Into, +{ + let mut fut = pin!(fut); + let mut cx = Context::from_waker(Waker::noop()); + for _ in 0..MAX_WASM_POLLS { + if let Poll::Ready(out) = fut.as_mut().poll(&mut cx) { + return out.map_err(Into::into); + } + } + Err(KeyRingError::GeneralError { + msg: "turso did not complete synchronously: the IO backend must complete \ + reads in place on wasm" + .to_string(), + }) +} + /// An open Turso database holding the `secrets` table. struct TursoStore { conn: Connection, - _db: Database, + /// Kept alive for as long as the store; `None` when the caller supplied + /// the connection and owns the database handle themselves. + _db: Option, } impl TursoStore { + /// Create the keyring's tables on an open connection, verifying the key. + async fn prepare(conn: Connection, db: Option) -> Result { + let mut rows = conn + .query(VERIFY_KEY_SQL, ()) + .await + .map_err(|_| invalid_key())?; + rows.next().await.map_err(|_| invalid_key())?; + drop(rows); + conn.execute(CREATE_SECRETS_SQL, ()).await?; + Ok(Self { conn, _db: db }) + } + + /// Open the database described by `builder` and create the tables. fn open(builder: Builder) -> Result { - block_on(async { + block_on::<_, Self, KeyRingError>(async { let db = builder.build().await?; let conn = db.connect()?; - let mut rows = conn - .query(VERIFY_KEY_SQL, ()) - .await - .map_err(|_| invalid_key())?; - rows.next().await.map_err(|_| invalid_key())?; - drop(rows); - conn.execute(CREATE_SECRETS_SQL, ()).await?; - Ok(Self { conn, _db: db }) + Self::prepare(conn, Some(db)).await }) } + /// Adopt an already-open connection. + /// + /// The keyring creates and owns its `secrets` table; everything else on + /// the connection is left alone, so application tables can share it. + fn adopt(conn: Connection) -> Result { + block_on(Self::prepare(conn, None)) + } + fn get(&self, id: &str) -> Result { block_on(async { let mut rows = self.conn.query(SELECT_SECRET_SQL, [id]).await?; @@ -89,6 +146,17 @@ impl TursoStore { Ok(()) } + fn ids(&self) -> Result> { + block_on::<_, Vec, KeyRingError>(async { + let mut rows = self.conn.query(SELECT_IDS_SQL, ()).await?; + let mut ids = Vec::new(); + while let Some(row) = rows.next().await? { + ids.push(row.get::(0)?); + } + Ok(ids) + }) + } + fn delete(&self, id: &str) -> Result<()> { block_on(self.conn.execute(DELETE_SECRET_SQL, [id]))?; Ok(()) @@ -96,7 +164,7 @@ impl TursoStore { /// Copy every secret into `dst` inside a single transaction. fn copy_into(&self, dst: &TursoStore) -> Result<()> { - block_on(async { + block_on::<_, (), KeyRingError>(async { let mut rows = self.conn.query("SELECT id, value FROM secrets", ()).await?; dst.conn.execute("BEGIN", ()).await?; while let Some(row) = rows.next().await? { @@ -113,7 +181,7 @@ impl TursoStore { /// Flush the WAL into the main database file and empty the WAL. fn checkpoint(&self) -> Result<()> { - block_on(async { + block_on::<_, (), KeyRingError>(async { let mut rows = self .conn .query("PRAGMA wal_checkpoint(TRUNCATE)", ()) @@ -130,10 +198,21 @@ impl TursoStore { /// carrying their encryption configuration. pub(crate) struct TursoFile { store: TursoStore, - db_path: PathBuf, - /// Exclusive advisory lock on a sidecar file, held for the keyring's - /// lifetime so `rekey`'s rename never races another opener. - _lock: File, + storage: Storage, +} + +/// Where a keyring's database lives, and who is responsible for it. +enum Storage { + /// cryptex opened the file itself and holds the single-opener lock. + File { + db_path: PathBuf, + /// Exclusive advisory lock on a sidecar file, held for the keyring's + /// lifetime so `rekey`'s rename never races another opener. + _lock: File, + }, + /// The caller supplied the storage: a connection, or a custom IO backend + /// such as OPFS. The caller owns single-writer access. + Caller, } impl TursoFile { @@ -147,15 +226,46 @@ impl TursoFile { let store = TursoStore::open(builder(path_str(&db_path)?))?; Ok(Self { store, - db_path, - _lock: lock, + storage: Storage::File { + db_path, + _lock: lock, + }, + }) + } + + /// Open through a caller-supplied [`Builder`], e.g. one carrying a custom + /// Turso `IO`. No path is resolved and no lock file is created: the caller + /// owns the storage. + #[cfg_attr(not(feature = "turso"), allow(dead_code))] + pub(crate) fn open_with(builder: Builder) -> Result { + Ok(Self { + store: TursoStore::open(builder)?, + storage: Storage::Caller, + }) + } + + /// Adopt an already-open connection. The keyring creates and owns its + /// `secrets` table and leaves every other table alone. + #[cfg_attr(not(feature = "turso"), allow(dead_code))] + pub(crate) fn adopt(conn: Connection) -> Result { + Ok(Self { + store: TursoStore::adopt(conn)?, + storage: Storage::Caller, }) } - /// Path of the main database file. + /// Copy every secret into another keyring's store. + pub(crate) fn copy_into(&self, dst: &TursoFile) -> Result<()> { + self.store.copy_into(&dst.store) + } + + /// Path of the main database file, when cryptex opened it itself. #[cfg(feature = "turso")] - pub(crate) fn db_path(&self) -> &Path { - &self.db_path + pub(crate) fn db_path(&self) -> Option<&Path> { + match &self.storage { + Storage::File { db_path, .. } => Some(db_path), + Storage::Caller => None, + } } /// Re-encrypt the keyring under the configuration produced by `builder`. @@ -163,11 +273,22 @@ impl TursoFile { /// Secrets are copied into a temporary database opened with the new /// configuration, which then atomically replaces the original. The /// original is untouched if anything fails before the rename. + /// + /// Only a keyring that cryptex opened from a path can be rekeyed; a + /// keyring adopted from a caller's connection or IO must be rekeyed by + /// the caller, who owns the storage. pub(crate) fn rekey(self, builder: B) -> Result where B: Fn(&str) -> Builder, { - let tmp_path = self.db_path.with_extension("cryptex-rekey-tmp"); + let Storage::File { db_path, _lock } = self.storage else { + return Err(KeyRingError::GeneralError { + msg: "rekey is only available for a keyring cryptex opened from a path; \ + copy the secrets into a new keyring instead" + .to_string(), + }); + }; + let tmp_path = db_path.with_extension("cryptex-rekey-tmp"); remove_db_files(&tmp_path)?; let copied = TursoStore::open(builder(path_str(&tmp_path)?)).and_then(|tmp| { @@ -180,12 +301,7 @@ impl TursoFile { } self.store.checkpoint()?; - let Self { - store, - db_path, - _lock, - } = self; - drop(store); + drop(self.store); remove_file_if_exists(&sibling_path(&tmp_path, "-wal"))?; remove_file_if_exists(&sibling_path(&db_path, "-wal"))?; fs::rename(&tmp_path, &db_path).map_err(|e| KeyRingError::GeneralError { @@ -195,12 +311,18 @@ impl TursoFile { let store = TursoStore::open(builder(path_str(&db_path)?))?; Ok(Self { store, - db_path, - _lock, + storage: Storage::File { db_path, _lock }, }) } } +impl TursoFile { + /// Every id in the keyring, in order. + pub(crate) fn ids(&self) -> Result> { + self.store.ids() + } +} + impl SecretStore for TursoFile { fn get(&self, id: &str) -> Result { self.store.get(id) @@ -243,15 +365,15 @@ mod tests { #[test] fn block_on_drives_pending_future() { let mut polled = false; - let fut = std::future::poll_fn(|cx| { + let fut = std::future::poll_fn::, _>(|cx| { if polled { - std::task::Poll::Ready(7) + std::task::Poll::Ready(Ok(7)) } else { polled = true; cx.waker().wake_by_ref(); std::task::Poll::Pending } }); - assert_eq!(block_on(fut), 7); + assert_eq!(block_on(fut).unwrap(), 7); } } diff --git a/src/keyring/turso_encrypted_io.rs b/src/keyring/turso_encrypted_io.rs index 418a448..e686e0c 100644 --- a/src/keyring/turso_encrypted_io.rs +++ b/src/keyring/turso_encrypted_io.rs @@ -23,9 +23,10 @@ use std::sync::{Arc, Mutex, MutexGuard}; use super::file_common::{self, derive_key_32, file_keyring, private_open_options}; use super::page_cipher::{self, ActiveCipher}; +use super::page_store::PageStore; use super::turso_common::TursoFile; -pub use super::page_cipher::CipherAlgorithm; +pub use super::cipher::CipherAlgorithm; /// Connection parameters for [`TursoEncryptedIoKeyring`]. /// @@ -112,14 +113,14 @@ impl TursoFileIo for EncryptedFile { fn pread(&self, pos: u64, c: Completion) -> TursoResult { let mut file = self.file()?; - let available = page_cipher::logical_size(&file) + let available = page_cipher::logical_size(&*file) .map_err(|e| io_error(e, "pread"))? .saturating_sub(pos); let read = { let buf = c.as_read().buf().as_mut_slice(); let n = buf.len().min(to_usize(available)?); self.cipher - .read_at(&mut file, to_usize(pos)?, &mut buf[..n]) + .read_at(&mut *file, to_usize(pos)?, &mut buf[..n]) .map_err(|e| io_error(e, "pread"))? }; c.complete(to_i32(read)?); @@ -136,7 +137,7 @@ impl TursoFileIo for EncryptedFile { } fn sync(&self, c: Completion, _sync_type: FileSyncType) -> TursoResult { - self.file()?.sync_all().map_err(|e| io_error(e, "sync"))?; + self.file()?.sync().map_err(|e| io_error(e, "sync"))?; c.complete(0); Ok(c) } @@ -146,7 +147,7 @@ impl TursoFileIo for EncryptedFile { } fn truncate(&self, len: u64, c: Completion) -> TursoResult { - page_cipher::truncate(&*self.file()?, to_usize(len)?) + page_cipher::truncate(&mut *self.file()?, to_usize(len)?) .map_err(|e| io_error(e, "truncate"))?; c.complete(0); Ok(c) diff --git a/src/keyring/turso_web.rs b/src/keyring/turso_web.rs new file mode 100644 index 0000000..f284a77 --- /dev/null +++ b/src/keyring/turso_web.rs @@ -0,0 +1,310 @@ +/* + Copyright Michael Lodder. All Rights Reserved. + SPDX-License-Identifier: Apache-2.0 +*/ +//! A Turso [`IO`] whose files live in process memory, for browsers and for +//! tests. +//! +//! Turso opens the database and its WAL as ordinary files. This backend keeps +//! each one in a [`PageStore`] buffer, so a whole database can be copied out +//! as one blob ([`WebIo::snapshot`]), stored somewhere durable such as +//! IndexedDB, and put back later ([`WebIo::restore`]). OPFS uses the same +//! shape with a synchronous access handle in place of the buffer. +//! +//! Reads and writes complete in place, so Turso never needs to park a thread — +//! which a wasm build cannot do. +//! +//! [`IO`]: ::turso::core::IO + +use super::page_store::{MemPages, PageStore}; +use super::web_time::WebClock; +use crate::Result; +use crate::error::KeyRingError; +use ::turso::core::io::FileId; +use ::turso::core::io::FileSyncType; +use ::turso::core::{ + Buffer, Clock, Completion, File as TursoFileIo, IO, LimboError, MonotonicInstant, OpenFlags, + WallClockInstant, io_error, +}; +use std::collections::HashMap; +use std::sync::{Arc, Mutex, MutexGuard}; + +type TursoResult = std::result::Result; + +const SNAPSHOT_MAGIC: &[u8; 10] = b"CRYPTEX-IO"; +const SNAPSHOT_VERSION: u8 = 1; + +/// Files held by [`WebIo`], keyed by the path Turso opened them with. +pub(crate) struct WebIo { + files: Mutex>>, + /// Distinguishes this IO in Turso's process-wide database registry. + /// + /// That registry is keyed by `file_id`, so two IOs holding a same-named + /// file would otherwise share one open database, including its encryption + /// key: one keyring would silently read and write the other's secrets. + instance: String, +} + +impl WebIo { + /// Create an empty IO backed by process memory. + pub(crate) fn in_memory() -> Arc { + Arc::new(Self { + files: Mutex::new(HashMap::new()), + instance: new_instance(), + }) + } + + /// The path of the database file in this IO, if it has one. + pub(crate) fn db_path(&self) -> Option { + let files = self.files.lock().ok()?; + files.keys().find(|path| path.ends_with(".db3")).cloned() + } + + /// Copy every file into one blob. + /// + /// Layout: `magic (10) | version (1) | count (u32 LE)` then, per file in + /// path order, `path_len (u32 LE) | path | len (u64 LE) | bytes`. + pub(crate) fn snapshot(&self) -> Result> { + let files = self.files()?; + let mut entries: Vec<(&String, &Arc)> = files.iter().collect(); + entries.sort_by(|a, b| a.0.cmp(b.0)); + + let mut out = Vec::new(); + out.extend_from_slice(SNAPSHOT_MAGIC); + out.push(SNAPSHOT_VERSION); + out.extend_from_slice(&(entries.len() as u32).to_le_bytes()); + for (path, file) in entries { + let store = file.store().map_err(|_| poisoned())?; + let size = store + .len() + .map_err(|e| KeyRingError::GeneralError { msg: e.to_string() })?; + out.extend_from_slice(&(path.len() as u32).to_le_bytes()); + out.extend_from_slice(path.as_bytes()); + out.extend_from_slice(&size.to_le_bytes()); + out.extend_from_slice(store.as_slice()); + } + Ok(out) + } + + /// Rebuild an IO from a blob produced by [`WebIo::snapshot`]. + pub(crate) fn restore(bytes: &[u8]) -> Result> { + let malformed = || KeyRingError::GeneralError { + msg: "the keyring image is not a cryptex database snapshot".to_string(), + }; + let mut rest = bytes; + if rest.len() < 11 || &rest[..10] != SNAPSHOT_MAGIC { + return Err(malformed()); + } + rest = &rest[10..]; + if rest[0] != SNAPSHOT_VERSION { + return Err(malformed()); + } + rest = &rest[1..]; + let (count, tail) = take::<4>(rest).ok_or_else(malformed)?; + rest = tail; + let count = u32::from_le_bytes(count); + // A database is the `.db3` file and the WAL beside it. A header + // claiming more is not a snapshot of ours, and sizing anything from it + // would let a fifteen-byte input ask for gigabytes. + if count > 2 { + return Err(malformed()); + } + // Open the image under a path of its own: the one in the image was + // chosen in another session, where the same path may still be open. + let base = unique_db_path(); + let mut files = HashMap::new(); + for _ in 0..count { + let (len, tail) = take::<4>(rest).ok_or_else(malformed)?; + rest = tail; + let path_len = u32::from_le_bytes(len) as usize; + if rest.len() < path_len { + return Err(malformed()); + } + let path = String::from_utf8(rest[..path_len].to_vec()).map_err(|_| malformed())?; + rest = &rest[path_len..]; + + let (len, tail) = take::<8>(rest).ok_or_else(malformed)?; + rest = tail; + let data_len = usize::try_from(u64::from_le_bytes(len)).map_err(|_| malformed())?; + if rest.len() < data_len { + return Err(malformed()); + } + let store = MemPages::from_vec(rest[..data_len].to_vec()); + rest = &rest[data_len..]; + let path = if path.ends_with("-wal") { + format!("{base}-wal") + } else { + base.clone() + }; + files.insert(path, Arc::new(WebFile::new(store))); + } + Ok(Arc::new(Self { + files: Mutex::new(files), + instance: new_instance(), + })) + } + + fn files(&self) -> Result>>> { + self.files.lock().map_err(|_| poisoned()) + } +} + +/// A database path no other in-memory keyring uses. +pub(crate) fn unique_db_path() -> String { + use std::sync::atomic::{AtomicU64, Ordering}; + + static NEXT: AtomicU64 = AtomicU64::new(1); + format!("cryptex-{}.db3", NEXT.fetch_add(1, Ordering::Relaxed)) +} + +/// An IO id no other IO in this process has. +pub(super) fn new_instance() -> String { + use std::sync::atomic::{AtomicU64, Ordering}; + + static NEXT: AtomicU64 = AtomicU64::new(1); + format!("io-{}", NEXT.fetch_add(1, Ordering::Relaxed)) +} + +fn poisoned() -> KeyRingError { + KeyRingError::GeneralError { + msg: "the in-memory database lock is poisoned".to_string(), + } +} + +fn take(bytes: &[u8]) -> Option<([u8; N], &[u8])> { + let head = bytes.get(..N)?; + let mut out = [0u8; N]; + out.copy_from_slice(head); + Some((out, &bytes[N..])) +} + +impl IO for WebIo { + fn open_file( + &self, + path: &str, + flags: OpenFlags, + _direct: bool, + ) -> TursoResult> { + let mut files = self + .files + .lock() + .map_err(|_| LimboError::InternalError("database lock poisoned".to_string()))?; + if let Some(file) = files.get(path) { + let existing: Arc = Arc::clone(file); + return Ok(existing); + } + if !flags.contains(OpenFlags::Create) { + return Err(io_error( + std::io::Error::from(std::io::ErrorKind::NotFound), + "open_file", + )); + } + let file = Arc::new(WebFile::new(MemPages::new())); + files.insert(path.to_string(), Arc::clone(&file)); + let opened: Arc = file; + Ok(opened) + } + + fn remove_file(&self, path: &str) -> TursoResult<()> { + let mut files = self + .files + .lock() + .map_err(|_| LimboError::InternalError("database lock poisoned".to_string()))?; + files.remove(path); + Ok(()) + } + + fn file_id(&self, path: &str) -> TursoResult { + Ok(FileId::from_path_hash(&format!( + "{}/{}", + self.instance, path + ))) + } + + fn is_memory(&self) -> bool { + true + } +} + +impl Clock for WebIo { + fn current_time_monotonic(&self) -> MonotonicInstant { + WebClock.current_time_monotonic() + } + + fn current_time_wall_clock(&self) -> WallClockInstant { + WebClock.current_time_wall_clock() + } +} + +struct WebFile { + store: Mutex, +} + +impl WebFile { + fn new(store: MemPages) -> Self { + Self { + store: Mutex::new(store), + } + } + + fn store(&self) -> TursoResult> { + self.store + .lock() + .map_err(|_| LimboError::InternalError("database file lock poisoned".to_string())) + } +} + +fn to_i32(n: usize) -> TursoResult { + i32::try_from(n).map_err(|_| LimboError::InternalError("I/O length overflows i32".into())) +} + +impl TursoFileIo for WebFile { + // A single opener per database is enforced by the caller, as in the + // browser storage and IndexedDB stores. + fn lock_file(&self, _exclusive: bool) -> TursoResult<()> { + Ok(()) + } + + fn unlock_file(&self) -> TursoResult<()> { + Ok(()) + } + + fn pread(&self, pos: u64, c: Completion) -> TursoResult { + let mut store = self.store()?; + let size = store.len().map_err(|e| io_error(e, "pread"))?; + let buf = c.as_read().buf().as_mut_slice(); + let n = (buf.len() as u64).min(size.saturating_sub(pos)) as usize; + store + .read_exact_at(pos, &mut buf[..n]) + .map_err(|e| io_error(e, "pread"))?; + c.complete(to_i32(n)?); + Ok(c) + } + + fn pwrite(&self, pos: u64, buffer: Arc, c: Completion) -> TursoResult { + let mut store = self.store()?; + store + .write_all_at(pos, buffer.as_slice()) + .map_err(|e| io_error(e, "pwrite"))?; + c.complete(to_i32(buffer.as_slice().len())?); + Ok(c) + } + + fn sync(&self, c: Completion, _sync_type: FileSyncType) -> TursoResult { + self.store()?.sync().map_err(|e| io_error(e, "sync"))?; + c.complete(0); + Ok(c) + } + + fn size(&self) -> TursoResult { + self.store()?.len().map_err(|e| io_error(e, "size")) + } + + fn truncate(&self, len: u64, c: Completion) -> TursoResult { + self.store()? + .set_len(len) + .map_err(|e| io_error(e, "truncate"))?; + c.complete(0); + Ok(c) + } +} diff --git a/src/keyring/web_storage.rs b/src/keyring/web_storage.rs new file mode 100644 index 0000000..2f436f8 --- /dev/null +++ b/src/keyring/web_storage.rs @@ -0,0 +1,268 @@ +/* + Copyright Michael Lodder. All Rights Reserved. + SPDX-License-Identifier: Apache-2.0 +*/ +//! A keyring kept in browser `localStorage`. +//! +//! The whole keyring is an encrypted image ([`MemoryKeyring::export`]) that is +//! rewritten whenever a secret changes. It is the simplest browser backend: +//! no worker and no asynchronous API, so it fits code that must stay +//! synchronous, such as an `onclick` handler. +//! +//! ```no_run +//! # use cryptex::web_storage::WebStorageKeyring; +//! # use cryptex::KeyRing; +//! let mut keyring = WebStorageKeyring::with_params( +//! &"password=mysecret salt=0okm9ijn8uhb7ygv".parse()?, +//! Some("settings"), +//! )?; +//! keyring.set_secret("api-token", b"secret")?; +//! # Ok::<(), Box>(()) +//! ``` +//! +//! `localStorage` belongs to the page, not to the worker: a web worker has no +//! `localStorage` at all. Use the [`indexeddb`](crate::indexeddb) store from a +//! worker instead. +//! +//! Every script on the origin can read `localStorage`, and browsers evict it +//! under storage pressure unless the site has been granted persistent storage +//! ([`request_persistent_storage`]). The image is encrypted, so what a script +//! gets is ciphertext. +//! +//! There is no cross-tab lock here: the whole image is rewritten on every +//! change, so two tabs on one name would lose each other's secrets. Take the +//! `cryptex:` Web Lock first, as the JavaScript `Keyring` does, or give +//! each tab its own name. + +use super::cipher::CipherAlgorithm; +use super::file_common; +use super::memory::MemoryKeyring; +use crate::KeyRingSecret; +use crate::error::KeyRingError; +use crate::{DynKeyRing, NewKeyRing, Result}; +use wasm_bindgen::JsCast; + +/// Connection parameters for [`WebStorageKeyring`]. +pub type ConnectionParams = file_common::ConnectionParams; + +/// `localStorage` key used when no name is given. +pub const DEFAULT_NAME: &str = "cryptex"; + +/// The encrypted image of a keyring, kept in one `localStorage` entry. +/// +/// The image is the same blob [`MemoryKeyring::export`] and +/// [`TursoKeyring::export`](crate::turso::TursoKeyring::export) produce, so a +/// Turso keyring can use this store too. +pub struct LocalStorageImage { + entry: String, +} + +impl LocalStorageImage { + /// Name the entry for a keyring called `name` (default [`DEFAULT_NAME`]). + pub fn new(name: Option<&str>) -> Result { + Ok(Self { + entry: entry_name(name), + }) + } + + /// The `localStorage` key this image is stored under. + pub fn entry(&self) -> &str { + &self.entry + } + + /// Read the stored image, if there is one. + pub fn load(&self) -> Result>> { + let storage = storage()?; + match storage.get_item(&self.entry).map_err(js_error)? { + Some(encoded) => hex::decode(encoded).map(Some).map_err(|_| invalid_blob()), + None => Ok(None), + } + } + + /// Write an image, replacing any previous one. + pub fn save(&self, image: &[u8]) -> Result<()> { + storage()? + .set_item(&self.entry, &hex::encode(image)) + .map_err(|e| match js_error(e) { + KeyRingError::GeneralError { msg } => KeyRingError::GeneralError { + msg: format!("unable to store the keyring in localStorage: {msg}"), + }, + other => other, + }) + } + + /// Remove the stored image. + pub fn delete(&self) -> Result<()> { + storage()?.remove_item(&self.entry).map_err(js_error) + } +} + +/// A keyring whose image lives in `localStorage`. +pub struct WebStorageKeyring { + inner: MemoryKeyring, + image: LocalStorageImage, +} + +impl WebStorageKeyring { + /// Open the keyring called `name` (default [`DEFAULT_NAME`]), creating it + /// on first use. + /// + /// A stored image is decrypted with the password or key in `params`; a + /// wrong one returns [`KeyRingError::AccessDenied`]. + pub fn with_params(params: &ConnectionParams, name: Option<&str>) -> Result { + let image = LocalStorageImage::new(name)?; + let inner = match image.load()? { + Some(blob) => MemoryKeyring::import(&blob, password_or_key(params)), + None => MemoryKeyring::with_params(params), + }?; + Ok(Self { inner, image }) + } + + /// The `localStorage` key this keyring is stored under. + pub fn entry(&self) -> &str { + self.image.entry() + } + + /// Copy the encrypted image out, e.g. to move it to another backend. + pub fn export(&self) -> Result> { + self.inner.export() + } + + /// Re-encrypt under new connection parameters and store the result. + pub fn rekey(&mut self, params: &ConnectionParams) -> Result<()> { + self.inner.rekey(params)?; + self.persist() + } + + /// The cipher the stored image is sealed with. + pub fn cipher(&self) -> CipherAlgorithm { + self.inner.cipher() + } + + /// Remove the stored image, leaving this keyring's contents in memory. + pub fn forget(&self) -> Result<()> { + self.image.delete() + } + + fn persist(&self) -> Result<()> { + self.image.save(&self.inner.export()?) + } +} + +impl DynKeyRing for WebStorageKeyring { + fn get_secret(&mut self, id: &str) -> Result { + self.inner.get_secret(id) + } + + fn set_secret(&mut self, id: &str, secret: &[u8]) -> Result<()> { + self.inner.set_secret(id, secret)?; + self.persist() + } + + fn delete_secret(&mut self, id: &str) -> Result<()> { + self.inner.delete_secret(id)?; + self.persist() + } +} + +impl NewKeyRing for WebStorageKeyring { + fn new>(lock_key: S) -> Result { + let params = lock_key.as_ref().parse::()?; + Self::with_params(¶ms, None) + } +} + +fn entry_name(name: Option<&str>) -> String { + format!("cryptex:{}", name.unwrap_or(DEFAULT_NAME)) +} + +fn password_or_key(params: &ConnectionParams) -> &[u8] { + if params.key.is_empty() { + ¶ms.password + } else { + ¶ms.key + } +} + +/// Ask the browser not to evict this origin's storage under pressure. +/// +/// Browsers grant this silently, prompt, or refuse; the answer is returned as +/// given. +pub async fn request_persistent_storage() -> Result { + let storage_manager = js_sys::Reflect::get( + &js_sys::global(), + &wasm_bindgen::JsValue::from_str("navigator"), + ) + .ok() + .and_then(|navigator| { + js_sys::Reflect::get(&navigator, &wasm_bindgen::JsValue::from_str("storage")).ok() + }) + .ok_or_else(|| KeyRingError::GeneralError { + msg: "this browser has no Storage Manager API".to_string(), + })?; + let persist = js_sys::Reflect::get( + &storage_manager, + &wasm_bindgen::JsValue::from_str("persist"), + ) + .map_err(js_error)? + .dyn_into::() + .map_err(|_| KeyRingError::GeneralError { + msg: "this browser cannot persist storage".to_string(), + })?; + let granted = persist + .call0(&storage_manager) + .map_err(js_error)? + .dyn_into::() + .map_err(js_error)?; + let value = wasm_bindgen_futures::JsFuture::from(granted) + .await + .map_err(js_error)?; + Ok(value.as_bool().unwrap_or(false)) +} + +/// Names of every keyring this origin keeps in `localStorage`. +/// +/// Reads the entry names only, never the images. A keyring entry is +/// `cryptex:`, the key [`LocalStorageImage`] writes for that name. +pub fn list_names() -> Result> { + const PREFIX: &str = "cryptex:"; + + let storage = storage()?; + let length = storage.length().map_err(js_error)?; + let mut names = Vec::new(); + for index in 0..length { + if let Some(name) = storage + .key(index) + .map_err(js_error)? + .and_then(|key| key.strip_prefix(PREFIX).map(str::to_string)) + { + names.push(name); + } + } + names.sort(); + Ok(names) +} + +fn storage() -> Result { + let window = web_sys::window().ok_or_else(|| KeyRingError::GeneralError { + msg: "localStorage is not available here: it exists only on a page, not in a worker" + .to_string(), + })?; + window + .local_storage() + .map_err(js_error)? + .ok_or_else(|| KeyRingError::GeneralError { + msg: "this browser blocks localStorage for the origin; cookies or private mode may be disabled" + .to_string(), + }) +} + +fn js_error(value: wasm_bindgen::JsValue) -> KeyRingError { + KeyRingError::from(value) +} + +fn invalid_blob() -> KeyRingError { + KeyRingError::AccessDenied { + msg: "the stored keyring is corrupt: its image could not be decoded".to_string(), + } +} diff --git a/src/keyring/web_time.rs b/src/keyring/web_time.rs new file mode 100644 index 0000000..ccff761 --- /dev/null +++ b/src/keyring/web_time.rs @@ -0,0 +1,79 @@ +/* + Copyright Michael Lodder. All Rights Reserved. + SPDX-License-Identifier: Apache-2.0 +*/ +//! Clocks for Turso I/O backends that run in a browser. +//! +//! Turso's own clock calls `Instant::now`, which panics on +//! `wasm32-unknown-unknown`: the platform has no monotonic clock behind it. +//! `performance.now()` is the closest equivalent and, unlike `Date.now()`, +//! only moves forward. WASI builds have `std::time` and use it. + +use ::turso::core::{Clock, MonotonicInstant, WallClockInstant}; + +/// A [`Clock`] backed by the JavaScript runtime. +pub(crate) struct WebClock; + +impl Clock for WebClock { + fn current_time_monotonic(&self) -> MonotonicInstant { + MonotonicInstant::from_nanos(monotonic_nanos()) + } + + fn current_time_wall_clock(&self) -> WallClockInstant { + wall_clock_now() + } +} + +/// Milliseconds since the time origin, from `performance.now()`. +/// +/// A worker has no `window`, so the value is read off the global object. +#[cfg(all(target_family = "wasm", target_os = "unknown"))] +fn performance_millis() -> Option { + use wasm_bindgen::{JsCast, JsValue}; + + let global = js_sys::global(); + let performance = js_sys::Reflect::get(&global, &JsValue::from_str("performance")).ok()?; + let now = js_sys::Reflect::get(&performance, &JsValue::from_str("now")).ok()?; + let now: js_sys::Function = now.dyn_into().ok()?; + now.call0(&performance).ok()?.as_f64() +} + +#[cfg(all(target_family = "wasm", target_os = "unknown"))] +fn monotonic_nanos() -> u128 { + // Fall back to the wall clock where `performance` is missing. + let millis = performance_millis().unwrap_or_else(js_sys::Date::now); + (millis * 1_000_000.0) as u128 +} + +#[cfg(not(all(target_family = "wasm", target_os = "unknown")))] +fn monotonic_nanos() -> u128 { + use std::sync::OnceLock; + use std::time::Instant; + + static EPOCH: OnceLock = OnceLock::new(); + EPOCH.get_or_init(Instant::now).elapsed().as_nanos() +} + +#[cfg(all(target_family = "wasm", target_os = "unknown"))] +fn wall_clock_now() -> WallClockInstant { + let millis = js_sys::Date::now(); + let secs = (millis / 1000.0).floor(); + let micros = ((millis - secs * 1000.0) * 1000.0).round() as u32; + WallClockInstant { + secs: secs as i64, + micros: micros.min(999_999), + } +} + +#[cfg(not(all(target_family = "wasm", target_os = "unknown")))] +fn wall_clock_now() -> WallClockInstant { + use std::time::{SystemTime, UNIX_EPOCH}; + + let since_epoch = SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap_or_default(); + WallClockInstant { + secs: since_epoch.as_secs() as i64, + micros: since_epoch.subsec_micros(), + } +} diff --git a/src/keyring/windows.rs b/src/keyring/windows.rs index 46e6910..a4ecffa 100644 --- a/src/keyring/windows.rs +++ b/src/keyring/windows.rs @@ -256,8 +256,8 @@ unsafe fn get_credentials( let secret = unsafe { std::slice::from_raw_parts(blob, blob_len) }; let mut secret_u16 = vec![0u16; blob_len / 2]; - for (i, chunk) in secret.chunks_exact(2).enumerate() { - secret_u16[i] = u16::from_le_bytes([chunk[0], chunk[1]]); + for (i, chunk) in secret.as_chunks::<2>().0.iter().enumerate() { + secret_u16[i] = u16::from_le_bytes(*chunk); } let t = match String::from_utf16(secret_u16.as_slice()).map(|pass| pass.to_string()) { Ok(s) => s, diff --git a/src/lib.rs b/src/lib.rs index 1e662a6..a3a96a5 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -20,6 +20,7 @@ pub use keyring::encrypted_vfs; #[cfg(any( feature = "file", feature = "encrypted-vfs", + feature = "memory", feature = "turso", feature = "turso-encrypted-io" ))] @@ -33,6 +34,10 @@ pub use keyring::encrypted_vfs; ))) )] pub use keyring::file_common; +#[cfg(feature = "memory")] +#[cfg_attr(docsrs, doc(cfg(feature = "memory")))] +#[cfg(feature = "indexeddb")] +pub use keyring::indexeddb; #[cfg(any(feature = "yubihsm-usb", feature = "yubihsm-http"))] #[cfg_attr( docsrs, @@ -48,6 +53,13 @@ pub use keyring::linux; #[cfg(all(target_os = "macos", feature = "macos-keychain"))] #[cfg_attr(docsrs, doc(cfg(all(target_os = "macos", feature = "macos-keychain"))))] pub use keyring::macos; +#[cfg(feature = "memory")] +pub use keyring::memory; +#[cfg(feature = "web-storage")] +pub use keyring::web_storage; + +#[cfg(feature = "js")] +mod wasm; #[cfg(feature = "file")] #[cfg_attr(docsrs, doc(cfg(feature = "file")))] pub use keyring::sqlcipher; @@ -70,6 +82,9 @@ pub use keyring::windows; )] pub use keyring::yubihsm; pub use keyring::*; +#[cfg(feature = "js")] +#[cfg_attr(docsrs, doc(cfg(feature = "js")))] +pub use wasm::{Keyring, request_persistent_storage, stored_keyrings}; #[cfg(any( all(target_os = "macos", feature = "macos-keychain"), diff --git a/src/main.rs b/src/main.rs index 9a38c1d..6ab6d95 100644 --- a/src/main.rs +++ b/src/main.rs @@ -11,514 +11,25 @@ trivial_numeric_casts )] -use clap::{Arg, ArgMatches, Command}; -use colored::Colorize; +//! The `cryptex` command-line tool. +//! +//! The CLI talks to OS keyrings, files and YubiHSM devices, none of which +//! exist in a browser or WASI sandbox, so a wasm build reports that instead of +//! exposing commands that cannot work. Use the library, or the JS bindings on +//! wasm. -// ── Imports used only when at least one active backend is compiled in ───────── - -#[cfg(any( - all(target_os = "macos", feature = "macos-keychain"), - all(target_os = "windows", feature = "windows-credentials"), - all(target_os = "linux", feature = "linux-secret-service"), - feature = "yubihsm-usb", - feature = "yubihsm-http", -))] -use std::fs::File; - -#[cfg(any( - all(target_os = "macos", feature = "macos-keychain"), - all(target_os = "windows", feature = "windows-credentials"), - all(target_os = "linux", feature = "linux-secret-service"), - feature = "yubihsm-usb", - feature = "yubihsm-http", -))] -use std::io::{self, IsTerminal, Read, Write}; - -#[cfg(any( - all(target_os = "macos", feature = "macos-keychain"), - all(target_os = "windows", feature = "windows-credentials"), - all(target_os = "linux", feature = "linux-secret-service"), - feature = "yubihsm-usb", - feature = "yubihsm-http", -))] -use std::path::PathBuf; - -#[cfg(any( - all(target_os = "macos", feature = "macos-keychain"), - all(target_os = "windows", feature = "windows-credentials"), - all(target_os = "linux", feature = "linux-secret-service"), - feature = "yubihsm-usb", - feature = "yubihsm-http", -))] -use zeroize::Zeroize; - -// ── Shared backend imports ──────────────────────────────────────────────────── - -#[cfg(any( - all(target_os = "macos", feature = "macos-keychain"), - all(target_os = "windows", feature = "windows-credentials"), - all(target_os = "linux", feature = "linux-secret-service"), - feature = "yubihsm-usb", - feature = "yubihsm-http", -))] -use cryptex::{KeyRing, KeyRingSecret}; - -#[cfg(any( - all(target_os = "macos", feature = "macos-keychain"), - all(target_os = "windows", feature = "windows-credentials"), - all(target_os = "linux", feature = "linux-secret-service"), - feature = "yubihsm-usb", - feature = "yubihsm-http", -))] -use std::collections::BTreeMap; - -// ── OS keyring ──────────────────────────────────────────────────────────────── - -#[cfg(any( - all(target_os = "macos", feature = "macos-keychain"), - all(target_os = "windows", feature = "windows-credentials"), - all(target_os = "linux", feature = "linux-secret-service"), -))] -use cryptex::{ListKeyRing, PeekableKeyRing, get_os_keyring}; - -#[cfg(all(target_os = "macos", feature = "macos-keychain"))] -use cryptex::macos::MacOsKeyRing as OsKeyRing; - -#[cfg(all(target_os = "linux", feature = "linux-secret-service"))] -use cryptex::linux::LinuxOsKeyRing as OsKeyRing; - -#[cfg(all(target_os = "windows", feature = "windows-credentials"))] -use cryptex::windows::WindowsOsKeyRing as OsKeyRing; - -// ── YubiHSM ─────────────────────────────────────────────────────────────────── - -#[cfg(any(feature = "yubihsm-usb", feature = "yubihsm-http"))] -use cryptex::NewKeyRing; - -#[cfg(any(feature = "yubihsm-usb", feature = "yubihsm-http"))] -use cryptex::yubihsm::YubiHsmKeyRing; - -// ───────────────────────────────────────────────────────────────────────────── +#[cfg(not(target_family = "wasm"))] +mod native; +#[cfg(not(target_family = "wasm"))] fn main() { - let matches = Command::new("cryptex") - .version(env!("CARGO_PKG_VERSION")) - .author("Michael Lodder") - .about("Platform-independent CLI for storing and retrieving secrets from secure keyrings") - .arg( - Arg::new("keyring") - .long("keyring") - .short('k') - .value_name("TYPE") - .global(true) - .help("Keyring backend to use: 'os' (default) or 'yubihsm'"), - ) - .subcommand( - Command::new("get") - .about("Retrieve a secret by ID") - .arg( - Arg::new("SERVICE") - .help("Service name (OS) or connection string (yubihsm)") - .required(true) - .index(1), - ) - .arg( - Arg::new("ID") - .help("The secret ID. If omitted, read from STDIN") - .required(false) - .index(2), - ), - ) - .subcommand( - Command::new("set") - .about("Save a secret by ID") - .arg( - Arg::new("SERVICE") - .help("Service name (OS) or connection string (yubihsm)") - .required(true) - .index(1), - ) - .arg( - Arg::new("ID") - .help("The secret ID") - .required(true) - .index(2), - ) - .arg( - Arg::new("SECRET") - .help("The secret value. If omitted, read from STDIN") - .required(false) - .index(3), - ), - ) - .subcommand( - Command::new("delete") - .about("Delete a secret by ID") - .arg( - Arg::new("SERVICE") - .help("Service name (OS) or connection string (yubihsm)") - .required(true) - .index(1), - ) - .arg( - Arg::new("ID") - .help("The secret ID. If omitted, read from STDIN") - .required(false) - .index(2), - ), - ) - .subcommand( - Command::new("peek") - .about("Inspect OS keyring entries without full retrieval (OS backends only)") - .arg( - Arg::new("ID") - .help("Filter as comma-separated name=value pairs (e.g. service=aws,account=key)") - .required(false) - .index(1), - ), - ) - .subcommand( - Command::new("list") - .about("List secret IDs. For 'os': lists all. For 'yubihsm': requires a connection string.") - .arg( - Arg::new("SERVICE") - .help("Connection string (required for 'yubihsm')") - .required(false) - .index(1), - ), - ) - .get_matches(); - - dispatch(&matches); -} - -fn dispatch(matches: &ArgMatches) { - let keyring_type = matches - .get_one::("keyring") - .map(|s| s.as_str()) - .unwrap_or("os"); - - match keyring_type { - "yubihsm" => { - #[cfg(any(feature = "yubihsm-usb", feature = "yubihsm-http"))] - dispatch_yubihsm(matches); - #[cfg(not(any(feature = "yubihsm-usb", feature = "yubihsm-http")))] - die::<()>( - "YubiHSM support is not compiled in. \ - Enable the 'yubihsm-usb' or 'yubihsm-http' feature.", - ); - } - "os" => dispatch_os(matches), - other => die::<()>(&format!( - "Unknown keyring type '{}'. Valid options: os, yubihsm", - other - )), - } + native::main(); } -// ── OS keyring dispatch ─────────────────────────────────────────────────────── - -#[cfg(any( - all(target_os = "macos", feature = "macos-keychain"), - all(target_os = "windows", feature = "windows-credentials"), - all(target_os = "linux", feature = "linux-secret-service"), -))] -fn dispatch_os(matches: &ArgMatches) { - if let Some(m) = matches.subcommand_matches("get") { - os_get(m); - } else if let Some(m) = matches.subcommand_matches("set") { - os_set(m); - } else if let Some(m) = matches.subcommand_matches("delete") { - os_delete(m); - } else if let Some(m) = matches.subcommand_matches("peek") { - os_peek(m); - } else if matches.subcommand_matches("list").is_some() { - os_list(); - } else { - die::<()>("Please specify a command: get | set | delete | peek | list"); - } -} - -#[cfg(not(any( - all(target_os = "macos", feature = "macos-keychain"), - all(target_os = "windows", feature = "windows-credentials"), - all(target_os = "linux", feature = "linux-secret-service"), -)))] -fn dispatch_os(_matches: &ArgMatches) { - die::<()>( - "No OS keyring available for this platform/feature combination. \ - Use '--keyring yubihsm' or enable a platform keyring feature.", +#[cfg(target_family = "wasm")] +fn main() { + eprintln!( + "cryptex CLI is not supported on wasm; use the cryptex library or its JS bindings instead" ); -} - -#[cfg(any( - all(target_os = "macos", feature = "macos-keychain"), - all(target_os = "windows", feature = "windows-credentials"), - all(target_os = "linux", feature = "linux-secret-service"), -))] -fn os_get(matches: &ArgMatches) { - let mut keyring = os_open(matches); - let id = get_id(matches, true); - let secret = keyring - .get_secret(&id) - .unwrap_or_else(|e| die::(&e.to_string())); - io::stdout().write_all(secret.as_slice()).unwrap(); - io::stdout().flush().unwrap(); -} - -#[cfg(any( - all(target_os = "macos", feature = "macos-keychain"), - all(target_os = "windows", feature = "windows-credentials"), - all(target_os = "linux", feature = "linux-secret-service"), -))] -fn os_set(matches: &ArgMatches) { - let mut keyring = os_open(matches); - let id = matches.get_one::("ID").map(|s| s.as_str()).unwrap(); - let mut secret = read_input(matches, "SECRET", true); - keyring - .set_secret(id, &secret) - .unwrap_or_else(|e| die::<()>(&format!("Failed: {}", e))); - secret.zeroize(); - println!("{}", "Success".green()); -} - -#[cfg(any( - all(target_os = "macos", feature = "macos-keychain"), - all(target_os = "windows", feature = "windows-credentials"), - all(target_os = "linux", feature = "linux-secret-service"), -))] -fn os_delete(matches: &ArgMatches) { - let mut keyring = os_open(matches); - let id = get_id(matches, true); - keyring - .delete_secret(&id) - .unwrap_or_else(|e| die::<()>(&e.to_string())); - println!("{}", "Success".green()); -} - -#[cfg(any( - all(target_os = "macos", feature = "macos-keychain"), - all(target_os = "windows", feature = "windows-credentials"), - all(target_os = "linux", feature = "linux-secret-service"), -))] -fn os_peek(matches: &ArgMatches) { - let id = get_id(matches, false); - let secrets = OsKeyRing::peek_secret(&id) - .unwrap_or_else(|e| die::>(&e.to_string())); - if secrets.len() == 1 && !id.is_empty() { - io::stdout().write_all(secrets[0].1.as_slice()).unwrap(); - io::stdout().flush().unwrap(); - println!(); - } else { - for s in secrets { - print!("{} -> ", s.0); - io::stdout().write_all(s.1.as_slice()).unwrap(); - println!(); - io::stdout().flush().unwrap(); - } - } -} - -#[cfg(any( - all(target_os = "macos", feature = "macos-keychain"), - all(target_os = "windows", feature = "windows-credentials"), - all(target_os = "linux", feature = "linux-secret-service"), -))] -fn os_list() { - let secret_names = OsKeyRing::list_secrets() - .unwrap_or_else(|e| die::>>(&e.to_string())); - for s in secret_names { - println!("{:?}", s); - } -} - -#[cfg(all(target_os = "linux", feature = "linux-secret-service"))] -fn os_open(matches: &ArgMatches) -> OsKeyRing<'_> { - let service = matches - .get_one::("SERVICE") - .map(|s| s.as_str()) - .unwrap(); - get_os_keyring(service).unwrap_or_else(|e| die(&format!("Unable to open OS keyring: {}", e))) -} - -#[cfg(any( - all(target_os = "macos", feature = "macos-keychain"), - all(target_os = "windows", feature = "windows-credentials"), -))] -fn os_open(matches: &ArgMatches) -> OsKeyRing { - let service = matches - .get_one::("SERVICE") - .map(|s| s.as_str()) - .unwrap(); - get_os_keyring(service).unwrap_or_else(|e| die(&format!("Unable to open OS keyring: {}", e))) -} - -// ── YubiHSM dispatch ───────────────────────────────────────────────────────── - -#[cfg(any(feature = "yubihsm-usb", feature = "yubihsm-http"))] -fn dispatch_yubihsm(matches: &ArgMatches) { - if let Some(m) = matches.subcommand_matches("get") { - yubihsm_get(m); - } else if let Some(m) = matches.subcommand_matches("set") { - yubihsm_set(m); - } else if let Some(m) = matches.subcommand_matches("delete") { - yubihsm_delete(m); - } else if let Some(m) = matches.subcommand_matches("list") { - yubihsm_list(m); - } else if matches.subcommand_matches("peek").is_some() { - die::<()>("The 'peek' command is not supported for the YubiHSM backend."); - } else { - die::<()>("Please specify a command: get | set | delete | list"); - } -} - -#[cfg(any(feature = "yubihsm-usb", feature = "yubihsm-http"))] -fn yubihsm_open(matches: &ArgMatches) -> YubiHsmKeyRing { - let connstr = matches - .get_one::("SERVICE") - .map(|s| s.as_str()) - .unwrap_or_else(|| die("A YubiHSM connection string is required as the SERVICE argument")); - YubiHsmKeyRing::new(connstr) - .unwrap_or_else(|e| die(&format!("Failed to connect to YubiHSM: {}", e))) -} - -#[cfg(any(feature = "yubihsm-usb", feature = "yubihsm-http"))] -fn yubihsm_get(matches: &ArgMatches) { - let mut ring = yubihsm_open(matches); - let id = get_id(matches, true); - let secret = ring - .get_secret(&id) - .unwrap_or_else(|e| die::(&e.to_string())); - io::stdout().write_all(secret.as_slice()).unwrap(); - io::stdout().flush().unwrap(); -} - -#[cfg(any(feature = "yubihsm-usb", feature = "yubihsm-http"))] -fn yubihsm_set(matches: &ArgMatches) { - let mut ring = yubihsm_open(matches); - let id = matches.get_one::("ID").map(|s| s.as_str()).unwrap(); - let mut secret = read_input(matches, "SECRET", true); - ring.set_secret(id, &secret) - .unwrap_or_else(|e| die::<()>(&format!("Failed: {}", e))); - secret.zeroize(); - println!("{}", "Success".green()); -} - -#[cfg(any(feature = "yubihsm-usb", feature = "yubihsm-http"))] -fn yubihsm_delete(matches: &ArgMatches) { - let mut ring = yubihsm_open(matches); - let id = get_id(matches, true); - ring.delete_secret(&id) - .unwrap_or_else(|e| die::<()>(&e.to_string())); - println!("{}", "Success".green()); -} - -#[cfg(any(feature = "yubihsm-usb", feature = "yubihsm-http"))] -fn yubihsm_list(matches: &ArgMatches) { - let ring = yubihsm_open(matches); - let entries = ring - .list_hsm_secrets() - .unwrap_or_else(|e| die::>>(&e.to_string())); - for entry in entries { - println!("{:?}", entry); - } -} - -// ── Shared helpers ──────────────────────────────────────────────────────────── - -#[cfg(any( - all(target_os = "macos", feature = "macos-keychain"), - all(target_os = "windows", feature = "windows-credentials"), - all(target_os = "linux", feature = "linux-secret-service"), - feature = "yubihsm-usb", - feature = "yubihsm-http", -))] -fn get_id(matches: &ArgMatches, read_stdin: bool) -> String { - let bytes = read_input(matches, "ID", read_stdin); - String::from_utf8(bytes).unwrap_or_else(|_| die("ID is not valid UTF-8")) -} - -#[cfg(any( - all(target_os = "macos", feature = "macos-keychain"), - all(target_os = "windows", feature = "windows-credentials"), - all(target_os = "linux", feature = "linux-secret-service"), - feature = "yubihsm-usb", - feature = "yubihsm-http", -))] -fn read_input(matches: &ArgMatches, name: &str, read_stdin: bool) -> Vec { - match matches.get_one::(name).map(|s| s.as_str()) { - Some(text) => match get_file(text) { - Some(file) => match File::open(file.as_path()) { - Ok(mut f) => read_stream(&mut f), - Err(_) => die(&format!("Unable to read file {}", file.to_str().unwrap())), - }, - None => text.as_bytes().to_vec(), - }, - None => { - if io::stdin().is_terminal() { - if read_stdin { - rpassword::prompt_password("Enter Secret: ") - .unwrap() - .as_bytes() - .to_vec() - } else { - Vec::new() - } - } else { - let mut f = io::stdin(); - read_stream(&mut f) - } - } - } -} - -#[cfg(any( - all(target_os = "macos", feature = "macos-keychain"), - all(target_os = "windows", feature = "windows-credentials"), - all(target_os = "linux", feature = "linux-secret-service"), - feature = "yubihsm-usb", - feature = "yubihsm-http", -))] -fn read_stream(f: &mut R) -> Vec { - let mut bytes = Vec::new(); - let mut buffer = [0u8; 4096]; - loop { - match f.read(&mut buffer) { - Ok(0) => break, - Ok(n) => bytes.extend_from_slice(&buffer[..n]), - Err(_) => break, - } - } - bytes -} - -#[cfg(any( - all(target_os = "macos", feature = "macos-keychain"), - all(target_os = "windows", feature = "windows-credentials"), - all(target_os = "linux", feature = "linux-secret-service"), - feature = "yubihsm-usb", - feature = "yubihsm-http", -))] -fn get_file(name: &str) -> Option { - let mut file = PathBuf::from(name); - if file.as_path().is_file() { - let metadata = file - .as_path() - .symlink_metadata() - .expect("symlink_metadata call failed"); - if metadata.file_type().is_symlink() { - match file.as_path().read_link() { - Ok(f) => file = f, - Err(_) => die::<()>(&format!("Can't read the symbolic link: {}", name)), - } - } - Some(file) - } else { - None - } -} - -fn die(final_message: &str) -> R { - eprintln!("{}", final_message.red()); std::process::exit(1); } diff --git a/src/native.rs b/src/native.rs new file mode 100644 index 0000000..d776f1c --- /dev/null +++ b/src/native.rs @@ -0,0 +1,516 @@ +/* + Copyright Michael Lodder. All Rights Reserved. + SPDX-License-Identifier: Apache-2.0 +*/ + +use clap::{Arg, ArgMatches, Command}; +use colored::Colorize; + +// ── Imports used only when at least one active backend is compiled in ───────── + +#[cfg(any( + all(target_os = "macos", feature = "macos-keychain"), + all(target_os = "windows", feature = "windows-credentials"), + all(target_os = "linux", feature = "linux-secret-service"), + feature = "yubihsm-usb", + feature = "yubihsm-http", +))] +use std::fs::File; + +#[cfg(any( + all(target_os = "macos", feature = "macos-keychain"), + all(target_os = "windows", feature = "windows-credentials"), + all(target_os = "linux", feature = "linux-secret-service"), + feature = "yubihsm-usb", + feature = "yubihsm-http", +))] +use std::io::{self, IsTerminal, Read, Write}; + +#[cfg(any( + all(target_os = "macos", feature = "macos-keychain"), + all(target_os = "windows", feature = "windows-credentials"), + all(target_os = "linux", feature = "linux-secret-service"), + feature = "yubihsm-usb", + feature = "yubihsm-http", +))] +use std::path::PathBuf; + +#[cfg(any( + all(target_os = "macos", feature = "macos-keychain"), + all(target_os = "windows", feature = "windows-credentials"), + all(target_os = "linux", feature = "linux-secret-service"), + feature = "yubihsm-usb", + feature = "yubihsm-http", +))] +use zeroize::Zeroize; + +// ── Shared backend imports ──────────────────────────────────────────────────── + +#[cfg(any( + all(target_os = "macos", feature = "macos-keychain"), + all(target_os = "windows", feature = "windows-credentials"), + all(target_os = "linux", feature = "linux-secret-service"), + feature = "yubihsm-usb", + feature = "yubihsm-http", +))] +use cryptex::{KeyRing, KeyRingSecret}; + +#[cfg(any( + all(target_os = "macos", feature = "macos-keychain"), + all(target_os = "windows", feature = "windows-credentials"), + all(target_os = "linux", feature = "linux-secret-service"), + feature = "yubihsm-usb", + feature = "yubihsm-http", +))] +use std::collections::BTreeMap; + +// ── OS keyring ──────────────────────────────────────────────────────────────── + +#[cfg(any( + all(target_os = "macos", feature = "macos-keychain"), + all(target_os = "windows", feature = "windows-credentials"), + all(target_os = "linux", feature = "linux-secret-service"), +))] +use cryptex::{ListKeyRing, PeekableKeyRing, get_os_keyring}; + +#[cfg(all(target_os = "macos", feature = "macos-keychain"))] +use cryptex::macos::MacOsKeyRing as OsKeyRing; + +#[cfg(all(target_os = "linux", feature = "linux-secret-service"))] +use cryptex::linux::LinuxOsKeyRing as OsKeyRing; + +#[cfg(all(target_os = "windows", feature = "windows-credentials"))] +use cryptex::windows::WindowsOsKeyRing as OsKeyRing; + +// ── YubiHSM ─────────────────────────────────────────────────────────────────── + +#[cfg(any(feature = "yubihsm-usb", feature = "yubihsm-http"))] +use cryptex::NewKeyRing; + +#[cfg(any(feature = "yubihsm-usb", feature = "yubihsm-http"))] +use cryptex::yubihsm::YubiHsmKeyRing; + +// ───────────────────────────────────────────────────────────────────────────── + +pub(crate) fn main() { + let matches = Command::new("cryptex") + .version(env!("CARGO_PKG_VERSION")) + .author("Michael Lodder") + .about("Platform-independent CLI for storing and retrieving secrets from secure keyrings") + .arg( + Arg::new("keyring") + .long("keyring") + .short('k') + .value_name("TYPE") + .global(true) + .help("Keyring backend to use: 'os' (default) or 'yubihsm'"), + ) + .subcommand( + Command::new("get") + .about("Retrieve a secret by ID") + .arg( + Arg::new("SERVICE") + .help("Service name (OS) or connection string (yubihsm)") + .required(true) + .index(1), + ) + .arg( + Arg::new("ID") + .help("The secret ID. If omitted, read from STDIN") + .required(false) + .index(2), + ), + ) + .subcommand( + Command::new("set") + .about("Save a secret by ID") + .arg( + Arg::new("SERVICE") + .help("Service name (OS) or connection string (yubihsm)") + .required(true) + .index(1), + ) + .arg( + Arg::new("ID") + .help("The secret ID") + .required(true) + .index(2), + ) + .arg( + Arg::new("SECRET") + .help("The secret value. If omitted, read from STDIN") + .required(false) + .index(3), + ), + ) + .subcommand( + Command::new("delete") + .about("Delete a secret by ID") + .arg( + Arg::new("SERVICE") + .help("Service name (OS) or connection string (yubihsm)") + .required(true) + .index(1), + ) + .arg( + Arg::new("ID") + .help("The secret ID. If omitted, read from STDIN") + .required(false) + .index(2), + ), + ) + .subcommand( + Command::new("peek") + .about("Inspect OS keyring entries without full retrieval (OS backends only)") + .arg( + Arg::new("ID") + .help("Filter as comma-separated name=value pairs (e.g. service=aws,account=key)") + .required(false) + .index(1), + ), + ) + .subcommand( + Command::new("list") + .about("List secret IDs. For 'os': lists all. For 'yubihsm': requires a connection string.") + .arg( + Arg::new("SERVICE") + .help("Connection string (required for 'yubihsm')") + .required(false) + .index(1), + ), + ) + .get_matches(); + + dispatch(&matches); +} + +fn dispatch(matches: &ArgMatches) { + let keyring_type = matches + .get_one::("keyring") + .map(|s| s.as_str()) + .unwrap_or("os"); + + match keyring_type { + "yubihsm" => { + #[cfg(any(feature = "yubihsm-usb", feature = "yubihsm-http"))] + dispatch_yubihsm(matches); + #[cfg(not(any(feature = "yubihsm-usb", feature = "yubihsm-http")))] + die::<()>( + "YubiHSM support is not compiled in. \ + Enable the 'yubihsm-usb' or 'yubihsm-http' feature.", + ); + } + "os" => dispatch_os(matches), + other => die::<()>(&format!( + "Unknown keyring type '{}'. Valid options: os, yubihsm", + other + )), + } +} + +// ── OS keyring dispatch ─────────────────────────────────────────────────────── + +#[cfg(any( + all(target_os = "macos", feature = "macos-keychain"), + all(target_os = "windows", feature = "windows-credentials"), + all(target_os = "linux", feature = "linux-secret-service"), +))] +fn dispatch_os(matches: &ArgMatches) { + if let Some(m) = matches.subcommand_matches("get") { + os_get(m); + } else if let Some(m) = matches.subcommand_matches("set") { + os_set(m); + } else if let Some(m) = matches.subcommand_matches("delete") { + os_delete(m); + } else if let Some(m) = matches.subcommand_matches("peek") { + os_peek(m); + } else if matches.subcommand_matches("list").is_some() { + os_list(); + } else { + die::<()>("Please specify a command: get | set | delete | peek | list"); + } +} + +#[cfg(not(any( + all(target_os = "macos", feature = "macos-keychain"), + all(target_os = "windows", feature = "windows-credentials"), + all(target_os = "linux", feature = "linux-secret-service"), +)))] +fn dispatch_os(_matches: &ArgMatches) { + die::<()>( + "No OS keyring available for this platform/feature combination. \ + Use '--keyring yubihsm' or enable a platform keyring feature.", + ); +} + +#[cfg(any( + all(target_os = "macos", feature = "macos-keychain"), + all(target_os = "windows", feature = "windows-credentials"), + all(target_os = "linux", feature = "linux-secret-service"), +))] +fn os_get(matches: &ArgMatches) { + let mut keyring = os_open(matches); + let id = get_id(matches, true); + let secret = keyring + .get_secret(&id) + .unwrap_or_else(|e| die::(&e.to_string())); + io::stdout().write_all(secret.as_slice()).unwrap(); + io::stdout().flush().unwrap(); +} + +#[cfg(any( + all(target_os = "macos", feature = "macos-keychain"), + all(target_os = "windows", feature = "windows-credentials"), + all(target_os = "linux", feature = "linux-secret-service"), +))] +fn os_set(matches: &ArgMatches) { + let mut keyring = os_open(matches); + let id = matches.get_one::("ID").map(|s| s.as_str()).unwrap(); + let mut secret = read_input(matches, "SECRET", true); + keyring + .set_secret(id, &secret) + .unwrap_or_else(|e| die::<()>(&format!("Failed: {}", e))); + secret.zeroize(); + println!("{}", "Success".green()); +} + +#[cfg(any( + all(target_os = "macos", feature = "macos-keychain"), + all(target_os = "windows", feature = "windows-credentials"), + all(target_os = "linux", feature = "linux-secret-service"), +))] +fn os_delete(matches: &ArgMatches) { + let mut keyring = os_open(matches); + let id = get_id(matches, true); + keyring + .delete_secret(&id) + .unwrap_or_else(|e| die::<()>(&e.to_string())); + println!("{}", "Success".green()); +} + +#[cfg(any( + all(target_os = "macos", feature = "macos-keychain"), + all(target_os = "windows", feature = "windows-credentials"), + all(target_os = "linux", feature = "linux-secret-service"), +))] +fn os_peek(matches: &ArgMatches) { + let id = get_id(matches, false); + let secrets = OsKeyRing::peek_secret(&id) + .unwrap_or_else(|e| die::>(&e.to_string())); + if secrets.len() == 1 && !id.is_empty() { + io::stdout().write_all(secrets[0].1.as_slice()).unwrap(); + io::stdout().flush().unwrap(); + println!(); + } else { + for s in secrets { + print!("{} -> ", s.0); + io::stdout().write_all(s.1.as_slice()).unwrap(); + println!(); + io::stdout().flush().unwrap(); + } + } +} + +#[cfg(any( + all(target_os = "macos", feature = "macos-keychain"), + all(target_os = "windows", feature = "windows-credentials"), + all(target_os = "linux", feature = "linux-secret-service"), +))] +fn os_list() { + let secret_names = OsKeyRing::list_secrets() + .unwrap_or_else(|e| die::>>(&e.to_string())); + for s in secret_names { + println!("{:?}", s); + } +} + +#[cfg(all(target_os = "linux", feature = "linux-secret-service"))] +fn os_open(matches: &ArgMatches) -> OsKeyRing<'_> { + let service = matches + .get_one::("SERVICE") + .map(|s| s.as_str()) + .unwrap(); + get_os_keyring(service).unwrap_or_else(|e| die(&format!("Unable to open OS keyring: {}", e))) +} + +#[cfg(any( + all(target_os = "macos", feature = "macos-keychain"), + all(target_os = "windows", feature = "windows-credentials"), +))] +fn os_open(matches: &ArgMatches) -> OsKeyRing { + let service = matches + .get_one::("SERVICE") + .map(|s| s.as_str()) + .unwrap(); + get_os_keyring(service).unwrap_or_else(|e| die(&format!("Unable to open OS keyring: {}", e))) +} + +// ── YubiHSM dispatch ───────────────────────────────────────────────────────── + +#[cfg(any(feature = "yubihsm-usb", feature = "yubihsm-http"))] +fn dispatch_yubihsm(matches: &ArgMatches) { + if let Some(m) = matches.subcommand_matches("get") { + yubihsm_get(m); + } else if let Some(m) = matches.subcommand_matches("set") { + yubihsm_set(m); + } else if let Some(m) = matches.subcommand_matches("delete") { + yubihsm_delete(m); + } else if let Some(m) = matches.subcommand_matches("list") { + yubihsm_list(m); + } else if matches.subcommand_matches("peek").is_some() { + die::<()>("The 'peek' command is not supported for the YubiHSM backend."); + } else { + die::<()>("Please specify a command: get | set | delete | list"); + } +} + +#[cfg(any(feature = "yubihsm-usb", feature = "yubihsm-http"))] +fn yubihsm_open(matches: &ArgMatches) -> YubiHsmKeyRing { + let connstr = matches + .get_one::("SERVICE") + .map(|s| s.as_str()) + .unwrap_or_else(|| die("A YubiHSM connection string is required as the SERVICE argument")); + YubiHsmKeyRing::new(connstr) + .unwrap_or_else(|e| die(&format!("Failed to connect to YubiHSM: {}", e))) +} + +#[cfg(any(feature = "yubihsm-usb", feature = "yubihsm-http"))] +fn yubihsm_get(matches: &ArgMatches) { + let mut ring = yubihsm_open(matches); + let id = get_id(matches, true); + let secret = ring + .get_secret(&id) + .unwrap_or_else(|e| die::(&e.to_string())); + io::stdout().write_all(secret.as_slice()).unwrap(); + io::stdout().flush().unwrap(); +} + +#[cfg(any(feature = "yubihsm-usb", feature = "yubihsm-http"))] +fn yubihsm_set(matches: &ArgMatches) { + let mut ring = yubihsm_open(matches); + let id = matches.get_one::("ID").map(|s| s.as_str()).unwrap(); + let mut secret = read_input(matches, "SECRET", true); + ring.set_secret(id, &secret) + .unwrap_or_else(|e| die::<()>(&format!("Failed: {}", e))); + secret.zeroize(); + println!("{}", "Success".green()); +} + +#[cfg(any(feature = "yubihsm-usb", feature = "yubihsm-http"))] +fn yubihsm_delete(matches: &ArgMatches) { + let mut ring = yubihsm_open(matches); + let id = get_id(matches, true); + ring.delete_secret(&id) + .unwrap_or_else(|e| die::<()>(&e.to_string())); + println!("{}", "Success".green()); +} + +#[cfg(any(feature = "yubihsm-usb", feature = "yubihsm-http"))] +fn yubihsm_list(matches: &ArgMatches) { + let ring = yubihsm_open(matches); + let entries = ring + .list_hsm_secrets() + .unwrap_or_else(|e| die::>>(&e.to_string())); + for entry in entries { + println!("{:?}", entry); + } +} + +// ── Shared helpers ──────────────────────────────────────────────────────────── + +#[cfg(any( + all(target_os = "macos", feature = "macos-keychain"), + all(target_os = "windows", feature = "windows-credentials"), + all(target_os = "linux", feature = "linux-secret-service"), + feature = "yubihsm-usb", + feature = "yubihsm-http", +))] +fn get_id(matches: &ArgMatches, read_stdin: bool) -> String { + let bytes = read_input(matches, "ID", read_stdin); + String::from_utf8(bytes).unwrap_or_else(|_| die("ID is not valid UTF-8")) +} + +#[cfg(any( + all(target_os = "macos", feature = "macos-keychain"), + all(target_os = "windows", feature = "windows-credentials"), + all(target_os = "linux", feature = "linux-secret-service"), + feature = "yubihsm-usb", + feature = "yubihsm-http", +))] +fn read_input(matches: &ArgMatches, name: &str, read_stdin: bool) -> Vec { + match matches.get_one::(name).map(|s| s.as_str()) { + Some(text) => match get_file(text) { + Some(file) => match File::open(file.as_path()) { + Ok(mut f) => read_stream(&mut f), + Err(_) => die(&format!("Unable to read file {}", file.to_str().unwrap())), + }, + None => text.as_bytes().to_vec(), + }, + None => { + if io::stdin().is_terminal() { + if read_stdin { + rpassword::prompt_password("Enter Secret: ") + .unwrap() + .as_bytes() + .to_vec() + } else { + Vec::new() + } + } else { + let mut f = io::stdin(); + read_stream(&mut f) + } + } + } +} + +#[cfg(any( + all(target_os = "macos", feature = "macos-keychain"), + all(target_os = "windows", feature = "windows-credentials"), + all(target_os = "linux", feature = "linux-secret-service"), + feature = "yubihsm-usb", + feature = "yubihsm-http", +))] +fn read_stream(f: &mut R) -> Vec { + let mut bytes = Vec::new(); + let mut buffer = [0u8; 4096]; + loop { + match f.read(&mut buffer) { + Ok(0) => break, + Ok(n) => bytes.extend_from_slice(&buffer[..n]), + Err(_) => break, + } + } + bytes +} + +#[cfg(any( + all(target_os = "macos", feature = "macos-keychain"), + all(target_os = "windows", feature = "windows-credentials"), + all(target_os = "linux", feature = "linux-secret-service"), + feature = "yubihsm-usb", + feature = "yubihsm-http", +))] +fn get_file(name: &str) -> Option { + let mut file = PathBuf::from(name); + if file.as_path().is_file() { + let metadata = file + .as_path() + .symlink_metadata() + .expect("symlink_metadata call failed"); + if metadata.file_type().is_symlink() { + match file.as_path().read_link() { + Ok(f) => file = f, + Err(_) => die::<()>(&format!("Can't read the symbolic link: {}", name)), + } + } + Some(file) + } else { + None + } +} + +fn die(final_message: &str) -> R { + eprintln!("{}", final_message.red()); + std::process::exit(1); +} diff --git a/src/wasm.rs b/src/wasm.rs new file mode 100644 index 0000000..e042837 --- /dev/null +++ b/src/wasm.rs @@ -0,0 +1,547 @@ +/* + Copyright Michael Lodder. All Rights Reserved. + SPDX-License-Identifier: Apache-2.0 +*/ +//! JavaScript bindings, for use from a browser with `wasm-bindgen`. +//! +//! ```js +//! import init, { Keyring } from "./pkg/cryptex.js"; +//! await init(); +//! +//! const keyring = await Keyring.open( +//! "password=mysecret salt=0okm9ijn8uhb7ygv", +//! "settings", +//! { backend: "turso", store: "indexeddb" }, +//! ); +//! await keyring.set("api-token", new TextEncoder().encode("secret")); +//! const token = keyring.get("api-token"); +//! await keyring.close(); +//! ``` +//! +//! Backends: +//! +//! | `backend` | what it is | +//! | --- | --- | +//! | `turso` (default) | a Turso database, encrypted with the key from the connection string | +//! | `memory` | an encrypted image in memory, no database | +//! +//! Stores, in order of preference: +//! +//! | `store` | where the image lives | works in | +//! | --- | --- | --- | +//! | `indexeddb` (default) | IndexedDB, one image per keyring, guarded by a Web Lock | page and worker | +//! | `localstorage` | `localStorage`, one string per keyring | page only | +//! | `opfs` | origin private file system, one file per keyring | worker only, `backend: "turso"` only | +//! | `memory` | nowhere: the keyring is gone when the page unloads | page and worker | +//! +//! Every store keeps the image encrypted; the key comes from the password (or +//! raw key) in the connection string. What a store protects against is other +//! origins and other users, not scripts running on the same origin: any script +//! there can read IndexedDB, OPFS and `localStorage`. +//! +//! Deriving the key runs Argon2, which blocks the thread it runs on. Open the +//! keyring in a worker (or with default parameters) to keep the page +//! responsive. + +use js_sys::Reflect; +use wasm_bindgen::prelude::*; +use zeroize::Zeroizing; + +use crate::DynKeyRing; +use crate::error::KeyRingError; +use crate::indexeddb::LockHold; +use crate::indexeddb::SnapshotStore; +use crate::memory::MemoryKeyring; +use crate::turso::TursoKeyring; +use crate::web_storage::{self, LocalStorageImage}; + +/// A keyring, opened from JavaScript. +#[wasm_bindgen] +pub struct Keyring { + inner: Inner, +} + +enum Inner { + /// A Turso keyring plus the store its image is written to. + Turso { + /// `None` once the keyring is closed: dropping it releases the + /// database, and with it an OPFS handle or an IndexedDB lock. + keyring: Option, + store: Store, + dirty: bool, + }, + Memory { + /// `None` once the keyring is closed. + keyring: Option, + store: Store, + dirty: bool, + }, +} + +enum Store { + /// The keyring persists itself, or is not persisted at all. + None, + /// The database is an OPFS file; it holds its own data. + Opfs, + IndexedDb(SnapshotStore), + /// An image in `localStorage`, with the lock that keeps two tabs from + /// overwriting each other's image. + LocalStorage(LocalStorageImage, LockHold), +} + +#[wasm_bindgen] +impl Keyring { + /// Open the keyring called `name`, creating it on first use. + /// + /// `connection` is a connection string such as + /// `password=mysecret salt=0okm9ijn8uhb7ygv`. `options` may name a + /// `backend` and a `store`; both default as shown above. A stored keyring + /// is refused with an `AccessDenied` error when the key is wrong. + #[wasm_bindgen(js_name = "open")] + pub async fn open(connection: &str, name: &str, options: JsValue) -> Result { + let options = Options::parse(options)?; + let name = if name.is_empty() { "default" } else { name }; + match options.backend { + Backend::Turso => open_turso(connection, name, options.store).await, + Backend::Memory => open_memory(connection, name, options.store).await, + } + } + + /// Reopen a keyring from an image returned by [`export`](Self::export). + /// + /// Only `backend` is consulted: the image is used as given, so nothing is + /// read from storage and nothing is written until the first change. + #[wasm_bindgen(js_name = "import")] + pub async fn import( + connection: &str, + image: &[u8], + options: JsValue, + ) -> Result { + let options = Options::parse(options)?; + match options.backend { + Backend::Turso => { + let keyring = + TursoKeyring::from_bytes(image, &turso_params(connection)?).map_err(js)?; + Ok(Keyring { + inner: Inner::Turso { + keyring: Some(keyring), + store: Store::None, + dirty: false, + }, + }) + } + Backend::Memory => { + let keyring = MemoryKeyring::import(image, memory_secret(connection)?.as_slice()) + .map_err(js)?; + Ok(Keyring { + inner: Inner::Memory { + keyring: Some(keyring), + store: Store::None, + dirty: false, + }, + }) + } + } + } + + /// Read a secret. Throws `ItemNotFound` when there is none. + pub fn get(&mut self, id: &str) -> Result, JsError> { + let secret = match &mut self.inner { + Inner::Turso { keyring, .. } => keyring.as_mut().ok_or_else(closed)?.get_secret(id), + Inner::Memory { keyring, .. } => keyring.as_mut().ok_or_else(closed)?.get_secret(id), + } + .map_err(js)?; + let value: Zeroizing> = Zeroizing::new(secret.0.clone()); + Ok(value.to_vec()) + } + + /// Store a secret, replacing any previous value. + /// + /// Resolves once the change has reached storage, so a resolved promise + /// means the secret survives a reload. + pub async fn set(&mut self, id: &str, secret: &[u8]) -> Result<(), JsError> { + match &mut self.inner { + Inner::Turso { + keyring, + store, + dirty, + } => { + let keyring = keyring.as_mut().ok_or_else(closed)?; + keyring.set_secret(id, secret).map_err(js)?; + *dirty = true; + flush(store, dirty, || keyring.export()).await + } + Inner::Memory { + keyring, + store, + dirty, + } => { + let keyring = keyring.as_mut().ok_or_else(closed)?; + keyring.set_secret(id, secret).map_err(js)?; + *dirty = true; + flush(store, dirty, || keyring.export()).await + } + } + } + + /// Remove a secret. Resolves once storage has been updated. + pub async fn delete(&mut self, id: &str) -> Result<(), JsError> { + match &mut self.inner { + Inner::Turso { + keyring, + store, + dirty, + } => { + let keyring = keyring.as_mut().ok_or_else(closed)?; + keyring.delete_secret(id).map_err(js)?; + *dirty = true; + flush(store, dirty, || keyring.export()).await + } + Inner::Memory { + keyring, + store, + dirty, + } => { + let keyring = keyring.as_mut().ok_or_else(closed)?; + keyring.delete_secret(id).map_err(js)?; + *dirty = true; + flush(store, dirty, || keyring.export()).await + } + } + } + + /// Re-encrypt under a new connection string and store the result. + /// + /// Nothing changes if the new key cannot be applied. An OPFS keyring + /// cannot be rekeyed in place: create a keyring with a new name and copy + /// the secrets into it. + pub async fn rekey(&mut self, connection: &str) -> Result<(), JsError> { + match &mut self.inner { + Inner::Turso { + keyring, + store, + dirty, + } => { + if matches!(store, Store::Opfs) { + return Err(JsError::new( + "GeneralError: an OPFS keyring cannot be rekeyed in place; \ + open a keyring with a new name and copy the secrets into it", + )); + } + let params = turso_params(connection)?; + let keyring = keyring.as_mut().ok_or_else(closed)?; + // Build the replacement first: if it fails, the keyring the + // caller holds is untouched. + let rekeyed = keyring.copy_under(¶ms).map_err(js)?; + *keyring = rekeyed; + *dirty = true; + flush(store, dirty, || keyring.export()).await + } + Inner::Memory { + keyring, + store, + dirty, + } => { + let keyring = keyring.as_mut().ok_or_else(closed)?; + keyring.rekey(&memory_params(connection)?).map_err(js)?; + *dirty = true; + flush(store, dirty, || keyring.export()).await + } + } + } + + /// Every id in this keyring, in order. + pub fn keys(&self) -> Result, JsError> { + match &self.inner { + Inner::Turso { keyring, .. } => keyring.as_ref().ok_or_else(closed)?.keys().map_err(js), + Inner::Memory { keyring, .. } => Ok(keyring.as_ref().ok_or_else(closed)?.keys()), + } + } + + /// Copy the encrypted image out, e.g. to move it to another store. + pub fn export(&self) -> Result, JsError> { + match &self.inner { + Inner::Turso { keyring, .. } => { + keyring.as_ref().ok_or_else(closed)?.export().map_err(js) + } + Inner::Memory { keyring, .. } => { + keyring.as_ref().ok_or_else(closed)?.export().map_err(js) + } + } + } + + /// Flush any pending change and release the store. + /// + /// A keyring holding a Web Lock releases it here, letting another tab + /// open the same name. Every other method then throws, so a caller cannot + /// keep writing to a keyring whose changes have nowhere to go. + pub async fn close(&mut self) -> Result<(), JsError> { + match &mut self.inner { + Inner::Turso { + keyring, + store, + dirty, + } => { + if let Some(keyring) = keyring.as_ref() { + flush(store, dirty, || keyring.export()).await?; + } + *keyring = None; + release(store).await; + } + Inner::Memory { + keyring, + store, + dirty, + } => { + if let Some(keyring) = keyring.as_ref() { + flush(store, dirty, || keyring.export()).await?; + } + *keyring = None; + release(store).await; + } + } + Ok(()) + } +} + +/// Ask the browser not to evict this origin's storage. +/// +/// Browsers may grant it silently, prompt, or refuse. Call it while the user +/// is interacting with the page; without it a browser under storage pressure +/// can delete the keyring. +#[wasm_bindgen(js_name = "requestPersistentStorage")] +pub async fn request_persistent_storage() -> Result { + web_storage::request_persistent_storage().await.map_err(js) +} + +/// The keyrings this origin already has in one store, in name order. +/// +/// `storedKeyrings({ store })` reads `indexeddb` (the default), `localstorage` +/// or `opfs` without opening anything, so a page can show what is stored +/// before the user picks a keyring. Nothing is listed for `memory`, which +/// keeps no store of its own. +#[wasm_bindgen(js_name = "storedKeyrings")] +pub async fn stored_keyrings(options: JsValue) -> Result, JsError> { + match Options::parse(options)?.store { + StoreKind::IndexedDb => SnapshotStore::list_names().await.map_err(js), + StoreKind::LocalStorage => web_storage::list_names().map_err(js), + StoreKind::Opfs => crate::opfs::list_names().await.map_err(js), + StoreKind::Memory => Ok(Vec::new()), + } +} + +async fn open_turso(connection: &str, name: &str, store: StoreKind) -> Result { + let params = turso_params(connection)?; + let (keyring, store) = match store { + StoreKind::IndexedDb => { + let snapshot = SnapshotStore::open(name).await.map_err(js)?; + let keyring = match snapshot.load().await.map_err(js)? { + Some(image) => TursoKeyring::from_bytes(&image, ¶ms).map_err(js)?, + None => TursoKeyring::in_memory(¶ms).map_err(js)?, + }; + (keyring, Store::IndexedDb(snapshot)) + } + StoreKind::LocalStorage => { + let hold = LockHold::acquire(&format!("cryptex:{name}")) + .await + .map_err(js)?; + let image = LocalStorageImage::new(Some(name))?; + let keyring = match image.load()? { + Some(bytes) => TursoKeyring::from_bytes(&bytes, ¶ms).map_err(js)?, + None => TursoKeyring::in_memory(¶ms).map_err(js)?, + }; + (keyring, Store::LocalStorage(image, hold)) + } + StoreKind::Opfs => { + let keyring = TursoKeyring::open_opfs(¶ms, name).await.map_err(js)?; + (keyring, Store::Opfs) + } + StoreKind::Memory => (TursoKeyring::in_memory(¶ms).map_err(js)?, Store::None), + }; + Ok(Keyring { + inner: Inner::Turso { + keyring: Some(keyring), + store, + dirty: false, + }, + }) +} + +async fn open_memory(connection: &str, name: &str, store: StoreKind) -> Result { + let params = memory_params(connection)?; + let secret = memory_secret(connection)?; + let (keyring, store) = match store { + StoreKind::IndexedDb => { + let snapshot = SnapshotStore::open(name).await.map_err(js)?; + let keyring = match snapshot.load().await.map_err(js)? { + Some(image) => MemoryKeyring::import(&image, secret.as_slice()).map_err(js)?, + None => MemoryKeyring::with_params(¶ms).map_err(js)?, + }; + (keyring, Store::IndexedDb(snapshot)) + } + StoreKind::LocalStorage => { + let hold = LockHold::acquire(&format!("cryptex:{name}")) + .await + .map_err(js)?; + let image = LocalStorageImage::new(Some(name))?; + let keyring = match image.load()? { + Some(bytes) => MemoryKeyring::import(&bytes, secret.as_slice()).map_err(js)?, + None => MemoryKeyring::with_params(¶ms).map_err(js)?, + }; + (keyring, Store::LocalStorage(image, hold)) + } + StoreKind::Memory => ( + MemoryKeyring::with_params(¶ms).map_err(js)?, + Store::None, + ), + // Refused when the options are parsed; OPFS stores database files. + StoreKind::Opfs => { + return Err(JsError::new( + "TypeError: the opfs store needs backend: \"turso\"", + )); + } + }; + Ok(Keyring { + inner: Inner::Memory { + keyring: Some(keyring), + store, + dirty: false, + }, + }) +} + +/// Drop the store, releasing a Web Lock only once the browser has done so. +async fn release(store: &mut Store) { + match store { + Store::IndexedDb(snapshot) => snapshot.release().await, + Store::LocalStorage(_, hold) => hold.release_async().await, + Store::None | Store::Opfs => {} + } + *store = Store::None; +} + +/// Write the keyring's current image to its store. +/// +/// Nothing to do for a keyring that keeps its own data (OPFS) or has no store: +/// `image` is only called when a store actually needs a copy. +async fn flush( + store: &Store, + dirty: &mut bool, + image: impl FnOnce() -> Result, KeyRingError>, +) -> Result<(), JsError> { + if !*dirty { + return Ok(()); + } + match store { + Store::None | Store::Opfs => {} + Store::IndexedDb(snapshot) => snapshot.save(&image().map_err(js)?).await.map_err(js)?, + Store::LocalStorage(local, _) => local.save(&image().map_err(js)?)?, + } + *dirty = false; + Ok(()) +} + +#[derive(Clone, Copy)] +enum Backend { + Turso, + Memory, +} + +#[derive(Clone, Copy)] +enum StoreKind { + IndexedDb, + LocalStorage, + Opfs, + Memory, +} + +struct Options { + backend: Backend, + store: StoreKind, +} + +impl Options { + fn parse(options: JsValue) -> Result { + let mut parsed = Self { + backend: Backend::Turso, + store: StoreKind::IndexedDb, + }; + if options.is_undefined() || options.is_null() { + return Ok(parsed); + } + if let Some(backend) = string_property(&options, "backend")? { + parsed.backend = match backend.as_str() { + "turso" => Backend::Turso, + "memory" => Backend::Memory, + other => return Err(unknown("backend", other)), + }; + } + if let Some(store) = string_property(&options, "store")? { + parsed.store = match store.as_str() { + "indexeddb" => StoreKind::IndexedDb, + "localstorage" => StoreKind::LocalStorage, + "opfs" => StoreKind::Opfs, + "memory" => StoreKind::Memory, + other => return Err(unknown("store", other)), + }; + } + // OPFS holds database files, so it needs a database backend. + if matches!(parsed.store, StoreKind::Opfs) && matches!(parsed.backend, Backend::Memory) { + return Err(JsError::new( + "TypeError: the opfs store needs backend: \"turso\"", + )); + } + Ok(parsed) + } +} + +fn string_property(value: &JsValue, name: &str) -> Result, JsError> { + let property = + Reflect::get(value, &JsValue::from_str(name)).map_err(|e| js(KeyRingError::from(e)))?; + if property.is_undefined() || property.is_null() { + return Ok(None); + } + property + .as_string() + .map(Some) + .ok_or_else(|| JsError::new(&format!("TypeError: options.{name} must be a string"))) +} + +fn unknown(field: &str, value: &str) -> JsError { + JsError::new(&format!( + "TypeError: unknown {field} '{value}'; expected one of the documented values" + )) +} + +fn turso_params(connection: &str) -> Result { + connection.parse().map_err(js) +} + +fn memory_params(connection: &str) -> Result { + connection.parse().map_err(js) +} + +/// The password or raw key from a connection string, for a memory keyring. +/// The password or raw key, wrapped so its copy is wiped on the way out. +fn memory_secret(connection: &str) -> Result>, JsError> { + let params = memory_params(connection)?; + Ok(Zeroizing::new(if params.key.is_empty() { + params.password.clone() + } else { + params.key.clone() + })) +} + +fn closed() -> JsError { + JsError::new("GeneralError: the keyring is closed") +} + +fn js(error: KeyRingError) -> JsError { + // Keep the kind as the first word so JavaScript can switch on it. + let kind = match &error { + KeyRingError::ItemNotFound => "ItemNotFound", + KeyRingError::AccessDenied { .. } => "AccessDenied", + KeyRingError::GeneralError { .. } => "GeneralError", + }; + JsError::new(&format!("{kind}: {error}")) +} diff --git a/tests/default_argon2_params.rs b/tests/default_argon2_params.rs index 5b432ac..79cfb57 100644 --- a/tests/default_argon2_params.rs +++ b/tests/default_argon2_params.rs @@ -5,9 +5,14 @@ use std::process::Command; #[test] fn default_argon2_params_are_checked_without_test_cfg() { let cargo = std::env::var("CARGO").unwrap_or_else(|_| "cargo".to_string()); + // A separate target dir: the cdylib crate type leaves the rlib unhashed, so a + // nested build with fewer features would replace the one doctests link. + let target_dir = concat!(env!("CARGO_TARGET_TMPDIR"), "/default_argon2_params"); let output = Command::new(cargo) .args([ "run", + "--target-dir", + target_dir, "--quiet", "--example", "default_argon2_params", diff --git a/tests/wasm.rs b/tests/wasm.rs new file mode 100644 index 0000000..6832545 --- /dev/null +++ b/tests/wasm.rs @@ -0,0 +1,189 @@ +/* + Copyright Michael Lodder. All Rights Reserved. + SPDX-License-Identifier: Apache-2.0 +*/ +//! Browser tests for the JavaScript bindings. +//! +//! Run with `wasm-pack test --headless --chrome --no-default-features +//! --features js`. Native `cargo test` skips this file. + +#![cfg(all(target_family = "wasm", target_os = "unknown", feature = "js"))] + +use cryptex::Keyring; +use wasm_bindgen_test::wasm_bindgen_test; + +wasm_bindgen_test::wasm_bindgen_test_configure!(run_in_browser); + +const CONNECTION: &str = "password=browser-test salt=0okm9ijn8uhb7ygv"; + +/// A keyring name no other run uses, so a leftover store cannot fool a test. +fn unique_name(prefix: &str) -> String { + use std::sync::atomic::{AtomicU32, Ordering}; + + static NEXT: AtomicU32 = AtomicU32::new(0); + format!("{prefix}-{}", NEXT.fetch_add(1, Ordering::Relaxed)) +} + +#[wasm_bindgen_test] +async fn memory_keyring_round_trips() { + let mut keyring = Keyring::open(CONNECTION, &unique_name("memory"), Default::default()) + .await + .expect("a memory keyring opens"); + + keyring.set("token", b"secret").await.expect("set succeeds"); + assert_eq!(keyring.get("token").expect("get succeeds"), b"secret"); + keyring.delete("token").await.expect("delete succeeds"); + assert!(keyring.get("token").is_err()); + + keyring.close().await.expect("close succeeds"); +} + +#[wasm_bindgen_test] +async fn a_closed_keyring_refuses_every_call() { + let mut keyring = Keyring::open(CONNECTION, &unique_name("closed"), Default::default()) + .await + .expect("a memory keyring opens"); + keyring.set("token", b"secret").await.expect("set succeeds"); + keyring.close().await.expect("close succeeds"); + + let error = keyring + .set("token", b"other") + .await + .expect_err("a closed keyring refuses writes"); + assert!(format!("{error:?}").contains("closed"), "{error:?}"); + assert!(keyring.get("token").is_err()); + assert!(keyring.delete("token").await.is_err()); + assert!(keyring.keys().is_err()); +} + +#[wasm_bindgen_test] +async fn local_storage_takes_one_opener() { + // Two tabs rewriting one image would lose each other's secrets, so the + // second opener is refused instead. + let name = unique_name("locked"); + let options = + || js_sys::JSON::parse(r#"{"store":"localstorage"}"#).expect("the options are JSON"); + + let mut first = Keyring::open(CONNECTION, &name, options()) + .await + .expect("the first opener gets the keyring"); + let second = Keyring::open(CONNECTION, &name, options()).await; + assert!(second.is_err(), "a second opener must be refused"); + + // Closing releases the lock, so the name can be opened again. + first.close().await.expect("close succeeds"); + let mut reopened = Keyring::open(CONNECTION, &name, options()) + .await + .expect("closing releases the lock"); + reopened.close().await.expect("close succeeds"); +} + +#[wasm_bindgen_test] +async fn indexeddb_keeps_the_secrets() { + let name = unique_name("indexeddb"); + + let mut keyring = Keyring::open(CONNECTION, &name, Default::default()) + .await + .expect("a keyring opens"); + keyring.set("token", b"value").await.expect("set succeeds"); + // A resolved set has reached the store, so the image is encrypted at rest. + let image = keyring.export().expect("export succeeds"); + assert!(!image.windows(5).any(|w| w == b"value")); + keyring.close().await.expect("close succeeds"); + + let mut reopened = Keyring::open(CONNECTION, &name, Default::default()) + .await + .expect("the keyring reopens"); + assert_eq!(reopened.get("token").expect("get succeeds"), b"value"); + reopened.close().await.expect("close succeeds"); +} + +#[wasm_bindgen_test] +async fn keys_and_keyring_names_are_listed() { + let name = unique_name("keys"); + let mut keyring = Keyring::open(CONNECTION, &name, Default::default()) + .await + .expect("a keyring opens"); + + keyring.set("b", b"two").await.expect("set succeeds"); + keyring.set("a", b"one").await.expect("set succeeds"); + assert_eq!( + keyring.keys().expect("keys succeeds"), + ["a".to_string(), "b".to_string()] + ); + + // A page can list what is stored without opening anything. + let stored = cryptex::stored_keyrings(wasm_bindgen::JsValue::UNDEFINED) + .await + .expect("the store lists"); + assert!(stored.contains(&name)); + + keyring.close().await.expect("close succeeds"); +} + +#[wasm_bindgen_test] +async fn every_store_lists_its_keyrings() { + use wasm_bindgen::JsValue; + + let indexeddb = cryptex::stored_keyrings(JsValue::UNDEFINED) + .await + .expect("IndexedDB lists"); + assert!(indexeddb.is_sorted()); + + // localStorage is a page API, so this test also covers the page case. + let name = unique_name("localstorage"); + let mut keyring = Keyring::open( + CONNECTION, + &name, + js_sys::JSON::parse(r#"{"backend":"turso","store":"localstorage"}"#) + .expect("the options are JSON"), + ) + .await + .expect("a localStorage keyring opens"); + keyring.set("token", b"value").await.expect("set succeeds"); + keyring.close().await.expect("close succeeds"); + + let listed = cryptex::stored_keyrings( + js_sys::JSON::parse(r#"{"store":"localstorage"}"#).expect("the options are JSON"), + ) + .await + .expect("localStorage lists"); + assert!(listed.contains(&name), "{listed:?} lacks {name}"); + + // OPFS listing reads the directory, which works from a page even though + // opening an OPFS keyring needs a worker. + let opfs = cryptex::stored_keyrings( + js_sys::JSON::parse(r#"{"store":"opfs"}"#).expect("the options are JSON"), + ) + .await + .expect("OPFS lists"); + assert!(opfs.is_sorted()); + + let memory = cryptex::stored_keyrings( + js_sys::JSON::parse(r#"{"store":"memory"}"#).expect("the options are JSON"), + ) + .await + .expect("memory lists"); + assert!(memory.is_empty()); +} + +#[wasm_bindgen_test] +async fn a_wrong_password_is_refused() { + let name = unique_name("indexeddb"); + let mut keyring = Keyring::open(CONNECTION, &name, Default::default()) + .await + .expect("a keyring opens"); + keyring.set("token", b"value").await.expect("set succeeds"); + keyring.close().await.expect("close succeeds"); + + let result = Keyring::open( + "password=wrong salt=0okm9ijn8uhb7ygv", + &name, + Default::default(), + ) + .await; + match result { + Err(error) => assert!(format!("{error:?}").contains("AccessDenied")), + Ok(_) => panic!("the wrong password is refused"), + } +}