인증 경로 보존과 의존성 보안 검증을 보강

This commit is contained in:
Yun Chan 2026-10-20 23:50:33 +09:00
parent d2ba836565
commit d801a1619d
10 changed files with 222 additions and 77 deletions

View file

@ -4,7 +4,7 @@ from __future__ import annotations
from typing import Literal
from pydantic import BaseModel, ConfigDict, Field, model_validator
from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator
AttentionSignalType = Literal[
@ -31,6 +31,17 @@ ManifestDomain = Literal["alliance", "rupture", "transfer", "calibration"]
DriftStatus = Literal["stable", "drift_flagged", "insufficient_evidence"]
def _validate_app_relative_route(value: str) -> str:
if not value.startswith("/") or value.startswith("//"):
raise ValueError("route must be an app-relative path")
if not all(
char.isascii() and (char.isalnum() or char in "_{}?&=./-")
for char in value
):
raise ValueError("route contains unsupported characters")
return value
class LedgerEvidencePointer(BaseModel):
model_config = ConfigDict(extra="forbid", frozen=True, protected_namespaces=())
@ -39,6 +50,11 @@ class LedgerEvidencePointer(BaseModel):
session_id: str | None = Field(default=None, max_length=180)
route_hint: str = Field(pattern=r"^/[a-zA-Z0-9_{}?&=./-]+$")
@field_validator("route_hint")
@classmethod
def require_app_relative_route(cls, value: str) -> str:
return _validate_app_relative_route(value)
class LearnerAttentionSignal(BaseModel):
model_config = ConfigDict(extra="forbid", frozen=True, protected_namespaces=())
@ -87,6 +103,13 @@ class AttentionQueueItem(BaseModel):
reasons: tuple[AttentionQueueReason, ...] = Field(min_length=1)
drilldown_routes: tuple[str, ...] = Field(min_length=1)
@field_validator("drilldown_routes")
@classmethod
def require_app_relative_drilldown_routes(
cls, value: tuple[str, ...]
) -> tuple[str, ...]:
return tuple(_validate_app_relative_route(route) for route in value)
@model_validator(mode="after")
def enforce_direct_drilldown(self) -> "AttentionQueueItem":
if len(self.drilldown_routes) > 3:

View file

@ -6,6 +6,7 @@ import asyncio
import importlib.util
import json
import unittest
from unittest.mock import patch
from .paths import repo_path
from .services import guardrail
@ -453,7 +454,12 @@ class ClientReplyQualityGateTest(unittest.TestCase):
).read_text(encoding="utf-8")
)
runner = _load_clinical_observation_runner()
current = asyncio.run(runner.build_observations(artifact["generated_at"]))
with patch.object(
runner.orchestrator.settings,
"client_affect_provider",
"legacy",
):
current = asyncio.run(runner.build_observations(artifact["generated_at"]))
self.assertEqual(
artifact["schema_version"],

View file

@ -140,6 +140,13 @@ class CaptureStreamEngine:
class OrchestratorMaskingGateTest(unittest.IsolatedAsyncioTestCase):
def setUp(self) -> None:
self.client_affect_provider_patch = patch.object(
orchestrator.settings,
"client_affect_provider",
"legacy",
)
self.client_affect_provider_patch.start()
self.addCleanup(self.client_affect_provider_patch.stop)
self.presidio_patch = patch.object(
guardrail,
"_try_load_presidio",

View file

@ -331,6 +331,15 @@ class ScenarioDirectorSelectionTests(unittest.TestCase):
class ScenarioDirectorPromptIntegrationTests(unittest.IsolatedAsyncioTestCase):
def setUp(self) -> None:
self.client_affect_provider_patch = patch.object(
orchestrator.settings,
"client_affect_provider",
"legacy",
)
self.client_affect_provider_patch.start()
self.addCleanup(self.client_affect_provider_patch.stop)
async def test_generate_request_keeps_cue_in_prompt_and_provenance_metadata_only(
self,
) -> None:

View file

@ -111,6 +111,13 @@ async def _consume_event_source(response: object) -> bytes:
class SessionTurnPersistenceTest(unittest.IsolatedAsyncioTestCase):
async def asyncSetUp(self) -> None:
self.client_affect_provider_patch = patch.object(
orchestrator.settings,
"client_affect_provider",
"legacy",
)
self.client_affect_provider_patch.start()
self.addCleanup(self.client_affect_provider_patch.stop)
store._sessions.clear()
sessions._RECALL_CACHE.clear()
sessions._KB_CUES_CACHE.clear()

View file

@ -6,7 +6,9 @@ from pathlib import Path
from pydantic import ValidationError
from .contracts.supervision_research import (
AttentionQueueItem,
EvaluationVersionBatch,
LedgerEvidencePointer,
LearnerAttentionSignal,
Phase3OutcomeEvidenceManifest,
TeacherAiDisagreement,
@ -99,6 +101,61 @@ class AttentionQueueTests(unittest.TestCase):
LearnerAttentionSignal.model_validate(payload)
class SupervisionRouteContractTests(unittest.TestCase):
VALID_ROUTES = (
"/teach",
"/teach/session/uuid/review",
"/teacher/dashboard?cohort=abc",
)
INVALID_ROUTES = (
"//evil.test/path",
"https://evil.test/path",
"/\\evil.test/path",
"/teach\nnext",
)
@classmethod
def setUpClass(cls) -> None:
cls.pack = load_supervision_research_benchmark(BENCHMARK_PATH)
cls.queue_item_payload = build_attention_queue(cls.pack.attention_signals)[
0
].model_dump(mode="json")
def test_ledger_evidence_routes_allow_app_relative_paths(self) -> None:
for route in self.VALID_ROUTES:
with self.subTest(route=route):
pointer = LedgerEvidencePointer(
ledger="measurement_event",
event_id="event-1",
route_hint=route,
)
self.assertEqual(pointer.route_hint, route)
def test_ledger_evidence_routes_reject_external_and_unsupported_paths(self) -> None:
for route in self.INVALID_ROUTES:
with self.subTest(route=route):
with self.assertRaises(ValidationError):
LedgerEvidencePointer(
ledger="measurement_event",
event_id="event-1",
route_hint=route,
)
def test_attention_queue_routes_allow_app_relative_paths(self) -> None:
payload = dict(self.queue_item_payload)
payload["drilldown_routes"] = list(self.VALID_ROUTES)
item = AttentionQueueItem.model_validate(payload)
self.assertEqual(item.drilldown_routes, self.VALID_ROUTES)
def test_attention_queue_routes_reject_external_and_unsupported_paths(self) -> None:
for route in self.INVALID_ROUTES:
with self.subTest(route=route):
payload = dict(self.queue_item_payload)
payload["drilldown_routes"] = [route]
with self.assertRaises(ValidationError):
AttentionQueueItem.model_validate(payload)
class CalibrationDatasetTests(unittest.TestCase):
@classmethod
def setUpClass(cls) -> None: