Spaces:
Running on T4
Running on T4
File size: 8,232 Bytes
7a3215f | 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 169 170 171 172 173 | """Observe ASGI messages without changing response bytes or buffering video streams."""
import hashlib
import json
import math
import re
import time
import uuid
from collections import deque
from datetime import UTC, datetime
from urllib.parse import parse_qs
from app.modules.api_audit.service import write_record
REDACTED = "[REDACTED]"
SAFE_HEADERS = {"content-type", "content-length", "x-request-id", "retry-after"}
SENSITIVE = re.compile(
r"password|token|secret|credential|authorization|cookie|signature|receipt|privatekey|apikey", re.I)
URL = re.compile(r"https?://[^\s\"<>]+", re.I)
BEARER = re.compile(r"\bBearer\s+\S+", re.I)
KEY = re.compile(r"AIza[0-9A-Za-z_-]{20,}|lsv2_[a-z]{2}_[0-9A-Za-z_]{16,}")
def sanitize(value, depth=0):
if depth > 40:
return "[DEPTH LIMIT]"
if isinstance(value, dict):
return {str(k).replace("\x00", "[NUL]"): REDACTED if SENSITIVE.search(re.sub(r"[^a-z0-9]", "", str(k).lower()))
or str(k).lower() in {"email", "phone", "signedpayload", "data"} else sanitize(v, depth + 1)
for k, v in value.items()}
if isinstance(value, list):
return [sanitize(v, depth + 1) for v in value]
if isinstance(value, str):
# URLs may contain storage credentials or reset tokens, including in their path.
return KEY.sub(REDACTED, BEARER.sub(REDACTED, URL.sub("[URL REDACTED]", value.replace("\x00", "[NUL]"))))
if isinstance(value, float) and not math.isfinite(value):
return "[NONFINITE NUMBER]"
return value
class Capture:
def __init__(self, content_type, limit):
self.json = content_type.split(";", 1)[0].strip().lower().endswith(("/json", "+json"))
self.limit = limit
self.buffer = bytearray()
self.size = 0
self.complete = False
def feed(self, body, complete):
self.size += len(body)
if self.json and len(self.buffer) < self.limit:
self.buffer.extend(body[:self.limit - len(self.buffer)])
self.complete = complete
def result(self):
status = ("incomplete" if not self.complete else "empty" if not self.size else
"non_json" if not self.json else "truncated" if self.size > self.limit else "captured")
body = None
if status == "captured":
try:
body = sanitize(json.loads(self.buffer, parse_constant=lambda _: (_ for _ in ()).throw(ValueError())))
except (ValueError, UnicodeError, RecursionError):
status = "invalid_json"
return {"capture_status": status, "observed_bytes": self.size, "body": body}
def headers(raw):
selected = {k.decode("latin1").lower(): sanitize(v.decode("latin1"))
for k, v in raw if k.decode("latin1").lower() in SAFE_HEADERS}
for key, value in raw:
if key.lower() == b"idempotency-key":
selected["idempotency-key-sha256"] = hashlib.sha256(value).hexdigest()
return selected
def as_uuid(value):
try:
return uuid.UUID(str(value))
except (ValueError, TypeError, AttributeError):
return None
class ApiAuditMiddleware:
def __init__(self, app, *, max_body_bytes=1048576, service_version="unknown", writer=write_record):
self.app = app
self.limit = max_body_bytes
self.version = service_version
self.writer = writer
async def __call__(self, scope, receive, send):
if scope["type"] != "http":
return await self.app(scope, receive, send)
started_at, started = datetime.now(UTC), time.monotonic()
incoming = headers(scope.get("headers", []))
request = Capture(incoming.get("content-type", ""), self.limit)
response = Capture("", self.limit)
outgoing, status, exception = {}, 500, None
replay = deque()
state = scope.setdefault("state", {})
# A server-generated ID is available even if routing fails before the app middleware.
state.setdefault("request_id", uuid.uuid4().hex)
async def observed_receive():
if replay:
return replay.popleft()
message = await receive()
if message["type"] == "http.request":
request.feed(message.get("body", b""), not message.get("more_body", False))
return message
async def observed_send(message):
nonlocal outgoing, status, response
if message["type"] == "http.response.start":
status = message["status"]
outgoing = headers(message.get("headers", []))
response = Capture("" if state.get("audit_omit_response") else outgoing.get("content-type", ""),
self.limit)
elif message["type"] == "http.response.body":
response.feed(message.get("body", b""), not message.get("more_body", False))
await send(message)
try:
# Small JSON bodies are captured even for early 401/404 responses. Replay unchanged.
if request.json:
while not request.complete and request.size <= self.limit:
message = await receive()
replay.append(message)
if message["type"] != "http.request":
break
request.feed(message.get("body", b""), not message.get("more_body", False))
await self.app(scope, observed_receive, observed_send)
except BaseException as exc:
exception = type(exc).__name__
raise
finally:
request_body, response_body = request.result(), response.result()
if state.get("audit_omit_response"):
response_body["capture_status"] = "omitted_audit_read"
body = request_body.get("body")
body = body if isinstance(body, dict) else {}
result = response_body.get("body")
result = result if isinstance(result, dict) else {}
params = scope.get("path_params", {})
route = getattr(scope.get("route"), "path", None)
# Device removal puts the push credential in the URL. Store the template instead.
path = scope.get("path", "")
if any(SENSITIVE.search(k) for k in params) or path.startswith("/v1/devices/"):
path = route or "/v1/devices/[REDACTED]"
error = result.get("error")
session = result.get("session")
session = session if isinstance(session, dict) else {}
report = session.get("report") or result.get("report")
report = report if isinstance(report, dict) else {}
analysis_id = body.get("analysis_id") or result.get("analysis_id") or report.get("analysis_id")
revision = body.get("analysis_revision", result.get("analysis_revision", report.get("analysis_revision")))
await self.writer({
"request_id": str(state.get("request_id"))[:128], "started_at": started_at,
"method": scope["method"][:16], "path": sanitize(path)[:2048], "route": route,
"status_code": status, "duration_ms": round((time.monotonic() - started) * 1000, 3),
"account_id": as_uuid(state.get("audit_account_id")),
"session_id": as_uuid(params.get("session_id") or body.get("session_id") or session.get("id")),
"analysis_id": analysis_id[:256] if isinstance(analysis_id, str) else None,
"analysis_revision": revision if type(revision) is int and 0 <= revision < 2147483648 else None,
"request_headers": incoming,
"query_params": sanitize(parse_qs(
scope.get("query_string", b"").decode("utf-8", errors="replace"))),
"request_payload": request_body, "response_headers": outgoing, "response_payload": response_body,
"error_code": str(error.get("code"))[:128] if isinstance(error, dict) else None,
"exception_type": exception or state.get("audit_exception_type"),
"response_complete": response.complete,
"service_version": self.version[:128],
})
|