feat(journal): add EmbedRegistry, YAML boot config, and pair-aware sanitizer
This commit is contained in:
@@ -22,18 +22,19 @@ var (
|
||||
goldmark.WithExtensions(extension.Footnote, extension.Table),
|
||||
goldmark.WithParserOptions(parser.WithAttribute()),
|
||||
// Winter's Markdown::parse passes raw HTML through, so imported HTML
|
||||
// bodies round-trip (D-03, PHP parity); htmlPolicy then sanitizes the
|
||||
// rendered result on every write path.
|
||||
// bodies round-trip (D-03, PHP parity); the registry HTML policy then
|
||||
// sanitizes the rendered result on every write path.
|
||||
goldmark.WithRendererOptions(html.WithUnsafe()),
|
||||
)
|
||||
|
||||
// htmlPolicy is the allow-list for stored journal HTML.
|
||||
htmlPolicy = newHTMLPolicy()
|
||||
// htmlPolicy is the default youtube-only bluemonday policy.
|
||||
htmlPolicy = defaultEmbedRegistry.Policy()
|
||||
)
|
||||
|
||||
// newHTMLPolicy extends bluemonday's UGC policy only with what goldmark
|
||||
// renders and what the imported posts and categories use.
|
||||
func newHTMLPolicy() *bluemonday.Policy {
|
||||
// newHTMLPolicyFor extends bluemonday's UGC policy only with what goldmark
|
||||
// renders, what imported posts and categories use, and the registered embed
|
||||
// providers.
|
||||
func newHTMLPolicyFor(providers []compiledEmbedProvider) *bluemonday.Policy {
|
||||
p := bluemonday.UGCPolicy()
|
||||
// Winter neither adds nor requires rel="nofollow", so links keep their
|
||||
// stored form.
|
||||
@@ -54,14 +55,22 @@ func newHTMLPolicy() *bluemonday.Policy {
|
||||
p.AllowAttrs("dir").Matching(regexp.MustCompile(`(?i)^(ltr|rtl|auto)$`)).Globally()
|
||||
p.AllowAttrs("data-message-author-role", "data-message-id").
|
||||
Matching(regexp.MustCompile(`^[A-Za-z0-9_-]+$`)).OnElements("div")
|
||||
// Blog Editor output (Phase 16.2 D-05), exactly what the editor writes
|
||||
// and nothing more; plan 02's editor-corpus.json pins it
|
||||
// (TestEditorOutputPassesPolicy) and the site layer mirrors these rules.
|
||||
// The embed placeholder <figure data-embed="youtube" data-id="..."></figure>:
|
||||
// the provider name and the 11-character video id, on figure only. The
|
||||
// layer expands it; no iframe is ever stored.
|
||||
p.AllowAttrs("data-embed").Matching(regexp.MustCompile(`^youtube$`)).OnElements("figure")
|
||||
p.AllowAttrs("data-id").Matching(regexp.MustCompile(`^[A-Za-z0-9_-]{11}$`)).OnElements("figure")
|
||||
// Embed placeholders: <figure data-embed="<provider>" data-id="<id>">.
|
||||
// bluemonday validates each attribute independently against the union of
|
||||
// registered providers and id patterns; enforceEmbedPairs then verifies
|
||||
// that each figure's data-id matches its own data-embed provider's pattern.
|
||||
if len(providers) > 0 {
|
||||
keys := make([]string, len(providers))
|
||||
pats := make([]string, len(providers))
|
||||
for i, cp := range providers {
|
||||
keys[i] = regexp.QuoteMeta(cp.provider.Key)
|
||||
pats[i] = "(?:" + cp.provider.IDPattern + ")"
|
||||
}
|
||||
p.AllowAttrs("data-embed").Matching(regexp.MustCompile("^(?:" + strings.Join(keys, "|") + ")$")).OnElements("figure")
|
||||
p.AllowAttrs("data-id").Matching(regexp.MustCompile("^(?:" + strings.Join(pats, "|") + ")$")).OnElements("figure")
|
||||
p.AllowAttrs("data-aspect").Matching(embedAspectPattern).OnElements("figure")
|
||||
p.AllowAttrs("data-height").Matching(embedHeightPattern).OnElements("figure")
|
||||
}
|
||||
// The editor's alt field takes free text, which UGC's Paragraph pattern
|
||||
// cuts at ':', '?', '"' and more. bluemonday accepts an attribute when
|
||||
// any of its rules matches and escapes the value on output; alt carries
|
||||
@@ -78,30 +87,31 @@ func newHTMLPolicy() *bluemonday.Policy {
|
||||
}
|
||||
|
||||
// FormatHTML converts journal post markdown to stored HTML using goldmark
|
||||
// footnote, table, and attribute extensions. Raw HTML in the source passes
|
||||
// through the renderer, as it does in Winter's Markdown::parse. The result is
|
||||
// then sanitized with a bluemonday allow-list that strips, as Winter's
|
||||
// Html::clean does, what it does not allow: script, style, iframe, object,
|
||||
// embed, form, base and meta elements, event handler attributes, and URLs
|
||||
// other than http, https, mailto and relative ones. HTML that the policy
|
||||
// keeps whole is returned byte for byte, so imported bodies round-trip. It
|
||||
// does not call cabana.RenderMarkdown, whose admin preview stays without
|
||||
// unsafe HTML.
|
||||
// footnote, table, and attribute extensions and the default embed registry.
|
||||
func FormatHTML(src string) (string, error) {
|
||||
return defaultEmbedRegistry.FormatHTML(src)
|
||||
}
|
||||
|
||||
// FormatHTML converts journal post markdown to stored HTML using goldmark
|
||||
// footnote, table, and attribute extensions, then sanitizes the result with
|
||||
// r's policy and pair-aware embed validation.
|
||||
func (r *EmbedRegistry) FormatHTML(src string) (string, error) {
|
||||
var buf bytes.Buffer
|
||||
if err := markdownEngine.Convert([]byte(strings.TrimSpace(src)), &buf); err != nil {
|
||||
return "", fmt.Errorf("journal: markdown: %w", err)
|
||||
}
|
||||
return SanitizeHTML(buf.String()), nil
|
||||
return r.SanitizeHTML(buf.String()), nil
|
||||
}
|
||||
|
||||
// SanitizeHTML filters doc, which is HTML and not markdown, through the
|
||||
// FormatHTML allow-list and strips what the policy does not allow. HTML the
|
||||
// policy keeps whole is returned byte for byte. It is the gate for
|
||||
// content_html supplied without markdown, such as a translation that carries
|
||||
// only content_html. It is the string half of SanitizeHTMLReport.
|
||||
// SanitizeHTML filters doc through the default embed registry allow-list.
|
||||
func SanitizeHTML(doc string) string {
|
||||
out, _ := SanitizeHTMLReport(doc)
|
||||
return defaultEmbedRegistry.SanitizeHTML(doc)
|
||||
}
|
||||
|
||||
// SanitizeHTML filters doc, which is HTML and not markdown, through r's
|
||||
// allow-list and strips what the policy does not allow.
|
||||
func (r *EmbedRegistry) SanitizeHTML(doc string) string {
|
||||
out, _ := r.SanitizeHTMLReport(doc)
|
||||
return out
|
||||
}
|
||||
|
||||
@@ -156,17 +166,23 @@ func addRemovalName(names []string, cut bool, name string) ([]string, bool) {
|
||||
return append(names, name), cut
|
||||
}
|
||||
|
||||
// SanitizeHTMLReport is SanitizeHTML with a report of what the policy
|
||||
// removed. HTML the policy keeps whole is returned byte for byte with an
|
||||
// empty report. Otherwise the policy's output is returned and the report is
|
||||
// built by aligning the start tags of doc with those of the output in order
|
||||
// (the policy only removes, it never adds or reorders): an input tag without
|
||||
// a counterpart is a removed element, and an attribute of a matched tag that
|
||||
// the output lacks or holds with another value is a removed attribute.
|
||||
// Comments are counted on their own. The report is empty exactly when the
|
||||
// returned string equals doc.
|
||||
// SanitizeHTMLReport is SanitizeHTML with a report of what the default policy
|
||||
// removed.
|
||||
func SanitizeHTMLReport(doc string) (string, HTMLRemovals) {
|
||||
clean, changed := sanitizeHTML(doc)
|
||||
return defaultEmbedRegistry.SanitizeHTMLReport(doc)
|
||||
}
|
||||
|
||||
// SanitizeHTMLReport is SanitizeHTML with a report of what r's policy removed.
|
||||
// HTML the policy keeps whole is returned byte for byte with an empty report.
|
||||
// Otherwise the policy's output is returned and the report is built by
|
||||
// aligning the start tags of doc with those of the output in order (the policy
|
||||
// only removes, it never adds or reorders): an input tag without a counterpart
|
||||
// is a removed element, and an attribute of a matched tag that the output
|
||||
// lacks or holds with another value is a removed attribute. Comments are
|
||||
// counted on their own. The report is empty exactly when the returned string
|
||||
// equals doc.
|
||||
func (r *EmbedRegistry) SanitizeHTMLReport(doc string) (string, HTMLRemovals) {
|
||||
clean, changed := r.sanitizeHTML(doc)
|
||||
if !changed || clean == doc {
|
||||
return doc, HTMLRemovals{}
|
||||
}
|
||||
@@ -293,20 +309,26 @@ func alignTags(in, out []reportTag, same func(in, out reportTag) bool) []int {
|
||||
return match
|
||||
}
|
||||
|
||||
// FormatTranslation sets attrs["content_html"] for one locale's translated
|
||||
// post attributes using the default embed registry.
|
||||
func FormatTranslation(attrs map[string]any) error {
|
||||
return defaultEmbedRegistry.FormatTranslation(attrs)
|
||||
}
|
||||
|
||||
// FormatTranslation sets attrs["content_html"] for one locale's translated
|
||||
// post attributes, so a translated content_html is stored under the same
|
||||
// policy as the host column. When attrs["content"] is not blank, content_html
|
||||
// is rendered from it with FormatHTML and a supplied content_html is
|
||||
// is rendered from it with r.FormatHTML and a supplied content_html is
|
||||
// replaced, as the host column is always derived from content. Otherwise a
|
||||
// supplied, non-null content_html is sanitized with SanitizeHTML; a value
|
||||
// supplied, non-null content_html is sanitized with r.SanitizeHTML; a value
|
||||
// that is not a string is sanitized as its text form. attrs without content
|
||||
// or content_html is left unchanged.
|
||||
func FormatTranslation(attrs map[string]any) error {
|
||||
func (r *EmbedRegistry) FormatTranslation(attrs map[string]any) error {
|
||||
if attrs == nil {
|
||||
return nil
|
||||
}
|
||||
if content := textOf(attrs["content"]); strings.TrimSpace(content) != "" {
|
||||
html, err := FormatHTML(content)
|
||||
html, err := r.FormatHTML(content)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -314,7 +336,7 @@ func FormatTranslation(attrs map[string]any) error {
|
||||
return nil
|
||||
}
|
||||
if v, has := attrs["content_html"]; has && v != nil {
|
||||
attrs["content_html"] = SanitizeHTML(textOf(v))
|
||||
attrs["content_html"] = r.SanitizeHTML(textOf(v))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -330,33 +352,127 @@ func textOf(v any) string {
|
||||
}
|
||||
}
|
||||
|
||||
// CheckHTML reports whether the FormatHTML allow-list would remove or
|
||||
// change any element, attribute or text in doc: it returns an error when it
|
||||
// would, nil when the policy keeps doc whole. Since Phase 16.2 no admin or
|
||||
// API write path refuses with it (admin saves strip and report through
|
||||
// SanitizeHTMLReport, D-10 amended); it is the predicate counterpart of the
|
||||
// site layer's isSafeJournalHtml, and the policy cross-check tests use it.
|
||||
// CheckHTML reports whether the default FormatHTML allow-list would remove or
|
||||
// change any element, attribute or text in doc.
|
||||
func CheckHTML(doc string) error {
|
||||
if _, changed := sanitizeHTML(doc); changed {
|
||||
return defaultEmbedRegistry.CheckHTML(doc)
|
||||
}
|
||||
|
||||
// CheckHTML reports whether r's allow-list would remove or change any element,
|
||||
// attribute or text in doc: it returns an error when it would, nil when the
|
||||
// policy keeps doc whole.
|
||||
func (r *EmbedRegistry) CheckHTML(doc string) error {
|
||||
if _, changed := r.sanitizeHTML(doc); changed {
|
||||
return errors.New("journal: HTML contains elements, attributes or URLs that are not allowed")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// sanitizeHTML returns doc unchanged when htmlPolicy keeps all of it, and the
|
||||
// policy's output with changed set otherwise. Keeping all of it means doc and
|
||||
// the policy output tokenize to the same HTML tokens, so an output that only
|
||||
// re-escapes text or attribute values is not a change. A tag that repeats an
|
||||
// attribute is always a change: the tokenizer keeps only the first of them,
|
||||
// so the comparison would not see the others in the stored bytes.
|
||||
func sanitizeHTML(doc string) (string, bool) {
|
||||
clean := htmlPolicy.Sanitize(doc)
|
||||
// sanitizeHTML returns doc unchanged when r's policy and pair-aware embed
|
||||
// validation keep all of it, and the cleaned output with changed set otherwise.
|
||||
func (r *EmbedRegistry) sanitizeHTML(doc string) (string, bool) {
|
||||
if r == nil {
|
||||
r = defaultEmbedRegistry
|
||||
}
|
||||
clean := r.Policy().Sanitize(doc)
|
||||
clean = enforceEmbedPairs(clean, r)
|
||||
if sameTokens(doc, clean) {
|
||||
return doc, false
|
||||
}
|
||||
return clean, true
|
||||
}
|
||||
|
||||
// enforceEmbedPairs verifies that every <figure> carrying embed attributes
|
||||
// has a valid (data-embed, data-id) pair matching that provider's compiled
|
||||
// pattern on reg. When mismatched or incomplete (or when data-aspect /
|
||||
// data-height appear without a valid embed pair), those embed attributes are
|
||||
// stripped from the <figure> start tag while all other attributes and children
|
||||
// remain intact.
|
||||
func enforceEmbedPairs(doc string, reg *EmbedRegistry) string {
|
||||
if !strings.Contains(doc, "<figure") {
|
||||
return doc
|
||||
}
|
||||
var (
|
||||
buf bytes.Buffer
|
||||
modified bool
|
||||
)
|
||||
z := xhtml.NewTokenizer(strings.NewReader(doc))
|
||||
for {
|
||||
tt := z.Next()
|
||||
if tt == xhtml.ErrorToken {
|
||||
break
|
||||
}
|
||||
raw := z.Raw()
|
||||
if tt != xhtml.StartTagToken && tt != xhtml.SelfClosingTagToken {
|
||||
buf.Write(raw)
|
||||
continue
|
||||
}
|
||||
if !isFigureTag(raw) {
|
||||
buf.Write(raw)
|
||||
continue
|
||||
}
|
||||
tok := z.Token()
|
||||
var (
|
||||
embedVal, idVal string
|
||||
hasEmbed, hasID bool
|
||||
hasEmbedAttr bool
|
||||
)
|
||||
for _, a := range tok.Attr {
|
||||
if a.Namespace != "" {
|
||||
continue
|
||||
}
|
||||
switch a.Key {
|
||||
case "data-embed":
|
||||
hasEmbed = true
|
||||
hasEmbedAttr = true
|
||||
embedVal = a.Val
|
||||
case "data-id":
|
||||
hasID = true
|
||||
hasEmbedAttr = true
|
||||
idVal = a.Val
|
||||
case "data-aspect", "data-height":
|
||||
hasEmbedAttr = true
|
||||
}
|
||||
}
|
||||
if !hasEmbedAttr || (hasEmbed && hasID && reg.Match(embedVal, idVal)) {
|
||||
buf.Write(raw)
|
||||
continue
|
||||
}
|
||||
filtered := make([]xhtml.Attribute, 0, len(tok.Attr))
|
||||
for _, a := range tok.Attr {
|
||||
if a.Namespace == "" && (a.Key == "data-embed" || a.Key == "data-id" || a.Key == "data-aspect" || a.Key == "data-height") {
|
||||
continue
|
||||
}
|
||||
filtered = append(filtered, a)
|
||||
}
|
||||
tok.Attr = filtered
|
||||
modified = true
|
||||
buf.WriteString(tok.String())
|
||||
}
|
||||
if !modified {
|
||||
return doc
|
||||
}
|
||||
return buf.String()
|
||||
}
|
||||
|
||||
func isFigureTag(raw []byte) bool {
|
||||
const prefix = "<figure"
|
||||
if len(raw) < len(prefix)+1 {
|
||||
return false
|
||||
}
|
||||
for i := 0; i < len(prefix); i++ {
|
||||
c := raw[i]
|
||||
if 'A' <= c && c <= 'Z' {
|
||||
c += 'a' - 'A'
|
||||
}
|
||||
if c != prefix[i] {
|
||||
return false
|
||||
}
|
||||
}
|
||||
next := raw[len(prefix)]
|
||||
return next == '>' || next == '/' || isHTMLSpace(next)
|
||||
}
|
||||
|
||||
// sameTokens reports whether a and b tokenize to the same sequence of HTML
|
||||
// tokens: type, tag name or decoded text, and the set of decoded attributes.
|
||||
// It is false when either repeats an attribute in a tag.
|
||||
|
||||
Reference in New Issue
Block a user