Skip to content
Open
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
119 changes: 119 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,123 @@ 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"`
}

type notificationHistoryCursor struct {
CreatedAt time.Time
ID string
}

// 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, CASE WHEN l.decision = ? THEN '' ELSE l.note END AS note, l.created_at, l.flushed_at", "failed").
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 != "" {
cursor, err := parseNotificationHistoryCursor(before)
if err != nil {
writeError(w, http.StatusBadRequest, "before must be an RFC3339 timestamp or timestamp|id cursor")
return
}
if cursor.ID == "" {
query = query.Where("l.created_at < ?", cursor.CreatedAt)
} else {
query = query.Where("(l.created_at < ? OR (l.created_at = ? AND l.id < ?))", cursor.CreatedAt, cursor.CreatedAt, cursor.ID)
}
}

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]
last := response.Items[len(response.Items)-1]
response.NextBefore = last.CreatedAt.UTC().Format(time.RFC3339Nano) + "|" + last.ID
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(response)
}
}

func parseNotificationHistoryCursor(raw string) (notificationHistoryCursor, error) {
ts, id, hasID := strings.Cut(raw, "|")
createdAt, err := time.Parse(time.RFC3339Nano, ts)
if err != nil {
return notificationHistoryCursor{}, err
}
if !hasID {
return notificationHistoryCursor{CreatedAt: createdAt}, nil
}
id = strings.TrimSpace(id)
if id == "" {
return notificationHistoryCursor{}, errors.New("missing cursor id")
}
return notificationHistoryCursor{CreatedAt: createdAt, ID: id}, nil
}

func CreateNotificationDest(db *gorm.DB) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if !requireAdminRequest(w, r) {
Expand Down
110 changes: 110 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,115 @@ 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_HidesFailedNotes(t *testing.T) {
database := newNotificationTestDB(t)
require.NoError(t, database.Create(&models.NotificationDest{
ID: "dest-failed", Name: "Ops Slack", Type: "slack", URL: "https://hooks.example/secret-token", Enabled: true,
}).Error)
require.NoError(t, database.Create(&models.NotificationLog{
ID: "log-failed", DestID: "dest-failed", IncidentID: "incident-1", Event: "incident_opened", Decision: "failed",
Note: "Post \"https://hooks.example/services/T000/B000/super-secret-token\": 404 Not Found", CreatedAt: time.Now().UTC(),
}).Error)

req := adminNotificationRequest(http.MethodGet, "/api/admin/notifications/history?decision=failed", nil)
req.URL.RawQuery = "decision=failed"
w := httptest.NewRecorder()
ListNotificationHistory(database)(w, req)

assert.Equal(t, http.StatusOK, w.Code)
body := w.Body.String()
assert.NotContains(t, body, "super-secret-token")
assert.NotContains(t, body, "hooks.example/services")
var response struct {
Items []struct {
Note string `json:"note"`
} `json:"items"`
}
require.NoError(t, json.Unmarshal([]byte(body), &response))
require.Len(t, response.Items, 1)
assert.Empty(t, response.Items[0].Note)
}

func TestListNotificationHistory_CompositeCursorKeepsSameTimestampRows(t *testing.T) {
database := newNotificationTestDB(t)
now := time.Now().UTC().Truncate(time.Second)
for _, id := range []string{"log-c", "log-b", "log-a"} {
require.NoError(t, database.Create(&models.NotificationLog{
ID: id, DestID: "dest", IncidentID: "incident", Event: "incident_opened", Decision: "sent", CreatedAt: now,
}).Error)
}

req := adminNotificationRequest(http.MethodGet, "/api/admin/notifications/history?limit=1", nil)
req.URL.RawQuery = "limit=1"
w := httptest.NewRecorder()
ListNotificationHistory(database)(w, req)
require.Equal(t, http.StatusOK, w.Code)
var first notificationHistoryResponse
require.NoError(t, json.Unmarshal(w.Body.Bytes(), &first))
require.Len(t, first.Items, 1)
require.Equal(t, "log-c", first.Items[0].ID)
require.NotEmpty(t, first.NextBefore)

req = adminNotificationRequest(http.MethodGet, "/api/admin/notifications/history", nil)
req.URL.RawQuery = "limit=2&before=" + first.NextBefore
w = httptest.NewRecorder()
ListNotificationHistory(database)(w, req)
require.Equal(t, http.StatusOK, w.Code)
var second notificationHistoryResponse
require.NoError(t, json.Unmarshal(w.Body.Bytes(), &second))
require.Len(t, second.Items, 2)
assert.Equal(t, "log-b", second.Items[0].ID)
assert.Equal(t, "log-a", second.Items[1].ID)
}

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
11 changes: 9 additions & 2 deletions server/internal/notify/notify.go
Original file line number Diff line number Diff line change
Expand Up @@ -148,7 +148,7 @@ func (d *Dispatcher) evaluateAndSend(dest models.NotificationDest, inc models.In
if err := sendTo(sendCtx, dest, inc, event, incURL, note, false); err != nil {
log.Printf("notify: send to %q (%s): %v", dest.Name, dest.Type, err)
if uerr := d.db.Model(&models.NotificationLog{}).Where("id = ?", row.ID).
Updates(map[string]interface{}{"decision": decisionFailed, "note": err.Error()}).Error; uerr != nil {
Updates(map[string]interface{}{"decision": decisionFailed, "note": failedDeliveryNote(err)}).Error; uerr != nil {
log.Printf("notify: mark failed for %q: %v", dest.Name, uerr)
}
}
Expand All @@ -164,13 +164,20 @@ func (d *Dispatcher) deliver(dest models.NotificationDest, inc models.Incident,
logNote := note
if err := sendTo(sendCtx, dest, inc, event, incURL, note, false); err != nil {
log.Printf("notify: send to %q (%s): %v", dest.Name, dest.Type, err)
decision, logNote = decisionFailed, err.Error()
decision, logNote = decisionFailed, failedDeliveryNote(err)
}
if err := d.logDecision(d.db, dest.ID, inc.ID, event, decision, logNote, d.now()); err != nil {
log.Printf("notify: log %s for %q: %v", decision, dest.Name, err)
}
}

func failedDeliveryNote(err error) string {
if err == nil {
return ""
}
return "delivery failed"
}

// SendTest sends a synthetic payload to a single destination and returns any
// delivery error directly to the caller.
func (d *Dispatcher) SendTest(ctx context.Context, dest models.NotificationDest) error {
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
Loading