Skip to content

fix: mark session as logged out on REST /v1/logout - #41573

Open
Rohit3523 wants to merge 9 commits into
developfrom
fix/rest-logout-session-cleanup
Open

fix: mark session as logged out on REST /v1/logout#41573
Rohit3523 wants to merge 9 commits into
developfrom
fix/rest-logout-session-cleanup

Conversation

@Rohit3523

@Rohit3523 Rohit3523 commented Jul 25, 2026

Copy link
Copy Markdown
Member

Proposed changes

When a user logs out via POST /v1/logout, the login token is removed from the user document but the session in the Sessions collection is never marked as logged out. The cleanup relies on an indirect chain (watch.users → in-memory callbacks → Accounts.onLogout → SAUMonitor → Sessions.logoutBySessionIdAndUserId) that breaks when the client closes its WebSocket upon receiving the logout response, the callbacks are destroyed before the broadcast arrives.

This adds a direct Sessions.logoutByloginTokenAndUserId() call in the logout handler, awaited before the response, so the session is always marked with logoutAt regardless of the WebSocket race.

Issue(s)

https://rocketchat.atlassian.net/browse/NATIVE-978

Steps to test or reproduce

  1. Log in on an Android/iOS client
  2. Verify the device appears in Device Manager
  3. Log out from the client
  4. Log back in
  5. Check Device Manager, should show only one active session not two

Further comments

The root cause is a race condition: POST /v1/logout broadcasts watch.users as fire-and-forget (void), but the mobile client closes its WebSocket on receiving the 200 response, removing the in-memory observer callbacks before the broadcast arrives. The SAUMonitor never receives the logout event, so logoutAt is never set on the session document. The direct Sessions.logoutByloginTokenAndUserId() call eliminates the dependency on this chain entirely.

Summary by CodeRabbit

  • Bug Fixes
    • Improved logout handling so POST /v1/logout explicitly marks the user’s session as logged out, preventing stale/orphaned sessions from persisting in Device Manager.
    • Reduced inconsistent session state by avoiding indirect, timing-sensitive cleanup during logout.
  • Tests
    • Added end-to-end coverage for POST /api/v1/logout to confirm session invalidation, logoutAt/logoutBy updates on the session record, and correct 401 responses for unauthenticated requests.

@Rohit3523
Rohit3523 requested a review from a team as a code owner July 25, 2026 15:32
@dionisio-bot

dionisio-bot Bot commented Jul 25, 2026

Copy link
Copy Markdown
Contributor

Looks like this PR is not ready to merge, because of the following issues:

  • This PR is missing the 'stat: QA assured' label
  • This PR is missing the required milestone or project

Please fix the issues and try again

If you have any trouble, please check the PR guidelines

@changeset-bot

changeset-bot Bot commented Jul 25, 2026

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: f0ee6c6

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 3 packages
Name Type
@rocket.chat/meteor Patch
@rocket.chat/core-typings Patch
@rocket.chat/rest-typings Patch

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

@coderabbitai

coderabbitai Bot commented Jul 25, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It 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 reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

Walkthrough

The REST logout flow now explicitly marks the matching session as logged out in the Sessions collection after removing the hashed login token. End-to-end tests cover session invalidation, logout metadata, and unauthenticated requests.

Changes

Logout session cleanup

Layer / File(s) Summary
Explicit session logout
apps/meteor/server/api/ApiClass.ts, .changeset/rest-logout-session-cleanup.md
The logout endpoint invokes Sessions.logoutBySessionIdAndUserId with the hashed token and user ID, and the changeset documents the patch release.
Logout endpoint validation
apps/meteor/tests/end-to-end/api/users.ts
End-to-end tests verify session invalidation, persisted logoutAt and logoutBy values, and HTTP 401 handling for unauthenticated requests.

Estimated code review effort: 2 (Simple) | ~10 minutes

Suggested labels: type: bug

Suggested reviewers: juliajforesti

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly summarizes the main change: marking the session logged out during REST POST /v1/logout.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

Warning

Review ran into problems

🔥 Problems

Errors were encountered while retrieving linked issues.

Errors (1)
  • NATIVE-978: Request failed with status code 401

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
apps/meteor/server/api/ApiClass.ts (1)

1131-1138: 🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift

Make token removal and session logout failure-safe.

If Sessions.logoutByloginTokenAndUserId() rejects after Users.updateOne() succeeds, the route returns an error with the token already invalidated, so the client cannot retry while the session remains active. Use an atomic transaction or a durable compensation/retry path for these two updates.

🤖 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/meteor/server/api/ApiClass.ts` around lines 1131 - 1138, Update the
token invalidation flow around Users.updateOne and
Sessions.logoutByloginTokenAndUserId so both operations are failure-safe and
cannot leave the token removed while the session remains active. Use the
project’s supported atomic transaction mechanism, or implement durable
compensation/retry handling that restores or retries the corresponding update
when either operation fails, while preserving the existing user and login-token
scope.
🤖 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.

Outside diff comments:
In `@apps/meteor/server/api/ApiClass.ts`:
- Around line 1131-1138: Update the token invalidation flow around
Users.updateOne and Sessions.logoutByloginTokenAndUserId so both operations are
failure-safe and cannot leave the token removed while the session remains
active. Use the project’s supported atomic transaction mechanism, or implement
durable compensation/retry handling that restores or retries the corresponding
update when either operation fails, while preserving the existing user and
login-token scope.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: d9751838-ac1a-4973-84b2-548640a8a892

📥 Commits

Reviewing files that changed from the base of the PR and between 6dc66fb and 3d47dff.

📒 Files selected for processing (2)
  • .changeset/rest-logout-session-cleanup.md
  • apps/meteor/server/api/ApiClass.ts
📜 Review details
⏰ Context from checks skipped due to timeout. (5)
  • GitHub Check: 📦 Build Packages
  • GitHub Check: cubic · AI code reviewer
  • GitHub Check: Hacktron Security Check
  • GitHub Check: CodeQL-Build
  • GitHub Check: CodeQL-Build
🧰 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/server/api/ApiClass.ts
🧠 Learnings (4)
📚 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/rest-logout-session-cleanup.md
📚 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/server/api/ApiClass.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/server/api/ApiClass.ts
📚 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/server/api/ApiClass.ts
🔇 Additional comments (2)
apps/meteor/server/api/ApiClass.ts (1)

5-5: LGTM!

.changeset/rest-logout-session-cleanup.md (1)

1-6: LGTM!

@cubic-dev-ai cubic-dev-ai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All reported issues were addressed across 2 files

Reply with feedback, questions, or to request a fix.

Re-trigger cubic

Comment thread apps/meteor/server/api/ApiClass.ts Outdated
Comment thread apps/meteor/server/api/ApiClass.ts Outdated
@codecov

codecov Bot commented Jul 25, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 68.72%. Comparing base (6dc66fb) to head (f0ee6c6).
⚠️ Report is 7 commits behind head on develop.

Additional details and impacted files

Impacted file tree graph

@@             Coverage Diff             @@
##           develop   #41573      +/-   ##
===========================================
+ Coverage    68.69%   68.72%   +0.03%     
===========================================
  Files         4139     4150      +11     
  Lines       159112   159417     +305     
  Branches     27917    27989      +72     
===========================================
+ Hits        109300   109566     +266     
- Misses       44666    44670       +4     
- Partials      5146     5181      +35     
Flag Coverage Δ
e2e 58.84% <ø> (+0.01%) ⬆️
e2e-api 45.62% <100.00%> (+0.01%) ⬆️
unit 70.70% <ø> (+0.05%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@KevLehman KevLehman left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

is it possible to do some api tests for this?

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 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/tests/end-to-end/api/users.ts`:
- Line 5534: The assertion around the session logout timestamp should verify
that session.logoutAt is persisted as a BSON Date rather than merely non-null.
Update the assertion at the existing session validation flow to check the
value’s BSON Date type, while preserving the surrounding session and logout
behavior.
🪄 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 Plus

Run ID: 7846262d-6f5d-41ac-842b-d8e45641762f

📥 Commits

Reviewing files that changed from the base of the PR and between b6e2eeb and f3f8ea5.

📒 Files selected for processing (1)
  • apps/meteor/tests/end-to-end/api/users.ts
📜 Review details
⏰ Context from checks skipped due to timeout. (3)
  • GitHub Check: cubic · AI code reviewer
  • GitHub Check: CodeQL-Build
  • GitHub Check: CodeQL-Build
⚠️ CI failures not shown inline (5)

GitHub Check: Dionisio QA: Some checks did not pass

Conclusion: failure

View job details

**Conclusion:** failure
### Steps
- ✅ **No merge conflicts**
- ❌ **QA assured** — This PR is missing the 'stat: QA assured' label
- ✅ **Mergeable**
- ❌ **Has milestone or project** — This PR is missing the required milestone or project
- ✅ **Valid PR title**
- ✅ **Correct target version**

GitHub Check: Dionisio QA: Some checks did not pass

Conclusion: failure

View job details

**Conclusion:** failure
### Steps
- ✅ **No merge conflicts**
- ❌ **QA assured** — This PR is missing the 'stat: QA assured' label
- ✅ **Mergeable**
- ❌ **Has milestone or project** — This PR is missing the required milestone or project
- ✅ **Valid PR title**
- ✅ **Correct target version**

GitHub Check: Dionisio QA: Some checks did not pass

Conclusion: failure

View job details

**Conclusion:** failure
### Steps
- ✅ **No merge conflicts**
- ❌ **QA assured** — This PR is missing the 'stat: QA assured' label
- ✅ **Mergeable**
- ❌ **Has milestone or project** — This PR is missing the required milestone or project
- ✅ **Valid PR title**
- ✅ **Correct target version**

GitHub Check: Dionisio QA: Some checks did not pass

Conclusion: failure

View job details

**Conclusion:** failure
### Steps
- ✅ **No merge conflicts**
- ❌ **QA assured** — This PR is missing the 'stat: QA assured' label
- ✅ **Mergeable**
- ❌ **Has milestone or project** — This PR is missing the required milestone or project
- ✅ **Valid PR title**
- ✅ **Correct target version**

GitHub Check: Dionisio QA: Some checks did not pass

Conclusion: failure

View job details

**Conclusion:** failure
### Steps
- ✅ **No merge conflicts**
- ❌ **QA assured** — This PR is missing the 'stat: QA assured' label
- ✅ **Mergeable**
- ❌ **Has milestone or project** — This PR is missing the required milestone or project
- ✅ **Valid PR title**
- ✅ **Correct target version**
🧰 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/tests/end-to-end/api/users.ts
🧠 Learnings (3)
📚 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/tests/end-to-end/api/users.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/tests/end-to-end/api/users.ts
📚 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/tests/end-to-end/api/users.ts

Comment thread apps/meteor/tests/end-to-end/api/users.ts Outdated
@Rohit3523

Copy link
Copy Markdown
Member Author

is it possible to do some api tests for this?

Added :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants