Kleidos API Search

In development. It changes without notice.

Topic

Vault Storage

The encrypted vault: how logins, one-time-code secrets and saved networks are stored, listed, changed, backed up and re-keyed.

VaultStore is the facade every caller uses. It sends each call to the vault worker, a task on core 0 that does all the reading, writing and deriving, and it owns the life of the session's key and the recovery after a cut in power. The parts behind it are subtopics: Record Log & Envelopes the log the records live in, Keys, Metadata & Rotation the keys, the metadata and the rotation, Record Repositories the stores of each kind of record, and Backup, Import & Export backups, imports and exports.

On flash (a LittleFS partition that an update does not touch):

File Holds
/vault/meta.bin The metadata: the salt, the work factor, the verifier, the wrapped vault key, the state of a rotation, and a generation counter for each slot.
/vault/r/rc_NN.bin A segment of the record log: the logins of a fixed range of slots.
/vault/r/rt_NN.bin The same for one-time-code secrets.
/vault/i/idx_NN.bin An encrypted segment of the list's index.
/vault/groups.bin The names of the groups.
/vault/wifi.bin The saved networks.
/vault/mut_stage.bin and .mark A record being changed, and the mark that says so. Present only meanwhile.
/vault/import_new/ and import.commit An import from a card being built, and the mark that says it is complete. Present only meanwhile.

A record is packed binary: each field carries its length, and the decoder checks every bound and refuses what does not fit. Each record and each file carries its own HMAC tag, checked before anything is decrypted. The tag also covers what the record is, its slot and that slot's generation, so a file that was moved, swapped for another kind or put back from an older copy is refused.

Opening and listing. The secret's key checks the verifier and unwraps the vault key out of the metadata; the vault key then checks the metadata's own tag and reads the list from the index segments, without opening a record. A record is decrypted only when it is shown, edited or sent. The key path is drawn in Cryptography. The vault key is wiped when the session locks and before any sleep.

A mount that fails formats nothing. The partition is formatted only when every sector of it reads blank, or when a person or a wipe asked for it.

See also
Cryptography, Security, Change of Owner & Resets, Record Log & Envelopes, Keys, Metadata & Rotation, Record Repositories, Backup, Import & Export

Topics

Record Log & Envelopes
The log the records are appended to, the binary form of a record, and the sealed envelope around it.
Keys, Metadata & Rotation
The vault's keys, the authenticated metadata that holds them wrapped, what a typed secret becomes before it is derived, and the key rotation.
Record Repositories
The store of each kind of record: logins, one-time-code secrets and saved networks, with the names of the groups and the order of the lists.
Backup, Import & Export
The sealed backup the portal and the SD card share, the import of other managers' CSV files, and the SD card's flows.

Files

file src/vault/factory_reset_tag.h
The bytes a factory reset leaves in the blank vault partition until NVS is erased too.
file src/vault/format_failure_record.h
Whether a refused vault mount follows a format that failed, across boots.
file src/vault/secret_epoch.h
The secret epoch's NVS counter: what refuses a meta.bin that a rollback brought back.
file src/vault/vault_layout.h
Creates the vault's directory tree, and recognizes a tree this build cannot read.
file src/vault/vault_paths.h
The single owner of every vault file path, directory and basename.
file src/vault/vault_store.cpp
The session state and the helpers the other sources share: the format-failure record, the meta I/O, the session keys and the crash-safe mutation (part of vault_store.h).
file src/vault/vault_store.h
The one way the rest of the firmware reaches the encrypted vault.
file src/vault/vault_store_credentials.cpp
VaultStore's credentials: the record adapters, save, load, delete and the last-used slot (part of vault_store.h).
file src/vault/vault_store_entries.cpp
VaultStore's other entries: the one-time codes, the saved Wi-Fi networks and the NTP servers (part of vault_store.h).
file src/vault/vault_store_groups.cpp
VaultStore's groups: the encrypted label table and the member sweeps (part of vault_store.h).
file src/vault/vault_store_index.cpp
VaultStore's index cache: the listing walks, the rebuild and the batch guard (part of vault_store.h).
file src/vault/vault_store_internal.h
What the sources of VaultStore share: the session state, the meta I/O, the session keys and the crash-safe mutation.
file src/vault/vault_store_lifecycle.cpp
VaultStore's lifecycle: the mount, the boot's verdicts, provisioning, the unlock and the lock (part of vault_store.h).
file src/vault/vault_store_order.cpp
VaultStore's list columns: favorites and the custom list order (part of vault_store.h).
file src/vault/vault_store_secret.cpp
VaultStore's secret change and the in-place key rotation (part of vault_store.h).
file src/vault/vault_store_transfer.cpp
VaultStore's backup boundary: the JSON import and the streamed restore (part of vault_store.h).
file src/vault/vault_store_types.h
Value types of the VaultStore facade API: the record structs, the capacity caps, and the unlock and wipe verdicts.
file src/vault/vault_store_wipe.cpp
VaultStore's wipes: the crypto-erase and sweep fallbacks, wipeAll and emptyKeepingSecret (part of vault_store.h).
file src/vault/vault_task.h
Single-owner vault / LittleFS worker task pinned to Core 0 (PRO_CPU).
file src/vault/wipe_marker.h
One NVS byte that says a wipe was asked and has not finished.

Namespaces

namespace kleidos::vault
The vault: its records and their encryption, the record log and index, backups, import and the worker that runs them.
namespace kleidos::vault::backup
The JSON backup of the vault: the export, and the streamed restore of a backup document.

Classes

struct kleidos::vault::factory_reset_tag::Tag
What a factory reset hands to the boot that finishes it. More about kleidos::vault::factory_reset_tag::Tag
struct kleidos::vault::factory_reset_tag::ReadResult
read's answer. More about kleidos::vault::factory_reset_tag::ReadResult
struct kleidos::vault::FormatFailureVerdict
What a mount leaves of the failed-format record, and what the vault reports. More about kleidos::vault::FormatFailureVerdict
struct kleidos::vault::secret_epoch::Counter
The counter as read. More about kleidos::vault::secret_epoch::Counter
class kleidos::vault::VaultLayout
Creating and recognizing the vault's on-flash directory tree. More about kleidos::vault::VaultLayout
class kleidos::VaultStore
Static facade for encrypted credential, TOTP, and meta storage on LittleFS. More about kleidos::VaultStore
class kleidos::VaultIndexBatch
Defers the list-index rewrite across a bulk credential operation. More about kleidos::VaultIndexBatch
struct kleidos::OrderPlanCost
What a ranking's plan cost — reported whether it was applied or refused, so a refusal can say what the maintenance action would do. More about kleidos::OrderPlanCost
struct kleidos::OrderProgress
Called as an ordering plan is read and written. More about kleidos::OrderProgress
struct kleidos::Credential
Decrypted credential held only in RAM. More about kleidos::Credential
struct kleidos::CredentialEntry
Credential list entry: slot, name, favorite and order, read without opening the record. More about kleidos::CredentialEntry
struct kleidos::TotpEntry
Decrypted TOTP entry held only in RAM. More about kleidos::TotpEntry
struct kleidos::TotpSummary
Secret-free listing view of a stored TOTP entry. More about kleidos::TotpSummary
struct kleidos::GroupEntry
One group id → display-name mapping surfaced by VaultStore::listGroups. More about kleidos::GroupEntry
struct kleidos::GroupSweepReport
What a group sweep did, whichever answer it went on to give. More about kleidos::GroupSweepReport
struct kleidos::CredentialExtras
Everything about a credential the login subset does not carry. More about kleidos::CredentialExtras
struct kleidos::CredentialDetail
What a credential's detail screen renders, and nothing more. More about kleidos::CredentialDetail
struct kleidos::vault::StoredUnlockShape
The unlock surface a vault's meta records: the PIN length and the kind of secret, as the raw persisted bytes. More about kleidos::vault::StoredUnlockShape
struct kleidos::vault::backup::RestoreTally
What a restore found in a backup and what of it this device took: the numbers every surface tells the owner when they differ. More about kleidos::vault::backup::RestoreTally

