Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

feat(ultrawiki): keep credentials out of the knowledge base

Ruben Lütke391a41e2decc
diff --git a/jarvis/ultrawiki/secret_scrub.py b/jarvis/ultrawiki/secret_scrub.py
new file mode 100644
index 0000000000..ca3748cb3d
--- /dev/null
+++ b/jarvis/ultrawiki/secret_scrub.py
@@ -0,0 +1,343 @@
+"""Keep credentials out of the knowledge base — deterministically, before storage.
+
+Reading "everything a source holds" changed what ingestion is. A folder walk, a
+Dropbox and a repository do not contain only documents: they contain `.env`
+files, `id_rsa`, `*.pem`, service-account JSON and cloud credentials. Those
+would land in a store that a language model reads from and that answers
+questions in plain text — so a single sync could turn a private key into
+something the assistant helpfully quotes back.
+
+This module is the last gate before storage. It is **deterministic**: regular
+expressions and file names, no model call, no judgement. A gate that asks an
+LLM whether something is a secret is a gate that leaks on the day the model is
+unavailable, slow, or wrong — and it would send the secret to the provider to
+ask.
+
+Two layers, because they answer different questions:
+
+* **Withhold by NAME** — a file whose whole purpose is to hold credentials is
+ never stored with its content. Redacting line by line would be a bet that the
+ patterns below are exhaustive, and for a credential file that bet is not
+ worth taking.
+* **Redact by SHAPE** — inside ordinary content, individual secrets are
+ replaced with a marker naming what was removed. A pasted token in a chat
+ message, an access key in a README, a connection string in a note.
+
+Both keep the ITEM. A withheld file still becomes a searchable record of its
+own existence — the memory may say "there is a .env in this project" (true and
+useful) without saying what is in it. Dropping the item instead would also
+break resume: the sync checkpoint is the last item's id.
+
+False positives cost a redaction marker in one paragraph. False negatives cost
+a leaked credential. The patterns are therefore written to catch the shapes
+whose formats are published and unmistakable, and the generic assignment rule
+demands a value that does not look like prose.
+"""
+
+from __future__ import annotations
+
+import re
+from dataclasses import dataclass, replace
+from pathlib import PurePosixPath
+
+from jarvis.ultrawiki.types import RawItem
+
+__all__ = [
+ "SECRET_FILENAMES",
+ "ScrubResult",
+ "looks_like_credential_file",
+ "redact_secrets",
+ "scrub_item",
+]
+
+#: Exact names whose entire purpose is holding credentials.
+_SECRET_NAMES: frozenset[str] = frozenset(
+ {
+ ".env",
+ ".envrc",
+ ".netrc",
+ "_netrc",
+ ".npmrc",
+ ".pypirc",
+ ".git-credentials",
+ ".htpasswd",
+ ".pgpass",
+ "credentials",
+ "credentials.json",
+ "client_secret.json",
+ "id_rsa",
+ "id_dsa",
+ "id_ecdsa",
+ "id_ed25519",
+ "secring.gpg",
+ "shadow",
+ }
+)
+
+#: Suffixes that mark key material or a credential store.
+_SECRET_SUFFIXES: frozenset[str] = frozenset(
+ {
+ ".pem",
+ ".key",
+ ".pfx",
+ ".p12",
+ ".jks",
+ ".keystore",
+ ".ppk",
+ ".kdbx",
+ ".asc",
+ ".gpg",
+ ".pgp",
+ }
+)
+
+#: Name shapes: `.env.production`, `secrets.yaml`, `service-account-x.json`.
+_SECRET_PATTERNS: tuple[re.Pattern[str], ...] = (
+ re.compile(r"^\.env(\..+)?$"),
+ re.compile(r"^secrets?\.(ya?ml|json|toml|ini|txt|env)$"),
+ re.compile(r"^service[-_]account.*\.json$"),
+ re.compile(r".*[-_]credentials?\.(json|ya?ml|ini|txt)$"),
+)
+
+#: Public view for the walkers and the UI that want to explain the rule.
+SECRET_FILENAMES: frozenset[str] = _SECRET_NAMES
+
+#: Item metadata keys that may carry the file's real name. An attachment, a
+#: Dropbox entry and a folder walk each name it differently, and the title is
+#: not always the filename.
+_NAME_KEYS: tuple[str, ...] = (
+ "filename",
+ "attachment_filename",
+ "path_display",
+ "relative_path",
+ "path",
+)
+
+#: Published credential formats. Each is unmistakable on its own: the prefix
+#: and the length are defined by the issuer, so a match is not a guess.
+_PATTERNS: tuple[tuple[str, re.Pattern[str]], ...] = (
+ (
+ "private key",
+ re.compile(
+ r"-----BEGIN [A-Z ]*PRIVATE KEY-----.*?-----END [A-Z ]*PRIVATE KEY-----",
+ re.DOTALL,
+ ),
+ ),
+ ("AWS access key id", re.compile(r"\b(?:AKIA|ASIA)[0-9A-Z]{16}\b")),
+ ("GitHub token", re.compile(r"\bgh[pousr]_[A-Za-z0-9]{30,}\b")),
+ ("GitHub token", re.compile(r"\bgithub_pat_[A-Za-z0-9_]{20,}\b")),
+ ("Slack token", re.compile(r"\bxox[abprs]-[A-Za-z0-9-]{10,}\b")),
+ ("Google API key", re.compile(r"\bAIza[0-9A-Za-z_-]{35}\b")),
+ ("Stripe key", re.compile(r"\b[sr]k_live_[A-Za-z0-9]{16,}\b")),
+ ("API key", re.compile(r"\bsk-(?:ant-)?[A-Za-z0-9_-]{24,}\b")),
+ (
+ "signed token",
+ re.compile(r"\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\b"),
+ ),
+ (
+ "connection string password",
+ re.compile(r"(?<=://)([^\s:/@]+):([^\s:/@]{6,})(?=@)"),
+ ),
+)
+
+#: `API_KEY=...`, `password: "..."`. The NAME is kept and only the value is
+#: replaced, so the record still says a password was configured there.
+_ASSIGNMENT = re.compile(
+ r"(?i)\b([a-z0-9_.-]*(?:api[_-]?key|secret|token|password|passwd|"
+ r"access[_-]?key|private[_-]?key|auth)[a-z0-9_.-]*)\s*[:=]\s*"
+ r"[\"']?([^\s\"',;]{12,})[\"']?"
+)
+
+#: A dotted or underscored identifier: `token_store`, `jarvis.brain.tools`,
+#: `MAX_RETRIES`. Code is what a developer's corpus is mostly MADE of, so this
+#: shape must never be mistaken for a credential. Case-consistent on purpose —
+#: identifiers are written in one case, while a generated token mixes them,
+#: and `qX7-longEnoughValue123` must stay redactable.
+_IDENTIFIER = re.compile(
+ r"^([a-z_][a-z0-9_]*([.\-][a-z0-9_]+)*|[A-Z_][A-Z0-9_]*([.\-][A-Z0-9_]+)*)$"
+)
+
+#: Words a document writes where a password would go. Every setup guide in
+#: existence contains `user:password@host`; redacting the WORD teaches nobody
+#: anything and makes the instructions unreadable.
+_PASSWORD_PLACEHOLDERS: frozenset[str] = frozenset(
+ {
+ "password",
+ "passwd",
+ "pass",
+ "pwd",
+ "secret",
+ "token",
+ "your_password",
+ "yourpassword",
+ "changeme",
+ "hunter2",
+ }
+)
+
+#: Characters that mark a path, a call or a URL: never part of a bare secret.
+_PATH_PUNCTUATION = "/\\()[]{}<>$\"'`,;|*?"
+
+#: A lowercase dotted tail — `.com`, `.py`, `.apps.googleusercontent.com`. A
+#: hostname and a filename both end this way; a generated credential does not.
+_DOTTED_TAIL = re.compile(r"\.[a-z]{2,24}$")
+
+#: What documentation writes where a value would go: `abc…`, `abc...`.
+_ELISIONS = ("…", "...")
+
+#: Minimum length for a machine-issued credential. Below this, requiring the
+#: other shape rules produces more false positives than it prevents leaks.
+_MIN_SECRET_CHARS = 16
+
+
+@dataclass(slots=True)
+class ScrubResult:
+ """What the gate did to one item, in terms a user can be shown."""
+
+ item: RawItem
+ withheld: bool = False
+ reason: str = ""
+ redactions: int = 0
+
+ @property
+ def touched(self) -> bool:
+ return self.withheld or self.redactions > 0
+
+
+def looks_like_credential_file(name: str) -> bool:
+ """Whether this file's purpose is holding credentials.
+
+ Judged on the name alone, deliberately: it is decided before anything is
+ read, so the rule also applies to a walker that never opens the file.
+ """
+ cleaned = str(name or "").strip().replace("\\", "/")
+ if not cleaned:
+ return False
+ base = PurePosixPath(cleaned).name.lower()
+ if not base:
+ return False
+ if base in _SECRET_NAMES:
+ return True
+ if PurePosixPath(base).suffix in _SECRET_SUFFIXES:
+ return True
+ return any(pattern.match(base) for pattern in _SECRET_PATTERNS)
+
+
+def _looks_like_secret_value(value: str) -> bool:
+ """Whether a labelled value has the SHAPE of a machine-issued credential.
+
+ Deliberately demanding. Measured over 1 500 real files from a developer's
+ own disk, the obvious rule — "anything after ``token =``" — produced 513
+ matches of which effectively all were code: ``cancel_token=None``,
+ ``authorization_url=...``, even a test filename containing "api_key". A
+ redactor that eats source and prose damages the knowledge base in a way
+ nobody notices until a search comes back empty, so a value has to look
+ like what an issuer generates: long, mixed, and neither an identifier nor
+ a path.
+ """
+ candidate = value.strip().strip("\"'")
+ if len(candidate) < _MIN_SECRET_CHARS:
+ return False
+ if any(character in _PATH_PUNCTUATION for character in candidate):
+ return False
+ if _IDENTIFIER.match(candidate):
+ return False # `token_store`, `jarvis.brain.tools`, `some-flag-name`
+ if _DOTTED_TAIL.search(candidate):
+ return False # a hostname or a filename, not a credential
+ if any(mark in candidate for mark in _ELISIONS):
+ return False # documentation showing the SHAPE of a value
+ has_digit = any(character.isdigit() for character in candidate)
+ has_lower = any(character.islower() for character in candidate)
+ has_upper = any(character.isupper() for character in candidate)
+ # Either the mix a random generator produces, or long enough that nothing
+ # a person types by hand reaches it.
+ return (has_digit and has_lower and has_upper) or (
+ has_digit and len(candidate) >= 32
+ )
+
+
+def redact_secrets(text: str) -> tuple[str, int]:
+ """``(text, count)`` with every recognised credential replaced by a marker.
+
+ The marker names the KIND, never the value: the record stays honest about
+ what was there without carrying it.
+ """
+ if not text:
+ return ("", 0)
+ count = 0
+
+ for label, pattern in _PATTERNS:
+ if label == "connection string password":
+
+ def _mask(match: re.Match[str]) -> str:
+ password = match.group(2)
+ # `postgresql://<user>:<password>@host` is a TEMPLATE — every
+ # connection-string example in every document looks like this,
+ # and redacting the word "password" out of documentation makes
+ # the instructions unreadable for no security gain.
+ if (
+ password.startswith(("<", "{", "$", "%"))
+ or password.lower().strip("*") in _PASSWORD_PLACEHOLDERS
+ or any(mark in password for mark in _ELISIONS)
+ ):
+ return match.group(0)
+ return f"{match.group(1)}:[redacted: password]"
+
+ text, hits = pattern.subn(_mask, text)
+ # subn counts every match; only the masked ones were redactions.
+ hits = text.count("[redacted: password]")
+ else:
+ text, hits = pattern.subn(f"[redacted: {label}]", text)
+ count += hits
+
+ def _mask_assignment(match: re.Match[str]) -> str:
+ nonlocal count
+ name, value = match.group(1), match.group(2)
+ if not _looks_like_secret_value(value) or value.startswith("[redacted:"):
+ return match.group(0)
+ count += 1
+ return f"{name}=[redacted: value]"
+
+ text = _ASSIGNMENT.sub(_mask_assignment, text)
+ return (text, count)
+
+
+def _candidate_names(item: RawItem) -> list[str]:
+ names = [str(item.metadata.get(key) or "") for key in _NAME_KEYS]
+ names.append(item.title)
+ return [name for name in names if name]
+
+
+def scrub_item(item: RawItem) -> ScrubResult:
+ """The gate every item passes before it is stored.
+
+ A credential FILE keeps its name, its date and its link and loses its
+ content; ordinary content keeps everything but the secrets inside it.
+ """
+ for name in _candidate_names(item):
+ if looks_like_credential_file(name):
+ reason = "this file holds credentials, so its content is not imported"
+ withheld = replace(
+ item,
+ body=f"File: {PurePosixPath(name.replace(chr(92), '/')).name}\n"
+ f"[content withheld: {reason}]",
+ metadata={
+ **item.metadata,
+ "secret_withheld": True,
+ "content_missing": True,
+ "content_missing_reason": reason,
+ },
+ )
+ return ScrubResult(item=withheld, withheld=True, reason=reason)
+
+ cleaned, count = redact_secrets(item.body)
+ if not count:
+ return ScrubResult(item=item)
+ return ScrubResult(
+ item=replace(
+ item,
+ body=cleaned,
+ metadata={**item.metadata, "secret_redactions": count},
+ ),
+ redactions=count,
+ )
diff --git a/jarvis/ultrawiki/service.py b/jarvis/ultrawiki/service.py
index 686fce6904..91272c1d2d 100644
--- a/jarvis/ultrawiki/service.py
+++ b/jarvis/ultrawiki/service.py
@@ -40,6 +40,7 @@ from datetime import UTC, datetime
from typing import Any
from jarvis.ultrawiki.progress import build_progress
+from jarvis.ultrawiki.secret_scrub import scrub_item
from jarvis.ultrawiki.types import (
ConnectorContext,
ConsentState,
@@ -233,6 +234,11 @@ class SyncJob:
changed: int = 0
unchanged: int = 0
tombstoned: int = 0
+ #: Credential files stored WITHOUT their content, and individual secrets
+ #: replaced inside otherwise ordinary items. Reported so the protection is
+ #: visible: a filter nobody can see is a filter nobody trusts.
+ secrets_withheld: int = 0
+ secrets_redacted: int = 0
error: str = ""
#: The asyncio.Task while the job is active; cleared when it ends.
task: Any = None
@@ -263,6 +269,8 @@ class SyncJob:
"changed": self.changed,
"unchanged": self.unchanged,
"tombstoned": self.tombstoned,
+ "secrets_withheld": self.secrets_withheld,
+ "secrets_redacted": self.secrets_redacted,
"error": self.error,
}
@@ -419,11 +427,20 @@ class UltraWikiService:
except Exception as exc: # noqa: BLE001 — no reader is not a boot failure
log.warning("UltraWiki: pull adapters could not register: %s", exc)
- async def ensure_started(self) -> None:
+ async def ensure_started(self, *, pipeline_grace_s: float = 0.0) -> None:
"""Open the store and start the pipeline (idempotent, off boot path).
The pipeline only starts while ``cfg.ultrawiki.enabled`` is true; a
later enable is picked up by the next ``ensure_started`` call.
+
+ ``pipeline_grace_s`` holds the WORKER back for that many seconds while
+ the store still opens immediately. The two have opposite cost profiles:
+ opening the store is cheap and is what every read, search and recall
+ needs at once, whereas the worker chews through the whole backlog and
+ was measured holding ~1.3 CPU cores indefinitely. Starting both at boot
+ made the backlog compete with the app's own startup for the machine.
+ Callers on the boot path pass a grace period; an in-app enable passes
+ none, because there the user is waiting for the work to begin.
"""
async with self._start_lock:
if self._store is None:
@@ -456,10 +473,32 @@ class UltraWikiService:
),
)
self._pipeline_task = asyncio.create_task(
- self._pipeline.run(self._cancel_event),
+ self._run_pipeline_after_grace(
+ self._pipeline, self._cancel_event, pipeline_grace_s
+ ),
name="ultrawiki-pipeline",
)
+ @staticmethod
+ async def _run_pipeline_after_grace(
+ pipeline: Any, cancel_event: asyncio.Event, grace_s: float
+ ) -> None:
+ """Wait out *grace_s*, then run the worker until cancelled.
+
+ The wait is a cancellable wait ON the shutdown event, never a blind
+ sleep: a plain sleep would keep ``stop()`` blocked for the rest of the
+ grace period, turning a startup optimisation into a shutdown stall.
+ A shutdown during the grace period therefore skips the run entirely.
+ """
+ if grace_s > 0:
+ try:
+ await asyncio.wait_for(cancel_event.wait(), timeout=grace_s)
+ except TimeoutError:
+ pass # grace elapsed, nothing asked us to stop -> start working
+ if cancel_event.is_set():
+ return
+ await pipeline.run(cancel_event)
+
async def _open_store(self) -> Any:
from jarvis.ultrawiki import store as store_mod # noqa: PLC0415 — lazy
@@ -1439,6 +1478,12 @@ class UltraWikiService:
max_cursor: int | None,
) -> int | None:
store = self._require_store()
+ # The LAST gate before storage, and deliberately the only one: every
+ # connector reaches the store through here, so a reader added later is
+ # covered without having to remember. Order matters — items are scrubbed
+ # BEFORE the write, never cleaned up afterwards, because a secret that
+ # was written once has already been indexed and embedded.
+ items = self._scrub(job, items)
counts = await store.upsert_items(source_id, items)
job.phase = "importing"
job.chunks += 1
@@ -1468,6 +1513,35 @@ class UltraWikiService:
await store.set_sync_state(source_id, **updates)
return max_cursor
+ @staticmethod
+ def _scrub(job: SyncJob, items: list[RawItem]) -> list[RawItem]:
+ """Credentials out, everything else through — and counted for the user.
+
+ Items are never DROPPED here. A withheld file keeps its name, date and
+ link, which is both honest ("there is a .env in this project" is true
+ and useful) and load-bearing: the backfill checkpoint is the last
+ item's id, so removing one would move the resume point.
+ """
+ scrubbed: list[RawItem] = []
+ withheld = 0
+ redactions = 0
+ for item in items:
+ result = scrub_item(item)
+ scrubbed.append(result.item)
+ withheld += 1 if result.withheld else 0
+ redactions += result.redactions
+ if withheld or redactions:
+ job.secrets_withheld += withheld
+ job.secrets_redacted += redactions
+ log.info(
+ "UltraWiki sync %s: withheld %d credential file(s) and redacted "
+ "%d secret(s) before storing",
+ job.source_id,
+ withheld,
+ redactions,
+ )
+ return scrubbed
+
@staticmethod
def _parse_cursor(cursor: Any) -> int | None:
if cursor is None or cursor == "":
diff --git a/tests/unit/ultrawiki/test_secret_scrub.py b/tests/unit/ultrawiki/test_secret_scrub.py
new file mode 100644
index 0000000000..04ea46f420
--- /dev/null
+++ b/tests/unit/ultrawiki/test_secret_scrub.py
@@ -0,0 +1,195 @@
+"""The gate that keeps credentials out of the knowledge base.
+
+Two properties matter more than any individual pattern, and both are pinned
+here: a credential FILE never reaches storage with its content, and an item is
+never DROPPED — because a memory that silently loses files is a memory nobody
+can reason about, and because the sync checkpoint is the last item's id.
+
+The false-positive tests are not politeness. A redactor that eats ordinary
+prose makes the knowledge base worse in a way nobody notices until a search
+comes back empty, so the ordinary sentences below must survive untouched.
+"""
+
+from __future__ import annotations
+
+from jarvis.ultrawiki.secret_scrub import (
+ looks_like_credential_file,
+ redact_secrets,
+ scrub_item,
+)
+from jarvis.ultrawiki.types import RawItem
+
+
+def _item(body: str, *, title: str = "note.md", **metadata: object) -> RawItem:
+ return RawItem(
+ external_id="x1",
+ body=body,
+ permalink="https://example.test/x1",
+ timestamp_utc="2026-03-01T10:00:00Z",
+ title=title,
+ metadata=dict(metadata),
+ )
+
+
+# ---------------------------------------------------------------------------
+# Credential files: withheld whole, never dropped
+# ---------------------------------------------------------------------------
+
+
+def test_the_files_whose_purpose_is_credentials_are_recognised():
+ for name in (
+ ".env",
+ ".env.production",
+ "id_rsa",
+ "server.pem",
+ "signing.key",
+ "credentials.json",
+ "service-account-prod.json",
+ "secrets.yaml",
+ ".npmrc",
+ "vault.kdbx",
+ "deploy/.git-credentials",
+ "C:\\Users\\Someone\\.aws\\credentials",
+ ):
+ assert looks_like_credential_file(name), name
+
+
+def test_ordinary_files_are_not_mistaken_for_credential_stores():
+ for name in (
+ "README.md",
+ "keyboard-shortcuts.md",
+ "environment.md",
+ "notes/secret-santa.md",
+ "Invoice 2026-03.pdf",
+ "monkey.png",
+ ):
+ assert not looks_like_credential_file(name), name
+
+
+def test_a_credential_file_keeps_its_name_and_loses_its_content():
+ """Withheld, not dropped: "there is a .env in this project" is true and
+ useful, and removing the item would move the sync's resume point."""
+ result = scrub_item(
+ _item("DATABASE_URL=postgres://user:hunter2@db/prod", title=".env")
+ )
+ assert result.withheld is True
+ assert "hunter2" not in result.item.body
+ assert "postgres" not in result.item.body
+ assert ".env" in result.item.body
+ assert result.item.external_id == "x1"
+ assert result.item.metadata["secret_withheld"] is True
+ assert result.item.metadata["content_missing"] is True
+
+
+def test_the_real_filename_is_read_from_metadata_not_only_the_title():
+ """An attachment's title is a display name; the filename lives in
+ metadata, and that is what the rule has to see."""
+ result = scrub_item(
+ _item(
+ "-----BEGIN RSA PRIVATE KEY-----\nMIIabc\n-----END RSA PRIVATE KEY-----",
+ title="Key for the staging box",
+ filename="staging.pem",
+ )
+ )
+ assert result.withheld is True
+ assert "MIIabc" not in result.item.body
+
+
+# ---------------------------------------------------------------------------
+# Redaction inside ordinary content
+# ---------------------------------------------------------------------------
+
+
+def test_published_credential_formats_are_replaced_by_a_named_marker():
+ cases = {
+ "AKIAIOSFODNN7EXAMPLE": "AWS access key id",
+ "ghp_" + "a" * 36: "GitHub token",
+ "xoxb-1234567890-abcdefghijkl": "Slack token",
+ "AIza" + "b" * 35: "Google API key",
+ "sk_live_" + "c" * 24: "Stripe key",
+ "sk-ant-" + "d" * 40: "API key",
+ }
+ for secret, label in cases.items():
+ cleaned, count = redact_secrets(f"the token is {secret} — keep it safe")
+ assert count == 1, secret
+ assert secret not in cleaned
+ assert f"[redacted: {label}]" in cleaned
+ # The sentence around it survives, so the record still reads.
+ assert "keep it safe" in cleaned
+
+
+def test_a_private_key_block_is_removed_entirely():
+ body = (
+ "Here is the deploy key:\n"
+ "-----BEGIN OPENSSH PRIVATE KEY-----\n"
+ "b3BlbnNzaC1rZXktdjEAAAAA\nmore lines\n"
+ "-----END OPENSSH PRIVATE KEY-----\n"
+ "Use it on the staging box."
+ )
+ cleaned, count = redact_secrets(body)
+ assert count == 1
+ assert "b3BlbnNzaC1rZXktdjEAAAAA" not in cleaned
+ assert "Use it on the staging box." in cleaned
+
+
+def test_a_password_in_a_connection_string_goes_but_the_host_stays():
+ """The host and the user are how a person recognises which system this
+ was; only the password is dangerous."""
+ cleaned, count = redact_secrets("postgres://appuser:[email protected]/prod")
+ assert count == 1
+ assert "s3cr3tpass" not in cleaned
+ assert "appuser" in cleaned
+ assert "db.internal" in cleaned
+
+
+def test_a_connection_string_TEMPLATE_survives_intact():
+ """Every setup guide contains one of these. Redacting the WORD "password"
+ out of documentation teaches nobody anything and makes the instructions
+ unreadable."""
+ for template in (
+ "postgresql://<user>:<password>@<host>:5432/<database>",
+ "scheme://user:password@host",
+ "postgresql://postgres.<ref>:…@<region>.pooler.supabase.com",
+ ):
+ cleaned, count = redact_secrets(template)
+ assert count == 0, template
+ assert cleaned == template
+
+
+def test_an_assignment_keeps_its_name_and_loses_its_value():
+ cleaned, count = redact_secrets('OPENAI_API_KEY="qX7-longEnoughValue123"')
+ assert count == 1
+ assert "qX7-longEnoughValue123" not in cleaned
+ # The record still says a key was configured HERE, which is the useful part.
+ assert "OPENAI_API_KEY" in cleaned
+
+
+def test_ordinary_prose_about_secrets_is_left_alone():
+ """The expensive failure mode. A redactor that eats sentences makes the
+ knowledge base worse in a way nobody notices until a search comes back
+ empty."""
+ for sentence in (
+ "The password is stored in the password manager, never in the repo.",
+ "api_key: <your-key-here>",
+ "SECRET_TOKEN=${DEPLOY_TOKEN}",
+ "password = changeme",
+ "Our token strategy is documented in the onboarding handbook.",
+ ):
+ cleaned, count = redact_secrets(sentence)
+ assert count == 0, sentence
+ assert cleaned == sentence
+
+
+def test_an_item_without_secrets_passes_through_untouched():
+ original = _item("Nothing sensitive here, just notes about the roadmap.")
+ result = scrub_item(original)
+ assert result.touched is False
+ assert result.item is original
+
+
+def test_a_secret_inside_an_ordinary_note_is_redacted_and_counted():
+ result = scrub_item(_item(f"Deploy with {'ghp_' + 'z' * 36} today"))
+ assert result.withheld is False
+ assert result.redactions == 1
+ assert "ghp_" not in result.item.body
+ assert result.item.metadata["secret_redactions"] == 1