Skip to content

fix(api): return 403 for authorization failures, reserve 401 for missing session - #41662

Open
surjeetkumar8006 wants to merge 1 commit into
RocketChat:developfrom
surjeetkumar8006:fix/api-401-403-semantics-v6
Open

fix(api): return 403 for authorization failures, reserve 401 for missing session#41662
surjeetkumar8006 wants to merge 1 commit into
RocketChat:developfrom
surjeetkumar8006:fix/api-401-403-semantics-v6

Conversation

@surjeetkumar8006

@surjeetkumar8006 surjeetkumar8006 commented Aug 2, 2026

Copy link
Copy Markdown

Proposal

Fixes REST API HTTP status code semantics for authentication vs authorization failures and aligns validation errorType naming consistency across the typed router, resolving #41589.

Endpoints

ApiClass, Router, permissionsMiddleware, rooms.getMembers, rooms.hide, rooms.bannedUsers, rooms.adminRooms

Notes

  • Reserve 401 status strictly for unauthenticated requests (!user / missing session).
  • Remap permission denials (error-unauthorized / error-not-authorized) to 403 (forbidden).
  • Align Router.ts body validation error type from invalid-params to error-invalid-params matching ajvQuery failure responses.
  • Clean up dead applyBreakingChanges branch in permissions.ts middleware and update rooms.ts response schemas to validateForbiddenErrorResponse.
  • Add changeset for patch release.

Task: #41589

Review in cubic

Summary by CodeRabbit

  • Bug Fixes

    • Authorization failures now consistently return 403 Forbidden; 401 Unauthorized is reserved for missing authentication sessions.
    • LDAP actions correctly report unauthenticated access.
    • Request validation errors now use the consistent error-invalid-params error type for query and body fields.
    • Added accurate forbidden responses for room and permission-protected API endpoints.
  • Documentation

    • Updated API migration guidance and endpoint testing recommendations for standardized validation and authorization responses.

@surjeetkumar8006
surjeetkumar8006 requested a review from a team as a code owner August 2, 2026 13:45
@dionisio-bot

dionisio-bot Bot commented Aug 2, 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 Aug 2, 2026

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 6f3b57f

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

This PR includes changesets to release 6 packages
Name Type
@rocket.chat/meteor Patch
@rocket.chat/http-router Patch
@rocket.chat/core-services Patch
@rocket.chat/federation-matrix 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

@CLAassistant

CLAassistant commented Aug 2, 2026

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@coderabbitai

coderabbitai Bot commented Aug 2, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 8da462ca-4130-4942-9df3-18dd4695f3b8

📥 Commits

Reviewing files that changed from the base of the PR and between 66e7811 and 6f3b57f.

📒 Files selected for processing (9)
  • .changeset/real-mails-count.md
  • apps/meteor/ee/server/api/ldap.ts
  • apps/meteor/server/api/ApiClass.ts
  • apps/meteor/server/api/v1/ldap.ts
  • apps/meteor/server/api/v1/middlewares/permissions.ts
  • apps/meteor/server/api/v1/rooms.ts
  • docs/api-endpoint-migration.md
  • packages/http-router/src/Router.spec.ts
  • packages/http-router/src/Router.ts
🚧 Files skipped from review as they are similar to previous changes (9)
  • packages/http-router/src/Router.spec.ts
  • packages/http-router/src/Router.ts
  • apps/meteor/server/api/v1/ldap.ts
  • apps/meteor/ee/server/api/ldap.ts
  • apps/meteor/server/api/v1/middlewares/permissions.ts
  • apps/meteor/server/api/ApiClass.ts
  • apps/meteor/server/api/v1/rooms.ts
  • .changeset/real-mails-count.md
  • docs/api-endpoint-migration.md

Walkthrough

The API now reserves 401 responses for missing sessions and returns 403 for authorization failures. LDAP and room endpoints use the updated responses. HTTP-router body validation now reports error-invalid-params.

Changes

API contract normalization

Layer / File(s) Summary
Authorization error routing
apps/meteor/server/api/ApiClass.ts, apps/meteor/ee/server/api/ldap.ts, apps/meteor/server/api/v1/ldap.ts, .changeset/real-mails-count.md
API error handling classifies missing sessions as unauthorized and authorization failures as forbidden. LDAP handlers use unauthorized for missing user IDs.
Forbidden endpoint responses
apps/meteor/server/api/v1/middlewares/permissions.ts, apps/meteor/server/api/v1/rooms.ts
Permission failures and selected room access failures return 403 responses. The affected room endpoints declare 403 response schemas.
Request validation normalization
packages/http-router/src/Router.ts, packages/http-router/src/Router.spec.ts, docs/api-endpoint-migration.md
Body validation uses error-invalid-params. Tests and migration guidance cover query and body validation.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Possibly related PRs

Suggested labels: type: bug, area: authentication

