Kleidos API Search

In development. It changes without notice.

Topic

Record Log & Envelopes

The log the records are appended to, the binary form of a record, and the sealed envelope around it.

Records are entries of an append-only log cut into fixed segments: a write appends, and a read finds the live entry of a slot through the log's own index. Each entry is an envelope of a version byte, the IV, the HMAC tag and the ciphertext. The list index, the pool of a login's optional fields, and the reserved buffers the record path works in are here too, so that saving a record allocates nothing it could be refused.

See also
Vault Storage, Keys, Metadata & Rotation, Record Repositories

Files

file src/vault/credential_pool.h
The credential record's flexible pool: everything optional, as TLV.
file src/vault/record_codec.h
In-house packed binary codec for the vault at-rest plaintext records.
file src/vault/record_log.h
The append-only record log: a few segment files hold every credential and TOTP entry.
file src/vault/record_scratch.h
The credential path's three large buffers, reserved rather than allocated.
file src/vault/record_store.h
Where a slot's live record is: the log plus a slot table in RAM.
file src/vault/segmented_walk.h
The one bounded-unit segmentation: slot partition, feed boundary, trace.
file src/vault/staged_record_name.h
Canonical grammar for vault file basenames (cred_NN.bin, wifi.bin, …).
file src/vault/vault_envelope.h
Shared encrypt-then-MAC envelope contract for the vault records.
file src/vault/vault_index.h
Slot-keyed encrypted list index (idx_NN.bin) for O(1) vault listing.

Classes

struct kleidos::vault::CredCustomField
One typed custom field of a credential. More about kleidos::vault::CredCustomField
struct kleidos::vault::CredHistoryEntry
One superseded password and when it stopped being current. More about kleidos::vault::CredHistoryEntry
class kleidos::vault::CredentialPool
The bounded TLV region of a credential record. More about kleidos::vault::CredentialPool
class kleidos::vault::codec::Writer
Append-only cursor that packs fields into a fixed stack buffer. More about kleidos::vault::codec::Writer
class kleidos::vault::codec::Reader
Forward-only cursor that decodes fields with a single guard. More about kleidos::vault::codec::Reader
struct kleidos::vault::LogEntry
One entry's header, plus where it sits. More about kleidos::vault::LogEntry
class kleidos::vault::RecordLog
The record log's operations. Stateless: every call opens the file. More about kleidos::vault::RecordLog
class kleidos::vault::ByteScratch< N, Tag >
One reserved byte buffer, lent out for the duration of a scope. More about kleidos::vault::ByteScratch< N, Tag >
class kleidos::vault::RecordScratch
One reserved, decrypted CredentialRecord, lent out for a scope. More about kleidos::vault::RecordScratch
class kleidos::vault::RecordStore
The record store's operations. All static; the vault worker owns it. More about kleidos::vault::RecordStore
class kleidos::vault::seg::SegmentedWalk
Drives a sequence of bounded units and owns what happens between them. More about kleidos::vault::seg::SegmentedWalk
struct kleidos::vault::SlottedFamily
One slotted record family: the stem its basenames start with, the kind that stem classifies as, and the build's capacity for that family. More about kleidos::vault::SlottedFamily
struct kleidos::vault::EnvelopeContext
Identity fields bound into the authenticated context prefix of a record. More about kleidos::vault::EnvelopeContext
struct kleidos::vault::IndexEntry
One cached list row: enough to render a list item without decrypting the full credential. More about kleidos::vault::IndexEntry
struct kleidos::vault::RotationKeys
The facts a segment read needs about a live rotation. More about kleidos::vault::RotationKeys
class kleidos::vault::VaultIndex
The encrypted vault list cache, with rebuild-on-miss semantics. More about kleidos::vault::VaultIndex

Typedefs

usingkleidos::vault::EnvelopeScratch
usingkleidos::vault::PlaintextScratch
usingkleidos::vault::seg::UnitTick
usingkleidos::vault::IndexRowVisitor
Per-row sink invoked by kleidos::vault::VaultIndex::forEach.

Enumerations

