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