mirror of
https://github.com/BaaRai/ARTEX.git
synced 2026-11-14 20:20:54 +08:00
Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0cc22cb794 |
+20
-53
@@ -126,12 +126,6 @@ func feishuSeverityTemplate(severity string) string {
|
||||
// clearly below that limit to also cover JSON wrapping overhead.
|
||||
const feishuMaxCardBytes = 16000
|
||||
|
||||
// feishuEnvelopeBytes is the size of what Send serializes around the card when a
|
||||
// signing secret is configured (without one the request is smaller):
|
||||
//
|
||||
// {"card":…,"msg_type":"interactive","sign":"<44 characters>","timestamp":"<10 digits>"}
|
||||
const feishuEnvelopeBytes = 113
|
||||
|
||||
// feishuCard builds the interactive card and returns it along with the **number
|
||||
// of items actually written**. kept serves the same purpose as in markdownBody:
|
||||
// only items that actually made it into the card should be marked as sent.
|
||||
@@ -141,51 +135,23 @@ func feishuCard(m Message) (map[string]any, int) {
|
||||
// TruncateBytes plays in markdownBody. With the summary or asset limit set to
|
||||
// 0 an item has no other bound, and an oversized card loses the whole message.
|
||||
budget := feishuMaxCardBytes - markdownReservedBytes
|
||||
card := map[string]any{
|
||||
"config": map[string]any{"wide_screen_mode": true},
|
||||
"header": map[string]any{"title": map[string]any{"tag": "plain_text", "content": markdownTitle(m)}},
|
||||
}
|
||||
if len(m.Items) > 0 {
|
||||
card["header"].(map[string]any)["template"] = feishuSeverityTemplate(m.Items[0].Severity)
|
||||
}
|
||||
elements := []any{}
|
||||
kept := 0
|
||||
if m.Batch {
|
||||
// digest assembles the elements of a digest card around the lines of its
|
||||
// first n items. The intro must state "the remaining N items will continue
|
||||
// in the next message", and N must come from the number of items that
|
||||
// actually fit.
|
||||
digest := func(n int, lines []any) []any {
|
||||
out := []any{feishuMarkdownDiv(markdownBatchIntro(m, m.Items[:n], len(m.Items)))}
|
||||
out = append(out, lines...)
|
||||
if m.HomeURL != "" {
|
||||
out = append(out, feishuButton("View all on the platform", m.HomeURL))
|
||||
}
|
||||
return out
|
||||
// Pack whole items first, then assemble the header: the header must state
|
||||
// "the remaining N items will continue in the next message", and N must
|
||||
// come from the number of items that actually fit.
|
||||
kept = packItemCount(m.Items, feishuMaxCardBytes, markdownReservedBytes, "", byteSize, func(it Item, idx int) string {
|
||||
return feishuBatchLine(it, idx+1, lim)
|
||||
})
|
||||
items := m.Items[:kept]
|
||||
elements = append(elements, feishuMarkdownDiv(markdownBatchIntro(m, items, len(m.Items))))
|
||||
for i, it := range items {
|
||||
elements = append(elements, feishuMarkdownDiv(TruncateBytes(feishuBatchLine(it, i+1, lim), budget)))
|
||||
}
|
||||
// Pack whole items (see packItemCount) against the request body as it will
|
||||
// be serialized, not against the text of the lines. Each line is sent as
|
||||
// its own element: about 52 bytes of JSON around the text, plus whatever
|
||||
// the encoding escapes. Counted as text alone, several hundred short lines
|
||||
// left as one request of more than twice the 20 KB limit. The rest of the
|
||||
// body is measured too: it changes with the number of items kept (the
|
||||
// intro) and with the platform link.
|
||||
//
|
||||
// The first item is always kept: otherwise one oversized item would jam
|
||||
// the whole batch in place. Its text is truncated to budget.
|
||||
var lines []any
|
||||
used := 0
|
||||
for i, it := range m.Items {
|
||||
line := feishuMarkdownDiv(TruncateBytes(feishuBatchLine(it, i+1, lim), budget))
|
||||
used += feishuJSONSize(line) + 1 // the element and its separating comma
|
||||
card["elements"] = digest(i+1, nil)
|
||||
if i > 0 && feishuEnvelopeBytes+feishuJSONSize(card)+used > feishuMaxCardBytes {
|
||||
break
|
||||
}
|
||||
lines = append(lines, line)
|
||||
if m.HomeURL != "" {
|
||||
elements = append(elements, feishuButton("View all on the platform", m.HomeURL))
|
||||
}
|
||||
kept = len(lines)
|
||||
elements = digest(kept, lines)
|
||||
} else if len(m.Items) > 0 {
|
||||
kept = 1
|
||||
it := m.Items[0]
|
||||
@@ -195,16 +161,17 @@ func feishuCard(m Message) (map[string]any, int) {
|
||||
}
|
||||
}
|
||||
|
||||
card["elements"] = elements
|
||||
card := map[string]any{
|
||||
"config": map[string]any{"wide_screen_mode": true},
|
||||
"header": map[string]any{"title": map[string]any{"tag": "plain_text", "content": markdownTitle(m)}},
|
||||
"elements": elements,
|
||||
}
|
||||
if len(m.Items) > 0 {
|
||||
card["header"].(map[string]any)["template"] = feishuSeverityTemplate(m.Items[0].Severity)
|
||||
}
|
||||
return card, kept
|
||||
}
|
||||
|
||||
// feishuJSONSize returns the number of bytes v takes in the request body.
|
||||
func feishuJSONSize(v any) int {
|
||||
raw, _ := json.Marshal(v)
|
||||
return len(raw)
|
||||
}
|
||||
|
||||
func feishuMarkdownDiv(content string) map[string]any {
|
||||
return map[string]any{"tag": "div", "text": map[string]any{"tag": "lark_md", "content": content}}
|
||||
}
|
||||
|
||||
@@ -1,11 +1,6 @@
|
||||
package notify
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"unicode/utf8"
|
||||
@@ -110,112 +105,6 @@ func TestFeishuPackingReportsKept(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestFeishuDigestBodiesStayWithinCardLimit covers digests of many short items.
|
||||
//
|
||||
// Every digest line is sent as its own card element, which costs about 52 bytes
|
||||
// of JSON around the text plus whatever the encoding escapes. The packing used
|
||||
// to count the text only, so a digest of several hundred short lines left as one
|
||||
// request of more than twice Feishu's 20 KB limit, and Feishu rejects such a
|
||||
// request as a whole.
|
||||
//
|
||||
// The digest is sent the way the delivery engine does it: the items a message
|
||||
// did not hold go into the next one. The bodies measured are the real ones sent
|
||||
// on the wire, signature included. No item may be lost on the way: across the
|
||||
// messages, every item appears exactly once and in order.
|
||||
func TestFeishuDigestBodiesStayWithinCardLimit(t *testing.T) {
|
||||
const total = 500
|
||||
|
||||
short := batchMsg(total)
|
||||
for i := range short.Items {
|
||||
short.Items[i].Assets = nil
|
||||
}
|
||||
// The JSON encoding escapes quotes, angle brackets and ampersands, and the
|
||||
// backslashes the lark_md escaping put in before it: these titles take
|
||||
// several times their length once serialized.
|
||||
escaped := batchMsg(total)
|
||||
for i := range escaped.Items {
|
||||
escaped.Items[i].Name = `<a href="x">R&D</a> vuln` + itoa(i+1)
|
||||
}
|
||||
|
||||
cases := []struct {
|
||||
name string
|
||||
m Message
|
||||
}{
|
||||
{"short lines without assets", short},
|
||||
{"short lines with one asset", batchMsg(total)},
|
||||
{"lines that grow when serialized", escaped},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
var raw []byte
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
raw, _ = io.ReadAll(r.Body)
|
||||
_, _ = io.WriteString(w, `{"code":0,"msg":"success"}`)
|
||||
}))
|
||||
defer srv.Close()
|
||||
cfg := map[string]any{"webhook": srv.URL, "secret": "SECtest123"}
|
||||
|
||||
m := tc.m
|
||||
seen, messages := 0, 0
|
||||
for len(m.Items) > 0 {
|
||||
kept, err := (feishuChannel{}).Send(context.Background(), cfg, m)
|
||||
if err != nil {
|
||||
t.Fatalf("message %d: delivery failed: %v", messages+1, err)
|
||||
}
|
||||
messages++
|
||||
if len(raw) > feishuMaxCardBytes {
|
||||
t.Fatalf("message %d: request body of %d bytes exceeds the limit of %d (%d of %d items left to send)",
|
||||
messages, len(raw), feishuMaxCardBytes, len(m.Items), total)
|
||||
}
|
||||
var body struct {
|
||||
Card json.RawMessage `json:"card"`
|
||||
}
|
||||
var card struct {
|
||||
Elements []struct {
|
||||
Tag string `json:"tag"`
|
||||
Text struct {
|
||||
Content string `json:"content"`
|
||||
} `json:"text"`
|
||||
} `json:"elements"`
|
||||
}
|
||||
if err := json.Unmarshal(raw, &body); err != nil {
|
||||
t.Fatalf("message %d: request body is not valid JSON: %v", messages, err)
|
||||
}
|
||||
if err := json.Unmarshal(body.Card, &card); err != nil {
|
||||
t.Fatalf("message %d: card is not valid JSON: %v", messages, err)
|
||||
}
|
||||
// The packing counts what Send adds around the card as a constant.
|
||||
if got := len(raw) - len(body.Card); got != feishuEnvelopeBytes {
|
||||
t.Fatalf("message %d: %d bytes around the card, feishuEnvelopeBytes says %d", messages, got, feishuEnvelopeBytes)
|
||||
}
|
||||
// Element 0 is the intro; the button, when present, is not a div.
|
||||
lines := 0
|
||||
for _, el := range card.Elements[1:] {
|
||||
if el.Tag != "div" {
|
||||
continue
|
||||
}
|
||||
lines++
|
||||
if want := "vuln" + itoa(seen+lines) + "**"; !strings.Contains(el.Text.Content, want) {
|
||||
t.Fatalf("message %d: line %d should be item %d (%q), got %q", messages, lines, seen+lines, want, el.Text.Content)
|
||||
}
|
||||
}
|
||||
if kept <= 0 || kept != lines {
|
||||
t.Fatalf("message %d: %d items reported as delivered, the body holds %d", messages, kept, lines)
|
||||
}
|
||||
t.Logf("message %d: %d items, %d bytes", messages, kept, len(raw))
|
||||
seen += kept
|
||||
m.Items = m.Items[kept:]
|
||||
}
|
||||
if seen != total {
|
||||
t.Fatalf("%d items went out across %d messages, want %d", seen, messages, total)
|
||||
}
|
||||
if messages < 2 {
|
||||
t.Fatalf("%d items should not fit one message", total)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestWebhookAndEmailReportAllItems(t *testing.T) {
|
||||
// These two channels do not truncate the body; the whole batch counts as
|
||||
// delivered.
|
||||
|
||||
@@ -32,6 +32,18 @@ import { ConfigField, FilterSummary } from "./_components/channel-form";
|
||||
import { DeliveryList } from "./_components/delivery-list";
|
||||
import { formatBacklog, StatTile } from "./_components/stat-tile";
|
||||
|
||||
// Upper bounds of the two message render limits. They mirror the backend, which answers 400 outside [0, max].
|
||||
const SUMMARY_LIMIT_MAX = 4000;
|
||||
const ASSETS_LIMIT_MAX = 50;
|
||||
|
||||
// limitInvalid reports whether a limit input holds anything other than a whole number in [0, max].
|
||||
// Empty is valid: it is not submitted, so the stored value stays as it is.
|
||||
function limitInvalid(raw: string, max: number): boolean {
|
||||
if (raw.trim() === "") return false;
|
||||
const n = Number(raw);
|
||||
return !Number.isInteger(n) || n < 0 || n > max;
|
||||
}
|
||||
|
||||
// This page only orchestrates: loading data, holding form state, calling the API.
|
||||
// Field definitions and parsing live in _components/channel-fields.ts, controls and the filter summary in
|
||||
// _components/channel-form.tsx, and the delivery log in _components/delivery-list.tsx —
|
||||
@@ -50,6 +62,8 @@ export default function NotifyPage() {
|
||||
const [globalSaving, setGlobalSaving] = React.useState(false);
|
||||
const [baseURL, setBaseURL] = React.useState("");
|
||||
const [digestMin, setDigestMin] = React.useState("");
|
||||
const [summaryMax, setSummaryMax] = React.useState("");
|
||||
const [assetsMax, setAssetsMax] = React.useState("");
|
||||
|
||||
const load = React.useCallback(() => {
|
||||
api
|
||||
@@ -60,6 +74,14 @@ export default function NotifyPage() {
|
||||
setDigestMin(m.digest_interval_min);
|
||||
})
|
||||
.catch((e) => toast.error("Failed to load notification settings: " + (e as Error).message));
|
||||
// The two render limits are not part of /notify/meta; they are only exposed through /api/settings.
|
||||
api
|
||||
.settings()
|
||||
.then((s) => {
|
||||
setSummaryMax(String(s.notify_summary_max_runes ?? ""));
|
||||
setAssetsMax(String(s.notify_assets_max_shown ?? ""));
|
||||
})
|
||||
.catch((e) => toast.error(`Failed to load message limits: ${(e as Error).message}`));
|
||||
// Channel-list load failures must be reported: failing silently would render as "no channels at all",
|
||||
// and users would think their config was lost — scarier than a straight-up error.
|
||||
api
|
||||
@@ -244,11 +266,23 @@ export default function NotifyPage() {
|
||||
}
|
||||
|
||||
async function saveGlobal() {
|
||||
// Checked before anything is sent: the backend applies the fields of one PUT in order,
|
||||
// so a 400 on a limit would leave the URL and digest interval already saved.
|
||||
if (limitInvalid(summaryMax, SUMMARY_LIMIT_MAX)) {
|
||||
toast.error(`Summary length must be a whole number between 0 and ${SUMMARY_LIMIT_MAX}`);
|
||||
return;
|
||||
}
|
||||
if (limitInvalid(assetsMax, ASSETS_LIMIT_MAX)) {
|
||||
toast.error(`Assets listed must be a whole number between 0 and ${ASSETS_LIMIT_MAX}`);
|
||||
return;
|
||||
}
|
||||
setGlobalSaving(true);
|
||||
try {
|
||||
const patch: Record<string, unknown> = { notify_public_base_url: baseURL.trim() };
|
||||
const n = Number(digestMin);
|
||||
if (Number.isFinite(n) && n > 0) patch.notify_digest_interval_min = n;
|
||||
if (summaryMax.trim() !== "") patch.notify_summary_max_runes = Number(summaryMax);
|
||||
if (assetsMax.trim() !== "") patch.notify_assets_max_shown = Number(assetsMax);
|
||||
await api.setSettings(patch);
|
||||
toast.success("Saved");
|
||||
load();
|
||||
@@ -331,6 +365,40 @@ export default function NotifyPage() {
|
||||
/>
|
||||
<p className="text-muted-foreground text-xs">Only applies to channels in "digest" mode.</p>
|
||||
</div>
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="n-summary-max">Summary length (characters)</Label>
|
||||
<Input
|
||||
id="n-summary-max"
|
||||
type="number"
|
||||
min={0}
|
||||
max={SUMMARY_LIMIT_MAX}
|
||||
step={1}
|
||||
placeholder="120"
|
||||
value={summaryMax}
|
||||
onChange={(e) => setSummaryMax(e.target.value)}
|
||||
aria-invalid={limitInvalid(summaryMax, SUMMARY_LIMIT_MAX)}
|
||||
/>
|
||||
<p className="text-muted-foreground text-xs">
|
||||
Longest finding summary shown in a message, 0–{SUMMARY_LIMIT_MAX}. 0 = no truncation.
|
||||
</p>
|
||||
</div>
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="n-assets-max">Assets listed per finding</Label>
|
||||
<Input
|
||||
id="n-assets-max"
|
||||
type="number"
|
||||
min={0}
|
||||
max={ASSETS_LIMIT_MAX}
|
||||
step={1}
|
||||
placeholder="3"
|
||||
value={assetsMax}
|
||||
onChange={(e) => setAssetsMax(e.target.value)}
|
||||
aria-invalid={limitInvalid(assetsMax, ASSETS_LIMIT_MAX)}
|
||||
/>
|
||||
<p className="text-muted-foreground text-xs">
|
||||
Most asset names listed for a finding, 0–{ASSETS_LIMIT_MAX}. 0 = no truncation (all assets listed).
|
||||
</p>
|
||||
</div>
|
||||
<div className="sm:col-span-2">
|
||||
<Button onClick={saveGlobal} disabled={globalSaving}>
|
||||
Save global settings
|
||||
|
||||
@@ -957,6 +957,9 @@ export interface Settings {
|
||||
notify_enabled?: boolean; // master push switch, on by default; one-click kill switch for maintenance windows
|
||||
notify_public_base_url?: string; // external base URL for vulnerability detail links; empty = messages carry no link
|
||||
notify_digest_interval_min?: number; // digest mode period (minutes), default 30
|
||||
// Render limits of IM messages; 0 = no truncation. The backend answers 400 outside the bounds.
|
||||
notify_summary_max_runes?: number; // summary characters per finding, 0-4000, default 120
|
||||
notify_assets_max_shown?: number; // asset names listed per finding, 0-50, default 3
|
||||
}
|
||||
|
||||
// ---- Vulnerability IM push ----
|
||||
|
||||
Reference in New Issue
Block a user