Files
aoc/backend/database.py
Tomas Kracmar e348881083 feat: Admin Operations SIEM — alerts, notifications, pre-built rules
- Add pluggable notification system (webhook, Slack, Teams) with retry
- Add alert deduplication: same rule + actor within 15 min = one alert
- Add 10 pre-built admin-ops rule templates seeded on startup:
  - Failed Conditional Access, After-Hours Admin Activity
  - New Application Registration, Admin Role Assignment
  - License Change, Bulk User Deletion
  - Device Compliance Failure, Exchange Transport Rule Change
  - Service Principal Credential Added, External Sharing Enabled
- Add /api/alerts, /api/alerts/{id}/status, /api/alerts/summary endpoints
- Add alert dashboard to frontend with status filters and ack/resolve buttons
- Add alert summary badge in hero header (high/medium/low counts)
- New env vars: ALERT_WEBHOOK_URL, ALERT_WEBHOOK_FORMAT, ALERT_DEDUPE_MINUTES
2026-04-22 14:12:36 +02:00

47 lines
1.9 KiB
Python

from contextlib import suppress
import structlog
from config import DB_NAME, MONGO_URI, RETENTION_DAYS
from pymongo import ASCENDING, DESCENDING, TEXT, MongoClient
client = MongoClient(MONGO_URI or "mongodb://localhost:27017")
db = client[DB_NAME]
events_collection = db["events"]
saved_searches_collection = db["saved_searches"]
alerts_collection = db["alerts"]
logger = structlog.get_logger("aoc.database")
def setup_indexes(max_retries: int = 5, delay: float = 2.0):
"""Ensure MongoDB indexes exist. Retries on connection errors."""
from time import sleep
for attempt in range(1, max_retries + 1):
try:
events_collection.create_index("dedupe_key", unique=True, sparse=True)
events_collection.create_index([("timestamp", DESCENDING)])
events_collection.create_index([("service", ASCENDING), ("timestamp", DESCENDING)])
events_collection.create_index("id")
saved_searches_collection.create_index([("created_by", ASCENDING), ("created_at", DESCENDING)])
events_collection.create_index(
[("actor_display", TEXT), ("raw_text", TEXT), ("operation", TEXT)],
name="text_search_index",
)
if RETENTION_DAYS > 0:
events_collection.create_index(
[("timestamp", ASCENDING)],
expireAfterSeconds=RETENTION_DAYS * 24 * 60 * 60,
name="ttl_timestamp",
)
else:
with suppress(Exception):
events_collection.drop_index("ttl_timestamp")
logger.info("MongoDB indexes ensured")
return
except Exception as exc:
if attempt == max_retries:
logger.error("Failed to ensure MongoDB indexes", error=str(exc))
raise
logger.warning("MongoDB not ready, retrying...", attempt=attempt, error=str(exc))
sleep(delay)