enum class kleidos::vault::CredPoolType : uint8_t { kleidos::vault::CredPoolType::Notes, kleidos::vault::CredPoolType::CustomField, kleidos::vault::CredPoolType::RecoveryCodes, kleidos::vault::CredPoolType::ExtraUrl, kleidos::vault::CredPoolType::SsoProvider, kleidos::vault::CredPoolType::PasswordHistory }
What one pool entry holds. More about kleidos::vault::CredPoolType
enum class kleidos::vault::CredFieldKind : uint8_t { kleidos::vault::CredFieldKind::Text, kleidos::vault::CredFieldKind::Concealed, kleidos::vault::CredFieldKind::Email, kleidos::vault::CredFieldKind::Url, kleidos::vault::CredFieldKind::Phone, kleidos::vault::CredFieldKind::Date }
What kind of value a custom field carries. More about kleidos::vault::CredFieldKind
enum class kleidos::vault::LogEntryType : uint8_t
enum class kleidos::vault::LogFind : uint8_t { kleidos::vault::LogFind::Found , kleidos::vault::LogFind::None , kleidos::vault::LogFind::Unreadable }
enum class kleidos::vault::LogScanEnd : uint8_t { kleidos::vault::LogScanEnd::Clean, kleidos::vault::LogScanEnd::TornTail, kleidos::vault::LogScanEnd::Damaged, kleidos::vault::LogScanEnd::Unreadable, kleidos::vault::LogScanEnd::Stopped }
enum class kleidos::vault::EnvelopeRead : uint8_t { kleidos::vault::EnvelopeRead::Ok , kleidos::vault::EnvelopeRead::Absent , kleidos::vault::EnvelopeRead::Unreadable }
Why a stored envelope could not be produced. More about kleidos::vault::EnvelopeRead
enum class kleidos::vault::RecordLoad : uint8_t { kleidos::vault::RecordLoad::Ok , kleidos::vault::RecordLoad::Absent , kleidos::vault::RecordLoad::Unreadable , kleidos::vault::RecordLoad::Rejected }
Why a stored record could not be produced. More about kleidos::vault::RecordLoad
enum class kleidos::vault::StagedKind : uint8_t { kleidos::vault::StagedKind::Meta, kleidos::vault::StagedKind::Cred, kleidos::vault::StagedKind::Totp, kleidos::vault::StagedKind::IndexSegment, kleidos::vault::StagedKind::Group, kleidos::vault::StagedKind::Wifi, kleidos::vault::StagedKind::RecordLog, kleidos::vault::StagedKind::Foreign }
Classification of a staged / canonical vault file by its basename. More about kleidos::vault::StagedKind
enum class kleidos::vault::RotateOutcome : uint8_t { kleidos::vault::RotateOutcome::Rotated , kleidos::vault::RotateOutcome::AlreadyThere , kleidos::vault::RotateOutcome::Unreadable , kleidos::vault::RotateOutcome::Failed }
enum class kleidos::vault::LoadVerdict : uint8_t { kleidos::vault::LoadVerdict::Verified , kleidos::vault::LoadVerdict::Rejected , kleidos::vault::LoadVerdict::Indeterminate }
Whether a stored artifact was proven to be a record this key set authenticates, proven not to be, or neither — the third value is what a caller acting on the answer must not fold into the second. More about kleidos::vault::LoadVerdict
enum class kleidos::vault::EnvelopeRecordType : uint8_t { kleidos::vault::EnvelopeRecordType::Credential, kleidos::vault::EnvelopeRecordType::Totp, kleidos::vault::EnvelopeRecordType::Wifi, kleidos::vault::EnvelopeRecordType::Group, kleidos::vault::EnvelopeRecordType::IndexSegment }
Per-record type discriminator bound into the authenticated tag. More about kleidos::vault::EnvelopeRecordType

Functions

size_tkleidos::vault::maxLogPayloadBytes (LogEntryType type)
The widest payload an entry of type may carry: the widest envelope THAT CLASS is stored as.
voidkleidos::vault::encodeLogEntryHeader (std::array< uint8_t, kLogEntryHeaderBytes > &out, LogEntryType type, bool tombstone, uint16_t slot, uint32_t gen, uint16_t len)
Write into out the header bytes an append of these fields writes, checksum included.
constexpr uint16_tkleidos::vault::logSegmentOf (uint16_t slot)
Segment that owns slot within its class.
constexpr uint16_tkleidos::vault::logSegmentsOf (LogEntryType type)
constexpr uint16_tkleidos::vault::seg::segmentCount (uint32_t slotCapacity)
Number of units that cover a slot space of slotCapacity.
constexpr uint16_tkleidos::vault::seg::segmentOf (uint32_t slotId)
Unit that owns slot slotId.
constexpr uint32_tkleidos::vault::seg::segmentFirstSlot (uint16_t segment)
First slot owned by unit segment.
constexpr uint32_tkleidos::vault::seg::segmentEndSlot (uint16_t segment, uint32_t slotCapacity)
One past the last slot owned by unit segment.
boolkleidos::vault::parseStagedSlot (const char *digits, size_t n, uint16_t &slotOut)
Parse the canonical decimal slot span of a record basename.
StagedKindkleidos::vault::classifyStagedName (const char *name, uint16_t &slotOut)
Classify a vault file basename; fills slotOut for Cred/Totp.
size_tkleidos::vault::writeEnvelopeContext (uint8_t *out, const EnvelopeContext &context) noexcept
Write the authenticated context prefix that precedes the IV in the MAC.
boolkleidos::vault::computeEnvelopeTagStreamed (const uint8_t *macKey, size_t macKeyLen, const EnvelopeContext &context, const uint8_t *iv, const uint8_t *cipher, size_t cipherLen, std::array< uint8_t, kHmacSize > &tagOut)
Compute the bound EtM tag HMAC(macKey, ctx || iv || cipher).
template<size_t MaxCipher>
boolkleidos::vault::computeEnvelopeTag (const uint8_t *macKey, size_t macKeyLen, const EnvelopeContext &context, const uint8_t *iv, const uint8_t *cipher, size_t cipherLen, std::array< uint8_t, kHmacSize > &tagOut)
Bound-checked wrapper kept for the record modules' call shape.
template<size_t MaxCipher>
boolkleidos::vault::verifyEnvelopeBytes (const uint8_t *macKey, size_t macKeyLen, const EnvelopeContext &context, const uint8_t *env, size_t len)
Verify an envelope held in memory — the record-log form of a file's verify-before-decrypt: version, block alignment, and the tag under context, compared in constant time.
constexpr uint16_tkleidos::vault::indexSegmentOf (uint16_t id)
Segment that caches credential slot id.
constexpr uint16_tkleidos::vault::indexSegmentFirstSlot (uint16_t segment)
First credential slot cached by segment segment.
constexpr uint16_tkleidos::vault::indexSegmentEndSlot (uint16_t segment)
One past the last credential slot cached by segment segment.
voidkleidos::vault::listDomain (const char *url, kleidos::util::str::InplaceString< kIndexDomainLen > &out)
Derive a record's list domain: the index's domain column for url.

Variables

