Files
ServerKit/backend/tests/test_notification_chat_connections.py
T

192 lines
8.4 KiB
Python

"""Org-level chat/webhook connections (plan 24 Phase 4).
Proves connection CRUD + encryption, category-matched routing (the bus fans a
notification out to matching connections), HMAC signing of the generic webhook
payload, the consumer delivery path, and legacy-import idempotency.
"""
import hashlib
import hmac
import json
import pytest
from werkzeug.security import generate_password_hash
from app import db
from app.models import User
from app.models.chat_webhook import ChatWebhookConnection
from app.models.notification_preferences import NotificationPreferences
from app.notifications.consumer import process_message
from app.notifications.models import NotificationDelivery
from app.notifications.service import GROUP_SLUG, QUEUE_SLUG, NotificationBusService
from app.queue_bus.service import QueueBusService
from app.services.chat_webhook_service import ChatWebhookService
@pytest.fixture(autouse=True)
def reset_broker(app):
QueueBusService.reset_broker()
def _make_user(username='alice', email='alice@example.com'):
user = User(email=email, username=username,
password_hash=generate_password_hash('x'), role='developer', is_active=True)
db.session.add(user)
db.session.commit()
# Enable everything so per-user gating never hides the org fan-out under test.
prefs = NotificationPreferences.get_or_create(user.id)
prefs.set_severities(['critical', 'warning', 'info', 'success'])
db.session.commit()
return user
def _drain():
msgs = QueueBusService.receive(GROUP_SLUG, QUEUE_SLUG, visibility_timeout_ms=60000, max_messages=100)
for m in msgs:
process_message(m)
return len(msgs)
class TestCrud:
def test_add_encrypts_and_first_is_default(self, app):
conn = ChatWebhookService.add({
'kind': 'webhook', 'name': 'Ops', 'url': 'https://hooks.example/abc',
'secret': 'shh', 'categories': ['security'],
})
assert conn.is_default is True
# URL + secret encrypted at rest, decrypt back, never serialized.
assert conn.raw_credentials()['url'] != 'https://hooks.example/abc'
assert conn.credentials()['url'] == 'https://hooks.example/abc'
assert 'shh' not in json.dumps(conn.to_dict())
assert conn.has_signing is True
def test_add_requires_destination(self, app):
with pytest.raises(ValueError):
ChatWebhookService.add({'kind': 'webhook', 'name': 'x'})
def test_delete_promotes_new_default(self, app):
a = ChatWebhookService.add({'kind': 'webhook', 'name': 'A', 'url': 'https://x/a'})
b = ChatWebhookService.add({'kind': 'webhook', 'name': 'B', 'url': 'https://x/b'})
assert a.is_default and not b.is_default
ChatWebhookService.delete(a.id)
db.session.refresh(b)
assert b.is_default is True
class TestCategoryRouting:
def test_catch_all_matches_every_category(self, app):
conn = ChatWebhookService.add({'kind': 'webhook', 'name': 'All', 'url': 'https://x/all'})
assert conn.matches_category('backups')
assert ChatWebhookService.active_for_category('security') == [conn]
def test_filtered_connection_only_matches_its_categories(self, app):
ChatWebhookService.add({'kind': 'webhook', 'name': 'Sec', 'url': 'https://x/s',
'categories': ['security']})
assert [c.name for c in ChatWebhookService.active_for_category('security')] == ['Sec']
assert ChatWebhookService.active_for_category('backups') == []
class TestBusFanout:
def test_matching_category_gets_a_connection_delivery(self, app):
user = _make_user()
conn = ChatWebhookService.add({'kind': 'webhook', 'name': 'Sec', 'url': 'https://x/s',
'categories': ['security']})
NotificationBusService.send('security.alert', to=user, data={'message': 'breach'})
chat = NotificationDelivery.query.filter_by(channel='webhook', target=f'conn:{conn.id}').all()
assert len(chat) == 1
assert chat[0].recipient_user_id is None # org-level, not per-user
def test_non_matching_category_is_skipped(self, app):
user = _make_user()
ChatWebhookService.add({'kind': 'webhook', 'name': 'Sec', 'url': 'https://x/s',
'categories': ['security']})
NotificationBusService.send('backup.completed', to=user, data={'app': 'blog'})
assert NotificationDelivery.query.filter_by(channel='webhook').count() == 0
def test_directed_send_skips_org_chat(self, app):
user = _make_user()
ChatWebhookService.add({'kind': 'webhook', 'name': 'All', 'url': 'https://x/all'})
# Explicit channels = transactional; org chat must not fan out.
NotificationBusService.send('user.welcome', to=user, channels=['email'], data={})
assert NotificationDelivery.query.filter_by(channel='webhook').count() == 0
class TestSigningAndDelivery:
def test_generic_webhook_signs_and_delivers(self, app, monkeypatch):
captured = {}
class _Resp:
ok = True
status_code = 200
def fake_post(url, data=None, headers=None, timeout=None, **kw):
captured.update({'url': url, 'data': data, 'headers': headers})
return _Resp()
monkeypatch.setattr('app.services.chat_webhook_service.requests.post', fake_post)
user = _make_user()
conn = ChatWebhookService.add({'kind': 'webhook', 'name': 'Ops', 'url': 'https://hooks/x',
'secret': 'topsecret', 'categories': ['security']})
NotificationBusService.send('security.alert', to=user, data={'message': 'breach'})
assert _drain() >= 1
assert captured['url'] == 'https://hooks/x'
body = captured['data']
expected = 'sha256=' + hmac.new(b'topsecret', body, hashlib.sha256).hexdigest()
assert captured['headers']['X-ServerKit-Signature'] == expected
payload = json.loads(body)
assert payload['event'] == 'security.alert'
assert payload['category'] == 'security'
delivery = NotificationDelivery.query.filter_by(target=f'conn:{conn.id}').one()
assert delivery.status == 'sent'
def test_discord_connection_delegates_to_formatter(self, app, monkeypatch):
from app.services.notification_service import NotificationService
seen = {}
monkeypatch.setattr(NotificationService, 'send_discord',
classmethod(lambda cls, alerts, cfg: seen.update({'cfg': cfg}) or {'success': True}))
user = _make_user()
ChatWebhookService.add({'kind': 'discord', 'name': 'Room',
'url': 'https://discord/webhook'})
NotificationBusService.send('backup.completed', to=user, data={'app': 'blog'})
assert _drain() >= 1
assert seen['cfg']['webhook_url'] == 'https://discord/webhook'
class TestImport:
def test_import_is_idempotent(self, app, monkeypatch):
from app.services.notification_service import NotificationService
cfg = {
'discord': {'webhook_url': 'https://discord/hook'},
'slack': {'webhook_url': 'https://hooks.slack/x'},
'generic_webhook': {'url': 'https://hooks/generic'},
'telegram': {},
}
monkeypatch.setattr(NotificationService, 'get_config', classmethod(lambda cls: cfg))
assert ChatWebhookService.import_legacy() == 3
assert ChatWebhookService.import_legacy() == 0 # second run is a no-op
kinds = {c.kind for c in ChatWebhookConnection.query.filter_by(imported=True).all()}
assert kinds == {'discord', 'slack', 'webhook'}
class TestApi:
def test_crud_roundtrip(self, app, client, auth_headers):
resp = client.post('/api/v1/notifications/admin/chat-connections',
json={'kind': 'webhook', 'name': 'Ops', 'url': 'https://x/ops',
'categories': ['security']}, headers=auth_headers)
assert resp.status_code == 201
cid = resp.get_json()['connection']['id']
listing = client.get('/api/v1/notifications/admin/chat-connections', headers=auth_headers)
assert listing.status_code == 200
body = listing.get_json()
assert any(c['id'] == cid for c in body['connections'])
assert 'webhook' in body['kinds']
dele = client.delete(f'/api/v1/notifications/admin/chat-connections/{cid}', headers=auth_headers)
assert dele.status_code == 200