Skip to content

Conversation

@krrish-sehgal
Copy link
Contributor

@krrish-sehgal krrish-sehgal commented Mar 17, 2025

Fixed #3864 and #3860
Screenshot 2025-03-18 at 8 40 33 AM

Screenshot 2025-03-18 at 8 40 39 AM

Summary by CodeRabbit

  • New Features

    • Introduced a new HTML email template for notifying users about new encrypted chat sessions.
    • Added a plain text version of the new chat email notification.
    • Enhanced the messaging thread creation process to include email notifications for users when a new thread is initiated.
  • Refactor

    • Streamlined the messaging process by simplifying how security keys are retrieved and updated, improving the efficiency of message handling for a smoother user experience.

Summary by CodeRabbit

  • New Features
    • Added visually enhanced email notifications for new encrypted chat sessions. Recipients now receive an email—with a direct link to the chat—when a new conversation is initiated. This update improves communication flow in secure messaging sessions.

@krrish-sehgal krrish-sehgal changed the title Direct messagse caching of key fixed Mar 17, 2025
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Mar 17, 2025

Walkthrough

This pull request streamlines the public key fetching method in the messaging template by directly updating the cached key. It adds a new HTML template for new encrypted chat email notifications and updates the thread creation view to send out these email notifications when a new messaging thread is initiated.

Changes

File(s) Change Summary
website/templates/messaging.html Simplified public key retrieval logic by removing the conditional cached check. The public key is now directly fetched from the server and assigned to cachedRecipientPublicKey, and the associated comment has been updated.
website/templates/email/new_chat.html Added a new HTML template for email notifications. The template includes meta tags, styling, a header with "New Encrypted Chat", message content addressing the recipient, a call-to-action button linking to the chat, and a signature.
website/views/user.py Updated the start_thread function to detect new threads and, when applicable, send an email notification. The function now creates a new thread if one does not exist and sends an email (using both plain text and HTML templates) to the other user if they have an email address.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Server
    participant EmailService

    User->>Server: Request to start new messaging thread
    alt No existing thread
        Server->>Server: Create new thread
    end
    alt Recipient has an email address
        Server->>EmailService: Invoke send_mail with plain text & HTML templates (including new_chat.html)
        EmailService-->>Server: Email sent confirmation
    end
Loading

Tip

⚡🧪 Multi-step agentic review comment chat (experimental)
  • We're introducing multi-step agentic chat in review comments. This experimental feature enhances review discussions with the CodeRabbit agentic chat by enabling advanced interactions, including the ability to create pull requests directly from comments.
    - To enable this feature, set early_access to true under in the settings.

📜 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 4396125 and f169b32.

