infrastructure.audit.postgres_adapter¶
src.infrastructure.audit.postgres_adapter
¶
PostgreSQL implementation of AuditProtocol.
This adapter provides immutable audit logging using PostgreSQL with: - Database RULES blocking UPDATE/DELETE operations - Async SQLAlchemy for database operations - Result types for error handling (no exceptions) - JSONB storage for flexible context data
Following hexagonal architecture: - Infrastructure implements domain protocol (AuditProtocol) - Domain doesn't know about PostgreSQL or SQLAlchemy - Easy to swap implementations (MongoDB, MySQL, in-memory for testing)
Immutability
Records are immutable by design: - PostgreSQL RULES block UPDATE operations (see migration) - PostgreSQL RULES block DELETE operations (see migration) - Only INSERT operations are allowed - TRUNCATE requires table owner privileges (documented limitation)
Compliance
PCI-DSS: 7+ year retention, immutable audit trail SOC 2: Security event tracking (who/what/when/where) GDPR: Personal data access tracking
Usage
from src.infrastructure.audit.postgres_adapter import PostgresAuditAdapter from src.domain.enums import AuditAction
Inject via container¶
adapter = PostgresAuditAdapter(session)
Record audit events (follows ATTEMPT → OUTCOME pattern)¶
Step 1: Record attempt¶
await adapter.record( action=AuditAction.USER_LOGIN_ATTEMPTED, user_id=None, resource_type="session", ip_address="192.168.1.1", context={"email": "user@example.com"}, )
Step 2: Record outcome (success or failure)¶
await adapter.record( action=AuditAction.USER_LOGIN_SUCCESS, user_id=user_id, resource_type="session", resource_id=session_id, ip_address="192.168.1.1", context={"method": "password", "mfa": True}, )
Classes¶
PostgresAuditAdapter
¶
PostgreSQL implementation of AuditProtocol.
Provides immutable audit logging with PostgreSQL database RULES enforcing immutability at the database level.
This adapter is stateless - all state lives in the database. Sessions are managed by FastAPI dependency injection.
Attributes:
| Name | Type | Description |
|---|---|---|
session |
SQLAlchemy async session for database operations. |
Thread Safety
This adapter is NOT thread-safe (uses provided session). FastAPI creates new session per request (safe).
Source code in src/infrastructure/audit/postgres_adapter.py
69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 | |
Functions¶
__init__
¶
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
session
|
AsyncSession
|
SQLAlchemy async session (injected by container). Session lifecycle managed by FastAPI dependency injection. |
required |
Source code in src/infrastructure/audit/postgres_adapter.py
record
async
¶
record(
*,
action: AuditAction,
resource_type: str,
user_id: UUID | None = None,
resource_id: UUID | None = None,
ip_address: str | None = None,
user_agent: str | None = None,
context: dict[str, Any] | None = None
) -> Result[None, AuditError]
Record an immutable audit entry.
Creates new audit log entry in PostgreSQL. Entry cannot be modified or deleted after creation (enforced by database RULES).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
action
|
AuditAction
|
What happened (enum for type safety). |
required |
resource_type
|
str
|
What was affected (user, account, provider, etc.). |
required |
user_id
|
UUID | None
|
Who performed the action (None for system actions). |
None
|
resource_id
|
UUID | None
|
Specific resource identifier (optional). |
None
|
ip_address
|
str | None
|
Client IP address (required for auth events). |
None
|
user_agent
|
str | None
|
Client user agent string (browser/app info). |
None
|
context
|
dict[str, Any] | None
|
Additional event context (stored as JSONB). |
None
|
Returns:
| Type | Description |
|---|---|
Result[None, AuditError]
|
Result[None, AuditError]: - Success(None) if audit entry recorded - Failure(AuditError) if database operation failed |
Example
Record login attempt¶
result = await adapter.record( action=AuditAction.USER_LOGIN_ATTEMPTED, user_id=None, resource_type="session", ip_address="192.168.1.1", user_agent="Mozilla/5.0...", context={"email": "user@example.com"}, )
After authentication succeeds, record success¶
result = await adapter.record( action=AuditAction.USER_LOGIN_SUCCESS, user_id=user_id, resource_type="session", resource_id=session_id, ip_address="192.168.1.1", user_agent="Mozilla/5.0...", context={ "method": "password", "mfa": True, }, )
Handle result¶
match result: case Success(): logger.info("Audit logged", action=action.value) case Failure(error): logger.error("Audit failed", error=error.message)
Note
- Timestamp is set automatically by database (created_at)
- Context is stored as JSONB (flexible schema)
- Immutability enforced by PostgreSQL RULES
- Foreign key to users table (not enforced yet - users table doesn't exist)
Source code in src/infrastructure/audit/postgres_adapter.py
95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 | |
query
async
¶
query(
*,
user_id: UUID | None = None,
action: AuditAction | None = None,
resource_type: str | None = None,
start_date: datetime | None = None,
end_date: datetime | None = None,
limit: int = 100,
offset: int = 0
) -> Result[list[dict[str, Any]], AuditError]
Query audit trail (read-only, for compliance reports).
Retrieves audit entries matching the specified filters. Used for compliance reports, security investigations, forensics.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
user_id
|
UUID | None
|
Filter by user who performed actions (None = all users). |
None
|
action
|
AuditAction | None
|
Filter by specific action type (None = all actions). |
None
|
resource_type
|
str | None
|
Filter by resource type (None = all types). |
None
|
start_date
|
datetime | None
|
From date inclusive (None = no lower bound). |
None
|
end_date
|
datetime | None
|
To date inclusive (None = no upper bound). |
None
|
limit
|
int
|
Maximum results (default 100, capped at 1000). |
100
|
offset
|
int
|
Pagination offset (skip this many results). |
0
|
Returns:
| Type | Description |
|---|---|
Result[list[dict[str, Any]], AuditError]
|
Result[list[dict[str, Any]], AuditError]: - Success(entries) if query succeeded (list may be empty) - Failure(AuditError) if database operation failed |
Result[list[dict[str, Any]], AuditError]
|
Each entry dict contains: - id: str (UUID as string) - action: str (audit action type) - user_id: str | None (UUID as string) - resource_type: str - resource_id: str | None (UUID as string) - ip_address: str | None - user_agent: str | None - context: dict (JSONB context) - created_at: str (ISO 8601 format) |
Example
User activity report (last 30 days)¶
result = await adapter.query( user_id=user_id, start_date=datetime.now() - timedelta(days=30), limit=100, )
match result: case Success(entries): for entry in entries: print(f"{entry['action']} at {entry['created_at']}") case Failure(error): logger.error("Query failed", error=error.message)
Note
- Read-only operation (safe to call repeatedly)
- Results ordered by created_at DESC (newest first)
- Limit capped at 1000 to prevent DoS
- UUIDs converted to strings for JSON serialization
- Dates converted to ISO 8601 strings
Source code in src/infrastructure/audit/postgres_adapter.py
210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 | |