forked from mtusi2026/mtusi2026lab4
58 lines
2.6 KiB
C#
58 lines
2.6 KiB
C#
using System.Net;
|
|
using System.Security.Cryptography;
|
|
using Amazon.S3;
|
|
using Messenger.Api.Services;
|
|
using Microsoft.Extensions.Configuration;
|
|
using Microsoft.Extensions.DependencyInjection;
|
|
|
|
// Проверяем реальный сервис с теми же настройками и ключами, что у API.
|
|
var configuration = new ConfigurationBuilder().AddEnvironmentVariables().Build();
|
|
var services = new ServiceCollection();
|
|
services.AddSingleton(S3Settings.From(configuration));
|
|
services.AddSingleton<IAttachmentStorage>(sp => new S3AttachmentStorage(sp.GetRequiredService<S3Settings>()));
|
|
using var provider = services.BuildServiceProvider();
|
|
var storage = provider.GetRequiredService<IAttachmentStorage>();
|
|
var settings = provider.GetRequiredService<S3Settings>();
|
|
using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(45));
|
|
var ct = timeout.Token;
|
|
var key = $"originals/csharp-check-{Guid.NewGuid():N}.png";
|
|
var original = await File.ReadAllBytesAsync(args.Single(), ct);
|
|
|
|
try
|
|
{
|
|
using var source = new MemoryStream(original, writable: false);
|
|
await storage.PutAsync(key, source, "image/png", ct);
|
|
if (!source.CanRead) throw new Exception("Upload closed the caller's stream");
|
|
Console.WriteLine("PASS: C# PutAsync uploads PNG and keeps the caller's stream open.");
|
|
|
|
using var destination = new MemoryStream();
|
|
await storage.CopyToAsync(key, destination, ct);
|
|
var downloaded = destination.ToArray();
|
|
if (!original.AsSpan().SequenceEqual(downloaded) ||
|
|
!SHA256.HashData(original).AsSpan().SequenceEqual(SHA256.HashData(downloaded)))
|
|
throw new Exception("Downloaded bytes/checksum differ");
|
|
Console.WriteLine("PASS: C# CopyToAsync returns identical bytes and SHA-256.");
|
|
|
|
using var http = new HttpClient { Timeout = TimeSpan.FromSeconds(5) };
|
|
using var anonymous = await http.GetAsync($"{settings.Endpoint.TrimEnd('/')}/{settings.Bucket}/{key}", ct);
|
|
if (anonymous.StatusCode != HttpStatusCode.Forbidden)
|
|
throw new Exception("Anonymous GET did not return 403");
|
|
Console.WriteLine("PASS: anonymously downloading the C#-uploaded object returns 403.");
|
|
|
|
await storage.DeleteAsync(key, ct);
|
|
try
|
|
{
|
|
await storage.CopyToAsync(key, Stream.Null, ct);
|
|
throw new Exception("Deleted object is still readable");
|
|
}
|
|
catch (AmazonS3Exception ex) when (ex.StatusCode == HttpStatusCode.NotFound)
|
|
{
|
|
Console.WriteLine("PASS: C# DeleteAsync removes the object; subsequent GET returns 404.");
|
|
}
|
|
}
|
|
finally
|
|
{
|
|
using var cleanup = new CancellationTokenSource(TimeSpan.FromSeconds(10));
|
|
await storage.DeleteAsync(key, cleanup.Token);
|
|
}
|