engine.oracle

Load a Python oracle and return a candidate verification callable.

An oracle can export verify(candidate) or a factory named build_oracle(config) that returns an object with a verify method. The loader prefers the factory if both exports exist.

Loading executes user-supplied Python with the caller’s privileges. The loader checks file and directory permissions and logs the loaded file’s SHA-256 digest at warning level.

class Oracle[source]

Bases: Protocol

Stateful oracle shape produced by build_oracle(config).

verify(candidate)[source]
Parameters:

candidate (bytes)

Return type:

bool

__init__(*args, **kwargs)
exception OracleLoadError[source]

Bases: RuntimeError

Raised when a user oracle file cannot be loaded or validated.

exception OracleBuildError[source]

Bases: OracleLoadError

The oracle imported/built and raised a NORMAL, reproducible exception.

The benign half of a sandbox rejection, split out so a caller can tell “this oracle disagrees with the config it was handed” (a user error the user can fix, e.g. a Shape-2 oracle probed before it has been configured) apart from “this oracle hung or was killed by a resource limit” (a hostile outcome that must never reach an in-process import).

A subclass, not a replacement: every existing except OracleLoadError still catches it and validate_oracle_sandboxed() keeps its published behaviour and message. Only callers that explicitly want the distinction — and they must opt in by naming this class — see any difference. Anything that raises a bare OracleLoadError therefore still reads as “not known to be benign”, which is the safe default for a security gate.

RESERVED_CONFIG_TABLE = 'memdiver'

MemDiver’s own automation table inside an oracle’s TOML config.

A bundled example declares its autofill rules and cipher requirement under [memdiver] in the same file as the oracle’s config, so the two can never be shipped out of sync. It is OUR metadata, not the oracle’s, and is dropped in _oracle_visible_config() before any user code sees it – an oracle that validates its config strictly would otherwise reject a key it never declared, and only on the surfaces that read the file.

load_oracle_config(path)[source]

Load an optional TOML config file into a plain dict.

Parameters:

path (Path | None)

Return type:

dict[str, Any]

validate_oracle_sandboxed(path, config=None, *, timeout_s=_SANDBOX_TIMEOUT_S, cpu_s=_SANDBOX_CPU_S, mem_bytes=_SANDBOX_MEM_BYTES)[source]

Validate an oracle’s load path in a sandboxed subprocess (strict).

Replays import + build_oracle(config) (never verify()) inside a spawned child under a wall-clock timeout_s plus best-effort CPU/memory caps, then returns None if the oracle loaded cleanly. Raises OracleLoadError if the oracle hangs (wall-clock timeout), is killed by a resource limit / OOM (RLIMIT_CPU/RLIMIT_AS → SIGKILL/SIGXCPU), or raises a normal exception during import/build.

The normal-exception case raises the OracleBuildError subclass, so a caller that wants the lenient policy can catch just that one and let the hostile outcomes through (assert_oracle_not_hostile() is that policy pre-packaged). Every existing caller, which catches OracleLoadError, is unaffected.

Spawn context is used for cross-platform + macOS safety; the target is a module-level function so it pickles cleanly.

Parameters:
Return type:

None

assert_oracle_not_hostile(path, config=None, *, timeout_s=_SANDBOX_TIMEOUT_S, cpu_s=_SANDBOX_CPU_S, mem_bytes=_SANDBOX_MEM_BYTES)[source]

Probe an oracle’s load path and block only a hang or a crash (lenient).

The containment half of validate_oracle_sandboxed(), exposed as a public policy so callers outside this module (notably the API’s oracle registry) never have to reach into the private _sandbox_probe(). Same spawned, resource-capped child, same “never calls verify()” guarantee — only the verdict differs:

  • hang / crash -> OracleLoadError. These are the outcomes that would damage the host: an infinite loop at import or inside build_oracle, or a RLIMIT_AS/RLIMIT_CPU kill. They must never reach an in-process import.

  • err -> allowed through. A reproducible exception means the oracle merely disagrees with the config it was handed, which is a user problem, not a hostile one — and it is re-checked, strictly and with the real config, at the point of user intent.

This is exactly the policy load_oracle()’s own guard has always applied (see its docstring); naming it makes the upload-time / arm-time split in memdiver.api.services.oracle_registry legible, and keeps the strict policy of validate_oracle_sandboxed() untouched for its existing callers (engine.brute_force runs the strict one before any worker loads the oracle).

Implemented by narrowing the strict validator rather than by classifying the probe result a second time, so the two policies are one policy by construction and cannot drift apart.

Parameters:
Return type:

None

load_oracle(path, config=None, *, sandbox=True, audited=False)[source]

Load a user oracle script and return a flat verify(bytes) -> bool.

Auto-detects Shape 1 (def verify(candidate)) vs Shape 2 (def build_oracle(config) -> Oracle). Shape 2 is preferred when the oracle needs to cache KDF state or open a network connection once; Shape 1 is fine for hot-path-only verifiers.

Raises OracleLoadError on missing files, unsafe permissions, import failures, or missing/invalid exports.

sandbox (default True) first replays the load path (import + build_oracle) in a resource-capped subprocess under a wall-clock timeout, rejecting a hanging/OOMing oracle BEFORE it runs in-process. A reproducible import/build exception is deliberately allowed to fall through to the in-process importer below, which yields the readable failed to import / raw-exception diagnostics; only a hang or a resource-limit/crash blocks here. Pass sandbox=False for already-validated re-loads (e.g. per-worker loads in the brute-force pool) so they don’t each pay for a redundant validation.

audited=True (a re-load of a file whose load the caller already logged, e.g. the brute-force pool workers) logs the fingerprint at DEBUG instead of WARNING, so one run prints the audit line once, not once per worker.

Parameters:
Return type:

Callable[[bytes], bool]