Spaces:
Paused

File size: 5,598 Bytes
383d839
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
579285c
383d839
 
 
 
 
 
 
 
579285c
383d839
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16a78e2
383d839
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16a78e2
383d839
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
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
"""
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",
]