136 lines
4.8 KiB
Python
136 lines
4.8 KiB
Python
"""KB 관리자 인덱싱 라우트의 RLS 컨텍스트 계약 테스트."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import unittest
|
|
from typing import Any
|
|
from unittest.mock import AsyncMock, patch
|
|
|
|
from fastapi import FastAPI
|
|
from fastapi.testclient import TestClient
|
|
|
|
from .deps import Principal, Role, get_current_principal
|
|
from .routes import kb
|
|
from .services import rag, source_pack_sync
|
|
|
|
|
|
ADMIN_ID = "00000000-0000-0000-0000-000000000901"
|
|
|
|
|
|
class _Acquire:
|
|
async def __aenter__(self) -> object:
|
|
return object()
|
|
|
|
async def __aexit__(self, exc_type: Any, exc: Any, traceback: Any) -> None:
|
|
return None
|
|
|
|
|
|
class KBAdminRouteTest(unittest.TestCase):
|
|
@staticmethod
|
|
def _app(principal: Principal | None = None) -> FastAPI:
|
|
app = FastAPI()
|
|
app.include_router(kb.router)
|
|
if principal is not None:
|
|
app.dependency_overrides[get_current_principal] = lambda: principal
|
|
return app
|
|
|
|
@staticmethod
|
|
def _index_body() -> dict[str, object]:
|
|
return {
|
|
"source_id": "kb-admin-route-test",
|
|
"doc_uri": "repo/kb-admin-route-test.json",
|
|
"chunks": [{"seq": 0, "chunk_text": "관리자 인덱싱 테스트"}],
|
|
}
|
|
|
|
def test_admin_index_injects_role_and_user_id_into_acquire(self) -> None:
|
|
principal = Principal(user_id=ADMIN_ID, role=Role.ADMIN)
|
|
acquire_calls: list[dict[str, Any]] = []
|
|
|
|
def fake_acquire(**kwargs: Any) -> _Acquire:
|
|
acquire_calls.append(kwargs)
|
|
return _Acquire()
|
|
|
|
with (
|
|
patch.object(kb, "acquire", fake_acquire),
|
|
patch.object(kb.rag, "validate_index_source", AsyncMock()),
|
|
patch.object(
|
|
kb.rag,
|
|
"index_document",
|
|
AsyncMock(
|
|
return_value=rag.IndexResult(
|
|
doc_id=1,
|
|
chunks_indexed=1,
|
|
skipped_unchanged=False,
|
|
embedded=False,
|
|
degraded=True,
|
|
)
|
|
),
|
|
),
|
|
):
|
|
with TestClient(self._app(principal)) as client:
|
|
response = client.post("/kb/index", json=self._index_body())
|
|
|
|
self.assertEqual(response.status_code, 202)
|
|
self.assertEqual(acquire_calls, [{"role": "admin", "user_id": ADMIN_ID}])
|
|
|
|
def test_admin_source_pack_sync_injects_role_and_user_id_into_acquire(self) -> None:
|
|
principal = Principal(user_id=ADMIN_ID, role=Role.ADMIN)
|
|
acquire_calls: list[dict[str, Any]] = []
|
|
|
|
def fake_acquire(**kwargs: Any) -> _Acquire:
|
|
acquire_calls.append(kwargs)
|
|
return _Acquire()
|
|
|
|
result = source_pack_sync.RepoSourcePackSyncResult(
|
|
sources_upserted=1,
|
|
manifest_count=1,
|
|
chunks_indexed=1,
|
|
skipped_unchanged=0,
|
|
embedded=False,
|
|
degraded=True,
|
|
applied=True,
|
|
items=[],
|
|
)
|
|
with (
|
|
patch.object(kb, "acquire", fake_acquire),
|
|
patch.object(
|
|
kb.source_pack_sync,
|
|
"build_repo_source_pack_manifest",
|
|
return_value=([{"source_id": "source-a"}], [{"source_id": "source-a"}]),
|
|
),
|
|
patch.object(
|
|
kb.source_pack_sync,
|
|
"sync_repo_source_packs",
|
|
AsyncMock(return_value=result),
|
|
),
|
|
):
|
|
with TestClient(self._app(principal)) as client:
|
|
response = client.post("/kb/live-coach/source-packs/sync")
|
|
|
|
self.assertEqual(response.status_code, 202)
|
|
self.assertEqual(acquire_calls, [{"role": "admin", "user_id": ADMIN_ID}])
|
|
|
|
def test_anonymous_requests_remain_unauthorized(self) -> None:
|
|
with TestClient(self._app()) as client:
|
|
index_response = client.post("/kb/index", json=self._index_body())
|
|
sync_response = client.post("/kb/live-coach/source-packs/sync")
|
|
|
|
self.assertEqual(index_response.status_code, 401)
|
|
self.assertEqual(sync_response.status_code, 401)
|
|
|
|
def test_learner_requests_remain_forbidden_before_acquire(self) -> None:
|
|
learner = Principal(user_id="learner-1", role=Role.LEARNER)
|
|
acquire = AsyncMock(side_effect=AssertionError("학습자는 DB 획득 전에 거절되어야 한다"))
|
|
|
|
with patch.object(kb, "acquire", acquire):
|
|
with TestClient(self._app(learner)) as client:
|
|
index_response = client.post("/kb/index", json=self._index_body())
|
|
sync_response = client.post("/kb/live-coach/source-packs/sync")
|
|
|
|
self.assertEqual(index_response.status_code, 403)
|
|
self.assertEqual(sync_response.status_code, 403)
|
|
acquire.assert_not_called()
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|