392 lines
13 KiB
Python
392 lines
13 KiB
Python
from __future__ import annotations
|
|
|
|
from datetime import UTC, datetime, timedelta
|
|
from types import SimpleNamespace
|
|
from unittest.mock import AsyncMock
|
|
|
|
import httpx
|
|
import pytest
|
|
from fastapi import FastAPI
|
|
from httpx import ASGITransport, AsyncClient
|
|
from sqlalchemy import create_engine
|
|
from sqlalchemy.orm import Session
|
|
|
|
from app.api.v1 import situational_awareness
|
|
from app.core.security import get_current_user
|
|
from app.db.session import get_db
|
|
from app.models.bgp_incident import BGPIncident
|
|
from app.models.situational_assessment import (
|
|
ComputeEvidenceCandidate,
|
|
EvidenceRecord,
|
|
SituationalAssessment,
|
|
StagePresentation,
|
|
)
|
|
from app.models.system_log import AuditLog
|
|
from app.models.system_setting import SystemSetting
|
|
from app.schemas.ai import SituationalAnalysisResponse
|
|
from app.services.ai.posture_agent import (
|
|
StrategicPostureBrief,
|
|
generate_or_get_compute_posture,
|
|
verify_brief_citations,
|
|
)
|
|
from app.services.ai.presentation_compiler import list_or_compile_presentations
|
|
from app.services.ai.semantic_delta import classify_snapshot_delta
|
|
from app.services.ai.thinking_sanitizer import (
|
|
assert_no_thinking_leak,
|
|
extract_json_object,
|
|
sanitize_analysis_response,
|
|
strip_thinking_text,
|
|
)
|
|
from app.services.ai.tool_registry import (
|
|
SSRFBlockedError,
|
|
safe_web_fetch,
|
|
validate_public_http_url,
|
|
)
|
|
from app.services.ai_client import get_ai_provider_client
|
|
from app.services.compute_history import compute_history
|
|
from app.services.earth_db_change_listener import build_earth_update_from_db_payload
|
|
|
|
|
|
def test_thinking_sanitizer_strips_tags_and_preserves_audit_blocks():
|
|
raw = "<think>Internal chain of thought step 1</think>\n```json\n{\"ok\": true}\n```"
|
|
cleaned, thoughts = strip_thinking_text(raw)
|
|
assert "<think>" not in cleaned
|
|
assert thoughts == ["Internal chain of thought step 1"]
|
|
assert extract_json_object(raw) == {"ok": True}
|
|
|
|
resp = SituationalAnalysisResponse(
|
|
provider="openai_compat",
|
|
model="deepseek-r1",
|
|
content="<thinking>drafting</thinking>Final concise briefing.",
|
|
text_blocks=["<think>block thought</think>Clean block"],
|
|
thinking_blocks=[],
|
|
raw_response={"reasoning_content": "provider reasoning trace"},
|
|
)
|
|
sanitized = sanitize_analysis_response(resp)
|
|
assert sanitized.content == "Final concise briefing."
|
|
assert sanitized.text_blocks == ["Clean block"]
|
|
assert "drafting" in sanitized.thinking_blocks
|
|
assert "provider reasoning trace" in sanitized.thinking_blocks
|
|
assert_no_thinking_leak(sanitized.content)
|
|
|
|
with pytest.raises(ValueError, match="Reasoning trace leaked"):
|
|
assert_no_thinking_leak({"text": "oops <think>secret</think>"})
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
"bad_url",
|
|
[
|
|
"http://127.0.0.1:8000/api/v1/settings",
|
|
"http://localhost/admin",
|
|
"http://169.254.169.254/latest/meta-data/",
|
|
"http://10.0.0.5/internal",
|
|
"http://192.168.1.1/",
|
|
"https://planet_postgres:5432/",
|
|
"file:///etc/passwd",
|
|
"https://admin:secret@example.com/report",
|
|
],
|
|
)
|
|
def test_ssrf_guard_blocks_internal_and_credentialed_urls(bad_url):
|
|
with pytest.raises(SSRFBlockedError):
|
|
validate_public_http_url(bad_url, resolve_dns=False)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_safe_web_fetch_blocks_redirect_to_loopback():
|
|
def handler(request: httpx.Request) -> httpx.Response:
|
|
if request.url.host == "public.example.org":
|
|
return httpx.Response(302, headers={"Location": "http://127.0.0.1:8080/secret"})
|
|
return httpx.Response(200, text="<html><body>secret</body></html>")
|
|
|
|
transport = httpx.MockTransport(handler)
|
|
with pytest.raises(SSRFBlockedError):
|
|
await safe_web_fetch(
|
|
"https://public.example.org/advisory",
|
|
transport=transport,
|
|
resolve_dns=False,
|
|
)
|
|
|
|
|
|
def test_semantic_delta_distinguishes_failures_retries_and_five_states():
|
|
now = datetime.now(UTC)
|
|
prev = {
|
|
"status": "success",
|
|
"completed_at": (now - timedelta(minutes=10)).isoformat(),
|
|
"record_count": 100,
|
|
"active_keys": ["inc-1"],
|
|
"metrics": {"cn_share": 31.0},
|
|
}
|
|
|
|
failed = classify_snapshot_delta(prev, {"status": "failed", "error": "timeout"}, now=now)
|
|
assert failed["verdict"] == "indeterminate"
|
|
assert failed["preserve_previous_snapshot"] is True
|
|
assert failed["emit_event"] is False
|
|
|
|
coverage_drop = classify_snapshot_delta(
|
|
prev,
|
|
{
|
|
"status": "success",
|
|
"completed_at": now.isoformat(),
|
|
"record_count": 30,
|
|
"active_keys": [],
|
|
},
|
|
now=now,
|
|
)
|
|
assert coverage_drop["verdict"] == "indeterminate"
|
|
assert coverage_drop["preserve_previous_snapshot"] is True
|
|
|
|
seen: set[str] = set()
|
|
changed = classify_snapshot_delta(
|
|
prev,
|
|
{
|
|
"status": "success",
|
|
"completed_at": now.isoformat(),
|
|
"record_count": 98,
|
|
"active_keys": ["inc-1", "inc-2"],
|
|
"metrics": {"cn_share": 23.0},
|
|
},
|
|
now=now,
|
|
seen_fingerprints=seen,
|
|
)
|
|
assert changed["verdict"] == "new_change"
|
|
assert changed["emit_event"] is True
|
|
assert changed["added_keys"] == ["inc-2"]
|
|
|
|
duplicate = classify_snapshot_delta(
|
|
prev,
|
|
{
|
|
"status": "success",
|
|
"completed_at": now.isoformat(),
|
|
"record_count": 98,
|
|
"active_keys": ["inc-1", "inc-2"],
|
|
"metrics": {"cn_share": 23.0},
|
|
},
|
|
now=now,
|
|
seen_fingerprints=seen,
|
|
)
|
|
assert duplicate["is_duplicate_retry"] is True
|
|
assert duplicate["emit_event"] is False
|
|
|
|
recovered = classify_snapshot_delta(
|
|
prev,
|
|
{
|
|
"status": "success",
|
|
"completed_at": now.isoformat(),
|
|
"record_count": 100,
|
|
"active_keys": [],
|
|
"metrics": {"cn_share": 31.0},
|
|
},
|
|
now=now,
|
|
)
|
|
assert recovered["verdict"] == "recovery_progress"
|
|
|
|
stable = classify_snapshot_delta(
|
|
{"status": "success", "record_count": 100, "active_keys": []},
|
|
{"status": "success", "completed_at": now.isoformat(), "record_count": 100, "active_keys": []},
|
|
now=now,
|
|
)
|
|
assert stable["verdict"] == "stable"
|
|
|
|
|
|
def test_posture_citation_validator_rejects_fake_evidence_id():
|
|
fake = StrategicPostureBrief(
|
|
headline="Test",
|
|
headline_en="Test",
|
|
executive_assertion="Assertion",
|
|
executive_assertion_en="Assertion",
|
|
causes=[],
|
|
breakthrough_levers=[],
|
|
blind_spots=[],
|
|
evidence_ids=["hallucinated-source-999"],
|
|
)
|
|
with pytest.raises(ValueError, match="Unverified evidence IDs"):
|
|
verify_brief_citations(fake, {"caict-2025": {"title": "Valid"}})
|
|
|
|
|
|
def test_outbox_adapter_maps_stage_presentations_to_delta_layer():
|
|
update = build_earth_update_from_db_payload(
|
|
{"table": "stage_presentations", "operation": "INSERT", "entity_key": "1"}
|
|
)
|
|
assert update is not None
|
|
assert update["layers"] == ["situationalAwareness"]
|
|
assert update["refresh_strategy"] == "delta"
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_sqlite_ledger_caching_presentations_copilot_and_report_export():
|
|
engine = create_engine("sqlite://")
|
|
for model in (
|
|
SystemSetting,
|
|
AuditLog,
|
|
BGPIncident,
|
|
EvidenceRecord,
|
|
SituationalAssessment,
|
|
StagePresentation,
|
|
ComputeEvidenceCandidate,
|
|
):
|
|
model.__table__.create(engine)
|
|
raw_session = Session(engine)
|
|
session = SimpleNamespace(
|
|
execute=AsyncMock(side_effect=raw_session.execute),
|
|
add=raw_session.add,
|
|
flush=AsyncMock(side_effect=raw_session.flush),
|
|
commit=AsyncMock(side_effect=raw_session.commit),
|
|
refresh=AsyncMock(side_effect=raw_session.refresh),
|
|
)
|
|
|
|
fake_ai = SimpleNamespace(
|
|
service_url="http://mock-ai",
|
|
analyze=AsyncMock(
|
|
return_value=SituationalAnalysisResponse(
|
|
provider="mock",
|
|
model="mock-model",
|
|
content='<think>internal thought</think>{"headline":"Bad","headline_en":"Bad","executive_assertion":"A","executive_assertion_en":"A","causes":[],"breakthrough_levers":[],"blind_spots":[],"evidence_ids":["nonexistent-id"]}',
|
|
text_blocks=[],
|
|
thinking_blocks=[],
|
|
raw_response={},
|
|
)
|
|
),
|
|
)
|
|
|
|
series = compute_history(["CN", "US"], "global_share")
|
|
first = await generate_or_get_compute_posture(
|
|
session,
|
|
countries=["CN", "US"],
|
|
mode="global_share",
|
|
series_payload=series,
|
|
ai_client=fake_ai,
|
|
prefer_llm=True,
|
|
)
|
|
await session.commit()
|
|
assert first["generation_mode"] == "deterministic_baseline"
|
|
assert first["cache_hit"] is False
|
|
assert "caict-2025" in first["evidence_ids"]
|
|
assert_no_thinking_leak(first["payload"])
|
|
|
|
second = await generate_or_get_compute_posture(
|
|
session,
|
|
countries=["CN", "US"],
|
|
mode="global_share",
|
|
series_payload=series,
|
|
)
|
|
assert second["cache_hit"] is True
|
|
assert second["revision"] == first["revision"]
|
|
|
|
default_no_drill = await list_or_compile_presentations(
|
|
session, after_cursor=0, countries=["CN", "US"], time_basis="retrospective"
|
|
)
|
|
assert len(default_no_drill["items"]) == 1
|
|
assert all(item["domain"] != "bgp" for item in default_no_drill["items"])
|
|
|
|
as_known = await list_or_compile_presentations(
|
|
session,
|
|
after_cursor=0,
|
|
countries=["CN", "US"],
|
|
time_basis="as_known_then",
|
|
include_drill=True,
|
|
)
|
|
await session.commit()
|
|
assert len(as_known["items"]) == 2
|
|
inc_pres = next(i for i in as_known["items"] if i["domain"] == "bgp")
|
|
assert inc_pres["is_drill"] is True
|
|
assert "ev-cloudflare-postmortem" not in inc_pres["contract"]["evidence"]
|
|
assert len(inc_pres["contract"]["steps"]) == 5
|
|
|
|
retro = await list_or_compile_presentations(
|
|
session,
|
|
after_cursor=0,
|
|
countries=["CN", "US"],
|
|
time_basis="retrospective",
|
|
include_drill=True,
|
|
)
|
|
await session.commit()
|
|
inc_retro = next(i for i in retro["items"] if i["domain"] == "bgp")
|
|
assert "ev-cloudflare-postmortem" in inc_retro["contract"]["evidence"]
|
|
|
|
expired = await list_or_compile_presentations(
|
|
session,
|
|
after_cursor=999999,
|
|
countries=["CN", "US"],
|
|
time_basis="retrospective",
|
|
include_drill=True,
|
|
)
|
|
assert expired["cursor_expired_full_sync"] is True
|
|
assert len(expired["items"]) == 2
|
|
|
|
app = FastAPI()
|
|
app.include_router(situational_awareness.router, prefix="/situational-awareness")
|
|
|
|
app.dependency_overrides[get_db] = lambda: session
|
|
app.dependency_overrides[get_ai_provider_client] = lambda: SimpleNamespace(service_url="")
|
|
app.dependency_overrides[get_current_user] = lambda: SimpleNamespace(
|
|
id=1, username="admin", role="admin"
|
|
)
|
|
|
|
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
|
|
posture_res = await client.get("/situational-awareness/posture/compute?countries=CN,US")
|
|
assert posture_res.status_code == 200
|
|
live_revision = posture_res.json()["revision"]
|
|
|
|
inv_res = await client.post(
|
|
"/situational-awareness/investigate",
|
|
json={
|
|
"domain": "compute",
|
|
"selected_codes": ["CN", "US"],
|
|
"question": "东数西算八大国家枢纽如何协同?",
|
|
},
|
|
)
|
|
assert inv_res.status_code == 200
|
|
inv_json = inv_res.json()
|
|
assert "hub-guizhou" in inv_json["reply"]["highlight_entities"]
|
|
|
|
exp_ok = await client.post(
|
|
"/situational-awareness/reports/export",
|
|
json={
|
|
"subject_type": "compute_posture",
|
|
"countries": ["CN", "US"],
|
|
"expected_revision": live_revision,
|
|
},
|
|
)
|
|
assert exp_ok.status_code == 200
|
|
assert "sha256:" in exp_ok.json()["markdown"]
|
|
|
|
exp_conflict = await client.post(
|
|
"/situational-awareness/reports/export",
|
|
json={
|
|
"subject_type": "compute_posture",
|
|
"countries": ["CN", "US"],
|
|
"expected_revision": 99,
|
|
},
|
|
)
|
|
assert exp_conflict.status_code == 409
|
|
|
|
ext_res = await client.post(
|
|
"/situational-awareness/candidates/extract",
|
|
json={
|
|
"year": 2024,
|
|
"excerpt": "报告显示,美国全球总算力份额达到 44%,中国全球总算力份额为 23%,全球智能算力份额中国为 21%。",
|
|
"source_id": "caict-2025",
|
|
"source_title": "先进计算暨算力发展指数蓝皮书(2025年)",
|
|
"source_url": "https://www.caict.ac.cn/report.pdf",
|
|
},
|
|
)
|
|
assert ext_res.status_code == 200
|
|
cand_items = ext_res.json()["items"]
|
|
assert len(cand_items) >= 1
|
|
cand_id = cand_items[0]["id"]
|
|
|
|
rev_res = await client.post(
|
|
f"/situational-awareness/candidates/{cand_id}/review",
|
|
json={
|
|
"decision": "approved",
|
|
"reason_code": "newer_authoritative_report",
|
|
"reason": "Verified against official CAICT 2025 blue book figures.",
|
|
},
|
|
)
|
|
assert rev_res.status_code == 200
|
|
assert rev_res.json()["status"] == "approved"
|
|
assert rev_res.json()["review_reason_code"] == "newer_authoritative_report"
|
|
|
|
raw_session.close()
|
|
engine.dispose()
|