From 12ecd83e89d1cc94ab232854b778d149a254b8e3 Mon Sep 17 00:00:00 2001 From: arjun Date: Mon, 30 Nov 2026 14:07:24 +0530 Subject: [PATCH 1/4] fix: enhance security and coverage reporting in various components --- .github/workflows/sonar.yml | 11 ++ .../Controllers/ImpersonationController.cs | 6 +- .../Middleware/ExceptionHandlingMiddleware.cs | 2 +- .../wwwroot/swagger-ui/swagger-auto-auth.js | 14 +- .../Emails/EmailBroadcastService.cs | 127 +++++------------- .../Permissions/PermissionService.cs | 2 +- src/Infrastructure/Roles/RoleService.cs | 5 +- .../Users/UserManagementService.cs | 3 - .../Helpers/EmailBroadcastServiceTests.cs | 118 ++++++++++++++++ .../MiddlewareIntegrationTests.cs | 33 +++++ .../Swagger/swagger-auto-auth.test.mjs | 70 ++++++++++ 11 files changed, 281 insertions(+), 110 deletions(-) create mode 100644 tests/Api.Tests/Helpers/EmailBroadcastServiceTests.cs create mode 100644 tests/Api.Tests/Swagger/swagger-auto-auth.test.mjs diff --git a/.github/workflows/sonar.yml b/.github/workflows/sonar.yml index 7748b46..c7e10de 100644 --- a/.github/workflows/sonar.yml +++ b/.github/workflows/sonar.yml @@ -47,6 +47,7 @@ jobs: "/d:sonar.token=$token" "/d:sonar.cs.opencover.reportsPaths=TestResults/**/coverage.opencover.xml" "/d:sonar.coverageReportPaths=TestResults/powershell-coverage.xml" + "/d:sonar.javascript.lcov.reportPaths=TestResults/swagger-coverage.lcov" "/d:sonar.qualitygate.wait=true" ) dotnet sonarscanner begin @scannerArgs @@ -106,6 +107,16 @@ jobs: $report.Save((Join-Path $results 'powershell-coverage.xml')) # Expected failures above set LASTEXITCODE, which the Actions shell propagates. $global:LASTEXITCODE = 0 + - uses: actions/setup-node@v4 + with: + node-version: '22.20.0' + - name: Test Swagger authentication and collect JavaScript coverage + run: > + node --test --experimental-test-coverage + --test-coverage-include=src/Api/wwwroot/swagger-ui/swagger-auto-auth.js + --test-reporter=spec --test-reporter-destination=stdout + --test-reporter=lcov --test-reporter-destination=TestResults/swagger-coverage.lcov + tests/Api.Tests/Swagger/swagger-auto-auth.test.mjs - name: Submit analysis env: SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }} diff --git a/src/Api/Controllers/ImpersonationController.cs b/src/Api/Controllers/ImpersonationController.cs index 79a414d..ce31c3c 100644 --- a/src/Api/Controllers/ImpersonationController.cs +++ b/src/Api/Controllers/ImpersonationController.cs @@ -43,7 +43,7 @@ public async Task Start([FromBody] StartImpersonationRequest requ Response.Cookies.Append("impersonation_restore_token", restoreToken, new CookieOptions { HttpOnly = true, - Secure = HttpContext.Request.IsHttps, + Secure = true, SameSite = SameSiteMode.Lax, Expires = DateTimeOffset.UtcNow.AddDays(_jwtSettings.RefreshTokenExpiryDays), }); @@ -75,7 +75,7 @@ private void SetAccessTokenCookie(string token, DateTime expiresAt) Response.Cookies.Append("access_token", token, new CookieOptions { HttpOnly = true, - Secure = HttpContext.Request.IsHttps, + Secure = true, SameSite = SameSiteMode.Lax, Expires = expiresAt, }); @@ -86,7 +86,7 @@ private void SetRefreshTokenCookie(string token) Response.Cookies.Append("refresh_token", token, new CookieOptions { HttpOnly = true, - Secure = HttpContext.Request.IsHttps, + Secure = true, SameSite = SameSiteMode.Lax, Expires = DateTimeOffset.UtcNow.AddDays(_jwtSettings.RefreshTokenExpiryDays), }); diff --git a/src/Api/Middleware/ExceptionHandlingMiddleware.cs b/src/Api/Middleware/ExceptionHandlingMiddleware.cs index 4485c9b..fb24d7e 100644 --- a/src/Api/Middleware/ExceptionHandlingMiddleware.cs +++ b/src/Api/Middleware/ExceptionHandlingMiddleware.cs @@ -53,7 +53,7 @@ public async Task InvokeAsync(HttpContext context) context.Response.StatusCode = statusCode; context.Response.ContentType = MediaTypeNames.Application.Json; - await context.Response.WriteAsJsonAsync(envelope); + await context.Response.WriteAsJsonAsync(envelope, context.RequestAborted); } } diff --git a/src/Api/wwwroot/swagger-ui/swagger-auto-auth.js b/src/Api/wwwroot/swagger-ui/swagger-auto-auth.js index 1c0cf24..931e831 100644 --- a/src/Api/wwwroot/swagger-ui/swagger-auto-auth.js +++ b/src/Api/wwwroot/swagger-ui/swagger-auto-auth.js @@ -10,7 +10,7 @@ function getUrl(args) { const target = args[0]; - return (typeof target === "string" ? target : (target && target.url) || "").toLowerCase(); + return (typeof target === "string" ? target : target?.url || "").toLowerCase(); } function getTokens(body) { @@ -40,7 +40,7 @@ } function applyBearer(token) { - if (!token || !window.ui || !window.ui.preauthorizeApiKey) { + if (!token || !window.ui?.preauthorizeApiKey) { return; } @@ -52,7 +52,7 @@ return; } - if (window.ui.authActions && window.ui.authActions.logout) { + if (window.ui.authActions?.logout) { window.ui.authActions.logout(); return; } @@ -100,7 +100,7 @@ } const init = args[1]; - if (!init || !init.body || typeof init.body !== "string") { + if (!init?.body || typeof init.body !== "string") { return args; } @@ -108,9 +108,11 @@ const body = JSON.parse(init.body); if (!body.refreshToken && !body.RefreshToken) { body.refreshToken = stored; - args[1] = Object.assign({}, init, { body: JSON.stringify(body) }); + args[1] = { ...init, body: JSON.stringify(body) }; } - } catch (e) { } + } catch { + // Forward the original request when its body cannot be patched as JSON. + } return args; } diff --git a/src/Infrastructure/Emails/EmailBroadcastService.cs b/src/Infrastructure/Emails/EmailBroadcastService.cs index 1e1a253..00bd7c2 100644 --- a/src/Infrastructure/Emails/EmailBroadcastService.cs +++ b/src/Infrastructure/Emails/EmailBroadcastService.cs @@ -1,7 +1,6 @@ using Application.Common; using Application.DTOs.ActivityLogs; using Application.DTOs.Emails; -using Application.Exceptions; using Application.Interfaces.ActivityLogs; using Application.Interfaces.Email; using Application.Interfaces.Emails; @@ -10,7 +9,6 @@ using Infrastructure.Common; using Infrastructure.Identity.Entities; using Infrastructure.Persistence.Contexts; -using Microsoft.AspNetCore.Identity; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Logging; @@ -19,14 +17,12 @@ namespace Infrastructure.Emails; public class EmailBroadcastService : TenantScopedService, IEmailBroadcastService { private readonly ApplicationDbContext _context; - private readonly UserManager _userManager; private readonly IEmailService _emailService; private readonly IActivityLogService _activityLogService; private readonly ILogger _logger; public EmailBroadcastService( ApplicationDbContext context, - UserManager userManager, ICurrentTenantService currentTenantService, IEmailService emailService, IActivityLogService activityLogService, @@ -34,7 +30,6 @@ public EmailBroadcastService( : base(currentTenantService) { _context = context; - _userManager = userManager; _emailService = emailService; _activityLogService = activityLogService; _logger = logger; @@ -50,93 +45,16 @@ public async Task BroadcastAsync( if (string.IsNullOrWhiteSpace(request.HtmlBody)) throw new InvalidOperationException("Email body is required."); - var targetType = IsSystemAdmin() - ? request.TargetType - : BroadcastTarget.CurrentTenant; + var targetType = IsSystemAdmin() ? request.TargetType : BroadcastTarget.CurrentTenant; + var recipients = _context.Users + .AsNoTracking() + .IgnoreQueryFilters() + .Where(user => user.IsActive && user.EmailConfirmed && user.DeletedAt == null && user.Email != null); - List recipientEmails; - - switch (targetType) - { - case BroadcastTarget.AllTenants: - if (!IsSystemAdmin()) - throw new ForbiddenException("Only system administrators can broadcast to all tenants."); - - recipientEmails = await _context.Users - .AsNoTracking() - .IgnoreQueryFilters() - .Where(u => u.TenantId != Guid.Empty - && u.IsActive - && u.EmailConfirmed - && u.DeletedAt == null - && u.Email != null) - .Select(u => u.Email!) - .Distinct() - .ToListAsync(cancellationToken); - break; - - case BroadcastTarget.SpecificTenants: - if (!IsSystemAdmin()) - throw new ForbiddenException("Only system administrators can broadcast to specific tenants."); - - if (request.TenantIds == null || request.TenantIds.Count == 0) - throw new InvalidOperationException("TenantIds is required for SpecificTenants target."); - - recipientEmails = await _context.Users - .AsNoTracking() - .IgnoreQueryFilters() - .Where(u => request.TenantIds.Contains(u.TenantId) - && u.IsActive - && u.EmailConfirmed - && u.DeletedAt == null - && u.Email != null) - .Select(u => u.Email!) - .Distinct() - .ToListAsync(cancellationToken); - break; - - case BroadcastTarget.SpecificUsers: - if (request.UserIds == null || request.UserIds.Count == 0) - throw new InvalidOperationException("UserIds is required for SpecificUsers target."); - - var userQuery = _context.Users - .AsNoTracking() - .IgnoreQueryFilters() - .Where(u => request.UserIds.Contains(u.Id) - && u.IsActive - && u.EmailConfirmed - && u.DeletedAt == null - && u.Email != null); - - // TenantAdmin can only send to users within their own tenant. - if (!IsSystemAdmin()) - { - var scopedTenantId = RequireTenantId(); - userQuery = userQuery.Where(u => u.TenantId == scopedTenantId); - } - - recipientEmails = await userQuery - .Select(u => u.Email!) - .Distinct() - .ToListAsync(cancellationToken); - break; - - default: // CurrentTenant - var tenantId = RequireTenantId(); - - recipientEmails = await _context.Users - .AsNoTracking() - .IgnoreQueryFilters() - .Where(u => u.TenantId == tenantId - && u.IsActive - && u.EmailConfirmed - && u.DeletedAt == null - && u.Email != null) - .Select(u => u.Email!) - .Distinct() - .ToListAsync(cancellationToken); - break; - } + var recipientEmails = await FilterRecipients(recipients, targetType, request) + .Select(user => user.Email!) + .Distinct() + .ToListAsync(cancellationToken); var recipientCount = recipientEmails.Count; var logTenantId = IsSystemAdmin() ? (Guid?)null : RequireTenantId(); @@ -151,7 +69,7 @@ public async Task BroadcastAsync( { try { - await _emailService.SendCustomEmailAsync(email, request.Subject, request.HtmlBody); + await _emailService.SendCustomEmailAsync(email, request.Subject, request.HtmlBody, CancellationToken.None); sent++; } catch (Exception ex) @@ -183,4 +101,29 @@ await _activityLogService.LogAsync(new LogActivityRequest Message = $"Email broadcast is being sent to {recipientCount} recipient(s).", }; } + + private IQueryable FilterRecipients( + IQueryable recipients, + BroadcastTarget targetType, + SendEmailBroadcastRequest request) + { + switch (targetType) + { + case BroadcastTarget.AllTenants: + return recipients.Where(user => user.TenantId != Guid.Empty); + case BroadcastTarget.SpecificTenants: + if (request.TenantIds is not { Count: > 0 } tenantIds) + throw new InvalidOperationException("TenantIds is required for SpecificTenants target."); + + return recipients.Where(user => tenantIds.Contains(user.TenantId)); + case BroadcastTarget.SpecificUsers: + if (request.UserIds is not { Count: > 0 } userIds) + throw new InvalidOperationException("UserIds is required for SpecificUsers target."); + + return recipients.Where(user => userIds.Contains(user.Id)); + default: + var tenantId = RequireTenantId(); + return recipients.Where(user => user.TenantId == tenantId); + } + } } diff --git a/src/Infrastructure/Permissions/PermissionService.cs b/src/Infrastructure/Permissions/PermissionService.cs index 6d1cf86..64c6c4a 100644 --- a/src/Infrastructure/Permissions/PermissionService.cs +++ b/src/Infrastructure/Permissions/PermissionService.cs @@ -49,7 +49,7 @@ public async Task GetCatalogAsync(SystemRole? scopeF var items = effectiveFilter.HasValue ? catalog.Items.Where(p => p.Scope == effectiveFilter.Value.ToString()).ToList() - : (IReadOnlyList)catalog.Items; + : catalog.Items; return BuildResponse(items, groupByModule); } diff --git a/src/Infrastructure/Roles/RoleService.cs b/src/Infrastructure/Roles/RoleService.cs index fc3da2a..c2fd4ae 100644 --- a/src/Infrastructure/Roles/RoleService.cs +++ b/src/Infrastructure/Roles/RoleService.cs @@ -1,4 +1,4 @@ -using Application.Common; +using Application.Common; using Application.DTOs.ActivityLogs; using Application.DTOs.Common; using Application.DTOs.Roles; @@ -23,7 +23,6 @@ public class RoleService : TenantScopedService, IRoleService private readonly RoleManager _roleManager; private readonly IActivityLogService _activityLogService; private readonly IRolePermissionLookup _rolePermissionLookup; - private readonly IAppCache _cache; private readonly IIdentityRoleService _identityRoleService; public RoleService( @@ -32,7 +31,6 @@ public RoleService( ICurrentTenantService currentTenantService, IActivityLogService activityLogService, IRolePermissionLookup rolePermissionLookup, - IAppCache cache, IIdentityRoleService identityRoleService) : base(currentTenantService) { @@ -40,7 +38,6 @@ public RoleService( _roleManager = roleManager; _activityLogService = activityLogService; _rolePermissionLookup = rolePermissionLookup; - _cache = cache; _identityRoleService = identityRoleService; } diff --git a/src/Infrastructure/Users/UserManagementService.cs b/src/Infrastructure/Users/UserManagementService.cs index e62dda0..198af71 100644 --- a/src/Infrastructure/Users/UserManagementService.cs +++ b/src/Infrastructure/Users/UserManagementService.cs @@ -32,7 +32,6 @@ public class UserManagementService : TenantScopedService, IUserManagementService private readonly ApplicationDbContext _context; private readonly UserManager _userManager; - private readonly RoleManager _roleManager; private readonly IActivityLogService _activityLogService; private readonly IAppCache _cache; private readonly IIdentityRoleService _identityRoleService; @@ -55,7 +54,6 @@ public class UserManagementService : TenantScopedService, IUserManagementService public UserManagementService( ApplicationDbContext context, UserManager userManager, - RoleManager roleManager, ICurrentTenantService currentTenantService, IActivityLogService activityLogService, IAppCache cache, @@ -70,7 +68,6 @@ public UserManagementService( { _context = context; _userManager = userManager; - _roleManager = roleManager; _activityLogService = activityLogService; _cache = cache; _identityRoleService = identityRoleService; diff --git a/tests/Api.Tests/Helpers/EmailBroadcastServiceTests.cs b/tests/Api.Tests/Helpers/EmailBroadcastServiceTests.cs new file mode 100644 index 0000000..a57e4f3 --- /dev/null +++ b/tests/Api.Tests/Helpers/EmailBroadcastServiceTests.cs @@ -0,0 +1,118 @@ +using System.Threading.Channels; +using Application.DTOs.Emails; +using Application.Interfaces.ActivityLogs; +using Application.Interfaces.Email; +using Application.Interfaces.Tenant; +using Infrastructure.Emails; +using Infrastructure.Identity.Entities; +using Infrastructure.Persistence.Contexts; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Logging.Abstractions; + +namespace Api.Tests.Helpers; + +public class EmailBroadcastServiceTests +{ + [Theory] + [InlineData(true, BroadcastTarget.AllTenants, "owner@example.test,other@example.test")] + [InlineData(true, BroadcastTarget.SpecificTenants, "other@example.test")] + [InlineData(true, BroadcastTarget.SpecificUsers, "other@example.test")] + [InlineData(true, BroadcastTarget.CurrentTenant, "owner@example.test")] + [InlineData(false, BroadcastTarget.AllTenants, "owner@example.test")] + [InlineData(false, BroadcastTarget.SpecificUsers, "owner@example.test")] + public async Task Broadcast_SendsOnlyToEligibleRecipients( + bool isSystemAdmin, BroadcastTarget target, string expectedRecipients) + { + var currentTenant = Guid.NewGuid(); + var otherTenant = Guid.NewGuid(); + var requestedUser = Guid.NewGuid(); + var tenant = new Mock(); + tenant.SetupGet(service => service.IsSystemAdmin).Returns(isSystemAdmin); + tenant.SetupGet(service => service.TenantId).Returns(currentTenant); + tenant.SetupGet(service => service.UserId).Returns(Guid.NewGuid()); + + await using var context = CreateContext(tenant.Object); + context.Users.AddRange( + CreateUser(Guid.NewGuid(), currentTenant, "owner@example.test"), + CreateUser(requestedUser, otherTenant, "other@example.test"), + CreateUser(Guid.NewGuid(), Guid.Empty, "system@example.test"), + CreateUser(Guid.NewGuid(), currentTenant, "unconfirmed@example.test", confirmed: false), + CreateUser(Guid.NewGuid(), currentTenant, "inactive@example.test", active: false)); + await context.SaveChangesAsync(); + + var sent = Channel.CreateUnbounded(); + var email = new Mock(); + email.Setup(service => service.SendCustomEmailAsync( + It.IsAny(), "Notice", "

