Moved to
github.com/cplieger/go/xmlx. Archived 2026-11-07. This repository is read-only. The published Go module stays available.
xmlx caps the memory and work an untrusted XML document can cost your Go program, before and during an encoding/xml decode.
A byte cap on the response body does not bound the decode, because encoding/xml builds each token before your code can check it. xmlx adds those bounds and keeps your decoder. It uses only the standard library, needs Go 1.27 or later, is a stable v1 module under semantic versioning and is licensed under Apache-2.0.
xmlx is built for Go code that decodes XML it did not write, such as an RSS or Atom feed or a third-party API reply.
Preflightscans the raw bytes once, with no allocation, and refuses an oversized text run or tag, too many attributes, elements or nesting levels, and any XML directive such as a DOCTYPE.- A
Budgetcaps each decoded value and the document's total decoded text while the value is still being read. - Every rejection wraps one sentinel,
ErrLimit, and names the bound. APreflightrejection also gives the byte offset. No rejection quotes the document. - A bound of zero or less is a configuration error, so no setting silently means unbounded.
Consider mattermost/xml-roundtrip-validator if your security depends on the document's shape, such as XML signature validation or SAML. It rejects input that does not survive an encoding/xml round trip, and it pairs with Preflight.
go get github.com/cplieger/xmlx@latestRun Preflight on the body before the decoder sees it:
if err := xmlx.Preflight(body, xmlx.DefaultLimits()); err != nil {
return err // a *xmlx.LimitError naming the bound and the byte offset
}
var doc feed
if err := xml.Unmarshal(body, &doc); err != nil {
return err
}With plain xml.Unmarshal, Preflight is the whole gate. A Budget works where you read tokens yourself, in a hand-written decoder or an UnmarshalXML method. Create one Budget per document and read each text field through it. DecodeText replaces d.DecodeElement(&s, &start) and refuses the value as soon as it grows past either cap:
budget, err := xmlx.NewBudget(4<<10, 4<<20) // per value, per document
if err != nil {
return err
}
d := xml.NewDecoder(bytes.NewReader(body))
var title, guid string
for {
tok, err := d.Token()
if err == io.EOF {
break
}
if err != nil {
return err
}
start, ok := tok.(xml.StartElement)
if !ok {
continue
}
switch start.Name.Local {
case "title":
title, err = budget.DecodeText(d)
case "guid":
guid, err = budget.DecodeText(d)
}
if err != nil {
return err
}
}
fmt.Println(title, guid, budget.Total())For a value the decoder has already handed you whole, such as an attribute value, call budget.Charge(a.Value) before you store it. In custom UnmarshalXML methods, give every element's decoder the same *Budget, and use d.Skip() for children you do not model. A value from DecodeText is already charged, so charge each value once. After any error from DecodeText, abandon the document. How xmlx bounds a document has the detail.
To add the gate to a working integration, log the Preflight error and decode anyway until your bounds are proven, so a mis-sized bound shows up in your logs instead of breaking the feed.
The package examples on pkg.go.dev show the gate, a rejection, a refused directive, the Budget loop and a value split across CDATA sections, and go test keeps them true.
Preflightis the raw-byte gate, andLimitswithDefaultLimitsholds its five bounds.NewBudgetandDefaultBudgetcreate the decode-time text accounting for one document, withDecodeText,Charge,Total,Remaining,MaxFieldBytesandMaxTotalBytes.LimitError,KindandErrLimitdescribe a rejection. Match the class witherrors.Is(err, xmlx.ErrLimit)and readKind,LimitandOffsetwitherrors.AsType[*xmlx.LimitError](err).ConfigErrorandErrInvalidLimitsreport a bound set to zero or less. That is a setup mistake, and it never wrapsErrLimit.
The full reference is on pkg.go.dev.
The defaults suit a small structured document, such as a feed or an API reply. They are a starting point.
| Bound | Default |
|---|---|
MaxTextRunBytes |
64 KiB |
MaxTokenBytes |
128 KiB |
MaxTagAttrs |
16 |
MaxDepth |
64 |
MaxElements |
100,000 |
Budget per value |
4 KiB |
Budget per document |
4 MiB |
Set MaxTextRunBytes to at least six times the Budget per-value cap. An entity such as " is six raw bytes that decode to one, so a smaller raw bound refuses values the Budget would keep. When your schema nests as deeply as the document, keep MaxDepth at 10000 or below, or 5000 on wasm. A catalogue-scale document will exceed MaxElements and the document cap, so set both from its real ceiling. For a compressed body, run Preflight on the inflated bytes. How xmlx bounds a document explains each bound.
- XML directives.
Preflightrefuses every<!DOCTYPE,<!ENTITY,<!ATTLISTand<!NOTATION. Decode a document that needs one under a byte cap and aBudgetinstead. - XXE and DTD-defined entity expansion.
encoding/xmldoes not resolve external entities or expand entities declared in a DTD. - Round-trip stability, which a round-trip validator covers.
- Schema validation, namespace policy, character-encoding conversion and well-formedness, which stay with
encoding/xml. - Streaming from an
io.Reader.Preflighttakes the whole body, so read it under a byte cap first. - Per-name limits such as "at most N
<item>elements", which belong at your decode site. - Decoder settings other than the defaults. If you turn
Strictoff or set anEntitymap, the token, depth and element bounds still hold. The attribute and text bounds can then miss input, so treat them as a guide.
What xmlx leaves out gives the reason for each.
- How xmlx bounds a document is for choosing bound values and reading a rejection.
- What xmlx leaves out is for deciding whether a case is in scope.
See CONTRIBUTING.md.
This project is built with care and follows security best practices, but it is intended for personal / self-hosted use. No guarantees of fitness for production environments. Use at your own risk.
This project was built with AI-assisted tooling using Claude, GPT, and Kiro. The human maintainer defines architecture, supervises implementation, and makes all final decisions.
Apache-2.0. See LICENSE.