constexpr size_tkleidos::vault::kCredPlaintextSize
constexpr size_tkleidos::vault::kCredFixedSize
constexpr size_tkleidos::vault::kCredPoolBytes
Bytes the pool may hold, entry headers included.
constexpr size_tkleidos::vault::kCredPoolEntryHeader
Bytes one pool entry costs beyond its value: [type u8][len u16].
constexpr size_tkleidos::vault::kCredNotesLen
Max notes length.
constexpr size_tkleidos::vault::kCredRecoveryCodesLen
Max recovery-codes block.
constexpr size_tkleidos::vault::kCredExtraUrlLen
Max length of one extra URL.
constexpr size_tkleidos::vault::kCredSsoProviderLen
Max SSO provider name.
constexpr size_tkleidos::vault::kCredCustomLabelLen
Max custom-field label.
constexpr size_tkleidos::vault::kCredCustomValueLen
Max custom-field value.
constexpr size_tkleidos::vault::kCredHistoryPassLen
Max historical password.
constexpr size_tkleidos::vault::kCredMaxCustomFields
Custom fields per record.
constexpr size_tkleidos::vault::kCredMaxExtraUrls
Extra URLs per record.
constexpr size_tkleidos::vault::kCredMaxHistory
History entries per record.
constexpr size_tkleidos::vault::kCredCustomFixedBytes
constexpr size_tkleidos::vault::kCredHistoryFixedBytes
Value bytes of a history entry before its password: [changedAt u32].
constexpr uint8_tkleidos::vault::kCredFieldKindMax
constexpr uint8_tkleidos::vault::kLogTombstoneFlag
Type-byte flag marking a tombstone: the slot was deleted; no payload.
constexpr size_tkleidos::vault::kLogEntryHeaderBytes
constexpr size_tkleidos::vault::kLogEntryMaxPayload
constexpr uint32_tkleidos::vault::kLogNoOffset
"No entry": the value a slot's offset holds when the log has none for it.
constexpr uint16_tkleidos::vault::kLogCredSlots
Credential slots this build declares.
constexpr uint16_tkleidos::vault::kLogTotpSlots
TOTP slots this build declares.
constexpr uint16_tkleidos::vault::kLogCredSegments
Segment files covering the credential slot space.
constexpr uint16_tkleidos::vault::kLogTotpSegments
Segment files covering the TOTP slot space.
constexpr uint16_tkleidos::vault::kLogSegmentCount
Segments of both classes together — what a whole-log walk visits.
constexpr size_tkleidos::vault::kRecordCompactMinGarbageBytes
constexpr uint16_tkleidos::vault::seg::kSegmentSlots
Slots covered by ONE bounded unit.
constexpr std::array< SlottedFamily, 5 >kleidos::vault::kSlottedFamilies
constexpr uint8_tkleidos::vault::kEnvelopeVersion
constexpr uint16_tkleidos::vault::kEnvelopeWifiSlot
Fixed slot id bound for the singleton WiFi-network file (it has no real slot).
constexpr uint32_tkleidos::vault::kEnvelopeWifiGeneration
constexpr uint16_tkleidos::vault::kEnvelopeGroupSlot
Fixed slot id bound for the singleton group-name file (it has no real slot).
constexpr uint32_tkleidos::vault::kEnvelopeGroupGeneration
constexpr size_tkleidos::vault::kEnvelopeContextSize
constexpr size_tkleidos::vault::kEnvelopeBytesHeader
Byte layout of an envelope in memory: [ver 1][iv 16][hmacTag 32][cipher].
constexpr size_tkleidos::vault::kIndexNameLen
Display-name length cached in the index (bounded to keep the file compact).
constexpr size_tkleidos::vault::kIndexUserLen
Username length cached in the index (bounded to keep the file compact).
constexpr size_tkleidos::vault::kIndexDomainLen
constexpr size_tkleidos::vault::kIndexSegmentPathCapacity
constexpr uint8_tkleidos::vault::kIndexFormatVersion
Current index-file format version.
constexpr size_tkleidos::vault::kIndexVerOffset
Field offsets within a serialized segment file (mirror the credential record).
constexpr size_tkleidos::vault::kIndexHeaderSize
Size of the fixed-length header (everything before the ciphertext).
constexpr size_tkleidos::vault::kIndexMinFileSize
Smallest valid file: header + one AES block of ciphertext.
constexpr uint16_tkleidos::vault::kIndexSegmentRows
Credential slots cached by ONE segment file.
constexpr uint16_tkleidos::vault::kIndexSegmentCount
Number of segment files that cover the whole slot space.
constexpr uint8_tkleidos::vault::kIndexSegmentPlaintextVer
Record-schema version of the packed-binary segment plaintext.
constexpr size_tkleidos::vault::kIndexRowMaxSize
constexpr size_tkleidos::vault::kIndexSegmentHeaderPlaintext
Fixed segment plaintext header: plaintextVer(1) + segIndex(2 LE) + rowCount(2 LE).
constexpr size_tkleidos::vault::kIndexSegmentMaxPlaintextSize
Worst-case segment plaintext: every row of the segment at full field lengths.
constexpr size_tkleidos::vault::kIndexSegmentMaxCipherSize
constexpr size_tkleidos::vault::kIndexSegmentMaxFileSize
Worst-case whole-file size of one segment (< the 4 KB LittleFS block).
constexpr size_tkleidos::vault::kIndexSegmentPlainBufferSize

Back to the top

Typedef Documentation

EnvelopeScratch #

using kleidos::vault::EnvelopeScratch

The [ver][iv][tag][cipher] bytes of one credential record, on their way to or from the log.

IndexRowVisitor #

