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.
442 lines
15 KiB
Python
442 lines
15 KiB
Python
"""Tests for application/api/user/sharing/routes.py.
|
|
|
|
Post-PG cutover: routes use the PG repositories (ConversationsRepository,
|
|
SharedConversationsRepository, AgentsRepository, AttachmentsRepository) and
|
|
the ``db_session`` / ``db_readonly`` context managers. These tests use the
|
|
ephemeral ``pg_conn`` fixture to exercise real SQL.
|
|
"""
|
|
|
|
from contextlib import contextmanager
|
|
from unittest.mock import patch
|
|
|
|
import pytest
|
|
from flask import Flask
|
|
|
|
|
|
@pytest.fixture
|
|
def app():
|
|
return Flask(__name__)
|
|
|
|
|
|
@contextmanager
|
|
def _patch_sharing_db(conn):
|
|
@contextmanager
|
|
def _yield_conn():
|
|
yield conn
|
|
|
|
with patch(
|
|
"application.api.user.sharing.routes.db_session", _yield_conn
|
|
), patch(
|
|
"application.api.user.sharing.routes.db_readonly", _yield_conn
|
|
):
|
|
yield
|
|
|
|
|
|
def _seed_conversation(pg_conn, user_id, name="Test Conv", message_count=0):
|
|
from application.storage.db.repositories.conversations import (
|
|
ConversationsRepository,
|
|
)
|
|
repo = ConversationsRepository(pg_conn)
|
|
conv = repo.create(user_id, name=name)
|
|
conv_id = str(conv["id"])
|
|
for i in range(message_count):
|
|
repo.append_message(conv_id, {"prompt": f"p{i}", "response": f"r{i}"})
|
|
return conv_id
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# ShareConversation — /share endpoint
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
@pytest.mark.unit
|
|
class TestShareConversation:
|
|
def test_returns_401_unauthenticated(self, app):
|
|
from application.api.user.sharing.routes import ShareConversation
|
|
|
|
with app.test_request_context(
|
|
"/api/share?isPromptable=false",
|
|
method="POST",
|
|
json={"conversation_id": "x"},
|
|
):
|
|
from flask import request
|
|
|
|
request.decoded_token = None
|
|
response = ShareConversation().post()
|
|
|
|
assert response.status_code == 401
|
|
|
|
def test_returns_400_missing_conversation_id(self, app):
|
|
from application.api.user.sharing.routes import ShareConversation
|
|
|
|
with app.test_request_context(
|
|
"/api/share?isPromptable=false",
|
|
method="POST",
|
|
json={},
|
|
):
|
|
from flask import request
|
|
|
|
request.decoded_token = {"sub": "u"}
|
|
response = ShareConversation().post()
|
|
|
|
assert response.status_code == 400
|
|
|
|
def test_returns_400_missing_isPromptable(self, app):
|
|
from application.api.user.sharing.routes import ShareConversation
|
|
|
|
with app.test_request_context(
|
|
"/api/share",
|
|
method="POST",
|
|
json={"conversation_id": "x"},
|
|
):
|
|
from flask import request
|
|
|
|
request.decoded_token = {"sub": "u"}
|
|
response = ShareConversation().post()
|
|
|
|
assert response.status_code == 400
|
|
|
|
def test_returns_404_for_missing_conversation(self, app, pg_conn):
|
|
from application.api.user.sharing.routes import ShareConversation
|
|
|
|
with _patch_sharing_db(pg_conn), app.test_request_context(
|
|
"/api/share?isPromptable=false",
|
|
method="POST",
|
|
json={"conversation_id": "00000000-0000-0000-0000-000000000000"},
|
|
):
|
|
from flask import request
|
|
|
|
request.decoded_token = {"sub": "u"}
|
|
response = ShareConversation().post()
|
|
|
|
assert response.status_code == 404
|
|
|
|
def test_creates_non_promptable_share(self, app, pg_conn):
|
|
from application.api.user.sharing.routes import ShareConversation
|
|
|
|
user = "user-npshare"
|
|
conv_id = _seed_conversation(pg_conn, user, message_count=3)
|
|
|
|
with _patch_sharing_db(pg_conn), app.test_request_context(
|
|
"/api/share?isPromptable=false",
|
|
method="POST",
|
|
json={"conversation_id": conv_id},
|
|
):
|
|
from flask import request
|
|
|
|
request.decoded_token = {"sub": user}
|
|
response = ShareConversation().post()
|
|
|
|
assert response.status_code == 201
|
|
assert response.json["success"] is True
|
|
assert "identifier" in response.json
|
|
|
|
def test_reuse_non_promptable_share_returns_same_identifier(
|
|
self, app, pg_conn,
|
|
):
|
|
from application.api.user.sharing.routes import ShareConversation
|
|
|
|
user = "user-reuse-np"
|
|
conv_id = _seed_conversation(pg_conn, user, message_count=1)
|
|
|
|
ids = []
|
|
for _ in range(2):
|
|
with _patch_sharing_db(pg_conn), app.test_request_context(
|
|
"/api/share?isPromptable=false",
|
|
method="POST",
|
|
json={"conversation_id": conv_id},
|
|
):
|
|
from flask import request
|
|
|
|
request.decoded_token = {"sub": user}
|
|
r = ShareConversation().post()
|
|
ids.append(r.json["identifier"])
|
|
assert ids[0] == ids[1]
|
|
|
|
def test_creates_promptable_share(self, app, pg_conn):
|
|
from application.api.user.sharing.routes import ShareConversation
|
|
|
|
user = "user-pshare"
|
|
conv_id = _seed_conversation(pg_conn, user, message_count=2)
|
|
|
|
with _patch_sharing_db(pg_conn), app.test_request_context(
|
|
"/api/share?isPromptable=true",
|
|
method="POST",
|
|
json={"conversation_id": conv_id, "chunks": 4},
|
|
):
|
|
from flask import request
|
|
|
|
request.decoded_token = {"sub": user}
|
|
response = ShareConversation().post()
|
|
|
|
assert response.status_code == 201
|
|
assert response.json["success"] is True
|
|
|
|
def test_reuse_promptable_share_returns_200(self, app, pg_conn):
|
|
from application.api.user.sharing.routes import ShareConversation
|
|
|
|
user = "user-reuse-p"
|
|
conv_id = _seed_conversation(pg_conn, user, message_count=1)
|
|
|
|
with _patch_sharing_db(pg_conn), app.test_request_context(
|
|
"/api/share?isPromptable=true",
|
|
method="POST",
|
|
json={"conversation_id": conv_id, "chunks": 2},
|
|
):
|
|
from flask import request
|
|
|
|
request.decoded_token = {"sub": user}
|
|
first = ShareConversation().post()
|
|
assert first.status_code == 201
|
|
|
|
with _patch_sharing_db(pg_conn), app.test_request_context(
|
|
"/api/share?isPromptable=true",
|
|
method="POST",
|
|
json={"conversation_id": conv_id, "chunks": 2},
|
|
):
|
|
from flask import request
|
|
|
|
request.decoded_token = {"sub": user}
|
|
second = ShareConversation().post()
|
|
# Second call reuses agent → status 200
|
|
assert second.status_code == 200
|
|
|
|
def test_promptable_with_invalid_chunks_coerces_none(self, app, pg_conn):
|
|
from application.api.user.sharing.routes import ShareConversation
|
|
|
|
user = "user-bad-chunks"
|
|
conv_id = _seed_conversation(pg_conn, user, message_count=1)
|
|
|
|
with _patch_sharing_db(pg_conn), app.test_request_context(
|
|
"/api/share?isPromptable=true",
|
|
method="POST",
|
|
json={"conversation_id": conv_id, "chunks": "notanumber"},
|
|
):
|
|
from flask import request
|
|
|
|
request.decoded_token = {"sub": user}
|
|
response = ShareConversation().post()
|
|
|
|
assert response.status_code == 201
|
|
|
|
def test_db_error_returns_400(self, app):
|
|
from application.api.user.sharing.routes import ShareConversation
|
|
|
|
@contextmanager
|
|
def _broken():
|
|
raise RuntimeError("boom")
|
|
yield
|
|
|
|
with patch(
|
|
"application.api.user.sharing.routes.db_session", _broken
|
|
), app.test_request_context(
|
|
"/api/share?isPromptable=false",
|
|
method="POST",
|
|
json={"conversation_id": "x"},
|
|
):
|
|
from flask import request
|
|
|
|
request.decoded_token = {"sub": "u"}
|
|
response = ShareConversation().post()
|
|
|
|
assert response.status_code == 400
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# GetPubliclySharedConversations — /shared_conversation/<identifier>
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
@pytest.mark.unit
|
|
class TestGetPubliclySharedConversations:
|
|
def test_returns_404_for_missing_identifier(self, app, pg_conn):
|
|
from application.api.user.sharing.routes import (
|
|
GetPubliclySharedConversations,
|
|
)
|
|
|
|
with _patch_sharing_db(pg_conn), app.test_request_context(
|
|
"/api/shared_conversation/abc-does-not-exist"
|
|
):
|
|
response = GetPubliclySharedConversations().get(
|
|
"00000000-0000-0000-0000-000000000000"
|
|
)
|
|
|
|
assert response.status_code == 404
|
|
|
|
def test_returns_shared_conversation(self, app, pg_conn):
|
|
from application.api.user.sharing.routes import (
|
|
GetPubliclySharedConversations,
|
|
ShareConversation,
|
|
)
|
|
|
|
user = "user-get-shared"
|
|
conv_id = _seed_conversation(pg_conn, user, name="Chat A", message_count=2)
|
|
|
|
with _patch_sharing_db(pg_conn), app.test_request_context(
|
|
"/api/share?isPromptable=false",
|
|
method="POST",
|
|
json={"conversation_id": conv_id},
|
|
):
|
|
from flask import request
|
|
|
|
request.decoded_token = {"sub": user}
|
|
share_resp = ShareConversation().post()
|
|
identifier = share_resp.json["identifier"]
|
|
|
|
with _patch_sharing_db(pg_conn), app.test_request_context(
|
|
f"/api/shared_conversation/{identifier}"
|
|
):
|
|
response = GetPubliclySharedConversations().get(identifier)
|
|
|
|
assert response.status_code == 200
|
|
data = response.json
|
|
assert data["success"] is True
|
|
assert data["title"] == "Chat A"
|
|
assert isinstance(data["queries"], list)
|
|
assert len(data["queries"]) == 2
|
|
# Non-promptable share should not expose api_key
|
|
assert "api_key" not in data
|
|
|
|
def test_returns_api_key_for_promptable_share(self, app, pg_conn):
|
|
from application.api.user.sharing.routes import (
|
|
GetPubliclySharedConversations,
|
|
ShareConversation,
|
|
)
|
|
|
|
user = "user-promptable"
|
|
conv_id = _seed_conversation(pg_conn, user, message_count=1)
|
|
|
|
with _patch_sharing_db(pg_conn), app.test_request_context(
|
|
"/api/share?isPromptable=true",
|
|
method="POST",
|
|
json={"conversation_id": conv_id, "chunks": 2},
|
|
):
|
|
from flask import request
|
|
|
|
request.decoded_token = {"sub": user}
|
|
share_resp = ShareConversation().post()
|
|
identifier = share_resp.json["identifier"]
|
|
|
|
with _patch_sharing_db(pg_conn), app.test_request_context(
|
|
f"/api/shared_conversation/{identifier}"
|
|
):
|
|
response = GetPubliclySharedConversations().get(identifier)
|
|
|
|
assert response.status_code == 200
|
|
assert "api_key" in response.json
|
|
assert response.json["api_key"]
|
|
|
|
def test_db_error_returns_400(self, app):
|
|
from application.api.user.sharing.routes import (
|
|
GetPubliclySharedConversations,
|
|
)
|
|
|
|
@contextmanager
|
|
def _broken():
|
|
raise RuntimeError("boom")
|
|
yield
|
|
|
|
with patch(
|
|
"application.api.user.sharing.routes.db_readonly", _broken
|
|
), app.test_request_context("/api/shared_conversation/abc"):
|
|
response = GetPubliclySharedConversations().get("abc")
|
|
|
|
assert response.status_code == 400
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Helper functions
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
@pytest.mark.unit
|
|
class TestResolvePromptPgId:
|
|
def test_returns_none_for_default(self, pg_conn):
|
|
from application.api.user.sharing.routes import _resolve_prompt_pg_id
|
|
|
|
assert _resolve_prompt_pg_id(pg_conn, "default", "u") is None
|
|
assert _resolve_prompt_pg_id(pg_conn, "", "u") is None
|
|
assert _resolve_prompt_pg_id(pg_conn, None, "u") is None
|
|
|
|
def test_resolves_uuid_by_ownership(self, pg_conn):
|
|
from application.api.user.sharing.routes import _resolve_prompt_pg_id
|
|
from application.storage.db.repositories.prompts import PromptsRepository
|
|
|
|
prompt = PromptsRepository(pg_conn).create("owner", "p", "c")
|
|
pid = str(prompt["id"])
|
|
assert _resolve_prompt_pg_id(pg_conn, pid, "owner") == pid
|
|
# Other user cannot claim
|
|
assert _resolve_prompt_pg_id(pg_conn, pid, "someone-else") is None
|
|
|
|
def test_returns_none_for_unknown_legacy(self, pg_conn):
|
|
from application.api.user.sharing.routes import _resolve_prompt_pg_id
|
|
|
|
assert _resolve_prompt_pg_id(pg_conn, "507f1f77bcf86cd799439011", "u") is None
|
|
|
|
|
|
@pytest.mark.unit
|
|
class TestResolveSourcePgId:
|
|
def test_returns_none_for_falsy(self, pg_conn):
|
|
from application.api.user.sharing.routes import _resolve_source_pg_id
|
|
|
|
assert _resolve_source_pg_id(pg_conn, None, "u") is None
|
|
assert _resolve_source_pg_id(pg_conn, "", "u") is None
|
|
|
|
def test_returns_none_for_unknown_uuid(self, pg_conn):
|
|
from application.api.user.sharing.routes import _resolve_source_pg_id
|
|
|
|
assert (
|
|
_resolve_source_pg_id(
|
|
pg_conn, "00000000-0000-0000-0000-000000000000", "u"
|
|
)
|
|
is None
|
|
)
|
|
|
|
def test_returns_none_for_unknown_legacy(self, pg_conn):
|
|
from application.api.user.sharing.routes import _resolve_source_pg_id
|
|
|
|
assert _resolve_source_pg_id(pg_conn, "507f1f77bcf86cd799439011", "u") is None
|
|
|
|
|
|
@pytest.mark.unit
|
|
class TestShareSourceAuthorization:
|
|
"""A share must not attach a source the sharer cannot read.
|
|
|
|
``_resolve_source_pg_id`` resolved any id with no ownership predicate, and
|
|
the id was baked into the agent the share creates — which ``/api/search``
|
|
then searched, returning another tenant's documents.
|
|
"""
|
|
|
|
def test_unauthorized_source_is_refused(self, monkeypatch, pg_conn):
|
|
"""A resolvable id the caller cannot read must not reach the agent."""
|
|
import application.api.user.team_sharing as ts
|
|
|
|
from application.api.user.sharing.routes import _resolve_source_pg_id
|
|
|
|
monkeypatch.setattr(ts, "can_access", lambda *a, **k: False)
|
|
assert (
|
|
_resolve_source_pg_id(
|
|
pg_conn, "00000000-0000-0000-0000-000000000000", "attacker"
|
|
)
|
|
is None
|
|
)
|
|
|
|
def test_missing_principal_resolves_nothing(self, pg_conn):
|
|
from application.api.user.sharing.routes import _resolve_source_pg_id
|
|
|
|
assert _resolve_source_pg_id(pg_conn, "any-id", None) is None
|
|
|
|
def test_authorized_source_passes_through(self, monkeypatch):
|
|
import application.api.user.team_sharing as ts
|
|
from application.api.user.sharing.routes import _authorized_source
|
|
|
|
monkeypatch.setattr(ts, "can_access", lambda *a, **k: True)
|
|
assert _authorized_source(None, ("src-1",), "owner") == "src-1"
|
|
|
|
def test_denied_source_returns_none(self, monkeypatch):
|
|
import application.api.user.team_sharing as ts
|
|
from application.api.user.sharing.routes import _authorized_source
|
|
|
|
monkeypatch.setattr(ts, "can_access", lambda *a, **k: False)
|
|
assert _authorized_source(None, ("src-1",), "stranger") is None
|