Skip to content

Kingfisher Secret Scanner for Python

The kingfisher-secret-scanner PyPI package provides native Python secret detection, credential validation and revocation. Install it with uv add kingfisher-secret-scanner; import it as kingfisher_sdk (the distribution and import names differ). See the Kingfisher GitHub repository for the full project, source code and broader CLI capabilities.

Kingfisher has two independent Python distributions:

Distribution Import / command Purpose
kingfisher-secret-scanner import kingfisher_sdk Native, in-process bindings to the Rust core, rules, scanner, validation and revocation code
kingfisher-bin uvx kingfisher-bin / kingfisher Existing packaged CLI; full repository, archive and remote-source enumeration

They can be installed together without module or entry-point conflicts. The SDK requires CPython 3.10+ with the standard GIL build. Wheels target Linux x64/ARM64 (glibc 2.28+), macOS x64/ARM64 (11+), and native Windows x64/ARM64. PyPy, free-threaded Python and musl wheels are not currently part of the release matrix.

The prepared SDK release is 1.7.0. It adds cryptographic helpers for custom rules and preserves existing Python APIs.

CLI and low-level Rust validation responses can include allowlisted identity metadata without additional requests. Python validation result representations and serialization remain unchanged and omit provider responses and private evidence. Use the SDK's explicit analysis API for identity or permission details. The SDK includes offline revocation preparation, structured input diagnostics, result-based and batch revocation, validation variables and SMTP support, opt-in CLI detection policies, SQLite/bytecode extraction, richer Git scopes and metadata, composable input enumeration, per-call controls, a reusable compiled rule cache and Rules.detail() inspection. Its version is independent of the CLI and Rust library packages; Python modules share the SDK version.

Install and scan

uv init my-scanner
cd my-scanner
uv add kingfisher-secret-scanner
from kingfisher_sdk import Scanner

scanner = Scanner()  # Compile the embedded catalog once and reuse it.
for finding in scanner.scan("text to inspect"):
    if finding.visible:
        print(finding.to_dict())  # Redacts the secret and all captures.

Scanning is offline. scan(str | bytes) scans a buffer; scan_file(path) scans one file with path-aware filters. For directories, local Git history and archives, compose the input APIs below. The SDK does not fetch repositories or enumerate cloud sources; supply their content from Python or use the CLI.

API modules

Module Public API
kingfisher_sdk.core Finding, shannon_entropy(bytes)
kingfisher_sdk.rules Rules(paths=(), builtins=True, confidence="medium", cache=True, cache_dir=None)
kingfisher_sdk.scanner Scanner(rules=None, base64=True, dedup=False, redact=False, min_entropy=None, policy=None), DetectionPolicy, DetectionScanner, CancellationToken, ScanResult
kingfisher_sdk.inputs ScanInput, filesystem, git_history, expand_archives, expand_content
kingfisher_sdk.git GitScope, GitInput, GitCommit, GitSignature, GitInputWarning, git_inputs
kingfisher_sdk.validation Validator, ValidationResult, ResolvedCredential, RevocationInputs, InputDiagnostic
kingfisher_sdk.revocation Revoker, RevocationResult, RevocationPlan, RevocationCandidate, BatchRevocationResult

These names are also exported from kingfisher_sdk. GitInputWarning supports standard Python warning policies for explicitly skipped Git blobs. Python modules wrap one PyO3 extension, sharing the Rust types and compiled rule database. Official wheels enable all scanner validator features, including HTTP, Betterleaks expressions, gRPC, raw/provider-specific validators, AWS, Azure, Coinbase, GCP, JWT, databases and local Ethereum key derivation.

Rules accepts files and directories containing Kingfisher YAML and Betterleaks TOML. Custom TOML IDs receive the custom. prefix. Use builtins=False for custom-only rules. Rules.metadata() lists exact IDs, names, visibility and whether each rule has validation/revocation. Rules.detail(exact_id) returns the loaded definition, including the regex, filters, dependencies and configured validation/revocation logic. Unknown or unloaded IDs raise ValueError.

The shared catalog includes betterleaks.generic-api-key at static low confidence, with every rejection filter but no confidence-upgrade branch. The default Rules(confidence="medium") excludes it before native regex compilation; use Rules(confidence="low") to include it. betterleaks.generic-credential-uri stays medium; generic-password and generic-username remain excluded from the catalog.

All rules use their configured confidence; there are no dynamic upgrades, demotions, or runtime confidence variants. Existing custom YAML/TOML rules still load without edits. Legacy one-string-argument setConfidence(...) and filter.setConfidence(...) calls are inert string passthroughs; rejection filters and association helpers remain active.

from kingfisher_sdk import Rules, Scanner

rules = Rules(["company.yml", "team.toml"], builtins=False)
scanner = Scanner(rules, dedup=True)
findings = scanner.scan_file("application.conf")
scanner.reset_dedup()

Finding.rule_id, .visible and .secret expose the matching ID, visibility and raw secret. Additional native properties expose .rule_name, .confidence, .entropy, .fingerprint, .captures, .blob_id, .is_base64_encoded and .location without serializing the whole finding. Dictionary properties return copies. to_dict() contains the same fields and redacts credentials and captures. Location offsets are bytes, the end is exclusive, lines start at 1 and columns start at 0. UTF-16/32 inputs may be normalized before scanning. to_dict(redact=False) explicitly exposes secret material. Repr omits credentials. Redaction does not erase earlier copies. Redacted reports retain fingerprint, entropy and content identity for correlation; these can disclose information about guessable secrets or inputs, so control report access as carefully as other security findings.

Reuse the compiled rule cache

Rules() and the default Scanner() now read and write the same compiled Vectorscan cache as the CLI. Previously, every Rules() construction recompiled the content database. Explicit cache_dir takes precedence over KF_RULE_CACHE_DIR; otherwise the platform cache directory is used. Paths accept strings or Path objects. cache=False bypasses both reads and writes, even when a directory or environment variable is supplied.

from pathlib import Path
from kingfisher_sdk import Rules, Scanner

# Run during image construction to populate the cache; use the same rules,
# confidence and directory at service startup, then reuse the Scanner.
# Prewarm as the service account so the runtime user owns the cache files.
rules = Rules(confidence="medium", cache_dir=Path("rule-cache"))
scanner = Scanner(rules)

# Opt out of disk caching for an embedding that needs no persistent state.
uncached = Scanner(Rules(cache=False))

CLI prewarming also works: kingfisher rules compile-cache --confidence medium --rule-cache-dir rule-cache prepares the same entry when the resolved rules and engine build match. Entries require compatible architecture, pointer width and endianness, the pinned binding versions and the exact native engine build identity. Transfer within a deployment using the same wheel/build; another operating system or engine build can require recompilation. Vectorscan checks native version and CPU-feature compatibility on load. Missing, stale, corrupt or rejected databases are recompiled on the receiving host; writes are best effort, so a read-only or unavailable cache does not prevent scanning. The new cache format causes a one-time recompile of older entries. Architecture changes also require recompilation. For containers, prewarm as the runtime account or transfer ownership before deployment; a root-owned cache is bypassed by an unprivileged runtime user. The builder's account, username and UID are not recorded in the cache key or serialized database. Ownership checks apply to the files on the receiving host, so deployment on a different host does not require the builder's account there. Custom external or patched engine builds that preserve their version/build string should use separate cache directories or cache=False.

Only the main Vectorscan content database is persisted. Rule loading, confirmation regexes and collection-level path/finding filters still initialize each time; keep one Rules/Scanner per process to reuse those resources. rules.cache_status is loaded, stored or bypassed, allowing applications to verify prewarming without logging rule contents. The cache stores compiled rule patterns and metadata, not findings or scanned content. No automatic cache pruning runs in the SDK; use the CLI's rules prune-cache when needed.

Cache directories must be trusted: serialized Vectorscan databases are native engine input. The default never falls back to shared system temporary storage; if no user cache directory is available, caching is disabled. Unix cache directories are created privately and untrusted ownership, permissions or symlinks disable caching. Windows cache directories/files must belong to the current user; write permissions may also include Administrators/SYSTEM. New directories and entries explicitly receive the process user SID as owner, including for SYSTEM services; existing paths must meet the same ownership checks. Protected ancestors may additionally be owned or maintained by TrustedInstaller, without allowing other accounts to replace the cache. A SHA-256 payload check catches corruption before native deserialization; it does not authenticate data supplied by someone with the same account privileges.

See the commented cache example.

Prewarm a container image for a non-root service

The commented Dockerfile implements the image-build/deploy workflow from issue #538. It installs one compatible SDK wheel, compiles the built-in medium-confidence catalog as root, then uses COPY --chown=10001:10001 to give the runtime service ownership of the cache directory and every entry. It explicitly creates the destination as that UID with mode 0700; copied files retain mode 0600. Root-owned, non-writable parent directories are supported. Changing only the directory owner is insufficient.

Build from the repository root, supplying a repaired Linux wheel matching the image architecture and Python ABI in dist-python/. The example's Docker ignore file excludes repository history and build outputs from the context. Deploy the resulting image unchanged so build and startup use the same engine:

# Set this to the wheel downloaded or built for your Linux image architecture.
SDK_WHEEL=dist-python/your-compatible-wheel.whl
docker build -f python/examples/rule_cache.Dockerfile \
  --build-arg SDK_WHEEL="$SDK_WHEEL" \
  -t kingfisher-cache-demo .
docker run --rm kingfisher-cache-demo
# On a compatible host, require reuse without recompilation or cache writes:
docker run --rm --read-only kingfisher-cache-demo --require-hit

The example uses a fixed numeric runtime UID/GID, which travels with the image; no matching host username is needed. For a single-stage build, prewarm after switching USER, or run chown -R <runtime-uid>:<runtime-gid> <cache-dir> before switching users. For bind mounts or arbitrary runtime UIDs, provision both the directory and files for the actual container UID (including user-namespace mapping), and prevent other accounts from modifying or replacing them.

A valid entry can load from a read-only filesystem. On an incompatible CPU, normal startup recompiles in memory and continues scanning. Persistence requires a writable, trusted cache; a read-only image cannot retain the replacement for the next process. --require-hit is a deployment check for known compatible hosts, rather than the normal startup policy. Keep Rules(confidence="medium") and one reusable Scanner per process, as shown in the example.

Inspect the bundled rules and their logic

import json
from kingfisher_sdk import Rules

rules = Rules(confidence="low")  # Include the full catalog, including helper rules.
for summary in rules.metadata():
    if summary["revocation"]:
        print(summary["id"], summary["name"])

