chore: migrate audit DDP methods to /v1/audit.* REST endpoints (EE) - #40736
Conversation
|
Looks like this PR is not ready to merge, because of the following issues:
Please fix the issues and try again If you have any trouble, please check the PR guidelines |
🦋 Changeset detectedLatest commit: 29ff63a The changes in this PR will be included in the next version bump. This PR includes changesets to release 3 packages
Not sure what this means? Click here to learn what changesets are. Click here if you're a maintainer who wants to add another changeset to this PR |
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
WalkthroughAudit retrieval now uses shared server functions behind new ChangesAudit REST endpoint migration
Estimated code review effort: 4 (Complex) | ~60 minutes Suggested labels: Suggested reviewers: Sequence Diagram(s)sequenceDiagram
participant AuditUI
participant AuditAPI
participant AuditFunctions
participant Messages
participant AuditLog
AuditUI->>AuditAPI: Request audit endpoint with ISO dates
AuditAPI->>AuditFunctions: Invoke audit retrieval function
AuditFunctions->>Messages: Query matching messages
AuditFunctions->>AuditLog: Record audit operation
AuditAPI-->>AuditUI: Return auditions or messages
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
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 |
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## develop #40736 +/- ##
===========================================
- Coverage 68.66% 68.66% -0.01%
===========================================
Files 4138 4138
Lines 159082 159082
Branches 27942 27953 +11
===========================================
- Hits 109238 109233 -5
- Misses 44696 44701 +5
Partials 5148 5148
Flags with carried forward coverage won't be shown. Click here to find out more. 🚀 New features to boost your workflow:
|
There was a problem hiding this comment.
Actionable comments posted: 6
🤖 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/meteor/client/views/audit/components/AuditLogTable.tsx`:
- Around line 27-33: The audit log query is still force-casting the REST
response into IAuditLog instead of converting it to the client shape. Update
AuditLogTable’s useEndpoint/queryFn path to deserialize the payload before
caching it, mapping REST fields like ts and date values into the IAuditLog
structure the table and AuditLogEntry expect, similar to how useAuditMutation
handles REST-to-client conversion.
In `@apps/meteor/client/views/audit/hooks/useAuditMutation.ts`:
- Around line 19-27: The `useAuditMutation` branch for `type === 'l'` is
ignoring the `AuditFields` filter values by hardcoding `visitor` and `agent` to
empty strings. Update the `getOmnichannelAuditMessages` call to forward the
actual `visitor` and `agent` values from the current audit filters, using the
existing `AuditFields` data in `useAuditMutation` so omnichannel searches stay
scoped correctly.
In `@apps/meteor/ee/server/lib/audit/functions.ts`:
- Around line 44-46: The shared audit helper in functions.ts is emitting a stale
DDP-only deprecation warning from logic now used by REST routes. Remove the
console.warn from the type === 'l' branch in the shared function and keep
deprecation logging only in the DDP wrapper path that calls this helper, so REST
calls do not report a misleading “method” warning or 4.0.0 removal target.
- Around line 175-177: The omnichannel audit path in auditGetMessagesMethod is
missing the same livechat room restriction filter used elsewhere, so apply
livechat.applyRoomRestrictions before the
LivechatRooms.findByVisitorIdAndAgentId lookup. Update the audit messages flow
in functions.ts so the visitor/agent room search is constrained consistently
with the standard audit path, using the existing auditGetMessagesMethod and
livechat.applyRoomRestrictions symbols as the insertion point.
- Around line 178-182: The `findByVisitorIdAndAgentId`/audit query path should
guard the no-room case before building the Mongo filter. In the `rids`/`query`
निर्माण, return or throw early when `rooms` is empty so `rid: { $in: undefined
}` is never created. Keep the fix localized around the `rids` assignment and the
`query: Filter<IMessage>` construction.
In `@apps/meteor/ee/server/lib/audit/methods.ts`:
- Around line 37-53: The audit DDP methods currently validate only the date
fields, so untyped payloads can still reach the shared audit query builders with
missing users, type, visitor, or agent data. Update the method boundaries in
auditGetOmnichannelMessages, auditGetMessages, and auditGetAuditions to validate
the full params object before calling auditGetOmnichannelMessagesMethod,
auditGetMessagesMethod, and auditGetAuditionsMethod. Keep the existing date
checks, but add validation for all required fields in each request shape so
invalid input is rejected early.
🪄 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: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 19e5eb95-46be-4ddd-908c-daa3adeb7a77
📒 Files selected for processing (7)
.changeset/ddp-migrate-batch6-audit-callers.md.changeset/rest-audit-endpoints.mdapps/meteor/client/views/audit/components/AuditLogTable.tsxapps/meteor/client/views/audit/hooks/useAuditMutation.tsapps/meteor/ee/server/api/audit.tsapps/meteor/ee/server/lib/audit/functions.tsapps/meteor/ee/server/lib/audit/methods.ts
📜 Review details
⏰ Context from checks skipped due to timeout. (7)
- GitHub Check: cubic · AI code reviewer
- GitHub Check: Hacktron Security Check
- GitHub Check: 🔨 Test Unit / Unit Tests
- GitHub Check: 🔎 Code Check / Code Lint
- GitHub Check: 🔎 Code Check / TypeScript
- GitHub Check: 🔨 Test Storybook / Test Storybook
- GitHub Check: 📦 Meteor Build (coverage)
🧰 Additional context used
📓 Path-based instructions (1)
**/*.{ts,tsx,js}
📄 CodeRabbit inference engine (.cursor/rules/playwright.mdc)
**/*.{ts,tsx,js}: Write concise, technical TypeScript/JavaScript with accurate typing in Playwright tests
Avoid code comments in the implementation
Files:
apps/meteor/client/views/audit/components/AuditLogTable.tsxapps/meteor/client/views/audit/hooks/useAuditMutation.tsapps/meteor/ee/server/lib/audit/functions.tsapps/meteor/ee/server/lib/audit/methods.tsapps/meteor/ee/server/api/audit.ts
🧠 Learnings (7)
📚 Learning: 2026-03-16T21:50:37.589Z
Learnt from: amitb0ra
Repo: RocketChat/Rocket.Chat PR: 39676
File: .changeset/migrate-users-register-openapi.md:3-3
Timestamp: 2026-03-16T21:50:37.589Z
Learning: For changes related to OpenAPI migrations in Rocket.Chat/OpenAPI, when removing endpoint types and validators from rocket.chat/rest-typings (e.g., UserRegisterParamsPOST, /v1/users.register) document this as a minor changeset (not breaking) per RocketChat/Rocket.Chat-Open-API#150 Rule 7. Note that the endpoint type is re-exposed via a module augmentation .d.ts in the consuming package (e.g., packages/web-ui-registration/src/users-register.d.ts). In reviews, ensure the changeset clearly states: this is a non-breaking change, the major version should not be bumped, and the changeset reflects a minor version bump. Do not treat this as a breaking change during OpenAPI migrations.
Applied to files:
.changeset/ddp-migrate-batch6-audit-callers.md.changeset/rest-audit-endpoints.md
📚 Learning: 2026-03-27T14:52:56.865Z
Learnt from: dougfabris
Repo: RocketChat/Rocket.Chat PR: 39892
File: apps/meteor/client/views/room/contextualBar/Threads/Thread.tsx:150-155
Timestamp: 2026-03-27T14:52:56.865Z
Learning: In Rocket.Chat, there are two different `ModalBackdrop` components with different prop APIs. During review, confirm the import source: (1) `rocket.chat/fuselage` `ModalBackdrop` uses `ModalBackdropProps` based on `BoxProps` (so it supports `onClick` and other Box/DOM props) and does not have an `onDismiss` prop; (2) `rocket.chat/ui-client` `ModalBackdrop` uses a narrower props interface like `{ children?: ReactNode; onDismiss?: () => void }` and handles Escape keypress and outside mouse-up, and it does not forward arbitrary DOM props such as `onClick`. Flag mismatched props (e.g., `onDismiss` passed to the fuselage component or `onClick` passed to the ui-client component) and ensure the usage matches the correct component being imported.
Applied to files:
apps/meteor/client/views/audit/components/AuditLogTable.tsx
📚 Learning: 2026-05-06T12:21:44.083Z
Learnt from: juliajforesti
Repo: RocketChat/Rocket.Chat PR: 40256
File: apps/meteor/client/components/CreateDiscussion/CreateDiscussion.tsx:121-149
Timestamp: 2026-05-06T12:21:44.083Z
Learning: Field wrappers in rocket.chat/fuselage-forms (Field, FieldLabel, FieldRow, FieldError, FieldHint) auto-create htmlFor/id associations, aria-describedby, and role="alert" for errors. Do not manually set htmlFor, id, aria-describedby, or role attributes when using these wrappers. This automatic wiring does not apply to plain rocket.chat/fuselage components, which require explicit ID wiring per the accessibility docs. In code reviews, prefer using fuselage-forms wrappers for form fields and verify there is no unnecessary manual ID/aria wiring in files that use these wrappers. If a component uses plain fuselage components, ensure proper id wiring as per docs.
Applied to files:
apps/meteor/client/views/audit/components/AuditLogTable.tsxapps/meteor/client/views/audit/hooks/useAuditMutation.tsapps/meteor/ee/server/lib/audit/functions.tsapps/meteor/ee/server/lib/audit/methods.tsapps/meteor/ee/server/api/audit.ts
📚 Learning: 2026-02-10T16:32:42.586Z
Learnt from: tassoevan
Repo: RocketChat/Rocket.Chat PR: 38528
File: apps/meteor/client/startup/roles.ts:14-14
Timestamp: 2026-02-10T16:32:42.586Z
Learning: In Rocket.Chat's Meteor client code, DDP streams use EJSON and Date fields arrive as Date objects; do not manually construct new Date() in stream handlers (for example, in sdk.stream()). Only REST API responses return plain JSON where dates are strings, so implement explicit conversion there if needed. Apply this guidance to all TypeScript files under apps/meteor/client to ensure consistent date handling in DDP streams and REST responses.
Applied to files:
apps/meteor/client/views/audit/hooks/useAuditMutation.ts
📚 Learning: 2026-05-11T20:30:35.265Z
Learnt from: tassoevan
Repo: RocketChat/Rocket.Chat PR: 40480
File: apps/meteor/client/meteor/startup/accounts.ts:59-61
Timestamp: 2026-05-11T20:30:35.265Z
Learning: In Rocket.Chat’s Meteor client code, when calling `dispatchToastMessage` with `{ type: 'error' }`, pass the raw caught error object as `message` without manual normalization. `dispatchToastMessage` is designed to accept `message: unknown` for error toasts, so avoid converting errors to strings (e.g., `String(error)`) or extracting `error.message` before passing them.
Applied to files:
apps/meteor/client/views/audit/hooks/useAuditMutation.ts
📚 Learning: 2026-02-26T19:25:44.063Z
Learnt from: gabriellsh
Repo: RocketChat/Rocket.Chat PR: 38778
File: packages/ui-voip/src/providers/useMediaSession.ts:192-192
Timestamp: 2026-02-26T19:25:44.063Z
Learning: In the Rocket.Chat repository, do not reference Biome lint rules in code review feedback. Biome is not used even if biome.json exists; only reference Biome rules if there is explicit, project-wide usage documented. For TypeScript files, review lint implications without Biome guidance unless the project enables Biome rules.
Applied to files:
apps/meteor/client/views/audit/hooks/useAuditMutation.tsapps/meteor/ee/server/lib/audit/functions.tsapps/meteor/ee/server/lib/audit/methods.tsapps/meteor/ee/server/api/audit.ts
📚 Learning: 2026-02-26T19:25:44.063Z
Learnt from: gabriellsh
Repo: RocketChat/Rocket.Chat PR: 38778
File: packages/ui-voip/src/providers/useMediaSession.ts:192-192
Timestamp: 2026-02-26T19:25:44.063Z
Learning: In this repository (RocketChat/Rocket.Chat), Biome lint rules are not used even if a biome.json exists. When reviewing TypeScript files (e.g., packages/ui-voip/src/providers/useMediaSession.ts), ensure lint suggestions do not reference Biome-specific rules. Rely on general ESLint/TypeScript lint rules and project conventions instead.
Applied to files:
apps/meteor/client/views/audit/hooks/useAuditMutation.tsapps/meteor/ee/server/lib/audit/functions.tsapps/meteor/ee/server/lib/audit/methods.tsapps/meteor/ee/server/api/audit.ts
🪛 ast-grep (0.44.0)
apps/meteor/ee/server/lib/audit/functions.ts
[warning] 131-131: Do not use variable for regular expressions
Context: new RegExp(escapeRegExp(msg).trim(), 'i')
Note: [CWE-1333] Inefficient Regular Expression Complexity. Security best practice.
(regexp-non-literal-typescript)
[warning] 189-189: Do not use variable for regular expressions
Context: new RegExp(escapeRegExp(msg).trim(), 'i')
Note: [CWE-1333] Inefficient Regular Expression Complexity. Security best practice.
(regexp-non-literal-typescript)
🔇 Additional comments (6)
.changeset/ddp-migrate-batch6-audit-callers.md (1)
1-6: LGTM!.changeset/rest-audit-endpoints.md (1)
1-12: LGTM!apps/meteor/ee/server/lib/audit/functions.ts (1)
1-19: LGTM!Also applies to: 59-148, 206-227
apps/meteor/ee/server/lib/audit/methods.ts (1)
7-8: LGTM!apps/meteor/ee/server/api/audit.ts (2)
1-122: LGTM!Also applies to: 288-404
125-130: 🎯 Functional CorrectnessUse the 400 failure path for invalid dates.
parseDateOrFail()throws a plainError, while these endpoints declare 400 responses for validation failures. Add an explicitAPI.v1.failure(...)/Meteor.Errormapping here, or the route layer may turn malformed dates into 500s.
There was a problem hiding this comment.
All reported issues were addressed across 7 files
Reply with feedback, questions, or to request a fix.
Re-trigger cubic
17505ef to
01fc5a4
Compare
042c4ef to
571d886
Compare
There was a problem hiding this comment.
All reported issues were addressed across 1 file (changes from recent commits).
Tip: Review your code locally with the cubic CLI to iterate faster.
Re-trigger cubic
94b75ac to
58e8c60
Compare
|
/jira ARCH-2166 |
Added three new REST endpoints (EE-only, license: auditing) covering the audit flows that previously only existed as DDP methods: - GET /v1/audit.auditions (auditGetAuditions) - POST /v1/audit.messages (auditGetMessages) - POST /v1/audit.omnichannel.messages (auditGetOmnichannelMessages) Method bodies extracted into apps/meteor/ee/server/lib/audit/functions.ts and reused by both DDP entrypoints (now thin + deprecation-logged) and the new REST handlers. Each REST endpoint: - requires the same per-action permission (can-audit / can-audit-log). - is rate-limited at 10/60s matching the DDP DDPRateLimiter rules. - writes the same AuditLog entry the DDP path produced. - accepts dates as ISO strings on the wire (parsed server-side). Client AuditLogTable + useAuditMutation swapped from useMethod to useEndpoint; date params serialized via toISOString(). DDP methods stay registered with deprecation logs pointing at the new routes until 9.0.0. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
- Add response schemas to /v1/audit.{auditions,messages,omnichannel.messages}
so TypedOptions infers queryParams/bodyParams correctly.
- mapMessageFromApi() each REST message in useAuditMutation so caller
AuditResult receives IMessage[] (Date) instead of Serialized<IMessage>[].
- Cast AuditLogEntry value through unknown→IAuditLog since the REST
response carries dates as strings while the consumer reads IAuditLog
(the component formats the Date itself, so the cast is just to satisfy
TS — same pattern other audit-adjacent code uses).
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
…sages Follow code style guide: endpoints use namespace.camelCaseAction (two segments), not a nested sub-namespace.
… deprecationLogger)
The console.warn fired for REST callers too now that this helper is shared, and the message (removal in 4.0.0) was long obsolete.
audit.auditions/omnichannelMessages now have invalid-date tests (matching audit.messages), and the messages/omnichannel 'matching' flows assert an AuditLog entry was created.
The /v1/audit.auditions payload serializes Date fields to strings; the query now converts ts/_updatedAt/fields.startDate/fields.endDate back to Date and returns a real IAuditLog[], removing the per-row `as unknown as IAuditLog` cast in the table.
When no omnichannel rooms match the visitor/agent filter, rids was undefined, so
{ $in: undefined } threw a MongoServerError instead of returning an empty result.
The Omnichannel audit form collects visitor/agent but the mutation drops them (carried over from the original DDP flow). Documented with a TODO; left for investigation.
The auditor role has can-audit but not can-audit-log by default, so the auditions validation tests were hitting 403 before reaching validation. Grant it suite-wide.
bebc023 to
fc2bf62
Compare
audit.auditions, audit.messages and audit.omnichannelMessages set authRequired + permissionsRequired + license but only declared 200/400. The typed router throws "Missing response validator" in TEST_MODE for any returned status code without a validator, so the unauthorized/forbidden paths were untestable. Add 401/403 validators to close that gap.
Replace the relaxed `{ type: 'object' }` items with a full schema matching
IAuditLog + the AuditLog.insertOne write path (u is exactly _id/username/
name?/avatarETag?; fields.type always set, rest optional; dates as date-time).
Verified against realistic payloads with the shared ajv. audit.messages/
omnichannelMessages stay relaxed with a comment — IMessage $ref 400s on the
attachment oneOf.
Stored AuditLog fields (rids, room, users, msg, visitor, agent, dates) persist as null when the write path passes undefined (e.g. ABAC branch leaves rids/room unset), so the strict schema must accept null to validate existing audit logs. Verified against the failing CI payload with the shared ajv.
There was a problem hiding this comment.
All reported issues were addressed across 1 file (changes from recent commits).
Tip: Review your code locally with the cubic CLI to iterate faster.
Re-trigger cubic
The AuditLog write passed undefined rids/room (ABAC branch) and optional
msg/visitor/agent straight into insertOne; the Mongo driver serialized those
as null, contradicting the optional IAuditLog.fields type. Pass
{ ignoreUndefined: true } so undefined keys are omitted (field absent) instead
of stored as null. The response schema keeps null-tolerance for pre-existing
audit documents.
Summary
Continues the DDP→REST sweep (#40659, #40711, #40675, #40724, #40728, #40734). This batch migrates the three
auditGet*DDP methods that backed the EE audit panel. DDP methods stay registered for external SDK/mobile clients with deprecation logs pointing at the new routes.New endpoints (EE —
auditinglicense required)auditGetAuditionsGET /v1/audit.auditionscan-audit-log?startDate=&endDate=(ISO)auditGetMessagesPOST /v1/audit.messagescan-audit{ rid?, startDate, endDate, users, msg, type, visitor?, agent? }auditGetOmnichannelMessagesPOST /v1/audit.omnichannel.messagescan-audit{ startDate, endDate, users, msg, type, visitor?, agent? }Each endpoint is rate-limited at 10/60s (matching the DDP
DDPRateLimiterrules) and writes the sameAuditLogentry the DDP path produced. Dates are serialized as ISO strings on the wire.Implementation
apps/meteor/ee/server/lib/audit/functions.ts; DDP entrypoints become thin + deprecation-logged.messagesandomnichannel.messagesarePOSTbecause the audit log insertion is a side effect (write) and the query params include arrays (users) that don't serialize cleanly into query strings.Client changes
AuditLogTable→useEndpoint('GET', '/v1/audit.auditions')useAuditMutation→useEndpoint('POST', '/v1/audit.messages')+useEndpoint('POST', '/v1/audit.omnichannel.messages').toISOString().Test plan
can-audit-logperm) → past entries rendercurland confirm 403 without license/permission, 200 with both🤖 Generated with Claude Code
Summary by CodeRabbit
/v1/audit.*(rate-limited to 10 requests per 60 seconds).startDate/endDatehandling as ISO strings and normalized REST responses to consistently returnauditions/messages.Task: ARCH-2269