bookclerk_keystore
OS keychain access for the library's data-encryption key.
Bookclerk can keep the library's data-encryption key (DEK) in the
operating system's credential store instead of in master.key:
| Platform | Store |
|---|---|
| macOS | Keychain Services (the login keychain) |
| Windows | Credential Manager (DPAPI, per user) |
| Linux and other Unix | Secret Service over the session D-Bus (GNOME Keyring, KWallet), in a plain session so the hosts link no block cipher |
This crate is deliberately small. It names one keychain item per install
(KeychainItemId, a random UUID minted with the key), reads, writes and
deletes that item's bytes through a Vault, and encodes the pointer
record (KeychainPointer) that master.key holds on a keychain
install. What the item's bytes mean (BCK1 or BCK2, the fingerprint
check) stays in bookclerk-library's master_key module.
OsKeychain is the real store. MemoryVault keeps items in memory,
for tests and for hosts that must never touch the keychain.
Errors never carry item bytes: the keychain libraries' own error values can
hold the secret they failed to decode, so KeystoreError keeps only a
category and a safe message.
See docs/adr/master-key-store.md.
| Item | Kind | Summary |
|---|---|---|
Vault |
trait | A store of master-key items: the OS keychain, or memory in tests. |
SystemdCredsVault |
struct | A master-key store that seals items with systemd-creds. |
KeystoreError |
struct | A key store failure, without any item bytes. |
KeychainItemId |
struct | Identifier of one install's master-key item: the item's account name under KEYCHAIN_SERVICE. |
KeychainPointer |
struct | What master.key holds on a keychain or systemd-creds install: which store and item carry the key, and the fingerprint the key inside must match. No key material. |
OsKeychain |
struct | The operating system's credential store. |
MemoryVault |
struct | Items kept in process memory: for tests, and for hosts that must not touch the OS keychain. |
KeystoreErrorKind |
enum | Why a keychain operation failed. |
ErrorStore |
enum | Which store a KeystoreError came from, so messages name the store the operator configured. |
PointerStore |
enum | Which store a pointer record names. |
PointerError |
enum | Why a byte string is not a pointer record. |
Result |
type alias | Result alias for keychain operations. |
CREDENTIAL_NAME |
constant | The credential name the key is sealed under, and the name a service unit hands it in as (LoadCredentialEncrypted=bookclerk-master-key). |
KEYCHAIN_SERVICE |
constant | Keychain service name every Bookclerk master-key item is stored under. |
POINTER_MAGIC |
constant | Four-byte header of a master.key pointer record for an OS keychain item (BCK3). |
CREDS_POINTER_MAGIC |
constant | Four-byte header of a master.key pointer record for a key sealed with systemd-creds (BCK4): the same layout as POINTER_MAGIC's. |
FINGERPRINT_LEN |
constant | Length in bytes of a key fingerprint (SHA-256 of the DEK). |
POINTER_LEN |
constant | Length in bytes of an encoded KeychainPointer: header, 16-byte item id, 32-byte fingerprint. |
MAX_ITEM_LEN |
constant | Largest item, in bytes, a Vault accepts. |
pub trait Vault: Send + Sync {
fn get(&self, item: KeychainItemId) -> Result<Zeroizing<Vec<u8>>>;
fn set(&self, item: KeychainItemId, bytes: &[u8]) -> Result<()>;
fn delete(&self, item: KeychainItemId) -> Result<()>;
}
A store of master-key items: the OS keychain, or memory in tests.
fn get(&self, item: KeychainItemId) -> Result<Zeroizing<Vec<u8>>>
Reads an item's bytes.
KeystoreErrorKind::NotFound when the item is missing, and the
store's other failures.
fn set(&self, item: KeychainItemId, bytes: &[u8]) -> Result<()>
Creates or replaces an item.
KeystoreErrorKind::Rejected when bytes is longer than
MAX_ITEM_LEN, and the store's failures.
fn delete(&self, item: KeychainItemId) -> Result<()>
Deletes an item. Deleting a missing item succeeds.
The store's failures other than a missing item.
Implemented by: MemoryVault, OsKeychain, SystemdCredsVault
pub struct SystemdCredsVault {
/* private fields */
}
A master-key store that seals items with systemd-creds.
Items live in one directory (the files directory) as
master-key-<item>.cred. See the module docs.
pub fn new(dir: impl Into<PathBuf>) -> Self
A store sealing items into dir with the system's systemd-creds,
reading a unit-provided copy from $CREDENTIALS_DIRECTORY when set.
dir- the directory sealed items go in (the files directory).
pub fn with_program(
dir: impl Into<PathBuf>,
program: Option<PathBuf>,
credentials_dir: Option<PathBuf>,
) -> Self
A store with an explicit tool and credentials directory, for tests
and for systems that install systemd-creds elsewhere.
dir- the directory sealed items go in.program- thesystemd-credsbinary, orNonefor none.credentials_dir- the unit's credentials directory, if any.
pub fn sealed_path(&self, item: KeychainItemId) -> PathBuf
Where item is sealed: <dir>/master-key-<item>.cred.
item- the item idmaster.keynames.
pub fn unit_credential(&self) -> Option<PathBuf>
The copy the service unit handed in, when there is one.
Implements: Clone, Debug, Vault
pub struct KeystoreError {
pub kind: KeystoreErrorKind,
pub store: ErrorStore,
pub message: String,
}
A key store failure, without any item bytes.
Fields
kind: What went wrong, for callers that branch on it.store: The store that failed.message: A human-readable explanation that never contains item bytes.
pub fn new(kind: KeystoreErrorKind, message: impl Into<String>) -> Self
Builds an OS keychain error of kind with message; see
KeystoreError::in_store for another store.
kind- the failure category.message- a safe, secret-free explanation.
pub fn in_store(self, store: ErrorStore) -> Self
The same error, naming store as the one that failed.
store- the store the error came from.
Implements: Clone, Debug, Display, Eq, Error, PartialEq
pub struct KeychainItemId(/* private */);
Identifier of one install's master-key item: the item's account name
under KEYCHAIN_SERVICE.
pub fn random() -> Self
Mints a fresh random item id (UUID v4).
pub fn as_bytes(&self) -> &[u8; 16]
The id's 16 raw bytes, as the pointer record stores them.
pub fn from_bytes(bytes: [u8; 16]) -> Self
Rebuilds an id from the 16 bytes a pointer record holds.
Implements: Clone, Copy, Debug, Display, Eq, Hash, PartialEq
pub struct KeychainPointer {
pub store: PointerStore,
pub item: KeychainItemId,
pub fingerprint: [u8; 32],
}
What master.key holds on a keychain or systemd-creds install: which
store and item carry the key, and the fingerprint the key inside must
match. No key material.
Fields
store: The store that holds the item.item: The item that holds the key envelope.fingerprint: SHA-256 of the unwrapped DEK, the same valuelibrary_identitystores. A key read from the item must hash to this.
pub fn encode(&self) -> [u8; 52]
Encodes the record: the store's header (BCK3 or BCK4), the item
id, the fingerprint.
pub fn parse(raw: &[u8]) -> Result<Self, PointerError>
Parses a record Self::encode wrote.
raw- the whole contents ofmaster.key.
PointerError::NotAPointer when the header is neither BCK3 nor
BCK4, and PointerError::BadLength when the length is not
exactly POINTER_LEN.
Implements: Clone, Copy, Debug, Eq, PartialEq
pub struct OsKeychain {
/* private fields */
}
The operating system's credential store.
On macOS and Windows the native store (through keyring-core) is opened
on first use and reused. On Linux and other Unix systems each call talks
to the Secret Service on the session D-Bus; a headless server usually has
none, and every call then fails with KeystoreErrorKind::Unavailable.
pub fn new() -> Self
A handle to this machine's credential store.
Implements: Default, Vault
pub struct MemoryVault {
/* private fields */
}
Items kept in process memory: for tests, and for hosts that must not touch the OS keychain.
pub fn new() -> Self
An empty vault.
pub fn fail_with(&self, kind: Option<KeystoreErrorKind>)
Makes every later call fail with kind (None restores normal use).
kind- the failure to report, orNone.
pub fn len(&self) -> usize
How many items the vault holds.
pub fn is_empty(&self) -> bool
True when the vault holds no items.
Implements: Default, Vault
pub enum KeystoreErrorKind {
Unavailable,
AccessDenied,
NotFound,
Corrupt,
Rejected,
}
Why a keychain operation failed.
Variants
Unavailable: No credential store is reachable on this machine or session: no Secret Service on the session bus, no login keychain, no D-Bus.AccessDenied: The store is there but refused access (locked collection, the user denied the prompt, or the app's signature changed).NotFound: The named item does not exist.Corrupt: The item exists but its contents are not what Bookclerk wrote.Rejected: The store rejected the request (too long, bad attributes, ambiguous).
Implements: Clone, Debug, Eq, PartialEq
pub enum ErrorStore {
OsKeychain,
SystemdCreds,
}
Which store a KeystoreError came from, so messages name the store
the operator configured.
Variants
OsKeychain: The OS keychain (also the label for the in-memory test store).SystemdCreds: Asystemd-credscredential (SystemdCredsVault).
Implements: Clone, Copy, Debug, Default, Eq, PartialEq
pub enum PointerStore {
Keychain,
SystemdCreds,
}
Which store a pointer record names.
Variants
Keychain: The OS keychain (OsKeychain); the record startsBCK3.SystemdCreds: A credential sealed withsystemd-creds(SystemdCredsVault); the record startsBCK4.
pub fn magic(self) -> &'static [u8; 4]
The record header for this store.
pub fn for_header(raw: &[u8]) -> Option<Self>
The store whose records start with raw's first four bytes, if any.
raw- the start ofmaster.key.
Implements: Clone, Copy, Debug, Eq, PartialEq
pub enum PointerError {
NotAPointer,
BadLength(usize),
}
Why a byte string is not a pointer record.
Variants
NotAPointer: The bytes start with neitherPOINTER_MAGICnorCREDS_POINTER_MAGIC.BadLength: The header is right but the record is not exactlyPOINTER_LENbytes.
Implements: Clone, Copy, Debug, Display, Eq, Error, PartialEq
pub type Result<T> = Result<T, KeystoreError>;
Result alias for keychain operations.
pub const CREDENTIAL_NAME: &str = "bookclerk-master-key";
The credential name the key is sealed under, and the name a service
unit hands it in as (LoadCredentialEncrypted=bookclerk-master-key).
pub const KEYCHAIN_SERVICE: &str = "app.bookclerk.master-key";
Keychain service name every Bookclerk master-key item is stored under.
The item's account (user) name is its KeychainItemId, so two installs
for one OS user (a development checkout beside an installed app) keep
separate items.
pub const POINTER_MAGIC: &[u8; 4] = b"BCK3";
Four-byte header of a master.key pointer record for an OS keychain
item (BCK3).
pub const CREDS_POINTER_MAGIC: &[u8; 4] = b"BCK4";
Four-byte header of a master.key pointer record for a key sealed with
systemd-creds (BCK4): the same layout as POINTER_MAGIC's.
pub const FINGERPRINT_LEN: usize = 32;
Length in bytes of a key fingerprint (SHA-256 of the DEK).
pub const POINTER_LEN: usize = _;
Length in bytes of an encoded [KeychainPointer]: header, 16-byte item
id, 32-byte fingerprint.
pub const MAX_ITEM_LEN: usize = 2048;
Largest item, in bytes, a Vault accepts.
A BCK2 envelope is 108 bytes; Windows Credential Manager caps a blob at
2,560 bytes. Anything larger is refused before it reaches the store.
Generated from crates/bookclerk-keystore at main · View as Markdown