# Use an exact ID from metadata(); custom TOML IDs start with "custom.".
rule_id = "betterleaks.aws-access-token"
detail = rules.detail(rule_id)
print(detail["pattern"])          # Stored pattern, including any rule comments.
print(detail["detection_regex"])  # Compiled Rust confirmation regex, comments removed.
print(json.dumps(detail["validation"], indent=2))
print(json.dumps(detail["revocation"], indent=2))
print(json.dumps(detail["depends_on_rule"], indent=2))

detail() includes the rule's name/ID, confidence, visibility, entropy threshold, path predicate, capture selection, Betterleaks filter, pattern requirements, dependencies, examples, references, TLS mode and validation/revocation definitions. The returned dictionary is a copy; changing it does not alter loaded rules. detection_regex is the compiled confirmation pattern, excluding the internal endpoint wrapper. A regex match is only a candidate: selected captures still pass the detector's filters and dependency requirements.

Missing validation/revocation is None. HTTP/gRPC definitions expose configured requests and response matchers; Betterleaks validation exposes its portable expression tree, component bindings and operational capabilities. Original Betterleaks expression text may be absent in release builds. Typed validators such as AWS/JWT and raw validators expose their dispatch type/name; their Rust implementation code is not embedded as inspectable Python text. Configuration presence alone does not establish authoritative live validation or successful revocation.

Inspection is offline and performs no validation or revocation. The output is rule configuration, without finding redaction; literals supplied in custom rules are returned as configured.

The rule inspection example lists the catalog, filters by ID glob or configured capabilities, and displays full details or selected fields:

uv run --no-sync python python/examples/rules.py --with-validation --with-revocation
uv run --no-sync python python/examples/rules.py --id-glob 'betterleaks.aws*'
uv run --no-sync python python/examples/rules.py betterleaks.aws-access-token --field pattern --field validation --field revocation
uv run --no-sync python python/examples/rules.py acme.python-demo --rules-path python/examples/demo.yml --no-builtins

Choose detection and reporting filters

Detection settings change which candidates can become findings. Reporting predicates select from completed findings and do not save matching work.

Setting Effect
Rules(confidence="high") Load only rules meeting this minimum confidence; confidence is rule metadata, not live validity
Rules(["company.yml"], builtins=False) Scan a focused custom catalog; metadata() lists its exact IDs and supported actions
Rules(cache_dir="rule-cache") Override the compiled rule cache directory; takes precedence over KF_RULE_CACHE_DIR
Rules(cache=False) Disable compiled rule cache reads and writes
Scanner(base64=False) Skip decoding/scanning Base64 strings
Scanner(min_entropy=4.0) Override every rule's entropy threshold; a lower value can admit extra candidates, so normally retain rule defaults
Scanner(dedup=True) Suppress subsequent successful scans of the same content and source path until reset_dedup(); this is not secret-level deduplication across files
Python path selection Skip inputs before calling scan_file; use Path.expanduser() for ~

For selective output, retain findings and apply Python predicates to their redacted dictionaries. Serialize once per finding rather than repeatedly building report dictionaries. Native scalar properties are inexpensive; use finding.rule_id or finding.entropy for filters before creating a report.

from fnmatch import fnmatchcase
from kingfisher_sdk import Scanner

scanner = Scanner()
findings = scanner.scan_file("application.conf")
for finding in findings:
    if not finding.visible:
        continue  # Hide component helpers in reports; retain them for validation.
    data = finding.to_dict()
    if not fnmatchcase(data["rule_id"], "betterleaks.*"):
        continue
    if data["entropy"] < 3.5:
        continue  # Report filter; does not override the detector's own threshold.
    print(data)

Other predicates can use any of these fields:

Field / property Example predicate
finding.visible Report primary findings only
data["rule_id"], data["rule_name"] Exact ID set membership, fnmatchcase globs, or name substring
data["confidence"] == "high" (low, medium, high)
data["entropy"] >= 3.5 (bits per byte); a report cutoff can hide valid low-entropy credentials
data["is_base64_encoded"] True to report only decoded findings
data["location"] data["location"]["line"] >= 10, byte ranges, or columns; decoded content may have normalized offsets
data["fingerprint"] An occurrence allowlist/key (rule_id, fingerprint); includes value, blob identity and offsets, so repeated secrets can have different fingerprints
data["blob_id"] Group findings from one input's content
data["captures"] Check capture-name presence; values are redacted by default

Paths are supplied to scan_file for native rule filters but are not stored in Finding; retain the path alongside your findings. Raw-value predicates require explicit finding.secret or to_dict(redact=False) access; keep those values out of reports. For format/context constraints that should run during detection, use custom rule entropy, pattern requirements and filters as described in RULES.md.

Apply report predicates after validation, preserving the complete list from one input. ValidationResult additionally supports predicates on .outcome, .http_status and .reason, for example result.outcome == "verified_active". The runnable validation example supports repeated --outcome and --rule report selectors; these do not prevent provider requests for other findings.

Custom rule requirements and component validation

Scanner and DetectionScanner enforce YAML pattern_requirements during offline detection, including character minimums, custom special characters, case-insensitive ignore_if_contains, and Liquid checksums. This includes Base64 matches. Named captures, MATCH/FULL_MATCH, and skip_if_missing use the CLI semantics described in the rule guide.

Use luhn_valid and iban_valid for offline structured-data checksums. These check formats/checksums, not card issuers, registered IBAN countries, country-specific lengths, or whether an account exists. The commented example loads a custom-only catalog, discards invalid checksums, and prints redacted findings:

uv run --no-sync python python/examples/pattern_requirements.py

Native findings retain compact full-match spans and assignment/object context for component windows and ranking, without retaining the source payload. Keep complete per-input findings, including invisible helpers, through Validator.validate(). Distinct component values normally skip validation. Rules explicitly setting verify_candidates: true use the same fixed-origin eligibility and bounded search as the CLI: at most 16 combinations, four concurrent searches, and the shorter of 30 seconds or the validator timeout. Setting timeout to zero disables the deadline. Only a verified active result selects a component. Rejection of every combination leaves the primary unresolved, not verified inactive. Offline input inspection still reports ambiguity until explicit validation resolves it.

Each validation batch groups repeated identical rule/resolved-input checks into one request, including candidate attempts. Different rules and resolved components stay independent; a later batch checks again. Validation is explicit, and revocation continues to require confirm=True.

Comparing SDK and CLI results

The SDK and CLI share native detection primitives, but their surrounding pipelines are different. A recursive Python scan is not automatically equivalent to kingfisher scan ~/example-repo:

  • The SDK can enumerate filesystem inputs, reachable Git history and archives explicitly through its input APIs. These do not read CLI configuration or apply CLI configuration or every exclusion policy. git_inputs() exposes explicit history, snapshot, diff and staged scopes. scan.py walks the current directory tree, skips .git, .venv, node_modules and symlink entries, and supports relative path globs; it does not read .gitignore or CLI configuration.
  • Use scan_file(path) to preserve path-aware rule/filter behavior. scan(bytes) has no source path, which can change matching and filtering.
  • Use DetectionScanner to opt into shared CLI matching windows, bounded nested Base64 decoding, inline-ignore directives and HTML/CSS parser checks. Existing Scanner defaults stay unchanged.
  • SDK scanning is offline. CLI scanning normally also validates credentials; use --no-validate when comparing detection alone.
  • SDK Revoker.prepare() accepts an exact rule ID/name or a deterministic ID family through Rules.resolve(). This is separate from CLI selector/legacy-alias resolution; preparation is offline, validation is explicit, and revocation still requires confirm=True.
  • The SDK returns invisible component helpers and defaults to deduplication off. Compare only visible findings, and use CLI --no-dedup to compare occurrences.

For a closer CLI comparison of working-tree detection, start with:

kingfisher scan ~/example-repo --git-history none --no-extract-archives --no-validate --no-dedup --no-update-check --format json

Then align the exact file list, rules/catalog version, confidence and Base64 settings. Compare rule IDs, source paths and locations rather than raw counts or redacted text. SDK fingerprints include blob identity and offsets; CLI fingerprints use source origin, so do not expect cross-interface fingerprint equality. If comparing credential values, compute keyed digests internally without printing raw values. Use DetectionScanner and align its matching, decoding and context settings as well. Enumeration, validation and reporting differences can still change results.

Compose filesystem, Git history and archives

Existing scan() and scan_file() signatures and behavior are unchanged: neither method enumerates inputs or automatically extracts archives. Use the new input layer to choose each stage independently:

from itertools import chain
from kingfisher_sdk import Scanner, filesystem, git_history, expand_archives

sources = chain(filesystem(["./repo"]), git_history("./repo", refs=["HEAD"]))
scanner = Scanner()
for result in scanner.scan_inputs(expand_archives(sources, depth=2)):
    for finding in result.findings:
        if finding.visible:
            print(result.input.path, result.input.commit, finding.to_dict())

All engine enumeration runs offline and in-process. Native Git enumeration does not require a Git executable or modify the checkout. Enumeration is separate from scanning; filter or combine iterators using ordinary Python. To enumerate the filesystem yourself, replace filesystem() with your own iterator:

from pathlib import Path
from kingfisher_sdk import ScanInput

sources = (ScanInput.from_file(path) for path in Path("./repo").rglob("*.conf")
           if path.is_file() and not path.is_symlink())
results = scanner.scan_inputs(expand_archives(sources))

For Git enumeration in Python, adapt your Git library's file versions to ScanInput(path="config.txt", data=blob_bytes, repository="./repo", commit=commit_hex, blob_id=blob_hex). Both kinds of input use the same scanner and archive transform. scanner.scan_input(source) also scans just one input and returns the existing list[Finding] type. Use ScanInput with bytes to preserve logical paths when scanning remote or historical content; scan(bytes) continues to have no source path.

Stage Behavior
ScanInput.from_file(path) Defers file reads until scanning/expansion; file paths must be strings or PathLike[str]
filesystem(roots, gitignore=True, hidden=False, max_file_size=None) Enumerates regular files; skips symlinks and .git; honors local Git/ignore files, but not global Git excludes or CLI configuration
git_history(path, refs=("HEAD",)) Visits reachable commits including merge parents and shallow boundaries; supports bare repositories; emits each (path, blob ID) once; excludes working-tree changes, symlinks, submodules and unreachable objects
expand_archives(inputs, depth=1, max_bytes=268435456, max_entries=10000) Uses shared CLI extractors for ZIP/ZIP-based formats, TAR, gzip/bzip2/xz and compressed TAR, zlib, ASAR and HWP; ZIP signatures detect containers without an extension
scanner.scan_inputs(inputs) Lazily yields ScanResult(input, findings) per input, including empty groups; retains invisible helpers for validation

Pass refs=None to enumerate all refs plus HEAD, including branches outside HEAD ancestry. Git paths are repository-relative strings; invalid UTF-8 is represented lossily, with the original bytes in GitInput.raw_path. input.commit is one encountered occurrence, not necessarily the first introduction; enumeration order is unspecified. After archive expansion, Git metadata still identifies the original container blob, while each finding's blob ID identifies its scanned content. Archive paths use outer.zip!member; single compressed streams use outer.gz!content. Repeated ZIP/TAR member names produce separate inputs with the same logical path and their own bytes. Depth 0 keeps containers raw; maximum depth is 32. Budgeted TAR/ZIP/ASAR expansion rejects malformed or unsafe members and staging I/O errors for the whole root, before yielding any of its members. Extraction uses temporary directories under optional temp_dir (default system temporary storage). Choose a protected temp_dir parent on every platform. SDK staging directories use owner-only Unix mode 0700, which the umask may restrict further; Windows inherits the parent DACL. Small ZIPs decode in memory. Cleanup is attempted on completion; temporary plaintext may survive a crash or cleanup failure. Applications can select encrypted or memory-backed storage. Other shared format extractors retain their own per-format limits and may skip unreadable entries; successful expansion is not a guarantee of complete archive coverage. Scanner 3.0.2 / Python SDK 1.6.2 tighten strict budgeted archive failures without changing API signatures or the CLI's legacy best-effort defaults.

filesystem(max_file_size=...) silently skips oversized files and does not emit GitInputWarning; Git blob-size skips are reported explicitly.

Filesystem and Git iterators accept timeout and cancellation. Their deadlines cover iterator lifetime, including consumer time. expand_archives accepts the same controls and expands one root fully before yielding its members; timeout and byte/entry budgets apply per root, cumulatively across nested layers. Entry budgets count inspected members, not only emitted files: TAR/ZIP include directories, ASAR counts indexed files, and HWP counts streams. Unsafe TAR/ZIP/ASAR paths fail the entire root, rather than being skipped. Normal inputs become byte inputs and are subject to max_bytes too. These budgets bound returned content and cap extraction streams with the remaining budget, including compressed TAR headers and padding. Nested layers share one byte/entry budget; limits are enforced while writing, before another layer is materialized. Stream-cap exhaustion raises a budget error before any members from that root are yielded. Temporary extraction also has the engine's independent limits. The root input is independently capped at max_bytes and is not debited from the cumulative output budget. Root and output buffers can coexist, and conversion to Python bytes creates transient copies; max_bytes is not a bound on total process memory. Invalid depth and byte/entry options are rejected when calling the transform, before iterating inputs. scan_inputs accepts the same scan controls, with timeout applying per input. Errors propagate, including filesystem errors, unresolved refs and archive failures. Already-yielded scan groups remain with the caller; the failed input never returns partial findings. Individual reads/extractions remain cooperative.

For validation, call validator.validate(result.findings) separately for each group, then filter visible results for reporting. Composing filesystem and Git history can include the same content twice; Scanner(dedup=True) suppresses repeat successful scans of identical content at the same source path, rather than credential values across different paths.

The commented example scripts demonstrate these choices separately:

# Let Python select filesystem inputs, then use native archive expansion.
uv run --no-sync python python/examples/inputs.py ./repo --filesystem-enumerator python --archive-depth 2

# Native history needs no Git executable; --all-refs includes all refs plus HEAD.
uv run --no-sync python python/examples/git_history.py ./repo --enumerator engine --all-refs

# The example Python adapter uses Git subprocesses; replace it with your Git library.
uv run --no-sync python python/examples/git_history.py ./repo --enumerator python --ref HEAD

# Self-contained synthetic archive demo: compare byte/file inputs and nested depth.
uv run --no-sync python python/examples/archives.py --source bytes --depth 2
uv run --no-sync python python/examples/archives.py --source file --depth 1

The Python filesystem example defines its own path policy rather than parsing .gitignore; choose --filesystem-enumerator engine for native ignore handling. The Python Git example requires Git on PATH and produces the same ScanInput shape as native enumeration. It demonstrates (path, blob ID) deduplication, regular-file selection, reachable refs and preservation of commit metadata. The archive demo loads demo.yml beside the script, creates only synthetic ZIP fixtures, and shows per-root extraction budgets and separate per-input scan controls. Download that fixture with the script when running outside a checkout. At depth 0 it scans the raw outer ZIP; depth 1 reaches the nested ZIP bytes; depth 2 reaches the inner configuration file and its synthetic finding. All three scripts report redacted output and leave validation explicit.

Opt-in CLI detection policies

Scanner(policy=DetectionPolicy(...)) opts into CLI matching, bounded nested Base64 decoding, inline-ignore and HTML/CSS context policies. DetectionPolicy is frozen; iterable ignore markers are copied into a tuple, so a policy can be reused across scanners and threads. All settings are applied at construction. DetectionScanner remains a compatibility facade over the same policy. It inherits scan(), scan_file(), scan_input(), scan_inputs() and reset_dedup(), with the same findings and interruption contracts. Existing Scanner default behavior remains unchanged when no policy is supplied.

from kingfisher_sdk import DetectionPolicy, Scanner, ScanInput

policy = DetectionPolicy(ignore_comments=("acme:ignore",))
scanner = Scanner(policy=policy)
findings = scanner.scan_input(ScanInput("config.html", html_bytes))

inline_ignores=True recognizes kingfisher:ignore and optional case-insensitive ignore_comments markers, including the CLI's adjacent-line and multiline rules. markup_context=True verifies ambiguous candidates in HTML attributes, visible text, script/style bodies and CSS values. Self-identifying credential formats and Base64 candidates bypass the markup gate, as in the CLI. Language inference uses the shared content inspector and logical path; pass language="html" or "css" to override it for bytes or extensionless sources. Structural checks are bounded to 2 MiB; larger inputs and secrets containing invalid UTF-8 retain candidates because the parsers cannot faithfully verify them.

cli_match_semantics=True uses the CLI's 4 KiB initial confirmation windows, full-match component anchors, per-rule secret containment checks, and overlapping Betterleaks credential-URI fallback suppression. This can change findings compared with Scanner, including offsets in long fixed-width runs. Set it to False to retain legacy SDK matching while choosing the context and Base64 policies separately. Reported secret locations and the Finding serialization shape stay unchanged.

base64_max_depth=2 enables two decoding layers. base64_max_input_bytes=64 * 1024 * 1024 skips Base64 decoding above a 64 MiB original-input limit; raw matching still runs. Depth zero disables the pass; base64=False also disables it. Use a different nonnegative depth or base64_max_input_bytes=None explicitly to change those limits. Nested findings identify the outer encoded region. Scanner keeps its existing one-layer, uncapped Base64 default. Containment checks are separate for raw input and each decoded buffer, preserving separately encoded sibling secrets even when they share the outer region's offsets.

Choose context policies independently with inline_ignores=False or markup_context=False. Inline-ignore and containment checks run before markup verification, then component requirements, URI fallback suppression, catalog deduplication and redaction. Keep invisible helper findings in one input's group for validation. Detection parity requires matching input lists, catalogs, confidence, entropy and Base64 settings; CLI source selection, validation, reporting and fingerprints still have their own contracts.

See the commented detection example:

uv run --no-sync python python/examples/detection.py

Private-key structure checks

Built-in PEM detectors use the CLI's bounded offline structure checks too. Recognized BER encodings and keys inside stub markers or partial diffs are kept when they may contain real key material; this is not cryptographic or live credential validation. See the private-key filter scope.

Extract PDF page text

Enable PDF extraction explicitly; existing expand_content() defaults and Scanner.scan_file() continue to leave PDF bytes unchanged:

from kingfisher_sdk import ScanInput, Scanner, expand_archives, expand_content

sources = expand_content(
    expand_archives([ScanInput.from_file("documents.zip")]),
    pdf=True, strict=True, max_bytes=64 * 1024 * 1024, timeout=10,
)
for result in Scanner(redact=True).scan_inputs(sources):
    print(result.input.path, len(result.findings))

The shared lopdf-based Rust extractor recognizes a %PDF- header or .pdf extension and emits document.pdf!page-N.txt inputs. Hex strings, compressed page streams, split text operands, and supported font encodings are decoded. Original Git/source metadata is retained; offsets refer to each page's UTF-8 text, not the PDF bytes. No rendering, OCR, PDF action execution, password support, embedded-file extraction, annotation extraction, or Form XObject text extraction.

max_bytes separately caps input, aggregate extracted text, and aggregate decoded page/font work. Shared streams are decoded once but charged on each page that uses them; repeated page IDs are skipped. Individual streams are capped at min(max_bytes, 32 MiB), with at most 10,000 pages per input. Loading divides the byte budget across a conservative count of literal stream markers (at most 32 MiB each), bounding aggregate eager decompression. Markers inside payloads/comments can tighten this budget and reject valid large streams. These caps are not a total process-memory limit. Controls run before/after parsing and between pages; an individual parser call cannot be preempted. Limits and interruption raise without yielding partial pages, even with strict=False. Image-only/empty PDFs pass through unchanged. Malformed or encrypted PDFs fall back to their original bytes with extraction_error="malformed_pdf", unless strict=True requests an error. With strict=False, individual undecodable streams are skipped while readable page text is retained. strict=True fails on those stream errors instead of yielding partial pages; unsupported features such as Form XObjects remain outside the extraction scope in either mode. Some codecs can silently recover corrupt data, so strict=True is not a guarantee that every stream was completely decoded. This is best-effort text coverage, not proof that a PDF is secret-free.

See the commented PDF example. Unlike the explicit SDK transform, CLI PDF extraction is on by default, scans raw PDF bytes alongside extracted text, and uses warning/raw-fallback behavior for over-budget PDFs.

Extract SQLite and Python bytecode

expand_content() is an explicit input transform using the same native SQLite and .pyc extractors as the CLI. It works with file inputs, historical blobs, caller-supplied bytes and archive members:

from kingfisher_sdk import DetectionScanner, ScanInput, expand_archives, expand_content

sources = expand_content(expand_archives([ScanInput.from_file("backup.zip")], depth=2))
for result in DetectionScanner().scan_inputs(sources):
    for finding in result.findings:
        if finding.visible:
            print(result.input.path, finding.to_dict())

