Skip to content

Django Signals for Automated Webhook Notifications #2317

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

Open
wants to merge 10 commits into
base: main
Choose a base branch
from

Conversation

TBoykott
Copy link

@TBoykott TBoykott commented Jul 22, 2025

The signals.py file in backend/core/ defines Django signal handlers that automatically monitor changes to two key models: ComplianceAssessment and AppliedControl. Whenever the status of these objects changes or a new object is created, the signals trigger and send a structured JSON payload to an external webhook URL (configured via the NOTIFICATION_WEBHOOK_URL environment variable).
This mechanism enables seamless integration with external systems (such as SIEM, ticketing, or monitoring tools) by providing real-time notifications about important compliance and control events within the application. The file centralizes and automates the notification logic, ensuring that key changes are always communicated to interested third-party services without manual intervention.

Summary by CodeRabbit

  • New Features

    • Added support for sending notifications to a configurable webhook when certain compliance or control statuses change or new assessments are created.
    • Introduced a new environment variable to configure the notification webhook URL.
  • Chores

    • Updated ignore files for Docker and Git to better manage excluded files and directories.
    • Streamlined Dockerfile build steps for improved efficiency.
    • Adjusted Docker Compose configuration to use a local backend image and set the notification webhook URL.

TBoykott added 2 commits July 22, 2025 11:36
- Add notification webhook URL to settings.py.
- Import custom signals in core apps.py for better signal management.
- Update Docker configuration and ignore files
- Refactor .dockerignore to include additional files and directories.
- Update docker-compose.yml to use a local backend image and add a new environment variable for notification webhook URL.
- Modify backend .gitignore to streamline ignored files and directories.
- Adjust Dockerfile to simplify poetry installation process.
Copy link
Contributor

github-actions bot commented Jul 22, 2025

CLA Assistant Lite bot All contributors have signed the CLA ✍️ ✅

@TBoykott
Copy link
Author

I have read the CLA Document and I hereby sign the CLA

github-actions bot added a commit that referenced this pull request Jul 22, 2025
Copy link
Contributor

coderabbitai bot commented Jul 22, 2025

Walkthrough

The changes introduce Django signal handlers to monitor status changes and creations for specific models, sending webhook notifications when relevant events occur. Supporting configuration and environment variable handling are added, along with updates to Docker and ignore files. The Docker Compose and Dockerfile setups are adjusted for local development and notification support.

Changes

File(s) Change Summary
.dockerignore, backend/.gitignore Expanded and reorganized ignore patterns for Docker and Git, including new directories and files, and removing some previous ignores
backend/Dockerfile Consolidated poetry install and cache removal into a single RUN command for efficiency
backend/ciso_assistant/settings.py Added NOTIFICATION_WEBHOOK_URL setting, sourced from environment variable
backend/core/apps.py Imported core.signals in app ready method to activate signal handlers
backend/core/signals.py New module: Defines Django signal handlers for model status changes and creations, sending notifications via webhook
backend/manage.py Commented out import of signals module
docker-compose.yml Changed backend image to local build, added NOTIFICATION_WEBHOOK_URL environment variable

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant DjangoApp
    participant SignalsModule
    participant Webhook

    User->>DjangoApp: Create or update ComplianceAssessment/AppliedControl
    DjangoApp->>SignalsModule: pre_save or post_save signal triggered
    SignalsModule->>SignalsModule: Compare status/creation, build payload
    alt Webhook URL configured
        SignalsModule->>Webhook: Send POST request with payload
        Webhook-->>SignalsModule: Responds with status
    else No webhook URL
        SignalsModule->>SignalsModule: Log missing configuration
    end
Loading

Estimated code review effort

4 (~90 minutes)

Poem

In the warren of code, a signal is sent,
When models change status, off a webhook it went.
Ignore files are tidied, the Docker build’s neat,
New settings and configs make the system complete.
With a twitch of my nose and a hop in my heart,
I celebrate changes—automation’s an art!
🐇✨


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 8c07104 and 4d60982.

