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,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));
}
}