SQLite is recognized by its file signature and exported as SQL per user table, including schema and named-column inserts. Paths use database.db!table.sql. The extractor reads a separate staged copy without modifying the database. Checkpoint or export live SQLite databases before scanning: writes existing only in a separate WAL are not part of the input bytes. BLOB values are represented as SQL hex. .pyc inputs are selected by extension; the shared magic/version-aware marshal parser extracts strings and nested code constants without importing or executing Python. Paths use module.pyc!strings.py. Offsets and finding blob IDs refer to extracted text; source repository, original blob and Git provenance are preserved.

sqlite=False and pyc=False disable the formats separately. Ordinary inputs, empty databases and unsupported bytecode pass through unchanged. Malformed inputs fall back to raw scanning with input.extraction_error set to malformed_sqlite or malformed_pyc; strict=True propagates parser errors. Diagnostic categories exclude potentially sensitive parser messages. Budgets and cancellation never fall back to raw content or return partial extracted input.

max_bytes (default 256 MiB) caps recognized input and total generated text. Output is bounded while extracting; exceeding it raises an error. Shared caps also limit SQL output to 256 MiB, bytecode output to 64 MiB and SQLite work to 100,000 rows per table. Bytecode structural safety limits raise budget errors, so deeply nested or oversized advertised collections cannot silently fall back. SQLite opens the staged snapshot read-only, enables defensive mode, disables trusted schema expressions, and limits native lengths/columns. Its VM progress handler checks deadlines/cancellation; bytecode parsing checks controls too. timeout applies per input. Native reads and individual operations remain cooperative; members are prepared completely before yielding.

SQLite lock waits remain bounded independently of content-size limits.

Bytecode and small ZIP extraction operate in memory. SQLite uses temporary storage under temp_dir (the system temporary directory by default). Choose a protected temp_dir parent on every platform. SDK staging directories use owner-only Unix mode 0700, which the umask may restrict further; Windows inherits the parent DACL. Cleanup is attempted on completion. Staging may survive a process crash or cleanup failure, so select encrypted or memory-backed storage if needed. Scanner.scan_file() continues to scan container bytes directly.

See the commented content extraction example, which builds a synthetic archive containing both formats:

uv run --no-sync python python/examples/content.py

Select Git scopes and retain provenance

Use git_inputs(repository, scope=GitScope(...)) for richer native enumeration. git_history() is a thin history facade over the same shared native enumerator and preserves its file-version contract; it accepts the same resource options. Both accept Python-controlled filtering and compose with the same extractors and scanners. Neither requires a Git executable, network or checkout writes.

from kingfisher_sdk import DetectionScanner, GitScope, git_inputs, expand_archives, expand_content

sources = git_inputs("./repo", scope=GitScope(refs=("HEAD",), since_commit="main"))
for result in DetectionScanner().scan_inputs(expand_content(expand_archives(sources))):
    for origin in result.input.origins:
        print(origin.id, origin.author.name, origin.committer.timestamp)
    # Keep full findings together for validation; report visible findings only.
Scope Selected content
GitScope() Changed regular-file versions across HEAD ancestry, visiting all merge parents and comparing each commit against its first parent
GitScope(refs=None) History from all refs plus HEAD
GitScope(since_commit="main", refs=("HEAD",)) Exclude the baseline and its ancestors; keep intermediate versions, even when deleted before HEAD
GitScope(branch_root="COMMIT", refs=("HEAD",)) Include this reachable root and later history, excluding the root's ancestors
GitScope(since_hours=24) Keep commits within the recent committer-time window, without pruning traversal on older timestamps
GitScope(since_time=START, until_time=END) Inclusive committer Unix timestamp bounds; applied after traversal to handle clock skew
GitScope(mode="snapshot", refs=("HEAD",)) Every regular file at one selected commit
GitScope(mode="diff", refs=("HEAD",), since_commit="main") Net changed target versions; deletions and intermediate versions are absent
GitScope(mode="staged") Changed index blobs against HEAD (empty baseline before the first commit), excluding unstaged edits
GitScope(mode="staged", since_commit="main") Changed index blobs against an explicit baseline
GitScope(refs=None, include_unreachable=True) Unbounded history including stored unreachable commits and stored blobs without regular-file provenance

since_hours must be positive and fit in signed 64-bit seconds after conversion from hours. Invalid scope bounds are rejected when constructing GitScope.

GitInput extends ScanInput with origins: tuple[GitCommit, ...], staged and unreachable. A history origin records a selected change occurrence, not every unchanged snapshot or guaranteed first-ever introduction. Reintroduced identical content at the same path shares one input with multiple origins. Snapshot/diff origins identify the target commit. Each commit exposes its ID, parent IDs, message, and author/committer GitSignature (name, email, Unix timestamp and timezone_offset in seconds east of UTC). Messages and identity emails are excluded from repr; messages are original repository content and may contain credentials. Commit metadata is shared across input origins rather than copied for every changed file.

The inherited input.commit identifies one scoped occurrence. Staged inputs have no commit or origins. Unassociated stored blobs use @git/<object-id>, no commit, and unreachable=None because their reachability cannot be inferred from a regular-file origin. unreachable=False/True describes whether an associated version has a selected reachable change occurrence. Extraction preserves all metadata through dataclasses.replace(); finding locations point into the member.

Descriptor/metadata preparation occurs before the first yield, uses memory proportional to selected changes, and loads payloads lazily. timeout covers preparation and the iterator's lifetime, including consumer time; cancellation is cooperative. Tree comparisons skip identical subtree IDs, so history work tracks changed paths rather than flattening every complete tree. Non-UTF-8 paths retain their original bytes in raw_path. Use max_commits and max_inputs to bound preparation (exhaustion raises an error); max_blob_size skips oversized blobs with a warning before loading their payloads. Missing objects in partial clones raise an error by default; skip_missing_blobs=True warns and continues without acquiring objects from the network. Complete local objects are required for full coverage.

By default discover=True searches parent directories for a repository; pass discover=False to require the supplied path to be a repository root. Revision arguments use Git revision syntax, including reflog expressions; they never execute shell commands or fetch remote data. Bare repositories and shallow boundaries are supported; shallow roots lack prior comparison content. Symlinks, submodules and intent-to-add index entries are excluded. Staged scanning requires a working repository and rejects conflicts and sparse indexes. No synthetic commit, index refresh, checkout or ref update is performed. Invalid or conflicting scope settings raise an error instead of widening the selection. In staged mode, leave refs at its default and use since_commit to select the baseline.

See the commented Git scopes example:

uv run --no-sync python python/examples/git_scopes.py ./repo --since-commit main
uv run --no-sync python python/examples/git_scopes.py ./repo --mode staged
uv run --no-sync python python/examples/git_scopes.py ./repo --mode diff --since-commit main

Scan timeouts and cancellation

from kingfisher_sdk import CancellationToken, Scanner

scanner = Scanner()
cancellation = CancellationToken()
findings = scanner.scan("text to inspect", timeout=2.0, cancellation=cancellation)
# Another thread can call cancellation.cancel() while scanning runs.

scan_file accepts the same keyword arguments. Timeout values must be finite, positive seconds; omit timeout for unlimited execution. An interrupted scan raises TimeoutError for an expired deadline or RuntimeError for cancellation, without partial findings or a dedup-cache entry. Tokens remain cancelled; create a new token for new work.

These controls are cooperative. Checks run between matching/filtering operations, in native match callbacks and during Base64 enumeration. File reads, decoding, rule compilation and individual native operations cannot be preempted. Python releases the GIL during scanning, allowing another thread to signal cancellation. Use a separate process when a hard wall-clock execution limit is required.

Validate explicitly

Starting in Python SDK 1.7.0, custom Liquid/Betterleaks rules can use the shared cryptographic authentication helpers (ECDH/ECDSA, AES-GCM, HKDF/PBKDF2 and Ed25519), without a separate Python crypto API. Load the complete scaffold through Rules, retain its invisible client-ID finding, and use Validator explicitly. Its .invalid endpoint and public test keys are teaching fixtures, not a live provider; review and adapt the protocol before enabling requests.

Custom YAML HTTP rules also support OAuth2 authentication for a configured verification service. Load the rule through Rules, set its credential environment variables, and reuse a Validator to share token refresh and failure cooldowns. Scanning remains offline; explicit validation obtains and uses the access token. Rules.detail() redacts literal OAuth2 usernames, passwords and client secrets without changing executable credentials; environment-variable names remain visible and are not resolved during inspection. Prefer username_env, password_env and client_secret_env so credentials stay outside rule files. Explicitly allowed loopback plain-HTTP token/verifier requests connect directly, without proxies; HTTPS retains strict TLS and environment proxy/NO_PROXY settings.

SMTP credential URIs are supported through the shared validator. Separate SMTP fields use the custom rule example; see the SMTP validation contract for TLS, port fallback, and result classification. The Python SMTP example loads those rules, retains supporting findings, and reports redacted outcomes.

from kingfisher_sdk import Scanner, Validator

findings = Scanner().scan_file("application.conf")
validator = Validator(timeout=10, concurrency=4)
for result in validator.validate(findings, timeout=30):  # Total batch deadline.
    if result.finding.visible:
        print(result.to_dict())

Keep the complete result list from one input, including invisible helper rules, until validation finishes: the Rust validator associates multi-part credentials using blob identity, encoding and proximity. Do not merge unrelated inputs into one validation call. Scanner(redact=True) prevents subsequent validation; retain raw findings internally and redact when reporting instead.

Validator accepts timeout (seconds), concurrency, retries (default 0), max_response_bytes (default 1 MiB for YAML HTTP), allow_internal_ips (default false) and variables (trusted template variables/endpoints). Response-size limits for other validator families remain provider-specific. TLS verification is enabled and the shared HTTP client disables redirects. The internal-address check is not a network sandbox or DNS-pinning guarantee.

SMTP session cleanup has a short independent timeout so stalled cleanup writes finish promptly after an authentication result is established.

Betterleaks v2 custom rules support Expr validation, analysis, and explicit revocation. Call validator.analyze(result, timeout=30) after confirmed validation to run a rule's analyze expression using the exact validated credential and private evidence. This returns public analysis JSON; private validation.analysis data stays out of result serialization. Analysis never runs automatically during scanning or validation. See the runnable analysis example. HTTP validation uses the primary endpoint only by default. Explicitly use Validator(http_fallbacks=True) to try up to two rule-defined fallback environments. Their reuse_primary_validation_logic boolean defaults to false (complete independent HTTP definition required); true copies primary validation with only the URL changed. Result-based revocation retains the selected environment. Independently opt in to reuse_primary_revocation_logic: true with revocation_url (HTTP) or revocation_urls (one per multi-step request), or supply an independent revocation definition. Otherwise revocation is unavailable; validation reuse never implies revocation reuse, and mutations never fail over to another environment. The CLI counterpart is --fallbacks, covering validation and selected-environment revocation. These switches reuse logic, not the primary destination. Existing rules and existing constructor calls need no edits. See fallback endpoint rules and the runnable example.