typedef bool(* kleidos::vault::IndexRowVisitor)(const IndexEntry &row, void *user)

Per-row sink invoked by kleidos::vault::VaultIndex::forEach.

A plain function pointer plus an opaque cookie, not a std::function: the sink is called from the vault worker with no allocation of its own (see sonar-project.properties, rule S5205/S5008).

Parameters
NameDirectionMeaning
rowinThe decoded row, valid only for the duration of the call.
userinThe cookie handed to forEach.
Return values
ValueMeaning
trueContinue with the next row.
falseStop the walk; the remaining rows are not delivered.
Warning
SECURITY: row carries a name, a username and an origin domain. The walk wipes the whole working set when it returns, so a sink that copies any of those out owns wiping its copy.

Mirror of the sink alias defined in vault_index.h, so VaultStore::forEachIndexRow can be declared without pulling that header in. A translation unit that includes both (vault_store.cpp does) makes the two declarations meet, so the compiler catches any future drift.

PlaintextScratch #

using kleidos::vault::PlaintextScratch

One credential record's plaintext — the encoder's output and the decrypt's destination, which is a padding block wider — and, while a restore reads a record or the backup's meta string, the text it unescapes them into.

UnitTick #

using kleidos::vault::seg::UnitTick

Paint slot handed to the caller between two bounded units: a plain function pointer, or nullptr for none. No caller passes one: a screen that shows the wait paints from inside each unit's wait on the vault worker (wait_pump.h), so nothing paints between the units.

Back to the top

Enumeration Type Documentation

CredFieldKind #

enum class kleidos::vault::CredFieldKind : uint8_t

What kind of value a custom field carries.

Mirrors the typed sections a 1Password export distinguishes, so an import keeps the distinction and the panel can render a date as a date. The device types Text, Concealed and Email; it shows the rest.

Enumerator
Text 

Plain text (the default).

Concealed 

Secret-grade text.

Email 

An e-mail address.

Url 

A URL.

Phone 

A phone number.

Date 

A date, as the exporting manager wrote it.

CredPoolType #

enum class kleidos::vault::CredPoolType : uint8_t

What one pool entry holds.

The numeric values are the wire format: they are read from records already on flash, so an existing one is never renumbered and a retired one is never reused. An unknown type decodes as an opaque entry — it is kept on re-encode, so a record written by a newer firmware survives a round trip through an older one.

Enumerator
Notes 

Free text. At most one.

CustomField 

Typed label + value (see CredCustomField).

RecoveryCodes 

Multi-line backup codes, always hidden. At most one.

ExtraUrl 

An additional URL beyond the record's primary one.

SsoProvider 

"Sign in with …" provider name. At most one.

PasswordHistory 

A superseded password and when it was replaced.

EnvelopeRead #

enum class kleidos::vault::EnvelopeRead : uint8_t

Why a stored envelope could not be produced.

The distinction that matters to a caller rebuilding a cache from the log: a slot that holds nothing is a row that must not be listed, while a log that could not be read is a row whose fate is simply unknown right now.

Enumerator
Ok 

The envelope bytes were produced.

Absent 

No entry stands at that slot and generation, or it is deleted.

Unreadable 

An entry may well be there; the log could not be read now.

EnvelopeRecordType #

enum class kleidos::vault::EnvelopeRecordType : uint8_t

Per-record type discriminator bound into the authenticated tag.

Distinct values give cross-type substitution a different recomputed tag, so a file of one type can never verify when loaded as another type.

Enumerator
Credential 

A credential entry of the record log.

Totp 

A TOTP entry of the record log.

Wifi 

wifi.bin (singleton; uses ::kEnvelopeWifiSlot).

Group 

groups.bin (singleton; uses ::kEnvelopeGroupSlot).

IndexSegment 

idx_XX.bin (slotId = segment number).

LoadVerdict #

enum class kleidos::vault::LoadVerdict : uint8_t

Whether a stored artifact was proven to be a record this key set authenticates, proven not to be, or neither — the third value is what a caller acting on the answer must not fold into the second.

Two-valued was the defect: a MAC that did not match, a file that was not there, and a heap or backend failure all collapsed into one false, and the singleton loaders read that as "the store is empty". The next mutator then read-modify-wrote that emptiness over a perfectly good record. Absence really is an empty store; a failure to check is not, and must reach the caller as its own answer.

The three spellings are the ones already used for staged records, kept deliberately identical so the vault has one vocabulary for "authenticated / provably not / could not tell" rather than three.

Enumerator
Verified 

Authenticated and decoded. An absent file is Verified-empty.

Rejected 

Provably not a record this key set authenticates.

Indeterminate 

The check could not be completed; nothing is proven.

LogEntryType #

enum class kleidos::vault::LogEntryType : uint8_t

Which record class an entry belongs to. A tombstone carries the class of the slot it deletes (credential slot 5 and TOTP slot 5 are different slots).

LogFind #

enum class kleidos::vault::LogFind : uint8_t

How a lookup by (slot, generation) ended.

"The log holds no such entry" and "the log could not be read" are the same false to a two-valued answer, and every caller of this lookup acts on the first by writing: a rebuild omits the row, a reconcile tombstones the slot. A scan that failed is no evidence for either, so it is a value of its own.

Enumerator
Found 

The entry was located; out describes it.

None 

The segment was read to its end and holds no such live entry.

Unreadable 

The segment was not read to its end; nothing is known.

LogScanEnd #

enum class kleidos::vault::LogScanEnd : uint8_t

How a scan ended.

TornTail and Damaged both mean the walk stopped before the file's end and everything in front of that point was delivered. They differ in whether the bytes at the stopping point are a header THIS FIRMWARE WROTE, which is what says whether the rest of the file may be thrown away.

The whole decision rests on the header's own checksum, and on nothing else: a header that verifies and declares a payload the file ends inside of is one interrupted append, so a rewrite drops that entry and keeps every other. Any other stopping point is damage of unknown extent, contained where it lies. No property of the bytes BEHIND the stopping point takes part — a run of intact entries is exactly what a mid-file bit flip leaves behind it, and every measure of that run (its width above all) reads the same on an interrupted append as on damage, because an entry of a class is not one width: a credential segment holds 11-byte tombstones beside 4 KB records.

Enumerator
Clean 

Every entry read; the last one ended exactly at the file's end.

TornTail 

The tail is an interrupted append: fewer bytes than a header, or a header that VERIFIES whose payload the file ends inside of.

Damaged 

The bytes at the stopping point are no header this build wrote.

Unreadable 

A segment could not be opened or a read failed part-way.

Stopped 

The visitor asked to stop.

RecordLoad #

enum class kleidos::vault::RecordLoad : uint8_t

Why a stored record could not be produced.

A cache rebuilt from the records has to tell "this slot holds nothing" from "this slot could not be read just now": the first is a row that must not be listed, the second is a row whose omission would publish a live credential as gone. RecordLoad::Rejected is the third: bytes that WERE read and failed their MAC, their version or their decode — damage, and permanent until the slot is written again.

Enumerator
Ok 

The record was produced.

Absent 

Nothing stands at that slot and generation.

Unreadable 

A busy buffer, a failed log read or a crypto resource failure.

Rejected 

The stored bytes were read and refused.

RotateOutcome #

enum class kleidos::vault::RotateOutcome : uint8_t

What re-encrypting a single-record store under a new key established.

The four answers are the four states a rotation step can actually be in, and collapsing any two of them costs something: Unreadable is a permanent loss the owner must be told about, while Failed is a retry — and AlreadyThere is the resume case, where a previous attempt's promote landed and re-doing the work would fail a proof on a file that no longer exists and retry for ever.

Enumerator
Rotated 

Read under the old keys and re-written under the new.

AlreadyThere 

Not readable under the old keys, but readable under the new ones: a previous attempt's promote already landed.

Unreadable 

Provably not this vault's record under EITHER key. It was already lost before the rotation began; record and move on.

Failed 

Nothing was proven. Nothing was written, and the caller retries; this must never be read as a loss.

StagedKind #

enum class kleidos::vault::StagedKind : uint8_t

Classification of a staged / canonical vault file by its basename.

Enumerator
Meta 

meta.bin — the vault's root of trust.

Cred 

cred_NN.bin / cred_NNN.bin — a credential record.

Totp 

totp_NN.bin / totp_NNN.bin — a TOTP record.

IndexSegment 

idx_NN.bin — one slot-keyed page of the listing cache.

Group 

groups.bin — the singleton group-label table.

Wifi 

wifi.bin — the singleton saved-network store.

RecordLog 

rc_NN.bin / rt_NN.bin — one record-log segment.

Foreign 

Anything else; never promoted, and rejects the whole import.

Back to the top

Function Documentation

classifyStagedName() #

StagedKind kleidos::vault::classifyStagedName(const char * name, uint16_t & slotOut)
inline

Classify a vault file basename; fills slotOut for Cred/Totp.

The singleton names (meta.bin, groups.bin, wifi.bin) match whole-string and exactly, so no near-miss spelling — a .tmp sidecar, a marker, a staging directory — can be mistaken for one of them.

Slot ids at or past the build-time capacity classify as ::StagedKind::Foreign, so an import carrying records this board cannot hold is refused whole rather than partially promoted.

Parameters
NameDirectionMeaning
nameinNUL-terminated basename (no directory component).
slotOutoutReceives the slot id for ::StagedKind::Cred / ::Totp, or the segment number for ::StagedKind::IndexSegment and ::StagedKind::RecordLog.
Returns
The basename's classification.

computeEnvelopeTag() #

template<size_t MaxCipher>
bool kleidos::vault::computeEnvelopeTag(const uint8_t * macKey, size_t macKeyLen, const EnvelopeContext & context, const uint8_t * iv, const uint8_t * cipher, size_t cipherLen, std::array< uint8_t, kHmacSize > & tagOut)

Bound-checked wrapper kept for the record modules' call shape.

Template Parameters
NameMeaning
MaxCipherCompile-time upper bound on cipherLen (schema sanity; no buffer of this size exists anywhere). Shared by every record module and the re-key path so all sites are bit-identical. The authenticated message is the context prefix (see writeEnvelopeContext) followed by the IV and ciphertext.

The three envelope parts are fed to a multipart HMAC — no concatenation buffer exists, so the cost is independent of cipherLen (the previous shape materialized ctx || iv || cipher in a MaxCipher-sized stack array, which at index capacity put ~15 KB on the worker stack per tag).

Parameters
NameDirectionMeaning
macKeyinFile-HMAC sub-key.
macKeyLeninLength of macKey in bytes.
contextinRecord identity fields (type, slot, generation).
ivin::kleidos::kIvSize-byte IV.
cipherinCiphertext bytes.
cipherLeninLength of cipher in bytes.
tagOutoutReceives the ::kHmacSize-byte tag.
Return values
ValueMeaning
trueTag computed.
falseBackend HMAC failure (tagOut wiped).
Note
This wrapper also returns false when cipherLen exceeds MaxCipher — the backend is never reached and tagOut is left untouched.

computeEnvelopeTagStreamed() #