Update

", CancellationToken.None)) + .Returns((string address, string _, string _, CancellationToken _) => + sent.Writer.WriteAsync(address).AsTask()); + var service = CreateService(context, tenant.Object, email.Object); + var response = await service.BroadcastAsync(new SendEmailBroadcastRequest + { + Subject = "Notice", + HtmlBody = "

Update

", + TargetType = target, + TenantIds = [otherTenant], + UserIds = [requestedUser], + }); + + var expected = expectedRecipients.Split(','); + Assert.Equal(expected.Length, response.RecipientCount); + using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(5)); + var actual = new List(); + foreach (var _ in expected) + actual.Add(await sent.Reader.ReadAsync(timeout.Token)); + + Assert.Equal(expected.Order(StringComparer.Ordinal), actual.Order(StringComparer.Ordinal)); + } + + [Theory] + [InlineData("", "body", BroadcastTarget.AllTenants, "Subject is required.")] + [InlineData("subject", "", BroadcastTarget.AllTenants, "Email body is required.")] + [InlineData("subject", "body", BroadcastTarget.SpecificTenants, "TenantIds is required for SpecificTenants target.")] + [InlineData("subject", "body", BroadcastTarget.SpecificUsers, "UserIds is required for SpecificUsers target.")] + public async Task Broadcast_RejectsInvalidInput( + string subject, string body, BroadcastTarget target, string expectedMessage) + { + var tenant = Mock.Of(value => value.IsSystemAdmin); + await using var context = CreateContext(tenant); + var email = new Mock(); + var service = CreateService(context, tenant, email.Object); + + var error = await Assert.ThrowsAsync(() => + service.BroadcastAsync(new SendEmailBroadcastRequest + { + Subject = subject, + HtmlBody = body, + TargetType = target, + })); + + Assert.Equal(expectedMessage, error.Message); + email.VerifyNoOtherCalls(); + } + + private static ApplicationDbContext CreateContext(ICurrentTenantService tenant) + { + var options = new DbContextOptionsBuilder() + .UseInMemoryDatabase(Guid.NewGuid().ToString()) + .Options; + return new ApplicationDbContext(options, tenant); + } + + private static EmailBroadcastService CreateService( + ApplicationDbContext context, ICurrentTenantService tenant, IEmailService email) => + new(context, tenant, email, Mock.Of(), + NullLogger.Instance); + + private static ApplicationUser CreateUser( + Guid id, Guid tenantId, string email, bool confirmed = true, bool active = true) => + new() + { + Id = id, + TenantId = tenantId, + FullName = email, + Email = email, + EmailConfirmed = confirmed, + IsActive = active, + }; +} diff --git a/tests/Api.Tests/IntegrationTests/MiddlewareIntegrationTests.cs b/tests/Api.Tests/IntegrationTests/MiddlewareIntegrationTests.cs index e7b9876..a5db879 100644 --- a/tests/Api.Tests/IntegrationTests/MiddlewareIntegrationTests.cs +++ b/tests/Api.Tests/IntegrationTests/MiddlewareIntegrationTests.cs @@ -111,6 +111,39 @@ public async Task Login_DoesNotExceedRateLimit_On_SingleRequest() // ── Impersonation endpoints are protected ────────────────────────────────── + [Fact] + public async Task Impersonation_StartAndStop_UsesSecureSessionCookies() + { + var login = await Client.PostAsync("/api/v1/auth/login", JsonContent(new + { + Email = CustomWebApplicationFactory.AdminEmail, + Password = CustomWebApplicationFactory.AdminPassword, + })); + Assert.Equal(HttpStatusCode.OK, login.StatusCode); + Client.DefaultRequestHeaders.TryAddWithoutValidation( + "X-Tenant-Id", CustomWebApplicationFactory.TestTenantId.ToString()); + + var start = await Client.PostAsync("/api/v1/impersonation/start", JsonContent(new + { + TargetUserId = CustomWebApplicationFactory.TenantUserId, + })); + Assert.Equal(HttpStatusCode.OK, start.StatusCode); + AssertSecureCookie(start, "impersonation_restore_token"); + AssertSecureCookie(start, "access_token"); + + var stop = await Client.PostAsync("/api/v1/impersonation/stop", null); + Assert.Equal(HttpStatusCode.OK, stop.StatusCode); + AssertSecureCookie(stop, "access_token"); + AssertSecureCookie(stop, "refresh_token"); + } + + private static void AssertSecureCookie(HttpResponseMessage response, string cookieName) + { + var cookie = Assert.Single(response.Headers.GetValues("Set-Cookie"), + value => value.StartsWith($"{cookieName}=", StringComparison.Ordinal)); + Assert.Contains("; secure", cookie, StringComparison.OrdinalIgnoreCase); + } + [Fact] public async Task StartImpersonation_WithoutRefreshToken_Returns400() { diff --git a/tests/Api.Tests/Swagger/swagger-auto-auth.test.mjs b/tests/Api.Tests/Swagger/swagger-auto-auth.test.mjs new file mode 100644 index 0000000..8f84bf0 --- /dev/null +++ b/tests/Api.Tests/Swagger/swagger-auto-auth.test.mjs @@ -0,0 +1,70 @@ +import assert from 'node:assert/strict' +import test from 'node:test' + +test('Swagger preserves request behavior and manages auth state', async () => { + const calls = [] + const storage = new Map() + const authorized = [] + const nextResponse = { ok: true, clone: () => ({ json: async () => ({ + accessToken: 'test-access', + refreshToken: 'test-refresh', + }) }) } + + globalThis.localStorage = { + getItem: key => storage.get(key), + setItem: (key, value) => storage.set(key, value), + removeItem: key => storage.delete(key), + } + globalThis.window = { + fetch: async (...args) => { + calls.push(args) + return nextResponse + }, + ui: { preauthorizeApiKey: (...args) => authorized.push(args) }, + } + + try { + await import('../../../src/Api/wwwroot/swagger-ui/swagger-auto-auth.js') + assert.equal(await window.fetch({ url: '/AUTH/LOGIN' }), nextResponse) + assert.deepEqual(authorized.pop(), ['Bearer', 'test-access']) + assert.equal(storage.get('swagger_refresh_token'), 'test-refresh') + + await window.fetch('/auth/refresh', { method: 'POST', body: '{}' }) + assert.deepEqual(JSON.parse(calls.at(-1)[1].body), { refreshToken: 'test-refresh' }) + await window.fetch('/auth/refresh', { body: 'plain text' }) + assert.equal(calls.at(-1)[1].body, 'plain text') + await window.fetch('/auth/refresh') + assert.equal(calls.at(-1).length, 1) + + await window.fetch('/auth/logout') + assert.equal(storage.size, 0) + assert.deepEqual(authorized.pop(), ['Bearer', '']) + + let logoutCalled = false + window.ui.authActions = { logout: () => { logoutCalled = true } } + await window.fetch('/auth/logout') + assert.equal(logoutCalled, true) + + delete window.ui + await window.fetch('/auth/login') + await window.fetch('/auth/logout') + await window.fetch(undefined) + assert.equal(storage.size, 0) + + nextResponse.ok = false + await window.fetch('/auth/login') + assert.equal(storage.size, 0) + + nextResponse.ok = true + nextResponse.clone = () => ({ json: async () => null }) + await window.fetch('/auth/login') + assert.equal(storage.size, 0) + + nextResponse.clone = () => ({ json: async () => { throw new SyntaxError('Invalid JSON') } }) + await window.fetch('/auth/login') + assert.equal(storage.size, 0) + } finally { + delete globalThis.window + delete globalThis.localStorage + } +}) From 1934f8397b9e3d74ef1e054c005618a5251e7ce0 Mon Sep 17 00:00:00 2001 From: arjun Date: Mon, 30 Nov 2026 14:22:04 +0530 Subject: [PATCH 2/4] fix: refactor role assignment logic and enhance email verification tests --- .github/workflows/sonar.yml | 13 +- .../Users/UserManagementService.cs | 72 ++++------ .../Helpers/EmailBroadcastServiceTests.cs | 2 +- .../EmailVerificationServiceTests.cs | 133 ++++++++++++++++++ .../IntegrationTests/UsersIntegrationTests.cs | 28 ++++ 5 files changed, 201 insertions(+), 47 deletions(-) create mode 100644 tests/Api.Tests/IntegrationTests/EmailVerificationServiceTests.cs diff --git a/.github/workflows/sonar.yml b/.github/workflows/sonar.yml index c7e10de..e16711e 100644 --- a/.github/workflows/sonar.yml +++ b/.github/workflows/sonar.yml @@ -47,7 +47,7 @@ jobs: "/d:sonar.token=$token" "/d:sonar.cs.opencover.reportsPaths=TestResults/**/coverage.opencover.xml" "/d:sonar.coverageReportPaths=TestResults/powershell-coverage.xml" - "/d:sonar.javascript.lcov.reportPaths=TestResults/swagger-coverage.lcov" + "/d:sonar.javascript.lcov.reportPaths=$((Join-Path (Get-Location).Path 'TestResults/swagger-coverage.lcov').Replace('\', '/'))" "/d:sonar.qualitygate.wait=true" ) dotnet sonarscanner begin @scannerArgs @@ -117,6 +117,17 @@ jobs: --test-reporter=spec --test-reporter-destination=stdout --test-reporter=lcov --test-reporter-destination=TestResults/swagger-coverage.lcov tests/Api.Tests/Swagger/swagger-auto-auth.test.mjs + - name: Verify and normalize the Swagger coverage report + shell: pwsh + run: | + $report = (Resolve-Path -LiteralPath TestResults/swagger-coverage.lcov).Path + $source = (Resolve-Path -LiteralPath src/Api/wwwroot/swagger-ui/swagger-auto-auth.js).Path.Replace('\', '/') + $coverage = [IO.File]::ReadAllText($report) + if ($coverage -notmatch '(?m)^SF:.*swagger-auto-auth\.js\r?$' -or $coverage -notmatch '(?m)^LH:[1-9]') { + throw 'The Swagger LCOV report is missing recorded coverage.' + } + $coverage = $coverage -replace '(?m)^SF:[^\r\n]+', "SF:$source" + [IO.File]::WriteAllText($report, $coverage) - name: Submit analysis env: SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }} diff --git a/src/Infrastructure/Users/UserManagementService.cs b/src/Infrastructure/Users/UserManagementService.cs index 198af71..3590780 100644 --- a/src/Infrastructure/Users/UserManagementService.cs +++ b/src/Infrastructure/Users/UserManagementService.cs @@ -350,20 +350,7 @@ await AddressHelper.ApplyUserAddressUpdateAsync( } } - if (request.RoleId.HasValue) - { - var role = await _context.Roles - .FirstOrDefaultAsync(r => r.Id == request.RoleId.Value && r.TenantId == user.TenantId) - ?? throw new NotFoundException($"Role '{request.RoleId}' was not found for this tenant."); - - var existingAssignments = await _context.Set>() - .Where(ur => ur.UserId == user.Id) - .ToListAsync(); - - _context.Set>().RemoveRange(existingAssignments); - - await _identityRoleService.AddUserToRoleAsync(user.Id, role.Id); - } + await UpdateRoleAssignmentAsync(user, request.RoleId); // UserManager.UpdateAsync internally calls SaveChangesAsync - no second call needed. await _userManager.UpdateAsync(user); @@ -648,20 +635,7 @@ public async Task UpdateTenantAdminAsync(UpdateTenantAdminRequest await AddressHelper.ApplyUserAddressUpdateAsync( _context, user, request.Address, request.ClearAddress); - if (request.RoleId.HasValue) - { - var role = await _context.Roles - .FirstOrDefaultAsync(r => r.Id == request.RoleId.Value && r.TenantId == user.TenantId) - ?? throw new NotFoundException($"Role '{request.RoleId}' was not found for this tenant."); - - var existingAssignments = await _context.Set>() - .Where(ur => ur.UserId == user.Id) - .ToListAsync(); - - _context.Set>().RemoveRange(existingAssignments); - - await _identityRoleService.AddUserToRoleAsync(user.Id, role.Id); - } + await UpdateRoleAssignmentAsync(user, request.RoleId); await _userManager.UpdateAsync(user); @@ -717,7 +691,7 @@ public async Task DeleteTenantAdminAsync(Guid id) await LogActivityAsync(ActivityActions.Users.Deleted, $"Deleted tenant admin '{user.Email}'."); } - public async Task UploadCurrentUserAvatarAsync(IFormFile file) + private static void ValidateAvatar(IFormFile file) { var extension = Path.GetExtension(file.FileName); if (!AvatarExtensions.Contains(extension)) @@ -735,6 +709,29 @@ public async Task UploadCurrentUserAvatarAsync(IFormFile file) throw new InvalidOperationException( $"Profile picture must be square ({width}×{height} is not square). Please crop your image before uploading."); } + } + + private async Task UpdateRoleAssignmentAsync(ApplicationUser user, Guid? roleId) + { + if (roleId.HasValue) + { + var role = await _context.Roles + .FirstOrDefaultAsync(r => r.Id == roleId.Value && r.TenantId == user.TenantId) + ?? throw new NotFoundException($"Role '{roleId}' was not found for this tenant."); + + var existingAssignments = await _context.Set>() + .Where(ur => ur.UserId == user.Id) + .ToListAsync(); + + _context.Set>().RemoveRange(existingAssignments); + + await _identityRoleService.AddUserToRoleAsync(user.Id, role.Id); + } + } + + public async Task UploadCurrentUserAvatarAsync(IFormFile file) + { + ValidateAvatar(file); var user = await GetCurrentUserEntityAsync(); var previousFileId = user.ProfileFileId; @@ -770,22 +767,7 @@ public async Task RemoveCurrentUserAvatarAsync() public async Task UploadUserAvatarByIdAsync(Guid userId, IFormFile file) { - var extension = Path.GetExtension(file.FileName); - if (!AvatarExtensions.Contains(extension)) - throw new InvalidOperationException("Profile picture must be a JPEG, PNG, GIF, or WebP image."); - - if (file.Length > AvatarMaxBytes) - throw new InvalidOperationException("Profile picture must be smaller than 5 MB."); - - using (var dimensionStream = file.OpenReadStream()) - { - var (width, height) = ReadImageDimensions(dimensionStream); - if (width <= 0 || height <= 0) - throw new InvalidOperationException("Could not read image dimensions. Please upload a valid image file."); - if (width != height) - throw new InvalidOperationException( - $"Profile picture must be square ({width}×{height} is not square). Please crop your image before uploading."); - } + ValidateAvatar(file); var user = await _userManager.Users .IgnoreQueryFilters() diff --git a/tests/Api.Tests/Helpers/EmailBroadcastServiceTests.cs b/tests/Api.Tests/Helpers/EmailBroadcastServiceTests.cs index a57e4f3..2ea8bf4 100644 --- a/tests/Api.Tests/Helpers/EmailBroadcastServiceTests.cs +++ b/tests/Api.Tests/Helpers/EmailBroadcastServiceTests.cs @@ -45,7 +45,7 @@ public async Task Broadcast_SendsOnlyToEligibleRecipients( email.Setup(service => service.SendCustomEmailAsync( It.IsAny(), "Notice", "

Update

", CancellationToken.None)) .Returns((string address, string _, string _, CancellationToken _) => - sent.Writer.WriteAsync(address).AsTask()); + sent.Writer.WriteAsync(address, CancellationToken.None).AsTask()); var service = CreateService(context, tenant.Object, email.Object); var response = await service.BroadcastAsync(new SendEmailBroadcastRequest { diff --git a/tests/Api.Tests/IntegrationTests/EmailVerificationServiceTests.cs b/tests/Api.Tests/IntegrationTests/EmailVerificationServiceTests.cs new file mode 100644 index 0000000..433a687 --- /dev/null +++ b/tests/Api.Tests/IntegrationTests/EmailVerificationServiceTests.cs @@ -0,0 +1,133 @@ +using Application.DTOs.Auth; +using Application.Exceptions; +using Application.Interfaces.ActivityLogs; +using Application.Interfaces.Email; +using Infrastructure.Authentication.Services; +using Infrastructure.Identity.Entities; +using Infrastructure.Persistence.Contexts; +using Microsoft.AspNetCore.Identity; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging.Abstractions; + +namespace Api.Tests.IntegrationTests; + +[Collection("Integration")] +public class EmailVerificationServiceTests : IClassFixture +{ + private readonly CustomWebApplicationFactory _factory; + + public EmailVerificationServiceTests(CustomWebApplicationFactory factory) => _factory = factory; + + [Fact] + public async Task Resend_ReplacesPendingCode_AndVerificationConsumesLatestCode() + { + using var scope = _factory.Services.CreateScope(); + var (service, context, user, sent) = await ArrangeAsync(scope); + await service.SendVerificationOtpAsync(user.Email!, user.TenantId); + var pending = await context.EmailVerificationOtps.SingleAsync(otp => otp.UserId == user.Id); + + await service.SendOtpAsync(new ResendEmailOtpRequest { Email = user.Email! }); + var replacement = await context.EmailVerificationOtps.SingleAsync(otp => otp.UserId == user.Id); + Assert.NotEqual(pending.Id, replacement.Id); + Assert.Equal(2, sent.Count); + Assert.Equal(6, sent[1].Length); + Assert.NotEqual(sent[1], replacement.OtpHash); + + await service.VerifyOtpAsync(new VerifyEmailOtpRequest { Email = user.Email!, Otp = sent[1] }); + + Assert.True(user.EmailConfirmed); + Assert.NotNull(replacement.UsedAt); + await service.SendOtpAsync(new ResendEmailOtpRequest { Email = user.Email! }); + await service.SendVerificationOtpAsync(user.Email!, user.TenantId); + Assert.Equal(2, sent.Count); + await Assert.ThrowsAsync(() => + service.VerifyOtpAsync(new VerifyEmailOtpRequest { Email = user.Email!, Otp = sent[1] })); + } + + [Theory] + [InlineData("invalid", "Invalid or expired verification code.")] + [InlineData("used", "This verification code has already been used.")] + [InlineData("expired", "This verification code has expired. Please request a new one.")] + public async Task Verify_RejectsUnusableCodes(string state, string expectedMessage) + { + using var scope = _factory.Services.CreateScope(); + var (service, context, user, sent) = await ArrangeAsync(scope); + await service.SendOtpAsync(new ResendEmailOtpRequest { Email = user.Email! }); + var pending = await context.EmailVerificationOtps.SingleAsync(otp => otp.UserId == user.Id); + var code = sent.Single(); + + if (state == "used") + pending.UsedAt = DateTime.UtcNow; + else if (state == "expired") + pending.ExpiresAt = DateTime.UtcNow.AddMinutes(-1); + else + code = code == "100000" ? "100001" : "100000"; + + await context.SaveChangesAsync(); + + var error = await Assert.ThrowsAsync(() => + service.VerifyOtpAsync(new VerifyEmailOtpRequest { Email = user.Email!, Otp = code })); + + Assert.Equal(expectedMessage, error.Message); + Assert.False(user.EmailConfirmed); + } + + [Fact] + public async Task UnknownEmail_DoesNotSendOrRevealAnAccount() + { + using var scope = _factory.Services.CreateScope(); + var (service, _, user, sent) = await ArrangeAsync(scope); + var email = $"{Guid.NewGuid():N}@example.test"; + + await service.SendVerificationOtpAsync(email, user.TenantId); + await service.SendOtpAsync(new ResendEmailOtpRequest { Email = email }); + Assert.Empty(sent); + + var error = await Assert.ThrowsAsync(() => + service.VerifyOtpAsync(new VerifyEmailOtpRequest { Email = email, Otp = "100000" })); + Assert.Equal("Invalid verification request.", error.Message); + } + + [Fact] + public async Task SendOtp_WhenDeliveryFails_KeepsOnePendingCode() + { + using var scope = _factory.Services.CreateScope(); + var (service, context, user, _) = await ArrangeAsync(scope, failDelivery: true); + + await service.SendOtpAsync(new ResendEmailOtpRequest { Email = user.Email! }); + + var pending = await context.EmailVerificationOtps.SingleAsync(otp => otp.UserId == user.Id); + Assert.Null(pending.UsedAt); + Assert.False(user.EmailConfirmed); + } + + private static async Task<(EmailVerificationService Service, ApplicationDbContext Context, + ApplicationUser User, List Sent)> ArrangeAsync(IServiceScope scope, bool failDelivery = false) + { + var context = scope.ServiceProvider.GetRequiredService(); + var manager = scope.ServiceProvider.GetRequiredService>(); + var email = $"{Guid.NewGuid():N}@example.test"; + var user = new ApplicationUser + { + Id = Guid.NewGuid(), + Email = email, + UserName = email, + FullName = "Verification Test", + TenantId = CustomWebApplicationFactory.TestTenantId, + }; + + var created = await manager.CreateAsync(user); + Assert.True(created.Succeeded); + var sent = new List(); + var sender = new Mock(); + sender.Setup(value => value.SendEmailVerificationOtpAsync( + email, user.FullName, It.IsAny(), It.IsAny())) + .Callback((string _, string _, string code, CancellationToken _) => sent.Add(code)) + .Returns(failDelivery ? Task.FromException(new InvalidOperationException("Delivery failed.")) : Task.CompletedTask); + + var service = new EmailVerificationService(context, manager, sender.Object, + Mock.Of(), NullLogger.Instance); + return (service, context, user, sent); + } +} diff --git a/tests/Api.Tests/IntegrationTests/UsersIntegrationTests.cs b/tests/Api.Tests/IntegrationTests/UsersIntegrationTests.cs index e874c91..8a53cf1 100644 --- a/tests/Api.Tests/IntegrationTests/UsersIntegrationTests.cs +++ b/tests/Api.Tests/IntegrationTests/UsersIntegrationTests.cs @@ -192,6 +192,7 @@ public async Task Update_ValidRequest_ReturnsOk() { Email = CustomWebApplicationFactory.TenantUserEmail, FullName = "Updated User Name", + RoleId = CustomWebApplicationFactory.TestRoleId, }; var response = await Client.PutAsync("/api/v1/users", JsonContent(payload)); @@ -376,4 +377,31 @@ public async Task Avatar_UnknownUser_Returns404ForUploadAndRemoval() Assert.Equal(HttpStatusCode.NotFound, upload.StatusCode); Assert.Equal(HttpStatusCode.NotFound, removal.StatusCode); } + + [Fact] + public async Task Update_WithUnknownRole_Returns404() + { + UseTenantAdminAuth(); + var response = await Client.PutAsync("/api/v1/users", JsonContent(new + { + Email = CustomWebApplicationFactory.TenantUserEmail, + FullName = "Unchanged User", + RoleId = Guid.NewGuid(), + })); + + Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); + } + + [Fact] + public async Task CurrentAvatar_TenantAdminCanUploadAndRemove() + { + UseTenantAdminAuth(); + const string endpoint = "/api/v1/users/current/avatar"; + using var content = CreatePngUpload("avatar", "avatar.png"); + + var upload = await Client.PostAsync(endpoint, content); + Assert.Equal(HttpStatusCode.OK, upload.StatusCode); + var remove = await Client.DeleteAsync(endpoint); + Assert.Equal(HttpStatusCode.OK, remove.StatusCode); + } } From 426d7abfd4bdca831fed856fb7d65c772272676a Mon Sep 17 00:00:00 2001 From: arjun Date: Mon, 30 Nov 2026 16:51:33 +0530 Subject: [PATCH 3/4] test: add unit and integration tests for core services - add coverage for avatar dimensions, smtp, email broadcast, and health checks - verify seed execution, super admin seeding, and tenant configuration - validate password reset, avatar uploads, and password updates - extend middleware tests for inactive users and tenants --- .../AcceptTenantAdminInvitationRequest.cs | 11 +- .../AcceptTenantCreationInvitationRequest.cs | 2 +- .../AcceptTenantUserInvitationRequest.cs | 2 +- ...ptTenantAdminInvitationRequestValidator.cs | 34 +--- ...enantCreationInvitationRequestValidator.cs | 43 +--- ...eptTenantUserInvitationRequestValidator.cs | 34 +--- .../Invitations/InvitationAcceptanceRules.cs | 40 ++++ .../Invitations/InvitationService.cs | 81 +++----- src/Infrastructure/Tenant/TenantService.cs | 51 +++-- .../Users/AvatarImageDimensions.cs | 100 ++++++++++ .../Users/UserManagementService.cs | 187 ++++-------------- tests/Api.Tests/Helpers/AddressHelperTests.cs | 136 +++++++++++++ .../Helpers/AvatarImageDimensionsTests.cs | 105 ++++++++++ .../Helpers/EmailBroadcastServiceTests.cs | 51 +++++ tests/Api.Tests/Helpers/SeedRunnerTests.cs | 99 ++++++++++ .../Helpers/SmtpEmailServiceTests.cs | 159 +++++++++++++++ .../Api.Tests/Helpers/SmtpHealthCheckTests.cs | 82 ++++++++ .../Helpers/TenantConfigServiceTests.cs | 124 ++++++++++++ .../MiddlewareIntegrationTests.cs | 59 ++++++ .../PasswordResetServiceTests.cs | 161 +++++++++++++++ .../IntegrationTests/SuperAdminSeedTests.cs | 63 ++++++ .../IntegrationTests/UsersIntegrationTests.cs | 47 +++++ 22 files changed, 1335 insertions(+), 336 deletions(-) create mode 100644 src/Application/Validators/Invitations/InvitationAcceptanceRules.cs create mode 100644 src/Infrastructure/Users/AvatarImageDimensions.cs create mode 100644 tests/Api.Tests/Helpers/AddressHelperTests.cs create mode 100644 tests/Api.Tests/Helpers/AvatarImageDimensionsTests.cs create mode 100644 tests/Api.Tests/Helpers/SeedRunnerTests.cs create mode 100644 tests/Api.Tests/Helpers/SmtpEmailServiceTests.cs create mode 100644 tests/Api.Tests/Helpers/SmtpHealthCheckTests.cs create mode 100644 tests/Api.Tests/Helpers/TenantConfigServiceTests.cs create mode 100644 tests/Api.Tests/IntegrationTests/PasswordResetServiceTests.cs create mode 100644 tests/Api.Tests/IntegrationTests/SuperAdminSeedTests.cs diff --git a/src/Application/DTOs/Invitations/AcceptTenantAdminInvitationRequest.cs b/src/Application/DTOs/Invitations/AcceptTenantAdminInvitationRequest.cs index f04ec2e..183a5af 100644 --- a/src/Application/DTOs/Invitations/AcceptTenantAdminInvitationRequest.cs +++ b/src/Application/DTOs/Invitations/AcceptTenantAdminInvitationRequest.cs @@ -6,7 +6,7 @@ namespace Application.DTOs.Invitations; /// Completes a TenantAdmin invitation. Invited user supplies full profile + /// company information and chooses a password. /// -public class AcceptTenantAdminInvitationRequest +public class AcceptTenantAdminInvitationRequest : IInvitationAcceptanceRequest { public string Token { get; set; } = default!; @@ -33,3 +33,12 @@ public class CompanyInfo public string? Industry { get; set; } } + +public interface IInvitationAcceptanceRequest +{ + string Token { get; } + string FullName { get; } + string? Phone { get; } + string Password { get; } + string ConfirmPassword { get; } +} diff --git a/src/Application/DTOs/Invitations/AcceptTenantCreationInvitationRequest.cs b/src/Application/DTOs/Invitations/AcceptTenantCreationInvitationRequest.cs index 1333ca8..89d11a0 100644 --- a/src/Application/DTOs/Invitations/AcceptTenantCreationInvitationRequest.cs +++ b/src/Application/DTOs/Invitations/AcceptTenantCreationInvitationRequest.cs @@ -2,7 +2,7 @@ namespace Application.DTOs.Invitations; -public class AcceptTenantCreationInvitationRequest +public class AcceptTenantCreationInvitationRequest : IInvitationAcceptanceRequest { public string Token { get; set; } = default!; diff --git a/src/Application/DTOs/Invitations/AcceptTenantUserInvitationRequest.cs b/src/Application/DTOs/Invitations/AcceptTenantUserInvitationRequest.cs index b887cc6..a320b1b 100644 --- a/src/Application/DTOs/Invitations/AcceptTenantUserInvitationRequest.cs +++ b/src/Application/DTOs/Invitations/AcceptTenantUserInvitationRequest.cs @@ -6,7 +6,7 @@ namespace Application.DTOs.Invitations; /// Completes a TenantUser invitation. Invited user supplies basic profile + /// a password. /// -public class AcceptTenantUserInvitationRequest +public class AcceptTenantUserInvitationRequest : IInvitationAcceptanceRequest { public string Token { get; set; } = default!; diff --git a/src/Application/Validators/Invitations/AcceptTenantAdminInvitationRequestValidator.cs b/src/Application/Validators/Invitations/AcceptTenantAdminInvitationRequestValidator.cs index 3b4637e..27556e1 100644 --- a/src/Application/Validators/Invitations/AcceptTenantAdminInvitationRequestValidator.cs +++ b/src/Application/Validators/Invitations/AcceptTenantAdminInvitationRequestValidator.cs @@ -1,5 +1,4 @@ using Application.DTOs.Invitations; -using Application.Validators; using FluentValidation; namespace Application.Validators.Invitations; @@ -9,36 +8,7 @@ public class AcceptTenantAdminInvitationRequestValidator { public AcceptTenantAdminInvitationRequestValidator() { - RuleFor(x => x.Token) - .NotEmpty(); - - RuleFor(x => x.FullName) - .NotEmpty() - .MaximumLength(200); - - RuleFor(x => x.Phone) - .MaximumLength(30) - .When(x => x.Phone != null); - - RuleFor(x => x.Password) - .NotEmpty() - .MinimumLength(8) - .Matches("[A-Z]").WithMessage("Password must contain at least one uppercase letter.") - .Matches("[a-z]").WithMessage("Password must contain at least one lowercase letter.") - .Matches("[0-9]").WithMessage("Password must contain at least one digit.") - .Matches("[^A-Za-z0-9]").WithMessage("Password must contain at least one special character."); - - RuleFor(x => x.ConfirmPassword) - .NotEmpty() - .Equal(x => x.Password).WithMessage("Passwords do not match."); - - RuleFor(x => x.Address) - .NotNull().WithMessage("Address is required."); - - When(x => x.Address != null, () => - { - RuleFor(x => x.Address!) - .SetValidator(new AddressRequestValidator()); - }); + InvitationAcceptanceRules.ApplyCommon(this); + InvitationAcceptanceRules.RequireAddress(this, request => request.Address!, "Address is required."); } } diff --git a/src/Application/Validators/Invitations/AcceptTenantCreationInvitationRequestValidator.cs b/src/Application/Validators/Invitations/AcceptTenantCreationInvitationRequestValidator.cs index 00affd6..c4d1748 100644 --- a/src/Application/Validators/Invitations/AcceptTenantCreationInvitationRequestValidator.cs +++ b/src/Application/Validators/Invitations/AcceptTenantCreationInvitationRequestValidator.cs @@ -1,5 +1,4 @@ using Application.DTOs.Invitations; -using Application.Validators; using FluentValidation; namespace Application.Validators.Invitations; @@ -9,49 +8,13 @@ public class AcceptTenantCreationInvitationRequestValidator { public AcceptTenantCreationInvitationRequestValidator() { - RuleFor(x => x.Token) - .NotEmpty(); - - RuleFor(x => x.FullName) - .NotEmpty() - .MaximumLength(200); - - RuleFor(x => x.Phone) - .MaximumLength(30) - .When(x => x.Phone != null); - - RuleFor(x => x.Password) - .NotEmpty() - .MinimumLength(8) - .Matches("[A-Z]").WithMessage("Password must contain at least one uppercase letter.") - .Matches("[a-z]").WithMessage("Password must contain at least one lowercase letter.") - .Matches("[0-9]").WithMessage("Password must contain at least one digit.") - .Matches("[^A-Za-z0-9]").WithMessage("Password must contain at least one special character."); - - RuleFor(x => x.ConfirmPassword) - .NotEmpty() - .Equal(x => x.Password).WithMessage("Passwords do not match."); + InvitationAcceptanceRules.ApplyCommon(this); RuleFor(x => x.TenantName) .NotEmpty() .MaximumLength(200); - RuleFor(x => x.TenantAddress) - .NotNull().WithMessage("Company address is required."); - - When(x => x.TenantAddress != null, () => - { - RuleFor(x => x.TenantAddress!) - .SetValidator(new AddressRequestValidator()); - }); - - RuleFor(x => x.UserAddress) - .NotNull().WithMessage("Personal address is required."); - - When(x => x.UserAddress != null, () => - { - RuleFor(x => x.UserAddress!) - .SetValidator(new AddressRequestValidator()); - }); + InvitationAcceptanceRules.RequireAddress(this, request => request.TenantAddress!, "Company address is required."); + InvitationAcceptanceRules.RequireAddress(this, request => request.UserAddress!, "Personal address is required."); } } diff --git a/src/Application/Validators/Invitations/AcceptTenantUserInvitationRequestValidator.cs b/src/Application/Validators/Invitations/AcceptTenantUserInvitationRequestValidator.cs index d72d3bd..d4f83f9 100644 --- a/src/Application/Validators/Invitations/AcceptTenantUserInvitationRequestValidator.cs +++ b/src/Application/Validators/Invitations/AcceptTenantUserInvitationRequestValidator.cs @@ -1,5 +1,4 @@ using Application.DTOs.Invitations; -using Application.Validators; using FluentValidation; namespace Application.Validators.Invitations; @@ -9,36 +8,7 @@ public class AcceptTenantUserInvitationRequestValidator { public AcceptTenantUserInvitationRequestValidator() { - RuleFor(x => x.Token) - .NotEmpty(); - - RuleFor(x => x.FullName) - .NotEmpty() - .MaximumLength(200); - - RuleFor(x => x.Phone) - .MaximumLength(30) - .When(x => x.Phone != null); - - RuleFor(x => x.Password) - .NotEmpty() - .MinimumLength(8) - .Matches("[A-Z]").WithMessage("Password must contain at least one uppercase letter.") - .Matches("[a-z]").WithMessage("Password must contain at least one lowercase letter.") - .Matches("[0-9]").WithMessage("Password must contain at least one digit.") - .Matches("[^A-Za-z0-9]").WithMessage("Password must contain at least one special character."); - - RuleFor(x => x.ConfirmPassword) - .NotEmpty() - .Equal(x => x.Password).WithMessage("Passwords do not match."); - - RuleFor(x => x.Address) - .NotNull().WithMessage("Address is required."); - - When(x => x.Address != null, () => - { - RuleFor(x => x.Address!) - .SetValidator(new AddressRequestValidator()); - }); + InvitationAcceptanceRules.ApplyCommon(this); + InvitationAcceptanceRules.RequireAddress(this, request => request.Address!, "Address is required."); } } diff --git a/src/Application/Validators/Invitations/InvitationAcceptanceRules.cs b/src/Application/Validators/Invitations/InvitationAcceptanceRules.cs new file mode 100644 index 0000000..6e36db3 --- /dev/null +++ b/src/Application/Validators/Invitations/InvitationAcceptanceRules.cs @@ -0,0 +1,40 @@ +using Application.DTOs.Common; +using Application.DTOs.Invitations; +using Application.Validators; +using FluentValidation; +using System.Linq.Expressions; + +namespace Application.Validators.Invitations; + +internal static class InvitationAcceptanceRules +{ + public static void ApplyCommon(AbstractValidator validator) + where T : IInvitationAcceptanceRequest + { + validator.RuleFor(request => request.Token).NotEmpty(); + validator.RuleFor(request => request.FullName).NotEmpty().MaximumLength(200); + validator.RuleFor(request => request.Phone) + .MaximumLength(30) + .When(request => request.Phone != null); + validator.RuleFor(request => request.Password) + .NotEmpty() + .MinimumLength(8) + .Matches("[A-Z]").WithMessage("Password must contain at least one uppercase letter.") + .Matches("[a-z]").WithMessage("Password must contain at least one lowercase letter.") + .Matches("[0-9]").WithMessage("Password must contain at least one digit.") + .Matches("[^A-Za-z0-9]").WithMessage("Password must contain at least one special character."); + validator.RuleFor(request => request.ConfirmPassword) + .NotEmpty() + .Equal(request => request.Password).WithMessage("Passwords do not match."); + } + + public static void RequireAddress( + AbstractValidator validator, + Expression> addressSelector, + string message) + { + validator.RuleFor(addressSelector) + .NotNull().WithMessage(message) + .SetValidator(new AddressRequestValidator()); + } +} diff --git a/src/Infrastructure/Invitations/InvitationService.cs b/src/Infrastructure/Invitations/InvitationService.cs index a98d83c..db1667b 100644 --- a/src/Infrastructure/Invitations/InvitationService.cs +++ b/src/Infrastructure/Invitations/InvitationService.cs @@ -469,23 +469,8 @@ public async Task AcceptTenantAdminInvitationAsync( try { // TenantAdmin permissions come from SystemRole — no role table entry needed. - var user = new ApplicationUser - { - Id = Guid.NewGuid(), - TenantId = invitation.TenantId, - SystemRole = SystemRole.TenantAdmin, - FullName = request.FullName, - Email = invitation.Email, - UserName = invitation.Email, - NormalizedEmail = invitation.Email.ToUpperInvariant(), - NormalizedUserName = invitation.Email.ToUpperInvariant(), - EmailConfirmed = true, - PhoneNumber = request.Phone, - IsActive = true, - CreatedVia = CreatedVia.Invitation, - PasswordSetAt = DateTime.UtcNow, - CreatedAt = DateTime.UtcNow, - }; + var user = CreateInvitedUser(invitation, invitation.TenantId, SystemRole.TenantAdmin, + request.FullName, request.Phone); var result = await _userManager.CreateAsync(user, request.Password); @@ -548,23 +533,8 @@ public async Task AcceptTenantUserInvitationAsync( await EnsureRolesExistAsync(roleIds, invitation.TenantId, cancellationToken); - var user = new ApplicationUser - { - Id = Guid.NewGuid(), - TenantId = invitation.TenantId, - SystemRole = SystemRole.TenantUser, - FullName = request.FullName, - Email = invitation.Email, - UserName = invitation.Email, - NormalizedEmail = invitation.Email.ToUpperInvariant(), - NormalizedUserName = invitation.Email.ToUpperInvariant(), - EmailConfirmed = true, - PhoneNumber = request.Phone, - IsActive = true, - CreatedVia = CreatedVia.Invitation, - PasswordSetAt = DateTime.UtcNow, - CreatedAt = DateTime.UtcNow, - }; + var user = CreateInvitedUser(invitation, invitation.TenantId, SystemRole.TenantUser, + request.FullName, request.Phone); var result = await _userManager.CreateAsync(user, request.Password); @@ -663,23 +633,8 @@ public async Task AcceptTenantCreationInvitationAsync( await _context.SaveChangesAsync(cancellationToken); } - var user = new ApplicationUser - { - Id = Guid.NewGuid(), - TenantId = tenant.Id, - SystemRole = SystemRole.TenantAdmin, - FullName = request.FullName, - Email = invitation.Email, - UserName = invitation.Email, - NormalizedEmail = invitation.Email.ToUpperInvariant(), - NormalizedUserName = invitation.Email.ToUpperInvariant(), - EmailConfirmed = true, - PhoneNumber = request.Phone, - IsActive = true, - CreatedVia = CreatedVia.Invitation, - PasswordSetAt = DateTime.UtcNow, - CreatedAt = DateTime.UtcNow, - }; + var user = CreateInvitedUser(invitation, tenant.Id, SystemRole.TenantAdmin, + request.FullName, request.Phone); var result = await _userManager.CreateAsync(user, request.Password); @@ -727,6 +682,30 @@ await LogInternalAsync( // ── Helpers ─────────────────────────────────────────────────────────────── + private static ApplicationUser CreateInvitedUser( + Invitation invitation, + Guid tenantId, + SystemRole systemRole, + string fullName, + string? phone) => + new() + { + Id = Guid.NewGuid(), + TenantId = tenantId, + SystemRole = systemRole, + FullName = fullName, + Email = invitation.Email, + UserName = invitation.Email, + NormalizedEmail = invitation.Email.ToUpperInvariant(), + NormalizedUserName = invitation.Email.ToUpperInvariant(), + EmailConfirmed = true, + PhoneNumber = phone, + IsActive = true, + CreatedVia = CreatedVia.Invitation, + PasswordSetAt = DateTime.UtcNow, + CreatedAt = DateTime.UtcNow, + }; + private async Task<(Invitation Record, string RawToken)> CreateInvitationAsync( Guid tenantId, string email, diff --git a/src/Infrastructure/Tenant/TenantService.cs b/src/Infrastructure/Tenant/TenantService.cs index 90fba05..7674ad3 100644 --- a/src/Infrastructure/Tenant/TenantService.cs +++ b/src/Infrastructure/Tenant/TenantService.cs @@ -242,19 +242,7 @@ await AddressHelper.ApplyTenantAddressUpdateAsync( await LogActivityAsync(ActivityActions.Tenants.Updated, $"Updated tenant '{tenant.Name}'."); - var address = await AddressHelper.GetTenantAddressAsync(_context, tenant.Id); - - var adminEmail = await _context.Users - .AsNoTracking() - .IgnoreQueryFilters() - .Where(u => u.TenantId == tenant.Id - && u.SystemRole == SystemRole.TenantAdmin - && u.DeletedAt == null) - .OrderBy(u => u.CreatedAt) - .Select(u => u.Email) - .FirstOrDefaultAsync(); - - return MapToResponse(tenant, address, adminEmail); + return await MapToResponseAsync(tenant, includeAdminEmail: true); } public async Task UpdateCurrentTenantAddressAsync(UpdateCurrentTenantAddressRequest request) @@ -305,19 +293,7 @@ await AddressHelper.ApplyTenantAddressUpdateAsync( await LogActivityAsync(ActivityActions.Tenants.Updated, $"Updated tenant settings for '{tenant.Name}'."); - var address = await AddressHelper.GetTenantAddressAsync(_context, tenant.Id); - - var adminEmail = await _context.Users - .AsNoTracking() - .IgnoreQueryFilters() - .Where(u => u.TenantId == tenant.Id - && u.SystemRole == SystemRole.TenantAdmin - && u.DeletedAt == null) - .OrderBy(u => u.CreatedAt) - .Select(u => u.Email) - .FirstOrDefaultAsync(); - - return MapToResponse(tenant, address, adminEmail); + return await MapToResponseAsync(tenant, includeAdminEmail: true); } public async Task DeleteAsync(DeleteTenantRequest request) @@ -644,6 +620,29 @@ private static TenantResponse MapToResponse( }; } + private async Task MapToResponseAsync( + Domain.Entities.Tenant tenant, + bool includeAdminEmail) + { + var address = await AddressHelper.GetTenantAddressAsync(_context, tenant.Id); + string? adminEmail = null; + + if (includeAdminEmail) + { + adminEmail = await _context.Users + .AsNoTracking() + .IgnoreQueryFilters() + .Where(user => user.TenantId == tenant.Id + && user.SystemRole == SystemRole.TenantAdmin + && user.DeletedAt == null) + .OrderBy(user => user.CreatedAt) + .Select(user => user.Email) + .FirstOrDefaultAsync(); + } + + return MapToResponse(tenant, address, adminEmail); + } + private async Task LogActivityAsync(string action, string description, Guid? tenantId = null) { await _activityLogService.LogAsync(new LogActivityRequest diff --git a/src/Infrastructure/Users/AvatarImageDimensions.cs b/src/Infrastructure/Users/AvatarImageDimensions.cs new file mode 100644 index 0000000..8fa8764 --- /dev/null +++ b/src/Infrastructure/Users/AvatarImageDimensions.cs @@ -0,0 +1,100 @@ +namespace Infrastructure.Users; + +/// Reads supported image dimensions from a file header without decoding pixels. +internal static class AvatarImageDimensions +{ + internal static (int Width, int Height) Read(Stream stream) + { + try + { + var header = new byte[30]; + var read = stream.Read(header, 0, header.Length); + + if (read < 12) return (0, 0); + + if (read >= 24 + && header[0] == 0x89 && header[1] == 0x50 && header[2] == 0x4E && header[3] == 0x47) + { + return (ReadInt32BE(header, 16), ReadInt32BE(header, 20)); + } + + if (read >= 10 && header[0] == 'G' && header[1] == 'I' && header[2] == 'F') + { + return (ReadUInt16LE(header, 6), ReadUInt16LE(header, 8)); + } + + if (read >= 28 + && header[0] == 'R' && header[1] == 'I' && header[2] == 'F' && header[3] == 'F' + && header[8] == 'W' && header[9] == 'E' && header[10] == 'B' && header[11] == 'P') + { + if (header[12] == 'V' && header[13] == 'P' && header[14] == '8' && header[15] == ' ' + && read >= 30 && header[23] == 0x9D && header[24] == 0x01 && header[25] == 0x2A) + { + return ((ReadUInt16LE(header, 26) & 0x3FFF) + 1, + (ReadUInt16LE(header, 28) & 0x3FFF) + 1); + } + + if (header[12] == 'V' && header[13] == 'P' && header[14] == '8' && header[15] == 'L' + && read >= 25 && header[20] == 0x2F) + { + var bits = ReadUInt32LE(header, 21); + return ((int)(bits & 0x3FFF) + 1, + (int)((bits >> 14) & 0x3FFF) + 1); + } + + if (header[12] == 'V' && header[13] == 'P' && header[14] == '8' && header[15] == 'X' + && read >= 30) + { + var width = header[24] | (header[25] << 8) | (header[26] << 16); + var height = header[27] | (header[28] << 8) | (header[29] << 16); + return (width + 1, height + 1); + } + } + + if (read >= 2 && header[0] == 0xFF && header[1] == 0xD8) + { + return ScanJpegDimensions(stream); + } + } + catch + { + // Malformed or non-seekable streams are reported as unknown dimensions. + } + + return (0, 0); + } + + private static (int Width, int Height) ScanJpegDimensions(Stream stream) + { + stream.Seek(2, SeekOrigin.Begin); + var buffer = new byte[7]; + while (stream.Read(buffer, 0, 2) == 2 && buffer[0] == 0xFF) + { + var marker = buffer[1]; + + if (marker is >= 0xC0 and <= 0xCF and not 0xC4 and not 0xC8 and not 0xCC) + { + if (stream.Read(buffer, 0, 7) < 7) break; + var height = (buffer[3] << 8) | buffer[4]; + var width = (buffer[5] << 8) | buffer[6]; + return (width, height); + } + + if (stream.Read(buffer, 0, 2) < 2) break; + var segmentLength = (buffer[0] << 8) | buffer[1]; + if (segmentLength < 2) break; + stream.Seek(segmentLength - 2, SeekOrigin.Current); + } + + return (0, 0); + } + + private static int ReadInt32BE(byte[] bytes, int offset) => + (bytes[offset] << 24) | (bytes[offset + 1] << 16) | (bytes[offset + 2] << 8) | bytes[offset + 3]; + + private static int ReadUInt16LE(byte[] bytes, int offset) => + bytes[offset] | (bytes[offset + 1] << 8); + + private static uint ReadUInt32LE(byte[] bytes, int offset) => + (uint)(bytes[offset] | (bytes[offset + 1] << 8) | (bytes[offset + 2] << 16) | (bytes[offset + 3] << 24)); +} diff --git a/src/Infrastructure/Users/UserManagementService.cs b/src/Infrastructure/Users/UserManagementService.cs index 3590780..cb5e91b 100644 --- a/src/Infrastructure/Users/UserManagementService.cs +++ b/src/Infrastructure/Users/UserManagementService.cs @@ -18,6 +18,7 @@ using Infrastructure.Onboarding; using Infrastructure.Persistence; using Infrastructure.Persistence.Contexts; +using Infrastructure.Users; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Identity; using Microsoft.EntityFrameworkCore; @@ -338,17 +339,7 @@ public async Task UpdateUserAsync(UpdateUserRequest request) await AddressHelper.ApplyUserAddressUpdateAsync( _context, user, request.Address, request.ClearAddress); - if (!string.IsNullOrWhiteSpace(request.Password)) - { - var token = await _userManager.GeneratePasswordResetTokenAsync(user); - var passwordResult = await _userManager.ResetPasswordAsync(user, token, request.Password); - - if (!passwordResult.Succeeded) - { - throw new InvalidOperationException( - string.Join(", ", passwordResult.Errors.Select(e => e.Description))); - } - } + await UpdatePasswordAsync(user, request.Password); await UpdateRoleAssignmentAsync(user, request.RoleId); @@ -374,17 +365,7 @@ public async Task UpdateCurrentUserAsync(UpdateCurrentUserRequest await AddressHelper.ApplyUserAddressUpdateAsync( _context, user, request.Address, request.ClearAddress); - if (!string.IsNullOrWhiteSpace(request.Password)) - { - var token = await _userManager.GeneratePasswordResetTokenAsync(user); - var passwordResult = await _userManager.ResetPasswordAsync(user, token, request.Password); - - if (!passwordResult.Succeeded) - { - throw new InvalidOperationException( - string.Join(", ", passwordResult.Errors.Select(e => e.Description))); - } - } + await UpdatePasswordAsync(user, request.Password); await _userManager.UpdateAsync(user); @@ -702,7 +683,7 @@ private static void ValidateAvatar(IFormFile file) using (var dimensionStream = file.OpenReadStream()) { - var (width, height) = ReadImageDimensions(dimensionStream); + var (width, height) = AvatarImageDimensions.Read(dimensionStream); if (width <= 0 || height <= 0) throw new InvalidOperationException("Could not read image dimensions. Please upload a valid image file."); if (width != height) @@ -734,19 +715,7 @@ public async Task UploadCurrentUserAvatarAsync(IFormFile file) ValidateAvatar(file); var user = await GetCurrentUserEntityAsync(); - var previousFileId = user.ProfileFileId; - - var uploaded = await _fileService.UploadAsync(file); - - user.ProfileFileId = uploaded.Id; - user.UpdatedAt = DateTime.UtcNow; - await _userManager.UpdateAsync(user); - - if (previousFileId.HasValue) - { - try { await _fileService.DeleteAsync(previousFileId.Value); } - catch { /* old file already gone - not fatal */ } - } + await UploadAvatarAsync(user, file); await LogActivityAsync(ActivityActions.Users.Updated, "Uploaded profile picture."); @@ -774,18 +743,7 @@ public async Task UploadUserAvatarByIdAsync(Guid userId, IFormFile .FirstOrDefaultAsync(u => u.Id == userId && u.DeletedAt == null) ?? throw new NotFoundException(UserNotFoundMessage); - var previousFileId = user.ProfileFileId; - var uploaded = await _fileService.UploadAsync(file); - - user.ProfileFileId = uploaded.Id; - user.UpdatedAt = DateTime.UtcNow; - await _userManager.UpdateAsync(user); - - if (previousFileId.HasValue) - { - try { await _fileService.DeleteAsync(previousFileId.Value); } - catch { /* old file already gone */ } - } + await UploadAvatarAsync(user, file); await LogActivityAsync(ActivityActions.Users.Updated, $"Uploaded profile picture for user '{user.Email}'."); @@ -852,123 +810,48 @@ private async Task GetCurrentUserEntityAsync() ?? throw new NotFoundException(UserNotFoundMessage); } - /// - /// Reads image dimensions from the stream header without decoding pixel data. - /// Supports JPEG, PNG, GIF, and WebP (lossy VP8 and lossless VP8L). - /// Returns (0, 0) when dimensions cannot be determined. - /// - private static (int Width, int Height) ReadImageDimensions(Stream stream) + private async Task FindManagedUserAsync(string email) { - try - { - var h = new byte[30]; - var read = stream.Read(h, 0, h.Length); - - if (read < 12) return (0, 0); - - // PNG: magic \x89PNG\r\n\x1a\n, then IHDR chunk at offset 8 (width at 16, height at 20) - if (read >= 24 - && h[0] == 0x89 && h[1] == 0x50 && h[2] == 0x4E && h[3] == 0x47) - { - return (ReadInt32BE(h, 16), ReadInt32BE(h, 20)); - } - - // GIF: GIF87a / GIF89a — logical width at offset 6, height at offset 8 (little-endian) - if (read >= 10 && h[0] == 'G' && h[1] == 'I' && h[2] == 'F') - { - return (ReadUInt16LE(h, 6), ReadUInt16LE(h, 8)); - } - - // WebP: "RIFF????WEBP VP8 " (lossy) or "RIFF????WEBP VP8L" (lossless) - if (read >= 28 - && h[0] == 'R' && h[1] == 'I' && h[2] == 'F' && h[3] == 'F' - && h[8] == 'W' && h[9] == 'E' && h[10] == 'B' && h[11] == 'P') - { - // Lossy VP8: chunk id "VP8 ", bitstream start code at h[23..25] = 9D 01 2A - if (h[12] == 'V' && h[13] == 'P' && h[14] == '8' && h[15] == ' ' - && read >= 30 && h[23] == 0x9D && h[24] == 0x01 && h[25] == 0x2A) - { - return ((ReadUInt16LE(h, 26) & 0x3FFF) + 1, - (ReadUInt16LE(h, 28) & 0x3FFF) + 1); - } - - // Lossless VP8L: chunk id "VP8L", signature byte 0x2F at h[20] - if (h[12] == 'V' && h[13] == 'P' && h[14] == '8' && h[15] == 'L' - && read >= 25 && h[20] == 0x2F) - { - // Dimensions packed in 28 bits: width-1 (14 bits) | height-1 (14 bits) - var bits = ReadUInt32LE(h, 21); - return ((int)(bits & 0x3FFF) + 1, - (int)((bits >> 14) & 0x3FFF) + 1); - } - - // Extended VP8X: canvas width at byte 24 (3-byte LE, +1), height at 27 (3-byte LE, +1) - if (h[12] == 'V' && h[13] == 'P' && h[14] == '8' && h[15] == 'X' && read >= 30) - { - var w = ((h[24]) | (h[25] << 8) | (h[26] << 16)) + 1; - var ht = ((h[27]) | (h[28] << 8) | (h[29] << 16)) + 1; - return (w, ht); - } - } - - // JPEG: FF D8 — scan for SOF (Start of Frame) marker - if (read >= 2 && h[0] == 0xFF && h[1] == 0xD8) - { - return ScanJpegDimensions(stream); - } - } - catch { } + var normalizedEmail = email.ToUpperInvariant(); + var tenantId = RequireTenantId(); - return (0, 0); + return await _userManager.Users + .FirstOrDefaultAsync(u => + u.NormalizedEmail == normalizedEmail && + u.TenantId == tenantId); } - private static (int Width, int Height) ScanJpegDimensions(Stream stream) + private async Task UpdatePasswordAsync(ApplicationUser user, string? password) { - stream.Seek(2, SeekOrigin.Begin); // skip SOI marker - var buf = new byte[7]; - while (stream.Read(buf, 0, 2) == 2 && buf[0] == 0xFF) + if (string.IsNullOrWhiteSpace(password)) { - var marker = buf[1]; + return; + } - // SOF markers: C0–CF except C4 (DHT), C8 (reserved), CC (DAC) - if (marker is >= 0xC0 and <= 0xCF and not 0xC4 and not 0xC8 and not 0xCC) - { - // Segment layout after FF Cx: - // [0-1] 2B length [2] 1B precision [3-4] 2B height (BE) [5-6] 2B width (BE) - if (stream.Read(buf, 0, 7) < 7) break; - var height = (buf[3] << 8) | buf[4]; - var width = (buf[5] << 8) | buf[6]; - return (width, height); - } + var token = await _userManager.GeneratePasswordResetTokenAsync(user); + var result = await _userManager.ResetPasswordAsync(user, token, password); - // Skip segment body (length includes its own 2 bytes) - if (stream.Read(buf, 0, 2) < 2) break; - var segLen = (buf[0] << 8) | buf[1]; - if (segLen < 2) break; - stream.Seek(segLen - 2, SeekOrigin.Current); + if (!result.Succeeded) + { + throw new InvalidOperationException( + string.Join(", ", result.Errors.Select(error => error.Description))); } - - return (0, 0); } - private static int ReadInt32BE(byte[] b, int offset) => - (b[offset] << 24) | (b[offset + 1] << 16) | (b[offset + 2] << 8) | b[offset + 3]; - - private static int ReadUInt16LE(byte[] b, int offset) => - b[offset] | (b[offset + 1] << 8); - - private static uint ReadUInt32LE(byte[] b, int offset) => - (uint)(b[offset] | (b[offset + 1] << 8) | (b[offset + 2] << 16) | (b[offset + 3] << 24)); - - private async Task FindManagedUserAsync(string email) + private async Task UploadAvatarAsync(ApplicationUser user, IFormFile file) { - var normalizedEmail = email.ToUpperInvariant(); - var tenantId = RequireTenantId(); + var previousFileId = user.ProfileFileId; + var uploaded = await _fileService.UploadAsync(file); - return await _userManager.Users - .FirstOrDefaultAsync(u => - u.NormalizedEmail == normalizedEmail && - u.TenantId == tenantId); + user.ProfileFileId = uploaded.Id; + user.UpdatedAt = DateTime.UtcNow; + await _userManager.UpdateAsync(user); + + if (previousFileId.HasValue) + { + try { await _fileService.DeleteAsync(previousFileId.Value); } + catch { /* the previous file may already be gone */ } + } } private async Task ApplyProfileFileUpdateAsync( diff --git a/tests/Api.Tests/Helpers/AddressHelperTests.cs b/tests/Api.Tests/Helpers/AddressHelperTests.cs new file mode 100644 index 0000000..5f09860 --- /dev/null +++ b/tests/Api.Tests/Helpers/AddressHelperTests.cs @@ -0,0 +1,136 @@ +using Application.DTOs.Common; +using Application.Interfaces.Tenant; +using Domain.Entities; +using Infrastructure.Persistence; +using Infrastructure.Persistence.Contexts; +using Microsoft.EntityFrameworkCore; + +namespace Api.Tests.Helpers; + +public class AddressHelperTests +{ + [Fact] + public async Task ApplyUserAddressUpdate_CreatesUpdatesAndClearsAddress() + { + var tenantId = Guid.NewGuid(); + await using var context = CreateContext(tenantId); + var user = new Infrastructure.Identity.Entities.ApplicationUser { Id = Guid.NewGuid(), TenantId = tenantId }; + var request = Address("1 First St"); + + await AddressHelper.ApplyUserAddressUpdateAsync(context, user, request, clearAddress: false); + await context.SaveChangesAsync(); + var address = await context.Addresses.SingleAsync(); + Assert.Equal(user.Id, address.UserId); + Assert.Equal(tenantId, address.TenantId); + Assert.Equal("1 First St", address.Line1); + + await AddressHelper.ApplyUserAddressUpdateAsync(context, user, null, clearAddress: false); + Assert.Equal("1 First St", address.Line1); + await AddressHelper.ApplyUserAddressUpdateAsync(context, user, Address("2 Second St"), clearAddress: false); + Assert.Equal("2 Second St", address.Line1); + Assert.NotNull(address.UpdatedAt); + + await AddressHelper.ApplyUserAddressUpdateAsync(context, user, null, clearAddress: true); + Assert.Null(address.UserId); + Assert.NotNull(address.DeletedAt); + } + + [Fact] + public async Task ApplyUserAddressUpdate_ClearWithoutExistingAddressIsNoOp() + { + await using var context = CreateContext(Guid.NewGuid()); + var user = new Infrastructure.Identity.Entities.ApplicationUser { Id = Guid.NewGuid() }; + + await AddressHelper.ApplyUserAddressUpdateAsync(context, user, null, clearAddress: true); + + Assert.Empty(await context.Addresses.ToListAsync()); + } + + [Fact] + public async Task ApplyTenantAddressUpdate_CreatesUpdatesAndClearsAddress() + { + var tenantId = Guid.NewGuid(); + await using var context = CreateContext(tenantId); + var tenant = new Tenant { Id = tenantId }; + + await AddressHelper.ApplyTenantAddressUpdateAsync(context, tenant, Address("1 First St"), clearAddress: false); + await context.SaveChangesAsync(); + var address = await context.Addresses.SingleAsync(); + Assert.Equal(tenantId, address.OwnerTenantId); + Assert.Equal(tenantId, address.TenantId); + + await AddressHelper.ApplyTenantAddressUpdateAsync(context, tenant, Address("2 Second St"), clearAddress: false); + Assert.Equal("2 Second St", address.Line1); + Assert.NotNull(address.UpdatedAt); + + await AddressHelper.ApplyTenantAddressUpdateAsync(context, tenant, null, clearAddress: true); + Assert.Null(address.OwnerTenantId); + Assert.NotNull(address.DeletedAt); + } + + [Fact] + public async Task GetAddressCollections_ReturnOnlyActiveRequestedOwners() + { + var tenantId = Guid.NewGuid(); + var otherTenant = Guid.NewGuid(); + var userId = Guid.NewGuid(); + var otherUserId = Guid.NewGuid(); + await using var context = CreateContext(tenantId); + context.Addresses.AddRange( + NewAddress(tenantId, userId, null, "user"), + NewAddress(otherTenant, otherUserId, null, "other"), + NewAddress(tenantId, null, tenantId, "tenant"), + NewAddress(tenantId, Guid.NewGuid(), null, "deleted", deleted: true)); + await context.SaveChangesAsync(); + + Assert.Empty(await AddressHelper.GetUserAddressesAsync(context, [], ignoreTenantFilter: true)); + Assert.Empty(await AddressHelper.GetTenantAddressesAsync(context, [])); + var userAddresses = await AddressHelper.GetUserAddressesAsync(context, [userId, otherUserId], ignoreTenantFilter: false); + Assert.Contains(userId, userAddresses.Keys); + Assert.Contains(otherUserId, userAddresses.Keys); + Assert.Equal("other", (await AddressHelper.GetUserAddressesAsync(context, [otherUserId], ignoreTenantFilter: true))[otherUserId].Line1); + Assert.Equal("tenant", (await AddressHelper.GetTenantAddressesAsync(context, [tenantId]))[tenantId].Line1); + } + + [Fact] + public async Task GetSingleAddress_RespectsTenantFilterOptionAndSkipsDeletedRecords() + { + var tenantId = Guid.NewGuid(); + var otherTenant = Guid.NewGuid(); + var userId = Guid.NewGuid(); + var otherUserId = Guid.NewGuid(); + await using var context = CreateContext(tenantId); + context.Addresses.AddRange( + NewAddress(otherTenant, otherUserId, null, "other"), + NewAddress(tenantId, Guid.NewGuid(), tenantId, "tenant"), + NewAddress(tenantId, userId, null, "deleted-user", deleted: true)); + await context.SaveChangesAsync(); + + Assert.Equal("other", (await AddressHelper.GetUserAddressAsync(context, otherUserId, ignoreTenantFilter: false))?.Line1); + Assert.Equal("other", (await AddressHelper.GetUserAddressAsync(context, otherUserId, ignoreTenantFilter: true))?.Line1); + Assert.Equal("tenant", (await AddressHelper.GetTenantAddressAsync(context, tenantId))?.Line1); + Assert.Null(await AddressHelper.GetUserAddressAsync(context, userId, ignoreTenantFilter: true)); + } + + private static ApplicationDbContext CreateContext(Guid tenantId) + { + var tenant = new Mock(); + tenant.SetupGet(service => service.TenantId).Returns(tenantId); + var options = new DbContextOptionsBuilder() + .UseInMemoryDatabase(Guid.NewGuid().ToString()) + .Options; + return new ApplicationDbContext(options, tenant.Object); + } + + private static AddressRequest Address(string line1) => new() + { + Line1 = line1, City = "Springfield", PostalCode = "12345", Country = "US", + }; + + private static Address NewAddress(Guid tenantId, Guid? userId, Guid? ownerTenantId, string line1, bool deleted = false) => new() + { + Id = Guid.NewGuid(), TenantId = tenantId, UserId = userId, OwnerTenantId = ownerTenantId, + Line1 = line1, City = "Springfield", PostalCode = "12345", Country = "US", + CreatedAt = DateTime.UtcNow, DeletedAt = deleted ? DateTime.UtcNow : null, + }; +} diff --git a/tests/Api.Tests/Helpers/AvatarImageDimensionsTests.cs b/tests/Api.Tests/Helpers/AvatarImageDimensionsTests.cs new file mode 100644 index 0000000..88337d5 --- /dev/null +++ b/tests/Api.Tests/Helpers/AvatarImageDimensionsTests.cs @@ -0,0 +1,105 @@ +using Infrastructure.Users; +using System.Buffers.Binary; +using System.Text; + +namespace Api.Tests.Helpers; + +public class AvatarImageDimensionsTests +{ + [Fact] + public void Read_PngHeader_ReturnsBigEndianDimensions() + { + var header = new byte[24]; + header[0] = 0x89; + Encoding.ASCII.GetBytes("PNG").CopyTo(header, 1); + BinaryPrimitives.WriteInt32BigEndian(header.AsSpan(16, 4), 40); + BinaryPrimitives.WriteInt32BigEndian(header.AsSpan(20, 4), 30); + + Assert.Equal((40, 30), Read(header)); + } + + [Fact] + public void Read_GifHeader_ReturnsLittleEndianDimensions() + { + var header = Encoding.ASCII.GetBytes("GIF89a").Concat(new byte[6]).ToArray(); + header[6] = 40; + header[8] = 30; + + Assert.Equal((40, 30), Read(header)); + } + + [Fact] + public void Read_WebpLossyHeader_ReturnsDimensions() + { + var header = WebpHeader("VP8 "); + header[23] = 0x9D; + header[24] = 0x01; + header[25] = 0x2A; + BinaryPrimitives.WriteUInt16LittleEndian(header.AsSpan(26, 2), 31); + BinaryPrimitives.WriteUInt16LittleEndian(header.AsSpan(28, 2), 29); + + Assert.Equal((32, 30), Read(header)); + } + + [Fact] + public void Read_WebpLosslessHeader_ReturnsPackedDimensions() + { + var header = WebpHeader("VP8L"); + header[20] = 0x2F; + BinaryPrimitives.WriteUInt32LittleEndian(header.AsSpan(21, 4), (29u << 14) | 31u); + + Assert.Equal((32, 30), Read(header)); + } + + [Fact] + public void Read_WebpExtendedHeader_ReturnsCanvasDimensions() + { + var header = WebpHeader("VP8X"); + header[24] = 31; + header[27] = 29; + + Assert.Equal((32, 30), Read(header)); + } + + [Fact] + public void Read_JpegSkipsMetadataAndReadsFrameDimensions() + { + var header = new byte[] + { + 0xFF, 0xD8, + 0xFF, 0xE0, 0x00, 0x04, 0xAA, 0xBB, + 0xFF, 0xC0, 0x00, 0x07, 0x08, 0x00, 0x20, 0x00, 0x30, + }; + + Assert.Equal((48, 32), Read(header)); + } + + [Fact] + public void Read_InvalidOrTooShortHeader_ReturnsUnknownDimensions() + { + Assert.Equal((0, 0), Read([0x01, 0x02, 0x03])); + Assert.Equal((0, 0), Read(new byte[30])); + Assert.Equal((0, 0), AvatarImageDimensions.Read(new NonSeekableStream( + [0xFF, 0xD8, 0xFF, 0xC0, 0, 7, 8, 0, 32, 0, 32, 0]))); + } + + private static (int Width, int Height) Read(byte[] header) => + AvatarImageDimensions.Read(new MemoryStream(header)); + + private static byte[] WebpHeader(string chunk) + { + var header = new byte[30]; + Encoding.ASCII.GetBytes("RIFF").CopyTo(header, 0); + Encoding.ASCII.GetBytes("WEBP").CopyTo(header, 8); + Encoding.ASCII.GetBytes(chunk).CopyTo(header, 12); + return header; + } + + private sealed class NonSeekableStream(byte[] bytes) : MemoryStream(bytes) + { + public override bool CanSeek => false; + + public override long Seek(long offset, SeekOrigin loc) => + throw new NotSupportedException("Seeking is unavailable."); + } +} diff --git a/tests/Api.Tests/Helpers/EmailBroadcastServiceTests.cs b/tests/Api.Tests/Helpers/EmailBroadcastServiceTests.cs index 2ea8bf4..9acce21 100644 --- a/tests/Api.Tests/Helpers/EmailBroadcastServiceTests.cs +++ b/tests/Api.Tests/Helpers/EmailBroadcastServiceTests.cs @@ -7,6 +7,7 @@ using Infrastructure.Identity.Entities; using Infrastructure.Persistence.Contexts; using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; namespace Api.Tests.Helpers; @@ -91,6 +92,37 @@ public async Task Broadcast_RejectsInvalidInput( email.VerifyNoOtherCalls(); } + [Fact] + public async Task Broadcast_WhenDeliveryFails_LogsFailureAndCompletesBackgroundWork() + { + var tenantId = Guid.NewGuid(); + var tenant = new Mock(); + tenant.SetupGet(service => service.IsSystemAdmin).Returns(true); + tenant.SetupGet(service => service.UserId).Returns(Guid.NewGuid()); + await using var context = CreateContext(tenant.Object); + context.Users.Add(CreateUser(Guid.NewGuid(), tenantId, "delivery-fails@example.test")); + await context.SaveChangesAsync(); + + var email = new Mock(); + email.Setup(service => service.SendCustomEmailAsync( + "delivery-fails@example.test", "Notice", "body", CancellationToken.None)) + .Returns(Task.FromException(new IOException("SMTP unavailable"))); + var logger = new RecordingLogger(); + var service = new EmailBroadcastService(context, tenant.Object, email.Object, + Mock.Of(), logger); + + var response = await service.BroadcastAsync(new SendEmailBroadcastRequest + { + Subject = "Notice", HtmlBody = "body", TargetType = BroadcastTarget.AllTenants, + }); + await logger.BroadcastCompleted.Task.WaitAsync(TimeSpan.FromSeconds(5)); + + Assert.Equal(1, response.RecipientCount); + Assert.Contains(logger.Messages, message => message.Contains("Broadcast email failed", StringComparison.Ordinal)); + Assert.Contains(logger.Messages, message => message.Contains("Sent=0 Failed=1", StringComparison.Ordinal)); + email.VerifyAll(); + } + private static ApplicationDbContext CreateContext(ICurrentTenantService tenant) { var options = new DbContextOptionsBuilder() @@ -115,4 +147,23 @@ private static ApplicationUser CreateUser( EmailConfirmed = confirmed, IsActive = active, }; + + private sealed class RecordingLogger : ILogger + { + public List Messages { get; } = []; + public TaskCompletionSource BroadcastCompleted { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); + + public IDisposable? BeginScope(TState state) where TState : notnull => null; + + public bool IsEnabled(LogLevel logLevel) => true; + + public void Log(LogLevel logLevel, EventId eventId, TState state, + Exception? exception, Func formatter) + { + var message = formatter(state, exception); + Messages.Add(message); + if (message.Contains("Email broadcast complete", StringComparison.Ordinal)) + BroadcastCompleted.TrySetResult(); + } + } } diff --git a/tests/Api.Tests/Helpers/SeedRunnerTests.cs b/tests/Api.Tests/Helpers/SeedRunnerTests.cs new file mode 100644 index 0000000..d419d50 --- /dev/null +++ b/tests/Api.Tests/Helpers/SeedRunnerTests.cs @@ -0,0 +1,99 @@ +using Application.Interfaces.Caching; +using Application.Interfaces.Tenant; +using Domain.Entities; +using Infrastructure.Persistence.Contexts; +using Infrastructure.Persistence.Seed; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Logging.Abstractions; + +namespace Api.Tests.Helpers; + +public class SeedRunnerTests +{ + [Fact] + public async Task PendingSeeds_AreOrderedAndExcludeAppliedEntries() + { + await using var context = CreateContext(); + context.SeedHistory.Add(new SeedHistory + { + SeedId = "02_AlreadyApplied", AppliedAt = DateTime.UtcNow, Description = "applied", + }); + await context.SaveChangesAsync(); + var runner = CreateRunner(context, + new FakeSeed("03_Last"), new FakeSeed("02_AlreadyApplied"), new FakeSeed("01_First")); + + var pending = await runner.GetPendingSeedIdsAsync(); + + Assert.Equal(["01_First", "03_Last"], pending); + } + + [Fact] + public async Task ApplyPendingSeeds_RecordsEachSeedAndInvalidatesPermissionCache() + { + await using var context = CreateContext(); + var first = new FakeSeed("02_Permissions"); + var second = new FakeSeed("01_Accounts"); + var cache = new Mock(); + var runner = CreateRunner(context, cache.Object, first, second); + + await runner.ApplyPendingSeedsAsync(); + + Assert.Equal(1, first.ApplyCount); + Assert.Equal(1, second.ApplyCount); + Assert.Equal(new[] { "01_Accounts", "02_Permissions" }, + await context.SeedHistory.OrderBy(history => history.SeedId).Select(history => history.SeedId).ToArrayAsync()); + cache.Verify(value => value.InvalidatePermissionCatalogs(), Times.Once); + + await runner.ApplyPendingSeedsAsync(); + Assert.Equal(1, first.ApplyCount); + Assert.Equal(1, second.ApplyCount); + cache.Verify(value => value.InvalidatePermissionCatalogs(), Times.Once); + } + + [Fact] + public async Task FailedSeed_DoesNotRecordItOrContinueToNextSeed() + { + await using var context = CreateContext(); + var failing = new FakeSeed("01_Failing", fail: true); + var later = new FakeSeed("02_Later"); + var runner = CreateRunner(context, failing, later); + + await Assert.ThrowsAsync(() => runner.ApplyPendingSeedsAsync()); + + Assert.Equal(1, failing.ApplyCount); + Assert.Equal(0, later.ApplyCount); + Assert.Empty(await context.SeedHistory.ToListAsync()); + } + + private static SeedRunner CreateRunner(ApplicationDbContext context, params IDataSeed[] seeds) => + CreateRunner(context, Mock.Of(), seeds); + + private static SeedRunner CreateRunner( + ApplicationDbContext context, IAppCache cache, params IDataSeed[] seeds) => + new(context, seeds, cache, NullLogger.Instance); + + private static ApplicationDbContext CreateContext() + { + var tenant = Mock.Of(); + var options = new DbContextOptionsBuilder() + .UseInMemoryDatabase(Guid.NewGuid().ToString()) + .Options; + return new ApplicationDbContext(options, tenant); + } + + private sealed class FakeSeed(string seedId, bool fail = false) : IDataSeed + { + public string SeedId => seedId; + public string Description => $"Seed {seedId}"; + public int ApplyCount { get; private set; } + + public Task ApplyAsync(CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); + ApplyCount++; + return fail + ? Task.FromException(new InvalidOperationException("Seed failed.")) + : Task.CompletedTask; + } + } +} diff --git a/tests/Api.Tests/Helpers/SmtpEmailServiceTests.cs b/tests/Api.Tests/Helpers/SmtpEmailServiceTests.cs new file mode 100644 index 0000000..ad56110 --- /dev/null +++ b/tests/Api.Tests/Helpers/SmtpEmailServiceTests.cs @@ -0,0 +1,159 @@ +using System.Net; +using System.Net.Sockets; +using System.Text; +using Infrastructure.Email; +using Microsoft.Extensions.Options; +using Microsoft.Extensions.Logging.Abstractions; + +namespace Api.Tests.Helpers; + +public class SmtpEmailServiceTests +{ + [Fact] + public async Task PublicSendMethods_ConnectAndSendRenderedMessages() + { + var captures = new List(); + var sendMethods = new Func[] + { + service => service.SendAccountSetupEmailAsync("to@example.test", "Alex", "https://app.test/setup"), + service => service.SendWelcomeEmailAsync("to@example.test", "Alex", "https://app.test/login"), + service => service.SendTenantAdminInvitationAsync("to@example.test", "https://app.test/invite", "Tenant"), + service => service.SendTenantUserInvitationAsync("to@example.test", "https://app.test/invite", "Tenant"), + service => service.SendNewTenantInvitationAsync("to@example.test", "https://app.test/invite"), + service => service.SendAccountActivationEmailAsync("to@example.test", "Alex", "https://app.test/login"), + service => service.SendAccountDeactivationEmailAsync("to@example.test", "Alex"), + service => service.SendPasswordResetEmailAsync("to@example.test", "Alex", "https://app.test/reset"), + service => service.SendEmailVerificationOtpAsync("to@example.test", "Alex", "123456"), + service => service.SendCustomEmailAsync("to@example.test", "Custom notice", "

Body

"), + }; + + foreach (var send in sendMethods) + { + using var listener = new TcpListener(IPAddress.Loopback, 0); + listener.Start(); + var port = ((IPEndPoint)listener.LocalEndpoint).Port; + var server = AcceptMessageAsync(listener); + var service = CreateService(new SmtpSettings + { + Host = "127.0.0.1", Port = port, EnableSsl = false, + FromName = "MultiTenant", FromAddress = "noreply@example.test", + }); + + await send(service); + captures.Add(await server); + } + + Assert.Equal(sendMethods.Length, captures.Count); + Assert.Contains("Subject: Custom notice", captures[^1]); + Assert.Contains("

Body

", captures[^1]); + Assert.All(captures, message => + { + Assert.Contains("From: MultiTenant ", message); + Assert.Contains("To: to@example.test", message); + }); + } + + [Fact] + public async Task SendCustomEmail_WhenCredentialsAreConfigured_Authenticates() + { + using var listener = new TcpListener(IPAddress.Loopback, 0); + listener.Start(); + var port = ((IPEndPoint)listener.LocalEndpoint).Port; + var server = AcceptMessageAsync(listener, authenticate: true); + var service = CreateService(new SmtpSettings + { + Host = "127.0.0.1", Port = port, EnableSsl = false, + Username = "smtp-user", Password = "smtp-password", + FromName = "MultiTenant", FromAddress = "noreply@example.test", + }); + + await service.SendCustomEmailAsync("to@example.test", "Authenticated", "body"); + + Assert.Contains("Subject: Authenticated", await server); + } + + [Fact] + public async Task SendCustomEmail_WhenSslIsRequired_RejectsServerWithoutStartTls() + { + using var listener = new TcpListener(IPAddress.Loopback, 0); + listener.Start(); + var port = ((IPEndPoint)listener.LocalEndpoint).Port; + var server = AcceptMessageAsync(listener); + var service = CreateService(new SmtpSettings + { + Host = "127.0.0.1", Port = port, EnableSsl = true, + FromName = "MultiTenant", FromAddress = "noreply@example.test", + }); + + await Assert.ThrowsAsync(() => + service.SendCustomEmailAsync("to@example.test", "Secure", "body")); + await server; + } + + private static SmtpEmailService CreateService(SmtpSettings settings) => + new(Options.Create(settings), NullLogger.Instance); + + private static async Task AcceptMessageAsync(TcpListener listener, bool authenticate = false) + { + using var client = await listener.AcceptTcpClientAsync().WaitAsync(TimeSpan.FromSeconds(5)); + using var stream = client.GetStream(); + using var reader = new StreamReader(stream, leaveOpen: true); + using var writer = new StreamWriter(stream) { AutoFlush = true, NewLine = "\r\n" }; + var message = new StringBuilder(); + await writer.WriteLineAsync("220 localhost ESMTP"); + + while (await reader.ReadLineAsync().WaitAsync(TimeSpan.FromSeconds(5)) is { } command) + { + if (command.StartsWith("EHLO", StringComparison.OrdinalIgnoreCase)) + { + await writer.WriteLineAsync("250-localhost"); + await writer.WriteLineAsync(authenticate ? "250-AUTH PLAIN LOGIN" : "250 SIZE 20480000"); + if (authenticate) + await writer.WriteLineAsync("250 SIZE 20480000"); + } + else if (command.StartsWith("AUTH PLAIN", StringComparison.OrdinalIgnoreCase)) + { + if (command.Length == "AUTH PLAIN".Length) + { + await writer.WriteLineAsync("334 "); + _ = await reader.ReadLineAsync().WaitAsync(TimeSpan.FromSeconds(5)); + } + await writer.WriteLineAsync("235 2.7.0 Authentication successful"); + } + else if (command.StartsWith("AUTH LOGIN", StringComparison.OrdinalIgnoreCase)) + { + await writer.WriteLineAsync("334 VXNlcm5hbWU6"); + _ = await reader.ReadLineAsync().WaitAsync(TimeSpan.FromSeconds(5)); + await writer.WriteLineAsync("334 UGFzc3dvcmQ6"); + _ = await reader.ReadLineAsync().WaitAsync(TimeSpan.FromSeconds(5)); + await writer.WriteLineAsync("235 2.7.0 Authentication successful"); + } + else if (command.StartsWith("MAIL FROM", StringComparison.OrdinalIgnoreCase) + || command.StartsWith("RCPT TO", StringComparison.OrdinalIgnoreCase)) + { + await writer.WriteLineAsync("250 2.1.0 OK"); + } + else if (command.Equals("DATA", StringComparison.OrdinalIgnoreCase)) + { + await writer.WriteLineAsync("354 End data with ."); + while (await reader.ReadLineAsync().WaitAsync(TimeSpan.FromSeconds(5)) is { } line + && line != ".") + { + message.AppendLine(line); + } + await writer.WriteLineAsync("250 2.0.0 queued"); + } + else if (command.StartsWith("QUIT", StringComparison.OrdinalIgnoreCase)) + { + await writer.WriteLineAsync("221 2.0.0 Goodbye"); + return message.ToString(); + } + else + { + await writer.WriteLineAsync("250 OK"); + } + } + + return message.ToString(); + } +} diff --git a/tests/Api.Tests/Helpers/SmtpHealthCheckTests.cs b/tests/Api.Tests/Helpers/SmtpHealthCheckTests.cs new file mode 100644 index 0000000..67625bc --- /dev/null +++ b/tests/Api.Tests/Helpers/SmtpHealthCheckTests.cs @@ -0,0 +1,82 @@ +using System.Net; +using System.Net.Sockets; +using Infrastructure.Email; +using Microsoft.Extensions.Diagnostics.HealthChecks; +using Microsoft.Extensions.Options; +using Microsoft.Extensions.Logging.Abstractions; + +namespace Api.Tests.Helpers; + +public class SmtpHealthCheckTests +{ + [Fact] + public async Task CheckHealthAsync_WhenNoHostIsConfigured_ReturnsHealthyStubMode() + { + var check = CreateCheck(new SmtpSettings { Host = " " }); + + var result = await check.CheckHealthAsync(new HealthCheckContext()); + + Assert.True(result.Status == HealthStatus.Healthy, result.Description); + Assert.Contains("stub mode", result.Description); + } + + [Fact] + public async Task CheckHealthAsync_WhenSmtpAcceptsConnection_ReturnsHealthy() + { + using var listener = new TcpListener(IPAddress.Loopback, 0); + listener.Start(); + var port = ((IPEndPoint)listener.LocalEndpoint).Port; + var server = RespondToHealthCheckAsync(listener); + var check = CreateCheck(new SmtpSettings { Host = "127.0.0.1", Port = port, EnableSsl = false }); + + var result = await check.CheckHealthAsync(new HealthCheckContext()); + + Assert.True(result.Status == HealthStatus.Healthy, result.Description); + Assert.Contains($"127.0.0.1:{port}", result.Description); + await server; + } + + [Fact] + public async Task CheckHealthAsync_WhenSmtpCannotBeReached_ReturnsDegraded() + { + using var listener = new TcpListener(IPAddress.Loopback, 0); + listener.Start(); + var port = ((IPEndPoint)listener.LocalEndpoint).Port; + listener.Stop(); + var check = CreateCheck(new SmtpSettings { Host = "127.0.0.1", Port = port }); + + var result = await check.CheckHealthAsync(new HealthCheckContext()); + + Assert.Equal(HealthStatus.Degraded, result.Status); + Assert.Contains("SMTP unreachable", result.Description); + } + + private static SmtpHealthCheck CreateCheck(SmtpSettings settings) => + new(Options.Create(settings), NullLogger.Instance); + + private static async Task RespondToHealthCheckAsync(TcpListener listener) + { + using var client = await listener.AcceptTcpClientAsync().WaitAsync(TimeSpan.FromSeconds(5)); + using var stream = client.GetStream(); + using var reader = new StreamReader(stream, leaveOpen: true); + using var writer = new StreamWriter(stream) { AutoFlush = true, NewLine = "\r\n" }; + await writer.WriteLineAsync("220 localhost ESMTP"); + + while (await reader.ReadLineAsync().WaitAsync(TimeSpan.FromSeconds(5)) is { } command) + { + if (command.StartsWith("EHLO", StringComparison.OrdinalIgnoreCase)) + { + await writer.WriteLineAsync("250 localhost"); + } + else if (command.StartsWith("QUIT", StringComparison.OrdinalIgnoreCase)) + { + await writer.WriteLineAsync("221 Goodbye"); + return; + } + else + { + await writer.WriteLineAsync("250 OK"); + } + } + } +} diff --git a/tests/Api.Tests/Helpers/TenantConfigServiceTests.cs b/tests/Api.Tests/Helpers/TenantConfigServiceTests.cs new file mode 100644 index 0000000..208df65 --- /dev/null +++ b/tests/Api.Tests/Helpers/TenantConfigServiceTests.cs @@ -0,0 +1,124 @@ +using Application.DTOs.TenantConfig; +using Application.Exceptions; +using Application.Interfaces.Authentication; +using Application.Interfaces.Tenant; +using Infrastructure.Persistence.Contexts; +using Infrastructure.TenantConfig; +using Microsoft.EntityFrameworkCore; + +namespace Api.Tests.Helpers; + +public class TenantConfigServiceTests +{ + [Fact] + public async Task GetCurrent_CreatesDefaultConfigOnce() + { + var tenantId = Guid.NewGuid(); + await using var context = CreateContext(tenantId); + var service = CreateService(context, CurrentTenant(tenantId, isSystemAdmin: false)); + + var first = await service.GetCurrentAsync(); + var second = await service.GetCurrentAsync(); + + Assert.Equal(tenantId, first.TenantId); + Assert.True(first.LoginEnabled); + Assert.True(first.WelcomeEmailEnabled); + Assert.False(first.MaintenanceMode); + Assert.Equal(first.TenantId, second.TenantId); + Assert.Equal(first.LoginEnabled, second.LoginEnabled); + Assert.Single(await context.TenantConfigs.ToListAsync()); + } + + [Fact] + public async Task UpdateByTenantId_DisablingLoginRevokesTenantRefreshTokens() + { + var tenantId = Guid.NewGuid(); + await using var context = CreateContext(null); + var refresh = new Mock(); + var service = CreateService(context, CurrentTenant(null, isSystemAdmin: true), refresh); + await service.GetByTenantIdAsync(tenantId); + + var response = await service.UpdateByTenantIdAsync(new UpdateTenantConfigRequest + { + TenantId = tenantId, LoginEnabled = false, WelcomeEmailEnabled = false, + MaintenanceMode = true, MaintenanceMessage = "Maintenance", + }); + + Assert.False(response.LoginEnabled); + Assert.False(response.WelcomeEmailEnabled); + Assert.True(response.MaintenanceMode); + Assert.Equal("Maintenance", response.MaintenanceMessage); + refresh.Verify(value => value.RevokeAllForTenantAsync(tenantId), Times.Once); + + await service.UpdateByTenantIdAsync(new UpdateTenantConfigRequest + { + TenantId = tenantId, LoginEnabled = false, WelcomeEmailEnabled = true, + }); + refresh.Verify(value => value.RevokeAllForTenantAsync(tenantId), Times.Once); + } + + [Fact] + public async Task UpdateCurrent_PreservesSystemAdminMaintenanceSettings() + { + var tenantId = Guid.NewGuid(); + await using var context = CreateContext(tenantId); + context.TenantConfigs.Add(new Domain.Entities.TenantConfig + { + Id = Guid.NewGuid(), TenantId = tenantId, LoginEnabled = true, + WelcomeEmailEnabled = true, MaintenanceMode = true, MaintenanceMessage = "System maintenance", + }); + await context.SaveChangesAsync(); + var refresh = new Mock(); + var service = CreateService(context, CurrentTenant(tenantId, isSystemAdmin: false), refresh); + + var response = await service.UpdateCurrentAsync(new UpdateCurrentTenantConfigRequest + { + LoginEnabled = false, WelcomeEmailEnabled = false, + }); + + Assert.False(response.LoginEnabled); + Assert.False(response.WelcomeEmailEnabled); + Assert.True(response.MaintenanceMode); + Assert.Equal("System maintenance", response.MaintenanceMessage); + refresh.Verify(value => value.RevokeAllForTenantAsync(tenantId), Times.Once); + } + + [Fact] + public async Task SystemAdminOnlyMethods_RejectTenantAdmin() + { + var tenantId = Guid.NewGuid(); + await using var context = CreateContext(tenantId); + var service = CreateService(context, CurrentTenant(tenantId, isSystemAdmin: false)); + + await Assert.ThrowsAsync(() => service.GetByTenantIdAsync(Guid.NewGuid())); + await Assert.ThrowsAsync(() => service.UpdateByTenantIdAsync( + new UpdateTenantConfigRequest { TenantId = Guid.NewGuid() })); + } + + private static TenantConfigService CreateService( + ApplicationDbContext context, + ICurrentTenantService tenant, + Mock? refresh = null) => + new(context, tenant, refresh?.Object ?? Mock.Of(), + Mock.Of()); + + private static ApplicationDbContext CreateContext(Guid? tenantId) + { + var tenant = new Mock(); + tenant.SetupGet(value => value.TenantId).Returns(tenantId); + tenant.SetupGet(value => value.UserId).Returns(Guid.NewGuid()); + var options = new DbContextOptionsBuilder() + .UseInMemoryDatabase(Guid.NewGuid().ToString()) + .Options; + return new ApplicationDbContext(options, tenant.Object); + } + + private static ICurrentTenantService CurrentTenant(Guid? tenantId, bool isSystemAdmin) + { + var tenant = new Mock(); + tenant.SetupGet(value => value.TenantId).Returns(tenantId); + tenant.SetupGet(value => value.UserId).Returns(Guid.NewGuid()); + tenant.SetupGet(value => value.IsSystemAdmin).Returns(isSystemAdmin); + return tenant.Object; + } +} diff --git a/tests/Api.Tests/IntegrationTests/MiddlewareIntegrationTests.cs b/tests/Api.Tests/IntegrationTests/MiddlewareIntegrationTests.cs index a5db879..be8a3c5 100644 --- a/tests/Api.Tests/IntegrationTests/MiddlewareIntegrationTests.cs +++ b/tests/Api.Tests/IntegrationTests/MiddlewareIntegrationTests.cs @@ -1,5 +1,12 @@ using System.Net; +using System.Net.Http.Headers; using System.Text.Json; +using Domain.Enums; +using Infrastructure.Identity.Entities; +using Infrastructure.Persistence.Contexts; +using Microsoft.AspNetCore.Identity; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; namespace Api.Tests.IntegrationTests; @@ -68,6 +75,58 @@ public async Task ActiveUser_CanAccessProtectedEndpoints() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } + [Fact] + public async Task InactiveUser_IsRejectedByStatusMiddleware() + { + Client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", GenerateToken( + CustomWebApplicationFactory.TestInactiveUserId, + CustomWebApplicationFactory.TestInactiveUserEmail, + "Inactive Setup User", + CustomWebApplicationFactory.TestTenantId, + SystemRole.TenantUser)); + + var response = await Client.GetAsync("/api/v1/auth/me"); + var payload = JsonDocument.Parse(await response.Content.ReadAsStringAsync()); + + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + Assert.Equal("user_inactive", payload.RootElement.GetProperty("errors").GetProperty("code").GetString()); + } + + [Fact] + public async Task InactiveTenant_IsRejectedByStatusMiddleware() + { + var tenantId = Guid.NewGuid(); + var userId = Guid.NewGuid(); + var email = $"inactive-tenant-{Guid.NewGuid():N}@test.com"; + using (var scope = Factory.Services.CreateScope()) + { + var context = scope.ServiceProvider.GetRequiredService(); + context.Tenants.Add(new Domain.Entities.Tenant + { + Id = tenantId, Name = "Inactive test tenant", IsActive = false, + CreatedVia = CreatedVia.Direct, CreatedAt = DateTime.UtcNow, + }); + await context.SaveChangesAsync(); + var manager = scope.ServiceProvider.GetRequiredService>(); + var user = new ApplicationUser + { + Id = userId, TenantId = tenantId, Email = email, UserName = email, + FullName = "Inactive Tenant User", EmailConfirmed = true, IsActive = true, + CreatedVia = CreatedVia.Direct, CreatedAt = DateTime.UtcNow, + }; + Assert.True((await manager.CreateAsync(user, "TenantUser123!")).Succeeded); + } + + Client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", GenerateToken( + userId, email, "Inactive Tenant User", tenantId, SystemRole.TenantUser)); + + var response = await Client.GetAsync("/api/v1/auth/me"); + var payload = JsonDocument.Parse(await response.Content.ReadAsStringAsync()); + + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + Assert.Equal("tenant_inactive", payload.RootElement.GetProperty("errors").GetProperty("code").GetString()); + } + // ── Error responses are envelope format ─────────────────────────────────── [Fact] diff --git a/tests/Api.Tests/IntegrationTests/PasswordResetServiceTests.cs b/tests/Api.Tests/IntegrationTests/PasswordResetServiceTests.cs new file mode 100644 index 0000000..8e4fafb --- /dev/null +++ b/tests/Api.Tests/IntegrationTests/PasswordResetServiceTests.cs @@ -0,0 +1,161 @@ +using Application.DTOs.Auth; +using Application.Exceptions; +using Application.Interfaces.ActivityLogs; +using Application.Interfaces.Email; +using Domain.Entities; +using Domain.Enums; +using Infrastructure.Authentication.Services; +using Infrastructure.Identity.Entities; +using Infrastructure.Persistence.Contexts; +using Microsoft.AspNetCore.Identity; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging.Abstractions; + +namespace Api.Tests.IntegrationTests; + +[Collection("Integration")] +public class PasswordResetServiceTests : IClassFixture +{ + private readonly CustomWebApplicationFactory _factory; + + public PasswordResetServiceTests(CustomWebApplicationFactory factory) => _factory = factory; + + [Fact] + public async Task SendAndResetPassword_StoresOnlyHashAndConsumesToken() + { + using var scope = _factory.Services.CreateScope(); + var (service, context, manager, user, sent) = await ArrangeAsync(scope); + var oldToken = new PasswordResetToken + { + Id = Guid.NewGuid(), UserId = user.Id, TenantId = user.TenantId, + TokenHash = Guid.NewGuid().ToString("N"), ExpiresAt = DateTime.UtcNow.AddHours(1), + CreatedAt = DateTime.UtcNow, + }; + context.PasswordResetTokens.Add(oldToken); + await context.SaveChangesAsync(); + + await service.SendResetEmailAsync(new ForgotPasswordRequest { Email = user.Email! }); + + Assert.NotNull(oldToken.UsedAt); + var stored = await context.PasswordResetTokens.SingleAsync(token => token.UserId == user.Id && token.Id != oldToken.Id); + var rawToken = Assert.IsType(sent.Single()); + Assert.NotEqual(rawToken, stored.TokenHash); + Assert.Equal(Infrastructure.Onboarding.TokenHelper.Hash(rawToken), stored.TokenHash); + Assert.True((await service.ValidateTokenAsync(rawToken)).IsValid); + + await service.ResetPasswordAsync(new ResetPasswordRequest + { + Token = rawToken, NewPassword = "NewPass123!", ConfirmPassword = "NewPass123!", + }); + + Assert.NotNull(stored.UsedAt); + Assert.True(await manager.CheckPasswordAsync(user, "NewPass123!")); + Assert.False((await service.ValidateTokenAsync(rawToken)).IsValid); + } + + [Fact] + public async Task SendResetEmail_RejectsUnknownAndInactiveAccounts() + { + using var scope = _factory.Services.CreateScope(); + var (service, _, _, user, sent) = await ArrangeAsync(scope); + + await Assert.ThrowsAsync(() => service.SendResetEmailAsync( + new ForgotPasswordRequest { Email = $"missing-{Guid.NewGuid():N}@example.test" })); + + user.IsActive = false; + await scope.ServiceProvider.GetRequiredService>().UpdateAsync(user); + await Assert.ThrowsAsync(() => service.SendResetEmailAsync( + new ForgotPasswordRequest { Email = user.Email! })); + Assert.Empty(sent); + } + + [Theory] + [InlineData("missing", "Token not found or already used.")] + [InlineData("used", "This reset link has already been used.")] + [InlineData("expired", "This reset link has expired. Please request a new one.")] + public async Task ValidateToken_RejectsMissingUsedAndExpiredTokens(string state, string expected) + { + using var scope = _factory.Services.CreateScope(); + var (service, context, _, user, _) = await ArrangeAsync(scope); + var raw = Guid.NewGuid().ToString("N"); + if (state != "missing") + { + var token = CreateToken(user, raw); + if (state == "used") token.UsedAt = DateTime.UtcNow; + if (state == "expired") token.ExpiresAt = DateTime.UtcNow.AddMinutes(-1); + context.PasswordResetTokens.Add(token); + await context.SaveChangesAsync(); + } + + var result = await service.ValidateTokenAsync(raw); + + Assert.False(result.IsValid); + Assert.Equal(expected, result.ErrorMessage); + } + + [Fact] + public async Task SendResetEmail_DeliveryFailureKeepsStoredToken() + { + using var scope = _factory.Services.CreateScope(); + var (service, context, _, user, _) = await ArrangeAsync(scope, failDelivery: true); + + await service.SendResetEmailAsync(new ForgotPasswordRequest { Email = user.Email! }); + + Assert.Single(await context.PasswordResetTokens.Where(token => token.UserId == user.Id).ToListAsync()); + } + + [Fact] + public async Task ResetPassword_RejectsMismatchedPasswordAndInvalidToken() + { + using var scope = _factory.Services.CreateScope(); + var (service, _, _, _, _) = await ArrangeAsync(scope); + + await Assert.ThrowsAsync(() => service.ResetPasswordAsync( + new ResetPasswordRequest { Token = "ignored", NewPassword = "one", ConfirmPassword = "two" })); + await Assert.ThrowsAsync(() => service.ResetPasswordAsync( + new ResetPasswordRequest { Token = "missing", NewPassword = "one", ConfirmPassword = "one" })); + } + + private async Task<(PasswordResetService Service, ApplicationDbContext Context, + UserManager Manager, ApplicationUser User, List Sent)> ArrangeAsync( + IServiceScope scope, bool failDelivery = false) + { + var context = scope.ServiceProvider.GetRequiredService(); + var manager = scope.ServiceProvider.GetRequiredService>(); + var emailAddress = $"password-reset-{Guid.NewGuid():N}@example.test"; + var user = new ApplicationUser + { + Id = Guid.NewGuid(), Email = emailAddress, UserName = emailAddress, FullName = "Reset Test", + TenantId = CustomWebApplicationFactory.TestTenantId, SystemRole = SystemRole.TenantUser, + IsActive = true, EmailConfirmed = true, CreatedAt = DateTime.UtcNow, + }; + Assert.True((await manager.CreateAsync(user, "OldPass123!")).Succeeded); + + var sent = new List(); + var sender = new Mock(); + sender.Setup(email => email.SendPasswordResetEmailAsync( + emailAddress, user.FullName, It.IsAny(), It.IsAny())) + .Callback((string _, string _, string url, CancellationToken _) => + { + var token = System.Web.HttpUtility.ParseQueryString(new Uri(url).Query)["token"]; + sent.Add(token!); + }) + .Returns(failDelivery + ? Task.FromException(new InvalidOperationException("SMTP unavailable")) + : Task.CompletedTask); + + var service = new PasswordResetService(context, manager, sender.Object, + Mock.Of(), NullLogger.Instance, + scope.ServiceProvider.GetRequiredService()); + return (service, context, manager, user, sent); + } + + private static PasswordResetToken CreateToken(ApplicationUser user, string rawToken) => new() + { + Id = Guid.NewGuid(), UserId = user.Id, TenantId = user.TenantId, + TokenHash = Infrastructure.Onboarding.TokenHelper.Hash(rawToken), + ExpiresAt = DateTime.UtcNow.AddHours(1), CreatedAt = DateTime.UtcNow, + }; +} diff --git a/tests/Api.Tests/IntegrationTests/SuperAdminSeedTests.cs b/tests/Api.Tests/IntegrationTests/SuperAdminSeedTests.cs new file mode 100644 index 0000000..62e14ae --- /dev/null +++ b/tests/Api.Tests/IntegrationTests/SuperAdminSeedTests.cs @@ -0,0 +1,63 @@ +using Domain.Enums; +using Infrastructure.Identity.Entities; +using Infrastructure.Persistence.Seed.Seeds; +using Microsoft.AspNetCore.Identity; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; + +namespace Api.Tests.IntegrationTests; + +[Collection("Integration")] +public class SuperAdminSeedTests : IClassFixture +{ + private readonly CustomWebApplicationFactory _factory; + + public SuperAdminSeedTests(CustomWebApplicationFactory factory) => _factory = factory; + + [Fact] + public async Task ApplyAsync_CreatesSystemAdminOnce() + { + using var scope = _factory.Services.CreateScope(); + var manager = scope.ServiceProvider.GetRequiredService>(); + var seed = CreateSeed(manager, "SuperAdmin123!"); + + await seed.ApplyAsync(); + await seed.ApplyAsync(); + + var admins = await manager.Users.IgnoreQueryFilters() + .Where(user => user.Email == "admin@system.com" && user.TenantId == Guid.Empty) + .ToListAsync(); + var admin = Assert.Single(admins); + Assert.Equal(SystemRole.SystemAdmin, admin.SystemRole); + Assert.True(admin.EmailConfirmed); + Assert.True(admin.IsActive); + Assert.True(await manager.CheckPasswordAsync(admin, "SuperAdmin123!")); + } + + [Theory] + [InlineData(null)] + [InlineData("")] + [InlineData(" ")] + public async Task ApplyAsync_RequiresConfiguredAdminPassword(string? password) + { + using var scope = _factory.Services.CreateScope(); + var manager = scope.ServiceProvider.GetRequiredService>(); + var seed = CreateSeed(manager, password); + + var error = await Assert.ThrowsAsync(() => seed.ApplyAsync()); + + Assert.Contains("Seeding:AdminPassword must be configured", error.Message); + } + + private static SuperAdminSeed CreateSeed(UserManager manager, string? password) + { + var configuration = new ConfigurationBuilder() + .AddInMemoryCollection(new Dictionary + { + ["Seeding:AdminPassword"] = password, + }) + .Build(); + return new SuperAdminSeed(manager, configuration); + } +} diff --git a/tests/Api.Tests/IntegrationTests/UsersIntegrationTests.cs b/tests/Api.Tests/IntegrationTests/UsersIntegrationTests.cs index 8a53cf1..f523a6b 100644 --- a/tests/Api.Tests/IntegrationTests/UsersIntegrationTests.cs +++ b/tests/Api.Tests/IntegrationTests/UsersIntegrationTests.cs @@ -1,5 +1,6 @@ using System.Net; using System.Text.Json; +using Microsoft.Extensions.DependencyInjection; namespace Api.Tests.IntegrationTests; @@ -404,4 +405,50 @@ public async Task CurrentAvatar_TenantAdminCanUploadAndRemove() var remove = await Client.DeleteAsync(endpoint); Assert.Equal(HttpStatusCode.OK, remove.StatusCode); } + + [Fact] + public async Task UserAvatar_TenantAdminCanUploadAndRemoveByUserId() + { + UseTenantAdminAuth(); + var endpoint = $"/api/v1/users/{CustomWebApplicationFactory.TenantUserId}/avatar"; + using var content = CreatePngUpload("avatar", "user-avatar.png"); + + var upload = await Client.PostAsync(endpoint, content); + Assert.Equal(HttpStatusCode.OK, upload.StatusCode); + var get = await Client.GetAsync(endpoint); + Assert.Equal(HttpStatusCode.OK, get.StatusCode); + Assert.Equal("image/webp", get.Content.Headers.ContentType?.MediaType); + var remove = await Client.DeleteAsync(endpoint); + Assert.Equal(HttpStatusCode.OK, remove.StatusCode); + } + + [Fact] + public async Task Update_WithNewPassword_ChangesPasswordForManagedUser() + { + UseTenantAdminAuth(); + var email = $"password-update-{Guid.NewGuid():N}@test.com"; + using (var scope = Factory.Services.CreateScope()) + { + var manager = scope.ServiceProvider.GetRequiredService>(); + var user = new Infrastructure.Identity.Entities.ApplicationUser + { + Id = Guid.NewGuid(), TenantId = CustomWebApplicationFactory.TestTenantId, + Email = email, UserName = email, FullName = "Password Update User", + EmailConfirmed = true, IsActive = true, + }; + Assert.True((await manager.CreateAsync(user, "OldPass123!")).Succeeded); + } + + var response = await Client.PutAsync("/api/v1/users", JsonContent(new + { + Email = email, FullName = "Password Updated User", Password = "NewPass123!", + })); + + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + using var verificationScope = Factory.Services.CreateScope(); + var userManager = verificationScope.ServiceProvider.GetRequiredService>(); + var updated = await userManager.FindByEmailAsync(email); + Assert.NotNull(updated); + Assert.True(await userManager.CheckPasswordAsync(updated, "NewPass123!")); + } } From 394214bbe4a1fdab1b54fd8a50680059e23fd4d6 Mon Sep 17 00:00:00 2001 From: arjun Date: Mon, 30 Nov 2026 17:19:04 +0530 Subject: [PATCH 4/4] fix: improve image dimension reading and test coverage --- .../Users/AvatarImageDimensions.cs | 141 ++++++++++++------ .../Helpers/AvatarImageDimensionsTests.cs | 25 ++++ tests/Api.Tests/Helpers/SeedRunnerTests.cs | 4 +- .../PasswordResetServiceTests.cs | 2 +- 4 files changed, 124 insertions(+), 48 deletions(-) diff --git a/src/Infrastructure/Users/AvatarImageDimensions.cs b/src/Infrastructure/Users/AvatarImageDimensions.cs index 8fa8764..4aaf4a5 100644 --- a/src/Infrastructure/Users/AvatarImageDimensions.cs +++ b/src/Infrastructure/Users/AvatarImageDimensions.cs @@ -3,6 +3,8 @@ namespace Infrastructure.Users; /// Reads supported image dimensions from a file header without decoding pixels. internal static class AvatarImageDimensions { + private const int MaxJpegHeaderMarkers = 256; + internal static (int Width, int Height) Read(Stream stream) { try @@ -10,45 +12,11 @@ internal static (int Width, int Height) Read(Stream stream) var header = new byte[30]; var read = stream.Read(header, 0, header.Length); - if (read < 12) return (0, 0); - - if (read >= 24 - && header[0] == 0x89 && header[1] == 0x50 && header[2] == 0x4E && header[3] == 0x47) - { - return (ReadInt32BE(header, 16), ReadInt32BE(header, 20)); - } - - if (read >= 10 && header[0] == 'G' && header[1] == 'I' && header[2] == 'F') + if (TryReadPng(header, read, out var dimensions) + || TryReadGif(header, read, out dimensions) + || TryReadWebP(header, read, out dimensions)) { - return (ReadUInt16LE(header, 6), ReadUInt16LE(header, 8)); - } - - if (read >= 28 - && header[0] == 'R' && header[1] == 'I' && header[2] == 'F' && header[3] == 'F' - && header[8] == 'W' && header[9] == 'E' && header[10] == 'B' && header[11] == 'P') - { - if (header[12] == 'V' && header[13] == 'P' && header[14] == '8' && header[15] == ' ' - && read >= 30 && header[23] == 0x9D && header[24] == 0x01 && header[25] == 0x2A) - { - return ((ReadUInt16LE(header, 26) & 0x3FFF) + 1, - (ReadUInt16LE(header, 28) & 0x3FFF) + 1); - } - - if (header[12] == 'V' && header[13] == 'P' && header[14] == '8' && header[15] == 'L' - && read >= 25 && header[20] == 0x2F) - { - var bits = ReadUInt32LE(header, 21); - return ((int)(bits & 0x3FFF) + 1, - (int)((bits >> 14) & 0x3FFF) + 1); - } - - if (header[12] == 'V' && header[13] == 'P' && header[14] == '8' && header[15] == 'X' - && read >= 30) - { - var width = header[24] | (header[25] << 8) | (header[26] << 16); - var height = header[27] | (header[28] << 8) | (header[29] << 16); - return (width + 1, height + 1); - } + return dimensions; } if (read >= 2 && header[0] == 0xFF && header[1] == 0xD8) @@ -64,31 +32,112 @@ internal static (int Width, int Height) Read(Stream stream) return (0, 0); } + private static bool TryReadPng(byte[] header, int read, out (int Width, int Height) dimensions) + { + dimensions = (0, 0); + if (read < 24 || header[0] != 0x89 || header[1] != 0x50 + || header[2] != 0x4E || header[3] != 0x47) + { + return false; + } + + dimensions = (ReadInt32BE(header, 16), ReadInt32BE(header, 20)); + return true; + } + + private static bool TryReadGif(byte[] header, int read, out (int Width, int Height) dimensions) + { + dimensions = (0, 0); + if (read < 10 || header[0] != 'G' || header[1] != 'I' || header[2] != 'F') + { + return false; + } + + dimensions = (ReadUInt16LE(header, 6), ReadUInt16LE(header, 8)); + return true; + } + + private static bool TryReadWebP(byte[] header, int read, out (int Width, int Height) dimensions) + { + dimensions = (0, 0); + if (read < 12 || header[0] != 'R' || header[1] != 'I' || header[2] != 'F' || header[3] != 'F' + || header[8] != 'W' || header[9] != 'E' || header[10] != 'B' || header[11] != 'P') + { + return false; + } + + if (read >= 30 && IsWebPChunk(header, ' ', 0x9D, 0x01, 0x2A)) + { + dimensions = ((ReadUInt16LE(header, 26) & 0x3FFF) + 1, + (ReadUInt16LE(header, 28) & 0x3FFF) + 1); + return true; + } + + if (read >= 25 && IsWebPChunk(header, 'L') && header[20] == 0x2F) + { + var bits = ReadUInt32LE(header, 21); + dimensions = ((int)(bits & 0x3FFF) + 1, (int)((bits >> 14) & 0x3FFF) + 1); + return true; + } + + if (read >= 30 && IsWebPChunk(header, 'X')) + { + var width = header[24] | (header[25] << 8) | (header[26] << 16); + var height = header[27] | (header[28] << 8) | (header[29] << 16); + dimensions = (width + 1, height + 1); + return true; + } + + return false; + } + + private static bool IsWebPChunk(byte[] header, char chunk, int marker1 = -1, int marker2 = -1, int marker3 = -1) => + header[12] == 'V' && header[13] == 'P' && header[14] == '8' && header[15] == chunk + && (marker1 < 0 || (header[23] == marker1 && header[24] == marker2 && header[25] == marker3)); + private static (int Width, int Height) ScanJpegDimensions(Stream stream) { stream.Seek(2, SeekOrigin.Begin); var buffer = new byte[7]; - while (stream.Read(buffer, 0, 2) == 2 && buffer[0] == 0xFF) + + for (var markerIndex = 0; markerIndex < MaxJpegHeaderMarkers; markerIndex++) { + if (stream.Read(buffer, 0, 2) != 2 || buffer[0] != 0xFF) + { + break; + } + var marker = buffer[1]; + if (IsJpegStartOfFrame(marker)) + { + if (stream.Read(buffer, 0, 7) < 7) + { + break; + } + + return ((buffer[5] << 8) | buffer[6], (buffer[3] << 8) | buffer[4]); + } - if (marker is >= 0xC0 and <= 0xCF and not 0xC4 and not 0xC8 and not 0xCC) + if (stream.Read(buffer, 0, 2) < 2) { - if (stream.Read(buffer, 0, 7) < 7) break; - var height = (buffer[3] << 8) | buffer[4]; - var width = (buffer[5] << 8) | buffer[6]; - return (width, height); + break; } - if (stream.Read(buffer, 0, 2) < 2) break; var segmentLength = (buffer[0] << 8) | buffer[1]; - if (segmentLength < 2) break; + if (segmentLength < 2 || stream.Position + segmentLength - 2 > stream.Length) + { + break; + } + stream.Seek(segmentLength - 2, SeekOrigin.Current); } return (0, 0); } + private static bool IsJpegStartOfFrame(byte marker) => + marker is >= 0xC0 and <= 0xCF and not 0xC4 and not 0xC8 and not 0xCC; + private static int ReadInt32BE(byte[] bytes, int offset) => (bytes[offset] << 24) | (bytes[offset + 1] << 16) | (bytes[offset + 2] << 8) | bytes[offset + 3]; diff --git a/tests/Api.Tests/Helpers/AvatarImageDimensionsTests.cs b/tests/Api.Tests/Helpers/AvatarImageDimensionsTests.cs index 88337d5..c138063 100644 --- a/tests/Api.Tests/Helpers/AvatarImageDimensionsTests.cs +++ b/tests/Api.Tests/Helpers/AvatarImageDimensionsTests.cs @@ -74,6 +74,31 @@ public void Read_JpegSkipsMetadataAndReadsFrameDimensions() Assert.Equal((48, 32), Read(header)); } + [Fact] + public void Read_JpegWithExcessiveMetadataMarkersStopsAtTheHeaderLimit() + { + var header = new byte[2 + 4 * 300]; + header[0] = 0xFF; + header[1] = 0xD8; + for (var marker = 0; marker < 300; marker++) + { + var offset = 2 + marker * 4; + header[offset] = 0xFF; + header[offset + 1] = 0xE0; + header[offset + 3] = 0x02; + } + + Assert.Equal((0, 0), Read(header)); + } + + [Fact] + public void Read_JpegWithSegmentExtendingPastEndStopsSafely() + { + var header = new byte[] { 0xFF, 0xD8, 0xFF, 0xE0, 0xFF, 0xFF, 0xAA }; + + Assert.Equal((0, 0), Read(header)); + } + [Fact] public void Read_InvalidOrTooShortHeader_ReturnsUnknownDimensions() { diff --git a/tests/Api.Tests/Helpers/SeedRunnerTests.cs b/tests/Api.Tests/Helpers/SeedRunnerTests.cs index d419d50..824551a 100644 --- a/tests/Api.Tests/Helpers/SeedRunnerTests.cs +++ b/tests/Api.Tests/Helpers/SeedRunnerTests.cs @@ -10,6 +10,8 @@ namespace Api.Tests.Helpers; public class SeedRunnerTests { + private static readonly string[] ExpectedSeedIds = ["01_Accounts", "02_Permissions"]; + [Fact] public async Task PendingSeeds_AreOrderedAndExcludeAppliedEntries() { @@ -40,7 +42,7 @@ public async Task ApplyPendingSeeds_RecordsEachSeedAndInvalidatesPermissionCache Assert.Equal(1, first.ApplyCount); Assert.Equal(1, second.ApplyCount); - Assert.Equal(new[] { "01_Accounts", "02_Permissions" }, + Assert.Equal(ExpectedSeedIds, await context.SeedHistory.OrderBy(history => history.SeedId).Select(history => history.SeedId).ToArrayAsync()); cache.Verify(value => value.InvalidatePermissionCatalogs(), Times.Once); diff --git a/tests/Api.Tests/IntegrationTests/PasswordResetServiceTests.cs b/tests/Api.Tests/IntegrationTests/PasswordResetServiceTests.cs index 8e4fafb..bcde7cb 100644 --- a/tests/Api.Tests/IntegrationTests/PasswordResetServiceTests.cs +++ b/tests/Api.Tests/IntegrationTests/PasswordResetServiceTests.cs @@ -118,7 +118,7 @@ await Assert.ThrowsAsync(() => service.ResetPasswordAsync( new ResetPasswordRequest { Token = "missing", NewPassword = "one", ConfirmPassword = "one" })); } - private async Task<(PasswordResetService Service, ApplicationDbContext Context, + private static async Task<(PasswordResetService Service, ApplicationDbContext Context, UserManager Manager, ApplicationUser User, List Sent)> ArrangeAsync( IServiceScope scope, bool failDelivery = false) {