Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Tornando Webhook mais seguro com JWT token #1318

Open
wants to merge 1 commit into
base: develop
Choose a base branch
from

Conversation

victoreduardo
Copy link

@victoreduardo victoreduardo commented Mar 19, 2025

Objetivo:

Validar se a mensagem está sendo enviada por um remetente autentico, evitando que requisições maliciosas utilizem a URL para enviar informações fraudulentas. Para isso, ao enviar a requisição para a URL do webhook, adicionamos uma camada de autenticação utilizando JWT token. Para quem utiliza n8n, por exemplo, conseguirá adicionar a autenticação por JWT no webhook, protegendo-o de requisições maliciosas.

Mudanças:

  • instala a dependencia jsonwebtoken para gerar o token
  • Quando hover a chave jwt_key dentro do campo headers da tabela Webhooks, então utilizaremos essa key para gerar o JWT token e encaminha-lo via requisição.

Summary by Sourcery

Enhance webhook security by adding JWT authentication. This ensures that webhook requests originate from an authenticated source, preventing malicious requests and fraudulent information.

Enhancements:

  • Implement JWT token generation and validation for webhook requests, using a 'jwt_key' in the webhook headers to generate a JWT token and include it in the Authorization header.
  • Add labels to the chat model.

Copy link

sourcery-ai bot commented Mar 19, 2025

Reviewer's Guide by Sourcery

This pull request introduces JWT authentication for webhooks, enhances the Chat model with labels, adds a unique constraint to the Chat model, and includes deployment configuration files.

Sequence diagram for Webhook JWT Authentication

sequenceDiagram
  participant Client
  participant WebhookController
  participant JWT
  participant Webhook

  Client->>WebhookController: Sends request to webhook URL with headers (including jwt_key)
  activate WebhookController
  WebhookController->>WebhookController: Checks for jwt_key in headers
  alt jwt_key exists
    WebhookController->>JWT: generateJwtToken(jwt_key)
    activate JWT
    JWT->>JWT: Sign payload with jwt_key using HS256
    JWT-->>WebhookController: Returns JWT token
    deactivate JWT
    WebhookController->>WebhookController: Adds Authorization header with JWT token
    WebhookController->>WebhookController: Removes jwt_key from headers
  end
  WebhookController->>Webhook: Sends request to webhook with updated headers (including Authorization)
  activate Webhook
  Webhook-->>WebhookController: Returns response
  deactivate Webhook
  WebhookController-->>Client: Returns response
  deactivate WebhookController
Loading

Updated class diagram for Chat model

classDiagram
  class Chat {
    instanceId: string
    remoteJid: string
    createdAt: DateTime
    labels: string[]
  }
  note for Chat "Added labels attribute to Chat model"
Loading

File-Level Changes

Change Details Files
Implements JWT authentication for webhook requests.
  • Adds logic to generate a JWT token if a jwt_key is present in the webhook headers.
  • Includes iat (issued at), exp (expiration), app, and action in the JWT payload.
  • Sets the token expiration time to 10 minutes.
  • Adds an Authorization header with the JWT token to the webhook request.
  • Removes the jwt_key from the headers before sending the request.
  • Adds error handling for JWT generation failures.
  • Adds jsonwebtoken as a project dependency.
src/api/integrations/event/webhook/webhook.controller.ts
package.json
Adds labels to the Chat model.
  • Adds labels field to the Chat model in the database query.
  • Includes labels in the mapped results for contacts.
src/api/services/channel.service.ts
Adds a unique constraint to the Chat model.
  • Adds a unique index on the instanceId and remoteJid columns of the Chat table.
prisma/postgresql-migrations/20250314220553_add_unique_chat/migration.sql
Adds deploy configuration file.
  • Adds a deploy.yml file to configure the deployment process.
config/deploy.yml
Adds kamal secrets file.
  • Adds a .kamal/secrets file to store sensitive information.
.kamal/secrets

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!
  • Generate a plan of action for an issue: Comment @sourcery-ai plan on
    an issue to generate a plan of action for it.

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

Copy link

@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 @victoreduardo - I've reviewed your changes - here's some feedback:

Overall Comments:

  • Consider adding a configuration option for the JWT expiration time, instead of hardcoding it to 10 minutes.
  • The addition of the jsonwebtoken dependency should be noted in the description.
Here's what I looked at during the review
  • 🟡 General issues: 1 issue found
  • 🟢 Security: all looks good
  • 🟢 Testing: all looks good
  • 🟢 Complexity: all looks good
  • 🟢 Documentation: all looks good

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.

@victoreduardo victoreduardo changed the title Tornando Webhook mais seguro com JWT Tornando Webhook mais seguro com JWT token Mar 19, 2025
@victoreduardo victoreduardo force-pushed the victoreduardos/jwt-webhook branch from 4b25e84 to cee2bc4 Compare March 19, 2025 21:04
@bergpinheiro
Copy link
Contributor

Se possivel deixar esse tipo de autenticação opcional. Nem todo mundo vai usar.

@victoreduardoss
Copy link

victoreduardoss commented Mar 20, 2025

Se possivel deixar esse tipo de autenticação opcional. Nem todo mundo vai usar.

a autenticação só é aplicada se existir jwt_key dentro de headers. Mesmo gerando a autenticação, ela só será utilizada se o destinatário (webhook URL) estiver habilitado para verificar a autenticação.

@DavidsonGomes DavidsonGomes changed the base branch from main to develop March 26, 2025 12:58
@DavidsonGomes
Copy link
Collaborator

Ajuste os conflitos e lint por favor, estava para a branch main, o correto é para a develop, rode o compando npm run lint

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.

4 participants