-
Notifications
You must be signed in to change notification settings - Fork 8
feat: save audit logs to postgres (M2-10911) #2076
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
Merged
Merged
Changes from all commits
Commits
Show all changes
12 commits
Select commit
Hold shift + click to select a range
2ad7bc1
feat: add audit_logs table schema and migration
sricharan-varanasi 8cff1d5
feat: add AuditLogCRUD for insert and applet-scoped query
sricharan-varanasi 3c7bfbe
feat: write audit events to postgres instead of opensearch
sricharan-varanasi 1ba3a29
feat: read audit events from postgres, remove opensearch connections
sricharan-varanasi 577d55a
test: rewrite audit module tests for postgres
sricharan-varanasi 5e90bb9
docs: update audit pipeline doc for postgres storage
sricharan-varanasi fa858aa
fix:cqf
sricharan-varanasi 5b1f611
test: prevent audit event persistence leaking across tests
sricharan-varanasi 2f6046e
fix: use contains() for GIN-compatible applet_ids array lookup
sricharan-varanasi 98a3a56
fix: wrap applet_id in list for array containment (@>) query
sricharan-varanasi 05f6f21
fix: remove index on event_action, keep user_id index
sricharan-varanasi 0134b95
fix: remove ix_audit_logs_event_action from migration
sricharan-varanasi 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
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
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,74 @@ | ||
| import datetime | ||
| import uuid | ||
|
|
||
| from sqlalchemy import and_, func, select | ||
| from sqlalchemy.dialects.postgresql import insert | ||
|
|
||
| from apps.audit.db.schemas import AuditLogSchema | ||
| from infrastructure.database.crud import BaseCRUD | ||
|
|
||
| DEFAULT_PAGE_SIZE = 1000 | ||
|
|
||
|
|
||
| def _to_naive_utc(value: datetime.datetime) -> datetime.datetime: | ||
| """Normalise a datetime to naive UTC to match the stored ``event_timestamp``.""" | ||
| if value.tzinfo is not None: | ||
| value = value.astimezone(datetime.timezone.utc).replace(tzinfo=None) | ||
| return value | ||
|
|
||
|
|
||
| class AuditLogCRUD(BaseCRUD[AuditLogSchema]): | ||
| schema_class = AuditLogSchema | ||
|
|
||
| async def save(self, schema: AuditLogSchema) -> None: | ||
| """Insert an audit log row. | ||
|
|
||
| Uses ``ON CONFLICT (event_id) DO NOTHING`` so that a retried worker | ||
| task (which re-delivers the same event) does not create a duplicate | ||
| row — preserving the idempotency OpenSearch gave us via ``id=event.id``. | ||
| """ | ||
| query = ( | ||
| insert(AuditLogSchema) | ||
| .values( | ||
| event_id=schema.event_id, | ||
| event_timestamp=schema.event_timestamp, | ||
| event_action=schema.event_action, | ||
| event_outcome=schema.event_outcome, | ||
| user_id=schema.user_id, | ||
| applet_ids=schema.applet_ids, | ||
| payload=schema.payload, | ||
| ) | ||
| .on_conflict_do_nothing(index_elements=[AuditLogSchema.event_id]) | ||
| ) | ||
| await self._execute(query) | ||
|
|
||
| async def search_applet_events( | ||
| self, | ||
| applet_id: uuid.UUID, | ||
| *, | ||
| from_datetime: datetime.datetime | None = None, | ||
| to_datetime: datetime.datetime | None = None, | ||
| page: int = 1, | ||
| limit: int = DEFAULT_PAGE_SIZE, | ||
| ) -> tuple[list[AuditLogSchema], int]: | ||
| conditions = [AuditLogSchema.applet_ids.contains([applet_id])] | ||
| if from_datetime is not None: | ||
| conditions.append(AuditLogSchema.event_timestamp >= _to_naive_utc(from_datetime)) | ||
| if to_datetime is not None: | ||
| conditions.append(AuditLogSchema.event_timestamp < _to_naive_utc(to_datetime)) | ||
|
|
||
| where = and_(*conditions) | ||
|
|
||
| query = ( | ||
| select(AuditLogSchema) | ||
| .where(where) | ||
| .order_by(AuditLogSchema.event_timestamp.asc(), AuditLogSchema.event_id.asc()) | ||
| .limit(limit) | ||
| .offset((page - 1) * limit) | ||
| ) | ||
| rows = (await self._execute(query)).scalars().all() | ||
|
|
||
| count_query = select(func.count()).select_from(AuditLogSchema).where(where) | ||
| total = (await self._execute(count_query)).scalar() or 0 | ||
|
|
||
| return list(rows), total |
Empty file.
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,30 @@ | ||
| from sqlalchemy import Column, DateTime, Index, String | ||
| from sqlalchemy.dialects.postgresql import ARRAY, JSONB, UUID | ||
|
|
||
| from infrastructure.database.base import Base | ||
|
|
||
|
|
||
| class AuditLogSchema(Base): | ||
| """Audit event stored in Postgres. | ||
|
|
||
| Append-only. A few columns are denormalized from the ECS document for | ||
| filtering/sorting; the full event is kept in ``payload`` as the same | ||
| dotted-alias JSON that is produced by ``AuditEvent.model_dump(mode="json")``. | ||
| """ | ||
|
|
||
| __tablename__ = "audit_logs" | ||
|
|
||
| event_id = Column(UUID(as_uuid=True), nullable=False, unique=True) | ||
| event_timestamp = Column(DateTime(), nullable=False) | ||
| event_action = Column(String(), nullable=False) | ||
| event_outcome = Column(String(), nullable=True) | ||
| user_id = Column(UUID(as_uuid=True), nullable=True, index=True) | ||
| applet_ids = Column(ARRAY(UUID(as_uuid=True)), nullable=True) | ||
| payload = Column(JSONB(), nullable=False) | ||
|
|
||
| __table_args__ = ( | ||
| # Covers the date-range filter and the (timestamp, event_id) sort order. | ||
| Index("ix_audit_logs_event_timestamp_event_id", "event_timestamp", "event_id"), | ||
| # Covers `applet_ids @> ARRAY[:applet_id]` membership lookups. | ||
| Index("ix_audit_logs_applet_ids", "applet_ids", postgresql_using="gin"), | ||
| ) | ||
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.