mirror of
https://github.com/tiennm99/DocsGPT.git
synced 2026-10-04 16:13:23 +00:00
Source access control --------------------- `active_docs` is client-supplied and reached the retriever unchecked, and the retriever queries `WHERE source_id = <id>` with no owner predicate — so any caller could pass any source id to /stream or /api/answer and have another tenant's documents quoted back, while /api/sources/<id>/search correctly refused the same id. Gate it through `can_access`, the helper the guarded endpoints already use, and filter `self.source` down to the authorized set. Fails closed: no principal, or a check that errors, drops the source. Three sibling paths had the same gap: - workflow agent nodes: `AgentNodeConfig.sources` is written verbatim from client JSON at save time and nothing validated it, so a node could name any tenant's source. Gate against the workflow owner, so shared workflows keep reading their owner's sources like shared agents do. - /api/share: `_resolve_source_pg_id` resolved any id with no ownership predicate and baked it into the agent the share creates; /api/search then searched it. Authorize before attaching. - search_service: re-resolve the ids stored on an agent row instead of trusting them, so a row written by any future path with the same gap cannot be read back. Team grantees previously lost their source's retrieval config: the post-check read was still owner-scoped, so it missed and fell back to defaults (an `agentic_tool` source was bulk-prefetched for every grantee). Read unscoped after `can_access` passes. Retrieval --------- `PGVectorStore._ensure_table_exists` created an IVFFlat index on the empty table it had just created. IVFFlat computes centroids at build time, so those centroids were random, and combined with the `source_id` post-filter a source with hundreds of embedded chunks returned zero rows — retrieval reported no documents, the model answered from memory, and nothing was logged. Stop creating the index (exact search is correct and fast well past the sizes most deployments reach); raise `ivfflat.probes` to sqrt(lists) where an index still exists; and re-run a short indexed search exactly, since post-filtering means no index setting can guarantee a full result. `graphrag` had the same empty-table index with no fallback at all. Also: bound `chunks` to 0-500 on both the request and agent paths (0 still means "skip retrieval"), let a source's configured `retrieval.chunks` outrank the request body, and cap ClassicRAG's per-source floor at max(top_k, n_sources) so attaching sources cannot inflate the result set. Silent failures --------------- An empty retrieval was invisible to both the model and the client: the `source` event was suppressed when the list was empty, so "searched and found nothing" looked identical to "no source attached", and the prompt said nothing at all. Emit the event always, and tell the model when a search ran and returned nothing. A file that parses to nothing now fails ingest with a message naming the cause instead of storing an embedding of the empty string. `score_threshold` returns warnings when the active store or retriever cannot honour it. Prompt structure ---------------- Retrieved documents move from the system prompt into the user turn, with the injection guard restated next to them: they change every turn (defeating prefix caching), they are third-party text that should not carry system authority, and routing them through the query budget makes them truncatable rather than silently crowding it out. Documents are shed lowest-ranked-first before the question is touched. The six chat presets (3 tones x 2 retrieval modes) differed only in their Answering section; they are now composed from single-source fragments at load time, not through Jinja inheritance, which would have opened a file-read surface in the template sandbox and broken the tool-prefetch parser. Per-tool guidance moves out of the prompt into tool schemas, so it travels with the tool and cannot render when the tool is absent. A plain-text custom prompt is staged as a persona value inside the skeleton instead of replacing it wholesale — it used to silently lose the injection guard, platform block, memory and attachments, and its braces are now inert. Other fixes ----------- - agents/base: an oversized system prompt drove the query budget negative and dispatched a full-price request with an empty question; raise instead. - llm/anthropic: migrate off the retired Text Completions API. It flattened history to first+last message and ignored tools entirely. Adds the missing Anthropic handler, without which every tool call was silently dropped. - sources/upload: `sitemap` had no branch, so every sitemap ingest died on a TypeError; `validate_url` now rejects a falsy URL cleanly. - workflow nodes: retrieved documents never reached the node agent, so a classic node with a source and an ordinary prompt answered "I have no documents" while the run reported completed. - parser/bulk: copy the metadata dict, or every chunk reports the last chunk's token_count. - crawler_loader: carry the page title, or citations render the whole chunk body as the label.
183 lines
7.5 KiB
Python
183 lines
7.5 KiB
Python
"""Tests for per-source search exposure partitioning (E1 / D11)."""
|
|
|
|
from __future__ import annotations
|
|
|
|
from unittest.mock import MagicMock, patch
|
|
|
|
import pytest
|
|
|
|
from application.api.answer.services.stream_processor import StreamProcessor
|
|
from application.storage.db.source_config import RetrievalConfig
|
|
|
|
|
|
def _processor() -> StreamProcessor:
|
|
"""A bare StreamProcessor with only the fields the exposure helpers touch.
|
|
|
|
Built via ``__new__`` to skip the DB-heavy ``__init__``; the exposure
|
|
methods read ``all_sources`` / ``source`` / ``agent_config`` only.
|
|
"""
|
|
sp = StreamProcessor.__new__(StreamProcessor)
|
|
sp.all_sources = []
|
|
sp.source = {}
|
|
sp.agent_config = {}
|
|
sp.retriever_config = {"retriever_name": "classic", "chunks": 2, "doc_token_limit": 50000}
|
|
sp.data = {}
|
|
return sp
|
|
|
|
|
|
@pytest.mark.unit
|
|
class TestExposurePartition:
|
|
def test_no_config_all_default_to_prefetch(self):
|
|
sp = _processor()
|
|
sp.all_sources = [{"id": "a", "retrieval": None}, {"id": "b", "retrieval": None}]
|
|
prefetch, agentic = sp._exposure_partition()
|
|
assert [e["id"] for e in prefetch] == ["a", "b"]
|
|
assert agentic == []
|
|
|
|
def test_mixed_partition(self):
|
|
sp = _processor()
|
|
sp.all_sources = [
|
|
{"id": "a", "retrieval": RetrievalConfig(exposure="prefetch")},
|
|
{"id": "b", "retrieval": RetrievalConfig(exposure="agentic_tool")},
|
|
{"id": "c", "retrieval": RetrievalConfig()}, # default prefetch
|
|
]
|
|
prefetch, agentic = sp._exposure_partition()
|
|
assert sorted(e["id"] for e in prefetch) == ["a", "c"]
|
|
assert [e["id"] for e in agentic] == ["b"]
|
|
|
|
def test_exposure_of_dict_and_model_and_missing(self):
|
|
sp = _processor()
|
|
assert sp._exposure_of(RetrievalConfig(exposure="agentic_tool")) == "agentic_tool"
|
|
assert sp._exposure_of({"exposure": "agentic_tool"}) == "agentic_tool"
|
|
assert sp._exposure_of(None) == "prefetch"
|
|
assert sp._exposure_of({}) == "prefetch"
|
|
|
|
def test_source_for_docs(self):
|
|
sp = _processor()
|
|
assert sp._source_for_docs(["a", "b"]) == {"active_docs": ["a", "b"]}
|
|
assert sp._source_for_docs([]) == {}
|
|
|
|
|
|
@pytest.mark.unit
|
|
class TestBuildAgentExposure:
|
|
def _agentic_processor(self):
|
|
sp = _processor()
|
|
sp.agent_config = {"agent_type": "agentic"}
|
|
sp.initialize = MagicMock()
|
|
sp.pre_fetch_docs = MagicMock(return_value=("docs_together", ["doc"]))
|
|
sp.pre_fetch_tools = MagicMock(return_value={"tool": {}})
|
|
sp.create_agent = MagicMock(return_value="AGENT")
|
|
return sp
|
|
|
|
def test_all_prefetch_is_today_no_partition(self):
|
|
# No agentic_tool source → today's behavior: no pre-fetch, no
|
|
# agentic_sources passed (tool exposes all sources).
|
|
sp = self._agentic_processor()
|
|
sp.all_sources = [
|
|
{"id": "a", "retrieval": RetrievalConfig()},
|
|
{"id": "b", "retrieval": None},
|
|
]
|
|
result = sp.build_agent("q")
|
|
assert result == "AGENT"
|
|
sp.pre_fetch_docs.assert_not_called()
|
|
_, kwargs = sp.create_agent.call_args
|
|
assert "agentic_sources" not in kwargs
|
|
|
|
def test_mixed_prefetches_and_scopes_tool(self):
|
|
sp = self._agentic_processor()
|
|
sp.all_sources = [
|
|
{"id": "a", "retrieval": RetrievalConfig(exposure="prefetch")},
|
|
{"id": "b", "retrieval": RetrievalConfig(exposure="agentic_tool")},
|
|
]
|
|
sp.build_agent("q")
|
|
# Pre-fetch ran scoped to the prefetch subset.
|
|
sp.pre_fetch_docs.assert_called_once()
|
|
_, pf_kwargs = sp.pre_fetch_docs.call_args
|
|
assert pf_kwargs.get("exposure") == "prefetch"
|
|
# create_agent received only the agentic_tool subset as the tool sources.
|
|
_, kwargs = sp.create_agent.call_args
|
|
assert [e["id"] for e in kwargs["agentic_sources"]] == ["b"]
|
|
|
|
def _classic_processor(self):
|
|
sp = _processor()
|
|
sp.agent_config = {"agent_type": "classic"}
|
|
sp.initialize = MagicMock()
|
|
sp.pre_fetch_docs = MagicMock(return_value=("docs_together", ["doc"]))
|
|
sp.pre_fetch_tools = MagicMock(return_value=None)
|
|
sp.create_agent = MagicMock(return_value="AGENT")
|
|
return sp
|
|
|
|
def test_classic_default_prefetches_all_no_partition(self):
|
|
# Default classic (all prefetch / no config): byte-identical to today —
|
|
# unscoped pre-fetch and no agentic_sources, so no search tool is added.
|
|
sp = self._classic_processor()
|
|
sp.all_sources = [
|
|
{"id": "a", "retrieval": RetrievalConfig()},
|
|
{"id": "b", "retrieval": None},
|
|
]
|
|
result = sp.build_agent("q")
|
|
assert result == "AGENT"
|
|
sp.pre_fetch_docs.assert_called_once_with("q")
|
|
_, kwargs = sp.create_agent.call_args
|
|
assert "agentic_sources" not in kwargs
|
|
|
|
def test_classic_no_per_source_detail_is_today(self):
|
|
# Single-source / no-config requests carry no per-source detail; classic
|
|
# must fall back to the unscoped pre-fetch (no exposure scoping).
|
|
sp = self._classic_processor()
|
|
sp.all_sources = []
|
|
sp.source = {"active_docs": ["a"]}
|
|
sp.build_agent("q")
|
|
sp.pre_fetch_docs.assert_called_once_with("q")
|
|
_, kwargs = sp.create_agent.call_args
|
|
assert "agentic_sources" not in kwargs
|
|
|
|
def test_classic_mixed_prefetches_and_scopes_tool(self):
|
|
# Classic with an agentic_tool source now pre-fetches only the prefetch
|
|
# subset and exposes the agentic_tool subset via the search tool.
|
|
sp = self._classic_processor()
|
|
sp.all_sources = [
|
|
{"id": "a", "retrieval": RetrievalConfig(exposure="prefetch")},
|
|
{"id": "b", "retrieval": RetrievalConfig(exposure="agentic_tool")},
|
|
]
|
|
sp.build_agent("q")
|
|
sp.pre_fetch_docs.assert_called_once()
|
|
_, pf_kwargs = sp.pre_fetch_docs.call_args
|
|
assert pf_kwargs.get("exposure") == "prefetch"
|
|
_, kwargs = sp.create_agent.call_args
|
|
assert [e["id"] for e in kwargs["agentic_sources"]] == ["b"]
|
|
|
|
|
|
@pytest.mark.unit
|
|
class TestNonAgentSourceConfig:
|
|
"""The non-agent chat path must also load per-source config so exposure
|
|
(and other per-source overrides) are honored, not just the agent path."""
|
|
|
|
def test_active_docs_loads_per_source_retrieval_config(self):
|
|
sp = StreamProcessor.__new__(StreamProcessor)
|
|
sp._agent_data = None
|
|
sp.data = {"active_docs": "s1"}
|
|
sp.initial_user_id = "user1"
|
|
sp.source = {}
|
|
sp.all_sources = []
|
|
fake_source = {
|
|
"config": {"retrieval": {"exposure": "agentic_tool", "chunks": 7}}
|
|
}
|
|
with patch(
|
|
"application.api.answer.services.stream_processor.db_readonly"
|
|
), patch(
|
|
"application.api.answer.services.stream_processor.can_access",
|
|
return_value=True,
|
|
), patch(
|
|
"application.api.answer.services.stream_processor.SourcesRepository"
|
|
) as repo:
|
|
# Read unscoped after the access check, so a team grantee gets the
|
|
# source's real config instead of silently falling back to defaults.
|
|
repo.return_value.get_by_id.return_value = fake_source
|
|
sp._configure_source()
|
|
assert sp.source == {"active_docs": "s1"}
|
|
assert len(sp.all_sources) == 1
|
|
assert sp.all_sources[0]["id"] == "s1"
|
|
assert sp.all_sources[0]["retrieval"].exposure == "agentic_tool"
|
|
assert sp.all_sources[0]["retrieval"].chunks == 7
|