feat: system and security - start-up, accounts, sign-in, licences, log, jobs, companies (M2)
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

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>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-11 15:29:24 +01:00
1 parent 4582837b70
commit 032c602b49
107 files changed
+12202 -116

No files matched your search

@@ -0,0 +1,351 @@
using System.Text.Json;
using Khaemhat.Core.Security;
using Khaemhat.Infrastructure.Security;
namespace Khaemhat.Application.Security;
/// <summary>The outcome of a password check at sign-in.</summary>
/// <param name="Succeeded">Whether the password was right and the account may go on.</param>
/// <param name="Error">The error code when it did not succeed (<see cref="SecurityErrors"/>).</param>
/// <param name="MustChangePassword">The password must be changed before entering.</param>
public sealed record PasswordCheck(bool Succeeded, string? Error, bool MustChangePassword)
{
/// <summary>A failure.</summary>
/// <param name="error">The error code.</param>
/// <returns>The outcome.</returns>
public static PasswordCheck Fail(string error) => new(false, error, false);
}
/// <summary>
/// The credential rules shared by instance accounts and company users (SPEC §7.3): password check with lockout,
/// password change with policy and history, temporary passwords, recovery tokens, TOTP and recovery codes.
/// The methods change the account in memory; the caller saves it.
/// </summary>
public sealed class AccountSecurity
{
private const string SecretPurpose = "account:totp";
private readonly PasswordPolicy _policy;
private readonly ISecretProtector _protector;
private readonly TimeProvider _clock;
/// <summary>Creates the service.</summary>
/// <param name="policy">The password policy.</param>
/// <param name="protector">Encrypts TOTP secrets.</param>
/// <param name="clock">The clock.</param>
public AccountSecurity(PasswordPolicy policy, ISecretProtector protector, TimeProvider clock)
{
ArgumentNullException.ThrowIfNull(policy);
ArgumentNullException.ThrowIfNull(protector);
ArgumentNullException.ThrowIfNull(clock);
_policy = policy;
_protector = protector;
_clock = clock;
}
/// <summary>The policy settings.</summary>
public SecurityPolicyOptions Options => _policy.Options;
private DateTime Now => _clock.GetUtcNow().UtcDateTime;
/// <summary>Checks the password typed at sign-in, counting failures and locking the account after too many.</summary>
/// <param name="account">The account.</param>
/// <param name="password">The password typed.</param>
/// <returns>The outcome.</returns>
public PasswordCheck CheckPassword(IAccount account, string password)
{
ArgumentNullException.ThrowIfNull(account);
ArgumentNullException.ThrowIfNull(password);
var now = Now;
if (!account.IsActive)
{
return PasswordCheck.Fail(SecurityErrors.AccountDisabled);
}
if (account.LockedUntil is { } locked && locked > now)
{
return PasswordCheck.Fail(SecurityErrors.AccountLocked);
}
var verification = PasswordHasher.Verify(account.PasswordHash, password);
if (verification == PasswordVerification.Failed)
{
account.FailedLoginCount++;
if (account.FailedLoginCount >= Options.MaxFailedAttempts)
{
account.LockedUntil = now + Options.LockoutDuration;
account.FailedLoginCount = 0;
return PasswordCheck.Fail(SecurityErrors.AccountLocked);
}
return PasswordCheck.Fail(SecurityErrors.InvalidCredentials);
}
account.FailedLoginCount = 0;
account.LockedUntil = null;
if (account.TemporaryPasswordExpiresAt is { } expires && expires <= now)
{
return PasswordCheck.Fail(SecurityErrors.TemporaryPasswordExpired);
}
if (verification == PasswordVerification.SucceededRehashNeeded)
{
account.PasswordHash = PasswordHasher.Hash(password, Options.HashIterations);
}
var expired = Options.ExpiryDays is { } days && account.PasswordChangedAt is { } changed && changed.AddDays(days) <= now;
return new PasswordCheck(true, null, account.MustChangePassword || expired);
}
/// <summary>Records a completed sign-in.</summary>
/// <param name="account">The account.</param>
public void RecordSignIn(IAccount account)
{
ArgumentNullException.ThrowIfNull(account);
account.LastLoginAt = Now;
}
/// <summary>Sets a new password chosen by the user, after checking policy and history.</summary>
/// <param name="account">The account.</param>
/// <param name="newPassword">The new password.</param>
/// <returns>The error codes; empty when the password was set.</returns>
public IReadOnlyList<string> ChangePassword(IAccount account, string newPassword)
{
ArgumentNullException.ThrowIfNull(account);
ArgumentNullException.ThrowIfNull(newPassword);
var errors = new List<string>(_policy.Check(newPassword, account.UserName));
if (errors.Count == 0 && IsReused(account, newPassword))
{
errors.Add(SecurityErrors.PasswordReused);
}
if (errors.Count == 0)
{
Store(account, newPassword, temporary: false);
}
return errors;
}
/// <summary>
/// Sets a password without the history check: the first password of the super user, or a temporary password made by
/// an administrator. Both must be changed at the next sign-in.
/// </summary>
/// <param name="account">The account.</param>
/// <param name="password">The password.</param>
/// <param name="temporary">Whether it expires after <see cref="SecurityPolicyOptions.TemporaryPasswordLifetime"/>.</param>
/// <returns>The policy error codes; empty when the password was set.</returns>
public IReadOnlyList<string> SetInitialPassword(IAccount account, string password, bool temporary)
{
ArgumentNullException.ThrowIfNull(account);
ArgumentNullException.ThrowIfNull(password);
var errors = _policy.Check(password, account.UserName);
if (errors.Count == 0)
{
Store(account, password, temporary);
account.MustChangePassword = true;
}
return errors;
}
/// <summary>Creates a temporary password that satisfies the policy and sets it.</summary>
/// <param name="account">The account.</param>
/// <returns>The password to give to the user, once.</returns>
public string IssueTemporaryPassword(IAccount account)
{
ArgumentNullException.ThrowIfNull(account);
// Two readable groups plus a lower-case suffix and a symbol: four classes, 14 characters.
var password = SecureTokenGenerator.CreateReadableCode(2) + "-" + SecureTokenGenerator.CreateReadableCode(1).ToLowerInvariant();
Store(account, password, temporary: true);
account.MustChangePassword = true;
return password;
}
/// <summary>Creates a single-use recovery token, valid for <see cref="SecurityPolicyOptions.RecoveryTokenLifetime"/>.</summary>
/// <param name="account">The account.</param>
/// <returns>The token to send by e-mail; only its hash is stored.</returns>
public string IssueRecoveryToken(IAccount account)
{
ArgumentNullException.ThrowIfNull(account);
var token = SecureTokenGenerator.Create();
account.RecoveryTokenHash = SecureTokenGenerator.Hash(token);
account.RecoveryTokenExpiresAt = Now + Options.RecoveryTokenLifetime;
return token;
}
/// <summary>Uses a recovery token to set a new password. The token stops working whatever the outcome of the policy.</summary>
/// <param name="account">The account.</param>
/// <param name="token">The token from the e-mail.</param>
/// <param name="newPassword">The new password.</param>
/// <returns>The error codes; empty when the password was set.</returns>
public IReadOnlyList<string> RedeemRecoveryToken(IAccount account, string token, string newPassword)
{
ArgumentNullException.ThrowIfNull(account);
ArgumentNullException.ThrowIfNull(token);
var valid = account.RecoveryTokenExpiresAt is { } expires && expires > Now
&& SecureTokenGenerator.HashesEqual(account.RecoveryTokenHash, SecureTokenGenerator.Hash(token));
if (!valid)
{
return [SecurityErrors.RecoveryTokenInvalid];
}
var errors = ChangePassword(account, newPassword);
if (errors.Count == 0)
{
account.RecoveryTokenHash = null;
account.RecoveryTokenExpiresAt = null;
account.LockedUntil = null;
account.FailedLoginCount = 0;
}
return errors;
}
/// <summary>Starts the TOTP setup: a new secret, stored encrypted and not yet active.</summary>
/// <param name="account">The account.</param>
/// <returns>The secret in base32, to show once with <see cref="TotpGenerator.ProvisioningUri"/>.</returns>
public string BeginTotpSetup(IAccount account)
{
ArgumentNullException.ThrowIfNull(account);
var secret = TotpGenerator.CreateSecret();
account.TotpSecret = _protector.Protect(secret, SecretPurpose);
account.TotpEnabled = false;
account.TotpLastStep = null;
return secret;
}
/// <summary>The secret of a setup started and not yet confirmed, so that reloading the page shows the same one.</summary>
/// <param name="account">The account.</param>
/// <returns>The secret in base32, or <see langword="null"/> when no setup is pending.</returns>
public string? PendingTotpSecret(IAccount account)
{
ArgumentNullException.ThrowIfNull(account);
return account is { TotpEnabled: false, TotpSecret: { } secret } ? _protector.Unprotect(secret, SecretPurpose) : null;
}
/// <summary>Completes the TOTP setup with a first code from the app, and creates the recovery codes.</summary>
/// <param name="account">The account.</param>
/// <param name="code">The code shown by the app.</param>
/// <returns>The ten recovery codes to show once; <see langword="null"/> if the code is wrong.</returns>
public IReadOnlyList<string>? ConfirmTotpSetup(IAccount account, string code)
{
ArgumentNullException.ThrowIfNull(account);
if (account.TotpSecret is null || !VerifyCode(account, code))
{
return null;
}
account.TotpEnabled = true;
var codes = Enumerable.Range(0, 10).Select(_ => SecureTokenGenerator.CreateReadableCode(2)).ToList();
account.TotpRecoveryCodes = JsonSerializer.Serialize(codes.Select(c => SecureTokenGenerator.Hash(c)).ToList());
return codes;
}
/// <summary>Checks a TOTP code at sign-in. A code is never accepted twice.</summary>
/// <param name="account">The account.</param>
/// <param name="code">The code.</param>
/// <returns>Whether the code is valid.</returns>
public bool VerifyTotp(IAccount account, string code)
{
ArgumentNullException.ThrowIfNull(account);
return account.TotpEnabled && account.TotpSecret is not null && VerifyCode(account, code);
}
/// <summary>Uses one of the recovery codes in place of a TOTP code. Each code works once.</summary>
/// <param name="account">The account.</param>
/// <param name="code">The recovery code.</param>
/// <returns>Whether the code was valid.</returns>
public static bool UseRecoveryCode(IAccount account, string code)
{
ArgumentNullException.ThrowIfNull(account);
ArgumentNullException.ThrowIfNull(code);
var hashes = Deserialize(account.TotpRecoveryCodes);
var hash = SecureTokenGenerator.Hash(code.Trim().ToUpperInvariant());
var index = hashes.FindIndex(h => SecureTokenGenerator.HashesEqual(h, hash));
if (!account.TotpEnabled || index < 0)
{
return false;
}
hashes.RemoveAt(index);
account.TotpRecoveryCodes = JsonSerializer.Serialize(hashes);
return true;
}
/// <summary>Turns the two-step verification off (an administrator resetting a lost phone).</summary>
/// <param name="account">The account.</param>
public static void ResetTotp(IAccount account)
{
ArgumentNullException.ThrowIfNull(account);
account.TotpEnabled = false;
account.TotpSecret = null;
account.TotpLastStep = null;
account.TotpRecoveryCodes = null;
}
private bool VerifyCode(IAccount account, string code)
{
string secret;
try
{
secret = _protector.Unprotect(account.TotpSecret!, SecretPurpose);
}
catch (SecretProtectionException)
{
return false;
}
var step = TotpGenerator.Verify(secret, code, _clock.GetUtcNow(), account.TotpLastStep);
if (step is null)
{
return false;
}
account.TotpLastStep = step;
return true;
}
private bool IsReused(IAccount account, string password)
{
if (PasswordHasher.Verify(account.PasswordHash, password) != PasswordVerification.Failed)
{
return true;
}
return Deserialize(account.PasswordHistory).Take(Options.HistorySize)
.Any(h => PasswordHasher.Verify(h, password) != PasswordVerification.Failed);
}
private void Store(IAccount account, string password, bool temporary)
{
if (account.PasswordHash is not null)
{
var history = Deserialize(account.PasswordHistory);
history.Insert(0, account.PasswordHash);
account.PasswordHistory = JsonSerializer.Serialize(history.Take(Math.Max(Options.HistorySize - 1, 0)).ToList());
}
account.PasswordHash = PasswordHasher.Hash(password, Options.HashIterations);
account.PasswordChangedAt = Now;
account.MustChangePassword = false;
account.TemporaryPasswordExpiresAt = temporary ? Now + Options.TemporaryPasswordLifetime : null;
}
private static List<string> Deserialize(string? json)
{
if (string.IsNullOrWhiteSpace(json))
{
return [];
}
try
{
return JsonSerializer.Deserialize<List<string>>(json) ?? [];
}
catch (JsonException)
{
return [];
}
}
}
@@ -0,0 +1,85 @@
using Khaemhat.Core.Security;
namespace Khaemhat.Application.Security;
/// <summary>
/// Who performs an action: an instance account (super user or administrator) or a company user. Services check the
/// actor; the interface only hides what the actor cannot do.
/// </summary>
/// <param name="UserName">The user name, written in the audit columns and logs.</param>
/// <param name="Level">The level.</param>
/// <param name="SystemUserId">The instance account, for super user and administrators.</param>
/// <param name="CompanyUserId">The company user (or the user an administrator is linked to).</param>
/// <param name="CompanyCode">The company the actor works in.</param>
public sealed record Actor(string UserName, UserLevel Level, long? SystemUserId, long? CompanyUserId, string? CompanyCode)
{
/// <summary>The instance itself: bootstrap, scheduled jobs.</summary>
public static Actor System { get; } = new("system", UserLevel.SuperUser, null, null, null);
/// <summary>Whether the actor is an instance account.</summary>
public bool IsInstanceAccount => Level >= UserLevel.Administrator;
/// <summary>Whether the actor is the super user.</summary>
public bool IsSuperUser => Level == UserLevel.SuperUser;
}
/// <summary>An action the actor may not perform. <see cref="Code"/> is one of <see cref="SecurityErrors"/>.</summary>
public sealed class AccessDeniedException : Exception
{
/// <summary>Creates the exception.</summary>
public AccessDeniedException()
: this(SecurityErrors.PermissionDenied, "Access denied.")
{
}
/// <summary>Creates the exception.</summary>
/// <param name="message">The message.</param>
public AccessDeniedException(string message)
: this(SecurityErrors.PermissionDenied, message)
{
}
/// <summary>Creates the exception.</summary>
/// <param name="message">The message.</param>
/// <param name="innerException">The cause.</param>
public AccessDeniedException(string message, Exception innerException)
: base(message, innerException) => Code = SecurityErrors.PermissionDenied;
/// <summary>Creates the exception.</summary>
/// <param name="code">The error code.</param>
/// <param name="message">The message.</param>
public AccessDeniedException(string code, string message)
: base(message) => Code = code;
/// <summary>The error code.</summary>
public string Code { get; }
}
/// <summary>A request the rules refuse (policy, duplicates); <see cref="Errors"/> holds error codes for the interface.</summary>
public sealed class ValidationFailedException : Exception
{
/// <summary>Creates the exception.</summary>
public ValidationFailedException()
: this([])
{
}
/// <summary>Creates the exception.</summary>
/// <param name="message">The message.</param>
public ValidationFailedException(string message)
: base(message) => Errors = [message];
/// <summary>Creates the exception.</summary>
/// <param name="message">The message.</param>
/// <param name="innerException">The cause.</param>
public ValidationFailedException(string message, Exception innerException)
: base(message, innerException) => Errors = [message];
/// <summary>Creates the exception.</summary>
/// <param name="errors">The error codes.</param>
public ValidationFailedException(IReadOnlyList<string> errors)
: base("The request is not valid: " + string.Join(", ", errors ?? [])) => Errors = errors ?? [];
/// <summary>The error codes.</summary>
public IReadOnlyList<string> Errors { get; }
}
@@ -0,0 +1,165 @@
using System.Text.RegularExpressions;
using Khaemhat.Infrastructure.Security;
namespace Khaemhat.Application.Security;
/// <summary>Sign-in names: 3 to 50 characters, letters, digits, dot, dash and underscore; compared in lower case.</summary>
public static partial class UserNames
{
/// <summary>Whether a name has the allowed form.</summary>
/// <param name="name">The name.</param>
/// <returns><see langword="true"/> if valid.</returns>
public static bool IsValid(string? name) => name is not null && Pattern().IsMatch(name.Trim());
/// <summary>The stored form: trimmed, lower case.</summary>
/// <param name="name">The name.</param>
/// <returns>The normalized name.</returns>
/// <exception cref="ArgumentException">The name is not valid.</exception>
public static string Normalize(string name)
{
ArgumentNullException.ThrowIfNull(name);
return IsValid(name)
? name.Trim().ToLowerInvariant()
: throw new ArgumentException("A user name has 3 to 50 characters: letters, digits, dot, dash or underscore.", nameof(name));
}
[GeneratedRegex(@"^[A-Za-z0-9][A-Za-z0-9._\-]{2,49}$", RegexOptions.CultureInvariant)]
private static partial Regex Pattern();
}
/// <summary>The security settings of accounts (SPEC §7.3). The defaults are those of the specification.</summary>
public sealed record SecurityPolicyOptions
{
/// <summary>Minimum password length.</summary>
public int MinimumLength { get; init; } = 10;
/// <summary>Minimum character classes among lower case, upper case, digits and symbols.</summary>
public int MinimumClasses { get; init; } = 3;
/// <summary>How many previous passwords cannot be reused.</summary>
public int HistorySize { get; init; } = 5;
/// <summary>Days after which a password must be changed; <see langword="null"/> for no expiry.</summary>
public int? ExpiryDays { get; init; }
/// <summary>Failed sign-ins before the account is locked.</summary>
public int MaxFailedAttempts { get; init; } = 5;
/// <summary>How long a locked account stays locked.</summary>
public TimeSpan LockoutDuration { get; init; } = TimeSpan.FromMinutes(15);
/// <summary>How long a temporary password works.</summary>
public TimeSpan TemporaryPasswordLifetime { get; init; } = TimeSpan.FromHours(72);
/// <summary>How long a password-recovery link works.</summary>
public TimeSpan RecoveryTokenLifetime { get; init; } = TimeSpan.FromMinutes(30);
/// <summary>The sliding lifetime of a session.</summary>
public TimeSpan SessionLifetime { get; init; } = TimeSpan.FromMinutes(480);
/// <summary>The lifetime of a session with "remember me on this device".</summary>
public TimeSpan PersistentSessionLifetime { get; init; } = TimeSpan.FromDays(14);
/// <summary>The time to complete a pending sign-in step (TOTP, password change).</summary>
public TimeSpan PendingStepLifetime { get; init; } = TimeSpan.FromMinutes(10);
/// <summary>Whether company users must use the two-step verification.</summary>
public bool TotpRequiredForUsers { get; init; }
/// <summary>PBKDF2 iterations; lowered only by tests.</summary>
public int HashIterations { get; init; } = PasswordHasher.Iterations;
}
/// <summary>Checks new passwords against the policy.</summary>
/// <param name="options">The policy.</param>
public sealed class PasswordPolicy(SecurityPolicyOptions options)
{
/// <summary>The policy settings.</summary>
public SecurityPolicyOptions Options { get; } = options ?? throw new ArgumentNullException(nameof(options));
/// <summary>Checks the form of a password.</summary>
/// <param name="password">The new password.</param>
/// <param name="userName">The user name, which the password must not contain.</param>
/// <returns>Error codes: <c>password_too_short</c>, <c>password_too_simple</c>, <c>password_contains_user_name</c>.</returns>
public IReadOnlyList<string> Check(string password, string? userName)
{
ArgumentNullException.ThrowIfNull(password);
var errors = new List<string>();
if (password.Length < Options.MinimumLength)
{
errors.Add(SecurityErrors.PasswordTooShort);
}
var classes = (password.Any(char.IsLower) ? 1 : 0) + (password.Any(char.IsUpper) ? 1 : 0)
+ (password.Any(char.IsDigit) ? 1 : 0) + (password.Any(c => !char.IsLetterOrDigit(c)) ? 1 : 0);
if (classes < Options.MinimumClasses)
{
errors.Add(SecurityErrors.PasswordTooSimple);
}
if (userName is { Length: >= 3 } && password.Contains(userName, StringComparison.OrdinalIgnoreCase))
{
errors.Add(SecurityErrors.PasswordContainsUserName);
}
return errors;
}
}
/// <summary>The error codes of the security services; the interface turns them into Italian messages.</summary>
public static class SecurityErrors
{
/// <summary>Wrong user, company or password (never says which).</summary>
public const string InvalidCredentials = "invalid_credentials";
/// <summary>Too many failed attempts: the account is locked for a while.</summary>
public const string AccountLocked = "account_locked";
/// <summary>The account is disabled.</summary>
public const string AccountDisabled = "account_disabled";
/// <summary>The temporary password has expired.</summary>
public const string TemporaryPasswordExpired = "temporary_password_expired";
/// <summary>The password is shorter than the policy.</summary>
public const string PasswordTooShort = "password_too_short";
/// <summary>The password uses too few character classes.</summary>
public const string PasswordTooSimple = "password_too_simple";
/// <summary>The password contains the user name.</summary>
public const string PasswordContainsUserName = "password_contains_user_name";
/// <summary>The password was used recently.</summary>
public const string PasswordReused = "password_reused";
/// <summary>The current password is wrong.</summary>
public const string CurrentPasswordWrong = "current_password_wrong";
/// <summary>The TOTP code is wrong or already used.</summary>
public const string TotpInvalid = "totp_invalid";
/// <summary>The recovery token is wrong, used or expired.</summary>
public const string RecoveryTokenInvalid = "recovery_token_invalid";
/// <summary>Too many attempts from this address.</summary>
public const string RateLimited = "rate_limited";
/// <summary>The licence allows no more concurrent users.</summary>
public const string ConcurrentUsersExceeded = "concurrent_users_exceeded";
/// <summary>The level of the account does not allow the action.</summary>
public const string LevelTooLow = "level_too_low";
/// <summary>The permission is missing.</summary>
public const string PermissionDenied = "permission_denied";
/// <summary>The module is not in the licence.</summary>
public const string ModuleNotLicensed = "module_not_licensed";
/// <summary>The company is in maintenance or disabled.</summary>
public const string CompanyUnavailable = "company_unavailable";
/// <summary>The licence allows no more of something (companies, users).</summary>
public const string LicenseLimitReached = "license_limit_reached";
}
@@ -0,0 +1,175 @@
using Khaemhat.Application.Licensing;
using Khaemhat.Application.Modules;
using Khaemhat.Core.Caching;
using Khaemhat.Core.Security;
using Khaemhat.Data;
using Khaemhat.Data.Querying;
namespace Khaemhat.Application.Security;
/// <summary>The per-user flags of SPEC §7.2.</summary>
/// <param name="OwnCustomersOnly">Sees only the customers assigned to the user.</param>
/// <param name="CanSeeCosts">Sees costs and margins.</param>
/// <param name="CanExport">Can export.</param>
/// <param name="CanUseApi">Can use the API.</param>
public sealed record UserFlags(bool OwnCustomersOnly, bool CanSeeCosts, bool CanExport, bool CanUseApi)
{
/// <summary>Everything allowed: instance accounts.</summary>
public static UserFlags Unrestricted { get; } = new(false, true, true, true);
}
/// <summary>What a user may do in a company, before the licence is applied. Cached per user.</summary>
/// <param name="AllAccess">Instance accounts: every permission.</param>
/// <param name="Granted">The patterns granted by roles and overrides.</param>
/// <param name="Denied">The patterns denied by overrides (they win).</param>
/// <param name="Flags">The per-user flags.</param>
public sealed record EffectivePermissions(bool AllAccess, IReadOnlyList<string> Granted, IReadOnlyList<string> Denied, UserFlags Flags)
{
/// <summary>Every permission.</summary>
public static EffectivePermissions All { get; } = new(true, ["*"], [], UserFlags.Unrestricted);
/// <summary>No permission.</summary>
public static EffectivePermissions None { get; } = new(false, [], [], new UserFlags(true, false, false, false));
/// <summary>Whether the roles and overrides allow a code (the licence is checked by <see cref="PermissionService"/>).</summary>
/// <param name="code">The permission code.</param>
/// <returns><see langword="true"/> if allowed.</returns>
public bool Allows(string code) =>
AllAccess || (!Denied.Any(d => PermissionPattern.Matches(d, code)) && Granted.Any(g => PermissionPattern.Matches(g, code)));
}
/// <summary>The outcome of a permission check: <see cref="Error"/> is <c>permission_denied</c>, <c>module_not_licensed</c> or <c>license_read_only</c>.</summary>
/// <param name="Allowed">Whether the action is allowed.</param>
/// <param name="Error">The reason otherwise.</param>
public sealed record PermissionCheck(bool Allowed, string? Error)
{
/// <summary>Allowed.</summary>
public static PermissionCheck Ok { get; } = new(true, null);
}
/// <summary>
/// Resolves permissions (SPEC §7.2): instance accounts have every permission; company users have the union of their
/// roles plus granted overrides, minus denied overrides. A module outside the licence is denied with
/// <c>module_not_licensed</c>; past the licence grace only <c>.read</c> permissions remain. Results are cached per user
/// under <c>kh:{company}:permissions:</c> and invalidated when roles or users change.
/// </summary>
public sealed class PermissionService(IUnitOfWorkFactory factory, ICacheProvider cache, ILicenseGate licenses, ModuleRegistry modules)
{
/// <summary>The error when the licence is expired beyond the grace period.</summary>
public const string LicenseReadOnly = "license_read_only";
private const string Area = "permissions";
private static readonly TimeSpan CacheTime = TimeSpan.FromMinutes(10);
/// <summary>The permissions of an actor in its company.</summary>
/// <param name="actor">The actor.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The permissions.</returns>
public async Task<EffectivePermissions> GetAsync(Actor actor, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(actor);
if (actor.IsInstanceAccount)
{
return EffectivePermissions.All;
}
if (actor.CompanyCode is not { } company || actor.CompanyUserId is not { } userId)
{
return EffectivePermissions.None;
}
return await cache.GetOrCreateAsync(
CacheKeys.For(company, Area, userId.ToString(System.Globalization.CultureInfo.InvariantCulture)),
ct => new ValueTask<EffectivePermissions>(LoadAsync(company, userId, ct)),
CacheTime,
cancellationToken).ConfigureAwait(false);
}
/// <summary>Checks one permission, licence included.</summary>
/// <param name="actor">The actor.</param>
/// <param name="code">The permission code.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The outcome.</returns>
public async Task<PermissionCheck> CheckAsync(Actor actor, string code, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(code);
if (modules.FindPermission(code) is not { } definition)
{
return new PermissionCheck(false, SecurityErrors.PermissionDenied);
}
if (!licenses.IsModuleActive(definition.Module))
{
return new PermissionCheck(false, SecurityErrors.ModuleNotLicensed);
}
if (licenses.Current.IsReadOnly && !code.EndsWith(".read", StringComparison.Ordinal))
{
return new PermissionCheck(false, LicenseReadOnly);
}
var permissions = await GetAsync(actor, cancellationToken).ConfigureAwait(false);
return permissions.Allows(code) ? PermissionCheck.Ok : new PermissionCheck(false, SecurityErrors.PermissionDenied);
}
/// <summary>Throws when the actor may not perform the action.</summary>
/// <param name="actor">The actor.</param>
/// <param name="code">The permission code.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
/// <exception cref="AccessDeniedException">The permission is missing or the module is not licensed.</exception>
public async Task DemandAsync(Actor actor, string code, CancellationToken cancellationToken = default)
{
var check = await CheckAsync(actor, code, cancellationToken).ConfigureAwait(false);
if (!check.Allowed)
{
throw new AccessDeniedException(check.Error!, $"Permission {code} is not granted.");
}
}
/// <summary>Whether the actor holds every permission a set of patterns would grant (roles are never above one's own).</summary>
/// <param name="actor">The actor.</param>
/// <param name="patterns">The patterns.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns><see langword="true"/> when nothing in the patterns exceeds the actor.</returns>
public async Task<bool> CoversAsync(Actor actor, IEnumerable<string> patterns, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(patterns);
var own = await GetAsync(actor, cancellationToken).ConfigureAwait(false);
return own.AllAccess || patterns.SelectMany(modules.Expand).All(p => own.Allows(p.Code));
}
/// <summary>Forgets the cached permissions of a company, here and on the other instances.</summary>
/// <param name="companyCode">The company.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public ValueTask InvalidateAsync(string companyCode, CancellationToken cancellationToken = default) =>
cache.PublishInvalidationAsync(CacheKeys.Prefix(CompanyCodes.Normalize(companyCode), Area), cancellationToken);
private async Task<EffectivePermissions> LoadAsync(string company, long userId, CancellationToken cancellationToken)
{
await using var unitOfWork = await factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var user = await unitOfWork.Repository<CompanyUser, long>().GetAsync(userId, cancellationToken).ConfigureAwait(false);
if (user is not { IsActive: true })
{
return EffectivePermissions.None;
}
var roleIds = (await unitOfWork.Repository<UserRole, long>()
.ListAsync(Query.For<UserRole>().Where(r => r.UserId == userId), cancellationToken).ConfigureAwait(false)).Items.Select(r => r.RoleId).ToArray();
var granted = roleIds.Length == 0
? []
: (await unitOfWork.Repository<RoleGrant, long>()
.ListAsync(Query.For<RoleGrant>().Where(g => roleIds.Contains(g.RoleId)), cancellationToken).ConfigureAwait(false)).Items
.Select(g => g.Permission).ToList();
var overrides = (await unitOfWork.Repository<UserPermissionOverride, long>()
.ListAsync(Query.For<UserPermissionOverride>().Where(o => o.UserId == userId), cancellationToken).ConfigureAwait(false)).Items;
granted.AddRange(overrides.Where(o => o.Allowed).Select(o => o.Permission));
var denied = overrides.Where(o => !o.Allowed).Select(o => o.Permission).ToList();
return new EffectivePermissions(
false,
[.. granted.Distinct(StringComparer.Ordinal)],
denied,
new UserFlags(user.OwnCustomersOnly, user.CanSeeCosts, user.CanExport, user.CanUseApi));
}
}
@@ -0,0 +1,238 @@
using System.Text.Json;
using Khaemhat.Application.Audit;
using Khaemhat.Application.Modules;
using Khaemhat.Core.Security;
using Khaemhat.Data;
using Khaemhat.Data.Querying;
namespace Khaemhat.Application.Security;
/// <summary>A role with its permission patterns.</summary>
/// <param name="Role">The role.</param>
/// <param name="Permissions">The patterns.</param>
public sealed record RoleWithPermissions(Role Role, IReadOnlyList<string> Permissions);
/// <summary>
/// Roles (SPEC §7.2): the eight predefined roles live as templates in <c>sys_roles_templates</c> and are copied into each
/// company, where they can be cloned but not changed. Users with <c>company.users.manage</c> manage roles never above
/// their own permissions.
/// </summary>
public sealed class RoleService(IUnitOfWorkFactory factory, PermissionService permissions, ISecurityAuditLog audit)
{
/// <summary>Writes or updates the predefined templates in the system database (bootstrap and every start).</summary>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public async Task SeedTemplatesAsync(CancellationToken cancellationToken = default)
{
await using var unitOfWork = await factory.CreateAsync(DatabaseScope.System, cancellationToken).ConfigureAwait(false);
var templates = unitOfWork.Repository<RoleTemplate, long>();
var existing = (await templates.ListAsync(Query.For<RoleTemplate>(), cancellationToken).ConfigureAwait(false)).Items
.ToDictionary(t => t.Code, StringComparer.Ordinal);
await unitOfWork.InTransactionAsync(
async ct =>
{
var order = 0;
foreach (var definition in PredefinedRoles.All)
{
var json = JsonSerializer.Serialize(definition.Permissions);
order += 10;
if (!existing.TryGetValue(definition.Code, out var template))
{
await templates.InsertAsync(
new RoleTemplate { Code = definition.Code, Name = definition.Name, Description = definition.Description, Permissions = json, SortOrder = order },
ct).ConfigureAwait(false);
}
else if (template.Permissions != json || template.Name != definition.Name || template.Description != definition.Description)
{
template.Name = definition.Name;
template.Description = definition.Description;
template.Permissions = json;
template.SortOrder = order;
await templates.UpdateAsync(template, ct).ConfigureAwait(false);
}
}
},
cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Copies the templates into a company: missing predefined roles are created, existing ones are brought in line
/// with their template (they are not modifiable, so the template wins).
/// </summary>
/// <param name="companyCode">The company.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public async Task SyncPredefinedRolesAsync(string companyCode, CancellationToken cancellationToken = default)
{
IReadOnlyList<RoleTemplate> templates;
await using (var system = await factory.CreateAsync(DatabaseScope.System, cancellationToken).ConfigureAwait(false))
{
templates = (await system.Repository<RoleTemplate, long>().ListAsync(Query.For<RoleTemplate>().OrderBy(t => t.SortOrder), cancellationToken)
.ConfigureAwait(false)).Items;
}
await using var unitOfWork = await factory.CreateAsync(DatabaseScope.Company(companyCode), cancellationToken).ConfigureAwait(false);
var roles = unitOfWork.Repository<Role, long>();
var grants = unitOfWork.Repository<RoleGrant, long>();
await unitOfWork.InTransactionAsync(
async ct =>
{
foreach (var template in templates)
{
var code = template.Code;
var role = await roles.FindAsync(Query.For<Role>().Where(r => r.Code == code), ct).ConfigureAwait(false);
if (role is null)
{
role = new Role { Code = code, Name = template.Name, Description = template.Description, IsPredefined = true, TemplateCode = code };
role.Id = await roles.InsertAsync(role, ct).ConfigureAwait(false);
}
else if (!role.IsPredefined)
{
continue;
}
var wanted = JsonSerializer.Deserialize<List<string>>(template.Permissions) ?? [];
await ReplaceGrantsAsync(grants, role.Id, wanted, ct).ConfigureAwait(false);
}
},
cancellationToken).ConfigureAwait(false);
await permissions.InvalidateAsync(companyCode, cancellationToken).ConfigureAwait(false);
}
/// <summary>The roles of a company with their permissions.</summary>
/// <param name="companyCode">The company.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The roles, predefined first.</returns>
public async Task<IReadOnlyList<RoleWithPermissions>> ListAsync(string companyCode, CancellationToken cancellationToken = default)
{
await using var unitOfWork = await factory.CreateAsync(DatabaseScope.Company(companyCode), cancellationToken).ConfigureAwait(false);
var roles = (await unitOfWork.Repository<Role, long>().ListAsync(Query.For<Role>().OrderByDescending(r => r.IsPredefined).OrderBy(r => r.Name), cancellationToken)
.ConfigureAwait(false)).Items;
var grants = (await unitOfWork.Repository<RoleGrant, long>().ListAsync(Query.For<RoleGrant>(), cancellationToken).ConfigureAwait(false)).Items
.ToLookup(g => g.RoleId);
return [.. roles.Select(r => new RoleWithPermissions(r, [.. grants[r.Id].Select(g => g.Permission).Order(StringComparer.Ordinal)]))];
}
/// <summary>Clones a role into a new, modifiable one.</summary>
/// <param name="actor">Who acts.</param>
/// <param name="companyCode">The company.</param>
/// <param name="sourceCode">The role to clone.</param>
/// <param name="newCode">The new code.</param>
/// <param name="newName">The new name.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The new role.</returns>
public async Task<Role> CloneAsync(Actor actor, string companyCode, string sourceCode, string newCode, string newName, CancellationToken cancellationToken = default)
{
await DemandManageAsync(actor, companyCode, cancellationToken).ConfigureAwait(false);
ArgumentException.ThrowIfNullOrWhiteSpace(newName);
var code = NormalizeCode(newCode);
await using var unitOfWork = await factory.CreateAsync(DatabaseScope.Company(companyCode), cancellationToken).ConfigureAwait(false);
var roles = unitOfWork.Repository<Role, long>();
var grants = unitOfWork.Repository<RoleGrant, long>();
var source = await roles.FindAsync(Query.For<Role>().Where(r => r.Code == sourceCode), cancellationToken).ConfigureAwait(false)
?? throw new KeyNotFoundException($"No role has code {sourceCode}.");
var sourceId = source.Id;
var patterns = (await grants.ListAsync(Query.For<RoleGrant>().Where(g => g.RoleId == sourceId), cancellationToken).ConfigureAwait(false)).Items
.Select(g => g.Permission).ToList();
if (!await permissions.CoversAsync(actor, patterns, cancellationToken).ConfigureAwait(false))
{
throw new AccessDeniedException(SecurityErrors.PermissionDenied, "A role cannot grant more than the permissions of who creates it.");
}
var role = new Role { Code = code, Name = newName.Trim(), Description = source.Description, IsPredefined = false, TemplateCode = source.Code };
await unitOfWork.InTransactionAsync(
async ct =>
{
if (await roles.CountAsync(Query.For<Role>().Where(r => r.Code == code), ct).ConfigureAwait(false) > 0)
{
throw new ValidationFailedException(["role_code_taken"]);
}
role.Id = await roles.InsertAsync(role, ct).ConfigureAwait(false);
await ReplaceGrantsAsync(grants, role.Id, patterns, ct).ConfigureAwait(false);
},
cancellationToken).ConfigureAwait(false);
await audit.WriteAsync(new SecurityEvent("role.cloned", actor.UserName, companyCode, code, new { from = source.Code }), cancellationToken).ConfigureAwait(false);
return role;
}
/// <summary>Sets the permissions of a cloned role. Predefined roles are refused.</summary>
/// <param name="actor">Who acts.</param>
/// <param name="companyCode">The company.</param>
/// <param name="roleCode">The role.</param>
/// <param name="patterns">The new permission patterns.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public async Task SetPermissionsAsync(Actor actor, string companyCode, string roleCode, IReadOnlyList<string> patterns, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(patterns);
await DemandManageAsync(actor, companyCode, cancellationToken).ConfigureAwait(false);
if (patterns.Any(p => p != "*" && !PermissionPattern.IsCode(p.Replace("*", "x", StringComparison.Ordinal))))
{
throw new ValidationFailedException(["permission_invalid"]);
}
if (!await permissions.CoversAsync(actor, patterns, cancellationToken).ConfigureAwait(false))
{
throw new AccessDeniedException(SecurityErrors.PermissionDenied, "A role cannot grant more than the permissions of who changes it.");
}
await using var unitOfWork = await factory.CreateAsync(DatabaseScope.Company(companyCode), cancellationToken).ConfigureAwait(false);
var role = await unitOfWork.Repository<Role, long>().FindAsync(Query.For<Role>().Where(r => r.Code == roleCode), cancellationToken).ConfigureAwait(false)
?? throw new KeyNotFoundException($"No role has code {roleCode}.");
if (role.IsPredefined)
{
throw new ValidationFailedException(["role_predefined"]);
}
await unitOfWork.InTransactionAsync(ct => ReplaceGrantsAsync(unitOfWork.Repository<RoleGrant, long>(), role.Id, patterns, ct), cancellationToken).ConfigureAwait(false);
await permissions.InvalidateAsync(companyCode, cancellationToken).ConfigureAwait(false);
await audit.WriteAsync(new SecurityEvent("role.permissions-changed", actor.UserName, companyCode, roleCode, new { patterns }), cancellationToken).ConfigureAwait(false);
}
/// <summary>Checks that the actor may manage users and roles of a company.</summary>
/// <param name="actor">The actor.</param>
/// <param name="companyCode">The company.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
/// <exception cref="AccessDeniedException">The actor may not.</exception>
internal async Task DemandManageAsync(Actor actor, string companyCode, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(actor);
if (actor.IsInstanceAccount)
{
return;
}
if (!string.Equals(actor.CompanyCode, CompanyCodes.Normalize(companyCode), StringComparison.Ordinal))
{
throw new AccessDeniedException(SecurityErrors.PermissionDenied, "A company user works only in its own company.");
}
await permissions.DemandAsync(actor, "company.users.manage", cancellationToken).ConfigureAwait(false);
}
private static string NormalizeCode(string code)
{
ArgumentNullException.ThrowIfNull(code);
var normalized = code.Trim().ToUpperInvariant();
return normalized.Length is >= 2 and <= 50 && normalized.All(c => char.IsAsciiLetterOrDigit(c) || c == '_')
? normalized
: throw new ValidationFailedException(["role_code_invalid"]);
}
private static async Task ReplaceGrantsAsync(IRepository<RoleGrant, long> grants, long roleId, IEnumerable<string> patterns, CancellationToken cancellationToken)
{
var current = (await grants.ListAsync(Query.For<RoleGrant>().Where(g => g.RoleId == roleId), cancellationToken).ConfigureAwait(false)).Items;
var wanted = patterns.Distinct(StringComparer.Ordinal).ToHashSet(StringComparer.Ordinal);
foreach (var grant in current.Where(g => !wanted.Contains(g.Permission)))
{
await grants.DeleteAsync(grant.Id, cancellationToken).ConfigureAwait(false);
}
foreach (var pattern in wanted.Except(current.Select(g => g.Permission)))
{
await grants.InsertAsync(new RoleGrant { RoleId = roleId, Permission = pattern }, cancellationToken).ConfigureAwait(false);
}
}
}
@@ -0,0 +1,468 @@
using Khaemhat.Core.Caching;
using Khaemhat.Core.Security;
using Khaemhat.Data;
using Khaemhat.Data.Companies;
using Khaemhat.Data.Querying;
using Khaemhat.Infrastructure.Security;
namespace Khaemhat.Application.Security;
/// <summary>
/// Who a session belongs to: an instance account (<c>sys_sessions</c>) or a user of a company (<c>user_sessions</c> in
/// that company's database).
/// </summary>
/// <param name="CompanyDatabase">The company whose database holds the user; <see langword="null"/> for instance accounts.</param>
/// <param name="UserId">The account.</param>
public sealed record SessionOwner(string? CompanyDatabase, long UserId)
{
/// <summary>Whether the owner is an instance account.</summary>
public bool IsInstanceAccount => CompanyDatabase is null;
}
/// <summary>What a valid session says about its user, resolved at each request and cached briefly.</summary>
/// <param name="SessionId">The session row.</param>
/// <param name="Owner">The owner.</param>
/// <param name="State">The sign-in state.</param>
/// <param name="UserName">The user name.</param>
/// <param name="DisplayName">The name shown.</param>
/// <param name="Level">The level.</param>
/// <param name="CompanyCode">The company the session works in.</param>
/// <param name="LinkedUserId">For administrators linked to a user of <paramref name="CompanyCode"/>: that user.</param>
/// <param name="ExpiresAt">When the session expires unless used.</param>
/// <param name="Persistent">Whether the cookie survives the browser.</param>
public sealed record SessionIdentity(
long SessionId, SessionOwner Owner, SessionState State, string UserName, string DisplayName, UserLevel Level,
string? CompanyCode, long? LinkedUserId, DateTime ExpiresAt, bool Persistent)
{
/// <summary>The actor for the services.</summary>
/// <returns>The actor.</returns>
public Actor ToActor() => Owner.IsInstanceAccount
? new Actor(UserName, Level, Owner.UserId, LinkedUserId, CompanyCode)
: new Actor(UserName, UserLevel.Standard, null, Owner.UserId, CompanyCode);
}
/// <summary>A session as listed to its user or to administrators.</summary>
/// <param name="Id">The session row.</param>
/// <param name="CreatedAt">The sign-in time.</param>
/// <param name="LastSeenAt">The last request.</param>
/// <param name="IpAddress">The client address.</param>
/// <param name="UserAgent">The browser.</param>
/// <param name="CompanyCode">The company.</param>
public sealed record SessionSummary(long Id, DateTime CreatedAt, DateTime LastSeenAt, string? IpAddress, string? UserAgent, string? CompanyCode);
/// <summary>
/// Sign-in sessions (SPEC §7.3). The cookie value is <c>&lt;scope&gt;.&lt;token&gt;</c>: the scope says which database
/// holds the row (<c>_</c> for the system database, otherwise the company code) and the token is 256 random bits, of which
/// only the SHA-256 hash is stored. Expiry is sliding; revocation takes effect at the next request.
/// </summary>
public sealed class SessionStore
{
private const string SystemScope = "_";
private const string CacheArea = "sessions";
private static readonly TimeSpan TouchInterval = TimeSpan.FromMinutes(1);
private static readonly TimeSpan CacheTime = TimeSpan.FromSeconds(30);
private readonly IUnitOfWorkFactory _factory;
private readonly ICompanyRegistry _companies;
private readonly ICacheProvider _cache;
private readonly SecurityPolicyOptions _policy;
private readonly TimeProvider _clock;
/// <summary>Creates the store.</summary>
/// <param name="factory">Opens the databases.</param>
/// <param name="companies">The company registry.</param>
/// <param name="cache">The cache of resolved sessions.</param>
/// <param name="policy">Session lifetimes.</param>
/// <param name="clock">The clock.</param>
public SessionStore(IUnitOfWorkFactory factory, ICompanyRegistry companies, ICacheProvider cache, SecurityPolicyOptions policy, TimeProvider clock)
{
ArgumentNullException.ThrowIfNull(factory);
ArgumentNullException.ThrowIfNull(companies);
ArgumentNullException.ThrowIfNull(cache);
ArgumentNullException.ThrowIfNull(policy);
ArgumentNullException.ThrowIfNull(clock);
_factory = factory;
_companies = companies;
_cache = cache;
_policy = policy;
_clock = clock;
}
private DateTime Now => DateTime.SpecifyKind(Data.Execution.DataAccessContext.Truncate(_clock.GetUtcNow().UtcDateTime), DateTimeKind.Utc);
/// <summary>Creates a session.</summary>
/// <param name="owner">The owner.</param>
/// <param name="state">The sign-in state.</param>
/// <param name="companyCode">The company the session works in.</param>
/// <param name="ipAddress">The client address.</param>
/// <param name="userAgent">The browser.</param>
/// <param name="persistent">"Remember me on this device".</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The cookie value.</returns>
public async Task<string> CreateAsync(
SessionOwner owner, SessionState state, string? companyCode, string? ipAddress, string? userAgent, bool persistent, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(owner);
var token = SecureTokenGenerator.Create();
var now = Now;
SessionRecord session = owner.IsInstanceAccount ? new SystemSession() : new UserSession();
session.TokenHash = SecureTokenGenerator.Hash(token);
session.UserId = owner.UserId;
session.State = state;
session.CompanyCode = companyCode;
session.IpAddress = Clip(ipAddress, 64);
session.UserAgent = Clip(userAgent, 400);
session.Persistent = persistent;
session.LastSeenAt = now;
session.ExpiresAt = now + Lifetime(state, persistent);
await using var unitOfWork = await OpenAsync(owner, cancellationToken).ConfigureAwait(false);
if (session is SystemSession system)
{
await unitOfWork.Repository<SystemSession, long>().InsertAsync(system, cancellationToken).ConfigureAwait(false);
}
else
{
await unitOfWork.Repository<UserSession, long>().InsertAsync((UserSession)session, cancellationToken).ConfigureAwait(false);
}
return (owner.CompanyDatabase ?? SystemScope) + "." + token;
}
/// <summary>Finds the valid session of a cookie (not revoked, not expired) and slides its expiry.</summary>
/// <param name="cookie">The cookie value.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The session row and owner, or <see langword="null"/>.</returns>
public async Task<(SessionRecord Session, SessionOwner Owner)?> FindAsync(string? cookie, CancellationToken cancellationToken = default)
{
if (!TryParse(cookie, out var owner, out var hash))
{
return null;
}
await using var unitOfWork = await OpenAsync(owner, cancellationToken).ConfigureAwait(false);
var session = owner.IsInstanceAccount
? await unitOfWork.Repository<SystemSession, long>().FindAsync(Query.For<SystemSession>().Where(s => s.TokenHash == hash), cancellationToken).ConfigureAwait(false)
: (SessionRecord?)await unitOfWork.Repository<UserSession, long>().FindAsync(Query.For<UserSession>().Where(s => s.TokenHash == hash), cancellationToken).ConfigureAwait(false);
var now = Now;
if (session is null || session.RevokedAt is not null || session.ExpiresAt <= now)
{
return null;
}
if (now - session.LastSeenAt >= TouchInterval)
{
session.LastSeenAt = now;
session.ExpiresAt = now + Lifetime(session.State, session.Persistent);
await SaveAsync(unitOfWork, session, cancellationToken).ConfigureAwait(false);
}
return (session, owner with { UserId = session.UserId });
}
/// <summary>Moves a session to another sign-in state and gives it a new token (the old cookie stops working).</summary>
/// <param name="cookie">The current cookie value.</param>
/// <param name="state">The new state.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The new cookie value, or <see langword="null"/> when the session is not valid.</returns>
public async Task<string?> AdvanceAsync(string cookie, SessionState state, CancellationToken cancellationToken = default)
{
if (await FindAsync(cookie, cancellationToken).ConfigureAwait(false) is not var (session, owner))
{
return null;
}
var token = SecureTokenGenerator.Create();
var now = Now;
session.TokenHash = SecureTokenGenerator.Hash(token);
session.State = state;
session.LastSeenAt = now;
session.ExpiresAt = now + Lifetime(state, session.Persistent);
await using var unitOfWork = await OpenAsync(owner, cancellationToken).ConfigureAwait(false);
await SaveAsync(unitOfWork, session, cancellationToken).ConfigureAwait(false);
await ForgetAsync(cookie, cancellationToken).ConfigureAwait(false);
return (owner.CompanyDatabase ?? SystemScope) + "." + token;
}
/// <summary>Changes the company a session of an instance account works in.</summary>
/// <param name="cookie">The cookie value.</param>
/// <param name="companyCode">The company, or <see langword="null"/>.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public async Task SetCompanyAsync(string cookie, string? companyCode, CancellationToken cancellationToken = default)
{
if (await FindAsync(cookie, cancellationToken).ConfigureAwait(false) is not var (session, owner) || !owner.IsInstanceAccount)
{
throw new AccessDeniedException(SecurityErrors.PermissionDenied, "Only instance accounts choose the company.");
}
session.CompanyCode = companyCode is null ? null : CompanyCodes.Normalize(companyCode);
await using var unitOfWork = await OpenAsync(owner, cancellationToken).ConfigureAwait(false);
await SaveAsync(unitOfWork, session, cancellationToken).ConfigureAwait(false);
await ForgetAsync(cookie, cancellationToken).ConfigureAwait(false);
}
/// <summary>Revokes the session of a cookie (sign-out).</summary>
/// <param name="cookie">The cookie value.</param>
/// <param name="reason">Why.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The owner of the revoked session, or <see langword="null"/>.</returns>
public async Task<SessionOwner?> RevokeAsync(string? cookie, string reason, CancellationToken cancellationToken = default)
{
if (await FindAsync(cookie, cancellationToken).ConfigureAwait(false) is not var (session, owner))
{
return null;
}
await RevokeAsync(owner, session.Id, reason, cancellationToken).ConfigureAwait(false);
await ForgetAsync(cookie!, cancellationToken).ConfigureAwait(false);
return owner;
}
/// <summary>Revokes one session of an owner (from the list of sessions).</summary>
/// <param name="owner">The owner.</param>
/// <param name="sessionId">The session row.</param>
/// <param name="reason">Why.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>Whether a session was revoked.</returns>
public async Task<bool> RevokeAsync(SessionOwner owner, long sessionId, string reason, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(owner);
var revoked = await RevokeWhereAsync(owner, s => s.Id == sessionId && s.UserId == owner.UserId, reason, cancellationToken).ConfigureAwait(false);
return revoked > 0;
}
/// <summary>Revokes every session of an owner, except one (password change, administrator action).</summary>
/// <param name="owner">The owner.</param>
/// <param name="reason">Why.</param>
/// <param name="exceptSessionId">The session to keep.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The number of sessions revoked.</returns>
public Task<int> RevokeAllAsync(SessionOwner owner, string reason, long? exceptSessionId = null, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(owner);
var keep = exceptSessionId ?? 0;
return RevokeWhereAsync(owner, s => s.UserId == owner.UserId && s.Id != keep, reason, cancellationToken);
}
/// <summary>
/// Revokes every session of the users of a company (maintenance, disabling): instance accounts keep theirs, also when
/// they work in that company.
/// </summary>
/// <param name="companyCode">The company.</param>
/// <param name="reason">Why.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The number of sessions revoked.</returns>
public async Task<int> RevokeCompanyAsync(string companyCode, string reason, CancellationToken cancellationToken = default)
{
var now = Now;
var why = Clip(reason, 100);
int count;
await using (var unitOfWork = await _factory.CreateAsync(DatabaseScope.Company(companyCode), cancellationToken).ConfigureAwait(false))
{
count = await unitOfWork.ExecuteAsync(
SqlFragment.Of($"UPDATE {SqlFragment.Identifier("user_sessions")} SET revoked_at = {now}, revoked_reason = {why} WHERE revoked_at IS NULL"),
cancellationToken).ConfigureAwait(false);
}
if (count > 0)
{
await _cache.PublishInvalidationAsync(CacheKeys.Prefix(null, CacheArea), cancellationToken).ConfigureAwait(false);
}
return count;
}
/// <summary>Whether a signed-in session is still valid (the periodic check of open Blazor circuits).</summary>
/// <param name="owner">The owner.</param>
/// <param name="sessionId">The session row.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns><see langword="true"/> while the session is active, not revoked and not expired.</returns>
public async Task<bool> IsActiveAsync(SessionOwner owner, long sessionId, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(owner);
var now = Now;
await using var unitOfWork = await OpenAsync(owner, cancellationToken).ConfigureAwait(false);
var userId = owner.UserId;
return owner.IsInstanceAccount
? await unitOfWork.Repository<SystemSession, long>().CountAsync(
Query.For<SystemSession>().Where(s => s.Id == sessionId && s.UserId == userId && s.RevokedAt == null && s.ExpiresAt > now && s.State == SessionState.Active),
cancellationToken).ConfigureAwait(false) > 0
: await unitOfWork.Repository<UserSession, long>().CountAsync(
Query.For<UserSession>().Where(s => s.Id == sessionId && s.UserId == userId && s.RevokedAt == null && s.ExpiresAt > now && s.State == SessionState.Active),
cancellationToken).ConfigureAwait(false) > 0;
}
/// <summary>The active sessions of an owner.</summary>
/// <param name="owner">The owner.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The sessions, most recent first.</returns>
public async Task<IReadOnlyList<SessionSummary>> ListAsync(SessionOwner owner, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(owner);
var now = Now;
var userId = owner.UserId;
await using var unitOfWork = await OpenAsync(owner, cancellationToken).ConfigureAwait(false);
IEnumerable<SessionRecord> sessions = owner.IsInstanceAccount
? (await unitOfWork.Repository<SystemSession, long>().ListAsync(
Query.For<SystemSession>().Where(s => s.UserId == userId && s.RevokedAt == null && s.ExpiresAt > now).OrderByDescending(s => s.LastSeenAt), cancellationToken)
.ConfigureAwait(false)).Items
: (await unitOfWork.Repository<UserSession, long>().ListAsync(
Query.For<UserSession>().Where(s => s.UserId == userId && s.RevokedAt == null && s.ExpiresAt > now).OrderByDescending(s => s.LastSeenAt), cancellationToken)
.ConfigureAwait(false)).Items;
return [.. sessions.Select(s => new SessionSummary(s.Id, s.CreatedAt, s.LastSeenAt, s.IpAddress, s.UserAgent, s.CompanyCode))];
}
/// <summary>Whether an owner has signed in before from the same browser (to warn about new devices).</summary>
/// <param name="owner">The owner.</param>
/// <param name="userAgent">The browser.</param>
/// <param name="exceptSessionId">The session just created.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns><see langword="true"/> if a previous session used the same browser.</returns>
public async Task<bool> IsKnownDeviceAsync(SessionOwner owner, string? userAgent, long exceptSessionId, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(owner);
var agent = Clip(userAgent, 400);
var userId = owner.UserId;
await using var unitOfWork = await OpenAsync(owner, cancellationToken).ConfigureAwait(false);
return owner.IsInstanceAccount
? await unitOfWork.Repository<SystemSession, long>().CountAsync(
Query.For<SystemSession>().Where(s => s.UserId == userId && s.UserAgent == agent && s.Id != exceptSessionId && s.State == SessionState.Active), cancellationToken)
.ConfigureAwait(false) > 0
: await unitOfWork.Repository<UserSession, long>().CountAsync(
Query.For<UserSession>().Where(s => s.UserId == userId && s.UserAgent == agent && s.Id != exceptSessionId && s.State == SessionState.Active), cancellationToken)
.ConfigureAwait(false) > 0;
}
/// <summary>
/// The users with an active session across the system database and every company (the concurrent-user limit of the
/// licence, SPEC §7.3).
/// </summary>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The owners with at least one active session.</returns>
public async Task<IReadOnlySet<SessionOwner>> ActiveOwnersAsync(CancellationToken cancellationToken = default)
{
var now = Now;
var owners = new HashSet<SessionOwner>();
await using (var system = await _factory.CreateAsync(DatabaseScope.System, cancellationToken).ConfigureAwait(false))
{
var rows = await system.QueryAsync<long>(
SqlFragment.Of($"SELECT DISTINCT user_id FROM {SqlFragment.Identifier("sys_sessions")} WHERE revoked_at IS NULL AND expires_at > {now} AND state = {nameof(SessionState.Active)}"),
cancellationToken).ConfigureAwait(false);
owners.UnionWith(rows.Select(id => new SessionOwner(null, id)));
}
foreach (var company in await _companies.ListAsync(cancellationToken).ConfigureAwait(false))
{
if (company.Status is Core.Instance.CompanyStatus.Disabled)
{
continue;
}
await using var unitOfWork = await _factory.CreateAsync(DatabaseScope.Company(company.Code), cancellationToken).ConfigureAwait(false);
var rows = await unitOfWork.QueryAsync<long>(
SqlFragment.Of($"SELECT DISTINCT user_id FROM {SqlFragment.Identifier("user_sessions")} WHERE revoked_at IS NULL AND expires_at > {now} AND state = {nameof(SessionState.Active)}"),
cancellationToken).ConfigureAwait(false);
owners.UnionWith(rows.Select(id => new SessionOwner(company.Code, id)));
}
return owners;
}
/// <summary>Deletes sessions expired or revoked more than <paramref name="age"/> ago (the cleanup job).</summary>
/// <param name="scope">The database.</param>
/// <param name="age">How long to keep them for the history.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The rows deleted.</returns>
public async Task<int> PurgeAsync(DatabaseScope scope, TimeSpan age, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(scope);
var limit = Now - age;
var table = scope.IsSystem ? "sys_sessions" : "user_sessions";
await using var unitOfWork = await _factory.CreateAsync(scope, cancellationToken).ConfigureAwait(false);
return await unitOfWork.ExecuteAsync(
SqlFragment.Of($"DELETE FROM {SqlFragment.Identifier(table)} WHERE expires_at < {limit} OR revoked_at < {limit}"), cancellationToken).ConfigureAwait(false);
}
/// <summary>The cache key of a cookie's resolved identity.</summary>
/// <param name="cookie">The cookie value.</param>
/// <returns>The key.</returns>
public static string CacheKey(string cookie) => CacheKeys.For(null, CacheArea, SecureTokenGenerator.Hash(cookie ?? string.Empty));
/// <summary>Forgets the cached identity of a cookie.</summary>
/// <param name="cookie">The cookie value.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public ValueTask ForgetAsync(string cookie, CancellationToken cancellationToken = default) => _cache.RemoveAsync(CacheKey(cookie), cancellationToken);
/// <summary>How long a resolved identity may stay cached (revocations by id also clear the whole area).</summary>
public static TimeSpan IdentityCacheTime => CacheTime;
private async Task<int> RevokeWhereAsync(SessionOwner owner, System.Linq.Expressions.Expression<Func<SessionRecord, bool>> filter, string reason, CancellationToken cancellationToken)
{
var now = Now;
var predicate = filter.Compile();
await using var unitOfWork = await OpenAsync(owner, cancellationToken).ConfigureAwait(false);
var userId = owner.UserId;
IEnumerable<SessionRecord> sessions = owner.IsInstanceAccount
? (await unitOfWork.Repository<SystemSession, long>().ListAsync(Query.For<SystemSession>().Where(s => s.UserId == userId && s.RevokedAt == null), cancellationToken).ConfigureAwait(false)).Items
: (await unitOfWork.Repository<UserSession, long>().ListAsync(Query.For<UserSession>().Where(s => s.UserId == userId && s.RevokedAt == null), cancellationToken).ConfigureAwait(false)).Items;
var count = 0;
foreach (var session in sessions.Where(predicate))
{
session.RevokedAt = now;
session.RevokedReason = Clip(reason, 100);
await SaveAsync(unitOfWork, session, cancellationToken).ConfigureAwait(false);
count++;
}
if (count > 0)
{
// The identity cache is keyed by cookie, which is unknown here: drop the whole area (entries live 30 seconds).
await _cache.PublishInvalidationAsync(CacheKeys.Prefix(null, CacheArea), cancellationToken).ConfigureAwait(false);
}
return count;
}
private static async Task SaveAsync(IUnitOfWork unitOfWork, SessionRecord session, CancellationToken cancellationToken)
{
if (session is SystemSession system)
{
await unitOfWork.Repository<SystemSession, long>().UpdateAsync(system, cancellationToken).ConfigureAwait(false);
}
else
{
await unitOfWork.Repository<UserSession, long>().UpdateAsync((UserSession)session, cancellationToken).ConfigureAwait(false);
}
}
private TimeSpan Lifetime(SessionState state, bool persistent) =>
state != SessionState.Active ? _policy.PendingStepLifetime : persistent ? _policy.PersistentSessionLifetime : _policy.SessionLifetime;
private Task<IUnitOfWork> OpenAsync(SessionOwner owner, CancellationToken cancellationToken) =>
_factory.CreateAsync(owner.IsInstanceAccount ? DatabaseScope.System : DatabaseScope.Company(owner.CompanyDatabase!), cancellationToken);
private static bool TryParse(string? cookie, out SessionOwner owner, out string hash)
{
owner = new SessionOwner(null, 0);
hash = string.Empty;
var dot = cookie?.IndexOf('.', StringComparison.Ordinal) ?? -1;
if (dot <= 0 || cookie!.Length - dot < 40)
{
return false;
}
var scope = cookie[..dot];
if (scope != SystemScope && !CompanyCodes.IsValid(scope))
{
return false;
}
owner = new SessionOwner(scope == SystemScope ? null : scope, 0);
hash = SecureTokenGenerator.Hash(cookie[(dot + 1)..]);
return true;
}
private static string? Clip(string? value, int length) => value is null || value.Length <= length ? value : value[..length];
}
@@ -0,0 +1,416 @@
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());
}
}
@@ -0,0 +1,297 @@
using Khaemhat.Application.Audit;
using Khaemhat.Core.Security;
using Khaemhat.Data;
using Khaemhat.Data.Querying;
namespace Khaemhat.Application.Security;
/// <summary>A new instance account.</summary>
/// <param name="UserName">The sign-in name.</param>
/// <param name="DisplayName">The name shown.</param>
/// <param name="Email">The e-mail address.</param>
public sealed record NewSystemUser(string UserName, string DisplayName, string? Email);
/// <summary>
/// Instance accounts (<c>sys_users</c>, SPEC §7.1): one super user, created at first start and never deleted or
/// demoted; administrators, created and managed only by the super user. An administrator manages only its own profile.
/// </summary>
public sealed class SystemUserService
{
private readonly IUnitOfWorkFactory _factory;
private readonly AccountSecurity _security;
private readonly ISecurityAuditLog _audit;
/// <summary>Creates the service.</summary>
/// <param name="factory">Opens the system database.</param>
/// <param name="security">The credential rules.</param>
/// <param name="audit">The security audit.</param>
public SystemUserService(IUnitOfWorkFactory factory, AccountSecurity security, ISecurityAuditLog audit)
{
ArgumentNullException.ThrowIfNull(factory);
ArgumentNullException.ThrowIfNull(security);
ArgumentNullException.ThrowIfNull(audit);
_factory = factory;
_security = security;
_audit = audit;
}
/// <summary>Whether any instance account exists (the bootstrap reads the variables only when none does).</summary>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns><see langword="true"/> when <c>sys_users</c> has rows.</returns>
public async Task<bool> AnyAsync(CancellationToken cancellationToken = default)
{
await using var unitOfWork = await _factory.CreateAsync(DatabaseScope.System, cancellationToken).ConfigureAwait(false);
return await unitOfWork.Repository<SystemUser, long>().CountAsync(Query.For<SystemUser>(), cancellationToken).ConfigureAwait(false) > 0;
}
/// <summary>Lists the instance accounts.</summary>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The accounts, super user first.</returns>
public async Task<IReadOnlyList<SystemUser>> ListAsync(CancellationToken cancellationToken = default)
{
await using var unitOfWork = await _factory.CreateAsync(DatabaseScope.System, cancellationToken).ConfigureAwait(false);
var page = await unitOfWork.Repository<SystemUser, long>()
.ListAsync(Query.For<SystemUser>().OrderByDescending(u => u.Level).OrderBy(u => u.UserName), cancellationToken).ConfigureAwait(false);
return page.Items;
}
/// <summary>Finds an account by sign-in name.</summary>
/// <param name="userName">The name, in any case.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The account, or <see langword="null"/>.</returns>
public async Task<SystemUser?> FindByNameAsync(string userName, CancellationToken cancellationToken = default)
{
if (!UserNames.IsValid(userName))
{
return null;
}
var name = UserNames.Normalize(userName);
await using var unitOfWork = await _factory.CreateAsync(DatabaseScope.System, cancellationToken).ConfigureAwait(false);
return await unitOfWork.Repository<SystemUser, long>().FindAsync(Query.For<SystemUser>().Where(u => u.UserName == name), cancellationToken)
.ConfigureAwait(false);
}
/// <summary>Finds an account.</summary>
/// <param name="id">The identifier.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The account, or <see langword="null"/>.</returns>
public async Task<SystemUser?> GetAsync(long id, CancellationToken cancellationToken = default)
{
await using var unitOfWork = await _factory.CreateAsync(DatabaseScope.System, cancellationToken).ConfigureAwait(false);
return await unitOfWork.Repository<SystemUser, long>().GetAsync(id, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Creates the super user at first start, from <c>KHAEMHAT_SUPERUSER*</c>. Refused when a super user exists.
/// The password must be changed at the first access and the two-step verification set up.
/// </summary>
/// <param name="account">The account.</param>
/// <param name="password">The first password.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The account.</returns>
/// <exception cref="ValidationFailedException">The password does not satisfy the policy.</exception>
public async Task<SystemUser> CreateSuperUserAsync(NewSystemUser account, string password, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(account);
var user = NewAccount(account, UserLevel.SuperUser);
var errors = _security.SetInitialPassword(user, password, temporary: false);
if (errors.Count > 0)
{
throw new ValidationFailedException(errors);
}
await using var unitOfWork = await _factory.CreateAsync(DatabaseScope.System, cancellationToken).ConfigureAwait(false);
var users = unitOfWork.Repository<SystemUser, long>();
await unitOfWork.InTransactionAsync(
async ct =>
{
await unitOfWork.AcquireLockAsync("sys-users", ct).ConfigureAwait(false);
if (await users.CountAsync(Query.For<SystemUser>().Where(u => u.Level == UserLevel.SuperUser), ct).ConfigureAwait(false) > 0)
{
throw new InvalidOperationException("The super user already exists.");
}
await users.InsertAsync(user, ct).ConfigureAwait(false);
},
cancellationToken).ConfigureAwait(false);
await _audit.WriteAsync(new SecurityEvent("user.superuser-created", Actor.System.UserName, Target: user.UserName), cancellationToken).ConfigureAwait(false);
return user;
}
/// <summary>Creates an administrator with a temporary password. Only the super user may.</summary>
/// <param name="actor">Who acts.</param>
/// <param name="account">The account.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The account and its temporary password, to give once.</returns>
public async Task<(SystemUser User, string TemporaryPassword)> CreateAdministratorAsync(
Actor actor, NewSystemUser account, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(actor);
ArgumentNullException.ThrowIfNull(account);
RequireSuperUser(actor);
var user = NewAccount(account, UserLevel.Administrator);
var password = _security.IssueTemporaryPassword(user);
await using var unitOfWork = await _factory.CreateAsync(DatabaseScope.System, cancellationToken).ConfigureAwait(false);
var users = unitOfWork.Repository<SystemUser, long>();
await unitOfWork.InTransactionAsync(
async ct =>
{
if (await users.CountAsync(Query.For<SystemUser>().Where(u => u.UserName == user.UserName), ct).ConfigureAwait(false) > 0)
{
throw new ValidationFailedException(["user_name_taken"]);
}
await users.InsertAsync(user, ct).ConfigureAwait(false);
},
cancellationToken).ConfigureAwait(false);
await _audit.WriteAsync(new SecurityEvent("user.administrator-created", actor.UserName, Target: user.UserName), cancellationToken).ConfigureAwait(false);
return (user, password);
}
/// <summary>Changes name, e-mail and state of an account.</summary>
/// <param name="actor">Who acts: the super user, or an administrator on its own profile.</param>
/// <param name="id">The account.</param>
/// <param name="displayName">The new name.</param>
/// <param name="email">The new e-mail.</param>
/// <param name="isActive">The new state; the super user cannot be disabled.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public async Task UpdateAsync(Actor actor, long id, string displayName, string? email, bool isActive, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(actor);
ArgumentException.ThrowIfNullOrWhiteSpace(displayName);
await ChangeAsync(
actor,
id,
"user.updated",
user =>
{
if (user.Level == UserLevel.SuperUser && !isActive)
{
throw new AccessDeniedException(SecurityErrors.LevelTooLow, "The super user cannot be disabled.");
}
if (!actor.IsSuperUser && user.IsActive != isActive)
{
throw new AccessDeniedException(SecurityErrors.LevelTooLow, "Only the super user enables or disables administrators.");
}
user.DisplayName = displayName.Trim();
user.Email = string.IsNullOrWhiteSpace(email) ? null : email.Trim();
user.IsActive = isActive;
},
allowSelf: true,
cancellationToken).ConfigureAwait(false);
}
/// <summary>Gives an administrator a new temporary password. Only the super user may.</summary>
/// <param name="actor">Who acts.</param>
/// <param name="id">The account.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The temporary password.</returns>
public async Task<string> ResetPasswordAsync(Actor actor, long id, CancellationToken cancellationToken = default)
{
string? password = null;
await ChangeAsync(actor, id, "user.password-reset", user => password = _security.IssueTemporaryPassword(user), allowSelf: false, cancellationToken)
.ConfigureAwait(false);
return password!;
}
/// <summary>Turns off the two-step verification of an administrator who lost the phone. Only the super user may.</summary>
/// <param name="actor">Who acts.</param>
/// <param name="id">The account.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public Task ResetTotpAsync(Actor actor, long id, CancellationToken cancellationToken = default) =>
ChangeAsync(actor, id, "user.totp-reset", AccountSecurity.ResetTotp, allowSelf: false, cancellationToken);
/// <summary>Links an administrator to a company user, to work as that user without a second sign-in.</summary>
/// <param name="actor">Who acts: the super user, or the administrator itself.</param>
/// <param name="id">The administrator.</param>
/// <param name="companyCode">The company, or <see langword="null"/> to remove the link.</param>
/// <param name="companyUserId">The company user.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public Task LinkAsync(Actor actor, long id, string? companyCode, long? companyUserId, CancellationToken cancellationToken = default) =>
ChangeAsync(
actor,
id,
"user.linked",
user =>
{
user.LinkedCompanyCode = companyCode is null ? null : CompanyCodes.Normalize(companyCode);
user.LinkedUserId = companyCode is null ? null : companyUserId;
},
allowSelf: true,
cancellationToken);
/// <summary>Deletes an administrator. Only the super user may; the super user itself cannot be deleted.</summary>
/// <param name="actor">Who acts.</param>
/// <param name="id">The account.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public async Task DeleteAsync(Actor actor, long id, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(actor);
RequireSuperUser(actor);
await using var unitOfWork = await _factory.CreateAsync(DatabaseScope.System, cancellationToken).ConfigureAwait(false);
var users = unitOfWork.Repository<SystemUser, long>();
var user = await users.GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException("No instance account has this identifier.");
if (user.Level == UserLevel.SuperUser)
{
throw new AccessDeniedException(SecurityErrors.LevelTooLow, "The super user cannot be deleted.");
}
await users.DeleteAsync(id, cancellationToken).ConfigureAwait(false);
await _audit.WriteAsync(new SecurityEvent("user.deleted", actor.UserName, Target: user.UserName), cancellationToken).ConfigureAwait(false);
}
/// <summary>Saves an account changed by the sign-in flow (failures, lockout, TOTP step, password).</summary>
/// <param name="user">The account.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public async Task SaveAsync(SystemUser user, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(user);
await using var unitOfWork = await _factory.CreateAsync(DatabaseScope.System, cancellationToken).ConfigureAwait(false);
await unitOfWork.Repository<SystemUser, long>().UpdateAsync(user, cancellationToken).ConfigureAwait(false);
}
private static SystemUser NewAccount(NewSystemUser account, UserLevel level) => new()
{
UserName = UserNames.Normalize(account.UserName),
DisplayName = string.IsNullOrWhiteSpace(account.DisplayName) ? account.UserName.Trim() : account.DisplayName.Trim(),
Email = string.IsNullOrWhiteSpace(account.Email) ? null : account.Email.Trim(),
Level = level,
IsActive = true,
};
private static void RequireSuperUser(Actor actor)
{
if (!actor.IsSuperUser)
{
throw new AccessDeniedException(SecurityErrors.LevelTooLow, "Only the super user manages administrators.");
}
}
private async Task ChangeAsync(Actor actor, long id, string action, Action<SystemUser> change, bool allowSelf, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(actor);
var self = actor.SystemUserId == id;
if (!actor.IsSuperUser && !(allowSelf && self))
{
throw new AccessDeniedException(SecurityErrors.LevelTooLow, "Only the super user manages other instance accounts.");
}
await using var unitOfWork = await _factory.CreateAsync(DatabaseScope.System, cancellationToken).ConfigureAwait(false);
var users = unitOfWork.Repository<SystemUser, long>();
var user = await users.GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException("No instance account has this identifier.");
change(user);
await users.UpdateAsync(user, cancellationToken).ConfigureAwait(false);
await _audit.WriteAsync(new SecurityEvent(action, actor.UserName, Target: user.UserName), cancellationToken).ConfigureAwait(false);
}
}
@@ -0,0 +1,274 @@
using Khaemhat.Application.Audit;
using Khaemhat.Core.Security;
using Khaemhat.Data;
using Khaemhat.Data.Querying;
namespace Khaemhat.Application.Security;
/// <summary>A new company user.</summary>
/// <param name="UserName">The sign-in name.</param>
/// <param name="DisplayName">The name shown.</param>
/// <param name="Email">The e-mail address.</param>
/// <param name="Kind">A person or a technical user for the API.</param>
/// <param name="Roles">The role codes.</param>
/// <param name="Flags">The per-user flags.</param>
public sealed record NewCompanyUser(string UserName, string DisplayName, string? Email, UserKind Kind, IReadOnlyList<string> Roles, UserFlags Flags);
/// <summary>
/// Company users (<c>users</c>, SPEC §7.1): created by instance accounts or by company users holding
/// <c>company.users.manage</c>, who can never give roles above their own permissions.
/// </summary>
public sealed class UserService(IUnitOfWorkFactory factory, AccountSecurity security, PermissionService permissions, RoleService roles, ISecurityAuditLog audit)
{
/// <summary>Lists the users of a company.</summary>
/// <param name="companyCode">The company.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The users by name.</returns>
public async Task<IReadOnlyList<CompanyUser>> ListAsync(string companyCode, CancellationToken cancellationToken = default)
{
await using var unitOfWork = await factory.CreateAsync(DatabaseScope.Company(companyCode), cancellationToken).ConfigureAwait(false);
return (await unitOfWork.Repository<CompanyUser, long>().ListAsync(Query.For<CompanyUser>().OrderBy(u => u.UserName), cancellationToken).ConfigureAwait(false)).Items;
}
/// <summary>Finds a user by sign-in name.</summary>
/// <param name="companyCode">The company.</param>
/// <param name="userName">The name, in any case.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The user, or <see langword="null"/>.</returns>
public async Task<CompanyUser?> FindByNameAsync(string companyCode, string userName, CancellationToken cancellationToken = default)
{
if (!UserNames.IsValid(userName))
{
return null;
}
var name = UserNames.Normalize(userName);
await using var unitOfWork = await factory.CreateAsync(DatabaseScope.Company(companyCode), cancellationToken).ConfigureAwait(false);
return await unitOfWork.Repository<CompanyUser, long>().FindAsync(Query.For<CompanyUser>().Where(u => u.UserName == name), cancellationToken).ConfigureAwait(false);
}
/// <summary>Finds a user.</summary>
/// <param name="companyCode">The company.</param>
/// <param name="id">The identifier.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The user, or <see langword="null"/>.</returns>
public async Task<CompanyUser?> GetAsync(string companyCode, long id, CancellationToken cancellationToken = default)
{
await using var unitOfWork = await factory.CreateAsync(DatabaseScope.Company(companyCode), cancellationToken).ConfigureAwait(false);
return await unitOfWork.Repository<CompanyUser, long>().GetAsync(id, cancellationToken).ConfigureAwait(false);
}
/// <summary>Creates a user with a temporary password (people) or none (technical users).</summary>
/// <param name="actor">Who acts.</param>
/// <param name="companyCode">The company.</param>
/// <param name="request">The user.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The user and its temporary password (<see langword="null"/> for technical users).</returns>
public async Task<(CompanyUser User, string? TemporaryPassword)> CreateAsync(
Actor actor, string companyCode, NewCompanyUser request, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(request);
await roles.DemandManageAsync(actor, companyCode, cancellationToken).ConfigureAwait(false);
var user = new CompanyUser
{
UserName = UserNames.Normalize(request.UserName),
DisplayName = string.IsNullOrWhiteSpace(request.DisplayName) ? request.UserName.Trim() : request.DisplayName.Trim(),
Email = string.IsNullOrWhiteSpace(request.Email) ? null : request.Email.Trim(),
Kind = request.Kind,
IsActive = true,
OwnCustomersOnly = request.Flags.OwnCustomersOnly,
CanSeeCosts = request.Flags.CanSeeCosts,
CanExport = request.Flags.CanExport,
CanUseApi = request.Kind == UserKind.Technical || request.Flags.CanUseApi,
TotpRequired = security.Options.TotpRequiredForUsers,
};
var password = request.Kind == UserKind.Human ? security.IssueTemporaryPassword(user) : null;
await using var unitOfWork = await factory.CreateAsync(DatabaseScope.Company(companyCode), cancellationToken).ConfigureAwait(false);
var users = unitOfWork.Repository<CompanyUser, long>();
await unitOfWork.InTransactionAsync(
async ct =>
{
if (await users.CountAsync(Query.For<CompanyUser>().Where(u => u.UserName == user.UserName), ct).ConfigureAwait(false) > 0)
{
throw new ValidationFailedException(["user_name_taken"]);
}
user.Id = await users.InsertAsync(user, ct).ConfigureAwait(false);
await AssignRolesAsync(unitOfWork, actor, user.Id, request.Roles, ct).ConfigureAwait(false);
},
cancellationToken).ConfigureAwait(false);
await audit.WriteAsync(new SecurityEvent("user.created", actor.UserName, companyCode, user.UserName, new { roles = request.Roles, kind = request.Kind.ToString() }), cancellationToken)
.ConfigureAwait(false);
return (user, password);
}
/// <summary>Replaces the roles of a user.</summary>
/// <param name="actor">Who acts.</param>
/// <param name="companyCode">The company.</param>
/// <param name="userId">The user.</param>
/// <param name="roleCodes">The role codes.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public async Task SetRolesAsync(Actor actor, string companyCode, long userId, IReadOnlyList<string> roleCodes, CancellationToken cancellationToken = default)
{
await roles.DemandManageAsync(actor, companyCode, cancellationToken).ConfigureAwait(false);
await using var unitOfWork = await factory.CreateAsync(DatabaseScope.Company(companyCode), cancellationToken).ConfigureAwait(false);
await unitOfWork.InTransactionAsync(ct => AssignRolesAsync(unitOfWork, actor, userId, roleCodes, ct), cancellationToken).ConfigureAwait(false);
await permissions.InvalidateAsync(companyCode, cancellationToken).ConfigureAwait(false);
await audit.WriteAsync(new SecurityEvent("user.roles-changed", actor.UserName, companyCode, userId.ToString(System.Globalization.CultureInfo.InvariantCulture), new { roles = roleCodes }), cancellationToken)
.ConfigureAwait(false);
}
/// <summary>Grants or denies single permissions to a user over its roles. Denials win.</summary>
/// <param name="actor">Who acts.</param>
/// <param name="companyCode">The company.</param>
/// <param name="userId">The user.</param>
/// <param name="overrides">Permission code and whether it is allowed.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public async Task SetOverridesAsync(Actor actor, string companyCode, long userId, IReadOnlyDictionary<string, bool> overrides, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(overrides);
await roles.DemandManageAsync(actor, companyCode, cancellationToken).ConfigureAwait(false);
if (!await permissions.CoversAsync(actor, overrides.Where(o => o.Value).Select(o => o.Key), cancellationToken).ConfigureAwait(false))
{
throw new AccessDeniedException(SecurityErrors.PermissionDenied, "A user cannot grant permissions it does not hold.");
}
await using var unitOfWork = await factory.CreateAsync(DatabaseScope.Company(companyCode), cancellationToken).ConfigureAwait(false);
var repository = unitOfWork.Repository<UserPermissionOverride, long>();
await unitOfWork.InTransactionAsync(
async ct =>
{
foreach (var old in (await repository.ListAsync(Query.For<UserPermissionOverride>().Where(o => o.UserId == userId), ct).ConfigureAwait(false)).Items)
{
await repository.DeleteAsync(old.Id, ct).ConfigureAwait(false);
}
foreach (var (code, allowed) in overrides)
{
await repository.InsertAsync(new UserPermissionOverride { UserId = userId, Permission = code, Allowed = allowed }, ct).ConfigureAwait(false);
}
},
cancellationToken).ConfigureAwait(false);
await permissions.InvalidateAsync(companyCode, cancellationToken).ConfigureAwait(false);
await audit.WriteAsync(new SecurityEvent("user.overrides-changed", actor.UserName, companyCode, userId.ToString(System.Globalization.CultureInfo.InvariantCulture), overrides), cancellationToken)
.ConfigureAwait(false);
}
/// <summary>Changes name, e-mail, flags and state of a user.</summary>
/// <param name="actor">Who acts.</param>
/// <param name="companyCode">The company.</param>
/// <param name="userId">The user.</param>
/// <param name="displayName">The name.</param>
/// <param name="email">The e-mail.</param>
/// <param name="flags">The flags.</param>
/// <param name="isActive">Whether it can sign in.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public async Task UpdateAsync(
Actor actor, string companyCode, long userId, string displayName, string? email, UserFlags flags, bool isActive, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(flags);
ArgumentException.ThrowIfNullOrWhiteSpace(displayName);
await ChangeAsync(actor, companyCode, userId, "user.updated", user =>
{
user.DisplayName = displayName.Trim();
user.Email = string.IsNullOrWhiteSpace(email) ? null : email.Trim();
user.OwnCustomersOnly = flags.OwnCustomersOnly;
user.CanSeeCosts = flags.CanSeeCosts;
user.CanExport = flags.CanExport;
user.CanUseApi = user.Kind == UserKind.Technical || flags.CanUseApi;
user.IsActive = isActive;
}, cancellationToken).ConfigureAwait(false);
}
/// <summary>Gives a user a new temporary password.</summary>
/// <param name="actor">Who acts.</param>
/// <param name="companyCode">The company.</param>
/// <param name="userId">The user.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The temporary password.</returns>
public async Task<string> ResetPasswordAsync(Actor actor, string companyCode, long userId, CancellationToken cancellationToken = default)
{
string? password = null;
await ChangeAsync(actor, companyCode, userId, "user.password-reset", user =>
{
if (user.Kind == UserKind.Technical)
{
throw new ValidationFailedException(["technical_user_has_no_password"]);
}
password = security.IssueTemporaryPassword(user);
}, cancellationToken).ConfigureAwait(false);
return password!;
}
/// <summary>Turns off the two-step verification of a user who lost the phone.</summary>
/// <param name="actor">Who acts.</param>
/// <param name="companyCode">The company.</param>
/// <param name="userId">The user.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public Task ResetTotpAsync(Actor actor, string companyCode, long userId, CancellationToken cancellationToken = default) =>
ChangeAsync(actor, companyCode, userId, "user.totp-reset", AccountSecurity.ResetTotp, cancellationToken);
/// <summary>Saves a user changed by the sign-in flow.</summary>
/// <param name="companyCode">The company.</param>
/// <param name="user">The user.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public async Task SaveAsync(string companyCode, CompanyUser user, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(user);
await using var unitOfWork = await factory.CreateAsync(DatabaseScope.Company(companyCode), cancellationToken).ConfigureAwait(false);
await unitOfWork.Repository<CompanyUser, long>().UpdateAsync(user, cancellationToken).ConfigureAwait(false);
}
private async Task ChangeAsync(Actor actor, string companyCode, long userId, string action, Action<CompanyUser> change, CancellationToken cancellationToken)
{
await roles.DemandManageAsync(actor, companyCode, cancellationToken).ConfigureAwait(false);
await using var unitOfWork = await factory.CreateAsync(DatabaseScope.Company(companyCode), cancellationToken).ConfigureAwait(false);
var users = unitOfWork.Repository<CompanyUser, long>();
var user = await users.GetAsync(userId, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException("No user has this identifier.");
change(user);
await users.UpdateAsync(user, cancellationToken).ConfigureAwait(false);
await permissions.InvalidateAsync(companyCode, cancellationToken).ConfigureAwait(false);
await audit.WriteAsync(new SecurityEvent(action, actor.UserName, companyCode, user.UserName), cancellationToken).ConfigureAwait(false);
}
private async Task AssignRolesAsync(IUnitOfWork unitOfWork, Actor actor, long userId, IReadOnlyList<string> roleCodes, CancellationToken cancellationToken)
{
var codes = roleCodes.Select(r => r.Trim().ToUpperInvariant()).Distinct(StringComparer.Ordinal).ToArray();
var found = codes.Length == 0
? []
: (await unitOfWork.Repository<Role, long>().ListAsync(Query.For<Role>().Where(r => codes.Contains(r.Code)), cancellationToken).ConfigureAwait(false)).Items;
if (found.Count != codes.Length)
{
throw new ValidationFailedException(["role_unknown"]);
}
var roleIds = found.Select(r => r.Id).ToArray();
var patterns = roleIds.Length == 0
? []
: (await unitOfWork.Repository<RoleGrant, long>().ListAsync(Query.For<RoleGrant>().Where(g => roleIds.Contains(g.RoleId)), cancellationToken).ConfigureAwait(false)).Items
.Select(g => g.Permission);
if (!await permissions.CoversAsync(actor, patterns, cancellationToken).ConfigureAwait(false))
{
throw new AccessDeniedException(SecurityErrors.PermissionDenied, "A user cannot assign roles above its own permissions.");
}
var userRoles = unitOfWork.Repository<UserRole, long>();
foreach (var old in (await userRoles.ListAsync(Query.For<UserRole>().Where(r => r.UserId == userId), cancellationToken).ConfigureAwait(false)).Items)
{
await userRoles.DeleteAsync(old.Id, cancellationToken).ConfigureAwait(false);
}
foreach (var roleId in roleIds)
{
await userRoles.InsertAsync(new UserRole { UserId = userId, RoleId = roleId }, cancellationToken).ConfigureAwait(false);
}
}
}