svg

package
v0.1.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 26, 2026 License: MIT Imports: 11 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

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

View Source
const (
	NamespaceSVG   = "http://www.w3.org/2000/svg"
	NamespaceXLink = "http://www.w3.org/1999/xlink"
)

Namespace URIs the policy cares about.

Variables

This section is empty.

Functions

func AttributeName

func AttributeName(space, local string) string

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 Inventory

func Inventory(root *Node) []string

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 SanitiseBytes

func SanitiseBytes(raw []byte, alsoStripClass bool) ([]byte, []string, error)

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

func Serialise(root *Node) []byte

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 StyleValueIsSafe

func StyleValueIsSafe(value string) bool

StyleValueIsSafe reports whether a style attribute value is permitted.

A url() aimed off the document is the CSS exfiltration vector, so every one in the value has to target a same-document fragment.

func SummariseRemoved

func SummariseRemoved(removed []string) string

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.

func (Attr) Name

func (a Attr) Name() string

Name is the policy's spelling of the attribute.

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

func Parse(raw []byte, stripComments bool) (*Node, error)

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 NodeKind

type NodeKind int

NodeKind distinguishes the three node types this package keeps.

const (
	ElementNode NodeKind = iota
	TextNode
	CommentNode
)

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"`
	// contains filtered or unexported fields
}

Policy is the parsed policy document.

func Load

func Load() (*Policy, error)

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 MustLoad

func MustLoad() *Policy

MustLoad is Load for callers with nowhere to put an error.

func (*Policy) AttributeAllowed

func (p *Policy) AttributeAllowed(name, value string, alsoStripClass bool) bool

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) TagAllowed

func (p *Policy) TagAllowed(name string) bool

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

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL