Skip to content

fix(password-policies): sanitize and validate forbidRepeatingCharactersCount before constructing RegExp - #41760

Open
sudoKrishna wants to merge 1 commit into
RocketChat:developfrom
sudoKrishna:fix/password-policy-regex-validation-clean
Open

fix(password-policies): sanitize and validate forbidRepeatingCharactersCount before constructing RegExp#41760
sudoKrishna wants to merge 1 commit into
RocketChat:developfrom
sudoKrishna:fix/password-policy-regex-validation-clean

Conversation

@sudoKrishna

@sudoKrishna sudoKrishna commented Aug 12, 2026

Copy link
Copy Markdown

summary

Sanitize forbidRepeatingCharactersCount before interpolating it into the RegExp constructor.

Invalid values (negative numbers, 0, floats, NaN, unsafe large numbers, non-numbers) now fall back to the default of 3, preventing a SyntaxError that could crash the workspace.

Why

Fixes #41620

Changes

  • Added validation that the count is a safe integer >= 1
  • Used the sanitized value for both the instance property and the RegExp
  • Added unit tests covering invalid inputs

Testing

Screenshot From 2026-08-12 11-30-11

All 20 tests passed:

yarn workspace @rocket.chat/password-policies test --runInBand

<!-- This is an auto-generated description by cubic. -->
<a href="https://cubic.dev/pr/RocketChat/Rocket.Chat/pull/41760?utm_source=github" target="_blank" rel="noopener noreferrer" data-no-image-dialog="true"><picture><source media="(prefers-color-scheme: dark)" srcset="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://www.cubic.dev/buttons/review-in-cubic-light.svg"><img alt="Review in cubic" src="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"></picture></a>
<!-- End of auto-generated description by cubic. -->



<!-- This is an auto-generated comment: release notes by coderabbit.ai -->

## Summary by CodeRabbit

* **Bug Fixes**
  * Improved password policy validation for repeating-character limits.
  * Invalid limits now safely fall back to a default value of 3.
  * Password policy configuration and validation messages now consistently reflect the corrected setting.


<!-- end of auto-generated comment: release notes by coderabbit.ai -->

@dionisio-bot

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

Copy link
Copy Markdown

⚠️ No Changeset found

Latest commit: 395e30a

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

@CLAassistant

Copy link
Copy Markdown

CLA assistant check
Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you sign our Contributor License Agreement before we can accept your contribution.
You have signed the CLA already but the status is still pending? Let us recheck it.

@coderabbitai

coderabbitai Bot commented Aug 12, 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: d6cbb435-b9a1-4f29-99ff-f087988d89d7

📥 Commits

Reviewing files that changed from the base of the PR and between e519470 and 395e30a.

📒 Files selected for processing (2)
  • packages/password-policies/src/PasswordPolicy.spec.ts
  • packages/password-policies/src/PasswordPolicy.ts
📜 Recent review details
⏰ Context from checks skipped due to timeout. (1)
  • GitHub Check: cubic · AI code reviewer
