Merge Sentry: API, worker, Site and Kanban (off until the DSNs are set)
All checks were successful
Build and deploy / Validate source (push) Successful in 6s
Build and deploy / Integration suite on a real stack (push) Successful in 6m3s
Build and deploy / Secret scan and release gate (push) Successful in 5s
Build and deploy / Publish images (push) Successful in 1m30s
All checks were successful
Build and deploy / Validate source (push) Successful in 6s
Build and deploy / Integration suite on a real stack (push) Successful in 6m3s
Build and deploy / Secret scan and release gate (push) Successful in 5s
Build and deploy / Publish images (push) Successful in 1m30s
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -29,6 +29,7 @@ jobs:
|
||||
tests.test_hotfolder \
|
||||
tests.test_migrate \
|
||||
tests.test_label \
|
||||
tests.test_observability \
|
||||
tests.test_secrets -v
|
||||
sh -n infra/lock_dependencies.sh
|
||||
|
||||
@@ -99,7 +100,7 @@ jobs:
|
||||
# the generator's geometry. The provider suites use a fake transport: they
|
||||
# prove the documented contract, not the integration.
|
||||
- name: Print-file geometry and provider adapters
|
||||
run: $COMPOSE exec -T api python -m unittest tests.test_printfile tests.test_printpng tests.test_mercadopago tests.test_tiny tests.test_cnpj tests.test_payment_messages tests.test_jadlog tests.test_correios tests.test_quote_review tests.test_moves tests.test_large_files tests.test_grade_check tests.test_schema tests.test_customer_document tests.test_mail_html tests.test_layout_rules tests.test_proof_cut tests.test_proof_render tests.test_prumo tests.test_speed tests.test_printpng_validate tests.test_machine_log tests.test_machine_stats tests.test_label tests.test_worker_drain -v
|
||||
run: $COMPOSE exec -T api python -m unittest tests.test_printfile tests.test_printpng tests.test_mercadopago tests.test_tiny tests.test_cnpj tests.test_payment_messages tests.test_jadlog tests.test_correios tests.test_quote_review tests.test_moves tests.test_large_files tests.test_grade_check tests.test_schema tests.test_customer_document tests.test_mail_html tests.test_layout_rules tests.test_proof_cut tests.test_proof_render tests.test_prumo tests.test_speed tests.test_printpng_validate tests.test_machine_log tests.test_machine_stats tests.test_label tests.test_observability tests.test_worker_drain -v
|
||||
|
||||
- name: Runtime and retention regressions
|
||||
run: |
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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'],
|
||||
|
||||
@@ -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
139
app/observability.py
Normal 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
|
||||
@@ -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)
|
||||
|
||||
@@ -27,6 +27,10 @@ x-app: &app
|
||||
ALLOWED_HOSTS: ${ALLOWED_HOSTS:-localhost,127.0.0.1}
|
||||
ALLOWED_ORIGINS: ${ALLOWED_ORIGINS:-http://localhost:${SITE_PORT:-8080},http://localhost:${KANBAN_PORT:-8081},http://127.0.0.1:${SITE_PORT:-8080},http://127.0.0.1:${KANBAN_PORT:-8081}}
|
||||
COOKIE_SECURE: "false"
|
||||
# Sentry stays off locally unless real DSNs are set in .env.
|
||||
SENTRY_DSN_API: ${SENTRY_DSN_API:-}
|
||||
SENTRY_DSN_WEB: ${SENTRY_DSN_WEB:-}
|
||||
SENTRY_ENVIRONMENT: ${SENTRY_ENVIRONMENT:-}
|
||||
# Sandbox testing only: set PAYMENT_ADAPTER=mercadopago with the MP_* test
|
||||
# credentials, or TINY_ADAPTER=tiny with a TINY_TOKEN, in .env. Never real
|
||||
# production credentials on a developer machine.
|
||||
@@ -274,6 +278,7 @@ services:
|
||||
# Empty unless testing Mercado Pago's card form; see docs/LOCAL_SETUP.md.
|
||||
PAYMENT_CSP_SOURCES: ${PAYMENT_CSP_SOURCES:-}
|
||||
PAYMENT_CHALLENGE_SOURCES: ${PAYMENT_CHALLENGE_SOURCES:-}
|
||||
SENTRY_CSP_SOURCES: ""
|
||||
ports:
|
||||
# Published ports are host-wide even bound to loopback, so on a shared
|
||||
# machine any of them can collide with something unrelated. CI overrides
|
||||
@@ -299,6 +304,7 @@ services:
|
||||
S3_PUBLIC_ENDPOINT: ${S3_PUBLIC_ENDPOINT:-http://localhost:${STORAGE_PORT:-9000}}
|
||||
PAYMENT_CSP_SOURCES: ""
|
||||
PAYMENT_CHALLENGE_SOURCES: ""
|
||||
SENTRY_CSP_SOURCES: ""
|
||||
ports: ["127.0.0.1:${KANBAN_PORT:-8081}:80"]
|
||||
networks: [local, edge]
|
||||
depends_on:
|
||||
|
||||
@@ -27,7 +27,7 @@ server {
|
||||
add_header Referrer-Policy no-referrer always;
|
||||
add_header X-Frame-Options DENY always;
|
||||
add_header Permissions-Policy "camera=(self), microphone=(), geolocation=()" always;
|
||||
add_header Content-Security-Policy "default-src 'self'; script-src 'self' @SCRIPT_HASHES@ ${PAYMENT_CSP_SOURCES}; script-src-attr 'none'; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; font-src 'self' https://fonts.gstatic.com; img-src 'self' data: blob: https://cdn.vnda.com.br ${S3_PUBLIC_ENDPOINT} ${PAYMENT_CSP_SOURCES}; media-src 'self' ${S3_PUBLIC_ENDPOINT}; connect-src 'self' ${S3_PUBLIC_ENDPOINT} https://cdn.vnda.com.br ${PAYMENT_CSP_SOURCES}; frame-src 'self' ${PAYMENT_CSP_SOURCES} ${PAYMENT_CHALLENGE_SOURCES}; worker-src 'self' blob:; object-src 'none'; base-uri 'none'; frame-ancestors 'none'; form-action 'self' ${PAYMENT_CHALLENGE_SOURCES}" always;
|
||||
add_header Content-Security-Policy "default-src 'self'; script-src 'self' @SCRIPT_HASHES@ ${PAYMENT_CSP_SOURCES}; script-src-attr 'none'; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; font-src 'self' https://fonts.gstatic.com; img-src 'self' data: blob: https://cdn.vnda.com.br ${S3_PUBLIC_ENDPOINT} ${PAYMENT_CSP_SOURCES}; media-src 'self' ${S3_PUBLIC_ENDPOINT}; connect-src 'self' ${S3_PUBLIC_ENDPOINT} https://cdn.vnda.com.br ${PAYMENT_CSP_SOURCES} ${SENTRY_CSP_SOURCES}; frame-src 'self' ${PAYMENT_CSP_SOURCES} ${PAYMENT_CHALLENGE_SOURCES}; worker-src 'self' blob:; object-src 'none'; base-uri 'none'; frame-ancestors 'none'; form-action 'self' ${PAYMENT_CHALLENGE_SOURCES}" always;
|
||||
|
||||
location = /health { access_log off; return 200 'ok'; }
|
||||
location /api/ {
|
||||
|
||||
@@ -76,6 +76,11 @@ BACKUP_SECRET_ACCESS_KEY=TBD
|
||||
BACKUP_AGE_RECIPIENT=age1...
|
||||
BACKUP_HOUR=3
|
||||
|
||||
# Sentry: empty DSNs keep it off; the environment defaults to production.
|
||||
SENTRY_DSN_API=
|
||||
SENTRY_DSN_WEB=
|
||||
SENTRY_ENVIRONMENT=
|
||||
|
||||
# Names of external Portainer/Docker Swarm secrets, never their values.
|
||||
DATABASE_URL_SECRET=TBD
|
||||
DATABASE_ADMIN_URL_SECRET=TBD
|
||||
|
||||
@@ -12,6 +12,10 @@ x-app-environment: &app-environment
|
||||
# connection per `with` block, exactly as before (the production default).
|
||||
DB_POOL: ${DB_POOL:-off}
|
||||
DB_POOL_SIZE: ${DB_POOL_SIZE:-20}
|
||||
# Sentry: empty DSNs leave it off; the environment defaults to production.
|
||||
SENTRY_DSN_API: ${SENTRY_DSN_API:-}
|
||||
SENTRY_DSN_WEB: ${SENTRY_DSN_WEB:-}
|
||||
SENTRY_ENVIRONMENT: ${SENTRY_ENVIRONMENT:-production}
|
||||
S3_ENDPOINT: ${R2_ENDPOINT:?set R2_ENDPOINT}
|
||||
S3_PUBLIC_ENDPOINT: ${R2_ENDPOINT:?set R2_ENDPOINT}
|
||||
S3_BUCKET: ${R2_BUCKET:?set R2_BUCKET}
|
||||
@@ -301,6 +305,8 @@ services:
|
||||
# Mercado Pago's card form loads from these origins; empty keeps the
|
||||
# Site at script-src 'self'. Set together with the Mercado Pago adapter.
|
||||
PAYMENT_CSP_SOURCES: ${PAYMENT_CSP_SOURCES:-}
|
||||
# The Sentry ingest origin(s) for connect-src; empty until the DSN exists.
|
||||
SENTRY_CSP_SOURCES: ${SENTRY_CSP_SOURCES:-https://o4510863040905216.ingest.us.sentry.io}
|
||||
# The bank's confirmation page for debit and other 3-D Secure cards is
|
||||
# on the issuer's own domain, so it cannot be listed: "https:" lets
|
||||
# frames and form posts reach it (never scripts). Empty turns it off.
|
||||
@@ -329,6 +335,8 @@ services:
|
||||
S3_PUBLIC_ENDPOINT: ${R2_ENDPOINT:?set R2_ENDPOINT}
|
||||
PAYMENT_CSP_SOURCES: ""
|
||||
PAYMENT_CHALLENGE_SOURCES: ""
|
||||
# The Kanban reports to Sentry too; set from the browser DSN host.
|
||||
SENTRY_CSP_SOURCES: ${SENTRY_CSP_SOURCES:-https://o4510863040905216.ingest.us.sentry.io}
|
||||
networks: [backend]
|
||||
ports:
|
||||
- target: 8080
|
||||
|
||||
@@ -243,6 +243,19 @@ behaviour). Set it to `on` in the stack's environment and redeploy to keep
|
||||
between 1 and `DB_POOL_SIZE` connections per process (`DB_POOL_SIZE` defaults
|
||||
to 20); set it back to `off` to return to one connection per block.
|
||||
|
||||
## 11. Sentry
|
||||
|
||||
Sentry is built into the API, the worker, the Site and the Kanban, and stays
|
||||
off while the DSNs are empty. Set `SENTRY_DSN_API` and `SENTRY_DSN_WEB` in the
|
||||
stack's environment, and optionally `SENTRY_ENVIRONMENT` (defaults to
|
||||
`production`). The API and worker initialise from `SENTRY_DSN_API`; the browser
|
||||
reads `SENTRY_DSN_WEB` from `/api/session` on the Site and from
|
||||
`/api/operator/me` on the Kanban. When the DSNs exist, also set
|
||||
`SENTRY_CSP_SOURCES` to the Sentry ingest origin, such as
|
||||
`https://o123.ingest.sentry.io` (or `https://*.ingest.sentry.io`), so the CSP
|
||||
`connect-src` allows the browser to send events. No image change is needed to
|
||||
switch it on: update the stack variables and redeploy.
|
||||
|
||||
## Current blocker
|
||||
|
||||
This is the final deployment shape, but it is not authorized for production
|
||||
|
||||
@@ -9,7 +9,7 @@ server {
|
||||
add_header Referrer-Policy no-referrer always;
|
||||
add_header X-Frame-Options DENY always;
|
||||
add_header Permissions-Policy "camera=(self), microphone=(), geolocation=()" always;
|
||||
add_header Content-Security-Policy "default-src 'self'; script-src 'self' @SCRIPT_HASHES@ ${PAYMENT_CSP_SOURCES}; script-src-attr 'none'; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; font-src 'self' https://fonts.gstatic.com; img-src 'self' data: blob: https://cdn.vnda.com.br ${S3_PUBLIC_ENDPOINT} ${PAYMENT_CSP_SOURCES}; media-src 'self' ${S3_PUBLIC_ENDPOINT}; connect-src 'self' ${S3_PUBLIC_ENDPOINT} https://cdn.vnda.com.br ${PAYMENT_CSP_SOURCES}; frame-src 'self' ${PAYMENT_CSP_SOURCES} ${PAYMENT_CHALLENGE_SOURCES}; worker-src 'self' blob:; object-src 'none'; base-uri 'none'; frame-ancestors 'none'; form-action 'self' ${PAYMENT_CHALLENGE_SOURCES}" always;
|
||||
add_header Content-Security-Policy "default-src 'self'; script-src 'self' @SCRIPT_HASHES@ ${PAYMENT_CSP_SOURCES}; script-src-attr 'none'; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; font-src 'self' https://fonts.gstatic.com; img-src 'self' data: blob: https://cdn.vnda.com.br ${S3_PUBLIC_ENDPOINT} ${PAYMENT_CSP_SOURCES}; media-src 'self' ${S3_PUBLIC_ENDPOINT}; connect-src 'self' ${S3_PUBLIC_ENDPOINT} https://cdn.vnda.com.br ${PAYMENT_CSP_SOURCES} ${SENTRY_CSP_SOURCES}; frame-src 'self' ${PAYMENT_CSP_SOURCES} ${PAYMENT_CHALLENGE_SOURCES}; worker-src 'self' blob:; object-src 'none'; base-uri 'none'; frame-ancestors 'none'; form-action 'self' ${PAYMENT_CHALLENGE_SOURCES}" always;
|
||||
location = /health { access_log off; return 200 'ok'; }
|
||||
location /api/ {
|
||||
limit_req zone=api_limit burst=100 nodelay;
|
||||
|
||||
@@ -34,6 +34,7 @@ certifi==2026.10.19 \
|
||||
# via
|
||||
# httpcore
|
||||
# httpx
|
||||
# sentry-sdk
|
||||
click==8.5.0 \
|
||||
--hash=sha256:255bc9599cf7748b4b1a446ccc735421bd08a2ae529a8b88597d3de5664ee360 \
|
||||
--hash=sha256:ba0d2089de75ea0310e2dde03160e6ca10009947fb95a182f9b54021bb272e34
|
||||
@@ -620,6 +621,10 @@ segno==1.6.6 \
|
||||
--hash=sha256:28c7d081ed0cf935e0411293a465efd4d500704072cdb039778a2ab8736190c7 \
|
||||
--hash=sha256:e60933afc4b52137d323a4434c8340e0ce1e58cec71439e46680d4db188f11b3
|
||||
# via -r infra/requirements.txt
|
||||
sentry-sdk==2.74.0 \
|
||||
--hash=sha256:40b205af015649df3ec9986e057ce24ce85956bee3fb75efa72c93aa7036bdff \
|
||||
--hash=sha256:dd91d75aacaef636006b579ac3ddb2fdbc9dce35f00f4b353b6b1b110c6b256a
|
||||
# via -r infra/requirements.txt
|
||||
six==1.17.0 \
|
||||
--hash=sha256:4721f391ed90541fddacab5acf947aa0d3dc7d27b2e1e8eda2be8970586c3274 \
|
||||
--hash=sha256:ff70335d468e7eb6ec65b95b99d3a2836546063f63acc5171de367e834932a81
|
||||
@@ -651,7 +656,9 @@ typing-inspection==0.4.4 \
|
||||
urllib3==2.7.0 \
|
||||
--hash=sha256:231e0ec3b63ceb14667c67be60f2f2c40a518cb38b03af60abc813da26505f4c \
|
||||
--hash=sha256:9fb4c81ebbb1ce9531cce37674bbc6f1360472bc18ca9a553ede278ef7276897
|
||||
# via botocore
|
||||
# via
|
||||
# botocore
|
||||
# sentry-sdk
|
||||
uvicorn==0.34.2 \
|
||||
--hash=sha256:0e929828f6186353a80b58ea719861d2629d766293b6d19baf086ba31d4f3328 \
|
||||
--hash=sha256:deb49af569084536d269fe0a6d67e3754f104cf03aba7c11c40f01aadf33c403
|
||||
|
||||
@@ -9,3 +9,4 @@ pillow==13.0.0
|
||||
pikepdf==10.13.0.post1
|
||||
pypdfium2==5.14.0
|
||||
segno==1.6.6
|
||||
sentry-sdk==2.74.0
|
||||
|
||||
83
tests/test_observability.py
Normal file
83
tests/test_observability.py
Normal file
@@ -0,0 +1,83 @@
|
||||
"""Sentry's scrubbing rules and its off switch (note Sentry)."""
|
||||
import os
|
||||
import unittest
|
||||
from unittest import mock
|
||||
|
||||
try:
|
||||
import sentry_sdk
|
||||
except ImportError: # pragma: no cover - the host may not have the dependency
|
||||
sentry_sdk = None
|
||||
|
||||
from app import observability
|
||||
|
||||
|
||||
@unittest.skipUnless(sentry_sdk, 'sentry-sdk is installed with the API image')
|
||||
class ScrubTest(unittest.TestCase):
|
||||
def test_request_credentials_tokens_and_bodies_are_removed(self):
|
||||
event = {'request': {
|
||||
'url': 'https://dtf.example/api/quotes?page=2&token=abc&X-Amz-Signature=def',
|
||||
'query_string': 'page=2&token=abc&X-Amz-Signature=def',
|
||||
'cookies': {'dtf_session': 'secret'},
|
||||
'data': '{"customer":{"mail":"maria@example.com"}}',
|
||||
'headers': {'Cookie': 'dtf_session=secret', 'Authorization': 'Bearer x',
|
||||
'X-Auth-Token': 'x', 'X-Amz-Security-Token': 'x',
|
||||
'X-Forwarded-For': '1.2.3.4'},
|
||||
}}
|
||||
observability.scrub(event)
|
||||
request = event['request']
|
||||
self.assertNotIn('cookies', request)
|
||||
self.assertNotIn('data', request)
|
||||
self.assertEqual(request['headers'], {'X-Forwarded-For': '1.2.3.4'})
|
||||
self.assertEqual(request['query_string'], 'page=2')
|
||||
self.assertEqual(request['url'], 'https://dtf.example/api/quotes?page=2')
|
||||
|
||||
def test_personal_data_in_messages_exceptions_and_breadcrumbs(self):
|
||||
event = {
|
||||
'message': 'Falha para maria@example.com, CPF 123.456.789-01, CNPJ 11.222.333/0001-81',
|
||||
'exception': {'values': [{'value': 'e-mail ana@example.com'}]},
|
||||
'breadcrumbs': [
|
||||
{'message': 'GET https://x/y?token=abc',
|
||||
'data': {'url': 'https://x/y?page=1&token=abc', 'note': 'CPF 12345678901'}},
|
||||
{'message': 'CNPJ 11222333000181'},
|
||||
],
|
||||
}
|
||||
observability.scrub(event)
|
||||
self.assertNotIn('maria@example.com', event['message'])
|
||||
self.assertNotIn('123.456.789-01', event['message'])
|
||||
self.assertNotIn('11.222.333/0001-81', event['message'])
|
||||
self.assertEqual(event['message'].count(observability.REDACTED), 3)
|
||||
self.assertNotIn('ana@example.com', event['exception']['values'][0]['value'])
|
||||
self.assertNotIn('token=abc', event['breadcrumbs'][0]['message'])
|
||||
self.assertNotIn('token=abc', event['breadcrumbs'][0]['data']['url'])
|
||||
self.assertNotIn('12345678901', event['breadcrumbs'][0]['data']['note'])
|
||||
self.assertNotIn('11222333000181', event['breadcrumbs'][1]['message'])
|
||||
|
||||
|
||||
@unittest.skipUnless(sentry_sdk, 'sentry-sdk is installed with the API image')
|
||||
class InitTest(unittest.TestCase):
|
||||
def test_no_dsn_does_nothing(self):
|
||||
with mock.patch.dict(os.environ, {'SENTRY_DSN_API': ''}):
|
||||
with mock.patch.object(sentry_sdk, 'init') as init:
|
||||
self.assertFalse(observability.init('api'))
|
||||
init.assert_not_called()
|
||||
|
||||
def test_a_dsn_initialises_without_pii_and_scrubs(self):
|
||||
env = {'SENTRY_DSN_API': 'https://key@o1.ingest.sentry.io/1',
|
||||
'SENTRY_ENVIRONMENT': 'test', 'IMAGE_TAG': 'abc123',
|
||||
'SENTRY_TRACES': '0.2'}
|
||||
with mock.patch.dict(os.environ, env):
|
||||
with mock.patch.object(sentry_sdk, 'init') as init, \
|
||||
mock.patch.object(sentry_sdk, 'set_tag') as set_tag:
|
||||
self.assertTrue(observability.init('api'))
|
||||
options = init.call_args.kwargs
|
||||
self.assertEqual(options['dsn'], env['SENTRY_DSN_API'])
|
||||
self.assertEqual(options['environment'], 'test')
|
||||
self.assertEqual(options['release'], 'abc123')
|
||||
self.assertIs(options['send_default_pii'], False)
|
||||
self.assertEqual(options['traces_sample_rate'], 0.2)
|
||||
self.assertIs(options['before_send'], observability.scrub)
|
||||
set_tag.assert_called_once_with('component', 'api')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -46,7 +46,11 @@
|
||||
let data;
|
||||
try { data = text ? JSON.parse(text) : {}; }
|
||||
catch (_) { throw new Error(response.ok ? 'Resposta inválida do serviço.' : 'O serviço está indisponível. Tente novamente em instantes.'); }
|
||||
if (!response.ok) { const error=new Error(problem(data.detail));error.status=response.status;throw error; }
|
||||
if (!response.ok) {
|
||||
const error=new Error(problem(data.detail));error.status=response.status;
|
||||
window.dtfObservability?.apiError?.(path,response.status,error.message,data.detail);
|
||||
throw error;
|
||||
}
|
||||
return data;
|
||||
};
|
||||
// A refusal as one sentence: the server's own, or the first field a form
|
||||
@@ -60,6 +64,9 @@
|
||||
}
|
||||
const ready = api('/session');
|
||||
ready.then(session=>{
|
||||
window.dtfEnvironment=session.sentry_environment||session.environment;
|
||||
window.dtfRelease=session.sentry_release||undefined;
|
||||
window.dtfObservability?.start?.(session.sentry_dsn_web,'site');
|
||||
window.dtfUploadMaxBytes=session.max_upload_bytes;
|
||||
const limit=document.getElementById('zLimite');
|
||||
if(limit)limit.textContent='Até '+(session.max_upload_bytes/1073741824).toFixed(0)+' GB por arquivo.';
|
||||
|
||||
@@ -641,6 +641,8 @@ h2 em{font-style:normal;color:var(--laranja)}
|
||||
@media(prefers-reduced-motion:reduce){*{transition:none!important;scroll-behavior:auto}}
|
||||
</style>
|
||||
<link rel="stylesheet" href="/site-v2.css">
|
||||
<script src="/vendor/sentry.min.js"></script>
|
||||
<script src="/observability.js"></script>
|
||||
<script src="/site-pages.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
|
||||
@@ -297,4 +297,4 @@
|
||||
<div class="scrim" id="scrim"></div>
|
||||
<aside class="drawer" id="panel" aria-label="Pedido"></aside>
|
||||
</div>
|
||||
<script src="/upload.js"></script><script src="/kanban-viewer.js"></script><script src="/kanban.js"></script><script src="/kanban-label.js"></script><script src="/kanban-numbers.js"></script><script src="/kanban-site.js"></script><script src="/packing.js"></script><script src="/kanban-montador.js"></script></body></html>
|
||||
<script src="/vendor/sentry.min.js"></script><script src="/observability.js"></script><script src="/upload.js"></script><script src="/kanban-viewer.js"></script><script src="/kanban.js"></script><script src="/kanban-label.js"></script><script src="/kanban-numbers.js"></script><script src="/kanban-site.js"></script><script src="/packing.js"></script><script src="/kanban-montador.js"></script></body></html>
|
||||
|
||||
@@ -230,7 +230,14 @@ function freightWeight(fr){
|
||||
function downloadButton(text,fn,className){const b=button(text,fn,className);b.prepend(svgIcon(IC.download,'i m'));return b;}
|
||||
async function api(path,body){
|
||||
const r=await fetch('/api/operator'+path,{headers:{'Content-Type':'application/json'},...(body===undefined?{}:{method:'POST',body:JSON.stringify(body)})});
|
||||
const d=await r.json();if(!r.ok){const error=new Error(typeof d.detail==='string'?d.detail:'Confira os campos ('+r.status+').');error.status=r.status;throw error;}return d;
|
||||
const d=await r.json();
|
||||
if(!r.ok){
|
||||
const error=new Error(typeof d.detail==='string'?d.detail:'Confira os campos ('+r.status+').');
|
||||
error.status=r.status;
|
||||
window.dtfObservability?.apiError?.(path,r.status,error.message,d.detail);
|
||||
throw error;
|
||||
}
|
||||
return d;
|
||||
}
|
||||
function download(uid,orderId){return async()=>{
|
||||
const result=await api('/uploads/'+uid+'/download'+(orderId?'?order_id='+encodeURIComponent(orderId):''));
|
||||
@@ -636,7 +643,11 @@ let seenOrders=null, seenPending=null, unseen=0;
|
||||
async function load(quiet=false){
|
||||
try{
|
||||
const [loaded,me]=await Promise.all([api('/board'),api('/me')]);
|
||||
board=absorb(loaded);ME=me;applyRole();paintMyMachine();
|
||||
board=absorb(loaded);ME=me;
|
||||
window.dtfEnvironment=me.sentry_environment||me.environment;
|
||||
window.dtfRelease=me.sentry_release||undefined;
|
||||
window.dtfObservability?.start?.(me.sentry_dsn_web,'kanban');
|
||||
applyRole();paintMyMachine();
|
||||
noticeNew(quiet);
|
||||
const known=new Set(board.orders.map(o=>o.id));
|
||||
board.orders.push(...olderFinished.filter(o=>!known.has(o.id)));
|
||||
|
||||
120
web/observability.js
Normal file
120
web/observability.js
Normal file
@@ -0,0 +1,120 @@
|
||||
/* Sentry for the Site and the Kanban, used only when the DSN arrives from the
|
||||
API. It loads after web/vendor/sentry.min.js and never fetches anything
|
||||
itself; DSNs are public by design, so an empty one leaves everything off.
|
||||
|
||||
beforeSend follows the server (app/observability.py): no cookies, credential
|
||||
headers, request bodies or signed/token query strings, and CPF/CNPJ and
|
||||
e-mails replaced by [removido]. */
|
||||
(function () {
|
||||
const EMAIL = /[^\s@]+@[^\s@]+\.[A-Za-z]{2,}/g;
|
||||
const DOCUMENT = /(?<!\d)(?:\d{2}\.?\d{3}\.?\d{3}\/?\d{4}-?\d{2}|\d{3}\.?\d{3}\.?\d{3}-?\d{2})(?!\d)/g;
|
||||
const SENSITIVE_PARAM = /token|signature|x-amz/i;
|
||||
const SENSITIVE_HEADER = /^(cookie|authorization|x-.*token.*)$/i;
|
||||
const REDACTED = '[removido]';
|
||||
let started = false;
|
||||
let app = '';
|
||||
|
||||
const clean = value => String(value == null ? '' : value)
|
||||
.replace(EMAIL, REDACTED).replace(DOCUMENT, REDACTED);
|
||||
|
||||
function scrubQuery(query) {
|
||||
if (!query) return query;
|
||||
return String(query).split('&').filter(part => {
|
||||
let key = part.split('=')[0] || '';
|
||||
try { key = decodeURIComponent(key.replace(/\+/g, ' ')); } catch (error) { /* keep the raw key */ }
|
||||
return !SENSITIVE_PARAM.test(key);
|
||||
}).join('&');
|
||||
}
|
||||
|
||||
function scrubText(value) {
|
||||
if (typeof value !== 'string') return value;
|
||||
value = clean(value);
|
||||
const at = value.indexOf('?');
|
||||
return at < 0 ? value : value.slice(0, at + 1) + scrubQuery(value.slice(at + 1));
|
||||
}
|
||||
|
||||
function scrubUrl(url) {
|
||||
if (typeof url !== 'string') return url;
|
||||
const at = url.indexOf('?');
|
||||
return at < 0 ? url : url.slice(0, at + 1) + scrubQuery(url.slice(at + 1));
|
||||
}
|
||||
|
||||
function scrubValue(value) {
|
||||
if (typeof value === 'string') return scrubText(value);
|
||||
if (Array.isArray(value)) return value.map(scrubValue);
|
||||
if (value && typeof value === 'object') {
|
||||
const out = {};
|
||||
for (const [key, item] of Object.entries(value)) out[key] = scrubValue(item);
|
||||
return out;
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
function scrubRequest(request) {
|
||||
if (!request || typeof request !== 'object') return;
|
||||
delete request.cookies;
|
||||
delete request.data;
|
||||
delete request.body;
|
||||
if (request.headers && typeof request.headers === 'object') {
|
||||
for (const key of Object.keys(request.headers)) {
|
||||
if (SENSITIVE_HEADER.test(key)) delete request.headers[key];
|
||||
}
|
||||
}
|
||||
if (request.query_string) request.query_string = scrubQuery(request.query_string);
|
||||
if (request.url) request.url = scrubUrl(request.url);
|
||||
}
|
||||
|
||||
function scrub(event) {
|
||||
if (!event || typeof event !== 'object') return event;
|
||||
scrubRequest(event.request);
|
||||
if (typeof event.message === 'string') event.message = scrubText(event.message);
|
||||
if (event.logentry && typeof event.logentry.message === 'string')
|
||||
event.logentry.message = scrubText(event.logentry.message);
|
||||
if (event.exception && Array.isArray(event.exception.values)) {
|
||||
for (const value of event.exception.values) {
|
||||
if (value && typeof value.value === 'string') value.value = scrubText(value.value);
|
||||
}
|
||||
}
|
||||
let breadcrumbs = event.breadcrumbs;
|
||||
if (breadcrumbs && !Array.isArray(breadcrumbs)) breadcrumbs = breadcrumbs.values;
|
||||
if (Array.isArray(breadcrumbs)) {
|
||||
for (const crumb of breadcrumbs) {
|
||||
if (!crumb || typeof crumb !== 'object') continue;
|
||||
if (typeof crumb.message === 'string') crumb.message = scrubText(crumb.message);
|
||||
if (crumb.data) crumb.data = scrubValue(crumb.data);
|
||||
}
|
||||
}
|
||||
if (event.extra) event.extra = scrubValue(event.extra);
|
||||
if (event.user) event.user = scrubValue(event.user);
|
||||
return event;
|
||||
}
|
||||
|
||||
function start(dsn, component) {
|
||||
if (started || !dsn || typeof Sentry === 'undefined') return;
|
||||
started = true;
|
||||
app = component || '';
|
||||
const options = {dsn, sendDefaultPii: false, beforeSend: scrub};
|
||||
if (window.dtfEnvironment) options.environment = window.dtfEnvironment;
|
||||
if (window.dtfRelease) options.release = window.dtfRelease;
|
||||
try {
|
||||
Sentry.init(options);
|
||||
Sentry.setTag('app', app);
|
||||
} catch (error) {
|
||||
started = false;
|
||||
}
|
||||
}
|
||||
|
||||
function apiError(path, status, message, detail) {
|
||||
if (!started || status === 401 || typeof Sentry === 'undefined') return;
|
||||
try {
|
||||
const extra = {path, status, page: location.pathname};
|
||||
if (status === 422 && detail) extra.detail = detail;
|
||||
Sentry.captureMessage(clean('API ' + status + ' ' + path + ': ' + (message || '')),
|
||||
{level: 'error', tags: {app}, extra});
|
||||
} catch (error) {
|
||||
// Reporting an error must never break the page.
|
||||
}
|
||||
}
|
||||
|
||||
window.dtfObservability = {start, apiError, scrub};
|
||||
})();
|
||||
21
web/vendor/LICENSE-sentry.txt
vendored
Normal file
21
web/vendor/LICENSE-sentry.txt
vendored
Normal file
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2019 Functional Software, Inc. dba Sentry
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of
|
||||
this software and associated documentation files (the "Software"), to deal in
|
||||
the Software without restriction, including without limitation the rights to
|
||||
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
|
||||
of the Software, and to permit persons to whom the Software is furnished to do
|
||||
so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
7
web/vendor/README.md
vendored
7
web/vendor/README.md
vendored
@@ -31,3 +31,10 @@ curl -s "https://api.cdnjs.com/libraries/pdf.js/<version>?fields=sri"
|
||||
documented workaround is `isEvalSupported: false`; `web/index.html` already passes
|
||||
that, so the known path is closed. Upgrading is worthwhile but is an API change,
|
||||
not a file swap, and belongs with its own browser testing — see `ROADMAP.md` 2.7.
|
||||
|
||||
## Sentry browser SDK 11.12.0
|
||||
|
||||
One line per vendored file: source, version, date and SHA-256.
|
||||
|
||||
- `sentry.min.js` — https://browser.sentry-cdn.com/11.12.0/bundle.min.js — @sentry/browser 11.12.0 — 2026-11-11 — sha256 `388cdc69ba60b5a883097874ee8e5e010543990d60b5846d9dd1a4e736a49902`
|
||||
- `LICENSE-sentry.txt` — https://registry.npmjs.org/@sentry/browser/-/browser-11.12.0.tgz (`package/LICENSE`) — @sentry/browser 11.12.0 — 2026-11-11 — sha256 `f3df0b92efcd9d8cc0de5a36c151569a12a647d65b851abbb696ef7b13dee10b`
|
||||
|
||||
3
web/vendor/sentry.min.js
vendored
Normal file
3
web/vendor/sentry.min.js
vendored
Normal file
File diff suppressed because one or more lines are too long
Reference in New Issue
Block a user