Skip to content

~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.

test(security): pin DB-adjacent resistance properties (backup posture, credential-store scope, KDF floor) (#6683)

LearningCircuit626684a5297d
diff --git a/.github/workflows/docker-tests.yml b/.github/workflows/docker-tests.yml
index df62f93d3e..fdccc246cf 100644
--- a/.github/workflows/docker-tests.yml
+++ b/.github/workflows/docker-tests.yml
@@ -367,9 +367,11 @@ jobs:
#
# Modules this lane collects at the time of writing:
# serial tests/security/test_db_connection_umask_perms.py
+ # tests/security/test_db_adjacent_backup_posture.py
# nonroot tests/security/test_db_connection_umask_perms.py
# tests/security/test_db_connection_create_hostile_dir.py
# tests/security/test_db_connection_readonly_hostile_fs.py
+ # tests/security/test_db_adjacent_backup_posture.py
# DELETING ALL OF THEM EMPTIES THE LANE: pytest exits 5 ("no tests
# collected") and this step fails hard -- the same class of breakage
# as #4411, which is why the security-tests.yml comment stopped
diff --git a/.github/workflows/security-tests.yml b/.github/workflows/security-tests.yml
index b6a793f817..a9e3039e58 100644
--- a/.github/workflows/security-tests.yml
+++ b/.github/workflows/security-tests.yml
@@ -124,6 +124,7 @@ jobs:
#
# Modules this lane collects at the time of writing:
# serial tests/security/test_db_connection_umask_perms.py
+ # serial tests/security/test_db_adjacent_backup_posture.py
# DELETING THEM ALL EMPTIES THE LANE: pytest exits 5 ("no tests
# collected") and this step fails hard -- the same #4411 breakage
# the step above's comment describes. If the last serial-marked
diff --git a/tests/security/test_db_adjacent_backup_posture.py b/tests/security/test_db_adjacent_backup_posture.py
new file mode 100644
index 0000000000..57dc96fe6e
--- /dev/null
+++ b/tests/security/test_db_adjacent_backup_posture.py
@@ -0,0 +1,282 @@
+"""Backup artifact permission posture and salt-stranding (round-9, C2+C5).
+
+C2 attack class: sensitive-file permission window during atomic-replace
+writes. ``BackupService._create_backup_impl`` exports into a ``.tmp``
+sibling (``backup_service.py:245-347``) that is chmod'd 0600 only AFTER
+export+verify (line 340) and then atomically renamed. Between ATTACH and
+chmod, the ``.tmp`` carries umask-default permissions (0644 under the
+realistic umasks probed here) -- a window in which a LOCAL same-host
+reader can observe the file. These tests pin, with a real SQLCipher
+engine, that the window is ciphertext-only and bounded:
+
+* every mid-flight ``.tmp`` sample is group/world read-only at worst
+ (never writable) under realistic umasks 022/002;
+* no mid-flight sample ever carries the plaintext SQLite magic header --
+ the content observable in the window is SQLCipher ciphertext under the
+ same derived key as the final artifact (a metadata window: existence,
+ size and mode leak; content does not);
+* the FINAL artifact is exactly 0600, the per-user backups directory is
+ exactly 0700 (enforced by ``get_user_backup_directory``, paths.py:214-
+ 221), and no ``.tmp`` survives the operation.
+
+This is a HOLD-with-documentation classification: ciphertext-only content
+plus local-reader tier. The exposure would only escalate if plaintext
+ever appeared in the ``.tmp`` -- pinned against here by the header check.
+
+C5 attack class: key-material stranding (availability, not disclosure).
+Backups store no salt of their own; verification explicitly re-derives
+the key via the SOURCE database's ``.salt`` (``backup_service.py:408-
+410``, ``set_sqlcipher_key(..., db_path=self.db_path)``). Deleting the
+source ``.salt`` strands every backup. The pinned property is that
+stranding fails CLEANLY: verification returns False (never a false
+success), the backup file is left byte-identical, and no partial
+artifacts appear. (A direct reopen of the backup file -- not going
+through ``_verify_backup`` -- fails the same way regardless of the
+source salt: the backup has no ``.salt`` file next to it, so key
+derivation always falls back to the legacy shared salt, which
+SQLCipher reports as "file is not a database".)
+
+Real engines throughout; whole module ``serial`` (mutates the
+process-global umask) and ``nonroot`` (permission-bit assertions no-op
+under root), same conventions as
+``tests/security/test_db_connection_umask_perms.py``.
+"""
+
+import hashlib
+import os
+import stat
+import threading
+import time
+from pathlib import Path
+
+import pytest
+
+# Module-level gate: without a working SQLCipher build every test below
+# is a no-op; skipping at import time makes that one visible signal.
+pytest.importorskip("sqlcipher3", reason="requires SQLCipher (encrypted mode)")
+
+pytestmark = [pytest.mark.serial, pytest.mark.nonroot]
+
+REALISTIC_UMASKS = [0o022, 0o002]
+
+SQLITE_MAGIC = b"SQLite format 3\x00"
+
+# Rows x ~1KB: enough export time for the poller to reliably sample the
+# mid-flight .tmp without making the test slow (~10MB source).
+_SOURCE_ROWS = 10000
+_ROW_PAYLOAD = "x" * 1000
+
+
+def hunt_env(tmp_path, monkeypatch):
+ """Isolated data dir with the sanctioned fast-KDF test knob."""
+ monkeypatch.setenv("LDR_DATA_DIR", str(tmp_path))
+ monkeypatch.setenv("LDR_DB_CONFIG_KDF_ITERATIONS", "1000")
+ return tmp_path
+
+
+def _create_source_db(username: str, password: str) -> Path:
+ """Create a real salted SQLCipher source DB at its true service path."""
+ from local_deep_research.config.paths import (
+ get_encrypted_database_path,
+ get_user_database_filename,
+ )
+ from local_deep_research.database.sqlcipher_utils import (
+ create_database_salt,
+ create_sqlcipher_connection,
+ )
+
+ db_path = get_encrypted_database_path() / get_user_database_filename(
+ username
+ )
+ create_database_salt(db_path)
+ conn = create_sqlcipher_connection(
+ str(db_path), password, creation_mode=True
+ )
+ cursor = conn.cursor()
+ cursor.execute("CREATE TABLE blob (id INTEGER PRIMARY KEY, data TEXT)")
+ cursor.executemany(
+ "INSERT INTO blob (data) VALUES (?)",
+ [(_ROW_PAYLOAD,) for _ in range(_SOURCE_ROWS)],
+ )
+ conn.commit()
+ cursor.close()
+ conn.close()
+ return db_path
+
+
+def _digest(path: Path) -> str:
+ return hashlib.sha256(path.read_bytes()).hexdigest()
+
+
+class TestBackupTmpPermissionWindow:
+ """C2: mid-flight ``.tmp`` posture and final-artifact hardening."""
+
+ @pytest.mark.parametrize("umask", REALISTIC_UMASKS)
+ def test_tmp_window_ciphertext_only_and_final_owner_only(
+ self, hunt_env, umask
+ ):
+ """Under realistic umasks the ``.tmp`` is never group/world
+ WRITABLE mid-flight, never exposes a plaintext SQLite header, the
+ final backup is exactly 0600, the backups dir exactly 0700, and
+ no ``.tmp`` survives."""
+ if os.geteuid() == 0:
+ pytest.skip("permission bits are not enforced for root")
+
+ from local_deep_research.database.backup.backup_service import (
+ BackupService,
+ )
+
+ username = f"c2probe_{umask:o}"
+ password = "C2Probe-Pw-1!" # noqa: S105
+ _create_source_db(username, password)
+
+ service = BackupService(username=username, password=password)
+ backup_dir = service.backup_dir
+ observed: list[tuple[int, bytes]] = []
+ stop = threading.Event()
+
+ def poll():
+ while not stop.is_set():
+ for entry in os.scandir(backup_dir):
+ if entry.name.endswith(".tmp"):
+ try:
+ mode = stat.S_IMODE(entry.stat().st_mode)
+ with open(entry.path, "rb") as fh:
+ head = fh.read(len(SQLITE_MAGIC))
+ observed.append((mode, head))
+ except (FileNotFoundError, PermissionError):
+ pass
+ time.sleep(0.001)
+
+ original = os.umask(umask)
+ try:
+ poller = threading.Thread(target=poll)
+ poller.start()
+ try:
+ result = service.create_backup(force=True)
+ finally:
+ stop.set()
+ poller.join(timeout=5)
+ finally:
+ os.umask(original)
+
+ assert result.success, f"backup failed: {result.error}"
+ assert result.backup_path is not None
+
+ # The window was actually observed (fail loud if the poll never
+ # saw the .tmp -- the assertions below would silently vacate).
+ assert observed, (
+ "poller never sampled the .tmp; widen the export or fix the test"
+ )
+
+ # Window posture: never group/world-writable under this umask...
+ for mode, _ in observed:
+ assert mode & 0o022 == 0, (
+ f"mid-flight .tmp is group/world-writable ({oct(mode)}) "
+ f"under umask {umask:o}"
+ )
+ # ...and never plaintext: no sample carries the SQLite magic.
+ for _, head in observed:
+ assert head != SQLITE_MAGIC, (
+ "mid-flight .tmp exposes a plaintext SQLite header -- the "
+ "documented ciphertext-only window assumption is FALSE"
+ )
+
+ # Final posture.
+ assert stat.S_IMODE(os.stat(result.backup_path).st_mode) == 0o600, (
+ "final backup is not exactly owner-only"
+ )
+ assert stat.S_IMODE(os.stat(backup_dir).st_mode) == 0o700, (
+ "per-user backups directory is not exactly 0o700"
+ )
+ assert list(backup_dir.glob("*.tmp")) == [], "orphaned .tmp files"
+
+ def test_final_artifact_owner_only_under_default_umask(self, hunt_env):
+ """Whatever the runner's own umask, the final backup lands exactly
+ 0600 (explicit chmod after verify -- not umask-masked) in a 0700
+ directory."""
+ if os.geteuid() == 0:
+ pytest.skip("permission bits are not enforced for root")
+
+ from local_deep_research.database.backup.backup_service import (
+ BackupService,
+ )
+
+ username = "c2default"
+ password = "C2Default-Pw-1!" # noqa: S105
+ _create_source_db(username, password)
+
+ service = BackupService(username=username, password=password)
+ result = service.create_backup(force=True)
+
+ assert result.success, f"backup failed: {result.error}"
+ assert result.backup_path is not None
+ assert stat.S_IMODE(os.stat(result.backup_path).st_mode) == 0o600, (
+ "final backup mode depends on umask -- explicit chmod regressed"
+ )
+ assert stat.S_IMODE(os.stat(service.backup_dir).st_mode) == 0o700
+
+
+class TestBackupSaltStranding:
+ """C5: deleting the source ``.salt`` strands backups -- cleanly."""
+
+ def test_missing_source_salt_fails_verification_cleanly(self, hunt_env):
+ """With a valid backup present, deleting the source ``.salt``
+ makes verification fail (no false success), leaves the backup
+ byte-identical, creates no partial artifacts, and reopening the
+ stranded backup raises instead of silently succeeding."""
+ from local_deep_research.database.backup.backup_service import (
+ BackupService,
+ )
+ from local_deep_research.database.sqlcipher_utils import (
+ create_sqlcipher_connection,
+ )
+
+ username = "c5strand"
+ password = "C5Strand-Pw-1!" # noqa: S105
+ db_path = _create_source_db(username, password)
+ salt_path = db_path.with_name(db_path.name + ".salt")
+ assert salt_path.exists(), "fixture: source DB must be salted (v2)"
+
+ service = BackupService(username=username, password=password)
+ result = service.create_backup(force=True)
+ assert result.success, f"backup failed: {result.error}"
+ backup_path = result.backup_path
+ assert backup_path is not None
+
+ # Positive control: the backup verifies while the salt exists.
+ assert service._verify_backup(backup_path) is True
+
+ before_digest = _digest(backup_path)
+ artifacts_before = sorted(p.name for p in service.backup_dir.iterdir())
+
+ salt_path.unlink()
+
+ # Stranded verification fails -- never a false success.
+ assert service._verify_backup(backup_path) is False, (
+ "verification succeeded after the source salt was deleted -- "
+ "false success on a stranded backup"
+ )
+
+ # Clean failure: backup untouched, no partial artifacts.
+ assert backup_path.exists()
+ assert _digest(backup_path) == before_digest, (
+ "failed verification mutated the backup file"
+ )
+ assert (
+ sorted(p.name for p in service.backup_dir.iterdir())
+ == artifacts_before
+ ), "failed verification left partial artifacts"
+
+ # Reopening the stranded backup fails loudly -- but this is
+ # independent of the source salt being deleted: create_sqlcipher_
+ # connection derives the salt from backup_path itself, and the
+ # backup never had a .salt file next to it, so it always falls
+ # back to the legacy shared salt, deriving a wrong key. SQLCipher
+ # reports that as a database-format error rather than a silent
+ # success. (The assertion that actually depends on the deleted
+ # source salt is the `_verify_backup(...) is False` check above,
+ # which explicitly re-derives the key via self.db_path.)
+ with pytest.raises(Exception, match="file is not a database"):
+ create_sqlcipher_connection(str(backup_path), password)
diff --git a/tests/security/test_db_adjacent_credential_store_scope.py b/tests/security/test_db_adjacent_credential_store_scope.py
new file mode 100644
index 0000000000..09bc218a08
--- /dev/null
+++ b/tests/security/test_db_adjacent_credential_store_scope.py
@@ -0,0 +1,121 @@
+"""Store-level scoping of ``get_any_session_password`` (round-9, C3).
+
+Attack class: in-process username-confusion / cross-tenant credential
+scavenging. ``get_any_session_password(username)`` is a username-wide
+fallback accessor (``database/session_passwords.py:84``) used by FastAPI
+routes where no Flask session id is available. Its blast radius is decided
+entirely by the store's key scoping: entries are keyed by the exact
+``(username, session_id)`` tuple, so a password stored for one account must
+never be resolvable under another account's username -- not for a wholly
+different user, not for a prefix-colliding username ("alice" vs "alice2"),
+not after TTL expiry, and not after the user's sessions are cleared.
+
+These tests stay at the STORE level on purpose: the ``require_auth`` web
+gate that fronts real callers is another layer's test surface. The HTTP
+replay boundary is not in scope here; what is in scope is that the store
+itself refuses every shape of wrong-username retrieval.
+
+Related upper-layer context (do not duplicate here):
+``tests/security/test_sqlcipher_key_lifecycle.py`` pins the credential
+LIFETIME findings around this accessor; this file pins only the scoping
+primitives.
+"""
+
+from local_deep_research.database.session_passwords import SessionPasswordStore
+
+
+class TestGetAnySessionPasswordScoping:
+ """Username scoping of the username-wide password fallback accessor."""
+
+ def test_no_stored_sessions_returns_none(self):
+ """A username with nothing stored -- the attacker-username shape --
+ gets ``None``, not a password scavenged from another user's
+ sessions."""
+ store = SessionPasswordStore(ttl_hours=1)
+ store.store_session_password("victim", "s1", "victim-pw") # noqa: S105
+
+ assert store.get_any_session_password("attacker") is None
+
+ def test_cross_username_isolation(self):
+ """Storing ``(alice, s1)`` never yields a password for ``bob``, in
+ either direction, even with both users live in the same store."""
+ store = SessionPasswordStore(ttl_hours=1)
+ store.store_session_password("alice", "s1", "alice-pw") # noqa: S105
+
+ assert store.get_any_session_password("bob") is None
+
+ store.store_session_password("bob", "s2", "bob-pw") # noqa: S105
+ assert store.get_any_session_password("alice") == "alice-pw"
+ assert store.get_any_session_password("bob") == "bob-pw"
+
+ def test_prefix_usernames_do_not_collide(self):
+ """Tuple-keyed exact matching: "alice2" is a different principal
+ from "alice" even though it shares a prefix, for both the
+ storage and the retrieval direction."""
+ store = SessionPasswordStore(ttl_hours=1)
+ store.store_session_password("alice", "s1", "alice-pw") # noqa: S105
+ store.store_session_password("alice2", "s1", "alice2-pw") # noqa: S105
+
+ assert store.get_any_session_password("alice") == "alice-pw"
+ assert store.get_any_session_password("alice2") == "alice2-pw"
+
+ def test_prefix_collision_attacker_direction_yields_none(self):
+ """Attacker direction of the prefix case: with only ``alice2``'s
+ entry in the store, ``alice`` (a mere prefix of the other
+ principal) must get ``None`` -- a weakened username match
+ (prefix or substring) must not let one account scavenge a
+ password stored under a prefix-colliding username."""
+ store = SessionPasswordStore(ttl_hours=1)
+ store.store_session_password("alice2", "s1", "alice2-pw") # noqa: S105
+
+ assert store.get_any_session_password("alice") is None
+
+ def test_expired_ttl_entries_yield_none_even_when_present(self):
+ """An entry past its ``expires_at`` yields ``None`` even though it
+ is still physically present in the store, and the scan cleans it
+ up on the way past (``session_passwords.py:104-108``)."""
+ import time
+
+ store = SessionPasswordStore(ttl_hours=1)
+ store.store_session_password("alice", "s1", "alice-pw") # noqa: S105
+ # Age the entry past its TTL without waiting for real time.
+ store._store[("alice", "s1")]["expires_at"] = time.time() - 1
+
+ assert store.get_any_session_password("alice") is None
+ assert ("alice", "s1") not in store._store
+
+ def test_mixed_expired_and_live_sessions_return_the_live_one(self):
+ """With one expired and one live session for the same user, the
+ scan skips the expired entry and returns the live password --
+ expiry must not be bypassed by having a stale entry linger."""
+ import time
+
+ store = SessionPasswordStore(ttl_hours=1)
+ store.store_session_password("alice", "stale", "stale-pw") # noqa: S105
+ store.store_session_password("alice", "live", "live-pw") # noqa: S105
+ store._store[("alice", "stale")]["expires_at"] = time.time() - 1
+
+ assert store.get_any_session_password("alice") == "live-pw"
+ assert ("alice", "stale") not in store._store
+
+ def test_clearing_users_sessions_makes_subsequent_get_any_none(self):
+ """After ``clear_all_for_user(alice)`` (the idle-sweeper/logout
+ teardown path), no password is resolvable for alice -- while
+ another user's entries survive untouched."""
+ store = SessionPasswordStore(ttl_hours=1)
+ store.store_session_password("alice", "s1", "alice-pw") # noqa: S105
+ store.store_session_password("bob", "s3", "bob-pw") # noqa: S105
+
+ store.clear_all_for_user("alice")
+
+ assert store.get_any_session_password("alice") is None
+ assert store.get_any_session_password("bob") == "bob-pw"
+
+ def test_positive_control_live_session_returns_password(self):
+ """Positive control for every negative above: a genuinely live
+ session does satisfy the accessor, for the right username only."""
+ store = SessionPasswordStore(ttl_hours=1)
+ store.store_session_password("alice", "s1", "alice-pw") # noqa: S105
+ store.store_session_password("alice", "s2", "alice-pw") # noqa: S105
+
+ assert store.get_any_session_password("alice") == "alice-pw"
diff --git a/tests/security/test_db_adjacent_kdf_floor.py b/tests/security/test_db_adjacent_kdf_floor.py
new file mode 100644
index 0000000000..3815c937af
--- /dev/null
+++ b/tests/security/test_db_adjacent_kdf_floor.py
@@ -0,0 +1,181 @@
+"""Creation-floor semantics of the effective SQLCipher KDF (round-9, C4).
+
+Attack class: at-rest work-factor downgrade via environment. The KDF
+iteration count is derived from the environment at open time
+(``database/sqlcipher_utils.py:437-448``) and is NOT stored with the
+database, so a hostile or fat-fingered ``LDR_DB_CONFIG_KDF_ITERATIONS``
+(or its deprecated ``LDR_DB_KDF_ITERATIONS`` alias) is the only lever an
+operator-side misconfiguration has against key-derivation strength.
+
+The clamp is a three-layer pipeline, and this file pins the END-TO-END
+semantics of ``get_sqlcipher_settings()["kdf_iterations"]``:
+
+1. Registry (``settings/env_definitions/db_config.py:70-77``): integer
+ values outside ``[1000, 1000000]`` raise a ``ValueError`` subclass
+ (``EnvironmentValueRangeError``) that ``SettingsRegistry.get`` catches,
+ substituting the caller default (256000). Non-integers like ``abc``
+ never reach that raise -- ``IntegerSetting._convert_value``
+ (``env_settings.py:167-175``) catches the ``int()`` conversion
+ failure itself and returns the setting's default directly.
+2. Floor window (``sqlcipher_utils.py:441-448``): values outside
+ ``[floor, 1000000]`` are REPLACED with the 256000 default -- the code
+ resets to default, it does NOT clamp up to the floor.
+3. Floor selection (``sqlcipher_utils.py:370-392``): 100000 in
+ production; 1 only under ``PYTEST_CURRENT_TEST`` presence or a
+ truthy ``LDR_TEST_MODE`` (explicitly parsed -- ``0``/``false`` do not
+ relax).
+
+Recon correction (round-9 triage guessed "env=1 -> the 100000 floor"):
+empirically, ``LDR_DB_CONFIG_KDF_ITERATIONS=1`` without test markers
+yields **256000**, not 100000 -- layer 1 rejects 1 (below the registry
+minimum of 1000) before the floor window ever sees it, and sub-floor
+in-registry values (e.g. 50000) hit layer 2's reset-to-default. Either
+way the security invariant below holds, which is what these tests pin:
+
+ without test-mode markers, the effective iteration count is NEVER
+ below 100000, and no environment value can make settings resolution
+ crash.
+
+Load-bearing test mechanics: ``PYTEST_CURRENT_TEST`` must be cleared in
+the TEST BODY, not in a setup-phase fixture -- pytest re-arms it at the
+start of every phase (setup -> call), so a fixture-level ``delenv`` is
+silently undone before the assertions run (same pattern as
+``tests/database/test_kdf_iterations.py``).
+
+The env-var matrix of ``_get_min_kdf_iterations`` itself is already
+pinned in ``tests/database/test_kdf_iterations.py`` (not duplicated
+here); this file covers the composed clamp plus the test-mode carve-out
+at the settings level, so a regression that accidentally drops the
+production floor or lets a weak value through any layer fails loudly.
+"""
+
+import pytest
+
+_ENV_KEYS = (
+ "PYTEST_CURRENT_TEST",
+ "LDR_TEST_MODE",
+ "LDR_DB_CONFIG_KDF_ITERATIONS",
+ "LDR_DB_KDF_ITERATIONS",
+)
+
+
+def _effective_kdf() -> int:
+ from local_deep_research.database.sqlcipher_utils import (
+ get_sqlcipher_settings,
+ )
+
+ return get_sqlcipher_settings()["kdf_iterations"]
+
+
+def _production_posture(monkeypatch):
+ """Clear every test marker and KDF knob -- in the body, see module
+ docstring. Returns the monkeypatch for further ``setenv`` calls."""
+ for key in _ENV_KEYS:
+ monkeypatch.delenv(key, raising=False)
+ return monkeypatch
+
+
+class TestAttemptedDowngradeWithoutTestMarkers:
+ """A weak configured KDF must not survive without test-mode markers."""
+
+ def test_env_of_one_is_rejected_not_floored(self, monkeypatch):
+ """``LDR_DB_CONFIG_KDF_ITERATIONS=1`` without test markers yields
+ the 256000 default -- not 1, and not the 100000 floor (the
+ registry's 1000 minimum rejects the value before the floor
+ window applies)."""
+ env = _production_posture(monkeypatch)
+ env.setenv("LDR_DB_CONFIG_KDF_ITERATIONS", "1")
+ assert _effective_kdf() == 256000
+
+ def test_sub_floor_in_registry_range_resets_to_default(self, monkeypatch):
+ """50000 parses cleanly and passes the registry, but sits below
+ the production floor: the clamp resets it to 256000 rather than
+ clamping UP to 100000."""
+ env = _production_posture(monkeypatch)
+ env.setenv("LDR_DB_CONFIG_KDF_ITERATIONS", "50000")
+ assert _effective_kdf() == 256000
+
+ def test_floor_boundary_is_exact(self, monkeypatch):
+ """99999 (one below the floor) is reset to 256000; 100000 (the
+ floor itself) passes through unchanged -- pin the boundary so an
+ off-by-one edit to the floor constant trips this test."""
+ env = _production_posture(monkeypatch)
+ env.setenv("LDR_DB_CONFIG_KDF_ITERATIONS", "99999")
+ assert _effective_kdf() == 256000
+ env.setenv("LDR_DB_CONFIG_KDF_ITERATIONS", "100000")
+ assert _effective_kdf() == 100000
+
+
+class TestAbsurdValuesNeverCrashNeverWeaken:
+ """Absurd or malformed values resolve to the 256000 default without
+ raising, and never to a below-floor count."""
+
+ @pytest.mark.parametrize(
+ "raw",
+ ["0", "-5", "1000000000000", "abc", "", "1.5"],
+ ids=[
+ "zero",
+ "negative",
+ "ten-to-the-twelve",
+ "non-numeric",
+ "empty",
+ "float-literal",
+ ],
+ )
+ def test_absurd_value_resolves_to_default(self, raw, monkeypatch):
+ env = _production_posture(monkeypatch)
+ env.setenv("LDR_DB_CONFIG_KDF_ITERATIONS", raw)
+ assert _effective_kdf() == 256000
+
+
+class TestTestModeCarveOut:
+ """The documented test-mode relaxation, pinned so that production
+ regressions which drop the floor (or widen the carve-out beyond
+ these markers) are caught."""
+
+ def test_ldr_test_mode_accepts_weak_kdf(self, monkeypatch):
+ """With ``LDR_TEST_MODE=1`` (and pytest's own marker cleared),
+ the floor drops to 1 and an in-registry 1000 is accepted -- the
+ sanctioned fast-KDF path used across the test suite."""
+ env = _production_posture(monkeypatch)
+ env.setenv("LDR_TEST_MODE", "1")
+ env.setenv("LDR_DB_CONFIG_KDF_ITERATIONS", "1000")
+ assert _effective_kdf() == 1000
+
+ @pytest.mark.parametrize("falsey", ["0", "false", "False", "no"])
+ def test_explicit_false_test_mode_does_not_relax(self, falsey, monkeypatch):
+ """``LDR_TEST_MODE`` is boolean-parsed: an explicit falsey value
+ leaves the production floor in force, so a weak 1000 resets to
+ 256000."""
+ env = _production_posture(monkeypatch)
+ env.setenv("LDR_TEST_MODE", falsey)
+ env.setenv("LDR_DB_CONFIG_KDF_ITERATIONS", "1000")
+ assert _effective_kdf() == 256000
+
+ def test_deprecated_alias_cannot_bypass_the_clamp(self, monkeypatch):
+ """The deprecated ``LDR_DB_KDF_ITERATIONS`` alias feeds the same
+ pipeline: under test mode it is honoured (1000 accepted), so
+ operators get no bypass the canonical name lacks."""
+ env = _production_posture(monkeypatch)
+ env.setenv("LDR_TEST_MODE", "1")
+ env.setenv("LDR_DB_KDF_ITERATIONS", "1000")
+ assert _effective_kdf() == 1000
+
+ def test_deprecated_alias_is_clamped_without_test_mode(self, monkeypatch):
+ """Without test-mode markers, the deprecated alias goes through the
+ same production clamp as the canonical name: a sub-floor value
+ (50000) resets to the 256000 default rather than being honoured
+ raw. A mutant that reads the alias straight off the environment
+ and skips the clamp entirely would return 50000 here."""
+ env = _production_posture(monkeypatch)
+ env.setenv("LDR_DB_KDF_ITERATIONS", "50000")
+ assert _effective_kdf() == 256000
+
+ def test_test_mode_still_rejects_below_registry_minimum(self, monkeypatch):
+ """Even in test mode the registry minimum (1000) holds: 1 never
+ reaches the floor, so the weakest effective configured KDF via
+ env is 1000, not 1."""
+ env = _production_posture(monkeypatch)
+ env.setenv("LDR_TEST_MODE", "1")
+ env.setenv("LDR_DB_CONFIG_KDF_ITERATIONS", "1")
+ assert _effective_kdf() == 256000