Skip to content

The agent that grows with you

feat(plugins): redaction pattern registry — vendor token formats as plugins

webdevtodayjasonfdd45323bf79
diff --git a/agent/redact.py b/agent/redact.py
index b5dca332c4a..06bd242a24a 100644
--- a/agent/redact.py
+++ b/agent/redact.py
@@ -11,6 +11,7 @@ import logging
import os
import re
import shlex
+import threading
from urllib.parse import unquote_plus
# Basenames treated as ``.env`` files by _command_reads_env_file. Imported
@@ -1167,6 +1168,107 @@ def _has_known_prefix_substring(text: str) -> bool:
return any(p in text for p in _PREFIX_SUBSTRINGS)
+# ---------------------------------------------------------------------------
+# Plugin-registered redaction patterns
+# ---------------------------------------------------------------------------
+#
+# Every new vendor token format has historically required a core PR appending
+# to ``_PREFIX_PATTERNS`` above (fw_, retaindb_, hsk-, mem0_, brv_, ...).
+# This registry lets plugins add their provider's format instead. It is
+# ADDITIVE-ONLY by design: a plugin can extend what gets masked but has no
+# API to remove or weaken a built-in pattern, so a plugin can only ever
+# over-redact, never expose. The operator's global opt-out
+# (``security.redact_secrets: false`` / HERMES_REDACT_SECRETS) applies to
+# plugin patterns exactly as it does to built-ins.
+
+_PLUGIN_PREFIX_PATTERNS: list = []
+_registry_lock = threading.Lock()
+
+
+def _rebuild_prefix_matcher() -> None:
+ """Recompile the prefix alternation and pre-screen substrings.
+
+ ``redact_sensitive_text`` and ``_mask_token_nonreusable`` look these
+ globals up at call time, so swapping the module attributes (atomic
+ under the GIL) propagates immediately to every caller.
+ """
+ global _PREFIX_RE, _PREFIX_SUBSTRINGS
+ combined = _PREFIX_PATTERNS + _PLUGIN_PREFIX_PATTERNS
+ _PREFIX_RE = re.compile(
+ r"(?<![A-Za-z0-9_-])(" + "|".join(combined) + r")(?![A-Za-z0-9_-])"
+ )
+ _PREFIX_SUBSTRINGS = tuple(_extract_literal_prefix(p) for p in combined)
+
+
+def register_redaction_patterns(patterns, source: str = "plugin") -> int:
+ """Additively register credential-token regexes with the redaction engine.
+
+ Each accepted pattern joins the vendor-prefix alternation used by
+ ``redact_sensitive_text`` (same masking, same head/tail rules, same
+ non-reusable sentinel on ``file_read``) — everywhere built-in patterns
+ apply: logs, terminal output, transport errors, transcripts.
+
+ Per-pattern validation (invalid entries are warned and skipped, never
+ raised — a broken plugin must not break startup):
+
+ * must be a non-empty string that compiles as a regex;
+ * must start with at least 2 literal characters (the pre-screen
+ substring gate in ``_has_known_prefix_substring`` needs a literal
+ anchor; it also structurally rules out redact-everything patterns
+ like ``.*``);
+ * duplicates of built-in or already-registered patterns are skipped.
+
+ Args:
+ patterns: iterable of regex strings (e.g. ``[r"nvapi-[A-Za-z0-9_-]{20,}"]``).
+ source: attribution label for log lines (e.g. ``"plugin:my-plugin"``).
+
+ Returns:
+ The number of patterns actually accepted.
+ """
+ accepted = []
+ for pattern in patterns or []:
+ if not isinstance(pattern, str) or not pattern.strip():
+ logger.warning("%s: skipping empty/non-string redaction pattern", source)
+ continue
+ pattern = pattern.strip()
+ try:
+ re.compile(pattern)
+ except re.error as exc:
+ logger.warning(
+ "%s: skipping invalid redaction pattern %r (%s)",
+ source, pattern, exc,
+ )
+ continue
+ if len(_extract_literal_prefix(pattern)) < 2:
+ logger.warning(
+ "%s: skipping redaction pattern %r — must start with at "
+ "least 2 literal characters (needed for the pre-screen "
+ "substring gate)",
+ source, pattern,
+ )
+ continue
+ if pattern in _PREFIX_PATTERNS or pattern in _PLUGIN_PREFIX_PATTERNS or pattern in accepted:
+ logger.debug("%s: redaction pattern %r already registered", source, pattern)
+ continue
+ accepted.append(pattern)
+
+ if accepted:
+ with _registry_lock:
+ _PLUGIN_PREFIX_PATTERNS.extend(accepted)
+ _rebuild_prefix_matcher()
+ logger.info(
+ "%s: registered %d redaction pattern(s)", source, len(accepted)
+ )
+ return len(accepted)
+
+
+def _reset_plugin_redaction_patterns() -> None:
+ """Drop all plugin-registered patterns (tests/teardown only)."""
+ with _registry_lock:
+ _PLUGIN_PREFIX_PATTERNS.clear()
+ _rebuild_prefix_matcher()
+
+
_HTTP_METHOD_SUBSTRINGS = (
"GET ",
"POST ",
diff --git a/hermes_cli/plugins.py b/hermes_cli/plugins.py
index dadd4d28541..393354f8ea9 100644
--- a/hermes_cli/plugins.py
+++ b/hermes_cli/plugins.py
@@ -2032,6 +2032,50 @@ class PluginContext:
display_name,
)
+ # -- redaction pattern registration --------------------------------------
+
+ def register_redaction_patterns(self, patterns) -> int:
+ """Additively register secret-token regexes with the redaction engine.
+
+ Accepted patterns join the vendor-prefix alternation in
+ :mod:`agent.redact` and are masked everywhere built-in patterns
+ apply — logs, terminal output, transport errors, transcripts —
+ with the same head/tail masking and the same non-reusable
+ sentinel on ``file_read`` content. Historically every new vendor
+ token format required a core PR appending to
+ ``_PREFIX_PATTERNS``; provider plugins should own their own
+ format instead.
+
+ The registry is **additive-only**: plugins can extend what gets
+ masked but cannot remove or weaken built-in patterns, so a
+ plugin can only ever over-redact, never expose. The operator's
+ global opt-out (``security.redact_secrets: false``) applies to
+ plugin patterns exactly as it does to built-ins.
+
+ Each pattern must compile as a regex and start with at least 2
+ literal characters (e.g. ``r"nvapi-[A-Za-z0-9_-]{20,}"``).
+ Invalid entries are warned and skipped — never raised.
+
+ Returns the number of patterns accepted.
+ """
+ from agent.redact import register_redaction_patterns as _register
+
+ try:
+ count = _register(
+ patterns, source=f"plugin:{self.manifest.name}",
+ )
+ except Exception as exc:
+ logger.warning(
+ "Plugin '%s' redaction pattern registration failed: %s",
+ self.manifest.name, exc,
+ )
+ return 0
+ logger.debug(
+ "Plugin %s registered %d redaction pattern(s)",
+ self.manifest.name, count,
+ )
+ return count
+
def register_hook(self, hook_name: str, callback: Callable) -> None:
"""Register a lifecycle hook callback.
diff --git a/plugins/nvapi-redaction/README.md b/plugins/nvapi-redaction/README.md
new file mode 100644
index 00000000000..744cbb044fd
--- /dev/null
+++ b/plugins/nvapi-redaction/README.md
@@ -0,0 +1,20 @@
+# nvapi-redaction
+
+Masks NVIDIA API keys (`nvapi-...`, used by NIM endpoints and
+build.nvidia.com) in logs, terminal output, transport errors, and
+transcripts — everywhere the built-in vendor prefixes are masked.
+
+Also the reference implementation for the
+`ctx.register_redaction_patterns()` plugin interface: vendor token
+formats as plugins instead of one-line core PRs to
+`agent/redact.py::_PREFIX_PATTERNS`.
+
+## Enable
+
+```bash
+hermes plugins enable nvapi-redaction
+```
+
+Respects the global `security.redact_secrets` setting like every
+built-in pattern. Additive-only: this plugin (and any redaction plugin)
+can extend masking but cannot weaken it.
diff --git a/plugins/nvapi-redaction/__init__.py b/plugins/nvapi-redaction/__init__.py
new file mode 100644
index 00000000000..c413f6fe950
--- /dev/null
+++ b/plugins/nvapi-redaction/__init__.py
@@ -0,0 +1,29 @@
+"""nvapi-redaction — a vendor token format as a plugin, not a core PR.
+
+NVIDIA API keys (``nvapi-...``) authenticate NIM endpoints and
+build.nvidia.com — common in self-hosted Hermes stacks running local
+NIM backends. The format is not in the core ``_PREFIX_PATTERNS`` list
+in ``agent/redact.py``, so today an ``nvapi-`` key that lands in a
+transport error or an ``env``-dump would be masked only if a generic
+pattern happens to catch it.
+
+Historically the fix was a one-line core PR appending to
+``_PREFIX_PATTERNS`` (that's how fw_, retaindb_, hsk-, mem0_, and brv_
+got there). This plugin is the same one-liner shipped through
+``ctx.register_redaction_patterns()`` instead — the reference
+implementation for the redaction-registry plugin interface.
+
+Registered patterns are additive-only: they extend what gets masked and
+cannot weaken built-in redaction.
+"""
+
+from __future__ import annotations
+
+# NVIDIA API keys: "nvapi-" followed by the token body. Real keys are
+# 60+ chars; the 20-char floor mirrors the conservative floors used for
+# other vendors in agent/redact.py while avoiding prose false-positives.
+NVAPI_PATTERN = r"nvapi-[A-Za-z0-9_-]{20,}"
+
+
+def register(ctx) -> None:
+ ctx.register_redaction_patterns([NVAPI_PATTERN])
diff --git a/plugins/nvapi-redaction/plugin.yaml b/plugins/nvapi-redaction/plugin.yaml
new file mode 100644
index 00000000000..6ddc67c9e22
--- /dev/null
+++ b/plugins/nvapi-redaction/plugin.yaml
@@ -0,0 +1,4 @@
+name: nvapi-redaction
+version: 1.0.0
+description: "Redact NVIDIA API keys (nvapi-...) from logs, terminal output, and transport errors. Reference implementation for the register_redaction_patterns plugin interface."
+author: "NousResearch (interface demo)"
diff --git a/tests/test_redaction_registry.py b/tests/test_redaction_registry.py
new file mode 100644
index 00000000000..b9460d8596f
--- /dev/null
+++ b/tests/test_redaction_registry.py
@@ -0,0 +1,179 @@
+"""Tests for the plugin redaction-pattern registry.
+
+Covers ``agent.redact.register_redaction_patterns`` (validation,
+dedupe, additive semantics, matcher rebuild), the
+``PluginContext.register_redaction_patterns`` wiring, and the bundled
+``nvapi-redaction`` reference plugin.
+
+All tests call ``redact_sensitive_text(..., force=True)`` so results
+don't depend on the HERMES_REDACT_SECRETS environment of the test run,
+and reset the plugin registry around each test so module-global state
+never leaks between tests.
+"""
+
+import importlib.util
+from pathlib import Path
+
+import pytest
+
+import agent.redact as redact_mod
+from agent.redact import (
+ _reset_plugin_redaction_patterns,
+ redact_sensitive_text,
+ register_redaction_patterns,
+)
+
+
+NVAPI_KEY = "nvapi-AbCdEfGhIjKlMnOpQrStUvWxYz0123456789_-abcdEFGH"
+NVAPI_PATTERN = r"nvapi-[A-Za-z0-9_-]{20,}"
+
+
[email protected](autouse=True)
+def _clean_registry():
+ _reset_plugin_redaction_patterns()
+ yield
+ _reset_plugin_redaction_patterns()
+
+
+# ── Baseline ────────────────────────────────────────────────────────────
+
+
+def test_unregistered_format_passes_through():
+ # Documents the gap the registry closes: an nvapi- key is not a
+ # built-in prefix, so without a plugin it survives redaction.
+ out = redact_sensitive_text(f"connect failed: {NVAPI_KEY}", force=True)
+ assert NVAPI_KEY in out
+
+
+# ── Core registry semantics ─────────────────────────────────────────────
+
+
+def test_registered_pattern_masks_token():
+ assert register_redaction_patterns([NVAPI_PATTERN], source="test") == 1
+ out = redact_sensitive_text(f"connect failed: {NVAPI_KEY}", force=True)
+ assert NVAPI_KEY not in out
+ # Head/tail mask preserved for debuggability (same rule as built-ins).
+ assert "nvapi-" in out and "..." in out
+
+
+def test_builtins_unaffected_by_registration():
+ register_redaction_patterns([NVAPI_PATTERN], source="test")
+ sk = "sk-proj-AbCdEf1234567890GhIjKl"
+ out = redact_sensitive_text(f"key={sk}", force=True)
+ assert sk not in out
+
+
+def test_invalid_regex_rejected():
+ assert register_redaction_patterns([r"nvapi-[unclosed"], source="test") == 0
+ out = redact_sensitive_text(f"x {NVAPI_KEY}", force=True)
+ assert NVAPI_KEY in out # nothing registered
+
+
+def test_pattern_without_literal_prefix_rejected():
+ # No literal anchor -> would defeat the pre-screen gate and could
+ # match everything. Must be rejected.
+ assert register_redaction_patterns([r".*secret.*"], source="test") == 0
+ assert register_redaction_patterns([r"[A-Za-z0-9]{30,}"], source="test") == 0
+ # One literal char is still too short.
+ assert register_redaction_patterns([r"x[A-Za-z0-9]{30,}"], source="test") == 0
+
+
+def test_duplicate_and_builtin_patterns_deduped():
+ assert register_redaction_patterns([NVAPI_PATTERN], source="test") == 1
+ assert register_redaction_patterns([NVAPI_PATTERN], source="test") == 0
+ # A pattern already shipped in core is skipped too.
+ builtin = redact_mod._PREFIX_PATTERNS[0]
+ assert register_redaction_patterns([builtin], source="test") == 0
+ # Same pattern twice in one call counts once.
+ _reset_plugin_redaction_patterns()
+ assert register_redaction_patterns([NVAPI_PATTERN, NVAPI_PATTERN], source="test") == 1
+
+
+def test_non_string_and_empty_entries_skipped():
+ assert register_redaction_patterns([None, "", " ", 42], source="test") == 0
+ assert register_redaction_patterns(None, source="test") == 0
+
+
+def test_file_read_sentinel_uses_plugin_prefix_label():
+ register_redaction_patterns([NVAPI_PATTERN], source="test")
+ out = redact_sensitive_text(
+ f"api_base_key: {NVAPI_KEY}", force=True, file_read=True,
+ )
+ assert NVAPI_KEY not in out
+ # Non-reusable sentinel carries the vendor label, no secret bytes.
+ assert "«redacted:nvapi-…»" in out
+
+
+def test_reset_restores_baseline():
+ register_redaction_patterns([NVAPI_PATTERN], source="test")
+ _reset_plugin_redaction_patterns()
+ out = redact_sensitive_text(f"x {NVAPI_KEY}", force=True)
+ assert NVAPI_KEY in out
+ # Built-ins still intact after reset.
+ sk = "sk-proj-AbCdEf1234567890GhIjKl"
+ assert sk not in redact_sensitive_text(sk, force=True)
+
+
+# ── PluginContext wiring ────────────────────────────────────────────────
+
+
+def test_plugin_context_method_registers():
+ import hermes_cli.plugins as plugins_mod
+
+ manager = plugins_mod.PluginManager()
+ manifest = plugins_mod.PluginManifest(name="test-redactor")
+ ctx = plugins_mod.PluginContext(manifest, manager)
+
+ assert ctx.register_redaction_patterns([NVAPI_PATTERN]) == 1
+ out = redact_sensitive_text(f"boom {NVAPI_KEY}", force=True)
+ assert NVAPI_KEY not in out
+
+
+def test_plugin_context_method_never_raises(monkeypatch):
+ import hermes_cli.plugins as plugins_mod
+
+ def _boom(patterns, source=""):
+ raise RuntimeError("registry exploded")
+
+ monkeypatch.setattr("agent.redact.register_redaction_patterns", _boom)
+
+ manager = plugins_mod.PluginManager()
+ manifest = plugins_mod.PluginManifest(name="test-redactor")
+ ctx = plugins_mod.PluginContext(manifest, manager)
+ assert ctx.register_redaction_patterns([NVAPI_PATTERN]) == 0
+
+
+# ── Bundled reference plugin ────────────────────────────────────────────
+
+
+def _load_demo_plugin():
+ plugin_init = (
+ Path(__file__).resolve().parent.parent
+ / "plugins" / "nvapi-redaction" / "__init__.py"
+ )
+ spec = importlib.util.spec_from_file_location("nvapi_redaction_demo", plugin_init)
+ module = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(module)
+ return module
+
+
+def test_demo_plugin_end_to_end():
+ import hermes_cli.plugins as plugins_mod
+
+ demo = _load_demo_plugin()
+ manager = plugins_mod.PluginManager()
+ manifest = plugins_mod.PluginManifest(name="nvapi-redaction")
+ demo.register(plugins_mod.PluginContext(manifest, manager))
+
+ out = redact_sensitive_text(
+ f"NIM request failed: 401 for key {NVAPI_KEY}", force=True,
+ )
+ assert NVAPI_KEY not in out
+ assert "nvapi-" in out # label survives for debuggability
+
+
+def test_demo_plugin_no_prose_false_positive():
+ demo = _load_demo_plugin()
+ register_redaction_patterns([demo.NVAPI_PATTERN], source="test")
+ prose = "the nvapi-endpoint docs describe rate limits"
+ assert redact_sensitive_text(prose, force=True) == prose