mirror of
https://github.com/BaaRai/ARTEX.git
synced 2026-12-03 13:11:05 +00:00
Escaping already stops the <!channel> and <@U…> forms. Plain "@channel", "@here" or "@user" is left unlinked by Slack's default; the payload now sets link_names=false so this does not depend on the default, and a test pins it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
226 lines
8.7 KiB
Go
226 lines
8.7 KiB
Go
package notify
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"net/url"
|
|
"regexp"
|
|
"strings"
|
|
"unicode"
|
|
"unicode/utf8"
|
|
)
|
|
|
|
// slackChannel implements Slack Incoming Webhooks.
|
|
//
|
|
// Platform traits:
|
|
// - The webhook URL (https://hooks.slack.com/services/T…/B…/…) is the entire
|
|
// credential: whoever holds it can post. Slack scans for leaked webhook URLs
|
|
// and revokes them.
|
|
// - Each URL is bound to the one destination picked when it was created: a
|
|
// channel or the installer's own direct messages. The payload cannot
|
|
// override the channel, username or icon, so several destinations mean
|
|
// several channel instances.
|
|
// - Slack documents 1 message per second with short bursts; beyond that it
|
|
// answers 429 with Retry-After.
|
|
// - Slack recommends keeping the text field under 4000 characters.
|
|
type slackChannel struct{}
|
|
|
|
// slackHosts are the only hosts a Slack webhook may point at: the commercial
|
|
// and the GovSlack endpoint. Restricting the host keeps a typo or a pasted
|
|
// look-alike URL from sending findings somewhere else. Tests add the host of
|
|
// their fake receiver.
|
|
var slackHosts = map[string]bool{
|
|
"hooks.slack.com": true,
|
|
"hooks.slack-gov.com": true,
|
|
}
|
|
|
|
// slackInsecureHosts may be reached over plain http. It is empty outside
|
|
// tests, whose httptest receivers do not speak TLS.
|
|
var slackInsecureHosts = map[string]bool{}
|
|
|
|
// slackWebhookPath is the shape of every Incoming Webhook path:
|
|
// /services/<team>/<bot>/<secret>.
|
|
var slackWebhookPath = regexp.MustCompile(`^/services/[A-Za-z0-9]+/[A-Za-z0-9]+/[A-Za-z0-9]+$`)
|
|
|
|
func (slackChannel) Kind() string { return KindSlack }
|
|
|
|
func (slackChannel) DefaultRatePerMin() int { return 60 }
|
|
|
|
// The whole URL is the credential and also the destination, like WeCom.
|
|
func (slackChannel) SecretKeys() []string { return []string{"webhook"} }
|
|
|
|
func (slackChannel) DestinationKeys() []string { return []string{"webhook"} }
|
|
|
|
// Validate checks the webhook address. Error messages never echo the URL: its
|
|
// path is the secret.
|
|
func (slackChannel) Validate(cfg map[string]any) error {
|
|
hook := cfgString(cfg, "webhook")
|
|
if hook == "" {
|
|
return errors.New("missing Webhook address")
|
|
}
|
|
u, err := url.Parse(hook)
|
|
if err != nil || u.Host == "" {
|
|
return errors.New("invalid Webhook address: it should look like https://hooks.slack.com/services/...")
|
|
}
|
|
host := strings.ToLower(u.Hostname())
|
|
if strings.ContainsFunc(hook, unicode.IsSpace) {
|
|
return errors.New("invalid Webhook address: it contains whitespace, paste it again from Slack")
|
|
}
|
|
if u.User != nil {
|
|
return errors.New("invalid Webhook address: user info is not allowed")
|
|
}
|
|
if u.Scheme != "https" && !(u.Scheme == "http" && slackInsecureHosts[host]) {
|
|
return errors.New("invalid Webhook address: https is required")
|
|
}
|
|
if !slackHosts[host] {
|
|
return fmt.Errorf("invalid Webhook address: host %q is not a Slack webhook host (hooks.slack.com)", host)
|
|
}
|
|
if u.Port() != "" && !slackInsecureHosts[host] {
|
|
return errors.New("invalid Webhook address: a port is not allowed")
|
|
}
|
|
if u.RawQuery != "" || u.ForceQuery || u.Fragment != "" {
|
|
return errors.New("invalid Webhook address: it should not have a query or fragment")
|
|
}
|
|
if !slackWebhookPath.MatchString(u.EscapedPath()) {
|
|
return errors.New("invalid Webhook address: the path should look like /services/T…/B…/…")
|
|
}
|
|
if err := validateHTTPURL(hook); err != nil {
|
|
return fmt.Errorf("invalid Webhook address: %w", err)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (c slackChannel) Send(ctx context.Context, cfg map[string]any, m Message) (int, error) {
|
|
if err := c.Validate(cfg); err != nil {
|
|
return 0, Permanent(err)
|
|
}
|
|
text, kept := slackText(m)
|
|
payload := map[string]any{
|
|
"text": text,
|
|
// Previews are fetched by Slack's servers; turning them off keeps a
|
|
// digest compact and stops a finding's URL from expanding into a card.
|
|
"unfurl_links": false,
|
|
"unfurl_media": false,
|
|
// Plain "@channel", "@here" or "@user" in finding text must stay text.
|
|
// Slack's default already leaves them unlinked; setting it here keeps that
|
|
// from depending on the default. Escaping covers the <!channel> form.
|
|
"link_names": false,
|
|
}
|
|
// Slack answers 200 with a plain "ok"; failures carry a meaningful status
|
|
// (404 no_service for a revoked hook, 429 rate_limited, ...), which doJSON
|
|
// already classifies as retryable or permanent.
|
|
if _, err := doJSON(ctx, "POST", cfgString(cfg, "webhook"), nil, payload); err != nil {
|
|
return 0, err
|
|
}
|
|
return kept, nil
|
|
}
|
|
|
|
// slackTextLimit is where a message is cut, in characters: Slack recommends
|
|
// keeping text under 4000 characters, and the cut is a little earlier.
|
|
const slackTextLimit = 3900
|
|
|
|
// slackReservedRunes is reserved for the digest title and a possible truncation
|
|
// notice (in characters).
|
|
const slackReservedRunes = 160
|
|
|
|
// slackText renders the mrkdwn text and returns it together with the number of
|
|
// items actually written (see Channel.Send). It mirrors telegramHTML.
|
|
func slackText(m Message) (string, int) {
|
|
lim := m.limits()
|
|
if m.Batch {
|
|
footer := ""
|
|
if m.HomeURL != "" {
|
|
footer = "\n\n" + slackLink(m.HomeURL, "View all on the platform")
|
|
}
|
|
// Lines are measured escaped, as written, so the escaped digest cannot
|
|
// outgrow the budget and drop items that were counted as sent.
|
|
kept := packItemCount(m.Items, slackTextLimit, slackReservedRunes, footer, runeSize, func(it Item, idx int) string {
|
|
return "\n" + slackEscape(slackBatchLine(it, idx+1, lim))
|
|
})
|
|
items := m.Items[:kept]
|
|
var b strings.Builder
|
|
b.WriteString("*" + slackEscape(slackBatchTitle(m, items, len(m.Items))) + "*")
|
|
for i, it := range items {
|
|
b.WriteString("\n" + slackEscape(slackBatchLine(it, i+1, lim)))
|
|
}
|
|
return slackFit(b.String(), footer), kept
|
|
}
|
|
var b strings.Builder
|
|
b.WriteString("*" + slackEscape(markdownTitle(m)) + "*")
|
|
if len(m.Items) == 0 {
|
|
return b.String(), 0
|
|
}
|
|
it := m.Items[0]
|
|
if it.IsStatusChange() {
|
|
b.WriteString("\n*Status change*: " + slackEscape(StatusLabel(it.FromStatus)) + " → " + slackEscape(StatusLabel(it.ToStatus)))
|
|
}
|
|
if it.VulnClass != "" && it.VulnClass != it.Title() {
|
|
b.WriteString("\n*Type*: " + slackEscape(OneLine(it.VulnClass, 0)))
|
|
}
|
|
if a := OneLine(assetLine(it.Assets, lim.AssetsShown), 0); a != "" {
|
|
b.WriteString("\n*Assets*: " + slackEscape(a))
|
|
}
|
|
if s := OneLine(it.Summary, lim.SummaryRunes); s != "" {
|
|
b.WriteString("\n*Summary*: " + slackEscape(s))
|
|
}
|
|
link := ""
|
|
if it.DetailURL != "" {
|
|
link = "\n\n" + slackLink(it.DetailURL, "View details")
|
|
}
|
|
return slackFit(b.String(), link), 1
|
|
}
|
|
|
|
// slackFit cuts body so that body+tail fits slackTextLimit, then appends tail.
|
|
// The tail (the detail or "view all" link) is never cut, and the cut backs off
|
|
// a split &entity; (TruncateHTML), which Slack would otherwise show raw.
|
|
func slackFit(body, tail string) string {
|
|
return TruncateHTML(body, slackTextLimit-utf8.RuneCountInString(tail)) + tail
|
|
}
|
|
|
|
// slackBatchLine renders one digest entry (unescaped; the caller escapes it).
|
|
// Untrusted text is single-lined: in mrkdwn a newline followed by *…* would
|
|
// render as a field label or a digest entry indistinguishable from real ones.
|
|
func slackBatchLine(it Item, idx int, lim Limits) string {
|
|
return OneLine(slackBatchLineRaw(it, idx, lim), 0)
|
|
}
|
|
|
|
func slackBatchLineRaw(it Item, idx int, lim Limits) string {
|
|
if a := assetLine(it.Assets, lim.AssetsShown); a != "" {
|
|
return fmt.Sprintf("%d. %s · %s — %s", idx, SeverityLabel(it.Severity), it.Title(), a)
|
|
}
|
|
return fmt.Sprintf("%d. %s · %s", idx, SeverityLabel(it.Severity), it.Title())
|
|
}
|
|
|
|
// slackBatchTitle renders the digest title. The count shown first is the batch
|
|
// total; when the message holds fewer items, it says how many follow.
|
|
func slackBatchTitle(m Message, items []Item, total int) string {
|
|
title := fmt.Sprintf("Vulnerability digest · %d total", total)
|
|
if extra := total - len(items); extra > 0 {
|
|
title += fmt.Sprintf(" (showing the first %d, %d more in the next message)", len(items), extra)
|
|
}
|
|
if m.WindowMinutes > 0 {
|
|
title = fmt.Sprintf("Last %d min · %s", m.WindowMinutes, title)
|
|
}
|
|
return title
|
|
}
|
|
|
|
// slackEscape escapes the three characters Slack treats as control characters
|
|
// in mrkdwn. Escaping < and > is what keeps untrusted text from forming a
|
|
// mention (<!channel>, <@U123>) or a link with hidden text (<url|text>).
|
|
// Slack decodes only these three entities, so nothing else is encoded.
|
|
func slackEscape(s string) string {
|
|
s = strings.ReplaceAll(s, "&", "&")
|
|
s = strings.ReplaceAll(s, "<", "<")
|
|
s = strings.ReplaceAll(s, ">", ">")
|
|
return s
|
|
}
|
|
|
|
// slackLink renders <url|text>. A | in the URL would end it early, so it is
|
|
// percent-encoded; the URLs come from ARTEX's own link-back setting.
|
|
func slackLink(u, text string) string {
|
|
if u == "" {
|
|
return ""
|
|
}
|
|
return "<" + slackEscape(strings.ReplaceAll(u, "|", "%7C")) + "|" + slackEscape(text) + ">"
|
|
}
|