Skip to content

security: prevent cross-instance auth bypass via query/body override (CVE pending, #2435)#2549

Merged
DavidsonGomes merged 2 commits into
developfrom
security/cve-2435-cross-instance-bypass
May 19, 2026
Merged

security: prevent cross-instance auth bypass via query/body override (CVE pending, #2435)#2549
DavidsonGomes merged 2 commits into
developfrom
security/cve-2435-cross-instance-bypass

Conversation

@DavidsonGomes
Copy link
Copy Markdown
Member

@DavidsonGomes DavidsonGomes commented May 19, 2026

Resumo

Corrige a vulnerabilidade reportada em #2435CWE-639: Authorization Bypass Through User-Controlled Key — que permite que qualquer dono de instância autenticado opere sobre qualquer outra instância da mesma instalação Evolution API.

Vetor de ataque

GET /chat/findMessages/MY_INSTANCE?instanceName=VICTIM_INSTANCE
apikey: <token-de-MY_INSTANCE>
  • auth.guard.ts valida req.params.instanceName === MY_INSTANCE → ✅ passa
  • abstract.router.ts dataValidate() faz Object.assign(instance, req.query)instance.instanceName agora é VICTIM_INSTANCE
  • execute(instance, ...) roda contra a instância da vítima

Afetava todos os endpoints que usam dataValidate() com param=true (basicamente todo o app: instance, message, chat, group, integrations).

Fix

Introduz sanitizeUntrustedInput() em src/api/abstract/abstract.router.ts que filtra PROTECTED_INSTANCE_FIELDS = ['instanceName', 'instanceId'] de qualquer fonte não-confiável antes do merge no objeto instance. Loga warning em tentativas para auditoria.

Aplicado nos dois pontos vulneráveis:

  • Object.assign(instance, request.query) → sanitiza query
  • Object.assign(instance, body) (no fluxo /instance/create) → sanitiza body

Auditoria adicional

Busquei outros padrões `Object.assign(.*request)` no projeto. Os outros métodos do RouterBroker (groupNoValidate, groupValidate, inviteCodeValidate, getParticipantsValidate) atribuem no objeto body/ref (validado pelo schema), não no instance, então não compartilham o bug.

Diff

Por que não há teste

O projeto não tem suite de testes formal (ver CLAUDE.md → "No unit test suite currently implemented"). Em vez disso:

  • Build TypeScript passa (npm run build → success em ~3s)
  • Comportamento legítimo preservado: query strings continuam fundindo no instance, exceto pelos 2 campos protegidos
  • Fluxo /instance/create continua funcionando — body do create não deveria mesmo conter instanceName/instanceId (esses vêm da URL)

Próximos passos sugeridos (follow-up, não nesta PR)

  1. Habilitar Private Vulnerability Reporting em Settings → Security (reporter pediu, e é importante para CVEs futuros)
  2. Solicitar CVE oficial após merge — fazemos via MITRE ou GitHub Security Advisories
  3. Considerar refator: mover a validação final para o auth guard rodando após o merge (mais robusto contra futuras regressões)

Closes #2435
Reported by @lighthousekeeper1212 via análise estática.

🤖 Generated with Claude Code

Summary by Sourcery

Prevent cross-instance authorization bypass by blocking overrides of protected instance identifiers via untrusted request data.

Bug Fixes:

  • Harden instance request handling so query/body data can no longer override protected fields like instanceName and instanceId, preventing cross-instance auth bypass across all affected routes.

Enhancements:

  • Add centralized sanitization of untrusted request input with logging of attempts to override protected instance fields for easier auditing and future monitoring.

Chores:

  • Remove an unnecessary blank line in the WhatsApp Baileys integration service to satisfy linting.

DavidsonGomes and others added 2 commits May 19, 2026 12:26
…2435)

The auth guard in src/api/guards/auth.guard.ts validates instance
ownership using req.params.instanceName. The abstract router then
merged req.query (and, on /instance/create, req.body) into the
instance object via Object.assign — which silently overwrote the
already-authenticated instanceName.

An attacker with one valid token could send:

  GET /chat/findMessages/MY_INSTANCE?instanceName=VICTIM_INSTANCE

Auth passed for MY_INSTANCE, but dataValidate() then replaced the
instance with VICTIM_INSTANCE before execute() ran — giving the
caller full access to read/send messages, modify settings, and
delete other tenants' instances.

CWE-639: Authorization Bypass Through User-Controlled Key

Fix: introduce sanitizeUntrustedInput() that strips
PROTECTED_INSTANCE_FIELDS (instanceName, instanceId) from any
untrusted source before merging into the instance object. Logs a
warning on attempts so abuse is auditable.

Closes #2435
Reported by @lighthousekeeper1212 via static analysis.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Pre-push lint flagged whatsapp.baileys.service.ts:531 (double blank
line after the stream:error 515 fix merged via #2509). Trivial
prettier fix.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
@sourcery-ai
Copy link
Copy Markdown
Contributor

sourcery-ai Bot commented May 19, 2026

Reviewer's guide (collapsed on small PRs)

Reviewer's Guide

Adds input sanitization in the abstract router to prevent cross-instance authorization bypass by blocking overrides of protected instance fields from query/body, and includes a minor formatting cleanup in the WhatsApp Baileys service.

Sequence diagram for sanitized instance merging in dataValidate

sequenceDiagram
  actor Client
  participant AuthGuard
  participant RouterBroker
  participant sanitizeUntrustedInput
  participant Controller

  Client->>AuthGuard: validate(instanceName from params)
  AuthGuard-->>Client: authorized

  Client->>RouterBroker: dataValidate(request, body)
  activate RouterBroker
  RouterBroker->>RouterBroker: instance = request.params

  alt request.query present
    RouterBroker->>sanitizeUntrustedInput: sanitizeUntrustedInput(request.query)
    sanitizeUntrustedInput-->>RouterBroker: sanitizedQuery (no instanceName, instanceId)
    RouterBroker->>RouterBroker: Object.assign(instance, sanitizedQuery)
  end

  alt request.originalUrl includes /instance/create
    RouterBroker->>sanitizeUntrustedInput: sanitizeUntrustedInput(body)
    sanitizeUntrustedInput-->>RouterBroker: sanitizedBody (no instanceName, instanceId)
    RouterBroker->>RouterBroker: Object.assign(instance, sanitizedBody)
  end

  RouterBroker->>Controller: execute(instance, ref, body)
  deactivate RouterBroker
Loading

File-Level Changes

Change Details Files
Sanitize untrusted request input before merging into the instance object to prevent overriding protected fields used for authorization.
  • Introduce a PROTECTED_INSTANCE_FIELDS constant listing protected instance properties that must not be overridden by clients.
  • Add sanitizeUntrustedInput(source) helper that filters out protected fields from arbitrary input objects and logs a warning when an override attempt is detected.
  • Use sanitizeUntrustedInput on request.query before merging into the instance object in dataValidate.
  • Use sanitizeUntrustedInput on the request body in the /instance/create flow before merging into the instance object, while keeping the existing merge into ref/body untouched.
src/api/abstract/abstract.router.ts
Minor cleanup in WhatsApp Baileys integration service.
  • Remove an unnecessary blank line inside the BaileysStartupService reconnect logic.
src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts

Possibly linked issues


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

@DavidsonGomes DavidsonGomes merged commit 7a55a2b into develop May 19, 2026
5 checks passed
@DavidsonGomes DavidsonGomes deleted the security/cve-2435-cross-instance-bypass branch May 19, 2026 15:30
Copy link
Copy Markdown
Contributor

@sourcery-ai sourcery-ai Bot left a comment

Choose a reason for hiding this comment

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

Hey - I've left some high level feedback:

  • Consider centralizing the PROTECTED_INSTANCE_FIELDS in a more globally shared config or type definition so any future places that need to protect instance identifiers can reuse the same list without duplicating constants.
  • The sanitizeUntrustedInput helper currently accepts Record<string, any> and returns a broad Record<string, any>; you could tighten its typing (e.g., using generics) so callers preserve stronger types while still getting the protected-field filtering.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- Consider centralizing the `PROTECTED_INSTANCE_FIELDS` in a more globally shared config or type definition so any future places that need to protect instance identifiers can reuse the same list without duplicating constants.
- The `sanitizeUntrustedInput` helper currently accepts `Record<string, any>` and returns a broad `Record<string, any>`; you could tighten its typing (e.g., using generics) so callers preserve stronger types while still getting the protected-field filtering.

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

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