Django, Flask and FastAPI
All three use python/bower_events.py,
which needs only the standard library (Python 3.10 and later). Read the
shared guidance first.
import bower_events
bower = bower_events.BowerClient() # BOWER_COLLECTOR_URL, BOWER_INGEST_TOKEN
event = bower_events.build_event(APP, {"eventCategory": "authentication", ...})
bower.send_async(event) # background thread, never raises
ip = bower_events.client_ip(peer, x_forwarded_for, TRUSTED)
logging_config.py is a dictConfig
for application logs: JSON lines, UTC, control characters stripped, and secret-named fields
replaced.
Flask
before_requestsetsg.request_idandg.client_ip;after_requestreturnsX-Request-Id.- Don't add werkzeug's
ProxyFixwith a fixed hop count.client_ip()checks the peer againstTRUSTED_PROXIESinstead. request.url_rule.ruleis the route template.@app.errorhandler(Exception)turnsBadRequestintoinput_validation_failureand other exceptions intoapplication_error, with a generic response.
FastAPI
- An HTTP middleware sets
request.state.request_idandclient_ip. - Run Uvicorn with
--no-proxy-headers. By default Uvicorn trustsX-Forwarded-Forfrom127.0.0.1and::1and rewritesrequest.clientbefore your code sees it. The example was tested both ways: with the flag, a spoofed header is ignored. - Events go out as
BackgroundTasks, after the response. - Handlers for
RequestValidationErrorandExceptionsend the validation and error events.
Django
bower_middleware.pyhasBowerSecurityMiddleware(request ID, client IP,process_exception) and receivers for Django'suser_logged_in,user_login_failedanduser_logged_outsignals. The receivers read only the username: Django passes the password incredentials.- Put the middleware first in
MIDDLEWARE, and import the module from yourAppConfig.ready()so the receivers connect. request.resolver_match.routeis the route pattern.USE_TZ = Truekeeps timestamps in UTC.
django_example/run.py starts the example with an in-memory database and a demo user.
What was run
Flask, FastAPI and Django were each run against a local collector with the ASVS pack (Flask 3.1.3, FastAPI 0.162.2 on Uvicorn 0.54.0, Django 6.1.3). All four test requests produced accepted events, with no password, CRLF or spoofed address in the redacted output. The helper matches the cross-language contract.