Documentation
¶
Overview ¶
Package alerts is the producer-facing seam for security alerting. It owns the alert Payload DTO and a publish-once dispatch indirection, so alert producers (the scan engines, policy, …) can fire alerts without depending on the webhook-delivery implementation, which stays in package main and is installed once at startup via SetSink. ADR-0002/0003 (sibling to the obs sink seam).
Index ¶
- func DedupEvictionsTotal() int64
- func Fire(event string, p Payload)
- func HasSubscriber(event string) bool
- func RetryDroppedTotal() int64
- func RetryExhaustedTotal() int64
- func RetryQueueDepth() int
- func RetryQueuePath() string
- func SetRetryQueuePath(path string)
- func SetSink(fn Sink)
- func SetSubscriberProbe(fn SubscriberProbe)
- func StartRetryLoop(ctx context.Context, current func() *Store)
- func ValidateURL(raw string) error
- type Delivery
- type Payload
- type Sink
- type Store
- func (as *Store) Add(h Webhook) Webhook
- func (as *Store) DedupTracked() int
- func (as *Store) Delete(id string) bool
- func (as *Store) Deliver(h Webhook, payload Payload) bool
- func (as *Store) DeliveryHistory() []Delivery
- func (as *Store) Dispatch(event string, payload Payload)
- func (as *Store) GetByID(id string) (Webhook, bool)
- func (as *Store) HasSubscriber(event string) bool
- func (as *Store) Init(path string)
- func (as *Store) List() []Webhook
- func (as *Store) RecordDelivery(d Delivery)
- func (as *Store) ResetDedupForTest()
- func (as *Store) SigningDegradedCount() int
- func (as *Store) Update(id string, upd Webhook) bool
- type SubscriberProbe
- type Webhook
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func DedupEvictionsTotal ¶ added in v1.0.202
func DedupEvictionsTotal() int64
DedupEvictionsTotal reports how many dedup keys were evicted by the CHAOS-27 cap. Non-zero means the alert key space is being flooded (a scanning/beaconing wave, or a producer emitting unique Detail text per request) and that duplicate suppression is degraded — alerts may be delivered more than once per window, never fewer.
func Fire ¶
Fire dispatches an alert through the installed sink. It is a no-op when no sink is installed (e.g. unit tests that never wire alerting), so producers never need a nil check or a dependency on the delivery layer.
func HasSubscriber ¶ added in v1.0.211
HasSubscriber reports whether firing event would reach anyone, so a producer on the request path can skip the goroutine, the payload build and the round trip through the process-wide dedup mutex when — as in the default posture — no webhook is configured. This is the internal-package half of the contract package main's fireDNSFailureAlert documents: producers whose rate is set by a FAULT rather than by the operator must gate, because the fault puts every request on that path and the alert would otherwise degrade the node hardest exactly when it is already degraded.
It fails toward DELIVERY: with no probe installed (unit tests that wire a sink but no store, and any call ordering where the store is not yet up) the answer is true, so a missing probe can never silence a real alert.
func RetryDroppedTotal ¶ added in v1.0.194
func RetryDroppedTotal() int64
RetryDroppedTotal returns the count of deliveries dropped because the retry queue was at capacity (retryQueueMax).
func RetryExhaustedTotal ¶ added in v1.0.194
func RetryExhaustedTotal() int64
RetryExhaustedTotal returns the count of deliveries that used up all retry attempts and were permanently dropped.
func RetryQueueDepth ¶ added in v1.0.194
func RetryQueueDepth() int
RetryQueueDepth returns the number of failed deliveries currently queued for retry.
func RetryQueuePath ¶ added in v1.0.218
func RetryQueuePath() string
RetryQueuePath reports the durable webhook retry queue path.
func SetRetryQueuePath ¶ added in v1.0.218
func SetRetryQueuePath(path string)
SetRetryQueuePath binds the durable webhook retry queue to path. Called once at boot, before Init, when the persisted-state root is resolved.
func SetSink ¶
func SetSink(fn Sink)
SetSink installs the dispatch implementation. Intended to be called once at startup (publish-once); a later call atomically replaces the sink.
A nil fn UNINSTALLS the sink rather than installing a nil function value. Storing &fn unconditionally made probe/sink non-nil while the function behind it was nil, so the guarded call below dereferenced a nil func and PANICKED — on the request goroutine, inside the scan path, in a seam whose whole contract is that producers "never need a nil check".
func SetSubscriberProbe ¶ added in v1.0.211
func SetSubscriberProbe(fn SubscriberProbe)
SetSubscriberProbe installs the subscription query (publish-once, same lifecycle as SetSink). A nil fn UNINSTALLS the probe, which HasSubscriber reads as "not wired yet" and therefore answers true — see SetSink for why a stored nil function value is not the same thing.
func StartRetryLoop ¶ added in v1.0.16
StartRetryLoop runs a background loop that retries failed deliveries. current resolves the store on every pass, so package main can pass a closure over its process-wide singleton (tolerating test reassignment — the pre-extraction loop read the global on each tick the same way).
func ValidateURL ¶ added in v1.0.16
ValidateURL checks that a webhook URL is well-formed (http/https with a non-empty host). Unlike main's validateExternalURL, it does not perform DNS resolution at config time — the SSRF check is deferred to delivery time via the ssrf-guarded dialer so that operator-configured internal endpoints remain usable.
Types ¶
type Delivery ¶ added in v1.0.16
type Delivery struct {
Timestamp string `json:"timestamp"`
WebhookID string `json:"webhookId"`
WebhookName string `json:"webhookName"`
Event string `json:"event"`
StatusCode int `json:"statusCode,omitempty"` // 0 if delivery failed before HTTP
Success bool `json:"success"`
Error string `json:"error,omitempty"`
Attempt int `json:"attempt"` // 1-based
}
Delivery records a single webhook delivery attempt.
type Payload ¶
type Payload struct {
Event string `json:"event"`
Timestamp string `json:"timestamp"`
Actor string `json:"actor"` // client IP or username
Host string `json:"host"`
Detail string `json:"detail"` // virus name / rule name / pattern
Source string `json:"source"` // "clamav","yara","threatfeed","policy","auth"
}
Payload is the JSON body delivered to webhooks for a security event.
type Sink ¶
Sink dispatches an alert. The real implementation (webhook fan-out, retry, HMAC signing, SSRF-guarded delivery) lives in package main.
type Store ¶ added in v1.0.16
type Store struct {
// contains filtered or unexported fields
}
Store holds the configured webhooks and the delivery-attempt history. The zero value is usable (main's process-wide singleton and several tests construct it as &Store{} / &AlertStore{}); Init sets the persistence path.
func (*Store) Add ¶ added in v1.0.16
Add stores a new webhook and returns it (secret redacted).
Retired event names are migrated on the way in (normalizeEventNames): this is the ingress used by both the admin API and `POST /api/config/import`, so a pre-rename config export replayed by a restore keeps its subscription instead of coming back permanently unsubscribed.
func (*Store) DedupTracked ¶ added in v1.0.202
DedupTracked reports how many dedup keys are currently held (≤ the cap).
func (*Store) Deliver ¶ added in v1.0.16
Deliver performs one delivery attempt (attempt=1) and records the result. Exposed for main's webhook-test admin endpoint; Dispatch and the retry loop use it internally.
The delivery is bounded by deliveryTimeout but not otherwise cancellable; callers that hold a lifecycle context (the retry pass) use deliverAttemptContext so a shutdown aborts the in-flight POST instead of waiting it out (CHAOS-93 RT-2).
func (*Store) DeliveryHistory ¶ added in v1.0.16
DeliveryHistory returns the most recent delivery records (newest first).
func (*Store) Dispatch ¶ added in v1.0.16
Dispatch fans payload out to all enabled webhooks matching event. Always non-blocking: delivery happens in background goroutines. Q17: Duplicate events with the same event+detail are suppressed within dedupTTL. package main's fireAlert wrapper (installed as the alerts.Fire sink) calls this on the process-wide store.
func (*Store) GetByID ¶ added in v1.0.16
GetByID returns the webhook with the given ID (secret included — callers use it for delivery/signing, never for display).
func (*Store) HasSubscriber ¶ added in v1.0.175
HasSubscriber reports whether any ENABLED webhook is subscribed to event (directly or via the "*" catch-all). Cheap: one RLock, no allocation.
It lets a producer skip the work of firing an alert nobody will receive — including, for producers that dispatch asynchronously, skipping the goroutine spawn entirely. That matters beyond efficiency: a producer driven by an external fault (a failing disk) would otherwise inject goroutine churn into every process that has no webhooks configured at all, which is the default posture and the state of every test binary.
func (*Store) Init ¶ added in v1.0.16
Init sets the persistence path and loads any persisted webhooks.
func (*Store) List ¶ added in v1.0.16
List returns the webhooks with secrets redacted.
SigningDegraded is the one status bit that travels with the redacted copy: with Secret blanked, it is the ONLY way an operator can tell a webhook that never had a signing secret from one whose secret is unusable and whose deliveries are therefore unsigned. It carries no key material — just the fact that the configured one could not be unwrapped.
func (*Store) RecordDelivery ¶ added in v1.0.16
RecordDelivery appends a delivery record to the in-memory history ring.
func (*Store) ResetDedupForTest ¶ added in v1.0.16
func (as *Store) ResetDedupForTest()
ResetDedupForTest clears the Q17 dedup window so a test can fire the same event+detail twice and observe both deliveries (needed under -count>1 / -shuffle=on where a previous run already fired the pair).
func (*Store) SigningDegradedCount ¶ added in v1.0.216
SigningDegradedCount returns how many webhooks were configured with a signing secret that could not be decrypted at load, so their deliveries go out UNSIGNED. Zero on every healthy node; non-zero means either the node-local key file (.alert_webhook_key) was lost — the reachable case is restoring a backup onto a fresh volume, since the key is deliberately never archived — or it was unreadable when the store loaded.
Feeds the alert_webhook_signing operator-contract row; carries no secret.
func (*Store) Update ¶ added in v1.0.16
Update replaces the webhook with the given ID. An empty Secret in upd preserves the existing secret.
Retired event names are migrated on the way in (normalizeEventNames), so an API client still sending a pre-rename name does not silently unsubscribe the hook it is editing.
type SubscriberProbe ¶ added in v1.0.211
SubscriberProbe reports whether any enabled webhook subscribes to event. The real implementation is *Store.HasSubscriber, installed from package main.
type Webhook ¶ added in v1.0.16
type Webhook struct {
ID string `json:"id"`
Name string `json:"name"`
URL string `json:"url"`
Events []string `json:"events"` // e.g. ["threat_detected","policy_block"]
Enabled bool `json:"enabled"`
Secret string `json:"secret,omitempty"` // HMAC-SHA256 signing secret (never returned in list)
// SigningDegraded is a READ-ONLY status field, set only on the redacted
// copies List returns: this webhook was configured WITH a signing secret,
// but the stored secret could not be decrypted (a lost or unreadable
// .alert_webhook_key), so deliveries carry no X-Culvert-Signature.
//
// It exists because Secret is blanked in List — which makes "no secret was
// ever configured" and "the configured secret is gone and deliveries are
// now UNSIGNED" render identically in the admin UI. An operator who cannot
// see the second case has no reason to re-enter the secret, and a receiver
// that verifies the HMAC silently stops accepting this node's alerts.
//
// Never persisted: save() clears it before marshalling (and a hook loaded
// from disk derives it from sealedSecret, never from the file).
SigningDegraded bool `json:"signing_degraded,omitempty"`
// contains filtered or unexported fields
}
Webhook describes a single webhook endpoint.