-
Notifications
You must be signed in to change notification settings - Fork 71
Add audit logs #647
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
varmar05
wants to merge
20
commits into
develop
Choose a base branch
from
audit_logs
base: develop
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Add audit logs #647
Changes from all commits
Commits
Show all changes
20 commits
Select commit
Hold shift + click to select a range
8c65b22
Add audit log foundation
varmar05 96491c7
Add audit logging for auth and sync events
varmar05 691faa5
Add login_method to password login events and project transfer audit …
varmar05 cc70bba
Align AuditEvent fields with DB sink column names
varmar05 1d005d2
Add missing project.version.created emits
varmar05 d1c7c20
Merge branch 'develop' into audit_logs
varmar05 1dc2d1c
Add user.locked and user.unlocked audit events
varmar05 7721b35
Fix: Populate actor email on user.created and user.login.failed audit…
varmar05 5ebd61c
Merge remote-tracking branch 'origin/develop' into audit_logs
varmar05 bc04a94
Merge remote-tracking branch 'origin/develop' into audit_logs
varmar05 b969695
Merge remote-tracking branch 'origin/develop' into audit_logs
varmar05 c6e0753
Audit logs fixes, renames and user/project events update
varmar05 d301c01
Merge remote-tracking branch 'origin/develop' into audit_logs
varmar05 8f9f99a
Ensure PROJECT/WORKSPACE_MEMBER_DELETED are called in case of cascade…
varmar05 fb4131c
Audit log fixes
varmar05 8c2fb4f
Fix PROJECT_DELETED event lost in Celery task
varmar05 5b7d245
Sanitize audit event metadata to JSON-safe values in emit()
varmar05 0e67044
Merge pull request #672 from MerginMaps/develop
MarcelGeo 81e096a
Audit logs fixes: Normalize project_name in metadata, fix project.del…
varmar05 47a95c8
Merge remote-tracking branch 'origin/master' into audit_logs
varmar05 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -36,3 +36,6 @@ docker-compose.local.yml | |
| # SSO | ||
| *.pem | ||
| *.crt | ||
|
|
||
| # Local Claude Code skills | ||
| .claude/commands/ | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,5 @@ | ||
| # Copyright (C) Lutra Consulting Limited | ||
| # | ||
| # SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-MerginMaps-Commercial | ||
|
|
||
| from .app import emit, register |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,78 @@ | ||
| # Copyright (C) Lutra Consulting Limited | ||
| # | ||
| # SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-MerginMaps-Commercial | ||
|
|
||
| import datetime | ||
| import enum | ||
| import json | ||
| import logging | ||
|
|
||
| from flask import Flask, current_app, has_app_context | ||
|
|
||
| from .events import AuditEvent, EventType | ||
| from .sinks import NullSink | ||
|
|
||
| logger = logging.getLogger(__name__) | ||
|
|
||
|
|
||
| def register(app: Flask) -> None: | ||
| """Wire the audit module into a Flask app. | ||
|
|
||
| Stores the sink in app.extensions["audit"] so emit() has one consistent lookup path. | ||
| """ | ||
| app.extensions["audit"] = {"sink": NullSink()} | ||
|
|
||
|
|
||
| def _json_safe(metadata: dict) -> dict: | ||
| """Sanitize metadata to a JSON-safe structure using the app's own JSON | ||
| provider. | ||
| """ | ||
|
|
||
| def default(o): | ||
| try: | ||
| return current_app.json.default(o) | ||
| except TypeError: | ||
| if isinstance(o, enum.Enum): | ||
| return o.value | ||
| return str(o) | ||
|
|
||
| return json.loads(json.dumps(metadata, default=default)) | ||
|
|
||
|
|
||
| def emit( | ||
| event_type: EventType, | ||
| actor_id=None, | ||
| actor_email=None, | ||
| actor_ua=None, | ||
| actor_device=None, | ||
| actor_ip=None, | ||
| target_user_id=None, | ||
| target_project_id=None, | ||
| target_workspace_id=None, | ||
| **metadata, | ||
| ) -> None: | ||
| """Emit one audit event to the configured sink. | ||
|
|
||
| Set at least one of target_user_id, target_project_id, target_workspace_id to identify the target. | ||
| Extra keyword arguments become the metadata dict — sanitized to a JSON-safe | ||
| form so callers never need to serialize values (e.g. datetimes) themselves. | ||
| """ | ||
| if not has_app_context() or "audit" not in current_app.extensions: | ||
| return | ||
| event = AuditEvent( | ||
| event_type=event_type, | ||
| actor_id=actor_id, | ||
| actor_email=actor_email, | ||
| actor_ua=actor_ua, | ||
| actor_device=actor_device, | ||
| actor_ip=actor_ip, | ||
| happened_at=datetime.datetime.utcnow(), | ||
| target_user_id=target_user_id, | ||
| target_project_id=target_project_id, | ||
| target_workspace_id=target_workspace_id, | ||
| metadata=_json_safe(metadata), | ||
| ) | ||
| try: | ||
| current_app.extensions["audit"]["sink"].write(event) | ||
| except Exception: | ||
| logger.warning("Failed to emit audit event %s", event_type, exc_info=True) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,29 @@ | ||
| # Copyright (C) Lutra Consulting Limited | ||
| # | ||
| # SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-MerginMaps-Commercial | ||
|
|
||
| import datetime | ||
| import uuid | ||
| from dataclasses import dataclass, field | ||
| from typing import Any | ||
|
|
||
| # Noun.verb dot-notation string, e.g. "user.login.succeeded". | ||
| # Each module defines its own str enum; the sink stores the raw string. | ||
| EventType = str | ||
|
|
||
|
|
||
| @dataclass(frozen=True) | ||
| class AuditEvent: | ||
| event_type: EventType | ||
| actor_ip: str | None | ||
| happened_at: datetime.datetime | ||
| actor_id: int | None | ||
| actor_email: str | None | ||
| actor_ua: str | None | ||
| actor_device: str | None # X-Device-Id header; set by mobile/QGIS clients | ||
| target_user_id: int | None # set when the target is a user | ||
| target_project_id: uuid.UUID | None # set when the target is a project | ||
| target_workspace_id: ( | ||
| int | None | ||
| ) # workspace the event belongs to; set for project and workspace events | ||
| metadata: dict[str, Any] = field(default_factory=dict) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,89 @@ | ||
| # Copyright (C) Lutra Consulting Limited | ||
| # | ||
| # SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-MerginMaps-Commercial | ||
|
|
||
| """ | ||
| Utilities for writing SQLAlchemy-based audit listeners in any module. | ||
| """ | ||
|
|
||
| import logging | ||
| from contextlib import contextmanager | ||
|
|
||
| from sqlalchemy import inspect as sa_inspect | ||
| from sqlalchemy.orm import ColumnProperty | ||
| from flask import has_request_context, request, current_app | ||
| from flask_login import current_user | ||
|
|
||
| from ..utils import get_ip, get_user_agent, get_device_id | ||
| from .app import emit | ||
|
|
||
| logger = logging.getLogger(__name__) | ||
|
|
||
|
|
||
| @contextmanager | ||
| def audit_session_flags(session, **flags): | ||
| """Context manager that sets db.session.info flags for the duration of a block | ||
| and removes them in a finally clause so they never leak on exceptions.""" | ||
| session.info.update(flags) | ||
| try: | ||
| yield | ||
| finally: | ||
| for key in flags: | ||
| session.info.pop(key, None) | ||
|
|
||
|
|
||
| def request_context(): | ||
| """Return the three request-derived actor kwargs: user_agent, device_id, ip. | ||
|
|
||
| Use **request_context() in explicit emit() calls so adding a new request | ||
| field only requires changing this one function. | ||
| """ | ||
| if not has_request_context(): | ||
| return dict(actor_ua=None, actor_device=None, actor_ip=None) | ||
| return dict( | ||
| actor_ua=get_user_agent(request), | ||
| actor_device=get_device_id(request), | ||
| actor_ip=get_ip(request), | ||
| ) | ||
|
|
||
|
|
||
| def actor_context(): | ||
| """Return full actor kwargs for emit() drawn from the current request context. | ||
|
|
||
| Used by SQLAlchemy listeners where current_user is the actor. | ||
| """ | ||
| actor_id = None | ||
| actor_email = None | ||
| if has_request_context() and hasattr( | ||
| current_app._get_current_object(), "login_manager" | ||
| ): | ||
| try: | ||
| if current_user.is_authenticated: | ||
| actor_id = current_user.id | ||
| actor_email = current_user.email | ||
| except Exception: | ||
| pass | ||
| return dict(actor_id=actor_id, actor_email=actor_email, **request_context()) | ||
|
|
||
|
|
||
| def field_changes(target, skip=frozenset()): | ||
| """Return flat old_<field>/new_<field> context for all changed non-skipped column fields. | ||
|
|
||
| Only column attributes are included — relationships are skipped because their | ||
| history entries are ORM instances, not JSON-serializable values. | ||
| """ | ||
| mapper = sa_inspect(type(target)) | ||
| ctx = {} | ||
| for attr in sa_inspect(target).attrs: | ||
| if attr.key in skip: | ||
| continue | ||
| if not isinstance(mapper.attrs[attr.key], ColumnProperty): | ||
| continue | ||
| hist = attr.history | ||
| if hist.has_changes(): | ||
| old = hist.deleted[0] if hist.deleted else None | ||
| new = hist.added[0] if hist.added else None | ||
| if old != new: | ||
| ctx[f"old_{attr.key}"] = old | ||
| ctx[f"new_{attr.key}"] = new | ||
| return ctx |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,21 @@ | ||
| # Copyright (C) Lutra Consulting Limited | ||
| # | ||
| # SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-MerginMaps-Commercial | ||
|
|
||
| from abc import ABC, abstractmethod | ||
|
|
||
| from .events import AuditEvent | ||
|
|
||
|
|
||
| class AbstractSink(ABC): | ||
| """Interface all audit sinks must implement.""" | ||
|
|
||
| @abstractmethod | ||
| def write(self, event: AuditEvent) -> None: ... | ||
|
|
||
|
|
||
| class NullSink(AbstractSink): | ||
| """Default sink — discards all events.""" | ||
|
|
||
| def write(self, event: AuditEvent) -> None: | ||
| pass |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.