deer-flow/backend/packages/harness/deerflow/agents/middlewares/input_sanitization_middleware.py
Xinmin Zeng 09988caf95
feat(skills): request-scoped secrets for skills (closes #3861) (#3871)
* feat(sandbox): per-call env injection + platform-secret scrubbing for skills

Add an env parameter to Sandbox.execute_command (abstract + local + AIO) so request-scoped secrets can be injected into skill subprocesses, and scrub platform credentials (*KEY*/*SECRET*/*TOKEN*/*PASSWORD*/*CREDENTIAL*) from the inherited environment by default so scoped injection is not security theatre. LocalSandbox always passes an explicit scrubbed env; AioSandbox routes env-bearing commands through bash.exec(env=) on a fresh session and leaves the legacy persistent-shell path unchanged. Part of #3861. BEHAVIOR CHANGE: execute_command no longer inherits the full os.environ; Windows encoding tests updated to assert the scrubbed dict.

* feat(skills): parse required-secrets frontmatter declaration

Add SecretRequirement and Skill.required_secrets, and parse the required-secrets SKILL.md frontmatter field (a string list or {name, optional} mappings), dropping malformed entries with a warning so one bad declaration does not invalidate the skill. The declared name is both the context.secrets key and the env var injected at activation. Part of #3861.

* feat(runtime): request-scoped secret carrier (context.secrets)

Add SECRETS_CONTEXT_KEY + extract_request_secrets, centralising the context.secrets carrier contract. The existing context passthrough (build_run_config -> _build_runtime_context) already carries the sub-key to runtime.context without mirroring it into configurable; characterization tests lock that behaviour. Part of #3861.

* feat(skills): inject declared secrets at slash-activation into bash env

Binding point A: when a skill is slash-activated, SkillActivationMiddleware resolves its declared required-secrets against the request's context.secrets and writes the per-run injection set to runtime.context. The bash tool forwards that set to execute_command(env=). A skill cannot harvest a host platform credential (is_host_platform_secret guard, cf. GHSA-rhgp-j443-p4rf), and injected values are redacted from bash output (mask_secret_values) so an echoed secret never re-enters the prompt/trace. Part of #3861.

* test(skills): lock the five secret leak surfaces + add trace redaction helper

Regression tests assert the secret value is absent from all five surfaces: prompt (activation message), checkpoint (graph state vs context separation), audit (journal records names only), trace (metadata builder never copies context; never mirrored to configurable), and stdout (mask_secret_values). Add redact_secret_context_keys as a defensive helper for any context serialization. Part of #3861.

* docs(backend): document request-scoped secrets for skills

Add Request-Scoped Secrets subsection (Skills) + env policy note (Sandbox) and the execute_command(env=) signature change, per the doc-sync policy. Part of #3861.

* fix(skills): close gaps found by end-to-end verification of request-scoped secrets

Real-gateway e2e + independent review of #3861 surfaced three defects, now fixed:

1. Slash activation never fired in the live chain. InputSanitizationMiddleware
   wraps user input in BEGIN/END markers before SkillActivationMiddleware sees it,
   and the original text was only preserved when an upload or IM channel set it.
   For a plain text message the slash command became undetectable, so no secret
   was ever resolved. Fix: the sanitizer now setdefaults the pre-wrap text into
   ORIGINAL_USER_CONTENT_KEY (additive; sanitization behaviour unchanged), so
   slash activation works for all messages. Pre-existing latent bug surfaced here.

2. The raw request config (with context.secrets) was persisted to runs.kwargs_json
   and echoed by the run API (RunResponse.kwargs). Fix: redact_config_secrets()
   strips secret-bearing context keys from the persisted/echoed copy in start_run;
   the live config that drives the run keeps them. build_run_config now also sets
   configurable.thread_id on the context path (the checkpointer requires it).

3. Connection-string credentials (DATABASE_URL, REDIS_URL, SENTRY_DSN, GH_PAT, ...)
   were not scrubbed from the inherited sandbox env. Fix: env_policy adds a *DSN*
   pattern plus an explicit connection-string denylist (no blanket *URL* — benign
   service URLs stay readable).

Verified end-to-end via a real gateway run (real LLM + skill activation + bash):
the secret reaches the sandbox subprocess and appears in NONE of prompt, trace,
checkpoint, audit, stdout, runs.kwargs_json, or the run API. Part of #3861.

* docs(backend): document the env scrub, persistence redaction, and sanitizer interaction

Sync the Request-Scoped Secrets section with the verification-driven fixes: inherited-env scrub (incl. connection-string denylist), run-record/run-API redaction as the 6th sealed leak surface, and the sanitizer preserving original content so slash activation fires. Part of #3861.

* fix(skills): inject caller secret over scrubbed host value; drop redundant host-name guard

A real-world demo (a skill calling a third-party cloud API with a request-scoped
key) exposed that the is_host_platform_secret guard was both wrong and harmful:
it refused to inject a caller-supplied secret whenever a same-named variable
existed in the Gateway env — which is exactly the #3861 use case (a per-user key
overriding a shared platform key). The guard was also redundant: build_sandbox_env
already scrubs secret-looking names from the inherited env before injection, so a
skill can never read a host credential — it only ever receives the caller's value.

