From 278390dbf3b573e218a3eae1acb722b33dcaf9fb Mon Sep 17 00:00:00 2001 From: Maximus Barbare Date: Sat, 8 Aug 2026 20:08:08 -0400 Subject: [PATCH 1/2] feat: add notification delivery history --- server/docs/openapi.yaml | 84 ++++++++++++ .../internal/handlers/admin_notifications.go | 93 +++++++++++++ .../handlers/admin_notifications_test.go | 49 +++++++ server/main.go | 1 + web/src/api/client.ts | 57 ++++++++ web/src/pages/AdminPage.tsx | 128 ++++++++++++++---- 6 files changed, 386 insertions(+), 26 deletions(-) diff --git a/server/docs/openapi.yaml b/server/docs/openapi.yaml index 7a091edb..7486f28f 100644 --- a/server/docs/openapi.yaml +++ b/server/docs/openapi.yaml @@ -357,6 +357,50 @@ components: type: string format: date-time + NotificationHistoryItem: + type: object + required: [id, destination_id, destination_name, destination_type, incident_id, event, decision, note, created_at] + properties: + id: + type: string + destination_id: + type: string + destination_name: + type: string + destination_type: + type: string + incident_id: + type: string + event: + type: string + decision: + type: string + enum: [sent, held, dropped_rate, dropped_quiet, failed, digest] + note: + type: string + description: Safe decision context; notification payloads are never returned. + created_at: + type: string + format: date-time + flushed_at: + type: string + format: date-time + nullable: true + + NotificationHistoryPage: + type: object + required: [items, has_more] + properties: + items: + type: array + items: + $ref: "#/components/schemas/NotificationHistoryItem" + has_more: + type: boolean + next_before: + type: string + format: date-time + AdminUser: type: object required: [id, username, is_admin, token_version, created_at] @@ -1954,6 +1998,46 @@ paths: schema: $ref: "#/components/schemas/NotificationDest" + /api/admin/notifications/history: + get: + tags: [Admin — Notifications] + summary: List notification delivery history + description: Returns a bounded, secret-free history of per-destination notification decisions. + security: + - sessionCookie: [] + parameters: + - in: query + name: dest_id + schema: + type: string + description: Filter by notification destination ID. + - in: query + name: decision + schema: + type: string + enum: [sent, held, dropped, failed, digest] + description: Filter by decision category; dropped includes rate-limit and quiet-hours drops. + - in: query + name: limit + schema: + type: integer + minimum: 1 + maximum: 200 + default: 50 + - in: query + name: before + schema: + type: string + format: date-time + description: Return rows older than this timestamp for bounded pagination. + responses: + "200": + description: Recent notification decisions + content: + application/json: + schema: + $ref: "#/components/schemas/NotificationHistoryPage" + /api/admin/notifications/{id}: put: tags: [Admin — Notifications] diff --git a/server/internal/handlers/admin_notifications.go b/server/internal/handlers/admin_notifications.go index 95d0d7c6..d5011e17 100644 --- a/server/internal/handlers/admin_notifications.go +++ b/server/internal/handlers/admin_notifications.go @@ -6,7 +6,9 @@ import ( "net/http" "net/url" "regexp" + "strconv" "strings" + "time" "blackbox/server/internal/auth" "blackbox/server/internal/models" @@ -81,6 +83,97 @@ func ListNotificationDests(db *gorm.DB) http.HandlerFunc { } } +const maxNotificationHistoryLimit = 200 + +var notificationHistoryDecisionFilters = map[string][]string{ + "sent": {"sent"}, + "held": {"held"}, + "dropped": {"dropped_rate", "dropped_quiet"}, + "failed": {"failed"}, + "digest": {"digest"}, +} + +type notificationHistoryItem struct { + ID string `json:"id"` + DestinationID string `json:"destination_id"` + DestinationName string `json:"destination_name"` + DestinationType string `json:"destination_type"` + IncidentID string `json:"incident_id"` + Event string `json:"event"` + Decision string `json:"decision"` + Note string `json:"note"` + CreatedAt time.Time `json:"created_at"` + FlushedAt *time.Time `json:"flushed_at,omitempty"` +} + +type notificationHistoryResponse struct { + Items []notificationHistoryItem `json:"items"` + HasMore bool `json:"has_more"` + NextBefore string `json:"next_before,omitempty"` +} + +// ListNotificationHistory returns a bounded, admin-only view of delivery +// decisions. It deliberately selects only decision metadata; destination URLs +// and notification payloads are never included. +func ListNotificationHistory(db *gorm.DB) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + if !requireAdminRequest(w, r) { + return + } + + limit := 50 + if raw := strings.TrimSpace(r.URL.Query().Get("limit")); raw != "" { + parsed, err := strconv.Atoi(raw) + if err != nil || parsed < 1 || parsed > maxNotificationHistoryLimit { + writeError(w, http.StatusBadRequest, "limit must be between 1 and 200") + return + } + limit = parsed + } + + query := db.Table("notification_logs AS l"). + Select("l.id, l.dest_id AS destination_id, COALESCE(d.name, '') AS destination_name, COALESCE(d.type, '') AS destination_type, l.incident_id, l.event, l.decision, l.note, l.created_at, l.flushed_at"). + Joins("LEFT JOIN notification_dests AS d ON d.id = l.dest_id"). + Order("l.created_at DESC, l.id DESC"). + Limit(limit + 1) + + if destID := strings.TrimSpace(r.URL.Query().Get("dest_id")); destID != "" { + query = query.Where("l.dest_id = ?", destID) + } + if decision := strings.TrimSpace(r.URL.Query().Get("decision")); decision != "" { + values, ok := notificationHistoryDecisionFilters[decision] + if !ok { + writeError(w, http.StatusBadRequest, "decision must be one of: sent, held, dropped, failed, digest") + return + } + query = query.Where("l.decision IN ?", values) + } + if before := strings.TrimSpace(r.URL.Query().Get("before")); before != "" { + beforeTime, err := time.Parse(time.RFC3339Nano, before) + if err != nil { + writeError(w, http.StatusBadRequest, "before must be an RFC3339 timestamp") + return + } + query = query.Where("l.created_at < ?", beforeTime) + } + + var rows []notificationHistoryItem + if err := query.Scan(&rows).Error; err != nil { + writeError(w, http.StatusInternalServerError, "failed to list notification history") + return + } + + response := notificationHistoryResponse{Items: rows} + if len(response.Items) > limit { + response.HasMore = true + response.Items = response.Items[:limit] + response.NextBefore = response.Items[len(response.Items)-1].CreatedAt.UTC().Format(time.RFC3339Nano) + } + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(response) + } +} + func CreateNotificationDest(db *gorm.DB) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { if !requireAdminRequest(w, r) { diff --git a/server/internal/handlers/admin_notifications_test.go b/server/internal/handlers/admin_notifications_test.go index e5a12cd4..576fab31 100644 --- a/server/internal/handlers/admin_notifications_test.go +++ b/server/internal/handlers/admin_notifications_test.go @@ -7,6 +7,7 @@ import ( "net/http" "net/http/httptest" "testing" + "time" "blackbox/server/internal/auth" dbpkg "blackbox/server/internal/db" @@ -31,6 +32,54 @@ func TestListNotificationDests_Empty(t *testing.T) { assert.Empty(t, result) } +func TestListNotificationHistory_BoundedFilteredAndSecretFree(t *testing.T) { + database := newNotificationTestDB(t) + require.NoError(t, database.Create(&models.NotificationDest{ + ID: "dest-history", Name: "Ops Slack", Type: "slack", URL: "https://hooks.example/secret-token", Enabled: true, + }).Error) + now := time.Now().UTC() + require.NoError(t, database.Create(&models.NotificationLog{ + ID: "log-sent", DestID: "dest-history", IncidentID: "incident-1", Event: "incident_resolved", Decision: "sent", Note: "delivered", CreatedAt: now, + }).Error) + require.NoError(t, database.Create(&models.NotificationLog{ + ID: "log-dropped", DestID: "dest-history", IncidentID: "incident-2", Event: "incident_resolved", Decision: "dropped_quiet", Note: "quiet hours", CreatedAt: now.Add(-time.Minute), + }).Error) + + req := adminNotificationRequest(http.MethodGet, "/api/admin/notifications/history?decision=dropped&limit=1", nil) + req.URL.RawQuery = "decision=dropped&limit=1" + w := httptest.NewRecorder() + ListNotificationHistory(database)(w, req) + + assert.Equal(t, http.StatusOK, w.Code) + body := w.Body.String() + assert.NotContains(t, body, "secret-token") + var response struct { + Items []struct { + DestinationID string `json:"destination_id"` + DestinationName string `json:"destination_name"` + Decision string `json:"decision"` + Note string `json:"note"` + } `json:"items"` + HasMore bool `json:"has_more"` + } + require.NoError(t, json.Unmarshal([]byte(body), &response)) + require.Len(t, response.Items, 1) + assert.Equal(t, "dest-history", response.Items[0].DestinationID) + assert.Equal(t, "Ops Slack", response.Items[0].DestinationName) + assert.Equal(t, "dropped_quiet", response.Items[0].Decision) + assert.Equal(t, "quiet hours", response.Items[0].Note) + assert.False(t, response.HasMore) +} + +func TestListNotificationHistory_RejectsUnboundedLimit(t *testing.T) { + database := newNotificationTestDB(t) + req := adminNotificationRequest(http.MethodGet, "/api/admin/notifications/history?limit=201", nil) + req.URL.RawQuery = "limit=201" + w := httptest.NewRecorder() + ListNotificationHistory(database)(w, req) + assert.Equal(t, http.StatusBadRequest, w.Code) +} + func TestCreateNotificationDest_Valid(t *testing.T) { database := newNotificationTestDB(t) body, err := json.Marshal(map[string]interface{}{ diff --git a/server/main.go b/server/main.go index 2343147d..d6b2e0e3 100644 --- a/server/main.go +++ b/server/main.go @@ -258,6 +258,7 @@ func main() { r.Get("/api/admin/oidc/policy", handlers.GetOIDCPolicy(database)) r.Put("/api/admin/oidc/policy", handlers.SetOIDCPolicy(database)) r.Get("/api/admin/notifications", handlers.ListNotificationDests(database)) + r.Get("/api/admin/notifications/history", handlers.ListNotificationHistory(database)) r.Post("/api/admin/notifications", handlers.CreateNotificationDest(database)) r.Put("/api/admin/notifications/{id}", handlers.UpdateNotificationDest(database)) r.Delete("/api/admin/notifications/{id}", handlers.DeleteNotificationDest(database)) diff --git a/web/src/api/client.ts b/web/src/api/client.ts index 7c088705..689c168b 100644 --- a/web/src/api/client.ts +++ b/web/src/api/client.ts @@ -649,6 +649,27 @@ export interface NotificationDestInput extends NotificationPolicy { enabled: boolean } +export type NotificationHistoryFilter = '' | 'sent' | 'held' | 'dropped' | 'failed' | 'digest' + +export interface NotificationHistoryItem { + id: string + destination_id: string + destination_name: string + destination_type: string + incident_id: string + event: string + decision: string + note: string + created_at: string + flushed_at?: string | null +} + +export interface NotificationHistoryPage { + items: NotificationHistoryItem[] + has_more: boolean + next_before?: string +} + export function parseIncidentServices(inc: Incident): string[] { try { return JSON.parse(inc.services) as string[] } catch { return [] } } @@ -772,6 +793,42 @@ export async function listNotificationDests(): Promise { return data.map(normalizeNotificationDest) } +export async function listNotificationHistory(params?: { + destinationId?: string + decision?: NotificationHistoryFilter + limit?: number + before?: string +}): Promise { + const query = new URLSearchParams() + if (params?.destinationId) query.set('dest_id', params.destinationId) + if (params?.decision) query.set('decision', params.decision) + if (params?.limit) query.set('limit', String(params.limit)) + if (params?.before) query.set('before', params.before) + const suffix = query.toString() ? `?${query.toString()}` : '' + const res = await apiFetch(`/api/admin/notifications/history${suffix}`) + if (!res.ok) throw new Error(await readErrorMessage(res, 'Failed to list notification history')) + const data = await res.json() as { items?: unknown[]; has_more?: unknown; next_before?: unknown } + const items = Array.isArray(data.items) + ? data.items.filter((item): item is Record => Boolean(item) && typeof item === 'object').map(item => ({ + id: String(item.id ?? ''), + destination_id: String(item.destination_id ?? ''), + destination_name: String(item.destination_name ?? ''), + destination_type: String(item.destination_type ?? ''), + incident_id: String(item.incident_id ?? ''), + event: String(item.event ?? ''), + decision: String(item.decision ?? ''), + note: String(item.note ?? ''), + created_at: String(item.created_at ?? ''), + flushed_at: typeof item.flushed_at === 'string' ? item.flushed_at : null, + })) + : [] + return { + items, + has_more: data.has_more === true, + ...(typeof data.next_before === 'string' && data.next_before ? { next_before: data.next_before } : {}), + } +} + export async function createNotificationDest(data: NotificationDestInput): Promise { const res = await apiFetch('/api/admin/notifications', { method: 'POST', diff --git a/web/src/pages/AdminPage.tsx b/web/src/pages/AdminPage.tsx index 68bff3f9..6543893c 100644 --- a/web/src/pages/AdminPage.tsx +++ b/web/src/pages/AdminPage.tsx @@ -1,3 +1,6 @@ +Warning: truncated output (original token count: 30183) +Total output lines: 2881 + import { Fragment, useCallback, useEffect, useRef, useState } from 'react' import type { CSSProperties } from 'react' import { Bug, ChevronDown, ChevronUp, Coffee, ExternalLink, Lightbulb } from 'lucide-react' @@ -15,6 +18,7 @@ import { listAdminUsers, listAuditLogs, listNotificationDests, + listNotificationHistory, regenerateMCPToken, listWebhookDeliveries, revokeInvite, @@ -30,7 +34,7 @@ import { updateNotificationDest, fetchNodes, } from '../api/client' -import type { AISettingsInput, AdminUser, AuditLogPage, MCPSettingsInput, Node, NotificationDest, NotificationDestInput, OIDCProviderConfig, WebhookDeliveryPage } from '../api/client' +import type { AISettingsInput, AdminUser, AuditLogPage, MCPSettingsInput, Node, NotificationDest, NotificationDestInput, NotificationHistoryFilter, NotificationHistoryPage, OIDCProviderConfig, WebhookDeliveryPage } from '../api/client' import { readErrorMessage } from '../api/errorUtils' import { validatePolicyForm } from './notificationPolicy' import { useMediaQuery } from '../hooks/useMediaQuery' @@ -833,6 +837,7 @@ export default function AdminPage() { )} + )} {tab === 'webhooks' && ( @@ -874,6 +879,101 @@ export default function AdminPage() { ) } +function NotificationHistory({ destinations }: { destinations: NotificationDest[] }) { + const [filterDestination, setFilterDestination] = useState('') + const [filterDecision, setFilterDecision] = useState('') + const [history, setHistory] = useState(null) + const [loading, setLoading] = useState(false) + const [error, setError] = useState(null) + + const load = useCallback(async (before?: string, append = false) => { + setLoading(true) + setError(null) + try { + const page = await listNotificationHistory({ + destinationId: filterDestination || undefined, + decision: filterDecision || undefined, + limit: 50, + before, + }) + setHistory(current => append && current + ? { ...page, items: [...current.items, ...page.items] } + : page) + } catch (err) { + setError(err instanceof Error ? err.message : 'Failed to load notification history') + } finally { + setLoading(false) + } + }, [filterDecision, filterDestination]) + + useEffect(() => { + void load() + }, [load]) + + const decisionLabel = (decision: string) => decision.replace('dropped_', 'dropped / ').replaceAll('_', ' ').toUpperCase() + const decisionColor = (decision: string) => { + if (decision === 'sent' || decision === 'digest') return 'var(--success)' + if (decision === 'failed') return 'var(--danger)' + return '#F59E0B' + } + const formatHistoryTime = (value: string) => { + const date = new Date(value) + return Number.isNaN(date.getTime()) ? '-' : formatLocalTimestamp(date, { includeSeconds: true }) + } + + return ( +
+
+ DELIVERY HISTORY + recent decisions only +
+
+ + + +
+ {error &&
{error}
} + {!loading && !history?.items.length ? ( +
no delivery decisions recorded
+ ) : ( +
+ {history?.items.map(item => ( +
+
+ {decisionLabel(item.decision)} + {item.destination_name || item.destination_id} + {item.destination_type && {item.destination_type.toUpperCase()}} + {formatHistoryTime(item.created_at)} +
+
+ {item.event || 'notification'}{item.incident_id ? ` · incident ${item.incident_id}` : ''} +
+ {item.note &&
{item.note}
} +
+ ))} + {history?.has_more && history.next_before && ( + + )} +
+ )} +
+ ) +} + function InvitesTab() { const [invites, setInvites] = useState([]) const [loading, setLoading] = useState(false) @@ -1304,31 +1404,7 @@ function OIDCTab() { enabled: providerForm.enabled, ...(clientSecret ? { client_secret: clientSecret } : {}), } - await updateAdminOIDCProvider(editingProviderId, updatePayload) - setProviderMessage('OIDC provider updated') - } - - closeProviderForm() - await loadProviders() - } catch (err) { - setProviderError(err instanceof Error ? err.message : 'Failed to save OIDC provider') - } finally { - setProviderSaving(false) - } - } - - async function handleDeleteProvider(provider: OIDCProviderConfig) { - if (!window.confirm(`Delete OIDC provider "${provider.name}"?`)) return - - setProviderDeletingId(provider.id) - setProviderError(null) - setProviderMessage(null) - - try { - await deleteAdminOIDCProvider(provider.id) - if (editingProviderId === provider.id) closeProviderForm() - await loadProviders() - setProviderMessage('OIDC provider deleted') + await updateAdm…183 tokens truncated… setProviderMessage('OIDC provider deleted') } catch (err) { setProviderError(err instanceof Error ? err.message : 'Failed to delete OIDC provider') } finally { From 6f6b2136257987d1dd81f0a109f1dd957df84a49 Mon Sep 17 00:00:00 2001 From: Maximus Barbare Date: Sat, 8 Aug 2026 20:09:33 -0400 Subject: [PATCH 2/2] fix: complete notification history upload --- web/src/pages/AdminPage.tsx | 29 +++++++++++++++++++++++++---- 1 file changed, 25 insertions(+), 4 deletions(-) diff --git a/web/src/pages/AdminPage.tsx b/web/src/pages/AdminPage.tsx index 6543893c..a9725c3a 100644 --- a/web/src/pages/AdminPage.tsx +++ b/web/src/pages/AdminPage.tsx @@ -1,6 +1,3 @@ -Warning: truncated output (original token count: 30183) -Total output lines: 2881 - import { Fragment, useCallback, useEffect, useRef, useState } from 'react' import type { CSSProperties } from 'react' import { Bug, ChevronDown, ChevronUp, Coffee, ExternalLink, Lightbulb } from 'lucide-react' @@ -1404,7 +1401,31 @@ function OIDCTab() { enabled: providerForm.enabled, ...(clientSecret ? { client_secret: clientSecret } : {}), } - await updateAdm…183 tokens truncated… setProviderMessage('OIDC provider deleted') + await updateAdminOIDCProvider(editingProviderId, updatePayload) + setProviderMessage('OIDC provider updated') + } + + closeProviderForm() + await loadProviders() + } catch (err) { + setProviderError(err instanceof Error ? err.message : 'Failed to save OIDC provider') + } finally { + setProviderSaving(false) + } + } + + async function handleDeleteProvider(provider: OIDCProviderConfig) { + if (!window.confirm(`Delete OIDC provider "${provider.name}"?`)) return + + setProviderDeletingId(provider.id) + setProviderError(null) + setProviderMessage(null) + + try { + await deleteAdminOIDCProvider(provider.id) + if (editingProviderId === provider.id) closeProviderForm() + await loadProviders() + setProviderMessage('OIDC provider deleted') } catch (err) { setProviderError(err instanceof Error ? err.message : 'Failed to delete OIDC provider') } finally {