Skip to content
Closed
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
84 changes: 84 additions & 0 deletions server/docs/openapi.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down Expand Up @@ -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]
Expand Down
93 changes: 93 additions & 0 deletions server/internal/handlers/admin_notifications.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,9 @@ import (
"net/http"
"net/url"
"regexp"
"strconv"
"strings"
"time"

"blackbox/server/internal/auth"
"blackbox/server/internal/models"
Expand Down Expand Up @@ -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) {
Expand Down
49 changes: 49 additions & 0 deletions server/internal/handlers/admin_notifications_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"net/http"
"net/http/httptest"
"testing"
"time"

"blackbox/server/internal/auth"
dbpkg "blackbox/server/internal/db"
Expand All @@ -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{}{
Expand Down
1 change: 1 addition & 0 deletions server/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -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))
Expand Down
57 changes: 57 additions & 0 deletions web/src/api/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 [] }
}
Expand Down Expand Up @@ -772,6 +793,42 @@ export async function listNotificationDests(): Promise<NotificationDest[]> {
return data.map(normalizeNotificationDest)
}

export async function listNotificationHistory(params?: {
destinationId?: string
decision?: NotificationHistoryFilter
limit?: number
before?: string
}): Promise<NotificationHistoryPage> {
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<string, unknown> => 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<NotificationDest> {
const res = await apiFetch('/api/admin/notifications', {
method: 'POST',
Expand Down
Loading
Loading