ARTEX/notify/slack_test.go
AdrianSantamariaR 3b6caf63f5 fix(notify): send link_names=false so plain @channel in finding text stays text
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>
2026-12-02 21:39:34 +01:00

272 lines
9.7 KiB
Go

package notify
import (
"context"
"io"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"testing"
"unicode/utf8"
)
// slackTestURL registers a fake receiver as an allowed Slack webhook host for
// the duration of the test and returns a webhook URL pointing at it. Plain
// httptest servers speak http, so the host is also allowed without TLS; the
// package TestMain already enables loopback delivery.
func slackTestURL(t *testing.T, srv *httptest.Server) string {
t.Helper()
u, err := url.Parse(srv.URL)
if err != nil {
t.Fatalf("parse test server URL: %v", err)
}
host := u.Hostname()
slackHosts[host] = true
slackInsecureHosts[host] = true
t.Cleanup(func() {
delete(slackHosts, host)
delete(slackInsecureHosts, host)
})
return srv.URL + "/services/T000/B000/XXXX"
}
func TestSlackValidate(t *testing.T) {
ok := []string{
"https://hooks.slack.com/services/T000/B000/XXXX",
"https://hooks.slack-gov.com/services/T000/B000/XXXX",
" https://hooks.slack.com/services/T000/B000/XXXX ", // cfgString trims whitespace
"https://HOOKS.SLACK.COM/services/T000/B000/XXXX", // host compared lowercase
}
for _, u := range ok {
if err := (slackChannel{}).Validate(map[string]any{"webhook": u}); err != nil {
t.Errorf("%q should be accepted, got %v", u, err)
}
}
bad := []string{
"",
"http://hooks.slack.com/services/T000/B000/XXXX",
"https://hooks.slack.com.evil.com/services/T000/B000/XXXX",
"https://evil.com/services/T000/B000/XXXX",
"https://hooks.slack.com/other/T000/XXXX",
"https://user@hooks.slack.com/services/T000/B000/XXXX",
"https://hooks.slack.com/services/T0 00/B000/XXXX", // inner whitespace from a broken paste
"not a url XXXX",
}
for _, u := range bad {
err := (slackChannel{}).Validate(map[string]any{"webhook": u})
if err == nil {
t.Errorf("%q should be rejected", u)
continue
}
if strings.Contains(err.Error(), "XXXX") {
t.Errorf("error for %q leaks the secret part of the URL: %v", u, err)
}
}
}
func TestSlackDeclaresWebhookAsSecretAndDestination(t *testing.T) {
c := slackChannel{}
if got := c.SecretKeys(); len(got) != 1 || got[0] != "webhook" {
t.Fatalf("SecretKeys = %v, want [webhook]", got)
}
if got := c.DestinationKeys(); len(got) != 1 || got[0] != "webhook" {
t.Fatalf("DestinationKeys = %v, want [webhook]", got)
}
if c.DefaultRatePerMin() != 60 {
t.Fatalf("DefaultRatePerMin = %d, want 60", c.DefaultRatePerMin())
}
}
func TestSlackSendsTextPayload(t *testing.T) {
var body map[string]any
var method, ctype string
srv := capturePost(t, "ok", func(t *testing.T, b map[string]any, r *http.Request) {
body, method, ctype = b, r.Method, r.Header.Get("Content-Type")
})
kept, err := (slackChannel{}).Send(context.Background(), map[string]any{"webhook": slackTestURL(t, srv)}, singleMsg())
if err != nil || kept != 1 {
t.Fatalf("Send = %d, %v; want 1, nil", kept, err)
}
if method != http.MethodPost || !strings.HasPrefix(ctype, "application/json") {
t.Fatalf("want a JSON POST, got %s %q", method, ctype)
}
if body["unfurl_links"] != false || body["unfurl_media"] != false {
t.Fatalf("link unfurling should be off, got %v / %v", body["unfurl_links"], body["unfurl_media"])
}
text, _ := body["text"].(string)
if !strings.Contains(text, "*["+SeverityLabel("high")+"]") {
t.Fatalf("title should be bold with the severity label, got %q", text)
}
if !strings.Contains(text, "<https://artex.local/function/findings/detail?id=42|View details>") {
t.Fatalf("detail link missing or malformed, got %q", text)
}
}
func TestSlackEscapesUntrustedContent(t *testing.T) {
var text string
srv := capturePost(t, "ok", func(t *testing.T, b map[string]any, _ *http.Request) {
text, _ = b["text"].(string)
})
m := Message{Items: []Item{{
Severity: "high",
// Title and summary come from the target / model output: untrusted.
Name: "<!channel> & <https://evil.example|click>",
Summary: "<@U123> a & b",
}}}
if _, err := (slackChannel{}).Send(context.Background(), map[string]any{"webhook": slackTestURL(t, srv)}, m); err != nil {
t.Fatalf("delivery failed: %v", err)
}
for _, raw := range []string{"<!channel>", "<@U123>", "<https://evil.example|click>"} {
if strings.Contains(text, raw) {
t.Fatalf("untrusted %q reached Slack unescaped: %q", raw, text)
}
}
for _, want := range []string{"&lt;!channel&gt; &amp; &lt;https://evil.example|click&gt;", "&lt;@U123&gt; a &amp; b"} {
if !strings.Contains(text, want) {
t.Fatalf("expected escaped %q in %q", want, text)
}
}
}
func TestSlackKeepsPlainMentionsAsText(t *testing.T) {
var body map[string]any
srv := capturePost(t, "ok", func(t *testing.T, b map[string]any, _ *http.Request) {
body = b
})
m := Message{Items: []Item{{
Severity: "high",
Name: "Admin panel @channel",
Summary: "@here @everyone @admin",
}}}
if _, err := (slackChannel{}).Send(context.Background(), map[string]any{"webhook": slackTestURL(t, srv)}, m); err != nil {
t.Fatalf("delivery failed: %v", err)
}
// link_names must be sent as false, so Slack never turns plain names into mentions.
if v, ok := body["link_names"]; !ok || v != false {
t.Fatalf("link_names should be sent as false, got %v (present=%v)", v, ok)
}
text, _ := body["text"].(string)
for _, want := range []string{"Admin panel @channel", "@here @everyone @admin"} {
if !strings.Contains(text, want) {
t.Fatalf("plain mention %q should reach Slack as text, got %q", want, text)
}
}
for _, special := range []string{"<!channel>", "<!here>", "<!everyone>"} {
if strings.Contains(text, special) {
t.Fatalf("plain text was turned into the mention %q: %q", special, text)
}
}
}
func TestSlackDigestPacksWithinLimit(t *testing.T) {
m := batchMsg(300)
for i := range m.Items {
m.Items[i].Name = "vuln🙂" + itoa(i)
m.Items[i].Summary = strings.Repeat("漏洞", 50)
}
text, kept := slackText(m)
if kept <= 0 || kept >= 300 {
t.Fatalf("kept = %d, want a partial digest", kept)
}
if n := utf8.RuneCountInString(text); n > slackTextLimit {
t.Fatalf("digest is %d characters, limit %d", n, slackTextLimit)
}
if !utf8.ValidString(text) {
t.Fatal("digest was cut inside a multi-byte character")
}
if !strings.Contains(text, "300 total") {
t.Fatalf("digest title should state the batch total, got %q", text[:80])
}
if !strings.Contains(text, "<https://artex.local/function/findings|View all on the platform>") {
t.Fatal("digest footer link missing")
}
if _, kept := slackText(batchMsg(3)); kept != 3 {
t.Fatalf("a small digest should keep every item, kept %d", kept)
}
}
func TestSlackErrorClassification(t *testing.T) {
cases := []struct {
code int
body string
permanent bool
}{
{http.StatusTooManyRequests, "rate_limited", false},
{http.StatusNotFound, "no_service", true},
{http.StatusInternalServerError, "rollup_error", false},
}
for _, c := range cases {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(c.code)
_, _ = io.WriteString(w, c.body)
}))
t.Cleanup(srv.Close)
_, err := (slackChannel{}).Send(context.Background(), map[string]any{"webhook": slackTestURL(t, srv)}, singleMsg())
if err == nil || IsPermanent(err) != c.permanent {
t.Errorf("HTTP %d %s: err = %v, permanent = %v; want permanent = %v", c.code, c.body, err, IsPermanent(err), c.permanent)
}
if err != nil && strings.Contains(err.Error(), "XXXX") {
t.Errorf("HTTP %d: error leaks the webhook secret: %v", c.code, err)
}
}
}
func TestSlackKeepsUntrustedFieldsOnOneLine(t *testing.T) {
single := Message{Items: []Item{{
Severity: "high",
Name: "title",
VulnClass: "c\n*Fake*: x",
Assets: []string{"h\n>q"},
}}}
text, _ := slackText(single)
for _, forged := range []string{"\n*Fake*", "\n&gt;q"} {
if strings.Contains(text, forged) {
t.Fatalf("untrusted newline forged a line %q in %q", forged, text)
}
}
digest := batchMsg(1)
digest.Items[0].Name = "a\n2. Critical · *fake* entry"
text, _ = slackText(digest)
if strings.Contains(text, "\n2. Critical") {
t.Fatalf("untrusted newline forged a digest entry in %q", text)
}
}
func TestSlackTruncationKeepsEntitiesAndLinks(t *testing.T) {
// A summary limit of 0 means "no limit", so the final cut is the only
// guard. The body is all entities: a naive rune cut splits one.
m := singleMsg()
m.Limits = &Limits{SummaryRunes: 0, AssetsShown: DefaultMaxAssetsShown}
m.Items[0].Summary = strings.Repeat("&", 5000)
text, _ := slackText(m)
if n := utf8.RuneCountInString(text); n > slackTextLimit {
t.Fatalf("message is %d characters, limit %d", n, slackTextLimit)
}
if !strings.HasSuffix(text, "<https://artex.local/function/findings/detail?id=42|View details>") {
t.Fatalf("the detail link should survive the cut, message ends with %q", text[len(text)-60:])
}
body := strings.TrimSuffix(text, "<https://artex.local/function/findings/detail?id=42|View details>")
if amp := strings.LastIndex(body, "&"); amp >= 0 && !strings.Contains(body[amp:], ";") {
t.Fatalf("the cut split an entity: ...%q", body[len(body)-20:])
}
}
func TestSlackValidateRequiresTheWebhookShape(t *testing.T) {
bad := []string{
"https://hooks.slack.com:8443/services/T000/B000/XXXX", // explicit port
"https://hooks.slack.com/services/T000/B000/XXXX?x=1", // query
"https://hooks.slack.com/services/T000/B000/XXXX#frag", // fragment
"https://hooks.slack.com/services/", // no token
"https://hooks.slack.com/services/T000/B000", // incomplete token
"https://hooks.slack.com/services/../api/XXXX/x", // path games
"https://hooks.slack.com/services/T000/B000/XXXX/extra",
}
for _, u := range bad {
if err := (slackChannel{}).Validate(map[string]any{"webhook": u}); err == nil {
t.Errorf("%q should be rejected", u)
} else if strings.Contains(err.Error(), "XXXX") {
t.Errorf("error for %q leaks the secret part of the URL: %v", u, err)
}
}
}