fix(auth): safely report cookie sign-in failures (#310)
Heimdall Gitea / Detect CI scope (push) Successful in 33s
Heimdall Gitea / Build and tests (push) Successful in 26m42s
Heimdall Gitea / Publish versioned release (push) Skipped
Heimdall Gitea / Build and scan server image (push) Successful in 8m45s
Heimdall Gitea / Build and scan agent image (push) Successful in 9m14s
Heimdall Gitea / Build and scan NVIDIA Agent image (push) Successful in 19m34s
Heimdall Gitea / Publish Docker Hub latest tags (push) Successful in 1m37s
Heimdall Gitea / CI policy (push) Successful in 2s
Heimdall Gitea / Detect CI scope (push) Successful in 33s
Heimdall Gitea / Build and tests (push) Successful in 26m42s
Heimdall Gitea / Publish versioned release (push) Skipped
Heimdall Gitea / Build and scan server image (push) Successful in 8m45s
Heimdall Gitea / Build and scan agent image (push) Successful in 9m14s
Heimdall Gitea / Build and scan NVIDIA Agent image (push) Successful in 19m34s
Heimdall Gitea / Publish Docker Hub latest tags (push) Successful in 1m37s
Heimdall Gitea / CI policy (push) Successful in 2s
## Résumé Le flux navigateur reçoit maintenant un résultat HTTP explicite du pont cookie; les échecs de cookie sont diagnostiqués sans exposer les messages d’exception ni les données de session. La validation 2FA par code de récupération recharge également l’utilisateur après rotation du security stamp avant d’émettre la session. ## Issue Refs #304 — l’observation GlitchTip post-déploiement reste nécessaire avant résolution. ## Travail effectué - `/_auth/signin` renvoie des erreurs génériques et journalise uniquement l’étape et le type d’exception. - Le pont JavaScript retourne le statut HTTP; les interruptions de circuit sont distinctes des réponses non-2xx. - Suppression des adresses e-mail des journaux auth/2FA. - Correction du chemin code de récupération 2FA pour émettre un jeton cohérent avec le security stamp actualisé. - Ajout de tests unitaires et d’intégration; documentation dans `skills/heimdall-identity/SKILL.md`. ## Preuves - `dotnet restore tests/Heimdall.Web.Tests/Heimdall.Web.Tests.csproj --locked-mode` — réussi. - `dotnet restore tests/Heimdall.IntegrationTests/Heimdall.IntegrationTests.csproj --locked-mode` — réussi. - `AuthHelperTests` — 6/6 réussis. - Tests d’intégration ciblés 2FA/recovery-cookie/TOTP-cookie/token malformé — 3/3 réussis. - Acceptance Compose source-built `heimdall-auth-cookie-20261108170745-28547` — bootstrap 200, TOTP 200, cookie sign-in 200, API avec cookie 200, jeton malformé 401 générique, secrets absents des logs. Nettoyage vérifié: conteneurs/volumes/réseau absents et tag `heimdall:heimdall-auth-cookie-20261108170745-28547-central` supprimé. - Analyse de l’événement GlitchTip: le circuit navigateur se déconnecte avant toute trace HTTP observée de `/_auth/signin`; la cause de cette occurrence production reste donc non démontrée. La correction améliore la visibilité sûre et le flux synthétique, sans prétendre reproduire cet événement. ## À suivre Après déploiement de ce commit, observer GlitchTip pendant au moins sept jours et vérifier si HEIMDALL-DU réapparaît. Ne pas résoudre l’issue avant cette preuve réelle. Reviewed-on: #310 Co-authored-by: Arnaud Dartois <admin@tordais.cc>
This commit was merged in pull request #310.
This commit is contained in:
1 parent
e042b832d8
commit
1d60f04691
12 files changed
+228
-31
No files matched your search
@@ -15,6 +15,7 @@ Read `AGENTS.md`, the focused Gitea issue and [the Gitea ticket workflow](../git
|
||||
- Keep public login/reset responses generic so they do not reveal account existence, lockout state, or Identity policy details. Logs must not contain emails, passwords, tokens, authenticator keys, recovery codes, or Identity error descriptions; log safe error codes only when needed.
|
||||
- Rotate `SecurityStamp` after password changes/resets, email or role changes, lock/unlock, and 2FA changes. Verify existing cookies, JWTs, and refresh tokens are rejected after the change.
|
||||
- Cookie principal validation runs on every authenticated HTTP request. Keep it asynchronous and use `AccountSessionPolicy.IsValidLiveAsync` with `IIdentityAccountService.GetSessionRecordAsync` plus an `IApplicationDbContext` projection; this bypasses Identity's tracked-user cache and avoids repeated `UserManager` database round trips while preserving fresh security-stamp, lockout, and email-confirmation checks. Do not replace it with claims-only validation.
|
||||
- The Blazor cookie bridge runs through `heimdallAuth.signIn` → `POST /_auth/signin`. Have JavaScript return only the HTTP status code (or `0` for a network failure); classify `JSDisconnectedException` separately from non-2xx responses. Log only the failure stage, HTTP status, or exception type—never exception messages, emails, user IDs, access tokens, cookies, or request bodies. Return generic public errors from the endpoint. Integration coverage should verify a successful 2FA response can create a usable cookie and that malformed tokens reveal no validation details.
|
||||
- Enroll an authenticator in two steps: create/show the setup key while 2FA remains disabled; renew the user's access token and cookie after Identity rotates the security stamp; verify a TOTP code before enabling 2FA and creating one-time recovery codes. Persist only hashes of recovery codes, redeem each atomically once, and clear them when 2FA is disabled.
|
||||
- Check every `IdentityResult` before proceeding. Avoid partial account creation; clean up the created user if role assignment fails.
|
||||
- Keep first-account provisioning on `/setup` → `/api/auth/bootstrap-admin`; later accounts and role assignment use `/users` → `/api/users`. Do not reintroduce a second Admin-registration endpoint.
|
||||
|
||||
@@ -82,6 +82,10 @@ public class Verify2faHandler : IRequestHandler<Verify2faCommand, ServiceResult<
|
||||
_logger.LogError("Unable to rotate security stamp after recovery code use for user {UserId}", user.Id);
|
||||
return ServiceResult<AuthResponse>.Failure("Unable to complete sign-in");
|
||||
}
|
||||
var refreshedUser = await _userManager.FindByIdAsync(user.Id, ct).ConfigureAwait(false);
|
||||
if (refreshedUser is null)
|
||||
return ServiceResult<AuthResponse>.Failure("Unable to complete sign-in");
|
||||
user = refreshedUser;
|
||||
_logger.LogInformation("Verify2fa: Recovery code redeemed UserId={UserId}", challenge.UserId);
|
||||
}
|
||||
|
||||
|
||||
@@ -131,19 +131,19 @@
|
||||
{
|
||||
_loading = true;
|
||||
_errorMessage = "";
|
||||
Logger.LogInformation("Login attempt for email: {Email}", _email);
|
||||
Logger.LogInformation("Login attempt");
|
||||
|
||||
try
|
||||
{
|
||||
var result = await Api.LoginAsync(_email, _password);
|
||||
if (result is null)
|
||||
{
|
||||
Logger.LogWarning("Login failed: Invalid credentials for {Email}", _email);
|
||||
Logger.LogWarning("Login failed: invalid credentials");
|
||||
_errorMessage = Text["LoginPage_InvalidCredentials"];
|
||||
return;
|
||||
}
|
||||
|
||||
Logger.LogInformation("Login successful for {Email}. Requires 2FA: {Requires2fa}", _email, result.Requires2fa);
|
||||
Logger.LogInformation("Login succeeded. Requires 2FA: {Requires2fa}", result.Requires2fa);
|
||||
|
||||
// Check if 2FA is required
|
||||
if (result.Requires2fa)
|
||||
@@ -152,7 +152,7 @@
|
||||
_password = "";
|
||||
_requires2fa = true;
|
||||
_loading = false;
|
||||
Logger.LogInformation("2FA required for {Email}", _email);
|
||||
Logger.LogInformation("2FA required");
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -160,7 +160,7 @@
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Logger.LogError(ex, "Login error for {Email}", _email);
|
||||
Logger.LogError("Login flow failed (error type {ErrorType})", ex.GetType().Name);
|
||||
_errorMessage = UiErrors.OperationFailed();
|
||||
}
|
||||
finally { _loading = false; }
|
||||
@@ -170,31 +170,31 @@
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(_twoFactorCode))
|
||||
{
|
||||
Logger.LogWarning("2FA verification attempted with empty code for {Email}", _email);
|
||||
Logger.LogWarning("2FA verification attempted with an empty code");
|
||||
_errorMessage = Text["LoginPage_TwoFactorCodeRequired"];
|
||||
return;
|
||||
}
|
||||
|
||||
_loading = true;
|
||||
_errorMessage = "";
|
||||
Logger.LogInformation("2FA verification attempt for {Email}", _email);
|
||||
Logger.LogInformation("2FA verification attempt");
|
||||
|
||||
try
|
||||
{
|
||||
var result = await Api.Verify2faAsync(_challengeId, _twoFactorCode.Trim());
|
||||
if (result is null)
|
||||
{
|
||||
Logger.LogWarning("2FA verification failed for {Email}", _email);
|
||||
Logger.LogWarning("2FA verification failed");
|
||||
_errorMessage = Text["LoginPage_InvalidTwoFactorCode"];
|
||||
return;
|
||||
}
|
||||
|
||||
Logger.LogInformation("2FA verification successful for {Email}", _email);
|
||||
Logger.LogInformation("2FA verification succeeded");
|
||||
await CompleteAuthAsync(result);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Logger.LogError(ex, "2FA verification error for {Email}", _email);
|
||||
Logger.LogError("2FA verification flow failed (error type {ErrorType})", ex.GetType().Name);
|
||||
_errorMessage = UiErrors.OperationFailed();
|
||||
}
|
||||
finally { _loading = false; }
|
||||
@@ -202,7 +202,7 @@
|
||||
|
||||
private async Task CompleteAuthAsync(AuthResponse result)
|
||||
{
|
||||
Logger.LogInformation("Completing authentication for {Email}", _email);
|
||||
Logger.LogInformation("Completing authentication");
|
||||
|
||||
// Update Blazor-level auth state
|
||||
await AuthStateProvider.NotifyLoginAsync(result);
|
||||
@@ -211,23 +211,24 @@
|
||||
var cookieOk = true;
|
||||
if (!string.IsNullOrEmpty(result.AccessToken))
|
||||
{
|
||||
Logger.LogDebug("Creating auth cookie for {Email}", _email);
|
||||
Logger.LogDebug("Creating auth cookie");
|
||||
cookieOk = await AuthHelper.SignInAsync(JsRuntime,
|
||||
Logger,
|
||||
AuthHelper.CreateSignInPayload(result.AccessToken));
|
||||
}
|
||||
else
|
||||
{
|
||||
Logger.LogWarning("No access token in auth response for {Email}", _email);
|
||||
Logger.LogWarning("No access token in auth response");
|
||||
}
|
||||
|
||||
if (!cookieOk)
|
||||
{
|
||||
Logger.LogError("Failed to create auth cookie for {Email}", _email);
|
||||
Logger.LogError("Failed to create auth cookie");
|
||||
_errorMessage = Text["LoginPage_AuthSessionFailed"];
|
||||
return;
|
||||
}
|
||||
|
||||
Logger.LogInformation("Authentication completed successfully for {Email}, redirecting to {ReturnUrl}", _email, _returnUrl);
|
||||
Logger.LogInformation("Authentication completed successfully, redirecting to {ReturnUrl}", _returnUrl);
|
||||
Snackbar.Add(Text["LoginPage_SignInSucceeded"], Severity.Success);
|
||||
Navigation.NavigateTo(_returnUrl);
|
||||
}
|
||||
|
||||
@@ -11,6 +11,7 @@
|
||||
@inject ISnackbar Snackbar
|
||||
@inject HeimdallAuthStateProvider AuthProvider
|
||||
@inject IJSRuntime JS
|
||||
@inject Microsoft.Extensions.Logging.ILogger<Profile> Logger
|
||||
|
||||
<MudText Typo="Typo.h1" Class="mb-6">
|
||||
<i class="fas fa-user-circle mr-2"></i>
|
||||
@@ -470,7 +471,7 @@ else if (_profile is not null)
|
||||
return;
|
||||
}
|
||||
await AuthProvider.NotifyLoginAsync(renewedSession);
|
||||
if (!await AuthHelper.SignInAsync(JS, AuthHelper.CreateSignInPayload(renewedSession.AccessToken)))
|
||||
if (!await AuthHelper.SignInAsync(JS, Logger, AuthHelper.CreateSignInPayload(renewedSession.AccessToken)))
|
||||
{
|
||||
_2faError = Text["OperationFailed"];
|
||||
_show2faDialog = true;
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
@inject HeimdallAuthStateProvider AuthStateProvider
|
||||
@inject NavigationManager Navigation
|
||||
@inject IJSRuntime JsRuntime
|
||||
@inject Microsoft.Extensions.Logging.ILogger<Setup> Logger
|
||||
|
||||
<div class="auth-page">
|
||||
<div class="auth-card">
|
||||
@@ -96,7 +97,7 @@
|
||||
}
|
||||
await AuthStateProvider.NotifyLoginAsync(result);
|
||||
var cookieOk = !string.IsNullOrEmpty(result.AccessToken) && await AuthHelper.SignInAsync(
|
||||
JsRuntime, AuthHelper.CreateSignInPayload(result.AccessToken));
|
||||
JsRuntime, Logger, AuthHelper.CreateSignInPayload(result.AccessToken));
|
||||
if (!cookieOk)
|
||||
{
|
||||
_error = Text["SetupAdmin_AutoLoginFailed"];
|
||||
|
||||
@@ -12,6 +12,7 @@
|
||||
<ItemGroup>
|
||||
<InternalsVisibleTo Include="Heimdall.Api.Tests" />
|
||||
<InternalsVisibleTo Include="Heimdall.IntegrationTests" />
|
||||
<InternalsVisibleTo Include="Heimdall.Web.Tests" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
|
||||
@@ -974,11 +974,13 @@ public partial class Program
|
||||
{
|
||||
if (string.IsNullOrEmpty(request.AccessToken))
|
||||
return Results.BadRequest(new { error = "AccessToken is required" });
|
||||
var failureStage = "token validation";
|
||||
try
|
||||
{
|
||||
var handler = new JwtSecurityTokenHandler();
|
||||
var principal = handler.ValidateToken(request.AccessToken,
|
||||
GetJwtValidationParameters(jwtKey, jwtIssuer, jwtAudience), out _);
|
||||
failureStage = "account session validation";
|
||||
if (!await ValidateAccountSessionAsync(principal, httpContext))
|
||||
return Results.Unauthorized();
|
||||
var userId = principal.FindFirst(ClaimTypes.NameIdentifier)?.Value;
|
||||
@@ -1003,6 +1005,7 @@ public partial class Program
|
||||
claims.Add(new Claim("permission", permission.Value));
|
||||
|
||||
var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
|
||||
failureStage = "cookie issuance";
|
||||
await httpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(identity),
|
||||
new AuthenticationProperties
|
||||
{
|
||||
@@ -1013,7 +1016,24 @@ public partial class Program
|
||||
return Results.Ok();
|
||||
}
|
||||
catch (SecurityTokenExpiredException) { return Results.Unauthorized(); }
|
||||
catch (Exception ex) { return Results.BadRequest(new { error = $"Token validation failed: {ex.Message}" }); }
|
||||
catch (SecurityTokenException ex)
|
||||
{
|
||||
logger.LogWarning("Cookie sign-in rejected a token (error type {ErrorType})", ex.GetType().Name);
|
||||
return Results.Unauthorized();
|
||||
}
|
||||
catch (ArgumentException ex) when (failureStage == "token validation")
|
||||
{
|
||||
logger.LogWarning("Cookie sign-in rejected a token (error type {ErrorType})", ex.GetType().Name);
|
||||
return Results.Unauthorized();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogError("Cookie sign-in failed during {FailureStage} (error type {ErrorType})",
|
||||
failureStage, ex.GetType().Name);
|
||||
return Results.Problem(
|
||||
statusCode: StatusCodes.Status500InternalServerError,
|
||||
title: "Authentication session could not be created");
|
||||
}
|
||||
});
|
||||
|
||||
app.MapPost("/_auth/signout", async (HttpContext httpContext, ILogger<Program> logger) =>
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
using Microsoft.JSInterop;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace Heimdall.Web.Services;
|
||||
|
||||
@@ -7,18 +8,30 @@ internal static class AuthHelper
|
||||
{
|
||||
/// <summary>Creates the middleware-level auth cookie via JS interop.</summary>
|
||||
/// <returns>True if the sign-in HTTP call succeeded (2xx).</returns>
|
||||
public static async Task<bool> SignInAsync(IJSRuntime jsRuntime, object user)
|
||||
public static async Task<bool> SignInAsync(IJSRuntime jsRuntime, ILogger logger, object user)
|
||||
{
|
||||
try
|
||||
{
|
||||
var ok = await jsRuntime.InvokeAsync<bool>("heimdallAuth.signIn", user);
|
||||
if (!ok)
|
||||
Console.Error.WriteLine("[AuthHelper] SignInAsync: /_auth/signin returned non-2xx status");
|
||||
return ok;
|
||||
var statusCode = await jsRuntime.InvokeAsync<int>("heimdallAuth.signIn", user);
|
||||
if (statusCode is >= 200 and < 300)
|
||||
return true;
|
||||
|
||||
logger.LogWarning("Cookie sign-in endpoint returned HTTP status {StatusCode}", statusCode);
|
||||
return false;
|
||||
}
|
||||
catch (JSDisconnectedException)
|
||||
{
|
||||
logger.LogInformation("Cookie sign-in was interrupted because the browser circuit disconnected");
|
||||
return false;
|
||||
}
|
||||
catch (JSException ex)
|
||||
{
|
||||
logger.LogWarning("Cookie sign-in JavaScript interop failed (error type {ErrorType})", ex.GetType().Name);
|
||||
return false;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.Error.WriteLine($"[AuthHelper] SignInAsync JS interop failed: {ex.Message}");
|
||||
logger.LogWarning("Cookie sign-in bridge failed (error type {ErrorType})", ex.GetType().Name);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,9 +11,9 @@ window.heimdallAuth = {
|
||||
body: JSON.stringify(data),
|
||||
credentials: 'include'
|
||||
});
|
||||
return response.ok;
|
||||
return response.status;
|
||||
} catch {
|
||||
return false;
|
||||
return 0;
|
||||
}
|
||||
},
|
||||
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
using System.Buffers.Binary;
|
||||
using System.Net;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Net.Http.Json;
|
||||
using System.Security.Cryptography;
|
||||
using Heimdall.Application.Auth.Services;
|
||||
using Heimdall.Application.DTOs;
|
||||
using Heimdall.Application.Users.Commands.AssignRoles;
|
||||
@@ -75,11 +77,94 @@ public sealed class AuthSessionSecurityTests(PostgreSqlContainerFixture postgres
|
||||
challenge.AccessToken.ShouldBeEmpty();
|
||||
var response = await _client.PostAsJsonAsync("/api/auth/2fa/verify", new { challengeId = challenge.ChallengeId, code });
|
||||
response.StatusCode.ShouldBe(HttpStatusCode.OK);
|
||||
(await response.Content.ReadFromJsonAsync<AuthResponse>())!.AccessToken.ShouldNotBeNullOrEmpty();
|
||||
var verifiedSession = (await response.Content.ReadFromJsonAsync<AuthResponse>())!;
|
||||
verifiedSession.AccessToken.ShouldNotBeNullOrEmpty();
|
||||
|
||||
var cookieResponse = await _client.PostAsJsonAsync("/_auth/signin", new { accessToken = verifiedSession.AccessToken });
|
||||
cookieResponse.StatusCode.ShouldBe(HttpStatusCode.OK);
|
||||
await AssertCookieSessionAsync(cookieResponse);
|
||||
|
||||
var replay = await _client.PostAsJsonAsync("/api/auth/2fa/verify", new { challengeId = challenge.ChallengeId, code });
|
||||
replay.StatusCode.ShouldBe(HttpStatusCode.Unauthorized);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Authenticator_2fa_success_emits_token_accepted_by_cookie_signin()
|
||||
{
|
||||
string code;
|
||||
using (var scope = _factory.Services.CreateScope())
|
||||
{
|
||||
var users = scope.ServiceProvider.GetRequiredService<UserManager<IdentityAppUser>>();
|
||||
var user = (await users.FindByIdAsync(_userId.ToString()))!;
|
||||
(await users.ResetAuthenticatorKeyAsync(user)).Succeeded.ShouldBeTrue();
|
||||
(await users.SetTwoFactorEnabledAsync(user, true)).Succeeded.ShouldBeTrue();
|
||||
var key = await users.GetAuthenticatorKeyAsync(user);
|
||||
code = GenerateTotp(key!);
|
||||
(await users.VerifyTwoFactorTokenAsync(user, TokenOptions.DefaultAuthenticatorProvider, code)).ShouldBeTrue();
|
||||
}
|
||||
|
||||
var challenge = await LoginAsync();
|
||||
challenge.Requires2fa.ShouldBeTrue();
|
||||
var verification = await _client.PostAsJsonAsync("/api/auth/2fa/verify", new
|
||||
{
|
||||
challengeId = challenge.ChallengeId,
|
||||
code
|
||||
});
|
||||
verification.StatusCode.ShouldBe(HttpStatusCode.OK, await verification.Content.ReadAsStringAsync());
|
||||
var session = (await verification.Content.ReadFromJsonAsync<AuthResponse>())!;
|
||||
session.AccessToken.ShouldNotBeNullOrEmpty();
|
||||
|
||||
var cookieResponse = await _client.PostAsJsonAsync("/_auth/signin", new { accessToken = session.AccessToken });
|
||||
cookieResponse.StatusCode.ShouldBe(HttpStatusCode.OK);
|
||||
await AssertCookieSessionAsync(cookieResponse);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Cookie_signin_rejects_malformed_tokens_without_returning_validation_details()
|
||||
{
|
||||
var response = await _client.PostAsJsonAsync("/_auth/signin", new { accessToken = "not-a-jwt" });
|
||||
|
||||
response.StatusCode.ShouldBe(HttpStatusCode.Unauthorized);
|
||||
var body = await response.Content.ReadAsStringAsync();
|
||||
body.ShouldNotContain("not-a-jwt");
|
||||
body.ShouldNotContain("IDX");
|
||||
}
|
||||
|
||||
private async Task AssertCookieSessionAsync(HttpResponseMessage cookieResponse)
|
||||
{
|
||||
var cookie = cookieResponse.Headers.GetValues("Set-Cookie")
|
||||
.Single(value => value.StartsWith(".Heimdall.Auth=", StringComparison.Ordinal)).Split(';')[0];
|
||||
var authenticatedRequest = new HttpRequestMessage(HttpMethod.Get, "/api/users/me");
|
||||
authenticatedRequest.Headers.Add("Cookie", cookie);
|
||||
(await _client.SendAsync(authenticatedRequest)).StatusCode.ShouldBe(HttpStatusCode.OK);
|
||||
}
|
||||
|
||||
#pragma warning disable CA5350
|
||||
private static string GenerateTotp(string base32Key)
|
||||
{
|
||||
const string alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
|
||||
var key = new List<byte>();
|
||||
var buffer = 0;
|
||||
var bits = 0;
|
||||
foreach (var character in base32Key.TrimEnd('='))
|
||||
{
|
||||
buffer = (buffer << 5) | alphabet.IndexOf(character);
|
||||
bits += 5;
|
||||
if (bits < 8) continue;
|
||||
bits -= 8;
|
||||
key.Add((byte)(buffer >> bits));
|
||||
}
|
||||
|
||||
Span<byte> message = stackalloc byte[8];
|
||||
BinaryPrimitives.WriteInt64BigEndian(message, DateTimeOffset.UtcNow.ToUnixTimeSeconds() / 30);
|
||||
var hash = HMACSHA1.HashData(key.ToArray(), message);
|
||||
var offset = hash[^1] & 0x0f;
|
||||
var binary = ((hash[offset] & 0x7f) << 24) | (hash[offset + 1] << 16)
|
||||
| (hash[offset + 2] << 8) | hash[offset + 3];
|
||||
return (binary % 1_000_000).ToString("D6", System.Globalization.CultureInfo.InvariantCulture);
|
||||
}
|
||||
#pragma warning restore CA5350
|
||||
|
||||
[Theory]
|
||||
[InlineData("lock")]
|
||||
[InlineData("roles")]
|
||||
|
||||
@@ -47,7 +47,7 @@ public class LoginTests : PageTestBase
|
||||
public async Task LoginPage_Succes_NavigueVersDashboard()
|
||||
{
|
||||
Handler.On(HttpMethod.Post, "api/auth/login", SuccessResponse());
|
||||
JSInterop.Setup<bool>("heimdallAuth.signIn", _ => true).SetResult(true);
|
||||
JSInterop.Setup<int>("heimdallAuth.signIn", _ => true).SetResult(200);
|
||||
|
||||
var nav = Navigate();
|
||||
var cut = RenderPage<Login>();
|
||||
@@ -119,7 +119,7 @@ public class LoginTests : PageTestBase
|
||||
var requires2fa = SuccessResponse() with { Requires2fa = true };
|
||||
Handler.On(HttpMethod.Post, "api/auth/login", requires2fa);
|
||||
Handler.On(HttpMethod.Post, "api/auth/2fa/verify", SuccessResponse());
|
||||
JSInterop.Setup<bool>("heimdallAuth.signIn", _ => true).SetResult(true);
|
||||
JSInterop.Setup<int>("heimdallAuth.signIn", _ => true).SetResult(200);
|
||||
|
||||
var nav = Navigate();
|
||||
var cut = RenderPage<Login>();
|
||||
@@ -151,7 +151,7 @@ public class LoginTests : PageTestBase
|
||||
public async Task LoginPage_ReturnUrl_UtilisePourLaNavigation()
|
||||
{
|
||||
Handler.On(HttpMethod.Post, "api/auth/login", SuccessResponse());
|
||||
JSInterop.Setup<bool>("heimdallAuth.signIn", _ => true).SetResult(true);
|
||||
JSInterop.Setup<int>("heimdallAuth.signIn", _ => true).SetResult(200);
|
||||
|
||||
var nav = Navigate();
|
||||
nav.NavigateTo("/login?returnUrl=/sites");
|
||||
@@ -168,7 +168,7 @@ public class LoginTests : PageTestBase
|
||||
public async Task LoginPage_ReturnUrlExterne_IgnoreEtVaSurDashboard()
|
||||
{
|
||||
Handler.On(HttpMethod.Post, "api/auth/login", SuccessResponse());
|
||||
JSInterop.Setup<bool>("heimdallAuth.signIn", _ => true).SetResult(true);
|
||||
JSInterop.Setup<int>("heimdallAuth.signIn", _ => true).SetResult(200);
|
||||
|
||||
var nav = Navigate();
|
||||
nav.NavigateTo("/login?returnUrl=https://evil.example.com");
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
using Heimdall.Web.Services;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.JSInterop;
|
||||
using Shouldly;
|
||||
|
||||
namespace Heimdall.Web.Tests.Services;
|
||||
|
||||
public sealed class AuthHelperTests
|
||||
{
|
||||
[Theory]
|
||||
[InlineData(200, true)]
|
||||
[InlineData(204, true)]
|
||||
[InlineData(401, false)]
|
||||
[InlineData(500, false)]
|
||||
[InlineData(0, false)]
|
||||
public async Task SignInAsync_UsesOnlyTheReturnedHttpStatus(int statusCode, bool expected)
|
||||
{
|
||||
var jsRuntime = new StubJsRuntime(statusCode);
|
||||
|
||||
var result = await AuthHelper.SignInAsync(jsRuntime, new RecordingLogger(), new { accessToken = "synthetic" });
|
||||
|
||||
result.ShouldBe(expected);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SignInAsync_LogsInteropFailureTypeWithoutExceptionMessage()
|
||||
{
|
||||
const string privateDetail = "synthetic-private-detail";
|
||||
var jsRuntime = new StubJsRuntime(new JSException(privateDetail));
|
||||
var logger = new RecordingLogger();
|
||||
|
||||
(await AuthHelper.SignInAsync(jsRuntime, logger, new { accessToken = "synthetic" })).ShouldBeFalse();
|
||||
|
||||
var logged = string.Join(" ", logger.Messages);
|
||||
logged.ShouldContain(nameof(JSException));
|
||||
logged.ShouldNotContain(privateDetail);
|
||||
}
|
||||
|
||||
private sealed class RecordingLogger : ILogger
|
||||
{
|
||||
public List<string> Messages { get; } = [];
|
||||
|
||||
public IDisposable? BeginScope<TState>(TState state) where TState : notnull => null;
|
||||
public bool IsEnabled(LogLevel logLevel) => true;
|
||||
|
||||
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception? exception,
|
||||
Func<TState, Exception?, string> formatter)
|
||||
=> Messages.Add(formatter(state, exception));
|
||||
}
|
||||
|
||||
private sealed class StubJsRuntime : IJSRuntime
|
||||
{
|
||||
private readonly int _statusCode;
|
||||
private readonly Exception? _exception;
|
||||
|
||||
public StubJsRuntime(int statusCode) => _statusCode = statusCode;
|
||||
public StubJsRuntime(Exception exception) => _exception = exception;
|
||||
|
||||
public ValueTask<TValue> InvokeAsync<TValue>(string identifier, object?[]? args)
|
||||
=> InvokeAsync<TValue>(identifier, CancellationToken.None, args);
|
||||
|
||||
public ValueTask<TValue> InvokeAsync<TValue>(string identifier, CancellationToken cancellationToken, object?[]? args)
|
||||
{
|
||||
if (_exception is not null)
|
||||
return ValueTask.FromException<TValue>(_exception);
|
||||
|
||||
return ValueTask.FromResult((TValue)(object)_statusCode);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user