RAGFlow is an agent-native database: a Retrieval-Augmented Generation (RAG) engine that grew into context infrastructure.
Go agent-harnessagent-native-databaseagentic-aiagentic-retrievalagentic-searchaiai-agentscontext-enginecontext-engineeringcontext-managementharness-engineeringknowledge-compilationragretrieval-augmented-generationretrieval-harnesssearch-harness
fix(api): make the API-key subject carve-out on POST /messages reachable (#18026)
Ali Farhan03d28357310d
diff --git a/api/apps/restful_apis/memory_api.py b/api/apps/restful_apis/memory_api.pyindex 90d18c0c6f..b320e0941a 100644--- a/api/apps/restful_apis/memory_api.py+++ b/api/apps/restful_apis/memory_api.py@@ -20,7 +20,7 @@ import timefrom quart import request, gfrom common.constants import RetCodefrom common.exceptions import ArgumentException, NotFoundException-from api.apps import login_required, current_user+from api.apps import AUTH_API, login_required, current_userfrom api.utils.api_utils import validate_request, get_request_json, get_error_argument_result, get_json_resultfrom api.apps.services import memory_api_servicefrom api.db.joint_services.tenant_model_service import ensure_tenant_model_ids_for_params@@ -208,13 +208,19 @@ async def add_message():# JWT / session users cannot spoof attribution; API-key callers may supply an external subject id.try:- trust_client_subject = bool(getattr(g, "auth_via_api_token", False))+ trust_client_subject = getattr(g, "auth_type", None) == AUTH_APIexcept RuntimeError:trust_client_subject = False+ effective_user_id = current_user.id+ from_client = Falseif trust_client_subject:- effective_user_id = req.get("user_id", "")- else:- effective_user_id = current_user.id+ requested_user_id = req.get("user_id")+ if isinstance(requested_user_id, str) and requested_user_id.strip():+ effective_user_id = requested_user_id.strip()+ from_client = True+ # The stored subject alone cannot say which path ran, since a client may send the+ # principal's own id. Record the decision, never the id, which identifies an end user.+ logging.info("memory message attribution: trusted_client=%s subject=%s", trust_client_subject, "client" if from_client else "principal")message_dict = {"user_id": effective_user_id,diff --git a/docs/references/http_api_reference.md b/docs/references/http_api_reference.mdindex 77ff56d121..6eaf6dc4e7 100644--- a/docs/references/http_api_reference.md+++ b/docs/references/http_api_reference.md@@ -6438,7 +6438,7 @@ curl --location 'http://{address}/api/v1/messages' \- `user_id`: (*Body parameter*), `string`, *Optional*- The user participating in the conversation with the agent. Defaults to `None`.+ The user participating in the conversation with the agent. Honoured only when the request is authenticated with an API key. Any other authentication, whether a JWT bearer token or a browser session, ignores it and attributes the message to the authenticated user. Surrounding whitespace is stripped, and a value that is missing, blank or not a string falls back to the API key owner.- `user_input`: (*Body parameter*), `string`, *Required*diff --git a/test/testcases/restful_api/test_memories_messages.py b/test/testcases/restful_api/test_memories_messages.pyindex dde6c2e6e5..d5acf0c8d7 100644--- a/test/testcases/restful_api/test_memories_messages.py+++ b/test/testcases/restful_api/test_memories_messages.py@@ -170,6 +170,32 @@ def test_messages_add_list_recent_content_update_forget(rest_client, create_memoassert forget_payload["code"] == 0, forget_payload+def test_message_keeps_the_caller_supplied_user_id(rest_client, create_memory_resource):+ """An API key belongs to an agent backend talking on behalf of its own end+ users, so the `user_id` it sends is the subject the memory is written+ against rather than the key owner's tenant id."""+ memory_id = create_memory_resource("restful_message_user_id")+ external_user_id = f"external-{uuid.uuid4().hex}"++ add_res = rest_client.post(+ "/messages",+ json={+ "memory_id": [memory_id],+ "agent_id": uuid.uuid4().hex,+ "session_id": uuid.uuid4().hex,+ "user_id": external_user_id,+ "user_input": "who am I?",+ "agent_response": "you are the one asking",+ },+ )+ assert add_res.status_code == 200+ assert add_res.json()["code"] == 0, add_res.json()++ message_list = _wait_for_memory_messages(rest_client, memory_id)+ assert {message["user_id"] for message in message_list} == {external_user_id}, message_list++@pytest.mark.p2def test_message_status_validation_requires_boolean(rest_client, create_memory_resource):memory_id = create_memory_resource("restful_message_status_validation")diff --git a/test/testcases/restful_api/test_message_routes_unit.py b/test/testcases/restful_api/test_message_routes_unit.pyindex ce6df884ac..e92979928f 100644--- a/test/testcases/restful_api/test_message_routes_unit.py+++ b/test/testcases/restful_api/test_message_routes_unit.py@@ -75,6 +75,7 @@ def _load_memory_routes_module(monkeypatch):apps_mod = ModuleType("api.apps")apps_mod.__path__ = [str(repo_root / "api" / "apps")]+ apps_mod.AUTH_API = "API"apps_mod.current_user = SimpleNamespace(id="user-1")apps_mod.login_required = lambda func: funcmonkeypatch.setitem(sys.modules, "api.apps", apps_mod)diff --git a/test/testcases/test_web_api/test_message_app/test_message_routes_unit.py b/test/testcases/test_web_api/test_message_app/test_message_routes_unit.pyindex 820c9782f9..cbf1d1fac8 100644--- a/test/testcases/test_web_api/test_message_app/test_message_routes_unit.py+++ b/test/testcases/test_web_api/test_message_app/test_message_routes_unit.py@@ -75,6 +75,7 @@ def _load_memory_routes_module(monkeypatch):apps_mod = ModuleType("api.apps")apps_mod.__path__ = [str(repo_root / "api" / "apps")]+ apps_mod.AUTH_API = "API"apps_mod.current_user = SimpleNamespace(id="user-1")apps_mod.login_required = lambda func: funcmonkeypatch.setitem(sys.modules, "api.apps", apps_mod)@@ -170,9 +171,7 @@ def test_search_message_rejects_top_n_above_rest_api_max(monkeypatch):monkeypatch.setattr(module,"request",- SimpleNamespace(- args=_DummyArgs({"memory_id": "m1", "query": "hello", "top_n": "500"})- ),+ SimpleNamespace(args=_DummyArgs({"memory_id": "m1", "query": "hello", "top_n": "500"})),)async def _search_message(_filter_dict, _params):diff --git a/test/unit_test/api/apps/restful_apis/test_add_message_user_id.py b/test/unit_test/api/apps/restful_apis/test_add_message_user_id.pynew file mode 100644index 0000000000..4f8bbf3c5f--- /dev/null+++ b/test/unit_test/api/apps/restful_apis/test_add_message_user_id.py@@ -0,0 +1,157 @@+#+# Copyright 2026 The InfiniFlow Authors. All Rights Reserved.+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.+#+"""Regression tests for message attribution in `POST /api/v1/messages`+(api/apps/restful_apis/memory_api.py).++An API key belongs to an agent backend talking to RAGFlow on behalf of its own+end users, so the `user_id` it sends is the subject the memory is written+against. A JWT or session caller is an end user in its own right and stays+pinned to the authenticated principal so it cannot write memory attributed to+somebody else.+"""++import importlib.util+import sys+from pathlib import Path+from types import ModuleType, SimpleNamespace++import pytest++AUTH_JWT = "JWT"+AUTH_API = "API"+TENANT_ID = "tenant-key-owner"+++class _PassthroughManager:+ def route(self, *_args, **_kwargs):+ return lambda func: func+++def _stub(monkeypatch, name, **attrs):+ mod = ModuleType(name)+ for key, value in attrs.items():+ setattr(mod, key, value)+ monkeypatch.setitem(sys.modules, name, mod)+ return mod+++def _load_memory_api(monkeypatch, auth_type, request_json, added):+ """Load memory_api.py with the minimum stubs `add_message` needs."""++ async def _get_request_json():+ return request_json++ async def _add_message(memory_ids, message_dict):+ added.append((memory_ids, message_dict))+ return True, "ok"++ _stub(+ monkeypatch,+ "quart",+ g=SimpleNamespace(auth_type=auth_type),+ request=SimpleNamespace(args={}),+ )+ _stub(+ monkeypatch,+ "api.apps",+ AUTH_API=AUTH_API,+ AUTH_JWT=AUTH_JWT,+ current_user=SimpleNamespace(id=TENANT_ID),+ login_required=lambda func=None, **_kwargs: (lambda f: f) if func is None else func,+ )+ _stub(monkeypatch, "api.apps.services", memory_api_service=SimpleNamespace(add_message=_add_message))+ _stub(monkeypatch, "api.db.joint_services.tenant_model_service", ensure_tenant_model_ids_for_params=lambda *_a, **_k: {})+ _stub(+ monkeypatch,+ "api.utils.api_utils",+ get_error_argument_result=lambda message="Sorry": {"code": 101, "message": message, "data": None},+ get_json_result=lambda code=0, message="", data=None: {"code": code, "message": message, "data": data},+ get_request_json=_get_request_json,+ validate_request=lambda *_a, **_k: lambda func: func,+ )++ repo_root = Path(__file__).resolve().parents[5]+ module_path = repo_root / "api" / "apps" / "restful_apis" / "memory_api.py"+ spec = importlib.util.spec_from_file_location("test_add_message_user_id_memory_api", module_path)+ module = importlib.util.module_from_spec(spec)+ module.manager = _PassthroughManager()+ monkeypatch.setitem(sys.modules, "test_add_message_user_id_memory_api", module)+ spec.loader.exec_module(module)+ return module+++async def _add(monkeypatch, auth_type, extra):+ added = []+ request_json = {+ "memory_id": ["mem-1"],+ "agent_id": "agent-1",+ "session_id": "session-1",+ "user_input": "hi",+ "agent_response": "hello",+ **extra,+ }+ module = _load_memory_api(monkeypatch, auth_type, request_json, added)+ response = await module.add_message()+ return response, added+++async def test_api_key_caller_attributes_the_message_to_its_end_user(monkeypatch):+ """The subject a trusted agent backend sends is what the memory is written+ against. Before the fix this branch was unreachable, because it keyed off+ `g.auth_via_api_token`, which the Python auth layer never sets."""+ response, added = await _add(monkeypatch, AUTH_API, {"user_id": "end-user-42"})++ assert response["code"] == 0+ assert added[0][1]["user_id"] == "end-user-42"+++async def test_jwt_caller_cannot_attribute_a_message_to_another_user(monkeypatch):+ """The guarantee #14745 was written for: a browser client's `user_id` loses+ to the authenticated principal."""+ _, added = await _add(monkeypatch, AUTH_JWT, {"user_id": "somebody-else"})++ assert added[0][1]["user_id"] == TENANT_ID+++async def test_api_key_caller_without_user_id_falls_back_to_the_key_owner(monkeypatch):+ """`user_id` is optional, so omitting it must not write an empty subject."""+ _, added = await _add(monkeypatch, AUTH_API, {})++ assert added[0][1]["user_id"] == TENANT_ID+++async def test_blank_and_non_string_user_id_fall_back_instead_of_being_stored(monkeypatch):+ _, added = await _add(monkeypatch, AUTH_API, {"user_id": " "})+ assert added[0][1]["user_id"] == TENANT_ID++ _, added = await _add(monkeypatch, AUTH_API, {"user_id": 12345})+ assert added[0][1]["user_id"] == TENANT_ID+++async def test_surrounding_whitespace_is_stripped_from_the_subject(monkeypatch):+ _, added = await _add(monkeypatch, AUTH_API, {"user_id": " end-user-42 "})++ assert added[0][1]["user_id"] == "end-user-42"