diff --git a/tests/E2E.Agent.Tests/PlaywrightRoutes.cs b/tests/E2E.Agent.Tests/PlaywrightRoutes.cs
index 3cf9a77bf..183b3d980 100644
--- a/tests/E2E.Agent.Tests/PlaywrightRoutes.cs
+++ b/tests/E2E.Agent.Tests/PlaywrightRoutes.cs
@@ -2,8 +2,9 @@
// Modified by Dario Kondratiuk.
// SPDX-License-Identifier: Apache-2.0
-using System.Globalization;
+using System.Collections.Concurrent;
using System.Net;
+using System.Net.WebSockets;
using System.Text;
using System.Text.Json;
using System.Text.RegularExpressions;
@@ -14,14 +15,18 @@ namespace E2E.Playground;
/// The routes of the tests ported from Playwright, a port of upstream's apps/testbed/app/playwright/routes.mjs:
/// its test assets (copied from microsoft/playwright tests/assets at v1.64.1, Apache-2.0, under
/// Testbed/playwright/assets next to the test assembly) and the dynamic routes its test server sets per test.
-/// The playground serves them for any path it has no page for. This port has /content, /never and the assets so far.
+/// The playground serves them for any path it has no page for. 127.0.0.1 and localhost on the playground's
+/// port are the two origins of the cross-origin cases, and the only ones trusted.
///
-internal static class PlaywrightRoutes
+internal static partial class PlaywrightRoutes
{
- private static readonly string Root = Path.GetFullPath(Path.Combine(AppContext.BaseDirectory, "Testbed", "playwright", "assets"));
+ private const int MaxDelayMs = 30_000;
+ private const int MaxBytes = 16 << 20;
- /// Cancelled when the process exits, which releases the requests a route holds.
- private static readonly CancellationTokenSource Shutdown = CreateShutdown();
+ // .NET-only: HttpListener has no close event for a request, so a held request is released after this long.
+ private static readonly TimeSpan HeldRequestLimit = TimeSpan.FromMinutes(2);
+
+ private static readonly string Root = Path.Combine(AppContext.BaseDirectory, "Testbed", "playwright", "assets");
private static readonly Dictionary Types = new(StringComparer.Ordinal)
{
@@ -35,63 +40,198 @@ internal static class PlaywrightRoutes
[".txt"] = "text/plain",
};
+ private static readonly ConcurrentDictionary Counts = new(StringComparer.Ordinal);
+ private static readonly ConcurrentDictionary> Logs = new(StringComparer.Ordinal);
+
/// Serves one request: a dynamic route, else an asset, else a 404.
public static async Task HandleAsync(HttpListenerContext context)
{
- var response = context.Response;
- var path = context.Request.Url!.AbsolutePath;
- if (path == "/content")
+ if (context.Request.IsWebSocketRequest)
{
- var html = context.Request.QueryString["html"] ?? "";
- response.ContentType = "text/html; charset=utf-8";
- await WriteAsync(response, FromBase64Url(html)).ConfigureAwait(false);
+ await UpgradeAsync(context).ConfigureAwait(false);
return;
}
- if (path == "/never")
+ var request = context.Request;
+ var response = context.Response;
+ var port = request.LocalEndPoint.Port;
+ var path = request.Url!.AbsolutePath;
+ var query = ParseQuery(request.Url.Query);
+ switch (path)
{
- // Holds the response and never answers, as upstream's /never. It ends when the run ends (the testbed never stops before that)
- // or after upstream's longest delay, so a held request cannot outlive the run.
- try
- {
- await Task.Delay(TimeSpan.FromSeconds(30), Shutdown.Token).ConfigureAwait(false);
- }
- catch (OperationCanceledException)
- {
- // The run is ending.
- }
+ case "/content":
+ response.ContentType = "text/html; charset=utf-8";
+ await WriteAsync(response, FromBase64Url(query.GetValueOrDefault("html") ?? "")).ConfigureAwait(false);
+ return;
+ case "/echo":
+ {
+ var received = await BodyAsync(request).ConfigureAwait(false);
+ response.ContentType = "application/json";
+ response.AddHeader("access-control-allow-origin", "*");
+ await WriteAsync(response, Echo(request, received)).ConfigureAwait(false);
+ return;
+ }
- response.Abort();
- return;
- }
+ case "/status":
+ response.StatusCode = Number(query.GetValueOrDefault("code"), 200);
+ response.ContentType = "text/plain";
+ await WriteAsync(response, Encoding.UTF8.GetBytes(query.GetValueOrDefault("body") ?? "")).ConfigureAwait(false);
+ return;
+ case "/slow":
+ await Task.Delay(Bounded(query.GetValueOrDefault("ms"), 1000, MaxDelayMs)).ConfigureAwait(false);
+ response.ContentType = query.GetValueOrDefault("type") ?? "text/plain";
+ response.AddHeader("access-control-allow-origin", "*");
+ await WriteAsync(response, Encoding.UTF8.GetBytes(query.GetValueOrDefault("body") ?? "slow")).ConfigureAwait(false);
+ return;
+ case "/never":
+ await HoldAsync().ConfigureAwait(false);
+ response.Abort();
+ return;
+ case "/redirect":
+ response.StatusCode = 302;
+ response.RedirectLocation = SameServer(query.GetValueOrDefault("to"), port);
+ return;
+ case "/download":
+ response.ContentType = "application/octet-stream";
+ response.AddHeader("content-disposition", $"attachment{(query.TryGetValue("name", out var name) ? $"; filename={name}" : "")}");
+ await WriteAsync(response, Encoding.UTF8.GetBytes(query.GetValueOrDefault("body") ?? "Hello world")).ConfigureAwait(false);
+ return;
+ case "/set-cookie":
+ response.AddHeader("set-cookie", query.GetValueOrDefault("cookie") ?? "name=value");
+ response.ContentType = "text/html";
+ await WriteAsync(response, Encoding.UTF8.GetBytes("cookie")).ConfigureAwait(false);
+ return;
+ case "/respond":
+ response.StatusCode = Number(query.GetValueOrDefault("status"), 200);
+ AddHeaders(response, query.GetValueOrDefault("headers") ?? "{}");
+ await WriteAsync(response, Encoding.UTF8.GetBytes(query.GetValueOrDefault("body") ?? "")).ConfigureAwait(false);
+ return;
+ case "/cors-echo":
+ {
+ response.AddHeader("access-control-allow-origin", TrustedOrigin(request, port));
+ response.AddHeader("access-control-allow-credentials", "true");
+ response.AddHeader("access-control-allow-methods", "POST, GET, OPTIONS, DELETE");
+ response.AddHeader("access-control-allow-headers", request.Headers["access-control-request-headers"] ?? "*");
+ if (request.HttpMethod == "OPTIONS" && query.ContainsKey("preflight"))
+ {
+ response.StatusCode = 204;
+ return;
+ }
- if (path == "/respond")
- {
- var query = context.Request.QueryString;
- response.StatusCode = int.TryParse(query["status"], CultureInfo.InvariantCulture, out var status) ? status : 200;
- if (query["headers"] is { } headers)
- {
- foreach (var (name, value) in JsonSerializer.Deserialize>(headers)!)
+ var received = await BodyAsync(request).ConfigureAwait(false);
+ response.ContentType = "text/plain";
+ await WriteAsync(response, Echo(request, received)).ConfigureAwait(false);
+ return;
+ }
+
+ case "/bounce":
{
- if (name.Equals("content-type", StringComparison.OrdinalIgnoreCase))
+ var options = request.HttpMethod == "OPTIONS";
+ if (!options)
{
- response.ContentType = value;
+ response.RedirectLocation = SameServer(query.GetValueOrDefault("to"), port);
}
- else
+
+ response.AddHeader("access-control-allow-origin", TrustedOrigin(request, port));
+ response.AddHeader("access-control-allow-credentials", "true");
+ response.AddHeader("access-control-allow-headers", request.Headers["access-control-request-headers"] ?? "*");
+ if (query.TryGetValue("cookie", out var cookie))
{
- response.AddHeader(name, value);
+ response.AddHeader("set-cookie", cookie);
}
+
+ response.StatusCode = options ? 204 : Number(query.GetValueOrDefault("status"), 302);
+ return;
}
- }
- await WriteAsync(response, Encoding.UTF8.GetBytes(query["body"] ?? "")).ConfigureAwait(false);
- return;
- }
+ case "/count":
+ {
+ var count = Counts.AddOrUpdate(query.GetValueOrDefault("key") ?? "", 1, (_, current) => current + 1);
+ response.ContentType = "text/plain";
+ await WriteAsync(response, Encoding.UTF8.GetBytes((count * 11).ToString(System.Globalization.CultureInfo.InvariantCulture))).ConfigureAwait(false);
+ return;
+ }
- if (path == "/upload")
- {
- await UploadAsync(context).ConfigureAwait(false);
- return;
+ case "/options":
+ {
+ var log = Logs.GetOrAdd(query.GetValueOrDefault("key") ?? "", _ => []);
+ lock (log)
+ {
+ log.Add($"{request.HttpMethod}:{path}");
+ }
+
+ var options = request.HttpMethod == "OPTIONS";
+ response.AddHeader("access-control-allow-origin", "*");
+ if (options)
+ {
+ response.AddHeader("access-control-allow-methods", "POST, GET, OPTIONS, DELETE");
+ response.AddHeader("access-control-allow-headers", "*");
+ response.AddHeader("cache-control", "no-cache");
+ }
+
+ await WriteAsync(response, Encoding.UTF8.GetBytes(options ? "Hello" : "World")).ConfigureAwait(false);
+ return;
+ }
+
+ case "/options-log":
+ {
+ response.ContentType = "application/json";
+ var log = Logs.GetValueOrDefault(query.GetValueOrDefault("key") ?? "") ?? [];
+ string[] entries;
+ lock (log)
+ {
+ entries = [.. log];
+ }
+
+ await WriteAsync(response, JsonSerializer.SerializeToUtf8Bytes(entries)).ConfigureAwait(false);
+ return;
+ }
+
+ case "/upload":
+ {
+ var received = await BodyAsync(request).ConfigureAwait(false);
+ response.ContentType = "text/plain";
+ response.AddHeader("access-control-allow-origin", "*");
+ await WriteAsync(response, JsonSerializer.SerializeToUtf8Bytes(Files(received, request.ContentType ?? ""))).ConfigureAwait(false);
+ return;
+ }
+
+ case "/binary":
+ {
+ var data = new byte[Bounded(query.GetValueOrDefault("bytes"), 1 << 20, MaxBytes)];
+ for (var i = 0; i < data.Length; i++)
+ {
+ data[i] = (byte)(unchecked((uint)((i + 1) * 2654435761L)) >> 24);
+ }
+
+ response.ContentType = "application/zip";
+ await WriteAsync(response, data).ConfigureAwait(false);
+ return;
+ }
+
+ case "/download-stall":
+ {
+ response.ContentType = "application/octet-stream";
+ response.AddHeader("content-disposition", "attachment; filename=file.txt");
+ response.SendChunked = true;
+ await response.OutputStream.WriteAsync(Encoding.ASCII.GetBytes(new string('a', 4096) + "foo")).ConfigureAwait(false);
+ await response.OutputStream.FlushAsync().ConfigureAwait(false);
+ await HoldAsync().ConfigureAwait(false);
+ response.Abort();
+ return;
+ }
+
+ case "/sse":
+ {
+ response.ContentType = "text/event-stream";
+ response.AddHeader("cache-control", "no-cache");
+ response.SendChunked = true;
+ await response.OutputStream.WriteAsync(Encoding.ASCII.GetBytes("data: hello\n\n")).ConfigureAwait(false);
+ await response.OutputStream.FlushAsync().ConfigureAwait(false);
+ await HoldAsync().ConfigureAwait(false);
+ response.Abort();
+ return;
+ }
}
var file = Path.GetFullPath(Path.Combine(Root, Uri.UnescapeDataString(path).TrimStart('/')));
@@ -108,62 +248,186 @@ public static async Task HandleAsync(HttpListenerContext context)
await WriteAsync(response, await File.ReadAllBytesAsync(file).ConfigureAwait(false)).ConfigureAwait(false);
}
- private static CancellationTokenSource CreateShutdown()
+ ///
+ /// /ws accepts the handshake and holds the socket open, as Playwright's server does, so an open WebSocket is in the
+ /// page during network-idle tests. Any other path is refused.
+ ///
+ private static async Task UpgradeAsync(HttpListenerContext context)
{
- var source = new CancellationTokenSource();
- AppDomain.CurrentDomain.ProcessExit += (_, _) => source.Cancel();
- return source;
+ if (context.Request.Url!.AbsolutePath != "/ws")
+ {
+ context.Response.Abort();
+ return;
+ }
+
+ var socket = (await context.AcceptWebSocketAsync(null).ConfigureAwait(false)).WebSocket;
+ using var limit = new CancellationTokenSource(HeldRequestLimit);
+ var buffer = new byte[256];
+ try
+ {
+ while (socket.State == WebSocketState.Open)
+ {
+ var received = await socket.ReceiveAsync(buffer, limit.Token).ConfigureAwait(false);
+ if (received.MessageType == WebSocketMessageType.Close)
+ {
+ break;
+ }
+ }
+ }
+ catch (Exception ex) when (ex is WebSocketException or OperationCanceledException)
+ {
+ }
+ finally
+ {
+ socket.Abort();
+ socket.Dispose();
+ }
}
- /// Answers a multipart form with the files it carried as JSON, as upstream's /upload: name, filename, mimetype, size, and the bytes (base64) of a file up to 64 KB.
- private static async Task UploadAsync(HttpListenerContext context)
+ /// A redirect target on this server (a path, or either origin), else the empty page.
+ private static string SameServer(string? target, int port)
{
- using var received = new MemoryStream();
- await context.Request.InputStream.CopyToAsync(received).ConfigureAwait(false);
- var data = received.GetBuffer().AsMemory(0, (int)received.Length);
- var type = context.Request.ContentType ?? "";
- var marker = type.IndexOf("boundary=", StringComparison.Ordinal);
- var boundary = Encoding.UTF8.GetBytes("--" + (marker < 0 ? "" : type[(marker + "boundary=".Length)..]));
- var files = new List>();
- var start = data.Span.IndexOf(boundary);
- while (start >= 0)
+ if (target is null)
+ {
+ return "/empty.html";
+ }
+
+ var origin = new Uri($"http://127.0.0.1:{port}");
+ if (!Uri.TryCreate(origin, target, out var resolved) || resolved.Scheme != "http" || resolved.Port != port || resolved.Host is not ("127.0.0.1" or "localhost"))
{
- var afterStart = start + boundary.Length;
- var relative = data.Span[afterStart..].IndexOf(boundary);
- if (relative < 0)
+ return "/empty.html";
+ }
+
+ return target.StartsWith('/') ? resolved.PathAndQuery + resolved.Fragment : resolved.AbsoluteUri;
+ }
+
+ ///
+ /// The request's origin when it is one of the server's own, the only ones granted credentials, or null,
+ /// the origin a cross-origin redirect leaves.
+ ///
+ private static string TrustedOrigin(HttpListenerRequest request, int port)
+ {
+ var origin = request.Headers["origin"];
+ if (origin == "null")
+ {
+ return "null";
+ }
+
+ return origin is not null && (origin == $"http://127.0.0.1:{port}" || origin == $"http://localhost:{port}") ? origin : $"http://127.0.0.1:{port}";
+ }
+
+ /// The request as JSON: { method, headers, body, url }.
+ private static byte[] Echo(HttpListenerRequest request, byte[] body)
+ {
+ var headers = new Dictionary(StringComparer.Ordinal);
+ foreach (var name in request.Headers.AllKeys)
+ {
+ if (name is not null)
{
- break;
+ headers[name.ToLowerInvariant()] = request.Headers[name]!;
+ }
+ }
+
+ return JsonSerializer.SerializeToUtf8Bytes(new { method = request.HttpMethod, headers, body = Encoding.UTF8.GetString(body), url = request.RawUrl });
+ }
+
+ /// The headers of a JSON object, a header with an array value sent once for each item.
+ private static void AddHeaders(HttpListenerResponse response, string json)
+ {
+ using var headers = JsonDocument.Parse(json);
+ foreach (var header in headers.RootElement.EnumerateObject())
+ {
+ JsonElement[] values = header.Value.ValueKind == JsonValueKind.Array ? [.. header.Value.EnumerateArray()] : [header.Value];
+ foreach (var value in values)
+ {
+ var text = value.ToString();
+ switch (header.Name.ToLowerInvariant())
+ {
+ case "content-type":
+ response.ContentType = text;
+ break;
+ case "location":
+ response.RedirectLocation = text;
+ break;
+ default:
+ response.AppendHeader(header.Name, text);
+ break;
+ }
}
+ }
+ }
- var next = afterStart + relative;
- var part = data[(afterStart + 2)..(next - 2)];
- var split = part.Span.IndexOf("\r\n\r\n"u8);
- if (split < 0)
+ /// The parts of a multipart body, as /upload answers with them.
+ private static List