📒 Files selected for processing (3)
  • backend/core/apps.py (1 hunks)
  • backend/core/signals.py (1 hunks)
  • docker-compose.yml (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • backend/core/apps.py
  • docker-compose.yml
🔇 Additional comments (4)
backend/core/signals.py (4)

1-11: LGTM! Clean imports and configuration setup.

The imports are properly organized and the webhook URL configuration follows Django best practices with appropriate fallback handling.


13-24: LGTM! Robust webhook notification implementation.

The function properly handles configuration checks, includes appropriate timeout settings, and uses specific exception handling. The logging approach correctly avoids exposing sensitive webhook URLs.


26-51: LGTM! Comprehensive payload structure with proper data handling.

The function creates a well-structured payload that includes all relevant fields with appropriate null handling for dates and structured data for related objects.


121-139: LGTM! Consistent and well-implemented signal handler.

The AppliedControl signal handler follows the same robust pattern as the ComplianceAssessment handler with proper status change detection, error handling, and logging.

✨ Finishing Touches
  • 📝 Generate Docstrings

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
🪧 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 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 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.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🧹 Nitpick comments (5)
backend/core/apps.py (1)

17-17: Use English for comment consistency.

The signal import is correctly placed, but the comment should be in English to maintain consistency with the rest of the codebase.

-        import core.signals  # Active les signaux personnalisés
+        import core.signals  # Activate custom signal handlers
docker-compose.yml (1)

4-4: Consider image consistency between backend and huey services.

The backend service now uses a local 'backend' image while the huey service still uses the remote image. This could lead to version mismatches. Consider whether both services should use the same image source for consistency.

If using local development setup:

 backend:
   container_name: backend
   image: backend
   
 huey:
   container_name: huey
-  image: ghcr.io/intuitem/ciso-assistant-community/backend:latest
-  pull_policy: always
+  image: backend
backend/core/signals.py (3)

1-9: Consolidate imports and remove verbose logging

  1. Combine the signal imports from lines 2 and 6 into a single import statement
  2. The module load logging on line 9 is unnecessary and will add noise to production logs
 import logging
-from django.db.models.signals import pre_save
+from django.db.models.signals import pre_save, post_save
 from django.dispatch import receiver
 from django.conf import settings
 from core.models import ComplianceAssessment, AppliedControl
-from django.db.models.signals import post_save

 logger = logging.getLogger(__name__)
-logger.info('signals.py loaded')

55-88: Translate comment and good defensive programming

The defensive programming for computed fields (lines 60-68) and attribute checks (lines 77, 84) is excellent. However, the French comment on line 87 should be in English.

         'compliance_percentage': compliance_percentage,
         'progress_percentage': progress_percentage,
-        # Ajoute d'autres champs si besoin
+        # Add other fields if needed
     }

14-141: Consider production-ready enhancements

For a production environment, consider these architectural improvements:

  1. Bulk operations: Current signals fire for each instance in bulk updates, which could overwhelm the webhook endpoint
  2. Async processing: Webhook calls are synchronous and could slow down save operations
  3. Retry mechanism: Failed webhook calls are not retried
  4. Dead letter queue: Failed notifications are lost

Consider using a task queue (like Celery) for asynchronous webhook delivery with retry logic.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 47e36f3 and 8c07104.

📒 Files selected for processing (8)
  • .dockerignore (1 hunks)
  • backend/.gitignore (1 hunks)
  • backend/Dockerfile (1 hunks)
  • backend/ciso_assistant/settings.py (1 hunks)
  • backend/core/apps.py (1 hunks)
  • backend/core/signals.py (1 hunks)
  • backend/manage.py (1 hunks)
  • docker-compose.yml (1 hunks)
🧠 Learnings (2)
docker-compose.yml (1)

Learnt from: ab-smith
PR: intuitem/ciso-assistant-community#0
File: :0-0
Timestamp: 2025-01-21T19:16:31.223Z
Learning: The new Helm chart for CISO Assistant supports both SQLite and PostgreSQL modes, with backend and frontend pods separated, and includes configurable security contexts (disabled by default).

