Files
Khaemhat/src/Khaemhat.Application/Security/SignInService.cs
T
Alby96andClaude Opus 5.5 032c602b49
CI / Build and test (SQLite) (pull_request) Successful in 55s
CI / PostgreSQL 16 integration (pull_request) Skipped
CI / PostgreSQL 17 integration (pull_request) Skipped
CI / YAML check (pull_request) Successful in 5s
CI / Docker image (pull_request) Failing after 2m4s
feat: system and security - start-up, accounts, sign-in, licences, log, jobs, companies (M2)
The instance now starts on its own from KHAEMHAT_* variables: it migrates the system
and company databases, creates the super user and the first company, and only then
reports ready. Users sign in with password and TOTP through revocable database
sessions, and licences decide which modules and how many companies are available.

- Configuration: every wrong variable reported at once (exit code 2), _FILE variants
- Accounts, password policy and lockout, TOTP with recovery codes, session states
  with token rotation, security audit with a hash chain
- Sign-in pages (mockups 001-003), authorization attributes, security headers and a
  CSP without inline scripts, login rate limit
- Signed licences, activation codes, test mode, licence tool
- DataProtection keys in the system database, encrypted with the instance key
- Memory or Redis cache (in-house RESP client) that falls back to memory
- Database log by section with trace id; cron scheduler with locks and system jobs;
  record history (audit_log)
- Company creation, states, company context and X-Company, 503 in maintenance
- In-memory SQLite databases stay alive for the process (tests, demo)
- Tests for all of the above, ADR 0019, wiki, SECURITY, CHANGELOG, STATUS, DATA-MODEL

Refs #15 #16 #17 #18 #19 #20 #21 #22 #23 #24

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 15:29:24 +01:00

417 lines
21 KiB
C#

using Khaemhat.Application.Audit;
using Khaemhat.Application.Licensing;
using Khaemhat.Application.Notifications;
using Khaemhat.Core.Instance;
using Khaemhat.Core.Security;
using Khaemhat.Data;
using Khaemhat.Data.Companies;
using Khaemhat.Infrastructure.Security;
using Microsoft.Extensions.Logging;
namespace Khaemhat.Application.Security;
/// <summary>A sign-in attempt from the login page (mockup 001).</summary>
/// <param name="CompanyCode">The company chosen; instance accounts may leave it empty.</param>
/// <param name="UserName">The user name.</param>
/// <param name="Password">The password.</param>
/// <param name="Persistent">"Remember me on this device".</param>
/// <param name="IpAddress">The client address.</param>
/// <param name="UserAgent">The browser.</param>
public sealed record SignInRequest(string? CompanyCode, string UserName, string Password, bool Persistent, string? IpAddress, string? UserAgent);
/// <summary>The outcome of a sign-in step.</summary>
/// <param name="Succeeded">Whether the step succeeded.</param>
/// <param name="Error">The error code otherwise (<see cref="SecurityErrors"/>).</param>
/// <param name="Cookie">The new cookie value to set.</param>
/// <param name="State">The state reached: the page to show next.</param>
public sealed record SignInResult(bool Succeeded, string? Error, string? Cookie, SessionState? State)
{
/// <summary>A failure.</summary>
/// <param name="error">The error code.</param>
/// <returns>The outcome.</returns>
public static SignInResult Fail(string error) => new(false, error, null, null);
}
/// <summary>The data of a TOTP setup, shown once.</summary>
/// <param name="Secret">The secret in base32, for manual entry.</param>
/// <param name="ProvisioningUri">The <c>otpauth://</c> address.</param>
public sealed record TotpSetup(string Secret, string ProvisioningUri);
/// <summary>
/// The sign-in flow (SPEC §7.3; mockups 001-003): password with lockout, then the two-step verification (mandatory for
/// instance accounts), then the forced password change, each step on a session in a pending state whose token is
/// renewed at every step. Instance accounts are found in the system database first; otherwise the company user.
/// Every outcome is recorded in <c>sys_security_audit</c>; the error never says whether the user exists.
/// </summary>
public sealed class SignInService(
SystemUserService systemUsers,
UserService companyUsers,
ICompanyRegistry companies,
AccountSecurity security,
SessionStore sessions,
ILicenseGate licenses,
NotificationDispatcher notifications,
ISecurityAuditLog audit,
ILogger<SignInService> logger)
{
/// <summary>Checks company, user and password and opens a session in the first state.</summary>
/// <param name="request">The attempt.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The outcome and the cookie.</returns>
public async Task<SignInResult> SignInAsync(SignInRequest request, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(request);
var companyCode = string.IsNullOrWhiteSpace(request.CompanyCode) ? null : request.CompanyCode.Trim().ToUpperInvariant();
if (companyCode is not null && !CompanyCodes.IsValid(companyCode))
{
return SignInResult.Fail(SecurityErrors.InvalidCredentials);
}
var company = companyCode is null ? null : await companies.FindAsync(companyCode, cancellationToken).ConfigureAwait(false);
if (companyCode is not null && company is null)
{
await AuditAsync("login.failed", request.UserName, companyCode, request, new { reason = "company_unknown" }, cancellationToken).ConfigureAwait(false);
return SignInResult.Fail(SecurityErrors.InvalidCredentials);
}
var instanceAccount = await systemUsers.FindByNameAsync(request.UserName, cancellationToken).ConfigureAwait(false);
if (instanceAccount is not null)
{
return await CompleteAsync(instanceAccount, new SessionOwner(null, instanceAccount.Id), company?.Code, request,
ct => systemUsers.SaveAsync(instanceAccount, ct), cancellationToken).ConfigureAwait(false);
}
if (company is null)
{
await AuditAsync("login.failed", request.UserName, null, request, new { reason = "company_missing" }, cancellationToken).ConfigureAwait(false);
return SignInResult.Fail(SecurityErrors.InvalidCredentials);
}
if (company.Status is CompanyStatus.Maintenance or CompanyStatus.Disabled)
{
return SignInResult.Fail(SecurityErrors.CompanyUnavailable);
}
var user = await companyUsers.FindByNameAsync(company.Code, request.UserName, cancellationToken).ConfigureAwait(false);
if (user is null || user.Kind == UserKind.Technical)
{
// Hash anyway, so that an unknown user takes as long as a wrong password.
_ = PasswordHasher.Verify(DummyHash.Value, request.Password);
await AuditAsync("login.failed", request.UserName, company.Code, request, new { reason = "user_unknown" }, cancellationToken).ConfigureAwait(false);
return SignInResult.Fail(SecurityErrors.InvalidCredentials);
}
return await CompleteAsync(user, new SessionOwner(company.Code, user.Id), company.Code, request,
ct => companyUsers.SaveAsync(company.Code, user, ct), cancellationToken).ConfigureAwait(false);
}
/// <summary>Checks the TOTP code (or a recovery code) of a session waiting for it.</summary>
/// <param name="cookie">The cookie value.</param>
/// <param name="code">The code.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The outcome and the new cookie.</returns>
public async Task<SignInResult> VerifyTotpAsync(string cookie, string code, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(code);
var pending = await LoadPendingAsync(cookie, SessionState.PendingTotp, cancellationToken).ConfigureAwait(false);
if (pending is null)
{
return SignInResult.Fail(SecurityErrors.InvalidCredentials);
}
var (account, owner, save, company) = pending.Value;
var valid = code.Contains('-', StringComparison.Ordinal) ? AccountSecurity.UseRecoveryCode(account, code) : security.VerifyTotp(account, code);
if (!valid)
{
account.FailedLoginCount++;
var locked = account.FailedLoginCount >= security.Options.MaxFailedAttempts;
if (locked)
{
account.LockedUntil = DateTime.UtcNow + security.Options.LockoutDuration;
account.FailedLoginCount = 0;
await sessions.RevokeAsync(cookie, "totp_locked", cancellationToken).ConfigureAwait(false);
}
await save(cancellationToken).ConfigureAwait(false);
await AuditAsync("login.totp-failed", account.UserName, company, null, null, cancellationToken).ConfigureAwait(false);
return SignInResult.Fail(locked ? SecurityErrors.AccountLocked : SecurityErrors.TotpInvalid);
}
account.FailedLoginCount = 0;
await save(cancellationToken).ConfigureAwait(false);
var next = account.MustChangePassword ? SessionState.PendingPasswordChange : SessionState.Active;
return await AdvanceAsync(cookie, next, account, owner, company, cancellationToken).ConfigureAwait(false);
}
/// <summary>Starts the TOTP setup of a session waiting for it, or of a complete session (profile).</summary>
/// <param name="cookie">The cookie value.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The secret to show, or <see langword="null"/> when the session is not valid.</returns>
public async Task<TotpSetup?> BeginTotpSetupAsync(string cookie, CancellationToken cancellationToken = default)
{
var pending = await LoadPendingAsync(cookie, null, cancellationToken).ConfigureAwait(false);
if (pending is null || pending.Value.Account.TotpEnabled)
{
return null;
}
var (account, _, save, company) = pending.Value;
var secret = security.PendingTotpSecret(account);
if (secret is null)
{
secret = security.BeginTotpSetup(account);
await save(cancellationToken).ConfigureAwait(false);
}
return new TotpSetup(secret, TotpGenerator.ProvisioningUri(secret, company is null ? account.UserName : account.UserName + "@" + company));
}
/// <summary>Completes the TOTP setup with the first code from the app.</summary>
/// <param name="cookie">The cookie value.</param>
/// <param name="code">The code.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The outcome, the new cookie and the recovery codes to show once.</returns>
public async Task<(SignInResult Result, IReadOnlyList<string>? RecoveryCodes)> ConfirmTotpSetupAsync(string cookie, string code, CancellationToken cancellationToken = default)
{
var pending = await LoadPendingAsync(cookie, null, cancellationToken).ConfigureAwait(false);
if (pending is null)
{
return (SignInResult.Fail(SecurityErrors.InvalidCredentials), null);
}
var (account, owner, save, company) = pending.Value;
var codes = security.ConfirmTotpSetup(account, code);
if (codes is null)
{
return (SignInResult.Fail(SecurityErrors.TotpInvalid), null);
}
await save(cancellationToken).ConfigureAwait(false);
await AuditAsync("user.totp-enabled", account.UserName, company, null, null, cancellationToken).ConfigureAwait(false);
var session = await sessions.FindAsync(cookie, cancellationToken).ConfigureAwait(false);
if (session?.Session.State != SessionState.PendingTotpSetup)
{
return (new SignInResult(true, null, cookie, session?.Session.State), codes);
}
return (await AdvanceAsync(cookie, SessionState.Active, account, owner, company, cancellationToken).ConfigureAwait(false), codes);
}
/// <summary>Changes the password: the forced change of mockup 003, or a change from the profile.</summary>
/// <param name="cookie">The cookie value.</param>
/// <param name="currentPassword">The current (or temporary) password.</param>
/// <param name="newPassword">The new password.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The outcome, with every policy error code joined in <see cref="SignInResult.Error"/>.</returns>
public async Task<SignInResult> ChangePasswordAsync(string cookie, string currentPassword, string newPassword, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(currentPassword);
ArgumentNullException.ThrowIfNull(newPassword);
var pending = await LoadPendingAsync(cookie, null, cancellationToken).ConfigureAwait(false);
if (pending is null)
{
return SignInResult.Fail(SecurityErrors.InvalidCredentials);
}
var (account, owner, save, company) = pending.Value;
if (PasswordHasher.Verify(account.PasswordHash, currentPassword) == PasswordVerification.Failed)
{
return SignInResult.Fail(SecurityErrors.CurrentPasswordWrong);
}
var errors = security.ChangePassword(account, newPassword);
if (errors.Count > 0)
{
return SignInResult.Fail(string.Join(',', errors));
}
await save(cancellationToken).ConfigureAwait(false);
var current = await sessions.FindAsync(cookie, cancellationToken).ConfigureAwait(false);
await sessions.RevokeAllAsync(owner, "password_changed", current?.Session.Id, cancellationToken).ConfigureAwait(false);
await AuditAsync("user.password-changed", account.UserName, company, null, null, cancellationToken).ConfigureAwait(false);
if (current?.Session.State != SessionState.PendingPasswordChange)
{
return new SignInResult(true, null, cookie, current?.Session.State);
}
var next = NeedsTotpSetup(account, owner) ? SessionState.PendingTotpSetup : SessionState.Active;
return await AdvanceAsync(cookie, next, account, owner, company, cancellationToken).ConfigureAwait(false);
}
/// <summary>Signs out: the session is revoked.</summary>
/// <param name="cookie">The cookie value.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public async Task SignOutAsync(string? cookie, CancellationToken cancellationToken = default)
{
var identity = await ResolveAsync(cookie, cancellationToken).ConfigureAwait(false);
var owner = await sessions.RevokeAsync(cookie, "sign_out", cancellationToken).ConfigureAwait(false);
if (owner is not null)
{
var userName = identity?.UserName ?? owner.UserId.ToString(System.Globalization.CultureInfo.InvariantCulture);
await AuditAsync("logout", userName, identity?.CompanyCode ?? owner.CompanyDatabase, null, null, cancellationToken).ConfigureAwait(false);
}
}
/// <summary>Resolves the identity of a cookie for the authentication handler.</summary>
/// <param name="cookie">The cookie value.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The identity, or <see langword="null"/> when the session is not valid or the account cannot sign in anymore.</returns>
public async Task<SessionIdentity?> ResolveAsync(string? cookie, CancellationToken cancellationToken = default)
{
if (await sessions.FindAsync(cookie, cancellationToken).ConfigureAwait(false) is not var (session, owner))
{
return null;
}
if (owner.IsInstanceAccount)
{
var account = await systemUsers.GetAsync(owner.UserId, cancellationToken).ConfigureAwait(false);
if (account is not { IsActive: true })
{
return null;
}
var linked = account.LinkedCompanyCode is not null && account.LinkedCompanyCode == session.CompanyCode ? account.LinkedUserId : null;
return new SessionIdentity(session.Id, owner, session.State, account.UserName, account.DisplayName, account.Level, session.CompanyCode, linked, session.ExpiresAt, session.Persistent);
}
var company = await companies.FindAsync(owner.CompanyDatabase!, cancellationToken).ConfigureAwait(false);
if (company is null || company.Status is CompanyStatus.Maintenance or CompanyStatus.Disabled)
{
return null;
}
var user = await companyUsers.GetAsync(owner.CompanyDatabase!, owner.UserId, cancellationToken).ConfigureAwait(false);
return user is { IsActive: true }
? new SessionIdentity(session.Id, owner, session.State, user.UserName, user.DisplayName, UserLevel.Standard, company.Code, null, session.ExpiresAt, session.Persistent)
: null;
}
private async Task<SignInResult> CompleteAsync(
IAccount account, SessionOwner owner, string? companyCode, SignInRequest request, Func<CancellationToken, Task> save, CancellationToken cancellationToken)
{
var check = security.CheckPassword(account, request.Password);
await save(cancellationToken).ConfigureAwait(false);
if (!check.Succeeded)
{
await AuditAsync("login.failed", account.UserName, companyCode, request, new { reason = check.Error }, cancellationToken).ConfigureAwait(false);
return SignInResult.Fail(check.Error!);
}
await licenses.RefreshAsync(cancellationToken).ConfigureAwait(false);
var isSuperUser = account is SystemUser { Level: UserLevel.SuperUser };
if (!isSuperUser)
{
var active = await sessions.ActiveOwnersAsync(cancellationToken).ConfigureAwait(false);
if (!active.Contains(owner) && active.Count >= licenses.Current.MaxConcurrentUsers)
{
await AuditAsync("login.refused", account.UserName, companyCode, request, new { reason = SecurityErrors.ConcurrentUsersExceeded }, cancellationToken).ConfigureAwait(false);
return SignInResult.Fail(SecurityErrors.ConcurrentUsersExceeded);
}
}
var state = account.TotpEnabled ? SessionState.PendingTotp
: check.MustChangePassword ? SessionState.PendingPasswordChange
: NeedsTotpSetup(account, owner) ? SessionState.PendingTotpSetup
: SessionState.Active;
var cookie = await sessions.CreateAsync(owner, state, companyCode, request.IpAddress, request.UserAgent, request.Persistent, cancellationToken).ConfigureAwait(false);
await AuditAsync("login.password-accepted", account.UserName, companyCode, request, new { next = state.ToString() }, cancellationToken).ConfigureAwait(false);
if (state == SessionState.Active)
{
await OnActiveAsync(cookie, account, owner, companyCode, save, cancellationToken).ConfigureAwait(false);
}
return new SignInResult(true, null, cookie, state);
}
private async Task<SignInResult> AdvanceAsync(string cookie, SessionState next, IAccount account, SessionOwner owner, string? company, CancellationToken cancellationToken)
{
var newCookie = await sessions.AdvanceAsync(cookie, next, cancellationToken).ConfigureAwait(false);
if (newCookie is null)
{
return SignInResult.Fail(SecurityErrors.InvalidCredentials);
}
if (next == SessionState.Active)
{
await OnActiveAsync(newCookie, account, owner, company, SaveFor(account, owner), cancellationToken).ConfigureAwait(false);
}
return new SignInResult(true, null, newCookie, next);
}
private async Task OnActiveAsync(string cookie, IAccount account, SessionOwner owner, string? company, Func<CancellationToken, Task> save, CancellationToken cancellationToken)
{
security.RecordSignIn(account);
await save(cancellationToken).ConfigureAwait(false);
await AuditAsync("login.succeeded", account.UserName, company, null, null, cancellationToken).ConfigureAwait(false);
if (await sessions.FindAsync(cookie, cancellationToken).ConfigureAwait(false) is var (session, _)
&& !await sessions.IsKnownDeviceAsync(owner, session.UserAgent, session.Id, cancellationToken).ConfigureAwait(false))
{
var message = new NotificationMessage(
"security",
NotificationSeverity.Warning,
"Nuovo accesso da un dispositivo non riconosciuto",
$"Accesso da {session.IpAddress ?? "indirizzo sconosciuto"} con {session.UserAgent ?? "browser sconosciuto"}. Se non sei stato tu, cambia la password e chiudi le sessioni dal profilo.",
"/profilo/sessioni");
if (owner.IsInstanceAccount)
{
await notifications.NotifyInstanceAsync(message, owner.UserId, cancellationToken).ConfigureAwait(false);
}
else
{
await notifications.NotifyCompanyAsync(owner.CompanyDatabase!, message, owner.UserId, cancellationToken).ConfigureAwait(false);
}
}
}
private bool NeedsTotpSetup(IAccount account, SessionOwner owner) =>
!account.TotpEnabled && (owner.IsInstanceAccount || account is CompanyUser { TotpRequired: true } || security.Options.TotpRequiredForUsers);
private Func<CancellationToken, Task> SaveFor(IAccount account, SessionOwner owner) => account switch
{
SystemUser system => ct => systemUsers.SaveAsync(system, ct),
CompanyUser user => ct => companyUsers.SaveAsync(owner.CompanyDatabase!, user, ct),
_ => throw new InvalidOperationException("Unknown account type."),
};
private async Task<(IAccount Account, SessionOwner Owner, Func<CancellationToken, Task> Save, string? Company)?> LoadPendingAsync(
string? cookie, SessionState? expected, CancellationToken cancellationToken)
{
if (await sessions.FindAsync(cookie, cancellationToken).ConfigureAwait(false) is not var (session, owner)
|| (expected is not null && session.State != expected))
{
return null;
}
IAccount? account = owner.IsInstanceAccount
? await systemUsers.GetAsync(owner.UserId, cancellationToken).ConfigureAwait(false)
: await companyUsers.GetAsync(owner.CompanyDatabase!, owner.UserId, cancellationToken).ConfigureAwait(false);
if (account is not { IsActive: true })
{
return null;
}
return (account, owner, SaveFor(account, owner), session.CompanyCode);
}
private async Task AuditAsync(string action, string? userName, string? company, SignInRequest? request, object? details, CancellationToken cancellationToken)
{
try
{
await audit.WriteAsync(new SecurityEvent(action, userName, company, null, details, request?.IpAddress), cancellationToken).ConfigureAwait(false);
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
logger.LogError(ex, "Security audit {Action} not written.", action);
}
}
/// <summary>A hash of a random password, compared when the user does not exist so the timing stays the same.</summary>
private static class DummyHash
{
public static readonly string Value = PasswordHasher.Hash(SecureTokenGenerator.Create());
}
}