trustgraph/tests/unit/test_base/test_audit_publisher.py
cybermaggedon d5f3b6d9f6
feat: add structured audit event system (#1027)
Add a complete audit event pipeline that emits structured, machine-
parseable events for every gateway request and IAM decision.

Schema and publisher:
- AuditEvent dataclass and notify-class queue (audit_events_queue)
- AuditPublisher utility: fire-and-forget emission with envelope
  (schema_version, event_id, event_type, timestamp, producer)
- New request_id and client_ip fields on IamRequest for correlation

Gateway (gateway.request events):
- aiohttp middleware assigns request_id, captures timing/status/sizes
  and emits an event after every HTTP request completes
- IamAuth.authenticate annotates the request with identity
- Main endpoint handlers annotate capability and workspace
- request_id and client_ip forwarded to IAM on authenticate/authorise

IAM service (iam.authenticate, iam.authorise, iam.management events):
- Emits iam.authenticate for resolve-api-key, login, anonymous auth
- Emits iam.authorise for authorise and authorise-many decisions
- Emits iam.management for user/workspace/key mutations
- All events include request_id for correlation with gateway events

Design: events land on a pub/sub notify topic — non-persistent,
per-subscriber delivery. If no audit consumer is deployed, events
are silently discarded. Storage, retention, and alerting are
consumer-side concerns outside this boundary.

Added unit tests for the publisher and gateway middleware, unit
tests for IAM audit emission, and a contract test for the AuditEvent
schema.

Tech spec: docs/tech-specs/audit-events.md
2026-07-06 10:47:49 +01:00

90 lines
2.8 KiB
Python

"""
Tests for the AuditPublisher utility.
Verifies envelope construction, fire-and-forget semantics, and
failure suppression.
"""
import json
import pytest
from unittest.mock import AsyncMock, MagicMock, patch
from trustgraph.base.audit_publisher import AuditPublisher
from trustgraph.schema import AuditEvent, audit_events_queue
class TestAuditPublisherInit:
def test_queue_is_notify_class(self):
assert audit_events_queue == "notify:tg:audit-events"
def test_creates_producer_with_audit_queue(self):
backend = MagicMock()
pub = AuditPublisher(
backend=backend,
component_name="test-component",
)
assert pub.producer.topic == audit_events_queue
assert pub.producer.schema == AuditEvent
assert pub.component_name == "test-component"
class TestAuditPublisherEmit:
@pytest.fixture
def publisher(self):
backend = MagicMock()
pub = AuditPublisher(
backend=backend,
component_name="test-svc",
processor_id="proc-1",
)
pub.producer = AsyncMock()
return pub
@pytest.mark.asyncio
async def test_emit_sends_structured_envelope(self, publisher):
await publisher.emit("gateway.request", {"path": "/test"})
publisher.producer.send.assert_called_once()
event = publisher.producer.send.call_args[0][0]
assert isinstance(event, AuditEvent)
assert event.schema_version == 1
assert event.event_type == "gateway.request"
assert event.producer == "test-svc"
assert event.event_id != ""
assert event.timestamp != ""
@pytest.mark.asyncio
async def test_emit_serializes_payload_as_json(self, publisher):
payload = {"method": "POST", "status_code": 200}
await publisher.emit("gateway.request", payload)
event = publisher.producer.send.call_args[0][0]
decoded = json.loads(event.payload_json)
assert decoded == payload
@pytest.mark.asyncio
async def test_emit_generates_unique_event_ids(self, publisher):
await publisher.emit("test.a", {})
await publisher.emit("test.b", {})
ids = [
call[0][0].event_id
for call in publisher.producer.send.call_args_list
]
assert ids[0] != ids[1]
@pytest.mark.asyncio
async def test_emit_swallows_send_failure(self, publisher):
publisher.producer.send.side_effect = RuntimeError("pub/sub down")
await publisher.emit("test.event", {"key": "value"})
@pytest.mark.asyncio
async def test_emit_timestamp_is_utc_iso(self, publisher):
await publisher.emit("test.event", {})
event = publisher.producer.send.call_args[0][0]
assert "T" in event.timestamp
assert "+" in event.timestamp or "Z" in event.timestamp