Merge main into bugs-uploads

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

# Conflicts:
#	web/checkout.js
This commit is contained in:
Cauê Faleiros
2026-11-11 15:03:53 -03:00
23 changed files with 453 additions and 9 deletions

View File

@@ -63,6 +63,10 @@ def session(request: Request, response: Response):
'unit_cents': band['unit_cents']}
for band in products[mode]['bands']]}
for mode in catalog.MODES},
# Public by design: the browser initialises Sentry with these; empty is off.
'sentry_dsn_web': os.environ.get('SENTRY_DSN_WEB', '').strip(),
'sentry_environment': os.environ.get('SENTRY_ENVIRONMENT') or ENVIRONMENT,
'sentry_release': os.environ.get('IMAGE_TAG', ''),
# Public by design: Mercado Pago's card form needs it in the browser.
'payment_public_key': os.environ.get('MP_PUBLIC_KEY', '') if payment.name == 'mercadopago' else '',
# The delivery options the cart quotes, or none: pickup only.

View File

@@ -5,6 +5,7 @@ changes it in "Minha senha". The superadmin is the system's own account, set fro
administrators manage everyone else. Nobody can remove, disable or demote
themselves, so the last administrator cannot lock the team out by accident.
"""
import os
import re
from decimal import Decimal
from typing import Literal
@@ -18,7 +19,7 @@ from ..core import db
from ..core.auth import (CAPABILITIES, MACHINE_QUESTION, audit, can, may_move, may_reorder, password_hash,
password_matches, signed_in)
from ..core.models import StrictModel
from ..runtime import BACK, STATES, TRANSITIONS
from ..runtime import BACK, ENVIRONMENT, STATES, TRANSITIONS
router = APIRouter()
@@ -68,6 +69,10 @@ def me(request: Request):
moves = [[a, b] for a, nexts in TRANSITIONS.items() for b in nexts if may_move(role, a, b)]
moves += [[a, b] for a, b in BACK.items() if may_move(role, a, b, back=True)]
return {'email': account['email'], 'name': account['name'], 'role': role,
# Public by design: the Kanban browser initialises Sentry with these.
'sentry_dsn_web': os.environ.get('SENTRY_DSN_WEB', '').strip(),
'sentry_environment': os.environ.get('SENTRY_ENVIRONMENT') or ENVIRONMENT,
'sentry_release': os.environ.get('IMAGE_TAG', ''),
# The machine this session is on, and whether to ask (item 12).
'machine': account['machine'], 'machine_question': MACHINE_QUESTION.get(role),
'machine_answered': account['machine_answered'],

View File

@@ -10,11 +10,14 @@ from fastapi import FastAPI
from fastapi.responses import JSONResponse
from starlette.middleware.trustedhost import TrustedHostMiddleware
from . import observability
from .core import db
from .core.auth import audit, client_ip
from .runtime import ALLOWED_HOSTS, ALLOWED_ORIGINS, storage
from .api import artwork, customer, health, machine_log, operator, orders, payments, quotes, reviews, site_admin, site_videos, stamps, uploads, users
observability.init('api')
@asynccontextmanager
async def lifespan(app):

139
app/observability.py Normal file
View File

@@ -0,0 +1,139 @@
"""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

View File

@@ -6,7 +6,7 @@ import threading
import time
from http.server import BaseHTTPRequestHandler, HTTPServer
from psycopg.types.json import Jsonb
from . import mail, unpaid
from . import mail, observability, unpaid
from .adapters import FakeTiny, LocalS3Storage, require_runtime
from .core.secrets import load as load_secret_files
from .core.db import connect
@@ -162,6 +162,7 @@ class Health(BaseHTTPRequestHandler):
pass
if __name__ == '__main__':
observability.init('worker')
scan_thread = threading.Thread(target=scan_loop,args=(storage,),daemon=True)
scan_thread.start()
render_thread = threading.Thread(target=render_loop,args=(storage,),daemon=True)