Expand description
§keyhog-core
Shared domain types for the KeyHog secret scanner: the detector spec model, the embedded detector corpus, chunk and finding types, redaction, and the report-safe boundary every other crate projects through.
Part of the KeyHog secret scanner.
use keyhog_core::{detector_spec_by_id, embedded_detector_count, redact};
// The compiled-in corpus. Every crate borrows this one materialized copy.
let count = embedded_detector_count();
assert!(count > 0);
// Detectors are addressable by their stable id. `aws-access-key` is in the
// shipped corpus, so this resolving is itself a check that the corpus loaded.
let spec = detector_spec_by_id("aws-access-key").expect("shipped detector");
assert_eq!(spec.id, "aws-access-key");
// Anything derived from scanned bytes is redacted before it can be printed.
// The control comes first: prove the needle is visible in the input, so a
// probe that can see nothing at all cannot pass this as a clean redaction.
let plaintext = "AKIAIOSFODNN7EXAMPLE";
assert!(plaintext.contains("IOSFODNN7"));
let safe = redact(plaintext);
assert!(!safe.contains("IOSFODNN7"));§Public entry points
load_embedded_detectors_or_failparses the compiled-in corpus and returns a typed error naming every detector that failed. It never returns a partial set.embedded_detector_specsis the one materialized corpus. Borrow from it rather than re-parsing, anddetector_spec_by_idindexes it.embedded_detector_count,detector_digest, andgit_hashidentify exactly which corpus and build you are running. Benchmarks and caches key on these.CredentialandSensitiveStringhold plaintext.redactand the report types inreportare the projection you use before anything leaves the process.specowns detector validation. A detector that does not validate is a build or authoring error, never a scan-time condition.
§Failure behavior
A corrupt compiled-in corpus stops startup with the exact parse error. The crate does not substitute an empty or reduced detector set, because a scanner that silently loads fewer detectors reports a clean result on a file that has a secret in it.
§Features
The default build has no optional features and no native build prerequisite.
The detector corpus is compiled in by build.rs from the workspace detectors/
directory, so the crate needs no data files at runtime.
§Documentation
- Detectors describes the spec schema these types model.
- Architecture describes where this crate sits and which direction dependencies run.
- API documentation is on docs.rs. Core types shared across all KeyHog crates.
Re-exports§
pub use crate::ascii_ci::contains_bytes_ignore_ascii_case;pub use crate::ascii_ci::contains_ignore_ascii_case;pub use crate::ascii_ci::ends_with_ignore_ascii_case;pub use crate::ascii_ci::starts_with_ignore_ascii_case;
Modules§
- ascii_
ci - Shared ASCII case-insensitive primitives:
starts_with/ends_with_ignore_ascii_caseand theci_findbyte-substring search. Single owner (ONE PLACE) for allocation-free case-folded comparisons on the scanner and verifier hot paths, callers use these instead of allocating a lowercased copy of each candidate. - git_lfs
- Git-LFS pointer recognition, shared by the scanner (oid suppression) and sources (unscanned-blob coverage gap). Git-LFS pointer recognition.
- guard_
state - Perpetual guard root state machine, policy identity, and receipt types. Perpetual guard root state machine, policy identity, and receipt types.
- guard_
store - Durable guard state store: schema, tables, and memory-bounded LRU. Durable guard state store: schema, tables, and memory-bounded LRU.
- json_
selector - Detector verification response selector grammar and evaluator. Bounded rooted selectors for detector-owned verification responses.
- retry
- The one retry policy: bounded attempts, one backoff, one classification of transient versus permanent. Retry is the second choice; see the module docs for what must never be routed through it. The one retry policy: bounded attempts, one backoff, one classification.
- timing
- Shared paired performance statistics used by release gates and routing evidence. Shared statistical evidence for paired performance comparisons.
- verification_
domain - Verification-domain policy shared by detector validation and the network verifier. Shared verification-domain policy.
- winpath
- Canonical Windows-path classification predicates.
Structs§
- Access
Target - One resource a credential is believed to open.
- Access
Target Coverage - What the pass actually managed to look at.
- Access
Target Report - The complete result of one association pass.
- Allowlist
- User-defined suppressions loaded from
.keyhogignore: credential hashes, detector IDs, and path globs. - Beta
Counters - A detector’s running Beta posterior counters. Always ≥1 each (Beta(1,1) uniform prior baseline) to avoid posterior_mean undefined when a detector has had no observations yet.
- Calibration
- Process-wide calibration store. Concurrent updates are serialized via
a single
RwLockbecause update events are rare (one perkeyhog calibrateinvocation or per verifier outcome) and the locked region is constant-time. We deliberately don’t shard via DashMap - the persisted artifact is small enough that contention is a non-issue. - Canonical
HexKey Material Spec - One detector-local pure-hex key-material policy.
- Chunk
- A scannable chunk of text with metadata about where it came from.
- Chunk
Metadata - Metadata that tracks the source location for a scanned chunk.
- Companion
Spec - Secondary pattern used to confirm a primary match or provide extra context.
- Confidence
Provenance - Exactly how a target’s confidence was produced.
- Correlated
Credential - A credential risk assembled from several findings.
- Correlated
Location - One place a correlated credential was seen.
- Correlated
Member - One finding participating in a correlation group.
- Coverage
Gap - One reason some findings had no file context, and how many were affected.
- Credential
- Opaque credential bytes. The inner
Arc<Zeroizing<Box<[u8]>>>clones are cheap (refcount bump) but every owningCredentialzeroizes on drop.Arclets the engine intern identical credentials without copying; when the last ref drops,Zeroizing<Box<[u8]>>overwrites the heap allocation beforeBox::dropreturns it to the allocator. - Credential
Hash - SHA-256 digest of a credential.
- Credential
Shape - Per-detector credential SHAPE constraint (
[detector.credential_shape]), OWNED HERE per the architecture law (was a centralizedrules/detector-credential-shapes.toml[[shape]]list keyed by detector id, a per-detector property in a second file). A candidate whose byte length / prefix / post-prefix body length does not fit the declared shape is suppressed by the scanner’s shape gate (CredentialShapeRule::allows). Only a couple of fixed-format vendor detectors declare it:aws-access-keyis exactly 20 bytes;anthropic-api-keyissk-ant-api03-+ an 80..=120 body. - Deduped
Match - A group of related raw matches representing a single distinct secret finding.
- Detector
Corpus Manifest - Directory-scoped compatibility contract for detector TOML files.
- Detector
Decode Transform Spec - Literal admission prefixes for detector-owned evasion recovery.
- Detector
File - Wrapping struct for a detector TOML file.
- Detector
Introspection - Redaction-safe serialized view of one detector declaration.
- Detector
Match Confidence Spec - Complete detector-local confidence policy for regex candidates.
- Detector
MlPolicy Spec - Complete detector-local configuration for the shared ML scoring engine.
- Detector
Plausibility Policy Spec - Strict candidate-plausibility policy owned by one detector TOML.
- Detector
Post Match Confidence Spec - Detector-local confidence penalties applied after optional model scoring.
- Detector
Relation Spec - A bounded relationship between findings from two detector owners.
- Detector
Spec - A complete detector definition loaded from a TOML file.
- Detector
Test Spec - One inline detector self-test fixture (
[[detector.tests]]). - Entropy
Fallback Confidence Spec - Confidence mapping for one detector’s synthetic entropy findings.
- Entropy
Fallback Metadata - Detector-owned identity for a finding emitted by the entropy fallback path.
- Entropy
Floor Bucket - One length bucket of a detector’s
DetectorSpec::entropy_floor. Owned in the detector’s TOML (entropy_floor = [{ max_len = 24, floor = 3.0 }, { floor = 3.5 }]). - Entropy
Shape Spec - A declarative structural shape that may cross a detector’s broad isolated entropy floor. Every field is detector TOML data and the scanner keeps one general matcher, so a new shape family (base64, hex block) is added by a detector TOML rather than a scanner enum variant.
- File
Content - One file’s content prefix, plus whether it was cut short.
- Filesystem
Content - Reads from the local filesystem.
- Generic
Assignment Confidence Spec - Confidence mapping for a detector-owned generic assignment candidate.
- Hardening
Report - Outcome of a hardening attempt - collected so callers can log which protections actually took.
- Header
Spec - Custom HTTP header specification.
- Json
Report Coverage Gap - One scan-wide coverage gap preserved in a versioned JSON report.
- Json
Report Envelope - Versioned machine-readable JSON report.
- Json
Report Schema Version - Version marker carried by every versioned JSON report.
- Jsonl
Stream - One validated segment of a JSONL input. Concatenated streams produce one segment per header, so boundaries remain explicit instead of being inferred from finding content.
- Jsonl
Stream Header - Header written as the first record of a versioned JSONL stream.
- Jsonl
Stream Summary - Terminal record written when a versioned JSONL stream completes.
- Loaded
Detector Corpus - A validated detector corpus paired with the schema identity that selected its normalization rules.
- Match
Location - Where a credential was found: file path, line number, commit, and author.
- Merkle
Index - In-memory file-hash index loaded from / saved to a JSON cache file.
- Merkle
Load Report - Result of loading a persisted
MerkleIndexcache. - Metadata
Spec - Metadata field specification for verification results.
- Observed
Paths - A Vec-compatible path list that records direct mutable access.
- OobSpec
- Out-of-band callback verification configuration.
- Pattern
Spec - A regex pattern with optional capture group and description.
- RawMatch
- A raw pattern match before verification or deduplication.
- RawMatch
Dedup Key - Borrowed raw-match identity used before report-scope deduplication.
- Redacted
Finding - Redacted, disk-safe view of a
RawMatch. Carries only the SHA-256 hash and a “first4…last4” preview, never the plaintext credential. Use this before verification;VerifiedFindingis the final report-safe shape. - Report
Error - Common error type used by all reporters.
The
Errortype, a wrapper around a dynamic error type. - Resolved
Scan Manifest - Stable, machine-diffable description of the resolved detection mode.
- Rule
Suppressor - Parsed
.keyhogignore.toml- a list of[[suppress]]rules, each compiled into aRuleFormula. - Scan
Backend Recovery Summary - Bounded, non-secret summary of one completed exact recovery.
- Scan
Config - Configuration for a scan run.
- Scan
Report - The format-neutral input shared by every report renderer.
- Scan
Report Metadata - Format-neutral operator-visible metadata for a scan report.
- Sensitive
String - A heap-allocated string that is zeroized on drop.
- Shape
Grouping - Fixed-width separator grouping, e.g. a Bluesky app password’s four dash-separated groups of four. Absent means an ungrouped run.
- Source
Admission Spec - Positive source selectors for detector families valid only in known locations.
- State
File Write Lock - Exclusive advisory lock held across a state file’s read/merge/write cycle.
- Static
Recovery Metrics - Exact, non-secret bounded static-recovery telemetry for one scan.
- Step
Spec - A single step in a multi-step verification flow.
- Success
Spec - Criteria for a successful verification response.
- Target
Evidence - Why one target is attributed to one credential.
- Targeted
Location - Where a credential with access targets was found.
- Verified
Finding - A finding after verification - the final output.
- Verify
Spec - Live verification configuration for a detector.
Enums§
- Access
Target Kind - What kind of thing a credential opens.
- Auth
Spec - Authentication scheme for verification requests.
- Calibration
Load Error - Error returned when an existing calibration cache cannot be trusted.
- Config
Error - Errors returned while validating a scan configuration.
- Content
Error - Why a file could not be turned into an index.
- Correlation
Kind - How a correlation group was joined.
- Correlation
Role - Why one finding belongs to a correlation group.
- Coverage
GapReason - Why the pass could not build file context for some findings.
- Dedup
Scope - Deduplication scope for grouping findings.
- Detector
Base64 Alphabet - Exact base64 dialect accepted by a detector-owned offline validator.
- Detector
Corpus Error - Failure to compose an effective detector corpus.
- Detector
Corpus Mode - How a custom detector corpus participates in the effective corpus.
- Detector
Kind - Which scan phase produces a detector’s findings (see
DetectorSpec::kind). - Detector
MlMode - How the shared ML model participates in one detector path.
- Detector
Relation Kind - Cross-detector evidence operation applied during deterministic match resolution.
- Detector
Validator Spec - An offline validator declared by one detector.
- Entropy
Detection Role - Detector-owned entry roles for the shared entropy engine.
- Entropy
Fallback Class - Semantic role of a detector-owned synthetic entropy finding.
- Evidence
Direction - How a contextual evidence match must be positioned relative to the primary credential.
- Evidence
Requirement - Whether contextual evidence admits, strengthens, or rejects a detector match.
- Evidence
Scope - The structural boundary in which contextual evidence may satisfy a relation.
- Evidence
Value Relation - The value relationship between a selected evidence capture and the primary credential.
- Http
Method - HTTP method for verification requests.
- Merkle
Load Status - Operator-relevant status for a Merkle cache load.
- OobPolicy
- How OOB observation combines with HTTP success criteria.
- OobProtocol
- Out-of-band callback protocol expected from a successful exfil.
- Provider
Evidence Role - Stable semantic role of provider evidence exposed in findings.
- Provider
Evidence Sensitivity - Confidentiality policy for detector-owned provider evidence.
- Quality
Issue - Quality issue found in a detector spec.
- Redaction
- What was done to a target value before it was allowed into an artifact.
- Report
Format - Output format and formatter options for
write_report. - Rule
Suppressor Error - Errors from loading or parsing
.keyhogignore.toml. - Scan
Completion Status - Terminal state carried by detached scan artifacts.
- Script
Engine - Script interpreter names accepted by the detector TOML schema.
- Severity
- Severity level for a finding.
- Shape
Charset - Character class an isolated entropy shape admits. Replaces the former per-shape enum variant so a new shape family is TOML data, not scanner code.
- Source
Coverage GapKind - Machine-readable reason a requested source surface was not fully scanned.
- Source
Error - Errors returned by input sources while enumerating or reading content.
- Spec
Error - Errors returned while loading or validating detector specifications.
- Success
Policy - How a verifier response establishes a successful credential check.
- Target
Relation - How a target was tied to a credential.
- Verification
Result - Result of live verification: whether the credential is active, revoked, or untested.
Constants§
- DEFAULT_
ENTROPY_ BPE_ MAX_ BYTES_ PER_ TOKEN - Single owner of the BPE “rare-not-random” gate default (the
ScanConfig::default().entropy_bpe_max_bytes_per_tokenknob). An entropy / generic candidate whosecl100k_basebytes-per-token is STRICTLY GREATER than this compresses into few common subword tokens, word-like (a probable false positive: dotted API paths, prose, XML) rather than a random secret and is suppressed.2.2is the empirical CredData F1 peak (seekeyhog_scanner::entropy::bpe; the offline A/B lifted F1 0.368→0.424). - DEFAULT_
ENTROPY_ THRESHOLD - Single owner of the Tier-A generic-entropy gate default (the
ScanConfig::default().entropy_thresholdknob). The scanner’s adjudicate fallback (generic_entropy_floor) resolves an absent per-scan value to this SAME number, so it references this const rather than re-spelling4.5: the two must stay equal by construction, not by two hand-kept literals. - DEFAULT_
MAX_ FILE_ SIZE_ BYTES - Shipped filesystem per-file scan cap.
- DETECTOR_
CORPUS_ MANIFEST_ FILE - Canonical file name for the directory-scoped detector corpus manifest.
- DETECTOR_
CORPUS_ MAX_ FORWARD_ SCHEMA_ VERSION - Highest newer detector schema this binary may inspect additively.
- DETECTOR_
CORPUS_ MIN_ SCHEMA_ VERSION - Oldest legacy detector schema this binary can migrate deterministically.
- DETECTOR_
CORPUS_ SCHEMA_ VERSION - Detector schema authored and enforced by this binary.
- DETECTOR_
TOML_ FILE_ BYTES - Maximum accepted size for one on-disk detector TOML file.
- HYPERSCAN_
CACHE_ FILE_ BYTES - Hard cap for one serialized Hyperscan shard cache file, including the KeyHog header.
- HYPERSCAN_
CACHE_ HEADER_ LEN - Byte length of the KeyHog Hyperscan cache header: magic plus little-endian version.
- HYPERSCAN_
CACHE_ MAGIC - Magic bytes at the front of every KeyHog Hyperscan shard cache file.
- HYPERSCAN_
CACHE_ VERSION - KeyHog-owned cache header version for serialized Hyperscan shard files.
- JSONL_
REPORT_ SCHEMA_ MINOR - Current minor version for the versioned JSONL stream contract.
- JSON_
REPORT_ SCHEMA_ MAJOR - Current major version for the versioned JSON report envelope.
- JSON_
REPORT_ SCHEMA_ MINOR - Current minor version for the versioned JSON report envelope. Minor 9 adds
the optional
correlationsarray and minor 10 the optionalaccess_targetsobject, each absent unless the producer opted in. - KEYHOG_
MATCHER_ ARTIFACTS_ SUBDIR - Sibling of [
KEYHOG_CACHE_SUBDIR] used for MatcherArtifact.khmfiles. - MATCHER_
ARTIFACT_ FILENAME_ PREFIX - Filename prefix for MatcherArtifact cache files (
matcher-<hex>.khm). - MATCHER_
ARTIFACT_ FORMAT_ VERSION - MatcherArtifact on-disk envelope version shared with lockdown header checks.
- MATCHER_
ARTIFACT_ MAGIC - On-disk magic for MatcherArtifact cache files (
KHMA). - MATCHER_
ARTIFACT_ SUFFIX - Filename suffix for MatcherArtifact cache files.
- STATIC_
RECOVERY_ METRICS_ SCHEMA_ VERSION - Schema generation for exact bounded static-recovery telemetry.
Traits§
- File
Content Source - Where the association pass gets file bytes.
- Source
- Produces chunks of text for the scanner to process. Each implementation handles a different input source.
Functions§
- access_
target_ rule_ ids - Rule ids the shipped policy defines, in file order.
- apply_
protections - Apply the process protections for the requested security mode.
- apply_
protections_ with_ persistence_ paths - Apply process protections and, in lockdown mode, fail closed on known persistence artifacts outside the default keyhog cache root.
- associate_
access_ targets - Attach access targets to a finding set, reading file context from disk.
- associate_
access_ targets_ with - Attach access targets using a caller-supplied content source.
- calibration_
default_ cache_ path - Default calibration cache location:
$XDG_CACHE_HOME/keyhog/calibration.json(or the macOS/Windows equivalents via thedirscrate). - compose_
detector_ corpus - Compose an effective detector corpus without implicit merging.
- compute_
detector_ corpus_ digest - Compute a deterministic digest of current-schema detector specs.
- compute_
detector_ corpus_ digest_ for_ schema - Compute a deterministic, schema-bound digest of a complete effective detector corpus.
- compute_
spec_ hash - Compute a stable BLAKE3 digest over the canonical detector set so a later scan can detect that detectors changed.
- correlate_
findings - Correlate the findings a report is about to publish.
- correlation_
composite_ part_ ids - Every detector id any composite row names, sorted and deduplicated.
- current_
executable_ sha256 - SHA-256 hex digest of the currently running executable, memoized once per process.
- decode_
standard_ base64 - Decode standard-alphabet base64 (with optional
=padding). - dedup_
cross_ detector - Cross-detector dedup at emit time.
- dedup_
matches - Deduplicate raw matches according to the given
DedupScope. - detector_
digest - Effective digest identifying the EXACT embedded detector set and the
directory-scoped
corpus.tomlschema contract compiled into this binary (<detector-count>-<fnv1a_hex>). Binding the manifest ensures caches, benchmarks, and autoroute evidence invalidate when parsing compatibility semantics change even if detector TOML bytes do not. Stamped bybuild.rsviacargo:rustc-env=KEYHOG_DETECTOR_DIGEST, this is the authoritative answer to “which effective corpus was compiled in” when cargo’srerun-if-changedcannot be trusted across in-place TOML edits. - detector_
spec_ by_ id - Canonical
id → DetectorSpeclookup over the embedded corpus, built EXACTLY ONCE. - embedded_
detector_ count - Number of embedded detector specs (authoritative for banners and tests).
- embedded_
detector_ specs - Every embedded detector spec, parsed EXACTLY ONCE for the whole process.
- finding_
metadata - Build the offline metadata for an AWS-access-key finding: always
{ "account_id": "<12 digits>" }for a decodableAKIA…/ASIA…key, plus{ "is_canary": "true", "canary_message": <note> }when the decoded account belongs to a known canary issuer.Nonewhencredentialis not a well-formed AWS access-key ID. - git_
hash - Git commit SHA the binary was built from, or
"unknown"for a build with no reachable.gittree (e.g. acargo package/ crates.io build). Stamped bybuild.rsviacargo:rustc-env=GIT_HASH;env!resolves here because the rustc-env applies to THIS crate’s compilation. Surfaced inkeyhog --versionand meant to be embedded in every result so a scan traces back to an exact commit (MC-06: the false “F1 regression” was a stale binary benched against HEAD, undetectable while every build reported the same empty version). - hex_
encode - Lower-case hex of digest bytes. The only place the hex string is materialized
for
CredentialHashvalues (reporters, Debug). - hyperscan_
cache_ filename - Build the on-disk filename of a KeyHog Hyperscan shard cache file from its
content
shard_key:hs-<shard_key>.db. Single owner of the name FORMAT, shared by the scanner shard writer (which persists the file) and the hardening lockdown gate (which recognises/strips it via [HYPERSCAN_CACHE_PREFIX]/[HYPERSCAN_CACHE_SUFFIX]), so writer and reader can never disagree on the shard filename. Previously the writer re-inlined thehs-/.dbaffixes in aformat!, a latent drift from this owner. - hyperscan_
cache_ header_ is_ valid - Return true when
headeris exactly the current KeyHog Hyperscan cache header. - key_
id_ canary_ status - Checked canary classifier used by live-verification paths.
- keyhog_
matcher_ artifacts_ root - Absolute path of the MatcherArtifact cache root
(
<os-cache>/keyhog-matcher-artifacts), orNonewhen the platform exposes no cache directory. - load_
detector_ corpus - Load all detector specs together with their normalized corpus schema identity.
- load_
detectors - Load all detector specs from a directory of TOML files. Runs the quality gate on each detector and fails closed if any detector cannot be read, parsed, or accepted by the gate.
- load_
embedded_ detectors_ or_ fail - Parse the embedded detector corpus, FAILING CLOSED on any malformed TOML.
- max_
decode_ depth_ limit - Maximum recursive decode passes accepted from CLI and TOML config.
- merkle_
default_ cache_ path - Default Merkle index location:
$XDG_CACHE_HOME/keyhog/merkle.idxor~/.cache/keyhog/merkle.idxon Linux,~/Library/Caches/keyhog/...on macOS. - parse_
canary_ account_ ids - Parse and validate raw 12-digit account IDs from
.keyhog.tomlconfig. - parse_
jsonl_ stream - Parse one or more concatenated, versioned JSONL streams.
- read_
detector_ toml_ file - Read one detector TOML without allowing metadata races to bypass the cap.
- redact
- Redact a sensitive credential string for safe display.
- redact_
companions - Redact every companion value at the process boundary.
- resolve_
safe_ bin - Resolve
nameto an absolute path inside one of the trusted system binary directories. ReturnsNoneif not found in any trusted dir (do NOT fall back toCommand::new(name)- that’s exactly the bug). - set_
extra_ canary_ accounts - Replace the process-local extra canary account set supplied by
.keyhog.toml. - set_
extra_ trusted_ dirs - Replace the caller-configured trusted binary directories.
- sha256_
hash - SHA-256 of a string as the
CredentialHashdomain type. This is the single source for credential hashing across the workspace (scanner, dedup, telemetry); hex encoding is a separate step at the serde/reporter boundary viahex_encode, keeping the pre-dedup hot path zero-heap. - state_
file_ lock_ path - Canonical sibling lock filename for a KeyHog state artifact.
- strip_
windows_ verbatim_ prefix - Strip the Windows verbatim path prefix (
\\?\) from a display string. - validate_
access_ target_ policy - Validate a candidate access-target policy document without installing it.
- validate_
canary_ accounts - Validate the compiled Tier-B canary account baseline.
- validate_
correlation_ policy - Validate a candidate correlation policy document.
- validate_
detector - Validate a detector spec against the quality gate.
- write_
csv_ coverage_ report - Write a CSV scan artifact with a self-describing scan-status preamble.
- write_
hyperscan_ cache_ header - Append the current KeyHog Hyperscan cache header to a serialized-cache buffer.
- write_
report - Write a complete findings report in the requested format.
- write_
scan_ report - Write a complete report from the shared scan model.
Type Aliases§
- Companion
Map - Companion values keyed by scanner-compiled, reference-counted names.
- Html
Scan Metadata - Compatibility name for callers that used the original HTML-only type.