Files
dtf-system/app/observability.py
Cauê Faleiros 457ed4cbdf feat: Sentry in the API, the worker, the Site and the Kanban (off until the DSNs are set)
app/observability.py starts sentry-sdk for the API and the worker when
SENTRY_DSN_API is set, with send_default_pii off and a scrub that strips
cookies, tokens, bodies, CPF/CNPJ and e-mails. The browser loads the
official Sentry bundle from our own origin (web/vendor, provenance in its
README) and starts with SENTRY_DSN_WEB from /api/session or
/api/operator/me; every failed API answer the customer or the team gets is
reported with its path, status and message, never the request body. The
CSP allows Blyzer's Sentry ingest host.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-11 14:48:01 -03:00

140 lines
4.9 KiB
Python

"""Sentry for the API and the worker, off until a DSN arrives (note Sentry).
`init(component)` reads `SENTRY_DSN_API` and returns without importing the SDK
when it is empty, so local and CI runs carry no Sentry dependency or network
cost. When it is set, `scrub` keeps cookies, credentials, request bodies and
Brazilian personal data out of the events (LGPD).
"""
import os
import re
from urllib.parse import parse_qsl, urlencode, urlsplit, urlunsplit
EMAIL = re.compile(r'[^\s@]+@[^\s@]+\.[A-Za-z]{2,}')
# CPF (11 digits) or CNPJ (14), with or without punctuation.
DOCUMENT = re.compile(r'(?<!\d)(?:\d{2}\.?\d{3}\.?\d{3}/?\d{4}-?\d{2}'
r'|\d{3}\.?\d{3}\.?\d{3}-?\d{2})(?!\d)')
SENSITIVE_PARAM = re.compile(r'token|signature|x-amz', re.I)
SENSITIVE_HEADER = re.compile(r'^(cookie|authorization|x-.*token.*)$', re.I)
REDACTED = '[removido]'
def _clean(text):
"""Replace e-mail addresses and CPF/CNPJ in one string."""
if not isinstance(text, str):
return text
return DOCUMENT.sub(REDACTED, EMAIL.sub(REDACTED, text))
def _scrub_query(query):
"""A query string without token, signature and X-Amz parameters."""
if not isinstance(query, str) or not query:
return query
pairs = parse_qsl(query, keep_blank_values=True)
kept = [(key, value) for key, value in pairs if not SENSITIVE_PARAM.search(key)]
return query if len(kept) == len(pairs) else urlencode(kept, doseq=True)
def _scrub_url(url):
if not isinstance(url, str):
return url
parts = urlsplit(url)
if not parts.query:
return url
return urlunsplit(parts._replace(query=_scrub_query(parts.query)))
def _scrub_text(value):
"""Personal data and a URL query string inside a message or crumb."""
value = _clean(value)
if not isinstance(value, str) or '?' not in value:
return value
head, _, query = value.partition('?')
return head + '?' + _scrub_query(query)
def _scrub_value(value):
if isinstance(value, str):
return _scrub_text(value)
if isinstance(value, list):
return [_scrub_value(item) for item in value]
if isinstance(value, dict):
return {key: _scrub_value(item) for key, item in value.items()}
return value
def _scrub_request(request):
"""Cookies, credentials, query tokens and bodies never leave the server."""
if not isinstance(request, dict):
return
request.pop('cookies', None)
request.pop('data', None)
request.pop('body', None)
headers = request.get('headers')
if isinstance(headers, dict):
request['headers'] = {key: value for key, value in headers.items()
if not SENSITIVE_HEADER.match(str(key))}
if 'query_string' in request:
request['query_string'] = _scrub_query(request['query_string'])
if 'url' in request:
request['url'] = _scrub_url(request['url'])
def scrub(event, hint=None):
"""before_send: strip credentials, bodies and personal data from an event."""
if not isinstance(event, dict):
return event
_scrub_request(event.get('request'))
if 'message' in event:
event['message'] = _scrub_text(event['message'])
logentry = event.get('logentry')
if isinstance(logentry, dict) and 'message' in logentry:
logentry['message'] = _scrub_text(logentry['message'])
exception = event.get('exception')
if isinstance(exception, dict):
for value in exception.get('values') or []:
if isinstance(value, dict) and 'value' in value:
value['value'] = _scrub_text(value['value'])
breadcrumbs = event.get('breadcrumbs')
if isinstance(breadcrumbs, dict):
breadcrumbs = breadcrumbs.get('values') or []
if isinstance(breadcrumbs, list):
for crumb in breadcrumbs:
if not isinstance(crumb, dict):
continue
if 'message' in crumb:
crumb['message'] = _scrub_text(crumb['message'])
if 'data' in crumb:
crumb['data'] = _scrub_value(crumb['data'])
if 'extra' in event:
event['extra'] = _scrub_value(event['extra'])
return event
def _traces_rate():
try:
return float(os.environ.get('SENTRY_TRACES', '0') or 0)
except (TypeError, ValueError):
return 0.0
def init(component):
"""Start Sentry for this process; False (and no imports) without a DSN."""
dsn = os.environ.get('SENTRY_DSN_API', '').strip()
if not dsn:
return False
import sentry_sdk
environment = os.environ.get('SENTRY_ENVIRONMENT')
if not environment:
from .runtime import ENVIRONMENT
environment = ENVIRONMENT
sentry_sdk.init(
dsn=dsn,
environment=environment,
release=os.environ.get('IMAGE_TAG') or None,
send_default_pii=False,
traces_sample_rate=_traces_rate(),
before_send=scrub,
)
sentry_sdk.set_tag('component', component)
return True