Documentation
¶
Overview ¶
Package notify adapts IM and email finding notifications. It depends only on the standard library and the locale catalog, not db/server. JSONB configuration arrives as map[string]any and content as Message, allowing signatures, UTF-8 truncation, and filters to be tested without PostgreSQL while server handles orchestration. Channel implementations must be stateless because concurrent configurations and bot instances share them; credentials always come from cfg and must never be cached in adapter fields.
Index ¶
- Constants
- func AtLeast(severity, min string) bool
- func ErrorMessage(lang locale.Lang, err error) string
- func IsMasked(v string) bool
- func IsPermanent(err error) bool
- func Kinds() []string
- func MaskConfig(kind string, cfg map[string]any) map[string]any
- func MaskedValue(secret string) string
- func Match(f Filter, s Snapshot) bool
- func MergeConfig(stored, incoming map[string]any) map[string]any
- func OneLine(s string, max int) string
- func Permanent(err error) error
- func PrepareConfigUpdate(kind string, stored, incoming map[string]any) (map[string]any, error)
- func SeverityLabel(severity string, langs ...locale.Lang) string
- func SeverityRank(severity string) int
- func StatusLabel(status string, langs ...locale.Lang) string
- func TruncateBytes(s string, max int) string
- func TruncateHTML(s string, max int) string
- func TruncateRunes(s string, max int) string
- func ValidKind(kind string) bool
- func ValidMinSeverity(s string) bool
- type Channel
- type ErrDestinationChangedWithoutCredentials
- type Filter
- type Item
- type Message
- type PermanentError
- type Snapshot
Constants ¶
const ( KindDingTalk = "dingtalk" // DingTalk custom bot. KindFeishu = "feishu" // Feishu/Lark custom bot. KindWeCom = "wecom" // WeCom group bot. KindWebhook = "webhook" // Generic webhook with custom method, headers, and JSON template. KindTelegram = "telegram" // Telegram Bot API KindEmail = "email" // SMTP email. )
Channel identifiers also define valid notification_channels.kind values. The server uses an allowlist instead of a DB CHECK, as with finding statuses, to simplify adding adapters.
const ( EventFindingCreated = "finding_created" EventFindingStatusChanged = "finding_status_changed" )
Event identifiers for notification_events.kind.
const AllowLocalTargetsEnv = "ARTEX_NOTIFY_ALLOW_LOCAL"
allowLocalTargets defaults to blocking loopback/link-local destinations, including local administration ports and cloud metadata at 169.254.169.254. A compromised/shared administrator session could read response snippets through last_error and delivery history, creating a partial- read SSRF primitive. Local SMTP relays are legitimate deployments, so ARTEX_NOTIFY_ALLOW_LOCAL=1 explicitly opts in. Exporting AllowLocalTargetsEnv also lets package/server tests enable loopback fake receivers.
const InitKind = KindDingTalk
InitKind is the fallback when configuration omits kind.
const MaskedPrefix = "__masked__"
MaskedPrefix marks API credential placeholders; submitting one preserves the stored value. A prefix rather than an empty/fixed value permits a recognizable suffix without requiring operators to paste secrets again.
Variables ¶
This section is empty.
Functions ¶
func AtLeast ¶
AtLeast checks a severity threshold. Empty min accepts everything; unknown severity ranks zero and fails supported nonempty thresholds (see severityRank).
func ErrorMessage ¶
ErrorMessage preserves retry markers and renders only known built-in errors. Unknown provider errors and their raw response content remain unchanged.
func IsPermanent ¶
IsPermanent reports whether the error chain contains a permanent-failure marker.
func Kinds ¶
func Kinds() []string
Kinds returns supported kinds in lexical order for stable UI options.
func MaskConfig ¶
MaskConfig copies configuration and masks credential fields. Unknown kinds return an empty map rather than risking exposure of unidentified secrets. Preserve non-secret fields for the UI.
func MaskedValue ¶
MaskedValue returns __masked__ for short secrets or __masked__:…ab12cd with the last six characters. Webhook identities vary at the end; shared prefixes are unhelpful. Six trailing characters help operators recognize a bot without exposing the full credential.
func Match ¶
Match determines delivery eligibility and never returns an error, favoring a match over internal failure as ParseFilter does. Evaluate event kind, severity, task/asset scope, then class keywords.
func MergeConfig ¶
MergeConfig applies partial updates: masks preserve stored values, empty strings explicitly delete keys, other supplied values replace, and omitted keys remain. Empty form fields deliberately mean clear rather than retain, giving operators a way to remove incorrect configuration; omission and masking already express preservation.
func OneLine ¶
OneLine collapses whitespace then truncates by rune count. This keeps multiline summaries from breaking IM titles or tables. max<=0 disables the limit.
func Permanent ¶
Permanent marks a failure as non-retryable. Nil remains nil, allowing return Permanent(someCheck()).
func PrepareConfigUpdate ¶
PrepareConfigUpdate replaces bare MergeConfig on channel updates. Otherwise an attacker with PATCH access can change only a destination and inherit omitted stored secrets: webhook Authorization headers, Telegram /bot<token>/ paths, or SMTP credentials after STARTTLS. This requires no redirect and defeats browser masking. Any destination change requires an explicit choice for every secret: a new value, or an empty value to remove it. Masks and omitted keys are rejected because both retain old credentials. Do not automatically drop optional credentials; silent authentication loss with a successful update is harder to diagnose than a clear error.
func SeverityLabel ¶
SeverityLabel returns a localized emoji label for titles. Unknown values remain verbatim.
func SeverityRank ¶
SeverityRank returns the ordinal, or zero for unknown values.
func StatusLabel ¶
StatusLabel localizes built-in workflow statuses for transition messages.
func TruncateBytes ¶
TruncateBytes keeps valid UTF-8 within max bytes. WeCom limits Markdown to 4096 bytes, and Chinese characters take three bytes; arbitrary byte slicing can split a character and cause rejection or mojibake. Backtrack from the budget to a rune boundary using utf8.RuneStart. max<=0 disables the limit; append an ellipsis unless the budget cannot hold it.
func TruncateHTML ¶
TruncateHTML first truncates by characters, then removes an unfinished trailing tag to avoid parser rejection or accidental attribute consumption. It does not balance tags because Telegram closes them; a custom balancer would need complex quote, comment, and self-closing-tag handling.
func TruncateRunes ¶
TruncateRunes limits characters rather than bytes and adds an ellipsis on truncation; max<=0 disables the limit. WeCom counts bytes while Telegram counts characters. Using bytes for Telegram silently cuts Chinese capacity to about one third, so retain both helpers and choose by channel.
func ValidMinSeverity ¶
ValidMinSeverity accepts supported thresholds and an empty unrestricted value.
Types ¶
type Channel ¶
type Channel interface {
// Kind returns the channel identifier, which must match its registry key.
Kind() string
// Validate checks required fields and formats before saving. Errors appear directly to operators, so
// identify the missing field rather than reporting a generic invalid configuration.
Validate(cfg map[string]any) error
// Send delivers a message and returns the number of items actually delivered. Platforms impose size
// limits; marking an entire truncated batch delivered would silently lose the omitted findings. Mark
// only the first kept items delivered and retain the rest for the next batch. An error means delivery
// failed; *PermanentError means it must not be retried. Ignore kept on failure.
Send(ctx context.Context, cfg map[string]any, m Message) (int, error)
// DefaultRatePerMin returns the platform's recommended per-minute limit for new configurations. Zero
// means no known limit.
DefaultRatePerMin() int
// SecretKeys identifies credential fields. The API masks them and preserves stored values when masks
// are submitted. Only each adapter knows its credentials (such as an entire WeCom webhook URL or a
// DingTalk signing secret); callers must not guess.
SecretKeys() []string
// DestinationKeys identifies fields controlling where messages are sent. Changing a destination while
// retaining credentials could send stored secrets to an attacker and defeat masking. See
// PrepareConfigUpdate.
DestinationKeys() []string
}
Channel adapts one notification transport. Implementations must be stateless: concurrent configurations share instances and supply credentials through cfg.
type ErrDestinationChangedWithoutCredentials ¶
type ErrDestinationChangedWithoutCredentials struct {
Changed []string // Changed destination keys.
Missing []string // Credential keys without an explicit choice.
}
ErrDestinationChangedWithoutCredentials rejects a destination change without explicit credential choices. See PrepareConfigUpdate for why neither silently allowing nor silently discarding credentials is safe.
func (*ErrDestinationChangedWithoutCredentials) Error ¶
func (e *ErrDestinationChangedWithoutCredentials) Error() string
type Filter ¶
type Filter struct {
// MinSeverity is low/medium/high/critical; empty disables the threshold.
MinSeverity string `json:"min_severity"`
// Empty TaskIDs/AssetIDs means unrestricted; otherwise the event must intersect the selected scope.
TaskIDs []int64 `json:"task_ids"`
AssetIDs []int64 `json:"asset_ids"`
// Empty VulnClassInclude accepts all classes; otherwise any keyword must match. Any exclusion match
// takes precedence. Case-insensitive substring matching avoids malformed regexes silently disabling
// delivery.
VulnClassInclude []string `json:"vulnclass_include"`
VulnClassExclude []string `json:"vulnclass_exclude"`
// OnStatusChange enables status-change events, relevant only to realtime channels.
OnStatusChange bool `json:"on_status_change"`
}
Filter defines the notification_channels.filter JSONB contract. All fields are optional; zero values mean no filtering, including malformed-config fallback (see ParseFilter).
func ParseFilter ¶
ParseFilter never returns an error. Malformed configuration falls back to a zero Filter and unrestricted matching: an extra finding notification is preferable to silently dropping a high- severity finding behind an apparently configured channel.
func (Filter) Validate ¶
Validate checks constrained fields on write. Unknown thresholds rank zero, so a typo such as hgih silently accepts everything; although this avoids missed findings, it defeats expected severity filtering with no warning. Reject such values at the boundary. Reads remain tolerant through ParseFilter so existing bad values do not make historical channels unreadable.
type Item ¶
type Item struct {
FindingID int64
Name string
VulnClass string
Severity string
Summary string
// Assets contains resolved display names such as domains or IPs. The server populates them because
// this package does not access the database.
Assets []string
// DetailURL links to the finding. An empty public_base_url omits the link.
DetailURL string
// Status-change fields; when present, render the old-to-new status transition.
FromStatus string
ToStatus string
}
Item is one finding prepared for channel rendering.
func (Item) IsStatusChange ¶
IsStatusChange reports whether this item describes a status change.
type Message ¶
type Message struct {
// Language controls built-in text only; an omitted value uses the server default.
Language locale.Lang `json:"-"`
// One item for an individual notification, or a full digest batch. Callers must supply at least one
// item.
Items []Item
// Batch selects digest rendering with a different title, time window, and count.
Batch bool
// WindowMinutes is the configured digest interval, used only for batch wording. Pass it explicitly
// instead of computing time.Since while rendering to keep output deterministic and testable.
WindowMinutes int
// HomeURL is the dashboard address from public_base_url; empty means no dashboard link.
HomeURL string
}
Message contains the complete content of one channel delivery.
type PermanentError ¶
type PermanentError struct{ Err error }
PermanentError marks non-retryable failures such as invalid credentials, rejection, or malformed requests. Retries help transient network failures, rate limits, and 5xx responses; retrying permanent failures only obscures the actual cause.
func (*PermanentError) Error ¶
func (e *PermanentError) Error() string
func (*PermanentError) Unwrap ¶
func (e *PermanentError) Unwrap() error
type Snapshot ¶
type Snapshot struct {
// Event kind: finding_created / finding_status_changed.
Kind string `json:"kind"`
FindingID int64 `json:"finding_id"`
TaskID int64 `json:"task_id"`
VulnClass string `json:"vulnclass"`
Name string `json:"name"`
Severity string `json:"severity"`
Summary string `json:"summary"`
AssetIDs []int64 `json:"asset_ids"`
// Populated only for finding_status_changed.
FromStatus string `json:"from_status,omitempty"`
ToStatus string `json:"to_status,omitempty"`
}
Snapshot defines the notification_events.snapshot JSONB contract. Finding transactions write it; server delivery and filters read it. The notification domain owns these semantics while db only serializes. Duplicated finding fields preserve the conclusion at event time despite later title, severity, or status edits; querying current values could dangerously downplay an originally severe event. Fan-out/rendering also avoid joining findings, tasks, and assets.