🧰 Additional context used
📓 Path-based instructions (3)
**/*.{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/password-policies/src/PasswordPolicy.spec.ts
  • packages/password-policies/src/PasswordPolicy.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/password-policies/src/PasswordPolicy.spec.ts
packages/**

📄 CodeRabbit inference engine (CLAUDE.md)

Shared libraries belong in packages/, while other services belong in apps/ and ee/.

Files:

  • packages/password-policies/src/PasswordPolicy.spec.ts
  • packages/password-policies/src/PasswordPolicy.ts
🧠 Learnings (9)
📓 Common learnings
Learnt from: abhinavkrin
Repo: RocketChat/Rocket.Chat PR: 41672
File: apps/meteor/client/lib/utils/getConfig.ts:17-20
Timestamp: 2026-08-03T19:17:04.787Z
Learning: For Rocket.Chat pagination endpoints that use `getPaginationItems`, `count=0` falls back to `API_Default_Count` unless `API_Allow_Infinite_Count` is enabled, fractional values are truncated with `parseInt`, and a negative count becomes a MongoDB negative `limit` that returns one batch. A `count=NaN` request is rejected by AJV coercion before this server-side normalization. Therefore, thread pagination fixes for CORE-2498 need finite numeric client configuration values to prevent `count=NaN`; positive safe integer validation is optional hardening.
Learnt from: ahmed-n-abdeltwab
Repo: RocketChat/Rocket.Chat PR: 39230
File: apps/meteor/app/api/server/v1/chat.ts:214-222
Timestamp: 2026-03-03T11:11:48.541Z
Learning: In apps/meteor/server/lib/moderation/reportMessage.ts, the reportMessage function validates that description is not empty or whitespace-only with `if (!description.trim())`. When migrating the chat.reportMessage endpoint to OpenAPI, adding minLength validation to the schema preserves this existing behavior.
Learnt from: nazabucciarelli
Repo: RocketChat/Rocket.Chat PR: 40306
File: apps/meteor/client/views/room/MessageList/hooks/useMessageBody.tsx:18-30
Timestamp: 2026-05-05T16:51:36.461Z
Learning: In Rocket.Chat, the `useMaxMarkdownParseLength` hook (in `apps/meteor/client/components/message/hooks/useMaxMarkdownParseLength.ts`) already normalizes values `<= 0` (or missing/non-numeric) to `Infinity`. Consumers like `useMessageBody` and `useNormalizedMessage` can safely use `message.msg.length > maxMarkdownParseLength` without an extra `maxMarkdownParseLength > 0` guard, because `length > Infinity` is always `false`.
📚 Learning: 2025-10-07T15:08:37.419Z
Learnt from: cardoso
Repo: RocketChat/Rocket.Chat PR: 36942
File: apps/meteor/client/lib/e2ee/pbkdf2.ts:13-45
Timestamp: 2025-10-07T15:08:37.419Z
Learning: In apps/meteor/client/lib/e2ee/pbkdf2.ts, PBKDF2 iteration count validation is not enforced because the iterations parameter is outside the user's control and is system-managed.

Applied to files:

  • packages/password-policies/src/PasswordPolicy.spec.ts
📚 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/password-policies/src/PasswordPolicy.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/password-policies/src/PasswordPolicy.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/password-policies/src/PasswordPolicy.spec.ts
  • packages/password-policies/src/PasswordPolicy.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/password-policies/src/PasswordPolicy.spec.ts
  • packages/password-policies/src/PasswordPolicy.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/password-policies/src/PasswordPolicy.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/password-policies/src/PasswordPolicy.spec.ts
  • packages/password-policies/src/PasswordPolicy.ts
📚 Learning: 2026-03-16T21:50:42.118Z
Learnt from: amitb0ra
Repo: RocketChat/Rocket.Chat PR: 39676
File: .changeset/migrate-users-register-openapi.md:3-3
Timestamp: 2026-03-16T21:50:42.118Z
Learning: In RocketChat/Rocket.Chat OpenAPI migration PRs, removing endpoint types and validators from `rocket.chat/rest-typings` (e.g., `UserRegisterParamsPOST`, `/v1/users.register` entry) is the *required* migration pattern per RocketChat/Rocket.Chat-Open-API#150 Rule 7 ("No More rest-typings or Manual Typings"). The endpoint type is re-exposed via a module augmentation `.d.ts` file in the consuming package (e.g., `packages/web-ui-registration/src/users-register.d.ts`). This is NOT a breaking change — the correct changeset bump for `rocket.chat/rest-typings` in this scenario is `minor`, not `major`. Do not flag this as a breaking change during OpenAPI migration reviews.

Applied to files:

  • packages/password-policies/src/PasswordPolicy.ts
🪛 ast-grep (0.45.1)
packages/password-policies/src/PasswordPolicy.ts

[warning] 99-99: Regular expression constructed from variable input detected. This can lead to Regular Expression Denial of Service (ReDoS) attacks if the variable contains malicious patterns. Use libraries like 'recheck' to validate regex safety or use static patterns.
Context: new RegExp((.)\\1{${safeForbidRepeatingCharactersCount},})
Note: [CWE-1333] Inefficient Regular Expression Complexity

(regexp-from-variable)

🔇 Additional comments (3)
packages/password-policies/src/PasswordPolicy.ts (2)

19-20: LGTM!

Also applies to: 37-38


82-100: LGTM!

packages/password-policies/src/PasswordPolicy.spec.ts (1)

219-245: LGTM!


Walkthrough

The password policy now accepts only safe integer repetition counts of at least 1. Invalid values use the default count of 3 before regex construction. Parameterized tests verify validation, messages, and policy metadata.

Changes

Password Policy Sanitization

Layer / File(s) Summary
Sanitize repeating-character count
packages/password-policies/src/PasswordPolicy.ts, packages/password-policies/src/PasswordPolicy.spec.ts
PasswordPolicy normalizes invalid forbidRepeatingCharactersCount values to 3 before constructing the regex. Tests verify validation results, messages, and returned policy metadata. Mapped type formatting is also normalized.

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

Suggested labels: type: bug

Suggested reviewers: tassoevan

🚥 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 describes sanitizing and validating the repeating-character count before constructing the regular expression.
Linked Issues check ✅ Passed The changes validate the count, fall back to 3 for invalid values, use the sanitized value, and add focused tests as required by issue #41620.
Out of Scope Changes check ✅ Passed The implementation, formatting updates, and tests remain within the scope of issue #41620.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

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.

@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.

1 issue found across 2 files

Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="packages/password-policies/src/PasswordPolicy.ts">

<violation number="1" location="packages/password-policies/src/PasswordPolicy.ts:85">
P2: This change silently alters the semantics of `forbidRepeatingCharactersCount: 0`. Previously `0` was a functional configuration producing the valid regex `(.)\1{0,}` (rejecting any repeated character) and, being falsy, suppressed the corresponding `get-password-policy` entry in `getPasswordPolicy()`. Now `0` is silently coerced to the default `3`, which relaxes the policy and, because `this.forbidRepeatingCharactersCount` becomes truthy, newly emits the policy entry where it was previously omitted. Since the corresponding setting is an `int` with no stated minimum, an admin who set `0` would see their policy quietly weakened without warning. Consider handling `0` explicitly (coerce only clearly-invalid values or clamp/log) rather than silently remapping to `3`, and document the behavior change if intentional.</violation>
</file>

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

Re-trigger cubic

const safeForbidRepeatingCharactersCount =
typeof forbidRepeatingCharactersCount === 'number' &&
Number.isSafeInteger(forbidRepeatingCharactersCount) &&
forbidRepeatingCharactersCount >= 1 ? forbidRepeatingCharactersCount : 3;

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.

P2: This change silently alters the semantics of forbidRepeatingCharactersCount: 0. Previously 0 was a functional configuration producing the valid regex (.)\1{0,} (rejecting any repeated character) and, being falsy, suppressed the corresponding get-password-policy entry in getPasswordPolicy(). Now 0 is silently coerced to the default 3, which relaxes the policy and, because this.forbidRepeatingCharactersCount becomes truthy, newly emits the policy entry where it was previously omitted. Since the corresponding setting is an int with no stated minimum, an admin who set 0 would see their policy quietly weakened without warning. Consider handling 0 explicitly (coerce only clearly-invalid values or clamp/log) rather than silently remapping to 3, and document the behavior change if intentional.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At packages/password-policies/src/PasswordPolicy.ts, line 85:

<comment>This change silently alters the semantics of `forbidRepeatingCharactersCount: 0`. Previously `0` was a functional configuration producing the valid regex `(.)\1{0,}` (rejecting any repeated character) and, being falsy, suppressed the corresponding `get-password-policy` entry in `getPasswordPolicy()`. Now `0` is silently coerced to the default `3`, which relaxes the policy and, because `this.forbidRepeatingCharactersCount` becomes truthy, newly emits the policy entry where it was previously omitted. Since the corresponding setting is an `int` with no stated minimum, an admin who set `0` would see their policy quietly weakened without warning. Consider handling `0` explicitly (coerce only clearly-invalid values or clamp/log) rather than silently remapping to `3`, and document the behavior change if intentional.</comment>

<file context>
@@ -79,19 +79,25 @@ export class PasswordPolicy {
+		const safeForbidRepeatingCharactersCount =
+			typeof forbidRepeatingCharactersCount === 'number' &&
+				Number.isSafeInteger(forbidRepeatingCharactersCount) &&
+				forbidRepeatingCharactersCount >= 1 ? forbidRepeatingCharactersCount : 3;
+
+
</file context>

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.

fix(password-policies): sanitize and validate forbidRepeatingCharactersCount before constructing RegExp

2 participants