Выполнениие лабораторной работы на 5, трек 2.
Skeleton contracts / contracts (pull_request) Canceled after 0s
Skeleton contracts / contracts (pull_request) Canceled after 0s
This commit is contained in:
@@ -0,0 +1,98 @@
|
||||
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;
|
||||
|
||||
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;
|
||||
|
||||
public string ConnectionString => _db.GetConnectionString();
|
||||
public string CacheConnection => $"{_cache.Hostname}:{_cache.GetMappedPublicPort(6379)}";
|
||||
|
||||
public async Task InitializeAsync()
|
||||
{
|
||||
await Task.WhenAll(_db.StartAsync(), _cache.StartAsync());
|
||||
_connectionFile = WriteConnectionFile(_db.GetConnectionString());
|
||||
}
|
||||
|
||||
async Task IAsyncLifetime.DisposeAsync()
|
||||
{
|
||||
await _db.DisposeAsync();
|
||||
await _cache.DisposeAsync();
|
||||
File.Delete(_connectionFile);
|
||||
}
|
||||
|
||||
protected override void ConfigureWebHost(IWebHostBuilder builder)
|
||||
{
|
||||
builder.UseSetting("DATABASE_URL_FILE", _connectionFile);
|
||||
builder.UseSetting("CACHE_CONNECTION", CacheConnection);
|
||||
builder.UseSetting("DIAGNOSTIC_HEADERS", "true");
|
||||
}
|
||||
|
||||
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,101 @@
|
||||
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();
|
||||
}
|
||||
|
||||
public static async Task<HttpResponseMessage> SendMessageAsync(HttpClient client, TestUser sender, Guid chatId, string text)
|
||||
{
|
||||
using var request = Request(HttpMethod.Post, $"/api/v1/chats/{chatId}/messages", sender,
|
||||
JsonContent.Create(new { text }));
|
||||
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,302 @@
|
||||
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}}"}"""));
|
||||
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,54 @@
|
||||
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()
|
||||
{
|
||||
using var client = fixture.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());
|
||||
}
|
||||
}
|
||||
@@ -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,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,53 @@
|
||||
using Messenger.Api.Services;
|
||||
|
||||
namespace Messenger.Api.Tests;
|
||||
|
||||
public class PasswordHasherTests
|
||||
{
|
||||
private readonly Argon2PasswordHasher _hasher = new();
|
||||
|
||||
[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 Verify_UnknownUser_ReturnsFalse()
|
||||
{
|
||||
Assert.False(await _hasher.VerifyAsync(null, "any-password-123", CancellationToken.None));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user