Files
Alphaeus Mote 890bab034b
CI / build-test (push) Successful in 38m1s
CI / images (push) Has been skipped
Release / release (push) Successful in 19m58s
Release / images (push) Successful in 12m49s
fix: devices follow the real server address; static screen host
- PUBLIC_SERVER_URL and TRUSTED_HOSTS left at .env.example's sample
  (control.example.com, any RFC 2606 name) are ignored with a startup
  warning: links follow the forwarded headers and devices download from
  the server URL they already use. .env.example ships them empty and
  deploy.sh clears sample values from an existing .env.
- The screen host is built from its own folder so .cargo/config.toml's
  +crt-static applies; the shipped exe imported VCRUNTIME140.dll and died
  without output on devices without the Visual C++ runtime ("the screen
  host gave no answer"). The build now refuses an exe with CRT imports.
- A failed screen host probe is retried with backoff (30 s up to 10 min)
  and the inventory is republished once it answers; the warning and the
  reason carry the exit code.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-07 20:02:03 -05:00

546 lines
27 KiB
C#

using System.Net;
using System.Net.Http.Json;
using System.Security.Cryptography;
using Backend.Files;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Shared.Contracts.Api;
using Xunit;
namespace Backend.Tests;
public sealed class S3KeyTests
{
[Theory]
[InlineData("tools/a.zip", true)]
[InlineData("tools/", true)]
[InlineData("", false)]
[InlineData("/rooted", false)]
[InlineData("a/../../b", false)]
[InlineData("a/./b", false)]
[InlineData("a\\b", false)]
[InlineData("a\nb", false)]
public void Keys_that_would_walk_out_of_a_folder_are_refused(string key, bool valid)
=> Assert.Equal(valid, S3Keys.IsValid(key));
}
/// <summary>
/// The real program under the real server. Needs it fetched first: scripts/Get-ObjectStore.ps1 -Runtime win-x64
/// -Destination artifacts/object-store/win-x64 (or the runtime at hand); skipped otherwise.
/// </summary>
public sealed class EmbeddedS3StoreTests : IClassFixture<EmbeddedS3StoreTests.Fixture>
{
public sealed class Fixture : IDisposable
{
public string Folder { get; } = Directory.CreateTempSubdirectory("executer-silo-").FullName;
public string? Program { get; } = Find();
private static string? Find()
{
var runtime = (OperatingSystem.IsWindows() ? "win-" : OperatingSystem.IsMacOS() ? "osx-" : "linux-")
+ System.Runtime.InteropServices.RuntimeInformation.OSArchitecture.ToString().ToLowerInvariant();
for (var at = new DirectoryInfo(AppContext.BaseDirectory); at is not null; at = at.Parent)
{
var candidate = Path.Combine(at.FullName, "artifacts", "object-store", runtime, OperatingSystem.IsWindows() ? "silo.exe" : "silo");
if (File.Exists(candidate))
{
return candidate;
}
}
return null;
}
public void Dispose()
{
try
{
Directory.Delete(Folder, recursive: true);
}
catch (IOException)
{
// The store may hold a file for a moment after it ends.
}
}
}
private readonly Fixture fixture;
public EmbeddedS3StoreTests(Fixture fixture) => this.fixture = fixture;
private async Task<(IAsyncDisposable Server, IServiceProvider Services, HttpClient Admin, HttpClient Anonymous)> StartAsync(string? publicUrl = null)
{
if (fixture.Program is null)
{
Assert.Skip("No store program under artifacts/object-store; run scripts/Get-ObjectStore.ps1.");
}
var data = Path.Combine(fixture.Folder, Guid.NewGuid().ToString("N"));
var server = new BackendTestFixture();
server.Settings["S3_EMBEDDED"] = "1";
server.Settings["S3_EMBEDDED_PROGRAM"] = fixture.Program;
server.Settings["S3_EMBEDDED_DATA"] = data;
server.Settings["PUBLIC_SERVER_URL"] = publicUrl ?? string.Empty;
var admin = await server.SignedInAsync("s3-admin");
var anonymous = server.CreateClient();
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, server.Services, admin, anonymous);
}
Assert.True(DateTime.UtcNow < deadline, $"The store did not start: {settings.Embedded?.LastError}");
await Task.Delay(250, TestContext.Current.CancellationToken);
}
}
private static string Content(string key, bool overwrite = false)
=> $"{ApiRoutes.S3ObjectContent}?key={Uri.EscapeDataString(key)}&overwrite={overwrite}";
private static async Task<string> LinkAsync(HttpClient admin, string key)
=> (await admin.GetFromJsonAsync<S3LinkDto>($"{ApiRoutes.S3ObjectLink}?key={Uri.EscapeDataString(key)}", TestContext.Current.CancellationToken))!.Url;
[Fact]
public async Task S3_works_with_nothing_configured_from_upload_to_download()
{
var ct = TestContext.Current.CancellationToken;
var (server, services, admin, anonymous) = await StartAsync();
await using var host = server;
// It is the chosen store, and passes the same round trip an external one must.
var settings = await admin.GetFromJsonAsync<S3SettingsDto>(ApiRoutes.S3Settings, ct);
Assert.Equal(S3Modes.Embedded, settings!.Mode);
Assert.True(settings.Enabled);
Assert.Null(settings.AccessKey);
var test = await (await admin.PostAsJsonAsync(ApiRoutes.S3SettingsTest, settings, ct)).Content.ReadFromJsonAsync<S3TestResultDto>(ct);
Assert.True(test!.Ok, string.Join("; ", test.Steps.Select(s => $"{s.Name}: {s.Detail}")));
// Its generated keys come out only on request, and they are the ones it runs with.
var keys = (await admin.GetFromJsonAsync<S3EmbeddedCredentialsDto>(ApiRoutes.S3EmbeddedCredentials, ct))!;
Assert.Equal(EmbeddedS3Store.Bucket, keys.Bucket);
Assert.StartsWith("http://127.0.0.1:", keys.Endpoint);
Assert.Equal(20, keys.AccessKey.Length);
Assert.Equal(40, keys.SecretKey.Length);
using (var direct = S3ClientFactory.Create(new S3Options
{
Enabled = true, Endpoint = keys.Endpoint, Bucket = keys.Bucket, AccessKey = keys.AccessKey, SecretKey = keys.SecretKey,
}))
{
Assert.Contains((await direct.ListBucketsAsync(ct)).Buckets, b => b.BucketName == EmbeddedS3Store.Bucket);
}
using (var scope = services.CreateScope())
{
Assert.True(await scope.ServiceProvider.GetRequiredService<Backend.Data.AppDbContext>()
.AuditEvents.AnyAsync(e => e.Action == "s3-built-in-keys-revealed", ct));
}
// Small and multipart, both whole.
var small = RandomNumberGenerator.GetBytes(1024);
var large = RandomNumberGenerator.GetBytes(40 * 1024 * 1024);
Assert.Equal(HttpStatusCode.NoContent, (await admin.PutAsync(Content("tools/small.bin"), new ByteArrayContent(small), ct)).StatusCode);
Assert.Equal(HttpStatusCode.NoContent, (await admin.PutAsync(Content("tools/deep/large.bin"), new ByteArrayContent(large), ct)).StatusCode);
Assert.Equal(HttpStatusCode.Conflict, (await admin.PutAsync(Content("tools/small.bin"), new ByteArrayContent(small), ct)).StatusCode);
Assert.Equal(HttpStatusCode.NoContent, (await admin.PutAsync(Content("tools/small.bin", overwrite: true), new ByteArrayContent(small), ct)).StatusCode);
var stat = await (await admin.PostAsJsonAsync(ApiRoutes.S3ObjectStat, new S3StatRequest(["tools/small.bin", "tools/none.bin"]), ct)).Content.ReadFromJsonAsync<S3StatResult>(ct);
Assert.Equal(["tools/small.bin"], stat!.Existing);
// Browse and search find them.
var level = await admin.GetFromJsonAsync<S3BrowseDto>($"{ApiRoutes.S3Objects}?prefix=tools/", ct);
Assert.Contains(level!.Objects, o => o.Key == "tools/small.bin" && o.SizeBytes == small.Length);
Assert.Contains(level.Folders, f => f.Prefix == "tools/deep/");
var found = await admin.GetFromJsonAsync<S3BrowseDto>($"{ApiRoutes.S3Objects}?search=large", ct);
Assert.Contains(found!.Objects, o => o.Key == "tools/deep/large.bin");
// A real presigned URL: it works with no session, through the server, and never renders on its origin.
var link = await LinkAsync(admin, "tools/deep/large.bin");
Assert.StartsWith($"{ApiRoutes.S3Store}/{EmbeddedS3Store.Bucket}/tools/deep/large.bin?", link);
Assert.Contains("X-Amz-Algorithm=AWS4-HMAC-SHA256", link);
Assert.Contains("X-Amz-Signature=", link);
var response = await anonymous.GetAsync(link, ct);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal(large, await response.Content.ReadAsByteArrayAsync(ct));
Assert.Equal("application/octet-stream", response.Content.Headers.ContentType?.MediaType);
Assert.Equal("attachment", response.Content.Headers.ContentDisposition?.DispositionType);
Assert.Equal("nosniff", response.Headers.GetValues("X-Content-Type-Options").Single());
// A device's If-None-Match costs no transfer, and a range is a range.
var etag = response.Headers.ETag!.Tag;
using var conditional = new HttpRequestMessage(HttpMethod.Get, link);
conditional.Headers.TryAddWithoutValidation("If-None-Match", etag);
Assert.Equal(HttpStatusCode.NotModified, (await anonymous.SendAsync(conditional, ct)).StatusCode);
using var ranged = new HttpRequestMessage(HttpMethod.Get, link);
ranged.Headers.Range = new System.Net.Http.Headers.RangeHeaderValue(10, 19);
var part = await anonymous.SendAsync(ranged, ct);
Assert.Equal(HttpStatusCode.PartialContent, part.StatusCode);
Assert.Equal(large[10..20], await part.Content.ReadAsByteArrayAsync(ct));
// A changed link gets nothing, and nothing but one signed object gets through to the store.
var store = $"{ApiRoutes.S3Store}/{EmbeddedS3Store.Bucket}";
Assert.Equal(HttpStatusCode.Forbidden, (await anonymous.GetAsync(link.Replace("large.bin", "small.bin"), ct)).StatusCode);
Assert.Equal(HttpStatusCode.Forbidden, (await anonymous.GetAsync($"{store}/tools/small.bin", ct)).StatusCode);
Assert.Equal(HttpStatusCode.Forbidden, (await anonymous.GetAsync($"{store}/tools/small.bin?X-Amz-Signature=made-up", ct)).StatusCode);
Assert.Equal(HttpStatusCode.NotFound, (await anonymous.GetAsync($"{store}/?X-Amz-Signature=x", ct)).StatusCode);
Assert.Equal(HttpStatusCode.NotFound, (await anonymous.GetAsync($"{ApiRoutes.S3Store}/minio/health/live?X-Amz-Signature=x", ct)).StatusCode);
// A GET link does not sign a PUT: the store refuses it.
Assert.Equal(HttpStatusCode.Forbidden, (await anonymous.PutAsync(link, new ByteArrayContent(small), ct)).StatusCode);
Assert.Equal(HttpStatusCode.Unauthorized, (await anonymous.GetAsync(ApiRoutes.S3Objects, ct)).StatusCode);
// A folder goes with everything in it.
Assert.Equal(HttpStatusCode.NoContent, (await admin.PostAsJsonAsync(ApiRoutes.S3ObjectFolder, new S3FolderRequest("empty/"), ct)).StatusCode);
var top = await admin.GetFromJsonAsync<S3BrowseDto>(ApiRoutes.S3Objects, ct);
Assert.Contains(top!.Folders, f => f.Prefix == "empty/");
var deleted = await (await admin.PostAsJsonAsync(ApiRoutes.S3ObjectDelete, new S3DeleteRequest(["tools/small.bin"], ["tools/deep/", "empty/"]), ct)).Content.ReadFromJsonAsync<S3DeleteResult>(ct);
Assert.Equal(3, deleted!.Deleted);
Assert.Empty(deleted.Failures);
top = await admin.GetFromJsonAsync<S3BrowseDto>(ApiRoutes.S3Objects, ct);
Assert.Empty(top!.Folders);
Assert.Equal(HttpStatusCode.NotFound, (await anonymous.GetAsync(link, ct)).StatusCode);
}
[Fact]
public async Task A_broken_upload_stores_nothing()
{
var ct = TestContext.Current.CancellationToken;
var (server, _, admin, _) = await StartAsync();
await using var host = server;
var body = new byte[40 * 1024 * 1024];
var content = new StreamContent(new FailingStream(body, failAfter: body.Length / 2));
content.Headers.ContentLength = body.Length;
await Assert.ThrowsAnyAsync<Exception>(() => admin.PutAsync(Content("broken.bin"), content, ct));
var top = await admin.GetFromJsonAsync<S3BrowseDto>(ApiRoutes.S3Objects, ct);
Assert.DoesNotContain(top!.Objects, o => o.Key == "broken.bin");
}
[Fact]
public async Task A_device_gets_the_public_address_when_set_and_a_server_path_otherwise()
{
var ct = TestContext.Current.CancellationToken;
var (bare, bareServices, bareAdmin, _) = await StartAsync();
await using (bare)
{
await bareAdmin.PutAsync(Content("a.bin"), new ByteArrayContent([1]), ct);
using var scope = bareServices.CreateScope();
var (url, _) = await scope.ServiceProvider.GetRequiredService<S3PresignService>().PresignGetAsync("a.bin", ct);
Assert.StartsWith(ApiRoutes.S3Store, url);
}
var (pinned, pinnedServices, pinnedAdmin, _) = await StartAsync("https://control.contoso.com/");
await using (pinned)
{
await pinnedAdmin.PutAsync(Content("a.bin"), new ByteArrayContent([1]), ct);
using var scope = pinnedServices.CreateScope();
var (url, _) = await scope.ServiceProvider.GetRequiredService<S3PresignService>().PresignGetAsync("a.bin", ct);
Assert.StartsWith($"https://control.contoso.com{ApiRoutes.S3Store}", url);
// The browser stays on whatever address it is already on.
Assert.StartsWith(ApiRoutes.S3Store, await LinkAsync(pinnedAdmin, "a.bin"));
}
}
[Fact]
public async Task Choosing_an_external_store_stops_the_built_in_one()
{
var ct = TestContext.Current.CancellationToken;
var (server, _, admin, _) = await StartAsync();
await using var host = server;
var settings = await admin.GetFromJsonAsync<S3SettingsDto>(ApiRoutes.S3Settings, ct);
var saved = await (await admin.PutAsJsonAsync(ApiRoutes.S3Settings, settings! with { Mode = S3Modes.External, Enabled = false }, ct)).Content.ReadFromJsonAsync<S3SettingsDto>(ct);
Assert.Equal(S3Modes.External, saved!.Mode);
var deadline = DateTime.UtcNow.AddSeconds(30);
while ((await admin.GetFromJsonAsync<S3SettingsDto>(ApiRoutes.S3Settings, ct))!.Embedded?.State != S3EmbeddedStates.Off)
{
Assert.True(DateTime.UtcNow < deadline, "The store kept running.");
await Task.Delay(250, ct);
}
}
[Fact]
public async Task An_ended_link_gets_nothing()
{
var ct = TestContext.Current.CancellationToken;
var (server, _, admin, anonymous) = await StartAsync();
await using var host = server;
Assert.Equal(HttpStatusCode.NoContent, (await admin.PutAsync(Content("a.bin"), new ByteArrayContent([1]), ct)).StatusCode);
var settings = await admin.GetFromJsonAsync<S3SettingsDto>(ApiRoutes.S3Settings, ct);
Assert.Equal(HttpStatusCode.OK, (await admin.PutAsJsonAsync(ApiRoutes.S3Settings, settings! with { PresignExpirySeconds = 1 }, ct)).StatusCode);
var link = await LinkAsync(admin, "a.bin");
await Task.Delay(TimeSpan.FromSeconds(3), ct);
Assert.Equal(HttpStatusCode.Forbidden, (await anonymous.GetAsync(link, ct)).StatusCode);
}
/// <summary>The real program again, this time as someone else's store at its own address, as Wasabi or AWS would be.</summary>
[Fact]
public async Task An_external_stores_presigned_urls_come_from_it_and_not_from_this_server()
{
var ct = TestContext.Current.CancellationToken;
if (fixture.Program is null)
{
Assert.Skip("No store program under artifacts/object-store; run scripts/Get-ObjectStore.ps1.");
}
var listener = new System.Net.Sockets.TcpListener(IPAddress.Loopback, 0);
listener.Start();
var port = ((IPEndPoint)listener.LocalEndpoint).Port;
listener.Stop();
var endpoint = $"http://127.0.0.1:{port}";
const string access = "external-access", secret = "external-secret-key-0123456789";
var start = new System.Diagnostics.ProcessStartInfo(fixture.Program!) { UseShellExecute = false, CreateNoWindow = true, RedirectStandardOutput = true, RedirectStandardError = true };
foreach (var argument in (string[])["server", "--address", $"127.0.0.1:{port}", "--anonymous", "--json", "--certs-dir", Path.Combine(fixture.Folder, "external-certs"), Path.Combine(fixture.Folder, "external-data")])
{
start.ArgumentList.Add(argument);
}
start.Environment["MINIO_ROOT_USER"] = access;
start.Environment["MINIO_ROOT_PASSWORD"] = secret;
start.Environment["MINIO_BROWSER"] = "off";
using var store = System.Diagnostics.Process.Start(start)!;
store.OutputDataReceived += (_, _) => { };
store.ErrorDataReceived += (_, _) => { };
store.BeginOutputReadLine();
store.BeginErrorReadLine();
try
{
var options = new S3Options { Enabled = true, Endpoint = endpoint, Bucket = "elsewhere", AccessKey = access, SecretKey = secret };
using var client = S3ClientFactory.Create(options);
var deadline = DateTime.UtcNow.AddSeconds(60);
while (true)
{
try
{
await client.PutBucketAsync("elsewhere", ct);
break;
}
catch (Exception) when (DateTime.UtcNow < deadline)
{
await Task.Delay(250, ct);
}
}
using var server = new BackendTestFixture();
server.Settings["S3_EMBEDDED"] = "1";
server.Settings["S3_EMBEDDED_PROGRAM"] = Path.Combine(fixture.Folder, "no-such-store");
server.Settings["PUBLIC_SERVER_URL"] = "https://control.contoso.com";
var admin = await server.SignedInAsync("s3-admin");
var settings = await admin.GetFromJsonAsync<S3SettingsDto>(ApiRoutes.S3Settings, ct);
var saved = await admin.PutAsJsonAsync(ApiRoutes.S3Settings, settings! with
{
Mode = S3Modes.External, Enabled = true, Endpoint = endpoint, Bucket = "elsewhere", AccessKey = access, SecretKey = secret, ForcePathStyle = true,
}, ct);
Assert.Equal(HttpStatusCode.OK, saved.StatusCode);
byte[] body = [1, 2, 3, 4];
Assert.Equal(HttpStatusCode.NoContent, (await admin.PutAsync(Content("tools/a.bin"), new ByteArrayContent(body), ct)).StatusCode);
// For a device and for the browser alike, straight to the store, nothing of this server in it.
using var scope = server.Services.CreateScope();
var (deviceUrl, _) = await scope.ServiceProvider.GetRequiredService<S3PresignService>().PresignGetAsync("tools/a.bin", ct);
Assert.StartsWith($"{endpoint}/elsewhere/tools/a.bin?", deviceUrl);
Assert.Contains("X-Amz-Signature=", deviceUrl);
Assert.StartsWith(endpoint, await LinkAsync(admin, "tools/a.bin"));
using var plain = new HttpClient();
Assert.Equal(body, await plain.GetByteArrayAsync(deviceUrl, ct));
}
finally
{
store.Kill(entireProcessTree: true);
store.WaitForExit(TimeSpan.FromSeconds(10));
}
}
[Fact]
public async Task A_name_with_any_letters_comes_back_under_that_name()
{
var ct = TestContext.Current.CancellationToken;
var (server, _, admin, anonymous) = await StartAsync();
await using var host = server;
const string key = "médias/déjà vu #1+2.bin";
Assert.Equal(HttpStatusCode.NoContent, (await admin.PutAsync(Content(key), new ByteArrayContent([1, 2, 3]), ct)).StatusCode);
var response = await anonymous.GetAsync(await LinkAsync(admin, key), ct);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal("déjà vu #1+2.bin", response.Content.Headers.ContentDisposition?.FileNameStar);
Assert.Equal([1, 2, 3], await response.Content.ReadAsByteArrayAsync(ct));
}
private sealed class FailingStream(byte[] data, int failAfter) : MemoryStream(data)
{
public override async ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken = default)
{
if (Position >= failAfter)
{
throw new IOException("The connection broke.");
}
return await base.ReadAsync(buffer, cancellationToken);
}
}
}
/// <summary>Which store a server uses, with no program to run: a store that can't start must change nothing else.</summary>
public sealed class S3StoreChoiceTests
{
private static BackendTestFixture Server(string embedded = "1", string? environmentEnabled = null)
{
var server = new BackendTestFixture();
server.Settings["S3_EMBEDDED"] = embedded;
server.Settings["S3_EMBEDDED_PROGRAM"] = Path.Combine(Path.GetTempPath(), $"no-such-store-{Guid.NewGuid():N}");
if (environmentEnabled is not null)
{
server.Settings["S3_ENABLED"] = environmentEnabled;
server.Settings["S3_BUCKET"] = "from-environment";
server.Settings["S3_ACCESS_KEY"] = "a";
server.Settings["S3_SECRET_KEY"] = "s";
}
return server;
}
private static Task<S3SettingsDto?> SettingsAsync(HttpClient admin)
=> admin.GetFromJsonAsync<S3SettingsDto>(ApiRoutes.S3Settings, TestContext.Current.CancellationToken);
[Fact]
public async Task A_new_server_uses_the_built_in_store_and_says_when_it_cant_run()
{
var ct = TestContext.Current.CancellationToken;
using var server = Server();
var admin = await server.SignedInAsync("s3-admin");
var settings = await SettingsAsync(admin);
Assert.Equal(S3Modes.Embedded, settings!.Mode);
Assert.True(settings.Enabled);
Assert.True(settings.EmbeddedAllowed);
var deadline = DateTime.UtcNow.AddSeconds(30);
while ((settings = await SettingsAsync(admin))!.Embedded!.State != S3EmbeddedStates.Unavailable)
{
Assert.True(DateTime.UtcNow < deadline, $"State stayed {settings.Embedded.State}");
await Task.Delay(100, ct);
}
Assert.False(settings.Embedded.Available);
Assert.NotNull(settings.Embedded.LastError);
// The rest of the server carries on, and S3's routes say why not.
Assert.Equal(HttpStatusCode.OK, (await admin.GetAsync(ApiRoutes.Health, ct)).StatusCode);
var browse = await admin.GetAsync(ApiRoutes.S3Objects, ct);
Assert.Equal(HttpStatusCode.ServiceUnavailable, browse.StatusCode);
Assert.Contains("built-in S3 store is not running", await browse.Content.ReadAsStringAsync(ct));
}
[Fact]
public async Task A_server_set_up_for_an_external_store_keeps_it()
{
var ct = TestContext.Current.CancellationToken;
using (var byEnvironment = Server(environmentEnabled: "1"))
{
var admin = await byEnvironment.SignedInAsync("s3-admin");
var settings = await SettingsAsync(admin);
Assert.Equal(S3Modes.External, settings!.Mode);
Assert.Equal("from-environment", settings.Bucket);
}
// Saved from the console before there was a choice: no mode, but a bucket.
using var saved = Server();
var client = await saved.SignedInAsync("s3-admin");
using (var scope = saved.Services.CreateScope())
{
var settings = scope.ServiceProvider.GetRequiredService<S3SettingsService>();
await settings.SetAsync(S3SettingsService.Keys.Bucket, "saved-bucket", false, "test", ct);
await settings.SetAsync(S3SettingsService.Keys.Enabled, "1", false, "test", ct);
}
var loaded = await SettingsAsync(client);
Assert.Equal(S3Modes.External, loaded!.Mode);
Assert.Equal("saved-bucket", loaded.Bucket);
}
[Fact]
public async Task An_old_switch_left_off_with_nothing_configured_still_gets_the_built_in_store()
{
var ct = TestContext.Current.CancellationToken;
using var server = Server();
var admin = await server.SignedInAsync("s3-admin");
using (var scope = server.Services.CreateScope())
{
await scope.ServiceProvider.GetRequiredService<S3SettingsService>().SetAsync(S3SettingsService.Keys.Enabled, "0", false, "test", ct);
}
var settings = await SettingsAsync(admin);
Assert.Equal(S3Modes.Embedded, settings!.Mode);
Assert.True(settings.Enabled);
}
[Fact]
public async Task Turned_off_the_environment_way_there_is_no_built_in_choice()
{
var ct = TestContext.Current.CancellationToken;
using var server = Server(embedded: "0");
var admin = await server.SignedInAsync("s3-admin");
var settings = await SettingsAsync(admin);
Assert.Equal(S3Modes.External, settings!.Mode);
Assert.False(settings.EmbeddedAllowed);
Assert.Null(settings.Embedded);
var refused = await admin.PutAsJsonAsync(ApiRoutes.S3Settings, settings with { Mode = S3Modes.Embedded }, ct);
Assert.Equal(HttpStatusCode.BadRequest, refused.StatusCode);
}
[Fact]
public async Task The_built_in_stores_download_route_is_nothing_with_an_external_store()
{
var ct = TestContext.Current.CancellationToken;
using var server = Server(embedded: "0");
using var anonymous = server.CreateClient();
Assert.Equal(HttpStatusCode.NotFound, (await anonymous.GetAsync($"{ApiRoutes.S3Store}/{EmbeddedS3Store.Bucket}/a?X-Amz-Signature=x", ct)).StatusCode);
}
[Fact]
public async Task Who_can_only_look_cant_change_the_bucket()
{
var ct = TestContext.Current.CancellationToken;
using var server = Server();
var viewer = await server.SignedInAsync("s3-viewer", "Viewer");
Assert.Equal(HttpStatusCode.Forbidden, (await viewer.PutAsync($"{ApiRoutes.S3ObjectContent}?key=a.bin", new ByteArrayContent([1]), ct)).StatusCode);
Assert.Equal(HttpStatusCode.Forbidden, (await viewer.PostAsJsonAsync(ApiRoutes.S3ObjectDelete, new S3DeleteRequest(["a.bin"], []), ct)).StatusCode);
Assert.Equal(HttpStatusCode.Forbidden, (await viewer.PostAsJsonAsync(ApiRoutes.S3ObjectFolder, new S3FolderRequest("a/"), ct)).StatusCode);
Assert.Equal(HttpStatusCode.Forbidden, (await viewer.PostAsJsonAsync(ApiRoutes.S3ObjectStat, new S3StatRequest(["a.bin"]), ct)).StatusCode);
Assert.Equal(HttpStatusCode.Forbidden, (await viewer.GetAsync($"{ApiRoutes.S3ObjectLink}?key=a.bin", ct)).StatusCode);
Assert.Equal(HttpStatusCode.Forbidden, (await viewer.GetAsync(ApiRoutes.S3EmbeddedCredentials, ct)).StatusCode);
}
[Fact]
public async Task There_are_no_built_in_keys_to_reveal_before_it_starts_or_without_it()
{
var ct = TestContext.Current.CancellationToken;
using (var server = Server())
{
var admin = await server.SignedInAsync("s3-admin");
Assert.Equal(HttpStatusCode.Conflict, (await admin.GetAsync(ApiRoutes.S3EmbeddedCredentials, ct)).StatusCode);
}
using (var server = Server(embedded: "0"))
{
var admin = await server.SignedInAsync("s3-admin");
Assert.Equal(HttpStatusCode.NotFound, (await admin.GetAsync(ApiRoutes.S3EmbeddedCredentials, ct)).StatusCode);
}
}
}