414 lines
18 KiB
C#
414 lines
18 KiB
C#
using System.Diagnostics;
|
|
using System.Net;
|
|
using System.Net.Http.Json;
|
|
using System.Text;
|
|
using Backend.Auth;
|
|
using Backend.Data;
|
|
using Backend.Logs;
|
|
using Microsoft.EntityFrameworkCore;
|
|
using Microsoft.Extensions.DependencyInjection;
|
|
using Microsoft.Extensions.Logging;
|
|
using Shared.Contracts.Api;
|
|
using Shared.Contracts.Messages;
|
|
using Shared.Contracts.Serialization;
|
|
using Xunit;
|
|
|
|
namespace Backend.Tests;
|
|
|
|
/// <summary>A device agent's logs on its Logs tab: who may see them, in which scope, and what reaches the agent.</summary>
|
|
public class DeviceLogEndpointTests(BackendTestFixture fixture) : IClassFixture<BackendTestFixture>
|
|
{
|
|
private FakeDeviceFileClient Agent => fixture.DeviceFiles;
|
|
|
|
private static readonly LogTailDto Tail = new("run-1", 2, [new LogLineDto(2, DateTimeOffset.UtcNow, LogLevels.Warning, "Agent.X", "careful")]);
|
|
|
|
private static readonly LogFilesDto Files = new(["C:\\Program Files\\ExecuteR\\Agent\\Logs"], [new LogFileDto("ExecuteR-Agent-20261106.log", 4, DateTimeOffset.UtcNow)]);
|
|
|
|
private static DeviceFileReply Answer(DeviceFileRequest request) => request.Operation switch
|
|
{
|
|
DeviceFileOperations.LogTail => new DeviceFileReply(DeviceFileStatuses.Ok, Log: Tail),
|
|
DeviceFileOperations.LogList => new DeviceFileReply(DeviceFileStatuses.Ok, LogFiles: Files),
|
|
DeviceFileOperations.LogRead => new DeviceFileReply(
|
|
DeviceFileStatuses.Ok,
|
|
Length: 4,
|
|
Entry: new DeviceFileEntry(request.Name!, $"C:\\Logs\\{request.Name}", false, 4, null, null, false, false, null)),
|
|
_ => new DeviceFileReply(DeviceFileStatuses.Ok),
|
|
};
|
|
|
|
private Task<Guid> RoleAsync(params string[] permissions) => fixture.WithDbAsync(async db =>
|
|
{
|
|
var role = new RoleEntity
|
|
{
|
|
Id = Guid.NewGuid(),
|
|
Name = $"logs-{Guid.NewGuid():N}",
|
|
PermissionsJson = JsonDefaults.Serialize(permissions),
|
|
CreatedUtc = DateTimeOffset.UtcNow,
|
|
UpdatedUtc = DateTimeOffset.UtcNow,
|
|
};
|
|
db.Roles.Add(role);
|
|
await db.SaveChangesAsync();
|
|
return role.Id;
|
|
});
|
|
|
|
private async Task<T> WithAgentAsync<T>(Func<Task<T>> action)
|
|
{
|
|
var before = Agent.Answer;
|
|
Agent.Answer = Answer;
|
|
try
|
|
{
|
|
return await action();
|
|
}
|
|
finally
|
|
{
|
|
Agent.Answer = before;
|
|
}
|
|
}
|
|
|
|
[Fact]
|
|
public async Task DeviceLogsAreTheirOwnPermission_NotFileBrowsing()
|
|
{
|
|
var device = await fixture.SeedDeviceAsync("LOGS-PERMS", online: true);
|
|
using var viewer = await fixture.SignedInAsync("logs-viewer", "Viewer");
|
|
using var helpDesk = await fixture.SignedInAsync("logs-helpdesk", "Help Desk");
|
|
using var browser = await fixture.SignedInAsync("logs-browser", roleId: await RoleAsync(Permissions.FilesBrowse));
|
|
using var logsOnly = await fixture.SignedInAsync("logs-only", roleId: await RoleAsync(Permissions.DevicesLogs));
|
|
var ct = TestContext.Current.CancellationToken;
|
|
|
|
await WithAgentAsync(async () =>
|
|
{
|
|
Assert.Equal(HttpStatusCode.Forbidden, (await viewer.GetAsync(ApiRoutes.For.DeviceLogTail(device), ct)).StatusCode);
|
|
Assert.Equal(HttpStatusCode.Forbidden, (await browser.GetAsync(ApiRoutes.For.DeviceLogFiles(device), ct)).StatusCode);
|
|
Assert.Equal(HttpStatusCode.OK, (await helpDesk.GetAsync(ApiRoutes.For.DeviceLogTail(device), ct)).StatusCode);
|
|
Assert.Equal(HttpStatusCode.OK, (await logsOnly.GetAsync(ApiRoutes.For.DeviceLogFiles(device), ct)).StatusCode);
|
|
|
|
// Logs reach no other file on the device, and server logs are another permission.
|
|
Assert.Equal(HttpStatusCode.Forbidden, (await logsOnly.GetAsync(ApiRoutes.For.DeviceFs(device, "roots"), ct)).StatusCode);
|
|
Assert.Equal(HttpStatusCode.Forbidden, (await logsOnly.GetAsync(ApiRoutes.ServerLogTail, ct)).StatusCode);
|
|
return true;
|
|
});
|
|
}
|
|
|
|
[Fact]
|
|
public async Task ADeviceOutOfScopeIsNotThere_AndTheAgentIsNeverAsked()
|
|
{
|
|
var mine = await fixture.SeedDeviceAsync("LOGS-MINE", online: true);
|
|
var theirs = await fixture.SeedDeviceAsync("LOGS-THEIRS", online: true);
|
|
using var scoped = await fixture.ScopedSignedInAsync("logs-scoped", mine);
|
|
var ct = TestContext.Current.CancellationToken;
|
|
|
|
await WithAgentAsync(async () =>
|
|
{
|
|
Assert.Equal(HttpStatusCode.OK, (await scoped.GetAsync(ApiRoutes.For.DeviceLogTail(mine), ct)).StatusCode);
|
|
|
|
int asked;
|
|
lock (Agent.Requests)
|
|
{
|
|
asked = Agent.Requests.Count;
|
|
}
|
|
|
|
Assert.Equal(HttpStatusCode.NotFound, (await scoped.GetAsync(ApiRoutes.For.DeviceLogTail(theirs), ct)).StatusCode);
|
|
Assert.Equal(HttpStatusCode.NotFound, (await scoped.GetAsync(ApiRoutes.For.DeviceLogFiles(theirs), ct)).StatusCode);
|
|
Assert.Equal(HttpStatusCode.NotFound, (await scoped.GetAsync(ApiRoutes.For.DeviceLogFile(theirs, "ExecuteR-Agent-20261106.log"), ct)).StatusCode);
|
|
lock (Agent.Requests)
|
|
{
|
|
Assert.Equal(asked, Agent.Requests.Count);
|
|
}
|
|
|
|
return true;
|
|
});
|
|
}
|
|
|
|
[Fact]
|
|
public async Task ATailCarriesItsCursorToTheAgent_AndItsAnswerBack()
|
|
{
|
|
var device = await fixture.SeedDeviceAsync("LOGS-TAIL", online: true);
|
|
using var admin = await fixture.SignedInAsync("logs-admin");
|
|
var ct = TestContext.Current.CancellationToken;
|
|
|
|
var tail = await WithAgentAsync(() => admin.GetFromJsonAsync<LogTailDto>(
|
|
$"{ApiRoutes.For.DeviceLogTail(device)}?source=watchdog&instance=run-1&after=1&wait=600", JsonDefaults.Options, ct));
|
|
|
|
Assert.Equal("careful", Assert.Single(tail!.Lines).Message);
|
|
Assert.Equal(LogLevels.Warning, tail.Lines[0].Level);
|
|
lock (Agent.Requests)
|
|
{
|
|
var asked = Agent.Requests.Last(r => r.Operation == DeviceFileOperations.LogTail);
|
|
Assert.Equal(LogSources.Watchdog, asked.Name);
|
|
Assert.Equal("run-1", asked.Instance);
|
|
Assert.Equal(1, asked.After);
|
|
Assert.Equal(LiveLogLimits.MaxWaitSeconds, asked.WaitSeconds);
|
|
Assert.Null(asked.Path);
|
|
}
|
|
|
|
Assert.Equal(HttpStatusCode.BadRequest, (await admin.GetAsync($"{ApiRoutes.For.DeviceLogTail(device)}?source=kernel", ct)).StatusCode);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task AnOfflineOrOldAgentSaysSo()
|
|
{
|
|
var device = await fixture.SeedDeviceAsync("LOGS-OLD", online: true);
|
|
using var admin = await fixture.SignedInAsync("logs-admin");
|
|
var ct = TestContext.Current.CancellationToken;
|
|
|
|
// An agent from before live logs answers ok with nothing in it.
|
|
Assert.Equal(HttpStatusCode.NotImplemented, (await admin.GetAsync(ApiRoutes.For.DeviceLogTail(device), ct)).StatusCode);
|
|
|
|
Agent.Offline = true;
|
|
try
|
|
{
|
|
Assert.Equal(HttpStatusCode.ServiceUnavailable, (await admin.GetAsync(ApiRoutes.For.DeviceLogFiles(device), ct)).StatusCode);
|
|
}
|
|
finally
|
|
{
|
|
Agent.Offline = false;
|
|
}
|
|
}
|
|
|
|
[Fact]
|
|
public async Task TheFileListIsTheAgents()
|
|
{
|
|
var device = await fixture.SeedDeviceAsync("LOGS-LIST", online: true);
|
|
using var admin = await fixture.SignedInAsync("logs-admin");
|
|
|
|
var files = await WithAgentAsync(() => admin.GetFromJsonAsync<LogFilesDto>(ApiRoutes.For.DeviceLogFiles(device), JsonDefaults.Options, TestContext.Current.CancellationToken));
|
|
|
|
Assert.Equal("ExecuteR-Agent-20261106.log", Assert.Single(files!.Files).Name);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task ADownloadNamesOnlyALogFile_AndIsAudited()
|
|
{
|
|
var device = await fixture.SeedDeviceAsync("LOGS-DOWNLOAD", online: true);
|
|
using var admin = await fixture.SignedInAsync("logs-download-admin");
|
|
var ct = TestContext.Current.CancellationToken;
|
|
Agent.Content = "logs"u8.ToArray();
|
|
|
|
var response = await WithAgentAsync(() => admin.GetAsync(ApiRoutes.For.DeviceLogFile(device, "ExecuteR-Agent-20261106.log"), ct));
|
|
|
|
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
|
Assert.Equal("ExecuteR-Agent-20261106.log", response.Content.Headers.ContentDisposition!.FileName!.Trim('"'));
|
|
Assert.Equal(4, response.Content.Headers.ContentLength);
|
|
Assert.Equal("logs", await response.Content.ReadAsStringAsync(ct));
|
|
lock (Agent.Requests)
|
|
{
|
|
var asked = Agent.Requests.Last(r => r.Operation == DeviceFileOperations.LogRead);
|
|
Assert.Equal("ExecuteR-Agent-20261106.log", asked.Name);
|
|
Assert.Null(asked.Path);
|
|
Assert.Null(asked.Paths);
|
|
}
|
|
|
|
var audit = await fixture.WithDbAsync(db => db.AuditEvents.AsNoTracking().Where(e => e.ClientId == device).ToListAsync());
|
|
var entry = Assert.Single(audit);
|
|
Assert.Equal("files", entry.Category);
|
|
Assert.Equal("log-downloaded", entry.Action);
|
|
Assert.Equal("logs-download-admin", entry.Actor);
|
|
Assert.Contains("ExecuteR-Agent-20261106.log", entry.Detail);
|
|
}
|
|
|
|
[Theory]
|
|
[InlineData("..%5Csecret.log")]
|
|
[InlineData("..%2Fsecret.log")]
|
|
[InlineData("C%3A%5CWindows%5Cwin.log")]
|
|
[InlineData("notes.txt")]
|
|
public async Task ANameThatIsNotALogFileNeverReachesTheAgent(string name)
|
|
{
|
|
var device = await fixture.SeedDeviceAsync("LOGS-NAMES", online: true);
|
|
using var admin = await fixture.SignedInAsync("logs-admin");
|
|
int before;
|
|
lock (Agent.Requests)
|
|
{
|
|
before = Agent.Requests.Count;
|
|
}
|
|
|
|
var response = await admin.GetAsync($"/api/devices/{device}/logs/files/{name}", TestContext.Current.CancellationToken);
|
|
|
|
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
|
|
lock (Agent.Requests)
|
|
{
|
|
Assert.Equal(before, Agent.Requests.Count);
|
|
}
|
|
}
|
|
|
|
[Fact]
|
|
public async Task SystemRolesGetDeviceLogs_AndOnlyAdminsServerLogs()
|
|
{
|
|
await fixture.WithDbAsync(async db =>
|
|
{
|
|
var roles = await db.Roles.AsNoTracking().Where(r => r.IsSystem).ToListAsync();
|
|
bool Has(string role, string permission)
|
|
=> JsonDefaults.Deserialize<string[]>(roles.Single(r => r.Name == role).PermissionsJson ?? "[]")!.Contains(permission);
|
|
|
|
Assert.True(Has("Operator", Permissions.DevicesLogs));
|
|
Assert.True(Has("Help Desk", Permissions.DevicesLogs));
|
|
Assert.False(Has("Viewer", Permissions.DevicesLogs));
|
|
Assert.All(roles.Where(r => r.Name != "Admin"), r => Assert.False(Has(r.Name, Permissions.LogsView)));
|
|
});
|
|
}
|
|
}
|
|
|
|
/// <summary>A server whose rolling log files go to a folder of the test's own.</summary>
|
|
public sealed class ServerLogFixture : IDisposable
|
|
{
|
|
public ServerLogFixture()
|
|
{
|
|
Server.Settings["LOG_DIRECTORY"] = Folder;
|
|
}
|
|
|
|
public string Folder { get; } = Directory.CreateTempSubdirectory("server-logs-").FullName;
|
|
|
|
public BackendTestFixture Server { get; } = new();
|
|
|
|
public void Dispose()
|
|
{
|
|
Server.Dispose();
|
|
try
|
|
{
|
|
Directory.Delete(Folder, recursive: true);
|
|
}
|
|
catch (IOException)
|
|
{
|
|
// Best effort.
|
|
}
|
|
}
|
|
}
|
|
|
|
/// <summary>The server's own logs: live, listed and downloaded, by administrators only.</summary>
|
|
public class ServerLogEndpointTests(ServerLogFixture logs) : IClassFixture<ServerLogFixture>
|
|
{
|
|
private BackendTestFixture Server => logs.Server;
|
|
|
|
[Fact]
|
|
public async Task OnlyAdministratorsSeeServerLogs()
|
|
{
|
|
using var operatorClient = await Server.SignedInAsync("server-logs-operator", "Operator");
|
|
using var admin = await Server.SignedInAsync("server-logs-admin");
|
|
var ct = TestContext.Current.CancellationToken;
|
|
|
|
Assert.Equal(HttpStatusCode.Forbidden, (await operatorClient.GetAsync(ApiRoutes.ServerLogTail, ct)).StatusCode);
|
|
Assert.Equal(HttpStatusCode.Forbidden, (await operatorClient.GetAsync(ApiRoutes.ServerLogFiles, ct)).StatusCode);
|
|
Assert.Equal(HttpStatusCode.OK, (await admin.GetAsync(ApiRoutes.ServerLogTail, ct)).StatusCode);
|
|
Assert.Equal(HttpStatusCode.OK, (await admin.GetAsync(ApiRoutes.ServerLogFiles, ct)).StatusCode);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task TheTailIsWhatTheServerLogs_WaitingForTheNextLine_WithSecretsMasked()
|
|
{
|
|
using var admin = await Server.SignedInAsync("server-logs-admin");
|
|
var ct = TestContext.Current.CancellationToken;
|
|
var logger = Server.Services.GetRequiredService<ILoggerFactory>().CreateLogger("Backend.Tests.Logs");
|
|
|
|
var first = await admin.GetFromJsonAsync<LogTailDto>(ApiRoutes.ServerLogTail, JsonDefaults.Options, ct);
|
|
Assert.False(string.IsNullOrEmpty(first!.Instance));
|
|
|
|
// The poll is out before the line is written, and answers with it (or with whatever else the server logged meanwhile).
|
|
var stopwatch = Stopwatch.StartNew();
|
|
var waiting = admin.GetFromJsonAsync<LogTailDto>(
|
|
$"{ApiRoutes.ServerLogTail}?instance={first.Instance}&after={first.Cursor}&wait=20", JsonDefaults.Options, ct);
|
|
await Task.Delay(200, ct);
|
|
logger.LogWarning("Signing {User} in with {Password}", "someone", "hunter2");
|
|
|
|
var page = (await waiting)!;
|
|
Assert.True(stopwatch.Elapsed < TimeSpan.FromSeconds(10), $"The poll waited {stopwatch.Elapsed}.");
|
|
var lines = page.Lines.ToList();
|
|
while (!lines.Any(l => l.Source == "Backend.Tests.Logs") && stopwatch.Elapsed < TimeSpan.FromSeconds(10))
|
|
{
|
|
page = (await admin.GetFromJsonAsync<LogTailDto>(
|
|
$"{ApiRoutes.ServerLogTail}?instance={page.Instance}&after={page.Cursor}&wait=5", JsonDefaults.Options, ct))!;
|
|
lines.AddRange(page.Lines);
|
|
}
|
|
|
|
var line = Assert.Single(lines, l => l.Source == "Backend.Tests.Logs");
|
|
Assert.Equal(LogLevels.Warning, line.Level);
|
|
Assert.Contains("someone", line.Message);
|
|
Assert.DoesNotContain("hunter2", line.Message);
|
|
Assert.False(page.Reset);
|
|
Assert.All(lines, l => Assert.True(l.Seq > first.Cursor));
|
|
}
|
|
|
|
[Fact]
|
|
public async Task TheListIsTheLogFolderOnly_AndANameCannotLeaveIt()
|
|
{
|
|
using var admin = await Server.SignedInAsync("server-logs-admin");
|
|
var ct = TestContext.Current.CancellationToken;
|
|
File.WriteAllText(Path.Combine(logs.Folder, "rolled-20261101.log"), "old");
|
|
File.WriteAllText(Path.Combine(logs.Folder, "notes.txt"), "not a log");
|
|
Directory.CreateDirectory(Path.Combine(logs.Folder, "sub"));
|
|
File.WriteAllText(Path.Combine(logs.Folder, "sub", "nested.log"), "below");
|
|
var outside = Path.Combine(Path.GetDirectoryName(logs.Folder)!, $"outside-{Guid.NewGuid():N}.log");
|
|
File.WriteAllText(outside, "secret");
|
|
try
|
|
{
|
|
var files = await admin.GetFromJsonAsync<LogFilesDto>(ApiRoutes.ServerLogFiles, JsonDefaults.Options, ct);
|
|
|
|
Assert.Contains(files!.Files, f => f.Name == "rolled-20261101.log");
|
|
Assert.All(files.Files, f => Assert.EndsWith(".log", f.Name));
|
|
Assert.DoesNotContain(files.Files, f => f.Name.Contains("nested") || f.Name.Contains("outside"));
|
|
Assert.Equal([Path.GetFullPath(logs.Folder)], files.Directories);
|
|
|
|
foreach (var name in new[]
|
|
{
|
|
$"..%2F{Path.GetFileName(outside)}", $"..%5C{Path.GetFileName(outside)}", "sub%2Fnested.log", "sub%5Cnested.log", "notes.txt",
|
|
Uri.EscapeDataString(outside),
|
|
})
|
|
{
|
|
var response = await admin.GetAsync($"/api/logs/server/files/{name}", ct);
|
|
Assert.True(response.StatusCode == HttpStatusCode.NotFound, $"{name}: {response.StatusCode}");
|
|
}
|
|
|
|
var rolled = await admin.GetAsync(ApiRoutes.For.ServerLogFile("rolled-20261101.log"), ct);
|
|
Assert.Equal("old", await rolled.Content.ReadAsStringAsync(ct));
|
|
}
|
|
finally
|
|
{
|
|
File.Delete(outside);
|
|
}
|
|
}
|
|
|
|
[Fact]
|
|
public async Task AFileStillBeingWrittenDownloadsAsItWas_AndTheDownloadIsAudited()
|
|
{
|
|
using var admin = await Server.SignedInAsync("server-logs-download-admin");
|
|
var ct = TestContext.Current.CancellationToken;
|
|
|
|
// The server's own rolling file, open in Serilog's shared mode right now.
|
|
var files = await admin.GetFromJsonAsync<LogFilesDto>(ApiRoutes.ServerLogFiles, JsonDefaults.Options, ct);
|
|
var current = files!.Files.First(f => f.Name is not ("rolled-20261101.log" or "busy.log"));
|
|
var own = await admin.GetAsync(ApiRoutes.For.ServerLogFile(current.Name), ct);
|
|
Assert.Equal(HttpStatusCode.OK, own.StatusCode);
|
|
Assert.True((await own.Content.ReadAsByteArrayAsync(ct)).Length > 0);
|
|
Assert.StartsWith("text/plain", own.Content.Headers.ContentType!.ToString());
|
|
|
|
// A writer that keeps appending while the download runs: the download is what was there when it began.
|
|
var path = Path.Combine(logs.Folder, "busy.log");
|
|
await using (var writer = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.ReadWrite | FileShare.Delete))
|
|
{
|
|
await writer.WriteAsync(Encoding.UTF8.GetBytes(new string('a', 300_000)), ct);
|
|
await writer.FlushAsync(ct);
|
|
|
|
var response = await admin.GetAsync(ApiRoutes.For.ServerLogFile("busy.log"), HttpCompletionOption.ResponseHeadersRead, ct);
|
|
await writer.WriteAsync("appended"u8.ToArray(), ct);
|
|
await writer.FlushAsync(ct);
|
|
|
|
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
|
Assert.Equal(300_000, response.Content.Headers.ContentLength);
|
|
var body = await response.Content.ReadAsStringAsync(ct);
|
|
Assert.Equal(300_000, body.Length);
|
|
Assert.DoesNotContain("appended", body);
|
|
}
|
|
|
|
var audit = await Server.WithDbAsync(db => db.AuditEvents.AsNoTracking()
|
|
.Where(e => e.Actor == "server-logs-download-admin" && e.Action == "server-log-downloaded")
|
|
.ToListAsync());
|
|
Assert.Contains(audit, a => a.Detail!.StartsWith("busy.log", StringComparison.Ordinal));
|
|
Assert.All(audit, a => Assert.Equal("files", a.Category));
|
|
}
|
|
|
|
[Fact]
|
|
public void TheLiveRingIsTheServersOwn()
|
|
{
|
|
var server = Server.Services.GetRequiredService<ServerLogs>();
|
|
Assert.Equal(LiveLogLimits.Capacity, server.Live.Capacity);
|
|
Assert.Equal([logs.Folder], server.Directories);
|
|
}
|
|
}
|