""" YAZ Care Platform — Correlation ID Middleware ====================================================== Injects a unique correlation_id into every request so that all log entries, error responses, and audit events can be traced end-to-end across services. Behaviour --------- - If the incoming request already carries ``X-Correlation-ID`` (forwarded from a gateway or upstream caller), that value is reused. - Otherwise a new UUID4 is generated. - The ID is attached to: * ``request.state.correlation_id`` * ``contextvars.ContextVar`` (accessible anywhere in the stack) * The outgoing response header ``X-Correlation-ID`` Usage ----- from core.correlation import CorrelationIDMiddleware, get_correlation_id app.add_middleware(CorrelationIDMiddleware) # anywhere inside a request handler or service cid = get_correlation_id() """ from __future__ import annotations import uuid import logging import structlog from contextvars import ContextVar from typing import Optional from starlette.middleware.base import BaseHTTPMiddleware from starlette.requests import Request from starlette.responses import Response from starlette.types import ASGIApp logger = structlog.get_logger(__name__) # --------------------------------------------------------------------------- # Context variable — holds the current correlation ID for the running async # task. Default is an empty string so callers always get a string back. # --------------------------------------------------------------------------- _correlation_id_ctx: ContextVar[str] = ContextVar("correlation_id", default="") REQUEST_ID_HEADER = "X-Request-ID" CORRELATION_ID_HEADER = "X-Correlation-ID" def get_correlation_id() -> str: """ Return the correlation ID for the current async context. Returns an empty string outside of a request context (so callers never have to handle ``None``). """ return _correlation_id_ctx.get("") def set_correlation_id(value: str) -> None: """Explicitly set the correlation ID for the current async context.""" _correlation_id_ctx.set(value) class CorrelationIDMiddleware(BaseHTTPMiddleware): """ ASGI middleware that guarantees every request has a traceable correlation ID attached to it before business logic runs. The middleware is deliberately lightweight (< 0.1 ms overhead) since it runs on every single request. """ HEADER_INCOMING = CORRELATION_ID_HEADER # client may pass this HEADER_OUTGOING = CORRELATION_ID_HEADER # always echoed on response def __init__(self, app: ASGIApp, header: str = CORRELATION_ID_HEADER) -> None: super().__init__(app) self.header = header async def dispatch(self, request: Request, call_next) -> Response: # 1. Resolve / generate correlation ID cid = ( request.headers.get(self.header) or request.headers.get(REQUEST_ID_HEADER) or str(uuid.uuid4()) ) # Sanitise — accept only safe characters (UUID format + dashes) cid = _sanitise(cid) # 2. Bind to context var so the whole async stack can access it token = _correlation_id_ctx.set(cid) # 3. Attach to request.state so route handlers can read it directly request.state.correlation_id = cid # 4. Process request try: response: Response = await call_next(request) finally: # Always reset – prevent ID from leaking into the next request if # a thread/task is reused. _correlation_id_ctx.reset(token) # 5. Echo the ID on the response response.headers[self.HEADER_OUTGOING] = cid return response # --------------------------------------------------------------------------- # Logging filter — attaches the correlation ID to every log record emitted # within a request so it shows up in JSON logs without explicit passing. # --------------------------------------------------------------------------- class CorrelationIDLogFilter(logging.Filter): """Injects the current correlation ID into every log record.""" def filter(self, record: logging.LogRecord) -> bool: record.correlation_id = get_correlation_id() # type: ignore[attr-defined] return True def install_correlation_log_filter(logger_name: Optional[str] = None) -> None: """ Attach :class:`CorrelationIDLogFilter` to the named logger (or root). Call once at application startup. """ target = logging.getLogger(logger_name) # Avoid adding duplicate filters on hot-reload if not any(isinstance(f, CorrelationIDLogFilter) for f in target.filters): target.addFilter(CorrelationIDLogFilter()) # --------------------------------------------------------------------------- # Internal helpers # --------------------------------------------------------------------------- _SAFE_CHARS = frozenset( "abcdefghijklmnopqrstuvwxyz" "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "0123456789" "-_." ) def _sanitise(value: str) -> str: """ Strip any characters outside the safe set and truncate to 64 chars. This prevents header-injection or log-injection via a crafted ``X-Correlation-ID`` value from an untrusted caller. """ cleaned = "".join(c for c in value if c in _SAFE_CHARS) return cleaned[:64] or str(uuid.uuid4()) __all__ = [ "CorrelationIDMiddleware", "CorrelationIDLogFilter", "get_correlation_id", "set_correlation_id", "install_correlation_log_filter", "CORRELATION_ID_HEADER", "REQUEST_ID_HEADER", ]