🚥 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 and concisely describes the main API change from 401 authorization failures to 403 while reserving 401 for missing sessions.
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)
  • API-401: 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.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 504dbca828

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

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

@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/server/api/v1/middlewares/permissions.ts`:
- Around line 46-47: Update the response schema for
rooms.adminRooms.privateRooms in validateUnauthorizedErrorResponse to use
validateForbiddenErrorResponse, matching the 403 returned by the permissions
middleware. Audit other permission-protected routes for the same incorrect
unauthorized declaration and replace it where their middleware returns forbidden
responses.
🪄 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: 06ab5dfb-2309-46fb-8322-a619d303e0b2

📥 Commits

Reviewing files that changed from the base of the PR and between 94478c6 and 504dbca.

📒 Files selected for processing (9)
  • .changeset/real-mails-count.md
  • apps/meteor/ee/server/api/ldap.ts
  • apps/meteor/server/api/ApiClass.ts
  • apps/meteor/server/api/v1/ldap.ts
  • apps/meteor/server/api/v1/middlewares/permissions.ts
  • apps/meteor/server/api/v1/rooms.ts
  • docs/api-endpoint-migration.md
  • packages/http-router/src/Router.spec.ts
  • packages/http-router/src/Router.ts
📜 Review details
⏰ Context from checks skipped due to timeout. (1)
  • GitHub Check: cubic · AI code reviewer
🧰 Additional context used
📓 Path-based instructions (2)
**/*.{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:

  • packages/http-router/src/Router.spec.ts
  • packages/http-router/src/Router.ts
  • apps/meteor/server/api/ApiClass.ts
  • apps/meteor/server/api/v1/middlewares/permissions.ts
  • apps/meteor/server/api/v1/ldap.ts
  • apps/meteor/ee/server/api/ldap.ts
  • apps/meteor/server/api/v1/rooms.ts
**/*.spec.ts

📄 CodeRabbit inference engine (.cursor/rules/playwright.mdc)

**/*.spec.ts: Use descriptive test names that clearly communicate expected behavior in Playwright tests
Use .spec.ts extension for test files (e.g., login.spec.ts)

Files:

  • packages/http-router/src/Router.spec.ts
🧠 Learnings (10)
📚 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/real-mails-count.md
📚 Learning: 2025-12-10T21:00:43.645Z
Learnt from: KevLehman
Repo: RocketChat/Rocket.Chat PR: 37091
File: ee/packages/abac/jest.config.ts:4-7
Timestamp: 2025-12-10T21:00:43.645Z
Learning: Adopt the monorepo-wide Jest testMatch pattern: <rootDir>/src/**/*.spec.{ts,js,mjs} (represented here as '**/src/**/*.spec.{ts,js,mjs}') to ensure spec files under any package's src directory are picked up consistently across all packages in the Rocket.Chat monorepo. Apply this pattern in jest.config.ts for all relevant packages to maintain uniform test discovery.

Applied to files:

  • packages/http-router/src/Router.spec.ts
📚 Learning: 2026-02-24T19:22:48.358Z
Learnt from: juliajforesti
Repo: RocketChat/Rocket.Chat PR: 38493
File: apps/meteor/tests/e2e/omnichannel/omnichannel-send-pdf-transcript.spec.ts:66-67
Timestamp: 2026-02-24T19:22:48.358Z
Learning: In Playwright end-to-end tests (e.g., under apps/meteor/tests/e2e/...), prefer locating elements by translated text (getByText) and ARIA roles (getByRole) over data-qa attributes. If translation values change, update the corresponding test locators accordingly. Never use data-qa locators. This guideline applies to all Playwright e2e test specs in the repository and helps keep tests robust to UI text changes and accessible semantics.

Applied to files:

  • packages/http-router/src/Router.spec.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:

  • packages/http-router/src/Router.spec.ts
  • packages/http-router/src/Router.ts
  • apps/meteor/server/api/ApiClass.ts
  • apps/meteor/server/api/v1/middlewares/permissions.ts
  • apps/meteor/server/api/v1/ldap.ts
  • apps/meteor/ee/server/api/ldap.ts
  • apps/meteor/server/api/v1/rooms.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:

  • packages/http-router/src/Router.spec.ts
  • packages/http-router/src/Router.ts
  • apps/meteor/server/api/ApiClass.ts
  • apps/meteor/server/api/v1/middlewares/permissions.ts
  • apps/meteor/server/api/v1/ldap.ts
  • apps/meteor/ee/server/api/ldap.ts
  • apps/meteor/server/api/v1/rooms.ts
📚 Learning: 2026-03-06T18:10:15.268Z
Learnt from: tassoevan
Repo: RocketChat/Rocket.Chat PR: 39397
File: packages/gazzodown/src/code/CodeBlock.spec.tsx:47-68
Timestamp: 2026-03-06T18:10:15.268Z
Learning: In tests (especially those using testing-library/dom/jsdom) for Rocket.Chat components, the HTML <code> element has an implicit ARIA role of 'code'. Therefore, screen.getByRole('code') or screen.findByRole('code') will locate <code> elements even without a role attribute. Do not flag findByRole('code') as invalid in reviews; prefer using the implicit role instead of adding role="code" unless necessary for accessibility.

Applied to files:

  • packages/http-router/src/Router.spec.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:

  • packages/http-router/src/Router.spec.ts
  • packages/http-router/src/Router.ts
  • apps/meteor/server/api/ApiClass.ts
  • apps/meteor/server/api/v1/middlewares/permissions.ts
  • apps/meteor/server/api/v1/ldap.ts
  • apps/meteor/ee/server/api/ldap.ts
  • apps/meteor/server/api/v1/rooms.ts
📚 Learning: 2026-07-31T02:44:35.111Z
Learnt from: ggazzo
Repo: RocketChat/Rocket.Chat PR: 41635
File: apps/meteor/ee/server/api/sessions.ts:114-138
Timestamp: 2026-07-31T02:44:35.111Z
Learning: In Rocket.Chat typed REST response schemas, accept the composition of a Typia-generated entity schema with an `allOf` branch requiring `success: true`: `allOf: [{ $ref: <entity schema> }, { properties: { success: { type: 'boolean', enum: [true] } }, required: ['success'] }]`. Do not flag this pattern when used for REST endpoints, provided TEST_MODE response validation passes, as demonstrated by the `IOAuthApps` and `IEmailInbox` endpoints.

Applied to files:

  • apps/meteor/server/api/ApiClass.ts
  • apps/meteor/server/api/v1/middlewares/permissions.ts
  • apps/meteor/server/api/v1/ldap.ts
  • apps/meteor/ee/server/api/ldap.ts
  • apps/meteor/server/api/v1/rooms.ts
📚 Learning: 2026-07-29T23:45:21.859Z
Learnt from: ggazzo
Repo: RocketChat/Rocket.Chat PR: 41632
File: apps/meteor/server/api/v1/groups.ts:948-959
Timestamp: 2026-07-29T23:45:21.859Z
Learning: For API v1 routes under apps/meteor/server/api/v1, keep item-level response schemas strict by using `$ref`-based schemas for list and messages (and ensure they intentionally mirror the corresponding route contracts, as done in channels.ts). Only use “loose”/non-`$ref` item schemas when the underlying data source is inherently partial (e.g., uploads where `content` can be `null`, or queries like `findUsersOfRoom` with a fixed projection). Do not relax item schemas merely because the route supports an optional client `fields` projection—optional field selection alone is not a reason to change schema strictness.

Applied to files:

  • apps/meteor/server/api/v1/ldap.ts
  • apps/meteor/server/api/v1/rooms.ts
📚 Learning: 2026-07-31T00:32:03.839Z
Learnt from: ggazzo
Repo: RocketChat/Rocket.Chat PR: 41635
File: apps/meteor/ee/server/api/roles.ts:101-111
Timestamp: 2026-07-31T00:32:03.839Z
Learning: In Rocket.Chat's typed EE REST API routes that use apps/meteor/ee/server/api/v1/middlewares/license.ts, account for unavailable route-level license modules returning HTTP 400 with { success: false, error, errorType: 'error-action-not-allowed' }, not HTTP 403. Declare the existing 400 bad-request response schema for these routes.

Applied to files:

  • apps/meteor/ee/server/api/ldap.ts
🔇 Additional comments (9)
packages/http-router/src/Router.ts (1)

248-248: LGTM!

packages/http-router/src/Router.spec.ts (1)

210-215: LGTM!

docs/api-endpoint-migration.md (2)

600-600: LGTM!


618-618: LGTM!

apps/meteor/server/api/ApiClass.ts (1)

898-918: LGTM!

apps/meteor/ee/server/api/ldap.ts (1)

32-32: LGTM!

apps/meteor/server/api/v1/ldap.ts (1)

34-34: LGTM!

Also applies to: 68-68

.changeset/real-mails-count.md (1)

1-6: LGTM!

apps/meteor/server/api/v1/rooms.ts (1)

739-739: LGTM!

Also applies to: 779-779, 815-815, 1142-1142, 1161-1161, 1301-1308, 1705-1712

Comment thread apps/meteor/server/api/v1/middlewares/permissions.ts

@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 9 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
Comment thread apps/meteor/server/api/v1/middlewares/permissions.ts
@surjeetkumar8006
surjeetkumar8006 force-pushed the fix/api-401-403-semantics-v6 branch from 504dbca to 66e7811 Compare August 2, 2026 13:55
@surjeetkumar8006
surjeetkumar8006 force-pushed the fix/api-401-403-semantics-v6 branch from 66e7811 to 6f3b57f Compare August 2, 2026 14:10
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