Typedefs

usingkleidos::vault::factory_reset_tag::TagBytes
The tag's bytes.
usingkleidos::CustomField
usingkleidos::PasswordHistoryEntry
One superseded password and when it was replaced (panel-only audit surface).

Enumerations

enum class kleidos::vault::factory_reset_tag::Reading : uint8_t { kleidos::vault::factory_reset_tag::Reading::Absent , kleidos::vault::factory_reset_tag::Reading::Present , kleidos::vault::factory_reset_tag::Reading::Unreadable }
What read found at offset 0 of the vault partition. More about kleidos::vault::factory_reset_tag::Reading
enum class kleidos::vault::secret_epoch::Reading : uint8_t { kleidos::vault::secret_epoch::Reading::Present , kleidos::vault::secret_epoch::Reading::Absent , kleidos::vault::secret_epoch::Reading::Unreadable }
What a read of the counter found. More about kleidos::vault::secret_epoch::Reading
enum class kleidos::vault::secret_epoch::Verdict : uint8_t { kleidos::vault::secret_epoch::Verdict::Current, kleidos::vault::secret_epoch::Verdict::Ahead, kleidos::vault::secret_epoch::Verdict::RolledBack, kleidos::vault::secret_epoch::Verdict::NoCounter, kleidos::vault::secret_epoch::Verdict::Unknown }
What a record's epoch is, against the counter. More about kleidos::vault::secret_epoch::Verdict
enum class kleidos::vault::LayoutVerdict : uint8_t { kleidos::vault::LayoutVerdict::Current , kleidos::vault::LayoutVerdict::Legacy , kleidos::vault::LayoutVerdict::Unknown }
What a look at the vault root says about the layout the vault was written in. More about kleidos::vault::LayoutVerdict
enum class kleidos::SlotWrite : uint8_t { kleidos::SlotWrite::Replace , kleidos::SlotWrite::Create }
What a caller means by writing to a slot it named. More about kleidos::SlotWrite
enum class kleidos::ListColumnResult : uint8_t { kleidos::ListColumnResult::Ok, kleidos::ListColumnResult::Stale, kleidos::ListColumnResult::Malformed, kleidos::ListColumnResult::Failed, kleidos::ListColumnResult::Damaged, kleidos::ListColumnResult::Exhausted }
How a list-column write (the star, the ranking) ended. More about kleidos::ListColumnResult
enum class kleidos::OrderWriteBudget : uint8_t { kleidos::OrderWriteBudget::Bounded , kleidos::OrderWriteBudget::Reseed }
What a ranking asks the vault to do with the labels. More about kleidos::OrderWriteBudget
enum class kleidos::ListColumnWrite : uint8_t { kleidos::ListColumnWrite::Keep , kleidos::ListColumnWrite::Set }
enum class kleidos::GroupSweepStage : uint8_t { kleidos::GroupSweepStage::NotStarted, kleidos::GroupSweepStage::Done, kleidos::GroupSweepStage::RecordsShort, kleidos::GroupSweepStage::LabelsKept, kleidos::GroupSweepStage::ColumnNotSwept }
enum class kleidos::PoolValue : uint8_t { kleidos::PoolValue::FieldValue , kleidos::PoolValue::RecoveryLine }
Which pool value VaultStore::loadCredentialPoolValue fetches. More about kleidos::PoolValue
enum class kleidos::vault::UnlockOutcome : uint8_t { kleidos::vault::UnlockOutcome::Unlocked, kleidos::vault::UnlockOutcome::WrongSecret, kleidos::vault::UnlockOutcome::LegacyLayout, kleidos::vault::UnlockOutcome::MetaUnreadable, kleidos::vault::UnlockOutcome::TamperDetected, kleidos::vault::UnlockOutcome::NotChecked, kleidos::vault::UnlockOutcome::BadArgument, kleidos::vault::UnlockOutcome::KeyfileUnavailable, kleidos::vault::UnlockOutcome::RolledBack }
What an unlock attempt established about the secret it was given. More about kleidos::vault::UnlockOutcome
enum class kleidos::vault::WipeOutcome : uint8_t { kleidos::vault::WipeOutcome::Erased , kleidos::vault::WipeOutcome::LogicalOnly , kleidos::vault::WipeOutcome::Incomplete , kleidos::vault::WipeOutcome::NotRun }
What a vault wipe established about the state it left behind. More about kleidos::vault::WipeOutcome
enum class kleidos::vault::EmptyOutcome : uint8_t { kleidos::vault::EmptyOutcome::Emptied, kleidos::vault::EmptyOutcome::ErasedSecretLost, kleidos::vault::EmptyOutcome::Incomplete, kleidos::vault::EmptyOutcome::WrongSecret, kleidos::vault::EmptyOutcome::NotEvaluated }
Verdict of VaultStore::emptyKeepingSecret, the vault-only wipe. More about kleidos::vault::EmptyOutcome
enum class kleidos::vault::backup::ImportStatus : uint8_t { kleidos::vault::backup::ImportStatus::Ok, kleidos::vault::backup::ImportStatus::Rejected, kleidos::vault::backup::ImportStatus::PartialWriteFailed, kleidos::vault::backup::ImportStatus::DoesNotFit, kleidos::vault::backup::ImportStatus::PartialEntriesRefused, kleidos::vault::backup::ImportStatus::ContentRefused, kleidos::vault::backup::ImportStatus::PartialLeftOut }
Outcome of a whole-vault restore. More about kleidos::vault::backup::ImportStatus
enum class kleidos::vault::backup::OverCapacity : uint8_t { kleidos::vault::backup::OverCapacity::Refuse , kleidos::vault::backup::OverCapacity::FillInOrder }
What a restore does with a backup that holds more than this device stores. More about kleidos::vault::backup::OverCapacity

Functions

TagByteskleidos::vault::factory_reset_tag::encode (const Tag &tag)
Encode tag.
std::optional< Tag >kleidos::vault::factory_reset_tag::decode (const TagBytes &bytes)
Decode bytes as a tag.
ReadResultkleidos::vault::factory_reset_tag::read ()
Read offset 0 of the vault partition and decode it.
boolkleidos::vault::factory_reset_tag::pendingOrUnknown ()
Whether a factory reset is pending, failing closed.
boolkleidos::vault::factory_reset_tag::write (const Tag &tag)
Write tag over the (blank) first bytes of the vault partition, and read it back.
boolkleidos::vault::factory_reset_tag::clear ()
Erase the tag's sector, and read the whole sector back erased.
constexpr FormatFailureVerdictkleidos::vault::formatFailureAfter (platform::littlefs::MountOutcome outcome, bool recorded)
The record and the report after a mount that ended in outcome.
constexpr Verdictkleidos::vault::secret_epoch::judge (uint32_t recordEpoch, const Counter &counter)
Judge a record's epoch against the counter.
constexpr boolkleidos::vault::secret_epoch::refuses (Verdict verdict)
Whether a verdict refuses the record.
constexpr uint32_tkleidos::vault::secret_epoch::next (uint32_t recordEpoch, const Counter &counter)
The epoch a new KEK half takes: one above the record it replaces and the counter.
Counterkleidos::vault::secret_epoch::read ()
Read the counter.
boolkleidos::vault::secret_epoch::raiseTo (uint32_t epoch)
Raise the counter to epoch, never lowering it, and read it back.
constexpr boolkleidos::vault::paths::literalEquals (const char *a, const char *b)
Are two NUL-terminated literals identical, at compile time?
template<size_t Capacity>
voidkleidos::vault::paths::credentialBasename (kleidos::util::str::InplaceString< Capacity > &out, uint16_t slot)
Build the canonical credential basename for slot.
template<size_t Capacity>
voidkleidos::vault::paths::totpBasename (kleidos::util::str::InplaceString< Capacity > &out, uint16_t slot)
Build the canonical one-time-code basename for slot.
template<size_t Capacity>
voidkleidos::vault::paths::indexSegmentBasename (kleidos::util::str::InplaceString< Capacity > &out, uint16_t segment)
Build the canonical list-index segment basename for segment.
template<size_t Capacity>
voidkleidos::vault::paths::join (kleidos::util::str::InplaceString< Capacity > &out, const char *dir, const char *name)
Join <dir>/<name> into out.
template<size_t Capacity>
voidkleidos::vault::paths::credentialPath (kleidos::util::str::InplaceString< Capacity > &out, uint16_t slot)
Build the canonical path of the credential in slot.
template<size_t Capacity>
voidkleidos::vault::paths::totpPath (kleidos::util::str::InplaceString< Capacity > &out, uint16_t slot)
Build the canonical path of the one-time code in slot.
template<size_t Capacity>
voidkleidos::vault::paths::recordLogBasename (kleidos::util::str::InplaceString< Capacity > &out, bool totp, uint16_t segment)
Build the basename of record-log segment segment.
template<size_t Capacity>
voidkleidos::vault::paths::recordLogPath (kleidos::util::str::InplaceString< Capacity > &out, bool totp, uint16_t segment)
Build the canonical path of record-log segment segment.
template<size_t Capacity>
voidkleidos::vault::paths::recordLogTempPath (kleidos::util::str::InplaceString< Capacity > &out, bool totp, uint16_t segment)
Build the compaction-twin path of record-log segment segment.
template<size_t Capacity>
voidkleidos::vault::paths::indexSegmentPath (kleidos::util::str::InplaceString< Capacity > &out, uint16_t segment)
Build the canonical path of list-index segment segment.
template<size_t Capacity>
voidkleidos::vault::paths::indexSegmentTempPath (kleidos::util::str::InplaceString< Capacity > &out, uint16_t segment)
Build the staging-twin path of list-index segment segment.
template<size_t Capacity>
voidkleidos::vault::paths::importStagePath (kleidos::util::str::InplaceString< Capacity > &out, const char *basename)
Build the SD-import staging path of basename.
const char *kleidos::vault::paths::directoryFor (const char *basename)
Directory a canonical basename belongs in.
template<size_t Capacity>
voidkleidos::vault::paths::canonicalPathFor (kleidos::util::str::InplaceString< Capacity > &out, const char *basename)
Build the canonical path a staged basename is promoted onto.
voidkleidos::vault::setTestTrustedEpochProvider (uint32_t(*provider)())
Native-test hook: inject the trusted-epoch source used for timestamps.
voidkleidos::vault::forgetFormatFailureRecordForTest ()
Native-test hook: forget the failed-format record this boot has read and the manual-recovery verdict, as a restart does.
constexpr boolkleidos::vault::countsAsFailedAttempt (UnlockOutcome outcome)
Whether a verdict is evidence of a wrong guess at the secret.
constexpr boolkleidos::vault::vaultIsGone (WipeOutcome outcome)
Whether a verdict entitles a surface to tell the owner the vault is gone.
constexpr boolkleidos::vault::emptyProvedSecret (EmptyOutcome outcome)
Whether the secret was proven by the vault-only wipe.
boolkleidos::vault::begin (kleidos::platform::rtos::Core core=kleidos::platform::rtos::Core::ProCpu, kleidos::platform::rtos::Priority priority=3)
Bring up the worker task. Safe to call multiple times: subsequent invocations are no-ops while the task is already running. The worker owns no shared state at construction; the queue and task handle are the only static resources.
voidkleidos::vault::shutdown ()
Stop the worker. Drains the queue first (with a bounded timeout), then signals the task to exit and joins it. Must be called before LittleFS unmount in the deep-sleep teardown sequence.
boolkleidos::vault::isRunning ()
True between begin() returning true and shutdown() returning. Used by the public VaultStore shim to decide whether to dispatch or run inline.
rtos::TaskHandlekleidos::vault::taskHandle ()
Returns the worker task handle, or nullptr when the task is not running. Exposed so the dispatcher can detect re-entrant calls from the worker itself and skip the queue.
uint32_tkleidos::vault::pendingRequests ()
Number of requests currently queued. A queue-depth probe for diagnostics surfaces (e.g. the serial debug console).
boolkleidos::vault::onWorker ()
True when (a) the worker is not running yet, or (b) the calling task IS the worker. In either case, public VaultStore shims must run their body inline rather than dispatching — otherwise the worker would deadlock on self-dispatch, and pre-begin() boot code would block forever.
template<typename Fn>
boolkleidos::vault::execute (Fn &&fn)
Run fn() on the vault worker thread and return its result. Fn must be callable as bool fn(). Capturing lambdas are allowed: the worker invokes them through a captureless trampoline, so all state in the closure stays on the caller's stack.

Variables

