# Audit Logging {#audit-logging}



## Overview {#overview}


The audit-service provides a centralized, append-only audit trail for all meaningful events across the MQUAD platform.


## Event Taxonomy {#event-taxonomy}


| Category | Event Types |
|----------|-------------|
| **Authentication** | `user.login`, `user.logout`, `user.login_failed` |
| **User Management** | `user.created`, `user.updated`, `user.deleted`, `user.role_changed` |
| **Survey** | `survey.created`, `survey.updated`, `survey.deleted`, `survey.published`, `survey.unpublished` |
| **Response** | `response.submitted`, `response.approved`, `response.rejected`, `response.invalidated`, `response.edited` |
| **Tenant** | `tenant.created`, `tenant.updated`, `tenant.suspended`, `tenant.dormant`, `tenant.reactivated` |
| **Billing** | `subscription.created`, `subscription.cancelled`, `subscription.updated`, `invoice.paid` |
| **Consent** | `consent.granted`, `consent.withdrawn`, `consent.expired` |


## Audit Log Format {#audit-log-format}


```json
{
  "event_id": "evt_uuid",
  "event_type": "response.approved",
  "actor_id": "user-uuid",
  "tenant_id": "tenant-uuid",
  "resource_type": "response",
  "resource_id": "response-uuid",
  "action": "approve",
  "timestamp": "2026-05-13T10:30:00.000Z",
  "source_ip": "192.168.1.1",
  "user_agent": "Mozilla/5.0...",
  "metadata": {
    "previous_status": "pending",
    "new_status": "approved"
  }
}
```


## Logging Events {#logging-events}


Services send audit events to the audit-service via HTTP:

```python
import httpx

async def log_audit(event_type, resource_type, resource_id, metadata=None):
    async with httpx.AsyncClient() as client:
        await client.post(
            "http://audit-service:8013/logs",
            json={
                "event_type": event_type,
                "actor_id": request.state.user_id,
                "tenant_id": request.state.tenant_id,
                "resource_type": resource_type,
                "resource_id": resource_id,
                "metadata": metadata or {}
            },
            headers={"X-Service-API-Key": SERVICE_API_KEY}
        )
```


## Querying Audit Logs {#querying-audit-logs}


```bash
# List logs with filtering
curl -H "Authorization: Bearer <token>" \
  "http://localhost:8000/api/v1/audit-logs?event_type=response.approved&from=2026-01-01&to=2026-05-13&skip=0&limit=50"

# Export logs
curl -H "Authorization: Bearer <token>" \
  "http://localhost:8000/api/v1/audit-logs/download?format=csv"
```


## Retention Policies {#retention-policies}


```python
RETENTION = {
    "audit_logs": timedelta(days=365),        # 1 year
    "data_access_logs": timedelta(days=90),   # 90 days
    "consent_records": timedelta(days=3650),  # 10 years (regulatory)
}
```


## Integrity {#integrity}


Audit logs are **append-only**. Physical deletion is not permitted — archived after retention period. Each event has a unique `event_id` (UUID v4) for tamper-evident sequencing.
