feat: system and security - start-up, accounts, sign-in, licences, log, jobs, companies (M2)
CI / Build and test (SQLite) (pull_request) Successful in 55s
CI / PostgreSQL 16 integration (pull_request) Skipped
CI / PostgreSQL 17 integration (pull_request) Skipped
CI / YAML check (pull_request) Successful in 5s
CI / Docker image (pull_request) Failing after 2m4s

The instance now starts on its own from KHAEMHAT_* variables: it migrates the system
and company databases, creates the super user and the first company, and only then
reports ready. Users sign in with password and TOTP through revocable database
sessions, and licences decide which modules and how many companies are available.

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

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

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-11 15:29:24 +01:00
1 parent 4582837b70
commit 032c602b49
107 files changed
+12202 -116

No files matched your search

@@ -0,0 +1,80 @@
namespace Khaemhat.Core.Caching;
/// <summary>
/// The application cache (SPEC §9): in memory, or Redis when <c>KHAEMHAT_REDIS</c> is set. Values are stored as JSON
/// in both cases, so the behaviour is the same with and without Redis. Keys follow <see cref="CacheKeys.For"/>.
/// </summary>
public interface ICacheProvider
{
/// <summary>Whether the cache is shared between instances (Redis reachable).</summary>
bool IsDistributed { get; }
/// <summary>Reads a value.</summary>
/// <typeparam name="T">The value type.</typeparam>
/// <param name="key">The key.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The value, or <see langword="default"/> when missing or expired.</returns>
ValueTask<T?> GetAsync<T>(string key, CancellationToken cancellationToken = default);
/// <summary>Stores a value.</summary>
/// <typeparam name="T">The value type.</typeparam>
/// <param name="key">The key.</param>
/// <param name="value">The value.</param>
/// <param name="timeToLive">How long it stays.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
ValueTask SetAsync<T>(string key, T value, TimeSpan timeToLive, CancellationToken cancellationToken = default);
/// <summary>Removes a value.</summary>
/// <param name="key">The key.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
ValueTask RemoveAsync(string key, CancellationToken cancellationToken = default);
/// <summary>Removes every key that starts with <paramref name="prefix"/>.</summary>
/// <param name="prefix">The prefix, for example <c>kh:DEMO:permissions:</c>.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
ValueTask RemoveByPrefixAsync(string prefix, CancellationToken cancellationToken = default);
/// <summary>Reads a value, or creates and stores it.</summary>
/// <typeparam name="T">The value type.</typeparam>
/// <param name="key">The key.</param>
/// <param name="factory">Creates the value when missing.</param>
/// <param name="timeToLive">How long it stays.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The value.</returns>
ValueTask<T> GetOrCreateAsync<T>(string key, Func<CancellationToken, ValueTask<T>> factory, TimeSpan timeToLive, CancellationToken cancellationToken = default);
/// <summary>
/// Removes the keys with <paramref name="prefix"/> here and tells the other instances to do the same (Redis pub/sub).
/// </summary>
/// <param name="prefix">The prefix.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
ValueTask PublishInvalidationAsync(string prefix, CancellationToken cancellationToken = default);
}
/// <summary>Cache keys: <c>kh:{company}:{area}:{key}</c>, with <c>_</c> for the instance (SPEC §9).</summary>
public static class CacheKeys
{
/// <summary>The instance scope.</summary>
public const string Instance = "_";
/// <summary>A key.</summary>
/// <param name="company">The company code, or <see langword="null"/> for the instance.</param>
/// <param name="area">The area, for example <c>permissions</c>.</param>
/// <param name="key">The key inside the area.</param>
/// <returns>The full key.</returns>
public static string For(string? company, string area, string key) => Prefix(company, area) + key;
/// <summary>The prefix of an area, for <see cref="ICacheProvider.RemoveByPrefixAsync"/>.</summary>
/// <param name="company">The company code, or <see langword="null"/> for the instance.</param>
/// <param name="area">The area.</param>
/// <returns>The prefix, ending with a colon.</returns>
public static string Prefix(string? company, string area)
{
ArgumentException.ThrowIfNullOrWhiteSpace(area);
return "kh:" + (string.IsNullOrEmpty(company) ? Instance : company) + ":" + area + ":";
}
}
@@ -0,0 +1,349 @@
using Khaemhat.Core.Entities;
namespace Khaemhat.Core.Instance;
/// <summary>Where an installed licence comes from.</summary>
public enum LicenseSource
{
/// <summary>A signed <c>.khl</c> instance licence.</summary>
File = 0,
/// <summary>A signed activation code for one module.</summary>
ActivationCode = 1,
/// <summary>A fictitious code of SPEC §8.3, accepted only in test mode.</summary>
TestCode = 2,
}
/// <summary>An installed licence or activation code (<c>sys_licenses</c>).</summary>
public sealed class LicenseRecord : Entity<long>
{
/// <summary>Where the licence comes from.</summary>
public LicenseSource Source { get; set; }
/// <summary>The licence text (<c>.khl</c> content or code), as installed.</summary>
public string Payload { get; set; } = string.Empty;
/// <summary>The licence holder.</summary>
public string? Licensee { get; set; }
/// <summary>The module codes, comma separated.</summary>
public string Modules { get; set; } = string.Empty;
/// <summary>Concurrent users granted (0 = not stated by this licence).</summary>
public int MaxConcurrentUsers { get; set; }
/// <summary>Companies granted (0 = not stated by this licence).</summary>
public int MaxCompanies { get; set; }
/// <summary>When the licence was issued.</summary>
public DateTime? IssuedAt { get; set; }
/// <summary>When the licence expires; <see langword="null"/> for no expiry.</summary>
public DateTime? ExpiresAt { get; set; }
/// <summary>Days of full use after the expiry.</summary>
public int GracePeriodDays { get; set; }
/// <summary>Whether the licence counts (a removed licence stays for the history).</summary>
public bool IsActive { get; set; } = true;
}
/// <summary>One step in the history of licences (<c>sys_license_activations</c>).</summary>
public sealed class LicenseActivation : Entity<long>
{
/// <summary>What happened: <c>activated</c>, <c>deactivated</c>, <c>rejected</c>, <c>verified</c>, <c>expired</c>.</summary>
public string Action { get; set; } = string.Empty;
/// <summary>The licence source.</summary>
public LicenseSource Source { get; set; }
/// <summary>The modules concerned, comma separated.</summary>
public string? Modules { get; set; }
/// <summary>The outcome code, for example <c>ok</c>, <c>license_test_only</c>, <c>signature_invalid</c>.</summary>
public string Outcome { get; set; } = string.Empty;
/// <summary>A short explanation.</summary>
public string? Message { get; set; }
}
/// <summary>An ASP.NET Core DataProtection key kept in the system database (<c>sys_data_protection_keys</c>).</summary>
public sealed class DataProtectionKey : Entity<long>
{
/// <summary>The key name given by DataProtection.</summary>
public string FriendlyName { get; set; } = string.Empty;
/// <summary>The key XML. The key material inside is encrypted with the instance key.</summary>
public string Xml { get; set; } = string.Empty;
}
/// <summary>One event of the application log (<c>sys_log</c>, SPEC §9.5).</summary>
public sealed class LogEntry : IEntity<long>
{
/// <inheritdoc />
public long Id { get; set; }
/// <summary>When the event happened (UTC).</summary>
public DateTime At { get; set; }
/// <summary>The level: Trace, Debug, Information, Warning, Error, Critical.</summary>
public string Level { get; set; } = string.Empty;
/// <summary>The section (SPEC §9.5), for example <c>Authentication</c>.</summary>
public string Section { get; set; } = string.Empty;
/// <summary>The logger category.</summary>
public string Source { get; set; } = string.Empty;
/// <summary>The message.</summary>
public string Message { get; set; } = string.Empty;
/// <summary>The exception with its stack, if any.</summary>
public string? Exception { get; set; }
/// <summary>The user name.</summary>
public string? UserName { get; set; }
/// <summary>The company code.</summary>
public string? CompanyCode { get; set; }
/// <summary>The trace identifier shown to the user as the error code.</summary>
public string? TraceId { get; set; }
/// <summary>The request (method and path).</summary>
public string? Request { get; set; }
/// <summary>The entity concerned.</summary>
public string? Entity { get; set; }
/// <summary>The identifier of the entity concerned.</summary>
public string? EntityId { get; set; }
/// <summary>Further structured data as JSON.</summary>
public string? Data { get; set; }
}
/// <summary>
/// A security or instance action (<c>sys_security_audit</c>): sign-ins, permissions, licences, databases, maintenance.
/// Rows are never updated; each one carries the hash of the previous row, so a removed or changed row breaks the chain.
/// </summary>
public sealed class SecurityAuditEntry : IEntity<long>
{
/// <inheritdoc />
public long Id { get; set; }
/// <summary>When it happened (UTC).</summary>
public DateTime At { get; set; }
/// <summary>The action code, for example <c>login.succeeded</c>.</summary>
public string Action { get; set; } = string.Empty;
/// <summary>Who acted.</summary>
public string? UserName { get; set; }
/// <summary>The company concerned.</summary>
public string? CompanyCode { get; set; }
/// <summary>The client address.</summary>
public string? IpAddress { get; set; }
/// <summary>What the action was about (a user, a module, a database...).</summary>
public string? Target { get; set; }
/// <summary>Details as JSON (never secrets).</summary>
public string? Details { get; set; }
/// <summary>The hash of the previous row (empty for the first).</summary>
public string PreviousHash { get; set; } = string.Empty;
/// <summary>SHA-256 of this row's content and <see cref="PreviousHash"/>.</summary>
public string Hash { get; set; } = string.Empty;
}
/// <summary>A change to company data (<c>audit_log</c>, SPEC §7.3), shown in the "Storico" of a record.</summary>
public sealed class AuditEntry : IEntity<long>
{
/// <inheritdoc />
public long Id { get; set; }
/// <summary>When it happened (UTC).</summary>
public DateTime At { get; set; }
/// <summary>The entity (table) changed.</summary>
public string Entity { get; set; } = string.Empty;
/// <summary>The identifier of the record.</summary>
public string EntityId { get; set; } = string.Empty;
/// <summary><c>insert</c>, <c>update</c> or <c>delete</c>.</summary>
public string Action { get; set; } = string.Empty;
/// <summary>Who changed it.</summary>
public string? UserName { get; set; }
/// <summary>The changed fields as JSON: <c>{"field": {"old": ..., "new": ...}}</c>.</summary>
public string? Diff { get; set; }
/// <summary>The trace of the request that made the change.</summary>
public string? TraceId { get; set; }
}
/// <summary>The outcome of a job run.</summary>
public enum JobOutcome
{
/// <summary>Still running.</summary>
Running = 0,
/// <summary>Completed.</summary>
Succeeded = 1,
/// <summary>Failed after the retries.</summary>
Failed = 2,
/// <summary>Stopped by the timeout.</summary>
TimedOut = 3,
/// <summary>Not started because another run held the lock.</summary>
Skipped = 4,
}
/// <summary>A scheduled task (<c>sys_scheduled_tasks</c>): a system job or an activity set up by administrators.</summary>
public sealed class ScheduledTask : Entity<long>
{
/// <summary>The task code, unique, for example <c>system.log-retention</c>.</summary>
public string Code { get; set; } = string.Empty;
/// <summary>The name shown in the interface.</summary>
public string Name { get; set; } = string.Empty;
/// <summary>The job type that runs it.</summary>
public string JobType { get; set; } = string.Empty;
/// <summary>The company it works on; <see langword="null"/> for the instance.</summary>
public string? CompanyCode { get; set; }
/// <summary>The cron expression (five fields).</summary>
public string Cron { get; set; } = string.Empty;
/// <summary>The time zone of the cron expression (IANA name).</summary>
public string TimeZone { get; set; } = "Europe/Rome";
/// <summary>The longest a run may last, in seconds.</summary>
public int TimeoutSeconds { get; set; } = 600;
/// <summary>How many times a failed run is retried.</summary>
public int MaxRetries { get; set; }
/// <summary>Whether the task runs.</summary>
public bool IsEnabled { get; set; } = true;
/// <summary>A system job, which administrators can suspend but not delete.</summary>
public bool IsSystem { get; set; }
/// <summary>The parameters as JSON.</summary>
public string? Parameters { get; set; }
/// <summary>The last start.</summary>
public DateTime? LastRunAt { get; set; }
/// <summary>The next planned start.</summary>
public DateTime? NextRunAt { get; set; }
/// <summary>The outcome of the last run.</summary>
public JobOutcome? LastOutcome { get; set; }
}
/// <summary>One run of a scheduled task (<c>sys_job_runs</c>).</summary>
public sealed class JobRun : IEntity<long>
{
/// <inheritdoc />
public long Id { get; set; }
/// <summary>The task code.</summary>
public string TaskCode { get; set; } = string.Empty;
/// <summary>When the run started (UTC).</summary>
public DateTime StartedAt { get; set; }
/// <summary>When the run ended.</summary>
public DateTime? FinishedAt { get; set; }
/// <summary>The outcome.</summary>
public JobOutcome Outcome { get; set; }
/// <summary>The attempt number, from 1.</summary>
public int Attempt { get; set; } = 1;
/// <summary>A short result or error message.</summary>
public string? Message { get; set; }
/// <summary>The trace identifier of the run, to find its log.</summary>
public string? TraceId { get; set; }
}
/// <summary>
/// A lock held by a job run (<c>sys_job_locks</c>): a row per running task, with an expiry so that a process that died
/// does not block the task for ever.
/// </summary>
public sealed class JobLock : IEntity<string>
{
/// <summary>The lock key (the task code).</summary>
public string Id { get; set; } = string.Empty;
/// <summary>The process that holds the lock.</summary>
public string Owner { get; set; } = string.Empty;
/// <summary>When the lock was taken.</summary>
public DateTime AcquiredAt { get; set; }
/// <summary>When the lock lapses.</summary>
public DateTime ExpiresAt { get; set; }
}
/// <summary>The weight of a notification.</summary>
public enum NotificationSeverity
{
/// <summary>Information.</summary>
Info = 0,
/// <summary>Something completed.</summary>
Success = 1,
/// <summary>Needs attention.</summary>
Warning = 2,
/// <summary>Something failed.</summary>
Error = 3,
}
/// <summary>An in-app notification (SPEC §9; mockup 010).</summary>
public abstract class NotificationRecord : Entity<long>
{
/// <summary>The recipient; <see langword="null"/> for every user of the scope (all administrators, all users).</summary>
public long? RecipientUserId { get; set; }
/// <summary>The area: <c>security</c>, <c>jobs</c>, <c>system</c>, <c>licenses</c>...</summary>
public string Category { get; set; } = string.Empty;
/// <summary>The weight.</summary>
public NotificationSeverity Severity { get; set; }
/// <summary>The title.</summary>
public string Title { get; set; } = string.Empty;
/// <summary>The text.</summary>
public string? Body { get; set; }
/// <summary>A link inside the application.</summary>
public string? Link { get; set; }
/// <summary>When the recipient read it.</summary>
public DateTime? ReadAt { get; set; }
}
/// <summary>A notification for instance accounts (<c>sys_notifications</c>).</summary>
public sealed class SystemNotification : NotificationRecord;
/// <summary>A notification for company users (<c>notifications</c>).</summary>
public sealed class Notification : NotificationRecord;
+131
View File
@@ -0,0 +1,131 @@
namespace Khaemhat.Core.Logging;
/// <summary>The sections of the application log (SPEC §9.5; mockup 084). Each module writes to its own.</summary>
public enum LogSection
{
/// <summary>Sistema.</summary>
System = 0,
/// <summary>Autenticazione.</summary>
Authentication = 1,
/// <summary>Database.</summary>
Database = 2,
/// <summary>Migrazioni.</summary>
Migrations = 3,
/// <summary>Documenti.</summary>
Documents = 4,
/// <summary>Contabilità.</summary>
Accounting = 5,
/// <summary>Magazzino.</summary>
Inventory = 6,
/// <summary>SDI/e-invoicing.</summary>
EInvoicing = 7,
/// <summary>CRM.</summary>
Crm = 8,
/// <summary>Automazioni.</summary>
Automation = 9,
/// <summary>Attività programmate.</summary>
ScheduledJobs = 10,
/// <summary>Backup.</summary>
Backup = 11,
/// <summary>API/MCP.</summary>
Api = 12,
/// <summary>E-mail/PEC.</summary>
Email = 13,
/// <summary>Integrazioni (VIES, BCE, intermediari).</summary>
Integrations = 14,
/// <summary>UI/circuiti.</summary>
Ui = 15,
/// <summary>Prestazioni.</summary>
Performance = 16,
}
/// <summary>Names, labels and the scope key of <see cref="LogSection"/>.</summary>
public static class LogSections
{
/// <summary>The scope key that carries the section (<c>using (logger.BeginScope(LogSections.Scope(...)))</c>).</summary>
public const string ScopeKey = "Section";
/// <summary>The scope key of the trace identifier.</summary>
public const string TraceIdKey = "TraceId";
/// <summary>The scope key of the user name.</summary>
public const string UserKey = "UserName";
/// <summary>The scope key of the company code.</summary>
public const string CompanyKey = "CompanyCode";
/// <summary>The scope key of the request (method and path).</summary>
public const string RequestKey = "Request";
/// <summary>The scope key of the entity concerned.</summary>
public const string EntityKey = "Entity";
/// <summary>The scope key of the entity identifier.</summary>
public const string EntityIdKey = "EntityId";
/// <summary>The Italian label shown in the log page.</summary>
/// <param name="section">The section.</param>
/// <returns>The label.</returns>
public static string Label(LogSection section) => section switch
{
LogSection.System => "Sistema",
LogSection.Authentication => "Autenticazione",
LogSection.Database => "Database",
LogSection.Migrations => "Migrazioni",
LogSection.Documents => "Documenti",
LogSection.Accounting => "Contabilità",
LogSection.Inventory => "Magazzino",
LogSection.EInvoicing => "SDI/e-invoicing",
LogSection.Crm => "CRM",
LogSection.Automation => "Automazioni",
LogSection.ScheduledJobs => "Attività programmate",
LogSection.Backup => "Backup",
LogSection.Api => "API/MCP",
LogSection.Email => "E-mail/PEC",
LogSection.Integrations => "Integrazioni",
LogSection.Ui => "UI/circuiti",
LogSection.Performance => "Prestazioni",
_ => section.ToString(),
};
/// <summary>A scope state that sets the section of the events logged inside it.</summary>
/// <param name="section">The section.</param>
/// <returns>The scope state.</returns>
public static IReadOnlyList<KeyValuePair<string, object?>> Scope(LogSection section) =>
[new(ScopeKey, section.ToString())];
/// <summary>
/// The section of a logger category when no scope sets one: by namespace, so that the framework's own events land in
/// a sensible place.
/// </summary>
/// <param name="category">The logger category.</param>
/// <returns>The section.</returns>
public static LogSection FromCategory(string? category) => category switch
{
null => LogSection.System,
_ when category.Contains(".Security", StringComparison.Ordinal) || category.Contains("Authentication", StringComparison.Ordinal)
|| category.Contains("Authorization", StringComparison.Ordinal) || category.Contains("Antiforgery", StringComparison.Ordinal) => LogSection.Authentication,
_ when category.Contains("Migration", StringComparison.Ordinal) => LogSection.Migrations,
_ when category.StartsWith("Khaemhat.Data", StringComparison.Ordinal) => LogSection.Database,
_ when category.Contains(".Jobs", StringComparison.Ordinal) => LogSection.ScheduledJobs,
_ when category.StartsWith("Microsoft.AspNetCore.Components", StringComparison.Ordinal) => LogSection.Ui,
_ when category.Contains("SlowQuer", StringComparison.Ordinal) || category.Contains("Performance", StringComparison.Ordinal) => LogSection.Performance,
_ => LogSection.System,
};
}
@@ -0,0 +1,203 @@
using System.Globalization;
namespace Khaemhat.Core.Scheduling;
/// <summary>
/// A five-field cron expression (<c>minute hour day-of-month month day-of-week</c>) for scheduled tasks (SPEC §9.4):
/// <c>*</c>, lists (<c>1,15</c>), ranges (<c>1-5</c>), steps (<c>*/10</c>, <c>8-18/2</c>); day of week 0-7 with 0 and 7
/// for Sunday. As in classic cron, when both day fields are restricted a day matches either. Times are computed in the
/// task's time zone, so "every day at 02:30" stays at 02:30 across daylight saving changes (a skipped local time is
/// skipped that day).
/// </summary>
public sealed class CronExpression
{
private readonly bool[] _minutes = new bool[60];
private readonly bool[] _hours = new bool[24];
private readonly bool[] _days = new bool[32];
private readonly bool[] _months = new bool[13];
private readonly bool[] _weekDays = new bool[7];
private readonly bool _anyDay;
private readonly bool _anyWeekDay;
private CronExpression(string text, string[] fields)
{
Text = text;
Fill(fields[0], 0, 59, _minutes);
Fill(fields[1], 0, 23, _hours);
_anyDay = Fill(fields[2], 1, 31, _days);
Fill(fields[3], 1, 12, _months);
var weekDays = new bool[8];
_anyWeekDay = Fill(fields[4], 0, 7, weekDays);
for (var i = 0; i < 7; i++)
{
_weekDays[i] = weekDays[i] || (i == 0 && weekDays[7]);
}
}
/// <summary>The expression as written.</summary>
public string Text { get; }
/// <summary>Parses an expression.</summary>
/// <param name="text">The expression.</param>
/// <returns>The parsed expression.</returns>
/// <exception cref="FormatException">The expression is not valid.</exception>
public static CronExpression Parse(string text) =>
TryParse(text, out var result, out var error) ? result : throw new FormatException(error);
/// <summary>Tries to parse an expression.</summary>
/// <param name="text">The expression.</param>
/// <param name="result">The parsed expression.</param>
/// <param name="error">Why it is not valid.</param>
/// <returns><see langword="true"/> when valid.</returns>
public static bool TryParse(string? text, [System.Diagnostics.CodeAnalysis.NotNullWhen(true)] out CronExpression? result, out string? error)
{
result = null;
var fields = (text ?? string.Empty).Split(' ', StringSplitOptions.RemoveEmptyEntries);
if (fields.Length != 5)
{
error = "A cron expression has five fields: minute hour day-of-month month day-of-week.";
return false;
}
try
{
result = new CronExpression(string.Join(' ', fields), fields);
error = null;
return true;
}
catch (FormatException ex)
{
error = ex.Message;
return false;
}
}
/// <summary>The first occurrence strictly after a moment.</summary>
/// <param name="afterUtc">The moment (UTC).</param>
/// <param name="zone">The time zone of the schedule.</param>
/// <returns>The next occurrence in UTC, or <see langword="null"/> when none exists in the next five years.</returns>
public DateTime? NextAfter(DateTime afterUtc, TimeZoneInfo zone)
{
ArgumentNullException.ThrowIfNull(zone);
var utc = DateTime.SpecifyKind(afterUtc, DateTimeKind.Utc);
var local = TimeZoneInfo.ConvertTimeFromUtc(utc, zone);
var candidate = new DateTime(local.Year, local.Month, local.Day, local.Hour, local.Minute, 0, DateTimeKind.Unspecified).AddMinutes(1);
var limit = candidate.AddYears(5);
while (candidate < limit)
{
if (!_months[candidate.Month])
{
candidate = new DateTime(candidate.Year, candidate.Month, 1, 0, 0, 0, DateTimeKind.Unspecified).AddMonths(1);
continue;
}
if (!DayMatches(candidate))
{
candidate = candidate.Date.AddDays(1);
continue;
}
if (!_hours[candidate.Hour])
{
candidate = candidate.Date.AddHours(candidate.Hour + 1);
continue;
}
if (!_minutes[candidate.Minute])
{
candidate = candidate.AddMinutes(1);
continue;
}
if (zone.IsInvalidTime(candidate))
{
candidate = candidate.AddMinutes(1);
continue;
}
var result = TimeZoneInfo.ConvertTimeToUtc(candidate, zone);
if (result > utc)
{
return result;
}
candidate = candidate.AddMinutes(1);
}
return null;
}
/// <inheritdoc />
public override string ToString() => Text;
private bool DayMatches(DateTime date)
{
var day = _days[date.Day];
var weekDay = _weekDays[(int)date.DayOfWeek];
return (_anyDay, _anyWeekDay) switch
{
(true, true) => true,
(true, false) => weekDay,
(false, true) => day,
_ => day || weekDay,
};
}
// Fills the allowed values of a field; returns true when the field is "*".
private static bool Fill(string field, int min, int max, bool[] allowed)
{
if (field == "*")
{
for (var i = min; i <= max; i++)
{
allowed[i] = true;
}
return true;
}
foreach (var part in field.Split(','))
{
var step = 1;
var range = part;
var slash = part.IndexOf('/', StringComparison.Ordinal);
if (slash >= 0)
{
step = Number(part[(slash + 1)..], 1, max, part);
range = part[..slash];
}
int from, to;
if (range == "*")
{
(from, to) = (min, max);
}
else if (range.IndexOf('-', StringComparison.Ordinal) is var dash and > 0)
{
from = Number(range[..dash], min, max, part);
to = Number(range[(dash + 1)..], min, max, part);
if (to < from)
{
throw new FormatException($"The range '{part}' goes backwards.");
}
}
else
{
from = Number(range, min, max, part);
to = slash >= 0 ? max : from;
}
for (var i = from; i <= to; i += step)
{
allowed[i] = true;
}
}
return false;
}
private static int Number(string text, int min, int max, string part) =>
int.TryParse(text, NumberStyles.None, CultureInfo.InvariantCulture, out var value) && value >= min && value <= max
? value
: throw new FormatException($"'{part}' is not valid: values go from {min} to {max}.");
}
+237
View File
@@ -0,0 +1,237 @@
using Khaemhat.Core.Entities;
namespace Khaemhat.Core.Security;
/// <summary>
/// The three access levels of SPEC §7.1, ordered: a higher value can do everything a lower one can.
/// <see cref="SystemUser"/> rows hold <see cref="Administrator"/> or <see cref="SuperUser"/>; company users are
/// <see cref="Standard"/>.
/// </summary>
public enum UserLevel
{
/// <summary>A company user, limited by the permissions of the roles.</summary>
Standard = 0,
/// <summary>An instance administrator, created by the super user.</summary>
Administrator = 1,
/// <summary>The only super user, created from the container variables at first start.</summary>
SuperUser = 2,
}
/// <summary>The kind of a company user.</summary>
public enum UserKind
{
/// <summary>A person who signs in with a password.</summary>
Human = 0,
/// <summary>A technical user for the API: no password, used only through API keys.</summary>
Technical = 1,
}
/// <summary>
/// The credential fields shared by instance accounts (<c>sys_users</c>) and company users (<c>users</c>), so that
/// password, lockout, TOTP and recovery rules are written once.
/// </summary>
public interface IAccount
{
/// <summary>The identifier.</summary>
long Id { get; }
/// <summary>The sign-in name, unique in its database (compared case-insensitively, stored lower-case).</summary>
string UserName { get; set; }
/// <summary>The name shown in the interface.</summary>
string DisplayName { get; set; }
/// <summary>The e-mail address for recovery and notifications.</summary>
string? Email { get; set; }
/// <summary>The password hash (<c>pbkdf2-sha256$...</c>); <see langword="null"/> for technical users.</summary>
string? PasswordHash { get; set; }
/// <summary>The previous password hashes, newest first, as a JSON array (policy: no reuse of the last five).</summary>
string? PasswordHistory { get; set; }
/// <summary>When the password was last set.</summary>
DateTime? PasswordChangedAt { get; set; }
/// <summary>Whether the next sign-in must change the password (first access, temporary password, expiry).</summary>
bool MustChangePassword { get; set; }
/// <summary>When a temporary password stops working; <see langword="null"/> for a normal password.</summary>
DateTime? TemporaryPasswordExpiresAt { get; set; }
/// <summary>Consecutive failed sign-ins since the last success.</summary>
int FailedLoginCount { get; set; }
/// <summary>The account is locked until this moment after too many failures.</summary>
DateTime? LockedUntil { get; set; }
/// <summary>The TOTP secret, encrypted with the instance key.</summary>
string? TotpSecret { get; set; }
/// <summary>Whether the two-step verification is active.</summary>
bool TotpEnabled { get; set; }
/// <summary>The last accepted TOTP time step: a code is never accepted twice.</summary>
long? TotpLastStep { get; set; }
/// <summary>The SHA-256 hashes of the unused recovery codes, as a JSON array.</summary>
string? TotpRecoveryCodes { get; set; }
/// <summary>The SHA-256 hash of the pending password-recovery token.</summary>
string? RecoveryTokenHash { get; set; }
/// <summary>When the recovery token expires.</summary>
DateTime? RecoveryTokenExpiresAt { get; set; }
/// <summary>Whether the account can sign in.</summary>
bool IsActive { get; set; }
/// <summary>The last successful sign-in.</summary>
DateTime? LastLoginAt { get; set; }
}
/// <summary>An instance account (<c>sys_users</c>): the super user or an administrator (SPEC §7.1).</summary>
public sealed class SystemUser : Entity<long>, IAccount
{
/// <inheritdoc />
public string UserName { get; set; } = string.Empty;
/// <inheritdoc />
public string DisplayName { get; set; } = string.Empty;
/// <inheritdoc />
public string? Email { get; set; }
/// <summary><see cref="UserLevel.SuperUser"/> or <see cref="UserLevel.Administrator"/>.</summary>
public UserLevel Level { get; set; }
/// <inheritdoc />
public string? PasswordHash { get; set; }
/// <inheritdoc />
public string? PasswordHistory { get; set; }
/// <inheritdoc />
public DateTime? PasswordChangedAt { get; set; }
/// <inheritdoc />
public bool MustChangePassword { get; set; }
/// <inheritdoc />
public DateTime? TemporaryPasswordExpiresAt { get; set; }
/// <inheritdoc />
public int FailedLoginCount { get; set; }
/// <inheritdoc />
public DateTime? LockedUntil { get; set; }
/// <inheritdoc />
public string? TotpSecret { get; set; }
/// <inheritdoc />
public bool TotpEnabled { get; set; }
/// <inheritdoc />
public long? TotpLastStep { get; set; }
/// <inheritdoc />
public string? TotpRecoveryCodes { get; set; }
/// <inheritdoc />
public string? RecoveryTokenHash { get; set; }
/// <inheritdoc />
public DateTime? RecoveryTokenExpiresAt { get; set; }
/// <inheritdoc />
public bool IsActive { get; set; } = true;
/// <inheritdoc />
public DateTime? LastLoginAt { get; set; }
/// <summary>The company of the linked user, for an administrator who works as a company user without a second sign-in.</summary>
public string? LinkedCompanyCode { get; set; }
/// <summary>The linked company user.</summary>
public long? LinkedUserId { get; set; }
}
/// <summary>A company user (<c>users</c> in the company database).</summary>
public sealed class CompanyUser : Entity<long>, IAccount
{
/// <inheritdoc />
public string UserName { get; set; } = string.Empty;
/// <inheritdoc />
public string DisplayName { get; set; } = string.Empty;
/// <inheritdoc />
public string? Email { get; set; }
/// <summary>A person or a technical user for the API.</summary>
public UserKind Kind { get; set; }
/// <inheritdoc />
public string? PasswordHash { get; set; }
/// <inheritdoc />
public string? PasswordHistory { get; set; }
/// <inheritdoc />
public DateTime? PasswordChangedAt { get; set; }
/// <inheritdoc />
public bool MustChangePassword { get; set; }
/// <inheritdoc />
public DateTime? TemporaryPasswordExpiresAt { get; set; }
/// <inheritdoc />
public int FailedLoginCount { get; set; }
/// <inheritdoc />
public DateTime? LockedUntil { get; set; }
/// <inheritdoc />
public string? TotpSecret { get; set; }
/// <inheritdoc />
public bool TotpEnabled { get; set; }
/// <summary>Whether this user must set up the two-step verification (configurable per user).</summary>
public bool TotpRequired { get; set; }
/// <inheritdoc />
public long? TotpLastStep { get; set; }
/// <inheritdoc />
public string? TotpRecoveryCodes { get; set; }
/// <inheritdoc />
public string? RecoveryTokenHash { get; set; }
/// <inheritdoc />
public DateTime? RecoveryTokenExpiresAt { get; set; }
/// <inheritdoc />
public bool IsActive { get; set; } = true;
/// <inheritdoc />
public DateTime? LastLoginAt { get; set; }
/// <summary>Sees only the customers assigned to the user (agents).</summary>
public bool OwnCustomersOnly { get; set; }
/// <summary>Sees costs and margins.</summary>
public bool CanSeeCosts { get; set; }
/// <summary>Can export lists and reports.</summary>
public bool CanExport { get; set; }
/// <summary>Can use the API.</summary>
public bool CanUseApi { get; set; }
}
+136
View File
@@ -0,0 +1,136 @@
using Khaemhat.Core.Entities;
namespace Khaemhat.Core.Security;
/// <summary>How far a sign-in has gone. Only <see cref="Active"/> sessions open the application.</summary>
public enum SessionState
{
/// <summary>The password was right; the TOTP code is still missing.</summary>
PendingTotp = 0,
/// <summary>The two-step verification must be set up before going on (mandatory for instance accounts).</summary>
PendingTotpSetup = 1,
/// <summary>The password must be changed before going on.</summary>
PendingPasswordChange = 2,
/// <summary>A complete session.</summary>
Active = 3,
}
/// <summary>
/// A sign-in session (SPEC §7.3). The cookie carries a random 256-bit token; the table stores only its SHA-256 hash,
/// so a copy of the database does not let anyone in.
/// </summary>
public abstract class SessionRecord : Entity<long>
{
/// <summary>The SHA-256 hash of the token, in lower-case hexadecimal.</summary>
public string TokenHash { get; set; } = string.Empty;
/// <summary>The account.</summary>
public long UserId { get; set; }
/// <summary>The state of the sign-in.</summary>
public SessionState State { get; set; }
/// <summary>The company the session works in (chosen at sign-in, changeable by instance accounts).</summary>
public string? CompanyCode { get; set; }
/// <summary>The client address.</summary>
public string? IpAddress { get; set; }
/// <summary>The browser, as sent by the client (truncated).</summary>
public string? UserAgent { get; set; }
/// <summary>Whether the cookie survives the browser ("remember me on this device").</summary>
public bool Persistent { get; set; }
/// <summary>The last request seen (updated at most once a minute).</summary>
public DateTime LastSeenAt { get; set; }
/// <summary>When the session expires unless used again (sliding expiry).</summary>
public DateTime ExpiresAt { get; set; }
/// <summary>When the session was revoked.</summary>
public DateTime? RevokedAt { get; set; }
/// <summary>Why the session was revoked (sign-out, administrator, password change, maintenance...).</summary>
public string? RevokedReason { get; set; }
}
/// <summary>A session of an instance account (<c>sys_sessions</c>).</summary>
public sealed class SystemSession : SessionRecord;
/// <summary>A session of a company user (<c>user_sessions</c>).</summary>
public sealed class UserSession : SessionRecord;
/// <summary>A predefined role kept in the system database and copied into each company (<c>sys_roles_templates</c>).</summary>
public sealed class RoleTemplate : Entity<long>
{
/// <summary>The role code, for example <c>ACCOUNTING</c>.</summary>
public string Code { get; set; } = string.Empty;
/// <summary>The name shown in the interface.</summary>
public string Name { get; set; } = string.Empty;
/// <summary>What the role is for.</summary>
public string? Description { get; set; }
/// <summary>The permission codes as a JSON array; <c>*</c> grants every permission.</summary>
public string Permissions { get; set; } = "[]";
/// <summary>The order in lists.</summary>
public int SortOrder { get; set; }
}
/// <summary>A role of a company (<c>roles</c>).</summary>
public sealed class Role : Entity<long>
{
/// <summary>The role code, unique in the company.</summary>
public string Code { get; set; } = string.Empty;
/// <summary>The name shown in the interface.</summary>
public string Name { get; set; } = string.Empty;
/// <summary>What the role is for.</summary>
public string? Description { get; set; }
/// <summary>A predefined role copied from a template: it can be cloned but not changed.</summary>
public bool IsPredefined { get; set; }
/// <summary>The template the role comes from, or the role it was cloned from.</summary>
public string? TemplateCode { get; set; }
}
/// <summary>A permission granted by a role (<c>role_permissions</c>).</summary>
public sealed class RoleGrant : Entity<long>
{
/// <summary>The role.</summary>
public long RoleId { get; set; }
/// <summary>The permission code, or <c>*</c>.</summary>
public string Permission { get; set; } = string.Empty;
}
/// <summary>A role assigned to a company user (<c>user_roles</c>).</summary>
public sealed class UserRole : Entity<long>
{
/// <summary>The user.</summary>
public long UserId { get; set; }
/// <summary>The role.</summary>
public long RoleId { get; set; }
}
/// <summary>A permission granted or denied to one user over the roles (<c>user_permission_overrides</c>). Denials win.</summary>
public sealed class UserPermissionOverride : Entity<long>
{
/// <summary>The user.</summary>
public long UserId { get; set; }
/// <summary>The permission code.</summary>
public string Permission { get; set; } = string.Empty;
/// <summary><see langword="true"/> grants, <see langword="false"/> denies.</summary>
public bool Allowed { get; set; }
}