CLI revoke --fallbacks validates first and selects the environment internally; it does not require a preceding validate call or manual endpoint variables. SDK Revoker.revoke(result, confirm=True) instead uses that result's original snapshot without revalidation. Both stop rather than mutate another environment if the selected action fails or is unavailable. Exact-ID revocation calls use only the primary action and reject reserved VALIDATION_* endpoint-selection variables; pass a validated result for fallbacks.

validate(findings, timeout=None, cancellation=None) adds a total batch deadline, including queued checks, independently of the constructor's per-check timeout. It checks Python signals while waiting on I/O, so Ctrl-C raises KeyboardInterrupt. Timeout and cancellation raise TimeoutError and RuntimeError without partial batch results. Cancelled I/O does not undo requests already submitted. Provider operations reuse a process-wide Tokio runtime sized from available CPUs (2–32 workers); provider request concurrency is set on each Validator.

Use Scanner.scan_with_attributes(data, attributes, timeout=None, cancellation=None) to supply Betterleaks source metadata such as path, git.sha, and git.author_name. Source prefilters and finding filters see these string values. The method preserves the scanner's detection policy, component context, and cancellation behavior; deduplication includes the supplied attributes.

Results preserve input order and include finding, outcome, reason and http_status. Outcomes are verified_active, verified_inactive, unavailable, skipped, not_attempted, assumed, locally_derived and invalid_material. An unavailable check is inconclusive; assumed validity and locally derived cryptographic material are not proof of live account access. Provider responses are intentionally omitted from the Python result.

Prepare revocation without knowing the rule ID

For a credential obtained outside Kingfisher, pass the token or its original source text to Revoker.prepare(). An optional provider selects an exact rule ID, exact display name, or family. Omit it to consider the loaded catalog.

import os
from kingfisher_sdk import Revoker, Validator

revoker = Revoker()
plan = revoker.prepare(os.environ["KINGFISHER_SECRET"], provider="github")
print(plan.rule_ids)            # All selected loaded GitHub rule IDs.
print(plan.candidate_rule_ids)  # Detected rules with revocation support.

# Explicit live checks; no revocation occurs here.
results = plan.validate(Validator(timeout=10, concurrency=4))
for result in results:
    print(result.finding.rule_id, result.outcome, result.revocation_ready)

# After inspecting/disambiguating the results, revoke a chosen ready result:
# revoked = revoker.revoke(chosen_result, confirm=True)

Rules.resolve(provider) and prepare(..., provider=provider) use this precedence:

Selector Behavior
Exact loaded ID, e.g. betterleaks.github-pat Selects only that rule, even when other IDs extend it. IDs are case-sensitive at this precedence step.
Exact display name from Rules.metadata() Case-insensitive exact match; duplicate names raise ValueError and require an exact ID.
Family, e.g. github or betterleaks.github Case-insensitive ID prefix followed by ., -, /, or the end of the ID. github matches github-pat and github-oauth, but excludes githubish-token.

Family matching checks both full IDs and IDs with the betterleaks., custom., kingfisher. or veles.secrets/ namespace removed. It is based on ID structure, not semantic provider classification or arbitrary substrings: a compact Veles ID such as slackappconfigaccesstoken requires that selector or its full ID, rather than slack. Unqualified IDs can also select descendants, so use a full exact ID to guarantee one rule. Only loaded rules participate, including the configured confidence level. Rules.resolve() returns sorted IDs and performs no scanning or network work. Unknown selectors raise ValueError; fuzzy suggestions are advisory only. There is no fuzzy execution, glob matching, or CLI legacy-alias resolution. Empty selectors and surrounding whitespace are rejected.

A family considers every selected detector, not every provider API. Preparation uses a reusable shared native scanner over the loaded catalog, then filters findings. rule_ids includes selected rules without revocation support; candidate_rule_ids includes only detected visible rules defining revocation. Unsupported rules and nonmatching token formats are not revocation candidates. plan.validate() checks detected candidates using their complete transitive supporting context, preserving native association of captures, companion values and windows. Supporting rules may be outside the selected family; helpers are not separately checked against provider APIs. Unrelated findings are excluded from the validation batch. It returns candidate ValidationResults in scan order, including inactive/inconclusive results. Multiple matches remain separate results; it never selects the first match or automatically revokes one.

Bare tokens can lack provider context, required companions or a source path needed for detection. Use prepare_from_text(text, path=...) for logical paths, or prepare_from_file(path) to read one real source file. Unlike normal scanning, preparation retains primary matches missing required companions so it can explain which supporting values are needed. It never fabricates context or companion findings. Preparation preserves overlapping catalog candidates and neither reads nor changes the scanner's cross-call deduplication state; other detection filters still apply. Empty candidates mean no revocable match, not proof that the credential is inactive. Empty plans make no provider requests. prepare(data, provider=None, variables=None, timeout=None, cancellation=None) accepts UTF-8 text or bytes and delegates to text preparation. All three methods accept the same selector, explicit variables, deadline and cancellation controls. The total preparation deadline covers native file reading (when applicable), scanning and offline inspection. File reads cannot be preempted; file handles close before return. File preparation reads just one file and does not enumerate directories or extract archives. The logical path argument is not read.

variables supplied to preparation are copied and retained for later validation; they overlay a supplied validator's variables. Captures and associated components retain native precedence, and required detected companions still require source context. A supplied Validator(variables=...) can configure supporting values and enterprise endpoints; plan.validate(validator=None, timeout=None, cancellation=None) uses the normal validator batch deadline and cancellation behavior. The default validator has its own default request limits, independent of the revoker's request timeout.

Plans retain credential and companion findings, omit them from repr, and do not retain original source text. Release plans/results when finished and avoid dataclasses.asdict() for reporting. The commented preparation example stays offline by default; --validate contacts providers and --confirm authorizes revocation only when there is exactly one ready candidate.

Inspect missing inputs and prepare compound credentials

from kingfisher_sdk import Revoker, Validator

revoker = Revoker()
# Preserve paths and nearby AWS access-key IDs/secret keys or other companions.
plan = revoker.prepare_from_file("application.conf", provider="aws")
# For in-memory configuration: revoker.prepare_from_text(text, path="application.conf")
for candidate in plan.candidates:
    print(candidate.rule_id, candidate.validation_supported, candidate.revocation_supported)
    for issue in candidate.input_diagnostics:
        print(issue.stage, issue.code, issue.variable, issue.rule_id, issue.message)

results = plan.validate(Validator(timeout=10, concurrency=4))  # Explicit network work.

plan.candidates contains selected visible detections, including rules without revocation. Each RevocationCandidate exposes its finding, capability flags, input_diagnostics, missing_inputs, and ready_for_validation. This readiness means known validation inputs are present; it does not establish live activity, provider permissions, or successful revocation. candidate_rule_ids includes revocation-capable matches even when they need additional inputs. Plans expose source_path and to_dict(redact=True) for reporting.

Each InputDiagnostic has stage (dependency, validation, revocation), code, variable, supporting rule_id when applicable, and a safe message. Codes include missing_dependency, ambiguous_dependency, missing_variable, redacted_input, and invalid_configuration. Applications can use the names to request an AWS access-key ID, supporting secret, key ID, or endpoint override. Diagnostics never contain credential values, actual endpoints, template source, or parser/provider response bodies. candidate.to_dict() and plan.to_dict() redact finding secrets by default; raw serialization requires redact=False.

Validator.inspect(findings, timeout=None, cancellation=None) provides the same offline diagnostics for an existing complete same-input finding group, preserving order. Validator.with_variables(mapping) clones execution policy and the shared client with explicit variable overrides, leaving the original unchanged. Inspection uses native association windows/defaults and the execution Liquid parser for HTTP/gRPC, multipart and multi-step requests; response-derived variables from earlier steps are not missing caller inputs. Names are advisory lexical diagnostics after a real template-render failure: conditional/fallback expressions can report extra names, and Liquid control-flow tags may lack a specific name. Inspection does not prove every Betterleaks expression branch or provider-specific constraint.

Prepared validation re-inspects with its actual execution variables. Known missing, ambiguous inputs without supported candidate-verification opt-ins, redacted inputs or invalid validation inputs yield skipped results before provider requests. A missing revocation-only input still allows live validation, but keeps revocation_ready false. Validation results expose snapshot input_diagnostics; existing ValidationResult.to_dict() fields stay unchanged.

Use custom revocation rules

Custom Kingfisher YAML rules can define validation: and revocation: using the same schema and engine as built-in rules. Supply the rule files or directories to Rules, then pass that catalog to Revoker. The default builtins=True combines custom and bundled rules; builtins=False loads only your custom catalog. The SDK does not discover custom rules from CLI configuration or environment variables.

The complete synthetic rule defines an authenticated GET /identity validation and a DELETE /token revocation with a 204 status matcher. Its revocation block is:

revocation:
  type: Http
  content:
    request:
      method: DELETE
      url: '{{ ENDPOINT }}/token'
      headers: {Authorization: 'Bearer {{ TOKEN }}'}
      response_matcher:
        - type: StatusMatch
          status: [204]

From a checkout, prepare that custom rule offline:

from kingfisher_sdk import Rules, Revoker, Validator

rules = Rules(["python/examples/demo.yml"], builtins=False)
revoker = Revoker(rules)
plan = revoker.prepare("demo_abcd1234efgh5678", provider="acme.python-demo",
                       variables={"ENDPOINT": "https://credentials.example.com"})
for candidate in plan.candidates:
    print(candidate.rule_id, candidate.revocation_supported, candidate.missing_inputs)

# Optional live steps: configure a trusted service implementing the rule's routes,
# inspect validation results, and explicitly authorize the selected credentials.
# results = plan.validate(Validator())
# statuses = revoker.revoke_many(results, confirm=True)
# Single-result equivalent: revoker.revoke(results[0], confirm=True).

Replace the example rule and endpoint with your service's definitions. The local lifecycle example runs this complete custom-rule flow against a loopback mock, including validation and revocation. As with built-ins, provider accepts a full custom ID, exact display name, or a deterministic ID family: "acme" selects loaded acme.* rules. Preparation and scanning use the supplied catalog; result-based single/batch revocation execute the original custom action and resolved endpoint/companion values retained by validation. The low-level revoker.revoke("acme.python-demo", secret, variables=..., confirm=True) instead looks up that exact ID in the revoker's catalog.

