mirror of
https://github.com/tiennm99/DocsGPT.git
synced 2026-10-13 14:15:52 +00:00
Hold resumed turns and public-link visitors to the right wiki rules
A paused turn is found by the agent owner's id, so anyone holding one of the owner's agent keys could resume the owner's own chat with its saved wiki edit rights. A resume now counts as an API or widget caller when either the saved state or the resuming request is one, cuts the wiki tool to wiki_view unless the wiki allows outside edits, and gives the tool executor the same flags. A request that names an agent, by key or id, may only resume that agent's turn; otherwise the claim is released and the request refused. Public-link visitors run as themselves and reach only wikis they may edit, so the wiki switch no longer applies to them. Instead every wiki write in a public-link run waits for the visitor's approval, so the agent owner's prompt or sources can't steer an edit to the visitor's wiki unasked.
This commit is contained in:
1 parent
91e70d2f0c
commit
051452c438
10 files changed
+405
-64
No files matched your search
@@ -23,7 +23,7 @@ MAX_WIKI_PAGE_BYTES = 1_000_000
|
||||
_WRITE_ACTIONS = frozenset({"create", "str_replace", "insert", "delete", "rename"})
|
||||
|
||||
OUTSIDE_EDITS_DENIED = (
|
||||
"Error: This wiki's owner doesn't let API, widget or public-link users edit it, "
|
||||
"Error: This wiki's owner doesn't let API or widget users edit it, "
|
||||
"so it can't be changed from here. You can still read it."
|
||||
)
|
||||
|
||||
@@ -45,8 +45,8 @@ class WikiTool(Tool):
|
||||
self.config = config
|
||||
self.source_id: Optional[str] = config.get("source_id")
|
||||
self.source_owner_id: Optional[str] = config.get("source_owner_id")
|
||||
# An API-key, widget or public-link run: it writes only while the
|
||||
# wiki's owner allows such edits.
|
||||
# An API-key or widget run (it acts as the agent's owner): it writes
|
||||
# only while the wiki's owner allows such edits.
|
||||
self.outside_caller: bool = bool(config.get("outside_caller"))
|
||||
decoded_token = config.get("decoded_token") or {}
|
||||
self.updated_by: Optional[str] = (
|
||||
@@ -249,7 +249,7 @@ class WikiTool(Tool):
|
||||
Fails closed on a missing row or a failed lookup.
|
||||
|
||||
Returns:
|
||||
bool: Whether an API, widget or public-link run may edit the wiki.
|
||||
bool: Whether an API-key or widget run may edit the wiki.
|
||||
"""
|
||||
try:
|
||||
with db_readonly() as conn:
|
||||
@@ -531,11 +531,12 @@ class WikiTool(Tool):
|
||||
return f"Renamed: {validated_old} -> {validated_new}"
|
||||
|
||||
|
||||
def build_wiki_tool_entry(writes_allowed: bool = True) -> Dict[str, Any]:
|
||||
def build_wiki_tool_entry(writes_allowed: bool = True, approval_required: bool = False) -> Dict[str, Any]:
|
||||
"""Build the synthetic tools_dict entry for the WikiTool.
|
||||
|
||||
Args:
|
||||
writes_allowed: False offers the model only ``wiki_view``.
|
||||
approval_required: Every write action waits for the caller's approval.
|
||||
"""
|
||||
entry = {"name": "wiki"}
|
||||
entry["actions"] = [
|
||||
@@ -543,6 +544,8 @@ def build_wiki_tool_entry(writes_allowed: bool = True) -> Dict[str, Any]:
|
||||
for action in _wiki_actions_metadata()
|
||||
if writes_allowed or action["name"] == "wiki_view"
|
||||
]
|
||||
if approval_required:
|
||||
_require_write_approval(entry)
|
||||
return entry
|
||||
|
||||
|
||||
@@ -550,8 +553,14 @@ def _wiki_actions_metadata() -> List[Dict[str, Any]]:
|
||||
return WikiTool().get_actions_metadata()
|
||||
|
||||
|
||||
def _require_write_approval(entry: Dict[str, Any]) -> None:
|
||||
for action in entry.get("actions") or []:
|
||||
if action.get("name") != "wiki_view":
|
||||
action["require_approval"] = True
|
||||
|
||||
|
||||
def outside_edits_allowed(source_row: Optional[Dict[str, Any]]) -> bool:
|
||||
"""Whether a wiki's owner lets API, widget and public-link runs edit it."""
|
||||
"""Whether a wiki's owner lets API-key and widget runs edit it."""
|
||||
return bool(source_row and source_row.get("wiki_outside_edits"))
|
||||
|
||||
|
||||
@@ -578,13 +587,17 @@ def add_wiki_tool(tools_dict: Dict, config: Dict) -> None:
|
||||
Mirrors ``add_internal_search_tool``: the entry carries ``id=WIKI_TOOL_ID``
|
||||
so the executor can resolve the synthetic (DB-rowless) tool, and a ``config``
|
||||
the executor copies into the loaded tool. Mutates ``tools_dict`` in place.
|
||||
``writes_allowed=False`` (an API, widget or public-link run on a wiki
|
||||
whose owner hasn't allowed their edits) offers only ``wiki_view``; the
|
||||
tool still refuses writes itself from ``outside_caller``.
|
||||
``writes_allowed=False`` (an API-key or widget run on a wiki whose owner
|
||||
hasn't allowed their edits) offers only ``wiki_view``; the tool still
|
||||
refuses writes itself from ``outside_caller``. ``approval_required`` (a
|
||||
public-link run) puts every write behind the caller's approval.
|
||||
"""
|
||||
if not config or not config.get("source_id") or not config.get("source_owner_id"):
|
||||
return
|
||||
entry = build_wiki_tool_entry(writes_allowed=config.get("writes_allowed", True) is not False)
|
||||
entry = build_wiki_tool_entry(
|
||||
writes_allowed=config.get("writes_allowed", True) is not False,
|
||||
approval_required=bool(config.get("approval_required")),
|
||||
)
|
||||
entry["id"] = WIKI_TOOL_ID
|
||||
entry["config"] = build_wiki_tool_config(
|
||||
source_id=config["source_id"],
|
||||
@@ -594,3 +607,46 @@ def add_wiki_tool(tools_dict: Dict, config: Dict) -> None:
|
||||
outside_caller=bool(config.get("outside_caller")),
|
||||
)
|
||||
tools_dict[WIKI_TOOL_ID] = entry
|
||||
|
||||
|
||||
def apply_resume_caller_rules(
|
||||
tools_dict: Dict, *, outside_caller: bool, public_link_caller: bool
|
||||
) -> None:
|
||||
"""Hold a resumed run's saved WikiTool entry to its caller's rules.
|
||||
|
||||
A paused turn is resumed by whoever sends its tool actions, which may not
|
||||
be who started it: a widget key can resume the owner's own chat. So the
|
||||
saved entry is tightened here rather than trusted. An API-key or widget
|
||||
run gets ``outside_caller`` and, unless the wiki's owner allows their
|
||||
edits (read live), only ``wiki_view``; a public-link run approves every
|
||||
write. Never loosens an entry. Mutates ``tools_dict`` in place.
|
||||
|
||||
Args:
|
||||
tools_dict: The resumed run's tools.
|
||||
outside_caller: The saved state or the resuming request is an
|
||||
API-key or widget caller.
|
||||
public_link_caller: The saved state or the resuming request reached
|
||||
the agent through its public link.
|
||||
"""
|
||||
entry = tools_dict.get(WIKI_TOOL_ID) if isinstance(tools_dict, dict) else None
|
||||
if not isinstance(entry, dict):
|
||||
return
|
||||
if public_link_caller:
|
||||
_require_write_approval(entry)
|
||||
if not outside_caller:
|
||||
return
|
||||
config = entry.get("config")
|
||||
if not isinstance(config, dict):
|
||||
config = {}
|
||||
entry["config"] = config
|
||||
config["outside_caller"] = True
|
||||
allowed = False
|
||||
source_id = config.get("source_id")
|
||||
if source_id:
|
||||
try:
|
||||
with db_readonly() as conn:
|
||||
allowed = outside_edits_allowed(SourcesRepository(conn).get_by_id(str(source_id)))
|
||||
except Exception:
|
||||
logger.exception("Wiki outside-edits check failed for source %s", source_id)
|
||||
if not allowed:
|
||||
entry["actions"] = [a for a in entry.get("actions") or [] if a.get("name") == "wiki_view"]
|
||||
@@ -1,9 +1,8 @@
|
||||
"""0043 wiki outside edits — the wiki owner's say on API, widget and public-link edits.
|
||||
"""0043 wiki outside edits — the wiki owner's say on API and widget edits.
|
||||
|
||||
An agent run from its API key or widget acts as the agent's owner, and a
|
||||
public-link user is a stranger to them, so neither should rewrite a wiki the
|
||||
agent can edit unless the wiki's owner allows it. ``wiki_outside_edits``
|
||||
records that choice on the source; it is off by default, so such runs can
|
||||
An agent run from its API key or widget acts as the agent's owner, so it
|
||||
could rewrite any wiki the owner can edit. ``wiki_outside_edits`` records
|
||||
whether the wiki's owner allows that; it is off by default, so such runs can
|
||||
still read the wiki but not change it.
|
||||
|
||||
Idempotent both ways.
|
||||
|
||||
@@ -27,7 +27,7 @@ from docsgpt.core.model_utils import (
|
||||
get_provider_from_model_id,
|
||||
validate_model_id,
|
||||
)
|
||||
from docsgpt.agents.tools.wiki import outside_edits_allowed
|
||||
from docsgpt.agents.tools.wiki import apply_resume_caller_rules, outside_edits_allowed
|
||||
from docsgpt.core.settings import settings
|
||||
from docsgpt.guardrails.config import AgentConfig
|
||||
from sqlalchemy import text as sql_text
|
||||
@@ -1261,10 +1261,14 @@ class StreamProcessor:
|
||||
this runs at most one owner+source lookup per chat on the hot path.
|
||||
Returns None when no writable wiki source is present.
|
||||
|
||||
An API-key, widget or public-link run (``outside_caller``) gets the
|
||||
edit actions only when the wiki's owner turned on
|
||||
``wiki_outside_edits``; otherwise ``writes_allowed`` is False and the
|
||||
tool offers only ``wiki_view``.
|
||||
An API-key or widget run (``outside_caller``) acts as the agent's
|
||||
owner, so it gets the edit actions only when the wiki's owner turned
|
||||
on ``wiki_outside_edits``; otherwise ``writes_allowed`` is False and
|
||||
the tool offers only ``wiki_view``. A public-link visitor runs as
|
||||
themselves, so they reach only wikis they may edit anyway; the switch
|
||||
doesn't apply to them, but each of their edits waits for their
|
||||
approval (``approval_required``), so the agent's prompt or sources
|
||||
can't steer the model into changing their wiki unasked.
|
||||
"""
|
||||
caller = self.decoded_token.get("sub") if self.decoded_token else None
|
||||
if not caller:
|
||||
@@ -1272,10 +1276,9 @@ class StreamProcessor:
|
||||
# Processors built without __init__ (tests, resume helpers) lack these.
|
||||
run_config = getattr(self, "agent_config", None) or {}
|
||||
outside_caller = bool(
|
||||
run_config.get("external_api_caller")
|
||||
or run_config.get("public_link_caller")
|
||||
or getattr(self, "external_caller", False)
|
||||
run_config.get("external_api_caller") or getattr(self, "external_caller", False)
|
||||
)
|
||||
approval_required = bool(run_config.get("public_link_caller"))
|
||||
|
||||
wiki_config: Optional[Dict[str, Any]] = None
|
||||
try:
|
||||
@@ -1301,6 +1304,7 @@ class StreamProcessor:
|
||||
"user": caller,
|
||||
"outside_caller": outside_caller,
|
||||
"writes_allowed": not outside_caller or outside_edits_allowed(source_doc),
|
||||
"approval_required": approval_required,
|
||||
}
|
||||
break
|
||||
except Exception:
|
||||
@@ -1763,21 +1767,37 @@ class StreamProcessor:
|
||||
from docsgpt.llm.handlers.handler_creator import LLMHandlerCreator
|
||||
from docsgpt.llm.llm_creator import LLMCreator
|
||||
|
||||
# Who is resuming, classified from this request alone: the saved state
|
||||
# says who paused the turn, but anyone holding the agent's key (a
|
||||
# widget key is public) can send the tool actions that resume it.
|
||||
request_key = self.data.get("api_key")
|
||||
original_token = self.decoded_token
|
||||
key_agent = None
|
||||
if request_key:
|
||||
with db_readonly() as conn:
|
||||
key_agent = AgentsRepository(conn).find_by_key(request_key)
|
||||
key_owner = (
|
||||
(key_agent.get("user_id") or key_agent.get("user")) if key_agent else None
|
||||
)
|
||||
request_external = bool(getattr(self, "external_caller", False)) or (
|
||||
bool(request_key) and is_external_api_caller(self.data, original_token, key_owner)
|
||||
)
|
||||
request_public_link = False
|
||||
named_agent = self.data.get("agent_id")
|
||||
if named_agent and not request_key:
|
||||
try:
|
||||
self._get_agent_key(str(named_agent), self.initial_user_id)
|
||||
except Exception as exc:
|
||||
raise ValueError("This conversation can't be resumed with that agent") from exc
|
||||
request_public_link = bool(getattr(self, "public_link_usage", False))
|
||||
|
||||
# api_key-in-body auth carries no JWT, so initial_user_id is None — but
|
||||
# the state was saved under the agent owner. Resolve the owner so the
|
||||
# lookup / mark_resuming / delete_state key on the same id. (No-op for
|
||||
# v1, which already passes an owner-scoped decoded_token.)
|
||||
if self.initial_user_id is None and self.data.get("api_key"):
|
||||
with db_readonly() as conn:
|
||||
agent_doc = AgentsRepository(conn).find_by_key(self.data["api_key"])
|
||||
owner = (
|
||||
(agent_doc.get("user_id") or agent_doc.get("user"))
|
||||
if agent_doc
|
||||
else None
|
||||
)
|
||||
if owner:
|
||||
self.initial_user_id = owner
|
||||
self.decoded_token = {"sub": owner}
|
||||
if self.initial_user_id is None and key_owner:
|
||||
self.initial_user_id = key_owner
|
||||
self.decoded_token = {"sub": key_owner}
|
||||
|
||||
cont_service = ContinuationService()
|
||||
state = claimed_state or cont_service.claim_state(
|
||||
@@ -1786,6 +1806,21 @@ class StreamProcessor:
|
||||
if not state:
|
||||
raise ValueError("No pending tool state found for this conversation")
|
||||
|
||||
# A request that names an agent (by key or id) resumes only that
|
||||
# agent's turn; the claim goes back so its rightful caller can resume.
|
||||
saved_agent = str((state.get("agent_config") or {}).get("agent_id") or "").lower()
|
||||
targets = []
|
||||
if request_key:
|
||||
targets.append(str((key_agent or {}).get("id") or (key_agent or {}).get("_id") or ""))
|
||||
if named_agent:
|
||||
targets.append(str(named_agent))
|
||||
if any(target.lower() != saved_agent or not target for target in targets):
|
||||
try:
|
||||
cont_service.release_claim(conversation_id, self.initial_user_id)
|
||||
except Exception:
|
||||
logger.warning("Failed to release a refused resume claim", exc_info=True)
|
||||
raise ValueError("This conversation belongs to a different agent")
|
||||
|
||||
messages = state["messages"]
|
||||
pending_tool_calls = state["pending_tool_calls"]
|
||||
tools_dict = state["tools_dict"]
|
||||
@@ -1821,15 +1856,19 @@ class StreamProcessor:
|
||||
if callable(importer):
|
||||
importer(agent_config.get("responses_state"))
|
||||
llm_handler = LLMHandlerCreator.create_handler(llm_name or "default")
|
||||
# Outside if either who paused the turn or who resumes it is.
|
||||
resume_external = bool(agent_config.get("external_api_caller")) or request_external
|
||||
resume_public_link = bool(agent_config.get("public_link_caller")) or request_public_link
|
||||
apply_resume_caller_rules(
|
||||
tools_dict, outside_caller=resume_external, public_link_caller=resume_public_link,
|
||||
)
|
||||
tool_executor = ToolExecutor(
|
||||
user_api_key=user_api_key,
|
||||
user=self.initial_user_id,
|
||||
decoded_token=self.decoded_token,
|
||||
agent_id=agent_id,
|
||||
external_caller=bool(
|
||||
agent_config.get("external_api_caller") or getattr(self, "external_caller", False)
|
||||
),
|
||||
public_link_caller=bool(agent_config.get("public_link_caller")),
|
||||
external_caller=resume_external,
|
||||
public_link_caller=resume_public_link,
|
||||
api_write_allowlist=agent_config.get("api_write_allowlist"),
|
||||
)
|
||||
tool_executor.conversation_id = conversation_id
|
||||
|
||||
@@ -381,7 +381,7 @@ sources_table = Table(
|
||||
),
|
||||
# Whose account a shared resource runs with: the owner's, or each member's.
|
||||
Column("credential_mode", Text, nullable=False, server_default="owner"),
|
||||
# A wiki's owner lets API, widget and public-link runs edit it (off: read only).
|
||||
# A wiki's owner lets API-key and widget runs edit it (off: read only).
|
||||
Column("wiki_outside_edits", Boolean, nullable=False, server_default="false"),
|
||||
)
|
||||
|
||||
|
||||
@@ -400,7 +400,7 @@ class SourcesRepository:
|
||||
self._conn.execute(stmt)
|
||||
|
||||
def set_wiki_outside_edits(self, source_id: str, user_id: str, allowed: bool) -> bool:
|
||||
"""Record whether API, widget and public-link runs may edit this wiki.
|
||||
"""Record whether API-key and widget runs may edit this wiki.
|
||||
|
||||
Kept out of :meth:`update`'s columns so no route that forwards a
|
||||
request body can change it; only the owner-checked wiki settings
|
||||
|
||||
Reference in new issue
Block a user