diff --git a/docs/for-developers/template-builder.md b/docs/for-developers/template-builder.md index c03c005..78a179c 100644 --- a/docs/for-developers/template-builder.md +++ b/docs/for-developers/template-builder.md @@ -244,7 +244,7 @@ builds it; its problems carry the JSON pointer. See the known limits for what th | Code | Severity | Meaning | |---|---|---| -| TB9300 | error | The syntax is broken (unclosed loop, …) or the file is not a DOCX/ODT template. | +| TB9300 | error | The syntax is broken (unclosed loop, …), the file is not a DOCX/ODT template, or it exceeds an upload limit (below). | | TB9301 | error | The copy reads a path the data does not have (`DataPath` names it as the copy writes it). | | TB9302 | error | Filling with the data's shape fails, for example a loop over a value. | | TB9303 | warning | No stamp: edited in an application that dropped it, or not built by the builder. | @@ -253,6 +253,22 @@ builds it; its problems carry the JSON pointer. See the known limits for what th | TB9306 | warning | Built from an older version of a component, or from one no longer registered in `Components`. | | TB92xx, others | error | `CheckDefinition`: the import's and the build's own codes (TB9203: unknown data path). | +**Upload limits.** An upload comes from outside, so `Check` reads the package once within limits before anything +parses it, counting what the entries really unpack to (a ZIP can declare false sizes). Exceeding a limit is TB9300 at +the entry (`word/document.xml`) or paragraph (`content.xml, paragraph 12`), and the check stops there. The defaults fit +real templates with room to spare; raise them in `TemplateCheckOptions` if yours are larger. Cap the size of the raw +upload in the host too: `Check` reads the whole stream before it looks inside. + +| Option | Default | Limits | +|---|---|---| +| `MaximumEntries` | 1,000 | entries in the package | +| `MaximumUnpackedSize` | 64 MiB | bytes all entries unpack to | +| `MaximumMarkupSize` | 8 MiB | bytes the XML entries unpack to (recognised by content, not name: what the engine parses; about half a second of checking per MiB) | +| `MaximumParagraphLength` | 20,000 | characters of text in one paragraph | + +The trial fill uses witness data in which a collection answers every index (`lines[999]`) with one shared item and +loops once, so it is linear in the template, however many indexes and nested loops it has. + **Changing the data.** Adding a field is safe. Renaming or removing one is a breaking change: stored templates that read it break. Check every stored template after such a change (for example on deploy) and show the result to the users (yellow for warnings, red for broken). The library only checks; storing templates, keeping a changelog of data @@ -556,8 +572,24 @@ Export the definitions a host stores with `TemplateJsonExportOptions.TextLanguag the JSON and an agent can read and change them; without, the texts come from the host's catalogue and the agent only sees the keys. -A patch that cannot be applied (malformed, a missing path, a failed `test` operation, a `move` into its own child) -changes nothing and reports TB9207 at the operation (`/1` is the second). The description and the schema are generated +A patch that cannot be applied (malformed, a missing path, a failed `test` operation, a `move` or `copy` into its own +child, or a limit below) changes nothing and reports TB9207 at the operation (`/1` is the second). + +**Limits.** Everything an agent sends is input from outside. Cap it in the host as well (request size, rate), and keep +these limits, which hold whatever the host does: + +| Limit | Default | Exceeded | +|---|---|---| +| `TemplateJsonImportOptions.MaximumLength` | 1,000,000 characters | TB9206 at `""` (import, check, preview); a patch that would make the definition longer: TB9207 at the operation | +| `TemplateJsonImportOptions.MaximumValues` | 100,000 JSON values (objects, arrays, strings, numbers, …) | TB9206 at `""` | +| operations in one patch | 1,000 | TB9207 at `/1000` | +| depth of a patched definition | 64 levels | TB9207 at the operation | + +A patch's growth is counted per operation, so a `copy` that doubles the definition is refused before memory runs +out; a patch longer than `MaximumLength` is refused at `""`, and one that copies or removes more than 16 times +`MaximumLength` in total at the operation that crosses it. `Patch` writes the result compact (as the length is counted); +`Read` gives indented parts to read. `Preview` without data fills with the contract's witness, which, like the check's, loops once and answers every +index with one item; `Preview` with data fills with the host's data as it is. The description and the schema are generated from one vocabulary that a test compares with the reader, so they always describe what the import accepts. ## Testing your definitions diff --git a/docs/superpowers/plans/2026-12-02-builder-input-limits.md b/docs/superpowers/plans/2026-12-02-builder-input-limits.md new file mode 100644 index 0000000..bcf644e --- /dev/null +++ b/docs/superpowers/plans/2026-12-02-builder-input-limits.md @@ -0,0 +1,76 @@ +# Builder input limits Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** Check, Preview and Patch stay fast and small on hostile input (#302). + +**Architecture:** a shared-item witness list for both witnesses; limit options on check and import options; size, +depth and count guards in the patch applier. + +**Tech Stack:** .NET 11/10, xUnit v3, System.Text.Json, System.IO.Compression, XmlReader. + +**Spec:** `docs/superpowers/specs/2026-12-02-builder-input-limits-design.md` + +## Global Constraints + +- Builder API is experimental (`[TPLB001]` lines in `PublicAPI.Unshipped.txt`); core untouched. +- Limits give problems (TB9300 / TB9206 / TB9207), never exceptions. +- Defaults: entries 1,000; unpacked 64 MiB; markup 8 MiB; paragraph 20,000 chars; definition 1,000,000 chars and + 100,000 values; patch 1,000 operations, depth 64. + +## Review Focus + +- A real template (sample, 100+ paragraphs, images) passes Check and Preview unchanged. +- Indexed paths still resolve in fills (`IndexedPathTests` stay green). +- Patch: legitimate `copy`/`move` of a section still works. +- ODT uploads hit the same limits (content.xml / styles.xml, `text:p`/`text:h`). +- A damaged ZIP is not reported as a limit (the engine's syntax error stays). + +--- + +### Task 1: Shared-item witness + +**Files:** Create `src/TriasDev.Templify.Builder/Typed/WitnessList.cs`; modify `DataContract.cs` (WitnessNode.ToData), +`Typed/DataCatalog.cs` (CreateWitness); test `tests/TriasDev.Templify.Builder.Tests/InputLimitTests.cs`. + +- [ ] Tests: `Preview_DeepIndexedPath_IsFastAndSmall` (definition with `{{c0[999].c1[999].c2[999].leaf}}`, Preview + without data completes < 1 s, allocations < 100 MB, a document comes back); + `Check_IndexedPlaceholderAndNestedLoops_IsFastAndSmall` (DOCX with `{{order.lines[999].description}}` and three + nested loops over catalogue collections; Check < 1 s, < 100 MB); `Witness_IndexedItem_Resolves`. +- [ ] Run, watch the first two fail (timeout/OOM guard via allocation assertion). +- [ ] `WitnessList(object? item, int count)`: `IList`, read-only, enumerates `[item]`. +- [ ] Green, plus `IndexedPathTests`, `DataContractTests`, `TemplateCheckTests`. + +### Task 2: Definition limits (TB9206) + +**Files:** `Json/TemplateJsonImportOptions.cs`, `Json/TemplateJson.cs` (Import), `BuildContext.cs` (code), PublicAPI. + +- [ ] Tests: just below / just above for `MaximumLength` and `MaximumValues` (Import throws TemplateBuildException with + TB9206 at `""`; CheckDefinition returns it as a problem). +- [ ] Implement; count values iteratively over the parsed `JsonElement`. + +### Task 3: Patch limits (TB9207) + +**Files:** `Json/JsonPatch.cs`, `Json/TemplateJson.cs` (Patch passes limits). + +- [ ] Tests: `Patch_SelfCopies_AreRefused` (23 × copy `/content` → `/content/-`: not applied, TB9207, < 1 s); + `Patch_CopyIntoItsOwnSource_IsRefused`; `Patch_TooManyOperations` (1,000 ok-shaped `test` ops pass, 1,001 → TB9207 + at `/1000`); `Patch_TooDeep` (TB9207, no exception); size just below/above with a small `MaximumLength`. +- [ ] Implement `JsonPatch.Apply(document, patch, maximumLength)`. + +### Task 4: Check limits (TB9300) + +**Files:** `TemplateCheck.cs` (options), `TemplateInspector.cs` (pre-scan), new `PackageLimits.cs`. + +- [ ] Tests per limit, DOCX and ODT where it matters: entries, unpacked (zip with a large stored media entry), markup, + paragraph length (just below Ok, just above TB9300 with Location naming the entry); a damaged ZIP keeps its old + result. +- [ ] Implement a pre-scan reading every entry through a counting stream; XmlReader (DTD prohibited) for paragraph + text in `.xml` entries. + +### Task 5: Property test, docs, core issue + +- [ ] `Limits_RandomNestingAndIndexes_StayBounded`: seeded random definitions (loop depth 1–6, indexes 0–999) through + Preview and CheckDefinition + built upload through Check; each < 2 s and < 100 MB. +- [ ] Docs: limits table and the agent-input sentence in `docs/for-developers/template-builder.md`. +- [x] Core issue #321 for the quadratic unterminated-tag scan. diff --git a/docs/superpowers/specs/2026-12-02-builder-input-limits-design.md b/docs/superpowers/specs/2026-12-02-builder-input-limits-design.md new file mode 100644 index 0000000..3cce1ba --- /dev/null +++ b/docs/superpowers/specs/2026-12-02-builder-input-limits-design.md @@ -0,0 +1,40 @@ +# Builder: limits for Check, Preview and Patch on untrusted input (#302) + +**Status:** approved without a design checkpoint (the maintainer accepts the reviewer's proposal, issue #302). + +## Intent + +`TemplateInspector.Check`, `TemplateJson.Preview` and `TemplateJson.Patch` are called by an agent host with input it +does not control. A few hundred bytes must not exhaust memory or keep a core busy for minutes. Every limit gives a +result with a problem, never an exception. + +## Goals + +- The three inputs from the issue (indexed placeholder + 3 nested loops in an upload; `c0[999].c1[999].c2[999]` in a + definition; 23 self-copies in a patch) return within 1 s and well under 100 MB. +- Limits on uploads (Check), definitions (Import and everything built on it) and patches, with documented defaults. + +Non-goals: limits on the host's own data in `Preview(…, data)` (the host owns it); the core's quadratic scan of +unterminated tags (a separate core issue; the paragraph limit below bounds it for Check). + +## Design + +1. **Witness: one shared item per collection.** A collection in witness data is a `WitnessList`: a read-only `IList` + whose `Count` is what the highest index needs (`[999]` → 1000), whose indexer returns the one shared item, and which + *enumerates one item*. The core indexes through `IList` and loops through `IEnumerable`, so indexed paths resolve + and every loop runs once. Witness data is linear in the contract, and a trial fill or a preview without data is + linear in the template. Used by `DataContract.CreateWitness` (Preview, test kit) and `DataCatalog.CreateWitness` + (Check). Ruling: with one enumerated item there is no product of loop sizes left, so no separate fill budget. +2. **Check limits** in `TemplateCheckOptions`, counted while reading the package (declared sizes can lie): + `MaximumEntries` (1,000), `MaximumUnpackedSize` (64 MiB, all entries), `MaximumMarkupSize` (8 MiB, `.xml`/`.rels` + entries: what the engine parses), `MaximumParagraphLength` (20,000 characters of text in one paragraph). Exceeding + one is TB9300 at the entry (`word/document.xml`), the paragraph limit also names the paragraph number. The check + stops there (no validation, no fill). +3. **Definition limits** in `TemplateJsonImportOptions`: `MaximumLength` (1,000,000 characters) and `MaximumValues` + (100,000 JSON values: objects, arrays, strings, numbers, …). Exceeding one is the new code TB9206 at `""`. All JSON + functions that import (Import, CheckDefinition, Patch's check, Preview) inherit them. +4. **Patch limits**: at most 1,000 operations; the patched document's size, estimated per operation (stored length, + plus the value's length for add/replace and the copied node's serialised length for copy/move), stays within the + import's `MaximumLength`; its depth stays within 64 (the target pointer's tokens plus the value's depth); `copy` + into its own source is refused like `move`. Each is TB9207 at the operation (`/n`). +5. **Docs**: the developer docs list the limits and defaults, and tell hosts to cap agent input. diff --git a/src/TriasDev.Templify.Builder/BuildContext.cs b/src/TriasDev.Templify.Builder/BuildContext.cs index b8e4a81..b9f482f 100644 --- a/src/TriasDev.Templify.Builder/BuildContext.cs +++ b/src/TriasDev.Templify.Builder/BuildContext.cs @@ -115,6 +115,9 @@ internal static class DiagnosticCodes /// A theme value the host sets on import names a token the definition's theme does not have; it is not used. public const string UnusedThemeValue = "TB9205"; + /// A JSON definition is longer or has more values than the import options allow. + public const string DefinitionTooLarge = "TB9206"; + /// was called more than once. public const string PageAlreadySet = "TB6001"; diff --git a/src/TriasDev.Templify.Builder/DataContract.cs b/src/TriasDev.Templify.Builder/DataContract.cs index d29610d..f61b8a8 100644 --- a/src/TriasDev.Templify.Builder/DataContract.cs +++ b/src/TriasDev.Templify.Builder/DataContract.cs @@ -118,8 +118,9 @@ public string ToJson() } /// - /// Builds data in which every path of the contract exists: each collection holds one item (or as many as its highest - /// index needs, items[2] → three), every item with the shape of all its uses; each value is the text "x". + /// Builds data in which every path of the contract exists: each collection holds one item, with the shape of all its + /// uses, which every index reads (items[2] is that item too); each value is the text "x". A loop over + /// it runs once. /// /// The data, as nested dictionaries and lists. public IReadOnlyDictionary CreateWitness() @@ -139,7 +140,7 @@ public string ToJson() // items[] (every item) or items[2] (one item): the same item shape, at least index + 1 items. string index = segment[(bracket + 1)..^1]; - node = node.Child(segment[..bracket]).Item(index.Length == 0 ? 1 : int.Parse(index, System.Globalization.CultureInfo.InvariantCulture) + 1); + node = node.Child(segment[..bracket]).Item(index.Length == 0 || !int.TryParse(index, System.Globalization.NumberStyles.None, System.Globalization.CultureInfo.InvariantCulture, out int at) ? 1 : Math.Min(at, int.MaxValue - 1) + 1); } if (entry.Usage == ContractUsage.Collection) @@ -337,7 +338,8 @@ public WitnessNode Item(int count = 1) { if (_item != null) { - return Enumerable.Range(0, _count).Select(_ => _item.ToData()).ToList(); + // One shared item, however high the index (#302): building each anew grows as count^depth. + return new WitnessList(_item.ToData(), _count); } if (_children.Count > 0) diff --git a/src/TriasDev.Templify.Builder/Json/JsonPatch.cs b/src/TriasDev.Templify.Builder/Json/JsonPatch.cs index ae2a8e4..68299c2 100644 --- a/src/TriasDev.Templify.Builder/Json/JsonPatch.cs +++ b/src/TriasDev.Templify.Builder/Json/JsonPatch.cs @@ -12,13 +12,39 @@ internal sealed class JsonPatchException(int index, string message) : Exception( public int Index { get; } = index; } -/// JSON Patch (RFC 6902) on : add, remove, replace, move, copy, test. +/// +/// JSON Patch (RFC 6902) on : add, remove, replace, move, copy, test. A patch comes from outside +/// (an agent), so it is bounded (#302): at most operations, a document that stays within +/// a size (estimated per operation, so a copy cannot double it unseen) and within levels, and +/// no copy or move into its own source. +/// internal static class JsonPatch { + /// The most operations one patch may have. + public const int MaximumOperations = 1000; + + /// The most nested levels a patched document may have (as System.Text.Json reads by default). + public const int MaximumDepth = 64; + + /// How a patched definition is written: compact, non-ASCII text unescaped. + public static readonly JsonSerializerOptions Compact = new JsonSerializerOptions + { + Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping, + }; + /// Applies the operations to a copy of ; all or none. - /// An operation is malformed or cannot be applied; the input is unchanged. - public static JsonNode? Apply(JsonNode? document, string patch) + /// The document. + /// The patch: a JSON array of operations. + /// The document's length as stored, in characters. + /// The most characters the patched document may have. + /// An operation is malformed, cannot be applied or exceeds a limit; the input is unchanged. + public static JsonNode? Apply(JsonNode? document, string patch, long length = 0, long maximumLength = long.MaxValue) { + if (patch.Length > maximumLength) + { + throw new JsonPatchException(-1, $"The patch has {patch.Length} characters; at most {maximumLength} are accepted (TemplateJsonImportOptions.MaximumLength)."); + } + JsonArray operations; try { @@ -29,15 +55,22 @@ internal static class JsonPatch throw new JsonPatchException(-1, "The patch is not JSON: " + exception.Message); } + if (operations.Count > MaximumOperations) + { + throw new JsonPatchException(MaximumOperations, $"Operation {MaximumOperations}: a patch has at most {MaximumOperations} operations; send the rest in another patch."); + } + JsonNode? root = document?.DeepClone(); + Budget budget = new Budget(length, maximumLength); for (int i = 0; i < operations.Count; i++) { try { - root = Operation(root, operations[i] as JsonObject ?? throw new ArgumentException("An operation is an object with \"op\" and \"path\".")); + root = Operation(root, operations[i] as JsonObject ?? throw new ArgumentException("An operation is an object with \"op\" and \"path\"."), budget); } - catch (ArgumentException exception) + catch (Exception exception) when (exception is ArgumentException or InvalidOperationException) { + // InvalidOperationException: a string System.Text.Json cannot write (a lone surrogate). throw new JsonPatchException(i, $"Operation {i}: {exception.Message}"); } } @@ -45,44 +78,46 @@ internal static class JsonPatch return root; } - private static JsonNode? Operation(JsonNode? root, JsonObject operation) + private static JsonNode? Operation(JsonNode? root, JsonObject operation, Budget budget) { string op = Member(operation, "op"); string path = Member(operation, "path"); switch (op) { case "add": - return Add(root, path, Value(operation)); + return Add(root, path, Value(operation), budget); case "remove": + budget.Remove(JsonPointer.Resolve(root, path)); Remove(root, path); return root; case "replace": - JsonPointer.Resolve(root, path); + JsonNode? old = JsonPointer.Resolve(root, path); if (path.Length == 0) { - return Value(operation); + budget.Remove(old); + return budget.Insert(path, Value(operation)); } + budget.Remove(old); Remove(root, path); - return Add(root, path, Value(operation)); + return Add(root, path, Value(operation), budget); case "move": string from = Member(operation, "from"); - if (path.StartsWith(from + "/", StringComparison.Ordinal)) - { - throw new ArgumentException($"'{from}' cannot be moved into itself ('{path}')."); - } - + IntoItself(from, path, "moved"); if (from == path) { JsonPointer.Resolve(root, from); return root; } - JsonNode? moved = JsonPointer.Resolve(root, from)?.DeepClone(); + // Detached, not cloned: a move neither copies nor changes the length. + JsonNode? moved = JsonPointer.Resolve(root, from); Remove(root, from); - return Add(root, path, moved); + return Add(root, path, moved, budget, JsonPointer.Parse(from).Count, charge: false); case "copy": - return Add(root, path, JsonPointer.Resolve(root, Member(operation, "from"))?.DeepClone()); + string source = Member(operation, "from"); + IntoItself(source, path, "copied"); + return Add(root, path, JsonPointer.Resolve(root, source)?.DeepClone(), budget, JsonPointer.Parse(source).Count); case "test": if (!JsonNode.DeepEquals(JsonPointer.Resolve(root, path), Value(operation))) { @@ -95,9 +130,20 @@ internal static class JsonPatch } } - private static JsonNode? Add(JsonNode? root, string path, JsonNode? value) + private static void IntoItself(string from, string path, string verb) + { + if (path.StartsWith(from + "/", StringComparison.Ordinal)) + { + throw new ArgumentException($"'{from}' cannot be {verb} into itself ('{path}')."); + } + } + + // sourceDepth: for a node taken from the document, how many levels down it was; charge: whether the value adds to + // the length (not for a move). + private static JsonNode? Add(JsonNode? root, string path, JsonNode? value, Budget budget, int? sourceDepth = null, bool charge = true) { IReadOnlyList tokens = JsonPointer.Parse(path); + value = budget.Insert(path, value, tokens.Count, sourceDepth, charge); if (tokens.Count == 0) { return value; @@ -159,4 +205,84 @@ private static string Member(JsonObject operation, string name) => private static JsonNode? Value(JsonObject operation) => operation.TryGetPropertyValue("value", out JsonNode? value) ? value?.DeepClone() : throw new ArgumentException("\"value\" is missing."); + /// + /// The patched document's length (as writes it), its depth limit, and the work a patch may + /// cause: serialising and walking nodes costs at most times the length limit, so a patch + /// that copies and removes a large part again and again stops early. + /// + private sealed class Budget(long length, long maximum) + { + private const long WorkFactor = 16; + + private readonly long _maximumWork = maximum > long.MaxValue / WorkFactor ? long.MaxValue : maximum * WorkFactor; + private long _length = length; + private long _work; + + /// Counts a value placed at ( levels down), or refuses it. + public JsonNode? Insert(string path, JsonNode? value, int depth = 0, int? sourceDepth = null, bool charge = true) + { + // The document is never deeper than the limit, so a node taken from it at least as deep fits anywhere higher. + if (!(sourceDepth >= depth) && depth + Depth(value) > MaximumDepth) + { + throw new ArgumentException($"the document would be deeper than {MaximumDepth} levels at '{path}'."); + } + + if (charge) + { + _length += Length(value); + if (_length > maximum) + { + throw new ArgumentException($"the definition would be longer than {maximum} characters (TemplateJsonImportOptions.MaximumLength)."); + } + } + + return value; + } + + public void Remove(JsonNode? value) => _length -= Length(value); + + private void Work(long amount) + { + _work += amount; + if (_work > _maximumWork) + { + throw new ArgumentException("the patch copies or removes too much in total; send smaller patches."); + } + } + + private long Length(JsonNode? value) + { + long length = value is null ? 4 : value.ToJsonString(Compact).Length; + Work(length); + return length; + } + + /// The nesting depth of a value: 0 for a scalar, 1 for an empty array or object (iterative). + private int Depth(JsonNode? value) + { + int deepest = 0; + Stack<(JsonNode Node, int Depth)> pending = new Stack<(JsonNode, int)>(); + if (value is JsonObject or JsonArray) + { + pending.Push((value, 1)); + } + + while (pending.Count > 0) + { + (JsonNode node, int depth) = pending.Pop(); + Work(1); + deepest = Math.Max(deepest, depth); + IEnumerable children = node is JsonObject o ? o.Select(p => p.Value) : node.AsArray(); + foreach (JsonNode? child in children) + { + if (child is JsonObject or JsonArray) + { + pending.Push((child, depth + 1)); + } + } + } + + return deepest; + } + } } diff --git a/src/TriasDev.Templify.Builder/Json/TemplateJson.cs b/src/TriasDev.Templify.Builder/Json/TemplateJson.cs index ceb6da0..7a6adbb 100644 --- a/src/TriasDev.Templify.Builder/Json/TemplateJson.cs +++ b/src/TriasDev.Templify.Builder/Json/TemplateJson.cs @@ -106,7 +106,7 @@ private static void CheckBuildsTheSame(ITemplateDefinition definition, TemplateB ITemplateDefinition imported; try { - imported = Import(json, new TemplateJsonImportOptions { Assets = assets, Components = export.Components, Shared = shared, AllowRawXml = true, AcceptsAnyValueFormat = true }); + imported = Import(json, new TemplateJsonImportOptions { Assets = assets, Components = export.Components, Shared = shared, AllowRawXml = true, AcceptsAnyValueFormat = true, MaximumLength = int.MaxValue, MaximumValues = int.MaxValue }); } catch (TemplateBuildException exception) { @@ -230,21 +230,24 @@ public static TemplatePatchResult Patch(string json, string patch, TemplateJsonI } JsonNode document = JsonOutline.Parse(json); - JsonNode? patched; + string text; try { - patched = JsonPatch.Apply(document, patch); + JsonNode? patched = JsonPatch.Apply(document, patch, document.ToJsonString(JsonPatch.Compact).Length, import.MaximumLength); + + // Compact, as the patch's length was counted: indenting a deeply nested value can multiply its length. + text = patched is null ? "null" : patched.ToJsonString(JsonPatch.Compact); } - catch (JsonPatchException exception) + catch (Exception exception) when (exception is JsonPatchException or InvalidOperationException) { + int index = exception is JsonPatchException failed ? failed.Index : -1; TemplateCheckProblem problem = new TemplateCheckProblem(CheckCodes.PatchFailed, TemplateCheckSeverity.Error, exception.Message) { - Location = exception.Index < 0 ? string.Empty : "/" + exception.Index.ToString(System.Globalization.CultureInfo.InvariantCulture), + Location = index < 0 ? string.Empty : "/" + index.ToString(System.Globalization.CultureInfo.InvariantCulture), }; return new TemplatePatchResult(false, json, new TemplateCheckResult(TriasDev.Templify.Core.TemplateFormat.Unknown, null, [problem])); } - string text = patched is null ? "null" : patched.ToJsonString(_indented); return new TemplatePatchResult(true, text, TemplateInspector.CheckDefinition(text, import, build)); } @@ -313,12 +316,6 @@ static TemplatePreview Failed(IEnumerable problems) => return new TemplatePreview(new TemplateCheckResult(template.Format, null, warnings), filled, PreviewText.Of(filled, template.Format)); } - private static readonly System.Text.Json.JsonSerializerOptions _indented = new System.Text.Json.JsonSerializerOptions - { - WriteIndented = true, - Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping, - }; - /// /// Imports a JSON definition. The result builds with like a C# definition; /// problems are reported as build errors with the JSON pointer in . @@ -331,6 +328,11 @@ public static ITemplateDefinition Import(string json, TemplateJsonImportOptions? { ArgumentNullException.ThrowIfNull(json); options ??= new TemplateJsonImportOptions(); + if (json.Length > options.MaximumLength) + { + throw TooLarge($"The definition has {json.Length} characters; at most {options.MaximumLength} are accepted (TemplateJsonImportOptions.MaximumLength)."); + } + System.Text.Json.JsonElement root; try { @@ -342,6 +344,11 @@ public static ITemplateDefinition Import(string json, TemplateJsonImportOptions? throw Invalid(string.Empty, "The text is not JSON: " + exception.Message); } + if (!WithinValues(root, options.MaximumValues)) + { + throw TooLarge($"The definition has more than {options.MaximumValues} JSON values (TemplateJsonImportOptions.MaximumValues)."); + } + if (root.ValueKind != System.Text.Json.JsonValueKind.Object || !root.TryGetProperty("templifyDefinition", out System.Text.Json.JsonElement version) || version.ValueKind != System.Text.Json.JsonValueKind.Number @@ -387,6 +394,42 @@ private static void CheckStructure(JsonDefinition definition) } } + private static TemplateBuildException TooLarge(string message) => + new TemplateBuildException([new BuildDiagnostic(DiagnosticCodes.DefinitionTooLarge, message) { Location = string.Empty }]); + + /// Whether a JSON value holds at most values, itself included (iterative: no deep recursion). + private static bool WithinValues(System.Text.Json.JsonElement root, int maximum) + { + Stack pending = new Stack(); + pending.Push(root); + long count = 0; + while (pending.Count > 0) + { + if (++count > maximum) + { + return false; + } + + System.Text.Json.JsonElement element = pending.Pop(); + if (element.ValueKind == System.Text.Json.JsonValueKind.Object) + { + foreach (System.Text.Json.JsonProperty property in element.EnumerateObject()) + { + pending.Push(property.Value); + } + } + else if (element.ValueKind == System.Text.Json.JsonValueKind.Array) + { + foreach (System.Text.Json.JsonElement item in element.EnumerateArray()) + { + pending.Push(item); + } + } + } + + return true; + } + private static TemplateBuildException Invalid(string location, string message) => new TemplateBuildException([new BuildDiagnostic(DiagnosticCodes.InvalidJson, message) { Location = location }]); } diff --git a/src/TriasDev.Templify.Builder/Json/TemplateJsonImportOptions.cs b/src/TriasDev.Templify.Builder/Json/TemplateJsonImportOptions.cs index f9b3b72..b2fdff2 100644 --- a/src/TriasDev.Templify.Builder/Json/TemplateJsonImportOptions.cs +++ b/src/TriasDev.Templify.Builder/Json/TemplateJsonImportOptions.cs @@ -33,6 +33,18 @@ public sealed class TemplateJsonImportOptions /// Gets a value indicating whether raw XML blocks are accepted. Default: false (a JSON definition is input from outside). public bool AllowRawXml { get; init; } + /// + /// Gets the most characters a definition may have; a longer one is refused (TB9206) before it is read. Default: + /// 1,000,000. A definition comes from outside (a customer, an agent): cap what you accept. + /// + public int MaximumLength { get; init; } = 1_000_000; + + /// + /// Gets the most JSON values (objects, arrays, strings, numbers, booleans, nulls) a definition may have; more is + /// refused (TB9206). Default: 100,000. + /// + public int MaximumValues { get; init; } = 100_000; + /// /// Whether any value format is accepted: the export's self-check, which reads back what the C# definition wrote /// (host formats included); the host's own list applies when it imports. diff --git a/src/TriasDev.Templify.Builder/PackageLimits.cs b/src/TriasDev.Templify.Builder/PackageLimits.cs new file mode 100644 index 0000000..015b0e4 --- /dev/null +++ b/src/TriasDev.Templify.Builder/PackageLimits.cs @@ -0,0 +1,240 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Globalization; +using System.IO.Compression; +using System.Xml; + +namespace TriasDev.Templify.Builder; + +/// +/// Reads an uploaded package once within the limits of before anything parses it +/// (#302): entries, unpacked bytes (counted while reading, since declared sizes can lie), XML bytes and the text of one +/// paragraph. An entry is XML by its content, not its name (a package may name its main part document.bin). A +/// package that is not a ZIP is left to the format check; an entry that cannot be read (encrypted, an unknown +/// compression) is skipped, since the engine cannot read it either. +/// +internal static class PackageLimits +{ + private const string WordNamespace = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"; + private const string TextNamespace = "urn:oasis:names:tc:opendocument:xmlns:text:1.0"; + + /// The first limit the package exceeds, as a TB9300 problem; null when it is within all of them. + public static TemplateCheckProblem? Check(byte[] package, TemplateCheckOptions options) + { + try + { + using ZipArchive archive = new ZipArchive(new MemoryStream(package, writable: false), ZipArchiveMode.Read); + if (archive.Entries.Count > options.MaximumEntries) + { + return Problem( + archive.Entries[options.MaximumEntries].FullName, + $"The package has {archive.Entries.Count} entries; at most {options.MaximumEntries} are read (TemplateCheckOptions.MaximumEntries)."); + } + + Counter counter = new Counter(options); + foreach (ZipArchiveEntry entry in archive.Entries) + { + try + { + if (Read(entry, counter, options) is { } problem) + { + return problem; + } + } + catch (Exception exception) when (exception is InvalidDataException or NotSupportedException or IOException) + { + // Unreadable here, so unreadable for the engine: what it yielded so far is counted. + } + } + } + catch (Exception exception) when (exception is InvalidDataException or NotSupportedException or IOException) + { + // Not a ZIP, or a damaged directory: the format check reports it. + } + + return null; + } + + private static TemplateCheckProblem? Read(ZipArchiveEntry entry, Counter counter, TemplateCheckOptions options) + { + bool markup = LooksLikeXml(entry); + using CountingStream stream = new CountingStream(entry.Open(), counter, markup); + try + { + if (markup) + { + if (Paragraphs(stream, options.MaximumParagraphLength) is { } paragraph) + { + return Problem( + $"{entry.FullName}, paragraph {paragraph.ToString(CultureInfo.InvariantCulture)}", + $"A paragraph has more than {options.MaximumParagraphLength} characters of text (TemplateCheckOptions.MaximumParagraphLength)."); + } + } + + stream.CopyTo(Stream.Null); + } + catch (LimitException exception) + { + return Problem(entry.FullName, exception.Message); + } + + return null; + } + + /// + /// Whether an entry starts like XML: < after an optional byte order mark and white space (a UTF-16 mark + /// counts too). Media, fonts and other binary data do not. + /// + private static bool LooksLikeXml(ZipArchiveEntry entry) + { + Span start = stackalloc byte[64]; + int length = 0; + using (Stream stream = entry.Open()) + { + int read; + while (length < start.Length && (read = stream.Read(start[length..])) > 0) + { + length += read; + } + } + + ReadOnlySpan bytes = start[..length]; + if (bytes.StartsWith((ReadOnlySpan)[0xFF, 0xFE]) || bytes.StartsWith((ReadOnlySpan)[0xFE, 0xFF])) + { + return true; + } + + if (bytes.StartsWith((ReadOnlySpan)[0xEF, 0xBB, 0xBF])) + { + bytes = bytes[3..]; + } + + bytes = bytes.TrimStart((ReadOnlySpan)[(byte)' ', (byte)'\t', (byte)'\r', (byte)'\n']); + return bytes.Length > 0 && bytes[0] == (byte)'<'; + } + + /// The 1-based number of the first paragraph (in document order) with too much text; null when none. + private static int? Paragraphs(Stream stream, int maximum) + { + XmlReaderSettings settings = new XmlReaderSettings { DtdProcessing = DtdProcessing.Prohibit, XmlResolver = null, CloseInput = false }; + Stack<(int Number, long Length)> open = new Stack<(int, long)>(); + int paragraphs = 0; + try + { + using XmlReader reader = XmlReader.Create(stream, settings); + while (reader.Read()) + { + switch (reader.NodeType) + { + case XmlNodeType.Element when IsParagraph(reader): + paragraphs++; + if (!reader.IsEmptyElement) + { + open.Push((paragraphs, 0)); + } + + break; + case XmlNodeType.EndElement when open.Count > 0 && IsParagraph(reader): + open.Pop(); + break; + case XmlNodeType.Text or XmlNodeType.CDATA or XmlNodeType.SignificantWhitespace or XmlNodeType.Whitespace when open.Count > 0: + (int number, long length) = open.Pop(); + length += reader.Value.Length; + if (length > maximum) + { + return number; + } + + open.Push((number, length)); + break; + } + } + } + catch (XmlException) + { + // Malformed XML: the engine reports it; the rest of the entry is still counted. + } + + return null; + } + + private static bool IsParagraph(XmlReader reader) => + (reader.LocalName == "p" && reader.NamespaceURI is WordNamespace or TextNamespace) + || (reader.LocalName == "h" && reader.NamespaceURI == TextNamespace); + + private static TemplateCheckProblem Problem(string location, string message) => + new TemplateCheckProblem(CheckCodes.Syntax, TemplateCheckSeverity.Error, message) { Location = location }; + + private sealed class LimitException(string message) : Exception(message); + + /// The bytes read so far, all entries and XML entries. + private sealed class Counter(TemplateCheckOptions options) + { + private long _total; + private long _markup; + + public void Add(int count, bool markup) + { + _total += count; + if (_total > options.MaximumUnpackedSize) + { + throw new LimitException($"The package unpacks to more than {options.MaximumUnpackedSize} bytes (TemplateCheckOptions.MaximumUnpackedSize)."); + } + + if (markup) + { + _markup += count; + if (_markup > options.MaximumMarkupSize) + { + throw new LimitException($"The package's XML unpacks to more than {options.MaximumMarkupSize} bytes (TemplateCheckOptions.MaximumMarkupSize)."); + } + } + } + } + + /// A read-only stream that counts what it yields. + private sealed class CountingStream(Stream inner, Counter counter, bool markup) : Stream + { + public override bool CanRead => true; + + public override bool CanSeek => false; + + public override bool CanWrite => false; + + public override long Length => throw new NotSupportedException(); + + public override long Position + { + get => throw new NotSupportedException(); + set => throw new NotSupportedException(); + } + + public override int Read(byte[] buffer, int offset, int count) + { + int read = inner.Read(buffer, offset, count); + counter.Add(read, markup); + return read; + } + + public override void Flush() + { + } + + public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException(); + + public override void SetLength(long value) => throw new NotSupportedException(); + + public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException(); + + protected override void Dispose(bool disposing) + { + if (disposing) + { + inner.Dispose(); + } + + base.Dispose(disposing); + } + } +} diff --git a/src/TriasDev.Templify.Builder/PublicAPI.Unshipped.txt b/src/TriasDev.Templify.Builder/PublicAPI.Unshipped.txt index aa2736c..a36bc9d 100644 --- a/src/TriasDev.Templify.Builder/PublicAPI.Unshipped.txt +++ b/src/TriasDev.Templify.Builder/PublicAPI.Unshipped.txt @@ -811,3 +811,15 @@ [TPLB001]TriasDev.Templify.Builder.LoopInfo.Number.get -> TriasDev.Templify.Builder.TemplatePath [TPLB001]TriasDev.Templify.Builder.LoopItem.Loop.get -> TriasDev.Templify.Builder.LoopInfo! [TPLB001]TriasDev.Templify.Builder.LoopItem.Loop.get -> TriasDev.Templify.Builder.LoopInfo! +[TPLB001]TriasDev.Templify.Builder.Json.TemplateJsonImportOptions.MaximumLength.get -> int +[TPLB001]TriasDev.Templify.Builder.Json.TemplateJsonImportOptions.MaximumLength.init -> void +[TPLB001]TriasDev.Templify.Builder.Json.TemplateJsonImportOptions.MaximumValues.get -> int +[TPLB001]TriasDev.Templify.Builder.Json.TemplateJsonImportOptions.MaximumValues.init -> void +[TPLB001]TriasDev.Templify.Builder.TemplateCheckOptions.MaximumEntries.get -> int +[TPLB001]TriasDev.Templify.Builder.TemplateCheckOptions.MaximumEntries.init -> void +[TPLB001]TriasDev.Templify.Builder.TemplateCheckOptions.MaximumUnpackedSize.get -> long +[TPLB001]TriasDev.Templify.Builder.TemplateCheckOptions.MaximumUnpackedSize.init -> void +[TPLB001]TriasDev.Templify.Builder.TemplateCheckOptions.MaximumMarkupSize.get -> long +[TPLB001]TriasDev.Templify.Builder.TemplateCheckOptions.MaximumMarkupSize.init -> void +[TPLB001]TriasDev.Templify.Builder.TemplateCheckOptions.MaximumParagraphLength.get -> int +[TPLB001]TriasDev.Templify.Builder.TemplateCheckOptions.MaximumParagraphLength.init -> void diff --git a/src/TriasDev.Templify.Builder/TemplateCheck.cs b/src/TriasDev.Templify.Builder/TemplateCheck.cs index 0946aa4..0042a72 100644 --- a/src/TriasDev.Templify.Builder/TemplateCheck.cs +++ b/src/TriasDev.Templify.Builder/TemplateCheck.cs @@ -58,6 +58,24 @@ public sealed record TemplateCheckOptions /// versioned component the host uses should be registered. /// public ComponentCatalog? Components { get; init; } + + /// + /// Gets the most entries the package may have; more is TB9300 and the check stops. Default: 1,000. Upload limits + /// are counted while reading, since a package can declare false sizes. + /// + public int MaximumEntries { get; init; } = 1000; + + /// Gets the most bytes all entries may unpack to; more is TB9300 at the entry that crosses it. Default: 64 MiB. + public long MaximumUnpackedSize { get; init; } = 64L * 1024 * 1024; + + /// + /// Gets the most bytes the XML entries (by their content, whatever their name: what the engine parses) may unpack + /// to; more is TB9300 at the entry that crosses it. Default: 8 MiB. + /// + public long MaximumMarkupSize { get; init; } = 8L * 1024 * 1024; + + /// Gets the most characters of text one paragraph may have; more is TB9300 at the paragraph. Default: 20,000. + public int MaximumParagraphLength { get; init; } = 20_000; } /// The result of or . diff --git a/src/TriasDev.Templify.Builder/TemplateInspector.cs b/src/TriasDev.Templify.Builder/TemplateInspector.cs index a9db156..c735d43 100644 --- a/src/TriasDev.Templify.Builder/TemplateInspector.cs +++ b/src/TriasDev.Templify.Builder/TemplateInspector.cs @@ -44,6 +44,11 @@ public static TemplateCheckResult Check(Stream template, TemplateCheckOptions op ArgumentNullException.ThrowIfNull(template); ArgumentNullException.ThrowIfNull(options); byte[] bytes = ReadAll(template); + if (PackageLimits.Check(bytes, options) is { } tooLarge) + { + return new TemplateCheckResult(TemplateFormat.Unknown, null, [tooLarge]); + } + TemplateFormat format = DetectFormat(bytes); TemplateStamp? stamp = ReadStamp(bytes, format); List problems = new List(); diff --git a/src/TriasDev.Templify.Builder/Typed/DataCatalog.cs b/src/TriasDev.Templify.Builder/Typed/DataCatalog.cs index b9b0c9f..bd4106f 100644 --- a/src/TriasDev.Templify.Builder/Typed/DataCatalog.cs +++ b/src/TriasDev.Templify.Builder/Typed/DataCatalog.cs @@ -109,11 +109,11 @@ public string ToJson() } /// - /// Builds data in which every path of the catalogue exists: values are the text "x", collections hold - /// items, and an open shape is an with the given names. + /// Builds data in which every path of the catalogue exists: values are the text "x", a collection answers + /// every index below with one shared item and enumerates it once, and an open shape is an with the given names. /// /// The names an open shape has (at any depth below it); null for none. - /// How many items every collection holds (an index [n] needs n + 1). + /// How many items every collection answers by index (an index [n] needs n + 1). internal IReadOnlyDictionary CreateWitness(IEnumerable? openNames = null, int items = 1) { OpenWitness open = new OpenWitness(openNames ?? []); @@ -139,7 +139,7 @@ public string ToJson() return open; case DataKind.Collection: object? item = byPath.TryGetValue(entry.Path + "[]", out DataCatalogEntry? itemEntry) ? Witness(itemEntry) : "x"; - return Enumerable.Repeat(item, items).ToList(); + return new WitnessList(item, items); default: return ObjectWitness(entry.Path); } diff --git a/src/TriasDev.Templify.Builder/Typed/WitnessList.cs b/src/TriasDev.Templify.Builder/Typed/WitnessList.cs new file mode 100644 index 0000000..b9c6f40 --- /dev/null +++ b/src/TriasDev.Templify.Builder/Typed/WitnessList.cs @@ -0,0 +1,62 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Collections; + +namespace TriasDev.Templify.Builder; + +/// +/// A collection of witness data: every index below reads the one shared item, and enumerating it +/// gives that item once. The engine indexes through and loops through , +/// so lines[999].name resolves while every loop runs once: witness data stays linear in the contract, and a fill +/// with it linear in the template, whatever indexes and nested loops it has (#302). +/// +internal sealed class WitnessList : IList +{ + private readonly object? _item; + + public WitnessList(object? item, int count) + { + _item = item; + Count = Math.Max(1, count); + } + + // Count is public, as on List: a template may read it. The other members are explicit, so a path cannot read a + // name (SyncRoot, IsReadOnly) that real data's lists do not offer. + public int Count { get; } + + bool IList.IsFixedSize => true; + + bool IList.IsReadOnly => true; + + bool ICollection.IsSynchronized => false; + + object ICollection.SyncRoot => this; + + public object? this[int index] + { + get => index >= 0 && index < Count ? _item : throw new ArgumentOutOfRangeException(nameof(index)); + set => throw new NotSupportedException(); + } + + public IEnumerator GetEnumerator() + { + yield return _item; + } + + public int Add(object? value) => throw new NotSupportedException(); + + public void Clear() => throw new NotSupportedException(); + + public bool Contains(object? value) => Equals(value, _item); + + public int IndexOf(object? value) => Contains(value) ? 0 : -1; + + public void Insert(int index, object? value) => throw new NotSupportedException(); + + public void Remove(object? value) => throw new NotSupportedException(); + + public void RemoveAt(int index) => throw new NotSupportedException(); + + public void CopyTo(Array array, int index) => array.SetValue(_item, index); +} diff --git a/tests/TriasDev.Templify.Builder.Tests/DataContractTests.cs b/tests/TriasDev.Templify.Builder.Tests/DataContractTests.cs index 3aef90c..dc780c3 100644 --- a/tests/TriasDev.Templify.Builder.Tests/DataContractTests.cs +++ b/tests/TriasDev.Templify.Builder.Tests/DataContractTests.cs @@ -108,9 +108,9 @@ public void Witness_HasEveryPathWithOneItemPerCollection() Dictionary order = Assert.IsType>(witness["order"]); Assert.Equal("x", order["number"]); - Dictionary line = Assert.IsType>(Assert.Single(Assert.IsType>(order["lines"]))); + Dictionary line = Assert.IsType>(Assert.Single(Assert.IsAssignableFrom(order["lines"]).Cast())); Assert.Equal("x", line["description"]); - Assert.Equal("x", Assert.Single(Assert.IsType>(line["tags"]))); + Assert.Equal("x", Assert.Single(Assert.IsAssignableFrom(line["tags"]).Cast())); Assert.Equal("x", ((Dictionary)((Dictionary)order["customer"]!)["address"]!)["city"]); } diff --git a/tests/TriasDev.Templify.Builder.Tests/InputLimitTests.cs b/tests/TriasDev.Templify.Builder.Tests/InputLimitTests.cs new file mode 100644 index 0000000..92d6ecd --- /dev/null +++ b/tests/TriasDev.Templify.Builder.Tests/InputLimitTests.cs @@ -0,0 +1,591 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Diagnostics; +using TriasDev.Templify.Builder.Json; +using TriasDev.Templify.Core; + +namespace TriasDev.Templify.Builder.Tests; + +/// #302: Check, Preview and Patch stay fast and small on input the host does not control. +public sealed class InputLimitTests +{ + // Generous for slow CI runners; the allocation bound is the real guard. + private static readonly TimeSpan _fast = TimeSpan.FromSeconds(3); + private const long Small = 100L * 1024 * 1024; + + public static TheoryData Formats => new TheoryData(BuilderHarness.Formats); + + private sealed record Note(string Text); + + private sealed record Part(string Name, List Notes); + + private sealed record Line(string Description, List Parts); + + private sealed record Order(List Lines); + + private sealed record Root(Order Order); + + /// Runs and asserts it was fast and allocated little on this thread. + internal static T Bounded(Func action) + { + long before = GC.GetAllocatedBytesForCurrentThread(); + Stopwatch watch = Stopwatch.StartNew(); + T result = action(); + watch.Stop(); + long allocated = GC.GetAllocatedBytesForCurrentThread() - before; + Assert.True(watch.Elapsed < _fast, $"took {watch.Elapsed}"); + Assert.True(allocated < Small, $"allocated {allocated / (1024 * 1024)} MB"); + return result; + } + + private static GeneratedTemplate IndexedUpload(TemplateFormat format, int loops) => + BuilderHarness.Build(new TestDefinition(t => t.Content(c => + { + TemplatePath order = t.Data["order"]; + c.Paragraph(x => x.Value(order["lines[999].description"])); + c.ForEach(order["lines"], "line", (line, b) => + { + b.Paragraph(line["description"]); + if (loops < 2) + { + return; + } + + b.ForEach(line["parts"], "part", (part, p) => + { + p.Paragraph(part["name"]); + if (loops < 3) + { + return; + } + + p.ForEach(part["notes"], "note", (note, n) => n.Paragraph(note["text"])); + }); + }); + })), format); + + [Theory] + [InlineData(TemplateFormat.Docx, 2)] + [InlineData(TemplateFormat.Docx, 3)] + [InlineData(TemplateFormat.Odt, 3)] + public void Check_IndexedPlaceholderAndNestedLoops_IsFastAndSmall(TemplateFormat format, int loops) + { + GeneratedTemplate upload = IndexedUpload(format, loops); + TemplateCheckResult result = Bounded(() => TemplateInspector.Check(upload.OpenRead(), new TemplateCheckOptions { Data = DataCatalog.From() })); + Assert.DoesNotContain(result.Problems, p => p.Severity == TemplateCheckSeverity.Error); + } + + [Theory] + [InlineData(99)] + [InlineData(999)] + public void Preview_DeepIndexedPath_IsFastAndSmall(int index) + { + string json = $$$""" + { "templifyDefinition": 1, "identity": { "id": "deep", "version": 1 }, + "content": [ "{{c0[{{{index}}}].c1[{{{index}}}].c2[{{{index}}}].leaf}}" ] } + """; + TemplatePreview preview = Bounded(() => TemplateJson.Preview(json, new TemplateJsonImportOptions(), BuilderHarness.Options(TemplateFormat.Docx))); + Assert.Equal(TemplateCheckStatus.Ok, preview.Check.Status); + Assert.Equal("x", preview.Text!.Trim()); + } + + [Theory] + [MemberData(nameof(Formats))] + public void Witness_IndexedItemResolves_AndLoopsRunOnce(TemplateFormat format) + { + TestDefinition definition = new TestDefinition(t => t.Content(c => + { + TemplatePath order = t.Data["order"]; + c.Paragraph(x => x.Text("at ").Value(order["lines[4].description"])); + c.ForEach(order["lines"], "line", (line, b) => b.Paragraph(x => x.Text("item ").Value(line["description"]))); + })); + GeneratedTemplate template = BuilderHarness.Build(definition, format); + (_, byte[] filled) = BuilderHarness.BuildAndFill(definition, format, template.Contract.CreateWitness()); + List texts = BuilderHarness.ParagraphTexts(format, filled); + Assert.Contains("at x", texts); + Assert.Single(texts, t => t == "item x"); + } +} + +/// #302: the size of a JSON definition is limited (TB9206). +public sealed class DefinitionLimitTests +{ + private static string Definition(int paragraphs) => + """{ "templifyDefinition": 1, "identity": { "id": "size", "version": 1 }, "content": [ """ + + string.Join(", ", Enumerable.Repeat("\"Hello\"", paragraphs)) + + " ] }"; + + // Values: the root, its version, the identity object with two values, the content array, one string per paragraph. + private static int Values(int paragraphs) => 6 + paragraphs; + + [Fact] + public void Length_JustBelow_Imports_JustAbove_IsTB9206() + { + string json = Definition(10); + TemplateJson.Import(json, new TemplateJsonImportOptions { MaximumLength = json.Length }); + + TemplateBuildException exception = Assert.Throws(() => TemplateJson.Import(json, new TemplateJsonImportOptions { MaximumLength = json.Length - 1 })); + BuildDiagnostic error = Assert.Single(exception.Errors); + Assert.Equal("TB9206", error.Code); + Assert.Equal(string.Empty, error.Location); + } + + [Fact] + public void Values_JustBelow_Imports_JustAbove_IsTB9206() + { + string json = Definition(10); + TemplateJson.Import(json, new TemplateJsonImportOptions { MaximumValues = Values(10) }); + + TemplateBuildException exception = Assert.Throws(() => TemplateJson.Import(json, new TemplateJsonImportOptions { MaximumValues = Values(10) - 1 })); + Assert.Equal("TB9206", Assert.Single(exception.Errors).Code); + } + + [Fact] + public void Defaults_AreDocumented() + { + TemplateJsonImportOptions options = new TemplateJsonImportOptions(); + Assert.Equal(1_000_000, options.MaximumLength); + Assert.Equal(100_000, options.MaximumValues); + } + + [Fact] + public void CheckDefinition_ReportsTheLimit() + { + TemplateCheckResult result = TemplateInspector.CheckDefinition(Definition(10), new TemplateJsonImportOptions { Data = DataCatalog.From(), MaximumValues = 5 }); + Assert.Equal(TemplateCheckStatus.Broken, result.Status); + Assert.Equal("TB9206", Assert.Single(result.Problems).Code); + } +} + +/// #302: a JSON Patch cannot grow a definition without bound (TB9207 at the operation). +public sealed class PatchLimitTests +{ + private const string Definition = """{"templifyDefinition":1,"identity":{"id":"patch","version":1},"content":["Hello","World"]}"""; + + private static TemplatePatchResult Patch(string patch, int maximumLength = 1_000_000) => + TemplateJson.Patch(Definition, patch, new TemplateJsonImportOptions { Data = DataCatalog.From(), MaximumLength = maximumLength }); + + private static TemplateCheckProblem Refused(TemplatePatchResult result, string location) + { + Assert.False(result.Applied); + Assert.Equal(Definition, result.Json); + TemplateCheckProblem problem = Assert.Single(result.Check.Problems); + Assert.Equal("TB9207", problem.Code); + Assert.Equal(location, problem.Location); + return problem; + } + + private static string Operations(IEnumerable operations) => "[" + string.Join(",", operations) + "]"; + + [Fact] + public void SelfCopies_AreRefused() + { + string patch = Operations(Enumerable.Repeat("""{"op":"copy","from":"/content","path":"/content/-"}""", 23)); + TemplatePatchResult result = InputLimitTests.Bounded(() => Patch(patch)); + Refused(result, "/0"); + } + + [Fact] + public void DoublingCopies_StopAtTheSizeLimit() + { + string patch = Operations(Enumerable.Range(0, 23).SelectMany(_ => new[] + { + """{"op":"copy","from":"/content","path":"/b"}""", + """{"op":"copy","from":"/b","path":"/content/-"}""", + })); + TemplatePatchResult result = InputLimitTests.Bounded(() => Patch(patch)); + Assert.False(result.Applied); + Assert.Equal("TB9207", Assert.Single(result.Check.Problems).Code); + } + + [Fact] + public void Size_JustBelow_Applies_JustAbove_IsRefused() + { + // The copied value "Hello" is 7 characters of JSON. + const string patch = """[{"op":"copy","from":"/content/0","path":"/content/-"}]"""; + TemplatePatchResult fits = Patch(patch, Definition.Length + 7); + Assert.True(fits.Applied); + Assert.DoesNotContain(fits.Check.Problems, p => p.Code == "TB9207"); + + Refused(Patch(patch, Definition.Length + 6), "/0"); + } + + [Fact] + public void Removing_MakesRoomAgain() + { + // The second paragraph is longer than the patch, so the patch itself is within the limit. + string stored = Definition.Replace("World", new string('W', 200), StringComparison.Ordinal); + const string patch = """[{"op":"remove","path":"/content/1"},{"op":"copy","from":"/content/0","path":"/content/-"}]"""; + Assert.True(TemplateJson.Patch(stored, patch, new TemplateJsonImportOptions { Data = DataCatalog.From(), MaximumLength = stored.Length }).Applied); + } + + [Fact] + public void CopyIntoItsOwnSource_IsRefused() + { + Refused(Patch("""[{"op":"add","path":"/x","value":{"a":[]}},{"op":"copy","from":"/x","path":"/x/a/-"}]"""), "/1"); + } + + [Fact] + public void Operations_JustBelow_Apply_JustAbove_AreRefused() + { + const string test = """{"op":"test","path":"/templifyDefinition","value":1}"""; + Assert.True(Patch(Operations(Enumerable.Repeat(test, 1000))).Applied); + Refused(Patch(Operations(Enumerable.Repeat(test, 1001))), "/1000"); + } + + [Fact] + public void TooDeep_IsRefused_NoException() + { + string deep = new string('[', 60) + new string(']', 60); + string patch = $$""" + [{"op":"add","path":"/a","value":{{deep}}}, + {"op":"add","path":"/b","value":{{deep}}}, + {"op":"copy","from":"/a","path":"/b/0/0/0/0/0/-"}] + """; + Refused(Patch(patch), "/2"); + } +} + +/// #302: Check reads an upload within limits (TB9300 at the entry), counted while reading. +public sealed class UploadLimitTests +{ + public static TheoryData Formats => new TheoryData(BuilderHarness.Formats); + + private static byte[] Upload(TemplateFormat format, string text = "Hello") => + BuilderHarness.Build(new TestDefinition(t => t.Content(c => c.Paragraph(text))), format).Content.ToArray(); + + private static TemplateCheckResult Check(byte[] upload, Func? limits = null) => + TemplateInspector.Check(new MemoryStream(upload), (limits ?? (o => o))(new TemplateCheckOptions { Data = DataCatalog.From() })); + + private static List<(string Name, long Length)> Entries(byte[] upload) + { + using System.IO.Compression.ZipArchive archive = new System.IO.Compression.ZipArchive(new MemoryStream(upload), System.IO.Compression.ZipArchiveMode.Read); + return archive.Entries.Select(e => (e.FullName, e.Length)).ToList(); + } + + private static void AssertOk(TemplateCheckResult result) => + Assert.DoesNotContain(result.Problems, p => p.Severity == TemplateCheckSeverity.Error); + + private static TemplateCheckProblem AssertLimit(TemplateCheckResult result, string location) + { + TemplateCheckProblem problem = Assert.Single(result.Problems); + Assert.Equal("TB9300", problem.Code); + Assert.Equal(TemplateCheckSeverity.Error, problem.Severity); + Assert.Equal(location, problem.Location); + return problem; + } + + /// The entry at which a running total of the selected entries first exceeds . + private static string Crossing(byte[] upload, long limit, Func counted) + { + long total = 0; + foreach ((string name, long length) in Entries(upload).Where(e => counted(e.Name))) + { + total += length; + if (total > limit) + { + return name; + } + } + + throw new InvalidOperationException("never crossed"); + } + + private static bool IsMarkup(string name) => name.EndsWith(".xml", StringComparison.OrdinalIgnoreCase) || name.EndsWith(".rels", StringComparison.OrdinalIgnoreCase); + + [Fact] + public void Defaults_AreDocumented() + { + TemplateCheckOptions options = new TemplateCheckOptions { Data = DataCatalog.From() }; + Assert.Equal(1000, options.MaximumEntries); + Assert.Equal(64L * 1024 * 1024, options.MaximumUnpackedSize); + Assert.Equal(8L * 1024 * 1024, options.MaximumMarkupSize); + Assert.Equal(20_000, options.MaximumParagraphLength); + } + + [Theory] + [MemberData(nameof(Formats))] + public void Entries_JustBelow_Ok_JustAbove_TB9300(TemplateFormat format) + { + byte[] upload = Upload(format); + List<(string Name, long Length)> entries = Entries(upload); + AssertOk(Check(upload, o => o with { MaximumEntries = entries.Count })); + AssertLimit(Check(upload, o => o with { MaximumEntries = entries.Count - 1 }), entries[^1].Name); + } + + [Theory] + [MemberData(nameof(Formats))] + public void UnpackedSize_JustBelow_Ok_JustAbove_TB9300(TemplateFormat format) + { + byte[] upload = Upload(format); + long total = Entries(upload).Sum(e => e.Length); + AssertOk(Check(upload, o => o with { MaximumUnpackedSize = total })); + AssertLimit(Check(upload, o => o with { MaximumUnpackedSize = total - 1 }), Crossing(upload, total - 1, _ => true)); + } + + [Theory] + [MemberData(nameof(Formats))] + public void MarkupSize_JustBelow_Ok_JustAbove_TB9300(TemplateFormat format) + { + byte[] upload = Upload(format); + long markup = Entries(upload).Where(e => IsMarkup(e.Name)).Sum(e => e.Length); + AssertOk(Check(upload, o => o with { MaximumMarkupSize = markup })); + AssertLimit(Check(upload, o => o with { MaximumMarkupSize = markup - 1 }), Crossing(upload, markup - 1, IsMarkup)); + } + + [Theory] + [MemberData(nameof(Formats))] + public void ParagraphLength_JustBelow_Ok_JustAbove_TB9300(TemplateFormat format) + { + byte[] upload = Upload(format, new string('a', 100)); + AssertOk(Check(upload, o => o with { MaximumParagraphLength = 100 })); + TemplateCheckProblem problem = AssertLimit(Check(upload, o => o with { MaximumParagraphLength = 99 }), BuilderHarness.MainPart(format) + ", paragraph 1"); + Assert.Contains("MaximumParagraphLength", problem.Message, StringComparison.Ordinal); + } + + [Fact] + public void ManyUnterminatedTags_InOneParagraph_AreFast() + { + byte[] upload = BuilderHarness.EditEntry(Upload(TemplateFormat.Docx, "PLACEHOLDER"), "word/document.xml", + xml => xml.Replace("PLACEHOLDER", string.Concat(Enumerable.Repeat("{{#if a ", 80_000)), StringComparison.Ordinal)); + TemplateCheckResult result = InputLimitTests.Bounded(() => Check(upload)); + AssertLimit(result, "word/document.xml, paragraph 1"); + } + + [Fact] + public void ALyingDeclaredSize_IsCountedWhileReading() + { + // The central directory says 1 byte for document.xml; the stream still yields the whole part. + byte[] upload = Upload(TemplateFormat.Docx); + long real = Entries(upload).Single(e => e.Name == "word/document.xml").Length; + byte[] lying = SetDeclaredSize(upload, "word/document.xml", 1); + TemplateCheckResult result = Check(lying, o => o with { MaximumUnpackedSize = real - 1 }); + Assert.Contains(result.Problems, p => p.Code == "TB9300" && p.Message.Contains("MaximumUnpackedSize", StringComparison.Ordinal)); + } + + /// Overwrites the uncompressed size of an entry in the local header and the central directory. + private static byte[] SetDeclaredSize(byte[] zip, string name, uint size) + { + byte[] copy = (byte[])zip.Clone(); + byte[] nameBytes = System.Text.Encoding.UTF8.GetBytes(name); + for (int i = 0; i + 46 < copy.Length; i++) + { + uint signature = BitConverter.ToUInt32(copy, i); + if (signature == 0x04034b50 && copy.AsSpan(i + 30, nameBytes.Length).SequenceEqual(nameBytes)) + { + BitConverter.TryWriteBytes(copy.AsSpan(i + 22, 4), size); + } + else if (signature == 0x02014b50 && copy.AsSpan(i + 46, Math.Min(nameBytes.Length, copy.Length - i - 46)).SequenceEqual(nameBytes)) + { + BitConverter.TryWriteBytes(copy.AsSpan(i + 24, 4), size); + } + } + + return copy; + } +} + +/// #302: no definition within the import limits makes Preview, CheckDefinition or Check grow out of bounds. +public sealed class LimitPropertyTests +{ + private sealed record Root(System.Text.Json.JsonElement Data); + + public static TheoryData Seeds => new TheoryData(Enumerable.Range(0, 12)); + + /// Loops nested deep, and in the innermost body a path indexed at every level. + private static string Definition(int depth, int index) + { + string indexed = "data." + string.Join(".", Enumerable.Range(0, depth).Select(level => $"c{level}[{index}]")) + ".leaf"; + string body = $$$"""[ "{{l{{{depth - 1}}}.leaf}} {{{{{indexed}}}}}" ]"""; + for (int level = depth - 1; level >= 0; level--) + { + string collection = level == 0 ? "data.c0" : $"l{level - 1}.c{level}"; + body = $$"""[ { "forEach": "{{collection}}", "as": "l{{level}}", "body": {{body}} } ]"""; + } + + return $$"""{ "templifyDefinition": 1, "identity": { "id": "nested", "version": 1 }, "content": {{body}} }"""; + } + + [Theory] + [MemberData(nameof(Seeds))] + public void RandomNestingAndIndexes_StayBounded(int seed) + { + Random random = new Random(302 + seed); + int depth = random.Next(1, 7); + int index = random.Next(0, 1000); + string json = Definition(depth, index); + TemplateJsonImportOptions import = new TemplateJsonImportOptions { Data = DataCatalog.From() }; + + TemplatePreview preview = InputLimitTests.Bounded(() => TemplateJson.Preview(json, import, BuilderHarness.Options(TemplateFormat.Docx))); + Assert.Equal(TemplateCheckStatus.Ok, preview.Check.Status); + + Assert.Equal(TemplateCheckStatus.Ok, InputLimitTests.Bounded(() => TemplateInspector.CheckDefinition(json, import)).Status); + + foreach (TemplateFormat format in BuilderHarness.Formats) + { + GeneratedTemplate upload = TemplateBuilder.Build(TemplateJson.Import(json, import), BuilderHarness.Options(format)); + TemplateCheckResult check = InputLimitTests.Bounded(() => TemplateInspector.Check(upload.OpenRead(), new TemplateCheckOptions { Data = DataCatalog.From() })); + Assert.DoesNotContain(check.Problems, p => p.Severity == TemplateCheckSeverity.Error); + } + } +} + +/// #302 review: the limits cannot be switched off by naming or by one unreadable entry; patches stay bounded. +public sealed class LimitReviewTests +{ + private const string LongParagraph = "PLACEHOLDER"; + + private static byte[] Upload() => + BuilderHarness.Build(new TestDefinition(t => t.Content(c => c.Paragraph(LongParagraph))), TemplateFormat.Docx).Content.ToArray(); + + private static string Unterminated => string.Concat(Enumerable.Repeat("{{#if a ", 80_000)); + + private static TemplateCheckResult Check(byte[] upload) => + TemplateInspector.Check(new MemoryStream(upload), new TemplateCheckOptions { Data = DataCatalog.From() }); + + /// Rewrites a package: each entry through (null drops it), with entries in front. + private static byte[] Rewrite(byte[] package, Func map, params (string Name, byte[] Data)[] first) + { + using MemoryStream output = new MemoryStream(); + using (System.IO.Compression.ZipArchive target = new System.IO.Compression.ZipArchive(output, System.IO.Compression.ZipArchiveMode.Create, leaveOpen: true)) + using (System.IO.Compression.ZipArchive source = new System.IO.Compression.ZipArchive(new MemoryStream(package), System.IO.Compression.ZipArchiveMode.Read)) + { + foreach ((string name, byte[] data) in first) + { + using Stream s = target.CreateEntry(name, System.IO.Compression.CompressionLevel.NoCompression).Open(); + s.Write(data); + } + + foreach (System.IO.Compression.ZipArchiveEntry entry in source.Entries) + { + using StreamReader reader = new StreamReader(entry.Open()); + if (map(entry.FullName, reader.ReadToEnd()) is { } mapped) + { + using StreamWriter writer = new StreamWriter(target.CreateEntry(mapped.Name).Open()); + writer.Write(mapped.Text); + } + } + } + + return output.ToArray(); + } + + [Fact] + public void MainPartNotNamedXml_IsStillMarkup() + { + byte[] upload = Rewrite(Upload(), (name, text) => name switch + { + "word/document.xml" => ("word/document.bin", text.Replace(LongParagraph, Unterminated, StringComparison.Ordinal)), + "word/_rels/document.xml.rels" => ("word/_rels/document.bin.rels", text), + _ => (name, text.Replace("word/document.xml", "word/document.bin", StringComparison.Ordinal) + .Replace("/word/document.xml", "/word/document.bin", StringComparison.Ordinal)), + }); + TemplateCheckResult result = InputLimitTests.Bounded(() => Check(upload)); + TemplateCheckProblem problem = Assert.Single(result.Problems); + Assert.Equal("TB9300", problem.Code); + Assert.Equal("word/document.bin, paragraph 1", problem.Location); + } + + [Fact] + public void AnUnreadableEntry_DoesNotSwitchOffTheLimits() + { + byte[] upload = Rewrite( + Upload(), + (name, text) => (name, text.Replace(LongParagraph, Unterminated, StringComparison.Ordinal)), + ("junk.bin", new byte[] { 1, 2, 3, 4 })); + upload = SetCompressionMethod(upload, "junk.bin", 99); + TemplateCheckResult result = InputLimitTests.Bounded(() => Check(upload)); + Assert.Contains(result.Problems, p => p.Code == "TB9300" && p.Location == "word/document.xml, paragraph 1"); + } + + private static byte[] SetCompressionMethod(byte[] zip, string name, ushort method) + { + byte[] nameBytes = System.Text.Encoding.UTF8.GetBytes(name); + for (int i = 0; i + 46 + nameBytes.Length < zip.Length; i++) + { + uint signature = BitConverter.ToUInt32(zip, i); + if (signature == 0x04034b50 && zip.AsSpan(i + 30, nameBytes.Length).SequenceEqual(nameBytes)) + { + BitConverter.TryWriteBytes(zip.AsSpan(i + 8, 2), method); + } + else if (signature == 0x02014b50 && zip.AsSpan(i + 46, nameBytes.Length).SequenceEqual(nameBytes)) + { + BitConverter.TryWriteBytes(zip.AsSpan(i + 10, 2), method); + } + } + + return zip; + } + + private static string Stored(int strings) => + """{"templifyDefinition":1,"identity":{"id":"big","version":1},"content":[""" + string.Join(",", Enumerable.Repeat("\"Hello world\"", strings)) + "]}"; + + private static TemplatePatchResult Patch(string json, string patch) => + TemplateJson.Patch(json, patch, new TemplateJsonImportOptions { Data = DataCatalog.From() }); + + [Fact] + public void DeeplyNestedValue_DoesNotInflateTheResult() + { + string value = new string('[', 60) + string.Join(",", Enumerable.Repeat("0", 300_000)) + new string(']', 60); + TemplatePatchResult result = InputLimitTests.Bounded(() => Patch(Stored(2), $$"""[{"op":"add","path":"/x","value":{{value}}}]""")); + Assert.True(result.Json.Length <= 1_000_000, $"result has {result.Json.Length} characters"); + } + + [Fact] + public void RepeatedMoves_OfALargeDefinition_AreCheap() + { + string stored = Stored(60_000); + string patch = "[" + string.Join(",", Enumerable.Range(0, 500).SelectMany(_ => new[] + { + """{"op":"move","from":"/content","path":"/t"}""", + """{"op":"move","from":"/t","path":"/content"}""", + })) + "]"; + TemplatePatchResult result = InputLimitTests.Bounded(() => Patch(stored, patch)); + Assert.True(result.Applied); + } + + [Fact] + public void RepeatedCopyAndRemove_OfALargeDefinition_IsRefused() + { + string stored = Stored(30_000); + string patch = "[" + string.Join(",", Enumerable.Range(0, 500).SelectMany(_ => new[] + { + """{"op":"copy","from":"/content","path":"/t"}""", + """{"op":"remove","path":"/t"}""", + })) + "]"; + TemplatePatchResult result = InputLimitTests.Bounded(() => Patch(stored, patch)); + Assert.False(result.Applied); + Assert.Equal("TB9207", Assert.Single(result.Check.Problems).Code); + } + + [Theory] + [InlineData("""[{"op":"add","path":"/content/-","value":"\ud800"}]""")] + [InlineData("""[{"op":"test","path":"/content/0","value":"\ud800"}]""")] + public void LoneSurrogate_IsAProblem_NotAnException(string patch) + { + TemplatePatchResult result = Patch(Stored(2), patch); + Assert.False(result.Applied); + Assert.Equal("TB9207", Assert.Single(result.Check.Problems).Code); + } + + [Fact] + public void APatchLongerThanTheDefinitionLimit_IsRefused() + { + string patch = """[{"op":"add","path":"/x","value":" """ + new string('a', 200) + "\"}]"; + TemplatePatchResult result = TemplateJson.Patch(Stored(2), patch, new TemplateJsonImportOptions { Data = DataCatalog.From(), MaximumLength = 150 }); + Assert.False(result.Applied); + TemplateCheckProblem problem = Assert.Single(result.Check.Problems); + Assert.Equal("TB9207", problem.Code); + Assert.Equal(string.Empty, problem.Location); + } + + [Fact] + public void WitnessList_ExposesOnlyCount_AsAProperty() + { + // Paths resolve public properties: a witness must not offer names that real lists do not (SyncRoot, IsReadOnly…). + string[] names = typeof(WitnessList).GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance) + .Where(p => p.GetIndexParameters().Length == 0).Select(p => p.Name).ToArray(); + Assert.Equal(["Count"], names); + } +}