alerts

package
v1.0.511 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 22, 2026 License: MIT Imports: 25 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

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

Constants

View Source
const MaxWebhooks = 100

MaxWebhooks bounds how many webhooks the store accepts through its write ingresses: the admin API's create arm and `POST /api/config/import` (CWE-770).

Real deployments configure a handful (chat, paging, a SIEM or two), so 100 is ample headroom and sits alongside the PAC caps of 64 profiles and 64 pools. The upper bound matters because delivery fans out per webhook: at 500 hooks, one alert to a dead endpoint fills the whole retry queue (retryQueueMax), and every Add rewrites and fsyncs the whole file, so an unbounded import cost O(N²) I/O.

Callers enforce it before Add; the store itself does not. A file already over the limit is grandfathered: Init loads every webhook and warns, and updates and deletes keep working, but new webhooks are refused until the count drops below the limit.

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

func Fire(event string, p Payload)

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

func HasSubscriber(event string) bool

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

func StartRetryLoop(ctx context.Context, current func() *Store)

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 URLOrigin added in v1.0.490

func URLOrigin(raw string) string

URLOrigin reduces a webhook URL to scheme://host — where alerts go, without the part that authorises posting there. Slack/Teams/PagerDuty-style receivers authenticate by a token in the path or query (and some by userinfo), so the full URL is a credential: it is shown only to the role that manages webhooks (operator) and never written to the viewer-readable audit log or delivery history. Unparseable input yields "" rather than being echoed back.

func ValidateEventNames added in v1.0.458

func ValidateEventNames(events []string) error

ValidateEventNames checks the shape of a webhook's subscribed event names.

SEC-ALERTS-EVENTNAME-1. Nothing used to constrain these: the admin API accepted any JSON string, normalizeEventNames only maps retired names and de-dupes, and Add/Update persist what they are given. The admin UI then rendered the stored names into the webhook table, so an operator-role client could persist markup that executed in the browser of every viewer, operator and ADMIN who opened the Alerts panel — a privilege escalation out of the operator role (CWE-79). The render sink is escaped now; this is the other half, so the value never reaches the file, the support bundle or any other consumer in the first place.

The check is a CHARACTER CLASS, not an allowlist of known events, on purpose. The catalog grows as rounds add alerts and is discovered by a differential oracle rather than declared in one list, so an allowlist here would reject a legitimate new event the moment it shipped — a silent subscription loss, which is the one failure normalizeEventNames exists to prevent. Every name in the catalog (and every legacy alias) is lowercase ASCII with underscores, so the class admits all of them and no markup, quote, angle bracket, control byte or newline.

Applied at the ADMIN API ingress only. Init (disk) deliberately does not validate: a name already persisted must keep dispatching rather than be dropped on load, and the escaped render sink is what makes that safe.

The "*" catch-all is admitted as a WHOLE name. It is a real subscription shape, matched by HasSubscriber and the dispatch walk, and it is how an operator subscribes to everything including events added later — refusing it would cause exactly the silent detection loss this package warns about. It is allowed only as the entire name, never as a character inside one, so it cannot smuggle a glob or markup into a longer string.

func ValidateURL added in v1.0.16

func ValidateURL(raw string) error

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

type Sink func(event string, p Payload)

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

func (as *Store) Add(h Webhook) Webhook

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

func (as *Store) DedupTracked() int

DedupTracked reports how many dedup keys are currently held (≤ the cap).

func (*Store) Delete added in v1.0.16

func (as *Store) Delete(id string) bool

Delete removes the webhook with the given ID.

func (*Store) Deliver added in v1.0.16

func (as *Store) Deliver(h Webhook, payload Payload) bool

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

func (as *Store) DeliveryHistory() []Delivery

DeliveryHistory returns the most recent delivery records (newest first).

func (*Store) Dispatch added in v1.0.16

func (as *Store) Dispatch(event string, payload Payload)

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

func (as *Store) GetByID(id string) (Webhook, bool)

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

func (as *Store) HasSubscriber(event string) bool

HasSubscriber reports whether any ENABLED webhook is subscribed to event (directly or via the "*" catch-all). Answered from the atomically published subscription index: one atomic pointer load, no lock, no allocation, and — the property that matters on the block path — no read-modify-write on any shared word, so the check scales WITH core count instead of against it. It used to take mu.RLock; subscriptions.go records what that cost and why.

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

func (as *Store) Init(path string)

Init sets the persistence path and loads any persisted webhooks.

It publishes the subscription index on EVERY exit, including the two that load nothing. Those are not the uninteresting cases: "no alert_webhooks.json on disk" is the DEFAULT posture of a fresh install and the state of every test binary, so it is the one that most needs HasSubscriber's fast path armed rather than left to the first blocked request to derive. Disk I/O stays off mu — the read happens before the lock is taken, exactly as before.

func (*Store) Len added in v1.0.495

func (as *Store) Len() int

Len returns how many webhooks the store holds, for the MaxWebhooks checks at the write ingresses (cheaper than len(List()), which copies every hook).

func (*Store) List added in v1.0.16

func (as *Store) List() []Webhook

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

func (as *Store) RecordDelivery(d Delivery)

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

func (as *Store) SigningDegradedCount() int

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

func (as *Store) Update(id string, upd Webhook) bool

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

type SubscriberProbe func(event string) bool

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.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL