from fastapi.testclient import TestClient from sqlalchemy.orm import Session from app.core.secrets import decrypt_secret from app.models import NotificationChannel def test_notification_channel_does_not_return_saved_secret(client: TestClient, db_session: Session) -> None: response = client.post( "/notifications/channels", json={ "name": "Operations Webhook", "channel_type": "generic_webhook", "settings": {"username": "OrbitalWard"}, "secret": "https://hooks.example.test/orbitalward", "is_enabled": True, }, ) assert response.status_code == 200 body = response.json() assert body["has_secret"] is True assert "secret" not in body assert "encrypted_secret" not in body channel = db_session.get(NotificationChannel, body["id"]) assert channel is not None assert channel.encrypted_secret != "https://hooks.example.test/orbitalward" assert decrypt_secret(channel.encrypted_secret) == "https://hooks.example.test/orbitalward" list_response = client.get("/notifications/channels") assert list_response.status_code == 200 listed_channel = list_response.json()[0] assert listed_channel["has_secret"] is True assert "secret" not in listed_channel assert "encrypted_secret" not in listed_channel def test_notification_channel_update_without_secret_preserves_existing_secret(client: TestClient, db_session: Session) -> None: create_response = client.post( "/notifications/channels", json={ "name": "Mattermost", "channel_type": "mattermost", "settings": {"username": "OrbitalWard"}, "secret": "https://hooks.example.test/mattermost", "is_enabled": True, }, ) channel_id = create_response.json()["id"] original_secret = db_session.get(NotificationChannel, channel_id).encrypted_secret update_response = client.patch( f"/notifications/channels/{channel_id}", json={ "name": "Mattermost Alerts", "settings": {"username": "OrbitalWard Alerts"}, "is_enabled": False, }, ) assert update_response.status_code == 200 body = update_response.json() assert body["name"] == "Mattermost Alerts" assert body["settings"]["username"] == "OrbitalWard Alerts" assert body["is_enabled"] is False assert body["has_secret"] is True assert "secret" not in body assert "encrypted_secret" not in body channel = db_session.get(NotificationChannel, channel_id) assert channel is not None assert channel.encrypted_secret == original_secret assert decrypt_secret(channel.encrypted_secret) == "https://hooks.example.test/mattermost"