deer-flow/backend/tests/test_run_metadata_secret_safety.py
Totoro 92e9afe6ea
feat(context): support client context capabilities (#7051)
* feat: support client context capabilities

(cherry picked from commit b7c223f9415dcd545cbe05a5f5a6e47073a42d68)
[Totoro-qaq: resolved onto main. The persisted-reminder middleware hunks and their tests are dropped (delivery is redesigned in a follow-up); the RunCreateRequest description moved to app/gateway/run_models.py.]

* fix: address client context review comments

(cherry picked from commit bce6da6b819228eda58e887872720b6f9b5fab69)
[Totoro-qaq: middleware hunks dropped with the redesigned delivery.]

* feat(agents): deliver client context as a request-scoped data block

The cherry-picked #3106 put context.client into the persisted first-turn
reminder, with change detection and a "not provided" clear marker. Main
has since moved the date reminder to a SystemMessage, made request-scoped
context (the project block, #5443) request-only, and agents/AGENTS.md now
requires user-influenced values to ride the HumanMessage data channel,
never system text.

Render runtime.context["client"] on every model call in
DynamicContextMiddleware.wrap_model_call/awrap_model_call as one hidden
HumanMessage right after the leading SystemMessages, where DurableContext
puts its data. It is never a state update and never flagged
dynamic_context_reminder, so nothing is checkpointed, summarized or
replayed, and a run without a client gets no block. An unchanged client
keeps the previous request as the next request's prefix.

The renderer sanitizes again (direct graph callers bypass the Gateway),
html-escapes values and frames them with frame_untrusted_text: the same
--- BEGIN/END USER INPUT --- boundary the user's own turn and the MCP task
notification get. The lead prompt treats everything outside those markers
as framework data, so unframed values would rank above the user's own
text; framed, context.client can say nothing the same caller could not
already say in input.messages. client_context joins _BLOCKED_TAG_NAMES so
a forged block in user input or a tool result is escaped, and one static,
value-free sentence in the lead prompt names the block as untrusted hints,
never instructions, permissions or identity. The now unused empty-context
marker is removed.

* fix(gateway): log dropped context.client fields without values

A run request is never rejected over context.client: unknown fields,
nested values and malformed entries are silently dropped, the same
leniency as the other context keys. That left no signal when a custom
client sent something the Gateway ignored (review on #3106).

Route both the config.context.client and the body context.client paths
through one helper that emits a debug line whenever sanitizing changed
the value. Like the malformed client_timezone branch, the line carries no
values; unlike client_timezone, client.name and preference strings are
free caller-controlled text, so they are never logged, not even
sanitized. A clean client, an explicit null or an absent key logs
nothing.

Tests also pin the config-only path (sanitized before the early return)
and the end-to-end start_run admission: the sanitized client reaches
config["context"] and never configurable.

* fix(runtime): bound numeric client context preferences

String preferences are capped at 200 characters, but integers were kept
at any size. A JSON body may carry integers of up to 4300 digits, so 32 of
them rendered a block of about 138,000 characters, re-sent on every model
call of the run. In-process callers could also pass an int past the str()
digit limit, which failed the model call, or a number subclass with its
own __str__.

Keep integers within JavaScript's Number.MAX_SAFE_INTEGER, the range a
browser client can send exactly, and coerce numbers to plain int and
float.

* docs(api): describe client context as advisory request-scoped hints

The cherry-picked section described a hidden reminder that no longer
exists. Document what a custom client can rely on: the allow-list and its
limits (strings, the integer range, and only the first 32 entries of each
map), debug-level logging of dropped fields, runtime-only forwarding, and
delivery as a per-request user-role block, framed like user input, rather
than system text or thread history.

Only top-level context.client is documented. An explicit
config.context.client is sanitized for the run as well, but the run record
keeps the caller's config as sent, so it is not offered as an alternative.

It also answers the #3106 review: capabilities and preferences are
advisory hints, not enforcement, which belongs outside the model; name is
informational and never for authorization; the same object should be
sent on every run to keep the cached prefix stable; subagents and
embedded DeerFlowClient runs do not receive it, and server-started runs
(schedules, IM channels, GitHub agents, MCP notifications, extensions
unless the plugin passes one) carry none.

* fix(context): declare client delivery and keep client out of configurable

The request-only <client_context> block is model-visible, so
DynamicContextMiddleware now declares its delivery and the sanitizer's
limits in release_policy_parameters(); runs before and after this change
no longer share a policy fingerprint.

build_run_config copies body.config['configurable'] verbatim and
configurable is persisted with checkpoints, so a client placed there is
dropped instead of being stored raw. Client context stays runtime-only.

Document context.client in the README and in the middleware guide.

* fix(context): apply the PII redaction policy to the client block

DynamicContextMiddleware adds the <client_context> message inside the
outer PiiRedactionMiddleware, and the hidden message is not re-sanitized,
so with pii_redaction enabled a preference such as an email address
reached the model verbatim while the same address in the user turn was
redacted. Pass the rendered block through the shared redact_text seam
with this middleware's app_config.pii_redaction, and declare the setting
in release_policy_parameters().

* fix(context): keep client hints out of stored run config

---------

Co-authored-by: Blair Leng <25675774+BlairLeng@users.noreply.github.com>
Co-authored-by: Totoro-qaq <279883115+Totoro-qaq@users.noreply.github.com>
2026-10-19 10:41:18 +08:00

179 lines
6.3 KiB
Python

import pytest
from app.gateway.routers.thread_runs import _record_to_response
from app.gateway.routers.threads import HistoryEntry, ThreadResponse, ThreadStateResponse
from deerflow.runtime.runs.manager import RunRecord
from deerflow.runtime.runs.schemas import DisconnectMode, RunStatus
from deerflow.runtime.secret_context import (
LegacyRunMetadataSecretError,
redact_config_secrets,
redact_metadata_secrets,
validate_run_metadata_secrets,
)
from deerflow.trace_context import DEERFLOW_TRACE_METADATA_KEY
@pytest.mark.parametrize("value", ["secret", "", None, {"nested": True}])
def test_validate_run_metadata_rejects_auth_token_key_by_presence(value):
with pytest.raises(LegacyRunMetadataSecretError, match=r"config\.context\.secrets"):
validate_run_metadata_secrets({"auth_token": value, "token_usage": 7})
@pytest.mark.parametrize(
"metadata",
[None, "not-a-mapping", {"token": "keep", "nested": {"auth_token": "keep"}}],
)
def test_validate_run_metadata_accepts_non_legacy_shapes(metadata):
validate_run_metadata_secrets(metadata)
def test_redact_metadata_secrets_removes_exact_key_without_mutating_source():
source = {
"auth_token": "legacy-secret",
"token_usage": 7,
"nested": {"auth_token": "ordinary-nested-metadata"},
}
redacted = redact_metadata_secrets(source)
assert redacted == {
"token_usage": 7,
"nested": {"auth_token": "ordinary-nested-metadata"},
}
assert source["auth_token"] == "legacy-secret"
assert redacted is not source
def test_redact_config_secrets_hides_legacy_config_metadata_without_mutating_source():
source = {
"metadata": {
"auth_token": "legacy-secret",
"token_usage": 7,
"nested": {"auth_token": "ordinary-nested-metadata"},
},
"context": {
"secrets": {"MCP_AUTH_TOKEN": "request-secret"},
"model_name": "default",
},
}
redacted = redact_config_secrets(source)
assert redacted == {
"metadata": {
"token_usage": 7,
"nested": {"auth_token": "ordinary-nested-metadata"},
},
"context": {"model_name": "default"},
}
assert source["metadata"]["auth_token"] == "legacy-secret"
assert source["context"]["secrets"] == {"MCP_AUTH_TOKEN": "request-secret"}
assert redacted is not source
assert redacted["metadata"] is not source["metadata"]
assert redacted["context"] is not source["context"]
def test_redact_config_secrets_drops_trace_id_from_metadata_and_context():
"""``body.config`` is persisted as ``runs.kwargs_json`` and echoed verbatim
by the runs API. ``deerflow_trace_id`` is ignored as an input everywhere
else, so echoing a caller-supplied one back would only manufacture
disagreement with the response header, the logs, and the run record."""
source = {
"metadata": {DEERFLOW_TRACE_METADATA_KEY: "forged-meta", "token_usage": 7},
"context": {DEERFLOW_TRACE_METADATA_KEY: "forged-ctx", "model_name": "default"},
}
redacted = redact_config_secrets(source)
assert redacted == {
"metadata": {"token_usage": 7},
"context": {"model_name": "default"},
}
assert source["metadata"][DEERFLOW_TRACE_METADATA_KEY] == "forged-meta"
assert source["context"][DEERFLOW_TRACE_METADATA_KEY] == "forged-ctx"
@pytest.mark.parametrize("section", ["context", "configurable"])
@pytest.mark.parametrize("client", [{"name": "synthetic-client", "access_token": "synthetic-secret"}, "malformed-client", None, 42])
def test_run_config_omits_client_without_mutating_request(section, client):
source = {section: {"client": client, "model_name": "kept"}, "metadata": {"client": "ordinary-metadata"}, "tags": ["kept"]}
redacted = redact_config_secrets(source)
assert redacted == {section: {"model_name": "kept"}, "metadata": {"client": "ordinary-metadata"}, "tags": ["kept"]}
assert "client" in source[section]
assert source[section]["client"] == client
assert redacted[section] is not source[section]
def test_run_response_hides_historical_auth_token_without_mutating_record():
legacy_metadata = {"auth_token": "legacy-secret", "token_usage": 7}
record = RunRecord(
run_id="legacy-run",
thread_id="legacy-thread",
assistant_id="lead_agent",
status=RunStatus.success,
on_disconnect=DisconnectMode.cancel,
metadata=legacy_metadata,
)
response = _record_to_response(record)
assert response.metadata == {"token_usage": 7}
assert record.metadata["auth_token"] == "legacy-secret"
def test_run_response_hides_historical_config_metadata_without_mutating_record():
legacy_config = {
"metadata": {
"auth_token": "legacy-secret",
"token_usage": 7,
"nested": {"auth_token": "ordinary-nested-metadata"},
},
"context": {
"secrets": {"MCP_AUTH_TOKEN": "request-secret"},
"model_name": "default",
},
}
record = RunRecord(
run_id="legacy-config-run",
thread_id="legacy-thread",
assistant_id="lead_agent",
status=RunStatus.success,
on_disconnect=DisconnectMode.cancel,
metadata={"token_usage": 7},
kwargs={"input": {}, "config": legacy_config},
)
response = _record_to_response(record)
assert response.kwargs["config"] == {
"metadata": {
"token_usage": 7,
"nested": {"auth_token": "ordinary-nested-metadata"},
},
"context": {"model_name": "default"},
}
assert record.kwargs["config"]["metadata"]["auth_token"] == "legacy-secret"
assert record.kwargs["config"]["context"]["secrets"] == {"MCP_AUTH_TOKEN": "request-secret"}
@pytest.mark.parametrize(
("response_class", "required_fields"),
[
(ThreadResponse, {"thread_id": "legacy-thread"}),
(ThreadStateResponse, {}),
(HistoryEntry, {"checkpoint_id": "legacy-checkpoint"}),
],
)
def test_thread_metadata_response_models_hide_historical_auth_token(
response_class,
required_fields,
):
source = {"auth_token": "legacy-secret", "token_usage": 7}
response = response_class(**required_fields, metadata=source)
assert response.metadata == {"token_usage": 7}
assert source["auth_token"] == "legacy-secret"