Skip to content

Potential fix for code scanning alert no. 367: Missing rate limiting - #85

Closed
mmeerrkkaa wants to merge 1 commit into
masterfrom
alert-autofix-367
Closed

mmeerrkkaa wants to merge 1 commit into
masterfrom
alert-autofix-367

Conversation

@mmeerrkkaa

@mmeerrkkaa mmeerrkkaa commented Oct 5, 2026 •

Copy link
Copy Markdown
Member

Potential fix for https://github.com/blockmineJS/blockmine/security/code-scanning/367

To fix missing rate limiting without changing functionality, keep the existing applyLimiter configuration but apply it before authenticateUniversal and authorize(...) in the /apply route middleware chain.

Best single fix in this file:

  • In backend/src/api/routes/panelUpdate.js, update the /apply route declaration so applyLimiter is the first middleware argument after the path.
  • No new imports, methods, or dependency changes are required.
  • This addresses all alert variants because they all refer to auth/authz occurring before rate limiting on the same route.

Suggested fixes powered by Copilot Autofix. Review carefully before merging.

Summary by Sourcery

Bug Fixes:

  • Apply rate limiting before authentication and authorization on the panel update endpoint to address the missing rate-limiting code scanning alert.

Summary by CodeRabbit

  • Изменения
    • Ограничение частоты запросов применяется до проверки авторизации при отправке настроек панели.

Co-authored-by: Copilot Autofix powered by AI <62310815+github-advanced-security[bot]@users.noreply.github.com>
@coderabbitai

coderabbitai Bot commented Oct 5, 2026 •

Copy link
Copy Markdown

Review in Change Stack →

Note

Currently processing new changes in this PR. This may take a few minutes, please wait...

⚙️ Run configuration
  • Configuration used: Organization UI
  • Review profile: ASSERTIVE
  • Plan: Advanced
  • Run ID: 97af1b5e-e12d-41f8-a88d-c97ac001637f
📥 Commits

Reviewing files that changed from the base of the PR and between 04b9f78 and 65c4400.

📒 Files selected for processing (1)
  • backend/src/api/routes/panelUpdate.js
 __________________________________________
< Performing energy-intensive code review. >
 ------------------------------------------
  \
   \   \
        \ /\
        ( )
      .( o ).
✨ Finishing Touches
📝 Generate docstrings
  • Commit to this branch
  • Create a new PR
🧪 Generate unit tests (beta)
  • Commit to this branch
  • Create a new PR
  • Autopilot · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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.

@sourcery-ai

sourcery-ai Bot commented Oct 5, 2026 •

Copy link
Copy Markdown
Contributor
Reviewer's guide (collapsed on small PRs)

Reviewer's Guide

The /apply panel update endpoint now applies its existing rate limiter before authentication and authorization, addressing the missing-rate-limiting alert without changing endpoint functionality or dependencies.

Sequence diagram for rate-limited panel update application

sequenceDiagram
    actor Client
    participant PanelUpdate as PanelUpdateEndpoint
    participant Limiter as applyLimiter
    participant Auth as authenticateUniversal
    participant Authorize as authorize
    participant Service as PanelUpdateService

    Client->>PanelUpdate: POST /apply
    PanelUpdate->>Limiter: applyLimiter
    alt rate limit exceeded
        Limiter-->>Client: Reject request
    else request allowed
        Limiter->>Auth: authenticateUniversal
        Auth->>Authorize: authorize(panel:settings:edit)
        Authorize->>Service: applyUpdate()
        Service-->>Client: Update result
    end
Loading

File-Level Changes

Change Details Files
Reorders the /apply middleware chain so rate limiting runs before authentication and authorization.
  • Moves the existing applyLimiter middleware to the first position after the route path.
  • Preserves the existing authentication, authorization, handler logic, configuration, and dependencies.
backend/src/api/routes/panelUpdate.js

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@mmeerrkkaa
mmeerrkkaa marked this pull request as ready for review October 5, 2026 22:40

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

Hey - I've found 1 issue

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location path="backend/src/api/routes/panelUpdate.js" line_range="39" />
<code_context>
 });

