Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 38 additions & 7 deletions frontend/src/components/views/WatchlistView.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
'use client';
import { useState, useEffect, useCallback } from 'react';
import { Eye, Plus, Trash2, Bell, Clock, RefreshCw, ChevronDown, ChevronUp, AlertTriangle, ArrowLeft, Pause, Play } from 'lucide-react';
import { listWatchlists, createWatchlist, deleteWatchlist, setWatchlistPaused } from '@/lib/api';
import { useTranslations } from '@/lib/i18n';
import type { Watchlist, ScanType } from '@/lib/types';
import { formatWatchlistChange } from '@/lib/watchlist-alert-utils';
import { listWatchlists, createWatchlist, deleteWatchlist, setWatchlistPaused, testWebhook } from '@/lib/api';

const SCAN_TYPES: (ScanType | 'auto')[] = ['auto', 'domain', 'ip', 'email', 'phone', 'username'];

Expand Down Expand Up @@ -32,6 +32,8 @@ export function WatchlistView({ onBack }: { onBack: () => void }) {
const [scanType, setScanType] = useState<ScanType | 'auto'>('auto');
const [interval, setIntervalHours] = useState(24);
const [webhook, setWebhook] = useState('');
const [testingWebhook, setTestingWebhook] = useState(false);
const [webhookTestResult, setWebhookTestResult] = useState<{ ok: boolean; message: string } | null>(null);

const load = useCallback(async () => {
setLoading(true);
Expand Down Expand Up @@ -71,6 +73,20 @@ export function WatchlistView({ onBack }: { onBack: () => void }) {
}
};

const handleTestWebhook = async () => {
if (!webhook.trim()) return;
setTestingWebhook(true);
setWebhookTestResult(null);
try {
await testWebhook(webhook.trim());
setWebhookTestResult({ ok: true, message: 'Test webhook delivered successfully.' });
} catch (e: unknown) {
setWebhookTestResult({ ok: false, message: e instanceof Error ? e.message : 'Test failed.' });
} finally {
setTestingWebhook(false);
}
};

const remove = async (id: string) => {
try {
await deleteWatchlist(id);
Expand Down Expand Up @@ -181,12 +197,27 @@ const exportAlertsCsv = (w: Watchlist) => {
</div>
<div className="sm:col-span-2">
<label className="block text-[10px] uppercase tracking-wider text-text-3 mb-1">{t('watchlist.webhookUrl')}</label>
<input
value={webhook}
onChange={e => setWebhook(e.target.value)}
placeholder="https://hooks.slack.com/…"
className="w-full bg-surface-2 border border-border-1 rounded px-3 py-2 text-sm text-text-1 font-mono focus:outline-none focus:border-blue"
/>
<div className="flex gap-2">
<input
value={webhook}
onChange={e => { setWebhook(e.target.value); setWebhookTestResult(null); }}
placeholder="https://hooks.slack.com/…"
className="flex-1 bg-surface-2 border border-border-1 rounded px-3 py-2 text-sm text-text-1 font-mono focus:outline-none focus:border-blue"
/>
<button
type="button"
disabled={!webhook.trim() || testingWebhook}
onClick={handleTestWebhook}
className="px-3 py-2 text-xs rounded border border-border-1 bg-surface-2 text-text-2 hover:border-blue hover:text-blue disabled:opacity-40 whitespace-nowrap"
>
{testingWebhook ? 'Sending…' : 'Send test'}
</button>
</div>
{webhookTestResult && (
<p className={`text-xs mt-1 ${webhookTestResult.ok ? 'text-green' : 'text-red'}`}>
{webhookTestResult.message}
</p>
)}
</div>
</div>
<button type="submit" disabled={creating || !target.trim()} className="btn-primary mt-3 disabled:opacity-50">
Expand Down
4 changes: 4 additions & 0 deletions frontend/src/lib/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -240,6 +240,10 @@ export function setWatchlistPaused(id: string, paused: boolean): Promise<Watchli
return patch(`/api/watchlist/${id}`, { paused });
}

export function testWebhook(webhook_url: string): Promise<{ ok: boolean; url: string }> {
return post('/api/watchlist/test-webhook', { webhook_url });
}

export function getWatchlistAlerts(id: string): Promise<{ id: string; alerts: WatchlistAlert[] }> {
return get(`/api/watchlist/${id}/alerts`);
}
Expand Down
92 changes: 92 additions & 0 deletions tests/test_webhook.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,3 +67,95 @@ def boom(*a, **kw):
monkeypatch.setattr(app_mod._requests, "post", boom)

app_mod._send_webhook("https://hooks.example.com/prism", {"x": 1})


class TestTestWebhookEndpoint:
"""Tests for POST /api/watchlist/test-webhook"""

def _client(self, monkeypatch, fake_post=None):
from web import app as app_mod
from web import security
from fastapi.testclient import TestClient

monkeypatch.setattr(security, "_API_KEYS", ["test-key"])
monkeypatch.setattr("socket.gethostbyname", lambda h: "93.184.216.34")
monkeypatch.setattr(
app_mod._requests, "head",
lambda *a, **kw: (_ for _ in ()).throw(Exception("skip"))
)
if fake_post is not None:
monkeypatch.setattr(app_mod._requests, "post", fake_post)
return TestClient(app_mod.app, raise_server_exceptions=True)

def test_returns_ok_on_success(self, monkeypatch):
captured = {}

def fake_post(url, json=None, headers=None, timeout=None):
captured["url"] = url
captured["json"] = json

client = self._client(monkeypatch, fake_post)
resp = client.post(
"/api/watchlist/test-webhook",
json={"webhook_url": "https://hooks.example.com/prism"},
headers={"X-API-Key": "test-key"},
)
assert resp.status_code == 200
assert resp.json()["ok"] is True
assert captured["json"]["event"] == "watchlist_test"

def test_rejects_private_url(self, monkeypatch):
from web import app as app_mod
from web import security
from fastapi.testclient import TestClient

monkeypatch.setattr(security, "_API_KEYS", ["test-key"])
monkeypatch.setattr("socket.gethostbyname", lambda h: "10.0.0.1")
client = TestClient(app_mod.app, raise_server_exceptions=True)
resp = client.post(
"/api/watchlist/test-webhook",
json={"webhook_url": "http://internal.corp/hook"},
headers={"X-API-Key": "test-key"},
)
assert resp.status_code == 400
assert "error" in resp.json()

def test_rejects_invalid_scheme(self, monkeypatch):
client = self._client(monkeypatch)
resp = client.post(
"/api/watchlist/test-webhook",
json={"webhook_url": "ftp://example.com/hook"},
headers={"X-API-Key": "test-key"},
)
assert resp.status_code == 400

def test_requires_api_key(self, monkeypatch):
from web import app as app_mod
from web import security
from fastapi.testclient import TestClient

monkeypatch.setattr(security, "_API_KEYS", ["test-key"])
client = TestClient(app_mod.app, raise_server_exceptions=True)
resp = client.post(
"/api/watchlist/test-webhook",
json={"webhook_url": "https://hooks.example.com/prism"},
)
assert resp.status_code in (401, 403)

def test_payload_shape(self, monkeypatch):
captured = {}

def fake_post(url, json=None, headers=None, timeout=None):
captured["json"] = json

client = self._client(monkeypatch, fake_post)
client.post(
"/api/watchlist/test-webhook",
json={"webhook_url": "https://hooks.example.com/prism"},
headers={"X-API-Key": "test-key"},
)
payload = captured["json"]
assert payload["event"] == "watchlist_test"
assert "target" in payload
assert "added" in payload
assert "changes" in payload
25 changes: 25 additions & 0 deletions web/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -734,6 +734,31 @@ async def patch_watchlist_entry(request: Request, watch_id: str, req: WatchlistP
return JSONResponse({"error": "Watchlist not found"}, status_code=404)
return entry

class TestWebhookRequest(BaseModel):
webhook_url: str

@app.post("/api/watchlist/test-webhook", dependencies=[Depends(require_api_key)])
@limiter.limit("10/minute")
async def test_webhook(request: Request, req: TestWebhookRequest):
try:
url = _validate_webhook_url(req.webhook_url.strip())
except ValueError as e:
return JSONResponse({"error": str(e)}, status_code=400)
payload = {
"event": "watchlist_test",
"message": "This is a test webhook from Prism.",
"target": "example.com",
"scan_type": "domain",
"added": 1,
"removed": 0,
"changes": ["+test.example.com"],
}
try:
_send_webhook(url, payload)
except Exception as e:
return JSONResponse({"error": f"Webhook delivery failed: {e}"}, status_code=502)
return {"ok": True, "url": url}

@app.post("/api/scan", dependencies=[Depends(require_api_key)])
@limiter.limit("10/minute")
async def start_scan(request: Request, req: ScanRequest):
Expand Down
Loading