Documentation
¶
Overview ¶
Package svg enforces the shared SVG policy.
svg-policy.json beside this file is a byte-identical copy of core/resources/security/svg-policy.json. It is vendored because this package has no dependency on ichava/core and cannot reach it; the copy is kept honest by .scripts/sync-svg-policy.mjs, which lists it as a consumer, and pinned by digest in the tests here.
Do not hand-edit the JSON. Edit the canonical file, run the sync script with --write, and update the pinned digest.
Index ¶
- Constants
- func AttributeName(space, local string) string
- func CSSValueIsSafe(value string) bool
- func DisplayValueIsSafe(value string) bool
- func Inventory(root *Node) []string
- func MarkerValueIsSafe(value string) bool
- func SanitiseBytes(raw []byte, alsoStripClass bool) ([]byte, []string, error)
- func Serialise(root *Node) []byte
- func StrayTextCount(removed []string) int
- func StyleValueIsSafe(value string) bool
- func SummariseRemoved(removed []string) string
- type Attr
- type FragmentOnlyRefs
- type Node
- type NodeKind
- type Policy
- type PolicyViolationError
Constants ¶
const ( DefaultMaxBytes = 4_500_000 DefaultMaxNodes = 30_000 )
Default caps. Measured 2026-11-04 over every .svg under icon-sets-*/: the largest file is 1,053,328 bytes and the largest has 6,741 elements, so these are about 4.3x and 4.5x the observed maximum.
They match the browser's AppConfig.limits (svgMaxChars 4,500,000, svgMaxNodes 30,000, set in react-icon-browser#197; the browser lives in icon-browser's resources/js since 2026-11-12) and core's caps, so this tool never accepts an SVG that a consumer rejects. Change all three together.
const ( NamespaceSVG = "http://www.w3.org/2000/svg" NamespaceXLink = "http://www.w3.org/1999/xlink" )
Namespace URIs the policy cares about.
const StrayText = "#text"
StrayText is the entry the removal list carries for each non-whitespace text or CDATA run dropped from directly under <svg> or <g>.
Variables ¶
This section is empty.
Functions ¶
func AttributeName ¶
AttributeName normalises a parsed attribute back to the policy's spelling.
The policy names the xlink attribute `xlink:href`, and both parsers hand it over resolved to its namespace URI -- lxml as {http://…/xlink}href, Go as a Name with that Space. Everything else loses its namespace.
func CSSValueIsSafe ¶ added in v0.1.3
CSSValueIsSafe reports whether a CSS value (a style attribute, the text of a style element, or a presentation attribute that takes a paint, url or filter) can be kept without allowing a fetch or script.
func DisplayValueIsSafe ¶ added in v0.1.3
DisplayValueIsSafe reports whether a display attribute value is permitted: bare keywords only, and still through the CSS value guard. OpenMoji hides the construction shapes of its subdivision flags with display="none"; stripping it makes them render.
func Inventory ¶
Inventory lists every element path and attribute the document holds.
It exists for the differential against the Python: comparing serialised bytes would fail on trivia -- attribute quoting, self-closing style, whitespace -- that no consumer can observe, while this compares the only thing the policy actually decides, which is what survives.
func MarkerValueIsSafe ¶ added in v0.1.3
MarkerValueIsSafe reports whether a marker-start, marker-mid or marker-end value is permitted: none, or url(#fragment), through the CSS value guard.
func SanitiseBytes ¶
SanitiseBytes filters a document to what the policy permits.
Returns the serialised result and the names of everything removed, so a caller can report *what* was wrong rather than only that something was.
func Serialise ¶
Serialise renders the tree.
Prefixes are resolved from the namespace declarations the document itself carries, so a file written with xlink: comes back with xlink: rather than a generated prefix.
func StrayTextCount ¶ added in v0.1.3
StrayTextCount is how many stray text runs a removal list records.
func StyleValueIsSafe ¶
StyleValueIsSafe reports whether a style attribute value is permitted.
It is CSSValueIsSafe: a url() aimed off the document is the CSS exfiltration vector, and so are the functions and escapes that spell one. See css.go.
func SummariseRemoved ¶
SummariseRemoved collapses a removal list into one sorted, deduplicated line, which is what the per-file violation report shows.
Types ¶
type Attr ¶
type Attr struct {
Space, Local string
Value string
// Prefix is the source spelling, so serialisation reproduces it rather
// than inventing one.
Prefix string
// IsNamespaceDecl marks xmlns and xmlns:* .
//
// This is the difference that would have broken every icon. lxml keeps
// namespace declarations out of el.attrib entirely, so the Python filter
// never sees them and they survive serialisation untouched. Go's decoder
// hands them over as ordinary attributes -- and `xmlns` is not in
// allowedAttributes, so filtering them would strip the SVG namespace from
// every document. They are marked here and skipped by the filter.
IsNamespaceDecl bool
}
Attr is one attribute, keeping both the resolved namespace and the prefix it was written with.
type FragmentOnlyRefs ¶
type FragmentOnlyRefs struct {
Attributes []string `json:"attributes"`
Allow string `json:"allow"`
}
FragmentOnlyRefs names the attributes restricted to same-document references, and the pattern a value must match.
type Node ¶
type Node struct {
Kind NodeKind
// Element fields.
Space, Local string
Attrs []Attr
Children []*Node
// Text and Comment payload, unescaped.
Text string
}
Node is an element, text or comment.
func Parse ¶
Parse reads a document and returns its root element.
Go's encoding/xml never resolves external entities and never fetches a DTD, so XXE and billion-laughs are closed by construction rather than by configuration -- the flags lxml needs (resolve_entities=False, no_network=True, huge_tree=False) have no Go equivalent because there is nothing to switch off.
An unparseable document is an error, not a recovery. That is deliberate and differs from the runtime parser in ichava/core, which recovers from six common author mistakes: this gate runs before a file is committed, where the right answer to malformed input is to say so rather than guess.
type Policy ¶
type Policy struct {
AllowedTags []string `json:"allowedTags"`
AllowedAttributes []string `json:"allowedAttributes"`
AllowedAttributePrefix []string `json:"allowedAttributePrefixes"`
DenyAttributePrefixes []string `json:"denyAttributePrefixes"`
ForbiddenTags []string `json:"forbiddenTags"`
FragmentOnlyRefs FragmentOnlyRefs `json:"fragmentOnlyRefs"`
StripComments bool `json:"stripComments"`
StripDoctype bool `json:"stripDoctype"`
StripEntities bool `json:"stripEntities"`
BlockImageNonFragment bool `json:"blockImageNonFragmentHref"`
BlockAnchorNonFragment bool `json:"blockAnchorNonFragmentHref"`
BlockCDATAScript bool `json:"blockCdataScript"`
Version int `json:"version"`
// StyleAttribute is NOT a boolean in the policy -- it is an object
// describing what a style value may contain. Python reads it with a
// truthiness test, so any non-empty object enables the `style` name.
//
// Typing this as `bool` is a live trap, not a tidy-up: the unmarshal fails,
// the whole policy fails to load, and if that failure were swallowed the
// merge below would drop `style` -- the sole paint source for over half
// of one pack's icons. Kept raw, and truthiness asked explicitly.
StyleAttribute json.RawMessage `json:"styleAttribute"`
// AllowedValues is a list of illustrative value shapes, not a map and not
// enforced by any of the four readers. Kept raw so the field round-trips
// without this package pretending to a structure it does not use.
AllowedValues json.RawMessage `json:"allowedValues"`
// MaxBytes and MaxNodes bound a document before and while it is parsed, so
// one hostile or corrupt file cannot cost unbounded time and memory. Not
// part of the shared policy JSON (the other runtimes carry their own caps);
// zero means "use the default". MaxNodes counts elements.
MaxBytes int `json:"-"`
MaxNodes int `json:"-"`
// contains filtered or unexported fields
}
Policy is the parsed policy document.
func Load ¶
Load returns the parsed policy.
Deliberately not forgiving. A policy that silently fell back to an empty document would strip every element from every icon, and one that fell back to a permissive default would be a security hole; both look like a working install until something renders.
func (*Policy) AttributeAllowed ¶
AttributeAllowed reports whether an attribute survives, by name then value.
Order matters and is the design. The deny prefix wins over everything, then the ARIA-style allow prefixes, then the name list, and only then the value checks. Being on the name list never means the value is trusted -- collapsing that distinction is how a sanitiser ends up permitting href="javascript:alert(1)" because `href` was "allowed".
func (*Policy) Sanitise ¶ added in v0.1.3
Sanitise is SanitiseBytes against this policy, honouring its MaxBytes and MaxNodes. A document over either cap is an error, like an unparseable one.
func (*Policy) TagAllowed ¶
TagAllowed reports whether an element may appear.
type PolicyViolationError ¶
type PolicyViolationError struct{ Violations []string }
PolicyViolationError reports a document that broke the policy, for strict mode.
func (*PolicyViolationError) Error ¶
func (e *PolicyViolationError) Error() string