Remove the guard; the injected (caller) value simply wins over the scrubbed host
value. Verified end-to-end: the agent called the real cloud API successfully with
the caller's key, the host's same-named key was scrubbed and never used, and the
caller's key leaked to none of the surfaces. Part of #3861.

* fix(skills): address review on request-scoped secrets (#3861)

Review fixes from PR #3871:

- E2BSandbox.execute_command now accepts env/timeout and routes them to
  commands.run(envs=, timeout=). The bash tool passes env= unconditionally,
  so the prior signature (command only) raised TypeError on every e2b bash
  call and broke e2b deployments entirely. env=None stays backward-compatible.
- SkillActivationMiddleware clears the active-secret set before resolving each
  activation, so a later skill in the same run never inherits an earlier
  skill's injection set (the #3861 contract: a skill only receives what the
  caller supplied AND that skill declared).
- AioSandbox env path uses a dedicated _DEFAULT_HARD_TIMEOUT — bash.exec exposes
  no idle/no-change timeout, so the prior reuse of the legacy idle constant
  conflated wall-clock vs idle semantics. The env path also retries on the
  ErrorObservation signature now, sharing the legacy persistent-shell recovery
  contract.
- mask_secret_values skips values below a minimum length floor so a short
  declared secret (e.g. "42") cannot shred unrelated bytes (exit codes,
  timestamps, sizes) of tool output. The secret is still injected into the
  subprocess; only the output mask skips it.

session_id reuse on the env path is intentionally NOT added: a shared session
could let request-scoped secrets ride the session env into later commands,
which the SDK does not contractually forbid. The fresh-session choice matches
the LocalSandbox model (each call is a fresh subprocess); the trade-off
(consecutive env-bearing calls do not share cwd/venv/exports) is documented on
_execute_with_env.
2026-07-03 07:51:22 +08:00

289 lines
11 KiB
Python

"""Input guardrail middleware for prompt-injection defense (issue #3630).
Escapes blocked XML-like tags in the last genuine user message (e.g.
``<system>`` → ``&lt;system&gt;``) so they render as literal text instead
of structured-context markers. This preserves the user's intent ("how do
I use DeerFlow's <think> tag?") while neutralizing injection attempts —
the same de-identify-don't-reject strategy as AWS Bedrock's PII ANONYMIZE.
Blocked: system-reserved tags (memory, analysis, etc.) + common injection
tags (system, instruction, role, etc.). Normal HTML/XML tags (<div>,
<span>) are NOT escaped.
Clean input is wrapped in plain-text boundary markers as a secondary
semantic defense (OWASP structured-prompt guidance).
"""
from __future__ import annotations
import logging
import re
from collections.abc import Awaitable, Callable
from typing import override
from langchain.agents import AgentState
from langchain.agents.middleware import AgentMiddleware
from langchain.agents.middleware.types import (
ModelCallResult,
ModelRequest,
ModelResponse,
)
from langchain_core.messages import HumanMessage
from langgraph.errors import GraphBubbleUp
from deerflow.utils.messages import ORIGINAL_USER_CONTENT_KEY, message_content_to_text
logger = logging.getLogger(__name__)
_SUMMARY_MESSAGE_NAME = "summary"
# Finite set of blocked tag names: system-reserved + common injection patterns.
_BLOCKED_TAG_NAMES: frozenset[str] = frozenset(
{
# System-reserved tags (used by the agent framework for structured context)
"system-reminder",
"memory",
"current_date",
"think",
"analysis",
"subagent_system",
"skill_system",
"uploaded_files",
"todo_list_system",
# Common prompt-injection tag patterns
"system",
"instruction",
"role",
"important",
"override",
"ignore",
"prompt",
}
)
# Matches a full blocked tag: <tag>, </tag>, <tag attrs>, <tag/>, bare <tag
_BLOCKED_TAG_PATTERN = re.compile(
r"<\s*/?\s*(?:" + "|".join(re.escape(t) for t in sorted(_BLOCKED_TAG_NAMES)) + r")\b[^>]*>?",
re.IGNORECASE,
)
# Plain-text boundary markers (OWASP structured-prompt guidance).
_USER_INPUT_BEGIN = "--- BEGIN USER INPUT ---"
_USER_INPUT_END = "--- END USER INPUT ---"
# Neutralized forms injected when the user's text already contains a marker.
# These look visually similar but do not match the real boundary delimiters.
_NEUTRALIZED_BEGIN = "[BEGIN USER INPUT]"
_NEUTRALIZED_END = "[END USER INPUT]"
# Matches either boundary token as a standalone line or embedded in text.
_BOUNDARY_TOKEN_RE = re.compile(
re.escape(_USER_INPUT_BEGIN) + r"|" + re.escape(_USER_INPUT_END),
)
def _escape_tag_match(match: re.Match) -> str:
"""Escape < and > in a blocked-tag match so it renders as literal text."""
return match.group(0).replace("<", "&lt;").replace(">", "&gt;")
def _is_genuine_user_message(message: object) -> bool:
"""Return True for real user messages, excluding system-injected HumanMessages.
System-injected context is marked via ``hide_from_ui`` — the same convention
used by DynamicContextMiddleware and TodoMiddleware.
"""
if not isinstance(message, HumanMessage):
return False
if message.additional_kwargs.get("hide_from_ui"):
return False
if message.name == _SUMMARY_MESSAGE_NAME:
return False
return True
def _check_user_content(text: str) -> str:
"""Sanitize user content: escape blocked tags, then wrap in boundary markers.
* Empty/whitespace-only → return unchanged (no marker noise).
* Blocked tags → HTML-escape ``<``/``>`` (e.g. ``<system>`` → ``&lt;system&gt;``).
* Boundary tokens in user text → neutralized so they cannot forge boundaries.
* Already wrapped (strict prefix+suffix) → return text unchanged (idempotent).
* Otherwise → wrap in boundary markers.
"""
if not text.strip():
return text
text = _BLOCKED_TAG_PATTERN.sub(_escape_tag_match, text)
# Idempotency: only skip if text is *exactly* wrapped (prefix+suffix),
# not if the user merely typed the begin token somewhere.
if text.startswith(_USER_INPUT_BEGIN) and text.endswith(_USER_INPUT_END):
# Still neutralize boundary tokens in the inner content — a user
# can forge the outer wrapping to bypass the neutralization below
# and inject inner boundary markers (break-out attack).
inner = text[len(_USER_INPUT_BEGIN) : -len(_USER_INPUT_END)]
neutralized_inner = _BOUNDARY_TOKEN_RE.sub(
lambda m: _NEUTRALIZED_BEGIN if m.group(0) == _USER_INPUT_BEGIN else _NEUTRALIZED_END,
inner,
)
if neutralized_inner == inner:
return text
return f"{_USER_INPUT_BEGIN}{neutralized_inner}{_USER_INPUT_END}"
# Neutralize any boundary tokens the user may have embedded, preventing
# both self-suppression (begin token skips wrapping) and break-out
# (end token creates a premature boundary inside the payload).
text = _BOUNDARY_TOKEN_RE.sub(
lambda m: _NEUTRALIZED_BEGIN if m.group(0) == _USER_INPUT_BEGIN else _NEUTRALIZED_END,
text,
)
return f"{_USER_INPUT_BEGIN}\n{text}\n{_USER_INPUT_END}"
class InputSanitizationMiddleware(AgentMiddleware[AgentState]):
"""Guardrail middleware that escapes prompt-injection tags in user input.
Blocked tags are HTML-escaped (not rejected) so the user's intent is
preserved while the tags lose their semantic significance. Clean input
is wrapped in plain-text boundary markers. Transformation is temporary
(wrap_model_call) — never written to state.
"""
@staticmethod
def _extract_text_from_content(content: str | list) -> tuple[str, list | None]:
"""Extract concatenated text from a plain-string or content-block-list.
Returns ``(text, extracted_blocks)``. *extracted_blocks* is None when
*content* is a string, or the list of text-content-block dicts when a list.
"""
if isinstance(content, str):
return content, None
if not isinstance(content, list):
return "", None
text_parts: list[str] = []
text_blocks: list[dict] = []
for block in content:
if isinstance(block, dict) and block.get("type") == "text" and isinstance(block.get("text"), str):
text_parts.append(block["text"])
text_blocks.append(block)
return "\n".join(text_parts), text_blocks
@staticmethod
def _rebuild_content(
original_content: list,
processed_text: str,
text_blocks: list[dict],
) -> list:
"""Replace text blocks with a single merged text block, preserving interleaved non-text blocks.
For ``[text, image, text]`` the image block between the two text blocks
is kept in place — only the text blocks are collapsed into one.
"""
text_block_ids = {id(b) for b in text_blocks}
first = last = None
for i, block in enumerate(original_content):
if id(block) in text_block_ids:
if first is None:
first = i
last = i
if first is None:
return original_content
result: list = [*original_content[:first], {"type": "text", "text": processed_text}]
# Re-insert any non-text blocks that sat between text blocks
for i in range(first + 1, last + 1):
if id(original_content[i]) not in text_block_ids:
result.append(original_content[i])
result.extend(original_content[last + 1 :])
return result
def _process_request(self, request: ModelRequest) -> ModelRequest:
"""Return a request with the last genuine user message sanitized.
Blocked tags are HTML-escaped (not rejected) so the user's intent is
preserved while the tags lose their semantic significance. Transformation
is temporary — the original request is never mutated.
"""
messages = list(request.messages)
for i in range(len(messages) - 1, -1, -1):
msg = messages[i]
if not _is_genuine_user_message(msg):
if isinstance(msg, HumanMessage):
logger.debug(
"_process_request: skipping non-genuine HumanMessage at pos=%d name=%s hide_from_ui=%s content_preview=%.80r",
i,
msg.name,
msg.additional_kwargs.get("hide_from_ui"),
msg.content,
)
continue
content = msg.content
logger.debug("_process_request: found genuine user message at pos=%d content=%.120r", i, content)
text_content, text_blocks = self._extract_text_from_content(content)
# No text at all (e.g. image-only message) — pass through
if not text_content and not isinstance(content, str):
logger.debug("_process_request: no text content in message — passing through")
return request
processed = _check_user_content(text_content)
if processed == text_content:
# Already wrapped — no override needed
return request
if text_blocks:
new_content = self._rebuild_content(content, processed, text_blocks)
else:
new_content = processed
# Preserve the pre-sanitization user text so downstream consumers that
# must see the genuine input (slash skill activation, regenerate) can
# recover it after the BEGIN/END wrapping. setdefault keeps an existing
# value (e.g. set by UploadsMiddleware or an IM channel) authoritative.
preserved_kwargs = dict(msg.additional_kwargs or {})
preserved_kwargs.setdefault(ORIGINAL_USER_CONTENT_KEY, message_content_to_text(content))
messages[i] = HumanMessage(
content=new_content,
id=msg.id,
name=msg.name,
additional_kwargs=preserved_kwargs,
)
logger.debug(
"InputSanitizationMiddleware: original=%r -> processed=%r",
content if isinstance(content, str) else "[content-blocks]",
processed,
)
return request.override(messages=messages)
return request
def _try_process(self, request: ModelRequest) -> ModelRequest:
"""Sanitize request; fail-open on unexpected errors.
GraphBubbleUp propagates; other exceptions return the original request.
"""
try:
return self._process_request(request)
except GraphBubbleUp:
raise
except Exception:
logger.warning(
"Input guardrail processing failed; passing original request to model",
exc_info=True,
)
return request
@override
def wrap_model_call(
self,
request: ModelRequest,
handler: Callable[[ModelRequest], ModelResponse],
) -> ModelCallResult:
return handler(self._try_process(request))
@override
async def awrap_model_call(
self,
request: ModelRequest,
handler: Callable[[ModelRequest], Awaitable[ModelResponse]],
) -> ModelCallResult:
return await handler(self._try_process(request))