-
Notifications
You must be signed in to change notification settings - Fork 153
feat: implement custom tracking domain CNAME integration (#485) #673
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
Bheemeswari497
wants to merge
2
commits into
Kuldeeep18:main
Choose a base branch
from
Bheemeswari497:feature/custom-tracking-domain-cname-485
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 1 commit
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,57 @@ | ||
| import logging | ||
| from django.utils.deprecation import MiddlewareMixin | ||
| from django.http import HttpResponseNotFound | ||
| from django.conf import settings | ||
| from urllib.parse import urlparse | ||
| from tenants.models import Organization | ||
| from tenants.middleware import _thread_locals | ||
|
|
||
| logger = logging.getLogger(__name__) | ||
|
|
||
| class CustomDomainMiddleware(MiddlewareMixin): | ||
| """ | ||
| Middleware that intercepts requests with custom domains in the Host header, | ||
| identifies the associated Organization, and restricts access to ONLY | ||
| the tracking endpoints, rewriting/routing them to existing handlers. | ||
| """ | ||
|
|
||
| TRACKING_ENDPOINTS = ( | ||
| '/api/v1/clicks/track/', | ||
| '/api/v1/webhooks/email/', | ||
| '/api/v1/unsubscribe/', | ||
| ) | ||
|
|
||
| def process_request(self, request): | ||
| host = request.get_host().split(':')[0].lower() | ||
| base_url = getattr(settings, 'BACKEND_BASE_URL', 'http://localhost:8000') | ||
| parsed_base = urlparse(base_url) | ||
| default_host = (parsed_base.hostname or 'localhost').lower() | ||
|
|
||
| # If the request comes via the default host or localhost, skip custom domain processing | ||
| if host == default_host or host == '127.0.0.1' or host == 'localhost': | ||
| return None | ||
|
|
||
| # Check if the host matches a custom tracking domain | ||
| try: | ||
| org = Organization.objects.get(custom_tracking_domain=host) | ||
| except Organization.DoesNotExist: | ||
| # If no matching organization exists, continue normal request processing. | ||
| return None | ||
|
|
||
| # Custom domain matched. Identify the correct tenant. | ||
| _thread_locals.tenant = org | ||
|
|
||
| # Enforce strict tenant isolation: A custom domain must ONLY access tracking resources. | ||
| is_tracking_endpoint = False | ||
| for endpoint in self.TRACKING_ENDPOINTS: | ||
| if request.path.startswith(endpoint): | ||
| is_tracking_endpoint = True | ||
| break | ||
|
|
||
| if not is_tracking_endpoint: | ||
| logger.warning(f"Blocked non-tracking access on custom domain {host} for path {request.path}") | ||
| return HttpResponseNotFound("Not Found") | ||
|
|
||
| # The request will naturally proceed to the existing tracking handlers | ||
| # preserving the request method and query parameters. | ||
| return None | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,114 @@ | ||
| from unittest.mock import patch | ||
| from django.test import TestCase, override_settings | ||
| from django.core.exceptions import ValidationError | ||
| from tenants.models import Organization | ||
| from django.conf import settings | ||
| from rest_framework.test import APIClient | ||
| from campaigns.tasks import rewrite_email_links | ||
| from campaigns.gmail_service import build_unsubscribe_url | ||
|
|
||
| class MockDnsRdata: | ||
| def __init__(self, target): | ||
| self.target_text = target | ||
|
|
||
| @property | ||
| def target(self): | ||
| class _Target: | ||
| def to_text(self_inner): | ||
| return self.target_text | ||
| return _Target() | ||
|
|
||
| @override_settings(BACKEND_BASE_URL='https://leadorbit.onrender.com') | ||
| class CustomDomainModelTests(TestCase): | ||
| def setUp(self): | ||
| self.org = Organization.objects.create(name="Acme Corp") | ||
|
|
||
| @patch('dns.resolver.resolve') | ||
| def test_valid_cname_configuration(self, mock_resolve): | ||
| # Mocking dns.resolver to return a valid CNAME pointing to our target | ||
| mock_resolve.return_value = [MockDnsRdata('leadorbit.onrender.com.')] | ||
|
|
||
| self.org.custom_tracking_domain = 'track.acme.test' | ||
| # Should not raise exception | ||
| self.org.clean() | ||
| self.org.save() | ||
| self.assertEqual(self.org.custom_tracking_domain, 'track.acme.test') | ||
|
|
||
| @patch('dns.resolver.resolve') | ||
| def test_invalid_cname_configuration(self, mock_resolve): | ||
| mock_resolve.return_value = [MockDnsRdata('wrong.target.com.')] | ||
|
|
||
| self.org.custom_tracking_domain = 'track.acme.test' | ||
| with self.assertRaises(ValidationError) as ctx: | ||
| self.org.clean() | ||
| self.assertIn("CNAME record must point to", str(ctx.exception)) | ||
|
|
||
| @patch('dns.resolver.resolve') | ||
| def test_dns_validation_failures(self, mock_resolve): | ||
| import dns.resolver | ||
| mock_resolve.side_effect = dns.resolver.NXDOMAIN | ||
|
|
||
| self.org.custom_tracking_domain = 'notexist.acme.test' | ||
| with self.assertRaises(ValidationError) as ctx: | ||
| self.org.clean() | ||
| self.assertIn("Domain does not exist", str(ctx.exception)) | ||
|
|
||
|
|
||
| from django.test import RequestFactory | ||
|
|
||
| @override_settings(DEBUG=False) | ||
| class CustomDomainMiddlewareTests(TestCase): | ||
| def setUp(self): | ||
| self.factory = RequestFactory() | ||
| self.org = Organization.objects.create(name="Acme Corp", custom_tracking_domain='track.acme.test') | ||
| from backend.middleware import CustomDomainMiddleware | ||
| self.middleware = CustomDomainMiddleware(lambda req: getattr(req, '_fake_response', None)) | ||
|
|
||
| def test_middleware_hostname_routing_tracking_endpoint(self): | ||
| request = self.factory.get('/api/v1/clicks/track/', HTTP_HOST='track.acme.test') | ||
| request._fake_response = "OK" | ||
| response = self.middleware(request) | ||
| self.assertEqual(response, "OK") # Allowed through | ||
|
|
||
| def test_tenant_isolation_non_tracking_endpoint(self): | ||
| request = self.factory.get('/api/v1/organizations/', HTTP_HOST='track.acme.test') | ||
| response = self.middleware(request) | ||
| self.assertEqual(response.status_code, 404) | ||
|
|
||
| def test_default_tracking_fallback(self): | ||
| request = self.factory.get('/api/v1/organizations/', HTTP_HOST='localhost') | ||
| request._fake_response = "OK" | ||
| response = self.middleware(request) | ||
| self.assertEqual(response, "OK") # Allowed through | ||
|
|
||
|
|
||
| class CustomDomainURLGenerationTests(TestCase): | ||
| def setUp(self): | ||
| self.org_custom = Organization.objects.create(name="Custom Org", custom_tracking_domain='track.custom.test') | ||
| self.org_default = Organization.objects.create(name="Default Org") | ||
|
|
||
| # Need mock campaign/lead to test rewrite_email_links, or just use string checking | ||
| from campaigns.models import Campaign, SequenceStep, CampaignLead | ||
| from leads.models import Lead | ||
|
|
||
| self.campaign = Campaign.objects.create(organization=self.org_custom, name="Test", status="ACTIVE", sent_count=0, bounced_count=0) | ||
| self.step = SequenceStep.objects.create(organization=self.org_custom, campaign=self.campaign, step_order=1, channel_type="EMAIL") | ||
| self.lead = Lead.objects.create(organization=self.org_custom, email="test@test.com") | ||
| self.clead = CampaignLead.objects.create( | ||
| organization=self.org_custom, campaign=self.campaign, lead=self.lead, current_step=self.step | ||
| ) | ||
|
|
||
| def test_rewrite_email_links_with_custom_domain(self): | ||
| html = '<a href="https://google.com">Google</a>' | ||
| rewritten = rewrite_email_links(html, self.clead.id, self.step.id, organization=self.org_custom) | ||
| self.assertIn('https://track.custom.test/api/v1/clicks/track/?t=', rewritten) | ||
|
|
||
| def test_rewrite_email_links_default_fallback(self): | ||
| html = '<a href="https://google.com">Google</a>' | ||
| rewritten = rewrite_email_links(html, self.clead.id, self.step.id, organization=self.org_default) | ||
| self.assertIn('/api/v1/clicks/track/', rewritten) | ||
| self.assertNotIn('track.custom.test', rewritten) | ||
|
|
||
| def test_build_unsubscribe_url_with_custom_domain(self): | ||
| url = build_unsubscribe_url(self.lead, organization=self.org_custom) | ||
| self.assertIn('https://track.custom.test/api/v1/unsubscribe/', url) |
18 changes: 18 additions & 0 deletions
18
backend/tenants/migrations/0003_organization_custom_tracking_domain.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,18 @@ | ||
| # Generated by Django 5.0.14 on 2026-07-12 15:38 | ||
|
|
||
| from django.db import migrations, models | ||
|
|
||
|
|
||
| class Migration(migrations.Migration): | ||
|
|
||
| dependencies = [ | ||
| ('tenants', '0002_organization_enable_ai_personalization_and_more'), | ||
| ] | ||
|
|
||
| operations = [ | ||
| migrations.AddField( | ||
| model_name='organization', | ||
| name='custom_tracking_domain', | ||
| field=models.CharField(blank=True, max_length=255, null=True, unique=True), | ||
| ), | ||
| ] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.