Repository navigation
feat: security event log with entity tracking, login throttle, metrics & admin ui - #3229
Conversation
…dMany adapters A client fields projection (e.g. ?fields[user]=id,name) stripped realm_id from the SQL SELECT, so the per-row realm_scope gate evaluated against a missing resource realm: ownOrNull-scoped readers received every realm's rows (cross-realm disclosure - for clients including a plaintext-secret gate misfire), while own-scoped readers were wrongly denied their own rows. The shared applyRealmScopeSelect helper now re-adds realm_id plus the other gate-read columns after applyQuery in the user, robot, client, role-attribute and user-attribute adapters (session migrated onto the same helper). Role/scope/permission/policy list reads carry no per-row realm gate and are unaffected.
The prometheus middleware skip() excluded /authorize and /token, leaving the generic per-route histogram blind to the security-critical endpoints. Only the /metrics self-scrape and the root status endpoint stay excluded; both metered paths are fixed strings, so there is no label-cardinality risk.
The UserValidator accepted 3-character passwords and the password-reset flow enforced an inconsistent minimum of 5. The floor is now a validator option defaulting to 10 (NIST 800-63B posture: length only, no composition rules), driven by the new passwordMinLength config key (env PASSWORD_MIN_LENGTH) and threaded to every password-write site: user create/update, registration and password reset. Applies to new writes only - existing password hashes keep verifying.
Client.grant_types existed end-to-end but was never read by an enforcement path. A non-null (space- or comma-delimited) list is now an opt-in allowlist checked after client resolution in the authorization_code, refresh_token (incl. the bound-client-from-token path), client_credentials and password grants, and in the /authorize code-request verifier (authorization_code membership, denied before the consent UI renders). Violations fail with the new unauthorized_client error code (RFC 6749 §5.2). A null column keeps allow-all semantics, so upgrades are backward compatible; deployments that stored decorative grant_types values should review them before upgrading.
…ow metrics Adds the persisted, PII-stripped security audit trail (plan 057 stage 1) as a first-class audit-event domain: closed AuditEventName/Scope taxonomy in core-kit, an append-only audit_events table (no FKs - rows survive deletion of everything they reference; per-row expires_at retention stamped from auditLogRetentionDays and swept by a cleaner component), a fire-and-forget write service behind an allowlist-first scalar-only sanitizer, and a read-only dual-mounted /audit-events API gated by the new audit_read permission with the session-service self-scope + per-row realm-reach shape (gate columns force-selected). The record shape follows the hub telemetry Event model (scope/name pair, ref_type/ref_id, denormalized actor snapshot, request context group). Explicit emits (never the CRUD bus): login, login_failed (canonicalized attempted identifier in actor_name), authorize, logout, refresh replay, register, account activation, password reset requested/completed. On top of the same table, the failed-login throttle (plan 053, default off): (identifier, ip)-pair keyed counting over indexed columns, HTTP 429 login_attempt_throttled with retryAfter, fail-loud config check when enabled without the audit log, and the dead AttemptLogin core-kit type is removed. Auth-flow metrics counters (plan 058 part 2): IAuthFlowMetrics port with noop + prom-client adapters on the default registry - authup_login_total, authup_token_grant_total, authup_authorize_total (denied reserved), authup_refresh_replay_total.
|
Warning Review limit reached
Next review available in: 11 minutes Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available. How can I continue?After more reviews become available, a review can be triggered using the To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews. How do review limits work?CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability. For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window. Please refer docs for additional details. Review details⚙️ Run configurationConfiguration used: defaults Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (5)
📝 WalkthroughWalkthroughAdds a persisted, PII-sanitized, append-only security event log with authenticated read APIs and an admin UI. Authentication flows emit audit events and Prometheus metrics, failed logins can be throttled, and entity CRUD events can be mirrored with sanitized diffs and retention cleanup. ChangesSecurity event platform
Estimated code review effort: 5 (Critical) | ~120 minutes Possibly related PRs
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
authup
@authup/client-web
@authup/server-core
@authup/access
@authup/client-web-kit
@authup/client-web-kit-theme
@authup/client-web-nuxt
@authup/client-web-theme
@authup/core-http-kit
@authup/core-kit
@authup/core-realtime-kit
@authup/errors
@authup/i18n
@authup/kit
@authup/server-adapter-kit
@authup/server-adapter-node
@authup/server-adapter-socket-io
@authup/server-adapter-web
@authup/server-kit
@authup/server-test-kit
@authup/specs
commit: |
|
Note Unit test generation is a beta feature. Expect some limitations and changes as we gather feedback and continue to improve it. Generating unit tests... This may take up to 20 minutes. |
|
Request timed out after 900000ms (requestId=903a07ca-9e62-4137-98cf-5633817db8bf) |
There was a problem hiding this comment.
Actionable comments posted: 3
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
apps/server-core/src/core/oauth2/grant-types/refresh-token.ts (1)
187-207: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick winReorder audit recording after session revocation to avoid blocking the security-critical path.
The
await this.auditEventService?.record(...)at line 187 places a non-critical side effect before the security-critical operations at lines 201–207 (token blocklisting and session revocation). While theIAuditEventService.recordcontract guarantees it won't throw, theawaitmeans the revocation is gated on the audit write completing. If the audit database is slow or hangs, the session remains active after a confirmed replay detection — extending the attack window.The contract itself describes the method as "Fire-and-forget-safe," which implies the caller need not block on it. Consider either moving the audit recording and metrics call after
this.sessionManager.revoke(sessionId), or dropping theawaitto make it truly fire-and-forget.🔒 Suggested fix: move audit/metrics after revocation
protected async revokeFamily(sessionId: string, jti: string, at: string) : Promise<void> { this.logger?.warn('OAuth2 refresh token replay detected; revoking session', { session_id: sessionId, jti, }); - await this.auditEventService?.record({ - scope: AuditEventScope.OAUTH2, - name: AuditEventName.REFRESH_REPLAY_DETECTED, - refType: AuditEventRefType.SESSION, - refId: sessionId, - data: { jti }, - }); - this.metrics?.recordRefreshReplay(); - // Blocklisting is best-effort (cache) — settle all of them so one cache // failure cannot skip the rest or, worse, abort the session delete // below (the load-bearing part of the revocation). Pin each TTL to the // token's real expiry (unix seconds) so a long-lived refresh token // cannot resurface as active via introspection after the fallback 1h. const rows = await this.sessionTokenRepository.revokeBySessionId(sessionId, at); await Promise.allSettled(rows.map((row) => this.tokenRepository.setInactive( row.id, Math.floor(new Date(row.expires_at).getTime() / 1_000), ))); await this.sessionManager.revoke(sessionId); + + this.auditEventService?.record({ + scope: AuditEventScope.OAUTH2, + name: AuditEventName.REFRESH_REPLAY_DETECTED, + refType: AuditEventRefType.SESSION, + refId: sessionId, + data: { jti }, + }).catch(() => {}); + this.metrics?.recordRefreshReplay(); }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@apps/server-core/src/core/oauth2/grant-types/refresh-token.ts` around lines 187 - 207, Move the awaited audit recording and metrics call from before the security-critical operations to after token blocklisting and this.sessionManager.revoke(sessionId) in the refresh replay handling flow. Keep the existing audit payload and metrics behavior unchanged, while ensuring session revocation is not gated by audit completion.
🧹 Nitpick comments (6)
apps/server-core/src/app/modules/metrics/prom.ts (1)
20-35: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueConsider guarding the
getOrCreateCountercast against metric type mismatches.
register.getSingleMetricreturnsMetric | undefined, and theas Counter<T>cast assumes the existing metric is always aCounter. If a different metric type (e.g.,Gauge) were ever registered with the same name, this would produce a runtime error on.inc(). A runtimeinstanceof Countercheck would make this robust without changing the happy path.This is a low-risk concern since the function is only called from one constructor with known names, but the guard is trivial to add.
♻️ Optional guard for metric type safety
function getOrCreateCounter<T extends string>( name: string, help: string, labelNames: T[] = [], ): Counter<T> { const existing = register.getSingleMetric(name); if (existing instanceof Counter) { return existing as Counter<T>; } return new Counter<T>({ name, help, labelNames, }); }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@apps/server-core/src/app/modules/metrics/prom.ts` around lines 20 - 35, Update getOrCreateCounter to verify that an existing metric is an instance of Counter before returning it; only reuse the existing metric when the runtime type matches, and otherwise proceed with the existing Counter creation path.apps/server-core/src/core/identity/password-recovery/service.ts (1)
129-139: 🔒 Security & Privacy | 🔵 Trivial | ⚡ Quick winInclude request context in password-recovery audit events for security completeness.
Both
PASSWORD_RESET_REQUESTEDandPASSWORD_RESET_COMPLETEDaudit events omit request context (requestIpAddress,requestUserAgent,requestPath,requestMethod). For a security audit log, the source IP and user agent are critical for investigating credential stuffing or account takeover attempts targeting the password recovery flow.Additionally,
actorId/actorNameare set to the user whose password is being reset — but inforgotPassword, the requester is unauthenticated and anonymous. TherefType/refIdalready identify the subject user, so the actor fields are redundant and semantically misleading. Consider passing request context throughIdentityWorkflowContextor the service context and including it in the record, and setting actor fields to reflect the actual requester (or omitting them for unauthenticated flows).♻️ Proposed refactor sketch
// In PasswordRecoveryServiceContext or IdentityWorkflowContext, add: // requestContext?: { ipAddress?: string; userAgent?: string; path?: string; method?: string } // In forgotPassword, pass request context to the audit event: await this.auditEventService?.record({ scope: AuditEventScope.IDENTITY, name: AuditEventName.PASSWORD_RESET_REQUESTED, refType: AuditEventRefType.USER, refId: merged.id, - actorType: IdentityType.USER, - actorId: merged.id, - actorName: merged.name, + // Actor is anonymous for forgotPassword — refType/refId already + // identify the subject user; include request source for investigation. + requestIpAddress: context?.requestContext?.ipAddress, + requestUserAgent: context?.requestContext?.userAgent, realmId: merged.realm_id, });Also applies to: 182-192
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@apps/server-core/src/core/identity/password-recovery/service.ts` around lines 129 - 139, Update the PASSWORD_RESET_REQUESTED and PASSWORD_RESET_COMPLETED audit-event creation in the password-recovery service to propagate IdentityWorkflowContext request metadata (requestIpAddress, requestUserAgent, requestPath, and requestMethod) into each record. For unauthenticated forgotPassword flows, remove the target user’s actorId and actorName or represent the requester as anonymous, while preserving merged.id as the subject refId.apps/server-core/src/core/oauth2/grant-types/password.ts (1)
76-93: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick winReconsider
awaitonauditEventService?.record— it contradicts the fire-and-forget contract.The
IAuditEventService.recordinterface states: "Fire-and-forget-safe: never throws — a write failure must not fail the originating auth operation." Theawaithere couples every successful login's response latency to the audit DB write and risks a hung response if the write stalls. If fire-and-forget is the intent, drop theawaitand usevoidto make it explicit:- await this.auditEventService?.record({ + void this.auditEventService?.record({ scope: AuditEventScope.OAUTH2, name: AuditEventName.LOGIN,If the
awaitis intentional (e.g., compliance requires the audit row to be durable before the token is returned), update the interface comment to reflect that callers should await, and consider adding a timeout to prevent unbounded blocking.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@apps/server-core/src/core/oauth2/grant-types/password.ts` around lines 76 - 93, Update the successful-login audit call in the password grant flow to follow IAuditEventService.record’s fire-and-forget contract: remove await and explicitly discard the optional promise with void, while keeping metrics recording and the audit payload unchanged.apps/server-core/src/core/authentication/login-throttle/service.ts (1)
48-58: 🩺 Stability & Availability | 🔵 Trivial | 💤 Low valueConsider computing
retryAfterfrom the oldest in-window event.
retryAfteris always set to the fullwindowSeconds(900 s default), but the actual remaining lockout time depends on when the oldest countedLOGIN_FAILEDevent occurred. A user who hit the threshold 899 seconds ago is told to wait 900 more seconds. This is safe but degrades UX. IfcountRecentcan also return the timestamp of the oldest matching event,retryAftercould be computed aswindowSeconds - elapsed.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@apps/server-core/src/core/authentication/login-throttle/service.ts` around lines 48 - 58, The login throttle currently reports the full window as retryAfter regardless of event age. Update the repository query and surrounding login-throttle service flow to obtain the oldest matching LOGIN_FAILED event, then compute retryAfter as the remaining window duration based on its elapsed age, clamped to a valid nonnegative value; preserve the existing threshold check and LoginThrottledError behavior.apps/server-core/test/unit/http/controllers/workflows/token/grant-password-throttle.spec.ts (1)
68-74: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueTest 2 depends on test 1's accumulated state.
"locks out even the correct password within the window" relies on the 4
LOGIN_FAILEDevents created by the preceding test. If thisitblock is run in isolation (e.g.,vitest -t "locks out"), the throttle won't trip and the assertion will fail. Consider either adding a brief comment documenting the ordering dependency or creating the failures within this test's own setup.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@apps/server-core/test/unit/http/controllers/workflows/token/grant-password-throttle.spec.ts` around lines 68 - 74, Make the “locks out even the correct password within the window” test self-contained by creating the required four LOGIN_FAILED events in its own setup before calling passwordAttempt. Preserve the existing throttled-response assertions and avoid relying on state accumulated by a preceding test.apps/server-core/src/core/entities/audit-event/service.ts (1)
129-160: 🚀 Performance & Scalability | 🔵 Trivial | ⚖️ Poor tradeoffPost-filter pagination
totalis inaccurate, and per-row permission checks are N+1.In the
canReadAllbranch,totalstarts frommeta.total(the full result-set count) and is decremented only for rows denied on the current page. The returnedmeta.totaltherefore reportsfullTotal − deniedOnThisPagerather than the number of rows the actor can actually see, which breaks page-count math for API consumers once denials span multiple pages. Separately, callingpermissionEvaluator.evaluate(...)once per row is an N+1 pattern that scales poorly for large pages.Consider computing accessibility at the query layer (realm-reach filter pushed into
findMany) so both the rows andtotalstay consistent, instead of filtering after pagination.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@apps/server-core/src/core/entities/audit-event/service.ts` around lines 129 - 160, Update the canReadAll path around repository.findMany and the per-entity permission loop to push the actor’s realm accessibility filter into the query via resourceRealmMatch, allowing findMany to return only readable entities and an accurate total; remove the per-row permissionEvaluator.evaluate checks and post-pagination total decrements while preserving ownership handling.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@apps/server-core/src/adapters/http/adapters/oauth2/grant-types/password.ts`:
- Line 69: Update the request IP resolution around getRequestIP in the password
grant flow to use the application's configurable proxy-trust setting instead of
hardcoding trustProxy: true. Thread the setting into this flow from its existing
configuration source, preserving undefined handling for requests without an IP.
In `@apps/server-core/src/components/audit-event-cleaner/module.ts`:
- Around line 22-32: Update the component startup flow around component.start()
to await the audit cleaner’s initial execute() promise, or explicitly catch and
log its rejection before startup continues. Ensure the initial await execute()
in the cleaner’s execute function cannot become an unhandled rejection while
preserving scheduled cleanup behavior.
In `@apps/server-core/src/core/oauth2/end-session/service.ts`:
- Around line 168-180: Update the logout flow around sessionManager.revoke and
auditEventService.record so the audit write is fire-and-forget rather than
awaited, allowing the revoke path and logout response to proceed without waiting
on audit persistence. Preserve the existing audit payload and ensure any
resulting promise handling does not block logout.
---
Outside diff comments:
In `@apps/server-core/src/core/oauth2/grant-types/refresh-token.ts`:
- Around line 187-207: Move the awaited audit recording and metrics call from
before the security-critical operations to after token blocklisting and
this.sessionManager.revoke(sessionId) in the refresh replay handling flow. Keep
the existing audit payload and metrics behavior unchanged, while ensuring
session revocation is not gated by audit completion.
---
Nitpick comments:
In `@apps/server-core/src/app/modules/metrics/prom.ts`:
- Around line 20-35: Update getOrCreateCounter to verify that an existing metric
is an instance of Counter before returning it; only reuse the existing metric
when the runtime type matches, and otherwise proceed with the existing Counter
creation path.
In `@apps/server-core/src/core/authentication/login-throttle/service.ts`:
- Around line 48-58: The login throttle currently reports the full window as
retryAfter regardless of event age. Update the repository query and surrounding
login-throttle service flow to obtain the oldest matching LOGIN_FAILED event,
then compute retryAfter as the remaining window duration based on its elapsed
age, clamped to a valid nonnegative value; preserve the existing threshold check
and LoginThrottledError behavior.
In `@apps/server-core/src/core/entities/audit-event/service.ts`:
- Around line 129-160: Update the canReadAll path around repository.findMany and
the per-entity permission loop to push the actor’s realm accessibility filter
into the query via resourceRealmMatch, allowing findMany to return only readable
entities and an accurate total; remove the per-row permissionEvaluator.evaluate
checks and post-pagination total decrements while preserving ownership handling.
In `@apps/server-core/src/core/identity/password-recovery/service.ts`:
- Around line 129-139: Update the PASSWORD_RESET_REQUESTED and
PASSWORD_RESET_COMPLETED audit-event creation in the password-recovery service
to propagate IdentityWorkflowContext request metadata (requestIpAddress,
requestUserAgent, requestPath, and requestMethod) into each record. For
unauthenticated forgotPassword flows, remove the target user’s actorId and
actorName or represent the requester as anonymous, while preserving merged.id as
the subject refId.
In `@apps/server-core/src/core/oauth2/grant-types/password.ts`:
- Around line 76-93: Update the successful-login audit call in the password
grant flow to follow IAuditEventService.record’s fire-and-forget contract:
remove await and explicitly discard the optional promise with void, while
keeping metrics recording and the audit payload unchanged.
In
`@apps/server-core/test/unit/http/controllers/workflows/token/grant-password-throttle.spec.ts`:
- Around line 68-74: Make the “locks out even the correct password within the
window” test self-contained by creating the required four LOGIN_FAILED events in
its own setup before calling passwordAttempt. Preserve the existing
throttled-response assertions and avoid relying on state accumulated by a
preceding test.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID: df13021c-dbdb-427a-8560-b5fc62600f94
📒 Files selected for processing (97)
.agents/architecture.mdapps/server-core/package.jsonapps/server-core/src/adapters/database/data-source/options/module.tsapps/server-core/src/adapters/database/domains/audit-event/entity.tsapps/server-core/src/adapters/database/domains/audit-event/index.tsapps/server-core/src/adapters/database/domains/index.tsapps/server-core/src/adapters/database/migrations/mysql/1783769340000-Default.tsapps/server-core/src/adapters/database/migrations/postgres/1783769340000-Default.tsapps/server-core/src/adapters/http/adapters/oauth2/authorization/module.tsapps/server-core/src/adapters/http/adapters/oauth2/grant-types/password.tsapps/server-core/src/adapters/http/adapters/oauth2/grant-types/types.tsapps/server-core/src/adapters/http/controllers/entities/audit-event/index.tsapps/server-core/src/adapters/http/controllers/entities/audit-event/module.tsapps/server-core/src/adapters/http/controllers/entities/index.tsapps/server-core/src/adapters/http/controllers/workflows/authorize/module.tsapps/server-core/src/adapters/http/controllers/workflows/authorize/types.tsapps/server-core/src/adapters/http/controllers/workflows/token/module.tsapps/server-core/src/adapters/http/controllers/workflows/token/types.tsapps/server-core/src/app/modules/components/module.tsapps/server-core/src/app/modules/config/constants.tsapps/server-core/src/app/modules/config/normalize.tsapps/server-core/src/app/modules/config/read/env.tsapps/server-core/src/app/modules/config/types.tsapps/server-core/src/app/modules/config/validator.tsapps/server-core/src/app/modules/database/constants.tsapps/server-core/src/app/modules/database/module.tsapps/server-core/src/app/modules/database/repositories/audit-event/index.tsapps/server-core/src/app/modules/database/repositories/audit-event/repository.tsapps/server-core/src/app/modules/database/repositories/index.tsapps/server-core/src/app/modules/http/module.tsapps/server-core/src/app/modules/http/modules/controller.tsapps/server-core/src/app/modules/index.tsapps/server-core/src/app/modules/metrics/constants.tsapps/server-core/src/app/modules/metrics/index.tsapps/server-core/src/app/modules/metrics/prom.tsapps/server-core/src/components/audit-event-cleaner/index.tsapps/server-core/src/components/audit-event-cleaner/module.tsapps/server-core/src/components/index.tsapps/server-core/src/core/authentication/index.tsapps/server-core/src/core/authentication/login-throttle/index.tsapps/server-core/src/core/authentication/login-throttle/service.tsapps/server-core/src/core/authentication/login-throttle/types.tsapps/server-core/src/core/entities/audit-event/index.tsapps/server-core/src/core/entities/audit-event/sanitize.tsapps/server-core/src/core/entities/audit-event/service.tsapps/server-core/src/core/entities/audit-event/types.tsapps/server-core/src/core/entities/index.tsapps/server-core/src/core/identity/password-recovery/service.tsapps/server-core/src/core/identity/password-recovery/types.tsapps/server-core/src/core/identity/registration/service.tsapps/server-core/src/core/identity/registration/types.tsapps/server-core/src/core/index.tsapps/server-core/src/core/metrics/index.tsapps/server-core/src/core/metrics/noop.tsapps/server-core/src/core/metrics/types.tsapps/server-core/src/core/oauth2/authorization/module.tsapps/server-core/src/core/oauth2/authorization/types.tsapps/server-core/src/core/oauth2/end-session/service.tsapps/server-core/src/core/oauth2/end-session/types.tsapps/server-core/src/core/oauth2/grant-types/password.tsapps/server-core/src/core/oauth2/grant-types/refresh-token.tsapps/server-core/src/core/oauth2/grant-types/types.tsapps/server-core/test/unit/config/index.spec.tsapps/server-core/test/unit/core/authentication/login-throttle/service.spec.tsapps/server-core/test/unit/core/entities/audit-event/fake-repository.tsapps/server-core/test/unit/core/entities/audit-event/sanitize.spec.tsapps/server-core/test/unit/core/entities/audit-event/service.spec.tsapps/server-core/test/unit/core/helpers/fake-audit-event-service.tsapps/server-core/test/unit/core/helpers/fake-auth-flow-metrics.tsapps/server-core/test/unit/core/helpers/index.tsapps/server-core/test/unit/core/oauth2/grant-types/refresh-token.spec.tsapps/server-core/test/unit/http/controllers/entities/audit-event-realm-isolation.spec.tsapps/server-core/test/unit/http/controllers/entities/audit-event.spec.tsapps/server-core/test/unit/http/controllers/workflows/token/grant-password-throttle.spec.tsapps/server-core/test/unit/http/middleware/metrics.spec.tsdocs/src/guide/deployment/configuration-server-core.mdpackages/core-http-kit/src/client/module.tspackages/core-http-kit/src/client/type.tspackages/core-http-kit/src/domains/entities/audit-event/index.tspackages/core-http-kit/src/domains/entities/audit-event/module.tspackages/core-http-kit/src/domains/entities/audit-event/types.tspackages/core-http-kit/src/domains/entities/index.tspackages/core-kit/src/domains/attempt-login/entity.tspackages/core-kit/src/domains/audit-event/constants.tspackages/core-kit/src/domains/audit-event/entity.tspackages/core-kit/src/domains/audit-event/index.tspackages/core-kit/src/domains/index.tspackages/core-kit/src/domains/permission/constants.tspackages/errors/src/built-in/check.tspackages/errors/src/built-in/index.tspackages/errors/src/built-in/login-throttled.tspackages/errors/src/constants.tspackages/errors/src/status.tspackages/i18n/src/catalogs/de/error.tspackages/i18n/src/catalogs/en/error.tspackages/i18n/src/catalogs/es/error.tspackages/i18n/src/catalogs/fr/error.ts
💤 Files with no reviewable changes (1)
- packages/core-kit/src/domains/attempt-login/entity.ts
| } | ||
|
|
||
| const user = await this.authenticator.authenticate(username, password, realm.id); | ||
| const ipAddress = getRequestIP(event, { trustProxy: true }) ?? undefined; |
There was a problem hiding this comment.
🔒 Security & Privacy | 🟡 Minor | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Look for an existing trust-proxy config the grant should honor instead of hardcoding true.
rg -nP -C2 'trustProxy|trust_proxy|TRUST_PROXY' --type=ts
# Compare with other getRequestIP call sites in the codebase.
rg -nP -C2 'getRequestIP\s*\(' --type=tsRepository: authup/authup
Length of output: 151
🏁 Script executed:
#!/bin/bash
set -euo pipefail
# Inspect the target file around the reported line.
sed -n '1,180p' apps/server-core/src/adapters/http/adapters/oauth2/grant-types/password.ts
# Find the base class and any related config wiring for the password grant.
rg -n --hidden --glob '!**/node_modules/**' --glob '!**/dist/**' --glob '!**/build/**' \
'class\s+PasswordGrantType|extends\s+PasswordGrantType|trustProxy|getRequestIP\(' \
apps/server-core/src
# Locate any server-level proxy-trust configuration in the repository.
rg -n --hidden --glob '!**/node_modules/**' --glob '!**/dist/**' --glob '!**/build/**' \
'trustProxy|trust_proxy|TRUST_PROXY|proxy.*trust|forwarded.*for' \
.Repository: authup/authup
Length of output: 10808
🏁 Script executed:
#!/bin/bash
set -euo pipefail
# Inspect the deployment guidance around proxy headers and any note about trusted proxies.
sed -n '1,120p' docs/src/guide/deployment/nginx.md
# Look for server deployment/configuration that indicates the app is expected to sit behind a reverse proxy.
rg -n --hidden --glob '!**/node_modules/**' --glob '!**/dist/**' --glob '!**/build/**' \
'publicUrl|reverse proxy|nginx|proxy_set_header|X-Forwarded-For|trustProxy|trust proxy' \
docs apps/server-core/src .agents
# Check the OAuth2 grant base for inherited audit/metrics fields mentioned in the original note.
sed -n '1,220p' apps/server-core/src/core/oauth2/grant-types/password.tsRepository: authup/authup
Length of output: 17135
🏁 Script executed:
#!/bin/bash
set -euo pipefail
# Inspect server-core configuration docs for deployment assumptions around proxies.
sed -n '1,90p' docs/src/guide/deployment/configuration-server-core.md
# Inspect where request IP is used in the OAuth2 grant flow to see whether this is a local one-off or a broader convention.
rg -n --hidden --glob '!**/node_modules/**' --glob '!**/dist/**' --glob '!**/build/**' \
'requestIpAddress|ipAddress: getRequestIP|getRequestIP\(event, \{ trustProxy: true \}\)' \
apps/server-core/src/adapters/http/adapters/oauth2/grant-types apps/server-core/src/adapters/http/controllers/entities/identity-provider/module.tsRepository: authup/authup
Length of output: 4450
Make trustProxy configurable
This trusts X-Forwarded-For unconditionally, so a direct deployment can spoof the IP used for throttling and audit records. Thread the proxy-trust setting through here instead of hardcoding true.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@apps/server-core/src/adapters/http/adapters/oauth2/grant-types/password.ts`
at line 69, Update the request IP resolution around getRequestIP in the password
grant flow to use the application's configurable proxy-trust setting instead of
hardcoding trustProxy: true. Thread the setting into this flow from its existing
configuration source, preserving undefined handling for requests without an IP.
There was a problem hiding this comment.
Valid concern, but pre-existing and repo-wide: every getRequestIP call site (8, all grant adapters + the identity-provider controller) hardcodes trustProxy: true — the session/session-token ip_address inventory shares the same trust. Threading a config key only through this one site would be inconsistent, so this is tracked as #3230 (config key TRUST_PROXY, default true, threaded through all call sites). This PR adds the deployment-docs warning on the throttle config in the meantime (f91c225).
There was a problem hiding this comment.
@tada5hi, that makes sense — treating this consistently across all 8 getRequestIP call sites via a dedicated TRUST_PROXY config key (#3230) is the right approach rather than a one-off fix here. Thanks for adding the deployment-docs warning in the meantime as an interim mitigation. Deferring to the tracked issue.
|
@coderabbitai pause |
✅ Action performedReviews paused. |
…he process Review follow-up (#3229): the cleaner components' start() is invoked fire-and-forget, so a rejected initial sweep became an unhandled rejection (fatal on modern node). Both cleaners now catch + log per sweep tick (next tick retries), the components module catches start() rejections for every component, and the throttle config docs note the X-Forwarded-For trust assumption.
Maintainer review follow-ups on #3229, pre-release renames (no compatibility surface exists yet): - AuditEvent -> Event across core-kit/server-core/core-http-kit (EventName/EventScope/EventRefType, EventService, EventController, EventRepositoryAdapter, EventAPI, client.event) - the domain is the general security event store; the CRUD-subscriber bridge lands in the same table later, mirroring hub's EntityEventHandler. - table audit_events -> auth_events (auth_* table convention), permission audit_read -> event_read (hub's permission vocabulary), routes /audit-events -> /events, config auditLog* -> eventLog* (EVENT_LOG_* env). - data column: simple-json -> text with the @authup/kit serialize/deserialize transformer (hub pattern), null-guarded on write since serialize(null) would persist the string 'null'. - expiring boolean column re-added (indexed, default false, stamped from the retention config); the sweeper predicate becomes hub's cleaner shape (expiring = true AND expires_at < now).
Every create/update/delete already published on the domain-event bus by the entity subscribers now also lands as an auth_events row (plan 057 stage 2, mirroring hub's EntityEventHandler): scope 'entity', name created/updated/deleted, ref_type/ref_id, realm-gated reads. Hardened beyond the hub design: the pre-mutation snapshot rides the publish CONTEXT (dataPrevious) - never the shared realtime wire payload; actor + request attribution comes from an AsyncLocalStorage request event context mounted after the authorization middleware (non-HTTP writes attribute as system/null); the scalar diff excludes secret-shaped keys (password/secret/hash/token/credential) and timestamp columns, and the write-boundary sanitizer re-validates the diff shape; created and deleted rows carry no column dumps. Entity rows self-prune via eventLogEntityRetentionDays (default 7 days); the bridge is gated by eventLogEntityEnabled. The hub<->authup mapping and the upstream-to-hub improvement candidates are recorded in .agents/references/privateaim-hub.md.
Events pages in client-web (list with typed VCTable columns, name search, pagination; hub-style detail page with general/actor/request cards and the pretty-printed data dict), a kit AEvents collection mirroring ASessions, an EVENT_READ-gated nav entry with route-meta enforcement on every matched record, EntityType.EVENT for the collection manager (inert server-side - no subscriber), and entity/ field/common i18n keys in all four locales (parity-tested).
EventName multi-word values follow the hub camelCase vocabulary (loginFailed, refreshReplayDetected, accountActivated, passwordResetRequested/Completed - stored values, safe pre-release), the authorize reason value becomes autoConsent, and the sanitizer's manual object checks collapse onto isObject from @authup/kit.
|
@coderabbitai resume |
✅ Action performedReviews resumed. |
|
@coderabbitai full review |
✅ Action performedFull review finished. Your plan includes PR reviews subject to rate limits. More reviews will be available in 59 minutes. |
There was a problem hiding this comment.
Actionable comments posted: 5
🧹 Nitpick comments (4)
apps/server-core/test/unit/core/helpers/fake-event-service.ts (1)
22-35: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueConsider accepting and storing
query/actor/idarguments for test assertions.
getMany()andgetOne()omit thequery,actor, andidparameters defined inIEventService. While TypeScript permits this (fewer-parameter functions are assignable to wider signatures), tests using this fake cannot verify that the correct query, actor context, or entity ID was passed — limiting the fake's usefulness for behavioral assertions.♻️ Optional refactor: capture call arguments
-async getMany(): Promise<EntityRepositoryFindManyResult<Event>> { +async getMany(query?: Record<string, any>, actor?: ActorContext): Promise<EntityRepositoryFindManyResult<Event>> { + this.getManyCalls.push({ query, actor }); return { data: [], meta: { total: 0, limit: 50, offset: 0, }, }; } -async getOne(): Promise<Event> { +async getOne(id?: string, actor?: ActorContext): Promise<Event> { + this.getOneCalls.push({ id, actor }); throw new Error('not implemented'); }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@apps/server-core/test/unit/core/helpers/fake-event-service.ts` around lines 22 - 35, Update the fake event service methods getMany and getOne to accept the query, actor, and id parameters required by IEventService, and store those arguments on the fake so tests can inspect the calls. Preserve the existing return values and unimplemented error behavior while exposing the captured inputs for assertions.apps/server-core/test/unit/core/entities/event/entity-event-handler.spec.ts (1)
138-163: 🎯 Functional Correctness | 🔵 Trivial | 💤 Low valueConsider adding a test for undefined
ctx.content.datawith an updated event.There's no test covering the case where
ctx.content.datais undefined and the event isupdatedwith adataPrevioussnapshot. This is the edge case flagged inentity-event-handler.tswherebuildEntityDiffcould throw onundefined. Adding a test would clarify the expected behavior and guard against regressions.🧪 Suggested test
it('records without diff when data is undefined for an updated event', async () => { await buildHandler().handle(buildPublishContext({ content: { event: 'updated', data: undefined as any, }, dataPrevious: { id: entityId, description: 'before' }, })); expect(eventService.recordCalls).toHaveLength(1); expect(eventService.recordCalls[0].data).toBeNull(); });🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@apps/server-core/test/unit/core/entities/event/entity-event-handler.spec.ts` around lines 138 - 163, Add a unit test alongside the updated-event cases in the handler spec covering an updated event with undefined content.data and a populated dataPrevious snapshot. Assert one event is recorded and its data is null, using buildHandler, buildPublishContext, and eventService.recordCalls.apps/server-core/src/core/entities/event/entity-event-handler.ts (1)
94-97: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winLog errors in the catch block for audit observability.
The silent catch is intentional for failure isolation, but a security audit system that silently drops records with no trace makes debugging impossible. Consider logging the error so operators can detect when audit records are being lost.
♻️ Proposed fix
- } catch { - // record() never throws, but the bridge itself must also never - // fail the originating publish. + } catch (e) { + // record() never throws, but the bridge itself must also never + // fail the originating publish. Log for observability so silent + // audit-record loss is detectable by operators. + console.error('[EntityEventHandler] failed to record audit event:', e); }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@apps/server-core/src/core/entities/event/entity-event-handler.ts` around lines 94 - 97, The catch block around the audit bridge must retain failure isolation while recording errors for audit observability. Update the catch associated with record() in the event handler to log the caught error with sufficient context, without rethrowing or changing the originating publish flow.apps/server-core/src/adapters/database/migrations/mysql/1783769340000-Default.ts (1)
42-51: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick winConsider a composite index for the retention sweep instead of separate single-column indexes.
IDX_auth_events_expiringandIDX_auth_events_expires_atare separate; the event-cleaner's retention sweep almost certainly filtersWHERE expiring = 1 AND expires_at < ?. A composite(expiring, expires_at)index would serve that query more efficiently than two low-selectivity single-column indexes, and reduces per-insert index-maintenance overhead on this high-frequency append-only table.♻️ Proposed composite index
- INDEX \`IDX_auth_events_expiring\` (\`expiring\`), - INDEX \`IDX_auth_events_expires_at\` (\`expires_at\`), + INDEX \`IDX_auth_events_expiring_expires_at\` (\`expiring\`, \`expires_at\`),🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@apps/server-core/src/adapters/database/migrations/mysql/1783769340000-Default.ts` around lines 42 - 51, Update the auth_events index definitions in the migration to replace the separate IDX_auth_events_expiring and IDX_auth_events_expires_at indexes with one composite index covering expiring and expires_at in that order. Preserve the existing index naming conventions and remove both redundant single-column definitions.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@apps/client-web/pages/events/`[id]/index.vue:
- Around line 106-113: Update the catch block in the event page setup around the
event fetch to return navigateTo({ path: '/events' }) directly, removing the
await and createError({}) throw so the failed load redirects cleanly without
triggering an empty fatal error.
In `@apps/server-core/src/adapters/http/request/event-context.ts`:
- Line 51: Make the trustProxy option used by getRequestIP in the request
context configurable rather than hardcoded to true. Reuse the existing server
configuration mechanism and ensure requestIpAddress continues to return null
when no address is available, while deployments without trusted proxies do not
accept spoofed forwarded addresses.
In `@apps/server-core/src/app/modules/components/module.ts`:
- Around line 41-45: Update the event cleaner condition in the module
initialization flow to start when event logging is enabled and either
eventLogRetentionDays or eventLogEntityRetentionDays is greater than zero. Keep
the existing createEventCleanerComponent(dataSource, logger) behavior unchanged.
In `@apps/server-core/src/components/oauth2-cleaner/module.ts`:
- Around line 39-41: Update the catch block in the expired-session sweep to
capture the thrown error and pass its details to logger?.warn while preserving
the existing swallowed-error behavior and non-crashing flow.
In `@apps/server-core/src/core/entities/event/entity-event-handler.ts`:
- Around line 71-76: Guard the buildEntityDiff call in the UPDATED event
handling branch so it only runs when ctx.content.data is present, alongside the
existing ctx.dataPrevious check. When next data is absent, skip creating the
diff payload while preserving the current behavior for valid data.
---
Nitpick comments:
In
`@apps/server-core/src/adapters/database/migrations/mysql/1783769340000-Default.ts`:
- Around line 42-51: Update the auth_events index definitions in the migration
to replace the separate IDX_auth_events_expiring and IDX_auth_events_expires_at
indexes with one composite index covering expiring and expires_at in that order.
Preserve the existing index naming conventions and remove both redundant
single-column definitions.
In `@apps/server-core/src/core/entities/event/entity-event-handler.ts`:
- Around line 94-97: The catch block around the audit bridge must retain failure
isolation while recording errors for audit observability. Update the catch
associated with record() in the event handler to log the caught error with
sufficient context, without rethrowing or changing the originating publish flow.
In `@apps/server-core/test/unit/core/entities/event/entity-event-handler.spec.ts`:
- Around line 138-163: Add a unit test alongside the updated-event cases in the
handler spec covering an updated event with undefined content.data and a
populated dataPrevious snapshot. Assert one event is recorded and its data is
null, using buildHandler, buildPublishContext, and eventService.recordCalls.
In `@apps/server-core/test/unit/core/helpers/fake-event-service.ts`:
- Around line 22-35: Update the fake event service methods getMany and getOne to
accept the query, actor, and id parameters required by IEventService, and store
those arguments on the fake so tests can inspect the calls. Preserve the
existing return values and unimplemented error behavior while exposing the
captured inputs for assertions.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID: ea69c995-4e3a-4e5d-b86a-2590b83ed124
⛔ Files ignored due to path filters (1)
package-lock.jsonis excluded by!**/package-lock.json
📒 Files selected for processing (105)
.agents/architecture.md.agents/references/authentik.md.agents/references/privateaim-hub.mdapps/client-web/config/layout/contants.tsapps/client-web/pages/events/[id]/index.vueapps/client-web/pages/events/index.vueapps/client-web/pages/events/index/index.vueapps/server-core/src/adapters/database/data-source/options/module.tsapps/server-core/src/adapters/database/domains/event/entity.tsapps/server-core/src/adapters/database/domains/event/index.tsapps/server-core/src/adapters/database/domains/index.tsapps/server-core/src/adapters/database/migrations/mysql/1783769340000-Default.tsapps/server-core/src/adapters/database/migrations/postgres/1783769340000-Default.tsapps/server-core/src/adapters/database/subscriber/module.tsapps/server-core/src/adapters/http/adapters/oauth2/grant-types/password.tsapps/server-core/src/adapters/http/controllers/entities/event/index.tsapps/server-core/src/adapters/http/controllers/entities/event/module.tsapps/server-core/src/adapters/http/controllers/entities/index.tsapps/server-core/src/adapters/http/controllers/workflows/authorize/module.tsapps/server-core/src/adapters/http/controllers/workflows/authorize/types.tsapps/server-core/src/adapters/http/controllers/workflows/token/module.tsapps/server-core/src/adapters/http/controllers/workflows/token/types.tsapps/server-core/src/adapters/http/request/event-context.tsapps/server-core/src/adapters/http/request/index.tsapps/server-core/src/app/modules/components/module.tsapps/server-core/src/app/modules/config/constants.tsapps/server-core/src/app/modules/config/normalize.tsapps/server-core/src/app/modules/config/read/env.tsapps/server-core/src/app/modules/config/types.tsapps/server-core/src/app/modules/config/validator.tsapps/server-core/src/app/modules/database/constants.tsapps/server-core/src/app/modules/database/module.tsapps/server-core/src/app/modules/database/repositories/event/index.tsapps/server-core/src/app/modules/database/repositories/event/repository.tsapps/server-core/src/app/modules/database/repositories/index.tsapps/server-core/src/app/modules/http/modules/controller.tsapps/server-core/src/app/modules/http/modules/middleware.tsapps/server-core/src/components/event-cleaner/index.tsapps/server-core/src/components/event-cleaner/module.tsapps/server-core/src/components/index.tsapps/server-core/src/components/oauth2-cleaner/module.tsapps/server-core/src/core/authentication/login-throttle/service.tsapps/server-core/src/core/authentication/login-throttle/types.tsapps/server-core/src/core/entities/event/diff.tsapps/server-core/src/core/entities/event/entity-event-handler.tsapps/server-core/src/core/entities/event/index.tsapps/server-core/src/core/entities/event/sanitize.tsapps/server-core/src/core/entities/event/service.tsapps/server-core/src/core/entities/event/types.tsapps/server-core/src/core/entities/index.tsapps/server-core/src/core/identity/password-recovery/service.tsapps/server-core/src/core/identity/password-recovery/types.tsapps/server-core/src/core/identity/registration/service.tsapps/server-core/src/core/identity/registration/types.tsapps/server-core/src/core/oauth2/authorization/module.tsapps/server-core/src/core/oauth2/authorization/types.tsapps/server-core/src/core/oauth2/end-session/service.tsapps/server-core/src/core/oauth2/end-session/types.tsapps/server-core/src/core/oauth2/grant-types/password.tsapps/server-core/src/core/oauth2/grant-types/refresh-token.tsapps/server-core/src/core/oauth2/grant-types/types.tsapps/server-core/test/unit/config/index.spec.tsapps/server-core/test/unit/core/authentication/login-throttle/service.spec.tsapps/server-core/test/unit/core/entities/event/diff.spec.tsapps/server-core/test/unit/core/entities/event/entity-event-handler.spec.tsapps/server-core/test/unit/core/entities/event/fake-repository.tsapps/server-core/test/unit/core/entities/event/sanitize.spec.tsapps/server-core/test/unit/core/entities/event/service.spec.tsapps/server-core/test/unit/core/helpers/fake-event-service.tsapps/server-core/test/unit/core/helpers/index.tsapps/server-core/test/unit/core/oauth2/grant-types/refresh-token.spec.tsapps/server-core/test/unit/http/controllers/entities/event-entity-bridge.spec.tsapps/server-core/test/unit/http/controllers/entities/event-realm-isolation.spec.tsapps/server-core/test/unit/http/controllers/entities/event.spec.tsdocs/src/guide/deployment/configuration-server-core.mdpackages/client-web-kit/src/components/entities/event/AEvents.tspackages/client-web-kit/src/components/entities/event/index.tspackages/client-web-kit/src/components/entities/index.tspackages/core-http-kit/src/client/module.tspackages/core-http-kit/src/client/type.tspackages/core-http-kit/src/domains/entities/event/index.tspackages/core-http-kit/src/domains/entities/event/module.tspackages/core-http-kit/src/domains/entities/event/types.tspackages/core-http-kit/src/domains/entities/index.tspackages/core-kit/src/domains/contstants.tspackages/core-kit/src/domains/event/constants.tspackages/core-kit/src/domains/event/entity.tspackages/core-kit/src/domains/event/index.tspackages/core-kit/src/domains/index.tspackages/core-kit/src/domains/permission/constants.tspackages/core-kit/src/domains/types.tspackages/i18n/src/catalogs/de/common.tspackages/i18n/src/catalogs/de/entity.tspackages/i18n/src/catalogs/de/field.tspackages/i18n/src/catalogs/en/common.tspackages/i18n/src/catalogs/en/entity.tspackages/i18n/src/catalogs/en/field.tspackages/i18n/src/catalogs/es/common.tspackages/i18n/src/catalogs/es/entity.tspackages/i18n/src/catalogs/es/field.tspackages/i18n/src/catalogs/fr/common.tspackages/i18n/src/catalogs/fr/entity.tspackages/i18n/src/catalogs/fr/field.tspackages/i18n/src/constants.tspackages/server-kit/src/domain-event/types.ts
✅ Files skipped from review due to trivial changes (13)
- packages/i18n/src/catalogs/es/entity.ts
- packages/i18n/src/catalogs/fr/entity.ts
- packages/client-web-kit/src/components/entities/index.ts
- packages/i18n/src/catalogs/de/entity.ts
- apps/server-core/test/unit/http/controllers/entities/event-realm-isolation.spec.ts
- apps/server-core/src/core/entities/event/index.ts
- apps/server-core/src/app/modules/database/repositories/event/index.ts
- packages/core-kit/src/domains/event/constants.ts
- packages/i18n/src/catalogs/es/common.ts
- packages/client-web-kit/src/components/entities/event/index.ts
- .agents/references/authentik.md
- apps/server-core/src/adapters/database/domains/event/index.ts
- .agents/architecture.md
🚧 Files skipped from review as they are similar to previous changes (11)
- apps/server-core/src/adapters/http/controllers/entities/index.ts
- apps/server-core/src/app/modules/database/repositories/index.ts
- apps/server-core/test/unit/core/helpers/index.ts
- apps/server-core/test/unit/config/index.spec.ts
- apps/server-core/src/core/authentication/login-throttle/types.ts
- apps/server-core/src/core/authentication/login-throttle/service.ts
- apps/server-core/src/adapters/http/controllers/workflows/token/module.ts
- apps/server-core/test/unit/core/authentication/login-throttle/service.spec.ts
- apps/server-core/test/unit/core/oauth2/grant-types/refresh-token.spec.ts
- apps/server-core/src/core/oauth2/authorization/module.ts
- apps/server-core/src/adapters/http/adapters/oauth2/grant-types/password.ts
- the event cleaner now also starts when only the entity retention is configured (eventLogRetentionDays 0 + eventLogEntityRetentionDays > 0 previously stamped expires_at on entity rows that were never swept) - the entity-event handler guards the diff build against a data-less update publish (Object.keys(undefined) would skip the whole row via the outer catch) - both cleaners log the swallowed sweep error for debuggability
Overview
Roadmap wave 2: the security event system in one PR — plan 057 (persisted event log, both stages: explicit security events + the entity-CRUD bridge), plan 053 (failed-login throttle), plan 058 Part 2 (auth-flow metrics counters), and the admin UI. One shared emit infrastructure, one table (
auth_events), four consumers.Design provenance
The system was designed from a deep investigation of PrivateAIM/hub's
@privateaim/telemetry-kit/server-telemetryevent system (itself Authentik-derived) and adopts its shape 1:1 —Eventdomain,(scope, name)verb pair (camelCase vocabulary per hub convention:loginFailed,refreshReplayDetected, …),ref_type/ref_idtarget reference, denormalizedactor_type/actor_id/actor_namesnapshot (survives actor deletion),request_*context group,expiring+ per-rowexpires_atretention,dataastextbehind the@authup/kitserialize/deserializetransformer,EVENT_READpermission,GET /events,client.event— while fixing what hub's own implementation lacks:EventName/EventScopeenumsupdated_at, deadupdate()client route)updated_atserialize(null)persists the string'null'varchar(15)IPv4-only IP column (::1rewrite hack)varchar(45)realm_id(the primary read filter) unindexed; 14 indexes elsewhererealm_idindexed; 10 justified indexes totalWEEK_IN_MSretentionThe full hub↔authup mapping + the back-port checklist ship in
.agents/references/privateaim-hub.md, tracked upstream as PrivateAIM/hub#1745.What ships
auth_events(fresh dual-dialect migration1783769340000): no FKs by design — rows survive deletion of everything they reference.EventService.record()is fire-and-forget-safe (a write failure logs, never fails the originating operation), stampsexpiring/expires_atfrom the retention config, and emits a structured logger line even with persistence off — free SIEM/Loki forwarding.login,loginFailed(canonicalized attempted identifier inactor_name,actor_idnull — the documented PII-posture call; it is the throttle key),authorize(data.reason: autoConsent|consent),logout(end-session hint revoke),refreshReplayDetected,register,accountActivated,passwordResetRequested/Completed. No per-token rows —auth_session_tokensalready inventories issuance.scope: entity,ref_type/ref_id, realm-gated) via anEntityEventHandleron the existing domain-event bus — the pre-mutation snapshot rides the publish context (never the shared realtime wire payload); actor + request attribution via anAsyncLocalStoragerequest-event-context mounted after the authorization middleware (non-HTTP writes = system/null actor); scalar diffs exclude secret-shaped keys (password|secret|hash|token|credential) and*_atcolumns and are re-validated at the write boundary; created/deleted rows carry no column dumps; entity rows self-prune (EVENT_LOG_ENTITY_RETENTION_DAYS, default 7d; gated byEVENT_LOG_ENTITY_ENABLED).GET /events(+ realm mount), read-only,EVENT_READ-gated with the session-service shape (self-scope fallback, per-row realm-reach drops, force-selected gate columns — plan-039 discipline, red-green-verified)./eventspages in client-web (typedVCTablelist with name search + pagination; hub-style detail page with General/Actor/Request cards + pretty-printeddata), kit<AEvents>collection,EVENT_READ-gated nav, entity/field i18n in all four locales.expiring = true AND expires_at < now); rejection-proof startup (both cleaners catch per tick; the components module catches everystart()).loginFailedrows counted per (identifier, ip) pair over indexed columns — never identifier alone (account-lockout-DoS mitigation; no derivable IP → fail open). HTTP 429login_attempt_throttledwithretryAfter; i18n in four locales; enabling it without the event log fails loud at boot. DeadAttemptLogintype deleted. X-Forwarded-For trust documented; repo-wideTRUST_PROXYconfigurability tracked in Make getRequestIP proxy trust configurable (trustProxy is hardcoded) #3230.authup_login_total{result},authup_token_grant_total{grant_type}(successes only),authup_authorize_total{outcome}(deniedreserved until plan 052),authup_refresh_replay_total. Noop whenmiddlewarePrometheusis off. Bounded label sets only.EVENT_LOG_ENABLED,EVENT_LOG_RETENTION_DAYS,EVENT_LOG_ENTITY_ENABLED,EVENT_LOG_ENTITY_RETENTION_DAYS,LOGIN_ATTEMPT_THROTTLE_ENABLED,LOGIN_ATTEMPT_THRESHOLD,LOGIN_ATTEMPT_WINDOW— all in the deployment reference; agent docs gain a Security Event Log section.Verification
/metricsscrape, config fail-loud, replay emit, diff builder, bridge handler, end-to-end bridge attribution incl. secret-free client-secret-rotation diff).nuxi typecheck+ full nuxt build; core-kit/server-kit/core-http-kit rebuilt;check:types+ eslint clean; migrations verified by thetests-migrationsround-trip in CI.Notes for reviewers
OAuth2Authorization.authorize()split into a thin emit wrapper +authorizeInner()(logic verbatim); the verifier's resolvedclientis threaded in (built_in→ consent reason).retryAfterat top level (standardAuthupError.toJSON()data spread).TRUST_PROXYconfigurability), Harden the telemetry event system (back-port authup's event-log improvements) PrivateAIM/hub#1745 (hub back-port of the hardening list).Summary by CodeRabbit