Выполнение работы на 4.
This commit is contained in:
@@ -0,0 +1,128 @@
|
||||
using DotNet.Testcontainers.Builders;
|
||||
using DotNet.Testcontainers.Containers;
|
||||
using Microsoft.AspNetCore.Hosting;
|
||||
using Microsoft.AspNetCore.Mvc.Testing;
|
||||
using Npgsql;
|
||||
using StackExchange.Redis;
|
||||
using Testcontainers.PostgreSql;
|
||||
using Amazon.S3;
|
||||
using Amazon.S3.Model;
|
||||
|
||||
namespace Messenger.Api.Tests;
|
||||
|
||||
// Один одноразовый контейнер PostgreSQL и один Valkey на весь тестовый прогон. Приложение поднимается в процессе теста
|
||||
// и применяет миграции к пустой БД, как при настоящем старте. Нужен только запущенный Docker.
|
||||
// Настройки передаются через UseSetting (а не переменные окружения), поэтому тест может поднять второй экземпляр
|
||||
// приложения с другими настройками: fixture.WithWebHostBuilder(b => b.UseSetting("SESSION_TTL_SECONDS", "2")).
|
||||
public sealed class ApiFixture : WebApplicationFactory<Program>, IAsyncLifetime
|
||||
{
|
||||
public const string PostgresImage = "postgres:17@sha256:b8faeff7712663c2773a190181e1246e37e364b887611c04658c28b44e2408fe";
|
||||
private const string ValkeyImage = "valkey/valkey:8.1@sha256:640c5e62cea04b6d6f2084232651d0cc70362d31f4f805e7be94dbed6855e8f2";
|
||||
|
||||
private readonly PostgreSqlContainer _db = new PostgreSqlBuilder().WithImage(PostgresImage).Build();
|
||||
|
||||
private readonly IContainer _cache = new ContainerBuilder()
|
||||
.WithImage(ValkeyImage)
|
||||
.WithPortBinding(6379, true)
|
||||
.WithWaitStrategy(Wait.ForUnixContainer().UntilMessageIsLogged("Ready to accept connections"))
|
||||
.Build();
|
||||
|
||||
private string _connectionFile = string.Empty;
|
||||
private string _s3AccessFile = string.Empty;
|
||||
private string _s3SecretFile = string.Empty;
|
||||
private const string S3Access = "integration-test-user";
|
||||
private const string S3Secret = "integration-only-not-a-real-secret";
|
||||
private readonly IContainer _s3 = new ContainerBuilder()
|
||||
.WithImage("quay.io/minio/minio@sha256:14cea493d9a34af32f524e538b8346cf79f3321eff8e708c1e2960462bd8936e")
|
||||
.WithEnvironment("MINIO_ROOT_USER", S3Access)
|
||||
.WithEnvironment("MINIO_ROOT_PASSWORD", S3Secret)
|
||||
.WithEnvironment("MINIO_BROWSER", "off")
|
||||
.WithCommand("server", "/data")
|
||||
.WithPortBinding(9000, true)
|
||||
.WithWaitStrategy(Wait.ForUnixContainer().UntilHttpRequestIsSucceeded(r => r.ForPort(9000).ForPath("/minio/health/ready")))
|
||||
.Build();
|
||||
|
||||
public string ConnectionString => _db.GetConnectionString();
|
||||
public string CacheConnection => $"{_cache.Hostname}:{_cache.GetMappedPublicPort(6379)}";
|
||||
|
||||
public async Task InitializeAsync()
|
||||
{
|
||||
await Task.WhenAll(_db.StartAsync(), _cache.StartAsync(), _s3.StartAsync());
|
||||
_connectionFile = WriteConnectionFile(_db.GetConnectionString());
|
||||
_s3AccessFile = WriteConnectionFile(S3Access);
|
||||
_s3SecretFile = WriteConnectionFile(S3Secret);
|
||||
using var client = new AmazonS3Client(S3Access, S3Secret, new AmazonS3Config
|
||||
{ ServiceURL = $"http://{_s3.Hostname}:{_s3.GetMappedPublicPort(9000)}", ForcePathStyle = true, AuthenticationRegion = "us-east-1" });
|
||||
await client.PutBucketAsync(new PutBucketRequest { BucketName = "integration-attachments" });
|
||||
}
|
||||
|
||||
async Task IAsyncLifetime.DisposeAsync()
|
||||
{
|
||||
await _db.DisposeAsync();
|
||||
await _cache.DisposeAsync();
|
||||
await _s3.DisposeAsync();
|
||||
File.Delete(_connectionFile);
|
||||
File.Delete(_s3AccessFile);
|
||||
File.Delete(_s3SecretFile);
|
||||
}
|
||||
|
||||
protected override void ConfigureWebHost(IWebHostBuilder builder)
|
||||
{
|
||||
builder.UseSetting("DATABASE_URL_FILE", _connectionFile);
|
||||
builder.UseSetting("CACHE_CONNECTION", CacheConnection);
|
||||
builder.UseSetting("DIAGNOSTIC_HEADERS", "true");
|
||||
builder.UseSetting("S3_ENDPOINT", $"http://{_s3.Hostname}:{_s3.GetMappedPublicPort(9000)}");
|
||||
builder.UseSetting("S3_BUCKET", "integration-attachments");
|
||||
builder.UseSetting("S3_ACCESS_KEY_ID_FILE", _s3AccessFile);
|
||||
builder.UseSetting("S3_SECRET_ACCESS_KEY_FILE", _s3SecretFile);
|
||||
// В Compose схему применяет отдельный контейнер (--migrate); тестовый процесс мигрирует пустую БД сам.
|
||||
builder.UseSetting("MIGRATE_ON_START", "true");
|
||||
builder.UseSetting("SHUTDOWN_DRAIN_SECONDS", "0");
|
||||
}
|
||||
|
||||
public static string WriteConnectionFile(string connectionString)
|
||||
{
|
||||
var path = Path.Combine(Path.GetTempPath(), $"messenger-test-{Guid.NewGuid():N}.conn");
|
||||
File.WriteAllText(path, connectionString);
|
||||
return path;
|
||||
}
|
||||
|
||||
// Прямой доступ к БД для проверок, которые нельзя выразить через API (например, состояние таблицы sessions).
|
||||
public async Task<NpgsqlConnection> OpenConnectionAsync()
|
||||
{
|
||||
var connection = new NpgsqlConnection(ConnectionString);
|
||||
await connection.OpenAsync();
|
||||
return connection;
|
||||
}
|
||||
|
||||
public async Task<T?> ScalarAsync<T>(string sql, params (string Name, object Value)[] parameters)
|
||||
{
|
||||
await using var db = await OpenConnectionAsync();
|
||||
await using var command = new NpgsqlCommand(sql, db);
|
||||
foreach (var (name, value) in parameters)
|
||||
{
|
||||
command.Parameters.AddWithValue(name, value);
|
||||
}
|
||||
|
||||
var result = await command.ExecuteScalarAsync();
|
||||
return result is null or DBNull ? default : (T)result;
|
||||
}
|
||||
|
||||
public async Task ExecuteAsync(string sql)
|
||||
{
|
||||
await using var db = await OpenConnectionAsync();
|
||||
await using var command = new NpgsqlCommand(sql, db);
|
||||
await command.ExecuteNonQueryAsync();
|
||||
}
|
||||
|
||||
// Полная очистка содержимого кэша (эквивалент FLUSHALL / перезапуска Valkey без persistence).
|
||||
public async Task FlushCacheAsync()
|
||||
{
|
||||
using var connection = await ConnectionMultiplexer.ConnectAsync(
|
||||
new ConfigurationOptions { EndPoints = { CacheConnection }, AllowAdmin = true });
|
||||
await connection.GetServer(connection.GetEndPoints()[0]).FlushAllDatabasesAsync();
|
||||
}
|
||||
}
|
||||
|
||||
[CollectionDefinition("api")]
|
||||
public sealed class ApiCollection : ICollectionFixture<ApiFixture>;
|
||||
@@ -0,0 +1,104 @@
|
||||
using System.Net;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace Messenger.Api.Tests;
|
||||
|
||||
internal sealed record TestUser(Guid Id, string Username, string Password, string Token);
|
||||
|
||||
internal static class ApiHelpers
|
||||
{
|
||||
public const string DefaultPassword = "correct horse battery staple";
|
||||
|
||||
public static StringContent Json(string raw) =>
|
||||
new(raw, Encoding.UTF8, "application/json");
|
||||
|
||||
// user != null — запрос с Bearer-токеном этого пользователя.
|
||||
public static HttpRequestMessage Request(HttpMethod method, string url, TestUser? user = null, HttpContent? content = null)
|
||||
{
|
||||
var request = new HttpRequestMessage(method, url) { Content = content };
|
||||
if (user is not null)
|
||||
{
|
||||
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", user.Token);
|
||||
}
|
||||
|
||||
return request;
|
||||
}
|
||||
|
||||
public static async Task<JsonElement> ReadJsonAsync(HttpResponseMessage response)
|
||||
{
|
||||
var body = await response.Content.ReadAsStringAsync();
|
||||
return JsonDocument.Parse(body).RootElement.Clone();
|
||||
}
|
||||
|
||||
public static async Task<string> ErrorCodeAsync(HttpResponseMessage response)
|
||||
{
|
||||
var json = await ReadJsonAsync(response);
|
||||
return json.GetProperty("error").GetProperty("code").GetString()!;
|
||||
}
|
||||
|
||||
public static string BasicHeader(string username, string password) =>
|
||||
"Basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes($"{username}:{password}"));
|
||||
|
||||
public static async Task<HttpResponseMessage> LoginAsync(HttpClient client, string username, string password)
|
||||
{
|
||||
using var request = new HttpRequestMessage(HttpMethod.Post, "/api/v1/auth/sessions");
|
||||
request.Headers.TryAddWithoutValidation("Authorization", BasicHeader(username, password));
|
||||
return await client.SendAsync(request);
|
||||
}
|
||||
|
||||
// Регистрирует пользователя и входит: возвращает его с рабочим Bearer-токеном.
|
||||
public static async Task<TestUser> CreateUserAsync(HttpClient client, string? username = null)
|
||||
{
|
||||
username ??= "u" + Guid.NewGuid().ToString("N")[..12];
|
||||
var response = await client.PostAsJsonAsync("/api/v1/users",
|
||||
new { username, display_name = "Тест", password = DefaultPassword });
|
||||
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
|
||||
var id = (await ReadJsonAsync(response)).GetProperty("id").GetGuid();
|
||||
|
||||
var login = await LoginAsync(client, username, DefaultPassword);
|
||||
Assert.Equal(HttpStatusCode.Created, login.StatusCode);
|
||||
var token = (await ReadJsonAsync(login)).GetProperty("token").GetString()!;
|
||||
return new TestUser(id, username, DefaultPassword, token);
|
||||
}
|
||||
|
||||
public static async Task<Guid> CreateChatAsync(HttpClient client, TestUser owner, params TestUser[] others)
|
||||
{
|
||||
var members = others.Append(owner).Select(u => u.Id).ToArray();
|
||||
using var request = Request(HttpMethod.Post, "/api/v1/chats", owner,
|
||||
JsonContent.Create(new { title = "Чат", member_ids = members }));
|
||||
var response = await client.SendAsync(request);
|
||||
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
|
||||
return (await ReadJsonAsync(response)).GetProperty("id").GetGuid();
|
||||
}
|
||||
|
||||
// key == null — новый уникальный Idempotency-Key (каждое сообщение независимо); иначе повтор с заданным ключом.
|
||||
public static async Task<HttpResponseMessage> SendMessageAsync(
|
||||
HttpClient client, TestUser sender, Guid chatId, string text, string? key = null)
|
||||
{
|
||||
using var request = Request(HttpMethod.Post, $"/api/v1/chats/{chatId}/messages", sender,
|
||||
JsonContent.Create(new { text }));
|
||||
request.Headers.Add("Idempotency-Key", key ?? Guid.NewGuid().ToString("N"));
|
||||
return await client.SendAsync(request);
|
||||
}
|
||||
|
||||
public static async Task<List<Guid>> ReadAllMessagesAsync(HttpClient client, Guid chatId, TestUser user, int limit)
|
||||
{
|
||||
string? cursor = null;
|
||||
var received = new List<Guid>();
|
||||
do
|
||||
{
|
||||
var url = $"/api/v1/chats/{chatId}/messages?limit={limit}" +
|
||||
(cursor is null ? "" : "&cursor=" + Uri.EscapeDataString(cursor));
|
||||
using var request = Request(HttpMethod.Get, url, user);
|
||||
var page = await ReadJsonAsync(await client.SendAsync(request));
|
||||
received.AddRange(page.GetProperty("items").EnumerateArray().Select(m => m.GetProperty("id").GetGuid()));
|
||||
var next = page.GetProperty("next_cursor");
|
||||
cursor = next.ValueKind == JsonValueKind.Null ? null : next.GetString();
|
||||
}
|
||||
while (cursor is not null);
|
||||
return received;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,303 @@
|
||||
using System.Net;
|
||||
using System.Text.Json;
|
||||
using static Messenger.Api.Tests.ApiHelpers;
|
||||
|
||||
namespace Messenger.Api.Tests;
|
||||
|
||||
[Collection("api")]
|
||||
public class ApiTests(ApiFixture fixture)
|
||||
{
|
||||
private HttpClient NewClient() => fixture.CreateClient();
|
||||
|
||||
[Fact]
|
||||
public async Task CreateUser_WithMalformedJson_ReturnsBadRequest()
|
||||
{
|
||||
using var client = NewClient();
|
||||
|
||||
var response = await client.PostAsync("/api/v1/users", Json("{bad"));
|
||||
|
||||
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
|
||||
Assert.Equal("invalid_request", await ErrorCodeAsync(response));
|
||||
Assert.True(response.Headers.Contains("X-Request-Id"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CreateUser_WithoutBody_ReturnsBadRequest()
|
||||
{
|
||||
using var client = NewClient();
|
||||
|
||||
var response = await client.PostAsync("/api/v1/users", null);
|
||||
|
||||
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
|
||||
Assert.Equal("invalid_request", await ErrorCodeAsync(response));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CreateUser_WithDuplicateUsername_ReturnsConflict()
|
||||
{
|
||||
using var client = NewClient();
|
||||
var user = await CreateUserAsync(client);
|
||||
|
||||
var response = await client.PostAsync("/api/v1/users",
|
||||
Json($$"""{"username":"{{user.Username}}","display_name":"Другой","password":"{{DefaultPassword}}"}"""));
|
||||
|
||||
Assert.Equal(HttpStatusCode.Conflict, response.StatusCode);
|
||||
Assert.Equal("conflict", await ErrorCodeAsync(response));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("short")]
|
||||
[InlineData("12345678901")] // 11 символов
|
||||
public async Task CreateUser_WithShortPassword_ReturnsBadRequest(string password)
|
||||
{
|
||||
using var client = NewClient();
|
||||
|
||||
var response = await client.PostAsync("/api/v1/users",
|
||||
Json($$"""{"username":"short_pw_probe","display_name":"A","password":"{{password}}"}"""));
|
||||
|
||||
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CreateUser_Response_DoesNotExposePasswordOrHash()
|
||||
{
|
||||
using var client = NewClient();
|
||||
|
||||
var response = await client.PostAsync("/api/v1/users",
|
||||
Json($$"""{"username":"no_leak_probe","display_name":"A","password":"{{DefaultPassword}}"}"""));
|
||||
|
||||
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
|
||||
var body = await response.Content.ReadAsStringAsync();
|
||||
Assert.DoesNotContain("password", body, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("argon2", body, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetChat_ByNonMember_ReturnsNotFound()
|
||||
{
|
||||
using var client = NewClient();
|
||||
var alice = await CreateUserAsync(client);
|
||||
var bob = await CreateUserAsync(client);
|
||||
var eve = await CreateUserAsync(client);
|
||||
var chatId = await CreateChatAsync(client, alice, bob);
|
||||
|
||||
using var request = Request(HttpMethod.Get, $"/api/v1/chats/{chatId}", eve);
|
||||
var response = await client.SendAsync(request);
|
||||
|
||||
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
|
||||
Assert.Equal("not_found", await ErrorCodeAsync(response));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ListChats_ShowsOnlyChatsOfCurrentUser()
|
||||
{
|
||||
using var client = NewClient();
|
||||
var alice = await CreateUserAsync(client);
|
||||
var bob = await CreateUserAsync(client);
|
||||
var eve = await CreateUserAsync(client);
|
||||
var shared = await CreateChatAsync(client, alice, bob);
|
||||
var other = await CreateChatAsync(client, eve);
|
||||
|
||||
using var request = Request(HttpMethod.Get, "/api/v1/chats", bob);
|
||||
var page = await ReadJsonAsync(await client.SendAsync(request));
|
||||
var ids = page.GetProperty("items").EnumerateArray().Select(c => c.GetProperty("id").GetGuid()).ToList();
|
||||
|
||||
Assert.Contains(shared, ids);
|
||||
Assert.DoesNotContain(other, ids);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CreateChat_WithUnknownMember_ReturnsBadRequestAndCreatesNothing()
|
||||
{
|
||||
using var client = NewClient();
|
||||
var alice = await CreateUserAsync(client);
|
||||
|
||||
using var request = Request(HttpMethod.Post, "/api/v1/chats", alice,
|
||||
Json($$"""{"title":"X","member_ids":["{{alice.Id}}","{{Guid.NewGuid()}}"]}"""));
|
||||
var response = await client.SendAsync(request);
|
||||
|
||||
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
|
||||
using var list = Request(HttpMethod.Get, "/api/v1/chats", alice);
|
||||
var page = await ReadJsonAsync(await client.SendAsync(list));
|
||||
Assert.Empty(page.GetProperty("items").EnumerateArray());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SendMessage_ToForeignChat_ReturnsNotFound()
|
||||
{
|
||||
using var client = NewClient();
|
||||
var alice = await CreateUserAsync(client);
|
||||
var bob = await CreateUserAsync(client);
|
||||
var eve = await CreateUserAsync(client);
|
||||
var chatId = await CreateChatAsync(client, alice, bob);
|
||||
|
||||
var response = await SendMessageAsync(client, eve, chatId, "чужое");
|
||||
|
||||
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("")]
|
||||
[InlineData(" ")]
|
||||
public async Task SendMessage_WithEmptyText_ReturnsBadRequest(string text)
|
||||
{
|
||||
using var client = NewClient();
|
||||
var alice = await CreateUserAsync(client);
|
||||
var chatId = await CreateChatAsync(client, alice);
|
||||
|
||||
var response = await SendMessageAsync(client, alice, chatId, text);
|
||||
|
||||
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
|
||||
Assert.Equal("invalid_request", await ErrorCodeAsync(response));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SendMessage_SenderIsTakenFromSession_NotFromRequest()
|
||||
{
|
||||
using var client = NewClient();
|
||||
var alice = await CreateUserAsync(client);
|
||||
var bob = await CreateUserAsync(client);
|
||||
var chatId = await CreateChatAsync(client, alice, bob);
|
||||
|
||||
using var request = Request(HttpMethod.Post, $"/api/v1/chats/{chatId}/messages", alice,
|
||||
Json($$"""{"text":"привет","sender_id":"{{bob.Id}}"}"""));
|
||||
request.Headers.Add("Idempotency-Key", Guid.NewGuid().ToString("N"));
|
||||
var withSender = await client.SendAsync(request);
|
||||
var ok = await SendMessageAsync(client, alice, chatId, "привет");
|
||||
|
||||
Assert.Equal(HttpStatusCode.BadRequest, withSender.StatusCode); // sender_id в запросе не принимается
|
||||
Assert.Equal(alice.Id, (await ReadJsonAsync(ok)).GetProperty("sender_id").GetGuid());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ListMessages_WalksAllPagesWithoutGapsOrDuplicates()
|
||||
{
|
||||
using var client = NewClient();
|
||||
var alice = await CreateUserAsync(client);
|
||||
var bob = await CreateUserAsync(client);
|
||||
var chatId = await CreateChatAsync(client, alice, bob);
|
||||
const int total = 7;
|
||||
var sent = new List<Guid>();
|
||||
for (var i = 0; i < total; i++)
|
||||
{
|
||||
var response = await SendMessageAsync(client, i % 2 == 0 ? alice : bob, chatId, $"сообщение {i}");
|
||||
sent.Add((await ReadJsonAsync(response)).GetProperty("id").GetGuid());
|
||||
}
|
||||
|
||||
var received = new List<Guid>();
|
||||
string? cursor = null;
|
||||
var pages = 0;
|
||||
do
|
||||
{
|
||||
var url = $"/api/v1/chats/{chatId}/messages?limit=3" +
|
||||
(cursor is null ? "" : "&cursor=" + Uri.EscapeDataString(cursor));
|
||||
using var request = Request(HttpMethod.Get, url, alice);
|
||||
var page = await ReadJsonAsync(await client.SendAsync(request));
|
||||
received.AddRange(page.GetProperty("items").EnumerateArray().Select(m => m.GetProperty("id").GetGuid()));
|
||||
var next = page.GetProperty("next_cursor");
|
||||
cursor = next.ValueKind == JsonValueKind.Null ? null : next.GetString();
|
||||
pages++;
|
||||
}
|
||||
while (cursor is not null && pages < 10);
|
||||
|
||||
Assert.Equal(3, pages);
|
||||
Assert.Equal(total, received.Count);
|
||||
// Один автор в одном чате: порядок истории совпадает с порядком отправки.
|
||||
Assert.Equal(sent, received);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ListMessages_WithCursorFromAnotherChat_ReturnsBadRequest()
|
||||
{
|
||||
using var client = NewClient();
|
||||
var alice = await CreateUserAsync(client);
|
||||
var chat1 = await CreateChatAsync(client, alice);
|
||||
var chat2 = await CreateChatAsync(client, alice);
|
||||
await SendMessageAsync(client, alice, chat1, "a");
|
||||
await SendMessageAsync(client, alice, chat1, "b");
|
||||
using var first = Request(HttpMethod.Get, $"/api/v1/chats/{chat1}/messages?limit=1", alice);
|
||||
var cursor = (await ReadJsonAsync(await client.SendAsync(first))).GetProperty("next_cursor").GetString()!;
|
||||
|
||||
using var request = Request(HttpMethod.Get,
|
||||
$"/api/v1/chats/{chat2}/messages?cursor={Uri.EscapeDataString(cursor)}", alice);
|
||||
var response = await client.SendAsync(request);
|
||||
|
||||
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ListMessages_ReturnsSameOrderForAnyPageSize()
|
||||
{
|
||||
using var client = NewClient();
|
||||
var alice = await CreateUserAsync(client);
|
||||
var chatId = await CreateChatAsync(client, alice);
|
||||
var sent = new List<Guid>();
|
||||
for (var i = 0; i < 120; i++)
|
||||
{
|
||||
var response = await SendMessageAsync(client, alice, chatId, $"m{i}");
|
||||
sent.Add((await ReadJsonAsync(response)).GetProperty("id").GetGuid());
|
||||
}
|
||||
|
||||
var baseline = await ReadAllMessagesAsync(client, chatId, alice, 100);
|
||||
Assert.Equal(sent, baseline);
|
||||
foreach (var limit in new[] { 1, 7, 50 })
|
||||
{
|
||||
var received = await ReadAllMessagesAsync(client, chatId, alice, limit);
|
||||
Assert.Equal(baseline, received);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ListMessages_AfterConcurrentSends_IsOrderedByTimeThenId()
|
||||
{
|
||||
using var client = NewClient();
|
||||
var users = new List<TestUser>();
|
||||
for (var i = 0; i < 10; i++)
|
||||
{
|
||||
users.Add(await CreateUserAsync(client));
|
||||
}
|
||||
|
||||
var chatId = await CreateChatAsync(client, users[0], users.Skip(1).ToArray());
|
||||
|
||||
var sends = Enumerable.Range(0, 300).Select(i => SendMessageAsync(client, users[i % 10], chatId, $"m{i}"));
|
||||
foreach (var response in await Task.WhenAll(sends))
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
|
||||
}
|
||||
|
||||
var items = new List<(string CreatedAt, Guid Id)>();
|
||||
string? cursor = null;
|
||||
do
|
||||
{
|
||||
var url = $"/api/v1/chats/{chatId}/messages?limit=100" +
|
||||
(cursor is null ? "" : "&cursor=" + Uri.EscapeDataString(cursor));
|
||||
using var request = Request(HttpMethod.Get, url, users[0]);
|
||||
var page = await ReadJsonAsync(await client.SendAsync(request));
|
||||
items.AddRange(page.GetProperty("items").EnumerateArray()
|
||||
.Select(m => (m.GetProperty("created_at").GetString()!, m.GetProperty("id").GetGuid())));
|
||||
var next = page.GetProperty("next_cursor");
|
||||
cursor = next.ValueKind == JsonValueKind.Null ? null : next.GetString();
|
||||
}
|
||||
while (cursor is not null);
|
||||
|
||||
Assert.Equal(300, items.Count);
|
||||
Assert.Equal(300, items.Select(x => x.Id).Distinct().Count());
|
||||
// Серверное время строго возрастает внутри чата (см. last_message_at), поэтому порядок истории — порядок записи.
|
||||
Assert.Equal(300, items.Select(x => x.CreatedAt).Distinct().Count());
|
||||
Assert.Equal(items.OrderBy(x => x.CreatedAt, StringComparer.Ordinal).ToList(), items);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("""{"USERNAME":"probe_case_a","display_name":"A","password":"correct horse battery staple"}""")]
|
||||
[InlineData("""{"username":"probe_case_b","Display_Name":"A","password":"correct horse battery staple"}""")]
|
||||
[InlineData("""{"Username":"probe_case_c","display_name":"A","password":"correct horse battery staple"}""")]
|
||||
public async Task CreateUser_WithDifferentlyCasedFieldNames_ReturnsBadRequest(string body)
|
||||
{
|
||||
using var client = NewClient();
|
||||
|
||||
var response = await client.PostAsync("/api/v1/users", Json(body));
|
||||
|
||||
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
|
||||
Assert.Equal("invalid_request", await ErrorCodeAsync(response));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,252 @@
|
||||
using System.Net;
|
||||
using System.Net.Http.Headers;
|
||||
using static Messenger.Api.Tests.ApiHelpers;
|
||||
|
||||
namespace Messenger.Api.Tests;
|
||||
|
||||
[Collection("api")]
|
||||
public class AuthTests(ApiFixture fixture)
|
||||
{
|
||||
private static readonly string[] ProtectedGets =
|
||||
[
|
||||
"/api/v1/users/me",
|
||||
"/api/v1/chats",
|
||||
"/api/v1/chats/00000000-0000-0000-0000-000000000001",
|
||||
"/api/v1/chats/00000000-0000-0000-0000-000000000001/messages"
|
||||
];
|
||||
|
||||
[Fact]
|
||||
public async Task Login_WithValidCredentials_ReturnsOpaqueBearerSession()
|
||||
{
|
||||
using var client = fixture.CreateClient();
|
||||
var user = await CreateUserAsync(client);
|
||||
|
||||
var response = await LoginAsync(client, user.Username, user.Password);
|
||||
|
||||
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
|
||||
var json = await ReadJsonAsync(response);
|
||||
Assert.Equal("Bearer", json.GetProperty("token_type").GetString());
|
||||
Assert.True(json.GetProperty("token").GetString()!.Length >= 43); // 256 бит в base64url
|
||||
Assert.Equal(user.Id, json.GetProperty("user").GetProperty("id").GetGuid());
|
||||
Assert.DoesNotContain("password", await response.Content.ReadAsStringAsync(), StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Login_AcceptsColonInPassword()
|
||||
{
|
||||
using var client = fixture.CreateClient();
|
||||
var username = "colon" + Guid.NewGuid().ToString("N")[..8];
|
||||
await client.PostAsync("/api/v1/users",
|
||||
Json($$"""{"username":"{{username}}","display_name":"A","password":"pass:with:colons-123"}"""));
|
||||
|
||||
var response = await LoginAsync(client, username, "pass:with:colons-123");
|
||||
|
||||
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Login_WrongPasswordAndUnknownUser_GiveIdenticalUnauthorized()
|
||||
{
|
||||
using var client = fixture.CreateClient();
|
||||
var user = await CreateUserAsync(client);
|
||||
|
||||
var wrongPassword = await LoginAsync(client, user.Username, "totally-wrong-password");
|
||||
var unknownUser = await LoginAsync(client, "nobody_" + Guid.NewGuid().ToString("N")[..8], DefaultPassword);
|
||||
|
||||
foreach (var response in new[] { wrongPassword, unknownUser })
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
Assert.Equal("Basic realm=\"messenger\", charset=\"UTF-8\"", response.Headers.WwwAuthenticate.ToString());
|
||||
Assert.Equal("unauthorized", await ErrorCodeAsync(response));
|
||||
}
|
||||
|
||||
var a = (await ReadJsonAsync(wrongPassword)).GetProperty("error").GetProperty("message").GetString();
|
||||
var b = (await ReadJsonAsync(unknownUser)).GetProperty("error").GetProperty("message").GetString();
|
||||
Assert.Equal(a, b);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("Basic !!!not-base64")]
|
||||
[InlineData("Basic bm9jb2xvbg==")] // "nocolon"
|
||||
[InlineData("Bearer sometoken")]
|
||||
[InlineData("")]
|
||||
public async Task Login_WithMalformedAuthorization_ReturnsUnauthorized(string header)
|
||||
{
|
||||
using var client = fixture.CreateClient();
|
||||
using var request = new HttpRequestMessage(HttpMethod.Post, "/api/v1/auth/sessions");
|
||||
if (header.Length > 0)
|
||||
{
|
||||
request.Headers.TryAddWithoutValidation("Authorization", header);
|
||||
}
|
||||
|
||||
var response = await client.SendAsync(request);
|
||||
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
Assert.StartsWith("Basic", response.Headers.WwwAuthenticate.ToString());
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[MemberData(nameof(ProtectedUrls))]
|
||||
public async Task ProtectedEndpoints_WithoutToken_ReturnUnauthorizedWithBearerChallenge(string url)
|
||||
{
|
||||
using var client = fixture.CreateClient();
|
||||
|
||||
var response = await client.GetAsync(url);
|
||||
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
Assert.Equal("Bearer realm=\"messenger\"", response.Headers.WwwAuthenticate.ToString());
|
||||
Assert.True(response.Headers.Contains("X-Request-Id"));
|
||||
}
|
||||
|
||||
public static IEnumerable<object[]> ProtectedUrls() => ProtectedGets.Select(u => new object[] { u });
|
||||
|
||||
[Fact]
|
||||
public async Task ProtectedEndpoint_WithBasicAuth_ReturnsUnauthorized()
|
||||
{
|
||||
using var client = fixture.CreateClient();
|
||||
var user = await CreateUserAsync(client);
|
||||
using var request = new HttpRequestMessage(HttpMethod.Get, "/api/v1/users/me");
|
||||
request.Headers.TryAddWithoutValidation("Authorization", BasicHeader(user.Username, user.Password));
|
||||
|
||||
var response = await client.SendAsync(request);
|
||||
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task XUserIdHeader_IsIgnored()
|
||||
{
|
||||
using var client = fixture.CreateClient();
|
||||
var alice = await CreateUserAsync(client);
|
||||
var eve = await CreateUserAsync(client);
|
||||
|
||||
// Без токена X-User-Id не даёт доступа.
|
||||
using var anonymous = new HttpRequestMessage(HttpMethod.Get, "/api/v1/users/me");
|
||||
anonymous.Headers.Add("X-User-Id", alice.Id.ToString());
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, (await client.SendAsync(anonymous)).StatusCode);
|
||||
|
||||
// С токеном — владелец сессии не подменяется.
|
||||
using var spoofed = Request(HttpMethod.Get, "/api/v1/users/me", alice);
|
||||
spoofed.Headers.Add("X-User-Id", eve.Id.ToString());
|
||||
var me = await ReadJsonAsync(await client.SendAsync(spoofed));
|
||||
Assert.Equal(alice.Id, me.GetProperty("id").GetGuid());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UnauthenticatedPostWithMalformedBody_ReturnsUnauthorizedNotBadRequest()
|
||||
{
|
||||
using var client = fixture.CreateClient();
|
||||
|
||||
var response = await client.PostAsync("/api/v1/chats", Json("{bad"));
|
||||
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); // сначала аутентификация
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Logout_RevokesTokenAndSecondLogoutIsUnauthorized()
|
||||
{
|
||||
using var client = fixture.CreateClient();
|
||||
var user = await CreateUserAsync(client);
|
||||
|
||||
using var first = Request(HttpMethod.Delete, "/api/v1/auth/sessions/current", user);
|
||||
var firstResponse = await client.SendAsync(first);
|
||||
Assert.Equal(HttpStatusCode.NoContent, firstResponse.StatusCode);
|
||||
Assert.Equal(0, firstResponse.Content.Headers.ContentLength ?? 0);
|
||||
|
||||
using var again = Request(HttpMethod.Delete, "/api/v1/auth/sessions/current", user);
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, (await client.SendAsync(again)).StatusCode);
|
||||
using var me = Request(HttpMethod.Get, "/api/v1/users/me", user);
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, (await client.SendAsync(me)).StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task LogoutOfOneSession_DoesNotAffectAnotherSessionOfSameUser()
|
||||
{
|
||||
using var client = fixture.CreateClient();
|
||||
var user = await CreateUserAsync(client);
|
||||
var secondLogin = await ReadJsonAsync(await LoginAsync(client, user.Username, user.Password));
|
||||
var second = user with { Token = secondLogin.GetProperty("token").GetString()! };
|
||||
|
||||
using var logout = Request(HttpMethod.Delete, "/api/v1/auth/sessions/current", user);
|
||||
await client.SendAsync(logout);
|
||||
|
||||
using var me = Request(HttpMethod.Get, "/api/v1/users/me", second);
|
||||
Assert.Equal(HttpStatusCode.OK, (await client.SendAsync(me)).StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExpiredSession_IsRejected()
|
||||
{
|
||||
using var client = fixture.CreateClient();
|
||||
var user = await CreateUserAsync(client);
|
||||
using var before = Request(HttpMethod.Get, "/api/v1/users/me", user);
|
||||
Assert.Equal(HttpStatusCode.OK, (await client.SendAsync(before)).StatusCode);
|
||||
|
||||
// Состарим сессию в БД: created_at < expires_at < now (ограничение таблицы требует expires_at > created_at).
|
||||
await using (var db = await fixture.OpenConnectionAsync())
|
||||
await using (var age = new Npgsql.NpgsqlCommand(
|
||||
"update sessions set created_at = now() - interval '10 seconds', expires_at = now() - interval '5 seconds' where user_id = @u", db))
|
||||
{
|
||||
age.Parameters.AddWithValue("u", user.Id);
|
||||
Assert.Equal(1, await age.ExecuteNonQueryAsync());
|
||||
}
|
||||
|
||||
using var after = Request(HttpMethod.Get, "/api/v1/users/me", user);
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, (await client.SendAsync(after)).StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ShortSessionTtl_ExpiresSessionByItself()
|
||||
{
|
||||
// Отдельный экземпляр приложения с SESSION_TTL_SECONDS=2 поверх той же БД: никаких подмен данных в таблице.
|
||||
await using var app = fixture.WithWebHostBuilder(b => b.UseSetting("SESSION_TTL_SECONDS", "2"));
|
||||
using var client = app.CreateClient();
|
||||
var user = await CreateUserAsync(client);
|
||||
|
||||
using (var alive = Request(HttpMethod.Get, "/api/v1/users/me", user))
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.OK, (await client.SendAsync(alive)).StatusCode);
|
||||
}
|
||||
|
||||
await Task.Delay(TimeSpan.FromSeconds(3));
|
||||
|
||||
using var expired = Request(HttpMethod.Get, "/api/v1/users/me", user);
|
||||
var response = await client.SendAsync(expired);
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
Assert.Equal("Bearer realm=\"messenger\"", response.Headers.WwwAuthenticate.ToString());
|
||||
// Истёкшая сессия не продлевается: повторный вход выдаёт новую.
|
||||
Assert.Equal(HttpStatusCode.Created, (await LoginAsync(client, user.Username, user.Password)).StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SessionsTable_StoresTokenHashNotToken()
|
||||
{
|
||||
using var client = fixture.CreateClient();
|
||||
var user = await CreateUserAsync(client);
|
||||
|
||||
await using var db = await fixture.OpenConnectionAsync();
|
||||
await using var query = new Npgsql.NpgsqlCommand(
|
||||
"select token_hash from sessions where user_id = @u", db);
|
||||
query.Parameters.AddWithValue("u", user.Id);
|
||||
var stored = (byte[])(await query.ExecuteScalarAsync())!;
|
||||
|
||||
Assert.Equal(32, stored.Length);
|
||||
Assert.NotEqual(System.Text.Encoding.UTF8.GetBytes(user.Token), stored);
|
||||
Assert.Equal(System.Security.Cryptography.SHA256.HashData(System.Text.Encoding.UTF8.GetBytes(user.Token)), stored);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task PasswordsAreStoredAsArgon2id()
|
||||
{
|
||||
using var client = fixture.CreateClient();
|
||||
var user = await CreateUserAsync(client);
|
||||
|
||||
await using var db = await fixture.OpenConnectionAsync();
|
||||
await using var query = new Npgsql.NpgsqlCommand("select password_hash from users where id = @u", db);
|
||||
query.Parameters.AddWithValue("u", user.Id);
|
||||
var hash = (string)(await query.ExecuteScalarAsync())!;
|
||||
|
||||
Assert.StartsWith("$argon2id$", hash);
|
||||
Assert.DoesNotContain(user.Password, hash);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
using System.Net;
|
||||
using Microsoft.AspNetCore.Mvc.Testing;
|
||||
using static Messenger.Api.Tests.ApiHelpers;
|
||||
|
||||
namespace Messenger.Api.Tests;
|
||||
|
||||
[Collection("api")]
|
||||
public class CacheTests(ApiFixture fixture)
|
||||
{
|
||||
private static string Header(HttpResponseMessage response, string name) =>
|
||||
response.Headers.TryGetValues(name, out var values) ? values.First() : "";
|
||||
|
||||
private static async Task<HttpResponseMessage> GetPageAsync(
|
||||
HttpClient client, TestUser user, Guid chatId, int limit = 50, string? cursor = null)
|
||||
{
|
||||
var url = $"/api/v1/chats/{chatId}/messages?limit={limit}" +
|
||||
(cursor is null ? "" : "&cursor=" + Uri.EscapeDataString(cursor));
|
||||
using var request = Request(HttpMethod.Get, url, user);
|
||||
return await client.SendAsync(request);
|
||||
}
|
||||
|
||||
private static async Task<(TestUser Alice, TestUser Bob, Guid Chat)> ChatWithMessagesAsync(HttpClient client, int messages)
|
||||
{
|
||||
var alice = await CreateUserAsync(client);
|
||||
var bob = await CreateUserAsync(client);
|
||||
var chat = await CreateChatAsync(client, alice, bob);
|
||||
for (var i = 0; i < messages; i++)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.Created, (await SendMessageAsync(client, alice, chat, $"m{i}")).StatusCode);
|
||||
}
|
||||
|
||||
return (alice, bob, chat);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SecondRead_IsServedFromCache_WithFewerSqlQueries_AndIdenticalBody()
|
||||
{
|
||||
using var client = fixture.CreateClient();
|
||||
var (_, bob, chat) = await ChatWithMessagesAsync(client, 3);
|
||||
|
||||
var first = await GetPageAsync(client, bob, chat);
|
||||
var second = await GetPageAsync(client, bob, chat);
|
||||
|
||||
Assert.Equal("miss", Header(first, "X-Cache"));
|
||||
Assert.Equal("hit", Header(second, "X-Cache"));
|
||||
// miss: сессия + версия/доступ + страница; hit: сессия + версия/доступ.
|
||||
Assert.Equal("3", Header(first, "X-Db-Queries"));
|
||||
Assert.Equal("2", Header(second, "X-Db-Queries"));
|
||||
Assert.Equal(await first.Content.ReadAsStringAsync(), await second.Content.ReadAsStringAsync());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ReadAfterWrite_NeverReturnsStaleCachedPage()
|
||||
{
|
||||
using var client = fixture.CreateClient();
|
||||
var (alice, bob, chat) = await ChatWithMessagesAsync(client, 2);
|
||||
await GetPageAsync(client, bob, chat); // прогрели кэш
|
||||
Assert.Equal("hit", Header(await GetPageAsync(client, bob, chat), "X-Cache"));
|
||||
|
||||
for (var i = 0; i < 20; i++)
|
||||
{
|
||||
var sent = await SendMessageAsync(client, alice, chat, $"new {i}");
|
||||
var id = (await ReadJsonAsync(sent)).GetProperty("id").GetGuid();
|
||||
|
||||
// Сразу после подтверждённой записи (201) следующее чтение обязано содержать новое сообщение.
|
||||
var ids = await ReadAllMessagesAsync(client, chat, bob, 100);
|
||||
Assert.Contains(id, ids);
|
||||
Assert.Equal(3 + i, ids.Count);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task FlushedCache_DoesNotChangeResults()
|
||||
{
|
||||
using var client = fixture.CreateClient();
|
||||
var (_, bob, chat) = await ChatWithMessagesAsync(client, 5);
|
||||
var before = await ReadAllMessagesAsync(client, chat, bob, 2);
|
||||
Assert.Equal("hit", Header(await GetPageAsync(client, bob, chat, 2), "X-Cache"));
|
||||
|
||||
await fixture.FlushCacheAsync();
|
||||
|
||||
var response = await GetPageAsync(client, bob, chat, 2);
|
||||
Assert.Equal("miss", Header(response, "X-Cache"));
|
||||
Assert.Equal(before, await ReadAllMessagesAsync(client, chat, bob, 2));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CachedPage_IsNotVisibleToNonMember()
|
||||
{
|
||||
using var client = fixture.CreateClient();
|
||||
var (_, bob, chat) = await ChatWithMessagesAsync(client, 2);
|
||||
var eve = await CreateUserAsync(client);
|
||||
await GetPageAsync(client, bob, chat);
|
||||
Assert.Equal("hit", Header(await GetPageAsync(client, bob, chat), "X-Cache"));
|
||||
|
||||
var response = await GetPageAsync(client, eve, chat);
|
||||
|
||||
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); // доступ проверяется до обращения к кэшу
|
||||
Assert.DoesNotContain("m0", await response.Content.ReadAsStringAsync());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task PagesWithDifferentLimitsAndCursors_AreCachedSeparately()
|
||||
{
|
||||
using var client = fixture.CreateClient();
|
||||
var (_, bob, chat) = await ChatWithMessagesAsync(client, 9);
|
||||
|
||||
var firstPass = await ReadAllMessagesAsync(client, chat, bob, 4);
|
||||
var secondPass = await ReadAllMessagesAsync(client, chat, bob, 4); // все страницы уже в кэше
|
||||
var otherLimit = await ReadAllMessagesAsync(client, chat, bob, 3);
|
||||
|
||||
Assert.Equal(9, firstPass.Count);
|
||||
Assert.Equal(firstPass, secondPass);
|
||||
Assert.Equal(firstPass, otherLimit);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UnavailableCache_IsBypassed_AndRequestsStillSucceed()
|
||||
{
|
||||
using var client = fixture.CreateClient();
|
||||
var (_, bob, chat) = await ChatWithMessagesAsync(client, 3);
|
||||
var expected = await ReadAllMessagesAsync(client, chat, bob, 100);
|
||||
|
||||
// Второй экземпляр приложения, у которого кэш указывает на закрытый порт.
|
||||
await using var broken = fixture.WithWebHostBuilder(b => b.UseSetting("CACHE_CONNECTION", "127.0.0.1:1"));
|
||||
using var brokenClient = broken.CreateClient();
|
||||
|
||||
for (var i = 0; i < 3; i++)
|
||||
{
|
||||
var response = await GetPageAsync(brokenClient, bob, chat);
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
Assert.Equal("bypass", Header(response, "X-Cache"));
|
||||
}
|
||||
|
||||
Assert.Equal(expected, await ReadAllMessagesAsync(brokenClient, chat, bob, 100));
|
||||
// Запись тоже не зависит от кэша.
|
||||
Assert.Equal(HttpStatusCode.Created, (await SendMessageAsync(brokenClient, bob, chat, "при отказе кэша")).StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UnavailableCache_DoesNotTrustAnonymousRequests()
|
||||
{
|
||||
await using var broken = fixture.WithWebHostBuilder(b => b.UseSetting("CACHE_CONNECTION", "127.0.0.1:1"));
|
||||
using var client = broken.CreateClient();
|
||||
|
||||
var response = await client.GetAsync($"/api/v1/chats/{Guid.NewGuid()}/messages");
|
||||
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
using System.Net;
|
||||
using static Messenger.Api.Tests.ApiHelpers;
|
||||
|
||||
namespace Messenger.Api.Tests;
|
||||
|
||||
[Collection("api")]
|
||||
public class ConcurencyTests(ApiFixture fixture)
|
||||
{
|
||||
[Fact]
|
||||
public async Task Create100MessagesBy10DifferentUsers_Concurrent()
|
||||
{
|
||||
using var client = fixture.CreateClient();
|
||||
var users = new List<TestUser>();
|
||||
for (var i = 0; i < 10; i++)
|
||||
{
|
||||
users.Add(await CreateUserAsync(client));
|
||||
}
|
||||
|
||||
var chat = await CreateChatAsync(client, users[0], users.Skip(1).ToArray());
|
||||
|
||||
var messageTasks = Enumerable.Range(0, 100)
|
||||
.Select(i => SendMessageAsync(client, users[i % 10], chat, $"Message {i + 1} from {users[i % 10].Username}"))
|
||||
.ToList();
|
||||
|
||||
foreach (var response in await Task.WhenAll(messageTasks))
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
|
||||
}
|
||||
|
||||
var messages = await ReadAllMessagesAsync(client, chat, users[0], 7);
|
||||
|
||||
Assert.Equal(100, messages.Count);
|
||||
Assert.Equal(100, messages.Distinct().Count());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RegisterSameUsernameConcurrently_ExactlyOneSucceeds_NoServerErrors()
|
||||
{
|
||||
// Проверяется гарантия уникального индекса, а не скорость железа: очередь хеширования делаем практически
|
||||
// неограниченной по времени (по умолчанию лишние запросы получают 503, см. следующий тест).
|
||||
await using var app = fixture.WithWebHostBuilder(b => b.UseSetting("PASSWORD_HASH_QUEUE_TIMEOUT_SECONDS", "120"));
|
||||
using var client = app.CreateClient();
|
||||
var username = "race" + Guid.NewGuid().ToString("N")[..10];
|
||||
|
||||
var attempts = Enumerable.Range(0, 20).Select(_ => client.PostAsync("/api/v1/users",
|
||||
Json($$"""{"username":"{{username}}","display_name":"Гонка","password":"{{DefaultPassword}}"}""")));
|
||||
var statuses = (await Task.WhenAll(attempts)).Select(r => r.StatusCode).ToList();
|
||||
|
||||
Assert.Single(statuses, HttpStatusCode.Created);
|
||||
Assert.Equal(19, statuses.Count(s => s == HttpStatusCode.Conflict));
|
||||
|
||||
await using var db = await fixture.OpenConnectionAsync();
|
||||
await using var count = new Npgsql.NpgsqlCommand("select count(*) from users where username = @u", db);
|
||||
count.Parameters.AddWithValue("u", username);
|
||||
Assert.Equal(1L, await count.ExecuteScalarAsync());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RegistrationBurstBeyondHashingCapacity_GetsBoundedUnavailable_NotServerError()
|
||||
{
|
||||
// Один слот Argon2 и ожидание 50 мс: пачка регистраций разных пользователей упирается в лимит.
|
||||
// Лишние запросы получают 503 unavailable (а не 500 и не зависание), принятые — 201.
|
||||
await using var app = fixture.WithWebHostBuilder(b => b
|
||||
.UseSetting("PASSWORD_HASH_CONCURRENCY", "1")
|
||||
.UseSetting("PASSWORD_HASH_QUEUE_TIMEOUT_SECONDS", "0.05"));
|
||||
using var client = app.CreateClient();
|
||||
var prefix = "burst" + Guid.NewGuid().ToString("N")[..6];
|
||||
|
||||
var responses = await Task.WhenAll(Enumerable.Range(0, 12).Select(i => client.PostAsync("/api/v1/users",
|
||||
Json($$"""{"username":"{{prefix}}_{{i}}","display_name":"Пачка","password":"{{DefaultPassword}}"}"""))));
|
||||
var statuses = responses.Select(r => r.StatusCode).ToList();
|
||||
|
||||
Assert.All(statuses, s => Assert.True(s is HttpStatusCode.Created or HttpStatusCode.ServiceUnavailable, $"неожиданный статус {s}"));
|
||||
Assert.Contains(HttpStatusCode.Created, statuses);
|
||||
Assert.Contains(HttpStatusCode.ServiceUnavailable, statuses);
|
||||
var rejected = responses.First(r => r.StatusCode == HttpStatusCode.ServiceUnavailable);
|
||||
Assert.Equal("unavailable", await ErrorCodeAsync(rejected));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,192 @@
|
||||
using System.Diagnostics;
|
||||
using System.Net;
|
||||
using System.Net.Sockets;
|
||||
using Microsoft.AspNetCore.Mvc.Testing;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Testcontainers.PostgreSql;
|
||||
using static Messenger.Api.Tests.ApiHelpers;
|
||||
|
||||
namespace Messenger.Api.Tests;
|
||||
|
||||
[Collection("api")]
|
||||
public class DependencyFailureTests(ApiFixture fixture)
|
||||
{
|
||||
private static int FreePort()
|
||||
{
|
||||
using var listener = new TcpListener(IPAddress.Loopback, 0);
|
||||
listener.Start();
|
||||
return ((IPEndPoint)listener.LocalEndpoint).Port;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DatabaseDown_Returns503_NeverTrustsAnonymous_AndRecovers()
|
||||
{
|
||||
// Отдельный контейнер БД, который тест останавливает и запускает снова на том же порту.
|
||||
var port = FreePort();
|
||||
await using var pg = new PostgreSqlBuilder().WithImage(ApiFixture.PostgresImage).WithPortBinding(port, 5432).Build();
|
||||
await pg.StartAsync();
|
||||
var file = ApiFixture.WriteConnectionFile(pg.GetConnectionString());
|
||||
try
|
||||
{
|
||||
await using var app = fixture.WithWebHostBuilder(b => b
|
||||
.UseSetting("DATABASE_URL_FILE", file)
|
||||
.UseSetting("DB_CONNECT_TIMEOUT_SECONDS", "2"));
|
||||
using var client = app.CreateClient();
|
||||
var user = await CreateUserAsync(client);
|
||||
using (var ok = Request(HttpMethod.Get, "/api/v1/users/me", user))
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.OK, (await client.SendAsync(ok)).StatusCode);
|
||||
}
|
||||
|
||||
await pg.StopAsync();
|
||||
|
||||
// Аутентифицированный запрос: ограниченная ошибка 503 без внутренних деталей.
|
||||
using var down = Request(HttpMethod.Get, "/api/v1/users/me", user);
|
||||
var downResponse = await client.SendAsync(down);
|
||||
Assert.Equal(HttpStatusCode.ServiceUnavailable, downResponse.StatusCode);
|
||||
Assert.Equal("unavailable", await ErrorCodeAsync(downResponse));
|
||||
var body = await downResponse.Content.ReadAsStringAsync();
|
||||
Assert.DoesNotContain("Npgsql", body);
|
||||
Assert.DoesNotContain("Host=", body);
|
||||
Assert.True(downResponse.Headers.Contains("X-Request-Id"));
|
||||
|
||||
// Анонимный запрос не становится доверенным: без токена по-прежнему 401, а не 200/503 «как гость».
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, (await client.GetAsync("/api/v1/chats")).StatusCode);
|
||||
// Токен, который нельзя проверить, не принимается.
|
||||
Assert.Equal(HttpStatusCode.ServiceUnavailable,
|
||||
(await LoginAsync(client, user.Username, user.Password)).StatusCode);
|
||||
// Готовность отражает отказ, живость — нет.
|
||||
Assert.Equal(HttpStatusCode.ServiceUnavailable, (await client.GetAsync("/health/ready")).StatusCode);
|
||||
Assert.Equal(HttpStatusCode.OK, (await client.GetAsync("/health/live")).StatusCode);
|
||||
|
||||
// Восстановление: после запуска БД тот же токен снова работает (данные не потеряны), без перезапуска API.
|
||||
await pg.StartAsync();
|
||||
var recovered = false;
|
||||
var started = Stopwatch.StartNew();
|
||||
while (started.Elapsed < TimeSpan.FromSeconds(30) && !recovered)
|
||||
{
|
||||
using var retry = Request(HttpMethod.Get, "/api/v1/users/me", user);
|
||||
recovered = (await client.SendAsync(retry)).StatusCode == HttpStatusCode.OK;
|
||||
if (!recovered)
|
||||
{
|
||||
await Task.Delay(500);
|
||||
}
|
||||
}
|
||||
|
||||
Assert.True(recovered, "API не восстановился после возврата PostgreSQL");
|
||||
}
|
||||
finally
|
||||
{
|
||||
File.Delete(file);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExhaustedConnectionPool_ReturnsBoundedError()
|
||||
{
|
||||
using var setup = fixture.CreateClient();
|
||||
var user = await CreateUserAsync(setup);
|
||||
|
||||
// Пул из одного соединения и короткое ожидание: пока тест держит единственное соединение, запросы не зависают.
|
||||
await using var app = fixture.WithWebHostBuilder(b => b
|
||||
.UseSetting("DB_MAX_POOL_SIZE", "1")
|
||||
.UseSetting("DB_CONNECT_TIMEOUT_SECONDS", "1"));
|
||||
using var client = app.CreateClient();
|
||||
|
||||
using var scope = app.Services.CreateScope();
|
||||
var held = scope.ServiceProvider.GetRequiredService<Data.MessengerDbContext>();
|
||||
await held.Database.OpenConnectionAsync();
|
||||
try
|
||||
{
|
||||
var started = Stopwatch.StartNew();
|
||||
using var request = Request(HttpMethod.Get, "/api/v1/users/me", user);
|
||||
var response = await client.SendAsync(request);
|
||||
started.Stop();
|
||||
|
||||
Assert.Equal(HttpStatusCode.ServiceUnavailable, response.StatusCode);
|
||||
Assert.True(started.Elapsed < TimeSpan.FromSeconds(6), $"ответ занял {started.Elapsed}");
|
||||
}
|
||||
finally
|
||||
{
|
||||
await held.Database.CloseConnectionAsync();
|
||||
}
|
||||
|
||||
// После освобождения соединения сервис работает.
|
||||
using var after = Request(HttpMethod.Get, "/api/v1/users/me", user);
|
||||
Assert.Equal(HttpStatusCode.OK, (await client.SendAsync(after)).StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task FailedMessageInsert_RollsBackVersionAndTimestamp()
|
||||
{
|
||||
using var client = fixture.CreateClient();
|
||||
var alice = await CreateUserAsync(client);
|
||||
var chat = await CreateChatAsync(client, alice);
|
||||
Assert.Equal(HttpStatusCode.Created, (await SendMessageAsync(client, alice, chat, "до сбоя")).StatusCode);
|
||||
|
||||
var marker = "boom-" + Guid.NewGuid().ToString("N");
|
||||
var suffix = Guid.NewGuid().ToString("N")[..8];
|
||||
// Сбой «после UPDATE чата, во время INSERT сообщения»: триггер БД отклоняет сообщение с маркером.
|
||||
await fixture.ExecuteAsync($$"""
|
||||
CREATE FUNCTION fail_{{suffix}}() RETURNS trigger LANGUAGE plpgsql AS $$
|
||||
BEGIN IF NEW.text = '{{marker}}' THEN RAISE EXCEPTION 'injected failure'; END IF; RETURN NEW; END $$;
|
||||
CREATE TRIGGER tr_{{suffix}} BEFORE INSERT ON messages FOR EACH ROW EXECUTE FUNCTION fail_{{suffix}}();
|
||||
""");
|
||||
try
|
||||
{
|
||||
var versionBefore = await fixture.ScalarAsync<long>("select history_version from chats where id = @c", ("c", chat));
|
||||
var lastBefore = await fixture.ScalarAsync<DateTime?>("select last_message_at from chats where id = @c", ("c", chat));
|
||||
|
||||
var failed = await SendMessageAsync(client, alice, chat, marker);
|
||||
|
||||
Assert.Equal(HttpStatusCode.InternalServerError, failed.StatusCode);
|
||||
var body = await failed.Content.ReadAsStringAsync();
|
||||
Assert.Contains("internal_error", body);
|
||||
Assert.DoesNotContain("injected", body); // внутренние детали не раскрываются
|
||||
Assert.Equal(versionBefore, await fixture.ScalarAsync<long>("select history_version from chats where id = @c", ("c", chat)));
|
||||
Assert.Equal(lastBefore, await fixture.ScalarAsync<DateTime?>("select last_message_at from chats where id = @c", ("c", chat)));
|
||||
Assert.Equal(1L, await fixture.ScalarAsync<long>("select count(*) from messages where chat_id = @c", ("c", chat)));
|
||||
|
||||
// Блокировка строки чата снята, следующая запись проходит и версия растёт ровно на 1.
|
||||
Assert.Equal(HttpStatusCode.Created, (await SendMessageAsync(client, alice, chat, "после сбоя")).StatusCode);
|
||||
Assert.Equal(versionBefore + 1, await fixture.ScalarAsync<long>("select history_version from chats where id = @c", ("c", chat)));
|
||||
}
|
||||
finally
|
||||
{
|
||||
await fixture.ExecuteAsync($"DROP TRIGGER tr_{suffix} ON messages; DROP FUNCTION fail_{suffix}();");
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task FailedChatMemberInsert_RollsBackWholeChat()
|
||||
{
|
||||
using var client = fixture.CreateClient();
|
||||
var alice = await CreateUserAsync(client);
|
||||
var bob = await CreateUserAsync(client);
|
||||
var suffix = Guid.NewGuid().ToString("N")[..8];
|
||||
var title = "rollback-" + suffix;
|
||||
|
||||
// Сбой при добавлении второго участника, уже после вставки строки чата и первого участника.
|
||||
await fixture.ExecuteAsync($$"""
|
||||
CREATE FUNCTION fail_{{suffix}}() RETURNS trigger LANGUAGE plpgsql AS $$
|
||||
BEGIN IF NEW.user_id = '{{bob.Id}}' THEN RAISE EXCEPTION 'injected failure'; END IF; RETURN NEW; END $$;
|
||||
CREATE TRIGGER tr_{{suffix}} BEFORE INSERT ON chat_members FOR EACH ROW EXECUTE FUNCTION fail_{{suffix}}();
|
||||
""");
|
||||
try
|
||||
{
|
||||
using var request = Request(HttpMethod.Post, "/api/v1/chats", alice,
|
||||
Json($$"""{"title":"{{title}}","member_ids":["{{alice.Id}}","{{bob.Id}}"]}"""));
|
||||
var response = await client.SendAsync(request);
|
||||
|
||||
Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);
|
||||
Assert.Equal(0L, await fixture.ScalarAsync<long>("select count(*) from chats where title = @t", ("t", title)));
|
||||
Assert.Equal(0L, await fixture.ScalarAsync<long>(
|
||||
"select count(*) from chat_members where user_id in (@a, @b) ", ("a", alice.Id), ("b", bob.Id)));
|
||||
}
|
||||
finally
|
||||
{
|
||||
await fixture.ExecuteAsync($"DROP TRIGGER tr_{suffix} ON chat_members; DROP FUNCTION fail_{suffix}();");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
using System.Net;
|
||||
|
||||
namespace Messenger.Api.Tests;
|
||||
|
||||
[Collection("api")]
|
||||
public class HealthTests(ApiFixture fixture)
|
||||
{
|
||||
[Fact]
|
||||
public async Task Live_ReturnsOk()
|
||||
{
|
||||
using var client = fixture.CreateClient();
|
||||
|
||||
var response = await client.GetAsync("/health/live");
|
||||
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Ready_ReturnsOkWhenDatabaseIsAvailable()
|
||||
{
|
||||
using var client = fixture.CreateClient();
|
||||
|
||||
var response = await client.GetAsync("/health/ready");
|
||||
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
Assert.True(response.Headers.Contains("X-Request-Id"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,261 @@
|
||||
using System.Net;
|
||||
using static Messenger.Api.Tests.ApiHelpers;
|
||||
|
||||
namespace Messenger.Api.Tests;
|
||||
|
||||
// lab3: общая идемпотентность отправки сообщения. «Разные реплики» в тесте моделируются разными экземплярами приложения
|
||||
// (fixture.WithWebHostBuilder) с общей PostgreSQL — ровно так же, как в Compose работают реплики за балансировщиком.
|
||||
[Collection("api")]
|
||||
public class IdempotencyTests(ApiFixture fixture)
|
||||
{
|
||||
private static string NewKey() => Guid.NewGuid().ToString("N");
|
||||
|
||||
private static async Task<int> CountMessagesAsync(HttpClient client, Guid chat, TestUser user) =>
|
||||
(await ReadAllMessagesAsync(client, chat, user, 100)).Count;
|
||||
|
||||
[Fact]
|
||||
public async Task Replay_ReturnsSameCodeAndSameMessage_WithoutDuplicate()
|
||||
{
|
||||
using var client = fixture.CreateClient();
|
||||
var alice = await CreateUserAsync(client);
|
||||
var chat = await CreateChatAsync(client, alice);
|
||||
var key = NewKey();
|
||||
|
||||
var first = await SendMessageAsync(client, alice, chat, "привет", key);
|
||||
var second = await SendMessageAsync(client, alice, chat, "привет", key);
|
||||
|
||||
Assert.Equal(HttpStatusCode.Created, first.StatusCode);
|
||||
Assert.Equal(HttpStatusCode.Created, second.StatusCode);
|
||||
Assert.Equal((await ReadJsonAsync(first)).ToString(), (await ReadJsonAsync(second)).ToString());
|
||||
Assert.Equal(1, await CountMessagesAsync(client, chat, alice));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SameKeyDifferentBody_Conflict_AndOriginalIsKept()
|
||||
{
|
||||
using var client = fixture.CreateClient();
|
||||
var alice = await CreateUserAsync(client);
|
||||
var chat = await CreateChatAsync(client, alice);
|
||||
var key = NewKey();
|
||||
|
||||
await SendMessageAsync(client, alice, chat, "первое", key);
|
||||
var other = await SendMessageAsync(client, alice, chat, "второе", key);
|
||||
|
||||
Assert.Equal(HttpStatusCode.Conflict, other.StatusCode);
|
||||
Assert.Equal("conflict", await ErrorCodeAsync(other));
|
||||
Assert.Equal(1, await CountMessagesAsync(client, chat, alice));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(null)]
|
||||
[InlineData("")]
|
||||
[InlineData("has space")]
|
||||
[InlineData("кириллица")]
|
||||
public async Task MissingOrInvalidKey_BadRequest(string? key)
|
||||
{
|
||||
using var client = fixture.CreateClient();
|
||||
var alice = await CreateUserAsync(client);
|
||||
var chat = await CreateChatAsync(client, alice);
|
||||
|
||||
using var request = Request(HttpMethod.Post, $"/api/v1/chats/{chat}/messages", alice,
|
||||
Json("""{"text":"x"}"""));
|
||||
if (key is not null)
|
||||
{
|
||||
request.Headers.TryAddWithoutValidation("Idempotency-Key", key);
|
||||
}
|
||||
|
||||
var response = await client.SendAsync(request);
|
||||
|
||||
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
|
||||
Assert.Equal(0, await CountMessagesAsync(client, chat, alice));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task KeyTooLong_BadRequest_ButMaxLengthAccepted()
|
||||
{
|
||||
using var client = fixture.CreateClient();
|
||||
var alice = await CreateUserAsync(client);
|
||||
var chat = await CreateChatAsync(client, alice);
|
||||
|
||||
var tooLong = await SendMessageAsync(client, alice, chat, "x", new string('a', 129));
|
||||
var maxLength = await SendMessageAsync(client, alice, chat, "x", new string('a', 128));
|
||||
|
||||
Assert.Equal(HttpStatusCode.BadRequest, tooLong.StatusCode);
|
||||
Assert.Equal(HttpStatusCode.Created, maxLength.StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SameKeyIsIndependent_ForDifferentUsersAndDifferentChats()
|
||||
{
|
||||
using var client = fixture.CreateClient();
|
||||
var alice = await CreateUserAsync(client);
|
||||
var bob = await CreateUserAsync(client);
|
||||
var chat1 = await CreateChatAsync(client, alice, bob);
|
||||
var chat2 = await CreateChatAsync(client, alice, bob);
|
||||
var key = NewKey();
|
||||
|
||||
var statuses = new[]
|
||||
{
|
||||
(await SendMessageAsync(client, alice, chat1, "a1", key)).StatusCode,
|
||||
(await SendMessageAsync(client, bob, chat1, "b1", key)).StatusCode,
|
||||
(await SendMessageAsync(client, alice, chat2, "a2", key)).StatusCode,
|
||||
};
|
||||
|
||||
Assert.All(statuses, s => Assert.Equal(HttpStatusCode.Created, s));
|
||||
Assert.Equal(2, await CountMessagesAsync(client, chat1, alice));
|
||||
Assert.Equal(1, await CountMessagesAsync(client, chat2, alice));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Replay_StillRequiresValidSessionAndAccess()
|
||||
{
|
||||
using var client = fixture.CreateClient();
|
||||
var alice = await CreateUserAsync(client);
|
||||
var eve = await CreateUserAsync(client);
|
||||
var chat = await CreateChatAsync(client, alice);
|
||||
var key = NewKey();
|
||||
await SendMessageAsync(client, alice, chat, "секрет", key);
|
||||
|
||||
// Посторонний не может «прочитать» чужой результат по ключу; без токена — 401.
|
||||
var asEve = await SendMessageAsync(client, eve, chat, "секрет", key);
|
||||
using var anonymous = Request(HttpMethod.Post, $"/api/v1/chats/{chat}/messages", null, Json("""{"text":"секрет"}"""));
|
||||
anonymous.Headers.Add("Idempotency-Key", key);
|
||||
var noToken = await client.SendAsync(anonymous);
|
||||
|
||||
Assert.Equal(HttpStatusCode.NotFound, asEve.StatusCode);
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, noToken.StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ConcurrentReplays_OnOneInstance_CreateExactlyOneMessage()
|
||||
{
|
||||
using var client = fixture.CreateClient();
|
||||
var alice = await CreateUserAsync(client);
|
||||
var chat = await CreateChatAsync(client, alice);
|
||||
var key = NewKey();
|
||||
|
||||
var responses = await Task.WhenAll(Enumerable.Range(0, 30)
|
||||
.Select(_ => Task.Run(() => SendMessageAsync(client, alice, chat, "гонка", key))));
|
||||
|
||||
Assert.All(responses, r => Assert.Equal(HttpStatusCode.Created, r.StatusCode));
|
||||
var ids = await Task.WhenAll(responses.Select(async r => (await ReadJsonAsync(r)).GetProperty("id").GetGuid()));
|
||||
Assert.Single(ids.Distinct());
|
||||
Assert.Equal(1, await CountMessagesAsync(client, chat, alice));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ConcurrentReplays_ThroughDifferentInstances_CreateExactlyOneMessage()
|
||||
{
|
||||
// Три независимых экземпляра приложения (как три реплики) с общей PostgreSQL.
|
||||
await using var replicaB = fixture.WithWebHostBuilder(b => b.UseSetting("INSTANCE_ID", "replica-b"));
|
||||
await using var replicaC = fixture.WithWebHostBuilder(b => b.UseSetting("INSTANCE_ID", "replica-c"));
|
||||
using var a = fixture.CreateClient();
|
||||
using var b = replicaB.CreateClient();
|
||||
using var c = replicaC.CreateClient();
|
||||
|
||||
var alice = await CreateUserAsync(a); // сессия создана на A и действует на B и C: сессии общие
|
||||
var chat = await CreateChatAsync(a, alice);
|
||||
var clients = new[] { a, b, c };
|
||||
|
||||
for (var round = 0; round < 5; round++)
|
||||
{
|
||||
var key = NewKey();
|
||||
var responses = await Task.WhenAll(Enumerable.Range(0, 30)
|
||||
.Select(i => Task.Run(() => SendMessageAsync(clients[i % 3], alice, chat, $"гонка {round}", key))));
|
||||
|
||||
Assert.All(responses, r => Assert.Equal(HttpStatusCode.Created, r.StatusCode));
|
||||
var ids = await Task.WhenAll(responses.Select(async r => (await ReadJsonAsync(r)).GetProperty("id").GetGuid()));
|
||||
Assert.Single(ids.Distinct());
|
||||
}
|
||||
|
||||
Assert.Equal(5, await CountMessagesAsync(b, chat, alice));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ConcurrentSameKeyWithDifferentBodies_ExactlyOneWins_OthersConflict()
|
||||
{
|
||||
using var client = fixture.CreateClient();
|
||||
var alice = await CreateUserAsync(client);
|
||||
var chat = await CreateChatAsync(client, alice);
|
||||
var key = NewKey();
|
||||
|
||||
var responses = await Task.WhenAll(Enumerable.Range(0, 10)
|
||||
.Select(i => Task.Run(() => SendMessageAsync(client, alice, chat, $"вариант {i}", key))));
|
||||
|
||||
var created = responses.Count(r => r.StatusCode == HttpStatusCode.Created);
|
||||
var conflicts = responses.Count(r => r.StatusCode == HttpStatusCode.Conflict);
|
||||
Assert.True(created >= 1 && created + conflicts == 10, $"created={created}, conflicts={conflicts}");
|
||||
Assert.Equal(1, await CountMessagesAsync(client, chat, alice));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task FailedWrite_IsNotRemembered_AndCanBeRetriedWithSameKey()
|
||||
{
|
||||
using var client = fixture.CreateClient();
|
||||
var alice = await CreateUserAsync(client);
|
||||
var chat = await CreateChatAsync(client, alice);
|
||||
var key = NewKey();
|
||||
|
||||
// Принудительная ошибка БД при вставке сообщения: транзакция (вместе с ключом) откатывается.
|
||||
var suffix = Guid.NewGuid().ToString("N")[..8];
|
||||
await fixture.ExecuteAsync($$"""
|
||||
CREATE FUNCTION fail_idem_{{suffix}}() RETURNS trigger AS $$ BEGIN RAISE EXCEPTION 'forced failure' USING ERRCODE = '53000'; END $$ LANGUAGE plpgsql;
|
||||
CREATE TRIGGER tr_idem_{{suffix}} BEFORE INSERT ON messages FOR EACH ROW WHEN (NEW.chat_id = '{{chat}}') EXECUTE FUNCTION fail_idem_{{suffix}}();
|
||||
""");
|
||||
try
|
||||
{
|
||||
var failed = await SendMessageAsync(client, alice, chat, "повторимо", key);
|
||||
Assert.True((int)failed.StatusCode >= 500, $"expected 5xx, got {(int)failed.StatusCode}");
|
||||
Assert.Equal(0L, await fixture.ScalarAsync<long>("select count(*) from idempotency_keys where chat_id = @c", ("c", chat)));
|
||||
}
|
||||
finally
|
||||
{
|
||||
await fixture.ExecuteAsync($"DROP TRIGGER tr_idem_{suffix} ON messages; DROP FUNCTION fail_idem_{suffix}();");
|
||||
}
|
||||
|
||||
var retried = await SendMessageAsync(client, alice, chat, "повторимо", key);
|
||||
var again = await SendMessageAsync(client, alice, chat, "повторимо", key);
|
||||
|
||||
Assert.Equal(HttpStatusCode.Created, retried.StatusCode);
|
||||
Assert.Equal(HttpStatusCode.Created, again.StatusCode);
|
||||
Assert.Equal(1, await CountMessagesAsync(client, chat, alice));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExpiredKey_CanBeReused_AsNewMessage()
|
||||
{
|
||||
await using var shortTtl = fixture.WithWebHostBuilder(b => b.UseSetting("IDEMPOTENCY_TTL_SECONDS", "1"));
|
||||
using var client = shortTtl.CreateClient();
|
||||
var alice = await CreateUserAsync(client);
|
||||
var chat = await CreateChatAsync(client, alice);
|
||||
var key = NewKey();
|
||||
|
||||
var first = await SendMessageAsync(client, alice, chat, "срок", key);
|
||||
await Task.Delay(TimeSpan.FromMilliseconds(1500));
|
||||
var second = await SendMessageAsync(client, alice, chat, "срок", key);
|
||||
|
||||
Assert.Equal(HttpStatusCode.Created, first.StatusCode);
|
||||
Assert.Equal(HttpStatusCode.Created, second.StatusCode);
|
||||
Assert.NotEqual(
|
||||
(await ReadJsonAsync(first)).GetProperty("id").GetGuid(),
|
||||
(await ReadJsonAsync(second)).GetProperty("id").GetGuid());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EveryResponse_HasInstanceId_IncludingErrorsAndHealth()
|
||||
{
|
||||
await using var replica = fixture.WithWebHostBuilder(b => b.UseSetting("INSTANCE_ID", "replica-x"));
|
||||
using var client = replica.CreateClient();
|
||||
|
||||
var health = await client.GetAsync("/health/live");
|
||||
var ready = await client.GetAsync("/health/ready");
|
||||
var unauthorized = await client.GetAsync("/api/v1/users/me");
|
||||
var notFound = await client.GetAsync("/no/such/route");
|
||||
var badJson = await client.PostAsync("/api/v1/users", Json("{broken"));
|
||||
|
||||
foreach (var response in new[] { health, ready, unauthorized, notFound, badJson })
|
||||
{
|
||||
Assert.Equal("replica-x", Assert.Single(response.Headers.GetValues("X-Instance-Id")));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<IsPackable>false</IsPackable>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="coverlet.collector" Version="6.0.4" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" Version="10.0.12" />
|
||||
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.14.1" />
|
||||
<PackageReference Include="Testcontainers.PostgreSql" Version="4.16.0" />
|
||||
<PackageReference Include="xunit" Version="2.9.3" />
|
||||
<PackageReference Include="xunit.runner.visualstudio" Version="3.1.4" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\Messenger.Api\Messenger.Api.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Using Include="Xunit" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,69 @@
|
||||
using Messenger.Api.Services;
|
||||
|
||||
namespace Messenger.Api.Tests;
|
||||
|
||||
public class PasswordHasherTests
|
||||
{
|
||||
private readonly Argon2PasswordHasher _hasher = new(new PasswordHashingSettings(4, TimeSpan.FromSeconds(30)));
|
||||
|
||||
[Fact]
|
||||
public async Task Hash_IsArgon2idPhcString_WithoutPlaintext()
|
||||
{
|
||||
var hash = await _hasher.HashAsync("correct horse battery staple", CancellationToken.None);
|
||||
|
||||
Assert.StartsWith("$argon2id$", hash);
|
||||
Assert.DoesNotContain("correct horse", hash);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Hash_UsesRandomSalt()
|
||||
{
|
||||
var a = await _hasher.HashAsync("same-password-123", CancellationToken.None);
|
||||
var b = await _hasher.HashAsync("same-password-123", CancellationToken.None);
|
||||
|
||||
Assert.NotEqual(a, b);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("correct horse battery staple")]
|
||||
[InlineData("пароль-с-юникодом-и:двоеточием-12")]
|
||||
public async Task Verify_AcceptsCorrect_RejectsWrong(string password)
|
||||
{
|
||||
var hash = await _hasher.HashAsync(password, CancellationToken.None);
|
||||
|
||||
Assert.True(await _hasher.VerifyAsync(hash, password, CancellationToken.None));
|
||||
Assert.False(await _hasher.VerifyAsync(hash, password + "x", CancellationToken.None));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Verify_DoesNotTruncateLongPasswords()
|
||||
{
|
||||
// Это ограничение bcrypt (72 байта); Argon2id его не имеет. Пароли отличаются только хвостом.
|
||||
var prefix = new string('я', 60); // 120 байт в UTF-8
|
||||
var hash = await _hasher.HashAsync(prefix + "A", CancellationToken.None);
|
||||
|
||||
Assert.False(await _hasher.VerifyAsync(hash, prefix + "B", CancellationToken.None));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Hash_WhenAllSlotsAreBusy_FailsWithBusyException()
|
||||
{
|
||||
// Один слот и почти нулевое ожидание: параллельные вызовы не копят память, лишние получают исключение (→ 503).
|
||||
var hasher = new Argon2PasswordHasher(new PasswordHashingSettings(1, TimeSpan.FromMilliseconds(20)));
|
||||
|
||||
var attempts = await Task.WhenAll(Enumerable.Range(0, 6).Select(async _ =>
|
||||
{
|
||||
try { await hasher.HashAsync("some-long-enough-password", CancellationToken.None); return true; }
|
||||
catch (PasswordHasherBusyException) { return false; }
|
||||
}));
|
||||
|
||||
Assert.Contains(true, attempts); // кто-то получил слот
|
||||
Assert.Contains(false, attempts); // остальные получили контролируемый отказ
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Verify_UnknownUser_ReturnsFalse()
|
||||
{
|
||||
Assert.False(await _hasher.VerifyAsync(null, "any-password-123", CancellationToken.None));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,211 @@
|
||||
using System.Net;
|
||||
using Amazon.S3;
|
||||
using Messenger.Api.Data;
|
||||
using Messenger.Api.Services;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Diagnostics;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using static Messenger.Api.Tests.ApiHelpers;
|
||||
|
||||
namespace Messenger.Api.Tests;
|
||||
|
||||
[Collection("api")]
|
||||
public class UploadCleanupTests(ApiFixture fixture)
|
||||
{
|
||||
private static byte[] Png => File.ReadAllBytes(Path.Combine(FindRoot(), "tests/fixtures/sample.png"));
|
||||
private static string FindRoot()
|
||||
{
|
||||
var dir = new DirectoryInfo(AppContext.BaseDirectory);
|
||||
while (dir is not null && !File.Exists(Path.Combine(dir.FullName, "lab.json"))) dir = dir.Parent;
|
||||
return dir?.FullName ?? throw new InvalidOperationException("Repository root missing");
|
||||
}
|
||||
|
||||
private static async Task<HttpResponseMessage> Upload(HttpClient client, TestUser user, Guid chat, string filename)
|
||||
{
|
||||
using var content = new ByteArrayContent(Png);
|
||||
content.Headers.ContentType = new("image/png");
|
||||
using var request = Request(HttpMethod.Post, $"/api/v1/chats/{chat}/attachments?filename={filename}", user, content);
|
||||
return await client.SendAsync(request);
|
||||
}
|
||||
|
||||
private sealed class MetadataFailure : SaveChangesInterceptor
|
||||
{
|
||||
public override ValueTask<InterceptionResult<int>> SavingChangesAsync(DbContextEventData data,
|
||||
InterceptionResult<int> result, CancellationToken ct = default)
|
||||
{
|
||||
if (data.Context!.ChangeTracker.Entries<AttachmentEntity>().Any(e => e.State == EntityState.Added))
|
||||
throw new InvalidOperationException("injected metadata commit failure");
|
||||
return ValueTask.FromResult(result);
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class StorageDecorator(IAttachmentStorage inner) : IAttachmentStorage, IDisposable
|
||||
{
|
||||
public bool FailDelete { get; set; }
|
||||
public Func<string, Task>? AfterPut { get; set; }
|
||||
public Task CheckAsync(CancellationToken ct) => inner.CheckAsync(ct);
|
||||
public async Task PutAsync(string key, Stream content, string mime, CancellationToken ct)
|
||||
{ await inner.PutAsync(key, content, mime, ct); if (AfterPut is not null) await AfterPut(key); }
|
||||
public Task CopyToAsync(string key, Stream output, CancellationToken ct) => inner.CopyToAsync(key, output, ct);
|
||||
public Task DeleteAsync(string key, CancellationToken ct) => FailDelete
|
||||
? throw new HttpRequestException("injected S3 outage") : inner.DeleteAsync(key, ct);
|
||||
public void Dispose() => (inner as IDisposable)?.Dispose();
|
||||
}
|
||||
|
||||
private async Task<UploadIntentEntity> Seed(IServiceProvider services, bool expired = true)
|
||||
{
|
||||
using var scope = services.CreateScope();
|
||||
var db = scope.ServiceProvider.GetRequiredService<MessengerDbContext>();
|
||||
var id = Guid.NewGuid();
|
||||
var now = Timestamps.UtcNowMilliseconds();
|
||||
var intent = new UploadIntentEntity { Id = id, ObjectKey = $"originals/{id:N}", CreatedAt = now,
|
||||
ExpiresAt = expired ? now.AddMinutes(-1) : now.AddMinutes(5), NextAttemptAt = expired ? now.AddMinutes(-1) : now.AddMinutes(5) };
|
||||
db.UploadIntents.Add(intent);
|
||||
await db.SaveChangesAsync();
|
||||
await scope.ServiceProvider.GetRequiredService<IAttachmentStorage>().PutAsync(intent.ObjectKey,
|
||||
new MemoryStream(Png), "image/png", CancellationToken.None);
|
||||
return intent;
|
||||
}
|
||||
|
||||
private static async Task AssertMissing(IServiceProvider services, string key)
|
||||
{
|
||||
var storage = services.GetRequiredService<IAttachmentStorage>();
|
||||
var error = await Assert.ThrowsAnyAsync<AmazonS3Exception>(() => storage.CopyToAsync(key, Stream.Null, CancellationToken.None));
|
||||
Assert.Equal(HttpStatusCode.NotFound, error.StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task MetadataFailureAfterS3Put_SurvivesApiRecreation_AndIsCleaned()
|
||||
{
|
||||
Guid pendingId;
|
||||
string key;
|
||||
var filename = $"fault-{Guid.NewGuid():N}.png";
|
||||
await using (var broken = fixture.WithWebHostBuilder(b => b.ConfigureServices(services =>
|
||||
services.AddDbContext<MessengerDbContext>(options => options.AddInterceptors(new MetadataFailure())))))
|
||||
{
|
||||
using var client = broken.CreateClient();
|
||||
var user = await CreateUserAsync(client);
|
||||
var chat = await CreateChatAsync(client, user);
|
||||
var response = await Upload(client, user, chat, filename);
|
||||
Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);
|
||||
using var scope = broken.Services.CreateScope();
|
||||
var db = scope.ServiceProvider.GetRequiredService<MessengerDbContext>();
|
||||
Assert.False(await db.Attachments.AnyAsync(a => a.Filename == filename));
|
||||
var intent = await db.UploadIntents.OrderByDescending(i => i.CreatedAt).FirstAsync();
|
||||
pendingId = intent.Id; key = intent.ObjectKey;
|
||||
using var output = new MemoryStream();
|
||||
await broken.Services.GetRequiredService<IAttachmentStorage>().CopyToAsync(key, output, CancellationToken.None);
|
||||
Assert.Equal(Png, output.ToArray());
|
||||
}
|
||||
// Новый экземпляр приложения читает тот же устойчивый журнал.
|
||||
await fixture.ExecuteAsync($"UPDATE upload_intents SET expires_at=now()-interval '1 minute', next_attempt_at=now()-interval '1 minute' WHERE id='{pendingId}'");
|
||||
await using var recovered = fixture.WithWebHostBuilder(_ => { });
|
||||
using var recoveredClient = recovered.CreateClient();
|
||||
var deadline = DateTime.UtcNow.AddSeconds(10);
|
||||
while (await fixture.ScalarAsync<int>("SELECT delete_count FROM upload_intents WHERE id=@id",("id",pendingId)) == 0 && DateTime.UtcNow < deadline)
|
||||
await Task.Delay(50);
|
||||
await AssertMissing(recovered.Services, key);
|
||||
Assert.Equal(1L, await fixture.ScalarAsync<long>("SELECT count(*) FROM upload_intents WHERE id=@id AND delete_count>0", ("id",pendingId)));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task FreshIntent_IsProtectedByGracePeriod()
|
||||
{
|
||||
using var client = fixture.CreateClient();
|
||||
var intent = await Seed(fixture.Services, expired: false);
|
||||
await fixture.Services.GetRequiredService<UploadCleanup>().RunOnceAsync(CancellationToken.None);
|
||||
using var result = new MemoryStream();
|
||||
await fixture.Services.GetRequiredService<IAttachmentStorage>().CopyToAsync(intent.ObjectKey, result, CancellationToken.None);
|
||||
Assert.Equal(Png, result.ToArray());
|
||||
Assert.Equal(0, await fixture.ScalarAsync<int>("SELECT delete_count FROM upload_intents WHERE id=@id",("id",intent.Id)));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task PublishedAttachment_IsNeverDeleted_EvenWithAnExpiredIntent()
|
||||
{
|
||||
using var client = fixture.CreateClient();
|
||||
var user = await CreateUserAsync(client);
|
||||
var chat = await CreateChatAsync(client, user);
|
||||
var response = await Upload(client, user, chat, "protected.png");
|
||||
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
|
||||
var id = (await ReadJsonAsync(response)).GetProperty("id").GetGuid();
|
||||
using var scope = fixture.Services.CreateScope();
|
||||
var db = scope.ServiceProvider.GetRequiredService<MessengerDbContext>();
|
||||
var attachment = await db.Attachments.SingleAsync(a => a.Id == id);
|
||||
var old = DateTimeOffset.UtcNow.AddMinutes(-1);
|
||||
db.UploadIntents.Add(new() { Id = id, ObjectKey = attachment.ObjectKey, CreatedAt = old, ExpiresAt = old, NextAttemptAt = old });
|
||||
await db.SaveChangesAsync();
|
||||
var cleanup = await fixture.Services.GetRequiredService<UploadCleanup>().RunOnceAsync(CancellationToken.None);
|
||||
Assert.True(cleanup.Protected >= 1);
|
||||
using var request = Request(HttpMethod.Get,$"/api/v1/attachments/{id}/content",user);
|
||||
Assert.Equal(Png, await (await client.SendAsync(request)).Content.ReadAsByteArrayAsync());
|
||||
Assert.False(await db.UploadIntents.AsNoTracking().AnyAsync(i => i.Id == id));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CleanupRetriesAfterS3Failure_AndDeletesALatePutAgain()
|
||||
{
|
||||
StorageDecorator? decorator = null;
|
||||
await using var app = fixture.WithWebHostBuilder(b => b.ConfigureServices(services =>
|
||||
services.AddSingleton<IAttachmentStorage>(sp => decorator = new(new S3AttachmentStorage(sp.GetRequiredService<S3Settings>())))));
|
||||
using var client = app.CreateClient();
|
||||
var intent = await Seed(app.Services);
|
||||
decorator!.FailDelete = true;
|
||||
var failed = await app.Services.GetRequiredService<UploadCleanup>().RunOnceAsync(CancellationToken.None);
|
||||
Assert.True(failed.Failed >= 1);
|
||||
Assert.Equal(0, await fixture.ScalarAsync<int>("SELECT delete_count FROM upload_intents WHERE id=@id",("id",intent.Id)));
|
||||
decorator.FailDelete = false;
|
||||
await fixture.ExecuteAsync($"UPDATE upload_intents SET next_attempt_at=now()-interval '1 minute' WHERE id='{intent.Id}'");
|
||||
await app.Services.GetRequiredService<UploadCleanup>().RunOnceAsync(CancellationToken.None);
|
||||
await AssertMissing(app.Services,intent.ObjectKey);
|
||||
// Имитация PUT, завершившегося с задержкой после первого DELETE.
|
||||
await decorator.PutAsync(intent.ObjectKey,new MemoryStream(Png),"image/png",CancellationToken.None);
|
||||
await fixture.ExecuteAsync($"UPDATE upload_intents SET next_attempt_at=now()-interval '1 minute' WHERE id='{intent.Id}'");
|
||||
await app.Services.GetRequiredService<UploadCleanup>().RunOnceAsync(CancellationToken.None);
|
||||
await AssertMissing(app.Services,intent.ObjectKey);
|
||||
Assert.Equal(2, await fixture.ScalarAsync<int>("SELECT delete_count FROM upload_intents WHERE id=@id",("id",intent.Id)));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExpiredUploadCannotPublish_AfterItsLeaseWasRevoked()
|
||||
{
|
||||
await using var app = fixture.WithWebHostBuilder(b => b.ConfigureServices(services =>
|
||||
services.AddSingleton<IAttachmentStorage>(sp => new StorageDecorator(new S3AttachmentStorage(sp.GetRequiredService<S3Settings>()))
|
||||
{ AfterPut = async key =>
|
||||
{
|
||||
var id = Guid.ParseExact(key["originals/".Length..],"N");
|
||||
await fixture.ExecuteAsync($"UPDATE upload_intents SET expires_at=now()-interval '1 minute', next_attempt_at=now()-interval '1 minute' WHERE id='{id}'");
|
||||
}
|
||||
})));
|
||||
using var client = app.CreateClient();
|
||||
var user = await CreateUserAsync(client);
|
||||
var chat = await CreateChatAsync(client,user);
|
||||
var name = $"expired-{Guid.NewGuid():N}.png";
|
||||
Assert.Equal(HttpStatusCode.ServiceUnavailable,(await Upload(client,user,chat,name)).StatusCode);
|
||||
using var scope = app.Services.CreateScope();
|
||||
Assert.False(await scope.ServiceProvider.GetRequiredService<MessengerDbContext>().Attachments.AnyAsync(a=>a.Filename==name));
|
||||
await app.Services.GetRequiredService<UploadCleanup>().RunOnceAsync(CancellationToken.None);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ConcurrentCleaners_ClaimAnIntentOnce()
|
||||
{
|
||||
using var client = fixture.CreateClient();
|
||||
var intent = await Seed(fixture.Services);
|
||||
var cleaner = fixture.Services.GetRequiredService<UploadCleanup>();
|
||||
await Task.WhenAll(cleaner.RunOnceAsync(CancellationToken.None),cleaner.RunOnceAsync(CancellationToken.None));
|
||||
await AssertMissing(fixture.Services,intent.ObjectKey);
|
||||
Assert.Equal(1,await fixture.ScalarAsync<int>("SELECT delete_count FROM upload_intents WHERE id=@id",("id",intent.Id)));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task OldTombstone_RemainsSoALatePutCannotBeForgotten()
|
||||
{
|
||||
using var client = fixture.CreateClient();
|
||||
var intent = await Seed(fixture.Services);
|
||||
await fixture.ExecuteAsync($"UPDATE upload_intents SET expires_at=now()-interval '2 days' WHERE id='{intent.Id}'");
|
||||
await fixture.Services.GetRequiredService<UploadCleanup>().RunOnceAsync(CancellationToken.None);
|
||||
await AssertMissing(fixture.Services,intent.ObjectKey);
|
||||
Assert.Equal(1L,await fixture.ScalarAsync<long>("SELECT count(*) FROM upload_intents WHERE id=@id AND delete_count>0",("id",intent.Id)));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user