bool kleidos::vault::computeEnvelopeTagStreamed(const uint8_t * macKey, size_t macKeyLen, const EnvelopeContext & context, const uint8_t * iv, const uint8_t * cipher, size_t cipherLen, std::array< uint8_t, kHmacSize > & tagOut)
inline

Compute the bound EtM tag HMAC(macKey, ctx || iv || cipher).

Shared by every record module and the re-key path so all sites are bit-identical. The authenticated message is the context prefix (see writeEnvelopeContext) followed by the IV and ciphertext.

The three envelope parts are fed to a multipart HMAC — no concatenation buffer exists, so the cost is independent of cipherLen (the previous shape materialized ctx || iv || cipher in a MaxCipher-sized stack array, which at index capacity put ~15 KB on the worker stack per tag).

Parameters
NameDirectionMeaning
macKeyinFile-HMAC sub-key.
macKeyLeninLength of macKey in bytes.
contextinRecord identity fields (type, slot, generation).
ivin::kleidos::kIvSize-byte IV.
cipherinCiphertext bytes.
cipherLeninLength of cipher in bytes.
tagOutoutReceives the ::kHmacSize-byte tag.
Return values
ValueMeaning
trueTag computed.
falseBackend HMAC failure (tagOut wiped).

encodeLogEntryHeader() #

void kleidos::vault::encodeLogEntryHeader(std::array< uint8_t, kLogEntryHeaderBytes > & out, LogEntryType type, bool tombstone, uint16_t slot, uint32_t gen, uint16_t len)

Write into out the header bytes an append of these fields writes, checksum included.

The single definition of the entry framing. Anything that has to PRODUCE entry bytes goes through here, so the bytes a scan accepts and the bytes something else lays down cannot come to disagree — the scan's whole tear-or-damage decision rests on the checksum matching the fields beside it.

Parameters
NameDirectionMeaning
outoutThe header bytes.
typeinRecord class.
tombstoneinThe entry is the slot's erasure; len must be 0.
slotinSlot within the class.
geninGeneration the entry is written at.
leninPayload bytes that follow the header.

indexSegmentEndSlot() #

uint16_t kleidos::vault::indexSegmentEndSlot(uint16_t segment)
constexpr

One past the last credential slot cached by segment segment.

Clamped to the build capacity, so the last segment may be short.

Parameters
NameDirectionMeaning
segmentinSegment number.
Returns
One past the highest slot id the segment owns.

indexSegmentFirstSlot() #

uint16_t kleidos::vault::indexSegmentFirstSlot(uint16_t segment)
constexpr

First credential slot cached by segment segment.

Parameters
NameDirectionMeaning
segmentinSegment number.
Returns
The lowest slot id the segment owns.

indexSegmentOf() #

uint16_t kleidos::vault::indexSegmentOf(uint16_t id)
constexpr

Segment that caches credential slot id.

Parameters
NameDirectionMeaning
idinCredential slot id.
Returns
The segment number whose file holds that slot's cached row.

listDomain() #

void kleidos::vault::listDomain(const char * url, kleidos::util::str::InplaceString< kIndexDomainLen > & out)

Derive a record's list domain: the index's domain column for url.

Canonicalizes through the brand registry (kleidos::brands::canonicalizeDomain, the one domain grammar: no scheme, user info or port, lowercase, no leading www.) and cuts the result to ::kIndexDomainLen bytes. A surface that holds the record's URL calls this to name the record exactly as its list row does (the brand token, ui::brandToken); the index fills its own column with it.

Parameters
NameDirectionMeaning
urlinURL text from the credential record (null or empty allowed).
outoutThe list domain; empty when url is empty or names no host.
Warning
SECURITY: the domain is record metadata. The canonical scratch is wiped before return; a caller wipes its own out.

logSegmentOf() #

uint16_t kleidos::vault::logSegmentOf(uint16_t slot)
constexpr

Segment that owns slot within its class.

Positional and computable, never stored: nothing has to be kept coherent when a slot is written, and a slot's entries can only ever be in one file.

Parameters
NameDirectionMeaning
slotinSlot id within its class.
Returns
The segment number.

logSegmentsOf() #

uint16_t kleidos::vault::logSegmentsOf(LogEntryType type)
constexpr

Segments the class type is split into.

Parameters
NameDirectionMeaning
typeinRecord class.
Returns
The segment count for that class.

maxLogPayloadBytes() #

size_t kleidos::vault::maxLogPayloadBytes(LogEntryType type)
nodiscard

The widest payload an entry of type may carry: the widest envelope THAT CLASS is stored as.

The log accepts one payload bound for both classes, so this is what holds an entry of one class to the width its own records have — on the append side, where a wider envelope is refused, and on the read side, where a header declaring more than its class holds is refused before a byte of it is read.

It is a function rather than a constant because the two widths are declared by credential_repository.h and totp_repository.h, which include this header and so cannot be included by it.

Parameters
NameDirectionMeaning
typeinRecord class.
Returns
Payload bytes, at most ::kLogEntryMaxPayload.

parseStagedSlot() #

bool kleidos::vault::parseStagedSlot(const char * digits, size_t n, uint16_t & slotOut)
inline

Parse the canonical decimal slot span of a record basename.

The grammar is canonical, i.e. digits → slot is injective: two digits spell every slot below 100 ("07" → 7) and three digits spell every slot at or above it ("123" → 123). A three-digit span starting with '0' is refused, because the writer never emits it and accepting it would alias two basenames onto one slot.

Parameters
NameDirectionMeaning
digitsinFirst digit of the span (not NUL-terminated).
ninNumber of digits in the span.
slotOutoutReceives the parsed slot on success; untouched otherwise.
Return values
ValueMeaning
truedigits is a canonical 2- or 3-digit slot spelling.
falseWrong length, a non-digit, or a non-canonical leading zero.

