Path: redb-route/redb.Route/Core/SafeXml.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route/Core/SafeXml.cs
----
using System.Xml;
using System.Xml.Linq;
namespace redb.Route.Core;
///
/// Reads XML that came from somewhere else. Every loader here goes through an
/// with and no resolver, which is the only shape in .NET that
/// refuses a document type declaration.
///
/// The direct loaders do not. Measured on .NET 10: a 452-byte document whose DTD declares nested
/// internal entities expands to 300 000 characters through ,
/// through and through
/// alike — LINQ to XML is no safer than the old DOM here. Setting XmlResolver = null does not
/// help either: it closes external entities, while the expansion is driven by internal ones (the
/// "billion laughs" shape of an XXE attack). One small message can therefore cost the worker
/// gigabytes, which is a denial of service against every route sharing the process.
///
///
/// A DTD is refused rather than expanded with a budget: SOAP forbids a document type declaration in
/// an envelope outright, and a payload that needs one is rare enough to be an explicit decision
/// rather than a default.
///
///
/// Every loader also checks the structure of the document while it reads (): depth,
/// attributes and namespace declarations per element, and where the caller asks, size, element count and
/// namespace declarations in the whole document. A document over a limit is refused with
/// before it is built, so whatever reads it next gets a bounded input. The loaders
/// without an argument apply , with maxCharacters as
/// the size bound.
///
///
public static class SafeXml
{
///
/// Reader settings that refuse a DTD and never resolve anything external. They do not check the structure: a
/// reader made from them alone is not bounded by , see .
///
/// Upper bound on the whole document, or null for no bound.
public static XmlReaderSettings Settings(long? maxCharacters = null) => new()
{
DtdProcessing = DtdProcessing.Prohibit,
XmlResolver = null,
MaxCharactersInDocument = maxCharacters ?? 0,
CloseInput = false,
};
/// A reader over that refuses a DTD and checks .
public static XmlReader CreateReader(Stream stream, XmlLimits limits) => CreateReader(stream, limits, baseUri: null);
/// A reader over that refuses a DTD and checks .
public static XmlReader CreateReader(TextReader text, XmlLimits limits)
{
ArgumentNullException.ThrowIfNull(text);
ArgumentNullException.ThrowIfNull(limits);
limits.Validate();
return new LimitedXmlReader(XmlReader.Create(text, Settings(limits.MaxCharacters)), limits);
}
private static XmlReader CreateReader(Stream stream, XmlLimits limits, string? baseUri)
{
ArgumentNullException.ThrowIfNull(stream);
ArgumentNullException.ThrowIfNull(limits);
limits.Validate();
var inner = baseUri is null
? XmlReader.Create(stream, Settings(limits.MaxCharacters))
: XmlReader.Create(stream, Settings(limits.MaxCharacters), baseUri);
return new LimitedXmlReader(inner, limits);
}
///
/// Reads to the end without building anything, and throws
/// or when it is over or not well-formed. For a receiver that
/// parses the same bytes several times: one check up front bounds every later parse.
///
public static void Check(byte[] xml, XmlLimits limits)
{
ArgumentNullException.ThrowIfNull(xml);
using var stream = new MemoryStream(xml, writable: false);
using var reader = CreateReader(stream, limits);
while (reader.Read()) { }
}
/// Loads a document from bytes, within and .
public static XDocument Load(byte[] xml, LoadOptions options = LoadOptions.None, long? maxCharacters = null) =>
Load(xml, Bounded(maxCharacters), options);
/// Loads a document from bytes within .
public static XDocument Load(byte[] xml, XmlLimits limits, LoadOptions options = LoadOptions.None)
{
ArgumentNullException.ThrowIfNull(xml);
using var stream = new MemoryStream(xml, writable: false);
return Load(stream, limits, options);
}
/// Loads a document from a stream, within and .
public static XDocument Load(Stream stream, LoadOptions options = LoadOptions.None, long? maxCharacters = null) =>
Load(stream, Bounded(maxCharacters), options);
/// Loads a document from a stream within .
public static XDocument Load(Stream stream, XmlLimits limits, LoadOptions options = LoadOptions.None)
{
using var reader = CreateReader(stream, limits);
return XDocument.Load(reader, options);
}
/// Loads a document from a file path, within and .
public static XDocument LoadFile(string path, LoadOptions options = LoadOptions.None, long? maxCharacters = null) =>
LoadFile(path, Bounded(maxCharacters), options);
/// Loads a document from a file path within .
public static XDocument LoadFile(string path, XmlLimits limits, LoadOptions options = LoadOptions.None)
{
ArgumentException.ThrowIfNullOrWhiteSpace(path);
using var stream = System.IO.File.OpenRead(path);
// The reader needs the base URI to report a usable location for an error in this file.
using var reader = CreateReader(stream, limits, path);
return XDocument.Load(reader, options);
}
/// Parses a document from text, within and .
public static XDocument Parse(string xml, LoadOptions options = LoadOptions.None, long? maxCharacters = null) =>
Parse(xml, Bounded(maxCharacters), options);
/// Parses a document from text within .
public static XDocument Parse(string xml, XmlLimits limits, LoadOptions options = LoadOptions.None)
{
ArgumentNullException.ThrowIfNull(xml);
using var reader = CreateReader(new StringReader(xml), limits);
return XDocument.Load(reader, options);
}
/// Parses a single element from text, within and .
public static XElement ParseElement(string xml, LoadOptions options = LoadOptions.None, long? maxCharacters = null) =>
ParseElement(xml, Bounded(maxCharacters), options);
/// Parses a single element from text within .
public static XElement ParseElement(string xml, XmlLimits limits, LoadOptions options = LoadOptions.None)
{
ArgumentNullException.ThrowIfNull(xml);
using var reader = CreateReader(new StringReader(xml), limits);
reader.MoveToContent();
return XElement.Load(reader, options);
}
///
/// Loads an , the shape System.Security.Cryptography.Xml needs for signatures and
/// encryption, within and .
/// defaults to true because canonicalization of a signed document depends on
/// it: dropping whitespace on load makes a valid signature fail to verify.
///
public static XmlDocument LoadDocument(byte[] xml, bool preserveWhitespace = true, long? maxCharacters = null) =>
LoadDocument(xml, Bounded(maxCharacters), preserveWhitespace);
/// Loads an from bytes within ; whitespace as in the other overload.
public static XmlDocument LoadDocument(byte[] xml, XmlLimits limits, bool preserveWhitespace = true)
{
ArgumentNullException.ThrowIfNull(xml);
using var stream = new MemoryStream(xml, writable: false);
return LoadDocument(stream, limits, preserveWhitespace);
}
/// Loads an from a stream within ; whitespace as in the other overload.
public static XmlDocument LoadDocument(Stream stream, XmlLimits limits, bool preserveWhitespace = true)
{
var document = new XmlDocument { PreserveWhitespace = preserveWhitespace, XmlResolver = null };
using var reader = CreateReader(stream, limits);
document.Load(reader);
return document;
}
private static XmlLimits Bounded(long? maxCharacters) =>
maxCharacters is null ? XmlLimits.Default : XmlLimits.Default with { MaxCharacters = maxCharacters };
}