Skip to content

Add support for authentication in custom webhooks#6907

Merged
ogenstad merged 1 commit into
developfrom
pog-authenticated-custom-webhooks-IFC-1532
Jul 29, 2025
Merged

Add support for authentication in custom webhooks#6907
ogenstad merged 1 commit into
developfrom
pog-authenticated-custom-webhooks-IFC-1532

Conversation

@ogenstad

@ogenstad ogenstad commented Jul 28, 2025

Copy link
Copy Markdown
Contributor

This PR adds support for an optional shared_key to custom webhooks.

Most of the work consists of just moving some data from the standard webhooks to the generic parent class so that they work in a similar way.

It currently assumes that the content_type of the transforms is JSON which is the only option now but will change in the future: opsmill/infrahub-sdk-python#282

Fixes #6521

Summary by CodeRabbit

  • New Features

    • Added support for authentication and signing mechanisms to custom webhooks using an optional shared key.
    • All webhook types can now optionally sign requests with a shared key for enhanced security.
  • Bug Fixes

    • Updated tests to ensure the shared key attribute is properly handled in webhook conversions.
  • Documentation

    • Added a changelog entry describing the new authentication and signing support for custom webhooks.

@coderabbitai

coderabbitai Bot commented Jul 28, 2025

Copy link
Copy Markdown
Contributor

Walkthrough

The changes introduce support for an optional shared_key attribute to custom webhooks, enabling authentication via HMAC signing. Schema definitions, core protocols, and webhook models are updated to handle the new attribute. Associated logic for signing webhook requests is centralized and unified, and relevant tests are updated to reflect the new attribute.

Changes

Cohort / File(s) Change Summary
Protocols: Add shared_key to CoreCustomWebhook
backend/infrahub/core/protocols.py
Added optional shared_key attribute to CoreCustomWebhook class.
Schema: Add shared_key attribute to custom webhook node schema
backend/infrahub/core/schema/definitions/core/webhook.py
Added shared_key as an optional password attribute to core_custom_webhook NodeSchema.
Webhook Models: Centralize and extend shared_key/signing logic
backend/infrahub/webhook/models.py
Added shared_key to base Webhook, centralized signing logic, updated subclasses to utilize new logic, and ensured all webhook types can use shared key authentication.
Tests: Update expected output for shared_key
backend/tests/functional/webhook/test_task.py
Modified test to assert presence of shared_key (as None) in converted webhook output.
Changelog
changelog/6521.added.md
Added changelog entry describing new authenticated custom webhook support.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant System
    participant WebhookReceiver

    User->>System: Define Custom Webhook with optional shared_key
    System->>System: Store shared_key in schema and model
    System->>WebhookReceiver: Send webhook request
    alt shared_key is set
        System->>System: Sign request using HMAC with shared_key
        System->>WebhookReceiver: Include signature headers
    else shared_key is not set
        System->>WebhookReceiver: Send request without signature
    end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~15 minutes

Assessment against linked issues

Objective Addressed Explanation
Add support for defining a Shared Key on Custom Webhook (6521)
Allow authentication of Custom Webhook requests using Shared Key (6521)
Centralize signing/authentication logic for webhooks (6521)

Assessment against linked issues: Out-of-scope changes

No out-of-scope changes found.

Note

⚡️ Unit Test Generation is now available in beta!

Learn more here, or try it out under "Finishing Touches" below.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch pog-authenticated-custom-webhooks-IFC-1532

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary or Summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@github-actions github-actions Bot added the group/backend Issue related to the backend (API Server, Git Agent) label Jul 28, 2025
@codspeed-hq

codspeed-hq Bot commented Jul 28, 2025

Copy link
Copy Markdown

CodSpeed Performance Report

Merging #6907 will not alter performance

Comparing pog-authenticated-custom-webhooks-IFC-1532 (2c10007) with develop (0b78b35)

Summary

✅ 10 untouched benchmarks

@ogenstad ogenstad force-pushed the pog-authenticated-custom-webhooks-IFC-1532 branch from 02ac187 to dd71ded Compare July 28, 2025 15:22
@ogenstad ogenstad force-pushed the pog-authenticated-custom-webhooks-IFC-1532 branch from dd71ded to 2c10007 Compare July 29, 2025 06:49
@ogenstad ogenstad marked this pull request as ready for review July 29, 2025 07:45
@ogenstad ogenstad requested a review from a team as a code owner July 29, 2025 07:45

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

Actionable comments posted: 0

🔭 Outside diff range comments (1)
backend/tests/functional/webhook/test_task.py (1)

245-268: Add test coverage for custom webhooks with authentication.

The current test only covers custom webhooks without a shared_key. Consider adding a test case that validates the behavior when a custom webhook has a shared_key configured.

Would you like me to generate a test case that covers custom webhooks with authentication enabled?

