Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(wecom): escape member-authored text in the inbox card, and keep the card inside the cap (MUL-5889) (#6592)
Xichang(Seacen) Zhao8d7e1c8d4b16
diff --git a/server/internal/integrations/wecom/inbox_message.go b/server/internal/integrations/wecom/inbox_message.goindex 0c60d67f66..4cbba92763 100644--- a/server/internal/integrations/wecom/inbox_message.go+++ b/server/internal/integrations/wecom/inbox_message.go@@ -78,6 +78,28 @@ func buildInboxMarkdown(item map[string]any, workspaceID, slug string) string {body := inboxItemBody(item)link := inboxItemLink(item, workspaceID, slug)+ // title and body are written by a member. They land inside an aibot+ // markdown card the recipient has every reason to trust — it comes from+ // the bot, not from the author — so link syntax in them must not render.+ // An issue titled "[click here](http://evil.example)" arrived as a+ // working link, and a body carrying "[重置密码]: https://evil.example"+ // plus "[重置密码]" arrived as one too.+ //+ // Per field rather than over the finished card, which is what the length+ // budget below needs — and it costs no coverage. Every line of member+ // text begins where the card's own line begins, bar the title's first,+ // and there the bot's "**[" prefix keeps the member out of the block+ // position a definition has to start in. The scan reads each field's+ // start as a line start anyway, so that one is guarded twice over rather+ // than not at all.+ //+ // Done here, before anything below measures a length: each break inserts+ // a space, and a body dense in "](" grows by half. Budget the grown text+ // or the card goes out over the cap, which WeCom refuses whole while+ // telling the sender it was delivered.+ title = breakMemberLinks(title)+ body = breakMemberLinks(body)+var b strings.Builderb.WriteString("**[")b.WriteString(inboxTypeLabel(typeStr))@@ -104,11 +126,37 @@ func buildInboxMarkdown(item map[string]any, workspaceID, slug string) string {if link != "" {suffix = "\n[查看详情](" + link + ")"}+ // Neither cut below can put a "]" back next to a "(" or a ":".+ // truncateRunes only drops a suffix, so it cannot recreate a pair+ // breakMemberLinks already separated, and every literal spliced in after+ // member text here starts with ".", "*" or "\n" — never "(" or ":".+ // Nor can dropping a suffix complete a reference definition: it can only+ // cut the destination off one. Pinned by the seam cases in+ // TestInboxCardNeverPutsCloseBracketNextToOpenParen and+ // TestInboxCardDefinesNoResolvableLinkReference.room := inboxMarkdownMaxLen - utf8.RuneCountInString(prefix) - utf8.RuneCountInString(suffix) - 4 // "\n...\n"- if room <= 0 {- return prefix + suffix- }- return prefix + "\n" + truncateRunes(body, room) + "..." + suffix+ if room > 0 {+ return prefix + "\n" + truncateRunes(body, room) + "..." + suffix+ }+ // No room for any body means the prefix itself is the problem — a long+ // enough title pushes prefix+suffix past the cap on its own, and+ // returning it unchanged means WeCom refuses the whole frame while the+ // sender is told it was delivered. Truncate the title so what goes out+ // always fits.+ fixed := utf8.RuneCountInString(prefix) - utf8.RuneCountInString(title)+ titleRoom := inboxMarkdownMaxLen - fixed - utf8.RuneCountInString(suffix) - 3 // "..."+ if titleRoom < 0 {+ // Clamping here still returns fixed+3+len(suffix) runes with no cap+ // check, so in principle this branch can hand back a card over the+ // cap. Reaching it needs a link suffix past ~3987 runes, i.e. an+ // appURL plus workspace slug of that length; both are operator- and+ // DB-constrained, never member-authored. Left as-is deliberately:+ // the alternative is dropping the link to make room, and no input+ // that exists can ask for it.+ titleRoom = 0+ }+ return "**[" + inboxTypeLabel(typeStr) + "] " ++ truncateRunes(title, titleRoom) + "...**" + suffix}// inboxItemBody extracts the body/description string from an inbox_item map.diff --git a/server/internal/integrations/wecom/inbox_message_test.go b/server/internal/integrations/wecom/inbox_message_test.goindex 2891d11803..ec4e5f8ffa 100644--- a/server/internal/integrations/wecom/inbox_message_test.go+++ b/server/internal/integrations/wecom/inbox_message_test.go@@ -4,6 +4,7 @@ import ("os""strings""testing"+ "unicode/utf8")func TestBuildInboxMarkdown_TitleBodyLink(t *testing.T) {@@ -132,3 +133,293 @@ func TestTruncateRunes(t *testing.T) {}}}++// TestInboxCardDoesNotRenderMemberAuthoredLinks: the card carries the bot's+// authority — it arrives from the bot, not from whoever wrote the issue — so+// link syntax in a member-written title must not render as a link.+func TestInboxCardDoesNotRenderMemberAuthoredLinks(t *testing.T) {+ item := map[string]any{+ "type": "mentioned",+ "title": "[click here](http://evil.example)",+ "body": "and the body [too](http://evil.example)",+ }+ out := buildInboxMarkdown(item, "ws-uuid", "acme")+ if strings.Contains(out, "](http://evil.example)") {+ t.Fatalf("member-authored link syntax rendered as a link in a bot-authored card: %q", out)+ }+ if !strings.Contains(out, "click here") {+ t.Errorf("the visible text was eaten: %q", out)+ }+}++// TestInboxCardFitsTheCapEvenWithAHugeTitle: WeCom refuses the whole frame+// past the cap, and the sender is told it was delivered — so a card that does+// not fit is a message silently lost, not a message truncated.+func TestInboxCardFitsTheCapEvenWithAHugeTitle(t *testing.T) {+ huge := strings.Repeat("标题", 4000) // far past inboxMarkdownMaxLen on its own+ t.Setenv("MULTICA_APP_URL", "https://multica.example")+ item := map[string]any{"type": "mentioned", "title": huge, "body": "body"}+ out := buildInboxMarkdown(item, "ws-uuid", "acme")+ if n := utf8.RuneCountInString(out); n > inboxMarkdownMaxLen {+ t.Fatalf("card is %d runes, cap is %d — WeCom refuses the frame and the push is lost", n, inboxMarkdownMaxLen)+ }+ if !strings.Contains(out, "查看详情") {+ t.Errorf("the view-detail affordance was dropped: %q", out[:120])+ }+}++// TestInboxCardKeepsAnOrdinaryBracketedTitleVerbatim pins the reason the+// mechanism changed. A live tenant showed backslash escaping is unusable here:+// "\[Bug\]" came back as an italic serif "Bug" with the brackets consumed —+// the client reads "\[...\]" as a display-math delimiter — and the+// conversation-list preview, which renders no markdown at all, showed the+// backslashes raw. "[Bug] ..." and "[WIP] ..." are everyday title forms, so+// the card must carry them through untouched.+func TestInboxCardKeepsAnOrdinaryBracketedTitleVerbatim(t *testing.T) {+ t.Setenv("WECOM_APP_URL", "")+ t.Setenv("MULTICA_APP_URL", "")+ t.Setenv("FRONTEND_ORIGIN", "")++ item := map[string]any{+ "type": "status_changed",+ "title": "[Bug] 登录失败",+ "body": "从 (todo) 到 (in_review)!",+ }+ out := buildInboxMarkdown(item, "ws-uuid", "acme")+ want := "**[状态变更] [Bug] 登录失败**\n从 (todo) 到 (in_review)!"+ if out != want {+ t.Fatalf("member text did not survive verbatim:\n got %q\nwant %q", out, want)+ }+ if strings.Contains(out, `\`) {+ t.Fatalf("a backslash reached the card: %q — WeCom either shows it raw in the list preview or reads it as a math delimiter in the bubble", out)+ }+}++// TestInboxCardNeverPutsCloseBracketNextToOpenParen pins the property the+// card's safety rests on: "](" never comes out adjacent. An inline link needs+// that adjacency under CommonMark ("immediately followed by") and under a+// naive `\[([^\]]+)\]\(([^)]+)\)` rewriter alike, and " {+ t.Setenv("WECOM_APP_URL", "")+ t.Setenv("MULTICA_APP_URL", "")+ t.Setenv("FRONTEND_ORIGIN", "")++ cases := []struct {+ name string+ title string+ body string+ }{+ {"link in title", "[click here](http://evil.example)", "body"},+ {"link in body", "title", "and the body [too](http://evil.example)"},+ {"image", "", "body"},+ {"nested brackets", "[a[b]](http://evil.example)", "body"},+ // A member putting a backslash in front of the pair, betting the+ // separator lands somewhere it can be undone.+ {"member-written backslash", `x\](http://evil.example)`, `y\](http://evil.example)`},+ // Both truncation branches: the cut must not fuse a "]" and a "("+ // that were separated.+ {"body truncated at the seam", "t", strings.Repeat("a", 3900) + strings.Repeat("](x)", 100)},+ {"title truncated at the seam", strings.Repeat("标题](x)", 2000), "body"},+ }+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ out := buildInboxMarkdown(map[string]any{+ "type": "mentioned", "title": tc.title, "body": tc.body,+ }, "ws-uuid", "acme")+ if i := strings.Index(out, "]("); i >= 0 {+ t.Fatalf("\"](\" came out adjacent at byte %d — that is a working link in a card the bot signs: %q",+ i, window(out, i))+ }+ })+ }+}++// TestInboxCardSeamSurvivesEveryCutOffset sweeps the truncation point across a+// dense run of "](" so some iteration cuts at every offset inside the pattern.+// The two fixed seam cases above happen to land on one offset each; this is+// the same property without the luck.+func TestInboxCardSeamSurvivesEveryCutOffset(t *testing.T) {+ t.Setenv("WECOM_APP_URL", "")+ t.Setenv("MULTICA_APP_URL", "")+ t.Setenv("FRONTEND_ORIGIN", "")++ for pad := 0; pad < 12; pad++ {+ body := strings.Repeat("a", 3900+pad) + strings.Repeat("](x)", 60)+ title := strings.Repeat("标", 3900+pad) + strings.Repeat("](x)", 60)+ for _, tc := range []struct {+ name string+ item map[string]any+ }{+ {"body", map[string]any{"type": "mentioned", "title": "t", "body": body}},+ {"title", map[string]any{"type": "mentioned", "title": title, "body": "b"}},+ } {+ out := buildInboxMarkdown(tc.item, "ws-uuid", "acme")+ if i := strings.Index(out, "]("); i >= 0 {+ t.Fatalf("%s cut at pad=%d fused a \"]\" onto a \"(\" at byte %d: %q", tc.name, pad, i, window(out, i))+ }+ if n := utf8.RuneCountInString(out); n > inboxMarkdownMaxLen {+ t.Fatalf("%s cut at pad=%d: card is %d runes, cap is %d — WeCom refuses the frame and the push is lost",+ tc.name, pad, n, inboxMarkdownMaxLen)+ }+ }+ }+}++// TestInboxCardBudgetsTheSpacesItInserts: breaking the adjacency inserts a+// visible character, so a body dense in "](" is longer going out than it was+// coming in — 1.5x in the limit. The budget has to be computed on the grown+// text. Measured after truncation, the card would ship over the cap and WeCom+// would refuse the whole frame while the send path reports success.+func TestInboxCardBudgetsTheSpacesItInserts(t *testing.T) {+ t.Setenv("MULTICA_APP_URL", "https://multica.example")+ item := map[string]any{+ "type": "mentioned",+ "title": "t",+ "body": strings.Repeat("](", 4000), // 8000 runes in, 12000 if broken+ }+ out := buildInboxMarkdown(item, "ws-uuid", "acme")+ if n := utf8.RuneCountInString(out); n > inboxMarkdownMaxLen {+ t.Fatalf("card is %d runes, cap is %d — the inserted spaces were not budgeted, so WeCom refuses the frame and the push is lost",+ n, inboxMarkdownMaxLen)+ }+}++// TestInboxCardDefinesNoResolvableLinkReference is the card-level half of the+// reference-definition guard: it proves the builder actually runs it, on both+// fields, and that neither truncation branch hands the definition back.+//+// The card is the whole document — one buildInboxMarkdown result becomes the+// "markdown.content" of exactly one aibot_send_msg frame, and nothing batches+// two items into one frame — so the definition and the label that uses it both+// have to be inside a single member's title or body for the attack to work.+// Which is what the live tenant showed: one comment body carried both.+//+// The app URL is cleared so the builder emits no link of its own; any link in+// the parsed output is then member-authored.+func TestInboxCardDefinesNoResolvableLinkReference(t *testing.T) {+ t.Setenv("WECOM_APP_URL", "")+ t.Setenv("MULTICA_APP_URL", "")+ t.Setenv("FRONTEND_ORIGIN", "")++ for _, tc := range linkReferenceAttacks {+ t.Run(tc.name, func(t *testing.T) {+ // A definition cannot begin mid-paragraph, so put a blank line+ // between the title's line and the attack — the shape a comment+ // with a second paragraph has anyway.+ body := "看这里\n\n" + tc.body++ // The same card without the guard, composed the way+ // buildInboxMarkdown composes it. Asserting it resolves keeps+ // this case from quietly becoming a test of nothing.+ unguarded := "**[提及你] t**\n" + body+ if !hasDestinationTo(markdownDestinations(unguarded), "evil.example") {+ t.Fatalf("unguarded card %q resolves no link to evil.example — this case proves nothing", unguarded)+ }++ out := buildInboxMarkdown(map[string]any{+ "type": "mentioned", "title": "t", "body": body,+ }, "ws-uuid", "acme")+ if dests := markdownDestinations(out); hasDestinationTo(dests, "evil.example") {+ t.Fatalf("body: a member-defined link survived into the card: %q resolves %v", out, dests)+ }++ // Same through the title. A title with a line break can carry a+ // definition too, and it goes through a different length branch.+ out = buildInboxMarkdown(map[string]any{+ "type": "mentioned", "title": body, "body": "b",+ }, "ws-uuid", "acme")+ if dests := markdownDestinations(out); hasDestinationTo(dests, "evil.example") {+ t.Fatalf("title: a member-defined link survived into the card: %q resolves %v", out, dests)+ }+ })+ }+}++// TestInboxCardKeepsAReferenceLikeTitleVerbatim is the constraint that shaped+// the rule. "[Bug]: 登录失败" is an everyday title, and a guard that broke every+// "]:" would trade it away to close an attack that needs a real destination —+// the same trade the backslash escaping already lost on this renderer. Byte+// for byte, or the guard is too blunt.+func TestInboxCardKeepsAReferenceLikeTitleVerbatim(t *testing.T) {+ t.Setenv("WECOM_APP_URL", "")+ t.Setenv("MULTICA_APP_URL", "")+ t.Setenv("FRONTEND_ORIGIN", "")++ item := map[string]any{+ "type": "status_changed",+ "title": "[Bug]: 登录失败",+ "body": "[WIP]: 明天再看\n\n[复现步骤]: 见 (todo) 到 (in_review)!",+ }+ out := buildInboxMarkdown(item, "ws-uuid", "acme")+ want := "**[状态变更] [Bug]: 登录失败**\n[WIP]: 明天再看\n\n[复现步骤]: 见 (todo) 到 (in_review)!"+ if out != want {+ t.Fatalf("member text did not survive verbatim:\n got %q\nwant %q", out, want)+ }+}++// TestInboxCardSeamKeepsDefinitionsBrokenAtEveryCutOffset sweeps the+// truncation point across a dense run of definitions. Cutting drops a suffix,+// so it cannot fuse a "]" back onto the ":" the guard separated — this is that+// claim under test rather than in a comment, at every offset inside the+// pattern, and it holds the card inside the cap while it is at it.+func TestInboxCardSeamKeepsDefinitionsBrokenAtEveryCutOffset(t *testing.T) {+ t.Setenv("WECOM_APP_URL", "")+ t.Setenv("MULTICA_APP_URL", "")+ t.Setenv("FRONTEND_ORIGIN", "")++ for pad := 0; pad < 12; pad++ {+ filler := strings.Repeat("a", 3900+pad)+ dense := strings.Repeat("[x]: https://evil.example\n\n[x]\n\n", 40)+ for _, tc := range []struct {+ name string+ item map[string]any+ }{+ {"body", map[string]any{"type": "mentioned", "title": "t", "body": filler + "\n\n" + dense}},+ {"title", map[string]any{"type": "mentioned", "title": filler + "\n\n" + dense, "body": "b"}},+ } {+ out := buildInboxMarkdown(tc.item, "ws-uuid", "acme")+ if dests := markdownDestinations(out); hasDestinationTo(dests, "evil.example") {+ t.Fatalf("%s cut at pad=%d let a member-defined link through: resolves %v", tc.name, pad, dests)+ }+ if n := utf8.RuneCountInString(out); n > inboxMarkdownMaxLen {+ t.Fatalf("%s cut at pad=%d: card is %d runes, cap is %d — WeCom refuses the frame and the push is lost",+ tc.name, pad, n, inboxMarkdownMaxLen)+ }+ }+ }+}++// TestInboxCardBudgetsTheSpacesTheDefinitionBreakInserts is the "](" budget+// case for the other break: a body that is nothing but definitions grows by+// one rune per line, and the budget has to be computed on the grown text or+// the card ships over the cap and WeCom drops the whole frame while the send+// path reports success.+func TestInboxCardBudgetsTheSpacesTheDefinitionBreakInserts(t *testing.T) {+ t.Setenv("MULTICA_APP_URL", "https://multica.example")+ item := map[string]any{+ "type": "mentioned",+ "title": "t",+ "body": strings.Repeat("[a]: https://evil.example\n", 500),+ }+ out := buildInboxMarkdown(item, "ws-uuid", "acme")+ if n := utf8.RuneCountInString(out); n > inboxMarkdownMaxLen {+ t.Fatalf("card is %d runes, cap is %d — the inserted spaces were not budgeted, so WeCom refuses the frame and the push is lost",+ n, inboxMarkdownMaxLen)+ }+}++// window returns a short readable slice around i for a failure message.+func window(s string, i int) string {+ lo, hi := i-10, i+10+ if lo < 0 {+ lo = 0+ }+ if hi > len(s) {+ hi = len(s)+ }+ return s[lo:hi]+}diff --git a/server/internal/integrations/wecom/markdown.go b/server/internal/integrations/wecom/markdown.gonew file mode 100644index 0000000000..138152af16--- /dev/null+++ b/server/internal/integrations/wecom/markdown.go@@ -0,0 +1,454 @@+package wecom++// markdown.go — keeping member-authored text from becoming markdown the bot+// appears to have written. Shared by the inbox card (inbox_message.go) and the+// /issue confirmation (replier.go), both of which splice someone else's words+// into a message that goes out under the bot's name.++import (+ "strings"+ "unicode/utf8"+)++// breakMemberLinks is what every caller splicing member-authored text into a+// bot-signed message runs it through. Both breaks below are needed and they+// close different constructs, so they live behind one entry point: a call site+// cannot take one and forget the other.+//+// Both are pure insertions of a single space, so the two orders agree and the+// pair is idempotent: neither can produce the pattern the other looks for.+func breakMemberLinks(s string) string {+ return breakLinkReferenceDefinitions(breakLinkAdjacency(s))+}++// breakLinkAdjacency stops member-authored text from forming a markdown link+// in a message the bot signs. An issue titled+// "[click here](http://evil.example)" otherwise arrives as a working link+// inside a card the recipient has every reason to trust: it is delivered by+// the bot, and nothing in it marks which parts are quoted from a user.+//+// It separates rather than escapes. A link is only formed when "]" and "(" are+// adjacent — CommonMark requires the link text to be followed *immediately* by+// "(", and the naive `\[([^\]]+)\]\(([^)]+)\)` rewriters that stand in for a+// real parser require it too. Image syntax "" needs the same adjacency,+// so it is covered by the same rule. One plain space between them is enough,+// and it is the only edit made: text that does not contain "](" comes back+// byte-identical, so the common "[Bug] 登录失败" title is untouched.+//+// The space is confirmed on the real renderer, not inferred: sent on its own,+// "[重置密码] (https://evil.example)" came back as plain black text with both+// brackets intact and the parenthesised URL not consumed as a destination.+//+// Backslash escaping was tried first and is unusable here. On a live tenant+// "\[Bug\]" came back as an italic serif "Bug" with the brackets gone, which+// is how a display-math block renders — the mechanism is inferred from the+// rendering, no WeCom doc describes it — and the conversation-list preview,+// which renders no markdown at all, showed the backslashes raw. So this+// function must never emit a backslash: it would either be visible or pull+// member text into a math block, and an unpaired "[" in a title would open one+// that never closes.+//+// Two properties the callers rely on:+//+// - The inserted space can never begin a line. A "]" always precedes it on+// the same line, so it cannot open an indented code block or turn into a+// trailing hard-break.+// - It adds one rune per occurrence, so callers that budget a length cap+// must call it before measuring, not after.+//+// What it does not cover. A bare URL is still auto-linkified by the client —+// observed, and out of scope: a bare URL displays its own destination, and the+// attack being closed is a label claiming to go somewhere it does not. Inline+// HTML is inert here, also observed: `<a href="https://evil.example">重置密码</a>`+// arrived as plain black text. The one construct that does reach a working+// link without "](" is a CommonMark link reference definition, and this+// renderer resolves those — see breakLinkReferenceDefinitions.+func breakLinkAdjacency(s string) string {+ return strings.ReplaceAll(s, "](", "] (")+}++// breakLinkReferenceDefinitions stops member-authored text from *defining* a+// link the bot's card then resolves. Pushed through a live tenant, a comment+// body containing+//+// [重置密码]: https://evil.example+// [重置密码]+//+// came back with the first line gone — swallowed as a definition — and the+// second rendered as a blue underlined link to evil.example. Nothing in it is+// adjacent, so breakLinkAdjacency passes the whole attack through untouched.+// Killing the definition kills the shortcut "[label]", the collapsed+// "[label][]" and the full "[text][label]" alike: all three resolve through+// the same map, and with no definition in the message none of them can.+//+// # The rule+//+// A "]" is separated from the ":" that follows it when all three hold:+//+// 1. Only block scaffolding precedes the opening "[" on its line —+// indentation, ">" blockquote markers, list bullets. Necessary, not+// decorative: a definition inside a blockquote or a list item still+// populates the whole document's reference map and resolves outside it.+// 2. The brackets form a CommonMark link label: closed by the first+// unescaped "]", no unescaped "[" inside, at least one non-whitespace+// character, at most 999. The label may span lines and still resolve, so+// the scan does too.+// 3. What follows the colon is plausibly a link *destination* — see+// looksLikeLinkDestination.+//+// Conditions 1 and 3 are halves of one question and are kept honest by one+// answer: containerPrefixBefore reports the block containers holding the+// label, and looksLikeLinkDestination is handed that same containerPrefix so+// it can step back into them when the destination sits on the next line.+// Teaching one half about a container and not the other is what leaves a+// definition intact — see the comment on containerPrefix.+//+// Condition 3 is the whole design. Breaking every "]:" would be simpler and is+// the wrong trade: "[Bug]: 登录失败" is a form real people write, and it comes+// back from here byte-identical because 登录失败 names no host — as a+// destination it is relative, so it resolves against whatever base the client+// itself is on and cannot aim the reader at someone else's server. That is the+// line the rule draws: a destination that leaves for another host is broken, a+// destination that cannot is left alone.+//+// # What it deliberately lets through+//+// - Relative destinations. "[文件]: report.pdf", "[页面]: /inbox",+// "[Owner]: R&D", "[Regex]: \d+" and "[Bug]: 登录失败" all still define a+// reference, and the label can still come out as a link — but pointing at+// the client's own base, not at an attacker. Paid knowingly to keep the+// human form intact.+// - "[foo]:(https://evil.example)". CommonMark keeps the parens inside the+// href, so it is not a URL anyone navigates to. A leading "(" is skipped+// anyway before the destination is examined, in case this renderer is+// looser, because skipping one costs nothing.+//+// # Where it over-fires, and why that is the safe side+//+// It models block containers only as a count of ">" markers, so it fires on a+// "[x]: https://…" line that CommonMark would fold into the preceding+// paragraph or read as indented code, and on a next-line destination whose+// blockquote nesting is shallower than the definition's. It does not check the+// spec's "nothing may follow the destination" rule either, so+// "[x]: https://evil.example 请点击" is broken too though CommonMark would+// leave it as prose. Every one of those costs a single space on a line that+// already carries a URL. Under-firing costs a working link under the bot's+// name, so the approximation runs this way round on purpose — the more so+// because this renderer is demonstrably not CommonMark-exact (it reads+// "\[ … \]" as a display-math delimiter).+//+// # Where the break goes+//+// Between the "]" and the ":". CommonMark requires the colon to follow the+// label immediately, so one space ends the definition; verified against a+// CommonMark parser in markdown_test.go, including inside a blockquote and+// with the destination on the next line. It cannot go inside the label —+// reference labels are matched on whitespace-collapsed, case-folded text, so+// "[ 重置密码]" would still match "[重置密码]" and the definition would live.+// It cannot be a backslash for the reason above. And it cannot go before the+// "[": there is no character that pushes a line out of block position without+// either showing up as content or, four spaces on, opening a code block.+//+// Like breakLinkAdjacency this adds one rune per occurrence, so callers that+// budget a length cap must call it before measuring; and its output holds no+// "]:" it would fire on again, so a second pass is a no-op.+func breakLinkReferenceDefinitions(s string) string {+ if !strings.Contains(s, "]:") {+ return s+ }+ var out strings.Builder+ prev := 0+ for i := 0; i < len(s); i++ {+ if s[i] != '[' {+ continue+ }+ container, ok := containerPrefixBefore(s, i)+ if !ok {+ continue+ }+ end, ok := linkLabelEnd(s, i)+ if !ok {+ continue+ }+ // A label holds no unescaped "[", so nothing inside it can open+ // another one — resume past it either way.+ i = end+ if end+1 >= len(s) || s[end+1] != ':' {+ continue+ }+ if !looksLikeLinkDestination(s[end+2:], container) {+ continue+ }+ out.WriteString(s[prev : end+1])+ out.WriteByte(' ')+ prev = end + 1+ }+ if prev == 0 {+ return s+ }+ out.WriteString(s[prev:])+ return out.String()+}++// containerPrefix is what a line's block scaffolding opens: the blockquote+// nesting the line sits inside. It is the one notion of a container the rule+// has, and both halves of the rule work from it — the half that decides what+// may precede the label produces one, the half that scans past the colon+// replays it. Neither can be taught about a container the other has not,+// which is the whole reason it exists as a value rather than as a bool.+//+// Only ">" markers are counted. Indentation and list bullets are scaffolding+// too, and they need no replay: CommonMark continues a list item with plain+// indentation, which the destination scan already steps over as whitespace.+// A blockquote is different — it repeats its marker on every line it holds,+// so a destination on the next line arrives as "> https://…", and a scan that+// does not expect the marker reads it as the destination.+type containerPrefix struct {+ quotes int+}++// containerPrefixBefore reports the containers holding the "[" at s[i], and+// whether everything between the start of its line and i is block scaffolding+// at all: indentation, ">" markers and list bullets. Anything else — a word, a+// "**" — means the "[" is inside a paragraph, where no definition can begin.+//+// It walks back only as far as the first byte that cannot be scaffolding, so a+// "[" in the middle of prose is settled by reading one byte rather than the+// whole line, and a body full of them stays linear.+func containerPrefixBefore(s string, i int) (containerPrefix, bool) {+ start := i+ for start > 0 && isBlockScaffoldByte(s[start-1]) {+ start--+ }+ if start > 0 && s[start-1] != '\n' {+ return containerPrefix{}, false+ }+ return parseContainerPrefix(s[start:i])+}++// parseContainerPrefix reads p as a whole run of block scaffolding and reports+// the containers it opens. ok is false when p holds anything that is not+// scaffolding.+func parseContainerPrefix(p string) (prefix containerPrefix, ok bool) {+ for len(p) > 0 {+ switch {+ case p[0] == ' ' || p[0] == '\t':+ p = p[1:]+ case p[0] == '>':+ prefix.quotes+++ p = p[1:]+ case (p[0] == '-' || p[0] == '+' || p[0] == '*') && len(p) > 1 && (p[1] == ' ' || p[1] == '\t'):+ p = p[2:]+ default:+ // An ordered list marker: up to 9 digits, then "." or ")",+ // then a space.+ n := 0+ for n < len(p) && n < 9 && p[n] >= '0' && p[n] <= '9' {+ n+++ }+ if n == 0 || n+1 >= len(p) || (p[n] != '.' && p[n] != ')') || (p[n+1] != ' ' && p[n+1] != '\t') {+ return containerPrefix{}, false+ }+ p = p[n+2:]+ }+ }+ return prefix, true+}++// skipContinuationPrefix steps over the markers of the containers in prefix at+// the start of a continuation line, and returns where the line's content+// begins. It is the replay half of containerPrefixBefore.+//+// It consumes at most prefix.quotes markers and never more. Fewer is allowed+// because a blockquote takes lazy continuation lines: "> [x]:" followed by a+// bare "https://…" with no marker still defines the reference. More is not a+// continuation of this definition at all — a line deeper than the block it+// continues opens a new one — so the scan stops and lets the leftover ">"+// speak for itself, which is to say it is not a destination.+func skipContinuationPrefix(s string, i int, prefix containerPrefix) int {+ i = skipSpacesTabs(s, i)+ for n := 0; n < prefix.quotes; n++ {+ if i >= len(s) || s[i] != '>' {+ return i+ }+ i = skipSpacesTabs(s, i+1)+ }+ return i+}++// isBlockScaffoldByte is the character set a scaffolding prefix can draw on —+// a superset of the markers parseContainerPrefix then parses exactly. It only+// decides how far back to walk; whether the run really is scaffolding is+// parseContainerPrefix's answer.+func isBlockScaffoldByte(c byte) bool {+ switch {+ case c == ' ', c == '\t', c == '>':+ return true+ case c == '-', c == '+', c == '*', c == '.', c == ')':+ return true+ case c >= '0' && c <= '9':+ return true+ }+ return false+}++// linkLabelEnd returns the byte offset of the "]" closing the link label that+// opens at s[open], and whether what it encloses is a label at all. Follows+// CommonMark: the first unescaped "]" closes it, an unescaped "[" disqualifies+// it, it must hold at least one non-whitespace character and at most 999, and+// it may run across line endings.+func linkLabelEnd(s string, open int) (int, bool) {+ const maxLabelRunes = 999+ runes, content := 0, false+ for i := open + 1; i < len(s); {+ r, size := utf8.DecodeRuneInString(s[i:])+ if r == ']' {+ return i, content+ }+ if r == '[' {+ return 0, false+ }+ if runes++; runes > maxLabelRunes {+ return 0, false+ }+ if r == '\\' && i+size < len(s) {+ // The backslash escapes what follows, so "\]" does not close+ // the label and "\[" does not disqualify it.+ _, n := utf8.DecodeRuneInString(s[i+size:])+ i += size + n+ runes+++ content = true+ continue+ }+ if r != ' ' && r != '\t' && r != '\n' && r != '\r' {+ content = true+ }+ i += size+ }+ return 0, false+}++// looksLikeLinkDestination reports whether rest — everything after a+// "[label]:" — opens a link destination that could send the reader to another+// host. This is the test that keeps "[Bug]: 登录失败" whole.+//+// A destination qualifies when it carries a scheme ("https:", and equally+// "javascript:" or "data:"), or is scheme-relative ("//host/path"), or uses+// the escape machinery that spells either of those after decoding.+//+// prefix is the containers the definition's own line sits inside, and it is a+// parameter rather than something rediscovered here for the reason given on+// containerPrefix: when the destination is on the next line it arrives behind+// the same markers, and a scan that walks past the colon without them reads+// the marker as the destination and clears a definition that resolves.+func looksLikeLinkDestination(rest string, prefix containerPrefix) bool {+ i := skipSpacesTabs(rest, 0)+ // CommonMark allows up to one line ending between the colon and the+ // destination, so the definition can span two lines. A second line+ // ending ends the block and there is no definition — falling through+ // with the newline still in place takes care of that, since a line+ // ending never begins a destination.+ if i < len(rest) && rest[i] == '\r' {+ i+++ }+ if i < len(rest) && rest[i] == '\n' {+ i = skipContinuationPrefix(rest, i+1, prefix)+ }+ if i < len(rest) && (rest[i] == '<' || rest[i] == '(') {+ // "<…>" is the spec's bracketed destination form, and it may hold+ // leading spaces that a client strips back off the URL.+ i = skipSpacesTabs(rest, i+1)+ }+ dest := rest[i:]+ if j := strings.IndexAny(dest, " \t\r\n"); j >= 0 {+ dest = dest[:j]+ }+ if dest == "" {+ return false+ }+ if strings.HasPrefix(dest, "//") || hasURIScheme(dest) {+ return true+ }+ // Backslash escapes and character references are recognised inside a+ // destination, and all of "https\://evil.example", "\/\/evil.example"+ // and "https://evil.example" resolve to a working off-host URL —+ // checked against a CommonMark parser, all three. Rather than decode+ // them, take any use of that machinery as a destination.+ //+ // The machinery, not the characters. A lone "\" or "&" spells nothing:+ // "R&D", "\d+", "docs\setup" and "foo&bar" are all relative destinations,+ // which this function promises to leave whole, and they carry no escape a+ // parser would act on.+ return hasBackslashEscape(dest) || hasCharacterReference(dest)+}++// hasBackslashEscape reports whether s uses a CommonMark backslash escape — a+// "\" before ASCII punctuation, which is the only place the backslash means+// anything. In "\d+" and "docs\setup" it stays literal text.+func hasBackslashEscape(s string) bool {+ for i := 0; i+1 < len(s); i++ {+ if s[i] == '\\' && isASCIIPunct(s[i+1]) {+ return true+ }+ }+ return false+}++// isASCIIPunct is CommonMark's ASCII punctuation set — every ASCII character+// that is neither a letter, a digit, nor a space.+func isASCIIPunct(c byte) bool {+ switch {+ case c >= '!' && c <= '/', c >= ':' && c <= '@', c >= '[' && c <= '`', c >= '{' && c <= '~':+ return true+ }+ return false+}++// hasCharacterReference reports whether s holds a character reference — "&",+// a name or a "#"-led numeric body, then ";". "R&D" and "foo&bar" have no ";"+// to close one, so nothing in them decodes.+//+// It does not check the name against HTML5's table: an unknown name decodes to+// nothing and breaking it costs one space, which is the side of this call the+// rest of the file already runs on.+func hasCharacterReference(s string) bool {+ for i := 0; i < len(s); i++ {+ if s[i] != '&' {+ continue+ }+ for j := i + 1; j < len(s); j++ {+ c := s[j]+ if c == ';' {+ return j > i+1+ }+ if !(c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || c == '#') {+ break+ }+ }+ }+ return false+}++// hasURIScheme reports whether s begins with a URI scheme followed by ":" —+// a letter, then letters, digits, "+", "-" or "." (RFC 3986).+func hasURIScheme(s string) bool {+ for i := 0; i < len(s); i++ {+ c := s[i]+ switch {+ case c >= 'a' && c <= 'z', c >= 'A' && c <= 'Z':+ case i > 0 && (c >= '0' && c <= '9' || c == '+' || c == '-' || c == '.'):+ case c == ':':+ return i > 0+ default:+ return false+ }+ }+ return false+}++func skipSpacesTabs(s string, i int) int {+ for i < len(s) && (s[i] == ' ' || s[i] == '\t') {+ i+++ }+ return i+}diff --git a/server/internal/integrations/wecom/markdown_test.go b/server/internal/integrations/wecom/markdown_test.gonew file mode 100644index 0000000000..1141cb4924--- /dev/null+++ b/server/internal/integrations/wecom/markdown_test.go@@ -0,0 +1,427 @@+package wecom++import (+ "net/url"+ "strings"+ "testing"++ "github.com/yuin/goldmark"+ "github.com/yuin/goldmark/ast"+ "github.com/yuin/goldmark/text"+)++// TestBreakLinkAdjacency covers the whole contract: the only edit is a space+// between "]" and "(", nothing else in the string moves, and no backslash is+// ever produced — a backslash is what the previous mechanism emitted and what+// the live tenant showed to be unusable.+func TestBreakLinkAdjacency(t *testing.T) {+ cases := []struct {+ name string+ in string+ want string+ }{+ {"ordinary bracketed title is untouched", "[Bug] 登录失败", "[Bug] 登录失败"},+ {"parens alone are untouched", "修复 (见 issue 12)", "修复 (见 issue 12)"},+ {"a lone bracket is untouched", "开了一个 [ 没关", "开了一个 [ 没关"},+ {"exclamation alone is untouched", "紧急!!!", "紧急!!!"},+ {"member backslash is left exactly as written", `修复路径 C:\`, `修复路径 C:\`},+ {"link", "[click here](http://evil.example)", "[click here] (http://evil.example)"},+ {"image", "", "![img] (http://evil.example/x.png)"},+ {"nested brackets", "[a[b]](http://evil.example)", "[a[b]] (http://evil.example)"},+ {"back to back", "](](", "] (] ("},+ {"two links", "[a](x) and [b](y)", "[a] (x) and [b] (y)"},+ {"backslash in front of the pair does not help the member", `x\](u)`, `x\] (u)`},+ }+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ got := breakLinkAdjacency(tc.in)+ if got != tc.want {+ t.Fatalf("breakLinkAdjacency(%q):\n got %q\nwant %q", tc.in, got, tc.want)+ }+ if strings.Contains(got, "](") {+ t.Fatalf("%q still holds an adjacent \"](\" — a link can still form", got)+ }+ if !strings.Contains(tc.in, `\`) && strings.Contains(got, `\`) {+ t.Fatalf("emitted a backslash for %q: %q — WeCom reads \"\\[\" as a math delimiter", tc.in, got)+ }+ })+ }+}++// TestBreakLinkAdjacencyIsIdempotent: the output contains no "](", so a second+// pass must be a no-op. Matters because the same text can reach more than one+// builder, and a mechanism that kept inserting spaces would drift.+func TestBreakLinkAdjacencyIsIdempotent(t *testing.T) {+ for _, in := range []string{"[a](b)", "](](", "[Bug] 登录失败", ""} {+ once := breakLinkAdjacency(in)+ if twice := breakLinkAdjacency(once); twice != once {+ t.Fatalf("second pass changed %q: %q → %q", in, once, twice)+ }+ }+}++// linkReferenceAttacks are bodies that define a link reference and then use it.+// Every one of them is a real CommonMark definition — the test below proves+// that by rendering each unguarded and requiring the attacker's host to come+// back as a destination, so the corpus cannot rot into a set of strings that+// were never dangerous.+//+// The shapes here are the ones a rule built on "]: looks like a URL" can get+// wrong: the destination hidden behind a "<", pushed onto the next line, spelt+// with backslash escapes or a character reference, or defined inside a+// blockquote or a list item where the label is no longer at column zero.+//+// The blockquote-continuation block is the one that got through: the label+// half accepted the ">" and the destination half did not expect it back on the+// next line, so the scan read the marker as the destination and cleared a+// definition that resolves. TestContainerPrefixHalvesAgree is the test for the+// disagreement itself; these pin the shapes it reached.+var linkReferenceAttacks = []struct {+ name string+ body string+}{+ {"plain", "[重置密码]: https://evil.example\n\n[重置密码]"},+ {"no space after the colon", "[重置密码]:https://evil.example\n\n[重置密码]"},+ {"indented three spaces", " [重置密码]: https://evil.example\n\n[重置密码]"},+ {"angle bracketed", "[重置密码]: <https://evil.example>\n\n[重置密码]"},+ {"destination on the next line", "[重置密码]:\nhttps://evil.example\n\n[重置密码]"},+ {"with a title", "[重置密码]: https://evil.example \"点这里\"\n\n[重置密码]"},+ {"title on the next line", "[重置密码]: https://evil.example\n\"点这里\"\n\n[重置密码]"},+ {"scheme relative", "[重置密码]: //evil.example/reset\n\n[重置密码]"},+ {"escaped scheme colon", `[重置密码]: https\://evil.example` + "\n\n[重置密码]"},+ {"escaped slashes", `[重置密码]: \/\/evil.example/reset` + "\n\n[重置密码]"},+ {"hex character reference", "[重置密码]: https://evil.example\n\n[重置密码]"},+ {"decimal character reference", "[重置密码]: https://evil.example\n\n[重置密码]"},+ {"inside a blockquote", "> [重置密码]: https://evil.example\n\n[重置密码]"},+ {"inside a list item", "- [重置密码]: https://evil.example\n\n[重置密码]"},+ {"inside an ordered list item", "1. [重置密码]: https://evil.example\n\n[重置密码]"},+ {"escaped bracket in the label", `[重置\]密码]: https://evil.example` + "\n\n" + `[重置\]密码]`},+ {"label across two lines", "[重置\n密码]: https://evil.example\n\n[重置\n密码]"},+ {"case folded label", "[Reset]: https://evil.example\n\n[reset]"},+ {"collapsed reference", "[重置密码]: https://evil.example\n\n[重置密码][]"},+ {"full reference", "[重置密码]: https://evil.example\n\n[点这里][重置密码]"},+ {"two definitions", "[a]: https://evil.example\n[b]: https://evil.example/2\n\n[a] [b]"},+ {"uppercase scheme", "[重置密码]: HTTPS://EVIL.EXAMPLE\n\n[重置密码]"},++ // The destination on its own line, behind the block container the+ // definition sits in.+ {"blockquote continuation", "> [重置密码]:\n> https://evil.example\n\n[重置密码]"},+ {"blockquote continuation, no space after the marker", ">[重置密码]:\n>https://evil.example\n\n[重置密码]"},+ {"blockquote continuation, tab after the marker", ">\t[重置密码]:\n>\thttps://evil.example\n\n[重置密码]"},+ {"blockquote continuation, CRLF", "> [重置密码]:\r\n> https://evil.example\r\n\r\n[重置密码]"},+ {"blockquote continuation, nested twice", "> > [重置密码]:\n> > https://evil.example\n\n[重置密码]"},+ {"blockquote continuation, nested three deep", "> > > [重置密码]:\n> > > https://evil.example\n\n[重置密码]"},+ {"blockquote continuation, indented markers", " > > [重置密码]:\n > > https://evil.example\n\n[重置密码]"},+ {"list inside a blockquote, continued by indentation", "> - [重置密码]:\n> https://evil.example\n\n[重置密码]"},+ {"ordered list inside a blockquote", "> 1. [重置密码]:\n> https://evil.example\n\n[重置密码]"},+ {"blockquote continuation, angle bracketed", "> [重置密码]:\n> <https://evil.example>\n\n[重置密码]"},+ {"blockquote continuation, scheme relative", "> [重置密码]:\n> //evil.example/x\n\n[重置密码]"},+ {"blockquote continuation, escaped scheme colon", "> [重置密码]:\n> " + `https\://evil.example` + "\n\n[重置密码]"},+ {"blockquote continuation, character reference", "> [重置密码]:\n> https://evil.example\n\n[重置密码]"},+ {"blockquote lazy continuation, marker dropped", "> [重置密码]:\nhttps://evil.example\n\n[重置密码]"},+ {"list continuation by indentation", "- [重置密码]:\n https://evil.example\n\n[重置密码]"},++ // A definition reached this way feeds the same reference map, so it is+ // worth pinning that every way of spending it is closed, not just the+ // shortcut form.+ {"blockquote continuation, collapsed reference", "> [重置密码]:\n> https://evil.example\n\n[重置密码][]"},+ {"blockquote continuation, full reference", "> [重置密码]:\n> https://evil.example\n\n[点这里][重置密码]"},+ {"blockquote continuation, image reference", "> [重置密码]:\n> https://evil.example\n\n![重置密码]"},+ {"blockquote continuation, used inside the blockquote", "> [重置密码]:\n> https://evil.example\n>\n> [重置密码]"},+}++// TestBreakLinkReferenceDefinitionsClosesEveryKnownDefinition is the guard's+// real assertion, and it is made against a CommonMark parser rather than+// against our own idea of one: for every attack shape, the guarded text must+// define no link that goes to the attacker's host.+//+// The unguarded half is not decoration. It pins that each entry really is a+// definition, so a later edit that makes the guard stop firing cannot pass by+// quietly shrinking what the corpus tests.+func TestBreakLinkReferenceDefinitionsClosesEveryKnownDefinition(t *testing.T) {+ for _, tc := range linkReferenceAttacks {+ t.Run(tc.name, func(t *testing.T) {+ if !hasDestinationTo(markdownDestinations(tc.body), "evil.example") {+ t.Fatalf("unguarded, %q resolves no link to evil.example — this case proves nothing", tc.body)+ }+ guarded := breakMemberLinks(tc.body)+ if dests := markdownDestinations(guarded); hasDestinationTo(dests, "evil.example") {+ t.Fatalf("a member-defined link survived the guard: %q → %q resolves %v",+ tc.body, guarded, dests)+ }+ })+ }+}++// TestBreakLinkReferenceDefinitionsLeavesProseAlone is the other half of the+// contract, and the reason the rule is not "always break ]:". Every string+// here must come back byte-identical: "[Bug]: 登录失败" is a title real people+// write, and mangling it to buy safety we can get another way is the same+// trade the backslash escaping already lost.+func TestBreakLinkReferenceDefinitionsLeavesProseAlone(t *testing.T) {+ for _, in := range []string{+ "[Bug]: 登录失败",+ "[Bug]: 登录失败\n\n[Bug] 还在复现",+ "[WIP]: 明天再看",+ "[文件]: report.pdf",+ "[页面]: /inbox",+ "[Bug]: 见 https://tracker.example/1", // destination is 见, not the URL+ // Relative destinations that happen to hold a "\" or an "&". Neither+ // character spells an escape or a character reference here, so there+ // is nothing to decode and nothing to break.+ "[Owner]: R&D",+ `[Regex]: \d+`,+ `[Path]: docs\setup`,+ "[Query]: foo&bar",+ "[Note]: see A&B for details",+ "[Bug] 登录失败",+ "修复 (见 issue 12)",+ "见 [文档]: https://wiki.example/x", // not at block position+ "**[提及你] t**",+ "[重置密码]:\n\nhttps://evil.example", // blank line: no definition+ "[ ]: https://evil.example", // no label content+ "[Bug]:",+ "没有方括号的一行",+ } {+ if got := breakMemberLinks(in); got != in {+ t.Fatalf("member text was altered:\n got %q\nwant %q (unchanged)", got, in)+ }+ }+}++// TestBreakLinkReferenceDefinitionsInsertsOneSpace pins where the break lands+// and that it is the only edit — one space, between the "]" and the ":".+func TestBreakLinkReferenceDefinitionsInsertsOneSpace(t *testing.T) {+ cases := []struct {+ name string+ in string+ want string+ }{+ {"plain", "[重置密码]: https://evil.example", "[重置密码] : https://evil.example"},+ {"no space after the colon", "[a]:https://x", "[a] :https://x"},+ {"next line destination", "[a]:\nhttps://x", "[a] :\nhttps://x"},+ {"blockquote", "> [a]: https://x", "> [a] : https://x"},+ {"list item", "- [a]: https://x", "- [a] : https://x"},+ {"two definitions", "[a]: https://x\n[b]: https://y", "[a] : https://x\n[b] : https://y"},+ {"only the definition on a mixed body", "看这里\n\n[a]: https://x\n\n[a]", "看这里\n\n[a] : https://x\n\n[a]"},+ // Over-fires, kept visible on purpose. Both cost one space on a line+ // that already carries a URL, and both are the safe side of a+ // renderer we cannot read: CommonMark would call the first indented+ // code and the second a paragraph, but this one is not CommonMark.+ {"four space indent is not a definition in commonmark", " [a]: https://x", " [a] : https://x"},+ {"trailing prose is not a definition in commonmark", "[a]: https://x 请点击", "[a] : https://x 请点击"},+ }+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ got := breakLinkReferenceDefinitions(tc.in)+ if got != tc.want {+ t.Fatalf("breakLinkReferenceDefinitions(%q):\n got %q\nwant %q", tc.in, got, tc.want)+ }+ if strings.Contains(got, `\`) && !strings.Contains(tc.in, `\`) {+ t.Fatalf("emitted a backslash for %q: %q — WeCom reads \"\\[\" as a math delimiter", tc.in, got)+ }+ })+ }+}++// scaffoldPrefixes enumerates block scaffolding by composing, up to depth+// pieces deep, everything a definition line can be indented and nested with.+// It is the alphabet containerPrefixBefore reads, so every prefix it accepts is+// somewhere a member can put a definition — which makes it the right thing to+// sweep both halves of the rule over.+func scaffoldPrefixes(depth int) []string {+ pieces := []string{" ", " ", "\t", ">", "> ", ">\t", "- ", "* ", "1. "}+ var out []string+ seen := map[string]bool{}+ var build func(string, int)+ build = func(cur string, d int) {+ if !seen[cur] {+ seen[cur] = true+ out = append(out, cur)+ }+ if d == 0 {+ return+ }+ for _, p := range pieces {+ build(cur+p, d-1)+ }+ }+ build("", depth)+ return out+}++// TestContainerPrefixHalvesAgree is the test for the mistake rather than for+// its symptoms, and it is the one that would have caught the blockquote+// continuation before it shipped.+//+// Breaking a definition is one rule decided in two places. containerPrefixBefore+// says what scaffolding may precede the label; looksLikeLinkDestination scans+// what follows the colon. CommonMark carries a blockquote's marker onto every+// line the quote holds, so the moment the first half accepts a ">" the second+// half has to expect it back on a destination that sits on the next line. Teach+// one and not the other and the definition survives untouched — which is+// exactly what happened.+//+// The expected marker count is taken here from the prefix text, not read off+// containerPrefixBefore's answer, so the halves are checked against the markdown+// rule instead of against each other's idea of it.+func TestContainerPrefixHalvesAgree(t *testing.T) {+ for _, prefix := range scaffoldPrefixes(3) {+ container, ok := containerPrefixBefore(prefix+"[重置密码]", len(prefix))+ if !ok {+ continue+ }+ quotes := strings.Count(prefix, ">")+ if container.quotes != quotes {+ t.Fatalf("prefix %q opens %d blockquotes, containerPrefixBefore reports %d",+ prefix, quotes, container.quotes)+ }+ // Every nesting from a lazy continuation carrying no marker at all up+ // to the definition's own depth is a line the parser still reads as+ // this definition's destination.+ for n := 0; n <= quotes; n++ {+ for _, marker := range []string{">", "> ", ">\t", " > ", " >"} {+ rest := "\n" + strings.Repeat(marker, n) + "https://evil.example"+ if !looksLikeLinkDestination(rest, container) {+ t.Fatalf("prefix %q may hold a definition, but the destination scan misses %q —\n"++ "the two halves disagree about what a block container is", prefix, rest)+ }+ }+ }+ // And no deeper. A line nested further than the definition's own block+ // starts a new one rather than continuing it, so stepping over that+ // marker would be swallowing a character that happened to be in the+ // way rather than modelling the container.+ deeper := "\n" + strings.Repeat("> ", quotes+1) + "https://evil.example"+ if looksLikeLinkDestination(deeper, container) {+ t.Fatalf("prefix %q opens %d blockquotes but the destination scan stepped over %d in %q",+ prefix, quotes, quotes+1, deeper)+ }+ }+}++// TestBreakLinkReferenceDefinitionsAcrossBlockScaffolding sweeps scaffolding on+// the definition line against scaffolding on the destination line and asserts+// against a real parser rather than against a list of shapes someone thought+// of: whatever combination genuinely defines a link to the attacker's host must+// come back from the guard defining none.+//+// Self-checking the way linkReferenceAttacks is. A combination is only asserted+// on after it has been shown to resolve unguarded, and the number that do is+// pinned, so the sweep cannot come to pass by testing nothing.+func TestBreakLinkReferenceDefinitionsAcrossBlockScaffolding(t *testing.T) {+ prefixes := scaffoldPrefixes(2)+ destinations := []string{+ "https://evil.example",+ "//evil.example/x",+ "<https://evil.example>",+ `https\://evil.example`,+ }+ live := 0+ for _, def := range prefixes {+ if _, ok := containerPrefixBefore(def+"[", len(def)); !ok {+ continue+ }+ for _, cont := range prefixes {+ for _, dest := range destinations {+ for _, nl := range []string{"\n", "\r\n"} {+ body := def + "[重置密码]:" + nl + cont + dest + nl + nl + "[重置密码]"+ if !sendsReaderTo(markdownDestinations(body), "evil.example") {+ continue+ }+ live+++ guarded := breakMemberLinks(body)+ if sendsReaderTo(markdownDestinations(guarded), "evil.example") {+ t.Fatalf("definition behind %q with its destination behind %q survived the guard:\n%q → %q",+ def, cont, body, guarded)+ }+ }+ }+ }+ }+ if live < 4000 {+ t.Fatalf("only %d swept combinations defined a link at all — the sweep has stopped testing anything", live)+ }+}++// TestBreakMemberLinksIsIdempotent: the same text can reach more than one+// builder, and the length budget is computed once, so a mechanism that kept+// inserting spaces would drift past the cap.+func TestBreakMemberLinksIsIdempotent(t *testing.T) {+ inputs := []string{+ "[a](b)", "](](", "[Bug] 登录失败", "", "[Bug]: 登录失败",+ // Both breaks firing on one string: neither can produce the pattern+ // the other looks for, so the pair has to settle after one pass.+ "[点这里](https://evil.example)\n\n[重置密码]: https://evil.example\n\n[重置密码]",+ }+ for _, tc := range linkReferenceAttacks {+ inputs = append(inputs, tc.body)+ }+ for _, in := range inputs {+ once := breakMemberLinks(in)+ if twice := breakMemberLinks(once); twice != once {+ t.Fatalf("second pass changed %q: %q → %q", in, once, twice)+ }+ }+}++// markdownDestinations parses md as CommonMark and returns the destination of+// every link and image — that is, every place a reader can be sent by clicking+// text the member chose the wording of.+//+// Autolinks are left out deliberately, and the distinction is the whole point+// of the guard. "<https://evil.example>" renders as a link whose visible text+// is its own URL, so it cannot lie about where it goes; the same is true of a+// bare URL the client linkifies. What the card must never carry is a label+// reading 重置密码 that quietly resolves somewhere else, and that is a Link or+// an Image, never an AutoLink.+func markdownDestinations(md string) []string {+ source := []byte(md)+ doc := goldmark.New().Parser().Parse(text.NewReader(source))+ var out []string+ _ = ast.Walk(doc, func(n ast.Node, entering bool) (ast.WalkStatus, error) {+ if !entering {+ return ast.WalkContinue, nil+ }+ switch node := n.(type) {+ case *ast.Link:+ out = append(out, string(node.Destination))+ case *ast.Image:+ out = append(out, string(node.Destination))+ }+ return ast.WalkContinue, nil+ })+ return out+}++// hasDestinationTo matches case-insensitively: a scheme and host in capitals+// resolve to the same server.+func hasDestinationTo(dests []string, host string) bool {+ for _, d := range dests {+ if strings.Contains(strings.ToLower(d), strings.ToLower(host)) {+ return true+ }+ }+ return false+}++// sendsReaderTo is the stricter reading of the same question, and the sweep+// above needs it: a destination has to actually aim at host, not merely spell+// its name. A tab before a ">" on the destination line makes goldmark read+// ">https://evil.example" as the destination — it contains the name and goes+// nowhere, because a leading ">" makes it relative and the client resolves it+// against its own base. Relative destinations are let through on purpose, so a+// sweep that counted those would be demanding breaks the guard's contract+// promises not to make.+func sendsReaderTo(dests []string, host string) bool {+ for _, d := range dests {+ u, err := url.Parse(strings.TrimSpace(d))+ if err != nil || u.Host == "" {+ continue+ }+ if strings.EqualFold(u.Hostname(), host) {+ return true+ }+ }+ return false+}diff --git a/server/internal/integrations/wecom/replier.go b/server/internal/integrations/wecom/replier.goindex be32f6ab26..8f4a471203 100644--- a/server/internal/integrations/wecom/replier.go+++ b/server/internal/integrations/wecom/replier.go@@ -231,7 +231,14 @@ func issueCreatedText(res engine.Result) string {if id == "" {id = fmt.Sprintf("#%d", res.IssueNumber)}- title := strings.TrimSpace(res.IssueTitle)+ // The title is the reporter's own text and this confirmation goes back+ // into the chat that triggered it — in a group, in front of the room. An+ // issue titled "安全升级:请点击 [重置密码](https://evil.example) 完成验证"+ // otherwise comes back from the bot as a working link, with the bot's+ // authority behind it. A title carrying a line break can define one+ // instead of writing it inline, which is why the reference-definition+ // break applies here too.+ title := breakMemberLinks(strings.TrimSpace(res.IssueTitle))if title == "" {return "✅ 已创建 " + id}diff --git a/server/internal/integrations/wecom/replier_test.go b/server/internal/integrations/wecom/replier_test.goindex eeca595be5..1b09f0a0e7 100644--- a/server/internal/integrations/wecom/replier_test.go+++ b/server/internal/integrations/wecom/replier_test.go@@ -365,3 +365,57 @@ func TestPost_HonoursTheCallersDeadline(t *testing.T) {"the deadline the publishing goroutine budgeted for is not being applied")}}++// TestIssueConfirmationDoesNotRenderReporterLinks: the confirmation goes back+// into the chat that triggered the /issue — in a group, in front of the room —+// and carries the bot's authority. A title is the reporter's own text.+func TestIssueConfirmationDoesNotRenderReporterLinks(t *testing.T) {+ res := engine.Result{+ IssueIdentifier: "MUL-1",+ IssueTitle: "安全升级:请点击 [重置密码](https://evil.example) 完成验证",+ }+ got := issueCreatedText(res)+ if strings.Contains(got, "](") {+ t.Fatalf("a reporter-authored link rendered in a bot-authored group message: %q", got)+ }+ if !strings.Contains(got, "重置密码") {+ t.Errorf("the visible text was eaten: %q", got)+ }+ if strings.Contains(got, `\`) {+ t.Fatalf("a backslash reached the reply: %q — WeCom shows it raw in the list preview and reads it as a math delimiter in the bubble", got)+ }+}++// TestIssueConfirmationDefinesNoLinkReference: a title carrying a line break+// can define the link instead of writing it inline, which reaches the same+// working link with no "](" anywhere in it.+func TestIssueConfirmationDefinesNoLinkReference(t *testing.T) {+ res := engine.Result{+ IssueIdentifier: "MUL-1",+ IssueTitle: "安全升级\n\n[重置密码]: https://evil.example\n\n[重置密码]",+ }+ got := issueCreatedText(res)+ if dests := markdownDestinations(got); hasDestinationTo(dests, "evil.example") {+ t.Fatalf("a reporter-defined link resolved in a bot-authored group message: %q resolves %v", got, dests)+ }+ if !strings.Contains(got, "重置密码") {+ t.Errorf("the visible text was eaten: %q", got)+ }+}++// TestIssueConfirmationKeepsAnOrdinaryTitleVerbatim: the confirmation echoes+// what the reporter typed straight back at them in the same chat, so anything+// added to it is immediately visible as a mistake. Only a title that actually+// contains "](", or a definition with a real destination behind it, is edited+// at all — "[Bug]: 登录失败" is not.+func TestIssueConfirmationKeepsAnOrdinaryTitleVerbatim(t *testing.T) {+ for _, title := range []string{+ "[Bug] 登录失败 (P0)!",+ "[Bug]: 登录失败",+ } {+ res := engine.Result{IssueIdentifier: "MUL-1", IssueTitle: title}+ if got, want := issueCreatedText(res), "✅ 已创建 MUL-1 — "+title; got != want {+ t.Fatalf("the reporter's own title came back altered:\n got %q\nwant %q", got, want)+ }+ }+}