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,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}.");
|
||||
}
|
||||
Reference in new issue
Block a user