|
| 1 | +"""Stand-alone audit logging example for flask-s3-viewer. |
| 2 | +
|
| 3 | +Copy the ``configure_audit_logger`` call into your own app's startup |
| 4 | +to start auditing. The block is intentionally self-contained — no |
| 5 | +other example file imports from it. |
| 6 | +
|
| 7 | +The ``flask_s3_viewer.audit`` logger emits one record per S3 CRUD |
| 8 | +action (list / download / upload / delete / presign). Every record |
| 9 | +carries these LogRecord extras: |
| 10 | +
|
| 11 | + action / namespace / key / user / result / status_code / |
| 12 | + client_ip / user_agent / request_id (+ error on failure) |
| 13 | +
|
| 14 | +Multi-file requests emit one row per file. All rows from the same |
| 15 | +Flask request share one ``request_id`` (8 hex chars), so plaintext |
| 16 | +greps can group them, e.g. ``grep "req=a1b2c3d4" audit.log``. |
| 17 | +
|
| 18 | +Drop this file's body into your app's startup (after ``logging.basicConfig`` |
| 19 | +or whatever root logging your host already does) and adjust the |
| 20 | +handler / formatter to taste — ``FileHandler`` with rotation, a JSON |
| 21 | +formatter via ``python-json-logger``, a Loki/Fluent Bit sink, etc. |
| 22 | +""" |
| 23 | + |
| 24 | +from __future__ import annotations |
| 25 | + |
| 26 | +import logging |
| 27 | + |
| 28 | + |
| 29 | +class DemoUserRedactFilter(logging.Filter): |
| 30 | + """Cheap email-tail redaction for the demo. |
| 31 | +
|
| 32 | + Production deployments should swap this out for the redaction |
| 33 | + policy that matches their compliance requirements — see |
| 34 | + ``docs/source/usage/configuration.rst`` for a ``RedactFilter`` / |
| 35 | + ``KeyErrorRedactFilter`` reference set. |
| 36 | + """ |
| 37 | + |
| 38 | + def filter(self, record: logging.LogRecord) -> bool: |
| 39 | + user = getattr(record, "user", None) |
| 40 | + if user and "@" in user: |
| 41 | + local, domain = user.split("@", 1) |
| 42 | + record.user = f"{local[:2]}***@{domain}" |
| 43 | + return True |
| 44 | + |
| 45 | + |
| 46 | +def configure_audit_logger( |
| 47 | + *, |
| 48 | + level: int = logging.INFO, |
| 49 | + propagate: bool = True, |
| 50 | + redact_user_emails: bool = True, |
| 51 | +) -> logging.Logger: |
| 52 | + """Attach a ``StreamHandler`` to ``flask_s3_viewer.audit`` and return it. |
| 53 | +
|
| 54 | + Parameters |
| 55 | + ---------- |
| 56 | + level |
| 57 | + Audit logger level. ``logging.INFO`` is the recommended default; |
| 58 | + denied (401/403) records emit at ``WARNING`` and exceptions at |
| 59 | + ``ERROR`` so they survive higher thresholds too. |
| 60 | + propagate |
| 61 | + When ``True`` (default) audit records also reach the host's root |
| 62 | + logger. Set ``False`` if you want the audit stream completely |
| 63 | + isolated from your application logs. |
| 64 | + redact_user_emails |
| 65 | + Install :class:`DemoUserRedactFilter` so emails appear as |
| 66 | + ``jo***@example.com`` in the demo output. Turn off (or replace |
| 67 | + with your own filter) for production. |
| 68 | + """ |
| 69 | + audit_logger = logging.getLogger("flask_s3_viewer.audit") |
| 70 | + audit_logger.setLevel(level) |
| 71 | + audit_logger.propagate = propagate |
| 72 | + |
| 73 | + handler = logging.StreamHandler() |
| 74 | + handler.setFormatter( |
| 75 | + logging.Formatter( |
| 76 | + "AUDIT %(asctime)s %(levelname)s " |
| 77 | + "action=%(action)s namespace=%(namespace)s " |
| 78 | + "key=%(key)s user=%(user)s result=%(result)s " |
| 79 | + "status=%(status_code)s req=%(request_id)s " |
| 80 | + "ip=%(client_ip)s", |
| 81 | + ), |
| 82 | + ) |
| 83 | + audit_logger.addHandler(handler) |
| 84 | + |
| 85 | + if redact_user_emails: |
| 86 | + audit_logger.addFilter(DemoUserRedactFilter()) |
| 87 | + |
| 88 | + return audit_logger |
| 89 | + |
| 90 | + |
| 91 | +if __name__ == "__main__": |
| 92 | + # Quick smoke test — emits one anonymous record outside a Flask |
| 93 | + # request context. Run with: python -m example.audit_logging |
| 94 | + from flask_s3_viewer.audit import emit |
| 95 | + from flask_s3_viewer.auth import ACTION_LIST |
| 96 | + |
| 97 | + configure_audit_logger() |
| 98 | + emit( |
| 99 | + action=ACTION_LIST, |
| 100 | + namespace="demo", |
| 101 | + key="demo/key", |
| 102 | + user="alice@example.com", |
| 103 | + result="ok", |
| 104 | + status_code=200, |
| 105 | + ) |
0 commit comments