Skip to content

ServerKit is a lightweight, modern server control panel for managing web applications, databases, and services on your VPS or dedicated server. Built with Python/Flask backend and React frontend.

feat(notifications): restore email-bounce webhook slice (plan 42 ph3)

Juan Denis4833f9145170
diff --git a/backend/app/api/notifications.py b/backend/app/api/notifications.py
index 989ea103..46670b81 100644
--- a/backend/app/api/notifications.py
+++ b/backend/app/api/notifications.py
@@ -1,12 +1,24 @@
+import hashlib
+import hmac
+import json
+
from flask import Blueprint, request, jsonify
from flask_jwt_extended import jwt_required, get_jwt_identity
from app.middleware.rbac import admin_required
from app.models import User, NotificationPreferences
from app import db
from app.services.notification_service import NotificationService
+from app.services.settings_service import SettingsService
+from app.services.bounce_service import BounceService
from app.notifications.service import NotificationBusService
from app.notifications.providers import EmailProviderService, SUPPORTED as EMAIL_PROVIDERS
+# Header carrying the provider's HMAC-SHA256 of the raw request body, formatted
+# as ``sha256=<hexdigest>`` (GitHub-style). The shared secret is
+# ``notify.inbound_secret``; the endpoint 404s until it is configured.
+INBOUND_SIGNATURE_HEADER = 'X-ServerKit-Signature'
+INBOUND_SECRET_KEY = 'notify.inbound_secret'
+
notifications_bp = Blueprint('notifications', __name__)
@@ -155,7 +167,14 @@ def get_user_preferences():
"""Get current user's notification preferences."""
current_user_id = get_jwt_identity()
prefs = NotificationPreferences.get_or_create(current_user_id)
- return jsonify(prefs.to_dict()), 200
+ payload = prefs.to_dict()
+ # Bounce/complaint suppression status for the address email would go to
+ # (personal override, else account email). Null when the address is clean.
+ user = User.query.get(current_user_id)
+ email = prefs.email or (user.email if user else None)
+ state = BounceService.state_for(email) if email else None
+ payload['email_status'] = state.to_dict() if state is not None else None
+ return jsonify(payload), 200
@notifications_bp.route('/preferences', methods=['PUT'])
@@ -488,3 +507,79 @@ def delete_email_provider(provider_id):
if not EmailProviderService.delete_provider(provider_id):
return jsonify({'error': 'Provider not found'}), 404
return jsonify({'success': True}), 200
+
+
+# ==========================================
+# INBOUND BOUNCE / COMPLAINT WEBHOOK (roadmap #24)
+# ==========================================
+
+@notifications_bp.route('/inbound/email', methods=['POST'])
+def inbound_email_webhook():
+ """Signed inbound webhook for provider bounce/complaint notifications.
+
+ Provider-agnostic: ``?provider=sendgrid|postmark|ses|mailgun|generic``
+ selects the payload mapping. The body is authenticated with an HMAC-SHA256
+ signature over the RAW request bytes (header ``X-ServerKit-Signature`` =
+ ``sha256=<hex>``) using the ``notify.inbound_secret`` setting. The endpoint
+ 404s while that secret is unset (feature off) and 401s on a bad signature.
+ Recorded events correlate to the originating delivery by provider
+ message-id and drive the address auto-mute.
+ """
+ secret = SettingsService.get(INBOUND_SECRET_KEY)
+ if not secret:
+ # Not configured — do not reveal the endpoint exists.
+ return jsonify({'error': 'Not found'}), 404
+
+ raw = request.get_data() or b''
+ provided = request.headers.get(INBOUND_SIGNATURE_HEADER, '') or ''
+ expected = 'sha256=' + hmac.new(
+ secret.encode('utf-8'), raw, hashlib.sha256).hexdigest()
+ if not hmac.compare_digest(provided, expected):
+ return jsonify({'error': 'Invalid signature'}), 401
+
+ try:
+ payload = json.loads(raw.decode('utf-8')) if raw else {}
+ except (ValueError, UnicodeDecodeError):
+ return jsonify({'error': 'Invalid JSON body'}), 400
+
+ provider = request.args.get('provider', 'generic')
+ recorded = BounceService.ingest(provider, payload)
+ return jsonify({
+ 'recorded': bool(recorded),
+ 'events': len(recorded),
+ 'addresses': [s.email for s in recorded],
+ }), 200
+
+
+# ==========================================
+# BOUNCE SUPPRESSION — user unmute + admin list
+# ==========================================
+
+@notifications_bp.route('/preferences/email/unmute', methods=['POST'])
+@jwt_required()
+def unmute_own_email():
+ """Clear a bounce-mute on the current user's notification email."""
+ current_user_id = get_jwt_identity()
+ prefs = NotificationPreferences.get_or_create(current_user_id)
+ user = User.query.get(current_user_id)
+ email = prefs.email or (user.email if user else None)
+ if not email:
+ return jsonify({'error': 'No notification email on file'}), 400
+ state = BounceService.unmute(email)
+ return jsonify({
+ 'success': True,
+ 'email_status': state.to_dict() if state is not None else None,
+ }), 200
+
+
+@notifications_bp.route('/admin/bouncing', methods=['GET'])
+@jwt_required()
+@admin_required
+def admin_list_bouncing():
+ """List addresses currently muted for bouncing/complaints (admin)."""
+ muted_only = request.args.get('all', '').lower() not in ('1', 'true', 'yes')
+ rows = BounceService.list_bouncing(muted_only=muted_only)
+ return jsonify({
+ 'addresses': [r.to_dict() for r in rows],
+ 'emails': [r.email for r in rows],
+ }), 200
diff --git a/backend/app/models/email_bounce.py b/backend/app/models/email_bounce.py
new file mode 100644
index 00000000..dfa11b74
--- /dev/null
+++ b/backend/app/models/email_bounce.py
@@ -0,0 +1,49 @@
+"""Email bounce / complaint suppression state (plan 33 Phase 4, roadmap #24).
+
+One row per email address that a provider reported a bounce or complaint for.
+A hard-bouncing address auto-mutes after ``MUTE_THRESHOLD`` consecutive hard
+bounces (a spam complaint mutes immediately); a muted address is skipped by the
+bus's email channel until an admin/user unmutes it. Fed by the signed inbound
+webhook (``POST /api/v1/notifications/inbound/email``).
+"""
+from datetime import datetime
+
+from app import db
+
+
+class EmailBounceState(db.Model):
+ __tablename__ = 'email_bounce_state'
+
+ KIND_BOUNCE = 'bounce'
+ KIND_COMPLAINT = 'complaint'
+
+ id = db.Column(db.Integer, primary_key=True)
+ email = db.Column(db.String(255), unique=True, nullable=False, index=True)
+
+ consecutive_bounces = db.Column(db.Integer, default=0, nullable=False)
+ total_events = db.Column(db.Integer, default=0, nullable=False)
+
+ muted = db.Column(db.Boolean, default=False, nullable=False, index=True)
+ muted_at = db.Column(db.DateTime, nullable=True)
+
+ last_kind = db.Column(db.String(20), nullable=True)
+ last_reason = db.Column(db.String(500), nullable=True)
+ last_event_at = db.Column(db.DateTime, nullable=True)
+
+ created_at = db.Column(db.DateTime, default=datetime.utcnow)
+ updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
+
+ def to_dict(self):
+ return {
+ 'email': self.email,
+ 'muted': bool(self.muted),
+ 'consecutive_bounces': self.consecutive_bounces or 0,
+ 'total_events': self.total_events or 0,
+ 'last_kind': self.last_kind,
+ 'last_reason': self.last_reason,
+ 'last_event_at': self.last_event_at.isoformat() if self.last_event_at else None,
+ 'muted_at': self.muted_at.isoformat() if self.muted_at else None,
+ }
+
+ def __repr__(self):
+ return f'<EmailBounceState {self.email} muted={self.muted} n={self.consecutive_bounces}>'
diff --git a/backend/app/notifications/channels/email.py b/backend/app/notifications/channels/email.py
index d077a4a7..66624468 100644
--- a/backend/app/notifications/channels/email.py
+++ b/backend/app/notifications/channels/email.py
@@ -51,6 +51,12 @@ class EmailAdapter(ChannelAdapter):
if not to_addr:
return DeliveryResult.skipped('no email target')
+ # A hard-bouncing / complained address is suppressed until unmuted
+ # (plan 33 Phase 4, roadmap #24). Fed by the inbound bounce webhook.
+ from app.services.bounce_service import BounceService
+ if BounceService.is_muted(to_addr):
+ return DeliveryResult.skipped('address muted (bouncing)')
+
rendered = self._render(delivery, notification)
# 1) A configured provider connection wins.
diff --git a/backend/app/services/bounce_service.py b/backend/app/services/bounce_service.py
new file mode 100644
index 00000000..9b72cf2d
--- /dev/null
+++ b/backend/app/services/bounce_service.py
@@ -0,0 +1,273 @@
+"""Bounce / complaint suppression service (plan 33 Phase 4, roadmap #24).
+
+Turns an inbound provider webhook (SendGrid / Postmark / SES / Mailgun / a
+generic shape) into ``EmailBounceState`` rows. Provider payloads are normalized
+by :meth:`BounceService.map_payload` into a common
+``{message_id, kind, reason, email}`` envelope; :meth:`record` upserts the
+per-address state, correlates the event to the originating
+``NotificationDelivery`` by provider message-id, and applies the auto-mute
+policy (a hard bounce mutes after ``MUTE_THRESHOLD`` consecutive events; a spam
+complaint mutes immediately). The bus's email channel calls
+:meth:`is_muted` to skip a muted address.
+
+Provider-agnostic by design: one adapter seam (``map_payload``) so a new
+provider only adds a mapping branch — the panel already treats SMTP transport
+as pluggable.
+"""
+from datetime import datetime
+
+from app import db
+from app.models.email_bounce import EmailBounceState
+from app.notifications.models import NotificationDelivery
+
+# Consecutive hard bounces before an address auto-mutes. A complaint mutes
+# immediately regardless of this threshold.
+MUTE_THRESHOLD = 3
+
+
+def _norm_email(value):
+ return (value or '').strip().lower() or None
+
+
+class BounceService:
+ MUTE_THRESHOLD = MUTE_THRESHOLD
+
+ KIND_BOUNCE = EmailBounceState.KIND_BOUNCE
+ KIND_COMPLAINT = EmailBounceState.KIND_COMPLAINT
+
+ # ------------------------------------------------------------------
+ # Provider payload mapping (the one adapter seam)
+ # ------------------------------------------------------------------
+ @staticmethod
+ def map_payload(provider, payload):
+ """Normalize ONE provider event into ``{message_id, kind, reason, email}``.
+
+ Returns ``None`` when the event is not a bounce/complaint (e.g. a
+ ``delivered`` webhook) so the caller can skip it. ``provider`` selects
+ the mapping; unknown providers fall back to the generic shape.
+ """
+ if not isinstance(payload, dict):
+ return None
+ provider = (provider or 'generic').lower()
+ mapper = {
+ 'sendgrid': BounceService._map_sendgrid,
+ 'postmark': BounceService._map_postmark,
+ 'ses': BounceService._map_ses,
+ 'mailgun': BounceService._map_mailgun,
+ }.get(provider, BounceService._map_generic)
+ mapped = mapper(payload)
+ if not mapped:
+ return None
+ kind = mapped.get('kind')
+ if kind not in (EmailBounceState.KIND_BOUNCE, EmailBounceState.KIND_COMPLAINT):
+ return None
+ email = _norm_email(mapped.get('email'))
+ return {
+ 'message_id': (mapped.get('message_id') or '').strip() or None,
+ 'kind': kind,
+ 'reason': (mapped.get('reason') or None),
+ 'email': email,
+ }
+
+ @staticmethod
+ def _map_generic(p):
+ kind = (p.get('kind') or p.get('type') or '').strip().lower()
+ if kind in ('complaint', 'complained', 'spam', 'spamreport'):
+ kind = EmailBounceState.KIND_COMPLAINT
+ elif kind in ('bounce', 'bounced', 'hard_bounce', 'failed', 'dropped'):
+ kind = EmailBounceState.KIND_BOUNCE
+ return {
+ 'message_id': p.get('message_id') or p.get('messageId'),
+ 'kind': kind,
+ 'reason': p.get('reason') or p.get('description'),
+ 'email': p.get('email') or p.get('recipient'),
+ }
+
+ @staticmethod
+ def _map_sendgrid(p):
+ event = (p.get('event') or '').strip().lower()
+ if event in ('bounce', 'dropped'):
+ kind = EmailBounceState.KIND_BOUNCE
+ elif event in ('spamreport', 'spam_report'):
+ kind = EmailBounceState.KIND_COMPLAINT
+ else:
+ return None
+ return {
+ 'message_id': p.get('sg_message_id') or p.get('smtp-id') or p.get('message_id'),
+ 'kind': kind,
+ 'reason': p.get('reason') or p.get('type'),
+ 'email': p.get('email'),
+ }
+
+ @staticmethod
+ def _map_postmark(p):
+ record = (p.get('RecordType') or '').strip().lower()
+ if record == 'bounce':
+ kind = EmailBounceState.KIND_BOUNCE
+ elif record == 'spamcomplaint':
+ kind = EmailBounceState.KIND_COMPLAINT
+ else:
+ return None
+ return {
+ 'message_id': p.get('MessageID'),
+ 'kind': kind,
+ 'reason': p.get('Description') or p.get('Details'),
+ 'email': p.get('Email'),
+ }
+
+ @staticmethod
+ def _map_ses(p):
+ ntype = (p.get('notificationType') or p.get('eventType') or '').strip().lower()
+ mail = p.get('mail') or {}
+ message_id = mail.get('messageId')
+ if ntype == 'bounce':
+ b = p.get('bounce') or {}
+ recips = b.get('bouncedRecipients') or [{}]
+ return {
+ 'message_id': message_id,
+ 'kind': EmailBounceState.KIND_BOUNCE,
+ 'reason': b.get('bounceSubType') or b.get('bounceType'),
+ 'email': recips[0].get('emailAddress'),
+ }
+ if ntype == 'complaint':
+ c = p.get('complaint') or {}
+ recips = c.get('complainedRecipients') or [{}]
+ return {
+ 'message_id': message_id,
+ 'kind': EmailBounceState.KIND_COMPLAINT,
+ 'reason': c.get('complaintFeedbackType') or 'complaint',
+ 'email': recips[0].get('emailAddress'),
+ }
+ return None
+
+ @staticmethod
+ def _map_mailgun(p):
+ data = p.get('event-data') or p
+ event = (data.get('event') or '').strip().lower()
+ if event in ('failed', 'bounced'):
+ kind = EmailBounceState.KIND_BOUNCE
+ elif event == 'complained':
+ kind = EmailBounceState.KIND_COMPLAINT
+ else:
+ return None
+ headers = ((data.get('message') or {}).get('headers')) or {}
+ return {
+ 'message_id': headers.get('message-id') or data.get('id'),
+ 'kind': kind,
+ 'reason': data.get('reason') or (data.get('delivery-status') or {}).get('description'),
+ 'email': data.get('recipient'),
+ }
+
+ # ------------------------------------------------------------------
+ # Recording + correlation
+ # ------------------------------------------------------------------
+ @staticmethod
+ def _delivery_for(message_id):
+ if not message_id:
+ return None
+ return (NotificationDelivery.query
+ .filter_by(provider_message_id=message_id)
+ .order_by(NotificationDelivery.id.desc())
+ .first())
+
+ @staticmethod
+ def record(mapped):
+ """Record one normalized bounce/complaint event.
+
+ Correlates to the originating delivery by ``message_id`` — when the
+ provider omits the recipient, the address is recovered from the matched
+ ``NotificationDelivery.target``. Returns the ``EmailBounceState`` (or
+ ``None`` if no address could be resolved).
+ """
+ if not mapped:
+ return None
+ kind = mapped.get('kind')
+ message_id = mapped.get('message_id')
+ delivery = BounceService._delivery_for(message_id)
+
+ email = mapped.get('email')
+ if not email and delivery is not None:
+ email = _norm_email(delivery.target)
+ email = _norm_email(email)
+ if not email:
+ return None
+
+ now = datetime.utcnow()
+ state = EmailBounceState.query.filter_by(email=email).first()
+ if state is None:
+ state = EmailBounceState(email=email, consecutive_bounces=0, total_events=0)
+ db.session.add(state)
+
+ state.total_events = (state.total_events or 0) + 1
+ state.last_kind = kind
+ state.last_reason = (mapped.get('reason') or None)
+ if state.last_reason:
+ state.last_reason = state.last_reason[:500]
+ state.last_event_at = now
+
+ if kind == EmailBounceState.KIND_COMPLAINT:
+ # A spam complaint mutes immediately.
+ if not state.muted:
+ state.muted = True
+ state.muted_at = now
+ else:
+ state.consecutive_bounces = (state.consecutive_bounces or 0) + 1
+ if state.consecutive_bounces >= MUTE_THRESHOLD and not state.muted:
+ state.muted = True
+ state.muted_at = now
+
+ db.session.commit()
+ return state
+
+ @staticmethod
+ def ingest(provider, payload):
+ """Map + record every bounce/complaint in a webhook payload.
+
+ Accepts either a single event dict or a list of them (e.g. SendGrid
+ batches). Returns the list of recorded ``EmailBounceState`` rows.
+ """
+ events = payload if isinstance(payload, list) else [payload]
+ recorded = []
+ for ev in events:
+ mapped = BounceService.map_payload(provider, ev)
+ if not mapped:
+ continue
+ state = BounceService.record(mapped)
+ if state is not None:
+ recorded.append(state)
+ return recorded
+
+ # ------------------------------------------------------------------
+ # Queries used by the bus + the API surface
+ # ------------------------------------------------------------------
+ @staticmethod
+ def state_for(email):
+ email = _norm_email(email)
+ if not email:
+ return None
+ return EmailBounceState.query.filter_by(email=email).first()
+
+ @staticmethod
+ def is_muted(email):
+ state = BounceService.state_for(email)
+ return bool(state and state.muted)
+
+ @staticmethod
+ def unmute(email):
+ """Clear the mute + bounce streak for an address. Returns the row or None."""
+ state = BounceService.state_for(email)
+ if state is None:
+ return None
+ state.muted = False
+ state.muted_at = None
+ state.consecutive_bounces = 0
+ db.session.commit()
+ return state
+
+ @staticmethod
+ def list_bouncing(muted_only=True):
+ """All addresses with a recorded bounce state (muted first)."""
+ q = EmailBounceState.query
+ if muted_only:
+ q = q.filter_by(muted=True)
+ return q.order_by(EmailBounceState.last_event_at.desc().nullslast()).all()
diff --git a/backend/tests/test_email_bounce.py b/backend/tests/test_email_bounce.py
new file mode 100644
index 00000000..e31ee1ee
--- /dev/null
+++ b/backend/tests/test_email_bounce.py
@@ -0,0 +1,222 @@
+"""Bounce / complaint suppression (plan 33 Phase 4, roadmap #24).
+
+Restored in plan 42 Phase 3. Proves the ``EmailBounceState`` model round-trip,
+the provider-agnostic payload mapping, the signed inbound webhook (404 while
+unconfigured, signature rejection, records + correlates by provider message-id),
+the auto-mute threshold + complaint-immediate-mute + unmute, and that a muted
+address is skipped by the bus's email channel.
+"""
+import hashlib
+import hmac
+import json
+
+import pytest
+
+from app import db
+from app.models import User
+from app.models.email_bounce import EmailBounceState
+from app.notifications.models import Notification, NotificationDelivery
+from app.services.bounce_service import BounceService, MUTE_THRESHOLD
+from app.services.settings_service import SettingsService
+
+SECRET = 'test-inbound-secret'
+INBOUND_URL = '/api/v1/notifications/inbound/email'
+
+
+def _sign(body_bytes):
+ return 'sha256=' + hmac.new(SECRET.encode(), body_bytes, hashlib.sha256).hexdigest()
+
+
+def _configure_secret(app):
+ with app.app_context():
+ SettingsService.set('notify.inbound_secret', SECRET)
+
+
+def _post_signed(client, payload, provider='generic'):
+ body = json.dumps(payload).encode('utf-8')
+ return client.post(
+ f'{INBOUND_URL}?provider={provider}',
+ data=body,
+ content_type='application/json',
+ headers={'X-ServerKit-Signature': _sign(body)},
+ )
+
+
+# ----------------------------------------------------------------------
+# Model
+# ----------------------------------------------------------------------
+
+class TestModel:
+ def test_round_trip(self, app):
+ with app.app_context():
+ st = EmailBounceState(email='[email protected]', consecutive_bounces=2,
+ total_events=2, muted=True)
+ db.session.add(st)
+ db.session.commit()
+ d = st.to_dict()
+ assert d['email'] == '[email protected]'
+ assert d['muted'] is True
+ assert d['consecutive_bounces'] == 2
+ assert d['total_events'] == 2
+ assert d['muted_at'] is None # never set
+ assert 'EmailBounceState' in repr(st)
+
+
+# ----------------------------------------------------------------------
+# Payload mapping (the adapter seam)
+# ----------------------------------------------------------------------
+
+class TestPayloadMapping:
+ def test_generic_normalizes_email(self):
+ mapped = BounceService.map_payload('generic', {
+ 'message_id': 'm1', 'kind': 'bounce',
+ 'reason': 'mailbox full', 'email': '[email protected]',
+ })
+ assert mapped == {
+ 'message_id': 'm1', 'kind': 'bounce',
+ 'reason': 'mailbox full', 'email': '[email protected]',
+ }
+
+ def test_non_bounce_event_ignored(self):
+ assert BounceService.map_payload('generic', {'kind': 'delivered'}) is None
+
+ def test_sendgrid_spamreport_is_complaint(self):
+ mapped = BounceService.map_payload('sendgrid', {
+ 'event': 'spamreport', 'email': '[email protected]', 'sg_message_id': 'sg1',
+ })
+ assert mapped['kind'] == EmailBounceState.KIND_COMPLAINT
+ assert mapped['message_id'] == 'sg1'
+
+ def test_postmark_bounce(self):
+ mapped = BounceService.map_payload('postmark', {
+ 'RecordType': 'Bounce', 'Email': '[email protected]',
+ 'MessageID': 'pm1', 'Description': 'blocked',
+ })
+ assert mapped['kind'] == EmailBounceState.KIND_BOUNCE
+ assert mapped['email'] == '[email protected]'
+
+
+# ----------------------------------------------------------------------
+# Inbound webhook
+# ----------------------------------------------------------------------
+
+class TestInboundWebhook:
+ def test_404_when_unconfigured(self, client):
+ r = client.post(INBOUND_URL, data=b'{}', content_type='application/json')
+ assert r.status_code == 404
+
+ def test_401_on_bad_signature(self, app, client):
+ _configure_secret(app)
+ body = json.dumps({'kind': 'bounce', 'email': '[email protected]'}).encode()
+ r = client.post(INBOUND_URL, data=body, content_type='application/json',
+ headers={'X-ServerKit-Signature': 'sha256=deadbeef'})
+ assert r.status_code == 401
+
+ def test_records_with_valid_signature(self, app, client):
+ _configure_secret(app)
+ r = _post_signed(client, {
+ 'message_id': 'gen-1', 'kind': 'bounce',
+ 'reason': 'mailbox full', 'email': '[email protected]',
+ })
+ assert r.status_code == 200
+ body = r.get_json()
+ assert body['recorded'] is True
+ assert body['events'] == 1
+ with app.app_context():
+ st = EmailBounceState.query.filter_by(email='[email protected]').first()
+ assert st is not None
+ assert st.total_events == 1
+ assert st.last_reason == 'mailbox full'
+
+ def test_correlates_to_delivery_by_message_id(self, app, client):
+ _configure_secret(app)
+ with app.app_context():
+ n = Notification(event_key='test.event', title='t')
+ db.session.add(n)
+ db.session.commit()
+ d = NotificationDelivery(
+ notification_id=n.id, channel='email',
+ target='[email protected]', provider_message_id='corr-42')
+ db.session.add(d)
+ db.session.commit()
+
+ # Payload carries the provider message-id but NO recipient — the address
+ # must be recovered from the correlated delivery.
+ r = _post_signed(client, {'message_id': 'corr-42', 'kind': 'bounce'})
+ assert r.status_code == 200
+ with app.app_context():
+ st = EmailBounceState.query.filter_by(email='[email protected]').first()
+ assert st is not None
+ assert st.total_events == 1
+
+
+# ----------------------------------------------------------------------
+# Mute policy + bus skip + API surface
+# ----------------------------------------------------------------------
+
+class TestMuteAndApi:
+ def test_bounce_threshold_auto_mutes(self, app):
+ with app.app_context():
+ for _ in range(MUTE_THRESHOLD):
+ BounceService.record({'message_id': None, 'kind': 'bounce',
+ 'reason': 'x', 'email': '[email protected]'})
+ assert BounceService.is_muted('[email protected]') is True
+ st = BounceService.state_for('[email protected]')
+ assert st.consecutive_bounces == MUTE_THRESHOLD
+
+ def test_bounce_below_threshold_not_muted(self, app):
+ with app.app_context():
+ BounceService.record({'message_id': None, 'kind': 'bounce',
+ 'reason': 'x', 'email': '[email protected]'})
+ assert BounceService.is_muted('[email protected]') is False
+
+ def test_complaint_mutes_immediately(self, app):
+ with app.app_context():
+ BounceService.record({'message_id': None, 'kind': 'complaint',
+ 'reason': 'spam', 'email': '[email protected]'})
+ assert BounceService.is_muted('[email protected]') is True
+
+ def test_muted_address_skipped_by_email_channel(self, app):
+ from app.notifications.channels.email import EmailAdapter
+ with app.app_context():
+ BounceService.record({'message_id': None, 'kind': 'complaint',
+ 'reason': 'spam', 'email': '[email protected]'})
+ n = Notification(event_key='test.event', title='t')
+ db.session.add(n)
+ db.session.commit()
+ d = NotificationDelivery(notification_id=n.id, channel='email',
+ target='[email protected]')
+ db.session.add(d)
+ db.session.commit()
+ result = EmailAdapter().deliver(d, n)
+ assert result.status == NotificationDelivery.STATUS_SKIPPED
+
+ def test_unmute_own_email(self, app, client, auth_headers):
+ with app.app_context():
+ BounceService.record({'message_id': None, 'kind': 'complaint',
+ 'reason': 'spam', 'email': '[email protected]'})
+ assert BounceService.is_muted('[email protected]') is True
+ r = client.post('/api/v1/notifications/preferences/email/unmute',
+ headers=auth_headers)
+ assert r.status_code == 200
+ assert r.get_json()['email_status']['muted'] is False
+ with app.app_context():
+ assert BounceService.is_muted('[email protected]') is False
+
+ def test_preferences_expose_email_status(self, app, client, auth_headers):
+ with app.app_context():
+ BounceService.record({'message_id': None, 'kind': 'bounce',
+ 'reason': 'x', 'email': '[email protected]'})
+ r = client.get('/api/v1/notifications/preferences', headers=auth_headers)
+ assert r.status_code == 200
+ status = r.get_json()['email_status']
+ assert status is not None
+ assert status['email'] == '[email protected]'
+
+ def test_admin_lists_bouncing(self, app, client, auth_headers):
+ with app.app_context():
+ BounceService.record({'message_id': None, 'kind': 'complaint',
+ 'reason': 'spam', 'email': '[email protected]'})
+ r = client.get('/api/v1/notifications/admin/bouncing', headers=auth_headers)
+ assert r.status_code == 200
+ assert '[email protected]' in r.get_json()['emails']