Skip to content

🛡️ Sentinel: implement dual rate-limiting on authentication server actions - #126

Open
projectamazonph wants to merge 3 commits into
mainfrom
fix/sentinel-dual-rate-limiting-auth-actions-3105092884023430613
Open

🛡️ Sentinel: implement dual rate-limiting on authentication server actions#126
projectamazonph wants to merge 3 commits into
mainfrom
fix/sentinel-dual-rate-limiting-auth-actions-3105092884023430613

Conversation

@projectamazonph

@projectamazonph projectamazonph commented Aug 12, 2026

Copy link
Copy Markdown
Owner

🛡️ Sentinel: [improving area/improvement type]

🚨 Severity

HIGH

💡 Vulnerability

The application originally relied on a single-key rate-limiting helper inside authentication server actions (signUpAction and signInAction) constrained only on target emails. This left the authentication entry points vulnerable to brute-force credential stuffing and, critically, Account Lockout Denial of Service (DoS) where an attacker could easily lock out legitimate users from accessing their accounts by repeatedly making failing requests with their emails from different IPs, or lock out whole networks via IP lockout.

🎯 Impact

A targeted brute-force or credential stuffing attack could trigger a CPU-exhaustion DoS on the Next.js event loop due to heavy cryptographic operations (e.g. password verification), or completely lockout legitimate student and admin accounts through bucket exhaustion of their specific email identifiers.

🔧 Fix

  1. Implemented an asynchronous rateLimitDual function in src/lib/rate-limit.ts that safely extracts client IP from headers (x-forwarded-for and x-real-ip) under strict TypeScript parameters (noUncheckedIndexedAccess) and checks the IP limit before checking the target key's limit.
  2. Protected signUpAction and signInAction in src/app/actions/auth.ts with rateLimitDual, ensuring limits are enforced before any database lookups or password hashing.
  3. Created resetRateLimits() to prevent state pollution between unit tests.
  4. Added comprehensive test suites in src/lib/__tests__/rate-limit.test.ts covering IP extraction, IP-bypass-first, case-insensitivity on email addresses, and graceful fallback.
  5. Recorded critical security learning in .jules/sentinel.md.

✅ Verification

  • All rate-limit unit tests pass successfully.
  • All auth-actions tests pass successfully.
  • Typechecking (pnpm typecheck), ESLint (pnpm lint), and production build (pnpm build) are 100% clean.

PR created automatically by Jules for task 3105092884023430613 started by @projectamazonph

Summary by CodeRabbit

  • Bug Fixes

    • Improved sign-in and sign-up protection against automated abuse and account-lockout attacks.
    • Added balanced request controls that limit repeated attempts by both network source and account identifier.
    • Preserved access for legitimate users while preventing blocked sources from consuming account-specific limits.
  • Documentation

    • Documented the authentication protection improvements and related security considerations.

…tions

- Implement asynchronous dual rate-limiting (`rateLimitDual`) inside `src/lib/rate-limit.ts` combining client IP checks (first) and target-based checks (second) to safeguard against credential stuffing and Account Lockout Denial of Service (DoS) attacks.
- Integrate `rateLimitDual` into both `signUpAction` and `signInAction` inside `src/app/actions/auth.ts` before database queries or CPU-intensive password-hashing verify calls.
- Implement helper function `resetRateLimits()` to clear maps and resolve inter-test pollution.
- Add comprehensive unit tests in `src/lib/__tests__/rate-limit.test.ts` to cover single and dual rate-limiting edge cases under `noUncheckedIndexedAccess`.
- Update `auth-actions.test.ts` to call `resetRateLimits` in its `beforeEach` hook.
- Append critical security learnings to `sentinel.md` journal.

Co-authored-by: projectamazonph <286085559+projectamazonph@users.noreply.github.com>
@google-labs-jules

Copy link
Copy Markdown
Contributor

👋 Jules, reporting for duty! I'm here to lend a hand with this pull request.

When you start a review, I'll add a 👀 emoji to each comment to let you know I've read it. I'll focus on feedback directed at me and will do my best to stay out of conversations between you and other bots or reviewers to keep the noise down.

