bb707b9b33
The runner runs the suite as SYSTEM: a pipe it owns is trusted by design, and its temp path's case varies. A presigned link signed a moment after its expiry was set reads one second shorter. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
513 lines
28 KiB
C#
513 lines
28 KiB
C#
using System.Net;
|
|
using System.Net.Http.Json;
|
|
using System.Security.Cryptography;
|
|
using Backend.Files;
|
|
using Backend.Messaging;
|
|
using Microsoft.EntityFrameworkCore;
|
|
using Microsoft.Extensions.Configuration;
|
|
using Microsoft.Extensions.DependencyInjection;
|
|
using Shared.Contracts.Api;
|
|
using Shared.Contracts.Messages;
|
|
using Shared.Infrastructure.Nats;
|
|
using Xunit;
|
|
using K = Backend.Files.S3SettingsService.Keys;
|
|
|
|
namespace Backend.Tests;
|
|
|
|
public sealed class DeviceUploadKeyTests
|
|
{
|
|
[Theory]
|
|
[InlineData("WS-0142", "ws-0142")]
|
|
[InlineData("My Host_01.corp.example", "my-host_01.corp.example")]
|
|
[InlineData(" ..Évry/Paris?? ", "vry-paris")]
|
|
[InlineData("MINWINPC-ABC123", "minwinpc-abc123")]
|
|
[InlineData("...", "client-1")]
|
|
[InlineData(null, "client-1")]
|
|
public void Hostnames_become_one_clean_segment(string? hostname, string expected)
|
|
=> Assert.Equal(expected, DeviceUploadKeys.Host(hostname, "Client-1"));
|
|
|
|
[Fact]
|
|
public void A_long_hostname_is_cut_to_63()
|
|
=> Assert.Equal(63, DeviceUploadKeys.Host(new string('a', 100), "c").Length);
|
|
|
|
[Theory]
|
|
[InlineData("a.log", "a.log")]
|
|
[InlineData("logs/app/a.log", "logs/app/a.log")]
|
|
[InlineData(@"logs\app\a.log", "logs/app/a.log")]
|
|
[InlineData("/rooted/a.log", "rooted/a.log")]
|
|
[InlineData("//double//slash/a.log", "double/slash/a.log")]
|
|
[InlineData("../a.log", null)]
|
|
[InlineData("logs/../../a.log", null)]
|
|
[InlineData("./a.log", null)]
|
|
[InlineData("C:/Windows/a.log", null)]
|
|
[InlineData("a\nb.log", null)]
|
|
[InlineData("a\u0000b.log", null)]
|
|
[InlineData(" ", null)]
|
|
[InlineData("logs/ /a.log", null)]
|
|
public void Relative_paths_are_cleaned_or_refused(string path, string? expected)
|
|
=> Assert.Equal(expected, DeviceUploadKeys.RelativePath(path));
|
|
|
|
[Fact]
|
|
public void Keys_stay_in_their_folder()
|
|
{
|
|
const string folder = "uploads/devices/ws-1/20261106-120000/";
|
|
Assert.Equal(folder + "a/b.log", DeviceUploadKeys.KeyOf(folder, @"a\b.log"));
|
|
Assert.Null(DeviceUploadKeys.KeyOf(folder, "../../ws-2/x"));
|
|
Assert.Null(DeviceUploadKeys.KeyOf(folder, new string('x', S3Keys.MaxLength)));
|
|
|
|
Assert.True(DeviceUploadKeys.IsIn(folder, folder + "a/b.log"));
|
|
Assert.False(DeviceUploadKeys.IsIn(folder, "uploads/devices/ws-2/20261106-120000/a.log"));
|
|
Assert.False(DeviceUploadKeys.IsIn(folder, folder + "../x"));
|
|
Assert.False(DeviceUploadKeys.IsIn(folder, folder + "a//b"));
|
|
Assert.False(DeviceUploadKeys.IsIn(folder, folder));
|
|
Assert.False(DeviceUploadKeys.IsIn("tools/", "tools/a"));
|
|
Assert.False(DeviceUploadKeys.IsIn(folder, null));
|
|
}
|
|
|
|
[Fact]
|
|
public void Large_files_go_in_parts_within_S3s_limits()
|
|
{
|
|
const long mb = 1024 * 1024;
|
|
var tuning = DeviceUploadTuning.Default;
|
|
Assert.Equal((0L, 0), tuning.Parts(64 * mb));
|
|
Assert.Equal((16 * mb, 5), tuning.Parts(65 * mb));
|
|
Assert.Equal((16 * mb, 320), tuning.Parts(5L * 1024 * mb));
|
|
|
|
// A file so large that 16 MB parts would be more than 10,000 grows its parts instead.
|
|
var (size, count) = tuning.Parts(DeviceUploadLimits.MaxObjectBytes);
|
|
Assert.True(count <= DeviceUploadTuning.S3MaxParts);
|
|
Assert.Equal(0, size % mb);
|
|
|
|
var low = DeviceUploadTuning.FromConfiguration(new ConfigurationBuilder().AddInMemoryCollection(
|
|
new Dictionary<string, string?> { ["DEVICE_UPLOAD_MULTIPART_BYTES"] = "1", ["DEVICE_UPLOAD_PART_BYTES"] = "1" }).Build());
|
|
Assert.Equal(DeviceUploadTuning.S3MinPartSize, low.MinPartSize);
|
|
Assert.Equal(DeviceUploadTuning.S3MinPartSize, low.MultipartThreshold);
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// The server's side of device uploads against an external store that is never reached: presigning is local, and
|
|
/// with overwrite on nothing asks the store whether a key is there.
|
|
/// </summary>
|
|
public sealed class DeviceUploadServiceTests : IClassFixture<BackendTestFixture>
|
|
{
|
|
private const string Bucket = "uploads-bucket";
|
|
private readonly BackendTestFixture fixture;
|
|
|
|
public DeviceUploadServiceTests(BackendTestFixture fixture)
|
|
{
|
|
this.fixture = fixture;
|
|
SetAsync(
|
|
(K.Mode, S3Modes.External), (K.Enabled, "1"), (K.Endpoint, "http://127.0.0.1:9"), (K.Region, "us-east-1"), (K.Bucket, Bucket),
|
|
(K.AccessKey, "AKIAEXAMPLE"), (K.SecretKey, "secret-example"), (K.ForcePathStyle, "1"),
|
|
(K.DeviceUploadsEnabled, "1"), (K.DeviceUploadsMaxFiles, "1000"), (K.DeviceUploadsMaxFileBytes, "5368709120"),
|
|
(K.DeviceUploadsMaxRequestBytes, "21474836480")).GetAwaiter().GetResult();
|
|
}
|
|
|
|
private async Task SetAsync(params (string Key, string? Value)[] values)
|
|
{
|
|
using var scope = fixture.Services.CreateScope();
|
|
var settings = scope.ServiceProvider.GetRequiredService<S3SettingsService>();
|
|
foreach (var (key, value) in values)
|
|
{
|
|
await settings.SetAsync(key, value, key == K.SecretKey, "test", CancellationToken.None);
|
|
}
|
|
}
|
|
|
|
private Task<DeviceUploadReplyPayload> AskAsync(string subjectClientId, DeviceUploadRequestPayload request)
|
|
=> DeviceEventHandler.AnswerUploadRequestAsync(
|
|
fixture.Services.GetRequiredService<IServiceScopeFactory>(), NatsSubjects.AgentEvent(subjectClientId), request, CancellationToken.None);
|
|
|
|
private static DeviceUploadRequestPayload Begin(string clientId, string? folder, params (string Name, long Size)[] files)
|
|
=> new(clientId, DeviceUploadActions.Begin, Guid.NewGuid(), [.. files.Select(f => new DeviceUploadFile(f.Name, f.Size))], folder, Overwrite: true,
|
|
LocalUser: @"CORP\admin", Source: DeviceUploadSources.Cli);
|
|
|
|
[Fact]
|
|
public async Task Keys_are_the_devices_own_and_presigned_for_exactly_that_key()
|
|
{
|
|
var clientId = await fixture.SeedDeviceAsync("Lab PC 07");
|
|
var begin = Begin(clientId, "case-42", ("logs/app.log", 10), (@"logs\sub\b.log", 20), ("../escape.log", 1), ("logs/app.log", 3));
|
|
var reply = await AskAsync(clientId, begin);
|
|
|
|
Assert.Equal(DeviceUploadStatuses.Ok, reply.Status);
|
|
Assert.Equal("uploads/devices/lab-pc-07/case-42/", reply.Folder);
|
|
Assert.NotNull(reply.Grant);
|
|
Assert.Equal(
|
|
[DeviceUploadStatuses.Ok, DeviceUploadStatuses.Ok, DeviceUploadStatuses.Invalid, DeviceUploadStatuses.Invalid],
|
|
reply.Targets!.Select(t => t.Status));
|
|
Assert.Equal(["logs/app.log", "logs/sub/b.log"], reply.Targets!.Take(2).Select(t => t.Name));
|
|
Assert.Equal("Named twice.", reply.Targets![3].Message);
|
|
|
|
var presign = await AskAsync(clientId, begin with
|
|
{
|
|
Action = DeviceUploadActions.Presign, Grant = reply.Grant, Key = reply.Folder + "logs/app.log", Size = 10, Files = null,
|
|
});
|
|
Assert.Equal(DeviceUploadStatuses.Ok, presign.Status);
|
|
var url = new Uri(presign.Url!);
|
|
Assert.Equal($"/{Bucket}/uploads/devices/lab-pc-07/case-42/logs/app.log", url.AbsolutePath);
|
|
Assert.Equal("127.0.0.1", url.Host);
|
|
Assert.Contains("X-Amz-Signature=", url.Query);
|
|
Assert.InRange(int.Parse(System.Web.HttpUtility.ParseQueryString(url.Query)["X-Amz-Expires"]!), 899, 900); // a second can pass while signing
|
|
Assert.DoesNotContain("uploadId", url.Query);
|
|
|
|
// The audit names the device, who asked, the folder and every key with its size.
|
|
var audit = await fixture.WithDbAsync(db => db.AuditEvents.Where(e => e.Action == "device-upload" && e.ClientId == clientId).SingleAsync());
|
|
Assert.Equal("device:Lab PC 07", audit.Actor);
|
|
Assert.Contains($"upload={begin.UploadId:D}", audit.Detail);
|
|
Assert.Contains(@"user=CORP\admin", audit.Detail);
|
|
Assert.Contains("folder=uploads/devices/lab-pc-07/case-42/ files=2/4 bytes=34", audit.Detail);
|
|
Assert.Contains("logs/app.log(10)", audit.Detail);
|
|
Assert.Contains("../escape.log(1 invalid)", audit.Detail);
|
|
Assert.DoesNotContain("X-Amz", audit.Detail);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task Without_a_folder_the_server_names_one_by_the_time()
|
|
{
|
|
var clientId = await fixture.SeedDeviceAsync("TIME-1");
|
|
var reply = await AskAsync(clientId, Begin(clientId, null, ("a.log", 1)));
|
|
Assert.Matches(@"^uploads/devices/time-1/\d{8}-\d{6}/$", reply.Folder);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task A_device_can_write_nowhere_but_its_own_folder()
|
|
{
|
|
var mine = await fixture.SeedDeviceAsync("MINE-1");
|
|
var other = await fixture.SeedDeviceAsync("OTHER-1");
|
|
|
|
// A payload claiming another device than the subject's is refused outright.
|
|
Assert.Equal(DeviceUploadStatuses.Invalid, (await AskAsync(mine, Begin(other, null, ("a.log", 1)))).Status);
|
|
|
|
var begin = Begin(mine, "x", ("a.log", 1));
|
|
var reply = await AskAsync(mine, begin);
|
|
var presign = begin with { Action = DeviceUploadActions.Presign, Grant = reply.Grant, Size = 1, Files = null };
|
|
|
|
// Another key, in another device's folder, or walking out of this one.
|
|
foreach (var key in new[] { "uploads/devices/other-1/x/a.log", "tools/a.log", reply.Folder + "../y/a.log", reply.Folder + "sub/../a.log", "/" + reply.Folder + "a.log" })
|
|
{
|
|
Assert.Equal(DeviceUploadStatuses.Invalid, (await AskAsync(mine, presign with { Key = key })).Status);
|
|
}
|
|
|
|
// The grant is this device's and this upload's only, and can't be made up.
|
|
Assert.Equal(DeviceUploadStatuses.Expired, (await AskAsync(other, presign with { ClientId = other, Key = reply.Folder + "a.log" })).Status);
|
|
Assert.Equal(DeviceUploadStatuses.Expired, (await AskAsync(mine, presign with { UploadId = Guid.NewGuid(), Key = reply.Folder + "a.log" })).Status);
|
|
Assert.Equal(DeviceUploadStatuses.Expired, (await AskAsync(mine, presign with { Grant = reply.Grant + "x", Key = reply.Folder + "a.log" })).Status);
|
|
Assert.Equal(DeviceUploadStatuses.Expired, (await AskAsync(mine, presign with { Grant = null, Key = reply.Folder + "a.log" })).Status);
|
|
Assert.Equal(DeviceUploadStatuses.Ok, (await AskAsync(mine, presign with { Key = reply.Folder + "a.log" })).Status);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task Limits_hold_on_the_server()
|
|
{
|
|
var clientId = await fixture.SeedDeviceAsync("LIMITS-1");
|
|
await SetAsync((K.DeviceUploadsMaxFiles, "2"), (K.DeviceUploadsMaxFileBytes, "100"), (K.DeviceUploadsMaxRequestBytes, "250"));
|
|
try
|
|
{
|
|
var tooMany = await AskAsync(clientId, Begin(clientId, null, ("a", 1), ("b", 1), ("c", 1)));
|
|
Assert.Equal(DeviceUploadStatuses.TooMany, tooMany.Status);
|
|
Assert.Contains("At most 2 files", tooMany.Message);
|
|
|
|
Assert.Equal(DeviceUploadStatuses.TooLarge, (await AskAsync(clientId, Begin(clientId, null, ("a", 100), ("b", 151)))).Status);
|
|
Assert.Equal(DeviceUploadStatuses.Invalid, (await AskAsync(clientId, Begin(clientId, null, ("a", -1)))).Status);
|
|
Assert.Equal(DeviceUploadStatuses.Invalid, (await AskAsync(clientId, Begin(clientId, null))).Status);
|
|
Assert.Equal(DeviceUploadStatuses.Invalid, (await AskAsync(clientId, Begin(clientId, "../up", ("a", 1)))).Status);
|
|
|
|
var begin = Begin(clientId, null, ("small", 100), ("big", 101));
|
|
var reply = await AskAsync(clientId, begin);
|
|
Assert.Equal([DeviceUploadStatuses.Ok, DeviceUploadStatuses.TooLarge], reply.Targets!.Select(t => t.Status));
|
|
|
|
// A size above the limit named later is refused too.
|
|
var presign = begin with { Action = DeviceUploadActions.Presign, Grant = reply.Grant, Key = reply.Folder + "small", Files = null };
|
|
Assert.Equal(DeviceUploadStatuses.TooLarge, (await AskAsync(clientId, presign with { Size = 101 })).Status);
|
|
Assert.Equal(DeviceUploadStatuses.Ok, (await AskAsync(clientId, presign with { Size = 100 })).Status);
|
|
}
|
|
finally
|
|
{
|
|
await SetAsync((K.DeviceUploadsMaxFiles, "1000"), (K.DeviceUploadsMaxFileBytes, "5368709120"), (K.DeviceUploadsMaxRequestBytes, "21474836480"));
|
|
}
|
|
}
|
|
|
|
[Fact]
|
|
public async Task Turned_off_nothing_is_signed()
|
|
{
|
|
var clientId = await fixture.SeedDeviceAsync("OFF-1");
|
|
var begin = Begin(clientId, null, ("a.log", 1));
|
|
var reply = await AskAsync(clientId, begin);
|
|
await SetAsync((K.DeviceUploadsEnabled, "0"));
|
|
try
|
|
{
|
|
var refused = await AskAsync(clientId, Begin(clientId, null, ("a.log", 1)));
|
|
Assert.Equal(DeviceUploadStatuses.Disabled, refused.Status);
|
|
Assert.Equal("Device uploads are turned off on the server.", refused.Message);
|
|
|
|
// An upload already under way stops getting links.
|
|
Assert.Equal(DeviceUploadStatuses.Disabled, (await AskAsync(clientId, begin with
|
|
{
|
|
Action = DeviceUploadActions.Presign, Grant = reply.Grant, Key = reply.Folder + "a.log", Size = 1, Files = null,
|
|
})).Status);
|
|
}
|
|
finally
|
|
{
|
|
await SetAsync((K.DeviceUploadsEnabled, "1"));
|
|
}
|
|
}
|
|
|
|
[Fact]
|
|
public async Task No_store_is_a_clear_refusal()
|
|
{
|
|
var clientId = await fixture.SeedDeviceAsync("NOSTORE-1");
|
|
await SetAsync((K.Enabled, "0"));
|
|
try
|
|
{
|
|
var reply = await AskAsync(clientId, Begin(clientId, null, ("a.log", 1)));
|
|
Assert.Equal(DeviceUploadStatuses.NotConfigured, reply.Status);
|
|
Assert.Equal("No S3 store to upload to: S3 is turned off.", reply.Message);
|
|
}
|
|
finally
|
|
{
|
|
await SetAsync((K.Enabled, "1"));
|
|
}
|
|
}
|
|
|
|
[Fact]
|
|
public async Task An_unknown_device_gets_nothing()
|
|
=> Assert.Equal(DeviceUploadStatuses.Invalid, (await AskAsync("client-none", Begin("client-none", null, ("a.log", 1)))).Status);
|
|
|
|
[Fact]
|
|
public async Task Settings_and_the_uploads_folder_from_the_console()
|
|
{
|
|
var admin = await fixture.SignedInAsync("upload-admin");
|
|
var ct = TestContext.Current.CancellationToken;
|
|
var settings = await admin.GetFromJsonAsync<DeviceUploadSettingsDto>(ApiRoutes.DeviceUploadSettings, ct);
|
|
Assert.True(settings!.Enabled);
|
|
Assert.Equal(1000, settings.MaxFiles);
|
|
|
|
Assert.Equal(HttpStatusCode.BadRequest, (await admin.PutAsJsonAsync(ApiRoutes.DeviceUploadSettings, settings with { MaxFiles = 0 }, ct)).StatusCode);
|
|
Assert.Equal(HttpStatusCode.BadRequest, (await admin.PutAsJsonAsync(ApiRoutes.DeviceUploadSettings, settings with { MaxFiles = 5001 }, ct)).StatusCode);
|
|
var saved = await (await admin.PutAsJsonAsync(ApiRoutes.DeviceUploadSettings, settings with { MaxFiles = 50 }, ct)).Content.ReadFromJsonAsync<DeviceUploadSettingsDto>(ct);
|
|
Assert.Equal(50, saved!.MaxFiles);
|
|
await admin.PutAsJsonAsync(ApiRoutes.DeviceUploadSettings, settings, ct);
|
|
|
|
var clientId = await fixture.SeedDeviceAsync("Folder Host");
|
|
var folder = await admin.GetFromJsonAsync<DeviceUploadsFolderDto>(ApiRoutes.DeviceUploadsFolder.Replace("{clientId}", clientId), ct);
|
|
Assert.Equal("uploads/devices/folder-host/", folder!.Prefix);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task The_console_asks_the_agent_and_audits_where_it_went()
|
|
{
|
|
var admin = await fixture.SignedInAsync("upload-console");
|
|
var ct = TestContext.Current.CancellationToken;
|
|
var clientId = await fixture.SeedDeviceAsync("CONSOLE-1", online: true);
|
|
fixture.DeviceFiles.Answer = request => request.Operation == DeviceFileOperations.S3Upload && request.Paths is [@"C:\Logs"]
|
|
? new DeviceFileReply(DeviceFileStatuses.Ok, Path: "uploads/devices/console-1/20261106-120000/", Total: 3, Length: 1234)
|
|
: new DeviceFileReply(DeviceFileStatuses.Invalid, "unexpected");
|
|
|
|
var response = await admin.PostAsJsonAsync(
|
|
ApiRoutes.DeviceFsUploadToS3.Replace("{clientId}", clientId), new DeviceUploadToS3Request([@"C:\Logs"]), ct);
|
|
var started = await response.Content.ReadFromJsonAsync<DeviceUploadStartedDto>(ct);
|
|
Assert.Equal(new DeviceUploadStartedDto("uploads/devices/console-1/20261106-120000/", 3, 1234, null), started);
|
|
var audit = await fixture.WithDbAsync(db => db.AuditEvents.Where(e => e.Action == "upload-to-s3" && e.ClientId == clientId).SingleAsync());
|
|
Assert.Equal("upload-console", audit.Actor);
|
|
Assert.Equal(@"C:\Logs to uploads/devices/console-1/20261106-120000/", audit.Detail);
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Device uploads end to end against the real built-in store: through the server's gateway (the built-in store), and
|
|
/// straight to the store from a second server that has it as its external store. Needs the store program
|
|
/// (scripts/Get-ObjectStore.ps1); skipped otherwise.
|
|
/// </summary>
|
|
public sealed class DeviceUploadStoreTests : IClassFixture<EmbeddedS3StoreTests.Fixture>
|
|
{
|
|
private const long Mb = 1024 * 1024;
|
|
private readonly EmbeddedS3StoreTests.Fixture store;
|
|
|
|
public DeviceUploadStoreTests(EmbeddedS3StoreTests.Fixture store) => this.store = store;
|
|
|
|
private async Task<(BackendTestFixture Server, HttpClient Admin)> StartEmbeddedAsync()
|
|
{
|
|
if (store.Program is null)
|
|
{
|
|
Assert.Skip("No store program under artifacts/object-store; run scripts/Get-ObjectStore.ps1.");
|
|
}
|
|
|
|
var server = new BackendTestFixture();
|
|
server.Settings["S3_EMBEDDED"] = "1";
|
|
server.Settings["S3_EMBEDDED_PROGRAM"] = store.Program;
|
|
server.Settings["S3_EMBEDDED_DATA"] = Path.Combine(store.Folder, Guid.NewGuid().ToString("N"));
|
|
server.Settings["PUBLIC_SERVER_URL"] = string.Empty;
|
|
server.Settings["DEVICE_UPLOAD_MULTIPART_BYTES"] = (6 * Mb).ToString();
|
|
server.Settings["DEVICE_UPLOAD_PART_BYTES"] = (5 * Mb).ToString();
|
|
var admin = await server.SignedInAsync("s3-admin");
|
|
var deadline = DateTime.UtcNow.AddSeconds(90);
|
|
while (true)
|
|
{
|
|
var settings = await admin.GetFromJsonAsync<S3SettingsDto>(ApiRoutes.S3Settings, TestContext.Current.CancellationToken);
|
|
if (settings!.Embedded?.State == S3EmbeddedStates.Running)
|
|
{
|
|
return (server, admin);
|
|
}
|
|
|
|
Assert.True(DateTime.UtcNow < deadline, $"The store did not start: {settings.Embedded?.LastError}");
|
|
await Task.Delay(250, TestContext.Current.CancellationToken);
|
|
}
|
|
}
|
|
|
|
/// <summary>Does what the agent does: begin, presign, PUT (whole or in parts), complete, finish.</summary>
|
|
private static async Task<(DeviceUploadReplyPayload Begin, List<string> Outcomes)> UploadAsync(
|
|
BackendTestFixture server, HttpClient http, string clientId, string? folder, bool overwrite, params (string Name, byte[] Content, int Extra)[] files)
|
|
{
|
|
var scopes = server.Services.GetRequiredService<IServiceScopeFactory>();
|
|
var subject = NatsSubjects.AgentEvent(clientId);
|
|
Task<DeviceUploadReplyPayload> Ask(DeviceUploadRequestPayload request)
|
|
=> DeviceEventHandler.AnswerUploadRequestAsync(scopes, subject, request, CancellationToken.None);
|
|
|
|
var uploadId = Guid.NewGuid();
|
|
var begin = await Ask(new DeviceUploadRequestPayload(
|
|
clientId, DeviceUploadActions.Begin, uploadId, [.. files.Select(f => new DeviceUploadFile(f.Name, f.Content.Length))], folder, overwrite));
|
|
Assert.Equal(DeviceUploadStatuses.Ok, begin.Status);
|
|
var outcomes = new List<string>();
|
|
for (var i = 0; i < files.Length; i++)
|
|
{
|
|
var target = begin.Targets![i];
|
|
if (target.Status != DeviceUploadStatuses.Ok)
|
|
{
|
|
outcomes.Add(target.Status);
|
|
continue;
|
|
}
|
|
|
|
var (_, content, extra) = files[i];
|
|
var step = new DeviceUploadRequestPayload(
|
|
clientId, DeviceUploadActions.Presign, uploadId, Grant: begin.Grant, Key: begin.Folder + target.Name, Size: content.Length);
|
|
var parts = new List<DeviceUploadPart>();
|
|
string? multipartId = null;
|
|
if (target.PartSize == 0)
|
|
{
|
|
var presigned = await Ask(step);
|
|
var sent = extra > 0 ? [.. content, .. new byte[extra]] : content;
|
|
(await http.PutAsync(presigned.Url, new ByteArrayContent(sent))).EnsureSuccessStatusCode();
|
|
}
|
|
else
|
|
{
|
|
var presigned = await Ask(step with { FirstPart = 1, PartCount = target.PartCount });
|
|
multipartId = presigned.MultipartId;
|
|
Assert.Equal(target.PartCount, presigned.PartUrls!.Count);
|
|
foreach (var part in presigned.PartUrls)
|
|
{
|
|
Assert.Contains("uploadId=", part.Url);
|
|
var offset = (int)((part.Number - 1) * target.PartSize);
|
|
var length = (int)Math.Min(target.PartSize, content.Length - offset);
|
|
var response = await http.PutAsync(part.Url, new ByteArrayContent(content, offset, length));
|
|
response.EnsureSuccessStatusCode();
|
|
parts.Add(new DeviceUploadPart(part.Number, response.Headers.ETag!.Tag));
|
|
}
|
|
}
|
|
|
|
var complete = await Ask(step with { Action = DeviceUploadActions.Complete, MultipartId = multipartId, Parts = parts.Count > 0 ? parts : null });
|
|
outcomes.Add(complete.Status == DeviceUploadStatuses.Ok ? "uploaded" : complete.Message!);
|
|
}
|
|
|
|
Assert.Equal(DeviceUploadStatuses.Ok, (await Ask(new DeviceUploadRequestPayload(
|
|
clientId, DeviceUploadActions.Finish, uploadId, Grant: begin.Grant,
|
|
Summary: new DeviceUploadSummary(outcomes.Count(o => o == "uploaded"), 0, 0, 0)))).Status);
|
|
return (begin, outcomes);
|
|
}
|
|
|
|
private static async Task<byte[]> DownloadAsync(HttpClient admin, HttpClient http, string key)
|
|
{
|
|
var link = (await admin.GetFromJsonAsync<S3LinkDto>($"{ApiRoutes.S3ObjectLink}?key={Uri.EscapeDataString(key)}", TestContext.Current.CancellationToken))!.Url;
|
|
return await http.GetByteArrayAsync(link);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task Through_the_built_in_stores_gateway_whole_and_in_parts()
|
|
{
|
|
var (server, admin) = await StartEmbeddedAsync();
|
|
await using var host = server;
|
|
var device = server.CreateClient();
|
|
var clientId = await server.SeedDeviceAsync("Gateway Host");
|
|
var small = RandomNumberGenerator.GetBytes(1000);
|
|
var large = RandomNumberGenerator.GetBytes((int)(12 * Mb + 123));
|
|
|
|
var (begin, outcomes) = await UploadAsync(server, device, clientId, "case-1", false, ("logs/small.log", small, 0), ("big.bin", large, 0));
|
|
Assert.Equal(["uploaded", "uploaded"], outcomes);
|
|
Assert.Equal("uploads/devices/gateway-host/case-1/", begin.Folder);
|
|
Assert.Equal((5 * Mb, 3), (begin.Targets![1].PartSize, begin.Targets[1].PartCount));
|
|
Assert.Equal(small, await DownloadAsync(admin, device, begin.Folder + "logs/small.log"));
|
|
Assert.Equal(large, await DownloadAsync(admin, device, begin.Folder + "big.bin"));
|
|
|
|
// The S3 page lists the device's folder.
|
|
var listing = await admin.GetFromJsonAsync<S3BrowseDto>($"{ApiRoutes.S3Objects}?prefix=uploads/devices/gateway-host/case-1/", TestContext.Current.CancellationToken);
|
|
Assert.Contains(listing!.Objects, o => o.Key == begin.Folder + "big.bin" && o.SizeBytes == large.Length);
|
|
Assert.Contains(listing.Folders, f => f.Prefix == begin.Folder + "logs/");
|
|
|
|
// Again without overwrite: what is there is skipped; with it, replaced.
|
|
var (_, again) = await UploadAsync(server, device, clientId, "case-1", false, ("logs/small.log", small, 0));
|
|
Assert.Equal([DeviceUploadStatuses.Exists], again);
|
|
var replacement = RandomNumberGenerator.GetBytes(10);
|
|
var (_, replaced) = await UploadAsync(server, device, clientId, "case-1", true, ("logs/small.log", replacement, 0));
|
|
Assert.Equal(["uploaded"], replaced);
|
|
Assert.Equal(replacement, await DownloadAsync(admin, device, begin.Folder + "logs/small.log"));
|
|
|
|
// More bytes than declared: refused at complete and removed.
|
|
var (lying, lied) = await UploadAsync(server, device, clientId, "case-2", false, ("short.log", small, 5));
|
|
Assert.StartsWith("Arrived with 1005 bytes", lied.Single());
|
|
var gone = await admin.GetFromJsonAsync<S3BrowseDto>($"{ApiRoutes.S3Objects}?prefix={lying.Folder}", TestContext.Current.CancellationToken);
|
|
Assert.Empty(gone!.Objects);
|
|
|
|
// The gateway takes a signed PUT for one object or one part, and nothing else.
|
|
var store = $"{ApiRoutes.S3Store}/{EmbeddedS3Store.Bucket}";
|
|
var getLink = (await admin.GetFromJsonAsync<S3LinkDto>($"{ApiRoutes.S3ObjectLink}?key={Uri.EscapeDataString(begin.Folder + "big.bin")}", TestContext.Current.CancellationToken))!.Url;
|
|
Assert.Equal(HttpStatusCode.Forbidden, (await device.PutAsync(getLink, new ByteArrayContent(small))).StatusCode);
|
|
Assert.Equal(HttpStatusCode.Forbidden, (await device.PutAsync($"{store}/x/y.bin", new ByteArrayContent(small))).StatusCode);
|
|
Assert.Equal(HttpStatusCode.NotFound, (await device.PutAsync($"{store}/x/y.bin?X-Amz-Signature=a&uploads=", new ByteArrayContent(small))).StatusCode);
|
|
Assert.Equal(HttpStatusCode.NotFound, (await device.PutAsync($"{store}/x/y.bin?X-Amz-Signature=a&partNumber=1", new ByteArrayContent(small))).StatusCode);
|
|
|
|
var audits = await server.WithDbAsync(db => db.AuditEvents.Where(e => e.ClientId == clientId).Select(e => e.Action).ToListAsync());
|
|
Assert.Equal(4, audits.Count(a => a == "device-upload"));
|
|
Assert.Equal(4, audits.Count(a => a == "device-upload-finished"));
|
|
}
|
|
|
|
[Fact]
|
|
public async Task Straight_to_an_external_store()
|
|
{
|
|
// The first server runs the store; the second has it as its external store, so links lead straight to it.
|
|
var (storeServer, storeAdmin) = await StartEmbeddedAsync();
|
|
await using var storeHost = storeServer;
|
|
var keys = (await storeAdmin.GetFromJsonAsync<S3EmbeddedCredentialsDto>(ApiRoutes.S3EmbeddedCredentials, TestContext.Current.CancellationToken))!;
|
|
|
|
await using var server = new BackendTestFixture();
|
|
server.Settings["DEVICE_UPLOAD_MULTIPART_BYTES"] = (6 * Mb).ToString();
|
|
server.Settings["DEVICE_UPLOAD_PART_BYTES"] = (5 * Mb).ToString();
|
|
using (var scope = server.Services.CreateScope())
|
|
{
|
|
var settings = scope.ServiceProvider.GetRequiredService<S3SettingsService>();
|
|
foreach (var (key, value) in new[]
|
|
{
|
|
(K.Mode, S3Modes.External), (K.Enabled, "1"), (K.Endpoint, keys.Endpoint), (K.Region, keys.Region), (K.Bucket, keys.Bucket),
|
|
(K.AccessKey, keys.AccessKey), (K.SecretKey, keys.SecretKey), (K.ForcePathStyle, "1"),
|
|
})
|
|
{
|
|
await settings.SetAsync(key, value, key == K.SecretKey, "test", CancellationToken.None);
|
|
}
|
|
}
|
|
|
|
var clientId = await server.SeedDeviceAsync("EXT-HOST");
|
|
using var direct = new HttpClient();
|
|
var content = RandomNumberGenerator.GetBytes((int)(11 * Mb));
|
|
var (begin, outcomes) = await UploadAsync(server, direct, clientId, null, false, ("dump.bin", content, 0), ("note.txt", "hello"u8.ToArray(), 0));
|
|
Assert.Equal(["uploaded", "uploaded"], outcomes);
|
|
|
|
using var s3 = S3ClientFactory.Create(new S3Options
|
|
{
|
|
Enabled = true, Endpoint = keys.Endpoint, Bucket = keys.Bucket, AccessKey = keys.AccessKey, SecretKey = keys.SecretKey,
|
|
});
|
|
using var got = await s3.GetObjectAsync(keys.Bucket, begin.Folder + "dump.bin", TestContext.Current.CancellationToken);
|
|
using var buffer = new MemoryStream();
|
|
await got.ResponseStream.CopyToAsync(buffer, TestContext.Current.CancellationToken);
|
|
Assert.Equal(content, buffer.ToArray());
|
|
Assert.StartsWith("uploads/devices/ext-host/", begin.Folder);
|
|
}
|
|
}
|