-router.post('/apply', authenticateUniversal, authorize('panel:settings:edit'), applyLimiter, async (req, res) => {
+router.post('/apply', applyLimiter, authenticateUniversal, authorize('panel:settings:edit'), async (req, res) => {
     try {
         const result = await PanelUpdateService.applyUpdate();
</code_context>
<issue_to_address>
**Administrators get blocked from updates**

When an unauthenticated client sends 20 POSTs from the same observed IP within five minutes before an administrator’s request, `applyLimiter` charges the IP-based quota before `authenticateUniversal` runs, so those requests exhaust the bucket and the administrator’s update request receives 429.

Run `authenticateUniversal` and `authorize` before `applyLimiter`.

Also at `backend/src/api/routes/panelUpdate.js:40`.
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨

});

router.post('/apply', authenticateUniversal, authorize('panel:settings:edit'), applyLimiter, async (req, res) => {
router.post('/apply', applyLimiter, authenticateUniversal, authorize('panel:settings:edit'), async (req, res) => {

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.

🟡 Medium · Administrators get blocked from updates

When an unauthenticated client sends 20 POSTs from the same observed IP within five minutes before an administrator’s request, applyLimiter charges the IP-based quota before authenticateUniversal runs, so those requests exhaust the bucket and the administrator’s update request receives 429.

Run authenticateUniversal and authorize before applyLimiter.

Also at backend/src/api/routes/panelUpdate.js:40.

Prompt for AI agents
In `backend/src/api/routes/panelUpdate.js` at line 39:

**Administrators get blocked from updates**

When an unauthenticated client sends 20 POSTs from the same observed IP within five minutes before an administrator’s request, `applyLimiter` charges the IP-based quota before `authenticateUniversal` runs, so those requests exhaust the bucket and the administrator’s update request receives 429.

Run `authenticateUniversal` and `authorize` before `applyLimiter`.

Also at `backend/src/api/routes/panelUpdate.js:40`.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

конкретнее. Если на одном айпи есть аккаунты админа и юзера7

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

🟡 Medium · Администраторы не могут получать обновления

Когда неаутентифицированный клиент отправляет 20 POST-запросов с одного и того же наблюдаемого IP-адреса в течение пяти минут до запроса администратора, applyLimiterэто приводит к исчерпанию квоты, основанной на IP-адресе authenticateUniversal, и, следовательно, к исчерпанию лимита запросов, а запрос на обновление от администратора получает ошибку 429.

Запустите authenticateUniversalи authorizeперед этим applyLimiter.

Также по адресу backend/src/api/routes/panelUpdate.js:40.

Запрос для агентов ИИ

конкретнее. Если на одном айпи есть аккаунты админа и юзера7

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.

Да. При текущем порядке (applyLimiter → authenticateUniversal → authorize) лимитер, судя по конфигурации, учитывает IP, а не аккаунт. Поэтому если администратор и user7 находятся за одним IP, их запросы /apply используют общий лимит в 20 запросов за 5 минут:

  • 20 запросов user7 исчерпают общий bucket;
  • следующий запрос администратора с того же IP получит 429;
  • это произойдёт даже если у администратора есть право panel:settings:edit.

Перестановка authenticateUniversal перед applyLimiter не разделит лимит между администратором и user7; она лишь не позволит неаутентифицированным запросам расходовать этот IP-бюджет. Чтобы аккаунты с одним IP не блокировали друг друга, лимитер должен использовать ключ, основанный на аутентифицированном пользователе или API-ключе, а не только на IP.

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.

Если администратор и user7 находятся за одним IP, то в текущем варианте applyLimiter они используют один общий IP-бакет:

  • первые 20 POST /apply за 5 минут — независимо от того, кто их отправил;
  • 21-й запрос, включая запрос администратора, получит 429;
  • неавторизованные запросы также расходуют этот же лимит, потому что applyLimiter выполняется первым.

Если поставить authenticateUniversal и authorize перед applyLimiter, запросы без авторизации или без права panel:settings:edit будут отклоняться до rate limiter и не смогут исчерпать его лимит. Но два авторизованных аккаунта с одного IP всё равно будут делить общий IP-лимит. Для раздельного лимитирования по аккаунтам потребовался бы отдельный ключ на основе идентификатора пользователя.

@mmeerrkkaa mmeerrkkaa closed this Oct 5, 2026
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.

1 participant