Merge remote-tracking branch 'origin/main' into audit/snapshot-gallery

This commit is contained in:
Arnaud Dartois committed 2026-10-20 07:41:41 +02:00
commit b3a705bc87
51 files changed
+6714 -245

No files matched your search

+8 -3
View File
@@ -12,13 +12,18 @@ internal static class AuthHelper
AppUser user,
IJwtService jwtService,
IRolePermissionService rolePermissionService,
UserManager<AppUser> userManager)
UserManager<AppUser> userManager,
DateTime? sessionStarted = null)
{
var roles = await userManager.GetRolesAsync(user).ConfigureAwait(false);
var permissions = rolePermissionService.GetPermissionsForRoles(roles);
var (accessToken, expiresAt) = jwtService.GenerateAccessToken(user, roles, permissions);
var (refreshToken, _) = jwtService.GenerateRefreshToken(user);
var (accessToken, expiresAt) = sessionStarted is null
? jwtService.GenerateAccessToken(user, roles, permissions)
: jwtService.GenerateAccessToken(user, roles, permissions, sessionStarted.Value);
var (refreshToken, _) = sessionStarted is null
? jwtService.GenerateRefreshToken(user)
: jwtService.GenerateRefreshToken(user, sessionStarted.Value);
return ServiceResult<AuthResponse>.Success(new AuthResponse(
accessToken,
@@ -1,4 +1,5 @@
using Heimdall.Application.Common;
using Heimdall.Application.Auth.Services;
using Heimdall.Application.DTOs;
using Heimdall.Application.Common.Persistence;
using Heimdall.Application.Services;
@@ -17,6 +18,7 @@ public class LoginHandler : IRequestHandler<LoginCommand, ServiceResult<AuthResp
private readonly IRolePermissionService _rolePermissionService;
private readonly IUserRepository _userRepository;
private readonly IAuthDataService _authData;
private readonly IApplicationDbContext _db;
private readonly ILogger<LoginHandler> _logger;
public LoginHandler(
@@ -26,7 +28,8 @@ public class LoginHandler : IRequestHandler<LoginCommand, ServiceResult<AuthResp
IRolePermissionService rolePermissionService,
IUserRepository userRepository,
IAuthDataService authData,
ILogger<LoginHandler> logger)
ILogger<LoginHandler> logger,
IApplicationDbContext db)
{
_userManager = userManager;
_signInService = signInService;
@@ -35,6 +38,7 @@ public class LoginHandler : IRequestHandler<LoginCommand, ServiceResult<AuthResp
_userRepository = userRepository;
_authData = authData;
_logger = logger;
_db = db;
}
public async Task<ServiceResult<AuthResponse>> Handle(LoginCommand request, CancellationToken ct)
@@ -55,29 +59,12 @@ public class LoginHandler : IRequestHandler<LoginCommand, ServiceResult<AuthResp
return ServiceResult<AuthResponse>.Failure("Account locked. Try again later.", 429);
}
if (await _userManager.GetTwoFactorEnabledAsync(user))
{
_logger.LogDebug("Login: 2FA required Email={Email}", request.Email);
var signIn = await _signInService.PasswordSignInAsync(user, request.Password, true).ConfigureAwait(false);
if (signIn.ResultType == SignInResultType.LockedOut)
{
_logger.LogWarning("Login: Account locked after 2FA attempt Email={Email}", request.Email);
return ServiceResult<AuthResponse>.Failure("Account locked. Try again later.", 429);
}
if (signIn.ResultType != SignInResultType.Success)
{
_logger.LogWarning("Login: 2FA failed Email={Email}", request.Email);
return ServiceResult<AuthResponse>.Unauthorized("Invalid email or password");
}
_logger.LogInformation("Login: 2FA passed Email={Email}", request.Email);
return ServiceResult<AuthResponse>.Success(new AuthResponse(
string.Empty, string.Empty, DateTime.UtcNow, true,
await AuthHelper.MapUserInfoAsync(user, _userManager)));
}
var result = await _signInService.PasswordSignInAsync(user, request.Password, true).ConfigureAwait(false);
if (result.ResultType != SignInResultType.Success)
var twoFactorEnabled = await _userManager.GetTwoFactorEnabledAsync(user);
if (result.ResultType == SignInResultType.LockedOut)
return ServiceResult<AuthResponse>.Failure("Account locked. Try again later.", 429);
if (result.ResultType != SignInResultType.Success
&& !(result.ResultType == SignInResultType.RequiresTwoFactor && twoFactorEnabled))
{
_logger.LogWarning("Login: Password mismatch Email={Email}", request.Email);
return ServiceResult<AuthResponse>.Unauthorized("Invalid email or password");
@@ -91,6 +78,14 @@ public class LoginHandler : IRequestHandler<LoginCommand, ServiceResult<AuthResp
return ServiceResult<AuthResponse>.Failure("Email not confirmed. Check your inbox for the confirmation link.", 403);
}
if (twoFactorEnabled)
{
var challengeId = await LoginChallengeService.CreateAsync(_db, user, ct);
return ServiceResult<AuthResponse>.Success(new AuthResponse(
string.Empty, string.Empty, DateTime.UtcNow, true,
await AuthHelper.MapUserInfoAsync(user, _userManager), challengeId));
}
_logger.LogInformation("Login: Success Email={Email}", request.Email);
return await AuthHelper.CreateAuthResponseAsync(user, _jwtService, _rolePermissionService, _userManager).ConfigureAwait(false);
}
@@ -1,4 +1,6 @@
using System.Security.Claims;
using System.Globalization;
using Heimdall.Application.Auth.Services;
using Heimdall.Application.Common;
using Heimdall.Application.DTOs;
using Heimdall.Application.Services;
@@ -6,6 +8,7 @@ using Heimdall.Domain.Entities;
using MediatR;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Logging;
using Microsoft.EntityFrameworkCore;
namespace Heimdall.Application.Auth.Commands.RefreshToken;
@@ -65,11 +68,24 @@ public class RefreshTokenHandler : IRequestHandler<RefreshTokenCommand, ServiceR
return ServiceResult<AuthResponse>.Unauthorized("User not found");
}
if (!await AccountSessionPolicy.IsValidAsync(principal, _userManager, _authData, ct)
|| !DateTime.TryParse(principal.FindFirstValue(AccountSessionPolicy.StartedClaim), CultureInfo.InvariantCulture,
DateTimeStyles.RoundtripKind, out var started) || started > DateTime.UtcNow || started.AddDays(7) <= DateTime.UtcNow)
return ServiceResult<AuthResponse>.Unauthorized("Session revoked or expired");
_logger.LogInformation("RefreshToken: Success UserId={UserId}", userId);
// Revoke the old refresh token (rotation)
await _authData.RevokeRefreshTokenAsync(request.RefreshToken, user.Id, ct).ConfigureAwait(false);
try
{
await _authData.RevokeRefreshTokenAsync(request.RefreshToken, user.Id, ct).ConfigureAwait(false);
}
catch (DbUpdateException)
{
// The unique token-id index arbitrates concurrent rotation between instances.
return ServiceResult<AuthResponse>.Unauthorized("Refresh token already consumed");
}
return await AuthHelper.CreateAuthResponseAsync(user, _jwtService, _rolePermissionService, _userManager).ConfigureAwait(false);
return await AuthHelper.CreateAuthResponseAsync(user, _jwtService, _rolePermissionService, _userManager, started).ConfigureAwait(false);
}
}
@@ -141,6 +141,9 @@ public class RegisterHandler : IRequestHandler<RegisterCommand, ServiceResult<Au
// Send confirmation email if SMTP is configured and confirmation is required
await TrySendConfirmationEmailAsync(user, ct).ConfigureAwait(false);
var confirmationRequired = await _authData.GetSettingValueAsync("email.confirmation.required", ct).ConfigureAwait(false);
if (string.Equals(confirmationRequired, "true", StringComparison.OrdinalIgnoreCase) && !user.EmailConfirmed)
return ServiceResult<AuthResponse>.Failure("Account created. Confirm your email before signing in.", 403);
return await AuthHelper.CreateAuthResponseAsync(user, _jwtService, _rolePermissionService, _userManager).ConfigureAwait(false);
}
@@ -4,4 +4,4 @@ using MediatR;
namespace Heimdall.Application.Auth.Commands.Verify2fa;
public record Verify2faCommand(string Email, string Code) : IRequest<ServiceResult<AuthResponse>>;
public record Verify2faCommand(string ChallengeId, string Code) : IRequest<ServiceResult<AuthResponse>>;
@@ -34,14 +34,19 @@ public class Verify2faHandler : IRequestHandler<Verify2faCommand, ServiceResult<
public async Task<ServiceResult<AuthResponse>> Handle(Verify2faCommand request, CancellationToken ct)
{
_logger.LogDebug("Verify2fa: Email={Email}", request.Email);
var challenge = await LoginChallengeService.TakeAttemptAsync(_db, request.ChallengeId ?? "", ct);
if (challenge is null)
return ServiceResult<AuthResponse>.Unauthorized("Invalid or expired challenge");
var user = await _userManager.FindByEmailAsync(request.Email).ConfigureAwait(false);
if (user is null)
{
_logger.LogWarning("Verify2fa: User not found Email={Email}", request.Email);
return ServiceResult<AuthResponse>.Unauthorized("Invalid request");
}
var user = await _userManager.FindByIdAsync(challenge.UserId.ToString());
var emailSetting = await _db.AppSettings.AsNoTracking()
.Where(x => x.Key == "email.confirmation.required").Select(x => x.Value).SingleOrDefaultAsync(ct);
var emailRequired = string.Equals(emailSetting, "true", StringComparison.OrdinalIgnoreCase);
if (user is null || user.SecurityStamp != challenge.SecurityStamp
|| !await _userManager.GetTwoFactorEnabledAsync(user)
|| await _userManager.IsLockedOutAsync(user)
|| (emailRequired && !user.EmailConfirmed))
return ServiceResult<AuthResponse>.Unauthorized("Account unavailable");
var isValid = await _userManager.VerifyTwoFactorTokenAsync(
user, TokenOptions.DefaultAuthenticatorProvider, request.Code);
@@ -52,13 +57,20 @@ public class Verify2faHandler : IRequestHandler<Verify2faCommand, ServiceResult<
var redeemed = await TryRedeemRecoveryCodeAsync(user, request.Code.Trim(), ct).ConfigureAwait(false);
if (!redeemed)
{
_logger.LogWarning("Verify2fa: Invalid code Email={Email}", request.Email);
_logger.LogWarning("Verify2fa: Invalid code UserId={UserId}", challenge.UserId);
await _userManager.AccessFailedAsync(user);
if (await _userManager.IsLockedOutAsync(user))
await _userManager.UpdateSecurityStampAsync(user);
await LoginChallengeService.ReleaseAttemptAsync(_db, challenge, ct);
return ServiceResult<AuthResponse>.Unauthorized("Invalid 2FA code");
}
_logger.LogInformation("Verify2fa: Recovery code redeemed Email={Email}", request.Email);
_logger.LogInformation("Verify2fa: Recovery code redeemed UserId={UserId}", challenge.UserId);
}
_logger.LogInformation("Verify2fa: Success Email={Email}", request.Email);
if (await LoginChallengeService.ConsumeAsync(_db, challenge, ct) != 1)
return ServiceResult<AuthResponse>.Unauthorized("Challenge already used");
await _userManager.ResetAccessFailedCountAsync(user);
_logger.LogInformation("Verify2fa: Success UserId={UserId}", challenge.UserId);
return await AuthHelper.CreateAuthResponseAsync(user, _jwtService, _rolePermissionService, _userManager).ConfigureAwait(false);
}
@@ -68,15 +80,8 @@ public class Verify2faHandler : IRequestHandler<Verify2faCommand, ServiceResult<
return false;
var codeHash = RecoveryCodeService.Hash(code);
var match = await _db.UserRecoveryCodes
.FirstOrDefaultAsync(r => r.UserId == user.Id && r.CodeHash == codeHash && r.UsedAt == null, ct)
.ConfigureAwait(false);
if (match is null)
return false;
match.MarkUsed();
await _db.SaveChangesAsync(ct).ConfigureAwait(false);
return true;
return await _db.UserRecoveryCodes
.Where(r => r.UserId == user.Id && r.CodeHash == codeHash && r.UsedAt == null)
.ExecuteUpdateAsync(s => s.SetProperty(r => r.UsedAt, DateTime.UtcNow), ct) == 1;
}
}
@@ -6,7 +6,7 @@ public class Verify2faValidator : AbstractValidator<Verify2faCommand>
{
public Verify2faValidator()
{
RuleFor(x => x.Email).NotEmpty().EmailAddress().MaximumLength(256);
RuleFor(x => x.Code).NotEmpty().Length(6).WithMessage("2FA code must be 6 digits");
RuleFor(x => x.ChallengeId).NotEmpty().Length(64);
RuleFor(x => x.Code).NotEmpty().MaximumLength(64);
}
}
@@ -0,0 +1,52 @@
using System.Security.Claims;
using System.Globalization;
using Heimdall.Application.Services;
using Heimdall.Application.Common;
using Heimdall.Domain.Entities;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
namespace Heimdall.Application.Auth.Services;
public static class AccountSessionPolicy
{
public const string StampClaim = "security_stamp";
public const string StartedClaim = "session_started";
public static async Task<bool> IsValidAsync(ClaimsPrincipal principal, UserManager<AppUser> users, IAuthDataService data, CancellationToken ct)
{
if (!DateTime.TryParse(principal.FindFirstValue(StartedClaim), CultureInfo.InvariantCulture,
DateTimeStyles.RoundtripKind, out var started) || started > DateTime.UtcNow || started.AddDays(7) <= DateTime.UtcNow)
return false;
var id = principal.FindFirstValue(ClaimTypes.NameIdentifier);
var user = id is null ? null : await users.FindByIdAsync(id);
if (user is null || string.IsNullOrEmpty(user.SecurityStamp)
|| principal.FindFirstValue(StampClaim) != user.SecurityStamp
|| await users.IsLockedOutAsync(user)) return false;
var required = await data.GetSettingValueAsync("email.confirmation.required", ct);
if (string.Equals(required, "true", StringComparison.OrdinalIgnoreCase) && !user.EmailConfirmed) return false;
return true;
}
/// <summary>Validates a live connection against persisted values without using Identity's tracked user cache.</summary>
public static async Task<bool> IsValidLiveAsync(ClaimsPrincipal principal, IApplicationDbContext db, CancellationToken ct)
{
if (!DateTime.TryParse(principal.FindFirstValue(StartedClaim), CultureInfo.InvariantCulture,
DateTimeStyles.RoundtripKind, out var started) || started > DateTime.UtcNow || started.AddDays(7) <= DateTime.UtcNow)
return false;
var id = principal.FindFirstValue(ClaimTypes.NameIdentifier);
if (!Guid.TryParse(id, out var userId)) return false;
var user = await db.Users.AsNoTracking().Where(u => u.Id == userId)
.Select(u => new { u.SecurityStamp, u.LockoutEnabled, u.LockoutEnd, u.EmailConfirmed })
.SingleOrDefaultAsync(ct);
if (user is null || string.IsNullOrEmpty(user.SecurityStamp)
|| principal.FindFirstValue(StampClaim) != user.SecurityStamp
|| (user.LockoutEnabled && user.LockoutEnd > DateTimeOffset.UtcNow)) return false;
var confirmationRequired = await db.AppSettings.AsNoTracking()
.Where(s => s.Key == "email.confirmation.required")
.Select(s => s.Value).SingleOrDefaultAsync(ct);
return !string.Equals(confirmationRequired, "true", StringComparison.OrdinalIgnoreCase) || user.EmailConfirmed;
}
}
@@ -0,0 +1,52 @@
using System.Security.Cryptography;
using System.Text;
using Heimdall.Application.Common;
using Heimdall.Domain.Entities;
using Microsoft.EntityFrameworkCore;
namespace Heimdall.Application.Auth.Services;
public static class LoginChallengeService
{
public static string Hash(string token) => Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(token)));
public static async Task<string> CreateAsync(IApplicationDbContext db, AppUser user, CancellationToken ct)
{
var token = Convert.ToHexString(RandomNumberGenerator.GetBytes(32));
db.GetSet<LoginChallenge>().Add(new LoginChallenge
{
Id = Hash(token), UserId = user.Id, SecurityStamp = user.SecurityStamp ?? "",
ExpiresAt = DateTime.UtcNow.AddMinutes(5)
});
await db.SaveChangesAsync(ct);
return token;
}
// Compare-and-swap allocates exactly one attempt to each verifier across instances.
public static async Task<LoginChallenge?> TakeAttemptAsync(IApplicationDbContext db, string token, CancellationToken ct)
{
if (token.Length != 64) return null;
var id = Hash(token);
var now = DateTime.UtcNow;
var query = db.GetSet<LoginChallenge>().Where(x => x.Id == id && !x.Consumed && !x.Verifying && x.ExpiresAt > now && x.Attempts < 5);
var challenge = await query.AsNoTracking().SingleOrDefaultAsync(ct);
if (challenge is null) return null;
var updated = await query.Where(x => x.Attempts == challenge.Attempts)
.ExecuteUpdateAsync(s => s.SetProperty(x => x.Attempts, x => x.Attempts + 1).SetProperty(x => x.Verifying, true), ct);
if (updated != 1) return null;
challenge.Attempts++;
return challenge;
}
public static Task<int> ReleaseAttemptAsync(IApplicationDbContext db, LoginChallenge challenge, CancellationToken ct) =>
db.GetSet<LoginChallenge>().Where(x => x.Id == challenge.Id && !x.Consumed && x.Attempts == challenge.Attempts)
.ExecuteUpdateAsync(s => s.SetProperty(x => x.Verifying, false), ct);
public static Task<int> ConsumeAsync(IApplicationDbContext db, LoginChallenge challenge, CancellationToken ct)
{
var now = DateTime.UtcNow;
return db.GetSet<LoginChallenge>()
.Where(x => x.Id == challenge.Id && !x.Consumed && x.ExpiresAt > now && x.Attempts == challenge.Attempts)
.ExecuteUpdateAsync(s => s.SetProperty(x => x.Consumed, true), ct);
}
}
+3 -2
View File
@@ -4,7 +4,7 @@ public record RegisterRequest(string Email, string Password, string DisplayName)
public record LoginRequest(string Email, string Password);
public record Verify2faRequest(string Email, string Code);
public record Verify2faRequest(string ChallengeId, string Code);
public record RefreshTokenRequest(string RefreshToken);
@@ -13,7 +13,8 @@ public record AuthResponse(
string RefreshToken,
DateTime ExpiresAt,
bool Requires2fa,
UserInfo User);
UserInfo User,
string? ChallengeId = null);
public record UserInfo(
Guid Id,
@@ -6,7 +6,9 @@ namespace Heimdall.Application.Services;
public interface IJwtService
{
(string token, DateTime expiresAt) GenerateAccessToken(AppUser user, IList<string> roles, IList<string> permissions);
(string token, DateTime expiresAt) GenerateAccessToken(AppUser user, IList<string> roles, IList<string> permissions, DateTime sessionStarted) => GenerateAccessToken(user, roles, permissions);
(string token, DateTime expiresAt) GenerateRefreshToken(AppUser user);
(string token, DateTime expiresAt) GenerateRefreshToken(AppUser user, DateTime sessionStarted) => GenerateRefreshToken(user);
ClaimsPrincipal? ValidateRefreshToken(string refreshToken);
string? GetUserIdFromExpiredToken(string token);
}
@@ -37,6 +37,7 @@ public class AssignRolesHandler : IRequestHandler<AssignRolesCommand, ServiceRes
await _userManager.RemoveFromRolesAsync(user, currentRoles).ConfigureAwait(false);
await _userManager.AddToRolesAsync(user, command.Roles).ConfigureAwait(false);
await _userManager.UpdateSecurityStampAsync(user).ConfigureAwait(false);
await _repository.AddAuditLogAsync(null, "UserRolesUpdated", "User",
command.UserId.ToString(),
@@ -24,6 +24,7 @@ public class LockUserHandler : IRequestHandler<LockUserCommand, ServiceResult>
return ServiceResult.NotFound("User not found");
await _userManager.SetLockoutEndDateAsync(user, DateTimeOffset.MaxValue).ConfigureAwait(false);
await _userManager.UpdateSecurityStampAsync(user).ConfigureAwait(false);
await _repository.AddAuditLogAsync(null, "UserLocked", "User",
command.UserId.ToString(), null, null, ct);
@@ -0,0 +1,13 @@
namespace Heimdall.Domain.Entities;
/// <summary>Short-lived password proof. Only the SHA-256 digest of the opaque token is stored.</summary>
public class LoginChallenge
{
public string Id { get; set; } = "";
public Guid UserId { get; set; }
public string SecurityStamp { get; set; } = "";
public DateTime ExpiresAt { get; set; }
public int Attempts { get; set; }
public bool Verifying { get; set; }
public bool Consumed { get; set; }
}
@@ -0,0 +1,18 @@
using Heimdall.Domain.Entities;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
namespace Heimdall.Infrastructure.Data.Configurations;
public class LoginChallengeConfiguration : IEntityTypeConfiguration<LoginChallenge>
{
public void Configure(EntityTypeBuilder<LoginChallenge> builder)
{
builder.ToTable("login_challenges");
builder.HasKey(x => x.Id);
builder.Property(x => x.Id).HasMaxLength(64);
builder.Property(x => x.SecurityStamp).HasMaxLength(256);
builder.HasIndex(x => x.ExpiresAt);
builder.HasOne<AppUser>().WithMany().HasForeignKey(x => x.UserId).OnDelete(DeleteBehavior.Cascade);
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,107 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Heimdall.Infrastructure.Migrations
{
/// <inheritdoc />
public partial class ReconcileExistingAccessSchema : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "group_camera_accesses",
columns: table => new
{
Id = table.Column<Guid>(type: "uuid", nullable: false),
GroupId = table.Column<Guid>(type: "uuid", nullable: false),
CameraId = table.Column<Guid>(type: "uuid", nullable: false),
CreatedAt = table.Column<DateTime>(type: "timestamp with time zone", nullable: false, defaultValueSql: "NOW()"),
UpdatedAt = table.Column<DateTime>(type: "timestamp with time zone", nullable: false, defaultValueSql: "NOW()")
},
constraints: table =>
{
table.PrimaryKey("PK_group_camera_accesses", x => x.Id);
table.ForeignKey(
name: "FK_group_camera_accesses_cameras_CameraId",
column: x => x.CameraId,
principalTable: "cameras",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_group_camera_accesses_groups_GroupId",
column: x => x.GroupId,
principalTable: "groups",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "UserCameraAccesses",
columns: table => new
{
UserId = table.Column<Guid>(type: "uuid", nullable: false),
SiteId = table.Column<Guid>(type: "uuid", nullable: false),
CameraId = table.Column<Guid>(type: "uuid", nullable: false),
CreatedAt = table.Column<DateTime>(type: "timestamp with time zone", nullable: false),
UpdatedAt = table.Column<DateTime>(type: "timestamp with time zone", nullable: false),
Id = table.Column<Guid>(type: "uuid", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_UserCameraAccesses", x => new { x.UserId, x.SiteId, x.CameraId });
table.ForeignKey(
name: "FK_UserCameraAccesses_cameras_CameraId",
column: x => x.CameraId,
principalTable: "cameras",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_UserCameraAccesses_sites_SiteId",
column: x => x.SiteId,
principalTable: "sites",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_UserCameraAccesses_users_UserId",
column: x => x.UserId,
principalTable: "users",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateIndex(
name: "IX_group_camera_accesses_CameraId",
table: "group_camera_accesses",
column: "CameraId");
migrationBuilder.CreateIndex(
name: "IX_group_camera_accesses_GroupId_CameraId",
table: "group_camera_accesses",
columns: new[] { "GroupId", "CameraId" },
unique: true);
migrationBuilder.CreateIndex(
name: "IX_UserCameraAccesses_CameraId",
table: "UserCameraAccesses",
column: "CameraId");
migrationBuilder.CreateIndex(
name: "IX_UserCameraAccesses_SiteId",
table: "UserCameraAccesses",
column: "SiteId");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "group_camera_accesses");
migrationBuilder.DropTable(
name: "UserCameraAccesses");
}
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,50 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Heimdall.Infrastructure.Migrations;
public partial class AddLoginChallenges : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "login_challenges",
columns: table => new
{
Id = table.Column<string>(type: "character varying(64)", maxLength: 64, nullable: false),
UserId = table.Column<Guid>(type: "uuid", nullable: false),
SecurityStamp = table.Column<string>(type: "character varying(256)", maxLength: 256, nullable: false),
ExpiresAt = table.Column<DateTime>(type: "timestamp with time zone", nullable: false),
Attempts = table.Column<int>(type: "integer", nullable: false),
Verifying = table.Column<bool>(type: "boolean", nullable: false),
Consumed = table.Column<bool>(type: "boolean", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_login_challenges", x => x.Id);
table.ForeignKey(
name: "FK_login_challenges_users_UserId",
column: x => x.UserId,
principalTable: "users",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateIndex(
name: "IX_login_challenges_ExpiresAt",
table: "login_challenges",
column: "ExpiresAt");
migrationBuilder.CreateIndex(
name: "IX_login_challenges_UserId",
table: "login_challenges",
column: "UserId");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "login_challenges");
}
}
@@ -1285,6 +1285,38 @@ namespace Heimdall.Infrastructure.Migrations
b.ToTable("groups", (string)null);
});
modelBuilder.Entity("Heimdall.Domain.Entities.GroupCameraAccess", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<Guid>("CameraId")
.HasColumnType("uuid");
b.Property<DateTime>("CreatedAt")
.ValueGeneratedOnAdd()
.HasColumnType("timestamp with time zone")
.HasDefaultValueSql("NOW()");
b.Property<Guid>("GroupId")
.HasColumnType("uuid");
b.Property<DateTime>("UpdatedAt")
.ValueGeneratedOnAdd()
.HasColumnType("timestamp with time zone")
.HasDefaultValueSql("NOW()");
b.HasKey("Id");
b.HasIndex("CameraId");
b.HasIndex("GroupId", "CameraId")
.IsUnique();
b.ToTable("group_camera_accesses", (string)null);
});
modelBuilder.Entity("Heimdall.Domain.Entities.KnownFace", b =>
{
b.Property<Guid>("Id")
@@ -1362,6 +1394,41 @@ namespace Heimdall.Infrastructure.Migrations
b.ToTable("license_plates", (string)null);
});
modelBuilder.Entity("Heimdall.Domain.Entities.LoginChallenge", b =>
{
b.Property<string>("Id")
.HasMaxLength(64)
.HasColumnType("character varying(64)");
b.Property<bool>("Verifying")
.HasColumnType("boolean");
b.Property<int>("Attempts")
.HasColumnType("integer");
b.Property<bool>("Consumed")
.HasColumnType("boolean");
b.Property<DateTime>("ExpiresAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("SecurityStamp")
.IsRequired()
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.Property<Guid>("UserId")
.HasColumnType("uuid");
b.HasKey("Id");
b.HasIndex("ExpiresAt");
b.HasIndex("UserId");
b.ToTable("login_challenges", (string)null);
});
modelBuilder.Entity("Heimdall.Domain.Entities.Notification", b =>
{
b.Property<Guid>("Id")
@@ -1780,6 +1847,35 @@ namespace Heimdall.Infrastructure.Migrations
b.ToTable("user_cameras", (string)null);
});
modelBuilder.Entity("Heimdall.Domain.Entities.UserCameraAccess", b =>
{
b.Property<Guid>("UserId")
.HasColumnType("uuid");
b.Property<Guid>("SiteId")
.HasColumnType("uuid");
b.Property<Guid>("CameraId")
.HasColumnType("uuid");
b.Property<DateTime>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<Guid>("Id")
.HasColumnType("uuid");
b.Property<DateTime>("UpdatedAt")
.HasColumnType("timestamp with time zone");
b.HasKey("UserId", "SiteId", "CameraId");
b.HasIndex("CameraId");
b.HasIndex("SiteId");
b.ToTable("UserCameraAccesses", (string)null);
});
modelBuilder.Entity("Heimdall.Domain.Entities.UserGroup", b =>
{
b.Property<Guid>("UserId")
@@ -2225,6 +2321,25 @@ namespace Heimdall.Infrastructure.Migrations
b.Navigation("DiscoveryResult");
});
modelBuilder.Entity("Heimdall.Domain.Entities.GroupCameraAccess", b =>
{
b.HasOne("Heimdall.Domain.Entities.Camera", "Camera")
.WithMany("GroupCameraAccesses")
.HasForeignKey("CameraId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Heimdall.Domain.Entities.Group", "Group")
.WithMany("GroupCameraAccesses")
.HasForeignKey("GroupId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Camera");
b.Navigation("Group");
});
modelBuilder.Entity("Heimdall.Domain.Entities.KnownFace", b =>
{
b.HasOne("Heimdall.Domain.Entities.Person", "Person")
@@ -2253,6 +2368,15 @@ namespace Heimdall.Infrastructure.Migrations
b.Navigation("Vehicle");
});
modelBuilder.Entity("Heimdall.Domain.Entities.LoginChallenge", b =>
{
b.HasOne("Heimdall.Domain.Entities.AppUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Heimdall.Domain.Entities.Recording", b =>
{
b.HasOne("Heimdall.Domain.Entities.Camera", "Camera")
@@ -2301,6 +2425,32 @@ namespace Heimdall.Infrastructure.Migrations
b.Navigation("User");
});
modelBuilder.Entity("Heimdall.Domain.Entities.UserCameraAccess", b =>
{
b.HasOne("Heimdall.Domain.Entities.Camera", "Camera")
.WithMany()
.HasForeignKey("CameraId")
.OnDelete(DeleteBehavior.Cascade);
b.HasOne("Heimdall.Domain.Entities.Site", "Site")
.WithMany()
.HasForeignKey("SiteId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Heimdall.Domain.Entities.AppUser", "User")
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Camera");
b.Navigation("Site");
b.Navigation("User");
});
modelBuilder.Entity("Heimdall.Domain.Entities.UserGroup", b =>
{
b.HasOne("Heimdall.Domain.Entities.Group", "Group")
@@ -2417,6 +2567,8 @@ namespace Heimdall.Infrastructure.Migrations
b.Navigation("Credentials");
b.Navigation("DetectionProfile");
b.Navigation("GroupCameraAccesses");
});
modelBuilder.Entity("Heimdall.Domain.Entities.CameraDiscoveryResult", b =>
@@ -2426,6 +2578,8 @@ namespace Heimdall.Infrastructure.Migrations
modelBuilder.Entity("Heimdall.Domain.Entities.Group", b =>
{
b.Navigation("GroupCameraAccesses");
b.Navigation("UserGroups");
});
@@ -15,7 +15,9 @@ public class AuthSignInService : IAuthSignInService
public async Task<SignInServiceResult> PasswordSignInAsync(AppUser user, string password, bool lockoutOnFailure)
{
var result = await _signInManager.PasswordSignInAsync(user, password, false, lockoutOnFailure).ConfigureAwait(false);
var result = await _signInManager.CheckPasswordSignInAsync(user, password, lockoutOnFailure).ConfigureAwait(false);
if (result.IsLockedOut)
await _signInManager.UserManager.UpdateSecurityStampAsync(user).ConfigureAwait(false);
return result switch
{
{ Succeeded: true } => new SignInServiceResult(SignInResultType.Success),
@@ -1,4 +1,6 @@
using Heimdall.Application.Auth.Services;
using System.IdentityModel.Tokens.Jwt;
using System.Globalization;
using System.Security.Claims;
using System.Text;
using Heimdall.Application.Services;
@@ -21,18 +23,23 @@ public class JwtService : IJwtService
}
public (string token, DateTime expiresAt) GenerateAccessToken(AppUser user, IList<string> roles, IList<string> permissions)
=> GenerateAccessToken(user, roles, permissions, DateTime.UtcNow);
public (string token, DateTime expiresAt) GenerateAccessToken(AppUser user, IList<string> roles, IList<string> permissions, DateTime sessionStarted)
{
var key = new SymmetricSecurityKey(
Encoding.UTF8.GetBytes(GetJwtKey()));
var expiresAt = DateTime.UtcNow.AddMinutes(
double.TryParse(_configuration["Jwt:AccessTokenExpiryMinutes"], out var minutes) ? minutes : 15);
double.TryParse(_configuration["Jwt:AccessTokenExpiryMinutes"], NumberStyles.Float, CultureInfo.InvariantCulture, out var minutes) ? minutes : 15);
var claims = new List<Claim>
{
new(JwtRegisteredClaimNames.Sub, user.Id.ToString()),
new(AccountSessionPolicy.StampClaim, user.SecurityStamp ?? ""),
new(JwtRegisteredClaimNames.Email, user.Email ?? ""),
new(JwtRegisteredClaimNames.Name, user.DisplayName),
new(AccountSessionPolicy.StartedClaim, sessionStarted.ToString("O")),
};
// Add individual role claims so [Authorize(Roles = "Admin")] works
@@ -55,18 +62,24 @@ public class JwtService : IJwtService
}
public (string token, DateTime expiresAt) GenerateRefreshToken(AppUser user)
=> GenerateRefreshToken(user, DateTime.UtcNow);
public (string token, DateTime expiresAt) GenerateRefreshToken(AppUser user, DateTime sessionStarted)
{
var refreshKeyValue = GetJwtRefreshKey();
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(refreshKeyValue));
var expiresAt = DateTime.UtcNow.AddDays(
double.TryParse(_configuration["Jwt:RefreshTokenExpiryDays"], out var days) ? days : 7);
double.TryParse(_configuration["Jwt:RefreshTokenExpiryDays"], NumberStyles.Float, CultureInfo.InvariantCulture, out var days) ? days : 7);
expiresAt = new[] { expiresAt, sessionStarted.AddDays(7) }.Min();
var tokenId = Guid.NewGuid().ToString(); // unique jti for DB revocation tracking
var claims = new List<Claim>
{
new(JwtRegisteredClaimNames.Sub, user.Id.ToString()),
new(AccountSessionPolicy.StampClaim, user.SecurityStamp ?? ""),
new(JwtRegisteredClaimNames.Jti, tokenId),
new(AccountSessionPolicy.StartedClaim, sessionStarted.ToString("O")),
new(JwtRegisteredClaimNames.Email, user.Email ?? ""),
};
@@ -100,9 +113,7 @@ public class JwtService : IJwtService
ClockSkew = TimeSpan.Zero
}, out _);
}
catch (Exception ex) when (ex is SecurityTokenExpiredException
or SecurityTokenInvalidSignatureException
or SecurityTokenInvalidIssuerException
catch (Exception ex) when (ex is SecurityTokenException
or ArgumentException)
{
_logger.LogWarning("Refresh token validation failed: {ExceptionType} — {Message}",
@@ -149,9 +160,7 @@ public class JwtService : IJwtService
return principal.FindFirst(ClaimTypes.NameIdentifier)?.Value
?? principal.FindFirst(JwtRegisteredClaimNames.Sub)?.Value;
}
catch (Exception ex) when (ex is SecurityTokenExpiredException
or SecurityTokenInvalidSignatureException
or SecurityTokenInvalidIssuerException
catch (Exception ex) when (ex is SecurityTokenException
or ArgumentException)
{
_logger.LogWarning("Failed to read expired token: {ExceptionType} — {Message}",
@@ -85,6 +85,7 @@
</div>
@code {
private string _challengeId = "";
private string _email = "";
private string _password = "";
private string _twoFactorCode = "";
@@ -142,6 +143,8 @@
// Check if 2FA is required
if (result.Requires2fa)
{
_challengeId = result.ChallengeId ?? "";
_password = "";
_requires2fa = true;
_loading = false;
Logger.LogInformation("2FA required for {Email}", _email);
@@ -173,7 +176,7 @@
try
{
var result = await Api.Verify2faAsync(_email, _twoFactorCode.Trim());
var result = await Api.Verify2faAsync(_challengeId, _twoFactorCode.Trim());
if (result is null)
{
Logger.LogWarning("2FA verification failed for {Email}", _email);
@@ -85,17 +85,17 @@ public class AuthController : ControllerBase
[ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)]
public async Task<IActionResult> Verify2fa([FromBody] Verify2faRequest request, CancellationToken ct)
{
_logger.LogInformation("2FA verification attempt for {Email}", request.Email);
var command = new Verify2faCommand(request.Email, request.Code);
_logger.LogInformation("2FA verification attempt");
var command = new Verify2faCommand(request.ChallengeId, request.Code);
var result = await _mediator.Send(command, ct);
if (result.IsSuccess)
{
_logger.LogInformation("2FA verification successful for {Email}", request.Email);
_logger.LogInformation("2FA verification successful");
return Ok(result.Data);
}
_logger.LogWarning("2FA verification failed for {Email}: {Error}", request.Email, result.Error);
_logger.LogWarning("2FA verification failed: {Error}", result.Error);
return StatusCode(result.StatusCode ?? 401, new { error = result.Error });
}
+30 -9
View File
@@ -1,3 +1,4 @@
using Heimdall.Api.Security;
using Heimdall.Application.Metrics;
using Heimdall.Application.Services;
using Microsoft.AspNetCore.Authorization;
@@ -13,24 +14,31 @@ namespace Heimdall.Api.Hubs;
public class AdminHub : Hub
{
private readonly ILogger<AdminHub> _logger;
private readonly ResourceAccess _access;
private readonly LiveSubscriptions _subscriptions;
public AdminHub(ILogger<AdminHub> logger) => _logger = logger;
public AdminHub(ILogger<AdminHub> logger, ResourceAccess access, LiveSubscriptions subscriptions)
{ _logger = logger; _access = access; _subscriptions = subscriptions; }
/// <summary>
/// Clients call this to join the admin broadcast group.
/// </summary>
public async Task JoinAdminBroadcast()
{
await Groups.AddToGroupAsync(Context.ConnectionId, "admin-broadcast");
var requester = await _access.ResolveAsync(Context.User, Context.ConnectionAborted);
if (requester is null || !await _access.IsAdminAsync(requester, Context.ConnectionAborted))
throw new HubException("Access denied");
_subscriptions.Join("admin", Context.ConnectionId, "admin-broadcast", Context.User!);
_logger.LogDebug("Admin client {ConnectionId} joined admin broadcast group", Context.ConnectionId);
}
/// <summary>
/// Clients call this to leave the admin broadcast group.
/// </summary>
public async Task LeaveAdminBroadcast()
public Task LeaveAdminBroadcast()
{
await Groups.RemoveFromGroupAsync(Context.ConnectionId, "admin-broadcast");
_subscriptions.Leave("admin", Context.ConnectionId, "admin-broadcast");
return Task.CompletedTask;
}
public override async Task OnConnectedAsync()
@@ -42,6 +50,7 @@ public class AdminHub : Hub
public override async Task OnDisconnectedAsync(Exception? exception)
{
_subscriptions.Disconnect("admin", Context.ConnectionId);
HeimdallMetrics.SignalRConnectionRemoved();
_logger.LogDebug("Admin disconnected from admin hub: {ConnectionId}", Context.ConnectionId);
await base.OnDisconnectedAsync(exception);
@@ -56,34 +65,46 @@ public class AdminBroadcastService : IAdminBroadcastService
{
private readonly IHubContext<AdminHub> _hubContext;
private readonly ILogger<AdminBroadcastService> _logger;
private readonly ResourceAccess _access;
private readonly LiveSubscriptions _subscriptions;
public AdminBroadcastService(IHubContext<AdminHub> hubContext, ILogger<AdminBroadcastService> logger)
public AdminBroadcastService(IHubContext<AdminHub> hubContext, ILogger<AdminBroadcastService> logger,
ResourceAccess access, LiveSubscriptions subscriptions)
{
_hubContext = hubContext;
_logger = logger;
_access = access;
_subscriptions = subscriptions;
}
public async Task NotifyConfigChanged(string key, string? oldValue, string? newValue, CancellationToken ct = default)
{
_logger.LogDebug("Broadcasting config change: {Key}", key);
await _hubContext.Clients.Group("admin-broadcast").SendAsync("ConfigChanged", new { key, oldValue, newValue }, ct);
await SendToAdminsAsync("ConfigChanged", new { key, oldValue, newValue }, ct);
}
public async Task NotifyCameraAdded(Guid siteId, Guid cameraId, string cameraName, CancellationToken ct = default)
{
_logger.LogDebug("Broadcasting camera added: {CameraName} ({CameraId})", cameraName, cameraId);
await _hubContext.Clients.Group("admin-broadcast").SendAsync("CameraAdded", new { siteId, cameraId, cameraName }, ct);
await SendToAdminsAsync("CameraAdded", new { siteId, cameraId, cameraName }, ct);
}
public async Task NotifyCameraRemoved(Guid siteId, Guid cameraId, CancellationToken ct = default)
{
_logger.LogDebug("Broadcasting camera removed: {CameraId}", cameraId);
await _hubContext.Clients.Group("admin-broadcast").SendAsync("CameraRemoved", new { siteId, cameraId }, ct);
await SendToAdminsAsync("CameraRemoved", new { siteId, cameraId }, ct);
}
public async Task NotifyUserRoleChanged(Guid userId, string newRole, CancellationToken ct = default)
{
_logger.LogDebug("Broadcasting user role change: User={UserId} Role={NewRole}", userId, newRole);
await _hubContext.Clients.Group("admin-broadcast").SendAsync("UserRoleChanged", new { userId, newRole }, ct);
await SendToAdminsAsync("UserRoleChanged", new { userId, newRole }, ct);
}
private async Task SendToAdminsAsync(string method, object payload, CancellationToken ct)
{
var recipients = await _subscriptions.AuthorizedAsync("admin", "admin-broadcast", _access,
r => _access.IsAdminAsync(r, ct), ct);
await _hubContext.Clients.Clients(recipients).SendAsync(method, payload, ct);
}
}
+34 -13
View File
@@ -1,4 +1,5 @@
using System.Security.Claims;
using Heimdall.Api.Security;
using Heimdall.Application.DTOs;
using Heimdall.Application.Metrics;
using Heimdall.Application.Services;
@@ -11,31 +12,39 @@ namespace Heimdall.Api.Hubs;
/// SignalR hub for in-app notifications with badge count.
/// JWT-authenticated users receive new notifications and unread count updates
/// without polling.
/// Groups: "notif_{userId}"
/// Personal notification subscriptions are reauthorized before each broadcast.
/// </summary>
[Authorize(AuthenticationSchemes = "JwtBearer")]
public class NotificationsHub : Hub
{
private readonly ILogger<NotificationsHub> _logger;
private readonly ResourceAccess _access;
private readonly LiveSubscriptions _subscriptions;
public NotificationsHub(ILogger<NotificationsHub> logger) => _logger = logger;
public NotificationsHub(ILogger<NotificationsHub> logger, ResourceAccess access, LiveSubscriptions subscriptions)
{ _logger = logger; _access = access; _subscriptions = subscriptions; }
/// <summary>
/// Clients call this to join their personal notification channel.
/// The user ID is extracted from the JWT claim.
/// Identity and account session are resolved from persisted state.
/// </summary>
public async Task JoinPersonalNotifications()
{
var userId = Context.User?.FindFirst(ClaimTypes.NameIdentifier)?.Value;
if (userId is null)
{
await Clients.Caller.SendAsync("Error", "User not authenticated");
return;
}
await Groups.AddToGroupAsync(Context.ConnectionId, $"notif_{userId}");
var requester = await _access.ResolveAsync(Context.User, Context.ConnectionAborted);
if (requester is null || requester.Kind != RequesterKind.Human)
throw new HubException("Access denied");
var userId = requester.Id.ToString();
_subscriptions.Join("notifications", Context.ConnectionId, userId, Context.User!);
_logger.LogDebug("Client {ConnectionId} joined personal notifications for user {UserId}", Context.ConnectionId, userId);
}
public Task LeavePersonalNotifications()
{
var id = Context.User?.FindFirstValue(ClaimTypes.NameIdentifier);
if (id is not null) _subscriptions.Leave("notifications", Context.ConnectionId, id);
return Task.CompletedTask;
}
public override async Task OnConnectedAsync()
{
HeimdallMetrics.SignalRConnectionAdded();
@@ -45,6 +54,7 @@ public class NotificationsHub : Hub
public override async Task OnDisconnectedAsync(Exception? exception)
{
_subscriptions.Disconnect("notifications", Context.ConnectionId);
HeimdallMetrics.SignalRConnectionRemoved();
_logger.LogDebug("Client disconnected from notifications hub: {ConnectionId}", Context.ConnectionId);
await base.OnDisconnectedAsync(exception);
@@ -59,22 +69,33 @@ public class NotificationBroadcastService : INotificationBroadcastService
{
private readonly IHubContext<NotificationsHub> _hubContext;
private readonly ILogger<NotificationBroadcastService> _logger;
private readonly ResourceAccess _access;
private readonly LiveSubscriptions _subscriptions;
public NotificationBroadcastService(IHubContext<NotificationsHub> hubContext, ILogger<NotificationBroadcastService> logger)
public NotificationBroadcastService(IHubContext<NotificationsHub> hubContext, ILogger<NotificationBroadcastService> logger,
ResourceAccess access, LiveSubscriptions subscriptions)
{
_hubContext = hubContext;
_logger = logger;
_access = access;
_subscriptions = subscriptions;
}
public async Task NotifyNewNotification(NotificationDto notification, CancellationToken ct = default)
{
_logger.LogDebug("Broadcasting new notification: {NotificationId} to user {UserId}", notification.Id, notification.UserId);
await _hubContext.Clients.Group($"notif_{notification.UserId}").SendAsync("NewNotification", notification, ct);
var recipients = await RecipientsAsync(notification.UserId, ct);
await _hubContext.Clients.Clients(recipients).SendAsync("NewNotification", notification, ct);
}
public async Task NotifyUnreadCount(Guid userId, int count, CancellationToken ct = default)
{
_logger.LogDebug("Broadcasting unread count: User={UserId} Count={Count}", userId, count);
await _hubContext.Clients.Group($"notif_{userId}").SendAsync("UnreadCount", new { count }, ct);
var recipients = await RecipientsAsync(userId, ct);
await _hubContext.Clients.Clients(recipients).SendAsync("UnreadCount", new { count }, ct);
}
private Task<IReadOnlyList<string>> RecipientsAsync(Guid userId, CancellationToken ct) =>
_subscriptions.AuthorizedAsync("notifications", userId.ToString(), _access,
r => Task.FromResult(r.Kind == RequesterKind.Human && r.Id == userId), ct);
}
+42 -13
View File
@@ -535,7 +535,7 @@ public partial class Program
options.Cookie.SameSite = SameSiteMode.Lax;
options.Cookie.SecurePolicy = CookieSecurePolicy.SameAsRequest;
options.ExpireTimeSpan = TimeSpan.FromDays(7);
options.SlidingExpiration = true;
options.SlidingExpiration = false;
});
}
@@ -562,9 +562,19 @@ public partial class Program
builder.Services.AddHttpContextAccessor();
builder.Services.AddScoped<HeimdallApiClient>();
builder.Services.AddScoped<NotificationsHubClient>();
builder.Services.AddTransient<TokenRefreshHandler>();
builder.Services.AddScoped<TokenRefreshHandler>(sp =>
{
var handler = ActivatorUtilities.CreateInstance<TokenRefreshHandler>(sp);
var origin = ActivatorUtilities.CreateInstance<SameOriginHttpMessageHandler>(sp);
origin.InnerHandler = sp.GetRequiredService<IHttpMessageHandlerFactory>().CreateHandler("HeimdallApi");
handler.InnerHandler = origin;
return handler;
});
builder.Services.AddTransient<SameOriginHttpMessageHandler>();
builder.Services.AddHttpClient("HeimdallRefresh")
.ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler { UseCookies = false });
var apiBaseUrlConfigured = ApiBaseUrlResolver.IsConfigured(builder.Configuration);
var apiBaseUrl = apiBaseUrlConfigured
? ApiBaseUrlResolver.ResolveConfigured(builder.Configuration)!
@@ -574,9 +584,7 @@ public partial class Program
var baseUrl = apiBaseUrl.EndsWith('/') ? apiBaseUrl : apiBaseUrl + "/";
client.BaseAddress = new Uri(baseUrl);
client.Timeout = TimeSpan.FromSeconds(30);
})
.AddHttpMessageHandler<TokenRefreshHandler>()
.AddHttpMessageHandler<SameOriginHttpMessageHandler>();
}).ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler { UseCookies = false });
if (apiBaseUrlConfigured)
Console.WriteLine($"[DIAG] ApiBaseUrl: {apiBaseUrl} (explicit)");
@@ -619,11 +627,16 @@ public partial class Program
// In production with HTTPS, the cookie will still be secure
options.Cookie.SecurePolicy = CookieSecurePolicy.SameAsRequest;
options.ExpireTimeSpan = TimeSpan.FromDays(7);
options.SlidingExpiration = true;
options.SlidingExpiration = false;
// Add logging events
options.Events = new CookieAuthenticationEvents
{
OnValidatePrincipal = async context =>
{
if (!await ValidateAccountSessionAsync(context.Principal!, context.HttpContext))
context.RejectPrincipal();
},
OnRedirectToLogin = context =>
{
var logger = context.HttpContext.RequestServices.GetRequiredService<ILogger<Program>>();
@@ -652,17 +665,16 @@ public partial class Program
}
context.Response.Redirect(context.RedirectUri);
return Task.CompletedTask;
},
OnValidatePrincipal = context =>
{
var logger = context.HttpContext.RequestServices.GetRequiredService<ILogger<Program>>();
logger.LogDebug("Validating principal for {Path}", context.HttpContext.Request.Path);
return Task.CompletedTask;
}
};
});
}
private static Task<bool> ValidateAccountSessionAsync(ClaimsPrincipal principal, HttpContext http) =>
Heimdall.Application.Auth.Services.AccountSessionPolicy.IsValidAsync(principal,
http.RequestServices.GetRequiredService<Microsoft.AspNetCore.Identity.UserManager<Heimdall.Domain.Entities.AppUser>>(),
http.RequestServices.GetRequiredService<Heimdall.Application.Services.IAuthDataService>(), http.RequestAborted);
private static void ConfigureJwtBearerAuthentication(AuthenticationBuilder authBuilder, string jwtKey, string jwtIssuer, string jwtAudience)
{
authBuilder.AddJwtBearer("JwtBearer", options =>
@@ -670,6 +682,11 @@ public partial class Program
options.TokenValidationParameters = GetJwtValidationParameters(jwtKey, jwtIssuer, jwtAudience);
options.Events = new JwtBearerEvents
{
OnTokenValidated = async context =>
{
if (!await ValidateAccountSessionAsync(context.Principal!, context.HttpContext))
context.Fail("Session revoked");
},
OnMessageReceived = context =>
{
var accessToken = context.Request.Query["access_token"];
@@ -866,6 +883,8 @@ public partial class Program
var handler = new JwtSecurityTokenHandler();
var principal = handler.ValidateToken(request.AccessToken,
GetJwtValidationParameters(jwtKey, jwtIssuer, jwtAudience), out _);
if (!await ValidateAccountSessionAsync(principal, httpContext))
return Results.Unauthorized();
var userId = principal.FindFirst(ClaimTypes.NameIdentifier)?.Value;
var email = principal.FindFirst(ClaimTypes.Email)?.Value;
var displayName = principal.FindFirst(ClaimTypes.Name)?.Value;
@@ -878,13 +897,23 @@ public partial class Program
new(ClaimTypes.Email, email),
new(ClaimTypes.Name, displayName ?? email),
};
claims.Add(new Claim(Heimdall.Application.Auth.Services.AccountSessionPolicy.StampClaim,
principal.FindFirstValue(Heimdall.Application.Auth.Services.AccountSessionPolicy.StampClaim)!));
claims.Add(new Claim(Heimdall.Application.Auth.Services.AccountSessionPolicy.StartedClaim,
principal.FindFirstValue(Heimdall.Application.Auth.Services.AccountSessionPolicy.StartedClaim)!));
foreach (var role in principal.FindAll(ClaimTypes.Role))
claims.Add(new Claim(ClaimTypes.Role, role.Value));
foreach (var permission in principal.FindAll("permission"))
claims.Add(new Claim("permission", permission.Value));
var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
await httpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(identity));
await httpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(identity),
new AuthenticationProperties
{
IsPersistent = false, AllowRefresh = false,
ExpiresUtc = DateTimeOffset.Parse(principal.FindFirstValue(Heimdall.Application.Auth.Services.AccountSessionPolicy.StartedClaim)!,
System.Globalization.CultureInfo.InvariantCulture).AddDays(7)
});
return Results.Ok();
}
catch (SecurityTokenExpiredException) { return Results.Unauthorized(); }
@@ -23,7 +23,12 @@ public sealed class LiveSubscriptions
foreach (var (key, principal) in _entries.Where(e => e.Key.Hub == hub && e.Key.Channel == channel))
{
var requester = await access.ResolveAsync(principal, ct);
if (requester is not null && await authorize(requester)) result.Add(key.Connection);
if (requester is null || !await authorize(requester))
{
_entries.TryRemove(key, out _);
continue;
}
result.Add(key.Connection);
}
return result;
}
+6 -2
View File
@@ -1,6 +1,8 @@
using System.Security.Claims;
using Heimdall.Application.Auth.Services;
using Heimdall.Application.Common;
using Heimdall.Application.Services;
using Heimdall.Domain.Entities;
using Heimdall.Infrastructure.Security;
using Microsoft.EntityFrameworkCore;
@@ -10,7 +12,9 @@ public enum RequesterKind { Human, Agent }
public sealed record Requester(RequesterKind Kind, Guid Id, Guid? SiteId = null);
/// <summary>Resolves identities from persisted state; never treats an API key ID as a user ID.</summary>
public sealed class ResourceAccess(IApplicationDbContext db, ICameraAccessService cameras)
public sealed class ResourceAccess(
IApplicationDbContext db,
ICameraAccessService cameras)
{
public async Task<Requester?> ResolveAsync(ClaimsPrincipal? principal, CancellationToken ct = default)
{
@@ -33,7 +37,7 @@ public sealed class ResourceAccess(IApplicationDbContext db, ICameraAccessServic
(claimedSite is not null && claimedSite != key.SiteId.Value.ToString())) return null;
return new(RequesterKind.Agent, bound[0], key.SiteId);
}
if (!await db.Users.AnyAsync(u => u.Id == id, ct)) return null;
if (!await AccountSessionPolicy.IsValidLiveAsync(principal, db, ct)) return null;
return new(RequesterKind.Human, id);
}
+4 -1
View File
@@ -9,6 +9,8 @@ public class AuthState
/// <summary>Nom du cookie d'authentification ASP.NET Core (schéma Cookies).</summary>
public const string AuthCookieName = ".Heimdall.Auth";
public SemaphoreSlim RefreshLock { get; } = new(1, 1);
public string? AccessToken { get; set; }
public string? RefreshToken { get; set; }
public UserInfo? User { get; set; }
@@ -83,7 +85,8 @@ public record AuthResponse(
[property: JsonPropertyName("refreshToken")] string RefreshToken,
[property: JsonPropertyName("expiresAt")] DateTime ExpiresAt,
[property: JsonPropertyName("requires2fa")] bool Requires2fa,
[property: JsonPropertyName("user")] UserInfo? User);
[property: JsonPropertyName("user")] UserInfo? User,
[property: JsonPropertyName("challengeId")] string? ChallengeId = null);
public record UserInfo(
[property: JsonPropertyName("id")] Guid Id,
+23 -8
View File
@@ -6,10 +6,11 @@ using Heimdall.Application.DTOs;
namespace Heimdall.Web.Services;
public class HeimdallApiClient
public class HeimdallApiClient : IDisposable
{
private readonly IHttpClientFactory _httpFactory;
private readonly AuthState _authState;
private readonly HttpClient? _sessionClient;
private const string InvalidServerResponse = "Réponse du serveur invalide.";
private static readonly JsonSerializerOptions Json = new()
@@ -18,18 +19,32 @@ public class HeimdallApiClient
PropertyNamingPolicy = JsonNamingPolicy.CamelCase
};
public HeimdallApiClient(IHttpClientFactory httpFactory, AuthState authState)
public HeimdallApiClient(IHttpClientFactory httpFactory, AuthState authState, TokenRefreshHandler? sessionHandler = null)
{
_httpFactory = httpFactory;
_authState = authState;
if (sessionHandler is not null)
{
using var configured = httpFactory.CreateClient("HeimdallApi");
_sessionClient = new HttpClient(sessionHandler, disposeHandler: false)
{
BaseAddress = configured.BaseAddress,
Timeout = configured.Timeout
};
}
}
public void Dispose()
{
_sessionClient?.Dispose();
GC.SuppressFinalize(this);
}
private HttpClient CreateClient()
{
var client = _httpFactory.CreateClient("HeimdallApi");
if (_authState.AccessToken is not null)
client.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Bearer", _authState.AccessToken);
var client = _sessionClient ?? _httpFactory.CreateClient("HeimdallApi");
client.DefaultRequestHeaders.Authorization = string.IsNullOrEmpty(_authState.AccessToken)
? null : new AuthenticationHeaderValue("Bearer", _authState.AccessToken);
return client;
}
@@ -220,10 +235,10 @@ public class HeimdallApiClient
return result;
}
public async Task<AuthResponse?> Verify2faAsync(string email, string code)
public async Task<AuthResponse?> Verify2faAsync(string challengeId, string code)
{
var client = CreateClient();
var response = await client.PostAsJsonAsync("api/auth/2fa/verify", new { email, code });
var response = await client.PostAsJsonAsync("api/auth/2fa/verify", new { challengeId, code });
if (!response.IsSuccessStatusCode) return null;
var result = await response.Content.ReadFromJsonAsync<AuthResponse>(Json);
if (result is not null) _lastAuthResponse = result;
@@ -1,28 +1,55 @@
using System.Security.Claims;
using System.IdentityModel.Tokens.Jwt;
using Heimdall.Application.Auth.Services;
using Heimdall.Application.Services;
using Heimdall.Domain.Entities;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Components.Server;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.AspNetCore.Components.Server.ProtectedBrowserStorage;
using Heimdall.Infrastructure.Security;
namespace Heimdall.Web.Services;
public class HeimdallAuthStateProvider : AuthenticationStateProvider
public class HeimdallAuthStateProvider : RevalidatingServerAuthenticationStateProvider
{
private readonly IServiceScopeFactory? _scopeFactory;
private readonly ProtectedSessionStorage _storage;
private readonly AuthState _authState;
private readonly IHttpContextAccessor _httpContextAccessor;
private bool _restoredFromStorage;
private const string StorageKey = "heimdall_auth";
public HeimdallAuthStateProvider(ProtectedSessionStorage storage, AuthState authState, IHttpContextAccessor httpContextAccessor)
: this(storage, authState, httpContextAccessor, null) { }
public HeimdallAuthStateProvider(
ProtectedSessionStorage storage,
AuthState authState,
IHttpContextAccessor httpContextAccessor)
IHttpContextAccessor httpContextAccessor, IServiceScopeFactory? scopeFactory)
: base(NullLoggerFactory.Instance)
{
_scopeFactory = scopeFactory;
_storage = storage;
_authState = authState;
_httpContextAccessor = httpContextAccessor;
}
protected override TimeSpan RevalidationInterval => TimeSpan.FromMinutes(1);
protected override async Task<bool> ValidateAuthenticationStateAsync(AuthenticationState state, CancellationToken cancellationToken)
{
if (_scopeFactory is null) return false;
await using var scope = _scopeFactory.CreateAsyncScope();
var valid = await AccountSessionPolicy.IsValidAsync(state.User,
scope.ServiceProvider.GetRequiredService<UserManager<AppUser>>(),
scope.ServiceProvider.GetRequiredService<IAuthDataService>(), cancellationToken);
if (!valid) await NotifyLogoutAsync();
return valid;
}
public override async Task<AuthenticationState> GetAuthenticationStateAsync()
{
// 1) Interactive circuit: the auth response is persisted in the browser
@@ -42,8 +69,16 @@ public class HeimdallAuthStateProvider : AuthenticationStateProvider
if (result.Success && result.Value is not null)
{
var authResponse = result.Value;
var state = CreateAuthenticationState(authResponse);
if (_scopeFactory is not null && !await ValidateAuthenticationStateAsync(state, CancellationToken.None))
return new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity()));
_authState.Login(authResponse);
return CreateAuthenticationState(authResponse);
if (!_restoredFromStorage)
{
_restoredFromStorage = true;
SetAuthenticationState(Task.FromResult(state));
}
return state;
}
}
catch
@@ -85,11 +120,13 @@ public class HeimdallAuthStateProvider : AuthenticationStateProvider
public virtual async Task NotifyLogoutAsync()
{
_authState.Logout();
if (_httpContextAccessor.HttpContext is null)
{
await _storage.DeleteAsync(StorageKey);
try { await _storage.DeleteAsync(StorageKey); }
catch (Microsoft.JSInterop.JSDisconnectedException) { }
catch (InvalidOperationException) { } // Revalidation may run while the circuit is disconnected.
}
_authState.Logout();
NotifyAuthenticationStateChanged(
Task.FromResult(new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity()))));
}
@@ -107,6 +144,13 @@ public class HeimdallAuthStateProvider : AuthenticationStateProvider
new(ClaimTypes.AuthenticationMethod, "Bearer")
};
if (new JwtSecurityTokenHandler().CanReadToken(response.AccessToken))
{
var token = new JwtSecurityTokenHandler().ReadJwtToken(response.AccessToken);
foreach (var claim in token.Claims.Where(c => c.Type == AccountSessionPolicy.StampClaim || c.Type == AccountSessionPolicy.StartedClaim))
claims.Add(claim);
}
foreach (var role in response.User.Roles ?? [])
claims.Add(new Claim(ClaimTypes.Role, role));
@@ -13,8 +13,8 @@ namespace Heimdall.Web.Services;
public class TokenRefreshHandler : DelegatingHandler
{
private readonly AuthState _authState;
private readonly IHttpClientFactory? _clientFactory;
private readonly HeimdallAuthStateProvider _authStateProvider;
private readonly IHttpContextAccessor _httpContextAccessor;
private readonly IConfiguration _configuration;
private static readonly JsonSerializerOptions Json = new()
{
@@ -22,25 +22,23 @@ public class TokenRefreshHandler : DelegatingHandler
PropertyNamingPolicy = JsonNamingPolicy.CamelCase
};
/// <summary>Prevents concurrent refresh storms when multiple requests fail at once.</summary>
private static readonly SemaphoreSlim _refreshLock = new(1, 1);
public TokenRefreshHandler(
AuthState authState,
HeimdallAuthStateProvider authStateProvider,
IHttpContextAccessor httpContextAccessor,
IConfiguration configuration)
IConfiguration configuration, IHttpClientFactory? clientFactory = null)
{
_clientFactory = clientFactory;
_authState = authState;
_authStateProvider = authStateProvider;
_httpContextAccessor = httpContextAccessor;
_configuration = configuration;
}
protected override async Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request, CancellationToken cancellationToken)
{
// Clone the request so we can retry it
var failedToken = request.Headers.Authorization?.Parameter;
using var retryRequest = await CloneHttpRequestMessageAsync(request);
var response = await base.SendAsync(request, cancellationToken);
// Only intercept 401 responses for the Heimdall API
@@ -51,7 +49,7 @@ public class TokenRefreshHandler : DelegatingHandler
}
// Try to refresh the token
var refreshed = await TryRefreshTokenAsync(cancellationToken);
var refreshed = await TryRefreshTokenAsync(failedToken, request.RequestUri!, cancellationToken);
if (!refreshed)
{
// Refresh failed — logout user
@@ -60,31 +58,35 @@ public class TokenRefreshHandler : DelegatingHandler
}
// Retry the original request with the new access token
var retryRequest = await CloneHttpRequestMessageAsync(request);
retryRequest.Headers.Authorization =
new AuthenticationHeaderValue("Bearer", _authState.AccessToken);
response.Dispose();
return await base.SendAsync(retryRequest, cancellationToken);
var retried = await base.SendAsync(retryRequest, cancellationToken);
if (retried.StatusCode == System.Net.HttpStatusCode.Unauthorized)
await _authStateProvider.NotifyLogoutAsync();
return retried;
}
private async Task<bool> TryRefreshTokenAsync(CancellationToken cancellationToken)
private async Task<bool> TryRefreshTokenAsync(string? failedToken, Uri apiUri, CancellationToken cancellationToken)
{
if (string.IsNullOrEmpty(_authState.RefreshToken))
return false;
await _refreshLock.WaitAsync(cancellationToken);
await _authState.RefreshLock.WaitAsync(cancellationToken);
try
{
// Double-check: another thread might have refreshed already
if (!string.IsNullOrEmpty(_authState.AccessToken))
if (!string.IsNullOrEmpty(_authState.AccessToken) && _authState.AccessToken != failedToken)
return true;
// Create a raw HttpClient (NOT the "HeimdallApi" named client which
// includes this handler — would cause an infinite loop).
var baseUrl = ApiBaseUrlResolver.Resolve(_httpContextAccessor, _configuration);
using var rawClient = new HttpClient { BaseAddress = new Uri(baseUrl) };
var response = await rawClient.PostAsJsonAsync(
var baseUrl = ApiBaseUrlResolver.ResolveConfigured(_configuration)
?? apiUri.GetLeftPart(UriPartial.Authority) + "/";
using var rawClient = _clientFactory?.CreateClient("HeimdallRefresh") ?? new HttpClient();
rawClient.BaseAddress = new Uri(baseUrl);
using var response = await rawClient.PostAsJsonAsync(
"api/auth/refresh",
new { refreshToken = _authState.RefreshToken },
cancellationToken);
@@ -102,13 +104,17 @@ public class TokenRefreshHandler : DelegatingHandler
await _authStateProvider.NotifyLoginAsync(result);
return true;
}
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
{
throw;
}
catch
{
return false;
}
finally
{
_refreshLock.Release();
_authState.RefreshLock.Release();
}
}
@@ -119,8 +125,8 @@ public class TokenRefreshHandler : DelegatingHandler
{
var contentBytes = await request.Content.ReadAsByteArrayAsync();
clone.Content = new ByteArrayContent(contentBytes);
if (request.Content.Headers.ContentType is not null)
clone.Content.Headers.ContentType = request.Content.Headers.ContentType;
foreach (var (key, values) in request.Content.Headers)
clone.Content.Headers.TryAddWithoutValidation(key, values);
}
foreach (var (key, value) in request.Headers)