운영 안정화와 화면 회귀 검증을 반영
Some checks failed
API contract / OpenAPI type drift (push) Failing after 6m2s

This commit is contained in:
Yun Chan 2026-10-20 16:33:48 +09:00
parent 6e3123091a
commit aeddaa6972
69 changed files with 3178 additions and 424 deletions

View file

@ -959,6 +959,9 @@ async def ensure_runtime_tables() -> None:
ON app.admin_health_daily_rollup FOR UPDATE
USING (app.current_role_name() = 'admin')
WITH CHECK (app.current_role_name() = 'admin');
CREATE POLICY p_admin_health_daily_rollup_delete
ON app.admin_health_daily_rollup FOR DELETE
USING (app.current_role_name() = 'admin');
ALTER TABLE app.support_ticket ENABLE ROW LEVEL SECURITY;
DROP POLICY IF EXISTS p_support_ticket_select ON app.support_ticket;

View file

@ -328,8 +328,8 @@ async def index_document(
chunks=[c.model_dump() for c in body.chunks],
)
try:
# 관리자 인덱싱은 RLS 미적용(쓰기 — kb 스키마 직접). role 주입 없이 acquire.
async with acquire() as conn:
# 관리자 RLS 컨텍스트를 주입해 kb 쓰기 정책을 충족한다.
async with acquire(role=principal.role.value, user_id=principal.user_id) as conn:
await rag.validate_index_source(conn, body.source_id)
result = await rag.index_document(conn, req)
except rag.IndexPolicyViolation as e:
@ -376,7 +376,7 @@ async def sync_live_coach_source_packs(
)
try:
async with acquire() as conn:
async with acquire(role=principal.role.value, user_id=principal.user_id) as conn:
result = await source_pack_sync.sync_repo_source_packs(
conn, apply=True, refresh=True
)

View file

