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.
Python astracloudflarecontrol-panelcyberpaneldnsfablehosting-control-panelhosting-panelkimi-k3server-managementserverkitubuntu-web-panelwebserver
feat(notifications): update chat connections
Marcos Paulo Dinizc11b3029112c
diff --git a/backend/app/api/notifications.py b/backend/app/api/notifications.pyindex 46670b81..705b9635 100644--- a/backend/app/api/notifications.py+++ b/backend/app/api/notifications.py@@ -423,6 +423,21 @@ def add_chat_connection():return jsonify({'connection': conn.to_dict()}), 201+@notifications_bp.route('/admin/chat-connections/<int:conn_id>', methods=['PUT'])+@jwt_required()+@admin_required+def update_chat_connection(conn_id):+ """Update mutable chat connection metadata and credentials."""+ from app.services.chat_webhook_service import ChatWebhookService+ try:+ conn = ChatWebhookService.update(conn_id, request.get_json() or {})+ except ValueError as exc:+ return jsonify({'error': str(exc)}), 400+ if conn is None:+ return jsonify({'error': 'Connection not found'}), 404+ return jsonify({'success': True, 'connection': conn.to_dict()}), 200++@notifications_bp.route('/admin/chat-connections/<int:conn_id>', methods=['DELETE'])@jwt_required()@admin_requireddiff --git a/backend/app/services/chat_webhook_service.py b/backend/app/services/chat_webhook_service.pyindex 0e5757f4..f2e77fd8 100644--- a/backend/app/services/chat_webhook_service.py+++ b/backend/app/services/chat_webhook_service.py@@ -84,6 +84,96 @@ class ChatWebhookService:db.session.commit()return conn+ @classmethod+ def update(cls, conn_id, data):+ """Update mutable connection fields without exposing stored secrets.++ Credential fields are patch-like: omitted values are preserved, empty+ optional values clear the credential, and required destinations cannot+ be cleared. The connection kind and default flag have dedicated+ lifecycle semantics and cannot be changed here.+ """+ if not isinstance(data, dict):+ raise ValueError('request body must be an object')++ conn = db.session.get(ChatWebhookConnection, conn_id)+ if conn is None:+ return None++ if 'kind' in data:+ kind = (data.get('kind') or '').strip().lower()+ if kind != conn.kind:+ raise ValueError('connection kind cannot be changed')+ if 'is_default' in data:+ raise ValueError('use the default endpoint to change is_default')++ new_name = conn.name+ new_categories_json = conn.categories_json+ new_is_active = conn.is_active+ new_credentials_json = conn.credentials_json++ if 'name' in data:+ new_name = str(data.get('name') or '').strip()+ if not new_name:+ raise ValueError('name is required')++ if 'categories' in data:+ categories = data.get('categories')+ if not isinstance(categories, list):+ raise ValueError('categories must be a list')+ categories = [category for category in categories if category]+ new_categories_json = json.dumps(categories) if categories else None++ if 'is_active' in data:+ new_is_active = bool(data.get('is_active'))++ url_supplied = 'url' in data or 'webhook_url' in data+ credential_supplied = url_supplied or any(+ field in data for field in ('secret', 'chat_id', 'bot_token')+ )+ if credential_supplied:+ credentials = conn.credentials()+ if conn.kind == 'telegram':+ if 'chat_id' in data:+ chat_id = str(data.get('chat_id') or '').strip()+ if not chat_id:+ raise ValueError('telegram connection requires a chat_id')+ credentials['chat_id'] = chat_id+ if 'bot_token' in data:+ bot_token = data.get('bot_token')+ if bot_token in (None, ''):+ credentials.pop('bot_token', None)+ else:+ credentials['bot_token'] = str(bot_token)+ else:+ if url_supplied:+ url_value = data.get('url') if 'url' in data else data.get('webhook_url')+ url = str(url_value or '').strip()+ if not url:+ raise ValueError(f'{conn.kind} connection requires a url')+ credentials['url'] = url+ if 'secret' in data:+ secret = data.get('secret')+ if secret in (None, ''):+ credentials.pop('secret', None)+ else:+ credentials['secret'] = str(secret)++ required = 'chat_id' if conn.kind == 'telegram' else 'url'+ if not credentials.get(required): # pragma: no cover - corrupt legacy row+ raise ValueError(f'{conn.kind} connection requires a {required}')+ new_credentials_json = json.dumps({+ key: encrypt_secret(str(value))+ for key, value in credentials.items()+ })++ conn.name = new_name+ conn.categories_json = new_categories_json+ conn.is_active = new_is_active+ conn.credentials_json = new_credentials_json+ db.session.commit()+ return conn+@classmethoddef delete(cls, conn_id):"""Delete a connection. If it was its kind's default, promote the oldestdiff --git a/backend/tests/test_notification_chat_connections.py b/backend/tests/test_notification_chat_connections.pyindex 3ee615cb..f422a445 100644--- a/backend/tests/test_notification_chat_connections.py+++ b/backend/tests/test_notification_chat_connections.py@@ -71,6 +71,105 @@ class TestCrud:db.session.refresh(b)assert b.is_default is True+ def test_update_changes_metadata_and_preserves_omitted_credentials(self, app):+ conn = ChatWebhookService.add({+ 'kind': 'webhook',+ 'name': 'Old name',+ 'url': 'https://hooks.example/old',+ 'secret': 'keep-me',+ 'categories': ['security'],+ })++ updated = ChatWebhookService.update(conn.id, {+ 'name': 'New name',+ 'categories': ['backups'],+ 'is_active': False,+ })++ assert updated.name == 'New name'+ assert updated.categories() == ['backups']+ assert updated.is_active is False+ assert updated.credentials() == {+ 'url': 'https://hooks.example/old',+ 'secret': 'keep-me',+ }++ def test_update_rotates_supplied_credentials(self, app):+ conn = ChatWebhookService.add({+ 'kind': 'webhook',+ 'name': 'Ops',+ 'url': 'https://hooks.example/old',+ 'secret': 'old-secret',+ })++ updated = ChatWebhookService.update(conn.id, {+ 'url': 'https://hooks.example/new',+ 'secret': 'new-secret',+ })++ assert updated.credentials() == {+ 'url': 'https://hooks.example/new',+ 'secret': 'new-secret',+ }+ assert updated.raw_credentials()['url'] != 'https://hooks.example/new'+ assert updated.raw_credentials()['secret'] != 'new-secret'++ def test_update_clears_explicitly_empty_optional_credential(self, app):+ conn = ChatWebhookService.add({+ 'kind': 'telegram',+ 'name': 'Bot',+ 'chat_id': '1234',+ 'bot_token': 'token-to-clear',+ })++ updated = ChatWebhookService.update(conn.id, {'bot_token': ''})++ assert updated.credentials() == {'chat_id': '1234'}++ def test_update_rejects_kind_change(self, app):+ conn = ChatWebhookService.add({+ 'kind': 'discord', 'name': 'Ops', 'url': 'https://discord/hook',+ })++ with pytest.raises(ValueError, match='kind cannot be changed'):+ ChatWebhookService.update(conn.id, {'kind': 'slack'})++ def test_update_rejects_non_list_categories(self, app):+ conn = ChatWebhookService.add({+ 'kind': 'discord', 'name': 'Ops', 'url': 'https://discord/hook',+ })++ with pytest.raises(ValueError, match='categories must be a list'):+ ChatWebhookService.update(conn.id, {'categories': 'security'})++ def test_update_rejects_empty_required_destination(self, app):+ conn = ChatWebhookService.add({+ 'kind': 'telegram', 'name': 'Bot', 'chat_id': '1234',+ })++ with pytest.raises(ValueError, match='requires a chat_id'):+ ChatWebhookService.update(conn.id, {'chat_id': ''})++ def test_update_validation_failure_does_not_mutate_connection(self, app):+ conn = ChatWebhookService.add({+ 'kind': 'telegram',+ 'name': 'Original',+ 'chat_id': '1234',+ 'categories': ['security'],+ })++ with pytest.raises(ValueError, match='requires a chat_id'):+ ChatWebhookService.update(conn.id, {+ 'name': 'Changed',+ 'categories': ['apps'],+ 'is_active': False,+ 'chat_id': '',+ })++ assert conn.name == 'Original'+ assert conn.categories() == ['security']+ assert conn.is_active is True+class TestCategoryRouting:def test_catch_all_matches_every_category(self, app):@@ -189,3 +288,50 @@ class TestApi:dele = client.delete(f'/api/v1/notifications/admin/chat-connections/{cid}', headers=auth_headers)assert dele.status_code == 200++ def test_update_connection(self, app, client, auth_headers):+ conn = ChatWebhookService.add({+ 'kind': 'webhook',+ 'name': 'Old name',+ 'url': 'https://hooks.example/original-destination',+ 'secret': 'never-serialize-me',+ })++ resp = client.put(+ f'/api/v1/notifications/admin/chat-connections/{conn.id}',+ json={'name': 'New name', 'categories': ['apps'], 'is_active': False},+ headers=auth_headers,+ )++ assert resp.status_code == 200+ body = resp.get_json()+ assert body['success'] is True+ assert body['connection']['name'] == 'New name'+ assert body['connection']['categories'] == ['apps']+ assert body['connection']['is_active'] is False+ assert 'never-serialize-me' not in json.dumps(body)+ assert 'https://hooks.example/original-destination' not in json.dumps(body)++ def test_update_connection_returns_404_for_unknown_id(self, app, client, auth_headers):+ resp = client.put(+ '/api/v1/notifications/admin/chat-connections/999999',+ json={'name': 'Missing'},+ headers=auth_headers,+ )++ assert resp.status_code == 404+ assert resp.get_json() == {'error': 'Connection not found'}++ def test_update_connection_returns_400_for_kind_change(self, app, client, auth_headers):+ conn = ChatWebhookService.add({+ 'kind': 'discord', 'name': 'Ops', 'url': 'https://discord/hook',+ })++ resp = client.put(+ f'/api/v1/notifications/admin/chat-connections/{conn.id}',+ json={'kind': 'slack'},+ headers=auth_headers,+ )++ assert resp.status_code == 400+ assert 'kind cannot be changed' in resp.get_json()['error']