using System.Text;
using AngleSharp.Dom;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.PixelFormats;
namespace XFESystem.Browser.Tests;
public sealed class BrowserRemoteContentTests
{
private const string Policy = "script-src https: 'strict-dynamic' 'nonce-YWJj'; base-uri 'self'";
[Theory]
[InlineData("location.assign('/next?q=value')")]
[InlineData("location.replace('/next?q=value')")]
[InlineData("location.href='/next?q=value'")]
[InlineData("window.location='/next?q=value'")]
[InlineData("document.location='/next?q=value'")]
public void LocationNavigationFetchesTheActualDestinationAfterTheScriptReturns(string script)
{
var transport = new Fixture("
actual response
"); var browser = new BrowserService(transport); browser.Navigate("https://page.test/");
browser.ExecuteJavaScript(script); browser.AdvanceTime(10);
Assert.Equal("https://page.test/next?q=value", browser.CurrentPage.Address);
Assert.Equal(new Uri(browser.CurrentPage.Address), transport.Requests.Last());
}
[Fact]
public void DomCollectionsHaveTheirActualInterfacesAndStaticVersusLiveMembership()
{
var browser = new BrowserService(new Fixture("
")) + "";
var browser = new BrowserService(new Fixture(html), new BrowserLimits { MaximumScriptMemoryBytes = 8_000_000 });
browser.Navigate("https://page.test/");
Assert.Equal("500", browser.ExecuteJavaScript("globalThis.snapshot=document.querySelectorAll('p');snapshot.length"));
browser.Document!.GetElementById("P499")!.Remove();
Assert.Equal("500:P499:false", browser.ExecuteJavaScript("snapshot.length+':'+snapshot.item(499).id+':'+snapshot.item(499).isConnected"));
}
[Fact]
public void IteratingALiveDescendantCollectionStaysWithinTheScriptAllocationBudget()
{
var html = "" + string.Concat(Enumerable.Range(0, 500).Select(index => "item")) + "";
var browser = new BrowserService(new Fixture(html), new BrowserLimits { MaximumScriptMemoryBytes = 128_000_000 });
browser.Navigate("https://page.test/");
Assert.Equal("500:P499", browser.ExecuteJavaScript("const elements=document.getElementsByTagName('span');let count=0,last='';for(let i=0;i");
var browser = new BrowserService(transport); browser.Navigate("https://page.test/");
Assert.Equal("1", browser.ExecuteJavaScript("'use strict';const form=document.getElementById('F'),nativeSubmit=form.submit;let calls=0;form.submit=function(){calls++;nativeSubmit.call(this)};form.submit();calls"));
browser.AdvanceTime(10); Assert.Contains("q=wrapped+query", transport.Requests.Last().Query);
}
[Fact]
public void HyperlinkUrlComponentsResolveAndReflectChangesWithoutUndefinedFields()
{
var browser = new BrowserService(new Fixture("link")); browser.Navigate("https://page.test/folder/index.html");
Assert.Equal("https:|page.test|page.test||/path|?q=one|#first|https://page.test", browser.ExecuteJavaScript("const a=document.getElementById('A');[a.protocol,a.host,a.hostname,a.port,a.pathname,a.search,a.hash,a.origin].join('|')"));
Assert.Equal("http://other.test/changed?q=two#last", browser.ExecuteJavaScript("a.protocol='http:';a.host='other.test:8080';a.pathname='/changed';a.search='?q=two';a.hash='#last';a.port='';a.toString()"));
Assert.Equal("https://example.test|u|p", browser.ExecuteJavaScript("a.href='https://u:p@example.test/x';[a.origin,a.username,a.password].join('|')"));
}
[Theory]
[InlineData("screen and (min-width:600px) and (max-width:900px)", true)]
[InlineData("(min-width:900px), (orientation:landscape)", true)]
[InlineData("only screen and (min-height:700px)", false)]
[InlineData("not screen and (min-width:900px)", true)]
[InlineData("print and (min-width:1px)", false)]
[InlineData("screen and (unknown:yes)", false)]
[InlineData("(min-resolution:96dpi)", true)]
[InlineData("(prefers-reduced-motion:reduce)", true)]
[InlineData("(prefers-reduced-motion:no-preference)", false)]
[InlineData("(prefers-color-scheme:light)", true)]
[InlineData("(width:800px) and (height:600px)", true)]
[InlineData("(min-aspect-ratio:4/3)", true)]
[InlineData("(min-width:600px) (max-width:900px)", false)]
public void MediaQueriesEvaluateConjunctionListsAndScreenPreferences(string query, bool expected)
=> Assert.Equal(expected, BrowserMediaQuery.Matches(query, new(800, 600)));
[Fact]
public void CssAndMediaQueryListsRespondToRealViewportResizeAndNotifyChanges()
{
var browser = new BrowserService(new Fixture("
text
"));
browser.ResizeViewport(800, 600); browser.Navigate("https://page.test/");
Assert.Equal("true", browser.ExecuteJavaScript("const m=matchMedia('screen and (min-width:600px) and (max-height:700px)');let changes=0;m.addListener(e=>{if(e.target===m&&!e.matches)changes++});m.matches"));
Assert.Equal(0xff0000u, browser.Layout(new(800, 600)).GetComputedStyle(browser.Document!.GetElementById("P")!)!.Color.Rgb);
browser.ResizeViewport(400, 600);
Assert.Equal("false:1", browser.ExecuteJavaScript("m.matches+':'+changes"));
Assert.Equal(0x0000ffu, browser.Layout(new(400, 600)).GetComputedStyle(browser.Document.GetElementById("P")!)!.Color.Rgb);
browser.ResizeViewport(350, 600); Assert.Equal("1", browser.ExecuteJavaScript("changes"));
}
[Fact]
public void ReassigningTheSameCssDeclarationPreservesCssTextAndCachedGeometry()
{
var browser = new BrowserService(new Fixture("
text
")); browser.Navigate("https://page.test/");
browser.Layout(new(300, 200)); long layouts = browser.LayoutPassCount;
Assert.Equal("0:color:red;width:100px", browser.ExecuteJavaScript("let records=0;const p=document.getElementById('P');new MutationObserver(r=>records+=r.length).observe(p,{attributes:true});for(let i=0;i<100;i++)p.style.color='red';records+':'+p.style.cssText"));
browser.Layout(new(300, 200)); Assert.Equal(layouts, browser.LayoutPassCount);
browser.ExecuteJavaScript("p.style.setProperty('color','red','important')"); browser.Layout(new(300, 200));
Assert.True(browser.LayoutPassCount > layouts); Assert.Contains("!important", browser.Document!.GetElementById("P")!.GetAttribute("style"));
}
[Fact]
public void RightFloatShrinksToItsContentAndStaysBesideAnExistingInlineForm()
{
var document = new AngleSharp.Html.Parser.HtmlParser().ParseDocument("
abc
");
var layout = new BrowserLayoutEngine().Layout(document, new(800, 500));
var header = layout.GetBoundingClientRect(document.GetElementById("Header")!);
var form = layout.GetBoundingClientRect(document.GetElementById("Form")!);
var login = layout.GetBoundingClientRect(document.GetElementById("Login")!);
Assert.Equal(form.Y, login.Y); Assert.InRange(login.Width, 20, 40);
Assert.Equal(header.Right - 32, login.Right); Assert.Equal(120, header.Height);
}
[Fact]
public void LeftFloatExcludesInlineTextAndClearMovesFollowingBlockBelowIt()
{
var document = new AngleSharp.Html.Parser.HtmlParser().ParseDocument("
text
after
");
var layout = new BrowserLayoutEngine().Layout(document, new(800, 500));
var floating = layout.GetBoundingClientRect(document.GetElementById("Float")!);
Assert.Equal(floating.Right, layout.GetBoundingClientRect(document.GetElementById("Text")!).X);
Assert.True(layout.GetBoundingClientRect(document.GetElementById("Clear")!).Y >= floating.Bottom);
}
[Fact]
public void PositionedRectClipAppliesToPaintingAndHitTestingIncludingDeferredDescendants()
{
var document = new AngleSharp.Html.Parser.HtmlParser().ParseDocument("
");
var layout = new BrowserLayoutEngine().Layout(document, new(800, 500));
Assert.InRange(layout.GetBoundingClientRect(document.GetElementById("Control")!).Width, 40, 80);
var icon = layout.GetBoundingClientRect(document.GetElementById("Icon")!);
Assert.Equal(16, icon.Width); Assert.Equal(16, icon.Height);
}
[Fact]
public void FlexRowsWrapBeforeShrinkingAndGeneratedAttributeTextStillInvalidates()
{
var doc = new AngleSharp.Html.Parser.HtmlParser().ParseDocument("
");
var layout = new BrowserLayoutEngine().Layout(doc, new(500, 300));
var first = layout.GetBoundingClientRect(doc.GetElementById("I0")!); var fourth = layout.GetBoundingClientRect(doc.GetElementById("I3")!);
Assert.Equal(100, first.Width); Assert.Equal(first.X, fourth.X); Assert.Equal(first.Bottom + 5, fourth.Y);
Assert.Equal(45, layout.GetBoundingClientRect(doc.GetElementById("Rows")!).Height);
var browser = new BrowserService(new Fixture("")); browser.Navigate("https://page.test/");
browser.Layout(new(300, 300)); browser.ExecuteJavaScript("document.getElementById('P').setAttribute('data-label','after')");
Assert.Contains(browser.Layout(new(300, 300)).Commands, command => command.Text == "after");
}
[Fact]
public void AttributeBudgetUsesDeltasAndStillRejectsCombinedGrowthAndReflectedFormValues()
{
var limits = new BrowserLimits { MaximumHtmlCharacters = 200 };
using var runtime = new JavaScriptRuntime(limits);
var document = new AngleSharp.Html.Parser.HtmlParser().ParseDocument("
text
");
var dom = new DomBridge(runtime, document, new("https://page.test/"), limits);
Assert.True(runtime.Evaluate("const p=document.getElementById('P');for(let i=0;i<100;i++)p.setAttribute('data-track',String(i))").Success);
Assert.InRange(dom.BudgetValidationCount, 1, 2);
Assert.True(runtime.Evaluate("p.removeAttribute('data-track');const q=document.getElementById('Q');q.setAttribute('value','x'.repeat(90))").Success);
var result = runtime.Evaluate("q.setAttribute('value','y'.repeat(120))");
Assert.False(result.Success); Assert.True(result.BudgetExceeded);
Assert.Equal("90:90", runtime.Evaluate("[q.value.length,q.getAttribute('value').length].join(':')").Value);
dom.ReleaseRetainedState();
}
[Fact]
public void TrackingAttributesKeepGeometryCacheButSelectorAttributesAndObserversStillUpdate()
{
var browser = new BrowserService(new Fixture("
value
")); browser.Navigate("https://page.test/");
browser.Layout(new(300, 300)); long before = browser.LayoutPassCount;
browser.ExecuteJavaScript("globalThis.Records=0;const p=document.getElementById('P');new MutationObserver(r=>Records+=r.length).observe(p,{attributes:true});p.setAttribute('data-track','one');p.setAttribute('data-track','one')");
browser.Layout(new(300, 300)); Assert.Equal(before, browser.LayoutPassCount); Assert.Equal("2", browser.ExecuteJavaScript("Records"));
browser.ExecuteJavaScript("p.setAttribute('data-state','red')");
var layout = browser.Layout(new(300, 300)); Assert.True(browser.LayoutPassCount > before);
Assert.Equal(0xff0000u, layout.GetComputedStyle(browser.Document!.GetElementById("P")!)!.Color.Rgb);
}
[Fact]
public void GeometryReadDuringTimerDoesNotDownloadAndDecodeDisplayImagesInsideAuthorCallback()
{
var transport = new Fixture("
geometry
");
transport.Images["/Actual.svg"] = Encoding.UTF8.GetBytes("");
var browser = new BrowserService(transport); browser.Navigate("https://page.test/"); browser.AdvanceTime(0);
Assert.Single(transport.Requests);
browser.Layout(new(300, 300)); Assert.Equal(2, transport.Requests.Count);
var image = browser.Document!.QuerySelector("img")!;
var rect = browser.Layout(new(300, 300)).GetBoundingClientRect(image);
Assert.Equal(4, rect.Width); Assert.Equal(4, rect.Height);
}
[Fact]
public void SingularScaleTransformsDoNotPaintOrReceivePointerInput()
{
var doc = new AngleSharp.Html.Parser.HtmlParser().ParseDocument("
hidden content
visible
");
var layout = new BrowserLayoutEngine().Layout(doc, new(300, 300));
Assert.DoesNotContain(layout.Commands, command => command.Text.Contains("hidden"));
Assert.Equal("Shown", layout.HitTest(20, 20)?.Element?.Id);
}
[Fact]
public void ScriptFormSubmitBypassesCanceledSubmitHandlerAndUsesCurrentValue()
{
var transport = new Fixture("");
var browser = new BrowserService(transport); browser.Navigate("https://page.test/");
browser.ExecuteJavaScript("document.getElementById('F').addEventListener('submit',e=>e.preventDefault());document.getElementById('F').requestSubmit()");
browser.AdvanceTime(0); Assert.Single(transport.Requests);
browser.ExecuteJavaScript("document.getElementById('F').submit()"); browser.AdvanceTime(10);
Assert.Equal("/search", transport.Requests.Last().AbsolutePath); Assert.Contains("q=real+query", transport.Requests.Last().Query);
}
[Fact]
public void PositionedDescendantsShareTheNearestStackingContextAndRetainAncestorClips()
{
var parser = new AngleSharp.Html.Parser.HtmlParser();
string high = "";
string low = "";
var layout = new BrowserLayoutEngine().Layout(parser.ParseDocument("
" + low), new(200, 200));
Assert.Equal("High", layout.HitTest(12, 12)?.Element?.Id); Assert.Equal("Low", layout.HitTest(20, 20)?.Element?.Id);
}
[Fact]
public void AttributeNodesAndDocumentSelectionExposeActualDocumentValues()
{
var browser = new BrowserService(new Fixture("
actual text
")); browser.Navigate("https://page.test/");
Assert.Equal("rtl:actual text:true:1", browser.ExecuteJavaScript("const p=document.getElementById('P');getSelection().selectAllChildren(p);[p.getAttributeNode('dir').value,getSelection().toString(),document.getSelection()===getSelection(),getSelection().rangeCount].join(':')"));
Assert.Equal("ltr:0", browser.ExecuteJavaScript("p.getAttributeNode('dir').value='ltr';getSelection().removeAllRanges();p.dir+':'+getSelection().rangeCount"));
}
[Fact]
public void LiveNodeCollectionSupportsHasPropertyUsedByArraySliceAndHydration()
{
var browser = new BrowserService(new Fixture("
")); browser.Navigate("https://page.test/");
Assert.Equal("A,B:true:false:A", browser.ExecuteJavaScript("const p=document.getElementById('P'),nodes=p.childNodes;[Array.prototype.slice.call(nodes).map(n=>n.id).join(','),0 in nodes,2 in nodes,Object.getOwnPropertyDescriptor(nodes,'0').value.id].join(':')"));
Assert.Equal("B:1:false", browser.ExecuteJavaScript("p.removeChild(p.firstChild);[Array.prototype.slice.call(nodes).map(n=>n.id).join(','),nodes.length,1 in nodes].join(':')"));
}
[Fact]
public void Base64UsesByteStringsAndForgivingAsciiWhitespaceWithoutAcceptingInvalidCharacters()
{
var browser = new BrowserService(new Fixture("
base64
")); browser.Navigate("https://page.test/");
Assert.Equal("AP8=:255:Man:Ma:null", browser.ExecuteJavaScript("[btoa('\\x00\\xff'),atob('AP8=').charCodeAt(1),atob(' T W\\nF u\\t'),atob('TWE'),atob(btoa(null))].join(':')"));
Assert.Equal("InvalidCharacterError:InvalidCharacterError:InvalidCharacterError:TypeError", browser.ExecuteJavaScript("[()=>btoa('中文'),()=>atob('A'),()=>atob('TW=E'),()=>atob()].map(f=>{try{f();return 'wrong'}catch(e){return e.name}}).join(':')"));
}
[Fact]
public void ImageDecodeResolvesActualPixelsAndRejectsBrokenOrEmptyImages()
{
var browser = new BrowserService(new Fixture("""
"""));
browser.Navigate("https://page.test/");
string result = browser.ExecuteJavaScript("Result.sort().join(',')");
Assert.Equal("EncodingError,EncodingError,true:2:3", result);
}
[Fact]
public void NonceProfileRunsTrustedDynamicScriptsButRejectsParserAndFragmentInjection()
{
var transport = new Fixture("""
before
""", Policy);
transport.Resources["/Code.js"] = ("application/x-javascript", "globalThis.DynamicExternal=84");
var browser = new BrowserService(transport); browser.Navigate("https://page.test/");
Assert.Equal("allowed", browser.Document!.GetElementById("Value")!.TextContent);
Assert.Equal("42:84:undefined:undefined:undefined", browser.ExecuteJavaScript("[DynamicInline,DynamicExternal,typeof Forbidden,typeof WrongNonce,typeof FragmentInjection].join(':')"));
}
[Fact]
public void AllPoliciesIntersectAndNonceDoesNotAuthorizeEvalOrEventAttributes()
{
var browser = new BrowserService(new Fixture("", Policy + ", script-src 'none'"));
browser.Navigate("https://page.test/"); Assert.Equal("undefined", browser.ExecuteJavaScript("typeof ShouldNotRun"));
browser = new(new Fixture("", Policy));
browser.Navigate("https://page.test/");
Assert.Equal("true:undefined:undefined", browser.ExecuteJavaScript("document.getElementById('B').click();[EvalError,typeof EvalRan,typeof AttributeRan].join(':')"));
}
[Fact]
public void SameOriginXhrCompletesOutsideAuthorEvaluationAndPrefetchIsReusedByScript()
{
var transport = new Fixture("""
""");
transport.Resources["/Code.js"] = ("text/javascript", "globalThis.Fetched=42");
var browser = new BrowserService(transport); browser.Navigate("https://page.test/");
Assert.Equal("2,3,4:42", browser.ExecuteJavaScript("States.join(',')+':'+Fetched"));
Assert.Equal(1, transport.Requests.Count(uri => uri.AbsolutePath == "/Code.js"));
}
[Fact]
public void ScriptFetchCannotReadCrossOriginOrRedirectedContent()
{
var transport = new Fixture("");
var browser = new BrowserService(transport); browser.Navigate("https://page.test/");
Assert.Equal("blocked", browser.ExecuteJavaScript("Result"));
Assert.Single(transport.Requests);
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void BitmapDecodingUsesActualPngOrWebpPixelsAndChecksDimensions(bool webp)
{
using var image = new Image(2, 1); image[0, 0] = new(255, 0, 0); image[1, 0] = new(0, 255, 0);
using var stream = new MemoryStream();
if (webp) image.SaveAsWebp(stream, new SixLabors.ImageSharp.Formats.Webp.WebpEncoder { FileFormat = SixLabors.ImageSharp.Formats.Webp.WebpFileFormatType.Lossless }); else image.SaveAsPng(stream);
var decoded = BrowserImageDecoder.Decode(stream.ToArray(), 2);
Assert.Equal(0xffff0000u, decoded.Pixel(0, 0)); Assert.Equal(0xff00ff00u, decoded.Pixel(1, 0));
Assert.Throws(() => BrowserImageDecoder.Decode(stream.ToArray(), 1));
}
[Fact]
public void SvgPathsTransformsAndTransparentBackgroundAreRasterized()
{
var bytes = Encoding.UTF8.GetBytes("");
var image = BrowserImageDecoder.Decode(bytes, 400);
Assert.Equal(0xffff0000u, image.Pixel(4, 4)); Assert.Equal(0xff00ff00u, image.Pixel(14, 14)); Assert.Equal(0u, image.Pixel(19, 0));
Assert.Throws(() => BrowserImageDecoder.Decode(bytes, 399));
}
[Fact]
public void SvgCompactArcFlagsAreSeparateTokensAndInvalidFlagsAreRejected()
{
var compact = BrowserImageDecoder.Decode(Encoding.UTF8.GetBytes(""), 144);
var spaced = BrowserImageDecoder.Decode(Encoding.UTF8.GetBytes(""), 144);
for (int y = 0; y < 12; y++) for (int x = 0; x < 12; x++) Assert.Equal(spaced.Pixel(x, y), compact.Pixel(x, y));
Assert.Equal(0xffff0000u, compact.Pixel(6, 6));
Assert.Throws(() => BrowserImageDecoder.Decode(Encoding.UTF8.GetBytes(""), 144));
}
[Fact]
public void SessionCookieJarPreservesDomainsAndHttpOnlyAndSecureVisibility()
{
var cookies = new BrowserCookieStore(); var page = new Uri("https://page.test/");
cookies.Receive(page, "sid=secret; Path=/; HttpOnly; Secure"); cookies.Receive(page, "theme=dark; Path=/; Secure");
Assert.Contains("sid=secret", cookies.RequestHeader(page)); Assert.DoesNotContain("sid", cookies.ReadDocumentCookies(page));
Assert.Equal("theme=dark", cookies.ReadDocumentCookies(page)); Assert.Empty(cookies.RequestHeader(new("https://other.test/")));
Assert.Empty(cookies.RequestHeader(new("http://page.test/"))); cookies.WriteDocumentCookie(page, "sid=changed");
Assert.Contains("sid=secret", cookies.RequestHeader(page)); Assert.DoesNotContain("changed", cookies.RequestHeader(page));
cookies.WriteDocumentCookie(page, "local=42; Path=/"); Assert.Contains("local=42", cookies.ReadDocumentCookies(page));
}
[Fact]
public void GetFormSubmissionUsesRealEditedValueAndSuccessfulControls()
{
var transport = new Fixture("");
var browser = new BrowserService(transport); browser.Navigate("https://page.test/");
var input = browser.Document!.GetElementById("Q")!; var rect = browser.Layout(new(800, 600)).GetBoundingClientRect(input);
browser.Pointer(new("mousedown", rect.X + 10, rect.Y + 5, 0, 1)); browser.Pointer(new("mouseup", rect.X + 10, rect.Y + 5, 0, 0));
browser.Key(new("keydown", "a", "KeyA", "a b&中文")); browser.Key(new("keydown", "Enter", "Enter"));
var query = transport.Requests.Last(); Assert.Equal("/search", query.AbsolutePath);
Assert.Contains("q=a+b%26", query.Query); Assert.Contains("form=Test", query.Query); Assert.Contains("go=yes", query.Query); Assert.DoesNotContain("disabled", query.Query);
}
[Fact]
public void ConstrainedParentHeightIsUsedByPercentageChildren()
{
var doc = new AngleSharp.Html.Parser.HtmlParser().ParseDocument("
text
");
Assert.Equal(52, new BrowserLayoutEngine().Layout(doc, new(800, 600)).GetBoundingClientRect(doc.GetElementById("Child")!).Height);
}
[Fact]
public void BlockDescendantOfInlineContainerStartsAndEndsItsOwnLine()
{
var doc = new AngleSharp.Html.Parser.HtmlParser().ParseDocument("
");
var layout = new BrowserLayoutEngine().Layout(doc, new(800, 600));
var a = layout.GetBoundingClientRect(doc.GetElementById("A")!); var b = layout.GetBoundingClientRect(doc.GetElementById("B")!);
Assert.Equal(400, a.Width); Assert.Equal(a.X, b.X); Assert.Equal(a.Bottom, b.Y);
}
private sealed class Fixture(string html, string? policy = null) : IWebTransport
{
internal readonly Dictionary Resources = [];
internal readonly Dictionary Images = [];
internal readonly List Requests = [];
public WebResponse Get(Uri address, BrowserLimits limits)
{
Requests.Add(address);
if (Images.TryGetValue(address.AbsolutePath, out var image)) return new(address, 200, "image/svg+xml", "", true, BinaryBody: image);
return Resources.TryGetValue(address.AbsolutePath, out var value) ? new(address, 200, value.Mime, value.Body, true) : new(address, 200, "text/html", html, true, policy);
}
}
}