segmentCount() #

uint16_t kleidos::vault::seg::segmentCount(uint32_t slotCapacity)
constexpr

Number of units that cover a slot space of slotCapacity.

Fixed by the build's capacity, not by how much the vault holds, so an empty vault walks the same number of units as a full one.

Parameters
NameDirectionMeaning
slotCapacityinSize of the slot space being partitioned.
Returns
Unit count; 0 for an empty slot space.

segmentEndSlot() #

uint32_t kleidos::vault::seg::segmentEndSlot(uint16_t segment, uint32_t slotCapacity)
constexpr

One past the last slot owned by unit segment.

Clamped to slotCapacity, so the last unit may be short.

Parameters
NameDirectionMeaning
segmentinUnit number.
slotCapacityinSize of the slot space being partitioned.
Returns
One past the highest slot id in the unit, never above slotCapacity.

segmentFirstSlot() #

uint32_t kleidos::vault::seg::segmentFirstSlot(uint16_t segment)
constexpr

First slot owned by unit segment.

Parameters
NameDirectionMeaning
segmentinUnit number.
Returns
The lowest slot id in the unit.

segmentOf() #

uint16_t kleidos::vault::seg::segmentOf(uint32_t slotId)
constexpr

Unit that owns slot slotId.

Parameters
NameDirectionMeaning
slotIdinSlot id.
Returns
The unit number covering that slot.

verifyEnvelopeBytes() #

template<size_t MaxCipher>
bool kleidos::vault::verifyEnvelopeBytes(const uint8_t * macKey, size_t macKeyLen, const EnvelopeContext & context, const uint8_t * env, size_t len)

Verify an envelope held in memory — the record-log form of a file's verify-before-decrypt: version, block alignment, and the tag under context, compared in constant time.

Template Parameters
NameMeaning
MaxCipherLargest ciphertext the caller's scratch holds.
Parameters
NameDirectionMeaning
macKeyinMAC sub-key bytes.
macKeyLeninBytes in macKey.
contextinWhat the tag is bound to.
envinEnvelope bytes.
leninBytes in env.
Return values
ValueMeaning
trueThe envelope is authentic for context.
falseIt is not, or it is malformed.

writeEnvelopeContext() #

size_t kleidos::vault::writeEnvelopeContext(uint8_t * out, const EnvelopeContext & context)
inlinenoexcept

Write the authenticated context prefix that precedes the IV in the MAC.

Layout: ver(1) || recordType(1) || slotId(2, LE) || generation(4, little-endian). The caller appends the IV and ciphertext after this prefix to form the full authenticated message, then HMACs it with the file MAC sub-key. Centralizing the prefix layout keeps every record module (and the re-key path) bit-identical.

Parameters
NameDirectionMeaning
outoutBuffer of at least ::kEnvelopeContextSize bytes.
contextinRecord identity fields (type, slot, generation).
Returns
Number of bytes written (::kEnvelopeContextSize).

Back to the top

Variable Documentation

kCredCustomFixedBytes #

size_t kleidos::vault::kCredCustomFixedBytes
inlineconstexpr

Value bytes of a custom-field entry before its label and value: [kind u8][hidden u8][labelLen u8].

kCredFieldKindMax #

uint8_t kleidos::vault::kCredFieldKindMax
inlineconstexpr

Highest CredFieldKind this build knows; a higher value decodes as CredFieldKind::Text so a newer record still renders.

kCredFixedSize #

size_t kleidos::vault::kCredFixedSize
inlineconstexpr

Bytes of the fixed part that precedes the pool (see credential_repository.h, which static_asserts its field sum against this).

kCredPlaintextSize #

size_t kleidos::vault::kCredPlaintextSize
inlineconstexpr

Plaintext bytes every credential record encodes to, padded before encryption. One LittleFS block, so a record never straddles a block.

kEnvelopeContextSize #

size_t kleidos::vault::kEnvelopeContextSize
inlineconstexpr

Size of the authenticated context prefix that precedes the IV: ver(1) || recordType(1) || slotId(2, LE) || generation(4, LE).

kEnvelopeGroupGeneration #

uint32_t kleidos::vault::kEnvelopeGroupGeneration
inlineconstexpr

Fixed generation bound for the group-name file: a singleton with no per-slot counter in meta.bin. A rolled-back groups.bin only restores the owner's own older group labels (no secret disclosure beyond the attacker-supplied old snapshot), so it carries no freshness anchor. The distinct ::EnvelopeRecordType::Group type byte still defeats cross-type substitution before decryption.

kEnvelopeVersion #

uint8_t kleidos::vault::kEnvelopeVersion
inlineconstexpr

On-disk envelope version byte. Stays 0x01; only the authenticated context (and thus the tag value) changed, never the file layout.

kEnvelopeWifiGeneration #

uint32_t kleidos::vault::kEnvelopeWifiGeneration
inlineconstexpr

Fixed generation bound for the WiFi-network file: like the index it is a singleton with no per-slot counter in meta.bin. A rolled-back wifi.bin only restores the owner's own older WiFi list (no secret disclosure beyond what the attacker-supplied old snapshot already contained), so it carries no freshness anchor. The distinct ::EnvelopeRecordType::Wifi type byte still defeats cross-type substitution before decryption.

kIndexDomainLen #

size_t kleidos::vault::kIndexDomainLen
inlineconstexpr

Origin-domain length cached in the index (derived from the record URL at save time so list surfaces render a site column / brand mark with zero per-row decrypts).