🧹 Nitpick comments (3)
changelog/6521.added.md (1)

1-1: Enhance the changelog entry with more specific details.

The changelog should be more explicit about the authentication method being implemented (HMAC-SHA256 signing) and clarify whether JSON-only support for transforms is a current limitation or a permanent design decision.

-Added support for authentication / signing to custom webhooks. If using a transform it is assumed that the transform renders JSON data.
+Added support for HMAC-SHA256 authentication to custom webhooks via an optional `shared_key` attribute. When using transforms with authenticated webhooks, the transform output must be JSON-formatted (currently the only supported format).
backend/infrahub/webhook/models.py (2)

151-155: Remove unnecessary error handling in signing_key property.

The signing_key property raises an exception when shared_key is not set, but this property is only accessed when shared_key exists (line 135 checks this). The error case is unreachable.

     @property
     def signing_key(self) -> str:
         """Return the signing key for the webhook."""
-        if self.shared_key:
-            return self.shared_key
-        raise ValueError("Shared key is not set for the webhook")
+        return self.shared_key  # type: ignore[return-value]

217-236: Consider security implications of transform output in authenticated webhooks.

When using transforms with authenticated webhooks, the transform completely replaces the payload that gets signed. This means the transform has full control over what data is sent and signed. Ensure this is documented and that users understand the security implications.

Consider adding validation or restrictions on transform output when used with authenticated webhooks to prevent potential security issues where a compromised transform could send arbitrary signed data.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 0b78b35 and 2c10007.

📒 Files selected for processing (5)
  • backend/infrahub/core/protocols.py (1 hunks)
  • backend/infrahub/core/schema/definitions/core/webhook.py (1 hunks)
  • backend/infrahub/webhook/models.py (4 hunks)
  • backend/tests/functional/webhook/test_task.py (1 hunks)
  • changelog/6521.added.md (1 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
backend/**/*

📄 CodeRabbit Inference Engine (.github/copilot-instructions.md)

Run backend tests with pytest or via invoke tasks

Files:

  • backend/infrahub/core/protocols.py
  • backend/infrahub/core/schema/definitions/core/webhook.py
  • backend/tests/functional/webhook/test_task.py
  • backend/infrahub/webhook/models.py
backend/tests/**/*

📄 CodeRabbit Inference Engine (.github/copilot-instructions.md)

Place backend tests in backend/tests/

Files:

  • backend/tests/functional/webhook/test_task.py
🔇 Additional comments (4)
backend/infrahub/core/protocols.py (1)

322-322: Verify shared_key optionality in webhook models
I didn’t find any documentation or in-code comments explaining why CoreStandardWebhook requires shared_key while CoreCustomWebhook makes it optional. Please confirm that this difference is intentional (e.g., for backward-compatibility or differing security needs) or update the definitions accordingly.

• backend/infrahub/core/protocols.py
– Line 322: class CoreCustomWebhookshared_key: StringOptional
– Line 531: class CoreStandardWebhookshared_key: String

backend/infrahub/core/schema/definitions/core/webhook.py (1)

123-125: LGTM! Schema implementation is consistent and secure.

The shared_key attribute is properly implemented with:

  • Appropriate Password kind for sensitive data handling
  • Consistent order weight (4000) matching StandardWebhook
  • Correct optional flag aligning with the protocol definition
backend/infrahub/webhook/models.py (2)

191-191: Ensure consistent handling of optional shared_key.

Both CustomWebhook and TransformWebhook pass obj.shared_key.value directly, which could be None for custom webhooks. This is handled correctly by the base class, but consider adding a comment to clarify this is intentional.

Also applies to: 253-253


129-143: Fix potential issues in the webhook signing implementation.

The signing implementation has a few issues that should be addressed:

  1. When uuid is None, the code generates a new UUID but the logic seems incorrect (line 136)
  2. The JSON serialization of an empty payload as {} might cause signature mismatches
-            message_id = f"msg_{uuid.hex}" if uuid else f"msg_{uuid4().hex}"
-            timestamp = str(at.to_timestamp()) if at else str(Timestamp().to_timestamp())
+            message_id = f"msg_{uuid.hex if uuid else uuid4().hex}"
+            timestamp = str(at.to_timestamp() if at else Timestamp().to_timestamp())

Also consider handling the edge case where _payload is None:

-            payload = json.dumps(self._payload or {})
+            payload = json.dumps(self._payload if self._payload is not None else {})

Likely an incorrect or invalid review comment.

@ogenstad ogenstad merged commit a43e72d into develop Jul 29, 2025
38 of 39 checks passed
@ogenstad ogenstad deleted the pog-authenticated-custom-webhooks-IFC-1532 branch July 29, 2025 10:33
@coderabbitai coderabbitai Bot mentioned this pull request Aug 18, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

group/backend Issue related to the backend (API Server, Git Agent)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants