# Audit Service

# Audit Service (Port 8013) {#audit-service-port-8013}


The **audit-service** provides structured audit logging for compliance, security monitoring, and data access tracking.


## Database {#database}


**Database:** `audit_db`

| Table | Purpose |
|-------|---------|
| `audit_logs` | Core audit event log |
| `data_access_logs` | Data access records |
| `consent_records` | Consent tracking for GDPR/regulatory compliance |


## API Endpoints {#api-endpoints}


| Method | Path | Purpose |
|--------|------|---------|
| GET | `/logs` | Query audit logs |
| GET | `/logs/export` | Export logs |
| GET | `/compliance` | Compliance reports |


## Audit Event Schema {#audit-event-schema}


Each audit event contains:

```json
{
  "event_id": "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:00Z",
  "metadata": {
    "previous_status": "pending",
    "new_status": "approved",
    "ip_address": "192.168.1.1",
    "user_agent": "Mozilla/5.0..."
  }
}
```


## Event Taxonomy {#event-taxonomy}


| Category | Event Types |
|----------|-------------|
| Authentication | `user.login`, `user.logout`, `user.login_failed` |
| User Management | `user.created`, `user.updated`, `user.deleted` |
| Survey | `survey.created`, `survey.published`, `survey.deleted` |
| Response | `response.submitted`, `response.approved`, `response.rejected` |
| Tenant | `tenant.created`, `tenant.suspended`, `tenant.dormant` |
| Billing | `subscription.created`, `subscription.cancelled` |


## Logging from Other Services {#logging-from-other-services}


Services send audit events via HTTP:

```python
async def log_audit_event(event_type, actor_id, resource_type, resource_id, metadata=None):
    async with httpx.AsyncClient() as client:
        await client.post(
            f"{AUDIT_SERVICE_URL}/logs",
            json={
                "event_type": event_type,
                "actor_id": actor_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}
        )
```


## Retention {#retention}


Log retention policies are configurable per tenant:

```python
RETENTION_POLICIES = {
    "audit_logs": timedelta(days=365),       # 1 year
    "data_access_logs": timedelta(days=90),  # 90 days
}
```


## Integrity {#integrity}


Audit logs are append-only. Deletion is not permitted — only archival after the retention period.