constexpr size_tkleidos::vault::factory_reset_tag::kTagBytes
Bytes the tag takes at offset 0 of the vault partition.
constexpr uint8_tkleidos::vault::factory_reset_tag::kTagVersion
The tag's layout version.
constexpr std::array< uint8_t, 16 >kleidos::vault::factory_reset_tag::kMagic
The tag's magic, NUL included.
constexpr size_tkleidos::vault::factory_reset_tag::kVersionOffset
Where the version byte sits.
constexpr size_tkleidos::vault::factory_reset_tag::kFloorOffset
Where the carried freshness floor sits.
constexpr size_tkleidos::vault::factory_reset_tag::kCrcOffset
Where the CRC sits; it covers every byte before it.
constexpr const char *kleidos::vault::secret_epoch::kNamespace
NVS namespace of the counter, apart from every preference.
constexpr const char *kleidos::vault::secret_epoch::kKey
NVS key of the counter.
constexpr size_tkleidos::vault::paths::kCanonicalPathCapacity
Capacity of a canonical-path buffer, excluding the NUL.
constexpr size_tkleidos::vault::paths::kStagedPathCapacity
Capacity of a staged-path buffer, excluding the NUL.
constexpr size_tkleidos::vault::paths::kBasenameCapacity
Capacity of a basename buffer, excluding the NUL.
constexpr const char *kleidos::vault::paths::kVaultDir
Root directory of the encrypted vault on LittleFS.
constexpr const char *kleidos::vault::paths::kCredentialDir
Directory of an older layout's credential files (cred_NN.bin), read only to detect that layout.
constexpr const char *kleidos::vault::paths::kTotpDir
Directory of an older layout's one-time-code files (totp_NN.bin), read only to detect that layout, as ::kCredentialDir is.
constexpr const char *kleidos::vault::paths::kIndexDir
Directory holding every idx_NN.bin list-index segment.
constexpr const char *kleidos::vault::paths::kRecordDir
Directory holding every record-log segment: rc_NN.bin for a fixed range of credential slots, rt_NN.bin for TOTP slots.
constexpr const char *kleidos::vault::paths::kImportStageDir
Staging tree the SD import copies an incoming vault into.
constexpr std::array< const char *, 5 >kleidos::vault::paths::kVaultDirectories
Every directory the canonical vault occupies, root first.
constexpr const char *kleidos::vault::paths::kSeparator
Path separator, so a joined path never spells one inline.
constexpr const char *kleidos::vault::paths::kMetaBasename
Basename of the vault metadata record — the root of trust.
constexpr const char *kleidos::vault::paths::kGroupBasename
Basename of the singleton group-label table.
constexpr const char *kleidos::vault::paths::kWifiBasename
Basename of the singleton saved-network store.
constexpr const char *kleidos::vault::paths::kMutStageBasename
Basename of the per-mutation record staging file.
constexpr const char *kleidos::vault::paths::kMutMarkerBasename
Basename of the per-mutation staging marker sidecar.
constexpr const char *kleidos::vault::paths::kImportCommitBasename
Basename of the SD-import commit marker.
constexpr const char *kleidos::vault::paths::kCredentialStem
Leading run of every credential basename.
constexpr const char *kleidos::vault::paths::kTotpStem
Leading run of every one-time-code basename.
constexpr const char *kleidos::vault::paths::kIndexStem
Leading run of every list-index segment basename.
constexpr const char *kleidos::vault::paths::kCredLogStem
Leading run of a credential-log segment basename.
constexpr const char *kleidos::vault::paths::kTotpLogStem
Leading run of a TOTP-log segment basename.
constexpr const char *kleidos::vault::paths::kRecordSuffix
Trailing run of every record basename.
constexpr const char *kleidos::vault::paths::kTempSuffix
Suffix of a file staged for an atomic rename onto its final name.
constexpr const char *kleidos::vault::paths::kSlotDigits
printf spelling of a slot id inside a basename.
constexpr const char *kleidos::vault::paths::kCredentialNameTemplate
printf template of a credential basename.
constexpr const char *kleidos::vault::paths::kTotpNameTemplate
printf template of a one-time-code basename.
constexpr const char *kleidos::vault::paths::kIndexNameTemplate
printf template of a list-index segment basename.
constexpr const char *kleidos::vault::paths::kCredLogNameTemplate
printf template of a credential-log segment basename.
constexpr const char *kleidos::vault::paths::kTotpLogNameTemplate
printf template of a TOTP-log segment basename.
constexpr const char *kleidos::vault::paths::kMetaPath
Canonical vault metadata path.
constexpr const char *kleidos::vault::paths::kMetaTempPath
Path the metadata is written to before its atomic rename into place.
constexpr const char *kleidos::vault::paths::kGroupPath
Canonical group-label table path.
constexpr const char *kleidos::vault::paths::kGroupTempPath
Path the group-label table is written to before its atomic rename.
constexpr const char *kleidos::vault::paths::kWifiPath
Canonical saved-network store path.
constexpr const char *kleidos::vault::paths::kWifiTempPath
Path the saved-network store is written to before its atomic rename.
constexpr const char *kleidos::vault::paths::kMutStagePath
Per-mutation record staging path.
constexpr const char *kleidos::vault::paths::kMutMarkerPath
Per-mutation staging marker path.
constexpr const char *kleidos::vault::paths::kImportCommitMarker
SD-import commit marker: present means roll FORWARD.
constexpr const char *kleidos::vault::paths::kImportCommitTemp
Temp name the import commit marker is written to before its rename.
constexpr const char *kleidos::vault::paths::kImportStageMetaPath
Staged metadata path inside the SD-import staging tree.

Back to the top

Typedef Documentation

CustomField #

using kleidos::CustomField

One typed custom field, as the pool stores it. The canonical type, not a mirror: there is one definition and the facade re-exports it.

Back to the top

Enumeration Type Documentation

EmptyOutcome #

enum class kleidos::vault::EmptyOutcome : uint8_t

Verdict of VaultStore::emptyKeepingSecret, the vault-only wipe.

Only WrongSecret weighed a secret and was wrong; only Emptied kept it.

Enumerator
Emptied 

The vault is empty, under the same secret and a new vault key.

ErasedSecretLost 

The partition is erased and blank, but the new record was not written.

Incomplete 

The erase did not empty the partition: no record was written.

WrongSecret 

The secret was weighed and refused; nothing was touched.

NotEvaluated 

No secret was weighed (unreadable meta, key file, backend): nothing touched.

GroupSweepStage #

enum class kleidos::GroupSweepStage : uint8_t

Which step of a group sweep answered, so a caller can say what is still true instead of attributing every failure to the sweep.

Enumerator
NotStarted 

Refused before a single record was read: a key rotation in progress, or session keys that would not derive. Nothing was swept and nothing dropped.

Done 

Members ungrouped, label(s) dropped, list column swept.

RecordsShort 

A slot would not resolve, read or rewrite. The label(s) are kept: freeing an id a record still carries hands those members to the next group created at it.

LabelsKept 

The sweep answered for every slot and the label write did not land. The members are ungrouped and the label(s) are still there.

ColumnNotSwept 

The label(s) are gone and the members are ungrouped; sweeping the list-index group column did not land. Every serving read drops a group id no label answers for, so the next listing shows them ungrouped anyway.

ImportStatus #

enum class kleidos::vault::backup::ImportStatus : uint8_t

Outcome of a whole-vault restore.

A restore fails in ways that mean opposite things to the vault owner, and a caller that collapses them into one boolean tells the user the wrong one. ImportStatus keeps them apart at the only boundary where they are still distinguishable:

  • ImportStatus::Rejected — every refusal fires BEFORE the first write, so the vault is byte-for-byte what it was. Nothing to recover from.
  • ImportStatus::DoesNotFit — the document's counts member says the backup holds more credentials or TOTP entries than this device has slots. Refused before the first write, like Rejected, but a different answer: the file is a good backup, of a bigger device. It is the question, not the end: the counts are in the restore's RestoreTally, and the owner who goes on restores again with OverCapacity::FillInOrder.
  • ImportStatus::ContentRefused — the document reached the restore and what it carries is not a backup this firmware reads: a version it does not know, a meta record no board writes, a malformed element. Refused before the first write, like Rejected, and a different answer for the reason DoesNotFit is one: a sealed backup can only reach this far once its envelope opened, so the passphrase was right, and a prompt that asks for it again reports a correct secret as a wrong one. Rejected keeps the refusals that say nothing about the document: an envelope that did not open, a document that never arrived whole, a vault that was locked or busy.

The two remaining answers both mean the vault was already being replaced and now holds a strict SUBSET of the backup: the previous contents are gone and the records that did not land are missing (visibly missing — never a pre-restore record masquerading as restored). The owner must be told the vault changed and that the backup file is still the good copy. What separates them is WHO failed, which is what decides whether restoring the same file again can do any better:

  • ImportStatus::PartialWriteFailed — this device could not write what the document legitimately carried: a record or a group label that did not commit, a stale table that would not drop, or a document that stopped arriving part-way. The file is fine; restoring it again on a device with room can complete it.
  • ImportStatus::PartialEntriesRefused — every write this device attempted landed, and what is missing are entries the document carries that fall outside the record grammar this device accepts: a one-time code whose secret, digit count or period this build does not read, a slot id that names no slot on any board (a record that sat beyond THIS board's slots on a bigger one is written to a free slot here), or a group id no label in the same document answers for. Nothing failed here, and restoring the same file again drops the same entries and reaches the same verdict, forever.
  • ImportStatus::PartialLeftOut — every write landed and the backup held more credentials or one-time codes than this device stores: the owner chose to go on (OverCapacity::FillInOrder), so the backup's entries were written in the backup's own order until each kind of slot was full, and the rest were left out. How many is in the restore's RestoreTally, which the owner is told: a loss the owner agreed to, never a silent one.

A restore that hits more than one answers the first of PartialWriteFailed, PartialEntriesRefused, PartialLeftOut: a device that failed to write is the most urgent fact, and it is the one for which a retry is worth the owner's time. The tally counts the entries left out whichever is answered.

Enumerator
Ok 

Envelope accepted and every record it carries is on flash.

Rejected 

Refused before the first write; the vault is untouched.

PartialWriteFailed 

Accepted, then a write this device attempted did not land (or the document stopped arriving); the vault is now a subset.

DoesNotFit 

The backup's counts exceed this device's slots; untouched.

PartialEntriesRefused 

Accepted and every write landed, but entries outside this device's record grammar were dropped; the vault is now a subset.

ContentRefused 

The document arrived and this firmware does not read what it carries; refused before the first write, the vault is untouched. Reached through a sealed backup only once its envelope opened: never a wrong passphrase.

PartialLeftOut 

Accepted and every write landed; the backup held more than this device stores, and the entries past its capacity were left out, in the backup's order, because the owner chose to go on (RestoreTally).

LayoutVerdict #

enum class kleidos::vault::LayoutVerdict : uint8_t

What a look at the vault root says about the layout the vault was written in.

Enumerator
Current 

No record file sits in the root; this build can read the vault.

Legacy 

A record file of an older layout: in the root, or under /vault/c or /vault/t.

Unknown 

The root would not list, so neither answer can be given.

ListColumnResult #

enum class kleidos::ListColumnResult : uint8_t

How a list-column write (the star, the ranking) ended.

A caller acting on a plain false has one response for every refusal, and the responses are opposite: a request the vault cannot apply to itself asks the caller to look at the vault again, while a vault that could not carry out a request it accepted asks for the same request once more. A remote caller cannot look at the vault at all, so the distinction has to reach it: the portal posts a ranking built from a list that a delete on the device may have moved under it, and answering that with a server error hides the one thing the user can act on.

Damaged is a fourth answer: the vault holds the row and the stored bytes were read and refused. Asking again reaches the same bytes, so it is neither a retry nor a re-read — it is the one refusal the owner has to hear about, because only re-saving that credential (which replaces the damaged bytes) or deleting it clears it.

Exhausted is a fifth: the request is valid and the vault could carry it out, but not inside the write cap a request path holds itself to. Nothing is written, and the answer carries what the plan would have cost so the caller can offer it as a maintenance action instead of hanging on it.

Enumerator
Ok 

The record carries what the caller asked for.

Stale 

The request names a credential this vault does not hold.

Malformed 

The request fits no vault: an id past capacity, or an id twice.

Failed 

The vault accepted the request and could not carry it out.

Damaged 

The credential is there and its stored bytes were refused.

Exhausted 

The plan needs more record writes than the request path allows.

ListColumnWrite #

enum class kleidos::ListColumnWrite : uint8_t

Whether a save writes one of the record's list columns or leaves it alone.

A save carries the WHOLE record, so an absent field cannot be distinguished from a cleared one by value. The device edit screens and the debug console never touch the star or the ranking, so the default has to be Keep: a two-state bool favorite would let every one of those saves clear a star.

Enumerator
Keep 

Leave the stored value exactly as it is.

Set 

Write the value carried alongside this marker.

OrderWriteBudget #

enum class kleidos::OrderWriteBudget : uint8_t

What a ranking asks the vault to do with the labels.

Enumerator
Bounded 

Realize the ranking with the FEWEST record writes, and at most kleidos::vault::kOrderRenumberMaxRows of them. A plan above that is refused with ListColumnResult::Exhausted and nothing is written: the write loop is one blocking worker call, so its worst case has to stay inside the timeout of whatever is waiting on it.

Reseed 

Re-space the ranking: every row onto the evenly spaced label of its position, however few writes the ranking itself would have needed, and with no cap on how many records that is. The maintenance action, run by a caller that has stated the time bound and waits for it. Lifting the cap alone would not do it — the plan that realizes an order the stored labels already carry is the empty plan, so the crowding that refused the move would survive the action offered to clear it.

OverCapacity #

enum class kleidos::vault::backup::OverCapacity : uint8_t

What a restore does with a backup that holds more than this device stores.

A backup is written by any board and restored on any other, and a board's only limit on what it takes is its own capacity: nothing else of the backup — its work factor, its meta, its slot ids — may stop an import. So a backup bigger than this device is never refused for good: the first answer (OverCapacity::Refuse) writes nothing and says how many the backup holds and how many fit, and the owner then chooses — the admin portal, where they pick which entries come over, or the device, which takes them in the backup's order.

Enumerator
Refuse 

Write nothing and answer ImportStatus::DoesNotFit with the counts (RestoreTally): the question the owner has to answer first.

FillInOrder 

The owner chose to go on: write the backup's entries in its own order until each kind of slot is full, leave the rest out and count them.

PoolValue #

enum class kleidos::PoolValue : uint8_t

Which pool value VaultStore::loadCredentialPoolValue fetches.

Enumerator
FieldValue 

The index-th custom field's value.

RecoveryLine 

The index-th line of the recovery-codes block.

Reading [1/2] #

enum class kleidos::vault::factory_reset_tag::Reading : uint8_t

What read found at offset 0 of the vault partition.

Enumerator
Absent 

No tag: erased flash, a file system, or a tag that did not finish.

Present 

A tag: a factory reset still has NVS to erase.

Unreadable 

The read failed: whether a reset is pending is unknown.

Reading [2/2] #

enum class kleidos::vault::secret_epoch::Reading : uint8_t

What a read of the counter found.

Enumerator
Present 

A value is stored.

Absent 

None is stored: a device that never held a vault, or NVS lost under one.

Unreadable 

The read failed: what is stored is unknown this moment.

SlotWrite #

enum class kleidos::SlotWrite : uint8_t

What a caller means by writing to a slot it named.

A save opens its destination truncating, so writing to an occupied slot replaces what is there. That is correct when the caller is editing a record it just read, and it is the loss of a live credential when the caller took the slot from VaultStore::findFreeSlot believing it empty. The two are indistinguishable at the write — the id looks the same either way — so the intent travels with the call.

The whole chain that produces a "free" slot is one predicate deep: a directory listing that could stop part-way, a mask bit, an id. Declaring SlotWrite::Create makes the write itself re-check the slot, so the record survives however that answer went wrong, including ways not yet found.

Enumerator
Replace 

The slot may hold a record; overwriting it is intended.

Create 

The slot is believed empty; refuse the write unless it is proven so.

UnlockOutcome #

enum class kleidos::vault::UnlockOutcome : uint8_t

What an unlock attempt established about the secret it was given.

VaultStore::unlockVault can fail for at least eight distinct reasons, and every caller feeds its failure branch to BruteForceGuard::registerFailure — which erases the whole vault at ten consecutive failures. A vault that could not be mounted, a meta.bin that could not be read, an allocation that failed inside the sub-key derivation and a MAC that did not verify are not guesses at the secret: counting them destroys the vault of an owner who typed the correct secret every time. The authority to destroy is a byte in NVS that outlives the boot the predicate ran in, so nothing downstream can recover a distinction thrown away here.

Only UnlockOutcome::WrongSecret is evidence about the secret. Route every verdict through countsAsFailedAttempt rather than counting every outcome but UnlockOutcome::Unlocked, which counts all eight.

Enumerator
Unlocked 

The secret was checked and matched; keyOut holds the vault key.

WrongSecret 

The secret was checked and did not match. THE ONLY countable failure.

LegacyLayout 

An older layout (flat, or one file per record): no secret opens this vault, so none was tried.

MetaUnreadable 

meta.bin absent, wrong size, short read, or malformed.

TamperDetected 

The secret matched but meta.bin failed its MAC — fail closed, do not count.

NotChecked 

A step could not run (unmounted vault, backend, allocation, binding).

BadArgument 

Caller passed no secret or no output buffer — a bug, never an attempt.

KeyfileUnavailable 

The record declares a key-file second factor the card did not give up, so the derivation input could not be assembled and NOTHING was derived. An unseated card is not a wrong secret; surfaces should say "seat the key file", never "wrong secret".

RolledBack 

The record's secret epoch is below the NVS counter, or no counter stands beside it: meta.bin is one a rollback brought back (an undone LittleFS commit, a written-back partition), refused before any secret is weighed. Not an attempt, so never counted (vault/secret_epoch.h).

Verdict #

enum class kleidos::vault::secret_epoch::Verdict : uint8_t

What a record's epoch is, against the counter.

Enumerator
Current 

Equal: the record the counter last followed.

Ahead 

Above: a change whose counter raise a cut stopped; the record stands.

RolledBack 

Below: an older record than the counter has seen. Refused.

NoCounter 

No counter beside a record: NVS lost or garbled under the vault. Refused.

Unknown 

The counter could not be read: nothing is decided on it.

WipeOutcome #

enum class kleidos::vault::WipeOutcome : uint8_t

What a vault wipe established about the state it left behind.

VaultStore::wipeAll runs beneath both wipes, the factory reset the 10th consecutive failure starts and the vault-only wipe: the owner is shown "wiped", an audit event is recorded and the device restarts. Every one of those is a report that the credentials, the KDF salt and the secret verifier are gone. A void cannot carry that report, so this verdict tells a wipe from a wipe that never ran.

The three verdicts are decided by different evidence. Erased means the whole-partition erase landed, which is the only step that removes bytes from flash on a copy-on-write filesystem. LogicalOnly means it did not, but every traversal that had to empty a directory finished and reported it empty. The residue that leaves is precise and worth stating exactly: the unlinks are logical, so LittleFS keeps the old blocks until they are reused — the record ciphertext, the KDF salt and the secret verifier are all still in freed blocks. On the open builds they are recoverable from a raw flash dump. On the hardened build, whose table flags the vault for Flash Encryption, the dump holds them as ciphertext under the chip's key and the KEK is bound to the chip, so the residue cannot open away from it. Incomplete means neither: a directory could not be listed or would not empty, so named files may still be sitting there under their own names.

Enumerator
Erased 

The partition erase landed; nothing survives on any build.

LogicalOnly 

Every logical step finished, the partition erase did not.

Incomplete 

A logical step could not finish AND the partition erase did not land.

NotRun 

The wipe body never executed; the vault is untouched.

Back to the top

Function Documentation

begin() #

Bring up the worker task. Safe to call multiple times: subsequent invocations are no-ops while the task is already running. The worker owns no shared state at construction; the queue and task handle are the only static resources.

Parameters
NameMeaning
coreTarget core. Defaults to PRO_CPU, the services core.
priorityApplication priority. Defaults to 3: above the services at 2 (the debug logger, name store, speaker, NTP sync) and below the TOTP worker and the BLE stack task (4). The unlock's crypto runs on this worker itself.
Return values
ValueMeaning
trueWorker spawned (or already running; idempotent).
falseQueue or task could not be created (typically OOM).

canonicalPathFor() #

template<size_t Capacity>
void kleidos::vault::paths::canonicalPathFor(kleidos::util::str::InplaceString< Capacity > & out, const char * basename)

Build the canonical path a staged basename is promoted onto.

Template Parameters
NameMeaning
CapacityCapacity of out.
Parameters
NameDirectionMeaning
outoutReceives the path.
basenameinCanonical basename.

clear() #

bool kleidos::vault::factory_reset_tag::clear()
inlinenodiscard

Erase the tag's sector, and read the whole sector back erased.

Return values
ValueMeaning
trueThe first sector was erased and every byte of it reads 0xFF.
falseThe erase failed, or a byte did not read back erased.

countsAsFailedAttempt() #

bool kleidos::vault::countsAsFailedAttempt(UnlockOutcome outcome)
constexpr

Whether a verdict is evidence of a wrong guess at the secret.

The single definition of what may escalate the brute-force counter. Every other verdict describes something that happened to the device, not something the user typed: the derivation either never ran or ran and matched, so the attempt taught an attacker nothing and must cost nothing.

Parameters
NameDirectionMeaning
outcomeinThe verdict from VaultStore::unlockVault.
Return values
ValueMeaning
trueUnlockOutcome::WrongSecret — count it.
falseEverything else — leave the counter where it was.

credentialBasename() #

template<size_t Capacity>
void kleidos::vault::paths::credentialBasename(kleidos::util::str::InplaceString< Capacity > & out, uint16_t slot)

Build the canonical credential basename for slot.

Template Parameters
NameMeaning
CapacityCapacity of out.
Parameters
NameDirectionMeaning
outoutReceives cred_NN.bin.
slotinCredential slot id.

credentialPath() #

template<size_t Capacity>
void kleidos::vault::paths::credentialPath(kleidos::util::str::InplaceString< Capacity > & out, uint16_t slot)

Build the canonical path of the credential in slot.

Template Parameters
NameMeaning
CapacityCapacity of out.
Parameters
NameDirectionMeaning
outoutReceives the path.
slotinCredential slot id.

decode() #

std::optional< Tag > kleidos::vault::factory_reset_tag::decode(const TagBytes & bytes)
inlinenodiscard

Decode bytes as a tag.

Parameters
NameDirectionMeaning
bytesin32 bytes read raw from offset 0 of the vault partition.
Returns
The tag, or nothing when the magic, the version, a reserved byte or the CRC does not match: erased flash, a file system or a half-written tag.

directoryFor() #

const char * kleidos::vault::paths::directoryFor(const char * basename)
inline

Directory a canonical basename belongs in.

The promote step of an import copies a staged file onto its canonical path, and it knows only the basename. Classification is by stem alone — no capacity, no record geometry — so this stays the one place that answers "where does a file with this name live", for the writer and the promoter alike.

Parameters
NameMeaning
basenameCanonical basename (no directory component).
Returns
The directory the file belongs in; ::kVaultDir for the singletons and for anything the record stems do not match.

emptyProvedSecret() #

bool kleidos::vault::emptyProvedSecret(EmptyOutcome outcome)
constexpr

Whether the secret was proven by the vault-only wipe.

Parameters
NameDirectionMeaning
outcomeinIts verdict.
Returns
true for every verdict that went past the authentication.

encode() #

TagBytes kleidos::vault::factory_reset_tag::encode(const Tag & tag)
inlinenodiscard

Encode tag.

Parameters
NameDirectionMeaning
taginWhat to carry.
Returns
Its 32 bytes.

execute() #

template<typename Fn>
bool kleidos::vault::execute(Fn && fn)
inline

Run fn() on the vault worker thread and return its result. Fn must be callable as bool fn(). Capturing lambdas are allowed: the worker invokes them through a captureless trampoline, so all state in the closure stays on the caller's stack.

Fast paths:

  • Worker not running yet → run inline on caller's thread.
  • Caller already on worker → run inline (re-entrancy).

A host build has no FreeRTOS worker and always runs fn inline.

Template Parameters
NameMeaning
FnCallable as bool fn(); capturing lambdas are allowed.
Parameters
NameDirectionMeaning
fninWork to run on the worker.
Returns
What fn returned, or false when the completion semaphore could not be created or the dispatch failed and fn did not run.

forgetFormatFailureRecordForTest() #

void kleidos::vault::forgetFormatFailureRecordForTest()

Native-test hook: forget the failed-format record this boot has read and the manual-recovery verdict, as a restart does.

On device the facade reads the record from NVS once a boot and keeps it in RAM (VaultStore::formatFailed). The host suites reset the fake NVS between cases (the shared amalgam runs this from that reset), so the next mount reads the record again instead of trusting what an earlier case left in RAM.

formatFailureAfter() #

FormatFailureVerdict kleidos::vault::formatFailureAfter(platform::littlefs::MountOutcome outcome, bool recorded)
nodiscardconstexpr

The record and the report after a mount that ended in outcome.

Parameters
NameDirectionMeaning
outcomeinHow the mount ended.
recordedinThe record as the mount found it.
Returns
The record to keep, and whether the refusal is a failed format.

importStagePath() #

template<size_t Capacity>
void kleidos::vault::paths::importStagePath(kleidos::util::str::InplaceString< Capacity > & out, const char * basename)

Build the SD-import staging path of basename.

Template Parameters
NameMeaning
CapacityCapacity of out.
Parameters
NameDirectionMeaning
outoutReceives the path.
basenameinCanonical basename to stage.

indexSegmentBasename() #

template<size_t Capacity>
void kleidos::vault::paths::indexSegmentBasename(kleidos::util::str::InplaceString< Capacity > & out, uint16_t segment)

Build the canonical list-index segment basename for segment.

Template Parameters
NameMeaning
CapacityCapacity of out.
Parameters
NameDirectionMeaning
outoutReceives idx_NN.bin.
segmentinIndex segment number.

indexSegmentPath() #

template<size_t Capacity>
void kleidos::vault::paths::indexSegmentPath(kleidos::util::str::InplaceString< Capacity > & out, uint16_t segment)

Build the canonical path of list-index segment segment.

Template Parameters
NameMeaning
CapacityCapacity of out.
Parameters
NameDirectionMeaning
outoutReceives the path.
segmentinIndex segment number.

indexSegmentTempPath() #

template<size_t Capacity>
void kleidos::vault::paths::indexSegmentTempPath(kleidos::util::str::InplaceString< Capacity > & out, uint16_t segment)

Build the staging-twin path of list-index segment segment.

A segment is written here and moved onto its canonical path with an atomic rename, so a reset during a write leaves the previous segment rather than a hole.

Template Parameters
NameMeaning
CapacityCapacity of out.
Parameters
NameDirectionMeaning
outoutReceives the path.
segmentinIndex segment number.

isRunning() #

bool kleidos::vault::isRunning()

True between begin() returning true and shutdown() returning. Used by the public VaultStore shim to decide whether to dispatch or run inline.

Return values
ValueMeaning
trueThe worker is running.
falseIt was never started, or has been shut down.

join() #

template<size_t Capacity>
void kleidos::vault::paths::join(kleidos::util::str::InplaceString< Capacity > & out, const char * dir, const char * name)

Join <dir>/<name> into out.

Template Parameters
NameMeaning
CapacityCapacity of out.
Parameters
NameDirectionMeaning
outoutReceives the joined path.
dirinDirectory, without a trailing separator.
nameinBasename.

judge() #

Verdict kleidos::vault::secret_epoch::judge(uint32_t recordEpoch, const Counter & counter)
nodiscardconstexpr

Judge a record's epoch against the counter.

Parameters
NameDirectionMeaning
recordEpochinThe epoch the record carries.
counterinThe counter as read.
Returns
The verdict.

literalEquals() #

bool kleidos::vault::paths::literalEquals(const char * a, const char * b)
constexpr

Are two NUL-terminated literals identical, at compile time?

Parameters
NameMeaning
aFirst literal.
bSecond literal.
Return values
ValueMeaning
trueSame characters and same length.
falseThey differ.

next() #

uint32_t kleidos::vault::secret_epoch::next(uint32_t recordEpoch, const Counter & counter)
nodiscardconstexpr

The epoch a new KEK half takes: one above the record it replaces and the counter.

It saturates at the top of the range, which no owner reaches (one per change of secret or vault key); an absent or unreadable counter counts as 0, the caller having refused an unreadable one before it gets here.

Parameters
NameDirectionMeaning
recordEpochinThe epoch of the record being replaced (0 when there is none).
counterinThe counter as read.
Returns
The new epoch.

onWorker() #

bool kleidos::vault::onWorker()
inline

True when (a) the worker is not running yet, or (b) the calling task IS the worker. In either case, public VaultStore shims must run their body inline rather than dispatching — otherwise the worker would deadlock on self-dispatch, and pre-begin() boot code would block forever.

Public VaultStore methods use this as a one-line guard:

bool VaultStore::saveCredential(args) {
    if (!kleidos::vault::onWorker()) {
        return kleidos::vault::execute(
            [&](){ return saveCredential(args); });
    }
    // ... original body ...
}
Return values
ValueMeaning
trueRun the body inline (always, on a host build: no worker thread exists there).
falseDispatch it to the worker.

pendingOrUnknown() #

bool kleidos::vault::factory_reset_tag::pendingOrUnknown()
inlinenodiscard

Whether a factory reset is pending, failing closed.

Return values
ValueMeaning
trueA tag is present, or the read failed: no vault may be minted.
falseNo tag.

pendingRequests() #

uint32_t kleidos::vault::pendingRequests()

Number of requests currently queued. A queue-depth probe for diagnostics surfaces (e.g. the serial debug console).

Returns
Number of pending dispatch requests.

raiseTo() #

bool kleidos::vault::secret_epoch::raiseTo(uint32_t epoch)
inlinenodiscard

Raise the counter to epoch, never lowering it, and read it back.

A counter already at or above epoch is left as it is. The value is read back after the write, so true means NVS holds at least epoch.

Parameters
NameDirectionMeaning
epochinThe epoch the record on flash now carries.
Return values
ValueMeaning
trueThe counter reads epoch or more.
falseIt could not be read or written; the caller decides what that costs.

read() [1/2] #

ReadResult kleidos::vault::factory_reset_tag::read()
inlinenodiscard

Read offset 0 of the vault partition and decode it.

Returns
What was there.

read() [2/2] #

Counter kleidos::vault::secret_epoch::read()
inlinenodiscard

Read the counter.

Returns
What is stored, or why nothing could be said.

recordLogBasename() #

template<size_t Capacity>
void kleidos::vault::paths::recordLogBasename(kleidos::util::str::InplaceString< Capacity > & out, bool totp, uint16_t segment)

Build the basename of record-log segment segment.

Template Parameters
NameMeaning
CapacityCapacity of out.
Parameters
NameDirectionMeaning
outoutReceives rc_NN.bin or rt_NN.bin.
totpinWhether the segment holds TOTP slots.
segmentinLog segment number within its class.

recordLogPath() #

template<size_t Capacity>
void kleidos::vault::paths::recordLogPath(kleidos::util::str::InplaceString< Capacity > & out, bool totp, uint16_t segment)

Build the canonical path of record-log segment segment.

Template Parameters
NameMeaning
CapacityCapacity of out.
Parameters
NameDirectionMeaning
outoutReceives the path.
totpinWhether the segment holds TOTP slots.
segmentinLog segment number within its class.

recordLogTempPath() #

template<size_t Capacity>
void kleidos::vault::paths::recordLogTempPath(kleidos::util::str::InplaceString< Capacity > & out, bool totp, uint16_t segment)

Build the compaction-twin path of record-log segment segment.

The live entries are copied here and the file is renamed over the segment in one step, so an interruption leaves either the segment intact (the rename has not happened) or the copy complete (it has).

Template Parameters
NameMeaning
CapacityCapacity of out.
Parameters
NameDirectionMeaning
outoutReceives the path with ::kTempSuffix appended.
totpinWhether the segment holds TOTP slots.
segmentinLog segment number within its class.

refuses() #

bool kleidos::vault::secret_epoch::refuses(Verdict verdict)
nodiscardconstexpr

Whether a verdict refuses the record.

Parameters
NameDirectionMeaning
verdictinWhat judge said.
Return values
ValueMeaning
trueRolledBack or NoCounter: the record may not open.
falseEvery other verdict.

setTestTrustedEpochProvider() #

void kleidos::vault::setTestTrustedEpochProvider(uint32_t(* provider )())

Native-test hook: inject the trusted-epoch source used for timestamps.

On device, VaultStore::saveCredential stamps ctime / mtime from the trust-gated wall clock (see time/wall_clock_epoch.h). The host build has no RTC, so the facade reads this provider instead — mirroring the platform/base/clock.h test-provider pattern. A null provider (the default) reads as epoch 0, i.e. "clock not trusted".

Parameters
NameDirectionMeaning
providerinFunction returning the current Unix epoch seconds, or null to restore the untrusted-clock default.

taskHandle() #

kleidos::platform::rtos::TaskHandle kleidos::vault::taskHandle()

Returns the worker task handle, or nullptr when the task is not running. Exposed so the dispatcher can detect re-entrant calls from the worker itself and skip the queue.

Returns
The worker task handle, or nullptr when not running.

totpBasename() #

template<size_t Capacity>
void kleidos::vault::paths::totpBasename(kleidos::util::str::InplaceString< Capacity > & out, uint16_t slot)

Build the canonical one-time-code basename for slot.

Template Parameters
NameMeaning
CapacityCapacity of out.
Parameters
NameDirectionMeaning
outoutReceives totp_NN.bin.
slotinOne-time-code slot id.

totpPath() #

template<size_t Capacity>
void kleidos::vault::paths::totpPath(kleidos::util::str::InplaceString< Capacity > & out, uint16_t slot)

Build the canonical path of the one-time code in slot.

Template Parameters
NameMeaning
CapacityCapacity of out.
Parameters
NameDirectionMeaning
outoutReceives the path.
slotinOne-time-code slot id.

vaultIsGone() #

bool kleidos::vault::vaultIsGone(WipeOutcome outcome)
constexpr

Whether a verdict entitles a surface to tell the owner the vault is gone.

The single definition of what "wiped" means to a toast, a countdown screen, a console line or an audit trail. WipeOutcome::LogicalOnly counts: every file the vault is reachable through is unlinked and the device reboots into onboarding. WipeOutcome::Incomplete and WipeOutcome::NotRun do not — under those, records are still on the filesystem under their own names.

Parameters
NameDirectionMeaning
outcomeinThe verdict from VaultStore::wipeAll.
Return values
ValueMeaning
trueSay the vault was wiped.
falseSay it was not; do not record a completed wipe.

write() #

bool kleidos::vault::factory_reset_tag::write(const Tag & tag)
inlinenodiscard

Write tag over the (blank) first bytes of the vault partition, and read it back.

The caller has proven the partition blank first: NOR flash only clears bits, so a tag written over anything else does not read back.

Parameters
NameDirectionMeaning
taginWhat to carry.
Return values
ValueMeaning
trueThe tag reads back as written.
falseThe write failed or did not read back.

Back to the top

Variable Documentation

kBasenameCapacity #

size_t kleidos::vault::paths::kBasenameCapacity
inlineconstexpr

Capacity of a basename buffer, excluding the NUL.

The longest basename is "mut_stage.mark" (14 characters).

kCanonicalPathCapacity #

size_t kleidos::vault::paths::kCanonicalPathCapacity
inlineconstexpr

Capacity of a canonical-path buffer, excluding the NUL.

The longest canonical path is the index staging twin, "/vault/i/idx_999.bin.tmp" (24 characters). The margin absorbs a deeper per-class directory without a sweep of every buffer declaration.

kCredentialDir #

const char* kleidos::vault::paths::kCredentialDir
inlineconstexpr

Directory of an older layout's credential files (cred_NN.bin), read only to detect that layout.

This firmware creates it empty with the others and writes no file in it. VaultLayout::inspect lists it, and a record file found in it reports the vault as one this firmware cannot read rather than as empty.

kRecordDir #

const char* kleidos::vault::paths::kRecordDir
inlineconstexpr

Directory holding every record-log segment: rc_NN.bin for a fixed range of credential slots, rt_NN.bin for TOTP slots.

The records live one directory down from ::kVaultDir, and share a file per slot range rather than one file each, because a LittleFS name lookup and a directory listing both cost in proportion to what the directory holds (on an ESP32, a listing grows by about 4 ms a file); and they share SEVERAL files rather than one, because a compaction copies the file it rewrites and the peak that copy adds is what bounds a board's capacity. One segment is the unit of that copy.

kSlotDigits #

const char* kleidos::vault::paths::kSlotDigits
inlineconstexpr

printf spelling of a slot id inside a basename.

A MINIMUM width, so a slot spells two digits below 100 and three from 100 on. The grammar is canonical — digits to slot is injective — because a zero-padded three-digit twin would let one slot be spelled two ways and a promote would then write a file nothing ever opens.

kStagedPathCapacity #

size_t kleidos::vault::paths::kStagedPathCapacity
inlineconstexpr

Capacity of a staged-path buffer, excluding the NUL.

The longest staged path is "/vault/import_new/cred_999.bin" (30 characters).

kVaultDirectories #

std::array<const char*, 5> kleidos::vault::paths::kVaultDirectories
inlineconstexpr

Every directory the canonical vault occupies, root first.

One list, so that everything which has to touch the WHOLE tree walks the same set: creating the layout before the first record is written, sweeping it on a wipe, and the SD export's traversal. A class directory added here reaches all three without a second enumeration to keep in step.

Back to the top