add audiolog

This commit is contained in:
2025-03-27 20:50:51 -03:00
parent 5af61465f3
commit 5756451738
10 changed files with 54 additions and 60 deletions

View File

@@ -1,3 +1,5 @@
import json
from aws_lambda_powertools.event_handler.api_gateway import (
APIGatewayHttpResolver,
Response,
@@ -6,10 +8,13 @@ from aws_lambda_powertools.event_handler.middlewares import (
BaseMiddlewareHandler,
NextMiddleware,
)
from aws_lambda_powertools.shared.json_encoder import Encoder
from layercake.dateutils import now, ttl
from layercake.dynamodb import ComposeKey, DynamoDBCollection, KeyPair
from pydantic import UUID4, BaseModel, Field
LOG_RETENTION_DAYS = 365 * 2 # 2 years
class AuthorizerMiddleware(BaseMiddlewareHandler):
def handler(
@@ -37,32 +42,52 @@ class AuthenticatedUser(BaseModel):
class AuditLogMiddleware(BaseMiddlewareHandler):
def __init__(self, action: str, /, collect: DynamoDBCollection) -> None:
"""This middleware logs audit details for successful requests, storing user,
action, and IP info with a specified retention period.."""
def __init__(
self,
action: str,
/,
collect: DynamoDBCollection,
retention_days: int | None = LOG_RETENTION_DAYS,
) -> None:
self.action = action
self.collect = collect
self.retention_days = retention_days
def handler(
self,
app: APIGatewayHttpResolver,
next_middleware: NextMiddleware,
) -> Response:
collect = self.collect
response = next_middleware(app)
auth_user = app.context.get('authenticated_user')
user = app.context.get('authenticated_user')
request_ctx = app.current_event.request_context
ip_addr = request_ctx.http.source_ip
# Successful request
if 200 <= response.status_code < 300 and auth_user:
if 200 <= response.status_code < 300 and user:
now_ = now()
data = (
json.dumps(response.body, cls=Encoder) if response.is_json() else None
)
retention_days = (
ttl(start_dt=now_, days=self.retention_days)
if self.retention_days
else None
)
self.collect.put_item(
collect.put_item(
key=KeyPair(
pk=ComposeKey(auth_user.id, prefix='logs'),
pk=ComposeKey(user.id, prefix='logs'),
sk=now_.isoformat(),
),
action=self.action,
data=data,
ip=ip_addr,
ttl=ttl(start_dt=now_, days=365 * 2),
ttl=retention_days,
)
return response