I'll push a commit with your requested changes shortly after. Please note there might be a delay between these steps, but rest assured I'm on the job!

For more direct control, you can switch me to Reactive Mode. When this mode is on, I will only act on comments where you specifically mention me with @jules. You can find this option in the Pull Request section of your global Jules UI settings. You can always switch back!

New to Jules? Learn more at jules.google/docs.


For security, I will only act on instructions from the user who triggered this task.

Copilot AI lite review requested due to automatic review settings August 12, 2026 12:51

Copilot AI 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.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@coderabbitai

coderabbitai Bot commented Aug 12, 2026

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

@projectamazonph, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 39 minutes

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

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 configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 77e2e027-08ae-4b8b-8db2-06c1ff058862

📥 Commits

Reviewing files that changed from the base of the PR and between afaf8ee and 0b7c0f2.

📒 Files selected for processing (1)
  • package.json
📝 Walkthrough

Walkthrough

Signup and signin now use IP-first dual rate limiting. The rate-limit utility adds client-IP extraction, target protection, fallback handling, reset support, and comprehensive tests.

Changes

Authentication rate limiting

Layer / File(s) Summary
IP-first rate-limit implementation
src/lib/rate-limit.ts, .jules/sentinel.md
Adds rateLimitDual, client-IP header handling, target fallback behavior, and resetRateLimits.
Authentication action integration
src/app/actions/auth.ts, src/app/actions/__tests__/auth-actions.test.ts
Signup and signin enforce 10 attempts per IP and 5 attempts per email within 60 seconds before authentication work. Tests reset rate-limit state.
Rate-limit behavior coverage
src/lib/__tests__/rate-limit.test.ts
Adds coverage for limits, cleanup, header extraction, normalized targets, IP-first rejection, and fallback behavior.

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

Possibly related PRs

Suggested reviewers: copilot

🚥 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 change: adding dual rate limiting to authentication server actions.
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.
✨ Finishing Touches 💡 1
🛠️ Fix failing CI checks 💡
  • Create stacked PR
  • Commit on current branch
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/sentinel-dual-rate-limiting-auth-actions-3105092884023430613

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

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (2)
src/app/actions/auth.ts (1)

35-37: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Replace em dashes in the new TypeScript comments.

  • src/app/actions/auth.ts#L35-L37: replace the em dash after work with a period or comma.
  • src/app/actions/auth.ts#L134-L136: replace the em dash after work with a period or comma.

As per coding guidelines, "Do not use emojis in code or commit messages, and do not use em-dashes."

🤖 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 `@src/app/actions/auth.ts` around lines 35 - 37, Replace the em dash after
“work” with a period or comma in the comments at src/app/actions/auth.ts lines
35-37 and 134-136; no other changes are needed.

Source: Coding guidelines

src/lib/__tests__/rate-limit.test.ts (1)

4-4: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Explain the mock purpose or remove the comment.

The comment restates the mock declaration. State why the tests need controllable request headers.

As per coding guidelines, "Comments should explain why."

🤖 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 `@src/lib/__tests__/rate-limit.test.ts` at line 4, Update the comment above the
next/headers mock to explain that the mock provides controllable request headers
for testing rate-limit behavior, rather than merely describing what is mocked.

Source: Coding guidelines

🤖 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 `@src/lib/rate-limit.ts`:
- Line 96: Normalize targetKey before the rateLimit call in the target-key path,
using the established key-normalization behavior or an explicit
normalized-target contract. In src/lib/rate-limit.ts lines 96-96, update the
code around rateLimit; in src/lib/__tests__/rate-limit.test.ts lines 51-77,
raise ipLimit above three and assert the third case-variant request is rejected
by targetLimit.

---

Nitpick comments:
In `@src/app/actions/auth.ts`:
- Around line 35-37: Replace the em dash after “work” with a period or comma in
the comments at src/app/actions/auth.ts lines 35-37 and 134-136; no other
changes are needed.

In `@src/lib/__tests__/rate-limit.test.ts`:
- Line 4: Update the comment above the next/headers mock to explain that the
mock provides controllable request headers for testing rate-limit behavior,
rather than merely describing what is mocked.
🪄 Autofix

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: 37e46914-a0a0-4044-a853-9f759253ae11

