Files
opengenesislinkserver/tools/ci/WebDavBackupRegression/Program.cs
T
OpenGenesisLINK Maintenance 2ef585be75
Generation 1.1 .NET 10 ARM64 Server Runtime / ROBUST and Simulator .NET 10 ARM64 build + boot (push) Waiting to run
OpenGenesisLINK main - .NET 10 Build Gate / .NET 10 Windows x64 build (push) Waiting to run
NexVerse CI / Build NexVerse (push) Failing after 1m0s
NexVerse CI / NV dollar live database matrix (push) Failing after 16s
Generation 1 Stable and Updates source policy / release-policy (push) Successful in 17s
OpenGenesisLINK main - .NET 10 Build Gate / .NET 10 generated-project and server build (push) Successful in 1m36s
OpenGenesisLINK Generation 1 - Abgeschlossene Branches bereinigen / Abgeschlossene und nicht mehr benoetigte Branches entfernen (push) Successful in 27s
Security(gen1): WebDAV-Zugangsdaten als private hostlokale DLL kapseln
2026-12-04 19:30:07 +01:00

136 lines
7.4 KiB
C#

// SPDX-License-Identifier: MPL-2.0
using System.Net;
using System.Net.Http.Headers;
using System.Xml.Linq;
using OpenGenesisLINK.Addons.OSWebInterface;
static void Check(bool value, string message)
{
if (!value) throw new Exception(message);
}
static async Task Reject(Func<Task> action, string message)
{
try { await action(); }
catch (WebDavBackupStore.BackupException) { return; }
throw new Exception(message);
}
if (args.Length == 2 && args[0] == "--private-fixture")
{
using var fixture = File.OpenRead(args[1]);
var header = WebDavBackupStore.ReadPrivateAssembly(fixture);
Check(header.Scheme == "Basic" && header.Parameter == Convert.ToBase64String(
System.Text.Encoding.UTF8.GetBytes("fixture-user:fixture-only-password")), "Private DLL metadata mismatch");
Console.WriteLine("Private DLL metadata regression PASS");
}
try
{
using var invalid = new MemoryStream(new byte[512]);
_ = WebDavBackupStore.ReadPrivateAssembly(invalid);
throw new Exception("Invalid private DLL accepted");
}
catch (BadImageFormatException) { }
var root = new Uri("https://backup.example.test/ogl-backup/");
using var handler = new MockDav(root);
using var store = new WebDavBackupStore(new HttpClient(handler), root,
() => new AuthenticationHeaderValue("Basic", "test-fixture"));
string folder = Path.Combine(Path.GetTempPath(), "ogl-webdav-regression-" + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(folder);
try
{
var user = Guid.NewGuid();
var region = Guid.NewGuid();
string iar = WebDavBackupStore.AvatarName(user);
string iarPath = "/ogl-backup/IAR/" + iar;
string file = Path.Combine(folder, "archive");
File.WriteAllBytes(file, new byte[] { 1, 2, 3 });
await store.SaveAsync("iar", iar, file);
Check(handler.Files[iarPath].SequenceEqual(new byte[] { 1, 2, 3 }), "Initial IAR");
File.WriteAllBytes(file, new byte[] { 4, 5, 6, 7 });
handler.FailPut = true;
await Reject(() => store.SaveAsync("iar", iar, file), "Failed PUT was accepted");
Check(handler.Files[iarPath].SequenceEqual(new byte[] { 1, 2, 3 }), "PUT failure destroyed IAR");
handler.FailPut = false;
handler.WrongSize = true;
await Reject(() => store.SaveAsync("iar", iar, file), "Wrong upload size accepted");
Check(handler.Files[iarPath].Length == 3, "Size mismatch replaced IAR");
handler.WrongSize = false;
handler.FailMove = true;
await Reject(() => store.SaveAsync("iar", iar, file), "Failed MOVE was accepted");
Check(handler.Files[iarPath].Length == 3, "MOVE failure destroyed IAR");
handler.FailMove = false;
await store.SaveAsync("iar", iar, file);
Check(handler.Files[iarPath].SequenceEqual(new byte[] { 4, 5, 6, 7 }), "IAR replacement");
Check(handler.Files.Count == 1, "Staging file leaked");
string oar = WebDavBackupStore.RegionName("Test/Region", region, Guid.NewGuid(), DateTimeOffset.UtcNow);
await store.SaveAsync("oar", oar, file);
await Reject(() => store.SaveAsync("oar", oar, file), "OAR overwrite permitted");
string second = WebDavBackupStore.RegionName("Test/Region", region, Guid.NewGuid(), DateTimeOffset.UtcNow);
await store.SaveAsync("oar", second, file);
handler.Files["/ogl-backup/IAR/upload-abcd.part"] = new byte[] { 42 };
handler.Files["/ogl-backup/IAR/not-an-archive.txt"] = new byte[] { 1 };
var listed = await store.ListAsync(CancellationToken.None);
Check(listed.Length == 3 && listed.Count(x => x.Kind == "iar") == 1, "Invalid listing or duplicate IAR");
Check(listed.All(x => x.Bytes == 4), "Incorrect list sizes");
await Reject(() => store.SaveAsync("iar", "../avatar.iar", file), "Traversal accepted");
Check(!WebDavBackupStore.ValidName("iar", iar + "\n"), "Unsafe filename accepted");
handler.FailAuth = true;
await Reject(() => store.ListAsync(CancellationToken.None), "Auth failure ignored");
handler.FailAuth = false;
handler.Redirect = true;
await Reject(() => store.ListAsync(CancellationToken.None), "Redirect accepted");
Console.WriteLine("WebDAV regression PASS: staged PUT, size check, atomic MOVE replacement, old IAR retention, unique OARs, filtered listing, traversal/auth/redirect rejection");
}
finally { Directory.Delete(folder, true); }
sealed class MockDav(Uri root) : HttpMessageHandler
{
public Dictionary<string, byte[]> Files { get; } = new();
public bool FailPut, FailMove, WrongSize, FailAuth, Redirect;
private readonly HashSet<string> _folders = new();
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage req, CancellationToken ct)
{
HttpResponseMessage Reply(HttpStatusCode code) => new(code);
string path = req.RequestUri!.AbsolutePath;
if (req.RequestUri.GetLeftPart(UriPartial.Authority) != root.GetLeftPart(UriPartial.Authority))
throw new Exception("Unexpected host");
if (FailAuth) return Reply(HttpStatusCode.Unauthorized);
if (Redirect) return Reply(HttpStatusCode.Found);
if (req.Headers.Authorization?.Scheme != "Basic") throw new Exception("Missing authentication");
switch (req.Method.Method)
{
case "MKCOL": return Reply(_folders.Add(path) ? HttpStatusCode.Created : HttpStatusCode.MethodNotAllowed);
case "PUT":
if (FailPut) { Files[path] = new byte[] { 99 }; return Reply(HttpStatusCode.InsufficientStorage); }
Files[path] = await req.Content!.ReadAsByteArrayAsync(ct);
return Reply(HttpStatusCode.Created);
case "HEAD":
if (!Files.TryGetValue(path, out var bytes)) return Reply(HttpStatusCode.NotFound);
var head = Reply(HttpStatusCode.OK);
head.Content = new ByteArrayContent(Array.Empty<byte>());
head.Content.Headers.ContentLength = bytes.Length + (WrongSize && path.EndsWith(".part") ? 1 : 0);
return head;
case "MOVE":
if (FailMove) return Reply(HttpStatusCode.InsufficientStorage);
var dest = new Uri(req.Headers.GetValues("Destination").Single()).AbsolutePath;
bool exists = Files.ContainsKey(dest);
if (exists && req.Headers.GetValues("Overwrite").Single() != "T") return Reply(HttpStatusCode.PreconditionFailed);
Files[dest] = Files[path]; Files.Remove(path);
return Reply(exists ? HttpStatusCode.NoContent : HttpStatusCode.Created);
case "DELETE":
Files.Remove(path); return Reply(HttpStatusCode.NoContent);
case "PROPFIND":
if (path != root.AbsolutePath && !_folders.Contains(path)) return Reply(HttpStatusCode.NotFound);
XNamespace d = "DAV:";
var xml = new XElement(d+"multistatus", Files.Where(x => x.Key.StartsWith(path))
.Select(x => new XElement(d+"response", new XElement(d+"href",x.Key),
new XElement(d+"propstat",new XElement(d+"prop",new XElement(d+"getcontentlength",x.Value.Length),
new XElement(d+"getlastmodified","Fri, 04 Dec 2026 18:00:00 GMT"),new XElement(d+"resourcetype")),
new XElement(d+"status","HTTP/1.1 200 OK")))));
var response = Reply((HttpStatusCode)207);
response.Content = new StringContent(xml.ToString());
return response;
default: throw new Exception("Unexpected DAV method: "+req.Method);
}
}
}