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
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:
1 parent
4582837b70
commit
032c602b49
107 files changed
+12202
-116
No files matched your search
@@ -0,0 +1,124 @@
|
||||
using System.Diagnostics;
|
||||
using System.Globalization;
|
||||
using System.Reflection;
|
||||
using System.Text.Json;
|
||||
using Khaemhat.Core.Entities;
|
||||
using Khaemhat.Core.Instance;
|
||||
using Khaemhat.Data;
|
||||
using Khaemhat.Data.Querying;
|
||||
|
||||
namespace Khaemhat.Application.Audit;
|
||||
|
||||
/// <summary>What happened to a record.</summary>
|
||||
public enum AuditAction
|
||||
{
|
||||
/// <summary>Created.</summary>
|
||||
Insert = 0,
|
||||
|
||||
/// <summary>Changed.</summary>
|
||||
Update = 1,
|
||||
|
||||
/// <summary>Deleted.</summary>
|
||||
Delete = 2,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The history of the records of a company (SPEC §7.4): every insert, update and delete of master data, documents,
|
||||
/// entries and settings writes a row in the company's <c>audit_log</c>, in the same unit of work as the change, with the
|
||||
/// changed fields as JSON <c>{"Field": [old, new]}</c>. Audit columns and secrets are never written.
|
||||
/// </summary>
|
||||
public sealed class AuditTrail(TimeProvider clock)
|
||||
{
|
||||
private static readonly HashSet<string> Skipped = new(StringComparer.Ordinal)
|
||||
{
|
||||
nameof(IAuditable.CreatedAt), nameof(IAuditable.CreatedBy), nameof(IAuditable.UpdatedAt), nameof(IAuditable.UpdatedBy), "RowVersion",
|
||||
"PasswordHash", "PasswordHistory", "TotpSecret", "TotpRecoveryCodes", "RecoveryTokenHash", "TokenHash", "ConnectionString",
|
||||
};
|
||||
|
||||
/// <summary>Writes the history row of a change, inside the caller's unit of work.</summary>
|
||||
/// <typeparam name="T">The entity type.</typeparam>
|
||||
/// <param name="unitOfWork">The company unit of work holding the change.</param>
|
||||
/// <param name="action">What happened.</param>
|
||||
/// <param name="entityId">The record.</param>
|
||||
/// <param name="before">The record before (updates and deletes).</param>
|
||||
/// <param name="after">The record after (inserts and updates).</param>
|
||||
/// <param name="userName">Who did it.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns><see langword="true"/> when a row was written (an update that changes nothing writes none).</returns>
|
||||
public async Task<bool> RecordAsync<T>(
|
||||
IUnitOfWork unitOfWork, AuditAction action, object entityId, T? before, T? after, string? userName, CancellationToken cancellationToken = default)
|
||||
where T : class
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(unitOfWork);
|
||||
ArgumentNullException.ThrowIfNull(entityId);
|
||||
var diff = Diff(before, after);
|
||||
if (action == AuditAction.Update && diff.Count == 0)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
await unitOfWork.Repository<AuditEntry, long>().InsertAsync(
|
||||
new AuditEntry
|
||||
{
|
||||
At = clock.GetUtcNow().UtcDateTime,
|
||||
Entity = typeof(T).Name,
|
||||
EntityId = Convert.ToString(entityId, CultureInfo.InvariantCulture) ?? string.Empty,
|
||||
Action = action.ToString(),
|
||||
UserName = userName,
|
||||
Diff = JsonSerializer.Serialize(diff),
|
||||
TraceId = Activity.Current?.TraceId.ToString(),
|
||||
},
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>The history of a record, newest first (the "Storico" panel).</summary>
|
||||
/// <param name="unitOfWork">A company unit of work.</param>
|
||||
/// <param name="entity">The entity name.</param>
|
||||
/// <param name="entityId">The record.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The rows.</returns>
|
||||
public static async Task<IReadOnlyList<AuditEntry>> HistoryAsync(IUnitOfWork unitOfWork, string entity, string entityId, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(unitOfWork);
|
||||
return (await unitOfWork.Repository<AuditEntry, long>().ListAsync(
|
||||
Query.For<AuditEntry>().Where(a => a.Entity == entity && a.EntityId == entityId).OrderByDescending(a => a.Id), cancellationToken).ConfigureAwait(false)).Items;
|
||||
}
|
||||
|
||||
/// <summary>The changed fields between two versions of a record.</summary>
|
||||
/// <typeparam name="T">The entity type.</typeparam>
|
||||
/// <param name="before">The old version, or <see langword="null"/>.</param>
|
||||
/// <param name="after">The new version, or <see langword="null"/>.</param>
|
||||
/// <returns>Field name to <c>[old, new]</c>.</returns>
|
||||
public static IReadOnlyDictionary<string, object?[]> Diff<T>(T? before, T? after)
|
||||
where T : class
|
||||
{
|
||||
var result = new SortedDictionary<string, object?[]>(StringComparer.Ordinal);
|
||||
foreach (var property in typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance))
|
||||
{
|
||||
if (!property.CanRead || property.GetIndexParameters().Length > 0 || Skipped.Contains(property.Name))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var old = before is null ? null : Simple(property.GetValue(before));
|
||||
var current = after is null ? null : Simple(property.GetValue(after));
|
||||
if (!Equals(old, current))
|
||||
{
|
||||
result[property.Name] = [old, current];
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
private static object? Simple(object? value) => value switch
|
||||
{
|
||||
null => null,
|
||||
string or bool or int or long or decimal or double => value,
|
||||
DateTime date => date.ToString("O", CultureInfo.InvariantCulture),
|
||||
Enum e => e.ToString(),
|
||||
IFormattable formattable => formattable.ToString(null, CultureInfo.InvariantCulture),
|
||||
_ => value.ToString(),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
using System.Globalization;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using Khaemhat.Core.Instance;
|
||||
using Khaemhat.Data;
|
||||
using Khaemhat.Data.Querying;
|
||||
|
||||
namespace Khaemhat.Application.Audit;
|
||||
|
||||
/// <summary>A security or instance action to record.</summary>
|
||||
/// <param name="Action">The action code, for example <c>login.succeeded</c>, <c>user.created</c>, <c>license.activated</c>.</param>
|
||||
/// <param name="UserName">Who acted.</param>
|
||||
/// <param name="CompanyCode">The company concerned.</param>
|
||||
/// <param name="Target">What the action was about.</param>
|
||||
/// <param name="Details">Further details, serialized as JSON (never secrets).</param>
|
||||
/// <param name="IpAddress">The client address.</param>
|
||||
public sealed record SecurityEvent(
|
||||
string Action, string? UserName, string? CompanyCode = null, string? Target = null, object? Details = null, string? IpAddress = null);
|
||||
|
||||
/// <summary>Writes <c>sys_security_audit</c>.</summary>
|
||||
public interface ISecurityAuditLog
|
||||
{
|
||||
/// <summary>Records an action.</summary>
|
||||
/// <param name="securityEvent">The action.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>A task.</returns>
|
||||
Task WriteAsync(SecurityEvent securityEvent, CancellationToken cancellationToken = default);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The immutable security audit (SPEC §7.3): rows are only inserted, each with the SHA-256 of its content chained to
|
||||
/// the previous row, under an application lock so that two writers never fork the chain. <see cref="VerifyAsync"/>
|
||||
/// finds a changed or removed row.
|
||||
/// </summary>
|
||||
/// <param name="factory">Opens the system database.</param>
|
||||
/// <param name="clock">The clock.</param>
|
||||
public sealed class SecurityAuditLog(IUnitOfWorkFactory factory, TimeProvider clock) : ISecurityAuditLog
|
||||
{
|
||||
private const string LockKey = "security-audit";
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task WriteAsync(SecurityEvent securityEvent, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(securityEvent);
|
||||
var entry = new SecurityAuditEntry
|
||||
{
|
||||
At = Truncate(clock.GetUtcNow().UtcDateTime),
|
||||
Action = Clip(securityEvent.Action, 100)!,
|
||||
UserName = Clip(securityEvent.UserName, 100),
|
||||
CompanyCode = Clip(securityEvent.CompanyCode, 20),
|
||||
Target = Clip(securityEvent.Target, 200),
|
||||
IpAddress = Clip(securityEvent.IpAddress, 64),
|
||||
Details = securityEvent.Details is null ? null : JsonSerializer.Serialize(securityEvent.Details),
|
||||
};
|
||||
|
||||
await using var unitOfWork = await factory.CreateAsync(DatabaseScope.System, cancellationToken).ConfigureAwait(false);
|
||||
await unitOfWork.InTransactionAsync(
|
||||
async ct =>
|
||||
{
|
||||
await unitOfWork.AcquireLockAsync(LockKey, ct).ConfigureAwait(false);
|
||||
var repository = unitOfWork.Repository<SecurityAuditEntry, long>();
|
||||
var last = await repository.FindAsync(Query.For<SecurityAuditEntry>().OrderByDescending(e => e.Id).Take(1), ct).ConfigureAwait(false);
|
||||
entry.PreviousHash = last?.Hash ?? string.Empty;
|
||||
entry.Hash = ComputeHash(entry);
|
||||
await repository.InsertAsync(entry, ct).ConfigureAwait(false);
|
||||
},
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>Checks the whole chain.</summary>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The identifier of the first row that does not match, or <see langword="null"/> when the chain is intact.</returns>
|
||||
public async Task<long?> VerifyAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
await using var unitOfWork = await factory.CreateAsync(DatabaseScope.System, cancellationToken).ConfigureAwait(false);
|
||||
var previous = string.Empty;
|
||||
const int PageSize = 1000;
|
||||
for (var offset = 0; ; offset += PageSize)
|
||||
{
|
||||
var page = await unitOfWork.Repository<SecurityAuditEntry, long>()
|
||||
.ListAsync(Query.For<SecurityAuditEntry>().OrderBy(e => e.Id).Page(offset, PageSize), cancellationToken).ConfigureAwait(false);
|
||||
foreach (var entry in page.Items)
|
||||
{
|
||||
if (entry.PreviousHash != previous || entry.Hash != ComputeHash(entry))
|
||||
{
|
||||
return entry.Id;
|
||||
}
|
||||
|
||||
previous = entry.Hash;
|
||||
}
|
||||
|
||||
if (page.Items.Count < PageSize)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The hash of a row: every field and the previous hash, separated so that fields cannot run into each other.</summary>
|
||||
/// <param name="entry">The row.</param>
|
||||
/// <returns>64 hexadecimal digits.</returns>
|
||||
public static string ComputeHash(SecurityAuditEntry entry)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(entry);
|
||||
var content = string.Join(
|
||||
'\u001F',
|
||||
entry.PreviousHash,
|
||||
DateTime.SpecifyKind(entry.At, DateTimeKind.Utc).ToString("yyyy-MM-ddTHH:mm:ss.ffffffZ", CultureInfo.InvariantCulture),
|
||||
entry.Action,
|
||||
entry.UserName ?? string.Empty,
|
||||
entry.CompanyCode ?? string.Empty,
|
||||
entry.IpAddress ?? string.Empty,
|
||||
entry.Target ?? string.Empty,
|
||||
entry.Details ?? string.Empty);
|
||||
return Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(content)));
|
||||
}
|
||||
|
||||
private static DateTime Truncate(DateTime value) => DateTime.SpecifyKind(new DateTime(value.Ticks - (value.Ticks % 10)), DateTimeKind.Utc);
|
||||
|
||||
private static string? Clip(string? value, int length) => value is null || value.Length <= length ? value : value[..length];
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
namespace Khaemhat.Application.Configuration;
|
||||
|
||||
/// <summary>
|
||||
/// Reads the <c>KHAEMHAT_*</c> variables of SPEC §6 into <see cref="KhaemhatOptions"/>, applying the <c>_FILE</c>
|
||||
/// rule of ADR 0014 to the sensitive ones: when <c>X_FILE</c> is set, the value of <c>X</c> is the content of that file
|
||||
/// without the final line break; setting both is a configuration error, and so is a file that cannot be read.
|
||||
/// Problems are collected in <see cref="KhaemhatOptions.ReadErrors"/>; values never appear in messages.
|
||||
/// </summary>
|
||||
public sealed class EnvironmentConfigurationReader
|
||||
{
|
||||
/// <summary>The variables that accept a <c>_FILE</c> variant (ADR 0014).</summary>
|
||||
public static readonly IReadOnlySet<string> FileVariables = new HashSet<string>(StringComparer.Ordinal)
|
||||
{
|
||||
"KHAEMHAT_SYSTEM_DB", "KHAEMHAT_DB_SERVER", "KHAEMHAT_SECRET_KEY", "KHAEMHAT_SECRET_KEY_NEW",
|
||||
"KHAEMHAT_SUPERUSER", "KHAEMHAT_SUPERUSER_PASSWORD", "KHAEMHAT_SUPERUSER_EMAIL", "KHAEMHAT_LICENSE",
|
||||
"KHAEMHAT_REDIS", "KHAEMHAT_SMTP_PASSWORD", "KHAEMHAT_UPDATE_TOKEN",
|
||||
};
|
||||
|
||||
private readonly Func<string, string?> _lookup;
|
||||
private readonly Func<string, string> _readFile;
|
||||
|
||||
/// <summary>Creates a reader.</summary>
|
||||
/// <param name="lookup">Returns a variable, or <see langword="null"/> when unset (the host configuration: environment and command line).</param>
|
||||
/// <param name="readFile">Reads a secret file; the default reads from disk.</param>
|
||||
public EnvironmentConfigurationReader(Func<string, string?> lookup, Func<string, string>? readFile = null)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(lookup);
|
||||
_lookup = lookup;
|
||||
_readFile = readFile ?? File.ReadAllText;
|
||||
}
|
||||
|
||||
/// <summary>Reads every variable.</summary>
|
||||
/// <returns>The options, with the reading problems in <see cref="KhaemhatOptions.ReadErrors"/>.</returns>
|
||||
public KhaemhatOptions Read()
|
||||
{
|
||||
var errors = new List<string>();
|
||||
string? Get(string name) => Value(name, errors);
|
||||
|
||||
return new KhaemhatOptions
|
||||
{
|
||||
SystemDb = Get("KHAEMHAT_SYSTEM_DB"),
|
||||
DbServer = Get("KHAEMHAT_DB_SERVER"),
|
||||
SecretKey = Get("KHAEMHAT_SECRET_KEY"),
|
||||
RotationSecretKey = Get("KHAEMHAT_SECRET_KEY_NEW"),
|
||||
SuperUser = Get("KHAEMHAT_SUPERUSER"),
|
||||
SuperUserPassword = Get("KHAEMHAT_SUPERUSER_PASSWORD"),
|
||||
SuperUserEmail = Get("KHAEMHAT_SUPERUSER_EMAIL"),
|
||||
CompanyCode = Get("KHAEMHAT_COMPANY_CODE"),
|
||||
CompanyName = Get("KHAEMHAT_COMPANY_NAME"),
|
||||
Country = Get("KHAEMHAT_COUNTRY") ?? "IT",
|
||||
LicenseMode = Get("KHAEMHAT_LICENSE_MODE") ?? "production",
|
||||
License = Get("KHAEMHAT_LICENSE"),
|
||||
Redis = Get("KHAEMHAT_REDIS"),
|
||||
DataDir = Get("KHAEMHAT_DATA_DIR") ?? "/data",
|
||||
Urls = Get("KHAEMHAT_URLS"),
|
||||
PublicUrl = Get("KHAEMHAT_PUBLIC_URL"),
|
||||
SmtpHost = Get("KHAEMHAT_SMTP_HOST"),
|
||||
SmtpPort = Get("KHAEMHAT_SMTP_PORT"),
|
||||
SmtpUser = Get("KHAEMHAT_SMTP_USER"),
|
||||
SmtpPassword = Get("KHAEMHAT_SMTP_PASSWORD"),
|
||||
SmtpFrom = Get("KHAEMHAT_SMTP_FROM"),
|
||||
SmtpSecurity = Get("KHAEMHAT_SMTP_SECURITY"),
|
||||
LogLevel = Get("KHAEMHAT_LOG_LEVEL"),
|
||||
SeedBase = Get("KHAEMHAT_SEED_BASE"),
|
||||
SeedDemo = Get("KHAEMHAT_SEED_DEMO"),
|
||||
UpdateFeed = Get("KHAEMHAT_UPDATE_FEED"),
|
||||
UpdateToken = Get("KHAEMHAT_UPDATE_TOKEN"),
|
||||
TimeZone = Get("TZ"),
|
||||
ReadErrors = errors,
|
||||
};
|
||||
}
|
||||
|
||||
private string? Value(string name, List<string> errors)
|
||||
{
|
||||
var direct = Normalize(_lookup(name));
|
||||
if (!FileVariables.Contains(name))
|
||||
{
|
||||
return direct;
|
||||
}
|
||||
|
||||
var path = Normalize(_lookup(name + "_FILE"));
|
||||
if (path is null)
|
||||
{
|
||||
return direct;
|
||||
}
|
||||
|
||||
if (direct is not null)
|
||||
{
|
||||
errors.Add($"{name} and {name}_FILE are both set: keep only one of them.");
|
||||
return null;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
return Normalize(TrimFinalLineBreak(_readFile(path)));
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or ArgumentException or NotSupportedException)
|
||||
{
|
||||
errors.Add($"{name}_FILE points to a file that cannot be read ({ex.GetType().Name}): check the path and the permissions of the secret.");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static string? Normalize(string? value) => string.IsNullOrWhiteSpace(value) ? null : value;
|
||||
|
||||
private static string TrimFinalLineBreak(string value)
|
||||
{
|
||||
if (value.EndsWith("\r\n", StringComparison.Ordinal))
|
||||
{
|
||||
return value[..^2];
|
||||
}
|
||||
|
||||
return value.EndsWith('\n') ? value[..^1] : value;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,356 @@
|
||||
using System.Globalization;
|
||||
using System.Net.Mail;
|
||||
using Khaemhat.Application.Security;
|
||||
using Khaemhat.Data;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace Khaemhat.Application.Configuration;
|
||||
|
||||
/// <summary>How the licences behave (<c>KHAEMHAT_LICENSE_MODE</c>).</summary>
|
||||
public enum LicenseMode
|
||||
{
|
||||
/// <summary>Only signed licences count.</summary>
|
||||
Production = 0,
|
||||
|
||||
/// <summary>The fictitious codes of SPEC §8.3 are accepted too. Never in production.</summary>
|
||||
Test = 1,
|
||||
}
|
||||
|
||||
/// <summary>The connection security of the mail server.</summary>
|
||||
public enum SmtpSecurity
|
||||
{
|
||||
/// <summary>STARTTLS on a plain connection (port 587).</summary>
|
||||
StartTls = 0,
|
||||
|
||||
/// <summary>TLS from the start (port 465).</summary>
|
||||
Ssl = 1,
|
||||
|
||||
/// <summary>No encryption: only for a local relay.</summary>
|
||||
None = 2,
|
||||
}
|
||||
|
||||
/// <summary>A configuration that does not let the instance start. The message lists every problem, never a value.</summary>
|
||||
public sealed class ConfigurationException : Exception
|
||||
{
|
||||
/// <summary>Creates the exception.</summary>
|
||||
public ConfigurationException()
|
||||
: this([])
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>Creates the exception.</summary>
|
||||
/// <param name="message">The message.</param>
|
||||
public ConfigurationException(string message)
|
||||
: base(message) => Errors = [message];
|
||||
|
||||
/// <summary>Creates the exception.</summary>
|
||||
/// <param name="message">The message.</param>
|
||||
/// <param name="innerException">The cause.</param>
|
||||
public ConfigurationException(string message, Exception innerException)
|
||||
: base(message, innerException) => Errors = [message];
|
||||
|
||||
/// <summary>Creates the exception from a list of problems.</summary>
|
||||
/// <param name="errors">The problems.</param>
|
||||
public ConfigurationException(IReadOnlyList<string> errors)
|
||||
: base(Describe(errors)) => Errors = errors;
|
||||
|
||||
/// <summary>The problems, one per line of the message.</summary>
|
||||
public IReadOnlyList<string> Errors { get; }
|
||||
|
||||
private static string Describe(IReadOnlyList<string> errors) =>
|
||||
"Khaemhat cannot start: the configuration is not valid (see docs/DEPLOY.md and the wiki page Installazione-Docker)."
|
||||
+ string.Concat((errors ?? []).Select(e => Environment.NewLine + " - " + e));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The instance configuration of SPEC §6, read from the environment by <see cref="EnvironmentConfigurationReader"/>.
|
||||
/// Values stay in memory: nothing is written to disk. <see cref="Validate"/> checks everything before the host starts;
|
||||
/// the typed accessors (<see cref="SystemDatabase"/>, <see cref="Mode"/>...) are meant for a validated instance.
|
||||
/// </summary>
|
||||
public sealed class KhaemhatOptions
|
||||
{
|
||||
/// <summary><c>KHAEMHAT_SYSTEM_DB</c>: the system database URL (required).</summary>
|
||||
public string? SystemDb { get; init; }
|
||||
|
||||
/// <summary><c>KHAEMHAT_DB_SERVER</c>: the PostgreSQL server where company databases are created.</summary>
|
||||
public string? DbServer { get; init; }
|
||||
|
||||
/// <summary><c>KHAEMHAT_SECRET_KEY</c>: base64 of at least 32 bytes (required).</summary>
|
||||
public string? SecretKey { get; init; }
|
||||
|
||||
/// <summary><c>KHAEMHAT_SECRET_KEY_NEW</c>: the new key during a rotation (SPEC §12.9).</summary>
|
||||
public string? RotationSecretKey { get; init; }
|
||||
|
||||
/// <summary><c>KHAEMHAT_SUPERUSER</c>: the super user name, read only while <c>sys_users</c> is empty.</summary>
|
||||
public string? SuperUser { get; init; }
|
||||
|
||||
/// <summary><c>KHAEMHAT_SUPERUSER_PASSWORD</c>: its first password, to change at the first access.</summary>
|
||||
public string? SuperUserPassword { get; init; }
|
||||
|
||||
/// <summary><c>KHAEMHAT_SUPERUSER_EMAIL</c>: its e-mail address.</summary>
|
||||
public string? SuperUserEmail { get; init; }
|
||||
|
||||
/// <summary><c>KHAEMHAT_COMPANY_CODE</c>: the first company, read only while <c>sys_companies</c> is empty.</summary>
|
||||
public string? CompanyCode { get; init; }
|
||||
|
||||
/// <summary><c>KHAEMHAT_COMPANY_NAME</c>: its name.</summary>
|
||||
public string? CompanyName { get; init; }
|
||||
|
||||
/// <summary><c>KHAEMHAT_COUNTRY</c>: the fiscal package of the first company (default <c>IT</c>).</summary>
|
||||
public string Country { get; init; } = "IT";
|
||||
|
||||
/// <summary><c>KHAEMHAT_LICENSE_MODE</c>: <c>production</c> (default) or <c>test</c>.</summary>
|
||||
public string LicenseMode { get; init; } = "production";
|
||||
|
||||
/// <summary><c>KHAEMHAT_LICENSE</c>: the text of a <c>.khl</c> licence; absent means Trial.</summary>
|
||||
public string? License { get; init; }
|
||||
|
||||
/// <summary><c>KHAEMHAT_REDIS</c>: <c>redis://</c> or <c>rediss://</c>; absent means in-memory cache.</summary>
|
||||
public string? Redis { get; init; }
|
||||
|
||||
/// <summary><c>KHAEMHAT_DATA_DIR</c>: the only folder the instance writes to (default <c>/data</c>).</summary>
|
||||
public string DataDir { get; init; } = "/data";
|
||||
|
||||
/// <summary><c>KHAEMHAT_URLS</c>: the listening addresses.</summary>
|
||||
public string? Urls { get; init; }
|
||||
|
||||
/// <summary><c>KHAEMHAT_PUBLIC_URL</c>: the address users reach, for links in e-mails.</summary>
|
||||
public string? PublicUrl { get; init; }
|
||||
|
||||
/// <summary><c>KHAEMHAT_SMTP_HOST</c>.</summary>
|
||||
public string? SmtpHost { get; init; }
|
||||
|
||||
/// <summary><c>KHAEMHAT_SMTP_PORT</c>.</summary>
|
||||
public string? SmtpPort { get; init; }
|
||||
|
||||
/// <summary><c>KHAEMHAT_SMTP_USER</c>.</summary>
|
||||
public string? SmtpUser { get; init; }
|
||||
|
||||
/// <summary><c>KHAEMHAT_SMTP_PASSWORD</c>.</summary>
|
||||
public string? SmtpPassword { get; init; }
|
||||
|
||||
/// <summary><c>KHAEMHAT_SMTP_FROM</c>.</summary>
|
||||
public string? SmtpFrom { get; init; }
|
||||
|
||||
/// <summary><c>KHAEMHAT_SMTP_SECURITY</c>: <c>starttls</c> (default), <c>ssl</c> or <c>none</c>.</summary>
|
||||
public string? SmtpSecurity { get; init; }
|
||||
|
||||
/// <summary><c>KHAEMHAT_LOG_LEVEL</c>: the minimum level on stdout.</summary>
|
||||
public string? LogLevel { get; init; }
|
||||
|
||||
/// <summary><c>KHAEMHAT_SEED_BASE</c>: load the base tables when a company is created (default true).</summary>
|
||||
public string? SeedBase { get; init; }
|
||||
|
||||
/// <summary><c>KHAEMHAT_SEED_DEMO</c>: load the demo data into an empty company (default false).</summary>
|
||||
public string? SeedDemo { get; init; }
|
||||
|
||||
/// <summary><c>KHAEMHAT_UPDATE_FEED</c>: the package list read by the update check.</summary>
|
||||
public string? UpdateFeed { get; init; }
|
||||
|
||||
/// <summary><c>KHAEMHAT_UPDATE_TOKEN</c>: a read-only token for the feed.</summary>
|
||||
public string? UpdateToken { get; init; }
|
||||
|
||||
/// <summary><c>TZ</c>: the time zone of the container.</summary>
|
||||
public string? TimeZone { get; init; }
|
||||
|
||||
/// <summary>The problems met while reading (both <c>X</c> and <c>X_FILE</c>, unreadable files).</summary>
|
||||
public IReadOnlyList<string> ReadErrors { get; init; } = [];
|
||||
|
||||
/// <summary>The system database, parsed.</summary>
|
||||
public DatabaseUrl SystemDatabase => DatabaseUrl.Parse(SystemDb ?? throw new ConfigurationException("KHAEMHAT_SYSTEM_DB is not set."));
|
||||
|
||||
/// <summary>
|
||||
/// Where company databases are created: <see cref="DbServer"/> when set, otherwise the server (PostgreSQL) or the
|
||||
/// folder (SQLite) of the system database.
|
||||
/// </summary>
|
||||
public DatabaseUrl CompanyServer => DbServer is { } server ? DatabaseUrl.Parse(server) : SystemDatabase;
|
||||
|
||||
/// <summary>The licence mode, parsed.</summary>
|
||||
public LicenseMode Mode => string.Equals(LicenseMode, "test", StringComparison.OrdinalIgnoreCase)
|
||||
? Configuration.LicenseMode.Test
|
||||
: Configuration.LicenseMode.Production;
|
||||
|
||||
/// <summary>Whether base data is loaded into new companies.</summary>
|
||||
public bool SeedBaseEnabled => ParseBool(SeedBase) ?? true;
|
||||
|
||||
/// <summary>Whether demo data is loaded into new, empty companies.</summary>
|
||||
public bool SeedDemoEnabled => ParseBool(SeedDemo) ?? false;
|
||||
|
||||
/// <summary>The SMTP port, defaulting by security mode.</summary>
|
||||
public int SmtpPortNumber => int.TryParse(SmtpPort, NumberStyles.None, CultureInfo.InvariantCulture, out var port)
|
||||
? port
|
||||
: SmtpSecurityMode == Configuration.SmtpSecurity.Ssl ? 465 : 587;
|
||||
|
||||
/// <summary>The SMTP security, parsed.</summary>
|
||||
public SmtpSecurity SmtpSecurityMode => SmtpSecurity?.ToUpperInvariant() switch
|
||||
{
|
||||
"SSL" or "TLS" => Configuration.SmtpSecurity.Ssl,
|
||||
"NONE" => Configuration.SmtpSecurity.None,
|
||||
_ => Configuration.SmtpSecurity.StartTls,
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Checks the whole configuration. Messages name the variable and the expected form, never its value.
|
||||
/// The variables needed only at first start (super user, first company) are checked by the bootstrap, which knows
|
||||
/// whether the tables are still empty; here only their form is checked when they are set.
|
||||
/// </summary>
|
||||
/// <returns>The problems; empty when the instance can start.</returns>
|
||||
public IReadOnlyList<string> Validate()
|
||||
{
|
||||
var errors = new List<string>(ReadErrors);
|
||||
|
||||
if (SystemDb is null)
|
||||
{
|
||||
if (!ReadErrors.Any(e => e.StartsWith("KHAEMHAT_SYSTEM_DB", StringComparison.Ordinal)))
|
||||
{
|
||||
errors.Add("KHAEMHAT_SYSTEM_DB is required: postgres://user:password@host:5432/khaemhat_system or sqlite:///data/system.db.");
|
||||
}
|
||||
}
|
||||
else if (!DatabaseUrl.TryParse(SystemDb, out _))
|
||||
{
|
||||
errors.Add("KHAEMHAT_SYSTEM_DB is not a valid database URL: use postgres://user:password@host:5432/khaemhat_system or sqlite:///data/system.db.");
|
||||
}
|
||||
|
||||
if (DbServer is not null && (!DatabaseUrl.TryParse(DbServer, out var server) || server.Engine != DbEngine.PostgreSql))
|
||||
{
|
||||
errors.Add("KHAEMHAT_DB_SERVER must be a PostgreSQL server URL: postgres://user:password@host:5432/ (a role with CREATEDB).");
|
||||
}
|
||||
|
||||
CheckKey("KHAEMHAT_SECRET_KEY", SecretKey, required: true, errors);
|
||||
CheckKey("KHAEMHAT_SECRET_KEY_NEW", RotationSecretKey, required: false, errors);
|
||||
|
||||
if (SuperUser is not null && !UserNames.IsValid(SuperUser))
|
||||
{
|
||||
errors.Add("KHAEMHAT_SUPERUSER must be 3 to 50 characters: letters, digits, dot, dash or underscore.");
|
||||
}
|
||||
|
||||
if (SuperUserEmail is not null && !IsEmail(SuperUserEmail))
|
||||
{
|
||||
errors.Add("KHAEMHAT_SUPERUSER_EMAIL is not a valid e-mail address.");
|
||||
}
|
||||
|
||||
if (CompanyCode is not null && !CompanyCodes.IsValid(CompanyCode.Trim().ToUpperInvariant()))
|
||||
{
|
||||
errors.Add("KHAEMHAT_COMPANY_CODE must be 1 to 20 characters: letters, digits or underscore, starting with a letter.");
|
||||
}
|
||||
|
||||
if (CompanyName is { Length: > 200 })
|
||||
{
|
||||
errors.Add("KHAEMHAT_COMPANY_NAME is longer than 200 characters.");
|
||||
}
|
||||
|
||||
if (!string.Equals(Country, "IT", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
errors.Add("KHAEMHAT_COUNTRY: the only fiscal package available is IT.");
|
||||
}
|
||||
|
||||
if (!string.Equals(LicenseMode, "production", StringComparison.OrdinalIgnoreCase)
|
||||
&& !string.Equals(LicenseMode, "test", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
errors.Add("KHAEMHAT_LICENSE_MODE must be production or test.");
|
||||
}
|
||||
|
||||
if (Redis is not null && !(Uri.TryCreate(Redis, UriKind.Absolute, out var redis) && redis.Scheme is "redis" or "rediss"))
|
||||
{
|
||||
errors.Add("KHAEMHAT_REDIS must be redis://[:password@]host:6379/0 or rediss:// for TLS.");
|
||||
}
|
||||
|
||||
if (string.IsNullOrWhiteSpace(DataDir) || !Path.IsPathFullyQualified(DataDir))
|
||||
{
|
||||
errors.Add("KHAEMHAT_DATA_DIR must be an absolute path (default /data).");
|
||||
}
|
||||
|
||||
if (PublicUrl is not null && !IsHttpUrl(PublicUrl))
|
||||
{
|
||||
errors.Add("KHAEMHAT_PUBLIC_URL must be an absolute http or https address, for example https://gestionale.example.com.");
|
||||
}
|
||||
|
||||
if (SmtpPort is not null && !(int.TryParse(SmtpPort, NumberStyles.None, CultureInfo.InvariantCulture, out var port) && port is > 0 and < 65536))
|
||||
{
|
||||
errors.Add("KHAEMHAT_SMTP_PORT must be a port number between 1 and 65535.");
|
||||
}
|
||||
|
||||
if (SmtpSecurity is not null && SmtpSecurity.ToUpperInvariant() is not ("STARTTLS" or "SSL" or "TLS" or "NONE"))
|
||||
{
|
||||
errors.Add("KHAEMHAT_SMTP_SECURITY must be starttls, ssl or none.");
|
||||
}
|
||||
|
||||
if (SmtpFrom is not null && !IsEmail(SmtpFrom))
|
||||
{
|
||||
errors.Add("KHAEMHAT_SMTP_FROM is not a valid e-mail address.");
|
||||
}
|
||||
|
||||
if (LogLevel is not null && !(Enum.TryParse<LogLevel>(LogLevel, ignoreCase: true, out var level) && Enum.IsDefined(level)))
|
||||
{
|
||||
errors.Add("KHAEMHAT_LOG_LEVEL must be Trace, Debug, Information, Warning, Error, Critical or None.");
|
||||
}
|
||||
|
||||
if (SeedBase is not null && ParseBool(SeedBase) is null)
|
||||
{
|
||||
errors.Add("KHAEMHAT_SEED_BASE must be true or false.");
|
||||
}
|
||||
|
||||
if (SeedDemo is not null && ParseBool(SeedDemo) is null)
|
||||
{
|
||||
errors.Add("KHAEMHAT_SEED_DEMO must be true or false.");
|
||||
}
|
||||
|
||||
if (UpdateFeed is not null && !IsHttpUrl(UpdateFeed))
|
||||
{
|
||||
errors.Add("KHAEMHAT_UPDATE_FEED must be an absolute http or https address.");
|
||||
}
|
||||
|
||||
if (TimeZone is not null && !TimeZoneInfo.TryFindSystemTimeZoneById(TimeZone, out _))
|
||||
{
|
||||
errors.Add("TZ is not a known time zone, for example Europe/Rome.");
|
||||
}
|
||||
|
||||
return errors;
|
||||
}
|
||||
|
||||
/// <summary>Throws when <see cref="Validate"/> finds problems.</summary>
|
||||
/// <exception cref="ConfigurationException">The configuration is not valid.</exception>
|
||||
public void EnsureValid()
|
||||
{
|
||||
var errors = Validate();
|
||||
if (errors.Count > 0)
|
||||
{
|
||||
throw new ConfigurationException(errors);
|
||||
}
|
||||
}
|
||||
|
||||
private static void CheckKey(string name, string? value, bool required, List<string> errors)
|
||||
{
|
||||
if (value is null)
|
||||
{
|
||||
if (required)
|
||||
{
|
||||
errors.Add($"{name} is required: the base64 of at least 32 random bytes (for example: openssl rand -base64 32).");
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
_ = Infrastructure.Security.SecretKey.FromBase64(value);
|
||||
}
|
||||
catch (FormatException ex)
|
||||
{
|
||||
errors.Add(ex.Message.Replace("KHAEMHAT_SECRET_KEY", name, StringComparison.Ordinal));
|
||||
}
|
||||
}
|
||||
|
||||
private static bool? ParseBool(string? value) => value?.Trim().ToUpperInvariant() switch
|
||||
{
|
||||
null => null,
|
||||
"TRUE" or "1" or "YES" or "SI" => true,
|
||||
"FALSE" or "0" or "NO" => false,
|
||||
_ => null,
|
||||
};
|
||||
|
||||
private static bool IsHttpUrl(string value) =>
|
||||
Uri.TryCreate(value, UriKind.Absolute, out var uri) && (uri.Scheme == Uri.UriSchemeHttp || uri.Scheme == Uri.UriSchemeHttps);
|
||||
|
||||
private static bool IsEmail(string value) => MailAddress.TryCreate(value, out var address) && address.Address == value.Trim();
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
using Khaemhat.Application.Security;
|
||||
using Khaemhat.Core.Instance;
|
||||
using Khaemhat.Data;
|
||||
using Khaemhat.Data.Companies;
|
||||
|
||||
namespace Khaemhat.Application.Instance;
|
||||
|
||||
/// <summary>The outcome of choosing the company a request or a circuit works in.</summary>
|
||||
public enum CompanyAccess
|
||||
{
|
||||
/// <summary>The company can be used.</summary>
|
||||
Granted = 0,
|
||||
|
||||
/// <summary>No company chosen (an instance account on instance pages).</summary>
|
||||
None = 1,
|
||||
|
||||
/// <summary>The company does not exist.</summary>
|
||||
NotFound = 2,
|
||||
|
||||
/// <summary>A company account asked for another company.</summary>
|
||||
Forbidden = 3,
|
||||
|
||||
/// <summary>The company is in maintenance and the account is not an instance account.</summary>
|
||||
Maintenance = 4,
|
||||
|
||||
/// <summary>The company is disabled.</summary>
|
||||
Disabled = 5,
|
||||
}
|
||||
|
||||
/// <summary>The company of the current request or Blazor circuit (SPEC §5.4).</summary>
|
||||
/// <param name="Access">Whether the company can be used.</param>
|
||||
/// <param name="Company">The company, when it exists.</param>
|
||||
public sealed record CompanyContextResult(CompanyAccess Access, Company? Company)
|
||||
{
|
||||
/// <summary>No company.</summary>
|
||||
public static CompanyContextResult None { get; } = new(CompanyAccess.None, null);
|
||||
|
||||
/// <summary>The company code, when granted.</summary>
|
||||
public string? Code => Access == CompanyAccess.Granted ? Company!.Code : null;
|
||||
|
||||
/// <summary>Whether writes are refused (company in <see cref="CompanyStatus.ReadOnly"/>).</summary>
|
||||
public bool IsReadOnly => Company?.Status == CompanyStatus.ReadOnly;
|
||||
|
||||
/// <summary>Whether the company is temporarily unavailable (the API answers 503).</summary>
|
||||
public bool IsUnavailable => Access is CompanyAccess.Maintenance or CompanyAccess.Disabled;
|
||||
|
||||
/// <summary>The database scope of the company.</summary>
|
||||
/// <returns>The scope.</returns>
|
||||
/// <exception cref="InvalidOperationException">No company is granted.</exception>
|
||||
public DatabaseScope Scope() =>
|
||||
Access == CompanyAccess.Granted ? DatabaseScope.Company(Company!.Code) : throw new InvalidOperationException("No company is available in this context.");
|
||||
}
|
||||
|
||||
/// <summary>The company the current user works in. Scoped: one per request and one per Blazor circuit.</summary>
|
||||
public interface ICompanyContext
|
||||
{
|
||||
/// <summary>Resolves (once) and returns the company.</summary>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The result.</returns>
|
||||
ValueTask<CompanyContextResult> GetAsync(CancellationToken cancellationToken = default);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The rules that choose the company (SPEC §1.4, §5.4): company accounts work only in their own company; instance
|
||||
/// accounts choose it (session company, or the <c>X-Company</c> header of an API call). A company in maintenance is open
|
||||
/// only to instance accounts; a disabled company to nobody.
|
||||
/// </summary>
|
||||
/// <param name="companies">The company registry.</param>
|
||||
public sealed class CompanyContextResolver(ICompanyRegistry companies)
|
||||
{
|
||||
/// <summary>The header naming the company of an API call.</summary>
|
||||
public const string Header = "X-Company";
|
||||
|
||||
/// <summary>Chooses the company.</summary>
|
||||
/// <param name="actor">The signed-in user, or <see langword="null"/>.</param>
|
||||
/// <param name="requested">The company asked by the request (header), or <see langword="null"/>.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The result.</returns>
|
||||
public async Task<CompanyContextResult> ResolveAsync(Actor? actor, string? requested, CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (actor is null)
|
||||
{
|
||||
return CompanyContextResult.None;
|
||||
}
|
||||
|
||||
requested = string.IsNullOrWhiteSpace(requested) ? null : requested.Trim().ToUpperInvariant();
|
||||
string? code;
|
||||
if (actor.IsInstanceAccount)
|
||||
{
|
||||
code = requested ?? actor.CompanyCode;
|
||||
}
|
||||
else
|
||||
{
|
||||
if (requested is not null && !string.Equals(requested, actor.CompanyCode, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return new CompanyContextResult(CompanyAccess.Forbidden, null);
|
||||
}
|
||||
|
||||
code = actor.CompanyCode;
|
||||
}
|
||||
|
||||
if (code is null)
|
||||
{
|
||||
return CompanyContextResult.None;
|
||||
}
|
||||
|
||||
var company = await companies.FindAsync(code, cancellationToken).ConfigureAwait(false);
|
||||
return company switch
|
||||
{
|
||||
null => new CompanyContextResult(CompanyAccess.NotFound, null),
|
||||
{ Status: CompanyStatus.Disabled } => new CompanyContextResult(CompanyAccess.Disabled, company),
|
||||
{ Status: CompanyStatus.Maintenance } when !actor.IsInstanceAccount => new CompanyContextResult(CompanyAccess.Maintenance, company),
|
||||
_ => new CompanyContextResult(CompanyAccess.Granted, company),
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,314 @@
|
||||
using Khaemhat.Application.Audit;
|
||||
using Khaemhat.Application.Licensing;
|
||||
using Khaemhat.Application.Security;
|
||||
using Khaemhat.Core.Instance;
|
||||
using Khaemhat.Core.Logging;
|
||||
using Khaemhat.Data;
|
||||
using Khaemhat.Data.Companies;
|
||||
using Khaemhat.Data.Migrations;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace Khaemhat.Application.Instance;
|
||||
|
||||
/// <summary>Where the databases of the instance are and which migrations they get.</summary>
|
||||
/// <param name="System">The system database (<c>KHAEMHAT_SYSTEM_DB</c>).</param>
|
||||
/// <param name="CompanyServer">Where new company databases are created (<c>KHAEMHAT_DB_SERVER</c>, or next to the system one).</param>
|
||||
/// <param name="SystemMigrations">The migrations of the system database.</param>
|
||||
/// <param name="CompanyMigrations">The migrations of every company database.</param>
|
||||
public sealed record InstanceDatabases(DatabaseUrl System, DatabaseUrl CompanyServer, MigrationCatalog SystemMigrations, MigrationCatalog CompanyMigrations);
|
||||
|
||||
/// <summary>A company to create.</summary>
|
||||
/// <param name="Code">The code (database <c>khaemhat_<code></c>).</param>
|
||||
/// <param name="Name">The company name.</param>
|
||||
/// <param name="IsDefault">Whether it becomes the default company.</param>
|
||||
/// <param name="Notes">Notes for administrators.</param>
|
||||
/// <param name="SeedDemo">Whether to load the demo data.</param>
|
||||
public sealed record NewCompany(string Code, string Name, bool IsDefault = false, string? Notes = null, bool SeedDemo = false);
|
||||
|
||||
/// <summary>
|
||||
/// Fills a new or migrated company database. Modules register their own: base data at creation (plan of accounts, VAT
|
||||
/// codes) and demo data when asked (SPEC §5.5). Seeders must be idempotent: they run again at every start.
|
||||
/// </summary>
|
||||
public interface ICompanySeeder
|
||||
{
|
||||
/// <summary>The order among seeders (lower first).</summary>
|
||||
int Order { get; }
|
||||
|
||||
/// <summary>Fills the database.</summary>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="context">What to load.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>A task.</returns>
|
||||
Task SeedAsync(string companyCode, CompanySeedContext context, CancellationToken cancellationToken = default);
|
||||
}
|
||||
|
||||
/// <summary>What a seeder is asked to load.</summary>
|
||||
/// <param name="IsNew">Whether the database was just created.</param>
|
||||
/// <param name="Base">Whether the base data is wanted (<c>KHAEMHAT_SEED_BASE</c>).</param>
|
||||
/// <param name="Demo">Whether the demo data is wanted.</param>
|
||||
public sealed record CompanySeedContext(bool IsNew, bool Base, bool Demo);
|
||||
|
||||
/// <summary>The predefined roles of SPEC §7.2, kept equal to their templates in every company.</summary>
|
||||
/// <param name="roles">The role service.</param>
|
||||
public sealed class PredefinedRolesSeeder(RoleService roles) : ICompanySeeder
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public int Order => 0;
|
||||
|
||||
/// <inheritdoc />
|
||||
public Task SeedAsync(string companyCode, CompanySeedContext context, CancellationToken cancellationToken = default) =>
|
||||
roles.SyncPredefinedRolesAsync(companyCode, cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates, attaches and migrates company databases (SPEC §5.4, §12.1; mockup 080). Creating a company is an
|
||||
/// instance administration task: super user or administrators. The number of companies is limited by the licence
|
||||
/// (module MULTI).
|
||||
/// </summary>
|
||||
public sealed class CompanyService
|
||||
{
|
||||
private readonly ICompanyRegistry _registry;
|
||||
private readonly DbProviderCatalog _providers;
|
||||
private readonly MigrationRunner _migrations;
|
||||
private readonly InstanceDatabases _databases;
|
||||
private readonly ILicenseGate _licenses;
|
||||
private readonly SessionStore _sessions;
|
||||
private readonly ISecurityAuditLog _audit;
|
||||
private readonly IReadOnlyList<ICompanySeeder> _seeders;
|
||||
private readonly ILogger<CompanyService> _logger;
|
||||
|
||||
/// <summary>Creates the service.</summary>
|
||||
/// <param name="registry">The company registry.</param>
|
||||
/// <param name="providers">The database providers.</param>
|
||||
/// <param name="migrations">Applies migrations.</param>
|
||||
/// <param name="databases">Where databases are.</param>
|
||||
/// <param name="licenses">The licence in force.</param>
|
||||
/// <param name="sessions">The sessions (revoked when a company goes into maintenance).</param>
|
||||
/// <param name="audit">The security audit.</param>
|
||||
/// <param name="seeders">The seeders of the modules.</param>
|
||||
/// <param name="logger">The log.</param>
|
||||
public CompanyService(
|
||||
ICompanyRegistry registry, DbProviderCatalog providers, MigrationRunner migrations, InstanceDatabases databases, ILicenseGate licenses,
|
||||
SessionStore sessions, ISecurityAuditLog audit, IEnumerable<ICompanySeeder> seeders, ILogger<CompanyService> logger)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(registry);
|
||||
ArgumentNullException.ThrowIfNull(providers);
|
||||
ArgumentNullException.ThrowIfNull(migrations);
|
||||
ArgumentNullException.ThrowIfNull(databases);
|
||||
ArgumentNullException.ThrowIfNull(licenses);
|
||||
ArgumentNullException.ThrowIfNull(sessions);
|
||||
ArgumentNullException.ThrowIfNull(audit);
|
||||
ArgumentNullException.ThrowIfNull(seeders);
|
||||
ArgumentNullException.ThrowIfNull(logger);
|
||||
_registry = registry;
|
||||
_providers = providers;
|
||||
_migrations = migrations;
|
||||
_databases = databases;
|
||||
_licenses = licenses;
|
||||
_sessions = sessions;
|
||||
_audit = audit;
|
||||
_seeders = [.. seeders.OrderBy(s => s.Order)];
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
/// <summary>The companies of the instance.</summary>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The companies by code.</returns>
|
||||
public Task<IReadOnlyList<Company>> ListAsync(CancellationToken cancellationToken = default) => _registry.ListAsync(cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Creates a company: a new database <c>khaemhat_<code></c> on the company server, registered, migrated and
|
||||
/// filled by the seeders.
|
||||
/// </summary>
|
||||
/// <param name="actor">Who acts: an instance account.</param>
|
||||
/// <param name="company">The company.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The registered company.</returns>
|
||||
/// <exception cref="AccessDeniedException">The actor is not an instance account, or the licence allows no more companies.</exception>
|
||||
public async Task<Company> CreateAsync(Actor actor, NewCompany company, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(actor);
|
||||
ArgumentNullException.ThrowIfNull(company);
|
||||
RequireInstanceAdministrator(actor);
|
||||
var code = Validate(company.Code, company.Name);
|
||||
await RequireRoomAsync(cancellationToken).ConfigureAwait(false);
|
||||
|
||||
var url = _databases.CompanyServer.WithDatabase(CompanyCodes.DatabaseName(code));
|
||||
var target = _providers.Resolve(url);
|
||||
if (!url.IsInMemory && await target.Provider.DatabaseExistsAsync(target.ConnectionString, cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
throw new ValidationFailedException([$"Il database {url.DatabaseName} esiste già: usa «Collega database esistente»."]);
|
||||
}
|
||||
|
||||
await target.Provider.EnsureDatabaseExistsAsync(target.ConnectionString, cancellationToken).ConfigureAwait(false);
|
||||
var registered = await _registry.RegisterAsync(new CompanyRegistration(code, company.Name, url, company.IsDefault, company.Notes), cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
await PrepareAsync(registered, new CompanySeedContext(IsNew: true, Base: true, Demo: company.SeedDemo), cancellationToken).ConfigureAwait(false);
|
||||
await _audit.WriteAsync(new SecurityEvent("company.created", actor.UserName, Target: code), cancellationToken).ConfigureAwait(false);
|
||||
return registered;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Attaches an existing company database (restored from a backup or moved from another instance) and migrates it.
|
||||
/// </summary>
|
||||
/// <param name="actor">Who acts: an instance account.</param>
|
||||
/// <param name="code">The company code.</param>
|
||||
/// <param name="name">The company name.</param>
|
||||
/// <param name="database">Where the database is.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The registered company.</returns>
|
||||
public async Task<Company> AttachAsync(Actor actor, string code, string name, DatabaseUrl database, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(actor);
|
||||
ArgumentNullException.ThrowIfNull(database);
|
||||
RequireInstanceAdministrator(actor);
|
||||
var normalized = Validate(code, name);
|
||||
await RequireRoomAsync(cancellationToken).ConfigureAwait(false);
|
||||
|
||||
var target = _providers.Resolve(database);
|
||||
if (!await target.Provider.DatabaseExistsAsync(target.ConnectionString, cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
throw new ValidationFailedException(["Il database indicato non esiste o non è raggiungibile."]);
|
||||
}
|
||||
|
||||
var registered = await _registry.RegisterAsync(new CompanyRegistration(normalized, name, database), cancellationToken).ConfigureAwait(false);
|
||||
await PrepareAsync(registered, new CompanySeedContext(IsNew: false, Base: false, Demo: false), cancellationToken).ConfigureAwait(false);
|
||||
await _audit.WriteAsync(new SecurityEvent("company.attached", actor.UserName, Target: normalized), cancellationToken).ConfigureAwait(false);
|
||||
return registered;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Changes the state of a company. Maintenance and disabling sign out its users at once; instance accounts can still
|
||||
/// open a company in maintenance.
|
||||
/// </summary>
|
||||
/// <param name="actor">Who acts: an instance account.</param>
|
||||
/// <param name="code">The company.</param>
|
||||
/// <param name="status">The new state.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>A task.</returns>
|
||||
public async Task SetStatusAsync(Actor actor, string code, CompanyStatus status, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(actor);
|
||||
RequireInstanceAdministrator(actor);
|
||||
await _registry.SetStatusAsync(code, status, cancellationToken).ConfigureAwait(false);
|
||||
if (status is CompanyStatus.Maintenance or CompanyStatus.Disabled)
|
||||
{
|
||||
var revoked = await _sessions.RevokeCompanyAsync(code, "company-" + status.ToString().ToLowerInvariant(), cancellationToken).ConfigureAwait(false);
|
||||
_logger.LogInformation("Company {Company} is now {Status}: {Count} sessions closed.", code, status, revoked);
|
||||
}
|
||||
|
||||
await _audit.WriteAsync(
|
||||
new SecurityEvent("company.status", actor.UserName, Target: CompanyCodes.Normalize(code), Details: status.ToString()), cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Migrates every company that is not disabled and runs the seeders again (at each start). A company whose
|
||||
/// migration fails is put in maintenance and logged; the others go on.
|
||||
/// </summary>
|
||||
/// <param name="seedDemo">Whether demo data is wanted (<c>KHAEMHAT_SEED_DEMO</c>).</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The companies that failed.</returns>
|
||||
public async Task<IReadOnlyList<string>> PrepareAllAsync(bool seedDemo, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var failed = new List<string>();
|
||||
foreach (var company in await _registry.ListAsync(cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
if (company.Status == CompanyStatus.Disabled)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
await PrepareAsync(company, new CompanySeedContext(IsNew: false, Base: false, Demo: seedDemo), cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException)
|
||||
{
|
||||
failed.Add(company.Code);
|
||||
using (_logger.BeginScope(LogSections.Scope(LogSection.Migrations)))
|
||||
{
|
||||
_logger.LogError(ex, "Company {Company} could not be migrated: it is put in maintenance.", company.Code);
|
||||
}
|
||||
|
||||
await _registry.SetStatusAsync(company.Code, CompanyStatus.Maintenance, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
return failed;
|
||||
}
|
||||
|
||||
private async Task PrepareAsync(Company company, CompanySeedContext context, CancellationToken cancellationToken)
|
||||
{
|
||||
var target = await _registry.ResolveAsync(company.Code, cancellationToken).ConfigureAwait(false);
|
||||
var report = await _migrations.RunAsync(target, _databases.CompanyMigrations, cancellationToken).ConfigureAwait(false);
|
||||
LogMigrations(_logger, report, company.Code);
|
||||
foreach (var seeder in _seeders)
|
||||
{
|
||||
await seeder.SeedAsync(company.Code, context, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Writes a migration report in the section <i>Migrazioni</i>.</summary>
|
||||
/// <param name="logger">The log.</param>
|
||||
/// <param name="report">The report.</param>
|
||||
/// <param name="companyCode">The company, or <see langword="null"/> for the system database.</param>
|
||||
public static void LogMigrations(ILogger logger, MigrationReport report, string? companyCode)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(logger);
|
||||
ArgumentNullException.ThrowIfNull(report);
|
||||
using var section = logger.BeginScope(LogSections.Scope(LogSection.Migrations));
|
||||
using var company = logger.BeginScope(new Dictionary<string, object?> { [LogSections.CompanyKey] = companyCode });
|
||||
foreach (var (migration, duration) in report.Applied)
|
||||
{
|
||||
logger.LogInformation("Migration {Migration} applied to {Database} in {Milliseconds} ms.", migration.ToString(), report.Database, (long)duration.TotalMilliseconds);
|
||||
}
|
||||
|
||||
foreach (var warning in report.Warnings)
|
||||
{
|
||||
logger.LogWarning("Database {Database}: {Warning}", report.Database, warning);
|
||||
}
|
||||
|
||||
if (report.Applied.Count == 0)
|
||||
{
|
||||
logger.LogDebug("Database {Database} is up to date ({Count} migrations).", report.Database, report.AlreadyApplied);
|
||||
}
|
||||
}
|
||||
|
||||
private static string Validate(string code, string name)
|
||||
{
|
||||
var errors = new List<string>();
|
||||
if (!CompanyCodes.IsValid((code ?? string.Empty).Trim().ToUpperInvariant()))
|
||||
{
|
||||
errors.Add("Il codice azienda deve avere da 1 a 20 caratteri tra lettere, cifre e trattino basso.");
|
||||
}
|
||||
|
||||
if (string.IsNullOrWhiteSpace(name) || name.Trim().Length > 200)
|
||||
{
|
||||
errors.Add("La ragione sociale è obbligatoria (al massimo 200 caratteri).");
|
||||
}
|
||||
|
||||
return errors.Count > 0 ? throw new ValidationFailedException(errors) : CompanyCodes.Normalize(code!);
|
||||
}
|
||||
|
||||
private async Task RequireRoomAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
var limit = _licenses.Current.MaxCompanies;
|
||||
var count = (await _registry.ListAsync(cancellationToken).ConfigureAwait(false)).Count;
|
||||
if (count >= limit)
|
||||
{
|
||||
throw new AccessDeniedException(
|
||||
SecurityErrors.LicenseLimitReached,
|
||||
limit <= 1
|
||||
? "La licenza consente una sola azienda: per gestirne altre serve il modulo Multi-azienda (MULTI)."
|
||||
: $"La licenza consente al massimo {limit} aziende.");
|
||||
}
|
||||
}
|
||||
|
||||
private static void RequireInstanceAdministrator(Actor actor)
|
||||
{
|
||||
if (!actor.IsInstanceAccount)
|
||||
{
|
||||
throw new AccessDeniedException(SecurityErrors.LevelTooLow, "Solo gli account di istanza possono gestire le aziende.");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,264 @@
|
||||
using System.Globalization;
|
||||
using Khaemhat.Application.Configuration;
|
||||
using Khaemhat.Application.Licensing;
|
||||
using Khaemhat.Application.Security;
|
||||
using Khaemhat.Core.Logging;
|
||||
using Khaemhat.Data;
|
||||
using Khaemhat.Data.Migrations;
|
||||
using Khaemhat.Infrastructure.Logging;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace Khaemhat.Application.Instance;
|
||||
|
||||
/// <summary>Where the start of the instance is.</summary>
|
||||
public enum BootstrapPhase
|
||||
{
|
||||
/// <summary>Migrations and first-start setup in progress: <c>/health/ready</c> answers 503.</summary>
|
||||
Starting = 0,
|
||||
|
||||
/// <summary>Ready to serve.</summary>
|
||||
Ready = 1,
|
||||
|
||||
/// <summary>The start failed; the process is stopping.</summary>
|
||||
Failed = 2,
|
||||
}
|
||||
|
||||
/// <summary>The start state, read by the readiness endpoint and the middleware.</summary>
|
||||
public sealed class BootstrapState
|
||||
{
|
||||
private volatile BootstrapPhase _phase;
|
||||
|
||||
/// <summary>The phase.</summary>
|
||||
public BootstrapPhase Phase => _phase;
|
||||
|
||||
/// <summary>Whether the instance serves requests.</summary>
|
||||
public bool IsReady => _phase == BootstrapPhase.Ready;
|
||||
|
||||
/// <summary>Why the start failed (no secrets).</summary>
|
||||
public string? Error { get; private set; }
|
||||
|
||||
/// <summary>Companies put in maintenance because their migration failed.</summary>
|
||||
public IReadOnlyList<string> FailedCompanies { get; private set; } = [];
|
||||
|
||||
/// <summary>Marks the start as completed.</summary>
|
||||
/// <param name="failedCompanies">The companies that could not be migrated.</param>
|
||||
public void MarkReady(IReadOnlyList<string> failedCompanies)
|
||||
{
|
||||
FailedCompanies = failedCompanies ?? [];
|
||||
_phase = BootstrapPhase.Ready;
|
||||
}
|
||||
|
||||
/// <summary>Marks the start as failed.</summary>
|
||||
/// <param name="error">Why.</param>
|
||||
public void MarkFailed(string error)
|
||||
{
|
||||
Error = error;
|
||||
_phase = BootstrapPhase.Failed;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The start sequence (SPEC §5.3, §7.1, §8, §23): migrate the system database, start writing the log there, fix the
|
||||
/// instance identifier and the trial start, seed the role templates, compute the licence, create the super user and the
|
||||
/// first company from the variables when the tables are empty, then migrate every company. Every step is idempotent: a
|
||||
/// second start, or two instances starting together, change nothing.
|
||||
/// </summary>
|
||||
public sealed class StartupOrchestrator
|
||||
{
|
||||
private readonly InstanceDatabases _databases;
|
||||
private readonly DbProviderCatalog _providers;
|
||||
private readonly MigrationRunner _migrations;
|
||||
private readonly SystemSettingsStore _settings;
|
||||
private readonly RoleService _roles;
|
||||
private readonly ILicenseGate _licenses;
|
||||
private readonly SystemUserService _systemUsers;
|
||||
private readonly CompanyService _companies;
|
||||
private readonly KhaemhatOptions _options;
|
||||
private readonly IUnitOfWorkFactory _factory;
|
||||
private readonly DbLogSink? _logSink;
|
||||
private readonly BootstrapState _state;
|
||||
private readonly TimeProvider _clock;
|
||||
private readonly ILogger<StartupOrchestrator> _logger;
|
||||
private bool _systemReady;
|
||||
|
||||
/// <summary>Creates the orchestrator.</summary>
|
||||
/// <param name="databases">Where databases are.</param>
|
||||
/// <param name="providers">The providers.</param>
|
||||
/// <param name="migrations">Applies migrations.</param>
|
||||
/// <param name="settings">The instance settings.</param>
|
||||
/// <param name="roles">The role templates.</param>
|
||||
/// <param name="licenses">The licence.</param>
|
||||
/// <param name="systemUsers">The instance accounts.</param>
|
||||
/// <param name="companies">The companies.</param>
|
||||
/// <param name="options">The variables.</param>
|
||||
/// <param name="factory">Opens the databases.</param>
|
||||
/// <param name="logSink">The database log, started once the system database is ready (absent in some tests).</param>
|
||||
/// <param name="state">The start state.</param>
|
||||
/// <param name="clock">The clock.</param>
|
||||
/// <param name="logger">The log.</param>
|
||||
public StartupOrchestrator(
|
||||
InstanceDatabases databases, DbProviderCatalog providers, MigrationRunner migrations, SystemSettingsStore settings, RoleService roles,
|
||||
ILicenseGate licenses, SystemUserService systemUsers, CompanyService companies, KhaemhatOptions options, IUnitOfWorkFactory factory,
|
||||
DbLogSink? logSink, BootstrapState state, TimeProvider clock, ILogger<StartupOrchestrator> logger)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(databases);
|
||||
ArgumentNullException.ThrowIfNull(providers);
|
||||
ArgumentNullException.ThrowIfNull(migrations);
|
||||
ArgumentNullException.ThrowIfNull(settings);
|
||||
ArgumentNullException.ThrowIfNull(roles);
|
||||
ArgumentNullException.ThrowIfNull(licenses);
|
||||
ArgumentNullException.ThrowIfNull(systemUsers);
|
||||
ArgumentNullException.ThrowIfNull(companies);
|
||||
ArgumentNullException.ThrowIfNull(options);
|
||||
ArgumentNullException.ThrowIfNull(factory);
|
||||
ArgumentNullException.ThrowIfNull(state);
|
||||
ArgumentNullException.ThrowIfNull(clock);
|
||||
ArgumentNullException.ThrowIfNull(logger);
|
||||
_databases = databases;
|
||||
_providers = providers;
|
||||
_migrations = migrations;
|
||||
_settings = settings;
|
||||
_roles = roles;
|
||||
_licenses = licenses;
|
||||
_systemUsers = systemUsers;
|
||||
_companies = companies;
|
||||
_options = options;
|
||||
_factory = factory;
|
||||
_logSink = logSink;
|
||||
_state = state;
|
||||
_clock = clock;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates (when missing) and migrates the system database, then starts writing the log there. It runs before the
|
||||
/// host starts serving, because DataProtection and sessions read the system database from the first request.
|
||||
/// </summary>
|
||||
/// <param name="cancellationToken">Cancellation (host stopping).</param>
|
||||
/// <returns>A task.</returns>
|
||||
public async Task PrepareSystemDatabaseAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (_systemReady)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
using var section = _logger.BeginScope(LogSections.Scope(LogSection.System));
|
||||
var system = _providers.Resolve(_databases.System);
|
||||
await system.Provider.EnsureDatabaseExistsAsync(system.ConnectionString, cancellationToken).ConfigureAwait(false);
|
||||
var report = await _migrations.RunAsync(system, _databases.SystemMigrations, cancellationToken).ConfigureAwait(false);
|
||||
CompanyService.LogMigrations(_logger, report, null);
|
||||
_logSink?.Start(_factory);
|
||||
_systemReady = true;
|
||||
}
|
||||
|
||||
/// <summary>Runs the start sequence and marks the state ready.</summary>
|
||||
/// <param name="cancellationToken">Cancellation (host stopping).</param>
|
||||
/// <returns>A task.</returns>
|
||||
/// <exception cref="ConfigurationException">First start without the variables it needs.</exception>
|
||||
public async Task RunAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
// 1. System database: created when missing (SQLite file, PostgreSQL database if the role may), then migrated.
|
||||
await PrepareSystemDatabaseAsync(cancellationToken).ConfigureAwait(false);
|
||||
using var section = _logger.BeginScope(LogSections.Scope(LogSection.System));
|
||||
|
||||
// 2. Instance identity and trial start, fixed at the first start and never changed.
|
||||
await _settings.GetOrAddAsync(SystemSettingsStore.InstanceIdKey, Guid.NewGuid().ToString("D"), cancellationToken).ConfigureAwait(false);
|
||||
await _settings.GetOrAddAsync(
|
||||
SystemSettingsStore.TrialStartedKey, _clock.GetUtcNow().UtcDateTime.ToString("O", CultureInfo.InvariantCulture), cancellationToken).ConfigureAwait(false);
|
||||
|
||||
// 3. Role templates and licence.
|
||||
await _roles.SeedTemplatesAsync(cancellationToken).ConfigureAwait(false);
|
||||
var license = await _licenses.RefreshAsync(cancellationToken).ConfigureAwait(false);
|
||||
_logger.LogInformation(
|
||||
"License: {Kind} {Status}, modules {Modules}, {Users} concurrent users, {Companies} companies.",
|
||||
license.Kind, license.Status, string.Join(',', license.Modules.Order(StringComparer.Ordinal)), license.MaxConcurrentUsers, license.MaxCompanies);
|
||||
|
||||
// 4. Super user, only when there is no instance account at all.
|
||||
if (!await _systemUsers.AnyAsync(cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
await CreateSuperUserAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
// 5. First company, only when the registry is empty.
|
||||
if ((await _companies.ListAsync(cancellationToken).ConfigureAwait(false)).Count == 0)
|
||||
{
|
||||
await CreateFirstCompanyAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
// 6. Every company migrated and seeded again.
|
||||
var failed = await _companies.PrepareAllAsync(_options.SeedDemoEnabled, cancellationToken).ConfigureAwait(false);
|
||||
_state.MarkReady(failed);
|
||||
_logger.LogInformation("Khaemhat is ready.");
|
||||
}
|
||||
|
||||
private async Task CreateSuperUserAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
var missing = new List<string>();
|
||||
if (_options.SuperUser is null)
|
||||
{
|
||||
missing.Add("KHAEMHAT_SUPERUSER is required at the first start: the user name of the super user.");
|
||||
}
|
||||
|
||||
if (_options.SuperUserPassword is null)
|
||||
{
|
||||
missing.Add("KHAEMHAT_SUPERUSER_PASSWORD (or KHAEMHAT_SUPERUSER_PASSWORD_FILE) is required at the first start: the first password of the super user.");
|
||||
}
|
||||
|
||||
if (missing.Count > 0)
|
||||
{
|
||||
throw new ConfigurationException(missing);
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
var user = await _systemUsers.CreateSuperUserAsync(
|
||||
new NewSystemUser(_options.SuperUser!, _options.SuperUser!, _options.SuperUserEmail), _options.SuperUserPassword!, cancellationToken).ConfigureAwait(false);
|
||||
_logger.LogInformation("Super user {UserName} created: change the password and set up the two-step verification at the first access.", user.UserName);
|
||||
}
|
||||
catch (ValidationFailedException ex)
|
||||
{
|
||||
throw new ConfigurationException([.. ex.Errors.Select(e => "KHAEMHAT_SUPERUSER_PASSWORD does not satisfy the password policy: " + e)]);
|
||||
}
|
||||
catch (InvalidOperationException)
|
||||
{
|
||||
// Another instance created it a moment ago.
|
||||
}
|
||||
}
|
||||
|
||||
private async Task CreateFirstCompanyAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
var code = _options.CompanyCode?.Trim().ToUpperInvariant();
|
||||
if (code is null)
|
||||
{
|
||||
_logger.LogWarning("No company exists and KHAEMHAT_COMPANY_CODE is not set: create the first company from Amministrazione > Aziende.");
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
var name = string.IsNullOrWhiteSpace(_options.CompanyName) ? code : _options.CompanyName.Trim();
|
||||
var url = _databases.CompanyServer.WithDatabase(CompanyCodes.DatabaseName(code));
|
||||
var target = _providers.Resolve(url);
|
||||
if (!url.IsInMemory && await target.Provider.DatabaseExistsAsync(target.ConnectionString, cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
// The system database was recreated but the company one survived: attach it instead of refusing.
|
||||
await _companies.AttachAsync(Actor.System, code, name, url, cancellationToken).ConfigureAwait(false);
|
||||
_logger.LogWarning("Company database {Database} already existed: attached as company {Company}.", url.DatabaseName, code);
|
||||
return;
|
||||
}
|
||||
|
||||
await _companies.CreateAsync(Actor.System, new NewCompany(code, name, IsDefault: true, SeedDemo: _options.SeedDemoEnabled), cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
_logger.LogInformation("Company {Company} created.", code);
|
||||
}
|
||||
catch (InvalidOperationException)
|
||||
{
|
||||
// Another instance registered it a moment ago; anything else is a real failure.
|
||||
if ((await _companies.ListAsync(cancellationToken).ConfigureAwait(false)).Count == 0)
|
||||
{
|
||||
throw;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
using Khaemhat.Core.Instance;
|
||||
using Khaemhat.Core.Security;
|
||||
using Khaemhat.Data;
|
||||
using Khaemhat.Data.Querying;
|
||||
|
||||
namespace Khaemhat.Application.Instance;
|
||||
|
||||
/// <summary>
|
||||
/// Instance settings in <c>sys_settings</c>. Secret values are encrypted with the instance key and the purpose
|
||||
/// <c>setting:<key></c>.
|
||||
/// </summary>
|
||||
/// <param name="factory">Opens the system database.</param>
|
||||
/// <param name="protector">Encrypts secret values.</param>
|
||||
public sealed class SystemSettingsStore(IUnitOfWorkFactory factory, ISecretProtector protector)
|
||||
{
|
||||
/// <summary>The identifier of the instance, created at first start.</summary>
|
||||
public const string InstanceIdKey = "instance.id";
|
||||
|
||||
/// <summary>When the trial started (ISO 8601 UTC), set at first start.</summary>
|
||||
public const string TrialStartedKey = "license.trial-started-at";
|
||||
|
||||
/// <summary>Reads a setting.</summary>
|
||||
/// <param name="key">The key.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The value (decrypted when secret), or <see langword="null"/>.</returns>
|
||||
public async Task<string?> GetAsync(string key, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(key);
|
||||
await using var unitOfWork = await factory.CreateAsync(DatabaseScope.System, cancellationToken).ConfigureAwait(false);
|
||||
var setting = await unitOfWork.Repository<SystemSetting, long>().FindAsync(Query.For<SystemSetting>().Where(s => s.Key == key), cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
if (setting?.Value is null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
return setting.IsSecret ? protector.Unprotect(setting.Value, Purpose(key)) : setting.Value;
|
||||
}
|
||||
|
||||
/// <summary>Writes a setting.</summary>
|
||||
/// <param name="key">The key.</param>
|
||||
/// <param name="value">The value.</param>
|
||||
/// <param name="secret">Whether to encrypt it.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>A task.</returns>
|
||||
public async Task SetAsync(string key, string? value, bool secret = false, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(key);
|
||||
await using var unitOfWork = await factory.CreateAsync(DatabaseScope.System, cancellationToken).ConfigureAwait(false);
|
||||
var settings = unitOfWork.Repository<SystemSetting, long>();
|
||||
var stored = value is null || !secret ? value : protector.Protect(value, Purpose(key));
|
||||
var setting = await settings.FindAsync(Query.For<SystemSetting>().Where(s => s.Key == key), cancellationToken).ConfigureAwait(false);
|
||||
if (setting is null)
|
||||
{
|
||||
await settings.InsertAsync(new SystemSetting { Key = key, Value = stored, IsSecret = secret }, cancellationToken).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
setting.Value = stored;
|
||||
setting.IsSecret = secret;
|
||||
await settings.UpdateAsync(setting, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>Writes a setting only if it does not exist yet (bootstrap values such as the instance id).</summary>
|
||||
/// <param name="key">The key.</param>
|
||||
/// <param name="value">The value.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The value now stored.</returns>
|
||||
public async Task<string> GetOrAddAsync(string key, string value, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var existing = await GetAsync(key, cancellationToken).ConfigureAwait(false);
|
||||
if (existing is not null)
|
||||
{
|
||||
return existing;
|
||||
}
|
||||
|
||||
await SetAsync(key, value, secret: false, cancellationToken).ConfigureAwait(false);
|
||||
return value;
|
||||
}
|
||||
|
||||
private static string Purpose(string key) => "setting:" + key;
|
||||
}
|
||||
@@ -0,0 +1,361 @@
|
||||
using System.Diagnostics;
|
||||
using Khaemhat.Application.Instance;
|
||||
using Khaemhat.Application.Notifications;
|
||||
using Khaemhat.Core.Instance;
|
||||
using Khaemhat.Core.Logging;
|
||||
using Khaemhat.Core.Scheduling;
|
||||
using Khaemhat.Data;
|
||||
using Khaemhat.Data.Querying;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace Khaemhat.Application.Jobs;
|
||||
|
||||
/// <summary>What a job run receives.</summary>
|
||||
/// <param name="Task">The task (code, company, parameters).</param>
|
||||
/// <param name="Attempt">The attempt number, from 1.</param>
|
||||
/// <param name="TraceId">The trace identifier of the run, also in the log.</param>
|
||||
public sealed record JobContext(ScheduledTask Task, int Attempt, string TraceId);
|
||||
|
||||
/// <summary>
|
||||
/// A kind of job the scheduler can run (SPEC §9.4). Modules register theirs (e-mail import, SDI polling, reminders,
|
||||
/// backups); <see cref="Type"/> is what <c>sys_scheduled_tasks.job_type</c> names.
|
||||
/// </summary>
|
||||
public interface IScheduledJob
|
||||
{
|
||||
/// <summary>The job type.</summary>
|
||||
string Type { get; }
|
||||
|
||||
/// <summary>Runs the job. The token is cancelled at the task timeout or at shutdown.</summary>
|
||||
/// <param name="context">The run.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>A message for the run history, or <see langword="null"/>.</returns>
|
||||
Task<string?> RunAsync(JobContext context, CancellationToken cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>A task created at start when missing.</summary>
|
||||
/// <param name="Code">The task code.</param>
|
||||
/// <param name="Name">The name shown.</param>
|
||||
/// <param name="JobType">The job type.</param>
|
||||
/// <param name="Cron">When it runs.</param>
|
||||
/// <param name="TimeoutSeconds">Its timeout.</param>
|
||||
public sealed record SystemTaskDefinition(string Code, string Name, string JobType, string Cron, int TimeoutSeconds = 600);
|
||||
|
||||
/// <summary>
|
||||
/// The scheduler (SPEC §9.4; mockup 083): reads <c>sys_scheduled_tasks</c>, runs the due ones with a lock in
|
||||
/// <c>sys_job_locks</c> (so two instances never run the same task together), applies timeout and retries, writes
|
||||
/// <c>sys_job_runs</c> and the section <i>Attività programmate</i> of the log, and notifies the instance accounts when a
|
||||
/// task fails for good.
|
||||
/// </summary>
|
||||
public sealed class JobScheduler
|
||||
{
|
||||
/// <summary>The system tasks of M2.</summary>
|
||||
public static readonly IReadOnlyList<SystemTaskDefinition> SystemTasks =
|
||||
[
|
||||
new("system.sessions-cleanup", "Pulizia sessioni scadute", SessionCleanupJob.JobType, "15 * * * *", 300),
|
||||
new("system.license-check", "Verifica licenza", LicenseCheckJob.JobType, "0 * * * *", 120),
|
||||
new("system.log-retention", "Conservazione del log", LogRetentionJob.JobType, "30 3 * * *", 1800),
|
||||
];
|
||||
|
||||
private readonly IUnitOfWorkFactory _factory;
|
||||
private readonly Dictionary<string, IScheduledJob> _jobs;
|
||||
private readonly NotificationDispatcher _notifications;
|
||||
private readonly TimeProvider _clock;
|
||||
private readonly ILogger<JobScheduler> _logger;
|
||||
private readonly string _owner = Environment.MachineName + ":" + Environment.ProcessId;
|
||||
|
||||
/// <summary>Creates the scheduler.</summary>
|
||||
/// <param name="factory">Opens the system database.</param>
|
||||
/// <param name="jobs">The job types.</param>
|
||||
/// <param name="notifications">Notifies failures.</param>
|
||||
/// <param name="clock">The clock.</param>
|
||||
/// <param name="logger">The log.</param>
|
||||
public JobScheduler(IUnitOfWorkFactory factory, IEnumerable<IScheduledJob> jobs, NotificationDispatcher notifications, TimeProvider clock, ILogger<JobScheduler> logger)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(factory);
|
||||
ArgumentNullException.ThrowIfNull(jobs);
|
||||
ArgumentNullException.ThrowIfNull(notifications);
|
||||
ArgumentNullException.ThrowIfNull(clock);
|
||||
ArgumentNullException.ThrowIfNull(logger);
|
||||
_factory = factory;
|
||||
_jobs = jobs.ToDictionary(j => j.Type, StringComparer.Ordinal);
|
||||
_notifications = notifications;
|
||||
_clock = clock;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
/// <summary>Creates the system tasks that are missing and computes the next run of every task without one.</summary>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>A task.</returns>
|
||||
public async Task EnsureSystemTasksAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
var now = _clock.GetUtcNow().UtcDateTime;
|
||||
await using var unitOfWork = await _factory.CreateAsync(DatabaseScope.System, cancellationToken).ConfigureAwait(false);
|
||||
var tasks = unitOfWork.Repository<ScheduledTask, long>();
|
||||
await unitOfWork.InTransactionAsync(
|
||||
async ct =>
|
||||
{
|
||||
await unitOfWork.AcquireLockAsync("scheduler-setup", ct).ConfigureAwait(false);
|
||||
foreach (var definition in SystemTasks)
|
||||
{
|
||||
var code = definition.Code;
|
||||
if (await tasks.CountAsync(Query.For<ScheduledTask>().Where(t => t.Code == code), ct).ConfigureAwait(false) == 0)
|
||||
{
|
||||
var task = new ScheduledTask
|
||||
{
|
||||
Code = code,
|
||||
Name = definition.Name,
|
||||
JobType = definition.JobType,
|
||||
Cron = definition.Cron,
|
||||
TimeoutSeconds = definition.TimeoutSeconds,
|
||||
IsSystem = true,
|
||||
};
|
||||
task.NextRunAt = Next(task, now);
|
||||
await tasks.InsertAsync(task, ct).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
},
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>Runs every enabled task that is due, one after the other.</summary>
|
||||
/// <param name="cancellationToken">Cancellation (shutdown).</param>
|
||||
/// <returns>How many tasks ran.</returns>
|
||||
public async Task<int> RunDueAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
var now = _clock.GetUtcNow().UtcDateTime;
|
||||
IReadOnlyList<ScheduledTask> due;
|
||||
await using (var unitOfWork = await _factory.CreateAsync(DatabaseScope.System, cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
due = (await unitOfWork.Repository<ScheduledTask, long>().ListAsync(
|
||||
Query.For<ScheduledTask>().Where(t => t.IsEnabled && t.NextRunAt != null && t.NextRunAt <= now).OrderBy(t => t.NextRunAt), cancellationToken)
|
||||
.ConfigureAwait(false)).Items;
|
||||
}
|
||||
|
||||
var count = 0;
|
||||
foreach (var task in due)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
if (await RunAsync(task.Code, cancellationToken).ConfigureAwait(false) is not JobOutcome.Skipped)
|
||||
{
|
||||
count++;
|
||||
}
|
||||
}
|
||||
|
||||
return count;
|
||||
}
|
||||
|
||||
/// <summary>Runs a task now (also "Esegui ora" from the administration page).</summary>
|
||||
/// <param name="code">The task code.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The outcome; <see cref="JobOutcome.Skipped"/> when another run holds the lock.</returns>
|
||||
public async Task<JobOutcome> RunAsync(string code, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ScheduledTask? task;
|
||||
await using (var unitOfWork = await _factory.CreateAsync(DatabaseScope.System, cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
task = await unitOfWork.Repository<ScheduledTask, long>().FindAsync(Query.For<ScheduledTask>().Where(t => t.Code == code), cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
if (task is null)
|
||||
{
|
||||
throw new KeyNotFoundException($"No scheduled task has code {code}.");
|
||||
}
|
||||
|
||||
var timeout = TimeSpan.FromSeconds(Math.Max(1, task.TimeoutSeconds));
|
||||
if (!await TryLockAsync(task.Code, timeout, cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
return JobOutcome.Skipped;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
return await RunLockedAsync(task, timeout, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
finally
|
||||
{
|
||||
await UnlockAsync(task.Code).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<JobOutcome> RunLockedAsync(ScheduledTask task, TimeSpan timeout, CancellationToken cancellationToken)
|
||||
{
|
||||
using var section = _logger.BeginScope(LogSections.Scope(LogSection.ScheduledJobs));
|
||||
var outcome = JobOutcome.Failed;
|
||||
string? message = null;
|
||||
for (var attempt = 1; attempt <= task.MaxRetries + 1; attempt++)
|
||||
{
|
||||
var traceId = ActivityTraceId.CreateRandom().ToString();
|
||||
using var scope = _logger.BeginScope(new Dictionary<string, object?> { [LogSections.TraceIdKey] = traceId, [LogSections.CompanyKey] = task.CompanyCode });
|
||||
var run = new JobRun { TaskCode = task.Code, StartedAt = _clock.GetUtcNow().UtcDateTime, Outcome = JobOutcome.Running, Attempt = attempt, TraceId = traceId };
|
||||
run.Id = await SaveRunAsync(run, insert: true, cancellationToken).ConfigureAwait(false);
|
||||
(outcome, message) = await ExecuteAsync(task, new JobContext(task, attempt, traceId), timeout, cancellationToken).ConfigureAwait(false);
|
||||
run.Outcome = outcome;
|
||||
run.Message = message is { Length: > 2000 } ? message[..2000] : message;
|
||||
run.FinishedAt = _clock.GetUtcNow().UtcDateTime;
|
||||
await SaveRunAsync(run, insert: false, CancellationToken.None).ConfigureAwait(false);
|
||||
if (outcome == JobOutcome.Succeeded || cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
await FinishAsync(task, outcome, cancellationToken).ConfigureAwait(false);
|
||||
if (outcome is JobOutcome.Failed or JobOutcome.TimedOut)
|
||||
{
|
||||
await _notifications.NotifyInstanceAsync(
|
||||
new NotificationMessage("jobs", NotificationSeverity.Error, $"Attività «{task.Name}» non riuscita", message, "/amministrazione/attivita"),
|
||||
cancellationToken: CancellationToken.None).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
return outcome;
|
||||
}
|
||||
|
||||
private async Task<(JobOutcome Outcome, string? Message)> ExecuteAsync(ScheduledTask task, JobContext context, TimeSpan timeout, CancellationToken cancellationToken)
|
||||
{
|
||||
if (!_jobs.TryGetValue(task.JobType, out var job))
|
||||
{
|
||||
_logger.LogError("Task {Task}: job type {JobType} is not known.", task.Code, task.JobType);
|
||||
return (JobOutcome.Failed, "Tipo di attività sconosciuto: " + task.JobType);
|
||||
}
|
||||
|
||||
using var timeoutSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
|
||||
timeoutSource.CancelAfter(timeout);
|
||||
var started = Stopwatch.GetTimestamp();
|
||||
try
|
||||
{
|
||||
var message = await job.RunAsync(context, timeoutSource.Token).ConfigureAwait(false);
|
||||
_logger.LogInformation("Task {Task} completed in {Milliseconds} ms. {Message}", task.Code, (long)Stopwatch.GetElapsedTime(started).TotalMilliseconds, message);
|
||||
return (JobOutcome.Succeeded, message);
|
||||
}
|
||||
catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
_logger.LogError("Task {Task} stopped after the timeout of {Seconds} s (attempt {Attempt}).", task.Code, (int)timeout.TotalSeconds, context.Attempt);
|
||||
return (JobOutcome.TimedOut, $"Interrotta dopo {(int)timeout.TotalSeconds} secondi.");
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException)
|
||||
{
|
||||
_logger.LogError(ex, "Task {Task} failed (attempt {Attempt}).", task.Code, context.Attempt);
|
||||
return (JobOutcome.Failed, ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task FinishAsync(ScheduledTask task, JobOutcome outcome, CancellationToken cancellationToken)
|
||||
{
|
||||
var now = _clock.GetUtcNow().UtcDateTime;
|
||||
await using var unitOfWork = await _factory.CreateAsync(DatabaseScope.System, CancellationToken.None).ConfigureAwait(false);
|
||||
var tasks = unitOfWork.Repository<ScheduledTask, long>();
|
||||
var current = await tasks.GetAsync(task.Id, CancellationToken.None).ConfigureAwait(false);
|
||||
if (current is null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
current.LastRunAt = now;
|
||||
current.LastOutcome = outcome;
|
||||
current.NextRunAt = Next(current, now);
|
||||
await tasks.UpdateAsync(current, cancellationToken.IsCancellationRequested ? CancellationToken.None : cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private async Task<long> SaveRunAsync(JobRun run, bool insert, CancellationToken cancellationToken)
|
||||
{
|
||||
await using var unitOfWork = await _factory.CreateAsync(DatabaseScope.System, cancellationToken).ConfigureAwait(false);
|
||||
var runs = unitOfWork.Repository<JobRun, long>();
|
||||
if (insert)
|
||||
{
|
||||
return await runs.InsertAsync(run, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await runs.UpdateAsync(run, cancellationToken).ConfigureAwait(false);
|
||||
return run.Id;
|
||||
}
|
||||
|
||||
// A lock row per task; an expired lock (a process that died) is taken over.
|
||||
private async Task<bool> TryLockAsync(string code, TimeSpan timeout, CancellationToken cancellationToken)
|
||||
{
|
||||
var now = _clock.GetUtcNow().UtcDateTime;
|
||||
await using var unitOfWork = await _factory.CreateAsync(DatabaseScope.System, cancellationToken).ConfigureAwait(false);
|
||||
var locks = unitOfWork.Repository<JobLock, string>();
|
||||
var acquired = false;
|
||||
await unitOfWork.InTransactionAsync(
|
||||
async ct =>
|
||||
{
|
||||
await unitOfWork.AcquireLockAsync("job-locks", ct).ConfigureAwait(false);
|
||||
var existing = await locks.GetAsync(code, ct).ConfigureAwait(false);
|
||||
if (existing is not null && existing.ExpiresAt > now)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (existing is not null)
|
||||
{
|
||||
await locks.DeleteAsync(code, ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await locks.InsertAsync(new JobLock { Id = code, Owner = _owner, AcquiredAt = now, ExpiresAt = now + timeout + TimeSpan.FromMinutes(1) }, ct).ConfigureAwait(false);
|
||||
acquired = true;
|
||||
},
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
return acquired;
|
||||
}
|
||||
|
||||
private async Task UnlockAsync(string code)
|
||||
{
|
||||
await using var unitOfWork = await _factory.CreateAsync(DatabaseScope.System, CancellationToken.None).ConfigureAwait(false);
|
||||
var owner = _owner;
|
||||
await unitOfWork.ExecuteAsync(
|
||||
SqlFragment.Of($"DELETE FROM {SqlFragment.Identifier("sys_job_locks")} WHERE id = {code} AND owner = {owner}"), CancellationToken.None).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private DateTime? Next(ScheduledTask task, DateTime now)
|
||||
{
|
||||
if (!CronExpression.TryParse(task.Cron, out var cron, out _))
|
||||
{
|
||||
_logger.LogError("Task {Task}: the cron expression '{Cron}' is not valid; the task will not run.", task.Code, task.Cron);
|
||||
return null;
|
||||
}
|
||||
|
||||
var zone = TimeZoneInfo.TryFindSystemTimeZoneById(task.TimeZone, out var found) ? found : TimeZoneInfo.Utc;
|
||||
return cron.NextAfter(now, zone);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Runs the scheduler every 30 seconds once the instance is ready.</summary>
|
||||
/// <param name="scheduler">The scheduler.</param>
|
||||
/// <param name="state">The start state.</param>
|
||||
/// <param name="logger">The log.</param>
|
||||
public sealed class JobSchedulerService(JobScheduler scheduler, BootstrapState state, ILogger<JobSchedulerService> logger) : BackgroundService
|
||||
{
|
||||
/// <summary>How often due tasks are looked for.</summary>
|
||||
public static readonly TimeSpan Interval = TimeSpan.FromSeconds(30);
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
|
||||
{
|
||||
while (!state.IsReady)
|
||||
{
|
||||
if (state.Phase == BootstrapPhase.Failed)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
await Task.Delay(TimeSpan.FromSeconds(1), stoppingToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await scheduler.EnsureSystemTasksAsync(stoppingToken).ConfigureAwait(false);
|
||||
using var timer = new PeriodicTimer(Interval);
|
||||
do
|
||||
{
|
||||
try
|
||||
{
|
||||
await scheduler.RunDueAsync(stoppingToken).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException)
|
||||
{
|
||||
using var section = logger.BeginScope(LogSections.Scope(LogSection.ScheduledJobs));
|
||||
logger.LogError(ex, "The scheduler could not read the tasks.");
|
||||
}
|
||||
}
|
||||
while (await timer.WaitForNextTickAsync(stoppingToken).ConfigureAwait(false));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
using System.Globalization;
|
||||
using Khaemhat.Application.Licensing;
|
||||
using Khaemhat.Application.Notifications;
|
||||
using Khaemhat.Application.Security;
|
||||
using Khaemhat.Core.Instance;
|
||||
using Khaemhat.Data;
|
||||
using Khaemhat.Data.Companies;
|
||||
|
||||
namespace Khaemhat.Application.Jobs;
|
||||
|
||||
/// <summary>Deletes sessions expired or revoked more than 30 days ago, in the system database and in every company.</summary>
|
||||
/// <param name="sessions">The sessions.</param>
|
||||
/// <param name="companies">The companies.</param>
|
||||
public sealed class SessionCleanupJob(SessionStore sessions, ICompanyRegistry companies) : IScheduledJob
|
||||
{
|
||||
/// <summary>The job type.</summary>
|
||||
public const string JobType = "system.sessions-cleanup";
|
||||
|
||||
/// <summary>How long ended sessions stay for the history.</summary>
|
||||
public static readonly TimeSpan Keep = TimeSpan.FromDays(30);
|
||||
|
||||
/// <inheritdoc />
|
||||
public string Type => JobType;
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<string?> RunAsync(JobContext context, CancellationToken cancellationToken)
|
||||
{
|
||||
var deleted = await sessions.PurgeAsync(DatabaseScope.System, Keep, cancellationToken).ConfigureAwait(false);
|
||||
foreach (var company in await companies.ListAsync(cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
if (company.Status is not CompanyStatus.Disabled)
|
||||
{
|
||||
deleted += await sessions.PurgeAsync(DatabaseScope.Company(company.Code), Keep, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
return string.Create(CultureInfo.InvariantCulture, $"{deleted} sessioni eliminate.");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Computes the licence again every hour (SPEC §8.2) and notifies the instance accounts when it is about to expire or
|
||||
/// has expired.
|
||||
/// </summary>
|
||||
/// <param name="licenses">The licence.</param>
|
||||
/// <param name="notifications">The notifications.</param>
|
||||
/// <param name="clock">The clock.</param>
|
||||
public sealed class LicenseCheckJob(ILicenseGate licenses, NotificationDispatcher notifications, TimeProvider clock) : IScheduledJob
|
||||
{
|
||||
/// <summary>The job type.</summary>
|
||||
public const string JobType = "system.license-check";
|
||||
|
||||
/// <inheritdoc />
|
||||
public string Type => JobType;
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<string?> RunAsync(JobContext context, CancellationToken cancellationToken)
|
||||
{
|
||||
var state = await licenses.RefreshAsync(cancellationToken).ConfigureAwait(false);
|
||||
var now = clock.GetUtcNow().UtcDateTime;
|
||||
var days = state.DaysLeft(now);
|
||||
if (state.Status != LicenseStatus.Valid)
|
||||
{
|
||||
await notifications.NotifyInstanceAsync(
|
||||
new NotificationMessage("licenses", NotificationSeverity.Error, "Licenza scaduta", "Rinnova la licenza da Amministrazione > Licenze e moduli.", "/amministrazione/licenze"),
|
||||
cancellationToken: cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
else if (days is 30 or 14 or 7 or 3 or 1 && now.Hour == 9)
|
||||
{
|
||||
await notifications.NotifyInstanceAsync(
|
||||
new NotificationMessage("licenses", NotificationSeverity.Warning, $"La licenza scade tra {days} giorni", null, "/amministrazione/licenze"),
|
||||
cancellationToken: cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
return $"{state.Kind} {state.Status}, moduli {string.Join(',', state.Modules.Order(StringComparer.Ordinal))}.";
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Deletes old log events (SPEC §9.5): debug and trace after 7 days, information after 90, warnings after 180, errors
|
||||
/// and critical events after 365.
|
||||
/// </summary>
|
||||
/// <param name="factory">Opens the system database.</param>
|
||||
/// <param name="clock">The clock.</param>
|
||||
public sealed class LogRetentionJob(IUnitOfWorkFactory factory, TimeProvider clock) : IScheduledJob
|
||||
{
|
||||
/// <summary>The job type.</summary>
|
||||
public const string JobType = "system.log-retention";
|
||||
|
||||
/// <summary>How many days each level is kept.</summary>
|
||||
public static readonly IReadOnlyDictionary<string, int> RetentionDays = new Dictionary<string, int>(StringComparer.Ordinal)
|
||||
{
|
||||
["Trace"] = 7,
|
||||
["Debug"] = 7,
|
||||
["Information"] = 90,
|
||||
["Warning"] = 180,
|
||||
["Error"] = 365,
|
||||
["Critical"] = 365,
|
||||
};
|
||||
|
||||
/// <inheritdoc />
|
||||
public string Type => JobType;
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<string?> RunAsync(JobContext context, CancellationToken cancellationToken)
|
||||
{
|
||||
var now = clock.GetUtcNow().UtcDateTime;
|
||||
var deleted = 0;
|
||||
await using var unitOfWork = await factory.CreateAsync(DatabaseScope.System, cancellationToken).ConfigureAwait(false);
|
||||
foreach (var (level, days) in RetentionDays)
|
||||
{
|
||||
var limit = now.AddDays(-days);
|
||||
deleted += await unitOfWork.ExecuteAsync(
|
||||
SqlFragment.Of($"DELETE FROM {SqlFragment.Identifier("sys_log")} WHERE level = {level} AND at < {limit}"), cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
return string.Create(CultureInfo.InvariantCulture, $"{deleted} eventi eliminati.");
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,11 @@
|
||||
<RootNamespace>Khaemhat.Application</RootNamespace>
|
||||
</PropertyGroup>
|
||||
|
||||
<!-- The ASP.NET Core shared framework (logging, options, DataProtection, hosting): part of .NET, not a package. -->
|
||||
<ItemGroup>
|
||||
<FrameworkReference Include="Microsoft.AspNetCore.App" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="../Khaemhat.Core/Khaemhat.Core.csproj" />
|
||||
<ProjectReference Include="../Khaemhat.Data/Khaemhat.Data.csproj" />
|
||||
|
||||
@@ -0,0 +1,384 @@
|
||||
using System.Globalization;
|
||||
using Khaemhat.Application.Audit;
|
||||
using Khaemhat.Application.Configuration;
|
||||
using Khaemhat.Application.Instance;
|
||||
using Khaemhat.Application.Modules;
|
||||
using Khaemhat.Application.Security;
|
||||
using Khaemhat.Core.Instance;
|
||||
using Khaemhat.Data;
|
||||
using Khaemhat.Data.Querying;
|
||||
using Khaemhat.Infrastructure.Licensing;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace Khaemhat.Application.Licensing;
|
||||
|
||||
/// <summary>The licence in force and the modules it activates.</summary>
|
||||
public interface ILicenseGate
|
||||
{
|
||||
/// <summary>The licence computed at the last refresh.</summary>
|
||||
LicenseState Current { get; }
|
||||
|
||||
/// <summary>Whether a module is licensed.</summary>
|
||||
/// <param name="moduleCode">The module code.</param>
|
||||
/// <returns><see langword="true"/> if active.</returns>
|
||||
bool IsModuleActive(string moduleCode);
|
||||
|
||||
/// <summary>Recomputes the licence from the database and the environment.</summary>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The new state.</returns>
|
||||
Task<LicenseState> RefreshAsync(CancellationToken cancellationToken = default);
|
||||
}
|
||||
|
||||
/// <summary>Where the gate reads the licence from the environment.</summary>
|
||||
/// <param name="EnvironmentLicense">The text of <c>KHAEMHAT_LICENSE</c>, if set.</param>
|
||||
/// <param name="Mode">The licence mode.</param>
|
||||
public sealed record LicenseSettings(string? EnvironmentLicense, LicenseMode Mode);
|
||||
|
||||
/// <summary>
|
||||
/// Computes the licence (SPEC §8): the best signed licence (environment or installed) bound to this instance, else the
|
||||
/// trial; plus the module activation codes; plus, in test mode only, the fictitious codes. Every signature is checked
|
||||
/// again at each refresh, so a row changed in the database does not grant anything.
|
||||
/// </summary>
|
||||
public sealed class LicenseGate : ILicenseGate
|
||||
{
|
||||
private readonly IUnitOfWorkFactory _factory;
|
||||
private readonly SystemSettingsStore _settings;
|
||||
private readonly LicenseVerifier _verifier;
|
||||
private readonly LicenseSettings _licenseSettings;
|
||||
private readonly TimeProvider _clock;
|
||||
private readonly ILogger<LicenseGate> _logger;
|
||||
private volatile LicenseState _current;
|
||||
|
||||
/// <summary>Creates the gate. Until the first refresh the state is the trial.</summary>
|
||||
/// <param name="factory">Opens the system database.</param>
|
||||
/// <param name="settings">The instance settings.</param>
|
||||
/// <param name="verifier">Checks signatures.</param>
|
||||
/// <param name="licenseSettings">The environment licence and mode.</param>
|
||||
/// <param name="clock">The clock.</param>
|
||||
/// <param name="logger">The log.</param>
|
||||
public LicenseGate(
|
||||
IUnitOfWorkFactory factory, SystemSettingsStore settings, LicenseVerifier verifier, LicenseSettings licenseSettings,
|
||||
TimeProvider clock, ILogger<LicenseGate> logger)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(factory);
|
||||
ArgumentNullException.ThrowIfNull(settings);
|
||||
ArgumentNullException.ThrowIfNull(verifier);
|
||||
ArgumentNullException.ThrowIfNull(licenseSettings);
|
||||
ArgumentNullException.ThrowIfNull(clock);
|
||||
ArgumentNullException.ThrowIfNull(logger);
|
||||
_factory = factory;
|
||||
_settings = settings;
|
||||
_verifier = verifier;
|
||||
_licenseSettings = licenseSettings;
|
||||
_clock = clock;
|
||||
_logger = logger;
|
||||
var now = clock.GetUtcNow().UtcDateTime;
|
||||
_current = Trial(now, now, 0, [], 0, licenseSettings.Mode == LicenseMode.Test);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public LicenseState Current => _current;
|
||||
|
||||
/// <summary>The instance identifier read at the last refresh.</summary>
|
||||
public string? InstanceId { get; private set; }
|
||||
|
||||
/// <inheritdoc />
|
||||
public bool IsModuleActive(string moduleCode) => _current.Includes(moduleCode);
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<LicenseState> RefreshAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
var now = _clock.GetUtcNow().UtcDateTime;
|
||||
var testMode = _licenseSettings.Mode == LicenseMode.Test;
|
||||
InstanceId = await _settings.GetAsync(SystemSettingsStore.InstanceIdKey, cancellationToken).ConfigureAwait(false);
|
||||
var trialStart = DateTime.TryParse(
|
||||
await _settings.GetAsync(SystemSettingsStore.TrialStartedKey, cancellationToken).ConfigureAwait(false),
|
||||
CultureInfo.InvariantCulture,
|
||||
DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal,
|
||||
out var started) ? started : now;
|
||||
|
||||
IReadOnlyList<LicenseRecord> records;
|
||||
await using (var unitOfWork = await _factory.CreateAsync(DatabaseScope.System, cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
records = (await unitOfWork.Repository<LicenseRecord, long>()
|
||||
.ListAsync(Query.For<LicenseRecord>().Where(r => r.IsActive).OrderBy(r => r.Id), cancellationToken).ConfigureAwait(false)).Items;
|
||||
}
|
||||
|
||||
var documents = records.Where(r => r.Source == LicenseSource.File).Select(r => r.Payload).ToList();
|
||||
if (_licenseSettings.EnvironmentLicense is { } environment)
|
||||
{
|
||||
documents.Insert(0, environment);
|
||||
}
|
||||
|
||||
var license = documents
|
||||
.Select(text => _verifier.Verify(text).Document)
|
||||
.Where(d => d is not null && (d.InstanceId is null || string.Equals(d.InstanceId, InstanceId, StringComparison.OrdinalIgnoreCase)))
|
||||
.OrderByDescending(d => d!.ExpiresAt ?? DateTime.MaxValue)
|
||||
.FirstOrDefault();
|
||||
|
||||
var extraModules = new HashSet<string>(StringComparer.Ordinal);
|
||||
foreach (var record in records.Where(r => r.Source == LicenseSource.ActivationCode))
|
||||
{
|
||||
var (code, _) = _verifier.VerifyActivationCode(record.Payload);
|
||||
if (code is not null && code.ExpiresAt > now && (InstanceId is null || code.IsFor(InstanceId)))
|
||||
{
|
||||
extraModules.Add(code.Module);
|
||||
}
|
||||
}
|
||||
|
||||
var testUsers = 0;
|
||||
var trialExtension = 0;
|
||||
if (testMode)
|
||||
{
|
||||
foreach (var test in records.Where(r => r.Source == LicenseSource.TestCode).Select(r => TestLicenseCatalog.Find(r.Payload)).OfType<TestCode>())
|
||||
{
|
||||
extraModules.UnionWith(test.Modules);
|
||||
testUsers = Math.Max(testUsers, test.ConcurrentUsers);
|
||||
trialExtension += test.TrialExtensionDays;
|
||||
}
|
||||
}
|
||||
|
||||
var state = license is null
|
||||
? Trial(now, trialStart, trialExtension, extraModules, testUsers, testMode)
|
||||
: Licensed(now, license, extraModules, testUsers, testMode);
|
||||
if (state.Status != _current.Status || state.Kind != _current.Kind)
|
||||
{
|
||||
_logger.LogInformation("Licence {Kind} {Status}: modules {Modules}, {Users} users.", state.Kind, state.Status, string.Join(',', state.Modules), state.MaxConcurrentUsers);
|
||||
}
|
||||
|
||||
_current = state;
|
||||
return state;
|
||||
}
|
||||
|
||||
private static LicenseState Trial(DateTime now, DateTime trialStart, int extensionDays, IEnumerable<string> extra, int testUsers, bool testMode)
|
||||
{
|
||||
var modules = new HashSet<string>(LicenseState.TrialModules, StringComparer.Ordinal);
|
||||
modules.UnionWith(extra);
|
||||
var expires = trialStart + LicenseState.TrialLength + TimeSpan.FromDays(extensionDays);
|
||||
return new LicenseState
|
||||
{
|
||||
Kind = LicenseKind.Trial,
|
||||
Status = now <= expires ? LicenseStatus.Valid : LicenseStatus.Expired,
|
||||
Modules = modules,
|
||||
MaxConcurrentUsers = Math.Max(LicenseState.TrialUsers, testUsers),
|
||||
MaxCompanies = modules.Contains(ModuleCodes.MultiCompany) ? int.MaxValue : 1,
|
||||
ExpiresAt = expires,
|
||||
GraceEndsAt = expires,
|
||||
IsTestMode = testMode,
|
||||
};
|
||||
}
|
||||
|
||||
private static LicenseState Licensed(DateTime now, LicenseDocument license, IEnumerable<string> extra, int testUsers, bool testMode)
|
||||
{
|
||||
var modules = new HashSet<string>(license.Modules.Select(m => m.Trim().ToUpperInvariant()), StringComparer.Ordinal) { ModuleCodes.Core };
|
||||
modules.UnionWith(extra);
|
||||
var graceEnds = license.ExpiresAt?.AddDays(license.GracePeriodDays);
|
||||
var status = license.ExpiresAt is not { } expires || now <= expires
|
||||
? LicenseStatus.Valid
|
||||
: now <= graceEnds ? LicenseStatus.Grace : LicenseStatus.Expired;
|
||||
return new LicenseState
|
||||
{
|
||||
Kind = LicenseKind.Licensed,
|
||||
Status = status,
|
||||
Licensee = license.Licensee,
|
||||
Modules = modules,
|
||||
MaxConcurrentUsers = Math.Max(license.MaxConcurrentUsers, testUsers),
|
||||
MaxCompanies = modules.Contains(ModuleCodes.MultiCompany) ? (license.MaxCompanies > 1 ? license.MaxCompanies : int.MaxValue) : 1,
|
||||
ExpiresAt = license.ExpiresAt,
|
||||
GraceEndsAt = graceEnds,
|
||||
IsTestMode = testMode,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The outcome of an activation.</summary>
|
||||
/// <param name="Succeeded">Whether the licence or code was installed.</param>
|
||||
/// <param name="Outcome">The outcome code: <c>ok</c> or one of <see cref="LicenseErrors"/>.</param>
|
||||
/// <param name="State">The licence in force afterwards.</param>
|
||||
public sealed record ActivationResult(bool Succeeded, string Outcome, LicenseState State);
|
||||
|
||||
/// <summary>Installs and removes licences (SPEC §8.2). Today offline; a remote activation server may come later.</summary>
|
||||
public interface ILicenseActivationService
|
||||
{
|
||||
/// <summary>Installs a <c>.khl</c> licence, a module activation code or, in test mode, a fictitious code.</summary>
|
||||
/// <param name="actor">Who acts: only the super user.</param>
|
||||
/// <param name="input">The licence text or the code.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The outcome.</returns>
|
||||
Task<ActivationResult> ActivateAsync(Actor actor, string input, CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>Removes an installed licence or code (it stays in the history).</summary>
|
||||
/// <param name="actor">Who acts: only the super user.</param>
|
||||
/// <param name="licenseId">The row of <c>sys_licenses</c>.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The licence in force afterwards.</returns>
|
||||
Task<LicenseState> DeactivateAsync(Actor actor, long licenseId, CancellationToken cancellationToken = default);
|
||||
}
|
||||
|
||||
/// <summary>Activation checked locally with the public key: no network involved.</summary>
|
||||
public sealed class OfflineActivationService(
|
||||
IUnitOfWorkFactory factory, LicenseGate gate, LicenseVerifier verifier, LicenseSettings settings, ModuleRegistry modules,
|
||||
ISecurityAuditLog audit, TimeProvider clock) : ILicenseActivationService
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public async Task<ActivationResult> ActivateAsync(Actor actor, string input, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(actor);
|
||||
RequireSuperUser(actor);
|
||||
var text = (input ?? string.Empty).Trim();
|
||||
var now = clock.GetUtcNow().UtcDateTime;
|
||||
if (gate.InstanceId is null)
|
||||
{
|
||||
await gate.RefreshAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
var (record, outcome) = Prepare(text, now);
|
||||
await using (var unitOfWork = await factory.CreateAsync(DatabaseScope.System, cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
await unitOfWork.InTransactionAsync(
|
||||
async ct =>
|
||||
{
|
||||
if (record is not null)
|
||||
{
|
||||
var licenses = unitOfWork.Repository<LicenseRecord, long>();
|
||||
if (record.Source == LicenseSource.File)
|
||||
{
|
||||
// A new instance licence replaces the previous one; codes stay.
|
||||
foreach (var old in (await licenses.ListAsync(
|
||||
Query.For<LicenseRecord>().Where(r => r.IsActive && r.Source == LicenseSource.File), ct).ConfigureAwait(false)).Items)
|
||||
{
|
||||
old.IsActive = false;
|
||||
await licenses.UpdateAsync(old, ct).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
await licenses.InsertAsync(record, ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await unitOfWork.Repository<LicenseActivation, long>().InsertAsync(
|
||||
new LicenseActivation
|
||||
{
|
||||
Action = record is null ? "rejected" : "activated",
|
||||
Source = record?.Source ?? SourceOf(text),
|
||||
Modules = record?.Modules,
|
||||
Outcome = outcome,
|
||||
},
|
||||
ct).ConfigureAwait(false);
|
||||
},
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await audit.WriteAsync(
|
||||
new SecurityEvent(record is null ? "license.rejected" : "license.activated", actor.UserName, Target: record?.Modules, Details: new { outcome }),
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
var state = await gate.RefreshAsync(cancellationToken).ConfigureAwait(false);
|
||||
return new ActivationResult(record is not null, outcome, state);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<LicenseState> DeactivateAsync(Actor actor, long licenseId, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(actor);
|
||||
RequireSuperUser(actor);
|
||||
string? modules;
|
||||
await using (var unitOfWork = await factory.CreateAsync(DatabaseScope.System, cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
var licenses = unitOfWork.Repository<LicenseRecord, long>();
|
||||
var record = await licenses.GetAsync(licenseId, cancellationToken).ConfigureAwait(false)
|
||||
?? throw new KeyNotFoundException("No installed licence has this identifier.");
|
||||
record.IsActive = false;
|
||||
modules = record.Modules;
|
||||
await licenses.UpdateAsync(record, cancellationToken).ConfigureAwait(false);
|
||||
await unitOfWork.Repository<LicenseActivation, long>().InsertAsync(
|
||||
new LicenseActivation { Action = "deactivated", Source = record.Source, Modules = record.Modules, Outcome = "ok" }, cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await audit.WriteAsync(new SecurityEvent("license.deactivated", actor.UserName, Target: modules), cancellationToken).ConfigureAwait(false);
|
||||
return await gate.RefreshAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private (LicenseRecord? Record, string Outcome) Prepare(string text, DateTime now)
|
||||
{
|
||||
if (TestLicenseCatalog.LooksLikeTestCode(text))
|
||||
{
|
||||
if (settings.Mode != LicenseMode.Test)
|
||||
{
|
||||
return (null, LicenseErrors.TestOnly);
|
||||
}
|
||||
|
||||
var test = TestLicenseCatalog.Find(text);
|
||||
return test is null
|
||||
? (null, LicenseErrors.FormatInvalid)
|
||||
: (new LicenseRecord { Source = LicenseSource.TestCode, Payload = text.ToUpperInvariant(), Modules = string.Join(',', test.Modules), Licensee = "Test" }, "ok");
|
||||
}
|
||||
|
||||
if (text.StartsWith(ModuleActivationCode.Prefix + "-", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
var (code, error) = verifier.VerifyActivationCode(text);
|
||||
if (code is null)
|
||||
{
|
||||
return (null, error!);
|
||||
}
|
||||
|
||||
if (modules.FindModule(code.Module) is null)
|
||||
{
|
||||
return (null, LicenseErrors.UnknownModule);
|
||||
}
|
||||
|
||||
if (code.ExpiresAt <= now)
|
||||
{
|
||||
return (null, LicenseErrors.Expired);
|
||||
}
|
||||
|
||||
if (gate.InstanceId is { } instance && !code.IsFor(instance))
|
||||
{
|
||||
return (null, LicenseErrors.WrongInstance);
|
||||
}
|
||||
|
||||
return (new LicenseRecord { Source = LicenseSource.ActivationCode, Payload = text.ToUpperInvariant(), Modules = code.Module, ExpiresAt = code.ExpiresAt }, "ok");
|
||||
}
|
||||
|
||||
var verification = verifier.Verify(text);
|
||||
if (verification.Document is not { } document)
|
||||
{
|
||||
return (null, verification.Error!);
|
||||
}
|
||||
|
||||
if (document.InstanceId is not null && !string.Equals(document.InstanceId, gate.InstanceId, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return (null, LicenseErrors.WrongInstance);
|
||||
}
|
||||
|
||||
if (document.ExpiresAt is { } expires && expires.AddDays(document.GracePeriodDays) <= now)
|
||||
{
|
||||
return (null, LicenseErrors.Expired);
|
||||
}
|
||||
|
||||
return (new LicenseRecord
|
||||
{
|
||||
Source = LicenseSource.File,
|
||||
Payload = text,
|
||||
Licensee = document.Licensee.Length > 200 ? document.Licensee[..200] : document.Licensee,
|
||||
Modules = string.Join(',', document.Modules),
|
||||
MaxConcurrentUsers = document.MaxConcurrentUsers,
|
||||
MaxCompanies = document.MaxCompanies,
|
||||
IssuedAt = document.IssuedAt,
|
||||
ExpiresAt = document.ExpiresAt,
|
||||
GracePeriodDays = document.GracePeriodDays,
|
||||
}, "ok");
|
||||
}
|
||||
|
||||
private static LicenseSource SourceOf(string text) =>
|
||||
TestLicenseCatalog.LooksLikeTestCode(text) ? LicenseSource.TestCode
|
||||
: text.StartsWith(ModuleActivationCode.Prefix + "-", StringComparison.OrdinalIgnoreCase) ? LicenseSource.ActivationCode
|
||||
: LicenseSource.File;
|
||||
|
||||
private static void RequireSuperUser(Actor actor)
|
||||
{
|
||||
if (!actor.IsSuperUser)
|
||||
{
|
||||
throw new AccessDeniedException(SecurityErrors.LevelTooLow, "Only the super user activates licences and modules.");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
using Khaemhat.Application.Modules;
|
||||
|
||||
namespace Khaemhat.Application.Licensing;
|
||||
|
||||
/// <summary>Where the instance stands with its licence.</summary>
|
||||
public enum LicenseStatus
|
||||
{
|
||||
/// <summary>Valid.</summary>
|
||||
Valid = 0,
|
||||
|
||||
/// <summary>Expired but within the grace period: everything works, with a banner.</summary>
|
||||
Grace = 1,
|
||||
|
||||
/// <summary>Expired beyond the grace period: read-only with a banner (SPEC §8.2).</summary>
|
||||
Expired = 2,
|
||||
}
|
||||
|
||||
/// <summary>What kind of licence is in force.</summary>
|
||||
public enum LicenseKind
|
||||
{
|
||||
/// <summary>No licence: CORE and ACCT, 3 users, 60 days.</summary>
|
||||
Trial = 0,
|
||||
|
||||
/// <summary>A signed licence.</summary>
|
||||
Licensed = 1,
|
||||
}
|
||||
|
||||
/// <summary>The licence in force, computed by <see cref="LicenseGate"/>. Immutable.</summary>
|
||||
public sealed record LicenseState
|
||||
{
|
||||
/// <summary>The trial modules (SPEC §6).</summary>
|
||||
public static readonly IReadOnlyList<string> TrialModules = [ModuleCodes.Core, ModuleCodes.Accounting];
|
||||
|
||||
/// <summary>The trial users.</summary>
|
||||
public const int TrialUsers = 3;
|
||||
|
||||
/// <summary>The trial length.</summary>
|
||||
public static readonly TimeSpan TrialLength = TimeSpan.FromDays(60);
|
||||
|
||||
/// <summary>The licence kind.</summary>
|
||||
public LicenseKind Kind { get; init; }
|
||||
|
||||
/// <summary>The status.</summary>
|
||||
public LicenseStatus Status { get; init; }
|
||||
|
||||
/// <summary>The holder.</summary>
|
||||
public string? Licensee { get; init; }
|
||||
|
||||
/// <summary>The active modules.</summary>
|
||||
public IReadOnlySet<string> Modules { get; init; } = new HashSet<string>(StringComparer.Ordinal);
|
||||
|
||||
/// <summary>The concurrent users allowed across all companies.</summary>
|
||||
public int MaxConcurrentUsers { get; init; }
|
||||
|
||||
/// <summary>The companies allowed.</summary>
|
||||
public int MaxCompanies { get; init; }
|
||||
|
||||
/// <summary>When the licence (or the trial) expires.</summary>
|
||||
public DateTime? ExpiresAt { get; init; }
|
||||
|
||||
/// <summary>When the grace period ends.</summary>
|
||||
public DateTime? GraceEndsAt { get; init; }
|
||||
|
||||
/// <summary>Whether the fictitious codes are accepted (<c>KHAEMHAT_LICENSE_MODE=test</c>): the interface shows a banner.</summary>
|
||||
public bool IsTestMode { get; init; }
|
||||
|
||||
/// <summary>Whether data can only be read.</summary>
|
||||
public bool IsReadOnly => Status == LicenseStatus.Expired;
|
||||
|
||||
/// <summary>Whether a module is active.</summary>
|
||||
/// <param name="module">The module code.</param>
|
||||
/// <returns><see langword="true"/> if licensed.</returns>
|
||||
public bool Includes(string module) => Modules.Contains(module);
|
||||
|
||||
/// <summary>Days left before the expiry (0 when expired), or <see langword="null"/> without expiry.</summary>
|
||||
/// <param name="now">The current time.</param>
|
||||
/// <returns>The days.</returns>
|
||||
public int? DaysLeft(DateTime now) => ExpiresAt is { } expires ? Math.Max(0, (int)Math.Ceiling((expires - now).TotalDays)) : null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The fictitious licence codes of SPEC §8.3, valid only with <c>KHAEMHAT_LICENSE_MODE=test</c>. Outside test mode they
|
||||
/// are refused with <c>license_test_only</c>. Automated tests use <see cref="All"/>.
|
||||
/// </summary>
|
||||
public static class TestLicenseCatalog
|
||||
{
|
||||
/// <summary>Every module.</summary>
|
||||
public const string All = "KH-TEST-ALL-0000-9999";
|
||||
|
||||
/// <summary>25 concurrent users.</summary>
|
||||
public const string Users25 = "KH-TEST-USERS-0025-0014";
|
||||
|
||||
/// <summary>60 more days of trial.</summary>
|
||||
public const string TrialExtension = "KH-TEST-TRIAL-0060-0015";
|
||||
|
||||
private static readonly Dictionary<string, TestCode> Codes = new(StringComparer.Ordinal)
|
||||
{
|
||||
["KH-TEST-CORE-0000-0001"] = Module(ModuleCodes.Core),
|
||||
["KH-TEST-ACCT-0000-0002"] = Module(ModuleCodes.Accounting),
|
||||
["KH-TEST-ASSET-0000-0003"] = Module(ModuleCodes.Assets),
|
||||
["KH-TEST-FIN-0000-0004"] = Module(ModuleCodes.Finance),
|
||||
["KH-TEST-EINV-0000-0005"] = Module(ModuleCodes.EInvoicing),
|
||||
["KH-TEST-INTRA-0000-0006"] = Module(ModuleCodes.Intrastat),
|
||||
["KH-TEST-CRM-0000-0007"] = Module(ModuleCodes.Crm),
|
||||
["KH-TEST-SVC-0000-0008"] = Module(ModuleCodes.Services),
|
||||
["KH-TEST-CHAN-0000-0009"] = Module(ModuleCodes.Channels),
|
||||
["KH-TEST-AUTO-0000-0010"] = Module(ModuleCodes.Automation),
|
||||
["KH-TEST-API-0000-0011"] = Module(ModuleCodes.Api),
|
||||
["KH-TEST-MULTI-0000-0012"] = Module(ModuleCodes.MultiCompany),
|
||||
["KH-TEST-REPORT-0000-0013"] = Module(ModuleCodes.Reports),
|
||||
[All] = new TestCode([.. BuiltInModules.All.Select(m => m.Code)], 0, 0),
|
||||
[Users25] = new TestCode([], 25, 0),
|
||||
[TrialExtension] = new TestCode([], 0, 60),
|
||||
};
|
||||
|
||||
/// <summary>Every code.</summary>
|
||||
public static IReadOnlyCollection<string> AllCodes => Codes.Keys;
|
||||
|
||||
/// <summary>Whether the text looks like a fictitious code (to refuse it with the right error outside test mode).</summary>
|
||||
/// <param name="text">The text.</param>
|
||||
/// <returns><see langword="true"/> if it starts with <c>KH-TEST-</c>.</returns>
|
||||
public static bool LooksLikeTestCode(string? text) => text?.Trim().StartsWith("KH-TEST-", StringComparison.OrdinalIgnoreCase) == true;
|
||||
|
||||
/// <summary>Finds a code.</summary>
|
||||
/// <param name="code">The code.</param>
|
||||
/// <returns>The effect, or <see langword="null"/> when unknown.</returns>
|
||||
public static TestCode? Find(string code) => Codes.GetValueOrDefault(code.Trim().ToUpperInvariant());
|
||||
|
||||
private static TestCode Module(string module) => new([module], 0, 0);
|
||||
}
|
||||
|
||||
/// <summary>The effect of a fictitious code.</summary>
|
||||
/// <param name="Modules">The modules it activates.</param>
|
||||
/// <param name="ConcurrentUsers">The users it grants (0 = no change).</param>
|
||||
/// <param name="TrialExtensionDays">The days it adds to the trial.</param>
|
||||
public sealed record TestCode(IReadOnlyList<string> Modules, int ConcurrentUsers, int TrialExtensionDays);
|
||||
@@ -0,0 +1,152 @@
|
||||
namespace Khaemhat.Application.Modules;
|
||||
|
||||
/// <summary>
|
||||
/// The modules of SPEC §8.1 with their permissions. Codes follow <c>area.entity.action</c>; the area is functional
|
||||
/// (<c>sales</c>, <c>ledger</c>...) while <see cref="PermissionDefinition.Module"/> is the licence code.
|
||||
/// </summary>
|
||||
public static class BuiltInModules
|
||||
{
|
||||
/// <summary>Every module, in the order of SPEC §8.1.</summary>
|
||||
public static IReadOnlyList<IModule> All { get; } =
|
||||
[
|
||||
Module(ModuleCodes.Core, "Base",
|
||||
("company.users.manage", "Gestire utenti e ruoli dell'azienda"),
|
||||
("company.settings.read", "Vedere le impostazioni dell'azienda"),
|
||||
("company.settings.write", "Modificare le impostazioni dell'azienda"),
|
||||
("parties.party.read", "Vedere anagrafiche"),
|
||||
("parties.party.write", "Creare e modificare anagrafiche"),
|
||||
("parties.party.delete", "Eliminare anagrafiche"),
|
||||
("parties.party.export", "Esportare anagrafiche"),
|
||||
("items.item.read", "Vedere articoli e listini"),
|
||||
("items.item.write", "Creare e modificare articoli e listini"),
|
||||
("items.item.delete", "Eliminare articoli"),
|
||||
("items.cost.read", "Vedere costi e margini degli articoli"),
|
||||
("sales.quote.read", "Vedere preventivi"),
|
||||
("sales.quote.write", "Creare e modificare preventivi"),
|
||||
("sales.order.read", "Vedere ordini cliente"),
|
||||
("sales.order.write", "Creare e modificare ordini cliente"),
|
||||
("sales.delivery.read", "Vedere DDT di vendita"),
|
||||
("sales.delivery.write", "Creare e modificare DDT di vendita"),
|
||||
("sales.invoice.read", "Vedere fatture di vendita"),
|
||||
("sales.invoice.write", "Creare e modificare fatture in bozza"),
|
||||
("sales.invoice.issue", "Emettere fatture di vendita"),
|
||||
("sales.invoice.delete", "Eliminare fatture in bozza"),
|
||||
("sales.invoice.print", "Stampare fatture di vendita"),
|
||||
("sales.invoice.export", "Esportare fatture di vendita"),
|
||||
("purchases.order.read", "Vedere ordini fornitore"),
|
||||
("purchases.order.write", "Creare e modificare ordini fornitore"),
|
||||
("purchases.invoice.read", "Vedere fatture di acquisto"),
|
||||
("purchases.invoice.write", "Registrare fatture di acquisto"),
|
||||
("inventory.stock.read", "Vedere giacenze"),
|
||||
("inventory.entry.read", "Vedere movimenti di magazzino"),
|
||||
("inventory.entry.write", "Creare movimenti di magazzino in bozza"),
|
||||
("inventory.entry.post", "Confermare movimenti di magazzino"),
|
||||
("attachments.read", "Vedere e scaricare allegati"),
|
||||
("attachments.write", "Caricare e generare allegati"),
|
||||
("attachments.delete", "Eliminare allegati"),
|
||||
("reports.report.read", "Vedere i report di base")),
|
||||
Module(ModuleCodes.Accounting, "Contabilità",
|
||||
("ledger.account.read", "Vedere il piano dei conti"),
|
||||
("ledger.account.write", "Modificare il piano dei conti"),
|
||||
("ledger.entry.read", "Vedere la prima nota"),
|
||||
("ledger.entry.write", "Registrare in prima nota"),
|
||||
("ledger.entry.finalize", "Rendere definitive le registrazioni"),
|
||||
("ledger.entry.reopen", "Riaprire registrazioni definitive"),
|
||||
("ledger.year.close", "Chiudere l'esercizio"),
|
||||
("vat.register.read", "Vedere i registri IVA"),
|
||||
("vat.settlement.read", "Vedere le liquidazioni IVA"),
|
||||
("vat.settlement.confirm", "Confermare le liquidazioni IVA")),
|
||||
Module(ModuleCodes.Assets, "Cespiti",
|
||||
("assets.asset.read", "Vedere i cespiti"),
|
||||
("assets.asset.write", "Gestire i cespiti"),
|
||||
("assets.depreciation.post", "Registrare gli ammortamenti")),
|
||||
Module(ModuleCodes.Finance, "Tesoreria",
|
||||
("finance.schedule.read", "Vedere lo scadenzario"),
|
||||
("finance.schedule.write", "Modificare lo scadenzario"),
|
||||
("finance.payment.read", "Vedere incassi e pagamenti"),
|
||||
("finance.payment.write", "Registrare incassi e pagamenti"),
|
||||
("finance.bank.reconcile", "Riconciliare i movimenti bancari")),
|
||||
Module(ModuleCodes.EInvoicing, "Fatturazione elettronica",
|
||||
("einvoice.document.read", "Vedere i documenti elettronici"),
|
||||
("einvoice.document.send", "Inviare documenti allo SDI"),
|
||||
("einvoice.inbox.read", "Vedere le fatture ricevute"),
|
||||
("einvoice.inbox.import", "Importare le fatture ricevute")),
|
||||
Module(ModuleCodes.Intrastat, "Intrastat",
|
||||
("intrastat.list.read", "Vedere gli elenchi Intrastat"),
|
||||
("intrastat.list.write", "Compilare gli elenchi Intrastat"),
|
||||
("intrastat.list.export", "Esportare il file per le Dogane")),
|
||||
Module(ModuleCodes.Crm, "CRM",
|
||||
("crm.lead.read", "Vedere i lead"),
|
||||
("crm.lead.write", "Gestire i lead"),
|
||||
("crm.opportunity.read", "Vedere le opportunità"),
|
||||
("crm.opportunity.write", "Gestire le opportunità"),
|
||||
("crm.activity.read", "Vedere attività e agenda"),
|
||||
("crm.activity.write", "Gestire attività e agenda"),
|
||||
("crm.campaign.read", "Vedere le campagne"),
|
||||
("crm.campaign.write", "Gestire le campagne"),
|
||||
("crm.ticket.read", "Vedere i ticket"),
|
||||
("crm.ticket.write", "Gestire i ticket")),
|
||||
Module(ModuleCodes.Services, "Servizi",
|
||||
("services.contract.read", "Vedere i contratti di assistenza"),
|
||||
("services.contract.write", "Gestire i contratti di assistenza"),
|
||||
("services.intervention.read", "Vedere gli interventi"),
|
||||
("services.intervention.write", "Gestire interventi e rapportini")),
|
||||
Module(ModuleCodes.Channels, "Canali e-commerce",
|
||||
("channels.channel.read", "Vedere i canali"),
|
||||
("channels.channel.write", "Configurare i canali"),
|
||||
("channels.order.import", "Importare gli ordini web")),
|
||||
Module(ModuleCodes.Automation, "Automazioni",
|
||||
("automation.rule.read", "Vedere le regole"),
|
||||
("automation.rule.write", "Gestire le regole"),
|
||||
("automation.procedure.run", "Eseguire le procedure")),
|
||||
Module(ModuleCodes.Api, "Integrazioni",
|
||||
("api.key.manage", "Gestire le chiavi API dell'azienda"),
|
||||
("api.webhook.manage", "Gestire i webhook")),
|
||||
Module(ModuleCodes.MultiCompany, "Multi-azienda"),
|
||||
Module(ModuleCodes.Reports, "Report avanzati",
|
||||
("reports.advanced.read", "Vedere i report avanzati"),
|
||||
("reports.schedule.write", "Pianificare report via e-mail"),
|
||||
("reports.accountant.export", "Esportare i dati per il commercialista")),
|
||||
];
|
||||
|
||||
private static ModuleDefinition Module(string code, string name, params (string Code, string Description)[] permissions) =>
|
||||
new(code, name, [.. permissions.Select(p => new PermissionDefinition(p.Code, code, p.Description))]);
|
||||
}
|
||||
|
||||
/// <summary>A predefined role (SPEC §7.2): kept in <c>sys_roles_templates</c> and copied into each company.</summary>
|
||||
/// <param name="Code">The role code.</param>
|
||||
/// <param name="Name">The name shown.</param>
|
||||
/// <param name="Description">What the role is for.</param>
|
||||
/// <param name="Permissions">The permission patterns.</param>
|
||||
public sealed record RoleTemplateDefinition(string Code, string Name, string Description, IReadOnlyList<string> Permissions);
|
||||
|
||||
/// <summary>The eight predefined roles of SPEC §7.2.</summary>
|
||||
public static class PredefinedRoles
|
||||
{
|
||||
/// <summary>The administration role: every permission.</summary>
|
||||
public const string Administration = "ADMIN";
|
||||
|
||||
/// <summary>The read-only role.</summary>
|
||||
public const string ReadOnly = "READONLY";
|
||||
|
||||
/// <summary>The roles, in display order.</summary>
|
||||
public static IReadOnlyList<RoleTemplateDefinition> All { get; } =
|
||||
[
|
||||
new(Administration, "Amministrazione", "Tutte le funzioni dell'azienda, compresi utenti e impostazioni.", ["*"]),
|
||||
new("ACCOUNTING", "Contabilità", "Contabilità, IVA, cespiti, tesoreria, fatturazione elettronica e Intrastat.",
|
||||
["ledger.*", "vat.*", "assets.*", "finance.*", "einvoice.*", "intrastat.*", "parties.party.read", "sales.invoice.read",
|
||||
"purchases.invoice.*", "reports.report.read", "attachments.read", "attachments.write"]),
|
||||
new("SALES", "Vendite", "Preventivi, ordini, DDT e fatture di vendita; anagrafiche clienti.",
|
||||
["sales.*", "parties.*", "items.item.read", "inventory.stock.read", "crm.lead.read", "crm.opportunity.read",
|
||||
"reports.report.read", "attachments.read", "attachments.write"]),
|
||||
new("PURCHASES", "Acquisti", "Ordini e fatture fornitore, anagrafiche e articoli.",
|
||||
["purchases.*", "parties.*", "items.*", "inventory.stock.read", "reports.report.read", "attachments.read", "attachments.write"]),
|
||||
new("WAREHOUSE", "Magazzino", "Movimenti, giacenze e DDT.",
|
||||
["inventory.*", "items.item.read", "items.item.write", "sales.delivery.*", "purchases.order.read", "attachments.read"]),
|
||||
new("CRM", "CRM", "Lead, opportunità, attività, campagne e ticket.",
|
||||
["crm.*", "parties.*", "sales.quote.*", "attachments.read", "attachments.write"]),
|
||||
new("SERVICES", "Servizi", "Contratti di assistenza, interventi e ticket.",
|
||||
["services.*", "parties.party.read", "items.item.read", "crm.ticket.*", "attachments.read", "attachments.write"]),
|
||||
new(ReadOnly, "Sola lettura", "Vede tutto ciò che la licenza comprende, senza modificare nulla.", ["*.read"]),
|
||||
];
|
||||
}
|
||||
@@ -0,0 +1,166 @@
|
||||
namespace Khaemhat.Application.Modules;
|
||||
|
||||
/// <summary>The module codes of SPEC §8.1, which are also the licence codes.</summary>
|
||||
public static class ModuleCodes
|
||||
{
|
||||
/// <summary>Base: parties, items, documents, warehouse, administration.</summary>
|
||||
public const string Core = "CORE";
|
||||
|
||||
/// <summary>Accounting and VAT.</summary>
|
||||
public const string Accounting = "ACCT";
|
||||
|
||||
/// <summary>Fixed assets.</summary>
|
||||
public const string Assets = "ASSET";
|
||||
|
||||
/// <summary>Treasury.</summary>
|
||||
public const string Finance = "FIN";
|
||||
|
||||
/// <summary>Electronic invoicing.</summary>
|
||||
public const string EInvoicing = "EINV";
|
||||
|
||||
/// <summary>Intrastat.</summary>
|
||||
public const string Intrastat = "INTRA";
|
||||
|
||||
/// <summary>CRM.</summary>
|
||||
public const string Crm = "CRM";
|
||||
|
||||
/// <summary>Services.</summary>
|
||||
public const string Services = "SVC";
|
||||
|
||||
/// <summary>E-commerce channels.</summary>
|
||||
public const string Channels = "CHAN";
|
||||
|
||||
/// <summary>Automations.</summary>
|
||||
public const string Automation = "AUTO";
|
||||
|
||||
/// <summary>API, MCP and webhooks.</summary>
|
||||
public const string Api = "API";
|
||||
|
||||
/// <summary>Companies beyond the first.</summary>
|
||||
public const string MultiCompany = "MULTI";
|
||||
|
||||
/// <summary>Advanced reports.</summary>
|
||||
public const string Reports = "REPORT";
|
||||
}
|
||||
|
||||
/// <summary>A permission a module declares: a code <c>module.entity.action</c> (SPEC §7.2).</summary>
|
||||
/// <param name="Code">The code, for example <c>sales.invoice.issue</c>.</param>
|
||||
/// <param name="Module">The licence code of the module that owns it.</param>
|
||||
/// <param name="Description">What it allows, in Italian (shown in the permission matrix).</param>
|
||||
public sealed record PermissionDefinition(string Code, string Module, string Description);
|
||||
|
||||
/// <summary>A functional module (SPEC §8.1): its licence code, its name and the permissions it declares.</summary>
|
||||
public interface IModule
|
||||
{
|
||||
/// <summary>The licence code.</summary>
|
||||
string Code { get; }
|
||||
|
||||
/// <summary>The name shown in the interface.</summary>
|
||||
string Name { get; }
|
||||
|
||||
/// <summary>The permissions.</summary>
|
||||
IReadOnlyList<PermissionDefinition> Permissions { get; }
|
||||
}
|
||||
|
||||
/// <summary>A module declared in code.</summary>
|
||||
/// <param name="Code">The licence code.</param>
|
||||
/// <param name="Name">The name shown.</param>
|
||||
/// <param name="Permissions">The permissions.</param>
|
||||
public sealed record ModuleDefinition(string Code, string Name, IReadOnlyList<PermissionDefinition> Permissions) : IModule;
|
||||
|
||||
/// <summary>
|
||||
/// The modules of the product and their permissions. The list is static: what the licence does not include stays
|
||||
/// declared but is filtered by <c>ILicenseGate</c> (menus hidden, permissions denied with
|
||||
/// <c>module_not_licensed</c>). Each milestone adds the permissions of the screens it delivers.
|
||||
/// </summary>
|
||||
public sealed class ModuleRegistry
|
||||
{
|
||||
private readonly Dictionary<string, IModule> _modules;
|
||||
private readonly Dictionary<string, PermissionDefinition> _permissions;
|
||||
|
||||
/// <summary>Creates a registry.</summary>
|
||||
/// <param name="modules">The modules.</param>
|
||||
/// <exception cref="InvalidOperationException">Two modules share a code, or two permissions share a code.</exception>
|
||||
public ModuleRegistry(IEnumerable<IModule> modules)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(modules);
|
||||
_modules = new Dictionary<string, IModule>(StringComparer.Ordinal);
|
||||
_permissions = new Dictionary<string, PermissionDefinition>(StringComparer.Ordinal);
|
||||
foreach (var module in modules)
|
||||
{
|
||||
if (!_modules.TryAdd(module.Code, module))
|
||||
{
|
||||
throw new InvalidOperationException($"Module {module.Code} is declared twice.");
|
||||
}
|
||||
|
||||
foreach (var permission in module.Permissions)
|
||||
{
|
||||
if (!PermissionPattern.IsCode(permission.Code) || permission.Module != module.Code)
|
||||
{
|
||||
throw new InvalidOperationException($"Permission {permission.Code} of {module.Code} is not a module.entity.action code of that module.");
|
||||
}
|
||||
|
||||
if (!_permissions.TryAdd(permission.Code, permission))
|
||||
{
|
||||
throw new InvalidOperationException($"Permission {permission.Code} is declared twice.");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The registry of the product modules.</summary>
|
||||
public static ModuleRegistry Default { get; } = new(BuiltInModules.All);
|
||||
|
||||
/// <summary>The modules, in the order of SPEC §8.1.</summary>
|
||||
public IReadOnlyCollection<IModule> Modules => _modules.Values;
|
||||
|
||||
/// <summary>Every permission.</summary>
|
||||
public IReadOnlyCollection<PermissionDefinition> Permissions => _permissions.Values;
|
||||
|
||||
/// <summary>Finds a module.</summary>
|
||||
/// <param name="code">The licence code.</param>
|
||||
/// <returns>The module, or <see langword="null"/>.</returns>
|
||||
public IModule? FindModule(string code) => _modules.GetValueOrDefault(code);
|
||||
|
||||
/// <summary>Finds a permission.</summary>
|
||||
/// <param name="code">The permission code.</param>
|
||||
/// <returns>The permission, or <see langword="null"/>.</returns>
|
||||
public PermissionDefinition? FindPermission(string code) => _permissions.GetValueOrDefault(code);
|
||||
|
||||
/// <summary>The permissions a pattern grants (<c>*</c>, <c>sales.*</c>, <c>*.read</c> or a code).</summary>
|
||||
/// <param name="pattern">The pattern.</param>
|
||||
/// <returns>The matching permissions.</returns>
|
||||
public IEnumerable<PermissionDefinition> Expand(string pattern) => _permissions.Values.Where(p => PermissionPattern.Matches(pattern, p.Code));
|
||||
}
|
||||
|
||||
/// <summary>Permission codes and the patterns used by roles: <c>*</c>, <c>module.*</c>, <c>*.action</c> or an exact code.</summary>
|
||||
public static class PermissionPattern
|
||||
{
|
||||
/// <summary>Whether <paramref name="code"/> has the form <c>module.entity.action</c> (two or three lower-case segments).</summary>
|
||||
/// <param name="code">The code.</param>
|
||||
/// <returns><see langword="true"/> if valid.</returns>
|
||||
public static bool IsCode(string? code) =>
|
||||
code is not null && code.Split('.') is { Length: 2 or 3 } parts
|
||||
&& parts.All(p => p.Length > 0 && p.All(c => c is (>= 'a' and <= 'z') or (>= '0' and <= '9') or '_'));
|
||||
|
||||
/// <summary>Whether a pattern grants a permission code.</summary>
|
||||
/// <param name="pattern">The pattern.</param>
|
||||
/// <param name="code">The permission code.</param>
|
||||
/// <returns><see langword="true"/> if it matches.</returns>
|
||||
public static bool Matches(string pattern, string code)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(pattern);
|
||||
ArgumentNullException.ThrowIfNull(code);
|
||||
if (pattern == "*" || pattern == code)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
if (pattern.EndsWith(".*", StringComparison.Ordinal))
|
||||
{
|
||||
return code.StartsWith(pattern[..^1], StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
return pattern.StartsWith("*.", StringComparison.Ordinal) && code.EndsWith(pattern[1..], StringComparison.Ordinal);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
using Khaemhat.Core.Instance;
|
||||
using Khaemhat.Data;
|
||||
using Khaemhat.Data.Querying;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace Khaemhat.Application.Notifications;
|
||||
|
||||
/// <summary>A notification to deliver.</summary>
|
||||
/// <param name="Category">The area: <c>security</c>, <c>jobs</c>, <c>system</c>, <c>licenses</c>...</param>
|
||||
/// <param name="Severity">The weight.</param>
|
||||
/// <param name="Title">The title.</param>
|
||||
/// <param name="Body">The text.</param>
|
||||
/// <param name="Link">A link inside the application.</param>
|
||||
public sealed record NotificationMessage(string Category, NotificationSeverity Severity, string Title, string? Body = null, string? Link = null);
|
||||
|
||||
/// <summary>
|
||||
/// Delivers in-app notifications (SPEC §9; mockup 010): to instance accounts in <c>sys_notifications</c>, to company
|
||||
/// users in the company's <c>notifications</c>. A notification without recipient goes to everyone in the scope.
|
||||
/// Delivery never breaks the caller: a failure is logged.
|
||||
/// </summary>
|
||||
/// <param name="factory">Opens the databases.</param>
|
||||
/// <param name="logger">The log.</param>
|
||||
public sealed class NotificationDispatcher(IUnitOfWorkFactory factory, ILogger<NotificationDispatcher> logger)
|
||||
{
|
||||
/// <summary>Notifies instance accounts.</summary>
|
||||
/// <param name="message">The notification.</param>
|
||||
/// <param name="recipientUserId">One account, or <see langword="null"/> for all of them.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>A task.</returns>
|
||||
public async Task NotifyInstanceAsync(NotificationMessage message, long? recipientUserId = null, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(message);
|
||||
try
|
||||
{
|
||||
await using var unitOfWork = await factory.CreateAsync(DatabaseScope.System, cancellationToken).ConfigureAwait(false);
|
||||
await unitOfWork.Repository<SystemNotification, long>().InsertAsync(Fill(new SystemNotification(), message, recipientUserId), cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException)
|
||||
{
|
||||
logger.LogError(ex, "Notification {Title} not delivered to instance accounts.", message.Title);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Notifies the users of a company.</summary>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="message">The notification.</param>
|
||||
/// <param name="recipientUserId">One user, or <see langword="null"/> for all of them.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>A task.</returns>
|
||||
public async Task NotifyCompanyAsync(string companyCode, NotificationMessage message, long? recipientUserId = null, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(message);
|
||||
try
|
||||
{
|
||||
await using var unitOfWork = await factory.CreateAsync(DatabaseScope.Company(companyCode), cancellationToken).ConfigureAwait(false);
|
||||
await unitOfWork.Repository<Notification, long>().InsertAsync(Fill(new Notification(), message, recipientUserId), cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException)
|
||||
{
|
||||
logger.LogError(ex, "Notification {Title} not delivered to company {Company}.", message.Title, companyCode);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The unread notifications of an instance account (its own and those for everyone).</summary>
|
||||
/// <param name="userId">The account.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The notifications, newest first.</returns>
|
||||
public async Task<IReadOnlyList<SystemNotification>> UnreadForInstanceAsync(long userId, CancellationToken cancellationToken = default)
|
||||
{
|
||||
await using var unitOfWork = await factory.CreateAsync(DatabaseScope.System, cancellationToken).ConfigureAwait(false);
|
||||
return (await unitOfWork.Repository<SystemNotification, long>().ListAsync(
|
||||
Query.For<SystemNotification>().Where(n => n.ReadAt == null && (n.RecipientUserId == null || n.RecipientUserId == userId)).OrderByDescending(n => n.Id).Take(100),
|
||||
cancellationToken).ConfigureAwait(false)).Items;
|
||||
}
|
||||
|
||||
/// <summary>The unread notifications of a company user.</summary>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="userId">The user.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The notifications, newest first.</returns>
|
||||
public async Task<IReadOnlyList<Notification>> UnreadForUserAsync(string companyCode, long userId, CancellationToken cancellationToken = default)
|
||||
{
|
||||
await using var unitOfWork = await factory.CreateAsync(DatabaseScope.Company(companyCode), cancellationToken).ConfigureAwait(false);
|
||||
return (await unitOfWork.Repository<Notification, long>().ListAsync(
|
||||
Query.For<Notification>().Where(n => n.ReadAt == null && (n.RecipientUserId == null || n.RecipientUserId == userId)).OrderByDescending(n => n.Id).Take(100),
|
||||
cancellationToken).ConfigureAwait(false)).Items;
|
||||
}
|
||||
|
||||
private static T Fill<T>(T notification, NotificationMessage message, long? recipient)
|
||||
where T : NotificationRecord
|
||||
{
|
||||
notification.RecipientUserId = recipient;
|
||||
notification.Category = Clip(message.Category, 40);
|
||||
notification.Severity = message.Severity;
|
||||
notification.Title = Clip(message.Title, 200);
|
||||
notification.Body = message.Body;
|
||||
notification.Link = message.Link is null ? null : Clip(message.Link, 400);
|
||||
return notification;
|
||||
}
|
||||
|
||||
private static string Clip(string value, int length) => value.Length <= length ? value : value[..length];
|
||||
}
|
||||
@@ -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><scope>.<token></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);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user