Preface
This book is the reference documentation for Keres: a Rust library and command-line tool for encrypting files and directory trees at rest.
It is written for two audiences:
- Users who want to encrypt files or keep an encrypted vault and need to understand the commands, defaults, and failure modes.
- Developers who are embedding the
kerescrate, reviewing the format, or contributing to the project.
How to read it
If you are new to Keres, start with the Introduction and Quick start. The Library guide and CLI guide cover day-to-day use. The Architecture and Security model chapters explain the design and its limits; they are required reading before making format or cryptographic changes.
Commands in this book are shown for a POSIX shell. On Windows, replace $HOME
with %USERPROFILE% and adjust path separators. Keres stores vaults in a
platform-neutral layout and uses native file locking on both Unix and
Windows.
Version
This documentation targets Keres 0.7.x. The container format is versioned; the Rust API is not yet stable. Compatibility rules are described in Compatibility.
Getting help
- Usage questions and bug reports: GitHub issues.
- Security reports: follow SECURITY.md and do not open a public issue.
- Changes between releases: CHANGELOG.md.
Introduction
Keres is an embedded encrypted storage engine for Rust applications: a
library (keres) for storing application files, plus a reference
command-line program (keres) built on the same container format and
cryptographic core.
It is aimed at developers building local-first apps, desktop clients, and services that own files on disk. Keres supplies authenticated streaming, encrypted metadata, crash-safe updates, key rotation, and recovery, so the application does not have to design its own format. The CLI is the reference implementation and a scripting/debugging tool, not the product.
Keres is designed around one rule: do not release plaintext until its authenticity has been checked. Every record is authenticated, and metadata is encrypted wherever the format can carry it.
Two modes, one format
| Mode | Rust entry points | CLI commands | Use when |
|---|---|---|---|
| Single file | encrypt_file, decrypt_file, encrypt_file_with_padding | keres encrypt, keres decrypt | You need one self-contained .krs file |
| Vault | Vault | keres init, add, list, extract, … | You need many files, directory trees, metadata protection, and password rotation |
Both modes use the same authenticated container:
- an 8-byte
KERES\0\0\0magic; - a versioned envelope header;
- 64 KiB AES-256-GCM chunk records;
- an authenticated trailer that records the payload type, original name, size, and chunk count.
Vaults add a key hierarchy, an encrypted index, keyslots, and crash-recovery journals on top of that container.
Design principles
- Authenticate before use. Chunk index and payload type are bound into every AEAD tag. Headers participate in key derivation. A modified, reordered, truncated, or transplanted ciphertext fails before plaintext is returned.
- Encrypt metadata where possible. Filenames, directory structure, and the vault index are encrypted. Exact sizes are not hidden by default; opt-in padding rounds them to buckets.
- Make crashes boring. New data is written first and committed last.
Configs, indexes, and outputs use temp-file +
fsync+rename. A crash can lose the operation in flight, never the previous consistent state. - Keep the trusted surface small. One container format, one chunk
engine, one error type, no async runtime, no network code, and no
unsafe(#![forbid(unsafe_code)]). - Separate passwords from data keys. In a vault, the password derives a key-encryption key that wraps a random master key. Changing a password re-wraps that key; it does not rewrite stored ciphertext.
Project status
Keres is pre-1.0. The current line is 0.7.x.
- The wire format is versioned and covered by committed test vectors.
- The public Rust API may change between minor releases until 1.0.
- The project has not yet had an independent security audit.
- Only the current container format is accepted. A 0.5.x vault can be
upgraded in place with
keres migrate; other legacy formats must be decrypted with the release that wrote them.
See Security model for the threat model and a list of limitations that are deliberate, not bugs.
Non-goals
Keres does not try to provide:
- plausible deniability or hidden volumes;
- protection against malware, keyloggers, or a compromised OS while a vault is unlocked;
- access-pattern hiding (ORAM) or exact entry-count hiding;
- hardware-backed anti-rollback guarantees;
- compatibility readers for retired formats.
Where to go next
- Installation — install the CLI or add the library.
- Quick start — encrypt a file and create a vault.
- Library guide — API patterns and examples.
- Embedding Keres — integration guidance for applications.
- CLI guide — workflows and command behavior.
- Architecture — wire format, key hierarchy, and crash safety.
- Security model — attacker model, guarantees, and limitations.
Installation
Keres has two installable parts and a few optional extras:
| Component | Package | Install with |
|---|---|---|
| Library | keres | cargo add keres |
| CLI | keres-cli (binary: keres) | cargo install keres-cli |
| Source build | workspace | git clone + cargo build |
| Documentation | mdBook sources | mdbook serve docs |
The library and CLI do not depend on each other at runtime. Install only what you need.
Platform support
Keres targets the stable Rust toolchain and supports:
| Platform | Status | Notes |
|---|---|---|
| Linux | Tested in CI | POSIX permissions and flock locking |
| macOS | Tested in CI | POSIX permissions and flock locking |
| Windows | Tested in CI | LockFileEx locking and native rename |
| Other Unix-like systems | Best effort | Needs std::fs, flock, and a working OS random source |
The minimum supported Rust version (MSRV) is 1.85.
Requirements
- Rust 1.85 or newer (install via rustup).
- A filesystem that supports atomic rename within a directory. Local filesystems do; some network and FUSE filesystems do not.
- Enough memory for Argon2id. The default KDF uses 64 MiB per derivation.
Next steps
Library installation
The library crate is named keres. The library target is also keres, so
imports use the crate name directly.
Add the dependency
$ cargo add keres
or edit Cargo.toml:
[dependencies]
keres = "0.7"
The crate currently exposes no optional Cargo features. It requires std:
Keres performs filesystem I/O and uses the operating system random source.
Requirements
- Rust 1.85 or newer.
- No async runtime, external services, or background threads.
- About 64 MiB of memory during password-based key derivation (Argon2id defaults).
Documentation
- API reference: docs.rs/keres
- Local rustdoc:
cargo doc -p keres --open - Guides: Library guide, Embedding Keres
Working from a checkout
$ cargo build -p keres
$ cargo test -p keres
$ cargo doc -p keres --open
The workspace root is the library package, so plain cargo build also builds
keres.
First example
#![allow(unused)]
fn main() {
use keres::{decrypt_file, encrypt_file};
use std::path::Path;
let container = encrypt_file("correct horse", Path::new("notes.txt"), None)?;
let name = decrypt_file("correct horse", &container, Path::new("restored.txt"))?;
assert_eq!(name, "notes.txt");
Ok::<(), keres::Error>(())
}
See the Library guide for vaults, streaming, recovery, and error handling.
CLI installation
The CLI package is keres-cli; the installed binary is keres.
From crates.io
$ cargo install keres-cli
$ keres --version
cargo install compiles the CLI and the library on your machine. Release
builds use size optimization for the binary, so a local debug install is
larger and slower.
Prebuilt binaries
The release workflow publishes archives for:
x86_64-unknown-linux-gnu(.tar.gz)aarch64-apple-darwin(.tar.gz)x86_64-pc-windows-msvc(.zip)
Each archive has a matching .sha256 file. Download them from
GitHub Releases, verify the
checksum, and place the keres binary on PATH.
From a checkout
$ cargo install --path keres-cli
To run without installing:
$ cargo run -p keres-cli -- help
With Nix
From the repository root:
$ nix run . -- --help
$ nix develop
nix build builds the workspace and installs the keres binary.
Where vaults are stored
By default:
| Platform | Location |
|---|---|
| Linux, macOS | $HOME/.keres/vaults/<name> |
| Windows | %USERPROFILE%\.keres\vaults\<name> |
| Any (override) | $KERES_HOME/vaults/<name> |
Set KERES_HOME to keep vaults on an encrypted volume or a synced directory:
$ export KERES_HOME="$HOME/sync/keres"
An empty KERES_HOME is rejected rather than silently falling back to the
home directory. Vault names are plain names, not paths; slashes, .., and
symlinked vault directories are rejected by the CLI.
Passwords
Interactive prompts are the default. For non-interactive use, the CLI supports:
--password-file <path>: read the first line of a file.--password-stdin: read the first line of standard input.KERES_PASSWORD: read the password from the environment.
See Passwords and automation for priority rules and security trade-offs.
Next steps
Building from source
The repository is a Cargo workspace with the library at the root and the CLI
in keres-cli/.
Prerequisites
- Rust 1.85 or newer via rustup
- Git
- Optional: mdBook for the documentation
- Optional: Nix, for a reproducible shell and build
$ git clone https://github.com/Keres-rs/keres.git
$ cd keres
Build and test
$ cargo build --workspace
$ cargo test --workspace --all-targets
$ cargo test --workspace --doc
The CLI binary is written to target/debug/keres; a release build goes to
target/release/keres:
$ cargo build --release -p keres-cli
The release profile enables LTO, one codegen unit, and symbol stripping. The
CLI additionally uses opt-level = "z".
Lint and documentation gates
These are the same gates CI runs:
$ cargo fmt --all -- --check
$ cargo clippy --workspace --all-targets -- -D warnings
$ cargo doc --workspace --no-deps
$ cargo deny check
Build the book
$ cargo install mdbook
$ mdbook serve docs
mdbook build docs writes the static site to docs/book/.
Nix
$ nix develop # rustc, cargo, clippy, rustfmt, rust-analyzer, mdbook
$ nix build # library + CLI
$ nix run . -- help # run the CLI from the flake
The flake reads the workspace version from Cargo.toml, so release builds and
the flake stay in sync.
Fuzzing
The fuzz/ directory is a separate Cargo workspace:
$ cd fuzz
$ cargo fuzz run read_container
$ cargo fuzz run parse_manifest
$ cargo fuzz run parse_config
$ cargo fuzz run sanitize
Fuzz targets require the nightly toolchain selected by
fuzz/rust-toolchain.toml.
Quick start
This page gets you from an installed binary to a working vault and an encrypted file. For the full command set, see the CLI reference.
Encrypt a single file
$ keres encrypt report.pdf
Encrypted to: 7d3a9c1e...f04.krs
Without an output argument, the CLI writes a hash-derived .krs name in the
current directory. The original filename is encrypted inside the container,
not stored on disk.
Decrypt it:
$ keres decrypt 7d3a9c1e...f04.krs report.pdf
Decrypted 'report.pdf' to: report.pdf
decrypt refuses to overwrite an existing destination unless you pass
--force.
Create and use a vault
$ keres init personal
Vault 'personal' created at /home/you/.keres/vaults/personal
$ keres add personal ./photos --name photos
Added successfully!
$ keres add personal ./notes.txt
Added successfully!
$ keres list personal
NAME SIZE TYPE
------------------------------------------------------------
notes.txt 4.2 KB file
photos - dir
$ keres extract personal photos ./restored
Extracted to: ./restored
$ keres verify personal
Vault integrity check:
Entries total: 42
Entries verified: 42
Status: OK — all files present and authenticated
Vaults store both files and directory trees. list shows top-level entries;
children are addressed by their full parent/child path in commands that take
an entry name.
Change the password
$ keres change-password personal
Current password:
New password:
Confirm new password:
Password changed successfully!
This re-wraps the vault’s master key. Stored ciphertext is not rewritten.
To change the data key itself, use keres rotate; see
Recovery, rotation, and migration.
Use the library
#![allow(unused)]
fn main() {
use keres::{decrypt_file, encrypt_file, Vault};
use std::path::Path;
let container = encrypt_file("correct horse", Path::new("report.pdf"), None)?;
let name = decrypt_file("correct horse", &container, Path::new("report.pdf"))?;
assert_eq!(name, "report.pdf");
let mut vault = Vault::new("personal".into());
vault.init("correct horse")?;
vault.add(Path::new("photos"), Some("photos"))?;
// Bytes already in memory can be stored and read without temp files.
let note = b"a note from the application";
vault.add_from_reader("notes.txt", ¬e[..], Some(note.len() as u64))?;
let mut restored = Vec::new();
vault.extract_to_writer("notes.txt", &mut restored)?;
assert_eq!(restored, note);
vault.extract("photos", Path::new("./restored"))?;
vault.lock();
Ok::<(), keres::Error>(())
}
Vault::init leaves the vault unlocked. For an existing vault, call
vault.unlock(password) before operations, and vault.lock() when finished.
Where to go next
- Library guide for the full API.
- Embedding Keres for async, key management, and concurrency guidance.
- CLI guide for workflows, destructive operations, and automation.
- Security model for what Keres does and does not protect.
Library guide
The keres crate exposes two high-level APIs and a small set of building
blocks:
| API | Import | Purpose |
|---|---|---|
| Single-file | keres::{encrypt_file, decrypt_file} | One self-contained .krs container |
| Vault | keres::Vault | Many files and directories under one password |
| Streaming | keres::streaming | Read/Write adapters over the same format |
| Options | keres::{EncryptOptions, VaultOptions, KdfParams} | Padding and Argon2id cost selection |
| Building blocks | keres::crypto, keres::kdf, keres::padding | Primitives and parameter types |
Everything commonly used is re-exported from keres::prelude. All fallible
operations return keres::Result<T> with a typed
Error.
Single-file encryption
#![allow(unused)]
fn main() {
use keres::{decrypt_file, encrypt_file};
use std::path::Path;
// `None` writes a hash-derived `.krs` name in the current directory.
let container = encrypt_file("correct horse", Path::new("report.pdf"), None)?;
// The returned String is the original filename stored in the trailer.
let name = decrypt_file("correct horse", &container, Path::new("restored.pdf"))?;
assert_eq!(name, "report.pdf");
Ok::<(), keres::Error>(())
}
Properties:
- The output is self-contained: KDF parameters and the original filename are inside the authenticated container.
- Output is written through a temporary file in the destination directory and
committed with
fsync+rename. An error leaves no partial plaintext or ciphertext file behind. - On Unix, new files and directories are created with owner-only permissions
(
0600/0700). - If
outputisNone, the filename issha256(argon_salt ‖ object_salt).krsin the current directory. It is opaque, not secret. - The filename returned by
decrypt_filecomes from the container. Treat it as untrusted if you use it to build paths, or pass it throughkeres::sanitize::sanitize_stored_name.
To hide the exact plaintext size behind a bucket:
#![allow(unused)]
fn main() {
use keres::Padding;
use std::path::Path;
let container = keres::encrypt_file_with_padding(
"correct horse",
Path::new("report.pdf"),
None,
Padding::Adaptive,
)?;
Ok::<(), keres::Error>(())
}
To change padding and the Argon2id cost together, use EncryptOptions:
#![allow(unused)]
fn main() {
use keres::{EncryptOptions, KdfParams};
use std::path::Path;
let options = EncryptOptions::new()
.padding(keres::Padding::Adaptive)
.kdf(KdfParams {
m_cost_kib: 32 * 1024, // 32 MiB
t_cost: 3,
p_cost: 2,
});
let container = keres::encrypt_file_with_options(
"correct horse",
Path::new("report.pdf"),
None,
options,
)?;
Ok::<(), keres::Error>(())
}
KdfParams::new() is the default: Argon2id with 64 MiB, 4 passes, and
parallelism 4. Lower values make tests and memory-constrained devices faster;
they also make offline guessing cheaper, so choose deliberately. Parameters
are stored in the container and read back on decryption, which means raising
the cost never breaks existing files.
Vault lifecycle
#![allow(unused)]
fn main() {
use keres::Vault;
use std::path::Path;
let mut vault = Vault::new("myvault".into());
// Create. Fails if the path is already an initialized vault.
// `init` leaves the vault unlocked.
vault.init("correct horse")?;
vault.lock();
// Later, in a new process:
let mut vault = Vault::new("myvault".into());
vault.unlock("correct horse")?;
vault.add(Path::new("report.pdf"), None)?;
vault.lock();
Ok::<(), keres::Error>(())
}
Vault::new only creates a handle. It does not touch the filesystem.
exists() reports whether the path has a vault config.
| Method | Requires unlocked | Notes |
|---|---|---|
init, init_with_padding, init_with_options | no | Creates the vault and leaves it unlocked |
unlock, lock | no | Loads/drops the master key in memory |
add, replace, add_from_reader, replace_from_reader | yes | Write file entries |
rename, remove | yes | Mutations commit through the index |
add_if, replace_if, apply_batch | yes | Conditional or batched mutations |
list, extract, extract_to_writer, padding, version | yes | Read or inspect the index |
verify | either | Takes the password; restores the previous lock state |
change_password, rotate, erase, migrate, recover | no | Authenticate the password/code passed to them |
keyslots | no | Slot ids are plaintext metadata |
create_recovery_kit | no | Verifies the password passed to it |
init_with_options sets the initial size-padding policy and Argon2id
parameters in one call. New keyslots and password changes inherit those
parameters, so a vault keeps the cost chosen when it was created.
#![allow(unused)]
fn main() {
use keres::{KdfParams, Padding, Vault, VaultOptions};
let mut vault = Vault::new("myvault".into());
vault.init_with_options(
"correct horse",
VaultOptions::new()
.padding(Padding::Adaptive)
.kdf(KdfParams {
m_cost_kib: 32 * 1024,
t_cost: 3,
p_cost: 2,
}),
)?;
Ok::<(), keres::Error>(())
}
Adding and reading entries
#![allow(unused)]
fn main() {
use keres::Vault;
use std::path::Path;
let mut vault = Vault::new("myvault".into());
vault.unlock("correct horse")?;
// Add one file and one directory tree.
vault.add(Path::new("report.pdf"), None)?;
vault.add(Path::new("photos"), Some("pictures"))?;
// List top-level entries.
for entry in vault.list()? {
println!(
"{} — {} bytes{}",
entry.name,
entry.size,
if entry.is_directory { " (directory)" } else { "" }
);
}
// Extract a file or a whole directory under `dest`.
let path = vault.extract("pictures", Path::new("./restored"))?;
println!("restored {}", path.display());
vault.lock();
Ok::<(), keres::Error>(())
}
Names are vault-relative paths. A top-level entry may not contain /, \,
.., or control characters. Children of a directory are addressed by their
full parent/child path, for example pictures/2026/summer.jpg when
extracting a single nested file.
Mutating operations:
#![allow(unused)]
fn main() {
use keres::Vault;
use std::path::Path;
let mut vault = Vault::new("myvault".into());
vault.unlock("correct horse")?;
// Replace a file: copy-on-write, new entry ID, old blob removed after commit.
vault.replace(Path::new("report-v2.pdf"), "report.pdf")?;
// Rename a top-level file or directory without re-encrypting its ciphertext.
vault.rename("report.pdf", "report-final.pdf")?;
// Remove a file, or a directory and everything below it.
vault.remove("report-final.pdf")?;
vault.lock();
Ok::<(), keres::Error>(())
}
In-memory readers and writers
Applications often hold data in memory or receive it from a network rather
than reading it from a file. add_from_reader and replace_from_reader
accept any Read, and extract_to_writer writes to any Write:
#![allow(unused)]
fn main() {
use keres::Vault;
let mut vault = Vault::new("myvault".into());
vault.unlock("correct horse")?;
let attachment = b"bytes from an upload".to_vec();
vault.add_from_reader("upload.bin", &attachment[..], Some(attachment.len() as u64))?;
let mut restored = Vec::new();
let size = vault.extract_to_writer("upload.bin", &mut restored)?;
assert_eq!(size, attachment.len() as u64);
assert_eq!(restored, attachment);
vault.lock();
Ok::<(), keres::Error>(())
}
add_from_reader accepts top-level names, like add. replace_from_reader
and extract_to_writer also address nested children by their full
parent/child path.
The len argument is the exact number of plaintext bytes the reader will
yield. It is required when the vault uses size padding, because the padded
length must be known before encryption starts; for an unpadded vault, pass
None to stream without knowing the size. A mismatch between len and the
actual stream is reported as Error::Operation and nothing is committed.
extract_to_writer returns the authenticated size. As with all streaming
reads, the trailer is verified only after the last chunk, so a caller that
must not use unverified plaintext should stage the output and discard it on
error.
Batches and conditional writes
version() returns an IndexVersion token. add_if and replace_if compare
against it and write nothing on a mismatch:
#![allow(unused)]
fn main() {
use keres::{Vault, WriteOutcome};
use std::path::Path;
let mut vault = Vault::new("myvault".into());
vault.unlock("correct horse")?;
let expected = vault.version()?;
match vault.add_if(Path::new("new.txt"), None, Some(expected))? {
WriteOutcome::Applied { version } => println!("added at {version:?}"),
WriteOutcome::Conflict { current } => println!("retry against {current:?}"),
}
vault.lock();
Ok::<(), keres::Error>(())
}
add_if also refuses to overwrite an existing name (if-none-match). Use
apply_batch to commit several operations with one index write:
#![allow(unused)]
fn main() {
use keres::{BatchOp, Vault};
use std::path::Path;
let mut vault = Vault::new("myvault".into());
vault.unlock("correct horse")?;
vault.apply_batch(&[
BatchOp::Add {
source: Path::new("new.txt").into(),
name: None,
},
BatchOp::Replace {
source: Path::new("report-v2.pdf").into(),
name: "report.pdf".into(),
},
BatchOp::Remove {
name: "old-notes.txt".into(),
},
])?;
vault.lock();
Ok::<(), keres::Error>(())
}
If any operation fails, the index is unchanged. Newly written blobs become
orphans and can be reclaimed with prune_orphans.
Integrity checks and cleanup
#![allow(unused)]
fn main() {
use keres::Vault;
let mut vault = Vault::new("myvault".into());
vault.unlock("correct horse")?;
let report = vault.verify("correct horse")?;
println!("{} of {} entries authenticated", report.verified, report.total_entries);
println!("missing: {:?}", report.missing);
println!("corrupted: {:?}", report.corrupted);
if report.missing.is_empty() && report.corrupted.is_empty() {
let removed = vault.prune_orphans()?;
println!("pruned {removed} orphan(s)");
}
Ok::<(), keres::Error>(())
}
verify authenticates every blob and the replayed index. It checks the
plaintext size and the SHA-256 content hash recorded in the index, so a
storage attacker cannot substitute an older valid blob under the same entry
ID. It does not write plaintext to disk and does not detect rollback of the
entire vault directory.
prune_orphans deletes .enc blobs and stale temp files under d/ that no
index record references. It requires an unlocked vault and refuses to run if
the index snapshot is missing, so a damaged vault is never mistaken for an
empty one.
Keyslots
A vault can have several independent passphrases, each wrapping the same master key:
#![allow(unused)]
fn main() {
use keres::Vault;
let mut vault = Vault::new("myvault".into());
// List slot ids. No password required.
for slot in vault.keyslots()? {
println!("slot {}", slot.id);
}
// Add a second passphrase, authorized by an existing one.
let slot = vault.add_keyslot("correct horse", "laptop passphrase")?;
println!("added {}", slot.id);
// Revoke a slot, authorized by a passphrase that will remain.
vault.remove_keyslot(&slot.id, "correct horse")?;
Ok::<(), keres::Error>(())
}
Removing a keyslot revokes that passphrase but does not change the master key.
Anyone who already unwrapped the master key with the revoked passphrase keeps
access to existing ciphertext. Use rotate when a passphrase or key may have
leaked.
Recovery kit
A recovery kit is a second wrapping of the master key, protected by a one-time printable code:
#![allow(unused)]
fn main() {
use keres::Vault;
let mut vault = Vault::new("myvault".into());
let code = vault.create_recovery_kit("correct horse")?;
// Print once and store offline, separately from the vault directory.
println!("{}", code.expose());
Ok::<(), keres::Error>(())
}
If vault.config is lost or damaged but vault.recovery survives:
#![allow(unused)]
fn main() {
use keres::Vault;
let mut vault = Vault::new("myvault".into());
vault.recover("<recovery code>", "new password")?;
vault.unlock("new password")?;
Ok::<(), keres::Error>(())
}
Recovery validates the recovered master key against the encrypted index, writes a fresh single-slot config, and consumes the kit. Additional keyslots are lost and must be re-added. Losing both the password and the code is unrecoverable.
Password changes, rotation, and erasure
These operations are easy to confuse:
| Operation | Master key | Stored data | Other keyslots | Recovery kit | Final state |
|---|---|---|---|---|---|
change_password | unchanged | untouched | untouched | untouched | unchanged |
rotate | new | re-encrypted | revoked | removed | locked |
erase | new | survivors re-encrypted, entry omitted | revoked | removed | locked |
#![allow(unused)]
fn main() {
use keres::Vault;
let mut vault = Vault::new("myvault".into());
// Re-wrap one keyslot. Cheap and safe.
vault.change_password("correct horse", "new password")?;
Ok::<(), keres::Error>(())
}
#![allow(unused)]
fn main() {
use keres::Vault;
// Deep rotation: fresh master key, every entry re-encrypted.
let mut vault = Vault::new("myvault".into());
let report = vault.rotate("old password", "new password")?;
println!(
"re-encrypted {} entries ({} bytes); revoked {} keyslot(s), kit removed: {}",
report.entries,
report.bytes,
report.discarded_keyslots,
report.recovery_kit_removed
);
Ok::<(), keres::Error>(())
}
erase removes one entry and rotates in one journaled commit:
#![allow(unused)]
fn main() {
use keres::Vault;
let mut vault = Vault::new("myvault".into());
vault.unlock("old password")?;
let report = vault.erase("old-secret.txt", "new password")?;
println!("erased; re-encrypted {} entries", report.entries);
Ok::<(), keres::Error>(())
}
Erasure is forward-looking. It stops the old key from working against the vault from now on, but it cannot revoke a copy of the deleted blob that an attacker already captured together with the old key material.
Both rotate and erase leave the vault locked. Both are crash-safe through
a journal: an interrupted run is completed or rolled back on the next open.
Size padding
Padding is opt-in and applies to future writes:
#![allow(unused)]
fn main() {
use keres::{Padding, Vault};
let mut vault = Vault::new("private".into());
vault.init_with_padding("correct horse", Padding::Adaptive)?;
// Show the policy, then switch to fixed 64 KiB buckets.
println!("{:?}", vault.padding()?);
vault.set_padding(Padding::fixed(65_536)?)?;
vault.lock();
Ok::<(), keres::Error>(())
}
Padding::None— exact sizes (default).Padding::Adaptive— next power of two clamped to 4 KiB–16 MiB; larger payloads round to the next 16 MiB multiple.Padding::Fixed { size }— next multiple of a bucket in the same range.
The policy is stored in the authenticated index, so an attacker cannot silently disable it. Existing blobs keep their original sizes until they are rewritten. Manifests and directory placeholders are never padded.
Streaming
keres::streaming encrypts and decrypts the .krs format over any
Read/Write pair:
#![allow(unused)]
fn main() {
use std::io::Cursor;
use keres::streaming::{decrypt_stream, encrypt_stream, StreamOptions};
let payload = b"streamed in 64 KiB chunks".to_vec();
let mut ciphertext = Vec::new();
encrypt_stream(
"correct horse",
&mut Cursor::new(payload.clone()),
&mut ciphertext,
Some("note.txt"),
StreamOptions::new(),
)?;
let mut plaintext = Vec::new();
let info = decrypt_stream(
"correct horse",
Cursor::new(ciphertext),
&mut plaintext,
StreamOptions::new(),
)?;
assert_eq!(plaintext, payload);
assert_eq!(info.original_name.as_deref(), Some("note.txt"));
Ok::<(), keres::Error>(())
}
EncryptWriter and DecryptReader are the underlying Write/Read
adapters. StreamOptions supports a cumulative progress callback, an
AtomicBool cancellation flag, and custom Argon2id parameters through
.kdf(...). Decryption always reads the parameters from the container
header, so the setting only affects encryption.
Integrity caveat: each chunk is authenticated before its plaintext is yielded, but the trailer (total size and chunk count) can only be checked at end-of-stream. A truncated or trailer-tampered stream can yield some valid plaintext before the final error. Write to a temporary file and discard it on error, as
decrypt_filedoes.
Error handling
Wrong passwords and tampered ciphertext both map to Error::Authentication.
This is deliberate: error messages must not become a tamper oracle.
#![allow(unused)]
fn main() {
use keres::{decrypt_file, Error};
use std::path::Path;
match decrypt_file("pw", Path::new("backup.krs"), Path::new("out.bin")) {
Ok(name) => println!("restored {name}"),
Err(Error::Authentication) => eprintln!("wrong password or corrupted data"),
Err(e) => eprintln!("failed: {e}"),
}
}
The full variant list is in the error taxonomy.
Concurrency and process safety
Vault operations take an advisory lock on vault.lock:
- writers take it exclusively;
- readers (
list,extract,verify) take it shared; - a contended call returns
Error::VaultBusyinstead of waiting.
The lock coordinates well-behaved processes. It is not a security boundary: a process that ignores the lock can still read or modify files. Run one writer per vault at a time, and do not point two Keres releases at the same vault directory (see Compatibility).
Embedding Keres
Keres is an encrypted storage engine for Rust applications. Use it when your application owns files that must be confidential and tamper-evident at rest, and you would otherwise design a container format, key hierarchy, and crash safety protocol yourself.
This chapter is about integrating the library. For the full method list see the library guide; for the format and threat model see Architecture and Security model.
Pick the right shape
| Your data | Use |
|---|---|
| One opaque blob per object, keyed by a password | Single-file containers |
| Many files with names, listing, replace, and one or more passphrases | Vaults |
| Bytes already in memory, a socket, or an object store | Readers/writers and streaming |
| Only primitives (AEAD, HKDF, Argon2id) | keres::crypto |
A vault is the right default for application data: it hides names and directory structure, supports many entries under one unlocked master key, and lets you change a passphrase without rewriting stored ciphertext. Use single-file containers when each object must be independently decryptable with only a password, for example a portable export or an email attachment.
A minimal embedded store
#![allow(unused)]
fn main() {
use keres::{KdfParams, Result, Vault, VaultOptions};
fn open_store(path: std::path::PathBuf, password: &str) -> Result<Vault> {
let mut vault = Vault::new(path);
if vault.exists() {
vault.unlock(password)?;
} else {
vault.init_with_options(
password,
VaultOptions::new().kdf(KdfParams::new()),
)?;
}
Ok(vault)
}
fn save_attachment(vault: &mut Vault, name: &str, bytes: &[u8]) -> Result<()> {
vault.add_from_reader(name, bytes, Some(bytes.len() as u64))
}
fn load_attachment(vault: &Vault, name: &str) -> Result<Vec<u8>> {
let mut out = Vec::new();
vault.extract_to_writer(name, &mut out)?;
Ok(out)
}
}
init leaves a new vault unlocked. On later runs, unlock loads the master
key; call lock (or drop the Vault) when the application no longer needs
it.
Do not put a password in the source
A vault password protects the key hierarchy, so treat it like a secret, not a configuration value. Common patterns:
- Ask the user once at startup and keep the unlocked
Vaultfor the session. - Generate a high-entropy passphrase with the OS random source, store it in
the platform keychain (Keychain, Credential Manager, Secret Service), and
pass it to
unlock. - Derive it from an application key only if that key is itself protected by the platform.
Keres never writes the password or master key to disk. The master key lives
in zeroizing memory and is scrubbed on lock or drop.
Blocking calls and async runtimes
The library is synchronous and performs CPU-bound Argon2id work plus blocking
file I/O. It does not require Tokio or any other runtime. In an async
application, wrap calls in spawn_blocking (Tokio) or the equivalent:
#![allow(unused)]
fn main() {
use keres::{Result, Vault};
async fn add_in_background(
path: std::path::PathBuf,
password: String,
name: String,
bytes: Vec<u8>,
) -> Result<Vault> {
tokio::task::spawn_blocking(move || {
let mut vault = Vault::new(path);
vault.unlock(&password)?;
let len = bytes.len() as u64;
vault.add_from_reader(&name, &bytes[..], Some(len))?;
Ok(vault)
})
.await
.expect("blocking task panicked")
}
}
Do not hold a Vault across .await points in a single-threaded executor:
the unlocked key and the advisory lock are process resources, not async
guards.
Unlocking is intentionally expensive. Do it once per session rather than per operation, and avoid running the default parameters inside a request handler on a latency-sensitive thread.
Concurrency
Mutation methods take &mut self, so a single Vault value serializes
writes naturally. The on-disk lock coordinates processes:
- writers take an exclusive lock;
- readers take a shared lock;
- a contended call returns
Error::VaultBusyimmediately instead of waiting.
The practical model is one writer per vault and any number of readers, with
the application serializing access to a single Vault value. If several
threads need to write, put the handle behind a mutex or send operations to one
owner thread. The lock is advisory: it coordinates well-behaved processes, not
malicious ones.
Errors
All fallible operations return keres::Result<T>. Match on Error rather
than parsing messages:
#![allow(unused)]
fn main() {
use keres::Error;
fn describe(error: &Error) -> &'static str {
match error {
Error::Authentication => "wrong password or corrupted data",
Error::VaultBusy => "another process is using this vault",
Error::VaultLocked => "unlock the vault first",
Error::EntryNotFound(_) => "no such entry",
Error::InvalidEntryName(_) => "the name is not a safe vault path",
_ => "storage operation failed",
}
}
}
Wrong passwords and tampered ciphertext deliberately share
Error::Authentication. Do not add detail that turns errors into a tamper
oracle.
Choosing KDF parameters
KdfParams::new() uses Argon2id with 64 MiB, 4 passes, and parallelism 4.
That is a reasonable desktop/server default. Consider:
- Memory-constrained devices: lower
m_cost_kibandt_cost, but stay within the validated range (8 MiB minimum). Argon2id memory is the main defense against parallel offline guessing. - Long-term archives: raise
t_costandm_cost_kibif unlock latency is acceptable. - Tests and CI: use a small cost such as 8 MiB, one pass, one lane. Never ship that as the default for real data.
Parameters are stored per keyslot and per container, so a later default change
does not break existing files. New keyslots inherit the vault’s parameters.
Current releases do not raise the cost of an existing vault in place; choose
the parameters deliberately at init, and treat a change as a migration that
creates a new vault and re-adds the data.
Size padding
Padding is opt-in. Without it, an observer who can measure storage learns the
exact plaintext size of every object. With Padding::Adaptive or a fixed
bucket, they learn only the bucket:
#![allow(unused)]
fn main() {
use keres::{Padding, Vault, VaultOptions};
let mut vault = Vault::new("myvault".into());
vault.init_with_options(
"correct horse",
VaultOptions::new().padding(Padding::Adaptive),
)?;
Ok::<(), keres::Error>(())
}
Padding requires the plaintext length up front, so add_from_reader needs
Some(len) on a padded vault. Padding costs storage and a little CPU; decide
per application rather than enabling it everywhere.
Versioning and stability
Keres is pre-1.0. The on-disk format is versioned and pinned by test vectors, but the Rust API may still change between minor releases. For production embedding:
- pin the exact version in
Cargo.lockand review the changelog before upgrading; - keep a test that opens a vault created by the previous release;
- do not treat the current API as a long-term compatibility promise until a 1.0 release;
- budget for an independent security audit before storing high-value data.
The full policy, including what minor and patch releases may change, the MSRV,
and how cargo-semver-checks is enforced, is in
API stability and versioning. The format is documented so
that data is not locked to this crate forever; see
Format test vectors and
Architecture.
Checklist before shipping
- The password comes from a user or a platform secret store, never a literal in the binary.
- Unlocking happens once per session, off the async executor’s hot path.
- One writer per vault, with a documented
VaultBusyretry policy. -
verifyis available as a maintenance/diagnostic operation. - The application has a recovery plan: recovery kit, password reset, or both.
- Padding is enabled if exact sizes are sensitive.
- The crate version is pinned and the changelog is reviewed on upgrade.
- The security model limitations are acceptable for the data being stored.
CLI guide
The keres binary has two families of commands:
keres encrypt/keres decryptfor standalone.krscontainers.keres init,add,list,extract, and related commands for vaults.
Run keres help for the command list, keres <command> --help for a single
command, or see the CLI reference for every option.
Global behavior
| Behavior | Detail |
|---|---|
| Password prompts | Interactive terminal prompt by default |
| Non-interactive sources | --password-file, --password-stdin, KERES_PASSWORD |
| Exit status | 0 on success; 1 on any error, including failed verification |
| Vault location | $KERES_HOME/vaults/<name> or ~/.keres/vaults/<name> |
| Overwrite policy | Refuses existing outputs unless --force |
| Destructive operations | Ask for confirmation on a terminal; require --force otherwise |
Single files
Encrypt
$ keres encrypt document.pdf
Encrypted to: 8e2f...b71.krs
With an explicit output path:
$ keres encrypt document.pdf backup.krs
The original filename is stored inside the container, not in the output
filename. Use --padding adaptive (or a fixed bucket) to hide the exact file
size:
$ keres encrypt document.pdf --padding adaptive
$ keres encrypt document.pdf backup.krs --padding 65536
Decrypt
$ keres decrypt backup.krs restored.pdf
Decrypted 'document.pdf' to: restored.pdf
decrypt refuses to overwrite an existing output unless --force is passed.
The source .krs file is never modified.
Vault basics
Create a vault
$ keres init personal
Vault 'personal' created at /home/you/.keres/vaults/personal
init prompts twice for the password and fails if the vault already exists.
To choose a padding policy at creation time:
$ keres init private --padding adaptive
$ keres init records --padding 65536
Add entries
$ keres add personal ./notes.txt
Added successfully!
$ keres add personal ./photos --name pictures
Added successfully!
Without --name, the source basename is used. Directories are added
recursively. Symlinks and special files are skipped. A name collision is an
error; use replace for a file or remove first.
List entries
$ keres list personal
NAME SIZE TYPE
------------------------------------------------------------
notes.txt 4.2 KB file
pictures - dir
Only top-level entries are listed. A nested entry is addressed by its full
parent/child path in commands that accept an entry name.
Extract
$ keres extract personal notes.txt ./out
Extracted to: ./out/notes.txt
$ keres extract personal pictures ./out
Extracted to: ./out/pictures
Extraction recreates directory structure under the destination. It refuses to
overwrite an existing destination path unless --force is passed. Stored
names are sanitized before joining paths, so a malicious vault cannot write
outside the destination.
Modifying a vault
$ keres replace personal ./notes-v2.txt notes.txt
Replaced successfully!
$ keres rename personal notes.txt journal.txt
Renamed 'notes.txt' to 'journal.txt'
$ keres remove personal journal.txt
Remove 'journal.txt' from vault 'personal'? This cannot be undone. [y/N]
replacewrites new ciphertext under a fresh entry ID and removes the old blob after the index commit. It works on files, not directories.renamechanges the top-level name in the encrypted index; ciphertext is not rewritten.removedeletes files, or a directory and its entire subtree. On a non-interactive stdin it requires--force.
Verify and repair
$ keres verify personal
Vault integrity check:
Entries total: 42
Entries verified: 42
Status: OK — all files present and authenticated
verify decrypts every entry and checks its AEAD tags, recorded size, and
content hash. Missing and corrupted entries are listed, and the command exits
with status 1.
Interrupted operations can leave unreferenced blobs behind. After a successful check, remove them with:
$ keres verify personal --prune
--prune only runs after a successful integrity check and refuses to run if
the index snapshot is missing.
Padding policy
$ keres padding personal
Padding policy: None
$ keres padding personal --set adaptive
Padding policy set to Adaptive
$ keres padding personal --set 65536
Padding policy set to Fixed { size: 65536 }
The policy is stored in the authenticated index. It affects future adds and
replaces; existing blobs are not rewritten. --padding none restores exact
sizes. Padding hides exact sizes, not access patterns.
Passwords and automation
By default the CLI prompts on the terminal without echoing. For scripts, use one of the following sources. They are consulted in this order:
--password-file <path>or--password-stdin(mutually exclusive)KERES_PASSWORD- interactive prompt (or a plain line when stdin is not a terminal)
# First line of a file, kept out of the environment.
$ keres --password-file /run/secrets/keres init personal
# First line of standard input.
$ printf '%s\n' "$SECRET" | keres --password-stdin list personal
# Environment variable. Convenient, but visible in /proc on many systems.
$ KERES_PASSWORD="$SECRET" keres add personal ./report.pdf
Every password value is held in a zeroizing buffer and scrubbed when the
process exits. On shared machines, prefer the terminal prompt or a
permission-restricted password file over KERES_PASSWORD.
Commands that set a new password (change-password, rotate, erase,
recovery use) still prompt for the new secret and its confirmation, even if
the current password came from a file or environment variable. With
--password-stdin, the new password is read from the next stdin lines.
Destructive operations
These commands can delete data or invalidate credentials:
| Command | Effect |
|---|---|
remove <vault> <name> | Deletes an entry and its subtree |
rotate <vault> | Re-encrypts everything under a new master key; revokes other keyslots and the recovery kit |
erase <vault> <name> | Removes an entry and rotates in one commit |
migrate <vault> | One-way upgrade of a 0.5.x vault |
They ask for confirmation when stdin is a terminal. In scripts, pass
--force. Read Recovery, rotation, and migration before
using rotate, erase, or migrate.
Recovery and keyslots
Keyslot commands manage additional passphrases:
$ keres keyslot list personal
$ keres keyslot add personal
$ keres keyslot remove personal 0123456789abcdef
Recovery kits let you regain access if vault.config is lost:
$ keres recovery create personal
Recovery code (store it offline; it will not be shown again):
XXXX-XXXX-XXXX-XXXX-XXXX-XXXX-XXXX-XXXX-XXXX
recovery use personal consumes the kit and resets the password. The full
procedures and caveats are in
Recovery, rotation, and migration.
Exit status and output
0— command completed successfully.1— any error: invalid password, missing entry, failed verification, declined confirmation, I/O failure, or an unsupported format.- Human-readable progress and results go to stdout; errors go to stderr as
Error: <message>.
There is no machine-readable (JSON) output mode yet. Scripts that need to parse results should prefer the library API.
Recovery, rotation, and migration
This chapter covers operations that change credentials, keys, or the on-disk format. Read the relevant section before running the command: several of these operations are deliberately destructive.
Password changes versus key rotation
| Operation | What changes | Stored ciphertext | Other keyslots | Recovery kit | Cost |
|---|---|---|---|---|---|
| Change password | The wrapped master key in one keyslot | Untouched | Keep working | Keep working | One Argon2id derivation |
| Deep rotation | A new master key and config | Re-encrypted | Revoked | Removed | Reads and rewrites every entry |
| Erase | New master key; one entry removed | Survivors re-encrypted | Revoked | Removed | Full rotation |
| Migration | Manifest v2 → v3 with fresh entry IDs | Re-encrypted | Kept | Kept | Reads and rewrites every entry |
Changing a password is cheap and should be the default. Rotate only when the data key itself may be compromised, or when policy requires periodic re-encryption.
Keyslots
A keyslot is an independent wrapping of the vault’s master key. Every slot unlocks the same vault; none is more privileged than another.
$ keres keyslot list personal
SLOT NOTE
------------------------------------------------------------
0123456789abcdef
$ keres keyslot add personal
Current vault password:
New passphrase:
Confirm new password:
Added keyslot 89abcdef01234567.
Store the new passphrase separately; any keyslot unlocks the same vault.
$ keres keyslot remove personal 0123456789abcdef
Password for a keyslot that will remain:
Removed keyslot 0123456789abcdef.
Rules enforced by the CLI and library:
- A slot is identified by a random 16-hex-character id.
- Adding a slot requires an existing passphrase.
- Removing a slot requires a passphrase from a slot that will remain, so a mistyped target cannot delete your only credential.
- The last slot cannot be removed.
- New passphrases must differ from the authorizing passphrase.
Slot ids and the slot count are plaintext metadata in vault.config. The
passphrases and master key are not.
Revocation is not rotation
Removing a keyslot drops that wrapping. It does not change the master key. Anyone who already used the revoked passphrase to unwrap the master key can still decrypt existing ciphertext. If a passphrase or device was compromised, run a deep rotation.
Recovery kits
A recovery kit is a second wrapping of the master key, protected by a random
160-bit code printed once. It exists so a lost or damaged vault.config does
not brick the vault.
Create a kit
$ keres recovery create personal
Enter vault password:
Recovery code (store it offline; it will not be shown again):
XXXX-XXXX-XXXX-XXXX-XXXX-XXXX-XXXX-XXXX-XXXX
A wrapped copy of the master key was written to /home/you/.keres/vaults/personal/vault.recovery.
Keep the code separate from the vault: either alone is not enough.
Store the code offline, separately from the vault directory. Anyone holding both the vault directory and the code can unlock the vault.
Creating a new kit replaces the old file and invalidates the old code:
$ keres recovery create personal --force
Recover after losing the config
If vault.config is missing or corrupt but vault.recovery survives:
$ keres recovery use personal
Recovery code:
New password:
Confirm new password:
Vault recovered. The recovery kit was consumed; create a new one if needed.
Recovery:
- unwraps the master key with the code;
- verifies that key against the encrypted index;
- writes a fresh single-slot
vault.configunder the new password; - deletes the kit so the code cannot be replayed.
Any additional keyslots are lost and must be re-added. If both the password and the recovery code are lost, the vault is unrecoverable.
The code is a second offline guessing target. It is 160 bits plus Argon2id, which makes exhaustive search infeasible, but it must still be handled like a password.
Deep rotation
Deep rotation generates a new master key and re-encrypts every entry. Use it when:
- a password or master key may have leaked;
- you are retiring a device that held a keyslot;
- policy requires re-encrypting stored data.
$ keres rotate personal
Rotate vault 'personal'? Every entry is re-encrypted under a fresh master key; 2 other keyslots will be revoked and the recovery kit will be deleted; the vault is left locked under the new password. [y/N] y
Current password:
New password:
Confirm new password:
Rotated: re-encrypted 42 entries (1.2 GB).
Revoked 2 other keyslots.
Removed the old recovery kit; create a new one with `keres recovery create`.
The vault is locked; unlock it with the new password.
Consequences:
- All entries are re-encrypted under a fresh master key.
- The vault ends up with exactly one keyslot, under the new password.
- Other keyslots stop working.
- Any recovery kit is removed; create a new one afterwards.
- The vault is left locked.
- The operation can take a long time and temporarily needs extra disk space for the new blobs.
If the process dies mid-rotation, the next operation that opens the vault
either completes or rolls back the rotation using the vault.rotate journal.
Old-key blobs listed in the journal are deleted; leftovers can be reclaimed
with keres verify --prune.
Rotation is not retroactive: ciphertext copied by an attacker before the rotation remains decryptable with the old key material.
Erasure
erase combines removal with rotation. It omits one entry and re-encrypts
every survivor under a fresh master key in one journaled commit.
$ keres erase personal old-secret.txt
Erase 'old-secret.txt' from vault 'personal'? This re-encrypts every other entry under a fresh master key. [y/N] y
Enter vault password:
New password after erase:
Confirm new password:
Erased 'old-secret.txt': re-encrypted 41 entries (1.1 GB).
Use it when a deleted entry’s old ciphertext must stop being usable with the current key. The old entry is left out of the new index, and survivors are re-encrypted. If the rotation fails, the old vault (including the entry) is left intact.
Erasure is forward-looking. It cannot revoke a copy of the deleted blob that was captured earlier together with the old key or config.
Migrating a 0.5.x vault
Keres 0.5.x wrote manifest version 2. The current reader rejects it with
MigrationRequired; it does not silently upgrade.
$ keres migrate legacy-vault
Migrate vault 'legacy-vault' to the current format? Every entry is re-encrypted in place. [y/N] y
Enter vault password:
Migrated 128 entries (640 MB re-encrypted).
Before migrating:
- Stop any process using the vault.
- Back up the entire vault directory, including
d/. - Keep the old release available until the migration is verified.
Migration is one-way. It keeps the same password, re-encrypts every entry
under a fresh entry ID, commits the new manifest atomically, and removes the
legacy blobs. A failure before the commit leaves the legacy manifest intact.
Afterwards, run keres verify and confirm access to a few entries before
deleting the backup.
Changing padding policy
$ keres padding personal --set adaptive
Padding policy set to Adaptive
The policy is stored in the authenticated index and applies to future adds and replaces. Existing blobs keep their original size until they are rewritten. Changing the policy does not rewrite the vault. To re-bucket existing entries, replace each entry one by one (or rewrite the vault).
Backup and restore
There is no special backup command. A vault is a directory; copy it while no
process is writing. Include every file, including vault.config, d/, and
vault.recovery if present.
Restoring an older copy of the directory rolls the vault back to that point. Keres detects snapshot/log swaps and substituted blobs, but it does not have a hardware-backed anti-rollback counter. Treat backups as sensitive data: they contain ciphertext and the config material needed to attempt offline password guesses.
After any interrupted add, remove, rotation, or compaction, run:
$ keres verify personal
$ keres verify personal --prune
--prune deletes only unreferenced blobs and stale temp files, and only after
a successful verification.
Keres Desktop
keres-desktop/ is a graphical client for Keres. It is a Rust +
iced application that embeds the library directly; it does not shell out to
the CLI.
The GUI is a separate Cargo workspace and is excluded from the library workspace. It is a reference consumer and a showcase, not part of the library’s compatibility contract.
What it shows
- The full vault lifecycle: create with padding and KDF options, unlock, lock, verify, migrate a legacy v2 manifest, rotate the master key, and crypto-erase an entry.
- Keyslots and recovery: independent passphrases, a one-time recovery kit, and recovery of a closed vault.
- The in-memory reader/writer APIs: the password store never writes plaintext to a temporary file.
- Honest security UX: a page that lists the threat model, known limitations, and the lack of an independent audit.
- Readability controls: the navbar scales all text from 80% to 300%, and the visual style uses sharp corners throughout.
The app is focused on storage. The generic symmetric, hash, key, and sign pages were removed so the vault, password store, and file containers lead.
Build and run
cd keres-desktop
cargo run
A graphical session is required. On Linux, use the included Nix flake for the toolchain and system libraries:
cd keres-desktop
nix develop
cargo run
See keres-desktop/README.md for the data layout, KERES_HOME, legacy
~/.krypton fallback, and development commands.
Security status
Keres has not had an independent security audit. The desktop app is a showcase and a reference consumer, not a security boundary. Read the security model and the stability policy before using it with high-value data.
CLI reference
This page is the command reference for the keres binary. For task-oriented
examples, see the CLI guide.
Synopsis
keres [GLOBAL OPTIONS] <COMMAND> [ARGS]
$ keres --version
keres 0.7.1
Global options
| Option | Meaning |
|---|---|
--password-file <PATH> | Read the password from the first line of PATH |
--password-stdin | Read the password from the first line of standard input |
-h, --help | Print help |
-V, --version | Print the version |
--password-file and --password-stdin conflict. Both are global and may be
placed before or after the subcommand. If neither is given, the CLI uses
KERES_PASSWORD, then an interactive prompt.
Environment variables
| Variable | Used by | Meaning |
|---|---|---|
KERES_HOME | CLI | Base directory for vaults; vaults live in $KERES_HOME/vaults/ |
KERES_PASSWORD | CLI | Password fallback when no explicit source is given |
HOME / USERPROFILE | CLI | Default home directory when KERES_HOME is unset |
An empty KERES_HOME, or an empty home directory, is an error rather than a
silent fallback.
Vault commands
Vault names are plain names, not paths. The CLI rejects names containing /
or \, ./.., an empty name, and vault locations that are symlinks.
keres init
keres init <VAULT> [--padding <POLICY>]
Creates a vault under the default vault directory and leaves it unlocked for that process only. Prompts twice for the password.
| Argument | Meaning |
|---|---|
<VAULT> | Vault name |
--padding <POLICY> | none (default), adaptive, or a fixed bucket size in bytes |
Example:
$ keres init personal --padding adaptive
keres add
keres add <VAULT> <PATH> [--name <NAME>]
Adds a file or a directory tree recursively. The default name is the source basename. Symlinks and special files are skipped. A colliding name is an error.
| Option | Meaning |
|---|---|
-n, --name <NAME> | Name in the vault instead of the source basename |
keres replace
keres replace <VAULT> <PATH> <NAME>
Replaces the contents of an existing file entry with PATH. Directory
entries cannot be replaced. The operation is copy-on-write and commits the
index before deleting the old blob.
keres rename
keres rename <VAULT> <FROM> <TO>
Renames a top-level file or directory. Nested paths are not accepted. Stored ciphertext is not rewritten.
keres remove
keres remove <VAULT> <NAME> [--force]
Removes a file, or a directory and its entire subtree. Asks for confirmation
on a terminal; requires --force on a non-interactive stdin.
keres list
keres list <VAULT>
Lists top-level entries with name, size, and type. Directory sizes are shown
as -. Does not touch entry blobs.
keres extract
keres extract <VAULT> <NAME> <DEST> [--force]
Extracts a file or directory tree under DEST. Recovered names are sanitized
before path joins. The destination must not already exist unless --force is
given.
keres change-password
keres change-password <VAULT>
Re-wraps one keyslot under a new password. Stored data and other keyslots are untouched. Prompts for the current password, then the new password twice. The new password must differ from the current one.
keres verify
keres verify <VAULT> [--prune]
Authenticates the index and every entry, checks recorded sizes and content
hashes, and prints missing/corrupted entries. Exits with status 1 if any
entry fails.
| Option | Meaning |
|---|---|
--prune | After a successful check, delete unreferenced blobs and stale temp files under d/ |
keres padding
keres padding <VAULT> [--set <POLICY>]
Without --set, prints the current policy. With --set, changes it for
future writes. Existing blobs keep their original sizes.
keres rotate
keres rotate <VAULT> [--force]
Deep rotation: generates a fresh master key, re-encrypts every entry, rewrites
the index, collapses the vault to one keyslot under the new password, and
removes any recovery kit. The vault is left locked. Asks for confirmation on
a terminal; requires --force otherwise.
keres erase
keres erase <VAULT> <NAME> [--force]
Removes one entry and performs a deep rotation in a single journaled commit. Survivors are re-encrypted under a fresh master key. Other keyslots and the recovery kit are removed. Leaves the vault locked under a new password.
keres migrate
keres migrate <VAULT> [--force]
One-way upgrade of a 0.5.x vault (manifest v2) to the current format. Every entry is re-encrypted in place, the same password is kept, and legacy blobs are removed after the commit. Back up the vault directory first.
Recovery commands
keres recovery create
keres recovery create <VAULT> [--force]
Creates or replaces vault.recovery, writes a second wrapping of the master
key, and prints a one-time recovery code. --force replaces an existing kit;
the old code stops working.
keres recovery use
keres recovery use <VAULT>
Prompts for the recovery code, validates it against the encrypted index, sets a new password, and consumes the kit. Additional keyslots are lost.
Keyslot commands
keres keyslot list
keres keyslot list <VAULT>
Lists plaintext slot ids from vault.config. No password required.
keres keyslot add
keres keyslot add <VAULT>
Adds an independent passphrase that unlocks the same master key. Prompts for an existing passphrase, then the new one twice.
keres keyslot remove
keres keyslot remove <VAULT> <SLOT>
Revokes a slot. Prompts for a passphrase from a slot that will remain, so a mistyped target cannot remove the only credential. The last slot cannot be removed.
Single-file commands
keres encrypt
keres encrypt <INPUT> [OUTPUT] [--force] [--padding <POLICY>]
Encrypts one file into a .krs container. With no OUTPUT, a hash-derived
name is written in the current directory. Refuses to overwrite an existing
output unless --force is given.
| Option | Meaning |
|---|---|
-f, --force | Overwrite an existing output |
--padding <POLICY> | none (default), adaptive, or a fixed bucket size |
keres decrypt
keres decrypt <INPUT> <OUTPUT> [--force]
Decrypts a .krs container, recovers the original filename, and writes the
plaintext to OUTPUT. Refuses to overwrite an existing output unless
--force is given.
Padding policies
| Value | Behavior |
|---|---|
none | No padding; exact plaintext size is visible in ciphertext length |
adaptive | Next power of two in 4 KiB–16 MiB; larger files round to the next 16 MiB multiple |
| integer | Fixed bucket size in bytes; must be in 4 KiB–16 MiB |
Examples: --padding none, --padding adaptive, --padding 65536.
Padding hides exact sizes, not access patterns. The vault policy is stored in the authenticated index; the single-file policy is recorded in the container.
Exit status
| Status | Meaning |
|---|---|
0 | Success |
1 | Error, failed verification, declined confirmation, or unsupported format |
Errors are printed to stderr as Error: <message>. Prompts and results are
printed to stdout.
Files written by the CLI
| Path | Contents |
|---|---|
$KERES_HOME/vaults/<name>/ or ~/.keres/vaults/<name>/ | Vault directory |
<hash>.krs | Single-file container when no output is given |
vault.recovery | Recovery kit, if created |
The vault directory layout is documented in Vault layout.
Architecture
Keres has four layers:
- Primitives — AES-256-GCM, Argon2id, HKDF-SHA256, SHA-256, and the OS CSPRNG.
- Stream engine — 64 KiB authenticated records.
- Container — the universal envelope shared by
.krsfiles, vault blobs, and the vault index. - Vault — key hierarchy, encrypted index, keyslots, journals, and file operations.
The layers are deliberately separate. A format change should not require a new crypto primitive, and a new vault operation should not need a new container format.
Cryptographic primitives
All primitives come from RustCrypto crates (aes-gcm, argon2, hkdf,
sha2, subtle). Randomness comes from the operating system CSPRNG.
| Primitive | Parameters | Used for |
|---|---|---|
| AES-256-GCM | 96-bit nonces, 128-bit tags | Every byte of ciphertext |
| Argon2id | Default 64 MiB, t=4, p=4; stored per container | Password → KEK |
| HKDF-SHA256 | Random 32-byte salt per object | Master/subkey separation and index-log keys |
| SHA-256 | — | Blob path derivation and per-entry content hashes |
subtle::ConstantTimeEq | — | Secret comparisons where needed |
KDF parameter bounds
Parameters travel inside containers so defaults can evolve. Because they are attacker-visible input, parsing enforces hard bounds to prevent denial of service:
| Field | Default | Accepted range when reading |
|---|---|---|
m_cost_kib | 65,536 (64 MiB) | 8 MiB – 4 GiB |
t_cost | 4 | 1 – 64 |
p_cost | 4 | 1 – 16 |
A hostile container can force at most a bounded amount of derivation work — never unbounded allocation or an infinite loop.
Key hierarchy
Two derivations exist, selected per container by a kind byte.
Standalone .krs (kind = password):
password ──Argon2id(argon_salt, params)──► KEK
──HKDF(object_salt, info)───────► content key
Vault objects (kind = hkdf):
vault.config: password ──Argon2id(slot salt, params)──► KEK
──AES-GCM-wrap──► master key
entry blob: master ──HKDF(object_salt, "keres-container-v1/" ‖ entry_id)──► content key
manifest: master ──HKDF(object_salt, "keres-container-v1/vault-manifest")──► content key
index log: master ──HKDF(log_id, "keres-vault-index-log-v1")──► log key
Properties that follow:
- Per-object keys. Every object has a fresh 32-byte object salt and an independent HKDF subkey.
- Password changes do not touch ciphertext. Only the wrapped master key
in
vault.configis re-encrypted. - No offline verifier. There is no password hash to check guesses against; every guess costs a full Argon2id run plus GCM verification.
- Renames do not re-encrypt. Vault blobs are bound to a stable random entry ID, not to the mutable path.
The universal container format
Every object the library produces — .krs files, vault blobs, manifests — is
one envelope. It is defined in src/container.rs; constants are public where
meaningful (MAGIC, ENVELOPE_VERSION).
Wire layout
offset size field
────────────────────────────────────────────────────────────────
0 8 "KERES\0\0\0" magic (NUL is a control byte:
cannot occur in ordinary text)
8 2 u16 LE envelope version (1, or 2 with padding)
10 1 kind 0 = HKDF-from-master
1 = password-derived
11 32 (kind 0) object_salt
11 76 (kind 1) argon_salt[32] ‖ object_salt[32]
‖ KdfParams[12] (three u32 LE)
… var chunk records [len u32 LE][ciphertext‖tag], repeated
… 4 00 00 00 00 end-of-chunks marker (unauthenticated;
safe — see below)
… 4 len u32 LE trailer length (≤ 1 MiB enforced)
… len trailer AES-GCM ct‖tag of JSON
Header sizes: 43 bytes for kind 0 and 87 bytes for kind 1. Padded containers add a 25-byte authenticated prelude after the header (see Size padding).
Header authentication
There is no separate header MAC. The header is authenticated implicitly: the magic and version are checked directly, while the kind, salts, and KDF parameters feed key derivation. Flipping any of those bytes yields a wrong key or an early parse error, so the first GCM tag check fails.
Any file whose magic is not exactly KERES\0\0\0 is rejected with
Error::IncompatibleFormat. That includes pre-rename Krypton containers,
pre-0.4 formats, and unrelated files. A newer envelope version fails with
UnsupportedVersion. Vaults are the one exception: a readable 0.5.x manifest
is reported as MigrationRequired and can be upgraded with keres migrate.
Trailer
After the chunk section, one final record carries a JSON document sealed with
the same content key under the reserved nonce [0xFF; 12]:
{
"typ": "file" | "directory" | "manifest",
"name": "original-filename.txt",
"size": 12345,
"chunk_count": 1
}
name is present for standalone .krs files and absent for vault objects.
On read, the trailer is cross-checked against observation:
typmust equal the caller-requested payload type;sizemust equal the decrypted byte count;chunk_countmust equal the number of records read;- nothing may follow the trailer.
Truncation, extension, and appended-junk attacks fail here even if a naive reader would have accepted a valid prefix.
Identity binding
Containers carry a caller-supplied identity string that participates in key
derivation: info = "keres-container-v1/" ‖ identity.
| Object | Identity | Effect |
|---|---|---|
| Vault entry blob | Stable random entry ID, e.g. "00112233…" | Copying one entry’s blob over another’s slot fails authentication; renaming does not invalidate a blob |
| Manifest | "vault-manifest" | Fixed constant; the manifest location is canonical |
Standalone .krs | Empty | Files are self-contained; there is nothing to bind |
Each entry gets a random 128-bit ID when it is added. The ID is stored in the
manifest and never changes, so blob location and AAD are independent of the
entry’s mutable path. This closes the blob-transplant attack: swapping two
blobs in the vault directory yields Corrupted entries from verify() and
errors on extract, never silently wrong content. The authenticated index also
records the plaintext SHA-256, so replaying an older valid blob under the same
entry ID is rejected.
Payload types
PayloadType has three variants: File, Directory, and Manifest. Adding
a new container kind means adding a variant with a new AAD context string —
never changing existing ones.
Chunking, nonces, and AAD binding
src/stream.rs implements record framing shared by all containers.
Chunk records
Plaintext streams through in 64 KiB chunks (CHUNK_SIZE). Each becomes one
record: [len u32 LE][ciphertext ‖ 16-byte GCM tag]. Lengths outside
16 ..= 64 KiB + 16 are rejected before allocation. There is no compression,
so there is no decompression-bomb analogue.
The maximum object size is 2^24 chunks × 64 KiB = 1 TiB. The
MAX_CHUNK_COUNT guard prevents nonce-space exhaustion and counter overflow.
Nonce strategy
| Record type | Nonce | Rationale |
|---|---|---|
| Data chunk i | [0x00; 4] ‖ i as u64 BE | Counter-based; collision-free within an object regardless of restarts |
| Padding metadata | [0xFE; 12] | Reserved domain, distinct from data and trailer |
| Trailer | [0xFF; 12] | Reserved domain, distinct from data |
| Config slot | Random 96-bit nonce | Fresh wrapping per slot write |
| Recovery kit | Random 96-bit nonce | Fresh wrapping per kit |
| Index-log record | Random 96-bit nonce | Fresh nonce per record under a per-log key |
Counter nonces eliminate the birthday-bound reuse risk of random nonces per
chunk. Combined with per-object salts, every (object, position) pair has a
unique (key, nonce) tuple.
AAD matrix
Every GCM operation binds context. Nothing is decrypted “bare”:
| Operation | AAD |
|---|---|
| Data chunk i | "keres-container-v1/{file|directory|manifest}" ‖ index bytes |
| Padded metadata | "keres-container-v2/padding" |
| Trailer | chunk context ‖ index ‖ "/trailer" |
| Config slot | "keres-vault-config-v3/" ‖ slot id |
| Recovery kit | "keres-vault-recovery-v1" |
| Index-log record | "keres-index-log-v1" ‖ log header ‖ record index |
Consequences:
- Reordering two chunks fails authentication.
- Moving a record between positions fails.
- Moving records between payload types fails because the context differs.
- Transplanting whole containers between logical locations fails because key derivation differs.
- The end-of-chunks marker is unauthenticated but harmless: it cannot be
forged into extra data because the authenticated trailer’s
chunk_countandsizemust match observation exactly.
Single-file mode
encrypt_file(password, input, output):
- Generates a fresh
argon_saltandobject_salt. - Builds a kind-1 container streaming the file (identity = empty) and stores the original filename in the trailer.
- Writes atomically: temp file (mode
0600) in the destination directory →fsync→rename. On Windows,renamereplaces the destination viaMoveFileExwithMOVEFILE_REPLACE_EXISTING, with no pre-delete window. - If no output path is given, produces
<sha256(argon_salt ‖ object_salt)>.krs— an opaque name that leaks nothing about content.
decrypt_file(password, input, output) authenticates the whole container
while streaming, recovers the original filename from the trailer, sanitizes
it, and returns it. Plaintext is also written through temp + rename.
Memory use is bounded by one chunk buffer (plus tag) regardless of file size.
Streaming API
keres::streaming exposes the same wire format to library code that does not
have files:
| Type / function | Direction |
|---|---|
EncryptWriter | Write: plaintext in, ciphertext out; finish() writes the trailer |
DecryptReader | Read: ciphertext in, authenticated plaintext out; EOF verifies the trailer |
encrypt_stream / decrypt_stream | Convenience loops that preserve the typed Error |
StreamOptions adds a cumulative-byte progress callback and an AtomicBool
cancellation flag polled once per chunk. Cancellation returns
Error::Cancelled; through the io adapters it is wrapped in an
io::Error, with the typed error recoverable from its source.
Every chunk is authenticated before its plaintext is yielded, but the trailer
holds the total size and chunk count, so a truncated or trailer-tampered
stream can deliver authenticated plaintext before the final error. File
writers should stage output through temp + rename, exactly as decrypt_file
does. This is inherent to streaming, not a weakness in chunk authentication.
Vault layout
A vault is a directory:
myvault/
├── vault.config bootstrap JSON: keyslots wrapping the master key
├── vault.recovery optional second wrapping (recovery kit)
├── vault.rotate transient deep-rotation journal
├── vault.lock advisory inter-process lock (empty)
└── d/
├── .manifest.enc compacted index snapshot (kind-0 container)
├── .index.log encrypted append-only mutations
├── .index.compact transient compaction journal
├── .manifest.enc.next staged manifest during rotation
├── .index.log.next staged log during compaction
├── .index.snapshot.next staged snapshot during compaction
└── <h2>/<h48>.enc one blob per entry
Every mutation takes an exclusive advisory lock on vault.lock; reads
(list, extract, verify) take a shared lock. Locks are non-blocking: a
second process receives Error::VaultBusy instead of waiting and racing on a
stale index. The lock is released when the operation returns. flock(2) is
used on Unix and LockFileEx on Windows via fs4.
If a rotation or index compaction committed but did not finish, the next operation that takes the lock recovers it first. A reader that only needs a shared lock silently upgrades to the exclusive lock for that recovery step.
vault.config
vault.config is a small JSON document — not a container, because it must be
parseable before any key exists. Version 3 holds a table of independent
keyslots, each wrapping the same master key under its own password-derived
KEK:
{
"version": 3,
"slots": [
{
"id": "0123456789abcdef",
"kdf": {"m_cost_kib": 65536, "t_cost": 4, "p_cost": 4},
"salt": [/* 32 bytes */],
"nonce": [/* 12 bytes */],
"wrapped_master_key": [/* master ‖ GCM tag */]
}
]
}
The master key is generated once at init. Each slot has a fresh random salt,
a random 96-bit nonce, and AAD "keres-vault-config-v3/" + slot_id, so
wrapped keys cannot be transplanted between slots. Unlocking tries each slot;
change_password re-wraps only the slot that matched; add_keyslot appends a
slot; remove_keyslot deletes one and must be authorized by a passphrase from
a slot that remains. Slot ids are plaintext, like the rest of the bootstrap
structure. Wrong password and tampered config are both Authentication; a
structurally malformed slot is InvalidVault.
Version 2 configs (the 0.5.x single implicit slot, fixed nonce, AAD
"keres-vault-config-v2") are still read and are rewritten as version 3 the
next time a key operation changes the config. The existing password does not
change during that upgrade.
vault.recovery
Optional. Created by keres recovery create /
Vault::create_recovery_kit: a second, independent wrapping of the same
master key.
{
"version": 1,
"kdf": {"m_cost_kib": 65536, "t_cost": 4, "p_cost": 4},
"salt": [/* 32 bytes */],
"nonce": [/* 12 bytes */],
"wrapped_master_key": [/* master ‖ GCM tag */]
}
The KEK is Argon2id over a random 160-bit code, printed once as nine groups of
four Crockford Base32 symbols with a 16-bit checksum. The code is never
stored. The file is not a container because it must be parsed before any key
exists; AEAD with a random nonce and AAD "keres-vault-recovery-v1"
authenticates it.
Vault::recover validates the unwrapped master against the encrypted index,
re-wraps vault.config as a fresh single-slot config, and consumes the kit.
Losing vault.config no longer bricks the vault; losing the code still does.
Any extra keyslots are lost in recovery and must be re-added.
vault.rotate
Vault::rotate / keres rotate performs an opt-in deep rotation: it
generates a fresh master key, streams every blob through re-encryption, and
rewrites the index under the new key. The new config has exactly one keyslot
under the new password; other keyslots and the recovery kit wrapped the old
master key and are discarded.
Rotation writes d/.manifest.enc.next, then a small vault.rotate journal
containing the new config (already wrapped) and the SHA-256 of the staged
manifest — never a plaintext key:
{
"version": 1,
"manifest_sha256": "…64 hex…",
"config": "{…v3 config…}",
"old_blobs": ["d/ab/cd….enc", "…"]
}
The journal write is the commit point. After it, the staged manifest is
renamed over .manifest.enc, the config is replaced, the old recovery kit is
removed, and the journal is deleted. If the process dies after the journal but
before completion, the next operation that opens the vault finishes the swap:
it compares the journal hash against the canonical and staged manifests,
promotes the staged one when it matches, and installs the config. If neither
manifest matches, the rotation is rolled back and the journal is discarded.
Before the journal exists, the old vault is untouched and the staged blobs are
ordinary orphans for prune_orphans.
old_blobs lists the old-key ciphertext paths so recovery can delete them
even though the old master is no longer available. Only paths under d/
ending in .enc (other than .manifest.enc) are accepted. Rotation removes
them best-effort after the swap; leftovers are reclaimed by
verify --prune.
Vault::erase reuses this machinery: the entry to erase is added to the
rotation’s removed set, so omission and re-encryption commit together. If
rotation fails, the old vault (including the entry) is left intact.
Blob locations
blob_path(entry_id) = d / sha256(master_key ‖ entry_id)[..2] /
sha256(...)[2..50] + ".enc"
Paths are deterministic (stable across restarts and renames), keyed by the master key (so unrelated vaults never share blob names), and leak nothing but entry count and rough sizes via the tree shape. Because the hash input is the entry’s stable ID rather than its path, renaming an entry only updates the encrypted index; no ciphertext is re-encrypted.
Index: snapshot + append-only log
The logical index is a BTreeMap<String, EntryMetadata> serialized to JSON.
Each entry records a non-empty 128-bit hex id, original name, size,
directory flag, child lists, and an optional SHA-256 of the plaintext
(content_hash). The hash binds a blob to the exact contents recorded by the
index; it is None for entries written by releases before the field existed,
which are size-checked only.
The index is stored in two parts:
d/.manifest.enc— a compacted snapshot, written as a kind-0 container with payload typeManifest.d/.index.log— encrypted, authenticated mutation batches appended after that snapshot.
Saving an operation does not rewrite the whole snapshot. The library loads
the logical index (snapshot plus replayed log), computes the put/delete
records that turn it into the new map, and appends one batch. Reading decodes
the snapshot once and replays each batch in order.
log header: b"KERESIDX" | version u16 | generation u64 |
snapshot_sha256[32] | log_id[32]
log record: len u32 | index u64 | nonce[12] | ciphertext ‖ GCM tag
Each log gets a random log_id; its record key is
HKDF(master, log_id, "keres-vault-index-log-v1"). Record AAD binds the full
header bytes and the record index, so records cannot be moved between logs,
reordered, or replayed under another generation. The header’s snapshot hash
ties the log to exactly one snapshot: mixing a log with a different snapshot
is InvalidVault, and a log whose key does not authenticate is
Authentication.
The snapshot’s authenticated JSON also carries a monotonic generation
(pre-generation v3 snapshots read as 0). A log must declare the same
generation as the snapshot it extends; a mismatch is InvalidVault.
Compaction writes generation + 1 into the new snapshot and its empty log.
Generations make replace/compaction swaps unambiguous, but without
hardware-backed state they are not rollback detectors.
A log batch is written with one write_all plus sync_data. A crash may
leave a torn final record; replay stops at the last valid record and the next
append truncates the tail. Damage in the middle of the log is an error, never
a silent truncation.
When the log reaches 512 records or 8 MiB, the next save compacts it: a fresh
snapshot is written, a new empty log is created that names it by SHA-256, and
the old log is removed. Compaction is journaled in d/.index.compact; an
interrupted compaction is finished on the next lock acquisition. Deep rotation
and migration install a new snapshot and remove any log encrypted under the
old index key.
Version 2 manifests are rejected by the reader with MigrationRequired (and
an empty ID in a version 3 manifest is rejected as InvalidVault; IDs are the
root of blob identity, so a missing one cannot be repaired safely).
Vault::migrate / keres migrate upgrades a v2 vault in place: it
re-encrypts every entry under a fresh ID, then commits the v3 snapshot
atomically. A failure before that commit leaves the legacy manifest intact.
Load semantics:
| State | Result |
|---|---|
| Snapshot absent | error — only init creates the first snapshot; treating it as empty would drop every record on the next save |
| Snapshot present but damaged, truncated, or unauthentic | error — never silently empty |
| Log present but snapshot absent, or bound to another snapshot/generation | error |
| Snapshot larger than the 64 MiB read cap | rejected before allocation |
Vault operations
| API | Behavior |
|---|---|
init(pw) | Creates the directory (mode 0700) and empty index snapshot, then writes the config; refuses to clobber a config-less vault that still has a recovery kit |
unlock / lock | Unwraps the master into memory / drops it |
add(src, name) | Validates a single-component root name, rejects collisions, pre-flights directories, writes every blob via temp + rename, appends the index batch last |
replace(src, name) | Writes a fresh blob under a new entry ID (copy-on-write), appends the index record, then deletes the old blob; directory entries are rejected |
rename(from, to) | Top-level only; pre-checks every destination in the moved subtree; appends put records for new keys and child lists without touching ciphertext |
add_if / replace_if | Conditional variants; return WriteOutcome and write nothing when the precondition fails |
apply_batch(ops) | Applies adds/replaces/removes with one index commit; old blobs are deleted after the commit |
list() | Reads snapshot + log only; no blobs touched |
extract(name, dest) | Recreates hierarchy, sanitizes names, verifies size and content hash, writes outputs via temp + rename |
remove(name) | Drops subtree index records and commits, then deletes blobs best-effort; a failed deletion leaves a pruneable orphan, never a dangling index |
erase(name, new_pw) | Omits the subtree and performs a deep rotation in one journaled commit; on failure the old vault and entry remain |
change_password(old, new) | Verifies old, re-wraps only that keyslot; ciphertext and other slots untouched |
rotate(old, new) | Deep rotation: fresh master key, all blobs re-encrypted, snapshot rewritten, old log removed; collapses to one keyslot, removes the recovery kit, leaves the vault locked |
keyslots() | Lists plaintext slot ids; no password required |
add_keyslot(existing, new) | Verifies an existing passphrase and appends an independent slot; upgrades a legacy config |
remove_keyslot(id, pw) | Revokes a slot, authorized by a passphrase from a slot that remains; the last slot is refused |
verify(pw) | Decrypts every blob (type-checked), checks size and content hash against the replayed index; returns IntegrityReport |
prune_orphans() | Deletes .enc blobs and stale .tmp-* files under d/ that no index record references; refuses if the snapshot is missing |
migrate(pw) | One-way v2 → v3 upgrade: re-encrypts every entry under a fresh ID, swaps the snapshot atomically, then removes legacy blobs |
create_recovery_kit(pw) | Verifies the password, writes vault.recovery, returns a one-time RecoveryCode |
recover(code, new_pw) | Unwraps the master with the code, validates it against the index, re-wraps the config, consumes the kit |
Directory removal walks the manifest’s own child lists (and the /-prefixed
range, so a stale child list cannot strand descendants), so removing a
directory removes everything beneath it even if nested names were added out of
order.
Path-traversal defense
Names recovered from trailers and manifests pass through src/sanitize.rs:
absolute paths, .. components, drive letters, separators, and NUL bytes are
rejected or rewritten before joining. An encrypted archive cannot plant files
outside the destination.
Crash safety and durability
Invariant: a crash may lose the current operation, never corrupt previous state.
- All persistent writes go through: create a temp file in the same directory →
restrict to owner-only → write →
sync_all()→rename()over the target →sync_dir()on the parent directory. - Containers and snapshots are immutable once written; updates replace whole files via temp + rename. The index log is the one append-in-place file; it is record-framed so a torn final write is detected and truncated.
- A failure mid-add leaves unreferenced blobs (the index batch was not
appended). They are invisible to readers and reclaimed by
verify --prune/Vault::prune_orphans. - Replaces are copy-on-write: a fresh blob and entry ID are written, the index is committed, and only then is the old blob deleted. A failed replace leaves the previous version fully readable.
- Removals commit the index first and delete blobs afterwards, so a deletion failure can leave an orphan but never an index that points at missing data.
apply_batchwrites all new blobs and computes the final index in memory before its single commit. A failure leaves the index unchanged; fresh blobs become pruneable orphans.- Deep rotation commits through
vault.rotatebefore touching the canonical index, so an interrupted run is either rolled back or completed on the next open. A staged.manifest.enc.nextwithout a journal is ignored. - Index compaction commits through
d/.index.compactbefore the snapshot/log swap. An interrupted run promotes or discards the staged pair on the next lock acquisition; staged files without a journal are deleted.
Memory hygiene
- Every key is
Key(Zeroizing<[u8; 32]>); plaintext buffers that contain secrets (master key, manifest JSON, trailer records) useZeroizing<Vec<u8>>. They are overwritten on drop. DebugforKeyprintsKey([REDACTED]); keys are passed by reference and never serialized or logged.- Chunk buffers are reused; scratch vectors holding secret material are zeroizing types.
- Not implemented by design, because
forbid(unsafe_code)blocks the calls:mlockand core-dump suppression. These are roadmapped behind a small audited unsafe boundary.
Size padding
By default a container’s ciphertext length tracks its plaintext length. That leaks the file size to anyone who can measure the storage medium. Opt-in padding rounds the plaintext up to a bucket before encryption, so an observer learns only the bucket.
Padding is selected per container:
.krs: aPaddingpassed toencrypt_file_with_padding(CLI:--padding).- Vault: a
Paddingstored in the authenticated index snapshot (ManifestFile.padding, defaultNone), so a storage attacker cannot silently disable it.Vault::padding/set_paddingexpose it. - Manifests and directory placeholders are always unpadded.
When padding is not None, the container uses envelope version 2. The
wire layout gains one authenticated fixed-width (25-byte) record after the
header and before the chunk section:
8 real size (BE) ‖ 8 padded size (BE) ‖ 1 mode ‖ 8 fixed bucket (BE)
It is sealed under nonce [0xFE; 12] with AAD keres-container-v2/padding.
The chunk section then contains exactly padded_size plaintext bytes: the
real bytes followed by zero-filled padding. Chunk boundaries depend only on
padded_size, so the last record’s length reveals only the bucket. The
trailer’s size field binds the padded length, so its variable-length
JSON does not leak the number of digits in the real size. On read, the reader
trims to the real size from the prelude and normalizes trailer.size to it
before returning.
Policies (Padding):
None— no padding (default, compact format).Adaptive— next power of two, clamped to[4 KiB, 16 MiB]; larger payloads round to the next multiple of 16 MiB.Fixed { size }— next multiple ofsize, which must lie in the same range.
DecryptReader supports v2 containers and yields only real plaintext.
EncryptWriter remains unpadded because it cannot know the total length
upfront.
Compatibility and versioning
Rules that keep the ecosystem stable:
- The 8-byte magic never changes, including the NUL control bytes.
- Envelope revisions bump the
u16version field; readers reject unknown versions withUnsupportedVersion. Released versions remain readable. - A released
PayloadTypenever changes meaning. New object kinds are new types with new AAD contexts. - Schema-bearing payloads (config v3, manifest v3) carry their own inner version integers, checked after authentication.
- Only the current format is accepted. Any other magic returns
IncompatibleFormat; extract old data with the release that wrote it, then re-add it. A 0.5.x vault manifest (v2) returnsMigrationRequiredand is upgraded in place withkeres migrate. - Vault directories are forward-only. Since 0.7 a vault may contain an
append-only
d/.index.log; pre-0.7 releases do not know about it and can silently show or write a stale index. Do not alternate releases on the same vault directory. - The Rust API is not stable before 1.0. The container format and on-disk vault layout are the compatibility contract.
Open format questions are tracked in Security model § Audit scope. The most likely future envelope revision is a key-commitment tag; it would be a new envelope version with a documented migration path, not a reinterpretation of v1 or v2.
Error taxonomy
One enum (Error, via thiserror), with Result<T> = std::result::Result<T, Error>:
| Variant | Meaning |
|---|---|
Authentication | Wrong password/key or any tampering — indistinguishable on purpose |
InvalidHeader | Malformed kind, lengths, or trailer |
UnsupportedVersion(u32) | Envelope/schema/config version newer than supported |
MigrationRequired | Legacy vault manifest; run keres migrate |
IncompatibleFormat | File is not a current Keres container |
InvalidVault | Vault structure problems (bad config, damaged manifest) |
VaultLocked / VaultUnlocked | State-machine misuse |
VaultBusy | Another process holds the vault lock |
Cancelled | A streaming operation was stopped by its cancellation flag |
EntryExists / EntryNotFound | Name conflicts |
Conflict | A conditional write’s precondition failed; the vault was not modified |
InvalidEntryName(String) | Validation failure (preview truncated to 32 characters) |
Operation(String) | User-level operation could not be performed |
Io(std::io::Error) | Filesystem layer |
Encryption / KeyDerivation / InvalidKdfParams / MalformedPayload | Internal/crypto-layer failures |
Callers cannot distinguish “wrong password” from “corrupted file” — both are
Authentication. This prevents error messages from becoming a tamper oracle.
API stability and versioning
This page states what upgrades can and cannot break. It covers the Rust API, the minimum supported Rust version (MSRV), and how the crate version relates to the on-disk format.
Crate version vs format version
These are independent:
- The crate version follows Semantic Versioning and describes the Rust API.
- The container and vault format versions are written into the data and evolve separately. They are documented in Architecture and pinned by test vectors.
A crate release can change the API without changing the format. A format change requires a new format version and a documented migration path; it does not silently reinterpret existing data.
Pre-1.0 policy (current)
Keres is currently 0.7.x.
- Patch releases (
0.7.1→0.7.2) fix bugs and security issues without intentionally breaking the public API. - Minor releases (
0.7.x→0.8.0) may include breaking API changes. They will be called out inCHANGELOG.mdwith upgrade notes. - The on-disk format is never changed in a way that makes existing data unreadable without a migration path.
Because breaking changes are allowed in minor releases, pin the exact version
in Cargo.lock and review the changelog before upgrading. Keep at least one
test that opens data written by the previous release.
What counts as a breaking change
The usual Rust rules apply: removing or renaming a public item, changing a signature, adding a required trait bound, or changing behaviour that callers can observe.
Two attributes are used deliberately to keep future changes non-breaking:
#[non_exhaustive]on growable enums (Error,BatchOp,WriteOutcome,Padding) and output structs (EntryInfo,StreamInfo,IntegrityReport,IndexVersion,KeyslotInfo,MigrationReport,RotationReport). Downstream code must include a wildcard arm when matching these enums and cannot construct the structs with a literal. In exchange, new variants and fields can be added in a patch or minor release.#[must_use]on constructors, getters, and builder methods whose result is otherwise easy to discard by accident.
Adding one of these attributes is itself a breaking change for downstream code that matched exhaustively or used a struct literal. Treat it as such when reviewing a release.
Deprecation
Public items are deprecated with #[deprecated] for at least one minor release
before removal. The replacement is named in the attribute and in the changelog.
Security fixes may remove an unsafe API faster, with an explicit advisory.
MSRV policy
The MSRV is Rust 1.85, declared as rust-version in Cargo.toml.
- CI builds and tests the workspace on the MSRV on every change.
- The MSRV may be raised in a minor release, never in a patch release.
- An MSRV bump is documented in
CHANGELOG.md. Following normal Rust ecosystem practice, it is not treated as a semver-breaking change for the library. - Raising the MSRV requires a reason: a required compiler feature, a dependency MSRV bump, or a security fix. It is not raised to use cosmetic syntax.
Semver checking
Releases run cargo-semver-checks
against the last published version before publishing. The check fails when the
public API changed in a way the version bump does not allow.
Run it locally before opening a release pull request:
$ cargo install cargo-semver-checks --locked
$ cargo semver-checks --package keres
The tool derives the release type from the version in Cargo.toml. If you
intend a breaking change, bump [workspace.package].version to the next minor
version before running it; a patch bump with a breaking change fails the check.
Supported versions
Security fixes are applied to the latest published release. Only the current
container format is supported; data written by an older format must be upgraded
with the release that introduced the upgrade (for example, keres migrate for
legacy vaults).
Stability checklist for embedders
-
Cargo.lockis committed and the crate version is pinned. - The changelog is read before every upgrade.
- A test opens a fixture written by the previous release.
- CI runs on the declared MSRV if you support it.
- The security model limitations are acceptable for your data.
Security model
Keres protects data at rest. The primary adversary has read access to the storage medium — a stolen laptop, a leaked backup, a seized disk, or a compromised sync folder — and may also modify stored files.
Keres does not protect against an attacker who can run code on the machine while a vault is unlocked, observe the screen or keyboard, or control the operating system. Those cases are outside the threat model.
Audit status: Keres has not yet had an independent security audit. This document describes the intended design and the properties the test suite checks; it is not a substitute for review before high-value deployment.
Security goals
In priority order:
- Confidentiality of content and metadata. File contents, names, and directory structure are encrypted.
- Tamper evidence. Modification, truncation, reordering, splicing, or transplantation of ciphertext is detected before plaintext is released.
- No accidental data loss. Corruption fails loudly; writes are atomic; interrupted operations never leave a half-written config or a dangling index.
- A small, auditable surface. One container format, one chunk engine,
no async runtime, no network code, and no
unsafe(#![forbid(unsafe_code)]).
Cryptographic primitives
All primitives come from RustCrypto crates (aes-gcm, argon2, hkdf,
sha2, subtle). Randomness comes from the operating system CSPRNG.
| Primitive | Parameters | Role |
|---|---|---|
| AES-256-GCM | 96-bit nonces, 128-bit tags | Every byte of ciphertext |
| Argon2id | Default 64 MiB, t=4, p=4; stored per container | Password → key-encryption key |
| HKDF-SHA256 | Random 32-byte salt per object | Master key → per-object content keys; index-log keys |
| SHA-256 | — | Blob path derivation and per-entry plaintext content hashes |
subtle::ConstantTimeEq | — | Comparisons on secrets where needed |
KDF parameters travel inside containers so defaults can evolve. When reading untrusted input they are bounded to prevent denial of service:
| Field | Default | Accepted range |
|---|---|---|
m_cost_kib | 65,536 KiB (64 MiB) | 8 MiB – 4 GiB |
t_cost | 4 | 1 – 64 |
p_cost | 4 | 1 – 16 |
Key hierarchy
Standalone .krs (password-derived):
password ──Argon2id(argon_salt, params)──► KEK
──HKDF(object_salt)──► content key
Vault:
password ──Argon2id(slot salt, params)──► KEK
──AES-GCM-wrap──► master key (vault.config, one wrapping per keyslot)
master key ──HKDF(object_salt, identity)──► per-entry content key
──HKDF(object_salt, "vault-manifest")──► index content key
Properties that follow:
- Per-object keys. Every entry gets a fresh random object salt and an independent HKDF subkey.
- Password changes do not rewrite data. Only the wrapped master key in
vault.configchanges. - No offline verifier. There is no password hash to check guesses against; each guess costs a full Argon2id run plus GCM verification.
- Keyslot revocation is not rotation. Removing a slot drops one wrapping; the master key stays the same. See Known limitations.
Nonces and associated data
| Record | Nonce | AAD |
|---|---|---|
| Data chunk i | 4 zero bytes ‖ i as u64 BE | "keres-container-v1/<type>" ‖ chunk index |
| Padded metadata | [0xFE; 12] | "keres-container-v2/padding" |
| Trailer | [0xFF; 12] | chunk context ‖ index ‖ "/trailer" |
| Config slot | Random 96-bit nonce | "keres-vault-config-v3/" ‖ slot id |
| Recovery kit | Random 96-bit nonce | "keres-vault-recovery-v1" |
| Index-log record | Random 96-bit nonce | log header bytes ‖ record index |
Consequences:
- Reordering chunks or moving records between positions fails authentication.
- Moving records between payload types or containers fails because the context or object key differs.
- The unauthenticated end-of-chunks marker is harmless: the authenticated
trailer’s
chunk_countandsizemust match what was actually read. - Counter nonces are collision-free within an object regardless of size or restarts.
See Architecture for the exact wire layout.
Key management
Passwords and keyslots
A vault starts with one keyslot. Each slot wraps the same random master key under a KEK derived from that slot’s password and salt. Unlocking tries the slots until one AEAD tag verifies.
change_password re-wraps one slot. add_keyslot appends a new wrapping.
remove_keyslot deletes a wrapping and requires authorization from a slot
that remains; the last slot cannot be removed.
Slot ids and the slot count are plaintext metadata in vault.config. A wrong
password and a tampered wrapping are both reported as
Error::Authentication.
Recovery kits
A recovery kit is an independent wrapping of the master key under a random
160-bit code, printed once. recover uses the kit to recreate a lost or
damaged vault.config, validates the recovered key against the encrypted
index, writes a fresh single-slot config, and deletes the kit.
The code is not stored. The recovery file is a second offline guessing target; 160 bits plus Argon2id makes exhaustive search infeasible, but the code must be stored separately and handled like a password.
Rotation and erasure
rotate generates a new master key, re-encrypts every entry, and writes a
fresh single-slot config. erase does the same while omitting one entry.
Both are forward-looking. They stop old key material from working against the vault from now on, but they cannot revoke ciphertext that an attacker already copied together with the old key or config.
Memory handling
- Keys live in
Zeroizing<[u8; 32]>; buffers containing secrets are zeroized on drop. DebugforKeyandRecoveryCoderedacts the value.- Keys are not serialized, logged, or included in errors.
Vault::lockdrops the in-memory master key.
Keres does not use mlock, madvise, or core-dump suppression. With
#![forbid(unsafe_code)], those would require an audited unsafe boundary;
they are on the roadmap. On a machine without encrypted swap, unlocked keys
can reach disk.
Filesystem and crash safety
- All persistent writes use: create a temp file in the same directory →
restrict permissions → write →
sync_all→rename→sync_dir. - Temp files are opened with
O_CREAT | O_EXCL, so an existing path or planted symlink causes failure instead of being written through. On Unix they are mode0600from creation. - Vault directories and single-file outputs are created with owner-only
permissions (
0700/0600) on Unix. - Names recovered from containers are sanitized before path joins. Absolute
paths,
.., separators, and control characters are rejected. - Adds write blobs first and commit the index last. A crash leaves unreferenced blobs, never an index pointing at missing data.
- Removals commit the index first and delete blobs afterwards. A failed deletion leaves a pruneable orphan.
- Replaces are copy-on-write: a new blob and entry ID are written, the index is committed, and only then is the old blob deleted.
- Rotation and index compaction are journaled; the next lock acquisition completes or rolls back an interrupted run.
- Vault access uses non-blocking advisory locks (
flockon Unix,LockFileExon Windows). Writers lock exclusively, readers share the lock, and contention returnsError::VaultBusy.
The lock coordinates well-behaved processes; it is not a security boundary.
Metadata leakage
Keres uses two informal levels in its documentation:
- Default — names and structure encrypted; exact entry sizes visible.
- Padded — opt-in size padding (
Padding::AdaptiveorPadding::Fixed).
| Signal | Default | Padded | Notes |
|---|---|---|---|
| Container magic / format existence | Visible | Visible | Deniability is out of scope |
| Vault existence and layout | Visible | Visible | Directory names and structure identify a vault |
| File names | Hidden | Hidden | Encrypted in the index or trailer |
| Directory structure | Hidden | Hidden | Encrypted in the index |
| Entry sizes | Exact | Bucket only | Manifests and directory placeholders are never padded |
| Number of top-level entries | Visible | Visible (coarse) | Count bucketing is not implemented |
| Access patterns | Visible | Visible | No ORAM; reads/writes and timing are observable |
| Modification times | OS-level | OS-level | Not coarsened |
| Index mutation count / order | Visible via log size | Visible via log size | Group commit and timing jitter are future work |
| Deleted-entry recoverability | Blob removed | Blob removed | Old copies remain decryptable unless erase is used |
| Rollback to an older valid copy | Possible | Possible | No hardware-backed anti-rollback counter |
Padding hides exact sizes, not which blob was accessed or when. It also adds storage overhead: adaptive padding wastes up to the current bucket size.
Verification
Vault::verify / keres verify authenticates the replayed index and every
blob. In addition to AEAD tags it checks:
- the payload type;
- the recorded plaintext size;
- the SHA-256 content hash stored in the authenticated index.
The content hash detects a substituted older blob under the same entry ID. Entries written by releases before content hashes existed are size-checked only. Verification does not detect a rollback of the entire vault directory.
Known limitations
- No memory locking. Keys can be swapped or captured in a core dump if the OS allows it.
- No retroactive key rotation. Rotation re-encrypts the current vault, but cannot reach copies an attacker already took.
- No deniability. The container magic and vault layout identify their contents as Keres data.
- Single-factor authentication. Passwords, keyslots, and recovery codes are all knowledge factors. There is no hardware token or multi-party split.
- Size leakage by default. Ciphertext length reveals plaintext length unless padding is enabled. Padding is opt-in.
- No hardware-backed anti-rollback. Restoring an older valid vault directory is possible. Content hashes and index generations detect some local substitutions, not a full-directory rollback. A truncated index-log tail is indistinguishable from an interrupted append.
- Operation-pattern leakage. The index log reveals how many mutations occurred and roughly when. Access patterns are not hidden.
- No independent audit. The implementation has not been reviewed by an external cryptography or security firm.
- No key commitment. AES-GCM is not key-committing: an attacker who controls a file could in principle construct one ciphertext that authenticates under two different keys. Keres limits the impact by using a single key per container, a fresh random object salt, and an authenticated, structured trailer (payload type, size, chunk count) that must also parse. A wrong password therefore still fails in practice, but the format has no formal commitment tag. This is tracked for a future envelope version and for the audit.
Audit scope
The first independent audit should focus on the following, in priority order. This list is also the starting point for quote requests.
- Container format and stream engine. Header binding, AAD domains, deterministic nonce construction, trailer and padding records, record and chunk-count limits, and parser behavior on truncated or oversized input. Fuzz targets cover the container reader, manifest decoder, config parser, and padding header.
- Key hierarchy. Argon2id parameter handling and bounds, HKDF domain separation between object kinds, keyslot wrapping and slot-id binding, recovery-kit construction, and the rotation and erasure journals.
- Key commitment and partitioning oracles. Whether the absence of a
commitment tag is exploitable for password-derived
.krsfiles, and whether single-key containers are sufficient in practice. - Rollback and truncation. Whole-directory rollback, index-log tail truncation, and the interaction between content hashes, generation numbers, and compaction.
- Metadata leakage. What the padding scheme actually hides, and whether this document matches the implementation.
- Filesystem and crash safety. Temp-file handling, permissions, symlink and race behavior, and recovery from interrupted rotation, compaction, and migration.
- API misuse resistance. Whether the hardened public API makes it hard to reuse a key accidentally, skip authentication, or ignore an error.
Out of scope for the first audit: ORAM and access-pattern hiding, plausible deniability, network synchronization, and hardware-backed factors.
Reporting a vulnerability
Do not open a public issue for a suspected vulnerability. Follow the process in SECURITY.md, including a minimal reproducer and the affected version.
Performance
Keres is built for streaming and bounded memory, not for benchmark records. Throughput is dominated by AES-256-GCM and by Argon2id for the first key derivation. This page explains where time goes and how to measure it.
Representative measurements
The following numbers come from a development machine in August 2026 (x86_64, AES-NI, release build). They are indicative, not a guarantee. Run the benchmarks on your own hardware before sizing an operation.
| Scenario | Time | Notes |
|---|---|---|
| Encrypt a small file | ~0.19 s | Almost entirely Argon2id (64 MiB, t=4) |
| Encrypt 200 MB | ~0.56 s (~360 MB/s) | Single thread |
| Decrypt 200 MB | ~0.53 s (~380 MB/s) | Byte-identical round trip |
| Vault add, 200 files | ~0.68 s | One unlock plus 200 blob writes |
| Vault list | ~0.17 s | Index only; no blob I/O |
| Vault verify, 201 entries | ~0.18 s | AEAD and content hash over every blob |
Analysis
- Argon2id sets the floor for small operations. Every password-based
unlock or
.krsencryption pays the full KDF cost. That cost is the brute-force defense; do not lower it casually. - Bulk throughput is single-threaded. 64 KiB chunks and per-record AAD construction are cheap, but chunks are processed sequentially. A parallel pipeline is on the roadmap and can be added without changing the format, because chunks are independent.
- Vault operations batch well. Unlock once, then add many entries. After unlock, per-entry work is essentially AES plus filesystem writes.
verifyis cheaper than a full rotation because it does not rewrite data, but it still reads and authenticates every byte once.- Deep rotation is the most expensive operation. It reads and rewrites every entry under a new master key.
Measuring locally
The Criterion benchmark covers the container engine and single-file mode:
$ cargo bench -p keres --bench throughput
For an end-to-end CLI measurement, use a release build:
$ cargo build --release -p keres-cli
$ /usr/bin/time -v target/release/keres encrypt large.bin out.krs
Keep the following fixed when comparing runs:
- release build, same CPU and filesystem;
- same file size and whether it is cached;
- same padding policy (padding increases I/O and changes bucket sizes);
- whether the vault is already unlocked (the CLI unlocks per invocation).
Memory and storage
- Streaming encryption uses one 64 KiB plaintext buffer plus ciphertext and tag space. Memory does not scale with file size.
- Argon2id uses 64 MiB by default per derivation. Several concurrent processes each pay that cost.
- Vaults store one ciphertext blob per entry, plus the index snapshot and log. Renames do not duplicate blobs; replaces use copy-on-write and briefly need space for both versions.
- Padding increases storage: adaptive padding can waste up to the current bucket size, and fixed buckets can waste almost a full bucket per entry.
Limits
- An object is capped at 1 TiB (2^24 chunks of 64 KiB).
- A trailer is capped at 1 MiB.
- A manifest payload is capped at 64 MiB on read.
- Index-log batches are capped at 64 MiB and compacted after 512 records or 8 MiB.
These limits are hostile-input guards, not tuning knobs.
Format test vectors
The container format has a committed, deterministic fixture so that an unintentional change to the wire layout fails loudly.
Fixture
tests/vectors/standalone.krs is a standalone .krs container built with
fixed inputs:
| Input | Value |
|---|---|
| Password | correct horse battery staple |
| Original name | hello.txt |
| Plaintext | 100,000 bytes, bytes[i] = i % 251 for i in 0..100_000 |
| Argon2id salt | 32 × 0x11 |
| HKDF object salt | 32 × 0x22 |
| Argon2id parameters | m = 8192 KiB, t = 1, p = 1 |
The KDF parameters are the minimum accepted by KdfParams::validate, chosen
so tests and external tools can derive the key quickly. They are explicit in
the container header, not implicit.
SHA-256 of the fixture:
978e1085b8ff2d199d70b52d0b4cff391ebadaa0efcc11298e3eaeff584f19d2
What the tests pin
tests/vectors.rs asserts that:
- The committed bytes equal the output of the generator
(
keres::test_vectors::standalone). - The SHA-256 digest matches the value above.
- The public
decrypt_fileAPI recovers the exact plaintext and name. - A wrong password returns
Error::Authentication. - A foreign magic returns
Error::IncompatibleFormat. - A flipped trailer byte returns
Error::Authentication. - A truncated container is rejected.
These checks catch accidental changes to header layout, KDF encoding, chunk framing, trailer JSON, or AAD construction. They do not replace the tamper sweeps in the unit and integration tests.
Regenerating
A format change is deliberate: update the generator, regenerate the fixture,
record the new digest here, and explain the change in CHANGELOG.md. The
fixture can be rebuilt with:
let plaintext: Vec<u8> = (0..100_000u32).map(|i| (i % 251) as u8).collect();
let bytes = keres::test_vectors::standalone(
"correct horse battery staple",
&plaintext,
"hello.txt",
);
std::fs::write("tests/vectors/standalone.krs", bytes)?;
Ok::<(), std::io::Error>(())
keres::test_vectors is a hidden developer module, not part of the stable
API. It exists so the fixture can be reproduced without reimplementing the
format.
Using the fixture outside Rust
The fixture is a normal container. A compatible implementation can open it with the password above and should recover:
- the filename
hello.txt; - exactly 100,000 plaintext bytes;
- the
bytes[i] = i % 251pattern.
It is also useful for checking a parser against malformed input: truncate the fixture at every record boundary, flip bytes in each header field, and confirm that no mutation is accepted.
Troubleshooting
This page covers common errors and recovery steps. If a step here would delete data, stop and make a copy of the vault directory first.
Authentication failed: wrong password or corrupted data
Keres deliberately reports wrong passwords and tampered ciphertext with the same error, so the message cannot be used as a tamper oracle.
Check, in order:
- The password source.
--password-filereads only the first line;--password-stdinconsumes one line;KERES_PASSWORDis used only when no explicit flag is present. - Whitespace or shell quoting around the password.
- Whether the container or vault was copied completely. Truncated downloads and partially synced folders fail authentication.
- Whether the file is a Keres container at all. A wrong magic returns
IncompatibleFormat, notAuthentication.
If the password is correct and the data still fails, restore from a known-good backup. Do not repeatedly rewrite the vault.
vault not found
The CLI resolves a vault to $KERES_HOME/vaults/<name> or
~/.keres/vaults/<name>. Check:
KERES_HOMEis set in the current shell and is not empty;- the vault name matches the directory name exactly;
- the path is a directory, not a symlink (the CLI refuses symlinked vaults);
- on Windows,
USERPROFILEis set ifKERES_HOMEis not.
vault is busy: another process is using it
Another process holds the advisory lock on vault.lock. Wait for it to finish
or stop it. The lock is released when the process exits; the empty
vault.lock file is always present and is not a stale-lock indicator.
Do not delete vault.lock while a process is running. It is the coordination
point, not a record of ownership.
vault uses a legacy format; run keres migrate
A 0.5.x vault (manifest v2) was opened by a current release. Back up the vault directory, then run:
$ keres migrate <vault>
Migration is one-way. See Recovery, rotation, and migration.
incompatible container format
The file is not a current Keres container. This includes pre-rename Krypton files and pre-0.4 formats. Use the release that wrote the file to decrypt it, then re-encrypt with the current release. There is no compatibility reader for retired formats.
unsupported container version
The file was written by a newer Keres release than the one you are running. Upgrade to that release or newer. Do not patch the version byte; the format may have changed.
entry already exists / entry not found
addrefuses to overwrite. Usereplacefor a file, orremovefirst.replaceandremovematch top-level names or fullparent/childpaths exactly.listshows only top-level entries; pass the full path for a nested entry.- Names containing
/,\,.., or control characters are rejected.
Verification reports missing or corrupted entries
keres verify exits with status 1 and lists the affected entries.
- Missing means the index references a blob that is not on disk. Restore the vault directory from a backup, or accept that the entry is lost.
- Corrupted means the blob exists but fails authentication, size, or content-hash checks. Restore that entry from a backup.
If the vault is otherwise healthy and you have interrupted operations, remove unreferenced blobs after a successful check:
$ keres verify <vault> --prune
--prune never runs after a failed check and never runs if the index snapshot
is missing.
vault.config is missing or damaged
Use the recovery kit:
$ keres recovery use <vault>
You need both the vault directory and the recovery code. Recovery writes a fresh single-slot config and consumes the kit. Additional keyslots are lost.
Without a recovery kit, a lost or damaged vault.config means the vault cannot
be unlocked. Do not delete the directory; a future release may add recovery
tooling, and the ciphertext is still there.
A rotation, erase, or migration was interrupted
Do not delete vault.rotate, d/.index.compact, or *.next files manually.
The next operation that opens the vault completes or rolls back the journaled
operation. Then run:
$ keres verify <vault>
$ keres verify <vault> --prune
If the process ran out of disk space, free space first. The old vault remains readable when rotation has not reached its commit point.
confirmation requires a terminal; pass --force
Destructive commands ask for y/N on a terminal. In scripts or CI, pass
--force explicitly:
$ keres remove --force personal old-notes.txt
Only use --force after checking the vault name and entry name.
already exists; pass --force to overwrite
encrypt, decrypt, and extract refuse to replace an existing destination.
Pass --force if replacement is intended. For extraction, the destination
path itself must not exist unless --force is given.
Password file or stdin fails
--password-filemust be readable and contain the password on the first line.--password-fileand--password-stdincannot be combined.- New passwords for
change-password,rotate,erase, andrecovery useare still prompted (or read from subsequent stdin lines), even when the current password came from a file orKERES_PASSWORD. - With
--password-stdin, provide consecutive lines in the order the prompts appear.
Operations are slower than expected
- The first unlock or
.krsencryption pays Argon2id: 64 MiB and four passes by default. This is intentional. - Bulk encryption is single-threaded today.
- Padding increases the amount of data written and may add I/O.
- Network filesystems and cloud-synced folders can be much slower than local disks, and some do not provide reliable atomic rename.
See Performance for measurement guidance.
Permissions
On Unix, Keres creates files with owner-only permissions (0600) and vault
directories with 0700. If a vault was copied with different ownership or
modes, restore access deliberately; do not loosen permissions on a shared
machine.
Getting more help
Include the following in a bug report:
- Keres version (
keres --version); - operating system and filesystem;
- the exact command and error text (with secrets removed);
- whether the vault was created by an older release;
- whether a process was interrupted, killed, or ran out of disk space.
For suspected vulnerabilities, follow SECURITY.md instead of opening a public issue.
Roadmap
Keres is developed security-first. This page lists the work that remains, not the work that is finished; completed changes are recorded in CHANGELOG.md.
Anything that weakens an authenticated property will not be accepted for compatibility or convenience.
0.7.x follow-ups
- Group commit. Coalesce concurrent writers into one durable index batch
so a busy vault pays for one
sync_dataper group instead of per mutation. - Timing and count hardening. Explore optional timing jitter and mutation count bucketing for the index log. Access-pattern hiding remains out of scope.
- Dependency slimming. Remove
walkdirfrom the production dependency graph by replacing the directory walk with a smallstd::fs::read_dirimplementation that preserves ordering and symlink behavior. - Rollback detection. Investigate a MAC’d monotonically increasing generation stored outside the vault directory. Without trusted external state this improves detection, not prevention.
- Documentation and examples. Keep the book, rustdoc, and CLI help in sync; add end-to-end examples for recovery and rotation.
- Embedding ergonomics. Continue widening the in-memory API (for example
streaming
Readhandles for vault entries).keres-desktop/is the in-repo local-first consumer; use its friction reports to drive API work rather than adding speculative surface.
1.0 readiness
- External security audit. A professional review of the container format, key hierarchy, and implementation. No amount of internal review substitutes for this.
- Memory locking. Evaluate
mlockand core-dump suppression behind a small audited unsafe boundary, feature-gated and disabled by default. - Hardware-backed factors. Optional TPM, Secure Enclave, or FIDO2
hmac-secretsupport combined with a password. Plain password vaults remain the default. - API stabilization. Freeze the public Rust API and commit to semantic
versioning.
#[non_exhaustive],#[must_use],cargo-semver-checks, and the MSRV policy are already in place; the remaining work is the 1.0 review. Until then, minor releases may change APIs. - Format freeze. Declare the current envelope, config, and manifest versions stable and document the long-term compatibility promise.
- Operational hardening. More crash-injection testing, cross-platform filesystem tests, and recovery drills for interrupted rotation, compaction, and migration.
Explicitly out of scope
- Plausible deniability / hidden volumes. The container magic is a feature; deniable schemes conflict with authenticated formats and invite catastrophic user error.
- Backward-compatibility readers for retired formats. Only the current
format is accepted. The sole exception is the one-way v2 → v3 vault upgrade
in
keres migrate. - Access-pattern hiding (ORAM). Keres documents access-pattern leakage rather than claiming to hide it.
- Network synchronization. Keres encrypts local files; syncing services are outside the trust boundary.
How priorities are chosen
- Security defects and data-loss risks.
- Correctness and crash safety.
- Documentation and usability gaps that can cause data loss.
- Performance and ergonomics.
Proposals that add a new format, a new primitive, or a new privileged code path need a written design and tests before implementation.
Contributing
Contributions are welcome. Keres handles other people’s data, so changes are reviewed with a bias toward correctness and explicit failure over convenience.
Repository layout
| Path | Contents |
|---|---|
src/ | The keres library: container format, crypto, vault |
keres-cli/ | The keres binary; keep it a thin wrapper over the library |
tests/, benches/ | Integration tests and Criterion benchmarks |
fuzz/ | cargo-fuzz targets (separate, excluded workspace) |
docs/ | This mdBook |
.github/workflows/ | CI, docs deployment, fuzzing, and release |
Getting started
$ git clone https://github.com/Keres-rs/keres.git
$ cd keres
$ cargo test --workspace --all-targets
$ cargo test --workspace --doc
Rust 1.85 or newer is required. Nix users can run nix develop for a shell
with the toolchain, clippy, rustfmt, rust-analyzer, and mdBook.
Before opening a pull request
Run the same gates as CI:
$ cargo fmt --all -- --check
$ cargo clippy --workspace --all-targets -- -D warnings
$ cargo test --workspace --all-targets
$ cargo test --workspace --doc
$ cargo doc --workspace --no-deps
$ cargo deny check
$ mdbook build docs
cargo deny check requires cargo-deny. The policy is in deny.toml; do not
broaden the license allowlist without review.
What a good change looks like
- Security first. Do not weaken an authenticated property for convenience. Changes to the format, key derivation, or AAD need a regression test and a written rationale.
- Fail loudly. A damaged manifest, malformed header, or missing blob must be an error. Never treat corruption as an empty vault.
- Test the failure path. New behavior needs a test that fails without the change. Crash-safety changes should explain what happens at each commit point.
- Document public API. The library denies missing docs and broken intra-doc links.
- Keep the CLI thin. Business logic belongs in the library.
- Respect the format. New object kinds are new payload types with new AAD contexts, never new magics or reused context strings.
Tests, fuzzing, and benchmarks
$ cargo test -p keres
$ cargo bench -p keres --bench throughput
$ cd fuzz
$ cargo fuzz run read_container
$ cargo fuzz run parse_manifest
$ cargo fuzz run parse_config
$ cargo fuzz run sanitize
Fuzz targets use the nightly toolchain from fuzz/rust-toolchain.toml and run
weekly in CI. Format test vectors live in tests/vectors/; see
Format test vectors. Never regenerate a fixture to make a
test pass — a digest change means the wire format changed and needs deliberate
review.
Documentation
- Update the relevant page in
docs/src/when behavior changes. - Keep relative links between pages; use absolute GitHub or docs.rs links in the root README, which is also published to crates.io.
- CLI examples should be runnable as written.
- Separate normative format details (architecture chapter) from task-oriented guides.
Build locally with mdbook serve docs.
Security reports
Do not open a public issue for a suspected vulnerability. Follow SECURITY.md.
Commits and review
- Keep commits focused and explain the why in the message.
- Do not commit generated build output, vaults, or
.krsfixtures other than the committed test vector. - Expect review questions about failure modes, rollback behavior, and secret handling.
By contributing, you agree that your contribution is licensed under Apache-2.0 (code) or CC0-1.0 (documentation), matching the repository.
Release process
Keres uses tag-driven releases. The workflow in
.github/workflows/release.yml publishes the crates, builds binary archives,
and creates the GitHub release.
Versioning
- The workspace version lives in
Cargo.tomlunder[workspace.package]. keresandkeres-clishare that version.- The CLI depends on the matching published
keresversion, so the library must be published first. - The container format version is independent of the crate version. Format compatibility is documented in Compatibility and versioning.
Release checklist
-
Update the version. Bump
[workspace.package].versionand runcargo update --workspaceif needed. -
Update the changelog. Add an entry to
CHANGELOG.mddescribing user impact, format changes, and upgrade notes. -
Run the gates.
$ cargo test --workspace --all-targets --locked $ cargo test --workspace --doc --locked $ cargo clippy --workspace --all-targets --locked -- -D warnings $ cargo fmt --all -- --check $ cargo doc --workspace --no-deps --locked $ cargo semver-checks --package keres $ cargo publish --dry-run --locked -p keres $ mdbook build docsThe release workflow also runs
cargo-semver-checks. It derives the release type from[workspace.package].version, so bump to the next minor version before the check if the release contains breaking API changes. -
Commit the release. The release workflow requires the tag to be on
main. -
Tag and push.
$ git tag v0.7.1 $ git push origin v0.7.1 -
Approve the deployment. The workflow uses the protected
releaseenvironment; a reviewer must approve before publishing.
What the workflow does
- Verifies the tag is an ancestor of
mainand matches the workspace version. - Runs
cargo test --workspace --locked. - Publishes
keres, waits for the crate to appear on crates.io, then publisheskeres-cli. - Builds the CLI for Linux (
x86_64-unknown-linux-gnu), macOS (aarch64-apple-darwin), and Windows (x86_64-pc-windows-msvc). - Packages each binary with a SHA-256 checksum and build-provenance attestation.
- Creates the GitHub release and attaches the archives and checksums.
The publish step is idempotent: a version already present on crates.io is skipped, so a failed release can be re-run from the same tag. The CLI publish retries while the registry index catches up.
One-time repository setup
- Configure Trusted Publishing on crates.io for both
keresandkeres-cli, pointing atKeres-rs/keresand.github/workflows/release.yml. - Create a
releaseenvironment in GitHub with required reviewers. - Allow
id-token: writeandattestations: writein the repository’s Actions policy.
Supported versions
Keres is pre-1.0. Security fixes are applied to the latest published release
(currently the 0.7.x line). Only the current container format is supported;
legacy formats must be decrypted with the release that wrote them. A 0.5.x
vault can be upgraded in place with keres migrate.
Release notes
CHANGELOG.md is the source of truth for user-visible changes. The GitHub
release should summarize upgrade notes and link to the changelog rather than
duplicating it.