@ -3,6 +3,7 @@
from __future__ import annotations
from dataclasses import dataclass
import re
from ..db import acquire
@ -12,18 +13,31 @@ class AdminHealthMaintenanceResult:
applied: bool
rollup_days: int
retention_days: int
rollup_retention_days: int
rollup_event_count: int
rollup_bucket_count: int
upserted_rollups: int
prunable_event_count: int
deleted_events: int
# apply 전에 이미 존재한 만료 일별 rollup 수다. 이번 집계에서 새로 생긴 행은 포함하지 않는다.
prunable_rollup_count: int
deleted_rollups: int
def _validate_windows(*, rollup_days: int, retention_days: int) -> None:
def _validate_windows(
*,
rollup_days: int,
retention_days: int,
rollup_retention_days: int,
) -> None:
if rollup_days < 1:
raise ValueError("rollup_days must be 1 or greater")
if retention_days < rollup_days:
raise ValueError("retention_days must be greater than or equal to rollup_days")
if rollup_retention_days < retention_days:
raise ValueError(
"rollup_retention_days must be greater than or equal to retention_days"
)
def _deleted_count(command_tag: str) -> int:
@ -45,19 +59,74 @@ def _row_int(row, key: str) -> int:
return 0
_EXPECTED_ROLLUP_DELETE_QUAL = "(app.current_role_name()='admin')"
def _normalize_policy_expression(expression: object) -> str:
if not isinstance(expression, str):
return ""
return re.sub(r"\s+", "", expression).replace("::text", "")
def _is_exact_rollup_delete_policy(policy) -> bool:
try:
return (
policy["policy_name"] == "p_admin_health_daily_rollup_delete"
and policy["command"] == "d"
and policy["permissive"] is True
and policy["rls_enabled"] is True
and _normalize_policy_expression(policy["qual"])
== _EXPECTED_ROLLUP_DELETE_QUAL
)
except (KeyError, TypeError):
return False
async def _require_rollup_delete_policy(conn) -> None:
policies = await conn.fetch(
"""
SELECT
policy.polname AS policy_name,
policy.polcmd::text AS command,
policy.polpermissive AS permissive,
relation.relrowsecurity AS rls_enabled,
pg_get_expr(policy.polqual, policy.polrelid) AS qual
FROM pg_policy AS policy
JOIN pg_class AS relation ON relation.oid = policy.polrelid
JOIN pg_namespace AS namespace ON namespace.oid = relation.relnamespace
WHERE namespace.nspname = 'app'
AND relation.relname = 'admin_health_daily_rollup'
AND policy.polpermissive IS TRUE
AND policy.polcmd IN ('d', '*')
ORDER BY policy.polname
"""
)
if len(policies) != 1 or not _is_exact_rollup_delete_policy(policies[0]):
raise RuntimeError(
"admin health daily rollup DELETE policy is missing, invalid, or permissive; "
"owner must apply migration 25_admin_health_rollup_retention.sql"
)
async def maintain_admin_health_events(
*,
rollup_days: int,
retention_days: int,
retention_days: int = 90,
rollup_retention_days: int = 365,
apply: bool = False,
) -> AdminHealthMaintenanceResult:
"""Roll up old health samples and optionally prune retained raw rows.
"""오래된 관리자 헬스 표본을 일별로 집계하고 보존 기간이 지난 행을 정리한다.
Dry-run mode returns the affected event and bucket counts without mutating
data. Apply mode upserts daily service rollups first, then deletes only raw
events older than the retention window.
dry-run은 데이터를 바꾸지 않고 영향받는 표본과 버킷 수만 반환한다.
prunable_rollup_count는 apply 전에 존재한 만료 일별 rollup 수다. 이번 집계에서
새로 생긴 만료 rollup은 이 수에 포함하지 않지만, apply에서는 일별 rollup upsert 후
raw 표본과 만료된 일별 rollup을 같은 트랜잭션에서 순서대로 삭제한다.
"""
_validate_windows(rollup_days=rollup_days, retention_days=retention_days)
_validate_windows(
rollup_days=rollup_days,
retention_days=retention_days,
rollup_retention_days=rollup_retention_days,
)
async with acquire(role="admin") as conn:
rollup_stats = await conn.fetchrow(
"""
@ -78,9 +147,19 @@ async def maintain_admin_health_events(
""",
retention_days,
)
rollup_prune_stats = await conn.fetchrow(
"""
SELECT COUNT(*)::int AS rollup_count
FROM app.admin_health_daily_rollup
WHERE rollup_date < current_date - $1::int
""",
rollup_retention_days,
)
upserted_rollups = 0
deleted_events = 0
deleted_rollups = 0
if apply:
await _require_rollup_delete_policy(conn)
rows = await conn.fetch(
"""
WITH rolled AS (
@ -164,14 +243,26 @@ async def maintain_admin_health_events(
retention_days,
)
)
deleted_rollups = _deleted_count(
await conn.execute(
"""
DELETE FROM app.admin_health_daily_rollup
WHERE rollup_date < current_date - $1::int
""",
rollup_retention_days,
)
)
return AdminHealthMaintenanceResult(
applied=apply,
rollup_days=rollup_days,
retention_days=retention_days,
rollup_retention_days=rollup_retention_days,
rollup_event_count=_row_int(rollup_stats, "event_count"),
rollup_bucket_count=_row_int(rollup_stats, "bucket_count"),
upserted_rollups=upserted_rollups,
prunable_event_count=_row_int(prune_stats, "event_count"),
deleted_events=deleted_events,
prunable_rollup_count=_row_int(rollup_prune_stats, "rollup_count"),
deleted_rollups=deleted_rollups,
)

View file

@ -8,14 +8,25 @@ import unittest.mock
from .services import admin_health_maintenance as maintenance
_VALID_ROLLUP_DELETE_POLICY = {
"policy_name": "p_admin_health_daily_rollup_delete",
"command": "d",
"permissive": True,
"rls_enabled": True,
"qual": "(app.current_role_name() = 'admin'::text)",
}
class _Acquire:
def __init__(self, conn):
self.conn = conn
self.exit_error = None
async def __aenter__(self):
return self.conn
async def __aexit__(self, exc_type, exc, tb):
self.exit_error = exc
return None
@ -29,7 +40,9 @@ class AdminHealthMaintenanceTest(unittest.IsolatedAsyncioTestCase):
self.fetch_calls.append((query, args))
if len(self.fetch_calls) == 1:
return {"event_count": 12, "bucket_count": 3}
return {"event_count": 4}
if len(self.fetch_calls) == 2:
return {"event_count": 4}
return {"rollup_count": 2}
async def fetch(self, *args, **kwargs):
raise AssertionError("dry-run must not upsert rollups")
@ -41,7 +54,6 @@ class AdminHealthMaintenanceTest(unittest.IsolatedAsyncioTestCase):
with unittest.mock.patch.object(maintenance, "acquire", return_value=_Acquire(conn)):
result = await maintenance.maintain_admin_health_events(
rollup_days=2,
retention_days=30,
apply=False,
)
@ -49,11 +61,17 @@ class AdminHealthMaintenanceTest(unittest.IsolatedAsyncioTestCase):
self.assertEqual(result.rollup_event_count, 12)
self.assertEqual(result.rollup_bucket_count, 3)
self.assertEqual(result.prunable_event_count, 4)
self.assertEqual(result.prunable_rollup_count, 2)
self.assertEqual(result.rollup_retention_days, 365)
self.assertEqual(result.upserted_rollups, 0)
self.assertEqual(result.deleted_events, 0)
self.assertEqual(result.deleted_rollups, 0)
self.assertEqual(conn.fetch_calls[0][1], (2,))
self.assertEqual(conn.fetch_calls[1][1], (30,))
self.assertEqual(result.retention_days, 90)
self.assertEqual(conn.fetch_calls[1][1], (90,))
self.assertEqual(conn.fetch_calls[2][1], (365,))
self.assertIn("observed_at::date < current_date - $1::int", conn.fetch_calls[0][0])
self.assertIn("rollup_date < current_date - $1::int", conn.fetch_calls[2][0])
async def test_apply_upserts_rollups_before_pruning_raw_events(self) -> None:
calls = []
@ -61,17 +79,22 @@ class AdminHealthMaintenanceTest(unittest.IsolatedAsyncioTestCase):
class Conn:
async def fetchrow(self, query, *args, **kwargs):
calls.append(("fetchrow", query, args))
if len([call for call in calls if call[0] == "fetchrow"]) == 1:
fetchrow_count = len([call for call in calls if call[0] == "fetchrow"])
if fetchrow_count == 1:
return {"event_count": 7, "bucket_count": 2}
return {"event_count": 5}
if fetchrow_count == 2:
return {"event_count": 5}
return {"rollup_count": 3}
async def fetch(self, query, *args, **kwargs):
calls.append(("fetch", query, args))
if "FROM pg_policy AS policy" in query:
return [_VALID_ROLLUP_DELETE_POLICY]
return [1, 1]
async def execute(self, query, *args, **kwargs):
calls.append(("execute", query, args))
return "DELETE 5"
return "DELETE 5" if "admin_health_event" in query else "DELETE 3"
with unittest.mock.patch.object(maintenance, "acquire", return_value=_Acquire(Conn())):
result = await maintenance.maintain_admin_health_events(
@ -83,16 +106,237 @@ class AdminHealthMaintenanceTest(unittest.IsolatedAsyncioTestCase):
self.assertTrue(result.applied)
self.assertEqual(result.upserted_rollups, 2)
self.assertEqual(result.deleted_events, 5)
self.assertEqual([call[0] for call in calls], ["fetchrow", "fetchrow", "fetch", "execute"])
self.assertIn("INSERT INTO app.admin_health_daily_rollup", calls[2][1])
self.assertIn("last_down_at", calls[2][1])
self.assertIn("DELETE FROM app.admin_health_event", calls[3][1])
self.assertEqual(result.deleted_rollups, 3)
self.assertEqual(
[call[0] for call in calls],
["fetchrow", "fetchrow", "fetchrow", "fetch", "fetch", "execute", "execute"],
)
self.assertIn("pg_get_expr(policy.polqual, policy.polrelid)", calls[3][1])
self.assertNotIn("LIKE", calls[3][1])
self.assertIn("INSERT INTO app.admin_health_daily_rollup", calls[4][1])
self.assertIn("last_down_at", calls[4][1])
self.assertIn("DELETE FROM app.admin_health_event", calls[5][1])
self.assertIn("DELETE FROM app.admin_health_daily_rollup", calls[6][1])
self.assertEqual(calls[6][2], (365,))
def test_invalid_windows_are_rejected(self) -> None:
with self.assertRaises(ValueError):
maintenance._validate_windows(rollup_days=0, retention_days=30)
maintenance._validate_windows(
rollup_days=0,
retention_days=30,
rollup_retention_days=365,
)
with self.assertRaises(ValueError):
maintenance._validate_windows(rollup_days=7, retention_days=2)
maintenance._validate_windows(
rollup_days=7,
retention_days=2,
rollup_retention_days=365,
)
with self.assertRaises(ValueError):
maintenance._validate_windows(
rollup_days=7,
retention_days=30,
rollup_retention_days=29,
)
async def test_rollup_delete_policy_requires_exact_admin_expression(self) -> None:
class Conn:
def __init__(self, policies):
self.policies = policies
self.query = ""
async def fetch(self, query, *args, **kwargs):
self.query = query
return self.policies
valid = Conn([_VALID_ROLLUP_DELETE_POLICY])
await maintenance._require_rollup_delete_policy(valid)
self.assertIn("policy.polcmd::text AS command", valid.query)
self.assertIn("pg_get_expr(policy.polqual, policy.polrelid)", valid.query)
self.assertIn("policy.polpermissive IS TRUE", valid.query)
self.assertIn("relation.relrowsecurity AS rls_enabled", valid.query)
self.assertIn("policy.polcmd IN ('d', '*')", valid.query)
self.assertNotIn("LIKE", valid.query)
invalid_policy_sets = (
[
{
**_VALID_ROLLUP_DELETE_POLICY,
"qual": "(app.current_role_name() = 'admin'::text) OR true",
}
],
[
{
**_VALID_ROLLUP_DELETE_POLICY,
"qual": "(app.current_role_name() = 'learner'::text)",
}
],
[
{
**_VALID_ROLLUP_DELETE_POLICY,
"permissive": 1,
}
],
[
{
**_VALID_ROLLUP_DELETE_POLICY,
"rls_enabled": False,
}
],
[
_VALID_ROLLUP_DELETE_POLICY,
{
"policy_name": "p_admin_health_daily_rollup_extra_delete",
"command": "d",
"permissive": True,
"qual": "true",
},
],
[
_VALID_ROLLUP_DELETE_POLICY,
{
"policy_name": "p_admin_health_daily_rollup_all",
"command": "*",
"permissive": True,
"qual": "true",
},
],
)
for policies in invalid_policy_sets:
with self.subTest(policies=policies):
with self.assertRaisesRegex(RuntimeError, "missing, invalid, or permissive"):
await maintenance._require_rollup_delete_policy(Conn(policies))
async def test_apply_stops_before_dml_when_rollup_delete_policy_is_missing(
self,
) -> None:
class Conn:
def __init__(self):
self.fetchrow_calls = 0
async def fetchrow(self, query, *args, **kwargs):
self.fetchrow_calls += 1
if self.fetchrow_calls == 1:
return {"event_count": 1, "bucket_count": 1}
if self.fetchrow_calls == 2:
return {"event_count": 0}
if self.fetchrow_calls == 3:
return {"rollup_count": 0}
async def fetch(self, query, *args, **kwargs):
if "FROM pg_policy AS policy" in query:
return []
raise AssertionError("missing policy must stop before rollup upsert")
async def execute(self, *args, **kwargs):
raise AssertionError("missing policy must stop before deletion")
context = _Acquire(Conn())
with unittest.mock.patch.object(maintenance, "acquire", return_value=context):
with self.assertRaisesRegex(
RuntimeError,
"owner must apply migration 25_admin_health_rollup_retention.sql",
):
await maintenance.maintain_admin_health_events(
rollup_days=90,
retention_days=90,
rollup_retention_days=365,
apply=True,
)
self.assertIsInstance(context.exit_error, RuntimeError)
async def test_repeat_apply_keeps_rollup_upsert_and_cutoff_contract(self) -> None:
calls = []
class Conn:
async def fetchrow(self, query, *args, **kwargs):
calls.append(("fetchrow", query, args))
if "admin_health_daily_rollup" in query:
return {"rollup_count": 0}
if "COUNT(DISTINCT" in query:
return {"event_count": 1, "bucket_count": 1}
return {"event_count": 0}
async def fetch(self, query, *args, **kwargs):
calls.append(("fetch", query, args))
if "FROM pg_policy AS policy" in query:
return [_VALID_ROLLUP_DELETE_POLICY]
return [1]
async def execute(self, query, *args, **kwargs):
calls.append(("execute", query, args))
return "DELETE 0"
context = _Acquire(Conn())
with unittest.mock.patch.object(maintenance, "acquire", return_value=context):
first = await maintenance.maintain_admin_health_events(
rollup_days=90,
retention_days=90,
rollup_retention_days=365,
apply=True,
)
second = await maintenance.maintain_admin_health_events(
rollup_days=90,
retention_days=90,
rollup_retention_days=365,
apply=True,
)
self.assertEqual(first.upserted_rollups, second.upserted_rollups)
upserts = [
call
for call in calls
if call[0] == "fetch" and "INSERT INTO app.admin_health_daily_rollup" in call[1]
]
self.assertEqual(2, len(upserts))
self.assertTrue(
all("ON CONFLICT (rollup_date, environment, engine_mode, service_key)" in call[1] for call in upserts)
)
rollup_prunes = [
call
for call in calls
if call[0] == "execute" and "admin_health_daily_rollup" in call[1]
]
self.assertEqual(2, len(rollup_prunes))
self.assertTrue(
all("rollup_date < current_date - $1::int" in call[1] for call in rollup_prunes)
)
self.assertTrue(all(call[2] == (365,) for call in rollup_prunes))
async def test_raw_prune_failure_stops_before_rollup_prune(self) -> None:
calls = []
class Conn:
async def fetchrow(self, query, *args, **kwargs):
if "admin_health_daily_rollup" in query:
return {"rollup_count": 0}
if "COUNT(DISTINCT" in query:
return {"event_count": 1, "bucket_count": 1}
return {"event_count": 1}
async def fetch(self, query, *args, **kwargs):
calls.append(("fetch", query))
if "FROM pg_policy AS policy" in query:
return [_VALID_ROLLUP_DELETE_POLICY]
return [1]
async def execute(self, query, *args, **kwargs):
calls.append(("execute", query))
raise RuntimeError("raw prune failed")
context = _Acquire(Conn())
with unittest.mock.patch.object(maintenance, "acquire", return_value=context):
with self.assertRaisesRegex(RuntimeError, "raw prune failed"):
await maintenance.maintain_admin_health_events(
rollup_days=90,
retention_days=90,
rollup_retention_days=365,
apply=True,
)
self.assertIsInstance(context.exit_error, RuntimeError)
self.assertEqual([call[0] for call in calls], ["fetch", "fetch", "execute"])
self.assertIn("FROM pg_policy AS policy", calls[0][1])
self.assertIn("DELETE FROM app.admin_health_event", calls[2][1])
def test_schema_defines_rollup_table_and_rls(self) -> None:
from pathlib import Path
@ -108,4 +352,19 @@ class AdminHealthMaintenanceTest(unittest.IsolatedAsyncioTestCase):
self.assertIn("CREATE POLICY p_admin_health_daily_rollup_select", schema)
self.assertIn("CREATE POLICY p_admin_health_daily_rollup_update", schema)
self.assertIn("CREATE POLICY p_admin_health_event_delete", schema)
self.assertNotIn("CREATE POLICY p_admin_health_daily_rollup_delete", schema)
self.assertIn("CREATE POLICY p_admin_health_daily_rollup_delete", schema)
self.assertIn("USING (app.current_role_name() = 'admin');", schema)
migration = (
root / "infra" / "db" / "init" / "25_admin_health_rollup_retention.sql"
).read_text(encoding="utf-8")
self.assertIn("DROP POLICY IF EXISTS p_admin_health_daily_rollup_delete", migration)
self.assertIn("CREATE POLICY p_admin_health_daily_rollup_delete", migration)
self.assertIn("FOR DELETE", migration)
self.assertIn("app.current_role_name() = 'admin'", migration)
self.assertNotIn("learner", migration)
bootstrap = (root / "apps" / "api" / "app" / "auth_sessions.py").read_text(
encoding="utf-8"
)
self.assertIn("CREATE POLICY p_admin_health_daily_rollup_delete", bootstrap)

View file

@ -923,7 +923,18 @@ class AdminOpsTest(unittest.IsolatedAsyncioTestCase):
self.assertIn("CREATE POLICY p_admin_health_event_delete", schema)
self.assertIn("CREATE POLICY p_admin_health_daily_rollup_select", schema)
self.assertIn("CREATE POLICY p_admin_health_daily_rollup_update", schema)
self.assertNotIn("CREATE POLICY p_admin_health_daily_rollup_delete", schema)
self.assertIn(
"CREATE POLICY p_admin_health_daily_rollup_delete\n"
" ON app.admin_health_daily_rollup FOR DELETE\n"
" USING (app.current_role_name() = 'admin');",
schema,
)
self.assertNotIn(
"CREATE POLICY p_admin_health_daily_rollup_delete\n"
" ON app.admin_health_daily_rollup FOR DELETE\n"
" USING (app.current_role_name() = 'learner');",
schema,
)
self.assertIn("CREATE POLICY p_support_ticket_insert", schema)
self.assertIn("reporter_id = app.current_uid()", schema)
self.assertIn("fingerprint TEXT NOT NULL DEFAULT ''", schema)

View file

@ -449,7 +449,7 @@ class ClientReplyQualityGateTest(unittest.TestCase):
"docs",
"ops",
"evidence",
"c-001-crisis-case-runtime-observations-2026-09-22.json",
"c-001-crisis-case-runtime-observations-2026-10-19.json",
).read_text(encoding="utf-8")
)
runner = _load_clinical_observation_runner()

View file

@ -0,0 +1,136 @@
"""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()

View file

@ -173,11 +173,13 @@ class LiveCoachSourcePackTest(unittest.TestCase):
self.assertIn("dsm5tr_case_formulation", row_ids)
self.assertIn("official_suicide_risk_guidelines", row_ids)
self.assertEqual(row_ids, payload_ids)
self.assertTrue({"C", "D"}.issubset({row["license_class"] for row in rows}))
for row in rows:
self.assertTrue(row["title"])
self.assertIn(row["license_class"], {"A", "B", "C", "D"})
self.assertTrue(row["external_llm_ok"])
if row["license_class"] in {"C", "D"}:
self.assertFalse(row["external_llm_ok"])
for payload in payloads:
self.assertRegex(payload["content_hash"], r"^[0-9a-f]{64}$")
@ -189,6 +191,10 @@ class LiveCoachSourcePackTest(unittest.TestCase):
self.assertNotIn("client", chunk["visible_to"])
self.assertTrue(chunk["meta"]["live_coaching_source"])
self.assertTrue(chunk["meta"]["citation"])
self.assertEqual(
chunk["meta"]["external_llm_ok"],
next(row for row in rows if row["source_id"] == payload["source_id"])["external_llm_ok"],
)
dsm = next(payload for payload in payloads if payload["source_id"] == "dsm5tr_case_formulation")
self.assertTrue(all(chunk["sensitivity"] == 2 for chunk in dsm["chunks"]))