feat(audit): Authentik events ingest worker (Phase 2 chunk 1)

Background worker that pulls Authentik's /api/v3/events/events/ on a
60s cadence and writes each event into our audit log via AuditService.
External system events now share the same /audit timeline as
internally-recorded platform mutations — operator queries don't have
to cross-reference Authentik's own UI to see logins, password changes,
group membership, impersonation, etc.

Pieces:
- src/schemas/ingest-cursor.schema.ts: one row per source, tracks
  lastEventAt + lastEventId so restarts resume without re-pulling.
- src/schemas/audit-event.schema.ts: new `externalId` field; new
  compound unique index on (source, externalId) with a partial filter
  on externalId being a string. Partial (not sparse) so internally-
  recorded events with externalId=null don't collide.
- src/audit/audit.service.ts: AuditRecordInput grows `externalId` +
  `at` fields. record() now silently swallows MongoError code 11000
  (duplicate key) so re-pulling the cursor overlap doesn't log noise.
- src/integrations/authentik.client.ts: listEvents(since, page,
  pageSize) on the existing client — reuses the admin token and base
  URL the provisioning code already configured.
- src/ingest/action-map.ts: 16 known Authentik actions → dotted
  authentik.* verbs (login, login_failed, password_changed,
  impersonation_started, …). Unknown actions fall through to
  authentik.<raw> rather than getting silently dropped.
- src/ingest/authentik.ingest.ts: OnApplicationBootstrap worker.
  Reads cursor → pulls events with created__gt=cursor, ordering=created
  ASC → paginates forward (10 pages × 100/page safety cap per tick) →
  writes each event with source='authentik' + externalId=pk + at=
  evt.created → advances cursor to the newest seen. inFlight guard
  prevents overlapping ticks. AUDIT_INGEST_ENABLED=false disables for
  test environments.
- Tenant inference: from the user's groups (same convention the portal
  flag-eval proxy uses). Admin groups stripped; first match against a
  real Tenant.slug wins. Unmatched → tenantSlug undefined, event still
  lands in the global timeline.

Smoke-tested: fresh Mongo + restart → 78 Authentik events ingested,
0 duplicates. Performed a login at app.dezky.local → next 60s tick
captured the new login row with actor email + IP. Compound unique
index on (source, externalId) verified to reject re-pulled events
silently (no error logs).

Out of scope here (covered by chunks 2 + 3):
- Stalwart webhook ingest
- OCIS file-tail ingest
This commit is contained in:
Ronni Baslund
2026-05-24 20:12:21 +02:00
parent 02341d8ba5
commit b1d717e466
8 changed files with 351 additions and 6 deletions
@@ -0,0 +1,43 @@
// Per-source mapping from raw event action strings to the dotted verbs we
// store on AuditEvent.action. Known actions get a clean explicit verb; unknown
// ones fall through to `<source>.<raw>` so we don't silently drop new event
// types Authentik / Stalwart / OCIS introduces.
import type { AuditOutcome, AuditResourceType } from '../schemas/audit-event.schema.js'
export interface MappedAction {
action: string
outcome: AuditOutcome
resourceType?: AuditResourceType
}
// Authentik action strings (from /api/v3/events/events/ — see
// https://goauthentik.io/docs/events/ for the full enum).
const AUTHENTIK_MAP: Record<string, MappedAction> = {
login: { action: 'authentik.login', outcome: 'success', resourceType: 'user' },
login_failed: { action: 'authentik.login_failed', outcome: 'failure', resourceType: 'user' },
logout: { action: 'authentik.logout', outcome: 'success', resourceType: 'user' },
user_write: { action: 'authentik.user_updated', outcome: 'success', resourceType: 'user' },
password_set: { action: 'authentik.password_changed', outcome: 'success', resourceType: 'user' },
secret_rotate: { action: 'authentik.secret_rotated', outcome: 'success', resourceType: 'system' },
group_membership_set: { action: 'authentik.group_membership_changed', outcome: 'success', resourceType: 'user' },
invitation_used: { action: 'authentik.invitation_used', outcome: 'success', resourceType: 'user' },
authorize_application: { action: 'authentik.app_authorized', outcome: 'success', resourceType: 'user' },
impersonation_started: { action: 'authentik.impersonation_started', outcome: 'success', resourceType: 'user' },
impersonation_ended: { action: 'authentik.impersonation_ended', outcome: 'success', resourceType: 'user' },
policy_execution: { action: 'authentik.policy_executed', outcome: 'success', resourceType: 'system' },
policy_exception: { action: 'authentik.policy_exception', outcome: 'failure', resourceType: 'system' },
configuration_error: { action: 'authentik.configuration_error', outcome: 'failure', resourceType: 'system' },
model_created: { action: 'authentik.model_created', outcome: 'success', resourceType: 'system' },
model_updated: { action: 'authentik.model_updated', outcome: 'success', resourceType: 'system' },
model_deleted: { action: 'authentik.model_deleted', outcome: 'success', resourceType: 'system' },
}
export function mapAuthentikAction(raw: string): MappedAction {
return (
AUTHENTIK_MAP[raw] ?? {
action: `authentik.${raw}`,
outcome: 'success',
}
)
}