Server reale e veste Docker (M5): composizione, collegamento, vista remota, salute, immagine e modello Unraid
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Mzbb6zeFTjT6Rp8b92AVkA
This commit is contained in:
35 files changed
+6124
-10
No files matched your search
@@ -0,0 +1,207 @@
|
||||
using System.Net;
|
||||
using System.Net.WebSockets;
|
||||
using System.Text;
|
||||
using Febe.Server;
|
||||
using Febe.Tests.Server.Support;
|
||||
using Febe.Tests.Web.Support;
|
||||
using Febe.Web;
|
||||
using Febe.Web.Connection;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
|
||||
namespace Febe.Tests.Server;
|
||||
|
||||
/// <summary>
|
||||
/// <c>/api/vista</c> (PROTOCOLLO.md, spec §13.1) without a browser: session and Origin checks, frames as binary
|
||||
/// messages, meta as text, input parsed and forwarded, limits, and the reasons a view ends.
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
public sealed class RemoteViewSocketTests
|
||||
{
|
||||
private const string Password = "la password della vista";
|
||||
|
||||
public TestContext TestContext { get; set; } = null!;
|
||||
|
||||
[TestMethod]
|
||||
public async Task TheViewNeedsTheSessionAndTheOriginOfTheInterface()
|
||||
{
|
||||
var host = new FakeRemoteViewHost();
|
||||
await using var server = await StartAsync(host);
|
||||
var cookies = await LoginAsync(server);
|
||||
|
||||
// No session: refused before the WebSocket opens.
|
||||
Assert.AreEqual(HttpStatusCode.Unauthorized, await RefusedAsync(server, null, server.Origin));
|
||||
|
||||
// Another page (another origin) cannot open it, even with the session cookie of Alberto's browser.
|
||||
Assert.AreEqual(HttpStatusCode.Forbidden, await RefusedAsync(server, cookies, "http://pagina-di-altri.example"));
|
||||
Assert.IsEmpty(host.Opened);
|
||||
|
||||
// The interface itself can.
|
||||
using var socket = await ConnectAsync(server, cookies);
|
||||
Assert.AreEqual(WebSocketState.Open, socket.State);
|
||||
Assert.HasCount(1, host.Opened);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task FramesAreBinaryMetaIsTextAndGesturesComeBack()
|
||||
{
|
||||
var host = new FakeRemoteViewHost();
|
||||
await using var server = await StartAsync(host);
|
||||
var cookies = await LoginAsync(server);
|
||||
using var socket = await ConnectAsync(server, cookies);
|
||||
var view = host.Opened.Single();
|
||||
|
||||
view.Write(new RemoteViewMeta(1279, 760, "http://127.0.0.1:8481/benvenuto"));
|
||||
view.Write(new RemoteViewFrame(new byte[] { 0xFF, 0xD8, 1, 2, 3, 0xFF, 0xD9 }));
|
||||
var (metaType, meta) = await ReceiveAsync(socket);
|
||||
Assert.AreEqual(WebSocketMessageType.Text, metaType);
|
||||
Assert.AreEqual("""{"type":"meta","width":1279,"height":760,"url":"http://127.0.0.1:8481/benvenuto"}""", Encoding.UTF8.GetString(meta));
|
||||
var (frameType, frame) = await ReceiveAsync(socket);
|
||||
Assert.AreEqual(WebSocketMessageType.Binary, frameType);
|
||||
CollectionAssert.AreEqual(new byte[] { 0xFF, 0xD8, 1, 2, 3, 0xFF, 0xD9 }, frame);
|
||||
|
||||
foreach (var message in new[]
|
||||
{
|
||||
"""{"type":"mouse","action":"down","x":0.25,"y":0.5,"button":"left","clickCount":1}""",
|
||||
"""{"type":"key","action":"down","key":"a","code":"KeyA","text":"a","modifiers":0}""",
|
||||
"""{"type":"key","action":"char","text":"è"}""",
|
||||
"""{"type":"navigate","action":"back"}""",
|
||||
"""{"type":"mouse","action":"move","x":1.5,"y":0.5}""",
|
||||
"""{"type":"navigate","action":"vai","url":"https://altrove.example/"}""",
|
||||
"""{"type":"script","code":"alert(1)"}""",
|
||||
"non è JSON",
|
||||
})
|
||||
{
|
||||
await socket.SendAsync(Encoding.UTF8.GetBytes(message), WebSocketMessageType.Text, true, TestContext.CancellationToken);
|
||||
}
|
||||
|
||||
await ServerTestBed.WaitUntilAsync(() => Task.FromResult(view.Inputs.Count >= 4), TimeSpan.FromSeconds(10), "quattro gesti inoltrati");
|
||||
await Task.Delay(200);
|
||||
var inputs = view.Inputs.ToArray();
|
||||
Assert.HasCount(4, inputs, "out-of-range, unknown and malformed messages are dropped");
|
||||
var mouse = (RemoteViewMouse)inputs[0];
|
||||
Assert.AreEqual(RemoteViewMouseAction.Down, mouse.Action);
|
||||
Assert.AreEqual(0.25, mouse.X);
|
||||
Assert.AreEqual(RemoteViewButton.Left, mouse.Button);
|
||||
var key = (RemoteViewKey)inputs[1];
|
||||
Assert.AreEqual(RemoteViewKeyAction.Down, key.Action);
|
||||
Assert.AreEqual("a", key.Text);
|
||||
Assert.AreEqual("RemoteViewKey(…)", key.ToString(), "a key never shows in a log line");
|
||||
Assert.AreEqual(RemoteViewKeyAction.Char, ((RemoteViewKey)inputs[2]).Action);
|
||||
Assert.AreEqual(RemoteViewNavigation.Back, inputs[3]);
|
||||
|
||||
await socket.CloseAsync(WebSocketCloseStatus.NormalClosure, "fine", TestContext.CancellationToken);
|
||||
await ServerTestBed.WaitUntilAsync(() => Task.FromResult(view.Disposed), TimeSpan.FromSeconds(10), "la vista chiusa dal server");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task AViewOpenedElsewhereReplacesTheOldOneAndATooLongMessageClosesIt()
|
||||
{
|
||||
var host = new FakeRemoteViewHost();
|
||||
await using var server = await StartAsync(host);
|
||||
var cookies = await LoginAsync(server);
|
||||
using var first = await ConnectAsync(server, cookies);
|
||||
using var second = await ConnectAsync(server, cookies);
|
||||
await ExpectCloseAsync(first, (WebSocketCloseStatus)RemoteViewSocket.CloseReplaced);
|
||||
Assert.AreEqual(RemoteViewEnd.Replaced, host.Opened[0].Ended);
|
||||
|
||||
await second.SendAsync(new byte[RemoteViewSocket.MaxMessageBytes + 10], WebSocketMessageType.Text, true, TestContext.CancellationToken);
|
||||
await ExpectCloseAsync(second, WebSocketCloseStatus.MessageTooBig);
|
||||
await ServerTestBed.WaitUntilAsync(() => Task.FromResult(host.Opened[1].Disposed), TimeSpan.FromSeconds(10), "la vista chiusa");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task WithoutBrowserOrOnTheDesktopThereIsNoView()
|
||||
{
|
||||
var host = new FakeRemoteViewHost { Unavailable = true };
|
||||
await using var server = await StartAsync(host);
|
||||
var cookies = await LoginAsync(server);
|
||||
Assert.AreEqual(HttpStatusCode.ServiceUnavailable, await RefusedAsync(server, cookies, server.Origin));
|
||||
|
||||
// A plain request is not a WebSocket.
|
||||
using var client = new HttpClient(new HttpClientHandler { CookieContainer = cookies }) { BaseAddress = server.Address };
|
||||
using (var plain = await client.GetAsync("/api/vista", TestContext.CancellationToken))
|
||||
{
|
||||
Assert.AreEqual(HttpStatusCode.BadRequest, plain.StatusCode);
|
||||
}
|
||||
|
||||
await using var desktop = await WebTestServer.StartAsync(new FebeWebOptions { Edition = FebeEdition.Desktop, Access = AccessMode.None }, s => s.AddSingleton<IRemoteViewHost>(new FakeRemoteViewHost()));
|
||||
using var response = await desktop.Client.GetAsync("/api/vista", TestContext.CancellationToken);
|
||||
Assert.AreEqual(HttpStatusCode.NotFound, response.StatusCode);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void KeysGetTheVirtualCodesChromiumNeeds()
|
||||
{
|
||||
Assert.AreEqual(65, RemoteKeys.ToStroke(new RemoteViewKey(RemoteViewKeyAction.Down, "a", "KeyA", "a", 0)).KeyCode);
|
||||
Assert.AreEqual(8, RemoteKeys.ToStroke(new RemoteViewKey(RemoteViewKeyAction.Down, "Backspace", "Backspace", null, 0)).KeyCode);
|
||||
var enter = RemoteKeys.ToStroke(new RemoteViewKey(RemoteViewKeyAction.Down, "Enter", "Enter", null, 0));
|
||||
Assert.AreEqual(13, enter.KeyCode);
|
||||
Assert.AreEqual("\r", enter.Text, "Enter submits forms only with its text");
|
||||
Assert.AreEqual(50, RemoteKeys.ToStroke(new RemoteViewKey(RemoteViewKeyAction.Down, "\"", "Digit2", "\"", 8)).KeyCode, "Italian layout: Shift+2");
|
||||
Assert.AreEqual(219, RemoteKeys.ToStroke(new RemoteViewKey(RemoteViewKeyAction.Down, "è", "BracketLeft", "è", 0)).KeyCode, "Italian layout: è");
|
||||
Assert.AreEqual("KeyStroke(…)", RemoteKeys.ToStroke(new RemoteViewKey(RemoteViewKeyAction.Down, "x", "KeyX", "x", 0)).ToString());
|
||||
Assert.AreEqual("http://127.0.0.1:8481/profilo/marta.prova/", BrowserRemoteViewConnection.WithoutQuery("http://127.0.0.1:8481/profilo/marta.prova/?gettone=segreto#x"));
|
||||
Assert.AreEqual("about:blank", BrowserRemoteViewConnection.WithoutQuery("about:blank"));
|
||||
}
|
||||
|
||||
private static Task<WebTestServer> StartAsync(FakeRemoteViewHost host) =>
|
||||
WebTestServer.StartAsync(
|
||||
new FebeWebOptions { Edition = FebeEdition.Docker, Access = AccessMode.Password, Password = Password },
|
||||
s => s.AddSingleton<IRemoteViewHost>(host));
|
||||
|
||||
private async Task<CookieContainer> LoginAsync(WebTestServer server)
|
||||
{
|
||||
var cookies = new CookieContainer();
|
||||
using var client = new HttpClient(new HttpClientHandler { CookieContainer = cookies, UseCookies = true }) { BaseAddress = server.Address };
|
||||
using var request = server.Request(HttpMethod.Post, "/api/accesso", $$"""{"password":"{{Password}}"}""");
|
||||
using var response = await client.SendAsync(request, TestContext.CancellationToken);
|
||||
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
|
||||
return cookies;
|
||||
}
|
||||
|
||||
private async Task<ClientWebSocket> ConnectAsync(WebTestServer server, CookieContainer cookies)
|
||||
{
|
||||
var socket = new ClientWebSocket();
|
||||
socket.Options.Cookies = cookies;
|
||||
socket.Options.SetRequestHeader("Origin", server.Origin);
|
||||
await socket.ConnectAsync(new UriBuilder(server.Address) { Scheme = "ws", Path = RemoteViewSocket.Path }.Uri, TestContext.CancellationToken);
|
||||
return socket;
|
||||
}
|
||||
|
||||
private async Task<HttpStatusCode?> RefusedAsync(WebTestServer server, CookieContainer? cookies, string origin)
|
||||
{
|
||||
using var socket = new ClientWebSocket();
|
||||
socket.Options.CollectHttpResponseDetails = true;
|
||||
socket.Options.SetRequestHeader("Origin", origin);
|
||||
if (cookies is not null)
|
||||
{
|
||||
socket.Options.Cookies = cookies;
|
||||
}
|
||||
|
||||
await Assert.ThrowsAsync<WebSocketException>(() => socket.ConnectAsync(new UriBuilder(server.Address) { Scheme = "ws", Path = RemoteViewSocket.Path }.Uri, TestContext.CancellationToken));
|
||||
return socket.HttpStatusCode;
|
||||
}
|
||||
|
||||
private async Task<(WebSocketMessageType Type, byte[] Data)> ReceiveAsync(ClientWebSocket socket)
|
||||
{
|
||||
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(TestContext.CancellationToken);
|
||||
timeout.CancelAfter(TimeSpan.FromSeconds(10));
|
||||
var buffer = new byte[8192];
|
||||
using var data = new MemoryStream();
|
||||
WebSocketReceiveResult result;
|
||||
do
|
||||
{
|
||||
result = await socket.ReceiveAsync(buffer, timeout.Token);
|
||||
data.Write(buffer, 0, result.Count);
|
||||
}
|
||||
while (!result.EndOfMessage);
|
||||
return (result.MessageType, data.ToArray());
|
||||
}
|
||||
|
||||
private async Task ExpectCloseAsync(ClientWebSocket socket, WebSocketCloseStatus status)
|
||||
{
|
||||
var (type, _) = await ReceiveAsync(socket);
|
||||
Assert.AreEqual(WebSocketMessageType.Close, type);
|
||||
Assert.AreEqual(status, socket.CloseStatus);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,265 @@
|
||||
using System.Net;
|
||||
using System.Net.WebSockets;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Text.RegularExpressions;
|
||||
using Febe.Core.Domain;
|
||||
using Febe.Core.Library;
|
||||
using Febe.Core.Storage;
|
||||
using Febe.SitoDiProva;
|
||||
using Febe.Tests.Server.Support;
|
||||
using Febe.Web.Connection;
|
||||
|
||||
namespace Febe.Tests.Server;
|
||||
|
||||
/// <summary>
|
||||
/// The real composition of the server (milestone M5) against the local test site, with Xvfb and a real Chromium: the
|
||||
/// password, the connection through the login page, accounts added through the API, «Controlla ora», a real session of
|
||||
/// the engine with the Governor's permits, files and thumbnails in the library, the stop on the verification page and
|
||||
/// the remote view. Never Instagram: the browser only sees 127.0.0.1.
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
[DoNotParallelize]
|
||||
public sealed partial class ServerEndToEndTests
|
||||
{
|
||||
public TestContext TestContext { get; set; } = null!;
|
||||
|
||||
[TestInitialize]
|
||||
public void RequireBrowser()
|
||||
{
|
||||
if (ServerTestBed.UnavailableReason() is { } reason)
|
||||
{
|
||||
Assert.Inconclusive(reason);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[Timeout(360_000, CooperativeCancellation = true)]
|
||||
public async Task TheRealServerCollectsFromTheTestSiteStopsAtTheVerificationAndShowsTheBrowser()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
await using var bed = await ServerTestBed.StartAsync();
|
||||
var server = bed.Server;
|
||||
Assert.IsEmpty(server.Problems);
|
||||
await server.Running.WaitAsync(TimeSpan.FromSeconds(60), ct);
|
||||
var connection = server.Connection!;
|
||||
|
||||
// The health check answers without a session; everything else wants the password.
|
||||
using (var health = await bed.Client.GetAsync("/salute", ct))
|
||||
{
|
||||
Assert.AreEqual(HttpStatusCode.OK, health.StatusCode);
|
||||
Assert.AreEqual("""{"stato":"ok"}""", await health.Content.ReadAsStringAsync(ct));
|
||||
}
|
||||
|
||||
using (var anonymous = await bed.Client.GetAsync("/api/accounts", ct))
|
||||
{
|
||||
Assert.AreEqual(HttpStatusCode.Unauthorized, anonymous.StatusCode);
|
||||
}
|
||||
|
||||
await bed.LoginAsync();
|
||||
|
||||
// A fresh profile: not connected, the engine waits.
|
||||
Assert.AreEqual(ConnectionState.NotConnected, (await connection.GetStatusAsync(ct)).State);
|
||||
|
||||
// Accounts added through the API, as from the «Aggiungi account» dialog.
|
||||
var added = await bed.JsonAsync(HttpMethod.Post, "/api/accounts", """{"usernames":["marta.prova","luca.prova"],"start":"everything"}""");
|
||||
Assert.AreEqual(2, added.GetProperty("added").GetInt32());
|
||||
var marta = await server.Database.Accounts.FindByUsernameAsync("marta.prova", ct) ?? throw new AssertFailedException("marta.prova manca");
|
||||
|
||||
// «Accedi a Instagram» opens the login page (here: the test site, whose first visit starts its session);
|
||||
// meanwhile Alberto is driving and the engine is still.
|
||||
await connection.BeginUserDrivingAsync(openLogin: true, ct);
|
||||
var driving = await connection.GetStatusAsync(ct);
|
||||
Assert.IsTrue(driving.UserIsDriving);
|
||||
Assert.IsTrue(server.Browser!.UserIsDriving);
|
||||
StringAssert.StartsWith(driving.CurrentUrl, bed.Site.SiteUrl, "the login page of the configured site, never Instagram in tests");
|
||||
|
||||
var finish = await connection.FinishAsync(ct);
|
||||
Assert.IsTrue(finish.Connected, finish.Message);
|
||||
Assert.IsFalse(server.Browser.UserIsDriving, "«Ho finito» ends the driving");
|
||||
Assert.IsNotNull(await server.Database.Settings.GetInt64Async(Febe.Server.ServerConnectionService.FirstConnectionKey, ct), "first connection recorded");
|
||||
Assert.AreEqual(ConnectionState.Connected, (await connection.GetStatusAsync(ct)).State);
|
||||
|
||||
// «Controlla ora».
|
||||
var check = await bed.JsonAsync(HttpMethod.Post, $"/api/accounts/{marta.Id}/check-now");
|
||||
if (check.GetProperty("status").GetString() == "needsConfirmation")
|
||||
{
|
||||
check = await bed.JsonAsync(HttpMethod.Post, $"/api/accounts/{marta.Id}/check-now", $$"""{"token":"{{check.GetProperty("token").GetString()}}"}""");
|
||||
}
|
||||
|
||||
Assert.AreEqual("queued", check.GetProperty("status").GetString(), check.GetProperty("message").GetString());
|
||||
|
||||
// The engine runs a session: every action toward the site has its Governor's permit in action_log.
|
||||
await ServerTestBed.WaitUntilAsync(
|
||||
async () => (await server.Database.ActionLog.ListAsync(DateTimeOffset.UnixEpoch, bed.Clock.Now.AddDays(1), ct)).Any(a => a.AccountId == marta.Id),
|
||||
TimeSpan.FromSeconds(90),
|
||||
"un'azione del motore su marta.prova nel registro delle azioni");
|
||||
var actions = await server.Database.ActionLog.ListAsync(DateTimeOffset.UnixEpoch, bed.Clock.Now.AddDays(1), ct);
|
||||
Assert.IsTrue(actions.All(a => a.SessionId is not null), "every counted action belongs to a session");
|
||||
Assert.IsNotNull(await server.Database.Sessions.GetLastAsync(ct));
|
||||
|
||||
// Files arrive in the library with the names of the scheme, and their thumbnails.
|
||||
var library = bed.Library;
|
||||
var thumbnails = bed.Thumbnails;
|
||||
List<(Entry Entry, Media Media)> stored = [];
|
||||
await ServerTestBed.WaitUntilAsync(
|
||||
async () =>
|
||||
{
|
||||
stored = await StoredAsync(server, marta.Id, ct);
|
||||
return stored.Count >= 3;
|
||||
},
|
||||
TimeSpan.FromSeconds(90),
|
||||
"tre file di marta.prova scaricati");
|
||||
foreach (var (entry, media) in stored)
|
||||
{
|
||||
var path = library.FullPath(marta, media.RelativePath!);
|
||||
Assert.IsTrue(File.Exists(path), path);
|
||||
Assert.AreEqual(media.Bytes, new FileInfo(path).Length, path);
|
||||
Assert.MatchesRegex(NamePattern(), media.RelativePath!, "naming scheme {tipo}/{anno}/{data}_{ora}_{codice}_{n}");
|
||||
if (media.Kind == MediaKind.Photo)
|
||||
{
|
||||
Assert.IsTrue(thumbnails.Exists(media.Sha256!), $"thumbnail of {media.RelativePath}");
|
||||
}
|
||||
}
|
||||
|
||||
Assert.IsTrue(File.Exists(Path.Combine(library.AccountFolder(marta), AccountJournal.FileName)), "_febe.jsonl");
|
||||
var recipes = (await server.Database.Events.ListAsync(new EventQuery(), ct)).Where(e => e.Code.StartsWith("ricetta.", StringComparison.Ordinal)).ToList();
|
||||
Assert.IsNotEmpty(recipes, "one event line per recipe run");
|
||||
TestContext.WriteLine($"Ricette: {string.Join(", ", recipes.Select(r => r.Code).Distinct())}; file di marta.prova: {stored.Count}.");
|
||||
|
||||
// The site asks for a verification: at its next action toward the site the engine stops and the banner appears
|
||||
// in /api/engine. Usually still in the first session (two accounts to read in full); if that session already
|
||||
// ended, in the next one, after the minimum pause (20 minutes at 10×: two real minutes).
|
||||
var servedBefore = bed.Site.Control.CdnFilesServed;
|
||||
bed.Site.Control.Set(StopMode.Challenge);
|
||||
await ServerTestBed.WaitUntilAsync(
|
||||
async () =>
|
||||
{
|
||||
var engine = await bed.JsonAsync(HttpMethod.Get, "/api/engine");
|
||||
var snapshot = engine.GetProperty("snapshot");
|
||||
return snapshot.GetProperty("mode").GetString() == "StoppedForVerification" && snapshot.GetProperty("banner").ValueKind == JsonValueKind.Object;
|
||||
},
|
||||
TimeSpan.FromSeconds(200),
|
||||
"la striscia di arresto per la verifica in /api/engine");
|
||||
Assert.AreEqual(ConnectionState.VerificationRequired, (await connection.GetStatusAsync(ct)).State);
|
||||
TestContext.WriteLine($"CDN: {servedBefore} file prima del fermo, {bed.Site.Control.CdnFilesServed} adesso.");
|
||||
|
||||
// The remote view: meta first, then JPEG frames; Alberto is driving while it is open.
|
||||
using (var socket = await bed.OpenRemoteViewAsync(ct))
|
||||
{
|
||||
var (metaType, meta) = await ReceiveAsync(socket, ct);
|
||||
Assert.AreEqual(WebSocketMessageType.Text, metaType);
|
||||
using var metaJson = JsonDocument.Parse(meta);
|
||||
Assert.AreEqual("meta", metaJson.RootElement.GetProperty("type").GetString());
|
||||
Assert.IsGreaterThan(0, metaJson.RootElement.GetProperty("width").GetInt32());
|
||||
Assert.IsTrue(server.Browser.UserIsDriving, "the engine is still while the view is open");
|
||||
|
||||
byte[]? jpeg = null;
|
||||
for (var i = 0; i < 20 && jpeg is null; i++)
|
||||
{
|
||||
// A gesture makes the page repaint, so a frame comes even on a still page.
|
||||
await SendAsync(socket, """{"type":"mouse","action":"move","x":0.5,"y":0.5}""", ct);
|
||||
var (type, data) = await ReceiveAsync(socket, ct);
|
||||
if (type == WebSocketMessageType.Binary)
|
||||
{
|
||||
jpeg = data;
|
||||
}
|
||||
}
|
||||
|
||||
Assert.IsNotNull(jpeg, "a JPEG frame");
|
||||
Assert.AreEqual(0xFF, jpeg[0]);
|
||||
Assert.AreEqual(0xD8, jpeg[1]);
|
||||
await socket.CloseAsync(WebSocketCloseStatus.NormalClosure, "fine", ct);
|
||||
}
|
||||
|
||||
await ServerTestBed.WaitUntilAsync(() => Task.FromResult(!server.Browser.UserIsDriving), TimeSpan.FromSeconds(10), "la vista chiusa libera il browser");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[Timeout(120_000, CooperativeCancellation = true)]
|
||||
public async Task FinishWithoutSessionSaysSoAndDisconnectDeletesTheProfile()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
await using var bed = await ServerTestBed.StartAsync(autoLogin: true);
|
||||
var server = bed.Server;
|
||||
await server.Running.WaitAsync(TimeSpan.FromSeconds(60), ct);
|
||||
var connection = server.Connection!;
|
||||
Assert.AreEqual(ConnectionState.Connected, (await connection.GetStatusAsync(ct)).State, "the test site's automatic login");
|
||||
|
||||
// «Scollega»: engine stopped, profile deleted, browser restarted empty.
|
||||
var marker = Path.Combine(server.Browser!.ProfileDirectory, "segno-della-prova");
|
||||
await File.WriteAllTextAsync(marker, "x", ct);
|
||||
await connection.DisconnectAsync(ct);
|
||||
Assert.IsFalse(File.Exists(marker), "the profile folder was deleted");
|
||||
Assert.IsTrue(server.Browser.IsAvailable, "the browser runs again, with an empty profile");
|
||||
Assert.AreEqual(ConnectionState.NotConnected, (await connection.GetStatusAsync(ct)).State);
|
||||
Assert.IsFalse(server.Browser.UserIsDriving);
|
||||
Assert.IsTrue(server.Engine!.Services.Runtime.IsRunning || await WaitRunningAsync(server), "the engine loop runs again (and waits for a connection)");
|
||||
|
||||
// «Ho finito» without having logged in: Febe says it does not find the session.
|
||||
await connection.BeginUserDrivingAsync(openLogin: false, ct);
|
||||
Assert.IsTrue(server.Browser.UserIsDriving);
|
||||
var finish = await connection.FinishAsync(ct);
|
||||
Assert.IsFalse(finish.Connected);
|
||||
StringAssert.Contains(finish.Message, "non trova la sessione");
|
||||
Assert.IsFalse(server.Browser.UserIsDriving);
|
||||
|
||||
// «Annulla» ends the driving and leaves the browser on the rest page.
|
||||
await connection.BeginUserDrivingAsync(openLogin: true, ct);
|
||||
await connection.CancelAsync(ct);
|
||||
Assert.IsFalse(server.Browser.UserIsDriving);
|
||||
Assert.AreEqual("about:blank", (await connection.GetStatusAsync(ct)).CurrentUrl);
|
||||
|
||||
// The debugging port listens on 127.0.0.1 only.
|
||||
Assert.IsTrue(Febe.Browser.Hosting.LoopbackPortCheck.IsLoopbackOnly(bed.Options.DebugPort, out _));
|
||||
}
|
||||
|
||||
private static async Task<bool> WaitRunningAsync(Febe.Server.FebeServer server)
|
||||
{
|
||||
for (var i = 0; i < 40 && !server.Engine!.Services.Runtime.IsRunning; i++)
|
||||
{
|
||||
await Task.Delay(100);
|
||||
}
|
||||
|
||||
return server.Engine!.Services.Runtime.IsRunning;
|
||||
}
|
||||
|
||||
private static async Task<List<(Entry Entry, Media Media)>> StoredAsync(Febe.Server.FebeServer server, long accountId, CancellationToken ct)
|
||||
{
|
||||
var list = new List<(Entry, Media)>();
|
||||
foreach (var entry in await server.Database.Entries.ListByAccountAsync(accountId, null, ct))
|
||||
{
|
||||
foreach (var media in await server.Database.Media.ListByEntryAsync(entry.Id, ct))
|
||||
{
|
||||
if (media.State == MediaState.Downloaded && media.RelativePath is not null && media.Sha256 is not null && entry.Kind != EntryKind.ProfilePicture)
|
||||
{
|
||||
list.Add((entry, media));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return list;
|
||||
}
|
||||
|
||||
private static Task SendAsync(ClientWebSocket socket, string json, CancellationToken ct) =>
|
||||
socket.SendAsync(Encoding.UTF8.GetBytes(json), WebSocketMessageType.Text, endOfMessage: true, ct);
|
||||
|
||||
private static async Task<(WebSocketMessageType Type, byte[] Data)> ReceiveAsync(ClientWebSocket socket, CancellationToken ct)
|
||||
{
|
||||
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct);
|
||||
timeout.CancelAfter(TimeSpan.FromSeconds(10));
|
||||
using var buffer = new MemoryStream();
|
||||
var chunk = new byte[64 * 1024];
|
||||
WebSocketReceiveResult result;
|
||||
do
|
||||
{
|
||||
result = await socket.ReceiveAsync(chunk, timeout.Token);
|
||||
buffer.Write(chunk, 0, result.Count);
|
||||
}
|
||||
while (!result.EndOfMessage);
|
||||
return (result.MessageType, buffer.ToArray());
|
||||
}
|
||||
|
||||
[GeneratedRegex(@"^(post|storie|evidenza/[^/]+|taggati)/(\d{4}/)?\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2}_[^_/]+_\d+\.(jpg|mp4)$")]
|
||||
private static partial Regex NamePattern();
|
||||
}
|
||||
@@ -0,0 +1,174 @@
|
||||
using System.Net;
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Server;
|
||||
using Febe.Tests.Support;
|
||||
using Febe.Web;
|
||||
|
||||
namespace Febe.Tests.Server;
|
||||
|
||||
/// <summary>The configuration of the container (spec §11) and the log of the server (spec §8.2, §13.2).</summary>
|
||||
[TestClass]
|
||||
public sealed class ServerOptionsTests
|
||||
{
|
||||
[TestMethod]
|
||||
public void TheContainerDefaultsAreThoseOfTheSpecification()
|
||||
{
|
||||
Assert.IsTrue(ServerOptions.TryParse([], Env(("FEBE_PASSWORD", "segreta")), out var o, out var problem), problem);
|
||||
Assert.AreEqual("segreta", o.Password);
|
||||
Assert.AreEqual(8480, o.Port);
|
||||
Assert.AreEqual(IPAddress.Any, o.ListenAddress);
|
||||
Assert.AreEqual("Europe/Rome", o.ZoneId);
|
||||
Assert.AreEqual("it_IT.UTF-8", o.Language);
|
||||
Assert.AreEqual("/dati", o.DataFolder);
|
||||
Assert.AreEqual("/libreria", o.LibraryFolder);
|
||||
Assert.AreEqual("/importa", o.ImportFolder);
|
||||
Assert.AreEqual(9222, o.DebugPort);
|
||||
Assert.AreEqual(":99", o.Display);
|
||||
Assert.IsFalse(o.NoSandbox, "--no-sandbox only when asked (S5)");
|
||||
Assert.AreEqual("instagram", o.Site.Name);
|
||||
Assert.AreEqual("https://www.instagram.com/accounts/login/", o.LoginUrl);
|
||||
Assert.IsEmpty(o.AllowedHostList(), "any host name by default");
|
||||
|
||||
var web = o.WebOptions();
|
||||
Assert.AreEqual(FebeEdition.Docker, web.Edition);
|
||||
Assert.AreEqual(AccessMode.Password, web.Access);
|
||||
Assert.AreEqual("segreta", web.Password);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TheEnvironmentAndTheDevelopmentOptionsAreRead()
|
||||
{
|
||||
var env = Env(
|
||||
("FEBE_PASSWORD", "x"),
|
||||
("FEBE_PORTA", "9000"),
|
||||
("TZ", "Europe/London"),
|
||||
("LANG", "it_IT.UTF-8"),
|
||||
("FEBE_HOST", "tower.local, 192.168.1.10"),
|
||||
("FEBE_PROXY_FIDATO", "1"),
|
||||
("FEBE_SENZA_SANDBOX", "1"),
|
||||
("FEBE_PORTA_DEBUG", "9333"));
|
||||
Assert.IsTrue(ServerOptions.TryParse(["--dati", "/tmp/d", "--sito-di-prova", "http://127.0.0.1:8481", "--accesso-di-prova", "--prima-sessione", "5"], env, out var o, out var problem), problem);
|
||||
Assert.AreEqual(9000, o.Port);
|
||||
Assert.AreEqual("Europe/London", o.ZoneId);
|
||||
Assert.IsTrue(o.TrustForwardedHost);
|
||||
Assert.IsTrue(o.NoSandbox);
|
||||
Assert.AreEqual(9333, o.DebugPort);
|
||||
Assert.AreEqual("/tmp/d", o.DataFolder);
|
||||
Assert.AreEqual(TimeSpan.FromSeconds(5), o.FirstSessionDelay);
|
||||
Assert.AreEqual("prova", o.Site.Name);
|
||||
Assert.AreEqual("http://127.0.0.1:8481", o.Site.BaseUrl);
|
||||
Assert.AreEqual("127.0.0.2:8482", o.Site.Hosts.CdnHosts.Single(), "the CDN of the test site tool by default");
|
||||
Assert.AreEqual("sessione_prova", o.Site.SessionCookie.CookieName);
|
||||
Assert.AreEqual("http://127.0.0.1:8481/benvenuto", o.LoginUrl);
|
||||
CollectionAssert.IsSubsetOf(new[] { "tower.local", "tower.local:*", "192.168.1.10:*", "127.0.0.1:*", "localhost:*" }, o.AllowedHostList().ToList());
|
||||
|
||||
var browser = o.BrowserEnvironment("/dati/home");
|
||||
Assert.AreEqual("Europe/London", browser["TZ"]);
|
||||
Assert.AreEqual("/dati/home", browser["HOME"]);
|
||||
Assert.IsNull(browser["HTTPS_PROXY"], "no proxy for the browser (rule 2)");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void WrongValuesAreRefusedInItalian()
|
||||
{
|
||||
var env = Env(("FEBE_PASSWORD", "x"));
|
||||
foreach (var (args, fragment) in new (string[], string)[]
|
||||
{
|
||||
(["--porta", "0"], "Porta non valida"),
|
||||
(["--sito-di-prova", "https://www.instagram.com"], "indirizzo http di questo computer"),
|
||||
(["--sito-di-prova", "http://192.168.1.5:8481"], "indirizzo http di questo computer"),
|
||||
(["--accesso-di-prova"], "solo con --sito-di-prova"),
|
||||
(["--password", "segreta"], "Opzione sconosciuta"),
|
||||
(["--display", "99"], "Display non valido"),
|
||||
(["--porta-debug", "8480"], "diversa"),
|
||||
})
|
||||
{
|
||||
Assert.IsFalse(ServerOptions.TryParse(args, env, out _, out var problem), string.Join(' ', args));
|
||||
StringAssert.Contains(problem, fragment, string.Join(' ', args));
|
||||
}
|
||||
|
||||
Assert.IsFalse(ServerOptions.TryParse([], Env(("FEBE_PORTA", "porta")), out _, out var portProblem));
|
||||
StringAssert.Contains(portProblem, "FEBE_PORTA");
|
||||
|
||||
// An unknown time zone is a warning, not a stop.
|
||||
Assert.IsTrue(ServerOptions.TryParse([], Env(("TZ", "Luna/Febe")), out var o, out _));
|
||||
Assert.AreEqual("Europe/Rome", o.ZoneId);
|
||||
StringAssert.Contains(o.Warnings.Single(), "Luna/Febe");
|
||||
Assert.IsNull(o.Password, "the password comes only from FEBE_PASSWORD");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TheBackupComesOnceADayAfterMidnight()
|
||||
{
|
||||
var zone = TestZones.Rome;
|
||||
var now = new DateTimeOffset(2026, 10, 13, 21, 0, 0, TimeSpan.FromHours(2));
|
||||
var wait = FebeServer.UntilNextBackup(now, zone);
|
||||
Assert.AreEqual(new DateTimeOffset(2026, 10, 14, 3, 20, 0, TimeSpan.FromHours(2)), now + wait);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TheLogHasNoAddressesRotatesByDayAndKeepsTwoWeeks()
|
||||
{
|
||||
using var temp = new TempFolder("registro");
|
||||
var clock = new ManualClock(new DateTimeOffset(2026, 10, 13, 10, 0, 0, TimeSpan.Zero), TestZones.Rome);
|
||||
var folder = temp.Combine("registro");
|
||||
Directory.CreateDirectory(folder);
|
||||
var old = Path.Combine(folder, ServerLog.FileNameFor(new DateOnly(2026, 9, 1)));
|
||||
File.WriteAllText(old, "vecchio");
|
||||
var unrelated = Path.Combine(folder, "appunti.txt");
|
||||
File.WriteAllText(unrelated, "di Alberto");
|
||||
using var console = new StringWriter();
|
||||
using (var log = new ServerLog(folder, console, clock))
|
||||
{
|
||||
log.Info("prova", "Scaricato https://cdn.example/m/abc.jpg?firma=SEGRETA da marta.prova");
|
||||
log.Warn("prova", "Errore", new InvalidOperationException("riga uno https://x.example/?t=1\nriga due"));
|
||||
clock.Now = clock.Now.AddDays(1);
|
||||
log.Info("prova", "Il giorno dopo");
|
||||
}
|
||||
|
||||
var first = File.ReadAllText(Path.Combine(folder, ServerLog.FileNameFor(new DateOnly(2026, 10, 13))));
|
||||
Assert.DoesNotContain("SEGRETA", first);
|
||||
Assert.DoesNotContain("cdn.example", first);
|
||||
StringAssert.Contains(first, "<indirizzo>");
|
||||
StringAssert.Contains(first, "marta.prova");
|
||||
StringAssert.Contains(first, "InvalidOperationException: riga uno <indirizzo>");
|
||||
Assert.DoesNotContain("riga due", first);
|
||||
StringAssert.Contains(File.ReadAllText(Path.Combine(folder, ServerLog.FileNameFor(new DateOnly(2026, 10, 14)))), "Il giorno dopo");
|
||||
Assert.IsFalse(File.Exists(old), "older than fourteen days");
|
||||
Assert.IsTrue(File.Exists(unrelated), "only febe-*.log files are removed");
|
||||
StringAssert.Contains(console.ToString(), "Il giorno dopo");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TheLogStopsGrowingAtItsDailyLimit()
|
||||
{
|
||||
using var temp = new TempFolder("registro");
|
||||
var clock = new ManualClock(new DateTimeOffset(2026, 10, 13, 10, 0, 0, TimeSpan.Zero), TestZones.Rome);
|
||||
using (var log = new ServerLog(temp.Path, null, clock, maxBytesPerDay: 2000))
|
||||
{
|
||||
for (var i = 0; i < 100; i++)
|
||||
{
|
||||
log.Info("prova", "Una riga di registro qualunque, abbastanza lunga da riempire il limite.");
|
||||
}
|
||||
}
|
||||
|
||||
var file = Path.Combine(temp.Path, ServerLog.FileNameFor(new DateOnly(2026, 10, 13)));
|
||||
Assert.IsLessThan(2200L, new FileInfo(file).Length);
|
||||
StringAssert.Contains(File.ReadAllText(file), "troppo lungo");
|
||||
}
|
||||
|
||||
private static Func<string, string?> Env(params (string Name, string Value)[] values)
|
||||
{
|
||||
var map = values.ToDictionary(v => v.Name, v => v.Value, StringComparer.Ordinal);
|
||||
return name => map.GetValueOrDefault(name);
|
||||
}
|
||||
|
||||
private sealed class ManualClock(DateTimeOffset start, TimeZoneInfo zone) : IClock
|
||||
{
|
||||
public DateTimeOffset Now { get; set; } = start;
|
||||
|
||||
public TimeZoneInfo LocalZone { get; } = zone;
|
||||
|
||||
public Task Delay(TimeSpan time, CancellationToken ct) => Task.CompletedTask;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,170 @@
|
||||
using System.Net;
|
||||
using System.Net.WebSockets;
|
||||
using System.Text;
|
||||
using Febe.Core.Library;
|
||||
using Febe.Server;
|
||||
using Febe.Tests.Support;
|
||||
|
||||
namespace Febe.Tests.Server;
|
||||
|
||||
/// <summary>
|
||||
/// Spec §8.2, §11: with the password missing, or the Data folder not writable or on a network share, neither the
|
||||
/// engine nor the browser start; the interface shows only the page that explains it and <c>/salute</c> says «problema».
|
||||
/// The remote view is never reachable without a password. No browser needed.
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
public sealed class StartupProblemTests
|
||||
{
|
||||
public TestContext TestContext { get; set; } = null!;
|
||||
|
||||
[TestMethod]
|
||||
public async Task WithoutPasswordOnlyTheErrorPageAnswersAndNothingStarts()
|
||||
{
|
||||
using var temp = new TempFolder("server-problemi");
|
||||
await using var server = await FebeServer.StartAsync(Options(temp) with { Password = null }, Hooks());
|
||||
var problem = server.Problems.Single();
|
||||
Assert.AreEqual(StartupChecks.PasswordMissing, problem.Code);
|
||||
StringAssert.Contains(problem.Remedy, "FEBE_PASSWORD");
|
||||
Assert.IsNull(server.Browser, "no browser");
|
||||
Assert.IsNull(server.Engine, "no engine");
|
||||
Assert.IsFalse(Directory.Exists(temp.Combine("dati", "registro")), "nothing written in the Data folder");
|
||||
Assert.IsFalse(File.Exists(temp.Combine("dati", "febe.sqlite")));
|
||||
|
||||
using var client = Client(server);
|
||||
await AssertHealthAsync(client, HttpStatusCode.ServiceUnavailable, """{"stato":"problema"}""");
|
||||
|
||||
// The error page and what it needs.
|
||||
foreach (var path in new[] { "/", "/libreria", "/impostazioni/collegamento", "/css/febe.css", "/js/app.js", "/testi/it.json", "/api/capabilities" })
|
||||
{
|
||||
using var response = await client.GetAsync(path, TestContext.CancellationToken);
|
||||
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode, path);
|
||||
}
|
||||
|
||||
// Nothing else: library, accounts, engine commands, login, the remote view.
|
||||
foreach (var path in new[] { "/api/accounts", "/api/library/days", "/api/engine", "/api/eventi" })
|
||||
{
|
||||
using var response = await client.GetAsync(path, TestContext.CancellationToken);
|
||||
Assert.AreEqual(HttpStatusCode.ServiceUnavailable, response.StatusCode, path);
|
||||
}
|
||||
|
||||
using (var login = await PostAsync(client, server, "/api/accesso", """{"password":"qualunque"}"""))
|
||||
{
|
||||
Assert.AreEqual(HttpStatusCode.ServiceUnavailable, login.StatusCode);
|
||||
}
|
||||
|
||||
await AssertNoRemoteViewAsync(server);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task ADataFolderThatIsAFileStopsTheEngineEvenWithThePassword()
|
||||
{
|
||||
using var temp = new TempFolder("server-problemi");
|
||||
var file = temp.Combine("dati-file");
|
||||
await File.WriteAllTextAsync(file, "non una cartella", TestContext.CancellationToken);
|
||||
await using var server = await FebeServer.StartAsync(Options(temp) with { DataFolder = file }, Hooks());
|
||||
var problem = server.Problems.Single();
|
||||
Assert.AreEqual(StartupChecks.DataNotWritable, problem.Code);
|
||||
Assert.IsNull(server.Engine);
|
||||
|
||||
var cookies = new CookieContainer();
|
||||
using var client = Client(server, cookies);
|
||||
await AssertHealthAsync(client, HttpStatusCode.ServiceUnavailable, """{"stato":"problema"}""");
|
||||
|
||||
// The password works, then only the problem page's API answers.
|
||||
using (var login = await PostAsync(client, server, "/api/accesso", """{"password":"una password"}"""))
|
||||
{
|
||||
Assert.AreEqual(HttpStatusCode.OK, login.StatusCode, await login.Content.ReadAsStringAsync());
|
||||
}
|
||||
|
||||
using (var capabilities = await client.GetAsync("/api/capabilities", TestContext.CancellationToken))
|
||||
{
|
||||
Assert.AreEqual(HttpStatusCode.OK, capabilities.StatusCode);
|
||||
}
|
||||
|
||||
using (var engine = await client.GetAsync("/api/engine", TestContext.CancellationToken))
|
||||
{
|
||||
Assert.AreEqual(HttpStatusCode.OK, engine.StatusCode, "the frame of the page may ask for the (offline) engine");
|
||||
}
|
||||
|
||||
using (var accounts = await client.GetAsync("/api/accounts", TestContext.CancellationToken))
|
||||
{
|
||||
Assert.AreEqual(HttpStatusCode.ServiceUnavailable, accounts.StatusCode);
|
||||
using var json = System.Text.Json.JsonDocument.Parse(await accounts.Content.ReadAsStringAsync());
|
||||
StringAssert.Contains(json.RootElement.GetProperty("message").GetString(), "Il motore non è partito");
|
||||
}
|
||||
|
||||
await AssertNoRemoteViewAsync(server, cookies);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task ADataFolderOnANetworkShareIsRefused()
|
||||
{
|
||||
using var temp = new TempFolder("server-problemi");
|
||||
var data = temp.Combine("dati");
|
||||
var mounts = $"/dev/sda1 / ext4 rw 0 0\n//nas/condivisa {temp.Path} cifs rw 0 0\n";
|
||||
await using var server = await FebeServer.StartAsync(Options(temp), Hooks() with { DataFolderCheck = new DataFolderCheck(() => mounts) });
|
||||
var problem = server.Problems.Single();
|
||||
Assert.AreEqual(StartupChecks.DataOnNetwork, problem.Code);
|
||||
StringAssert.Contains(problem.Message, "cifs");
|
||||
Assert.IsFalse(Directory.Exists(Path.Combine(data, "registro")));
|
||||
using var client = Client(server);
|
||||
await AssertHealthAsync(client, HttpStatusCode.ServiceUnavailable, """{"stato":"problema"}""");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task TheHealthCheckCommandReadsSalute()
|
||||
{
|
||||
using var temp = new TempFolder("server-problemi");
|
||||
await using var server = await FebeServer.StartAsync(Options(temp) with { Password = null }, Hooks());
|
||||
using var output = new StringWriter();
|
||||
Assert.AreEqual(1, await HealthCheckCommand.CheckAsync(new Uri(server.Address, "/salute"), output));
|
||||
StringAssert.Contains(output.ToString(), "problema");
|
||||
|
||||
// Nobody listening: not healthy.
|
||||
Assert.AreEqual(1, await HealthCheckCommand.CheckAsync(new Uri($"http://127.0.0.1:{Febe.Tests.Browser.TestSupport.LocalTestSite.FreePort()}/salute"), TextWriter.Null));
|
||||
}
|
||||
|
||||
internal static ServerOptions Options(TempFolder temp) => new()
|
||||
{
|
||||
Password = "una password",
|
||||
ListenAddress = IPAddress.Loopback,
|
||||
Port = 0,
|
||||
DataFolder = temp.Combine("dati"),
|
||||
LibraryFolder = temp.Combine("libreria"),
|
||||
ImportFolder = temp.Combine("importa"),
|
||||
};
|
||||
|
||||
internal static ServerHooks Hooks() => new() { Console = TextWriter.Null };
|
||||
|
||||
private static HttpClient Client(FebeServer server, CookieContainer? cookies = null) =>
|
||||
new(new HttpClientHandler { UseCookies = cookies is not null, CookieContainer = cookies ?? new CookieContainer(), AllowAutoRedirect = false }) { BaseAddress = server.Address };
|
||||
|
||||
private static async Task<HttpResponseMessage> PostAsync(HttpClient client, FebeServer server, string path, string json)
|
||||
{
|
||||
using var request = new HttpRequestMessage(HttpMethod.Post, path) { Content = new StringContent(json, Encoding.UTF8, "application/json") };
|
||||
request.Headers.TryAddWithoutValidation("Origin", $"http://{server.Address.Authority}");
|
||||
return await client.SendAsync(request);
|
||||
}
|
||||
|
||||
private async Task AssertHealthAsync(HttpClient client, HttpStatusCode status, string body)
|
||||
{
|
||||
using var response = await client.GetAsync("/salute", TestContext.CancellationToken);
|
||||
Assert.AreEqual(status, response.StatusCode);
|
||||
Assert.AreEqual(body, await response.Content.ReadAsStringAsync(TestContext.CancellationToken));
|
||||
}
|
||||
|
||||
private async Task AssertNoRemoteViewAsync(FebeServer server, CookieContainer? session = null)
|
||||
{
|
||||
using var socket = new ClientWebSocket();
|
||||
socket.Options.SetRequestHeader("Origin", $"http://{server.Address.Authority}");
|
||||
if (session is not null)
|
||||
{
|
||||
socket.Options.Cookies = session;
|
||||
}
|
||||
|
||||
socket.Options.CollectHttpResponseDetails = true;
|
||||
var address = new UriBuilder(server.Address) { Scheme = "ws", Path = "/api/vista" }.Uri;
|
||||
await Assert.ThrowsAsync<WebSocketException>(() => socket.ConnectAsync(address, TestContext.CancellationToken));
|
||||
Assert.AreNotEqual(HttpStatusCode.SwitchingProtocols, socket.HttpStatusCode);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
using System.Collections.Concurrent;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Threading.Channels;
|
||||
using Febe.Web.Connection;
|
||||
|
||||
namespace Febe.Tests.Server.Support;
|
||||
|
||||
/// <summary>A remote view without browser: the test writes what goes to the page and reads what comes back.</summary>
|
||||
internal sealed class FakeRemoteViewHost : IRemoteViewHost
|
||||
{
|
||||
private readonly Lock _gate = new();
|
||||
|
||||
public List<FakeRemoteViewConnection> Opened { get; } = [];
|
||||
|
||||
public bool Unavailable { get; set; }
|
||||
|
||||
public Task<IRemoteViewConnection> OpenAsync(CancellationToken ct)
|
||||
{
|
||||
if (Unavailable)
|
||||
{
|
||||
throw new RemoteViewUnavailableException("Il browser di prova non c'è.");
|
||||
}
|
||||
|
||||
var connection = new FakeRemoteViewConnection();
|
||||
lock (_gate)
|
||||
{
|
||||
if (Opened.LastOrDefault() is { Disposed: false } previous)
|
||||
{
|
||||
previous.End(RemoteViewEnd.Replaced);
|
||||
}
|
||||
|
||||
Opened.Add(connection);
|
||||
}
|
||||
|
||||
return Task.FromResult<IRemoteViewConnection>(connection);
|
||||
}
|
||||
}
|
||||
|
||||
internal sealed class FakeRemoteViewConnection : IRemoteViewConnection
|
||||
{
|
||||
private readonly Channel<RemoteViewOutput> _output = Channel.CreateUnbounded<RemoteViewOutput>();
|
||||
|
||||
public ConcurrentQueue<object> Inputs { get; } = new();
|
||||
|
||||
public bool Disposed { get; private set; }
|
||||
|
||||
public RemoteViewEnd? Ended { get; private set; }
|
||||
|
||||
public void Write(RemoteViewOutput output) => _output.Writer.TryWrite(output);
|
||||
|
||||
public void End(RemoteViewEnd reason)
|
||||
{
|
||||
Ended = reason;
|
||||
_output.Writer.TryComplete();
|
||||
}
|
||||
|
||||
public async IAsyncEnumerable<RemoteViewOutput> ReadAsync([EnumeratorCancellation] CancellationToken ct)
|
||||
{
|
||||
await foreach (var output in _output.Reader.ReadAllAsync(ct))
|
||||
{
|
||||
yield return output;
|
||||
}
|
||||
}
|
||||
|
||||
public Task MouseAsync(RemoteViewMouse input, CancellationToken ct)
|
||||
{
|
||||
Inputs.Enqueue(input);
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
public Task KeyAsync(RemoteViewKey input, CancellationToken ct)
|
||||
{
|
||||
Inputs.Enqueue(input);
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
public Task NavigateAsync(RemoteViewNavigation action, CancellationToken ct)
|
||||
{
|
||||
Inputs.Enqueue(action);
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
public ValueTask DisposeAsync()
|
||||
{
|
||||
Disposed = true;
|
||||
_output.Writer.TryComplete();
|
||||
return ValueTask.CompletedTask;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,192 @@
|
||||
using System.Net;
|
||||
using System.Net.WebSockets;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using Febe.Browser.Hosting;
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Core.Library;
|
||||
using Febe.Server;
|
||||
using Febe.SitoDiProva;
|
||||
using Febe.Tests.Browser.TestSupport;
|
||||
using Febe.Tests.Collection.Support;
|
||||
using Febe.Tests.Support;
|
||||
|
||||
namespace Febe.Tests.Server.Support;
|
||||
|
||||
/// <summary>
|
||||
/// The real server composition (<see cref="FebeServer"/>) against the local test site, with Xvfb and a real Chromium,
|
||||
/// in a temporary Data/Library/Import folder, on free ports and a free display. Never Instagram: the browser only ever
|
||||
/// sees 127.0.0.1. Time runs on a compressed clock (10×) in a time zone where it is around noon now, so that the
|
||||
/// engine is inside its active window whatever the hour of the test.
|
||||
/// </summary>
|
||||
internal sealed class ServerTestBed : IAsyncDisposable
|
||||
{
|
||||
public const string Password = "una password di prova per il server";
|
||||
|
||||
private ServerTestBed(TempFolder temp, TestSite site, FebeServer server, CompressedClock clock, ServerOptions options)
|
||||
{
|
||||
Temp = temp;
|
||||
Site = site;
|
||||
Server = server;
|
||||
Clock = clock;
|
||||
Options = options;
|
||||
Client = new HttpClient(new HttpClientHandler { UseCookies = true, CookieContainer = Cookies, AllowAutoRedirect = false })
|
||||
{
|
||||
BaseAddress = server.Address,
|
||||
Timeout = TimeSpan.FromSeconds(30),
|
||||
};
|
||||
}
|
||||
|
||||
public TempFolder Temp { get; }
|
||||
|
||||
public TestSite Site { get; }
|
||||
|
||||
public FebeServer Server { get; }
|
||||
|
||||
public CompressedClock Clock { get; }
|
||||
|
||||
public ServerOptions Options { get; }
|
||||
|
||||
public CookieContainer Cookies { get; } = new();
|
||||
|
||||
public HttpClient Client { get; }
|
||||
|
||||
/// <summary>«http://127.0.0.1:port»: the Origin of requests coming from the interface.</summary>
|
||||
public string Origin => $"{Server.Address.Scheme}://{Server.Address.Authority}";
|
||||
|
||||
public static string? UnavailableReason() => RealBrowser.UnavailableReason();
|
||||
|
||||
public static async Task<ServerTestBed> StartAsync(bool autoLogin = false, double factor = 10)
|
||||
{
|
||||
var temp = new TempFolder("server");
|
||||
var site = await TestSite.StartAsync(new TestSiteOptions());
|
||||
var zone = NoonZone();
|
||||
var clock = new CompressedClock(factor, zone);
|
||||
var options = new ServerOptions
|
||||
{
|
||||
Password = Password,
|
||||
ListenAddress = IPAddress.Loopback,
|
||||
Port = 0,
|
||||
ZoneId = zone.Id,
|
||||
Zone = zone,
|
||||
Language = "it_IT.UTF-8",
|
||||
DataFolder = temp.Combine("dati"),
|
||||
LibraryFolder = temp.Combine("libreria"),
|
||||
ImportFolder = temp.Combine("importa"),
|
||||
NoSandbox = RealBrowser.IsRoot,
|
||||
ChromiumPath = RealBrowser.ChromiumPath(),
|
||||
DebugPort = LocalTestSite.FreePort(),
|
||||
Display = XvfbProcess.FindFreeDisplay(300, 399) ?? throw new InvalidOperationException("Nessun display libero."),
|
||||
TestSite = new Uri(site.SiteUrl + "/"),
|
||||
TestCdn = new Uri(site.CdnUrl + "/"),
|
||||
TestSiteAutoLogin = autoLogin,
|
||||
FirstSessionDelay = TimeSpan.FromSeconds(1),
|
||||
};
|
||||
Directory.CreateDirectory(options.ImportFolder);
|
||||
FebeServer server;
|
||||
try
|
||||
{
|
||||
server = await FebeServer.StartAsync(options, new ServerHooks { Clock = clock, Random = new SeededRandom(20261013), Console = TextWriter.Null });
|
||||
}
|
||||
catch
|
||||
{
|
||||
await site.DisposeAsync();
|
||||
temp.Dispose();
|
||||
throw;
|
||||
}
|
||||
|
||||
return new ServerTestBed(temp, site, server, clock, options);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A fixed-offset zone where the local time is between 12:00 and 13:00 now: inside the active window of every
|
||||
/// caution profile, so the test does not depend on when it runs.
|
||||
/// </summary>
|
||||
public static TimeZoneInfo NoonZone()
|
||||
{
|
||||
var offset = 12 - DateTimeOffset.UtcNow.Hour;
|
||||
if (offset > 12)
|
||||
{
|
||||
offset -= 24;
|
||||
}
|
||||
else if (offset < -12)
|
||||
{
|
||||
offset += 24;
|
||||
}
|
||||
|
||||
// The sign of the Etc/GMT names is inverted: Etc/GMT-2 is two hours east of Greenwich.
|
||||
var id = offset == 0 ? "Etc/GMT" : offset > 0 ? $"Etc/GMT-{offset}" : $"Etc/GMT+{-offset}";
|
||||
return TimeZoneInfo.FindSystemTimeZoneById(id);
|
||||
}
|
||||
|
||||
/// <summary>Logs in with the interface password (cookie in <see cref="Cookies"/>).</summary>
|
||||
public async Task LoginAsync()
|
||||
{
|
||||
using var response = await SendAsync(HttpMethod.Post, "/api/accesso", $$"""{"password":"{{Password}}"}""");
|
||||
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode, await response.Content.ReadAsStringAsync());
|
||||
}
|
||||
|
||||
/// <summary>A request as the interface sends it: Origin of the interface, JSON body.</summary>
|
||||
public async Task<HttpResponseMessage> SendAsync(HttpMethod method, string path, string? json = null)
|
||||
{
|
||||
using var request = new HttpRequestMessage(method, path);
|
||||
request.Headers.TryAddWithoutValidation("Origin", Origin);
|
||||
if (json is not null)
|
||||
{
|
||||
request.Content = new StringContent(json, Encoding.UTF8, "application/json");
|
||||
}
|
||||
|
||||
return await Client.SendAsync(request);
|
||||
}
|
||||
|
||||
public async Task<JsonElement> JsonAsync(HttpMethod method, string path, string? json = null)
|
||||
{
|
||||
using var response = await SendAsync(method, path, json);
|
||||
var text = await response.Content.ReadAsStringAsync();
|
||||
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode, $"{path}: {text}");
|
||||
return JsonDocument.Parse(text).RootElement.Clone();
|
||||
}
|
||||
|
||||
/// <summary>The remote view, opened like the Browser page does: session cookie and Origin of the interface.</summary>
|
||||
public async Task<ClientWebSocket> OpenRemoteViewAsync(CancellationToken ct)
|
||||
{
|
||||
var socket = new ClientWebSocket();
|
||||
socket.Options.Cookies = Cookies;
|
||||
socket.Options.SetRequestHeader("Origin", Origin);
|
||||
var address = new UriBuilder(Server.Address) { Scheme = "ws", Path = "/api/vista" }.Uri;
|
||||
await socket.ConnectAsync(address, ct);
|
||||
return socket;
|
||||
}
|
||||
|
||||
public LibraryLayout Library => Server.Library ?? throw new InvalidOperationException("Nessuna libreria.");
|
||||
|
||||
public ThumbnailStore Thumbnails => new(Server.Data!.Thumbnails);
|
||||
|
||||
/// <summary>Waits (real time) until <paramref name="condition"/> holds; fails with <paramref name="what"/> otherwise.</summary>
|
||||
public static async Task WaitUntilAsync(Func<Task<bool>> condition, TimeSpan timeout, string what)
|
||||
{
|
||||
var deadline = DateTime.UtcNow + timeout;
|
||||
while (true)
|
||||
{
|
||||
if (await condition())
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (DateTime.UtcNow > deadline)
|
||||
{
|
||||
Assert.Fail($"Tempo scaduto: {what}.");
|
||||
}
|
||||
|
||||
await Task.Delay(250);
|
||||
}
|
||||
}
|
||||
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
Client.Dispose();
|
||||
await Server.DisposeAsync();
|
||||
await Site.DisposeAsync();
|
||||
Temp.Dispose();
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user