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

+120
View File
@@ -0,0 +1,120 @@
using Khaemhat.Application.Licensing;
using Khaemhat.Application.Security;
using Khaemhat.Core.Security;
using Microsoft.AspNetCore.Authorization;
using Microsoft.Extensions.Options;
namespace Khaemhat.Web.Security;
/// <summary>Requires a permission (SPEC §7.2), checked with the licence: <c>[RequirePermission("sales.invoices.create")]</c>.</summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true)]
public sealed class RequirePermissionAttribute : AuthorizeAttribute
{
/// <summary>Creates the attribute.</summary>
/// <param name="code">The permission code.</param>
public RequirePermissionAttribute(string code)
: base(KhaemhatPolicies.PermissionPrefix + code) => Code = code;
/// <summary>The permission code.</summary>
public string Code { get; }
}
/// <summary>Requires a level: <c>[RequireLevel(UserLevel.Administrator)]</c> for instance administration.</summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false)]
public sealed class RequireLevelAttribute : AuthorizeAttribute
{
/// <summary>Creates the attribute.</summary>
/// <param name="level">The minimum level.</param>
public RequireLevelAttribute(UserLevel level)
: base(KhaemhatPolicies.LevelPrefix + level) => Level = level;
/// <summary>The minimum level.</summary>
public UserLevel Level { get; }
}
/// <summary>Requires a licensed module: <c>[RequireModule("CRM")]</c>.</summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true)]
public sealed class RequireModuleAttribute : AuthorizeAttribute
{
/// <summary>Creates the attribute.</summary>
/// <param name="moduleCode">The module code.</param>
public RequireModuleAttribute(string moduleCode)
: base(KhaemhatPolicies.ModulePrefix + moduleCode) => ModuleCode = moduleCode;
/// <summary>The module code.</summary>
public string ModuleCode { get; }
}
/// <summary>The policy names built from the attributes.</summary>
public static class KhaemhatPolicies
{
/// <summary>Prefix of permission policies.</summary>
public const string PermissionPrefix = "perm:";
/// <summary>Prefix of level policies.</summary>
public const string LevelPrefix = "level:";
/// <summary>Prefix of module policies.</summary>
public const string ModulePrefix = "module:";
}
/// <summary>A requirement built from a policy name.</summary>
/// <param name="Kind">The prefix.</param>
/// <param name="Value">The permission, level or module.</param>
internal sealed record KhaemhatRequirement(string Kind, string Value) : IAuthorizationRequirement;
/// <summary>Builds the policies named by <see cref="KhaemhatPolicies"/> on demand; other names go to the default provider.</summary>
/// <param name="options">The authorization options.</param>
internal sealed class KhaemhatPolicyProvider(IOptions<AuthorizationOptions> options) : IAuthorizationPolicyProvider
{
private readonly DefaultAuthorizationPolicyProvider _fallback = new(options);
/// <inheritdoc />
public Task<AuthorizationPolicy> GetDefaultPolicyAsync() => _fallback.GetDefaultPolicyAsync();
/// <inheritdoc />
public Task<AuthorizationPolicy?> GetFallbackPolicyAsync() => _fallback.GetFallbackPolicyAsync();
/// <inheritdoc />
public Task<AuthorizationPolicy?> GetPolicyAsync(string policyName)
{
foreach (var prefix in (string[])[KhaemhatPolicies.PermissionPrefix, KhaemhatPolicies.LevelPrefix, KhaemhatPolicies.ModulePrefix])
{
if (policyName.StartsWith(prefix, StringComparison.Ordinal))
{
return Task.FromResult<AuthorizationPolicy?>(new AuthorizationPolicyBuilder(SessionCookie.Scheme)
.RequireAuthenticatedUser()
.AddRequirements(new KhaemhatRequirement(prefix, policyName[prefix.Length..]))
.Build());
}
}
return _fallback.GetPolicyAsync(policyName);
}
}
/// <summary>Evaluates <see cref="KhaemhatRequirement"/> with the permission service and the licence.</summary>
/// <param name="permissions">The permissions.</param>
/// <param name="licenses">The licence.</param>
internal sealed class KhaemhatAuthorizationHandler(PermissionService permissions, ILicenseGate licenses) : AuthorizationHandler<KhaemhatRequirement>
{
/// <inheritdoc />
protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context, KhaemhatRequirement requirement)
{
if (SessionCookie.ActorOf(context.User) is not { } actor)
{
return;
}
var allowed = requirement.Kind switch
{
KhaemhatPolicies.LevelPrefix => Enum.TryParse<UserLevel>(requirement.Value, out var level) && actor.Level >= level,
KhaemhatPolicies.ModulePrefix => licenses.IsModuleActive(requirement.Value),
_ => (await permissions.CheckAsync(actor, requirement.Value).ConfigureAwait(false)).Allowed,
};
if (allowed)
{
context.Succeed(requirement);
}
}
}
+70
View File
@@ -0,0 +1,70 @@
using Khaemhat.Application.Security;
using Khaemhat.Core.Security;
namespace Khaemhat.Web.Security;
/// <summary>The pages of the sign-in flow and the messages shown for the error codes of <see cref="SecurityErrors"/>.</summary>
public static class LoginFlow
{
/// <summary>The login page (mockup 001).</summary>
public const string LoginPage = "/login";
/// <summary>The TOTP page (mockup 002).</summary>
public const string TotpPage = "/login/verifica";
/// <summary>The TOTP setup page.</summary>
public const string TotpSetupPage = "/login/configura-verifica";
/// <summary>The forced password change (mockup 003).</summary>
public const string PasswordChangePage = "/login/cambio-password";
/// <summary>Where a session in a state goes next.</summary>
/// <param name="state">The state reached.</param>
/// <param name="returnUrl">Where the user wanted to go.</param>
/// <returns>The local address.</returns>
public static string NextPage(SessionState? state, string? returnUrl) => state switch
{
SessionState.PendingTotp => TotpPage + Carry(returnUrl),
SessionState.PendingTotpSetup => TotpSetupPage + Carry(returnUrl),
SessionState.PendingPasswordChange => PasswordChangePage + Carry(returnUrl),
SessionState.Active => SafeReturnUrl(returnUrl),
_ => LoginPage,
};
/// <summary>A return address only when it stays on this site.</summary>
/// <param name="returnUrl">The address asked for.</param>
/// <returns>The address, or <c>/</c>.</returns>
public static string SafeReturnUrl(string? returnUrl) =>
returnUrl is { Length: > 0 } url && url[0] == '/' && !url.StartsWith("//", StringComparison.Ordinal) && !url.StartsWith("/\\", StringComparison.Ordinal)
&& !url.StartsWith("/login", StringComparison.OrdinalIgnoreCase)
? url
: "/";
/// <summary>The Italian message of an error code (several codes may be joined by commas).</summary>
/// <param name="error">The code(s).</param>
/// <returns>The messages.</returns>
public static IReadOnlyList<string> Messages(string? error) =>
string.IsNullOrEmpty(error) ? [] : [.. error.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries).Select(Message)];
private static string Message(string code) => code switch
{
SecurityErrors.InvalidCredentials => "Azienda, utente o password non corretti.",
SecurityErrors.AccountLocked => "Troppi tentativi non riusciti: l'account è bloccato per 15 minuti.",
SecurityErrors.AccountDisabled => "L'account è disattivato: rivolgiti all'amministratore.",
SecurityErrors.TemporaryPasswordExpired => "La password provvisoria è scaduta: chiedine una nuova all'amministratore.",
SecurityErrors.PasswordTooShort => "La nuova password è troppo corta: servono almeno 10 caratteri.",
SecurityErrors.PasswordTooSimple => "La nuova password deve contenere almeno tre tipi di carattere tra minuscole, maiuscole, cifre e simboli.",
SecurityErrors.PasswordContainsUserName => "La nuova password non può contenere il nome utente.",
SecurityErrors.PasswordReused => "La nuova password è uguale a una delle ultime cinque.",
SecurityErrors.CurrentPasswordWrong => "La password attuale non è corretta.",
SecurityErrors.TotpInvalid => "Codice non valido: controlla l'ora del telefono e riprova.",
SecurityErrors.RateLimited => "Troppi tentativi: riprova tra un minuto.",
SecurityErrors.ConcurrentUsersExceeded => "È stato raggiunto il numero massimo di utenti collegati previsto dalla licenza.",
SecurityErrors.CompanyUnavailable => "L'azienda è in manutenzione o non è disponibile.",
SecurityErrors.LicenseLimitReached => "La licenza non consente altri accessi di questo tipo.",
_ => "Accesso non riuscito.",
};
private static string Carry(string? returnUrl) =>
SafeReturnUrl(returnUrl) is var url && url != "/" ? "?returnUrl=" + Uri.EscapeDataString(url) : string.Empty;
}
@@ -0,0 +1,216 @@
using System.Globalization;
using System.Security.Claims;
using System.Text.Encodings.Web;
using Khaemhat.Application.Configuration;
using Khaemhat.Application.Security;
using Khaemhat.Core.Security;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.AspNetCore.Components.Server;
using Microsoft.Extensions.Options;
namespace Khaemhat.Web.Security;
/// <summary>The session cookie and the claims built from it.</summary>
public static class SessionCookie
{
/// <summary>The authentication scheme.</summary>
public const string Scheme = "KhaemhatSession";
/// <summary>The cookie name.</summary>
public const string Name = "khaemhat_session";
/// <summary>Claim: the session row.</summary>
public const string SessionIdClaim = "kh:session";
/// <summary>Claim: the database holding the account (<c>_</c> for instance accounts).</summary>
public const string OwnerClaim = "kh:owner";
/// <summary>Claim: the account row.</summary>
public const string UserIdClaim = "kh:user";
/// <summary>Claim: the level.</summary>
public const string LevelClaim = "kh:level";
/// <summary>Claim: the company the session works in.</summary>
public const string CompanyClaim = "kh:company";
/// <summary>Claim: the linked company user of an administrator.</summary>
public const string LinkedUserClaim = "kh:linked";
/// <summary>Claim: the name shown.</summary>
public const string DisplayNameClaim = "kh:display";
/// <summary>Sets the cookie.</summary>
/// <param name="context">The request.</param>
/// <param name="value">The cookie value.</param>
/// <param name="persistentUntil">Expiry for "remember me"; <see langword="null"/> for a browser-session cookie.</param>
public static void Write(HttpContext context, string value, DateTimeOffset? persistentUntil = null)
{
ArgumentNullException.ThrowIfNull(context);
context.Response.Cookies.Append(Name, value, Options(context, persistentUntil));
}
/// <summary>Removes the cookie.</summary>
/// <param name="context">The request.</param>
public static void Clear(HttpContext context)
{
ArgumentNullException.ThrowIfNull(context);
context.Response.Cookies.Delete(Name, Options(context, null));
}
/// <summary>The cookie of the request.</summary>
/// <param name="context">The request.</param>
/// <returns>The value, or <see langword="null"/>.</returns>
public static string? Read(HttpContext context) => context?.Request.Cookies[Name];
/// <summary>The claims of a signed-in session.</summary>
/// <param name="identity">The session.</param>
/// <returns>The principal.</returns>
public static ClaimsPrincipal Principal(SessionIdentity identity)
{
ArgumentNullException.ThrowIfNull(identity);
var claims = new List<Claim>
{
new(ClaimTypes.Name, identity.UserName),
new(DisplayNameClaim, identity.DisplayName),
new(SessionIdClaim, identity.SessionId.ToString(CultureInfo.InvariantCulture)),
new(OwnerClaim, identity.Owner.CompanyDatabase ?? "_"),
new(UserIdClaim, identity.Owner.UserId.ToString(CultureInfo.InvariantCulture)),
new(LevelClaim, identity.Level.ToString()),
};
if (identity.CompanyCode is not null)
{
claims.Add(new Claim(CompanyClaim, identity.CompanyCode));
}
if (identity.LinkedUserId is { } linked)
{
claims.Add(new Claim(LinkedUserClaim, linked.ToString(CultureInfo.InvariantCulture)));
}
return new ClaimsPrincipal(new ClaimsIdentity(claims, Scheme, ClaimTypes.Name, LevelClaim));
}
/// <summary>The actor of a principal built by <see cref="Principal"/>.</summary>
/// <param name="user">The principal.</param>
/// <returns>The actor, or <see langword="null"/> when not signed in.</returns>
public static Actor? ActorOf(ClaimsPrincipal? user)
{
if (user?.Identity is not { IsAuthenticated: true, Name: { } name } || OwnerOf(user) is not { } owner)
{
return null;
}
var level = Enum.TryParse<UserLevel>(user.FindFirst(LevelClaim)?.Value, out var parsed) ? parsed : UserLevel.Standard;
var company = user.FindFirst(CompanyClaim)?.Value;
var linked = long.TryParse(user.FindFirst(LinkedUserClaim)?.Value, NumberStyles.None, CultureInfo.InvariantCulture, out var l) ? l : (long?)null;
return owner.IsInstanceAccount
? new Actor(name, level, owner.UserId, linked, company)
: new Actor(name, UserLevel.Standard, null, owner.UserId, company);
}
/// <summary>The account of a principal.</summary>
/// <param name="user">The principal.</param>
/// <returns>The owner, or <see langword="null"/>.</returns>
public static SessionOwner? OwnerOf(ClaimsPrincipal? user)
{
var database = user?.FindFirst(OwnerClaim)?.Value;
return database is not null && long.TryParse(user!.FindFirst(UserIdClaim)?.Value, NumberStyles.None, CultureInfo.InvariantCulture, out var id)
? new SessionOwner(database == "_" ? null : database, id)
: null;
}
/// <summary>The session row of a principal.</summary>
/// <param name="user">The principal.</param>
/// <returns>The session id, or <see langword="null"/>.</returns>
public static long? SessionIdOf(ClaimsPrincipal? user) =>
long.TryParse(user?.FindFirst(SessionIdClaim)?.Value, NumberStyles.None, CultureInfo.InvariantCulture, out var id) ? id : null;
private static CookieOptions Options(HttpContext context, DateTimeOffset? persistentUntil)
{
var publicUrl = context.RequestServices.GetService<KhaemhatOptions>()?.PublicUrl;
return new CookieOptions
{
HttpOnly = true,
IsEssential = true,
SameSite = SameSiteMode.Lax,
Path = "/",
Secure = context.Request.IsHttps || (publicUrl?.StartsWith("https://", StringComparison.OrdinalIgnoreCase) ?? false),
Expires = persistentUntil,
};
}
}
/// <summary>
/// Authenticates requests with the session cookie (SPEC §7.3): only sessions that completed every sign-in step count;
/// a pending session (TOTP, password change) is handled by the login pages themselves.
/// </summary>
/// <param name="options">The scheme options.</param>
/// <param name="logger">The log factory.</param>
/// <param name="encoder">The URL encoder.</param>
/// <param name="signIn">Resolves sessions.</param>
internal sealed class SessionAuthenticationHandler(
IOptionsMonitor<AuthenticationSchemeOptions> options, ILoggerFactory logger, UrlEncoder encoder, SignInService signIn)
: AuthenticationHandler<AuthenticationSchemeOptions>(options, logger, encoder)
{
/// <summary>The key of the resolved identity in <see cref="HttpContext.Items"/>.</summary>
public const string IdentityItem = "kh:identity";
/// <inheritdoc />
protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
{
var cookie = SessionCookie.Read(Context);
if (string.IsNullOrEmpty(cookie))
{
return AuthenticateResult.NoResult();
}
var identity = await signIn.ResolveAsync(cookie, Context.RequestAborted).ConfigureAwait(false);
if (identity is null)
{
return AuthenticateResult.NoResult();
}
Context.Items[IdentityItem] = identity;
return identity.State == SessionState.Active
? AuthenticateResult.Success(new AuthenticationTicket(SessionCookie.Principal(identity), SessionCookie.Scheme))
: AuthenticateResult.NoResult();
}
/// <inheritdoc />
protected override Task HandleChallengeAsync(AuthenticationProperties properties)
{
var path = Request.Path + Request.QueryString;
Response.Redirect("/login" + (path.Length > 1 ? "?returnUrl=" + Uri.EscapeDataString(path) : string.Empty));
return Task.CompletedTask;
}
/// <inheritdoc />
protected override Task HandleForbiddenAsync(AuthenticationProperties properties)
{
Response.Redirect("/accesso-negato");
return Task.CompletedTask;
}
}
/// <summary>
/// Checks every minute that the session behind an open Blazor circuit is still valid: a revoked or expired session
/// (sign-out elsewhere, maintenance, disabled account) ends the circuit's authentication.
/// </summary>
/// <param name="loggerFactory">The log factory.</param>
/// <param name="sessions">The sessions.</param>
internal sealed class SessionRevalidatingStateProvider(ILoggerFactory loggerFactory, SessionStore sessions)
: RevalidatingServerAuthenticationStateProvider(loggerFactory)
{
/// <inheritdoc />
protected override TimeSpan RevalidationInterval => TimeSpan.FromMinutes(1);
/// <inheritdoc />
protected override async Task<bool> ValidateAuthenticationStateAsync(AuthenticationState authenticationState, CancellationToken cancellationToken)
{
var user = authenticationState.User;
return SessionCookie.OwnerOf(user) is { } owner && SessionCookie.SessionIdOf(user) is { } id
&& await sessions.IsActiveAsync(owner, id, cancellationToken).ConfigureAwait(false);
}
}
@@ -0,0 +1,46 @@
using System.Security.Claims;
using Khaemhat.Application.Instance;
using Microsoft.AspNetCore.Components.Authorization;
namespace Khaemhat.Web.Security;
/// <summary>
/// The company of a Blazor circuit or of an HTTP request: the user comes from the authentication state of the circuit,
/// or from the request outside circuits, where an API call may also name the company in <c>X-Company</c>.
/// </summary>
/// <param name="authentication">The authentication state of the circuit.</param>
/// <param name="http">The current request, outside circuits.</param>
/// <param name="resolver">The rules.</param>
internal sealed class WebCompanyContext(AuthenticationStateProvider authentication, IHttpContextAccessor http, CompanyContextResolver resolver) : ICompanyContext
{
private CompanyContextResult? _result;
/// <inheritdoc />
public async ValueTask<CompanyContextResult> GetAsync(CancellationToken cancellationToken = default)
{
if (_result is not null)
{
return _result;
}
ClaimsPrincipal? user;
string? requested = null;
try
{
user = (await authentication.GetAuthenticationStateAsync().ConfigureAwait(false)).User;
}
catch (InvalidOperationException)
{
// Outside a circuit the authentication state is not set: use the request.
var context = http.HttpContext;
user = context?.User;
if (context?.Request.Path.StartsWithSegments("/api") == true)
{
requested = context.Request.Headers[CompanyContextResolver.Header].ToString();
}
}
_result = await resolver.ResolveAsync(SessionCookie.ActorOf(user), requested, cancellationToken).ConfigureAwait(false);
return _result;
}
}