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; /// A sign-in attempt from the login page (mockup 001). /// The company chosen; instance accounts may leave it empty. /// The user name. /// The password. /// "Remember me on this device". /// The client address. /// The browser. public sealed record SignInRequest(string? CompanyCode, string UserName, string Password, bool Persistent, string? IpAddress, string? UserAgent); /// The outcome of a sign-in step. /// Whether the step succeeded. /// The error code otherwise (). /// The new cookie value to set. /// The state reached: the page to show next. public sealed record SignInResult(bool Succeeded, string? Error, string? Cookie, SessionState? State) { /// A failure. /// The error code. /// The outcome. public static SignInResult Fail(string error) => new(false, error, null, null); } /// The data of a TOTP setup, shown once. /// The secret in base32, for manual entry. /// The otpauth:// address. public sealed record TotpSetup(string Secret, string ProvisioningUri); /// /// 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 sys_security_audit; the error never says whether the user exists. /// public sealed class SignInService( SystemUserService systemUsers, UserService companyUsers, ICompanyRegistry companies, AccountSecurity security, SessionStore sessions, ILicenseGate licenses, NotificationDispatcher notifications, ISecurityAuditLog audit, ILogger logger) { /// Checks company, user and password and opens a session in the first state. /// The attempt. /// Cancellation. /// The outcome and the cookie. public async Task 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); } /// Checks the TOTP code (or a recovery code) of a session waiting for it. /// The cookie value. /// The code. /// Cancellation. /// The outcome and the new cookie. public async Task 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); } /// Starts the TOTP setup of a session waiting for it, or of a complete session (profile). /// The cookie value. /// Cancellation. /// The secret to show, or when the session is not valid. public async Task 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)); } /// Completes the TOTP setup with the first code from the app. /// The cookie value. /// The code. /// Cancellation. /// The outcome, the new cookie and the recovery codes to show once. public async Task<(SignInResult Result, IReadOnlyList? 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); } /// Changes the password: the forced change of mockup 003, or a change from the profile. /// The cookie value. /// The current (or temporary) password. /// The new password. /// Cancellation. /// The outcome, with every policy error code joined in . public async Task 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); } /// Signs out: the session is revoked. /// The cookie value. /// Cancellation. /// A task. 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); } } /// Resolves the identity of a cookie for the authentication handler. /// The cookie value. /// Cancellation. /// The identity, or when the session is not valid or the account cannot sign in anymore. public async Task 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 CompleteAsync( IAccount account, SessionOwner owner, string? companyCode, SignInRequest request, Func 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 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 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 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 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); } } /// A hash of a random password, compared when the user does not exist so the timing stays the same. private static class DummyHash { public static readonly string Value = PasswordHasher.Hash(SecureTokenGenerator.Create()); } }