📥 Commits

Reviewing files that changed from the base of the PR and between 9d0e0bf and afaf8ee.

📒 Files selected for processing (5)
  • .jules/sentinel.md
  • src/app/actions/__tests__/auth-actions.test.ts
  • src/app/actions/auth.ts
  • src/lib/__tests__/rate-limit.test.ts
  • src/lib/rate-limit.ts

Comment thread src/lib/rate-limit.ts
}
}

return rateLimit(targetKey, targetLimit, targetWindowMs);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Normalize target keys and make the test evaluate the target bucket.

Line 96 sends case variants to separate target buckets. The test's third call is denied by ipLimit: 2 before it can validate target normalization.

  • src/lib/rate-limit.ts#L96-L96: normalize the target key before calling rateLimit, or define and enforce an explicit normalized-target contract.
  • src/lib/__tests__/rate-limit.test.ts#L51-L77: set ipLimit above three and assert that the third case variant is rejected by targetLimit.
Proposed fix
-  return rateLimit(targetKey, targetLimit, targetWindowMs);
+  return rateLimit(targetKey.toLowerCase(), targetLimit, targetWindowMs);
-        ipLimit: 2,
+        ipLimit: 5,
📍 Affects 2 files
  • src/lib/rate-limit.ts#L96-L96 (this comment)
  • src/lib/__tests__/rate-limit.test.ts#L51-L77
🤖 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 `@src/lib/rate-limit.ts` at line 96, Normalize targetKey before the rateLimit
call in the target-key path, using the established key-normalization behavior or
an explicit normalized-target contract. In src/lib/rate-limit.ts lines 96-96,
update the code around rateLimit; in src/lib/__tests__/rate-limit.test.ts lines
51-77, raise ipLimit above three and assert the third case-variant request is
rejected by targetLimit.

google-labs-jules Bot and others added 2 commits August 12, 2026 12:57
…nd resolve CI pnpm failure

- Implement asynchronous dual rate-limiting (`rateLimitDual`) inside `src/lib/rate-limit.ts` combining client IP checks (first) and target-based checks (second) to safeguard against credential stuffing and Account Lockout Denial of Service (DoS) attacks.
- Integrate `rateLimitDual` into both `signUpAction` and `signInAction` inside `src/app/actions/auth.ts` before database queries or CPU-intensive password-hashing verify calls.
- Implement helper function `resetRateLimits()` to clear maps and resolve inter-test pollution.
- Add comprehensive unit tests in `src/lib/__tests__/rate-limit.test.ts` to cover single and dual rate-limiting edge cases under `noUncheckedIndexedAccess`.
- Update `auth-actions.test.ts` to call `resetRateLimits` in its `beforeEach` hook.
- Pin `packageManager` in `package.json` to stable `pnpm@11.12.0` to prevent CI setup-pnpm self-installer failure with broken `pnpm@11.13.0`.
- Append critical security learnings to `sentinel.md` journal.

Co-authored-by: projectamazonph <286085559+projectamazonph@users.noreply.github.com>
…nd resolve CI pnpm failure

- Implement asynchronous dual rate-limiting (`rateLimitDual`) inside `src/lib/rate-limit.ts` combining client IP checks (first) and target-based checks (second) to safeguard against credential stuffing and Account Lockout Denial of Service (DoS) attacks.
- Integrate `rateLimitDual` into both `signUpAction` and `signInAction` inside `src/app/actions/auth.ts` before database queries or CPU-intensive password-hashing verify calls.
- Implement helper function `resetRateLimits()` to clear maps and resolve inter-test pollution.
- Add comprehensive unit tests in `src/lib/__tests__/rate-limit.test.ts` to cover single and dual rate-limiting edge cases under `noUncheckedIndexedAccess`.
- Update `auth-actions.test.ts` to call `resetRateLimits` in its `beforeEach` hook.
- Pin `packageManager` in `package.json` to the verified healthy `pnpm@11.14.0` version to resolve CI setup-pnpm self-installer failures with broken releases.
- Append critical security learnings to `sentinel.md` journal.

Co-authored-by: projectamazonph <286085559+projectamazonph@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants