docsite: allowlist inlined SVGs; refuse unclosed fences
Final review of docs site Plan 2 (Astra): the SVG blocklist let encoded and unusual active content through (svg/onload, javascript:, iframe, style), and an unclosed fence passed the Go gate but broke the website build. An inlined SVG is now checked against allowed elements and attributes, with quoted values, links and url() only to local #ids, and no DOCTYPE or entities beyond the basic five. UnclosedFence catches a fence that is never closed, in CheckDiagrams and across the corpus.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2 files changed,
+160
−5
internal/docsite/diagrams.go+99 −5internal/docsite/diagrams_test.go+61 −0
CI passed — run details
Intent
Attributed to this commit: 21.3 g CO₂e (2,692,420 tokens). This is an attribution, not a measurement — usage counted from this commit's own marker forward to the next one on design-docs-site, never backward from it. A turn that produced more than one commit books all of its tokens to the last one, and a concurrent session on this branch can add to the same figure. Some of it was priced using the shared default rate, because no model-specific factor row exists yet for at least one model involved. The Carbon view has the repo total, which is never derived from this attribution.
diff --git a/internal/docsite/diagrams.go b/internal/docsite/diagrams.go| index 365f9553f..cea247007 100644 |
| --- a/internal/docsite/diagrams.go |
| +++ b/internal/docsite/diagrams.go |
| @@ -47,9 +47,100 @@ type Diagram struct { |
| var diagramFile = regexp.MustCompile(`^[a-z0-9][a-z0-9-]*\.svg$`) |
| -// activeSVG matches what an inlined SVG must never carry: script, event |
| -// handlers, javascript: URLs and foreign HTML. |
| -var activeSVG = regexp.MustCompile(`(?i)<script|\son[a-z]+\s*=|javascript:|<foreignobject`) |
| +// An inlined SVG is checked against an allowlist, not a blocklist (Astra's |
| +// final review found encoded and unusual forms a blocklist missed). The |
| +// website's hack/docs-markdown.mjs applies the same rules. |
| +var ( |
| + svgProlog = regexp.MustCompile(`^\s*<\?xml[^>]*\?>`) |
| + svgComment = regexp.MustCompile(`(?s)<!--.*?-->`) |
| + svgTag = regexp.MustCompile(`<(/?)([^\s/>]+)([^>]*)>`) |
| + svgAttrs = regexp.MustCompile(`^(\s+[A-Za-z_:][\w:.-]*\s*=\s*("[^"]*"|'[^']*'))*\s*/?\s*$`) |
| + svgAttr = regexp.MustCompile(`([A-Za-z_:][\w:.-]*)\s*=\s*("[^"]*"|'[^']*')`) |
| + svgEntity = regexp.MustCompile(`&(?:amp|lt|gt|quot|apos);`) |
| + svgLocalRef = regexp.MustCompile(`^#[A-Za-z_][\w-]*$`) |
| + svgURL = regexp.MustCompile(`url\(`) |
| + svgLocalURLs = regexp.MustCompile(`^(?:[^u]|u[^r]|ur[^l]|url[^(]|url\(#[A-Za-z_][\w-]*\))*$`) |
| +) |
| + |
| +var svgElements = setOf("svg", "g", "defs", "title", "desc", "rect", "circle", "ellipse", "line", "polyline", "polygon", "path", "text", "tspan", "marker", "use", "linearGradient", "radialGradient", "stop", "clipPath", "symbol") |
| + |
| +var svgAttributes = setOf("id", "class", "viewBox", "width", "height", "x", "y", "x1", "y1", "x2", "y2", "cx", "cy", "r", "rx", "ry", "dx", "dy", "d", "points", "transform", |
| + "fill", "fill-opacity", "stroke", "stroke-width", "stroke-dasharray", "stroke-linecap", "stroke-linejoin", "stroke-opacity", "opacity", |
| + "font-size", "font-weight", "font-family", "letter-spacing", "text-anchor", "dominant-baseline", |
| + "role", "aria-label", "aria-labelledby", "aria-hidden", "focusable", "xmlns", "xmlns:xlink", "version", "preserveAspectRatio", |
| + "marker-start", "marker-mid", "marker-end", "markerWidth", "markerHeight", "markerUnits", "refX", "refY", "orient", |
| + "offset", "stop-color", "stop-opacity", "gradientUnits", "clip-path", "clipPathUnits", "href", "xlink:href") |
| + |
| +func setOf(names ...string) map[string]bool { |
| + m := make(map[string]bool, len(names)) |
| + for _, n := range names { |
| + m[n] = true |
| + } |
| + return m |
| +} |
| + |
| +// svgProblem returns why an SVG may not be inlined, or "" if it may. |
| +func svgProblem(svg string) string { |
| + body := svgComment.ReplaceAllString(svgProlog.ReplaceAllString(svg, ""), "") |
| + if strings.Contains(body, "<!") { |
| + return "carries a DOCTYPE, CDATA or entity declaration" |
| + } |
| + if amps := strings.Count(body, "&"); amps != len(svgEntity.FindAllString(body, -1)) { |
| + return "carries a character reference other than & < > " '" |
| + } |
| + tags := svgTag.FindAllStringSubmatch(body, -1) |
| + if strings.Count(body, "<") != len(tags) { |
| + return "carries a < that does not open a tag" |
| + } |
| + for _, m := range tags { |
| + name, attrs := m[2], m[3] |
| + if !svgElements[name] { |
| + return fmt.Sprintf("carries a <%s> element, which is not on the allowed list", name) |
| + } |
| + if m[1] == "/" { |
| + if strings.TrimSpace(attrs) != "" { |
| + return fmt.Sprintf("carries a malformed </%s>", name) |
| + } |
| + continue |
| + } |
| + if !svgAttrs.MatchString(attrs) { |
| + return fmt.Sprintf("carries an unquoted or malformed attribute on <%s>", name) |
| + } |
| + for _, a := range svgAttr.FindAllStringSubmatch(attrs, -1) { |
| + key, val := a[1], a[2][1:len(a[2])-1] |
| + if !svgAttributes[key] { |
| + return fmt.Sprintf("carries a %s attribute, which is not on the allowed list", key) |
| + } |
| + if (key == "href" || key == "xlink:href") && !svgLocalRef.MatchString(val) { |
| + return fmt.Sprintf("carries %s=%q; only links to #ids in the same SVG are allowed", key, val) |
| + } |
| + if svgURL.MatchString(val) && !svgLocalURLs.MatchString(val) { |
| + return fmt.Sprintf("carries %s=%q; url() may only point to #ids in the same SVG", key, val) |
| + } |
| + } |
| + } |
| + return "" |
| +} |
| + |
| +// UnclosedFence reports the 1-based line of a fence that is opened and |
| +// never closed. Markdown renders such a fence to the end of the page, |
| +// swallowing everything after it, and the page parser records only |
| +// closed fences, so the other gates would never see it. |
| +func UnclosedFence(body string) (int, bool) { |
| + open, mark := 0, "" |
| + for i, line := range strings.Split(body, "\n") { |
| + m, _, ok := fenceDelim(strings.TrimSpace(line)) |
| + if !ok { |
| + continue |
| + } |
| + if open == 0 { |
| + open, mark = i+1, m |
| + } else if sameFence(m, mark) { |
| + open, mark = 0, "" |
| + } |
| + } |
| + return open, open != 0 |
| +} |
| // ParseDiagramFence parses the body of a diagram or stepper fence. |
| func ParseDiagramFence(kind, body string) (Diagram, error) { |
| @@ -134,6 +225,9 @@ func CheckDiagrams(site *Site, dir string) []string { |
| var problems []string |
| checked := map[string]string{} |
| for _, p := range site.Pages() { |
| + if line, ok := UnclosedFence(p.Body); ok { |
| + problems = append(problems, fmt.Sprintf("%s:%d: a fence is never closed, so the rest of the page renders as code", p.Slug, line)) |
| + } |
| for _, f := range p.Fences { |
| if f.Lang != "diagram" && f.Lang != "stepper" { |
| continue |
| @@ -164,8 +258,8 @@ func checkSVG(path string) string { |
| if err != nil { |
| return "does not exist in docs/site/diagrams" |
| } |
| - if m := activeSVG.Find(raw); m != nil { |
| - return fmt.Sprintf("carries %q, and an inlined SVG must hold no script, event handlers, javascript: links or foreign HTML", strings.TrimSpace(string(m))) |
| + if why := svgProblem(string(raw)); why != "" { |
| + return why + " (an inlined SVG may hold only drawing elements and attributes)" |
| } |
| return "" |
| } |
diff --git a/internal/docsite/diagrams_test.go b/internal/docsite/diagrams_test.go| index aa2f93bbc..64b64bb25 100644 |
| --- a/internal/docsite/diagrams_test.go |
| +++ b/internal/docsite/diagrams_test.go |
| @@ -76,6 +76,17 @@ func TestCheckDiagramsRefusesActiveSVG(t *testing.T) { |
| "onclick": `<svg><rect OnClick="x()"/></svg>`, |
| "javascript": `<svg><a href="javascript:alert(1)"><text>x</text></a></svg>`, |
| "foreign": `<svg><foreignObject><div>x</div></foreignObject></svg>`, |
| + // Astra's final review: a blocklist missed these. |
| + "slash onload": `<svg/onload=alert(1)></svg>`, |
| + "encoded js href": `<svg><a href="javascript:alert(1)"><text>x</text></a></svg>`, |
| + "xlink js": `<svg xmlns:xlink="http://www.w3.org/1999/xlink"><use xlink:href="javascript:x"/></svg>`, |
| + "iframe": `<svg></svg><iframe srcdoc="<script>alert(1)</script>"></iframe>`, |
| + "style element": `<svg><style>body { display: none }</style></svg>`, |
| + "style attribute": `<svg><rect style="display:none"/></svg>`, |
| + "external use": `<svg><use href="https://example.com/x.svg#a"/></svg>`, |
| + "data uri": `<svg><image href="data:image/svg+xml;base64,PHN2Zz4="/></svg>`, |
| + "doctype entity": `<!DOCTYPE svg [<!ENTITY x "y">]><svg>&x;</svg>`, |
| + "unquoted attr": `<svg><rect width=10 /></svg>`, |
| } { |
| dir := t.TempDir() |
| if err := os.WriteFile(filepath.Join(dir, "bad.svg"), []byte(svg), 0o644); err != nil { |
| @@ -98,3 +109,53 @@ func TestCheckDiagramsOnTheRealCorpus(t *testing.T) { |
| t.Error(p) |
| } |
| } |
| + |
| +func TestCheckDiagramsAcceptsAPlainSVG(t *testing.T) { |
| + dir := t.TempDir() |
| + svg := `<?xml version="1.0" encoding="UTF-8"?> |
| +<!-- a comment is fine --> |
| +<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 40" role="img" aria-labelledby="t"> |
| + <title id="t">Console & boxes</title> |
| + <defs><marker id="arrow" viewBox="0 0 10 10" refX="5" refY="5" markerWidth="6" markerHeight="6" orient="auto"><path d="M0 0 L10 5 L0 10 z"/></marker></defs> |
| + <g class="parts"> |
| + <rect class="shape on" x="1" y="1" width="40" height="20" rx="4"/> |
| + <circle cx="70" cy="10" r="5" class="shape"/> |
| + <line class="line" x1="41" y1="11" x2="65" y2="11" marker-end="url(#arrow)"/> |
| + <text x="5" y="15" class="small" text-anchor="start">edge <tspan class="on">on</tspan></text> |
| + <use href="#arrow"/> |
| + </g> |
| +</svg>` |
| + if err := os.WriteFile(filepath.Join(dir, "plain.svg"), []byte(svg), 0o644); err != nil { |
| + t.Fatal(err) |
| + } |
| + site := diagramSite(t, "# Guide\n\n```diagram\nfile: plain.svg\nCaption.\n```\n") |
| + if problems := CheckDiagrams(site, dir); len(problems) != 0 { |
| + t.Errorf("a plain SVG was refused: %q", problems) |
| + } |
| +} |
| + |
| +func TestUnclosedFenceIsCaught(t *testing.T) { |
| + if line, ok := UnclosedFence("# Guide\n\n```stepper\ntitle: T\nframe: a.svg\nOne.\n"); !ok || line != 3 { |
| + t.Errorf("UnclosedFence = %d, %v; want 3, true", line, ok) |
| + } |
| + if _, ok := UnclosedFence("# Guide\n\n```sh\nx\n```\n"); ok { |
| + t.Error("a closed fence was reported") |
| + } |
| + site := diagramSite(t, "# Guide\n\n```stepper\ntitle: T\nframe: a.svg\nOnly one.\n") |
| + problems := CheckDiagrams(site, t.TempDir()) |
| + if len(problems) != 1 || !strings.Contains(problems[0], "guide:3") || !strings.Contains(problems[0], "never closed") { |
| + t.Errorf("problems = %q, want one naming guide:3 and an unclosed fence", problems) |
| + } |
| +} |
| + |
| +func TestEveryFenceInTheCorpusIsClosed(t *testing.T) { |
| + site, err := Load(root) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, p := range site.Pages() { |
| + if line, ok := UnclosedFence(p.Body); ok { |
| + t.Errorf("%s:%d: a fence is never closed, so the rest of the page renders as code", p.Slug, line) |
| + } |
| + } |
| +} |