Piattaforme: istanza unica dopo lo spostamento dei dati, avvio sicuro del contenitore, rilascio con prove e immagine, accesso senza reindirizzamenti esterni (pkg-1, pkg-2, pkg-3, pkg-4, pkg-5, pkg-6, websec-2, web-8, websec-3)
Registro di casa 192.168.30.23:3000 (HTTP) nel modello Unraid, in compose e nel rilascio con buildx; profilo seccomp fuori da /dati. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Mzbb6zeFTjT6Rp8b92AVkA
This commit is contained in:
36 files changed
+1683
-152
No files matched your search
@@ -305,4 +305,43 @@ public sealed class DesktopCompositionTests
|
||||
await DesktopTestBed.WaitUntilAsync(() => browser.LastError is not null, TimeSpan.FromSeconds(10), "il tentativo di avviare Edge");
|
||||
Assert.IsFalse(browser.IsAvailable, "the fake msedge.exe does not exist: the browser is retried, nothing else breaks");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[Timeout(60_000, CooperativeCancellation = true)]
|
||||
public async Task EveryEdgeFebeStartsIsTiedToFebeSoACrashLeavesNoEdgeHoldingThePort()
|
||||
{
|
||||
if (!OperatingSystem.IsLinux())
|
||||
{
|
||||
Assert.Inconclusive("Il finto msedge.exe di questa prova è uno script di shell.");
|
||||
return;
|
||||
}
|
||||
|
||||
// An «Edge» that starts and closes at once: every start must be tied to Febe before anything else happens, also
|
||||
// the starts that fail and the ones after (pkg-6: an Edge left behind by a crash keeps the port 9222).
|
||||
using var temp = new TempFolder("desktop-edge");
|
||||
var edge = temp.Combine("Edge", "msedge.exe");
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(edge)!);
|
||||
await File.WriteAllTextAsync(edge, "#!/bin/sh\nexit 3\n", TestContext.CancellationToken);
|
||||
File.SetUnixFileMode(edge, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute);
|
||||
var shell = new FakeDesktopShell { EdgePath = edge, TieSucceeds = false };
|
||||
await using var bed = await DesktopTestBed.StartAsync(["--browser", "edge"], shell, temp, adjust: o => o with { EdgeDebugPort = FreePort() });
|
||||
await DesktopTestBed.WaitUntilAsync(() => !shell.TiedToFebe.IsEmpty, TimeSpan.FromSeconds(20), "Edge legato alla vita di Febe");
|
||||
var browser = (EdgeBrowser)bed.App.Browser!;
|
||||
await DesktopTestBed.WaitUntilAsync(() => browser.LastError is not null, TimeSpan.FromSeconds(20), "il primo avvio di Edge, che si chiude subito");
|
||||
Assert.IsFalse(browser.IsAvailable);
|
||||
await bed.StopAsync();
|
||||
|
||||
// Windows refused: the log says what to do, in Italian.
|
||||
var log = string.Concat(Directory.EnumerateFiles(Path.Combine(bed.Folders.DefaultDataFolder, "registro")).Select(File.ReadAllText));
|
||||
StringAssert.Contains(log, "Windows non ha legato Edge a Febe");
|
||||
}
|
||||
|
||||
private static int FreePort()
|
||||
{
|
||||
var listener = new System.Net.Sockets.TcpListener(IPAddress.Loopback, 0);
|
||||
listener.Start();
|
||||
var port = ((IPEndPoint)listener.LocalEndpoint).Port;
|
||||
listener.Stop();
|
||||
return port;
|
||||
}
|
||||
}
|
||||
@@ -295,6 +295,170 @@ public sealed class DesktopLogicTests
|
||||
Assert.IsNull(store.Pending);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void AfterAMoveThisFebeHoldsTheNewFolderSoASecondLaunchDoesNotStartASecondFebe()
|
||||
{
|
||||
// pkg-1: the guard is named after the Data folder. After a move every launch reads the new folder: this Febe
|
||||
// must hold its guard, or the next launch would start a second interface, browser and engine on it.
|
||||
using var temp = new TempFolder("desktop-sposta");
|
||||
var from = temp.Combine("vecchia");
|
||||
var to = temp.Combine("nuova");
|
||||
Directory.CreateDirectory(from);
|
||||
File.WriteAllText(Path.Combine(from, "febe.sqlite"), "database");
|
||||
var guards = new FakeInstanceGuards();
|
||||
var store = new MemoryLocationStore { Pending = to };
|
||||
using var started = guards.TryAcquire(from);
|
||||
Assert.IsNotNull(started, "Program: the guard of the folder this Febe started on");
|
||||
|
||||
(string? Recorded, bool Written)? atClaim = null;
|
||||
var result = DataFolderMove.ApplyPending(store, from, claimTarget: folder =>
|
||||
{
|
||||
atClaim = (store.Current, Directory.Exists(folder));
|
||||
return guards.TryAcquire(folder);
|
||||
});
|
||||
Assert.AreEqual(DataFolderMoveOutcome.Moved, result.Outcome, result.Message);
|
||||
Assert.AreEqual((null, false), atClaim, "the guard comes before the folder is recorded and before anything is written in it");
|
||||
Assert.IsNotNull(result.TargetGuard);
|
||||
Assert.AreEqual(Path.GetFullPath(to), store.Current);
|
||||
|
||||
// The next launch (Start menu, a start with the computer) reads the recorded folder and finds this Febe.
|
||||
Assert.IsNull(guards.TryAcquire(store.Current!), "a second launch signals this Febe instead of starting another");
|
||||
result.TargetGuard!.Dispose();
|
||||
using var afterExit = guards.TryAcquire(store.Current!);
|
||||
Assert.IsNotNull(afterExit, "after Esci the folder is free again");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void AMoveIntoAFolderAnotherFebeHoldsDoesNotHappenAndAFailedMoveGivesTheGuardBack()
|
||||
{
|
||||
using var temp = new TempFolder("desktop-sposta");
|
||||
var from = temp.Combine("vecchia");
|
||||
Directory.CreateDirectory(from);
|
||||
File.WriteAllText(Path.Combine(from, "febe.sqlite"), "database");
|
||||
var guards = new FakeInstanceGuards();
|
||||
|
||||
// Another Febe (started with --dati) already holds the new folder: nothing is copied, the old folder stays.
|
||||
var taken = temp.Combine("presa");
|
||||
using (guards.TryAcquire(taken))
|
||||
{
|
||||
var store = new MemoryLocationStore { Pending = taken };
|
||||
var refused = DataFolderMove.ApplyPending(store, from, claimTarget: guards.TryAcquire);
|
||||
Assert.AreEqual(DataFolderMoveOutcome.Failed, refused.Outcome);
|
||||
StringAssert.Contains(refused.Message, "un altro Febe la sta già usando");
|
||||
Assert.IsNull(refused.TargetGuard);
|
||||
Assert.IsNull(store.Pending);
|
||||
Assert.IsNull(store.Current);
|
||||
Assert.IsFalse(Directory.Exists(taken), "nothing written there");
|
||||
Assert.IsTrue(File.Exists(Path.Combine(from, "febe.sqlite")));
|
||||
}
|
||||
|
||||
// A copy that fails: Febe stays on the old folder and does not keep the guard of the new one.
|
||||
var halfway = temp.Combine("a-meta");
|
||||
var failing = new MemoryLocationStore { Pending = halfway };
|
||||
var failed = DataFolderMove.ApplyPending(failing, from, new SyncProgress(_ => throw new IOException("disco pieno")), claimTarget: guards.TryAcquire);
|
||||
Assert.AreEqual(DataFolderMoveOutcome.Failed, failed.Outcome);
|
||||
Assert.IsNull(failed.TargetGuard);
|
||||
using var free = guards.TryAcquire(halfway);
|
||||
Assert.IsNotNull(free, "the guard of a move that did not happen is given back");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TheDataFolderLockLetsOneFebeOpenTheFolderWhateverItsSpelling()
|
||||
{
|
||||
using var temp = new TempFolder("desktop-blocco");
|
||||
var data = temp.Combine("dati");
|
||||
Assert.AreEqual(DataFolderLockOutcome.Acquired, DataFolderLock.TryAcquire(data, out var first, TimeSpan.Zero));
|
||||
Assert.IsNotNull(first);
|
||||
Assert.AreEqual(Path.Combine(data, DataFolderLock.FileName), first.Path);
|
||||
Assert.IsTrue(File.Exists(first.Path));
|
||||
|
||||
// The same folder under another name (on Windows: a short 8.3 name, subst, a junction; here a symbolic link):
|
||||
// the guards are named after the path and differ, the lock is the same file.
|
||||
var alias = temp.Combine("alias");
|
||||
Directory.CreateSymbolicLink(alias, data);
|
||||
Assert.AreNotEqual(InstanceIdentity.For(data), InstanceIdentity.For(alias));
|
||||
Assert.AreEqual(DataFolderLockOutcome.HeldByAnother, DataFolderLock.TryAcquire(alias, out var second, TimeSpan.Zero));
|
||||
Assert.IsNull(second);
|
||||
|
||||
// Held for a moment only (an antivirus looking at the file): the start waits instead of giving up.
|
||||
var release = Task.Run(async () =>
|
||||
{
|
||||
await Task.Delay(300, TestContext.CancellationToken);
|
||||
first.Dispose();
|
||||
}, TestContext.CancellationToken);
|
||||
Assert.AreEqual(DataFolderLockOutcome.Acquired, DataFolderLock.TryAcquire(alias, out var later, TimeSpan.FromSeconds(10)));
|
||||
release.Wait(TestContext.CancellationToken);
|
||||
later!.Dispose();
|
||||
|
||||
// A Data folder where nothing can be written: the start-up checks explain it, the lock does not decide.
|
||||
var file = temp.Combine("un-file");
|
||||
File.WriteAllText(file, "x");
|
||||
Assert.AreEqual(DataFolderLockOutcome.Unavailable, DataFolderLock.TryAcquire(file, out var none, TimeSpan.Zero));
|
||||
Assert.IsNull(none);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void AFebeStartedWithItsOwnDataFolderHasItsOwnStartWithTheComputer()
|
||||
{
|
||||
// pkg-5: «Febe.exe --dati D:\FebeSecondo» (a second account) must start that folder at the next login, and its
|
||||
// switch must neither show nor remove the start of the usual Febe.
|
||||
var exe = Path.Combine(Path.GetTempPath(), "Programmi", "Febe", "Febe.exe");
|
||||
var second = Path.Combine(Path.GetTempPath(), "Febe Secondo");
|
||||
Assert.AreEqual("Febe", Autostart.ValueNameFor(null));
|
||||
Assert.AreEqual(InstanceIdentity.For(second), Autostart.ValueNameFor(second));
|
||||
StringAssert.StartsWith(Autostart.ValueNameFor(second), "Febe-");
|
||||
Assert.AreNotEqual(Autostart.ValueNameFor(second), Autostart.ValueNameFor(second + "2"));
|
||||
|
||||
var command = Autostart.Command(exe, second);
|
||||
Assert.AreEqual($"\"{exe}\" --nascosto --dati \"{second}\"", command);
|
||||
Assert.IsTrue(Autostart.PointsTo(command, exe, second));
|
||||
Assert.IsTrue(Autostart.PointsTo(command, exe, second + Path.DirectorySeparatorChar), "the same folder");
|
||||
Assert.IsFalse(Autostart.PointsTo(command, exe), "the usual Febe does not take it for its own");
|
||||
Assert.IsFalse(Autostart.PointsTo(Autostart.Command(exe), exe, second), "nor the reverse: that command starts the usual folder");
|
||||
Assert.IsFalse(Autostart.PointsTo(Autostart.Command(exe, second + "2"), exe, second), "another account");
|
||||
Assert.IsFalse(Autostart.PointsTo($"\"{exe}\" --nascosto --dati", exe, second));
|
||||
|
||||
// Febe.exe reads the command back as written: hidden, on that Data folder.
|
||||
var words = Autostart.Split(command)!;
|
||||
Assert.AreEqual(exe, words[0]);
|
||||
Assert.IsTrue(DesktopCommandLine.TryParse([.. words.Skip(1)], out var options, out var problem), problem);
|
||||
Assert.IsTrue(options.StartHidden);
|
||||
Assert.AreEqual(Path.GetFullPath(second), options.DataFolder);
|
||||
|
||||
// A folder at the root of a drive: the backslash before the closing quote is doubled, so it reads back whole.
|
||||
CollectionAssert.AreEqual(new[] { exe, "--nascosto", "--dati", @"D:\" }, Autostart.Split(Autostart.Command(exe, @"D:\")));
|
||||
CollectionAssert.AreEqual(new[] { "a", "b\"c", @"d\e" }, Autostart.Split("a \"b\\\"c\" d\\e"));
|
||||
Assert.ThrowsExactly<ArgumentException>(() => Autostart.Command(exe, "C:\\a\"b"));
|
||||
}
|
||||
|
||||
/// <summary>The single-instance guards of Windows (named mutexes), by Data folder, in memory.</summary>
|
||||
private sealed class FakeInstanceGuards
|
||||
{
|
||||
private readonly HashSet<string> _held = [];
|
||||
|
||||
public IDisposable? TryAcquire(string dataFolder)
|
||||
{
|
||||
var name = InstanceIdentity.MutexName(dataFolder);
|
||||
lock (_held)
|
||||
{
|
||||
return _held.Add(name) ? new Guard(this, name) : null;
|
||||
}
|
||||
}
|
||||
|
||||
private void Release(string name)
|
||||
{
|
||||
lock (_held)
|
||||
{
|
||||
_held.Remove(name);
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class Guard(FakeInstanceGuards owner, string name) : IDisposable
|
||||
{
|
||||
public void Dispose() => owner.Release(name);
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class SyncProgress(Action<DataFolderMoveProgress> report) : IProgress<DataFolderMoveProgress>
|
||||
{
|
||||
public void Report(DataFolderMoveProgress value) => report(value);
|
||||
|
||||
@@ -47,7 +47,12 @@ internal sealed class DesktopTestBed : IAsyncDisposable
|
||||
|
||||
public string Origin => $"{App.Address.Scheme}://{App.Address.Authority}";
|
||||
|
||||
public static async Task<DesktopTestBed> StartAsync(string[]? args = null, FakeDesktopShell? shell = null, TempFolder? temp = null, MemoryLocationStore? locations = null)
|
||||
/// <param name="args">The command line of Febe.exe.</param>
|
||||
/// <param name="shell">The fake Windows-only part.</param>
|
||||
/// <param name="temp">The folder of «AppData» and «Immagini»; null: a new one, deleted with the bed.</param>
|
||||
/// <param name="locations">The registry values of the Data folder.</param>
|
||||
/// <param name="adjust">Options the command line cannot give (the debugging port of Edge).</param>
|
||||
public static async Task<DesktopTestBed> StartAsync(string[]? args = null, FakeDesktopShell? shell = null, TempFolder? temp = null, MemoryLocationStore? locations = null, Func<DesktopOptions, DesktopOptions>? adjust = null)
|
||||
{
|
||||
var ownsTemp = temp is null;
|
||||
temp ??= new TempFolder("desktop");
|
||||
@@ -58,6 +63,8 @@ internal sealed class DesktopTestBed : IAsyncDisposable
|
||||
throw new ArgumentException(problem);
|
||||
}
|
||||
|
||||
options = adjust?.Invoke(options) ?? options;
|
||||
|
||||
var folders = new DesktopFolders(temp.Combine("AppData", "Local"), temp.Combine("Immagini"));
|
||||
var platform = new DesktopPlatform(options, shell, locations, dataFolderFixed: options.DataFolder is not null);
|
||||
var app = await FebeApp.StartAsync(options.AppOptions(options.DataFolder ?? folders.DefaultDataFolder, folders), platform, new FebeAppHooks { ShutdownTimeout = TimeSpan.FromSeconds(1) });
|
||||
|
||||
@@ -50,6 +50,18 @@ internal sealed class FakeDesktopShell : IDesktopShell
|
||||
ProcessWindows.Enqueue("nascondi " + processId);
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
/// <summary>The processes the platform asked to tie to Febe's life (Edge), by id.</summary>
|
||||
public ConcurrentQueue<int> TiedToFebe { get; } = new();
|
||||
|
||||
/// <summary>What «Windows» answers when a process is tied to Febe.</summary>
|
||||
public bool TieSucceeds { get; set; } = true;
|
||||
|
||||
public bool EndWithFebe(System.Diagnostics.Process process)
|
||||
{
|
||||
TiedToFebe.Enqueue(process.Id);
|
||||
return TieSucceeds;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Folder picker, explorer, default browser, notifications (the Windows alerts) and autostart, faked.</summary>
|
||||
|
||||
@@ -0,0 +1,298 @@
|
||||
using System.Diagnostics;
|
||||
using System.Text.RegularExpressions;
|
||||
using System.Xml.Linq;
|
||||
using Febe.Tests.Desktop.Support;
|
||||
using Febe.Tests.Support;
|
||||
|
||||
namespace Febe.Tests.Packaging;
|
||||
|
||||
/// <summary>
|
||||
/// What ships Febe (spec §11, §12): the start of the container as root never follows what the unprivileged user can
|
||||
/// plant in <c>/dati</c> (pkg-2); the seccomp profile Docker reads on the server stays outside the Data volume (pkg-2);
|
||||
/// the release waits for the tests and for the image, and says when the image was not published (pkg-3); Docker Compose
|
||||
/// is released with the profile it points to (pkg-4); the image lives on the registry of the Gitea at home, in HTTP.
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
public sealed partial class PackagingTests
|
||||
{
|
||||
private const string Registry = "192.168.30.23:3000";
|
||||
private const int Nobody = 65534;
|
||||
|
||||
public TestContext TestContext { get; set; } = null!;
|
||||
|
||||
[TestMethod]
|
||||
[Timeout(60_000, CooperativeCancellation = true)]
|
||||
public async Task TheStartOfTheContainerNeverFollowsLinksPlantedInTheDataFolder()
|
||||
{
|
||||
var reason = EntrypointUnavailableReason();
|
||||
if (reason is not null)
|
||||
{
|
||||
Assert.Inconclusive(reason);
|
||||
}
|
||||
|
||||
using var temp = new TempFolder("avvio-contenitore");
|
||||
|
||||
// What a compromised browser (running as PUID) could leave in /dati before a restart: /dati/home pointing to
|
||||
// a folder of the container, /dati/seccomp.json pointing to one of its files.
|
||||
var victimFolder = temp.Combine("vittima");
|
||||
Directory.CreateDirectory(victimFolder);
|
||||
var victimFile = temp.Combine("vittima.txt");
|
||||
await File.WriteAllTextAsync(victimFile, "originale", TestContext.CancellationToken);
|
||||
var data = temp.Combine("dati");
|
||||
Directory.CreateDirectory(data);
|
||||
await RunAsync("chown", $"{Nobody}:{Nobody}", data);
|
||||
File.CreateSymbolicLink(Path.Combine(data, "home"), victimFolder);
|
||||
File.CreateSymbolicLink(Path.Combine(data, "seccomp.json"), victimFile);
|
||||
var before = (Folder: await StatAsync(victimFolder), File: await StatAsync(victimFile));
|
||||
|
||||
var (code, _, errors) = await RunEntrypointAsync(temp, "true");
|
||||
Assert.AreEqual(0, code, errors);
|
||||
Assert.AreEqual(before.Folder, await StatAsync(victimFolder), "a folder of the container never changes owner or mode");
|
||||
Assert.AreEqual(before.File, await StatAsync(victimFile));
|
||||
Assert.AreEqual("originale", await File.ReadAllTextAsync(victimFile, TestContext.CancellationToken), "nor is a file written through a link");
|
||||
StringAssert.Contains(errors, "/dati/seccomp.json non si aggiorna più", "the old profile in /dati is pointed out");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[Timeout(60_000, CooperativeCancellation = true)]
|
||||
public async Task TheStartOfTheContainerPreparesTheDataFolderAsTheUserAndKeepsTheProfileOut()
|
||||
{
|
||||
var reason = EntrypointUnavailableReason();
|
||||
if (reason is not null)
|
||||
{
|
||||
Assert.Inconclusive(reason);
|
||||
}
|
||||
|
||||
// A first start: /dati and /libreria just created by Docker (root), a folder of photos inside the library.
|
||||
using var temp = new TempFolder("avvio-contenitore");
|
||||
Directory.CreateDirectory(temp.Combine("libreria", "foto"));
|
||||
var whoAmI = temp.Combine("dati", "home", "chi");
|
||||
var (code, _, errors) = await RunEntrypointAsync(temp, "/bin/sh", "-c", $"id -u > '{whoAmI}'");
|
||||
Assert.AreEqual(0, code, errors);
|
||||
Assert.AreEqual($"{Nobody}:{Nobody} 750", await StatAsync(temp.Combine("dati")));
|
||||
Assert.AreEqual($"{Nobody}:{Nobody} 700", await StatAsync(temp.Combine("dati", "home")), "HOME of Chromium, made by the user");
|
||||
Assert.AreEqual(Nobody.ToString(System.Globalization.CultureInfo.InvariantCulture), (await File.ReadAllTextAsync(whoAmI, TestContext.CancellationToken)).Trim(), "Febe runs as PUID");
|
||||
Assert.IsFalse(File.Exists(temp.Combine("dati", "seccomp.json")), "the profile Docker reads stays out of /dati");
|
||||
Assert.AreEqual($"{Nobody}:{Nobody}", (await StatAsync(temp.Combine("libreria"))).Split(' ')[0]);
|
||||
Assert.AreEqual("0:0", (await StatAsync(temp.Combine("libreria", "foto"))).Split(' ')[0], "the library is never changed recursively");
|
||||
|
||||
// A /dati/home left by a start as root (a real folder): given back to the user.
|
||||
await RunAsync("chown", "0:0", temp.Combine("dati", "home"));
|
||||
(code, _, errors) = await RunEntrypointAsync(temp, "true");
|
||||
Assert.AreEqual(0, code, errors);
|
||||
Assert.AreEqual($"{Nobody}:{Nobody} 700", await StatAsync(temp.Combine("dati", "home")));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TheUnraidTemplateUsesTheRegistryAtHomeAndKeepsTheSeccompProfileOutOfTheDataFolder()
|
||||
{
|
||||
var template = XDocument.Load(Repository.PathOf("docker", "unraid", "febe.xml")).Root!;
|
||||
string Field(string name) => template.Element(name)?.Value.Trim() ?? string.Empty;
|
||||
Assert.AreEqual($"{Registry}/alby96/febe:latest", Field("Repository"));
|
||||
foreach (var name in new[] { "Registry", "Support", "Project", "TemplateURL", "Icon" })
|
||||
{
|
||||
StringAssert.StartsWith(Field(name), $"http://{Registry}/Alby96/", name);
|
||||
}
|
||||
|
||||
StringAssert.EndsWith(Field("TemplateURL"), "/raw/branch/main/docker/unraid/febe.xml");
|
||||
StringAssert.EndsWith(Field("Icon"), "/raw/branch/main/docker/unraid/febe.png");
|
||||
StringAssert.Contains(Field("Requires"), "insecure-registries");
|
||||
|
||||
// pkg-2: Docker reads the profile on the server when it creates the container; inside the Data volume the user
|
||||
// of the container could loosen it.
|
||||
var data = template.Elements("Config").Single(c => (string?)c.Attribute("Target") == "/dati").Value.Trim();
|
||||
var profile = SeccompProfile().Match(Field("ExtraParams"));
|
||||
Assert.IsTrue(profile.Success, Field("ExtraParams"));
|
||||
var path = profile.Groups["path"].Value;
|
||||
Assert.IsFalse(path.StartsWith(data.TrimEnd('/') + "/", StringComparison.Ordinal), $"{path} is inside {data}");
|
||||
StringAssert.Contains(Field("Requires"), path, "the template says how to put the profile there");
|
||||
StringAssert.Contains(Field("Requires"), "/usr/share/febe/seccomp.json");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TheComposeFilePointsToTheRegistryAtHomeAndToAProfileOutsideTheDataVolume()
|
||||
{
|
||||
var compose = File.ReadAllText(Repository.PathOf("docker", "compose.yml"));
|
||||
StringAssert.Contains(compose, $"image: {Registry}/alby96/febe:latest");
|
||||
StringAssert.Contains(compose, "- seccomp=./chromium/seccomp.json");
|
||||
Assert.IsTrue(File.Exists(Repository.PathOf("docker", "chromium", "seccomp.json")), "the profile is next to compose.yml");
|
||||
StringAssert.Contains(compose, ":/dati");
|
||||
Assert.DoesNotContain("seccomp.json:/dati", compose);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TheReleaseWaitsForTheTestsAndTheImageAndShipsComposeWithItsProfile()
|
||||
{
|
||||
var workflow = Workflow("rilascio.yml");
|
||||
var prove = Job(workflow, "prove");
|
||||
StringAssert.Contains(prove, "dotnet build Febe.slnx -c Release -nologo -warnaserror");
|
||||
StringAssert.Contains(prove, "dotnet test tests/Febe.Tests -c Release --no-build");
|
||||
StringAssert.Contains(Job(workflow, "windows"), "needs: prove");
|
||||
var image = Job(workflow, "immagine");
|
||||
StringAssert.Contains(image, "needs: prove");
|
||||
|
||||
// pkg-3: the release needs the tests, the installer and the image job, which says whether it published.
|
||||
var release = Job(workflow, "release");
|
||||
StringAssert.Contains(release, "needs: [prove, windows, immagine]");
|
||||
Assert.DoesNotContain("if:", release, "no «always()»: a failed build or push stops the release");
|
||||
StringAssert.Contains(image, "pubblicata: ${{ steps.pubblicazione.outputs.pubblicata }}");
|
||||
StringAssert.Contains(release, "PUBBLICATA: ${{ needs.immagine.outputs.pubblicata }}");
|
||||
StringAssert.Contains(release, "non è stata pubblicata");
|
||||
|
||||
// Without the secret the image is built and tested, and the job still succeeds: the release says so.
|
||||
var secret = Step(image, "Segreto per il registro");
|
||||
Assert.DoesNotContain("exit 1", secret);
|
||||
StringAssert.Contains(secret, "presente=no");
|
||||
StringAssert.Contains(Step(image, "Pubblicazione sul registro di Gitea"), "if: steps.segreto.outputs.presente == 'si'");
|
||||
|
||||
// The registry at home answers in HTTP: buildx with its own builder, told so, and no «docker login».
|
||||
StringAssert.Contains(image, "uses: docker/setup-buildx-action@v3");
|
||||
StringAssert.Contains(image, "http = true");
|
||||
StringAssert.Contains(image, "insecure = true");
|
||||
StringAssert.Contains(image, "--push");
|
||||
Assert.DoesNotContain("docker login", image);
|
||||
Assert.DoesNotContain("docker push", image);
|
||||
|
||||
// pkg-4: compose.yml goes out with chromium/seccomp.json next to it, never alone.
|
||||
StringAssert.Contains(release, "cp docker/compose.yml \"$COMPOSE/compose.yml\"");
|
||||
StringAssert.Contains(release, "cp docker/chromium/seccomp.json \"$COMPOSE/chromium/seccomp.json\"");
|
||||
StringAssert.Contains(release, "\"$COMPOSE.tar.gz\"");
|
||||
Assert.DoesNotContain("febe-compose-$VERSION.yml", release);
|
||||
}
|
||||
|
||||
/// <summary>Why the entrypoint cannot be run here (it needs Linux, root, setpriv and the user «nobody»); null when it can.</summary>
|
||||
private static string? EntrypointUnavailableReason()
|
||||
{
|
||||
if (!OperatingSystem.IsLinux())
|
||||
{
|
||||
return "L'avvio del contenitore si prova solo su Linux.";
|
||||
}
|
||||
|
||||
if (Environment.UserName != "root")
|
||||
{
|
||||
return "L'avvio del contenitore gira come root: la prova si salta senza root.";
|
||||
}
|
||||
|
||||
foreach (var tool in new[] { "sh", "setpriv", "stat", "chown", "getent" })
|
||||
{
|
||||
if (FindOnPath(tool) is null)
|
||||
{
|
||||
return $"Manca {tool}: la prova dell'avvio del contenitore si salta.";
|
||||
}
|
||||
}
|
||||
|
||||
// The entrypoint creates the user and the group when they are missing: never on the machine of the tests.
|
||||
return Run("getent", "passwd", Nobody.ToString(System.Globalization.CultureInfo.InvariantCulture)) && Run("getent", "group", Nobody.ToString(System.Globalization.CultureInfo.InvariantCulture))
|
||||
? null
|
||||
: $"L'utente o il gruppo {Nobody} non esistono qui: la prova si salta per non crearli.";
|
||||
}
|
||||
|
||||
/// <summary>The real entrypoint, with /dati, /libreria and the profile of the image moved into <paramref name="temp"/>.</summary>
|
||||
private async Task<(int Code, string Output, string Errors)> RunEntrypointAsync(TempFolder temp, params string[] command)
|
||||
{
|
||||
var text = await File.ReadAllTextAsync(Repository.PathOf("docker", "entrypoint.sh"), TestContext.CancellationToken);
|
||||
var image = temp.Combine("immagine-seccomp.json");
|
||||
await File.WriteAllTextAsync(image, "{}", TestContext.CancellationToken);
|
||||
var relocated = text
|
||||
.Replace("/usr/share/febe/seccomp.json", image, StringComparison.Ordinal)
|
||||
.Replace("/dati", temp.Combine("dati"), StringComparison.Ordinal)
|
||||
.Replace("/libreria", temp.Combine("libreria"), StringComparison.Ordinal)
|
||||
.Replace("groupadd ", ": groupadd ", StringComparison.Ordinal)
|
||||
.Replace("useradd ", ": useradd ", StringComparison.Ordinal);
|
||||
var script = temp.Combine("avvio.sh");
|
||||
await File.WriteAllTextAsync(script, relocated, TestContext.CancellationToken);
|
||||
var start = new ProcessStartInfo("sh") { RedirectStandardOutput = true, RedirectStandardError = true };
|
||||
start.ArgumentList.Add(script);
|
||||
foreach (var part in command)
|
||||
{
|
||||
start.ArgumentList.Add(part);
|
||||
}
|
||||
|
||||
start.Environment["PUID"] = Nobody.ToString(System.Globalization.CultureInfo.InvariantCulture);
|
||||
start.Environment["PGID"] = Nobody.ToString(System.Globalization.CultureInfo.InvariantCulture);
|
||||
using var process = Process.Start(start)!;
|
||||
var output = process.StandardOutput.ReadToEndAsync(TestContext.CancellationToken);
|
||||
var errors = process.StandardError.ReadToEndAsync(TestContext.CancellationToken);
|
||||
await process.WaitForExitAsync(TestContext.CancellationToken);
|
||||
return (process.ExitCode, await output, await errors);
|
||||
}
|
||||
|
||||
/// <summary>Owner, group and mode of a path, without following a final link («0:0 755»).</summary>
|
||||
private async Task<string> StatAsync(string path)
|
||||
{
|
||||
var start = new ProcessStartInfo("stat") { RedirectStandardOutput = true };
|
||||
foreach (var part in new[] { "-c", "%u:%g %a", path })
|
||||
{
|
||||
start.ArgumentList.Add(part);
|
||||
}
|
||||
|
||||
using var process = Process.Start(start)!;
|
||||
var text = await process.StandardOutput.ReadToEndAsync(TestContext.CancellationToken);
|
||||
await process.WaitForExitAsync(TestContext.CancellationToken);
|
||||
Assert.AreEqual(0, process.ExitCode, path);
|
||||
return text.Trim();
|
||||
}
|
||||
|
||||
private async Task RunAsync(string program, params string[] arguments)
|
||||
{
|
||||
using var process = Process.Start(new ProcessStartInfo(program, arguments))!;
|
||||
await process.WaitForExitAsync(TestContext.CancellationToken);
|
||||
Assert.AreEqual(0, process.ExitCode, $"{program} {string.Join(' ', arguments)}");
|
||||
}
|
||||
|
||||
private static bool Run(string program, params string[] arguments)
|
||||
{
|
||||
using var process = Process.Start(new ProcessStartInfo(program, arguments) { RedirectStandardOutput = true, RedirectStandardError = true })!;
|
||||
process.StandardOutput.ReadToEnd();
|
||||
process.StandardError.ReadToEnd();
|
||||
process.WaitForExit();
|
||||
return process.ExitCode == 0;
|
||||
}
|
||||
|
||||
/// <summary>A workflow of .gitea/workflows; inconclusive in the build of the image, whose context leaves .gitea out.</summary>
|
||||
private static string Workflow(string name)
|
||||
{
|
||||
var path = Repository.PathOf(".gitea", "workflows", name);
|
||||
var root = Repository.Root()!;
|
||||
if (!File.Exists(path) && !Directory.Exists(Path.Combine(root, ".git")) && !File.Exists(Path.Combine(root, ".git")))
|
||||
{
|
||||
Assert.Inconclusive("Questa copia del repository non ha .gitea/ (costruzione dell'immagine Docker).");
|
||||
}
|
||||
|
||||
return File.ReadAllText(path).Replace("\r\n", "\n", StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
/// <summary>The block of a job: from « name:» to the next job.</summary>
|
||||
private static string Job(string workflow, string name)
|
||||
{
|
||||
var match = Regex.Match(workflow, $@"^ {Regex.Escape(name)}:\n(?<body>(?:(?: .*|\s*)\n)*)", RegexOptions.Multiline);
|
||||
Assert.IsTrue(match.Success, $"manca il lavoro {name}");
|
||||
return match.Groups["body"].Value;
|
||||
}
|
||||
|
||||
/// <summary>The block of a step, from its «- name:» to the next step.</summary>
|
||||
private static string Step(string job, string name)
|
||||
{
|
||||
var start = job.IndexOf("- name: " + name, StringComparison.Ordinal);
|
||||
Assert.IsGreaterThanOrEqualTo(0, start, $"manca il passo «{name}»");
|
||||
var next = job.IndexOf("\n - ", start + 1, StringComparison.Ordinal);
|
||||
return next < 0 ? job[start..] : job[start..next];
|
||||
}
|
||||
|
||||
private static string? FindOnPath(string name)
|
||||
{
|
||||
foreach (var folder in (Environment.GetEnvironmentVariable("PATH") ?? string.Empty).Split(Path.PathSeparator, StringSplitOptions.RemoveEmptyEntries))
|
||||
{
|
||||
var path = Path.Combine(folder, name);
|
||||
if (File.Exists(path))
|
||||
{
|
||||
return path;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
[GeneratedRegex(@"--security-opt seccomp=(?<path>\S+)")]
|
||||
private static partial Regex SeccompProfile();
|
||||
}
|
||||
@@ -0,0 +1,219 @@
|
||||
using System.Diagnostics;
|
||||
using System.Net;
|
||||
using System.Text.Json;
|
||||
using Febe.Tests.Desktop.Support;
|
||||
using Febe.Tests.Support;
|
||||
using Febe.Tests.Web.Support;
|
||||
using Febe.Web;
|
||||
using Febe.Web.Security;
|
||||
|
||||
namespace Febe.Tests.Web;
|
||||
|
||||
/// <summary>
|
||||
/// The login page of the Docker interface (spec §13.1): after the password it goes back only to a page of the interface
|
||||
/// («torna»), never to another site (websec-2, web-8); the session cookie is <c>Secure</c> whenever the browser talked
|
||||
/// HTTPS, also through the trusted proxy of <c>FEBE_PROXY_FIDATO</c> (websec-3).
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
public sealed class LoginSecurityTests
|
||||
{
|
||||
private const string Password = "una password lunga";
|
||||
|
||||
/// <summary>Values of «torna» a crafted link could carry, each of which a browser resolves to another site.</summary>
|
||||
private static readonly string[] Foreign =
|
||||
[
|
||||
"//evil.example",
|
||||
"/\\evil.example",
|
||||
"/\\/evil.example",
|
||||
"/\t/evil.example",
|
||||
"/\n/evil.example",
|
||||
"/\r/evil.example",
|
||||
"\\\\evil.example",
|
||||
"/./\\evil.example",
|
||||
"http://evil.example/",
|
||||
"https:evil.example",
|
||||
"javascript:alert(1)",
|
||||
" /libreria",
|
||||
"/libreria\u0000",
|
||||
"libreria",
|
||||
"",
|
||||
];
|
||||
|
||||
/// <summary>Paths of the interface, which must still work.</summary>
|
||||
private static readonly string[] Own = ["/libreria", "/account/12", "/impostazioni/collegamento", "/libreria?tipo=foto#x", "/%5Cnon-un-sito", "/.//dentro"];
|
||||
|
||||
public TestContext TestContext { get; set; } = null!;
|
||||
|
||||
[TestMethod]
|
||||
public void TheServerAcceptsOnlyPathsOfTheInterface()
|
||||
{
|
||||
foreach (var value in Foreign)
|
||||
{
|
||||
Assert.IsFalse(LoginReturn.IsSafe(value), JsonSerializer.Serialize(value));
|
||||
Assert.AreEqual("/accesso", LoginReturn.LoginAddress(value));
|
||||
}
|
||||
|
||||
Assert.IsFalse(LoginReturn.IsSafe(null));
|
||||
Assert.IsFalse(LoginReturn.IsSafe("/" + new string('a', LoginReturn.MaxLength)));
|
||||
foreach (var value in Own)
|
||||
{
|
||||
Assert.IsTrue(LoginReturn.IsSafe(value), value);
|
||||
}
|
||||
|
||||
Assert.AreEqual("/accesso?torna=%2Faccount%2F12", LoginReturn.LoginAddress("/account/12"));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task ACraftedLinkToTheLoginPageLosesItsReturnBeforeThePageShows()
|
||||
{
|
||||
await using var server = await StartAsync(trustProxy: false);
|
||||
foreach (var page in new[] { "/accesso", "/accesso.html" })
|
||||
{
|
||||
foreach (var value in new[] { "/\\evil.example", "//evil.example", "/\t/evil.example", "http://evil.example/" })
|
||||
{
|
||||
using var response = await server.Client.GetAsync($"{page}?torna={Uri.EscapeDataString(value)}", TestContext.CancellationToken);
|
||||
Assert.AreEqual(HttpStatusCode.Redirect, response.StatusCode, $"{page} {JsonSerializer.Serialize(value)}");
|
||||
Assert.AreEqual("/accesso", response.Headers.Location?.OriginalString);
|
||||
}
|
||||
}
|
||||
|
||||
using (var own = await server.Client.GetAsync("/accesso?torna=%2Faccount%2F12", TestContext.CancellationToken))
|
||||
{
|
||||
Assert.AreEqual(HttpStatusCode.OK, own.StatusCode, "a page of the interface stays");
|
||||
}
|
||||
|
||||
// A page asked through an address that a browser would read as another site: the login page, without «torna».
|
||||
using (var crafted = await server.Client.GetAsync("/%5Cevil.example", TestContext.CancellationToken))
|
||||
{
|
||||
Assert.AreEqual(HttpStatusCode.Redirect, crafted.StatusCode);
|
||||
Assert.AreEqual("/accesso", crafted.Headers.Location?.OriginalString);
|
||||
}
|
||||
|
||||
using (var normal = await server.Client.GetAsync("/account/12", TestContext.CancellationToken))
|
||||
{
|
||||
Assert.AreEqual("/accesso?torna=%2Faccount%2F12", normal.Headers.Location?.OriginalString);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TheLoginPageGoesBackOnlyToAPageOfTheInterface()
|
||||
{
|
||||
var accesso = File.ReadAllText(Repository.PathOf("src", "Febe.Web", "wwwroot", "js", "accesso.js"));
|
||||
StringAssert.Contains(accesso, "import { returnAddress } from './core/return-path.js';");
|
||||
StringAssert.Contains(accesso, "location.href = returnAddress(");
|
||||
Assert.DoesNotContain("startsWith('//')", accesso, "the old check let «/\\host» through");
|
||||
|
||||
var node = FindOnPath("node");
|
||||
if (node is null)
|
||||
{
|
||||
Assert.Inconclusive("Node non è installato: la regola della pagina di accesso si prova solo dove c'è (CI, sviluppo).");
|
||||
}
|
||||
|
||||
const string origin = "http://tower:8480";
|
||||
List<(string? Value, string Expected)> cases =
|
||||
[
|
||||
.. Foreign.Select(v => ((string?)v, origin + "/libreria")),
|
||||
(null, origin + "/libreria"),
|
||||
("/account/12", origin + "/account/12"),
|
||||
("/libreria?tipo=foto#x", origin + "/libreria?tipo=foto#x"),
|
||||
("/%5Cnon-un-sito", origin + "/%5Cnon-un-sito"),
|
||||
// The path is normalised to «//dentro», but the page goes to the absolute address: still this site.
|
||||
("/.//dentro", origin + "//dentro"),
|
||||
];
|
||||
|
||||
using var temp = new TempFolder("accesso-js");
|
||||
var script = temp.Combine("prova.mjs");
|
||||
var module = new Uri(Repository.PathOf("src", "Febe.Web", "wwwroot", "js", "core", "return-path.js")).AbsoluteUri;
|
||||
File.WriteAllText(script, $$"""
|
||||
import { returnAddress } from '{{module}}';
|
||||
const cases = JSON.parse(process.argv[2]);
|
||||
console.log(JSON.stringify(cases.map(v => returnAddress(v, '{{origin}}'))));
|
||||
""");
|
||||
var start = new ProcessStartInfo(node) { RedirectStandardOutput = true, RedirectStandardError = true };
|
||||
start.ArgumentList.Add(script);
|
||||
start.ArgumentList.Add(JsonSerializer.Serialize(cases.Select(c => c.Value)));
|
||||
using var process = Process.Start(start)!;
|
||||
var output = process.StandardOutput.ReadToEnd();
|
||||
var errors = process.StandardError.ReadToEnd();
|
||||
process.WaitForExit();
|
||||
Assert.AreEqual(0, process.ExitCode, errors);
|
||||
var results = JsonSerializer.Deserialize<string[]>(output)!;
|
||||
for (var i = 0; i < cases.Count; i++)
|
||||
{
|
||||
Assert.AreEqual(cases[i].Expected, results[i], JsonSerializer.Serialize(cases[i].Value));
|
||||
Assert.AreEqual("tower:8480", new Uri(results[i]).Authority, "never another site");
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task TheSessionCookieIsSecureBehindTheTrustedProxyWithHttps()
|
||||
{
|
||||
// Plain HTTP on the network of home: no Secure, or the browser would drop the cookie.
|
||||
await using (var plain = await StartAsync(trustProxy: false))
|
||||
{
|
||||
Assert.IsFalse(IsSecure(await LoginAsync(plain, origin: null, forwardedHost: null, forwardedProto: null)));
|
||||
|
||||
// Without FEBE_PROXY_FIDATO the header is anybody's: it changes nothing.
|
||||
Assert.IsFalse(IsSecure(await LoginAsync(plain, origin: null, forwardedHost: null, forwardedProto: "https")));
|
||||
}
|
||||
|
||||
await using var proxied = await StartAsync(trustProxy: true);
|
||||
Assert.IsTrue(IsSecure(await LoginAsync(proxied, origin: "https://febe.example.org", forwardedHost: "febe.example.org", forwardedProto: "https")));
|
||||
Assert.IsTrue(IsSecure(await LoginAsync(proxied, origin: null, forwardedHost: null, forwardedProto: "https, http")), "the value the proxy next to the browser wrote");
|
||||
Assert.IsFalse(IsSecure(await LoginAsync(proxied, origin: null, forwardedHost: null, forwardedProto: "http")), "the proxy says the browser used HTTP");
|
||||
var session = await LoginAsync(proxied, origin: null, forwardedHost: null, forwardedProto: null);
|
||||
Assert.IsFalse(IsSecure(session), "LAN access next to the proxy");
|
||||
|
||||
using var logout = proxied.Request(HttpMethod.Post, "/api/uscita");
|
||||
logout.Headers.TryAddWithoutValidation("Cookie", session.Split(';')[0]);
|
||||
logout.Headers.TryAddWithoutValidation("X-Forwarded-Proto", "https");
|
||||
using var response = await proxied.Client.SendAsync(logout, TestContext.CancellationToken);
|
||||
Assert.IsTrue(IsSecure(response.Headers.GetValues("Set-Cookie").Single()), "the logout clears the same cookie");
|
||||
}
|
||||
|
||||
private static Task<WebTestServer> StartAsync(bool trustProxy) => WebTestServer.StartAsync(new FebeWebOptions
|
||||
{
|
||||
Access = AccessMode.Password,
|
||||
Password = Password,
|
||||
TrustForwardedHost = trustProxy,
|
||||
Lockout = new LockoutOptions { AttemptsPerClient = 50, AttemptsOverall = 50 },
|
||||
});
|
||||
|
||||
private async Task<string> LoginAsync(WebTestServer server, string? origin, string? forwardedHost, string? forwardedProto)
|
||||
{
|
||||
using var request = server.Request(HttpMethod.Post, "/api/accesso", new { password = Password }, origin ?? string.Empty);
|
||||
if (forwardedHost is not null)
|
||||
{
|
||||
request.Headers.TryAddWithoutValidation("X-Forwarded-Host", forwardedHost);
|
||||
}
|
||||
|
||||
if (forwardedProto is not null)
|
||||
{
|
||||
request.Headers.TryAddWithoutValidation("X-Forwarded-Proto", forwardedProto);
|
||||
}
|
||||
|
||||
using var response = await server.Client.SendAsync(request, TestContext.CancellationToken);
|
||||
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode, await response.Content.ReadAsStringAsync(TestContext.CancellationToken));
|
||||
return response.Headers.GetValues("Set-Cookie").Single();
|
||||
}
|
||||
|
||||
private static bool IsSecure(string setCookie) =>
|
||||
setCookie.Split(';').Any(part => string.Equals(part.Trim(), "secure", StringComparison.OrdinalIgnoreCase));
|
||||
|
||||
private static string? FindOnPath(string name)
|
||||
{
|
||||
foreach (var folder in (Environment.GetEnvironmentVariable("PATH") ?? string.Empty).Split(Path.PathSeparator, StringSplitOptions.RemoveEmptyEntries))
|
||||
{
|
||||
foreach (var candidate in new[] { name, name + ".exe" })
|
||||
{
|
||||
var path = Path.Combine(folder, candidate);
|
||||
if (File.Exists(path))
|
||||
{
|
||||
return path;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user