Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions .github/workflows/sonar.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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=$((Join-Path (Get-Location).Path 'TestResults/swagger-coverage.lcov').Replace('\', '/'))"
"/d:sonar.qualitygate.wait=true"
)
dotnet sonarscanner begin @scannerArgs
Expand Down Expand Up @@ -106,6 +107,27 @@ 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: 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 }}
Expand Down
6 changes: 3 additions & 3 deletions src/Api/Controllers/ImpersonationController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ public async Task<IActionResult> 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),
});
Expand Down Expand Up @@ -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,
});
Expand All @@ -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),
});
Expand Down
2 changes: 1 addition & 1 deletion src/Api/Middleware/ExceptionHandlingMiddleware.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
}

Expand Down
14 changes: 8 additions & 6 deletions src/Api/wwwroot/swagger-ui/swagger-auto-auth.js
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down Expand Up @@ -40,7 +40,7 @@
}

function applyBearer(token) {
if (!token || !window.ui || !window.ui.preauthorizeApiKey) {
if (!token || !window.ui?.preauthorizeApiKey) {
return;
}

Expand All @@ -52,7 +52,7 @@
return;
}

if (window.ui.authActions && window.ui.authActions.logout) {
if (window.ui.authActions?.logout) {
window.ui.authActions.logout();
return;
}
Expand Down Expand Up @@ -100,17 +100,19 @@
}

const init = args[1];
if (!init || !init.body || typeof init.body !== "string") {
if (!init?.body || typeof init.body !== "string") {
return args;
}

try {
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;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ namespace Application.DTOs.Invitations;
/// Completes a TenantAdmin invitation. Invited user supplies full profile +
/// company information and chooses a password.
/// </summary>
public class AcceptTenantAdminInvitationRequest
public class AcceptTenantAdminInvitationRequest : IInvitationAcceptanceRequest
{
public string Token { get; set; } = default!;

Expand All @@ -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; }
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

namespace Application.DTOs.Invitations;

public class AcceptTenantCreationInvitationRequest
public class AcceptTenantCreationInvitationRequest : IInvitationAcceptanceRequest
{
public string Token { get; set; } = default!;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ namespace Application.DTOs.Invitations;
/// Completes a TenantUser invitation. Invited user supplies basic profile +
/// a password.
/// </summary>
public class AcceptTenantUserInvitationRequest
public class AcceptTenantUserInvitationRequest : IInvitationAcceptanceRequest
{
public string Token { get; set; } = default!;

Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
using Application.DTOs.Invitations;
using Application.Validators;
using FluentValidation;

namespace Application.Validators.Invitations;
Expand All @@ -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.");
}
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
using Application.DTOs.Invitations;
using Application.Validators;
using FluentValidation;

namespace Application.Validators.Invitations;
Expand All @@ -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.");
}
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
using Application.DTOs.Invitations;
using Application.Validators;
using FluentValidation;

namespace Application.Validators.Invitations;
Expand All @@ -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.");
}
}
Original file line number Diff line number Diff line change
@@ -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<T>(AbstractValidator<T> 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<T>(
AbstractValidator<T> validator,
Expression<Func<T, AddressRequest>> addressSelector,
string message)
{
validator.RuleFor(addressSelector)
.NotNull().WithMessage(message)
.SetValidator(new AddressRequestValidator());
}
}
Loading
Loading