📒 Files selected for processing (1)
  • website/views/user.py (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • website/views/user.py
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: Run Tests
  • GitHub Check: docker-test
  • GitHub Check: Analyze (python)

🪧 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.
    • Generate unit testing code for this file.
    • 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 generate unit testing code for this file.
    • @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 generate unit testing code.
    • @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.

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

@krrish-sehgal
Copy link
Contributor Author

@coderabbitai does this meets the requirements of #3864

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Mar 17, 2025

Tip

For best results, initiate chat on the files or code changes.

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# First, let's get details about the issue
gh issue view 3864 --repo OWASP-BLT/BLT

# Next, let's look at the PR changes
git diff --stat HEAD~1 HEAD

# Get more details about the changes
git show

Length of output: 74249


🏁 Script executed:

#!/bin/bash
# First, let's get the specific PR details
gh pr view 3972 --repo OWASP-BLT/BLT

# Let's find files related to the issue by searching for keywords
git log -p -G "recipient public key" --oneline
git log -p -G "caching of key" --oneline

# Try to find the specific changes in this PR
git fetch origin pull/3972/head:pr-3972
git checkout pr-3972
git diff origin/main -- $(git diff --name-only origin/main)

# Let's look for any chat-related files or encryption files
find . -type f -name "*.py" | xargs grep -l "chat" | head -10
find . -type f -name "*.py" | xargs grep -l "encrypt" | head -10
find . -type f -name "*.js" | xargs grep -l "decrypt" | head -10

Length of output: 2904


@krrish-sehgal Yes, the changes in PR #3972 do meet the requirements of issue #3864.

Looking at issue #3864 "Remove caching of recepient public key, or change it as soon as the chat is changed", I can see that your PR properly addresses this by modifying the messaging.html file to always fetch the recipient's public key when loading messages, rather than relying on a cached version.

Specifically, you changed the code from:

  1. Previously: Only fetching a new public key if the cached one (cachedRecipientPublicKey) wasn't available
  2. Now: Always fetching a fresh copy of the recipient's public key via API call

This change ensures that the encryption/decryption process always uses the most up-to-date public key, which should prevent the "Error decrypting message: OperationError" mentioned in the issue.

The implementation is clean and focused on the specific problem, making it a good solution for the reported issue.

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: 0

🧹 Nitpick comments (1)
website/templates/messaging.html (1)

336-340: Refined Key Fetching Logic in openChat

The updated code now unconditionally fetches and updates the recipient's public key from the server before loading messages. This change streamlines the process by eliminating the previous conditional check, ensuring that the most up-to-date key is always used in this context.

Please verify that this behavior is intended solely for the message-loading workflow in openChat. Notably, the "send message" event handler (lines 378–384) still uses a conditional check to fetch the key. If the goal is to consistently avoid caching in favor of always retrieving a fresh key, you might consider aligning that logic as well or documenting why the approaches differ.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 92131a1 and 8f01ee7.

📒 Files selected for processing (1)
  • website/templates/messaging.html (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: Run Tests
  • GitHub Check: docker-test
  • GitHub Check: Analyze (javascript-typescript)

coderabbitai[bot]
coderabbitai bot previously approved these changes Mar 17, 2025
@krrish-sehgal
Copy link
Contributor Author

@coderabbitai can you help me point out how can i fix #3860 in this PR itself, by pointing out the right pre exisiting email code

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Mar 17, 2025

Tip

For best results, initiate chat on the files or code changes.

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Get details about issue #3860
gh issue view 3860 --repo OWASP-BLT/BLT

# Let's search for email-related files/code
find . -type f -name "*.py" | xargs grep -l "email" | head -15
find . -type f -name "*.py" | xargs grep -l "send_mail" | head -10
find . -type f -name "*.py" | xargs grep -l "EmailMessage" | head -10

# Let's look at some potential email utility files
find . -path "*/utils*" -type f -name "*.py" | xargs grep -l "email" | head -10

Length of output: 1400


🏁 Script executed:

#!/bin/bash
# Let's look at the main email-related files
echo "==== website/management/commands/email.py ===="
cat website/management/commands/email.py

echo "==== website/utils.py (email-related functions) ===="
grep -n -A 20 -B 5 "email\|mail" website/utils.py | head -50

echo "==== website/views/issue.py (EmailMessage usage) ===="
grep -n -A 10 -B 5 "EmailMessage" website/views/issue.py

# Let's also look at the messaging functionality to understand where to integrate email notifications
echo "==== Examining messaging views/templates ===="
find . -type f -name "*.py" | xargs grep -l "message\|chat" | head -10

# Looking specifically for the chat/messaging view
find website -type f -name "*.py" | xargs grep -n -l "def message" || echo "No direct message function found"

Length of output: 6383


🏁 Script executed:

#!/bin/bash
# Let's examine the messaging functionality code more closely
echo "==== Looking for messaging views/controllers ===="
find website -type f -name "views.py" | xargs grep -l "message\|chat" | head -10

# Let's look at website/views.py or website/views/chat.py if it exists
find website/views -type f -name "*.py" | xargs grep -l "message\|chat" | head -10

# Let's check the current PR to understand the messaging.html file that's being modified
echo "==== Current PR changes ===="
git show

# Look at the website/templates/messaging.html file 
echo "==== website/templates/messaging.html ===="
cat website/templates/messaging.html | head -100

# Look for files handling notifications or sending emails for other features
echo "==== Files with notification functions ===="
find website -type f -name "*.py" | xargs grep -n "def.*notif\|send_.*mail" | head -15

Length of output: 74391


🏁 Script executed:

#!/bin/bash
# Let's first get the full content of website/templates/messaging.html
echo "==== website/templates/messaging.html (full file) ===="
cat website/templates/messaging.html

# Let's examine the views that might handle the messaging functionality
echo "==== Looking for chat/messaging related views ===="
grep -r "def.*message\|def.*chat" --include="*.py" website/

# Let's look for email sending functionality
echo "==== Looking for email sending functions ===="
grep -r "send_mail\|send_email" --include="*.py" website/

Length of output: 22952


🏁 Script executed:

#!/bin/bash
# Let's look at the consumer implementation which handles saving messages
echo "==== website/consumers.py (save_message function) ===="
grep -A 30 "def save_message" website/consumers.py

# Let's examine the messaging models to understand thread structure
echo "==== website/models.py (messaging related models) ===="
grep -A 50 "class Message\|class Thread" website/models.py

# Let's look at issue 3860 details to confirm requirements
echo "==== Details for issue 3860 ===="
gh issue view 3860 --repo OWASP-BLT/BLT

# Look at the notification logic to understand email formatting
echo "==== Examining a typical email sending example ===="
grep -A 20 -B 5 "send_mail" website/views/issue.py | head -40

Length of output: 6896


@krrish-sehgal Looking at issue #3860, I'll help you implement email notifications when someone starts an encrypted chat. Let me show you how to add this feature to the current PR:

First, I need to see the current implementation of the messaging consumer where new messages are saved:


🏁 Script executed:

#!/bin/bash
# Let's look at the full messaging consumer implementation
echo "==== website/consumers.py (MessagingConsumer) ===="
grep -A 100 "class MessagingConsumer" website/consumers.py

# Let's check the API views related to messaging to see if there's any thread creation code
echo "==== website/api/views.py (messaging functions) ===="
grep -r "def.*message" --include="*.py" website/api/

Length of output: 341


🏁 Script executed:

#!/bin/bash
# Let's look for thread creation and messaging API endpoints
echo "==== website/api/views.py (look for messaging) ===="
grep -A 50 "messaging" website/api/views.py || echo "Not found"

# Look for URLs related to messaging
echo "==== URLs related to messaging ===="
grep -A 30 "messaging" website/urls.py || echo "Not found in website/urls.py"
grep -r "path.*message" --include="*.py" . | grep -v "templates" || echo "No messaging URLs found"

# Let's look at all of consumers.py to understand the messaging system
echo "==== Full content of website/consumers.py ===="
cat website/consumers.py | head -200

# Let's look at create thread function if it exists
echo "==== Looking for thread creation functions ===="
grep -r "create.*thread\|new.*thread\|start.*chat" --include="*.py" website/

Length of output: 8998


🏁 Script executed:

#!/bin/bash
# Let's get the full user.py file to find the thread creation code
echo "==== website/views/user.py (thread creation) ===="
grep -A 50 "Create a new thread" website/views/user.py || echo "No match found"

# Let's check if there are any API endpoints for creating threads
echo "==== Looking for thread creation in API views ===="
grep -A 50 "create.*thread\|new.*message" --include="*.py" website/api/views.py || echo "No match found"

# Let's check the URLs to identify messaging endpoints
echo "==== URLs for messaging ===="
grep -r "path.*messaging\|url.*messaging" --include="*.py" .

# Let's examine the structure of the Thread model again
echo "==== Thread model definition ===="
grep -A 20 "class Thread" website/models.py

Length of output: 3980


🏁 Script executed:

#!/bin/bash
# Get the start_thread function from user.py
echo "==== website/views/user.py (start_thread function) ===="
grep -A 50 "def start_thread" website/views/user.py

# Let's get the messaging_home view to understand the URLs and page structure
echo "==== website/views/user.py (messaging_home function) ===="
grep -A 30 "def messaging_home" website/views/user.py

# Let's examine current email sending format from other parts
echo "==== Email sending examples from website/views/ ===="
grep -A 20 "send_mail" website/views/issue.py | head -40

Length of output: 4963


@krrish-sehgal Based on my analysis, I can see that to implement issue #3860 (sending an email when someone starts an encrypted chat), we need to modify the start_thread function in website/views/user.py. This is the function that creates a new chat thread between users.

Here's how to modify the function to send an email notification:

  1. First, add these imports at the top of the file if they're not already there:
from django.core.mail import send_mail
from django.template.loader import render_to_string
from django.urls import reverse
from django.conf import settings
  1. Then modify the start_thread function to add email notification when a new thread is created:
def start_thread(request, user_id):
    if request.method == "POST":
        other_user = get_object_or_404(User, id=user_id)

        # Check if a thread already exists between the two users
        thread = Thread.objects.filter(participants=request.user).filter(participants=other_user).first()
        
        # Flag if this is a new thread (for sending email)
        is_new_thread = not thread

        if not thread:
            # Create a new thread
            thread = Thread.objects.create()
            thread.participants.set([request.user, other_user])  # Use set() for ManyToManyField
            
            # Send email notification to the recipient for new thread
            if other_user.email:
                subject = f"New encrypted chat from {request.user.username} on OWASP BLT"
                chat_url = request.build_absolute_uri(reverse('messaging'))
                
                # Create context for the email template
                context = {
                    'sender_username': request.user.username,
                    'recipient_username': other_user.username,
                    'chat_url': chat_url,
                }
                
                # Render the email content
                msg_plain = render_to_string('email/new_chat.txt', context)
                msg_html = render_to_string('email/new_chat.html', context)
                
                # Send the email
                send_mail(
                    subject,
                    msg_plain,
                    settings.EMAIL_TO_STRING,
                    [other_user.email],
                    html_message=msg_html,
                )

        return JsonResponse({"success": True, "thread_id": thread.id})

    return JsonResponse({"success": False, "error": "Invalid request"}, status=400)
  1. Create the email templates:

Create a file website/templates/email/new_chat.txt:

Hello {{ recipient_username }},

{{ sender_username }} has started a new encrypted chat with you on OWASP BLT.

Click the link below to view and respond to the conversation:
{{ chat_url }}

This is a secure end-to-end encrypted chat. Only you and the sender can read the messages.

Regards,
The OWASP BLT Team

Create a file website/templates/email/new_chat.html:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>New Encrypted Chat</title>
</head>
<body style="font-family: Arial, sans-serif; line-height: 1.6; color: #333; margin: 0; padding: 20px;">
    <div style="max-width: 600px; margin: 0 auto;">
        <div style="background-color: #e74c3c; color: white; padding: 10px 20px; text-align: center;">
            <h1>New Encrypted Chat</h1>
        </div>
        <div style="padding: 20px; border: 1px solid #ddd; border-top: none;">
            <p>Hello {{ recipient_username }},</p>
            
            <p><strong>{{ sender_username }}</strong> has started a new encrypted chat with you on OWASP BLT.</p>
            
            <p>Click the button below to view and respond to the conversation:</p>
            
            <p style="text-align: center;">
                <a href="{{ chat_url }}" style="display: inline-block; background-color: #e74c3c; color: white; text-decoration: none; padding: 10px 20px; border-radius: 5px;">Open Chat</a>
            </p>
            
            <p>This is a secure chat with end-to-end encryption. Only you and {{ sender_username }} can read the messages.</p>
            
            <p>Regards,<br>The OWASP BLT Team</p>
        </div>
        <div style="margin-top: 20px; font-size: 12px; color: #777; text-align: center;">
            <p>If you're having trouble with the button above, copy and paste this link into your browser: {{ chat_url }}</p>
        </div>
    </div>
</body>
</html>

This implementation will send an email notification to the recipient when someone initiates a new encrypted chat with them, providing a link to open the conversation.

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: 0

🧹 Nitpick comments (1)
website/views/user.py (1)

1068-1091: Email notification implementation is well structured

The email notification logic is implemented clearly with appropriate context variables for the templates. However, I suggest adding error handling around the email sending process to prevent potential failures from affecting the thread creation.

Consider adding a try-except block around the email sending process:

            # Send email notification to the recipient for new thread
            if other_user.email:
+               try:
                    subject = f"New encrypted chat from {request.user.username} on OWASP BLT"
                    chat_url = request.build_absolute_uri(reverse('messaging'))
                    
                    # Create context for the email template
                    context = {
                        'sender_username': request.user.username,
                        'recipient_username': other_user.username,
                        'chat_url': chat_url,
                    }
                    
                    # Render the email content
                    msg_plain = render_to_string('email/new_chat.txt', context)
                    msg_html = render_to_string('email/new_chat.html', context)
                    
                    # Send the email
                    send_mail(
                        subject,
                        msg_plain,
                        settings.EMAIL_TO_STRING,
                        [other_user.email],
                        html_message=msg_html,
                    )
+               except Exception as e:
+                   logger.error(f"Failed to send email notification for new chat thread: {e}")
+                   # Thread is still created even if email fails
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 8f01ee7 and a3f04cc.

📒 Files selected for processing (3)
  • website/templates/email/new_chat.html (1 hunks)
  • website/templates/email/new_chat.txt (1 hunks)
  • website/views/user.py (1 hunks)
✅ Files skipped from review due to trivial changes (2)
  • website/templates/email/new_chat.txt
  • website/templates/email/new_chat.html
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: Run Tests
  • GitHub Check: docker-test
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (3)
website/views/user.py (3)

1058-1067: Good implementation of thread creation logic and new thread tracking

The logic to check for an existing thread between users and create a new one if needed is implemented correctly. Using a flag to track whether this is a new thread is a clean approach for determining when to send notifications.


1072-1078: Well-designed context dictionary for email templates

The context dictionary provides all necessary information for a helpful email notification, including both usernames and the chat URL.


1081-1091:

✅ Verification successful

Proper use of template rendering for both plain text and HTML emails

Using both plain text and HTML templates follows best practices for email compatibility across different email clients.

Please verify that the email templates exist in the expected locations:


🏁 Script executed:

#!/bin/bash
# Check if email templates exist
echo "Checking for email templates..."
fd "new_chat\.(txt|html)" --exec echo "Found template: {}"

Length of output: 244


Templates verified – code approved

The email templates were confirmed to exist at:

  • ./website/templates/email/new_chat.txt
  • ./website/templates/email/new_chat.html

The current implementation in website/views/user.py (lines 1081-1091) properly utilizes both plain text and HTML template rendering for enhanced email compatibility. No further changes are required.

coderabbitai[bot]
coderabbitai bot previously approved these changes Mar 17, 2025
@krrish-sehgal krrish-sehgal changed the title caching of key fixed caching of key fixed and email get sent when encrypted chat is started Mar 17, 2025
coderabbitai[bot]
coderabbitai bot previously approved these changes Mar 17, 2025
@DonnieBLT
Copy link
Collaborator

@krrish-sehgal please check the tests

@DonnieBLT DonnieBLT enabled auto-merge (squash) March 18, 2025 04:33
@DonnieBLT DonnieBLT merged commit 4394457 into OWASP-BLT:main Mar 18, 2025
10 checks passed
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.

Remove caching of recepient public key , or change it as soon as the chat is changed.

2 participants