deer-flow/backend/tests/test_extension_route_principal.py
Nan Gao 13f0a7f263
feat(extensions): let an out-of-tree extension observe what the agent did (#4863)
* feat(extensions): let an out-of-tree extension observe what the agent did

DeerFlow's extension system can contribute middleware, services and routes,
but an extension cannot answer basic questions about a run without reaching
into host internals. Several of the facts it would need are destroyed by the
operations that produce them:

  * The middleware chain injects and rewrites a lot of context — date
    reminders, recalled memory, compaction summaries, durable-context data,
    image payloads, activated skill bodies. Downstream, none of it is
    attributable: at the model-call boundary an injected HumanMessage is
    indistinguishable from the user's own, and anything wanting to tell them
    apart has to pattern-match prompt wording, which breaks on the next copy
    edit.

  * Two runs of "the same agent" are only comparable if the chain enforced the
    same limits, prompts and thresholds. Recovering that from outside means
    reading private attributes and guessing which of them change behaviour — a
    guess that rots silently as middlewares gain fields.

  * The lead-agent factory resolves a model after runtime overrides, renders a
    prompt, filters tools through authorization and composes a stack, all
    inside one synchronous call, and none of it survives: a middleware sees its
    neighbours but not the prompt, the run worker sees a graph but not what
    went into it.

  * Summarization is destructive by design. N messages leave the context and
    one summary enters it; afterwards only the summary exists, so "which
    messages became this?" is not reconstructible.

This adds seven neutral facilities so those facts are recorded where they are
still true, and releases the contract package as 0.2.0.

Message provenance
  Producers stamp `deerflow_content_kind` / `deerflow_producer_kind` onto the
  messages they inject or rewrite. Stamping is unconditional — a fact whose
  presence depends on whether an observer is installed is not a fact — and the
  keys are server-owned, so provenance cannot be forged from a request.

Middleware self-description
  Twelve middlewares declare their own behaviour-affecting parameters through
  a duck-typed `release_policy_parameters()`. Long text is hashed rather than
  embedded: a declaration is an identity, not a copy of the prompt.

Agent assembly descriptor
  `assemble_lead_agent()` returns the graph plus a descriptor whose fingerprint
  answers "did anything about this agent change between these two runs?".
  `make_lead_agent()` keeps its graph-only signature — it is the LangGraph
  Server ABI declared in langgraph.json. Tools and skills are sorted before
  hashing because their assembly order is incidental; middlewares are not,
  because stack order decides what wraps what. Host build identity is reported
  but excluded from the fingerprint, so a redeploy does not invalidate every
  agent's identity.

Context compaction observation
  Summarization emits the content hashes of the messages it is about to remove
  joined to the summary that replaced them. Content is the only identity
  available at that seam: the summary does not become a message, and what later
  projects it into a request renders it bounded and escaped rather than
  verbatim.

Neutral policy, transform and MCP-source facts
  Guardrail decisions are published to runtime context under a `__`-prefixed
  key; result-rewriting middlewares append a declared, ordered transform trail;
  MCP tools carry their credential-free logical origin.

Extension route identity
  Contributed routes are session-authenticated and cannot opt out, but
  "logged in" and "administrator" are different questions. Extensions get a
  neutral projection of the caller rather than the host's auth context, and
  `require_admin` fails closed when identity cannot be determined.

Extension-owned tables
  An extension that persists data owns its own MetaData and migration chain, so
  its tables are absent from Base.metadata and `alembic revision --autogenerate`
  proposes dropping them. Extensions declare a table prefix, which is rejected
  at registration if it would shadow a host table.

The contract package stays dependency-free and imports no host code; every new
Protocol method has a default so later additions remain additive. The loader's
pre-1.0 rule requires an exact major.minor match, so extensions written against
0.1 are now refused at startup with an actionable install hint rather than
loading into a host that implements a different surface.

uv.lock records the contract package's new version, so `uv sync --locked` still
resolves on a fresh checkout.

* fix(backend): sort gateway service imports
2026-08-23 09:57:12 +08:00

110 lines
4.1 KiB
Python

"""Contributed routers need the caller's identity without importing app.*.
Every extension route is session-authenticated (contributed routers cannot
enter host-reserved or auth-exempt prefixes), but "logged in" and "admin" are
different questions and an extension must be able to ask the second one.
"""
from types import SimpleNamespace
import pytest
from deerflow_extension_api import (
EXTENSION_PRINCIPAL_RESOLVER_KEY,
ExtensionPrincipal,
require_admin,
resolve_principal,
)
ADMIN = ExtensionPrincipal(user_id="u1", is_admin=True, is_internal=False)
PLAIN = ExtensionPrincipal(user_id="u2", is_admin=False, is_internal=False)
def _request(principal):
state = SimpleNamespace(**{EXTENSION_PRINCIPAL_RESOLVER_KEY: (lambda request: principal)})
return SimpleNamespace(app=SimpleNamespace(state=state))
def test_resolve_returns_the_hosts_principal():
assert resolve_principal(_request(ADMIN)) == ADMIN
def test_resolve_returns_none_when_the_host_installed_no_resolver():
request = SimpleNamespace(app=SimpleNamespace(state=SimpleNamespace()))
assert resolve_principal(request) is None
def test_resolve_returns_none_rather_than_raising_when_the_resolver_fails():
def boom(request):
raise RuntimeError("nope")
state = SimpleNamespace(**{EXTENSION_PRINCIPAL_RESOLVER_KEY: boom})
request = SimpleNamespace(app=SimpleNamespace(state=state))
assert resolve_principal(request) is None
def test_require_admin_accepts_an_admin():
assert require_admin(_request(ADMIN)) == ADMIN
def test_require_admin_rejects_a_plain_user():
with pytest.raises(PermissionError):
require_admin(_request(PLAIN))
def test_require_admin_fails_closed_with_no_resolver():
"""An unanswerable authorization question must not resolve to 'allowed'."""
request = SimpleNamespace(app=SimpleNamespace(state=SimpleNamespace()))
with pytest.raises(PermissionError):
require_admin(request)
@pytest.fixture
def _stub_app_config(monkeypatch):
"""Keep ``create_app()`` independent of a real ``config.yaml``.
The repo-root ``config.yaml`` is gitignored; a checkout that configures
plugins there would otherwise make this test load them for real and leak
a populated extension registry into the process-global singleton other
tests read through (see ``tests/test_extension_app_loading.py`` for the
same pattern).
"""
import app.gateway.app as app_module
from deerflow.config.app_config import AppConfig
from deerflow.config.sandbox_config import SandboxConfig
from deerflow.extensions import reset_loaded_extensions, reset_runtime_diagnostics
config = AppConfig(sandbox=SandboxConfig(use="test"))
monkeypatch.setattr(app_module, "get_app_config", lambda: config)
reset_loaded_extensions()
reset_runtime_diagnostics()
yield
reset_runtime_diagnostics()
reset_loaded_extensions()
def test_host_installs_a_resolver_on_app_state(_stub_app_config):
from app.gateway.app import create_app
app = create_app()
assert callable(getattr(app.state, EXTENSION_PRINCIPAL_RESOLVER_KEY, None))
def test_the_installed_resolver_projects_system_role_into_roles(_stub_app_config):
"""The host's only role concept is the single system_role column; the
projection must actually populate ``roles`` from it rather than reading a
"roles" attribute the user model never had (which would always resolve to
an empty tuple, silently breaking the documented contract)."""
from app.gateway.app import create_app
app = create_app()
resolver = getattr(app.state, EXTENSION_PRINCIPAL_RESOLVER_KEY)
admin_request = SimpleNamespace(state=SimpleNamespace(user=SimpleNamespace(id="u1", system_role="admin"), auth_source=None))
assert resolver(admin_request).roles == ("admin",)
plain_request = SimpleNamespace(state=SimpleNamespace(user=SimpleNamespace(id="u2", system_role="user"), auth_source=None))
assert resolver(plain_request).roles == ("user",)
no_role_request = SimpleNamespace(state=SimpleNamespace(user=SimpleNamespace(id="u3", system_role=None), auth_source=None))
assert resolver(no_role_request).roles == ()