Compare commits

..
Author SHA1 Message Date
james.maesandClaude Fable 5.2 b095d1a183 fix(rendering): refuse unsupported markup as an error and keep large documents linear
node / node (push) Successful in 14s
build / scripts (push) Successful in 14s
windows / windows (push) Successful in 1m57s
build / windows (push) Successful in 1m57s
Element nesting is bounded before any library walks the parsed tree: a
count kept while tokens arrive stops runaway input early, and an exact
measurement of the parsed tree applies the limit of 256 levels. The
renderer parses once with the sanitizer's own settings and sanitizes that
tree, so the bound is enforced between the parse and the sanitizer's
passes. Deeper markup is an ArgumentException, which the reader already
reports as an unsupported document.

An unterminated script or comment can report a text run past the end of
its block, and malformed markup can report one that starts inside
another; both are handled instead of failing the open. Raw-text
formatting is applied in one forward pass, and repeated heading titles
continue from the last anchor suffix used, so neither grows with the
square of the document. DocumentOutline accepts a cancellation token that
is honoured between its phases.

The threat model states that nesting is bounded and parse time is not.

Closes #50

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Signed-off-by: James Maes <james@kof22.com>
2026-11-10 17:19:26 -06:00
22 changed files with 605 additions and 281 deletions

No files matched your search

+1 -14
View File
@@ -6,6 +6,7 @@ on:
jobs:
windows:
uses: self:KofTwentyTwo/ci-workflows/.gitea/workflows/windows.yaml@v1
secrets: inherit
with:
commands: |
dotnet restore MarkdownViewr.Windows.slnx -p:Platform=x64 --locked-mode
@@ -15,22 +16,8 @@ jobs:
$env:Platform = 'x64'
dotnet format MarkdownViewr.Windows.slnx --verify-no-changes --severity warn --no-restore
Remove-Item Env:Platform
# The host runner keeps its workspace between runs; the coverage gate must see this run's report only.
if (Test-Path TestResults) { Remove-Item TestResults -Recurse -Force }
dotnet test tests/MarkdownViewr.Windows.Core.Tests --no-build --settings coverage.runsettings --collect:"XPlat Code Coverage" --logger trx --results-directory TestResults
pwsh -NoProfile -File ./build/Assert-Coverage.ps1 -ResultsDirectory TestResults -Packages MarkdownViewr.Windows.Core
# Windows adapters (files, watcher, registry) against the real operating system. The Desktop
# category drives the app with mouse and keyboard and needs an interactive session.
dotnet test tests/MarkdownViewr.Windows.UiTests --no-build --filter "Category!=Desktop" --logger trx --results-directory TestResults
# The runs above include the seeded parser campaigns at 500 iterations. Main and tags repeat
# them at 10000; a filter that matches no test fails, so a renamed category cannot pass unseen.
if ($env:GITHUB_REF -eq 'refs/heads/main' -or $env:GITHUB_REF -like 'refs/tags/*') {
$env:K22_FUZZ_ITERATIONS = '10000'
Write-Output "Parser campaigns at $env:K22_FUZZ_ITERATIONS iterations for $env:GITHUB_REF"
dotnet test tests/MarkdownViewr.Windows.Core.Tests --no-build --filter "Category=Fuzz" -- RunConfiguration.TreatNoTestsAsError=true
dotnet test tests/MarkdownViewr.Windows.UiTests --no-build --filter "Category=Fuzz" -- RunConfiguration.TreatNoTestsAsError=true
Remove-Item Env:K22_FUZZ_ITERATIONS
}
# PowerShell build scripts: analyzer and Pester boundary tests with pinned modules saved to the job's temp directory.
$modules = Join-Path ($env:RUNNER_TEMP ?? [IO.Path]::GetTempPath()) "psmodules-$env:GITHUB_RUN_ID"
New-Item -ItemType Directory -Force -Path $modules | Out-Null
+3 -4
View File
@@ -13,13 +13,12 @@ Use Windows and the .NET 10 SDK selected by `global.json`:
```powershell
dotnet restore MarkdownViewr.Windows.slnx -p:Platform=x64 --locked-mode
dotnet build MarkdownViewr.Windows.slnx -p:Platform=x64 -warnaserror
dotnet test tests/MarkdownViewr.Windows.Core.Tests --no-build --settings coverage.runsettings --collect:'XPlat Code Coverage' --results-directory TestResults # TestResults must start empty
pwsh -NoProfile -File ./build/Assert-Coverage.ps1 -ResultsDirectory TestResults -Packages MarkdownViewr.Windows.Core
dotnet test tests/MarkdownViewr.Windows.UiTests --no-build --filter "Category!=Desktop"
dotnet test tests/MarkdownViewr.Windows.Core.Tests --settings coverage.runsettings --collect:'XPlat Code Coverage' --results-directory TestResults
./build/Assert-Coverage.ps1 -ResultsDirectory TestResults
dotnet format MarkdownViewr.Windows.slnx --verify-no-changes --severity warn --no-restore
```
Desktop tests require an explicitly available interactive desktop. Run `dotnet test tests/MarkdownViewr.Windows.UiTests --no-build --filter "Category=Desktop"` only when input will not interfere with other work. Preserve 100% measured core coverage; use xUnit and deterministic injected time/filesystem boundaries. Follow `Method_Scenario_Expectation` test names.
Desktop tests require an explicitly available interactive desktop. Run `dotnet test tests/MarkdownViewr.Windows.UiTests` only when input will not interfere with other work. Preserve 100% measured core coverage; use xUnit and deterministic injected time/filesystem boundaries. Follow `Method_Scenario_Expectation` test names.
## Style and Contributions
+3 -7
View File
@@ -9,16 +9,12 @@ its Windows desktop reference architecture.
```powershell
dotnet restore MarkdownViewr.Windows.slnx -p:Platform=x64 --locked-mode
dotnet build MarkdownViewr.Windows.slnx -p:Platform=x64 -warnaserror
dotnet test tests/MarkdownViewr.Windows.Core.Tests --no-build --settings coverage.runsettings --collect:"XPlat Code Coverage" --results-directory TestResults # TestResults must start empty
pwsh -NoProfile -File ./build/Assert-Coverage.ps1 -ResultsDirectory TestResults -Packages MarkdownViewr.Windows.Core
dotnet test tests/MarkdownViewr.Windows.UiTests --no-build --filter "Category!=Desktop" # Windows adapters; no window, no input
dotnet test tests/MarkdownViewr.Windows.UiTests --no-build --filter "Category=Desktop" # drives the app with mouse and keyboard
dotnet test MarkdownViewr.Windows.slnx -p:Platform=x64 --no-build --filter "FullyQualifiedName!~UiTests" --settings coverage.runsettings --collect:"XPlat Code Coverage" --results-directory TestResults
./build/Assert-Coverage.ps1 -ResultsDirectory TestResults
dotnet test tests/MarkdownViewr.Windows.UiTests --no-build # launches the app on the desktop
dotnet format MarkdownViewr.Windows.slnx --verify-no-changes --severity warn --no-restore
```
Build through the solution. Passing `-p:Platform=x64` to one test project selects a different
output folder, so a following `--no-build` test run would use stale binaries.
## Rules
- GitHub Flow: topic branch `<type>/<desc>` → PR to `main` → squash merge. Conventional
+1 -1
View File
@@ -30,7 +30,7 @@ This Product follows the [KofTwentyTwo standards](https://github.com/KofTwentyTw
- Preserve original MIT notices and dependency credits.
- Disclose substantial AI assistance and include a `Co-Authored-By:` trailer naming the model.
CI runs on every push and covers the build, formatting, core tests with the coverage gate, Windows adapter tests, parser fuzzing, and tooling tests. It also verifies npm registry signatures, and the NuGet restore reports known vulnerable packages. Desktop and installed-update acceptance, the secret and workflow scans, and CodeQL are not automated at present; [DEVELOPERS.md](DEVELOPERS.md#what-runs-where) lists what to run by hand. Local hooks check the commit title, the sign-off, and secrets.
Required CI covers build/coverage/style, reader and installed-update acceptance, parser fuzzing, tooling tests, dependency/secret/workflow scans, CodeQL, PR title, and DCO.
Under the single-maintainer policy, `review / automated` also requires a genuine current-commit acknowledgement from the configured human maintainer. An agent cannot provide that acknowledgement. See [repository setup](docs/repository-setup.md).
+7 -21
View File
@@ -28,40 +28,26 @@ To isolate preview data, set `MARKDOWNVIEWR_WINDOWS_DATA_DIR` for that process t
## Tests and quality gates
After the solution build above:
```powershell
if (Test-Path TestResults) { Remove-Item TestResults -Recurse -Force }
dotnet test tests/MarkdownViewr.Windows.Core.Tests --no-build --settings coverage.runsettings --collect:"XPlat Code Coverage" --results-directory TestResults
pwsh -NoProfile -File ./build/Assert-Coverage.ps1 -ResultsDirectory TestResults -Packages MarkdownViewr.Windows.Core
dotnet test tests/MarkdownViewr.Windows.UiTests --no-build --filter "Category!=Desktop"
dotnet test tests/MarkdownViewr.Windows.Core.Tests --settings coverage.runsettings --collect:"XPlat Code Coverage" --results-directory TestResults
./build/Assert-Coverage.ps1 -ResultsDirectory TestResults
dotnet format MarkdownViewr.Windows.slnx --verify-no-changes --severity warn --no-restore
npm ci --ignore-scripts
npm run lint
npm test
```
Core tests use xUnit and Coverlet; retain 100% measured core line coverage. The coverage gate reads every report under the results directory, so start from an empty one, and run the gate as its own process: called in-process, a failure does not stop the calling script. Name tests `Method_Scenario_Expectation` and add meaningful regression coverage for fixes. Deterministic tests inject time and filesystem boundaries.
Core tests use xUnit and Coverlet; retain 100% measured core line coverage. Name tests `Method_Scenario_Expectation` and add meaningful regression coverage for fixes. Deterministic tests inject time and filesystem boundaries.
The `UiTests` assembly holds two kinds of test. Adapter tests exercise the Windows file, watcher, and registry code against the real operating system without opening a window. Tests in the `Desktop` category use FlaUI/UIA3 to drive the app with the mouse and keyboard and need an interactive desktop:
Native desktop tests use FlaUI/UIA3 and require an available interactive desktop:
```powershell
dotnet test tests/MarkdownViewr.Windows.UiTests --no-build --filter "Category=Desktop"
dotnet test tests/MarkdownViewr.Windows.UiTests
```
Reserve the desktop before running them. Build through the solution: passing `-p:Platform=x64` to one test project selects a different output folder, and a following `--no-build` run would test stale binaries.
Reserve the desktop before running physical-input tests. Hosted CI also exercises published output and actual stable/dev installation, update/restart, registration, and coexistence. See [installed-update acceptance](docs/installed-updates.md). Synthetic unsigned fixtures do not establish production signing.
For PowerShell, use PSScriptAnalyzer 1.25.0 with `PSScriptAnalyzerSettings.psd1`, then Pester 5.7.1 against `build/*.Tests.ps1`. Reproduce the exact sequential analyzer partitions in [build.yaml](.gitea/workflows/build.yaml); engine exceptions and rule findings are failures.
### What runs where
The repository is hosted on Gitea, with GitHub as a mirror. [build.yaml](.gitea/workflows/build.yaml) runs on every push to any branch: locked restore, zero-warning build, formatting, core tests with the coverage gate, the adapter tests, the seeded parser campaigns, script analysis with Pester, and the JavaScript lint and tests. A pull request shows the result for its head commit.
The workflows under `.github/` belong to the mirror, where GitHub Actions is currently switched off. Until it is switched on again, these checks have no automated run and are run by hand before a release:
- the `Desktop` tests, against a local build and against published output;
- [installed-update acceptance](docs/installed-updates.md): actual stable and development installation, update and restart, registration, and coexistence. Its synthetic unsigned fixtures do not establish production signing;
- secret and workflow scans, and CodeQL.
For PowerShell, use PSScriptAnalyzer 1.25.0 with `PSScriptAnalyzerSettings.psd1`, then Pester 5.7.1 against `build/*.Tests.ps1`. Reproduce the exact sequential analyzer partitions and negative fixtures in [scripts.yml](.github/workflows/scripts.yml); engine exceptions and rule findings are failures.
Run the [seeded parser campaigns](docs/security/fuzzing.md) when changing parser or activation boundaries. Never use private documents as a corpus.
+22 -135
View File
@@ -12,42 +12,25 @@ BeforeAll `
<#
.SYNOPSIS
Writes a synthetic report for one package: one line per entry of -Hits, in one class.
Writes a synthetic report so tests can exercise release-gate exit codes.
#>
function Write-CoverageReport
{
[CmdletBinding()]
param(
[Parameter(Mandatory)] [string] $Directory,
[string] $Package = 'Probe',
[int[]] $Hits = @(1, 1),
# What the report claims in its summary attribute; the gate must not believe it.
[string] $StatedRate = '1'
[Parameter(Mandatory)] [ValidateRange(0, 1)] [double] $Rate
)
$number = 0
$lines = foreach ($count in $Hits) { $number++; "<line number=`"$number`" hits=`"$count`" />" }
$rateText = $Rate.ToString([Globalization.CultureInfo]::InvariantCulture)
$secondLineHits = if ($Rate -eq 1) { 1 } else { 0 }
$report = @"
<coverage line-rate="$StatedRate"><packages><package name="$Package" line-rate="$StatedRate"><classes>
<class filename="$Package.cs"><lines>$($lines -join '')</lines></class>
<coverage><packages><package name="Probe" line-rate="$rateText"><classes>
<class filename="Probe.cs"><lines><line number="1" hits="1" /><line number="2" hits="$secondLineHits" /></lines></class>
</classes></package></packages></coverage>
"@
New-Item -ItemType Directory -Force -Path $Directory | Out-Null
Set-Content -LiteralPath (Join-Path $Directory 'coverage.cobertura.xml') -Value $report
}
<#
.SYNOPSIS
Runs the gate as CI does, in its own process, and returns its exit code and combined output.
#>
function Invoke-CoverageGate
{
[CmdletBinding()]
param([Parameter(ValueFromRemainingArguments)] [string[]] $Arguments)
$output = (& pwsh -NoProfile -File $script:CoverageGate -ResultsDirectory $script:ReportsDirectory @Arguments 2>&1) -join "`n"
[pscustomobject]@{ ExitCode = $LASTEXITCODE; Output = $output }
}
}
Describe 'Required coverage gate' `
@@ -60,128 +43,32 @@ Describe 'Required coverage gate' `
It 'rejects a run that produced no report' `
{
$result = Invoke-CoverageGate -Packages Probe
$result.ExitCode | Should -Be 1
$result.Output | Should -Match 'No coverage.cobertura.xml'
$output = (& pwsh -NoProfile -File $script:CoverageGate -ResultsDirectory $script:ReportsDirectory -Packages Probe 2>&1) -join "`n"
$LASTEXITCODE | Should -Be 1
$output | Should -Match 'No coverage.cobertura.xml'
}
It 'rejects an absent required package' `
{
Write-CoverageReport -Directory $script:ReportsDirectory
$result = Invoke-CoverageGate -Packages Missing
$result.ExitCode | Should -Be 1
$result.Output | Should -Match "'Missing' not found"
Write-CoverageReport -Directory $script:ReportsDirectory -Rate 1
$output = (& pwsh -NoProfile -File $script:CoverageGate -ResultsDirectory $script:ReportsDirectory -Packages Missing 2>&1) -join "`n"
$LASTEXITCODE | Should -Be 1
$output | Should -Match 'Missing.*not found'
}
It 'does not take a longer or differently cased package name for the required one' `
It 'rejects coverage below the required percentage' `
{
Write-CoverageReport -Directory (Join-Path $script:ReportsDirectory 'longer') -Package 'ProbeExtra'
Write-CoverageReport -Directory (Join-Path $script:ReportsDirectory 'cased') -Package 'probe'
$result = Invoke-CoverageGate -Packages Probe
$result.ExitCode | Should -Be 1
$result.Output | Should -Match "'Probe' not found"
}
It 'rejects coverage below the required percentage and names the uncovered lines' `
{
Write-CoverageReport -Directory $script:ReportsDirectory -Hits 1, 0, 1, 0
$result = Invoke-CoverageGate -Packages Probe
$result.ExitCode | Should -Be 1
$result.Output | Should -Match 'Probe line coverage: 50% \(2 of 4 lines'
$result.Output | Should -Match 'uncovered: Probe\.cs lines 2, 4(\s|$)'
$result.Output | Should -Match 'Coverage gate FAILED'
Write-CoverageReport -Directory $script:ReportsDirectory -Rate 0.5
$output = (& pwsh -NoProfile -File $script:CoverageGate -ResultsDirectory $script:ReportsDirectory -Packages Probe 2>&1) -join "`n"
$LASTEXITCODE | Should -Be 1
$output | Should -Match 'Coverage gate FAILED'
}
It 'accepts full coverage of the required package' `
{
Write-CoverageReport -Directory $script:ReportsDirectory
$result = Invoke-CoverageGate -Packages Probe
$result.ExitCode | Should -Be 0
$result.Output | Should -Match 'Probe line coverage: 100% \(2 of 2 lines'
$result.Output | Should -Match 'Coverage gate passed'
}
It 'counts the lines itself instead of believing the stated rate <StatedRate>' -ForEach @(
@{ StatedRate = '1' }
@{ StatedRate = '1.5' }
@{ StatedRate = 'NaN' }
@{ StatedRate = '0,5' }
) `
{
Write-CoverageReport -Directory $script:ReportsDirectory -Hits 1, 0 -StatedRate $StatedRate
$result = Invoke-CoverageGate -Packages Probe
$result.ExitCode | Should -Be 1
$result.Output | Should -Match 'Probe line coverage: 50% \(1 of 2 lines'
}
It 'never shows a package just under the bar as having reached it' `
{
Write-CoverageReport -Directory $script:ReportsDirectory -Hits (@(1) * 19999 + 0)
$result = Invoke-CoverageGate -Packages Probe
$result.ExitCode | Should -Be 1
$result.Output | Should -Match 'Probe line coverage: 99\.99% \(19999 of 20000 lines'
}
It 'rejects a package no report measured a line of' `
{
Write-CoverageReport -Directory $script:ReportsDirectory -Hits @()
$result = Invoke-CoverageGate -Packages Probe
$result.ExitCode | Should -Be 1
$result.Output | Should -Match 'no measured lines'
}
It 'ignores an empty report when another test project measured the package' `
{
Write-CoverageReport -Directory (Join-Path $script:ReportsDirectory 'first') -Hits @()
Write-CoverageReport -Directory (Join-Path $script:ReportsDirectory 'second') -Hits 1, 0
$result = Invoke-CoverageGate -Packages Probe
$result.ExitCode | Should -Be 1
$result.Output | Should -Match 'Probe line coverage: 50% \(1 of 2 lines'
}
It 'takes the test project that covers the package best' `
{
Write-CoverageReport -Directory (Join-Path $script:ReportsDirectory 'first') -Hits 1, 0
Write-CoverageReport -Directory (Join-Path $script:ReportsDirectory 'second') -Hits 1, 1
$result = Invoke-CoverageGate
$result.ExitCode | Should -Be 0
$result.Output | Should -Match 'Probe line coverage: 100% \(2 of 2 lines.*second'
}
It 'lists uncovered lines only from the report it used' `
{
Write-CoverageReport -Directory (Join-Path $script:ReportsDirectory 'first') -Hits 0, 0, 0, 1
Write-CoverageReport -Directory (Join-Path $script:ReportsDirectory 'second') -Hits 1, 1, 0, 1
$result = Invoke-CoverageGate -Packages Probe
$result.ExitCode | Should -Be 1
$result.Output | Should -Match 'Probe line coverage: 75% \(3 of 4 lines.*second'
$result.Output | Should -Match 'uncovered: Probe\.cs lines 3(\s|$)'
$result.Output | Should -Not -Match 'lines 1, 2, 3'
}
It 'gates every package named in one comma-separated argument' `
{
Write-CoverageReport -Directory (Join-Path $script:ReportsDirectory 'first') -Package 'First'
Write-CoverageReport -Directory (Join-Path $script:ReportsDirectory 'second') -Package 'Second' -Hits 1, 0
$result = Invoke-CoverageGate -Packages 'First,Second'
$result.ExitCode | Should -Be 1
$result.Output | Should -Match 'First line coverage: 100%'
$result.Output | Should -Match 'Coverage gate FAILED: Second'
}
It 'gates every measured package when none is named' `
{
Write-CoverageReport -Directory (Join-Path $script:ReportsDirectory 'first') -Package 'First'
Write-CoverageReport -Directory (Join-Path $script:ReportsDirectory 'second') -Package 'Second' -Hits 1, 0
$result = Invoke-CoverageGate
$result.ExitCode | Should -Be 1
$result.Output | Should -Match 'Coverage gate FAILED: Second'
}
It 'holds the package to a lower bar when one is given' `
{
Write-CoverageReport -Directory $script:ReportsDirectory -Hits 1, 0
(Invoke-CoverageGate -MinimumPercent 50).ExitCode | Should -Be 0
(Invoke-CoverageGate -MinimumPercent 51).ExitCode | Should -Be 1
Write-CoverageReport -Directory $script:ReportsDirectory -Rate 1
$output = (& pwsh -NoProfile -File $script:CoverageGate -ResultsDirectory $script:ReportsDirectory -Packages Probe 2>&1) -join "`n"
$LASTEXITCODE | Should -Be 0
$output | Should -Match 'Coverage gate passed'
}
}
+26 -62
View File
@@ -1,32 +1,21 @@
#Requires -Version 7.4
# Copyright (c) 2026 James Maes
# SPDX-License-Identifier: MIT
<#
.SYNOPSIS
Fails when any named assembly is below the required line coverage.
.DESCRIPTION
Reads every coverage.cobertura.xml under -ResultsDirectory (one per test project
run) and, for each package, takes the report that covers it best. A package can be
split across test projects, and the report that exercises it most is authoritative.
Without -Packages, every package the reports measured is gated: coverage.runsettings
already limits measurement to the assemblies held to the bar.
The rate is counted from the lines each report lists, not read from its summary
attributes, so a report cannot state a rate its lines do not support.
Exits 1 on any shortfall, when a package named in -Packages is missing, or when no
report measured a single line of it.
Every report under the directory counts, including one left by an earlier run, so
collect into an empty directory. Run the script as its own process: called
in-process, its exit code does not stop the caller.
run) and, for each package, takes the best line rate any report measured. A package
can be split across test projects, and the report that exercises it most is
authoritative. Without -Packages, every package the reports measured is gated:
coverage.runsettings already limits measurement to the assemblies held to the bar.
Exits 1 on any shortfall, or when a package named in -Packages is missing.
.EXAMPLE
pwsh -NoProfile -File ./build/Assert-Coverage.ps1 -ResultsDirectory TestResults
./build/Assert-Coverage.ps1 -ResultsDirectory TestResults
.EXAMPLE
pwsh -NoProfile -File ./build/Assert-Coverage.ps1 -ResultsDirectory TestResults -Packages MarkdownViewr.Windows.Core
./build/Assert-Coverage.ps1 -ResultsDirectory TestResults -Packages MarkdownViewr.Windows.Core
#>
[CmdletBinding()]
param(
@@ -48,70 +37,45 @@ if ($files.Count -eq 0)
exit 1
}
# One entry per package per report: where it was measured, how many lines, and how many of them ran.
$measured = foreach ($file in $files)
{
$document = [xml](Get-Content -LiteralPath $file.FullName -Raw)
foreach ($package in $document.SelectNodes('/coverage/packages/package'))
{
$lines = $package.SelectNodes('classes/class/lines/line')
$covered = 0
foreach ($line in $lines)
{
if ([int]::Parse($line.GetAttribute('hits'), [Globalization.CultureInfo]::InvariantCulture) -gt 0) { $covered++ }
}
[pscustomobject]@{
Name = $package.GetAttribute('name')
Report = $file.FullName
Lines = $lines.Count
Covered = $covered
Package = $package
}
}
}
$measured = @($measured)
$reports = foreach ($file in $files) { [xml](Get-Content -LiteralPath $file.FullName -Raw) }
if ($Packages.Count -eq 0)
{
$Packages = @($measured | ForEach-Object { $_.Name } | Where-Object { $_ } | Sort-Object -Unique)
$Packages = @($reports | ForEach-Object { @($_.coverage.packages.package) } | ForEach-Object { $_.name } | Where-Object { $_ } | Sort-Object -Unique)
if ($Packages.Count -eq 0)
{
Write-Error 'The coverage reports measured no packages; check the Include filter in coverage.runsettings.' -ErrorAction Continue
exit 1
}
}
$required = $MinimumPercent / 100
$failed = $false
foreach ($name in $Packages)
{
$found = @($measured | Where-Object { $_.Name -ceq $name })
if ($found.Count -eq 0)
$rates = foreach ($doc in $reports)
{
$package = @($doc.coverage.packages.package) | Where-Object { $_.name -eq $name }
if ($package) { [double]::Parse($package.'line-rate', [Globalization.CultureInfo]::InvariantCulture) }
}
if (-not $rates)
{
Write-Error "Package '$name' not found in any coverage report." -ErrorAction Continue
$failed = $true
continue
}
# A package with no measured lines proves nothing.
$counted = @($found | Where-Object { $_.Lines -gt 0 })
if ($counted.Count -eq 0)
$best = ($rates | Measure-Object -Maximum).Maximum
Write-Output ("{0} line coverage: {1}% (required {2}%)" -f $name, [math]::Round($best * 100, 2), $MinimumPercent)
if ($best -lt $required)
{
Write-Error "Package '$name' has no measured lines in any coverage report." -ErrorAction Continue
$failed = $true
continue
}
# Best covered share first; between equal shares, the report that measured more lines.
$best = $counted | Sort-Object -Property @{ Expression = { $_.Covered / $_.Lines }; Descending = $true }, @{ Expression = { $_.Lines }; Descending = $true } | Select-Object -First 1
$percent = 100 * $best.Covered / $best.Lines
# Rounded down, so a package just under the bar is never shown as having reached it.
$shown = [math]::Floor($percent * 100) / 100
Write-Output ("{0} line coverage: {1}% ({2} of {3} lines, required {4}%), from {5}" -f $name, $shown, $best.Covered, $best.Lines, $MinimumPercent, $best.Report)
if ($percent -lt $MinimumPercent)
{
foreach ($class in $best.Package.SelectNodes('classes/class'))
foreach ($doc in $reports)
{
$missed = @($class.SelectNodes('lines/line[@hits="0"]') | ForEach-Object { $_.GetAttribute('number') })
if ($missed.Count -gt 0) { Write-Output " uncovered: $($class.GetAttribute('filename')) lines $($missed -join ', ')" }
$package = @($doc.coverage.packages.package) | Where-Object { $_.name -eq $name }
foreach ($class in @($package.classes.class))
{
$missed = @($class.lines.line) | Where-Object { $_.hits -eq '0' } | ForEach-Object { $_.number }
if ($missed) { Write-Output " uncovered: $($class.filename) lines $($missed -join ', ')" }
}
}
Write-Error "Coverage gate FAILED: $name is below $MinimumPercent%." -ErrorAction Continue
$failed = $true
+4 -3
View File
@@ -1,8 +1,9 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Coverage contract for the 100% gate (K22-TEST-10): every hand-written line of the
UI-free core counts. There is deliberately no Include filter: coverlet measures the
projects the unit tests reference whose sources are in this repository, never test
assemblies or NuGet packages, and the gate names the package it requires.
UI-free core and the command line counts. There is deliberately no Include filter:
coverlet measures the projects the unit tests reference whose sources are in this
repository (Core and the CLI), never test assemblies or NuGet packages, and an Include
filter would silently drop the CLI, whose assembly name (the app id) contains dashes.
Excluded, with intent:
- GeneratedCodeAttribute: source-generated JSON contexts and MVVM Toolkit members.
- ExcludeFromCodeCoverageAttribute: thin adapters a test cannot reach, each with a
-7
View File
@@ -5,13 +5,6 @@ Releases follow the
Pushing a protected `v*` tag on `main` runs [`.github/workflows/release.yml`](../.github/workflows/release.yml),
which calls the shared `release-velopack.yml` workflow in KofTwentyTwo/standards.
## Current state
The repository moved to Gitea, and GitHub is now a mirror with GitHub Actions switched
off. The release workflow this document describes exists only on GitHub, so until a
signing release job exists on Gitea, pushing a `v*` tag builds and tests the tag on
Gitea and publishes nothing. Do not tag expecting a release.
## Workflow baseline
The signing release builder is pinned to standards v1.1.1 (`96cbdf208a15c9c524676bd15ff9e323228a952b`); other shared gates retain v0.1.2. The release caller checks main ancestry and reruns build, coverage, formatting, UI tests, security scans and CodeQL before publication.
+6 -4
View File
@@ -14,8 +14,10 @@ dotnet tool install vpk --version 1.2.161 --tool-path artifacts/smoke-tools
The harness publishes the actual starter app four times with locked dependencies,
self-contained .NET and Windows App SDK settings matching the release builder.
Core declares the Windows runtime identifiers so its committed lock supports
runtime-specific publishing.
Core and CLI declare the Windows runtime identifiers so their committed locks
support runtime-specific publishing. Their single-file analyzer setting also locks
the SDK's ILLink tool dependency used when publishing the CLI as one executable.
The harness publishes and runs each CLI version when that head exists.
Keep `VelopackApp.Build().Run()` directly in
the app's entry point: the packer's startup check cannot recognize an indirect
AppKit wrapper call. Do not disable that pack-time check.
@@ -77,8 +79,8 @@ checks do not establish the corruption's cause.
## Evidence and cleanup
The harness has no automated run at present; run it by hand before a release. It
writes JSON results, process/installer logs and TRX UI reports. Local evidence stays under a fresh `artifacts/installed-smoke-*`
CI requires `installed-updates` and retains JSON results, process/installer logs
and TRX UI reports. Local evidence stays under a fresh `artifacts/installed-smoke-*`
directory. Existing output directories are refused so each attempt tests fresh
packages and results. Packer children receive a private `VELOPACK_TEMP` directory
named for the unique test package ID, isolating staging from other app builds.
+1 -1
View File
@@ -14,7 +14,7 @@
"tests/MarkdownViewr.Windows.UiTests/ActivationFuzzTests.cs"
],
"command": "dotnet test tests/MarkdownViewr.Windows.Core.Tests -c Release -p:Platform=x64 --no-build --no-restore --filter Category=Fuzz",
"workflow": ".gitea/workflows/build.yaml",
"workflow": ".github/workflows/fuzz.yml",
"evidence": "docs/security/fuzzing.md"
}
}
+7 -6
View File
@@ -35,12 +35,13 @@ dotnet test tests/MarkdownViewr.Windows.UiTests -c Release -p:Platform=x64 --fil
$env:K22_FUZZ_ITERATIONS = '10000'
```
Each target uses seeds 22023 and 99173. Every push runs 500 iterations per
seed/target (5000 generated property evaluations total) as part of the ordinary
test runs in `.gitea/workflows/build.yaml`. Pushes to `main` and to a tag repeat
the campaigns at 10000 (100000 total), and that step fails if its filter matches
no test. There is no scheduled campaign. Iteration configuration outside 1–100000
fails explicitly.
Each target uses seeds 22023 and 99173. PR/main campaigns run 500 iterations per
seed/target (5000 generated property evaluations total); weekly and every release
reuse run 10000 (100000 total). `fuzz.yml` runs on PRs, `main`, weekly and manual
requests; release.yml calls it and requires success before publication. The
`fuzzing` check is declared in the repository protection plan; apply and verify
that live protection after its first hosted run. The job has a 15-minute bound;
iteration configuration outside 1–100000 fails explicitly.
Failures retain seed, target, zero-based iteration and JSON-escaped synthetic
input in TRX/CI logs. To replay the sequence, use the same checkout/runtime/seed
+1 -1
View File
@@ -46,7 +46,7 @@ physical directory. It does not authorize native commands or remote resource acc
| Image traversal, device/ADS paths or encoded separators | Core path-policy tests pass; denied before filesystem access |
| Junction/symlink escape or check/reopen race | Check normalized physical path on opened image handle; read same handle; real junction rejection test passes |
| Remote image tracking / resource exfiltration | No-referrer header, no document networking; actual listening-server browser denial passed on 77dd04d |
| Oversized input / image denial of service | Pre-parse character bound and image byte bound; native limit tests pass; performance acceptance remains |
| Oversized input / image denial of service | Pre-parse character bound and image byte bound; native limit tests pass. Element nesting is bounded at 256 levels before any library walks the parsed tree recursively, with an early count that stops runaway nesting while it is still being parsed; deeper markup is refused as an unsupported document. Parse time is not bounded: it grows with document size, runs off the window thread, and can be cancelled between the render, the parse and each heading |
| Settings corruption / UI exception | AppKit shell sanitation and crash handling; inherited foundation tests |
| Tampered installer/update | Fail-closed signing/provenance/checksum release pipeline; real Azure CI authorization and signed artifacts remain unverified |
| Privileged repository review abuse | Trusted review workflow only; current-SHA human acknowledgement remains required |
@@ -18,16 +18,25 @@ public sealed class DocumentOutline
/// <summary>Sanitizes first; authored identifiers cannot impersonate the generated navigation targets.</summary>
public DocumentOutline(string markdown, FrontmatterMode frontmatter = FrontmatterMode.Hide, MarkdownExtensions? extensions = null)
/// <summary>
/// Sanitizes first; authored identifiers cannot impersonate the generated navigation targets.
/// A large document takes time that grows with its size: cancellation is honoured between the
/// render, the parse and each heading, so a closed window or a newer load does not wait for it.
/// </summary>
public DocumentOutline(string markdown, FrontmatterMode frontmatter = FrontmatterMode.Hide, MarkdownExtensions? extensions = null, CancellationToken cancellation = default)
{
var sources = new DocumentSourceMap(markdown);
var sourceHeadings = new List<DocumentSourceHeading>();
using AngleSharp.Html.Dom.IHtmlDocument document = new HtmlParser().ParseDocument(new MarkdownRenderer(extensions).RenderWithSources(markdown, frontmatter, sources));
cancellation.ThrowIfCancellationRequested();
string rendered = new MarkdownRenderer(extensions).RenderWithSources(markdown, frontmatter, sources);
cancellation.ThrowIfCancellationRequested();
using AngleSharp.Html.Dom.IHtmlDocument document = new HtmlParser().ParseDocument(rendered);
IElement body = document.Body!;
var fragments = new Dictionary<string, string>(StringComparer.Ordinal);
var nextSuffix = new Dictionary<string, int>(StringComparer.Ordinal);
foreach(IElement element in body.QuerySelectorAll("h1,h2,h3,h4,h5,h6"))
{
cancellation.ThrowIfCancellationRequested();
var heading = new DocumentHeading(_headings.Count, element.LocalName[1] - '0', element.TextContent.Trim());
_headings.Add(heading);
if(element.GetAttribute(sources.AttributeName) is { } identity && sources.TryGetPosition(identity, out (int Start, int End) position))
@@ -37,11 +46,15 @@ public sealed class DocumentOutline
_elements.Add(element, heading);
element.Id = "mv-heading-" + heading.Index.ToString(CultureInfo.InvariantCulture);
string slug = Markdig.Helpers.LinkHelper.UrilizeAsGfm(heading.Title);
// Repeated titles continue from the last suffix used for that title instead of rescanning from one.
string fragment = slug;
for(int suffix = 1; fragments.ContainsKey(fragment); suffix++)
int suffix = nextSuffix.GetValueOrDefault(slug, 1);
while(fragments.ContainsKey(fragment))
{
fragment = slug + "-" + suffix.ToString(CultureInfo.InvariantCulture);
suffix++;
}
nextSuffix[slug] = suffix;
fragments.Add(fragment, element.Id);
}
foreach(IElement element in body.QuerySelectorAll("[" + sources.AttributeName + "]"))
@@ -56,6 +69,7 @@ public sealed class DocumentOutline
link.SetAttribute("href", "#" + target);
}
}
cancellation.ThrowIfCancellationRequested();
foreach(IElement element in body.QuerySelectorAll("*").Reverse())
{
if(!_elements.ContainsKey(element))
@@ -142,10 +142,12 @@ internal sealed class DocumentSourceMap
string html = string.Join('\n', lines.Take(block.Lines.Count).Select(line => line.Slice.ToString()));
int? close = null;
bool seenTag = false;
var nesting = new HtmlNesting();
var parser = new HtmlParser(new HtmlParserOptions
{
OnToken = (token, range) =>
{
nesting.Observe(token);
if(!seenTag && token.Type is HtmlTokenType.StartTag or HtmlTokenType.EndTag
&& token.Name.Length == 2 && token.Name[0] == 'h' && token.Name[1] is >= '1' and <= '6')
{
@@ -209,11 +211,13 @@ internal sealed class DocumentSourceMap
private static HtmlParser CreateSourceParser(Dictionary<int, int> headingEnds)
{
int pendingHeading = -1;
var nesting = new HtmlNesting();
return new HtmlParser(new HtmlParserOptions
{
IsKeepingSourceReferences = true,
OnToken = (token, range) =>
{
nesting.Observe(token);
if(token.Name.Length == 2 && token.Name[0] == 'h' && token.Name[1] is >= '1' and <= '6')
{
if(token.Type == HtmlTokenType.StartTag)
@@ -0,0 +1,90 @@
/*
* Copyright (c) 2026 James Maes
* SPDX-License-Identifier: MIT
*/
using AngleSharp.Dom;
using AngleSharp.Html.Parser;
using AngleSharp.Html.Parser.Tokens;
namespace MarkdownViewr.Windows.Core.Documents;
/// <summary>
/// Bounds how deeply authored HTML may nest. Libraries that walk the parsed tree recursively
/// overflow the stack on a few thousand levels, and a stack overflow cannot be caught, so the
/// bound is enforced before any such walk: a cheap count while tokens arrive stops runaway
/// input early, and an exact measurement of the parsed tree applies the real limit.
/// </summary>
internal sealed class HtmlNesting
{
/// <summary>The deepest element nesting a document may have; ordinary documents use a few dozen levels.</summary>
public const int MaximumDepth = 256;
/// <summary>Start tags left open before parsing stops; an upper bound on depth that keeps the parser's work small.</summary>
public const int MaximumOpenTags = 4096;
private const string Message = "The document nests HTML more deeply than the supported limit.";
private static readonly HashSet<string> s_neverOpen = new(StringComparer.Ordinal)
{
// Void elements have no content.
"area", "base", "br", "col", "embed", "hr", "img", "input", "link", "meta", "source", "track", "wbr",
// A new one of these closes the previous one, so siblings left unclosed do not nest.
"caption", "colgroup", "dd", "dt", "li", "optgroup", "option", "p", "tbody", "td", "tfoot", "th", "thead", "tr",
};
private readonly Stack<string> _open = new();
/// <summary>
/// Counts start tags that are still open. An end tag closes only the tag on top, so the count
/// can exceed the real depth for carelessly closed markup but never falls below it.
/// </summary>
public void Observe(HtmlToken token)
{
if(token.Type == HtmlTokenType.StartTag && !s_neverOpen.Contains(token.Name))
{
_open.Push(token.Name);
if(_open.Count > MaximumOpenTags)
{
throw new ArgumentException(Message, nameof(token));
}
}
else if(token.Type == HtmlTokenType.EndTag && _open.TryPeek(out string? top) && string.Equals(top, token.Name, StringComparison.Ordinal))
{
_open.Pop();
}
}
/// <summary>Measures the parsed tree without recursion and rejects one deeper than <see cref="MaximumDepth"/>.</summary>
public static void ThrowIfTooDeep(INode root)
{
int depth = 0;
INode? node = root;
while(node is not null)
{
if(node.FirstChild is { } child)
{
node = child;
if(++depth > MaximumDepth)
{
throw new ArgumentException(Message, nameof(root));
}
}
else
{
// A leaf: climb to the nearest ancestor that has a sibling still to visit.
while(node != root && node!.NextSibling is null)
{
node = node.Parent;
depth--;
}
node = node == root ? null : node!.NextSibling;
}
}
}
}
@@ -6,6 +6,8 @@
using System.Text;
using System.Text.RegularExpressions;
using AngleSharp;
using AngleSharp.Css.Parser;
using AngleSharp.Dom;
using AngleSharp.Html.Dom;
using AngleSharp.Html.Parser;
@@ -24,6 +26,14 @@ public sealed class MarkdownRenderer
/// <summary>Bounds parser work before an opened document can consume unbounded memory.</summary>
public const int MaximumCharacters = 16 * 1024 * 1024;
// The sanitizer's own parser settings: scripting on, so noscript content stays text, and its CSS-aware context.
private static readonly IBrowsingContext s_sanitizerContext = BrowsingContext.New(Configuration.Default.WithCss(new CssParserOptions
{
IsIncludingUnknownDeclarations = true,
IsIncludingUnknownRules = true,
IsToleratingInvalidSelectors = true,
}));
private readonly MarkdownPipeline _pipeline;
private readonly MarkdownExtensions _extensions;
@@ -100,7 +110,23 @@ public sealed class MarkdownRenderer
_ => "",
} : "";
string html = sources is null ? RenderDocument(Markdown.Parse(body, _pipeline)) : sources.Render(body, _pipeline, markdown.Length - body.Length, RenderDocument);
return _sanitizer.Sanitize(prefix + html);
return Sanitize(prefix + html);
}
/// <summary>
/// Parses once with the sanitizer's own settings, proves the tree is shallow enough for the
/// sanitizer's recursive passes, and only then sanitizes and serializes it.
/// </summary>
private string Sanitize(string html)
{
var nesting = new HtmlNesting();
var parser = new HtmlParser(new HtmlParserOptions { IsScripting = true, OnToken = (token, _) => nesting.Observe(token) }, s_sanitizerContext);
using IHtmlDocument document = parser.ParseDocument("<!doctype html><html><body>" + html);
HtmlNesting.ThrowIfTooDeep(document.Body!);
_sanitizer.SanitizeDom(document, document.Body!);
return document.Body!.ChildNodes.ToHtml(_sanitizer.OutputFormatter);
}
@@ -124,21 +150,26 @@ public sealed class MarkdownRenderer
var block = (HtmlBlock)node;
string html = string.Join('\n', block.Lines.Lines.Take(block.Lines.Count).Select(line => line.Slice.ToString()));
var changes = new List<(int Start, int End, string Value)>();
var nesting = new HtmlNesting();
var parser = new HtmlParser(new HtmlParserOptions
{
OnToken = (token, range) =>
{
nesting.Observe(token);
if(token.Type is HtmlTokenType.StartTag or HtmlTokenType.EndTag && token.Name is "code" or "pre")
{
codeDepth = Math.Max(0, codeDepth + (token.Type == HtmlTokenType.StartTag ? 1 : -1));
}
else if(token.Type == HtmlTokenType.Character && codeDepth == 0)
{
string text = html[range.Start.Index..range.End.Index];
// An unterminated script or comment reports a range past the end of the block.
int start = Math.Min(range.Start.Index, html.Length);
int end = Math.Clamp(range.End.Index, start, html.Length);
string text = html[start..end];
string formatted = FormatRawText(text, extendSubscript);
if(!string.Equals(text, formatted, StringComparison.Ordinal))
{
changes.Add((range.Start.Index, range.End.Index, formatted));
changes.Add((start, end, formatted));
}
}
},
@@ -148,13 +179,7 @@ public sealed class MarkdownRenderer
{
continue;
}
var rewritten = new StringBuilder(html);
for(int index = changes.Count - 1; index >= 0; index--)
{
(int start, int end, string value) = changes[index];
rewritten.Remove(start, end - start).Insert(start, value);
}
string[] lines = rewritten.ToString().Split('\n');
string[] lines = Rewrite(html, changes).Split('\n');
for(int index = 0; index < block.Lines.Count; index++)
{
block.Lines.Lines[index].Slice = new Markdig.Helpers.StringSlice(lines[index]);
@@ -165,6 +190,28 @@ public sealed class MarkdownRenderer
/// <summary>
/// Applies replacements in one forward pass, so the work is linear in the block. Malformed markup
/// can report a text run that starts inside an earlier one; that run is left as authored.
/// </summary>
private static string Rewrite(string html, List<(int Start, int End, string Value)> changes)
{
var rewritten = new StringBuilder(html.Length + 64);
int copied = 0;
foreach((int start, int end, string value) in changes)
{
if(start < copied)
{
continue;
}
rewritten.Append(html, copied, start - copied).Append(value);
copied = end;
}
return rewritten.Append(html, copied, html.Length - copied).ToString();
}
/// <summary>Reference extension syntax applies only to tokenized visible text, with bounded regex work and unchanged entity spelling.</summary>
private string FormatRawText(string text, bool extendSubscript)
{
@@ -198,10 +245,12 @@ public sealed class MarkdownRenderer
}
else if(node is HtmlBlock block)
{
var nesting = new HtmlNesting();
var parser = new HtmlParser(new HtmlParserOptions
{
OnToken = (token, _) =>
{
nesting.Observe(token);
if(token.Type is HtmlTokenType.StartTag or HtmlTokenType.EndTag && token.Name is "code" or "pre")
{
codeDepth = Math.Max(0, codeDepth + (token.Type == HtmlTokenType.StartTag ? 1 : -1));
@@ -6,6 +6,8 @@
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<RuntimeIdentifiers>win-x86;win-x64;win-arm64</RuntimeIdentifiers>
<!-- Include the SDK tool dependency in the lock used by single-file CLI publishing. -->
<EnableSingleFileAnalyzer>true</EnableSingleFileAnalyzer>
</PropertyGroup>
<ItemGroup>
@@ -30,6 +30,12 @@
"resolved": "3.0.296",
"contentHash": "1Yp/6OK/Ev66hE2YLe9UvIgtJrKOX/xvoGDe0UbdtuG2ZxUoDoyONdEn+HWCDuy02Mu8SmglHEd/9SGPrM1qYg=="
},
"Microsoft.NET.ILLink.Tasks": {
"type": "Direct",
"requested": "[10.0.14, )",
"resolved": "10.0.14",
"contentHash": "YlTamXppEQls6DYWt7RdUuwWDb0lyw/vXCaGeQpLCpsLmfwGuCkOz/vIGgMTV7ECsJcavkCOkxZXv9s8rdAHkQ=="
},
"AngleSharp": {
"type": "Transitive",
"resolved": "1.7.2",
@@ -0,0 +1,218 @@
/*
* Copyright (c) 2026 James Maes
* SPDX-License-Identifier: MIT
*/
using AngleSharp.Html.Dom;
using AngleSharp.Html.Parser;
using MarkdownViewr.Windows.Core.Documents;
namespace MarkdownViewr.Windows.Core.Tests;
/// <summary>
/// Deeply nested markup must be refused as an ordinary error. The renders here run on a thread
/// with a quarter of the default stack, so a recursive walk that the bound failed to stop would
/// end the test run instead of passing by luck.
/// </summary>
public sealed class HtmlNestingTests
{
private const int SmallStackBytes = 256 * 1024;
/// <summary>The deepest markup the bound allows renders completely, with stack to spare.</summary>
[Fact]
public void Render_NestingAtTheLimit_RendersOnASmallStack()
{
int levels = HtmlNesting.MaximumDepth - 1;
string markup = Repeat("<div>", levels) + "deepest" + Repeat("</div>", levels);
string? html = null;
Assert.Null(OnSmallStack(() => html = new MarkdownRenderer().Render(markup)));
using IHtmlDocument parsed = new HtmlParser().ParseDocument(html!);
Assert.Equal(levels, parsed.QuerySelectorAll("div").Length);
Assert.Contains("deepest", html, StringComparison.Ordinal);
Assert.Equal(256, HtmlNesting.MaximumDepth);
}
/// <summary>One level past the limit is an argument error, the failure the reader already reports for an unsupported document.</summary>
[Fact]
public void Render_NestingOnePastTheLimit_IsRejected()
{
string markup = Repeat("<div>", HtmlNesting.MaximumDepth) + "too deep";
Assert.IsType<ArgumentException>(OnSmallStack(() => new MarkdownRenderer().Render(markup)));
}
/// <summary>
/// A few kilobytes of nested elements, in every shape that nests, are refused before any
/// library walks the tree recursively.
/// </summary>
[Theory]
[InlineData("<div>", 3000)]
[InlineData("<b>", 3000)]
[InlineData("<span><i>", 1500)]
[InlineData("<table><tr><td>", 3000)]
[InlineData("<blockquote>", 2000)]
[InlineData("<ul><li>", 2000)]
[InlineData("<details><summary>s</summary>", 1500)]
[InlineData("<div></section>", 3000)]
public void Render_DeeplyNestedMarkup_IsRejectedBeforeAnyRecursiveWalk(string unit, int count)
{
string markup = Repeat(unit, count) + "x";
Assert.IsType<ArgumentException>(OnSmallStack(() => new MarkdownRenderer().Render(markup)));
Assert.IsType<ArgumentException>(OnSmallStack(() => _ = new DocumentOutline(markup)));
}
/// <summary>
/// Nesting far past the limit is stopped by the count kept while tokens arrive, not after the
/// whole input has been parsed: parsing it to the end takes time that grows with its square.
/// </summary>
[Fact]
public void Render_RunawayNesting_IsStoppedWhileParsing()
{
string block = Repeat("<div>", 100000) + "x";
ArgumentException stoppedInBlock = Assert.IsType<ArgumentException>(OnSmallStack(() => new MarkdownRenderer().Render(block)));
Assert.Equal("token", stoppedInBlock.ParamName);
string inline = "Paragraph " + Repeat("<b>", 100000) + "x";
ArgumentException stoppedInline = Assert.IsType<ArgumentException>(OnSmallStack(() => new MarkdownRenderer().Render(inline)));
Assert.Equal("token", stoppedInline.ParamName);
ArgumentException measured = Assert.IsType<ArgumentException>(OnSmallStack(() => new MarkdownRenderer().Render(Repeat("<div>", 300) + "x")));
Assert.Equal("root", measured.ParamName);
}
/// <summary>Nesting assembled from inline tags in a paragraph, or from many separate blocks, is measured as a whole.</summary>
[Theory]
[InlineData("Paragraph ", "<b>", "")]
[InlineData("", "<div>", "\n\n")]
[InlineData("- item ", "<span>", "")]
[InlineData("> quoted ", "<i>", "")]
public void Render_NestingAcrossInlineTagsAndBlocks_IsRejected(string prefix, string unit, string separator)
{
string markup = prefix + string.Concat(Enumerable.Repeat(unit + separator, 400)) + "x";
Assert.IsType<ArgumentException>(OnSmallStack(() => new MarkdownRenderer().Render(markup)));
}
/// <summary>Nesting hidden in frontmatter rendered as Markdown is bounded like the body.</summary>
[Fact]
public void Render_DeepNestingInMarkdownFrontmatter_IsRejected()
{
string markup = "---\n" + Repeat("<div>", 3000) + "\n---\nBody";
Assert.IsType<ArgumentException>(OnSmallStack(() => new MarkdownRenderer().Render(markup, FrontmatterMode.Markdown)));
Assert.Null(OnSmallStack(() => new MarkdownRenderer().Render(markup, FrontmatterMode.Hide)));
}
/// <summary>Wide documents are not deep: thousands of siblings, unclosed paragraphs, list items and cells render normally.</summary>
[Theory]
[InlineData("<div>x</div>")]
[InlineData("<p>x")]
[InlineData("x<br>")]
[InlineData("<span>x</span><b>y</b>")]
public void Render_ManySiblings_AreNotMistakenForNesting(string unit)
{
string markup = "<div>" + Repeat(unit, HtmlNesting.MaximumOpenTags + 500) + "</div>";
string? html = null;
Assert.Null(OnSmallStack(() => html = new MarkdownRenderer().Render(markup)));
Assert.Contains("x", html, StringComparison.Ordinal);
}
/// <summary>List items and table cells left unclosed are siblings, however many there are.</summary>
[Fact]
public void Render_ManyUnclosedItemsAndCells_AreNotMistakenForNesting()
{
string markup = "<ul>" + Repeat("<li>item", 5000) + "</ul>\n\n<table>" + Repeat("<tr><td>a<td>b", 5000) + "</table>";
string? html = null;
Assert.Null(OnSmallStack(() => html = new MarkdownRenderer().Render(markup)));
using IHtmlDocument parsed = new HtmlParser().ParseDocument(html!);
Assert.Equal(5000, parsed.QuerySelectorAll("li").Length);
Assert.Equal(10000, parsed.QuerySelectorAll("td").Length);
}
/// <summary>The early count allows exactly its bound of open tags and stops at the next one.</summary>
[Theory]
[InlineData(HtmlNesting.MaximumOpenTags, false)]
[InlineData(HtmlNesting.MaximumOpenTags + 1, true)]
public void Observe_OpenTagsAtAndPastTheBound_StopsExactlyPastIt(int count, bool stopped)
{
Assert.Equal(stopped, Record.Exception(() => Tokenize(Repeat("<div>", count))) is ArgumentException);
Assert.Equal(4096, HtmlNesting.MaximumOpenTags);
}
/// <summary>
/// The early count never falls below the real depth: an end tag closes only the tag on top,
/// so an end tag the parser would ignore cannot be used to hide nesting from the count.
/// </summary>
[Theory]
[InlineData("<div></span>")]
[InlineData("<div><table><tr><td></div>")]
[InlineData("<section><p></article>")]
public void Observe_EndTagThatDoesNotCloseTheOpenTag_DoesNotReduceTheCount(string unit)
=> Assert.IsType<ArgumentException>(Record.Exception(() => Tokenize(Repeat(unit, HtmlNesting.MaximumOpenTags + 1))));
/// <summary>Properly closed elements, void elements and self-closing siblings never accumulate.</summary>
[Theory]
[InlineData("<div><span>x</span></div>")]
[InlineData("<img src=x><br><hr><input>")]
[InlineData("<p>x<li>y<td>z<option>o")]
public void Observe_ClosedVoidAndImplicitlyClosedTags_DoNotAccumulate(string unit)
=> Assert.Null(Record.Exception(() => Tokenize(Repeat(unit, HtmlNesting.MaximumOpenTags + 1))));
/// <summary>The exact measurement walks every branch and counts from the root it is given.</summary>
[Fact]
public void ThrowIfTooDeep_ShallowWideAndBranchingTrees_AreAccepted()
{
using IHtmlDocument empty = new HtmlParser().ParseDocument("");
HtmlNesting.ThrowIfTooDeep(empty.Body!);
using IHtmlDocument branching = new HtmlParser().ParseDocument(Repeat("<div>", 200) + "a" + Repeat("</div>", 200) + "<p>b</p>" + Repeat("<span>c</span>", 2000) + Repeat("<div>", 254) + "d");
HtmlNesting.ThrowIfTooDeep(branching.Body!);
using IHtmlDocument late = new HtmlParser().ParseDocument("<p>first</p><p>second</p>" + Repeat("<div>", 256) + "deep");
Assert.Throws<ArgumentException>(() => HtmlNesting.ThrowIfTooDeep(late.Body!));
}
/// <summary>Feeds markup through a parser whose tokens go to a fresh count, as the renderer does.</summary>
private static void Tokenize(string html)
{
var nesting = new HtmlNesting();
using IHtmlDocument document = new HtmlParser(new HtmlParserOptions { OnToken = (token, _) => nesting.Observe(token) }).ParseDocument(html);
}
/// <summary>Runs on a thread with a quarter of the default stack and returns what it threw, if anything.</summary>
private static Exception? OnSmallStack(Action action)
{
Exception? failure = null;
var thread = new Thread(() => failure = Record.Exception(action), SmallStackBytes);
thread.Start();
thread.Join();
return failure;
}
/// <summary>The unit repeated without separators.</summary>
private static string Repeat(string unit, int count) => string.Concat(Enumerable.Repeat(unit, count));
}
@@ -0,0 +1,126 @@
/*
* Copyright (c) 2026 James Maes
* SPDX-License-Identifier: MIT
*/
using AngleSharp.Html.Dom;
using AngleSharp.Html.Parser;
using MarkdownViewr.Windows.Core.Documents;
namespace MarkdownViewr.Windows.Core.Tests;
/// <summary>Malformed and very repetitive documents render, with work that grows in step with their size.</summary>
public sealed class RendererRobustnessTests
{
/// <summary>An unterminated script followed by a comment opener reports a text run past the end of its block; the document still opens and stays passive.</summary>
[Theory]
[InlineData("<script>x<!--")]
[InlineData("<script><!--")]
[InlineData("<script>==a==\n<!--")]
[InlineData("<script>*<!--")]
[InlineData("<div>==kept==</div><script>\n<!--\n")]
public void Render_UnterminatedScriptAndComment_OpensAsPassiveMarkup(string markdown)
{
string html = new MarkdownRenderer().Render(markdown + "\n\nAfter the block.");
Assert.DoesNotContain("<script", html, StringComparison.OrdinalIgnoreCase);
var outline = new DocumentOutline("# Title\n\n" + markdown);
Assert.Equal("Title", Assert.Single(outline.Headings).Title);
Assert.DoesNotContain("<script", outline.Html, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Markup is parsed with scripting on, as the sanitizer library parses it: the content of a
/// noscript element is text that ends at the first closing tag, wherever that tag appears.
/// </summary>
[Fact]
public void Render_NoscriptContent_IsParsedAsTextEndingAtItsFirstClosingTag()
{
const string Markdown = "<noscript><p title=\"</noscript><img src=x onerror=execute() alt=after>\"></noscript>";
using IHtmlDocument parsed = new HtmlParser().ParseDocument(new MarkdownRenderer().Render(Markdown));
AngleSharp.Dom.IElement image = Assert.Single(parsed.QuerySelectorAll("img"));
Assert.Equal(["alt", "src"], image.Attributes.Select(attribute => attribute.Name).Order(StringComparer.Ordinal), StringComparer.Ordinal);
Assert.Empty(parsed.QuerySelectorAll("noscript,p[title]"));
}
/// <summary>Markup broken so that one text run starts inside another is left as authored there, formatted elsewhere, and still sanitized.</summary>
[Fact]
public void Render_OverlappingTextRuns_RendersWithoutRewritingTheOverlap()
{
const string Markdown = "<iframe srcdoc='<script>execute()</scr<pre><code>==literal== ^literal^ ++literal++</code></pre>\nipt>'></iframe></style><script>execute()</script>";
string html = new MarkdownRenderer().Render(Markdown);
using IHtmlDocument parsed = new HtmlParser().ParseDocument(html);
Assert.Empty(parsed.QuerySelectorAll("script,iframe,style"));
Assert.DoesNotContain("execute()</script>", html, StringComparison.Ordinal);
}
/// <summary>Every text run in a long raw block is formatted once, in place, in document order.</summary>
[Fact]
public void Render_ManyFormattedRunsInOneBlock_FormatsEachInOrder()
{
const int Runs = 3000;
string block = "<div>" + string.Concat(Enumerable.Range(0, Runs).Select(index => $"<span>==m{index}== and ^s{index}^</span>")) + "</div>";
using IHtmlDocument parsed = new HtmlParser().ParseDocument(new MarkdownRenderer().Render(block));
Assert.Equal(Enumerable.Range(0, Runs).Select(index => "m" + index.ToString(System.Globalization.CultureInfo.InvariantCulture)), parsed.QuerySelectorAll("mark").Select(mark => mark.TextContent), StringComparer.Ordinal);
Assert.Equal(Enumerable.Range(0, Runs).Select(index => "s" + index.ToString(System.Globalization.CultureInfo.InvariantCulture)), parsed.QuerySelectorAll("sup").Select(sup => sup.TextContent), StringComparer.Ordinal);
Assert.Equal(Runs, parsed.QuerySelectorAll("span").Length);
}
/// <summary>A raw block whose text needs no formatting is passed through unchanged between its neighbours.</summary>
[Fact]
public void Render_FormattedRunsBetweenUnchangedText_KeepsTheTextAroundThem()
{
using IHtmlDocument parsed = new HtmlParser().ParseDocument(new MarkdownRenderer().Render("<div>before <b>==first==</b> middle <i>plain</i> ++last++ after</div>"));
Assert.Equal("before first middle plain last after", parsed.Body!.TextContent.Trim());
Assert.Equal("first", Assert.Single(parsed.QuerySelectorAll("mark")).TextContent);
Assert.Equal("last", Assert.Single(parsed.QuerySelectorAll("ins")).TextContent);
}
/// <summary>Thousands of headings with one title get distinct anchors, and a link to any of them finds its heading.</summary>
[Fact]
public void Outline_ManyHeadingsWithTheSameTitle_AnchorEachOne()
{
const int Count = 4000;
string markdown = string.Concat(Enumerable.Repeat("# Same\n\n", Count)) + "[first](#same) [second](#same-1) [last](#same-3999) [none](#same-4000)\n";
var outline = new DocumentOutline(markdown);
Assert.Equal(Count, outline.Headings.Count);
using IHtmlDocument parsed = new HtmlParser().ParseDocument(outline.Html);
Assert.Equal(["#mv-heading-0", "#mv-heading-1", "#mv-heading-3999", "#same-4000"], parsed.QuerySelectorAll("a").Select(link => link.GetAttribute("href")!), StringComparer.Ordinal);
}
/// <summary>A heading that is literally named like a generated anchor keeps its own anchor; repeats step past it.</summary>
[Theory]
[InlineData("# Same\n\n# Same-1\n\n# Same\n\n# Same\n\n", new[] { "#same", "#same-1", "#same-2", "#same-3" })]
[InlineData("# Same-1\n\n# Same\n\n# Same\n\n# Same-1\n\n", new[] { "#same-1", "#same", "#same-2", "#same-1-1" })]
[InlineData("# A\n\n# B\n\n# A\n\n# B\n\n", new[] { "#a", "#b", "#a-1", "#b-1" })]
public void Outline_RepeatedAndLiteralSuffixTitles_AnchorInDocumentOrder(string headings, string[] anchors)
{
string markdown = headings + string.Concat(anchors.Select(anchor => $"[link]({anchor}) "));
using IHtmlDocument parsed = new HtmlParser().ParseDocument(new DocumentOutline(markdown).Html);
Assert.Equal(["#mv-heading-0", "#mv-heading-1", "#mv-heading-2", "#mv-heading-3"], parsed.QuerySelectorAll("a").Select(link => link.GetAttribute("href")!), StringComparer.Ordinal);
}
/// <summary>A load that is no longer wanted stops instead of building its outline.</summary>
[Fact]
public void Outline_CancelledBeforeItStarts_StopsWithoutBuilding()
{
using var cancellation = new CancellationTokenSource();
cancellation.Cancel();
Assert.Throws<OperationCanceledException>(() => new DocumentOutline("# Title\n\nBody", cancellation: cancellation.Token));
Assert.Equal("Title", Assert.Single(new DocumentOutline("# Title\n\nBody", cancellation: CancellationToken.None).Headings).Title);
}
}
@@ -20,7 +20,6 @@ namespace MarkdownViewr.Windows.UiTests;
/// UI tests share one desktop, so they never run in parallel.
/// </summary>
[Collection("Desktop")]
[Trait("Category", "Desktop")]
public partial class AppTests
{
private readonly ITestOutputHelper _output;