Adds authorization module tests

This commit is contained in:
BinaryAlley committed 2025-01-01 22:56:07 +02:00
1 parent 718e1c49cf
commit 0114ff13e8
125 files changed
+10411 -203

No files matched your search

@@ -0,0 +1,52 @@
#region ========================================================================= USING =====================================================================================
using FluentAssertions;
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
using Microsoft.AspNetCore.Http;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Text.Json;
#endregion
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Admin.Authorization.Permissions;
/// <summary>
/// Contains security tests for the <c>/permissions</c> route.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetPermissionsEndpointTests : IClassFixture<LuminaApiFactory>
{
private readonly HttpClient _client;
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true
};
/// <summary>
/// Initializes a new instance of the <see cref="GetPermissionsTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public GetPermissionsEndpointTests(LuminaApiFactory apiFactory)
{
_client = apiFactory.CreateClient();
}
[Fact]
public async Task GetPermissions_WhenUnauthorized_ShouldReturnUnauthorizedResult()
{
// Act
HttpResponseMessage response = await _client.GetAsync("/api/v1/permissions");
// Assert
response.StatusCode.Should().Be(HttpStatusCode.Unauthorized);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
problemDetails.Should().NotBeNull();
problemDetails!["status"].GetInt32().Should().Be(StatusCodes.Status401Unauthorized);
problemDetails["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc7235#section-3.1");
problemDetails["title"].GetString().Should().Be("Unauthorized");
problemDetails["instance"].GetProperty("value").GetString().Should().Be("/api/v1/permissions");
problemDetails["detail"].GetString().Should().Be("Authentication failed");
}
}
@@ -0,0 +1,61 @@
#region ========================================================================= USING =====================================================================================
using FluentAssertions;
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
using Microsoft.AspNetCore.Http;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Text;
using System.Text.Json;
#endregion
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Admin.Authorization.Roles;
/// <summary>
/// Contains security tests for the <c>/roles</c> route.
/// </summary>
[ExcludeFromCodeCoverage]
public class AddRoleEndpointTests : IClassFixture<LuminaApiFactory>
{
private readonly HttpClient _client;
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true
};
/// <summary>
/// Initializes a new instance of the <see cref="AddRoleEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public AddRoleEndpointTests(LuminaApiFactory apiFactory)
{
_client = apiFactory.CreateClient();
}
[Fact]
public async Task AddRole_WhenUnauthorized_ShouldReturnUnauthorizedResult()
{
// Arrange
var requestBody = new
{
RoleName = "Editor",
Permissions = new[] { Guid.NewGuid(), Guid.NewGuid() }
};
StringContent content = new(JsonSerializer.Serialize(requestBody), Encoding.UTF8, "application/json");
// Act
HttpResponseMessage response = await _client.PostAsync("/api/v1/roles", content);
// Assert
response.StatusCode.Should().Be(HttpStatusCode.Unauthorized);
string responseContent = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(responseContent, _jsonOptions);
problemDetails.Should().NotBeNull();
problemDetails!["status"].GetInt32().Should().Be(StatusCodes.Status401Unauthorized);
problemDetails["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc7235#section-3.1");
problemDetails["title"].GetString().Should().Be("Unauthorized");
problemDetails["instance"].GetProperty("value").GetString().Should().Be("/api/v1/roles");
problemDetails["detail"].GetString().Should().Be("Authentication failed");
}
}
@@ -0,0 +1,56 @@
#region ========================================================================= USING =====================================================================================
using FluentAssertions;
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
using Microsoft.AspNetCore.Http;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Text.Json;
#endregion
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Admin.Authorization.Roles;
/// <summary>
/// Contains security tests for the <c>/roles/{roleId}</c> route.
/// </summary>
[ExcludeFromCodeCoverage]
public class DeleteRoleEndpointTests : IClassFixture<LuminaApiFactory>
{
private readonly HttpClient _client;
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true
};
/// <summary>
/// Initializes a new instance of the <see cref="DeleteRoleEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public DeleteRoleEndpointTests(LuminaApiFactory apiFactory)
{
_client = apiFactory.CreateClient();
}
[Fact]
public async Task DeleteRole_WhenUnauthorized_ShouldReturnUnauthorizedResult()
{
// Arrange
Guid roleId = Guid.NewGuid();
string url = $"/api/v1/roles/{roleId}";
// Act
HttpResponseMessage response = await _client.DeleteAsync(url);
// Assert
response.StatusCode.Should().Be(HttpStatusCode.Unauthorized);
string responseContent = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(responseContent, _jsonOptions);
problemDetails.Should().NotBeNull();
problemDetails!["status"].GetInt32().Should().Be(StatusCodes.Status401Unauthorized);
problemDetails["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc7235#section-3.1");
problemDetails["title"].GetString().Should().Be("Unauthorized");
problemDetails["instance"].GetProperty("value").GetString().Should().Be(url);
problemDetails["detail"].GetString().Should().Be("Authentication failed");
}
}
@@ -0,0 +1,56 @@
#region ========================================================================= USING =====================================================================================
using FluentAssertions;
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
using Microsoft.AspNetCore.Http;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Text.Json;
#endregion
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Admin.Authorization.Roles;
/// <summary>
/// Contains security tests for the <c>/roles/{roleId}/permissions</c> route.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetRolePermissionsEndpointTests : IClassFixture<LuminaApiFactory>
{
private readonly HttpClient _client;
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true
};
/// <summary>
/// Initializes a new instance of the <see cref="GetRolePermissionsEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public GetRolePermissionsEndpointTests(LuminaApiFactory apiFactory)
{
_client = apiFactory.CreateClient();
}
[Fact]
public async Task GetRolePermissions_WhenUnauthorized_ShouldReturnUnauthorizedResult()
{
// Arrange
Guid roleId = Guid.NewGuid();
string url = $"/api/v1/roles/{roleId}/permissions";
// Act
HttpResponseMessage response = await _client.GetAsync(url);
// Assert
response.StatusCode.Should().Be(HttpStatusCode.Unauthorized);
string responseContent = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(responseContent, _jsonOptions);
problemDetails.Should().NotBeNull();
problemDetails!["status"].GetInt32().Should().Be(StatusCodes.Status401Unauthorized);
problemDetails["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc7235#section-3.1");
problemDetails["title"].GetString().Should().Be("Unauthorized");
problemDetails["instance"].GetProperty("value").GetString().Should().Be(url);
problemDetails["detail"].GetString().Should().Be("Authentication failed");
}
}
@@ -0,0 +1,52 @@
#region ========================================================================= USING =====================================================================================
using FluentAssertions;
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
using Microsoft.AspNetCore.Http;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Text.Json;
#endregion
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Admin.Authorization.Roles;
/// <summary>
/// Contains security tests for the <c>/roles</c> route.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetRolesEndpointTests : IClassFixture<LuminaApiFactory>
{
private readonly HttpClient _client;
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true
};
/// <summary>
/// Initializes a new instance of the <see cref="GetRolesEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public GetRolesEndpointTests(LuminaApiFactory apiFactory)
{
_client = apiFactory.CreateClient();
}
[Fact]
public async Task GetRoles_WhenUnauthorized_ShouldReturnUnauthorizedResult()
{
// Act
HttpResponseMessage response = await _client.GetAsync("/api/v1/roles");
// Assert
response.StatusCode.Should().Be(HttpStatusCode.Unauthorized);
string responseContent = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(responseContent, _jsonOptions);
problemDetails.Should().NotBeNull();
problemDetails!["status"].GetInt32().Should().Be(StatusCodes.Status401Unauthorized);
problemDetails["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc7235#section-3.1");
problemDetails["title"].GetString().Should().Be("Unauthorized");
problemDetails["instance"].GetProperty("value").GetString().Should().Be("/api/v1/roles");
problemDetails["detail"].GetString().Should().Be("Authentication failed");
}
}
@@ -0,0 +1,67 @@
#region ========================================================================= USING =====================================================================================
using FluentAssertions;
using Lumina.Contracts.Requests.Authorization;
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
using Microsoft.AspNetCore.Http;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Text;
using System.Text.Json;
#endregion
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Admin.Authorization.Roles;
/// <summary>
/// Contains security tests for the <c>/roles</c> route.
/// </summary>
[ExcludeFromCodeCoverage]
public class UpdateRoleEndpointTests : IClassFixture<LuminaApiFactory>
{
private readonly HttpClient _client;
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true
};
/// <summary>
/// Initializes a new instance of the <see cref="UpdateRoleEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public UpdateRoleEndpointTests(LuminaApiFactory apiFactory)
{
_client = apiFactory.CreateClient();
}
[Fact]
public async Task UpdateRole_WhenUnauthorized_ShouldReturnUnauthorizedResult()
{
// Arrange
UpdateRoleRequest requestBody = new(
RoleId: Guid.NewGuid(),
RoleName: "Editor",
Permissions: []
);
StringContent content = new(
JsonSerializer.Serialize(requestBody),
Encoding.UTF8,
"application/json"
);
// Act
HttpResponseMessage response = await _client.PutAsync("/api/v1/roles", content);
// Assert
response.StatusCode.Should().Be(HttpStatusCode.Unauthorized);
string responseContent = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(responseContent, _jsonOptions);
problemDetails.Should().NotBeNull();
problemDetails!["status"].GetInt32().Should().Be(StatusCodes.Status401Unauthorized);
problemDetails["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc7235#section-3.1");
problemDetails["title"].GetString().Should().Be("Unauthorized");
problemDetails["instance"].GetProperty("value").GetString().Should().Be("/api/v1/roles");
problemDetails["detail"].GetString().Should().Be("Authentication failed");
}
}
@@ -22,7 +22,7 @@ namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.UsersManagement.A
/// Contains security tests for the <c>/auth/change-password</c> route.
/// </summary>
[ExcludeFromCodeCoverage]
public class AuthChangePasswordTests : IClassFixture<LuminaApiFactory>, IDisposable
public class ChangePasswordEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
{
private readonly LuminaApiFactory _apiFactory;
private readonly HttpClient _client;
@@ -34,10 +34,10 @@ public class AuthChangePasswordTests : IClassFixture<LuminaApiFactory>, IDisposa
};
/// <summary>
/// Initializes a new instance of the <see cref="AuthLoginTests"/> class.
/// Initializes a new instance of the <see cref="LoginEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public AuthChangePasswordTests(LuminaApiFactory apiFactory)
public ChangePasswordEndpointTests(LuminaApiFactory apiFactory)
{
_apiFactory = apiFactory;
_client = apiFactory.CreateClient();
@@ -48,7 +48,7 @@ public class AuthChangePasswordTests : IClassFixture<LuminaApiFactory>, IDisposa
}
[Fact]
public async Task ChangePassword_WithoutAuthentication_ShouldReturn401()
public async Task ChangePassword_WithoutAuthentication_ShouldReturnUnauthorizedResult()
{
// Arrange
ChangePasswordRequest request = new(
@@ -106,7 +106,7 @@ public class AuthChangePasswordTests : IClassFixture<LuminaApiFactory>, IDisposa
stdDev.Should().BeLessThan(200);
}
private double CalculateStandardDeviation(List<long> values)
private static double CalculateStandardDeviation(List<long> values)
{
double average = values.Average();
double sumOfSquaresOfDifferences = values.Select(value => (value - average) * (value - average)).Sum();
@@ -0,0 +1,52 @@
#region ========================================================================= USING =====================================================================================
using FluentAssertions;
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
using Microsoft.AspNetCore.Http;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Text.Json;
#endregion
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.UsersManagement.Authentication;
/// <summary>
/// Contains security tests for the <c>/auth/users</c> route.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetUsersEndpointTests : IClassFixture<LuminaApiFactory>
{
private readonly HttpClient _client;
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true
};
/// <summary>
/// Initializes a new instance of the <see cref="GetUsersEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public GetUsersEndpointTests(LuminaApiFactory apiFactory)
{
_client = apiFactory.CreateClient();
}
[Fact]
public async Task GetUsers_WhenUnauthorized_ShouldReturnUnauthorizedResult()
{
// Act
HttpResponseMessage response = await _client.GetAsync("/api/v1/auth/users");
// Assert
response.StatusCode.Should().Be(HttpStatusCode.Unauthorized);
string responseContent = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(responseContent, _jsonOptions);
problemDetails.Should().NotBeNull();
problemDetails!["status"].GetInt32().Should().Be(StatusCodes.Status401Unauthorized);
problemDetails["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc7235#section-3.1");
problemDetails["title"].GetString().Should().Be("Unauthorized");
problemDetails["instance"].GetProperty("value").GetString().Should().Be("/api/v1/auth/users");
problemDetails["detail"].GetString().Should().Be("Authentication failed");
}
}
@@ -25,7 +25,7 @@ namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.UsersManagement.A
/// Contains security tests for the <c>/auth/login</c> route.
/// </summary>
[ExcludeFromCodeCoverage]
public class AuthLoginTests : IClassFixture<LuminaApiFactory>, IDisposable
public class LoginEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
{
private readonly HashService _hashService;
private readonly ICryptographyService _cryptographyService;
@@ -40,10 +40,10 @@ public class AuthLoginTests : IClassFixture<LuminaApiFactory>, IDisposable
private readonly string _testUsername;
/// <summary>
/// Initializes a new instance of the <see cref="AuthLoginTests"/> class.
/// Initializes a new instance of the <see cref="LoginEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public AuthLoginTests(LuminaApiFactory apiFactory)
public LoginEndpointTests(LuminaApiFactory apiFactory)
{
_apiFactory = apiFactory;
_client = apiFactory.CreateClient();
@@ -19,7 +19,7 @@ namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.UsersManagement.A
/// Contains security tests for the <c>/auth/recover-password</c> route.
/// </summary>
[ExcludeFromCodeCoverage]
public class AuthRecoverPasswordTests : IClassFixture<LuminaApiFactory>, IDisposable
public class RecoverPasswordEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
{
private readonly LuminaApiFactory _apiFactory;
private readonly HttpClient _client;
@@ -31,10 +31,10 @@ public class AuthRecoverPasswordTests : IClassFixture<LuminaApiFactory>, IDispos
private readonly string _testUsername;
/// <summary>
/// Initializes a new instance of the <see cref="AuthRecoverPasswordTests"/> class.
/// Initializes a new instance of the <see cref="RecoverPasswordEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public AuthRecoverPasswordTests(LuminaApiFactory apiFactory)
public RecoverPasswordEndpointTests(LuminaApiFactory apiFactory)
{
_apiFactory = apiFactory;
_client = apiFactory.CreateClient();
@@ -21,7 +21,7 @@ namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.UsersManagement.A
/// Contains security tests for the <c>/auth/register</c> route.
/// </summary>
[ExcludeFromCodeCoverage]
public class AuthRegisterTests : IClassFixture<LuminaApiFactory>, IDisposable
public class RegisterEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
{
private readonly HashService _hashService;
private readonly LuminaApiFactory _apiFactory;
@@ -33,7 +33,7 @@ public class AuthRegisterTests : IClassFixture<LuminaApiFactory>, IDisposable
};
private readonly string _testUsername;
public AuthRegisterTests(LuminaApiFactory apiFactory)
public RegisterEndpointTests(LuminaApiFactory apiFactory)
{
_apiFactory = apiFactory;
_client = apiFactory.CreateClient();
@@ -1,29 +1,25 @@
#region ========================================================================= USING =====================================================================================
using FluentAssertions;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Contracts.Requests.Authorization;
using Lumina.DataAccess.Core.UoW;
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Text.Json;
using System.Text.Json.Serialization;
#endregion
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.UsersManagement.Authorization;
/// <summary>
/// Contains integration tests for the <see cref="GetAuthorizationEndpoint"/> class.
/// Contains security tests for the <c>/auth/get-authorization</c> route.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetAuthorizationEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
public class GetAuthorizationEndpointTests : IClassFixture<LuminaApiFactory>
{
private readonly LuminaApiFactory _apiFactory;
private readonly JsonSerializerOptions _jsonOptions;
private HttpClient _client;
private readonly string _testUsername;
private readonly HttpClient _client;
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true
};
/// <summary>
/// Initializes a new instance of the <see cref="GetAuthorizationEndpointTests"/> class.
@@ -31,33 +27,25 @@ public class GetAuthorizationEndpointTests : IClassFixture<LuminaApiFactory>, ID
/// <param name="apiFactory">Injected in-memory API factory.</param>
public GetAuthorizationEndpointTests(LuminaApiFactory apiFactory)
{
_apiFactory = apiFactory;
_client = apiFactory.CreateClient();
_client.DefaultRequestHeaders.Clear();
_client.DefaultRequestHeaders.Add("X-Forwarded-For", $"192.168.1.12");
_testUsername = $"testuser_{Guid.NewGuid()}";
_jsonOptions = new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true,
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
};
}
[Fact]
public async Task ExecuteAsync_WhenUnauthorized_ShouldReturnUnauthorized()
public async Task GetAuthorization_WhenUnauthorized_ShouldReturnUnauthorizedResult()
{
// Arrange
_client = _apiFactory.CreateClient(); // unauthenticated client
GetAuthorizationRequest request = new(Guid.NewGuid());
Guid userId = Guid.NewGuid();
string url = $"/api/v1/auth/get-authorization?UserId={userId}";
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/auth/get-authorization?userId={request.UserId}");
HttpResponseMessage response = await _client.GetAsync(url);
// Assert
response.StatusCode.Should().Be(HttpStatusCode.Unauthorized);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
string responseContent = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(responseContent, _jsonOptions);
problemDetails.Should().NotBeNull();
problemDetails!["status"].GetInt32().Should().Be(StatusCodes.Status401Unauthorized);
problemDetails["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc7235#section-3.1");
@@ -65,22 +53,4 @@ public class GetAuthorizationEndpointTests : IClassFixture<LuminaApiFactory>, ID
problemDetails["instance"].GetProperty("value").GetString().Should().Be("/api/v1/auth/get-authorization");
problemDetails["detail"].GetString().Should().Be("Authentication failed");
}
/// <summary>
/// Disposes API factory resources.
/// </summary>
public void Dispose()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
UserEntity? user = dbContext.Users.FirstOrDefault(u => u.Username == _testUsername);
if (user is not null)
{
dbContext.Users.Remove(user);
dbContext.SaveChanges();
}
_client.DefaultRequestHeaders.Authorization = null;
}
}
@@ -0,0 +1,55 @@
#region ========================================================================= USING =====================================================================================
using FluentAssertions;
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
using Microsoft.AspNetCore.Http;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Text.Json;
#endregion
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.UsersManagement.Authorization;
/// <summary>
/// Contains security tests for the <c>/auth/users/{userId}/permissions</c> route.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetUserPermissionsEndpointTests : IClassFixture<LuminaApiFactory>
{
private readonly HttpClient _client;
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true
};
/// <summary>
/// Initializes a new instance of the <see cref="GetUserPermissionsEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public GetUserPermissionsEndpointTests(LuminaApiFactory apiFactory)
{
_client = apiFactory.CreateClient();
}
[Fact]
public async Task GetUserPermissions_WhenUnauthorized_ShouldReturnUnauthorizedResult()
{
// Arrange
string url = $"/api/v1/auth/users/{Guid.NewGuid()}/permissions";
// Act
HttpResponseMessage response = await _client.GetAsync(url);
// Assert
response.StatusCode.Should().Be(HttpStatusCode.Unauthorized);
string responseContent = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(responseContent, _jsonOptions);
problemDetails.Should().NotBeNull();
problemDetails!["status"].GetInt32().Should().Be(StatusCodes.Status401Unauthorized);
problemDetails["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc7235#section-3.1");
problemDetails["title"].GetString().Should().Be("Unauthorized");
problemDetails["instance"].GetProperty("value").GetString().Should().Be(url);
problemDetails["detail"].GetString().Should().Be("Authentication failed");
}
}
@@ -0,0 +1,56 @@
#region ========================================================================= USING =====================================================================================
using FluentAssertions;
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
using Microsoft.AspNetCore.Http;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Text.Json;
#endregion
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.UsersManagement.Authorization;
/// <summary>
/// Contains security tests for the <c>/auth/users/{userId}/role</c> route.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetUserRoleEndpointTests : IClassFixture<LuminaApiFactory>
{
private readonly HttpClient _client;
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true
};
/// <summary>
/// Initializes a new instance of the <see cref="GetUserRoleEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public GetUserRoleEndpointTests(LuminaApiFactory apiFactory)
{
_client = apiFactory.CreateClient();
}
[Fact]
public async Task GetUserRole_WhenUnauthorized_ShouldReturnUnauthorizedResult()
{
// Arrange
Guid userId = Guid.NewGuid();
string url = $"/api/v1/auth/users/{userId}/role";
// Act
HttpResponseMessage response = await _client.GetAsync(url);
// Assert
response.StatusCode.Should().Be(HttpStatusCode.Unauthorized);
string responseContent = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(responseContent, _jsonOptions);
problemDetails.Should().NotBeNull();
problemDetails!["status"].GetInt32().Should().Be(StatusCodes.Status401Unauthorized);
problemDetails["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc7235#section-3.1");
problemDetails["title"].GetString().Should().Be("Unauthorized");
problemDetails["instance"].GetProperty("value").GetString().Should().Be(url);
problemDetails["detail"].GetString().Should().Be("Authentication failed");
}
}
@@ -0,0 +1,57 @@
#region ========================================================================= USING =====================================================================================
using FluentAssertions;
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
using Microsoft.AspNetCore.Http;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Text;
using System.Text.Json;
#endregion
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.UsersManagement.Authorization;
/// <summary>
/// Contains security tests for the <c>/auth/users/{userId}/role-and-permissions</c> route.
/// </summary>
[ExcludeFromCodeCoverage]
public class UpdateUserRoleAndPermissionsEndpointTests : IClassFixture<LuminaApiFactory>
{
private readonly HttpClient _client;
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true
};
/// <summary>
/// Initializes a new instance of the <see cref="UpdateUserRoleAndPermissionsEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public UpdateUserRoleAndPermissionsEndpointTests(LuminaApiFactory apiFactory)
{
_client = apiFactory.CreateClient();
}
[Fact]
public async Task UpdateUserRoleAndPermissions_WhenUnauthorized_ShouldReturnUnauthorizedResult()
{
// Arrange
Guid userId = Guid.NewGuid();
string url = $"/api/v1/auth/users/{userId}/role-and-permissions";
// Act
HttpResponseMessage response = await _client.PutAsync(url, new StringContent("{}", Encoding.UTF8, "application/json"));
// Assert
response.StatusCode.Should().Be(HttpStatusCode.Unauthorized);
string responseContent = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(responseContent, _jsonOptions);
problemDetails.Should().NotBeNull();
problemDetails!["status"].GetInt32().Should().Be(StatusCodes.Status401Unauthorized);
problemDetails["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc7235#section-3.1");
problemDetails["title"].GetString().Should().Be("Unauthorized");
problemDetails["instance"].GetProperty("value").GetString().Should().Be(url);
problemDetails["detail"].GetString().Should().Be("Authentication failed");
}
}