This commit is contained in:
2025-05-16 14:29:14 -03:00
parent 17131380ac
commit cc9bd08daa
49 changed files with 177 additions and 54 deletions

View File

@@ -0,0 +1,11 @@
from .audit_log_middleware import AuditLogMiddleware
from .authentication_middleware import AuthenticationMiddleware, User
from .tenant_middelware import Tenant, TenantMiddleware
__all__ = [
'AuthenticationMiddleware',
'AuditLogMiddleware',
'TenantMiddleware',
'User',
'Tenant',
]

View File

@@ -0,0 +1,97 @@
from aws_lambda_powertools.event_handler.api_gateway import (
APIGatewayHttpResolver,
Response,
)
from aws_lambda_powertools.event_handler.middlewares import (
BaseMiddlewareHandler,
NextMiddleware,
)
from aws_lambda_powertools.shared.functions import (
extract_event_from_common_models,
)
from layercake.dateutils import now, ttl
from layercake.dynamodb import (
ComposeKey,
DynamoDBCollection,
KeyPair,
)
from layercake.funcs import pick
from .authentication_middleware import User
YEAR_DAYS = 365
LOG_RETENTION_DAYS = YEAR_DAYS * 2
class AuditLogMiddleware(BaseMiddlewareHandler):
"""This middleware logs audit details for successful requests, storing user,
action, and IP info with a specified retention period.
Parameters
----------
action: str
The identifier for the audit log action.
collect: DynamoDBCollection
The collection instance used to persist the audit log data.
audit_attrs: tuple of str, optional
A tuple of attribute names to extract from the response body for logging.
These represent the specific fields to include in the audit log.
retention_days: int or None, optional
The number of days the log is retained on the server.
If None, no time-to-live (TTL) will be applied.
"""
def __init__(
self,
action: str,
/,
collect: DynamoDBCollection,
audit_attrs: tuple[str, ...] = (),
retention_days: int | None = LOG_RETENTION_DAYS,
) -> None:
self.action = action
self.collect = collect
self.audit_attrs = audit_attrs
self.retention_days = retention_days
def handler(
self,
app: APIGatewayHttpResolver,
next_middleware: NextMiddleware,
) -> Response:
user: User | None = app.context.get('user')
req_context = app.current_event.request_context
ip_addr = req_context.http.source_ip
response = next_middleware(app)
# Successful response
# https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Status#successful_responses
if 200 <= response.status_code < 300 and user:
now_ = now()
author = pick(('id', 'name'), dict(user))
data = (
pick(self.audit_attrs, extract_event_from_common_models(response.body))
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(
key=KeyPair(
# Post-migration: remove `delimiter` and update prefix from `log` to `logs`
# in ComposeKey.
pk=ComposeKey(user.id, prefix='log', delimiter=':'),
sk=now_.isoformat(),
),
action=self.action,
data=data,
ip=ip_addr,
author=author,
ttl=retention_days,
)
return response

View File

@@ -0,0 +1,49 @@
from auth import AuthFlowType
from aws_lambda_powertools.event_handler.api_gateway import (
APIGatewayHttpResolver,
Response,
)
from aws_lambda_powertools.event_handler.middlewares import (
BaseMiddlewareHandler,
NextMiddleware,
)
from pydantic import UUID4, BaseModel, EmailStr, Field
class User(BaseModel):
id: str
name: str
email: EmailStr
class CognitoUser(User):
id: str = Field(alias='custom:user_id')
email_verified: bool
sub: UUID4
class AuthenticationMiddleware(BaseMiddlewareHandler):
"""This middleware extracts user authentication details from the Lambda authorizer context
and makes them available in the application context."""
def handler(
self,
app: APIGatewayHttpResolver,
next_middleware: NextMiddleware,
) -> Response:
# Gets the Lambda authorizer associated with the current API Gateway event.
# You can check the file `auth.py` for more details.
context = app.current_event.request_context.authorizer.get_lambda
auth_flow_type = context.get('auth_flow_type')
if not auth_flow_type:
return next_middleware(app)
cls = {
AuthFlowType.USER_AUTH: CognitoUser,
AuthFlowType.API_AUTH: User,
}.get(auth_flow_type)
if cls:
app.append_context(user=cls(**context['user']))
return next_middleware(app)

View File

@@ -0,0 +1,123 @@
from http import HTTPStatus
from auth import AuthFlowType
from aws_lambda_powertools.event_handler.api_gateway import (
APIGatewayHttpResolver,
Response,
)
from aws_lambda_powertools.event_handler.exceptions import (
BadRequestError,
NotFoundError,
ServiceError,
)
from aws_lambda_powertools.event_handler.middlewares import (
BaseMiddlewareHandler,
NextMiddleware,
)
from layercake.dynamodb import ComposeKey, DynamoDBCollection, KeyPair
from pydantic import UUID4, BaseModel
from .authentication_middleware import User
class Tenant(BaseModel):
id: UUID4 | str
name: str
class TenantMiddleware(BaseMiddlewareHandler):
"""Middleware that associates a Tenant instance with the request context based on the authentication flow.
For API authentication (`AuthFlowType.API_AUTH`), it assigns tenant information directly from the authorizer context.
For user authentication (`AuthFlowType.USER_AUTH`), it gets the Tenant ID from the specified request header.
Parameters
----------
collect : DynamoDBCollection
The DynamoDB collection used to validate user access and retrieve tenant information.
header : str, optional
The request header name containing the tenant ID. Defaults to `'X-Tenant'`.
"""
def __init__(
self,
collect: DynamoDBCollection,
/,
header: str = 'X-Tenant',
) -> None:
self.collect = collect
self.header = header
def handler(
self,
app: APIGatewayHttpResolver,
next_middleware: NextMiddleware,
) -> Response:
context = app.current_event.request_context.authorizer.get_lambda
auth_flow_type = context.get('auth_flow_type')
if auth_flow_type == AuthFlowType.API_AUTH:
app.append_context(tenant=Tenant(**context['tenant']))
if auth_flow_type == AuthFlowType.USER_AUTH:
app.append_context(
tenant=_tenant(
app.current_event.headers.get(self.header),
app.context.get('user'), # type: ignore
collect=self.collect,
)
)
return next_middleware(app)
class ForbiddenError(ServiceError):
def __init__(self, *args, **kwargs):
super().__init__(HTTPStatus.FORBIDDEN, 'Deny')
def _tenant(
tenant_id: str | None,
user: User,
/,
collect: DynamoDBCollection,
) -> Tenant:
"""Get a Tenant instance based on the provided tenant_id and user's access permissions.
Parameters
----------
tenant_id : str | None
The identifier of the tenant. Must not be None or empty.
user : User
The user attempting to access the tenant.
collect : DynamoDBCollection
The DynamoDB collection used to retrieve tenant information.
Returns
-------
Tenant
The Tenant instance corresponding to the provided tenant_id.
Raises
------
BadRequestError
If tenant_id is not provided.
ForbiddenError
If the user lacks the necessary ACL permissions for the specified tenant_id.
NotFoundError
If tenant not found.
"""
if not tenant_id:
raise BadRequestError('Missing tenant')
# Ensure user has ACL
collect.get_item(
KeyPair(user.id, ComposeKey(tenant_id, prefix='acls')),
exception_cls=ForbiddenError,
)
# For root tenant, provide the default Tenant
if tenant_id == '*':
return Tenant(id=tenant_id, name='default')
obj = collect.get_item(KeyPair(tenant_id, '0'), exception_cls=NotFoundError)
return Tenant.parse_obj(obj)