A custom rule must actually define a revocation action; detection alone does not make a credential revocable. Custom Betterleaks TOML can supply detection and validation but does not import a revocation action. Use Kingfisher YAML for custom revocation flows, and inspect Rules.metadata() for each loaded rule's capabilities. See rule authoring and the revocation schema guide.

Both preparation examples accept repeated --rules-path and optional --no-builtins:

uv run --no-sync python python/examples/prepare_revocation.py acme.python-demo --file application.conf --rules-path python/examples/demo.yml --no-builtins
uv run --no-sync python python/examples/batch_revoke.py application.conf --provider acme --rules-path python/examples/demo.yml --no-builtins

These commands remain offline unless --validate or --confirm is supplied. Pass any required endpoint/companion values through KINGFISHER_VARIABLES JSON.

Revoke explicitly

from kingfisher_sdk import Rules, Scanner, Validator, Revoker

rules = Rules()
findings = Scanner(rules).scan_file("application.conf")
validator = Validator(timeout=10, concurrency=4)
revoker = Revoker(rules)

# Validate this input's complete findings, including invisible helpers.
for result in validator.validate(findings):
    if result.finding.visible and result.revocation_ready:
        revoked = revoker.revoke(result, confirm=True)
        print(result.finding.rule_id, revoked.revoked, revoked.http_status)

This performs real revocations. Validation alone never revokes. Result-based revocation requires a verified active result with resolved revocation inputs and confirm=True. It uses the original rule and the exact input snapshot retained by validation, including captures, companion credentials and explicitly supplied endpoint overrides. It does not re-associate components, read credential environment variables, or use a different rule from the revoker's catalog. Secret/variable overrides are rejected for result-based calls. A manually constructed ValidationResult cannot be used for this workflow.

For AWS, the access-key finding's matched secret is the access-key ID. Kingfisher retains its selected invisible secret-key component and applies the catalog's revocation bindings: the secret-access key becomes the revocation secret and the access-key ID becomes AKID. Callers do not implement dependency windows or provider-specific branches. A GCP service-account finding supplies its JSON key; not every GCP or other provider credential type supports revocation.

The scan/validate/revoke example targets AWS, GCP, Hugging Face, GitLab, Slack and GitHub, deduplicates complete credential inputs, and requires --confirm to revoke. Without that flag it still contacts providers for validation, then reports readiness. GitHub's accepted revocation request may complete asynchronously.

Each validation result exposes:

  • credential: a ResolvedCredential snapshot, or None when input binding was not reached or failed (for example, missing/ambiguous/redacted dependencies).
  • credential.secret, credential.variables, and credential.components: the primary secret, validation variables excluding TOKEN, and selected supporting findings (one representative occurrence per dependency), preserving their location/blob/encoding metadata. Variables are read-only; component findings and dictionaries returned by inspection are independent copies.
  • credential.revocation: RevocationInputs(secret, variables), or None for unsupported or unresolved revocation. Variables include trusted endpoint overrides, captures, dependencies and catalog binding overrides.
  • revocation_supported: whether the original rule defines an action; revocation_ready: verified active with resolved action inputs; revocation_reason: a credential-free validation/binding diagnostic when present. Readiness does not guarantee provider permissions or a successful mutation.

Secret-bearing fields are omitted from repr. Both input objects provide to_dict(redact=True); raw serialization requires redact=False. The existing ValidationResult.to_dict() shape is unchanged and does not include retained inputs. Provider bodies are not retained. Holding results now also retains supporting secrets; release the result when finished. dataclasses.asdict() is not a reporting API.

The low-level API remains supported: revoker.revoke(rule_id, secret, variables=..., confirm=True). It accepts an exact rule ID and explicit companion values; it does not infer them from scan results. Use Rules.metadata() to inspect rule capabilities. Variable names are uppercased; avoid keys differing only by case. TOKEN always comes from the explicit secret. Only load trusted rules: revocation sends credentials to their configured URLs, including private addresses. HTTP/multi-step execution, AWS deactivation and GCP service-account key deletion run in-process through the shared Rust engine. HTTP revocation requests are not retried; AWS retries only definitive IAM throttling responses (up to three attempts), never an ambiguous mutation failure.

A RevocationResult contains rule_id, revoked, http_status; it never contains provider bodies. Missing/unsupported rules and invalid configuration raise ValueError or RuntimeError. A timeout or transport failure may occur after the provider applied revocation: inspect provider state before retrying. A mutating HTTP 429 also has an unknown outcome and is never retried; rate limiting does not prove the action was rejected before it was applied. revoke(..., timeout=None, cancellation=None) also accepts an application deadline/cancellation signal and responds to Ctrl-C. Interruption has the same unknown-outcome risk and never triggers retries. Failure messages preserve safe categories such as timeout, connection, HTTP status, response and I/O without including credentials, endpoint URLs or provider bodies.

Exact-ID calls to Revoker.revoke() still require a secret and raise TypeError when it is omitted. Hand-built ValidationResults have no retained native inputs and are skipped as unresolved_inputs in a batch. A completed provider response is retained when interruption arrives during result bookkeeping.

Revoke a batch explicitly

from kingfisher_sdk import Revoker, Validator

revoker = Revoker()
plan = revoker.prepare_from_file("application.conf", provider="github")
results = plan.validate(Validator(timeout=10, concurrency=4))
# Inspect/disambiguate overlapping detector candidates before authorizing all.
statuses = revoker.revoke_many(results, confirm=True, timeout=60)
for status in statuses:
    print(status.index, status.rule_id, status.outcome, status.reason, status.duplicate_of)

This performs real revocations. revoke_many(results, confirm=False, timeout=None, cancellation=None) requires confirm=True, eagerly materializes and type-checks the iterable before mutations, and runs sequentially in input order. It accepts native-backed validated snapshots and skips unsupported, inactive, unresolved or manually constructed results. No scanning or validation occurs inside the batch method. Batch scopes can include results from separately validated input groups because each retains its own resolved snapshot.

Deduplication is scoped to this call and compares the original rule ID, exact revocation definition, secret and complete action variables. Different AWS pairs, endpoint overrides and original action definitions stay distinct. Attempts are recorded before submission, so duplicate entries are not retried even after a failed or unknown action. Different rule IDs remain distinct: batch authorization does not resolve overlapping detector/provider ambiguity. No dedup state persists between calls. Caller-owned generator iteration cannot be preempted.

Every returned BatchRevocationResult corresponds to an original input index and contains rule_id, outcome, optional result (RevocationResult), a safe reason and duplicate_of (the earlier input index). Outcomes are:

Outcome Meaning
revoked The provider result satisfied the existing revocation matcher; asynchronous provider acceptance has the same semantics as single revocation.
not_confirmed A completed provider response did not satisfy that matcher; it is not proof that no mutation occurred.
skipped No request was submitted because the snapshot was not ready or its inputs were rejected before execution.
duplicate The same target was already attempted earlier in this batch, even if its result was unknown.
failed Configuration or a preparatory lookup failed before a mutating request was submitted.
unknown A submitted action failed/interrupted without a confirmed outcome; inspect provider state before retrying.

Failures before mutation yield safe failed statuses; failures after submission yield unknown. Processing continues for other targets without retries. The constructor timeout still bounds each provider operation. The optional timeout bounds the entire batch, including input materialization and queued actions. Total-deadline expiry, cancellation and Ctrl-C stop pending actions and propagate TimeoutError, RuntimeError or KeyboardInterrupt. These interruption exceptions carry .completed (a tuple of credential-free statuses already produced) and .pending_indices (unattempted input indices). An interrupted in-flight request is recorded as unknown in .completed; cancellation cannot roll back a provider mutation. Do not retry unknown actions automatically. Batch statuses are safe to serialize with dataclasses.asdict(); plans and credential snapshots are not.

The batch example prepares files and reports diagnostics offline by default. --validate checks live and --confirm authorizes all ready, unambiguous snapshots while preserving interruption outcomes.

Runnable examples

Run these from a checkout after the local setup below. Each link opens the full program, and the example files are also included in the source distribution.

  • Rule catalog and definition inspection: uv run --no-sync python python/examples/rules.py --with-revocation lists supported actions; pass an exact ID to inspect regex and configured logic.
  • Offline file/directory scanning: uv run --no-sync python python/examples/scan.py ~/example-repo --timeout 5 --unique supports custom rules, confidence, path exclusions, rule-ID globs, entropy and Base64 report filters, redacted JSONL and cooperative Ctrl-C cancellation. Run with --help for all options. Scan errors/timeouts produce a nonzero exit; intentional path/report exclusions do not.
  • Composable filesystem/history/archive scanning: uv run --no-sync python python/examples/inputs.py repo --git-history --archive-depth 2 composes native history with either Python or engine filesystem enumeration. Use --filesystem-enumerator python to choose caller-side file traversal.
  • Native or Python-managed Git history: uv run --no-sync python python/examples/git_history.py repo --enumerator python --ref HEAD adapts caller-managed Git traversal into ScanInput objects; --enumerator engine uses native enumeration and --all-refs expands the selected history scope.
  • Synthetic nested archive scanning: uv run --no-sync python python/examples/archives.py --source bytes --depth 2 shows file/byte inputs, nested depth, budgets and source paths with the local demo.yml rule. Compare --source file --depth 1 to stop at the nested container.
  • Live validation: uv run --no-sync python python/examples/validate.py path/to/file --outcome verified_active supports custom rules, trusted JSON supporting variables, YAML HTTP response limits, request timeout/concurrency/retries and report filters. Scan controls do not cancel validation or revocation.
  • Scan, validate and revoke six providers: uv run --no-sync python python/examples/scan_validate_revoke.py path/to/file --confirm uses only scanned credentials and retained validation inputs; omit --confirm to report validation and readiness without revoking.
  • Explicit live revocation: uv run --no-sync python python/examples/revoke.py EXACT_RULE_ID --confirm reads KINGFISHER_SECRET and optional JSON KINGFISHER_VARIABLES from the environment.
  • Prepare using an exact rule or provider family: uv run --no-sync python python/examples/prepare_revocation.py github reads KINGFISHER_SECRET or --file; accepts custom --rules-path/--no-builtins.
  • Prepare a file, inspect inputs and revoke a batch: uv run --no-sync python python/examples/batch_revoke.py application.conf --provider github accepts custom --rules-path/--no-builtins and optional JSON KINGFISHER_VARIABLES.
  • Complete local lifecycle, using a synthetic rule: uv run --no-sync python python/examples/local_workflow.py. It starts a loopback mock provider, detects a fake credential, proves it active, revokes it, and proves it inactive. No real provider is contacted.

All SDK operations are synchronous. Compilation, scanning, validation and revocation release the GIL; reuse scanners and validators across threads. In an async application use await asyncio.to_thread(validator.validate, findings). Cancelling that Python await does not stop the worker; the configured native deadline still applies. Never assume cancellation cancelled provider revocation.

Build and test locally with uv

Prerequisites: Rust 1.99+, uv, a C/C++ toolchain, platform SDK/linker and curl. Default builds download checksum-verified Vectorscan static archives. See installation for platform prerequisites. Windows uses MSYS2 MINGW64 with x86_64-pc-windows-gnu, or CLANGARM64 with aarch64-pc-windows-gnullvm. MSVC builds are outside the release workflow's supported matrix. Do not relabel an x64 extension wheel as ARM64.

The --locked Maturin commands in this section assume a full source checkout. From that checkout's repository root:

uv sync --locked --no-install-project
uv run --no-sync maturin develop --locked --profile dev
uv run --no-sync python -m pytest python/tests -q
uv run --no-sync python python/examples/local_workflow.py

On Windows, use native CPython with the same architecture as the extension, install the matching MSYS2 C/C++ toolchain, CMake and pkgconf, and select the Rust target explicitly. Run the following in MINGW64 for x64 or CLANGARM64 for ARM64, after creating the uv environment with that native Python:

case "$MSYSTEM" in
  MINGW64) sdk_target=x86_64-pc-windows-gnu; sdk_cc=gcc; sdk_cxx=g++ ;;
  CLANGARM64) sdk_target=aarch64-pc-windows-gnullvm; sdk_cc=clang; sdk_cxx=clang++ ;;
  *) echo 'Use a MINGW64 or CLANGARM64 shell'; exit 1 ;;
esac
rustup target add "$sdk_target"

# Prefer native CPython's stable-ABI import library. MSYS2's libpython import
# archives otherwise can shadow it and link the extension to MSYS2 Python.
native_python_libs="$(uv run --no-sync python -c 'import sys; from pathlib import Path; print(Path(sys.base_prefix) / "libs")')"
test -f "$(cygpath -u "$native_python_libs")/python3.lib" || {
  echo 'Native CPython stable-ABI python3.lib is missing' >&2
  exit 1
}
sdk_link_flags=(-L "native=$native_python_libs" -L "native=$(cygpath -w "$MINGW_PREFIX/lib")")
if [ "$MSYSTEM" = MINGW64 ]; then
  libgcc_path="$(gcc -print-libgcc-file-name)"
  sdk_link_flags+=(-L "native=$(cygpath -w "$(dirname "$libgcc_path")")")
fi
sdk_link_flags+=(-C target-feature=+crt-static -C link-arg=-static)

# Encode each argument separately to preserve Windows paths containing spaces.
sdk_encoded_flags=''
for flag in "${sdk_link_flags[@]}"; do
  sdk_encoded_flags+="${sdk_encoded_flags:+$'\x1f'}$flag"
done
# Scope C/C++ selection to the extension target, not Rust's MSVC host dependencies.
native_target="${sdk_target//-/_}"
env "CC_$native_target=$sdk_cc" "CXX_$native_target=$sdk_cxx" \
  CARGO_ENCODED_RUSTFLAGS="$sdk_encoded_flags" CMAKE_GENERATOR="MinGW Makefiles" \
  uv run --no-sync maturin develop --locked --profile dev --target "$sdk_target"

Keep the same link flags for subsequent wheel builds. They apply only to the command above and do not modify the MSYS2 installation. Keep the MSYS2 toolchain on PATH while testing development builds; the CI release job repairs wheels so installed users do not need that toolchain.

Before running SDK tests from either MSYS2 shell, select the current user's protected temporary directory. MSYS2's shared /tmp permits other users to modify files, so rule-cache trust checks intentionally reject fixtures there:

test_tmp_dir="$(cygpath -u "$LOCALAPPDATA")/Temp"
mkdir -p "$test_tmp_dir"
native_test_tmp="$(cygpath -w "$test_tmp_dir")"
export TMP="$native_test_tmp" TEMP="$native_test_tmp"
unset TMPDIR
uv run --no-sync python -m pytest python/tests -q

The CLI's make windows-test-x64 and make windows-test-arm64 targets select this directory automatically.

--no-sync preserves the explicitly built development extension. Plain uv sync also works, but builds the installable extension with the python-release profile. Python builds use unwind panics so PyO3 can contain Rust panics; the CLI's release profile remains unchanged.

Build and test the actual distributable wheel in a fresh environment:

uv run --no-sync maturin build --locked --profile python-release --out dist-python
uv venv .venv-wheel --python 3.13
uv pip install --python .venv-wheel dist-python/*.whl pytest
uv run --no-project --python .venv-wheel python -m pytest python/tests -q
uv run --no-sync maturin sdist --out dist-python

For Windows wheel builds, use the same CARGO_ENCODED_RUSTFLAGS, target-specific CC/CXX, and CMAKE_GENERATOR settings as the development build above. On PowerShell, expand wheel paths with Get-ChildItem instead of a shell glob. Use a clean output directory per build to avoid installing multiple versions. Local Linux builds may need --compatibility linux for local-only wheels; public Linux wheels are built from vendored Vectorscan source inside manylinux 2.28, because the prebuilt Linux archives require glibc 2.35.

The SDK source archive contains a normalized SDK-only Cargo workspace. Standard package installation refreshes its workspace lock metadata automatically. For a manual --locked Maturin build from an unpacked archive, first refresh metadata with cargo metadata --offline; this prunes CLI-only lock records. Confirm the remaining dependency versions are unchanged before the locked build.

Shared Rust revocation tests:

cargo test --locked -p kingfisher-scanner --features validation validation::revocation

The Python tests cover custom YAML/TOML loading, built-in metadata, byte/file scanning, composable input enumeration, archive formats and limits, Git refs/merges/ shallow/bare history, paths with spaces, concurrency, deduplication, redaction, validation, revocation authorization, compiled cache reuse/opt-out/fallback and the mock provider lifecycle. They do not revoke real credentials. Windows verification requires both architecture jobs to pass; a successful macOS or Linux run does not establish Windows compatibility.

GitHub Actions and PyPI publishing

The Python SDK workflow builds and tests six native wheels on pull requests and standalone test-only manual runs. The release coordinator also calls its build phase for upstream main, CLI/SDK tag pushes, and coordinated manual runs. Reusable SDK and CLI-wheel workflows are build-only and have no OIDC permission. Both PyPI uploads run as ordinary jobs directly in release.yml, with explicit attestations: true; PyPI's id-token: write permission is confined to those post-gate upload jobs. Linux wheels use manylinux 2.28; Windows wheels bundle runtime DLLs using delvewheel and are tested under ordinary CPython outside MSYS2. A separate job builds an sdist, installs it with CPython 3.10, and runs the same tests. Wheel jobs use CPython 3.13. Each wheel job also seeds demo and built-in rule caches. The cache-portability jobs exchange these fixtures across all six targets, verify scans after reuse or recompilation, and assert that the resulting local entry is reused on the next load. Publishing depends on all wheel, source and cache-portability tests succeeding. Each target also requires cache hits from its own exact wheel/build fixture; foreign targets verify safe fallback and subsequent local reuse. Windows artifact transfers explicitly assign the receiving account's SID as owner before loading; downloaded files can otherwise belong to Administrators under an elevated token. Every reuse assertion checks cache_status == "loaded" as well as unchanged entry timestamps, so a bypass cannot masquerade as a hit.

For a manual transfer check, run python python/tests/cache_portability.py seed rule-cache on the producer, copy the directory to the consumer, and run python python/tests/cache_portability.py check rule-cache there using its native SDK. Provision the receiving directory and entries for the consumer account, retaining private permissions rather than preserving the producer's ownership. Add --require-hit for the exact same wheel/engine build on hosts with known compatible CPU features to assert that no recompilation occurs.

Merging a new SDK version to main automatically releases kingfisher-secret-scanner only after the coordinator's normal binary tests/builds, four verified Cargo packages, npm tarball tests, all Python wheel/sdist/cache tests, and six CLI wheel builds succeed at the same SHA. CLI/Python/npm tag pushes also release pending Python SDK/crate versions through that shared gate. CLI v* releases additionally publish kingfisher-bin wheels. PRs and ordinary standalone SDK manual runs are test-only. Manual main publication is opt-in through the coordinator; Python SDK publication remains restricted to mongodb/kingfisher, a pinned commit merged into upstream main, and the protected pypi-sdk environment.

npm still runs its complete tests even unchanged/already published, but npm uploads remain tag-only: the original top-level node-sdk.yml / npm publisher requires an existing npm-v<committed SDK version> tag at the producer's exact SHA. Missing or different-SHA tags skip npm on main/CLI/Python triggers without blocking PyPI or crates; the npm tag's own coordinator cohort can publish it. CI never creates or moves tags, and the existing npmjs trust, npm-v*-only environment and reviewer need no changes. See the npm handoff and retry guidance. Registry uploads are gated but not transactionally atomic; partial failures must recover with the original tested artifacts.

The root pyproject.toml uses a dynamic version from crates/kingfisher-python/Cargo.toml, independently of the CLI version. Prepare a new stable SDK version when Python runtime code, native bindings, shared Rust sources/rules, or SDK build dependencies change, and keep its Cargo.lock entry in sync. The read-only preflight runs before wheel/source jobs:

  • An already published version with unchanged SDK runtime inputs skips publication, but coordinated releases still run its complete build/test matrix to gate the other registries. CLI-only, documentation, tests and examples do not by themselves require an SDK version bump.
  • PR/main runtime changes targeting an existing PyPI version fail with bump SDK version. The guard compares committed versions and meaningful source/build inputs against the push's before SHA or PR base SHA; it also rejects a bump to another already published version. PRs with a new version or only non-runtime changes still run the full test matrix.
  • An ordinary explicit manual publication fails if its version exists, even if that release has no files or only yanked files. Only HTTP 404 means unused; network, authorization and server errors fail closed after bounded retries. Partial-upload recovery instead uses the original verified artifacts through the separate artifact-only SDK recovery mode.

For a read-only local/orchestrator check (Python 3.11+), run:

python3 scripts/check-sdk-release.py --require-new --expected-version 1.7.0

Omit --expected-version to infer the prepared manifest version. The command never builds or writes to the registry. It exits nonzero if the expected version mismatches, the manifest/lock entry is invalid, the version already exists, or PyPI cannot be checked reliably. Without --require-new, it reports existence.

For an explicit manual publication, first merge the prepared version, confirm that HEAD is the current upstream main commit, and use the exact version/SHA:

gh workflow run release.yml --repo mongodb/kingfisher --ref main \
  -f publish=true \
  -f expected_sha="$(git rev-parse HEAD)" \
  -f expected_version=1.7.0

publish defaults to false. Publication requires both safety inputs: the full expected_sha must match the pinned checkout, event SHA and current upstream main tip, and expected_version must match the SDK manifest. Wrong repository, ref, unmerged source, SHA or version fails before native builds. Optional python-v<version> push tags must match the manifest and point into upstream main history.

After all six wheels, sdist and cache-portability tests pass, a read-only plan stages only filenames still missing from PyPI. The coordinator waits for that plan and every other binary/npm/Cargo build gate before its direct SDK upload job; skip-existing handles a concurrent upload after the plan. For a transient upload failure in a run whose publishing workflow is already correct, retry the original failed upload job with its tested artifacts. A later workflow fix cannot repair an old run's snapshot; use artifact-only SDK recovery when eligible. Never rebuild or replace artifacts under a partially published version.

Maintainer release checklist:

  1. Review and prepare the SDK version, synchronize Cargo.lock (and uv.lock only if its resolved dependencies change), regenerate rule provenance as described in publishing guidance, and merge normally. These checks/commands never bump, commit or merge versions for you.
  2. Inspect all six tested wheels and the source artifact in the main-branch run. The protected publish job runs only after all tests and release gates succeed.
  3. Have an authorized PyPI project owner add the matching publisher records below before approving publication. The existing protected pypi-sdk environment allows main and tag patterns v*, python-v*, and npm-v* for coordinated releases; keep its approved policies and reviewers unchanged.

Configure PyPI Trusted Publishers

PyPI does not support reusable workflows as Trusted Publishers. A same-repository/same-ref call does not make the called-workflow identity compatible with the caller's attestation identity. Both upload jobs therefore live directly in release.yml, not in reusable python-sdk.yml or pypi.yml publish phases.

An authorized project owner must manually add these GitHub Trusted Publisher records in each PyPI project's publishing settings:

PyPI project Repository owner Repository Workflow filename Environment
kingfisher-secret-scanner (SDK) mongodb kingfisher release.yml pypi-sdk
kingfisher-bin (CLI) mongodb kingfisher release.yml None — leave empty

Use the filename only, not .github/workflows/release.yml. The CLI project name is kingfisher-bin, as declared in its package metadata; it is not kingfisher or the SDK project. Preserve the CLI job's existing absence of a GitHub environment. Do not widen any GitHub environment policy for this change.

Keep the old SDK python-sdk.yml / pypi-sdk and CLI pypi.yml / no-environment records until the new flow is verified; deleting them afterward is optional cleanup. Committing or merging YAML does not change PyPI account configuration, and a read-only check does not prove that a live publication will succeed. Publishing uses Trusted Publishing without a stored API token, and both direct jobs explicitly keep attestations enabled.

A local TestPyPI rehearsal can use uv publish --publish-url https://test.pypi.org/legacy/ dist-python/* after configuring credentials outside the repository. Linux/Windows public artifacts should come from the repaired CI builds, not an arbitrary local platform tag. Packaging follows the Maturin mixed-project layout.

Artifact-only SDK recovery

Use this manual, opt-in mode only to publish retained, already tested SDK artifacts from a verified original coordinator run. It runs in the same release.yml and uses the same direct SDK publisher, protected pypi-sdk environment, attestation setting and publication concurrency lock. It performs no Rust, wheel or binary builds and no crates, npm, CLI PyPI, Docker or GitHub-release publication. It verifies the original complete cohort rather than replacing its evidence with new builds.

For example, run 43954600383 at producer SHA 84b8733639e20ff0469186f73a011d1f84f7196f passed the coordinated gates, all six SDK wheels, sdist and cache-portability tests; crates published. Its first SDK upload was rejected with HTTP 400 because the OIDC publisher identity was python-sdk.yml while the attestation certificate's Build Config URI identified release.yml. The old CLI uploader explicitly used attestations: false; this SDK-specific HTTP 400 is not evidence that the CLI had the same failure. Changing PyPI settings alone cannot fix the old SDK run, and rerunning it still executes its broken workflow snapshot, not the reviewed code now on main.

Plan the main-run concurrency: merging the repair still triggers the ordinary full-cohort automatic main run. SDK-only dispatch shares its concurrency slot and waits behind it. For original-artifact recovery, stop only that new automatic main run before it builds/publishes, then dispatch sdk_only. Never cancel/rerun the pinned original failed producer or let a new ordinary build publish different bytes under the same SDK version first. Do not disable Actions, change account/branch policies or weaken gates; only recovery itself is build-free.

After the repaired workflow and validator are merged and the matching SDK PyPI publisher has been added, use a clean checkout of current, reviewed upstream main. Independently verify the original run attempt and exact retained python-sdk-pending artifact ID; do not guess them. The dispatch inputs distinguish these two source identities:

Input Meaning
release_run_id Exact original producer run, not a newer build
release_run_attempt Verified original producer attempt
artifact_id Immutable ID of that producer's python-sdk-pending artifact
producer_sha Original source SHA that built and tested those distributions
expected_sha Current reviewed main/recovery-workflow SHA, pinned independently of producer_sha
expected_version Original SDK version to recover, such as 1.6.4
sdk_only=true, publish=true Explicit artifact-only publication authorization; sdk_only defaults to false

The two SHA pins identify separate roles, not a requirement that their values differ. They differ for this CI-fix recovery; they may match when current main is unchanged.

Read-only inspection of that producer identified attempt 1, pending artifact 14273355973, size 110898976 bytes, digest sha256:1752a6dea7eb8900c03e42ac2246c6917f93b674f12e744dfeb9ad4feca735e2, and expiry 2027-02-14 20:54:34 UTC. Recheck that evidence immediately before recovery; these recorded values do not extend retention or authorize a dispatch.

gh workflow run release.yml --repo mongodb/kingfisher --ref main \
  -f publish=true -f sdk_only=true \
  -f release_run_id=43954600383 \
  -f release_run_attempt=1 \
  -f artifact_id=14273355973 \
  -f producer_sha=84b8733639e20ff0469186f73a011d1f84f7196f \
  -f expected_sha="$(git rev-parse HEAD)" \
  -f expected_version=1.6.4

Leave crates_only false. A read-only validator requires:

  • The upstream producer workflow/ref/SHA/attempt and successful latest-effective complete-cohort gates, SDK builds/tests and publication plan. A newer failure, skip or pending result cannot fall back to an older success.
  • The exact immutable pending artifact, whose API metadata proves its upstream repository/run/SHA, digest, unexpired retention and creation within the selected successful SDK plan job; the downloaded contents must be the exact distributions.
  • The producer as an ancestor of current reviewed main, with the same SDK manifest version. Permitted drift is limited to the three publication workflows (release.yml, python-sdk.yml, pypi.yml), the maintainer release runbook, recovery validator, release-source authorization guard, crate publication/staging helper, allowlisted CI test scripts, and Markdown documentation/generated docs. Runtime, SDK, manifest, lockfile, rules and other build inputs cannot change.

Do not broaden the source policy to slip unrelated changes into recovery, and do not check out the old producer under the new workflow's publishing identity. These checks run again after protected environment approval, before authentication/upload; inspect their evidence before approving pypi-sdk. After upload, recovery verifies every staged filename and exact SHA-256 against PyPI, with bounded read-only visibility retries, so skip-existing cannot hide a concurrent different-byte upload.

The artifact must still be retained and unexpired; missing, expired, changed or mismatched evidence fails closed. Do not substitute another run, rebuild, repackage or replace distributions. A CI-only correction does not itself require an SDK version bump when no files were ever published. For a partial upload, recover only with the exact original tested artifacts; published immutable filenames and bytes must remain unchanged. SDK/runtime changes instead need a normal new-version release with the full build/test cohort. Finally, verify the exact PyPI version, file hashes and attestations and test a fresh consumer installation; neither the workflow change nor these instructions claim that publication has been tested live.

Existing CLI wheel distribution

The following commands package kingfisher-bin, not the SDK.

Build prerequisites

  1. Build the Kingfisher binary for your target platform (see INSTALLATION.md for make targets).
  2. Install uv; the commands below supply the Python build tooling in an isolated environment.

Build a wheel

Run the helper script from the repo root:

uv run --no-project --with build scripts/build-pypi-wheel.sh \
  --binary ./path/to/kingfisher \
  --version 1.2.3 \
  --plat-name manylinux_2_17_x86_64

For Windows, pass the .exe binary and a Windows platform tag:

uv run --no-project --with build scripts/build-pypi-wheel.sh \
  --binary .\\path\\to\\kingfisher.exe \
  --version 1.2.3 \
  --plat-name win_amd64

If you only build a Windows x64 binary, you can still ship a win_arm64 wheel using the same executable (it runs under emulation on ARM64 Windows):

uv run --no-project --with build scripts/build-pypi-wheel.sh \
  --binary .\\path\\to\\kingfisher.exe \
  --version 1.2.3 \
  --plat-name win_arm64

The resulting wheel will be placed in dist-pypi/ by default.

Test locally

uv venv .venv-cli
uv pip install --python .venv-cli dist-pypi/kingfisher_bin-*.whl
uv run --no-project --python .venv-cli kingfisher --help

Publish

Upload the wheels to PyPI using twine (or your preferred tool):

uvx twine upload dist-pypi/*

The pypi-wheels workflow is build-only:

  1. It builds six platform-tagged wheels from that same run's exact binary artifacts.
  2. The coordinator requires the complete shared release gate; CLI-tag runs also wait for successful GitHub release asset publication.
  3. An ordinary top-level job in release.yml uploads the staged wheels using Trusted Publishing (OIDC), without rebuilding, with explicit attestations: true.

Ordinary standalone manual runs build/test only and receive no OIDC permission. An authorized owner must add the kingfisher-bin PyPI Trusted Publisher for owner mongodb, repository kingfisher, workflow release.yml, and no environment. This is distinct from the SDK's release.yml / pypi-sdk record. Keep legacy records until the new flow is verified; see publisher setup. No API token is required once Trusted Publishing is configured.

If you do not use Trusted Publishing, generate a PyPI API token and provide it to twine (for example via TWINE_USERNAME=__token__ and TWINE_PASSWORD=<pypi-token>).