kIndexRowMaxSize #

size_t kleidos::vault::kIndexRowMaxSize
inlineconstexpr

Worst-case packed-binary size of one row, as a sum of its per-field maxima (see record_codec.h and the wire table in the .cpp): id(2, LE) + name (1 + 32) + user (1 + 32) + brand(2) + flags(1)

  • order(2, LE) + group(1) + mtime(4) + domain (1 + 24) = 2 + 33 + 33 + 2 + 1 + 2 + 1 + 4 + 25 = 103 bytes.

kIndexSegmentMaxCipherSize #

size_t kleidos::vault::kIndexSegmentMaxCipherSize
inlineconstexpr

Worst-case segment ciphertext. PKCS#7 always appends 1..16 bytes and pads to the next block boundary, so this is exact rather than an upper bound.

kIndexSegmentPathCapacity #

size_t kleidos::vault::kIndexSegmentPathCapacity
inlineconstexpr

Capacity of a segment-path buffer. The segment path itself is built by kleidos::vault::paths::indexSegmentPath and its staging twin by kleidos::vault::paths::indexSegmentTempPath . The new envelope is committed to the twin and only then promoted onto the canonical path with an atomic rename, so a torn write can never leave a half-written segment where a whole one was — the next read would rebuild it from the records at a decrypt per row. Readers never open the twin, and the vault-file basename grammar classifies it as non-content so it never rides a backup.

kIndexSegmentPlainBufferSize #

size_t kleidos::vault::kIndexSegmentPlainBufferSize
inlineconstexpr

Capacity of the DECRYPTED-segment buffer.

Sized to the ciphertext, not to the payload: AES-CBC writes the full ciphertext length into the destination and PKCS#7 stripping only shortens the reported length afterwards, so a buffer of ::kIndexSegmentMaxPlaintextSize would be overrun by the 11 pad bytes of a full-width segment — a segment this module's own write path produces from 32 maximum-width rows.

kIndexSegmentRows #

uint16_t kleidos::vault::kIndexSegmentRows
inlineconstexpr

Credential slots cached by ONE segment file.

The number that fixes the working set. 32 rows put the worst-case plaintext at 3,301 B and the whole file at 3,361 B, so a segment never spills a 4 KB LittleFS block. 32 is also the hard ceiling of the layout, not just a tuning choice: the per-slot bitmasks that validate, carry and rebuild a segment are uint32_t, and ::kMaxGenerationLag is one counter step per cached slot, so anything above 32 is undefined behavior rather than a wider segment. Halving it to 16 costs one more block per 16 slots at the re-key peak, which drops the credential ceiling of an 8 MB board without PSRAM below the 250 slots it offers.

The value itself lives in kleidos::vault::seg::kSegmentSlots, the one definition site shared with every other bounded walk; this is the index's name for it and the place its on-flash consequences are asserted.

kLogEntryHeaderBytes #

size_t kleidos::vault::kLogEntryHeaderBytes
inlineconstexpr

Bytes an entry adds beyond its payload: nine bytes of header fields plus the two-byte checksum over them.

kLogEntryMaxPayload #

size_t kleidos::vault::kLogEntryMaxPayload
inlineconstexpr

Largest payload an entry may carry — a bound a scan trusts a header against, so a corrupt length cannot walk it off the file.

Sized to the widest envelope the vault stores: a credential record is a fixed 4 KiB plaintext plus one AES padding block plus the 49-byte [ver][iv][tag] header, and the slack above that is room for the envelope to gain a field without a log-format change. credential_repository.h static_asserts the real envelope size against this.

kRecordCompactMinGarbageBytes #

size_t kleidos::vault::kRecordCompactMinGarbageBytes
inlineconstexpr

Garbage a log segment must hold before rewriting it is worth the copy: the one policy value the per-mutation compaction and the restore's closing pass share, so neither can drift from the flash model the other is measured by.

kSegmentSlots #

uint16_t kleidos::vault::seg::kSegmentSlots
inlineconstexpr

Slots covered by ONE bounded unit.

The single tuning parameter of the whole segmentation, and the only definition site: the index's on-flash geometry (kleidos::vault::kIndexSegmentRows) and the TOTP scan both read it, and the build's capacity check parses this line so the capacity model cannot drift from the firmware.

Two minima pull against each other when choosing it. Per unit: small enough that no single unit blocks the UI task long. In total: not so small that the fixed per-unit cost inflates the whole walk. meta.bin authenticates once per session, not once per unit, so the fixed cost per unit is one worker round-trip, the unit's own file read and its decrypt. The total-cost curve still rises as the stride shrinks, so the sweep is looking for the minimum of the two curves, not of either.

The two artifacts pay differently for a change, which matters when sweeping:

  • The index: the value is its on-flash geometry. Moving it re-shapes idx_NN.bin, moves every board's capacity ceiling, and is capped at 32 by the layout itself (the per-slot bitmasks are uint32_t) — so it can only be swept DOWN, and a value that wins on time may cost a board capacity. The build's capacity check recomputes the ceilings and fails when it does.
  • The TOTP scan: the value is not just control flow here: a TOTP record is an entry of the append-only record log, whose segments are cut on this same stride (record_log.h: one segment per range of ::kSegmentSlots slots, the same partition the index uses). Moving the value therefore re-shapes rt_NN.bin as well, and the compaction peak — the live vault plus one segment — moves with it.

kSlottedFamilies #

std::array<SlottedFamily, 5> kleidos::vault::kSlottedFamilies
inlineconstexpr

Every slotted family, in the order a basename is tested against. The stems are disjoint prefixes, so the order is presentational only.

Back to the top