Close 12 audit-driven platform-compliance gaps on a single branch. - D4 dispatch: app/integrations/dispatch_client.py participant `legacyhub`, emits LegacyhubDocumentIndexed + AssetDerivativeReady after the indexing commit (idempotent uuid5), http_inbox route (reindex/tombstone) with audit-based dedupe; docs/dispatch-contract.md. Celery+Redis stays intra-module. - D2 SSO: app/integrations/identity.py validates X-TeamHub-* + role/scope mapper; security.py adds trusted-header enforcement (AUTH_REQUIRE_IDENTITY) and a scope check on /search; docker-compose.teamhub.yml (external teamhub_net + internal db net, api not host-published); RUNBOOK network/firewall section. - Asset standard: SearchHit/Citation carry asset_id/owner_module; buckets renamed teamhub-legacyhub-* (+quarantine/tmp/exports); purge-by-asset_id with legal-hold guard (app/indexing/projection.py); OCR-markdown derivative event. - audit_log model + Alembic 0003 + record_audit on writes (same transaction). - Secret masking: app/common/json_logger.py recursive mask wired into structlog (+ensure_ascii=False); event payloads redacted before persistence. - Service X-API-Key mandatory on ingest endpoints (defence-in-depth). - Port: host API 8000->8050 (collision with SalesHUB/MailHUB resolved), container still listens on 8000. - Config: no plaintext secret defaults; fail-loud in non-dev (no value leak). - Docs drift: README PG 5440, layered-auth note, 5173 removed from CORS; ingest/folder gated by ENABLE_FOLDER_INGEST (410 by default). - ADRs: layers mapping, shared-core extraction, UI locale (RU-first). Tests: 78 passing (ruff, compileall, pytest, tsc, vite build, compose config). Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
129 lines
3.9 KiB
Python
129 lines
3.9 KiB
Python
"""Tests for mandatory service-key auth on the ingest endpoints."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import importlib
|
|
import os
|
|
|
|
import pytest
|
|
from fastapi import HTTPException
|
|
from fastapi.testclient import TestClient
|
|
|
|
from app.api.security import require_service_api_key
|
|
|
|
|
|
class _Req:
|
|
def __init__(self, headers: dict[str, str]) -> None:
|
|
self.headers = headers
|
|
|
|
|
|
def test_open_when_no_key_configured(monkeypatch):
|
|
from app.config import settings
|
|
|
|
monkeypatch.setattr(settings, "ingest_api_key", "")
|
|
monkeypatch.setattr(settings, "api_key", "")
|
|
require_service_api_key(_Req({})) # must not raise
|
|
|
|
|
|
def test_rejects_missing_key(monkeypatch):
|
|
from app.config import settings
|
|
|
|
monkeypatch.setattr(settings, "ingest_api_key", "svc-key")
|
|
monkeypatch.setattr(settings, "api_key", "")
|
|
with pytest.raises(HTTPException) as exc:
|
|
require_service_api_key(_Req({}))
|
|
assert exc.value.status_code == 401
|
|
|
|
|
|
def test_accepts_valid_x_api_key(monkeypatch):
|
|
from app.config import settings
|
|
|
|
monkeypatch.setattr(settings, "ingest_api_key", "svc-key")
|
|
monkeypatch.setattr(settings, "api_key", "")
|
|
require_service_api_key(_Req({"x-api-key": "svc-key"})) # must not raise
|
|
|
|
|
|
def test_falls_back_to_global_api_key_via_bearer(monkeypatch):
|
|
from app.config import settings
|
|
|
|
monkeypatch.setattr(settings, "ingest_api_key", "")
|
|
monkeypatch.setattr(settings, "api_key", "glob-key")
|
|
require_service_api_key(_Req({"authorization": "Bearer glob-key"})) # must not raise
|
|
|
|
|
|
def test_rejects_wrong_key(monkeypatch):
|
|
from app.config import settings
|
|
|
|
monkeypatch.setattr(settings, "ingest_api_key", "svc-key")
|
|
monkeypatch.setattr(settings, "api_key", "")
|
|
with pytest.raises(HTTPException):
|
|
require_service_api_key(_Req({"x-api-key": "nope"}))
|
|
|
|
|
|
# ---- integration ----
|
|
|
|
_MANIFEST = {
|
|
"manifest": {
|
|
"manifest_version": "1.0",
|
|
"asset": {
|
|
"asset_id": "asset_x",
|
|
"owner_module": "qms",
|
|
"owner_record_type": "doc",
|
|
"owner_record_id": "1",
|
|
"asset_kind": "document",
|
|
"content_type": "application/pdf",
|
|
"size_bytes": 10,
|
|
"sha256": "a" * 64,
|
|
},
|
|
"storage": {
|
|
"provider": "minio",
|
|
"bucket": "teamhub-qms-originals",
|
|
"object_key": "qms/2026/01/01/asset_x/original/f.pdf",
|
|
},
|
|
# pending gate -> handler short-circuits before any storage access.
|
|
"security": {"gate_status": "pending"},
|
|
"retention": {"policy_id": "default", "legal_hold": False},
|
|
}
|
|
}
|
|
|
|
|
|
@pytest.fixture
|
|
def ingest_secured_app(monkeypatch):
|
|
monkeypatch.setenv("INGEST_API_KEY", "svc-key")
|
|
monkeypatch.delenv("API_KEY", raising=False)
|
|
import app.config as cfg
|
|
import app.main as main_module
|
|
|
|
cfg.get_settings.cache_clear()
|
|
importlib.reload(cfg)
|
|
importlib.reload(main_module)
|
|
yield main_module.app
|
|
for _k in ("API_KEY", "INGEST_API_KEY", "AUTH_REQUIRE_IDENTITY"):
|
|
os.environ.pop(_k, None)
|
|
cfg.get_settings.cache_clear()
|
|
importlib.reload(cfg)
|
|
importlib.reload(main_module)
|
|
|
|
|
|
def test_knowledge_ingest_rejects_without_service_key(ingest_secured_app):
|
|
from app.config import settings
|
|
|
|
client = TestClient(ingest_secured_app)
|
|
res = client.post(f"{settings.app_api_prefix}/knowledge-ingest", json=_MANIFEST)
|
|
assert res.status_code == 401
|
|
|
|
|
|
def test_knowledge_ingest_accepts_with_service_key(ingest_secured_app):
|
|
from app.config import settings
|
|
|
|
client = TestClient(ingest_secured_app)
|
|
res = client.post(
|
|
f"{settings.app_api_prefix}/knowledge-ingest",
|
|
headers={"X-API-Key": "svc-key"},
|
|
json=_MANIFEST,
|
|
)
|
|
# Auth passed; the pending gate makes the handler return a clean rejection.
|
|
assert res.status_code == 200
|
|
assert res.json()["status"] == "rejected"
|
|
assert res.json()["reason_code"] == "security_gate_not_approved"
|