253 lines
11 KiB
C#
253 lines
11 KiB
C#
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);
|
|
}
|
|
}
|