backend/Dockerfile (1)

Learnt from: nas-tabchiche
PR: #1641
File: dispatcher/startup.sh:1-6
Timestamp: 2025-04-17T17:28:15.732Z
Learning: In the CISO Assistant project, the startup.sh script is an entrypoint script that's intended to be executed only inside Docker containers where the uv package manager is installed at build time. The uv run commands are appropriate in this context.

🧰 Additional context used
🧠 Learnings (2)
docker-compose.yml (1)

Learnt from: ab-smith
PR: intuitem/ciso-assistant-community#0
File: :0-0
Timestamp: 2025-01-21T19:16:31.223Z
Learning: The new Helm chart for CISO Assistant supports both SQLite and PostgreSQL modes, with backend and frontend pods separated, and includes configurable security contexts (disabled by default).

backend/Dockerfile (1)

Learnt from: nas-tabchiche
PR: #1641
File: dispatcher/startup.sh:1-6
Timestamp: 2025-04-17T17:28:15.732Z
Learning: In the CISO Assistant project, the startup.sh script is an entrypoint script that's intended to be executed only inside Docker containers where the uv package manager is installed at build time. The uv run commands are appropriate in this context.

🔇 Additional comments (6)
backend/ciso_assistant/settings.py (1)

499-499: No action needed—None/empty URL is handled in send_webhook_notification.

The signal handler in backend/core/signals.py already does:

  • Retrieves WEBHOOK_URL with a default of None.
  • Checks if not WEBHOOK_URL and logs a warning before skipping.

This covers both None and empty values, so the new setting is safe as-is.

backend/.gitignore (1)

21-21: No action needed: root docker-compose.yml contains local overrides

The docker-compose.yml in the project root holds environment-specific settings (debug flags, webhook URLs, etc.) and isn’t meant to be version-controlled. The canonical compose definitions live under config/ (as templates and build scripts), so ignoring the root file prevents accidental commits of sensitive or local overrides.

backend/manage.py (1)

6-6: LGTM! Proper signal registration pattern.

Moving the signals import from manage.py to the app's ready() method is the correct Django approach. This ensures signal handlers are registered once during app initialization rather than on every management command execution.

backend/Dockerfile (1)

43-44: Good optimization: Consolidated RUN commands

Combining the poetry install and cache cleanup into a single RUN instruction reduces Docker layers, which improves build efficiency and reduces image size.

.dockerignore (1)

2-15: Improved Docker build context exclusions

The updated patterns provide better coverage:

  • Recursive .DS_Store matching is more comprehensive
  • Added cache directories (__pycache__, .pytest_cache, .ruff_cache) reduce context size
  • Including db, static/, and test artifacts is appropriate
  • Excluding .dockerignore and Dockerfile from the build context is a best practice
backend/core/signals.py (1)

91-141: Well-implemented signal handlers

The signal handlers are properly structured with:

  • Clear separation between creation and update logic
  • Comprehensive logging for debugging
  • Proper handling of DoesNotExist exceptions
  • Correct use of pre_save for status changes and post_save for creation notifications

@ab-smith
Copy link
Contributor

Hello,
thank you for the contribution, we really appreciate it 🙏
This feature is currently being developed on our side, but we can consider a mixture between the two.

Two pointers:

  • going with full signals is not prefered given their overhead on performance and how tricky they can be to debug. We believe that relevant changes to capture won't concern all objects and we can afford to override the save methods for relevant ones.
  • you've made some strange changes on .gitignore. Was it a mistake?

@TBoykott
Copy link
Author

Hello @ab-smith ,

I appreciate your feedback and am pleased to hear that this feature is being developed on your end.

Regarding your two points, I recognize that there's a performance issue, and I may address it in my next optimization. As for the .gitignore file, including it was an error.. There are URLs in the docker-compose that I prefer not to expose publicly.

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