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,238 @@
|
||||
using System.Text.Json;
|
||||
using Khaemhat.Application.Audit;
|
||||
using Khaemhat.Application.Modules;
|
||||
using Khaemhat.Core.Security;
|
||||
using Khaemhat.Data;
|
||||
using Khaemhat.Data.Querying;
|
||||
|
||||
namespace Khaemhat.Application.Security;
|
||||
|
||||
/// <summary>A role with its permission patterns.</summary>
|
||||
/// <param name="Role">The role.</param>
|
||||
/// <param name="Permissions">The patterns.</param>
|
||||
public sealed record RoleWithPermissions(Role Role, IReadOnlyList<string> Permissions);
|
||||
|
||||
/// <summary>
|
||||
/// Roles (SPEC §7.2): the eight predefined roles live as templates in <c>sys_roles_templates</c> and are copied into each
|
||||
/// company, where they can be cloned but not changed. Users with <c>company.users.manage</c> manage roles never above
|
||||
/// their own permissions.
|
||||
/// </summary>
|
||||
public sealed class RoleService(IUnitOfWorkFactory factory, PermissionService permissions, ISecurityAuditLog audit)
|
||||
{
|
||||
/// <summary>Writes or updates the predefined templates in the system database (bootstrap and every start).</summary>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>A task.</returns>
|
||||
public async Task SeedTemplatesAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
await using var unitOfWork = await factory.CreateAsync(DatabaseScope.System, cancellationToken).ConfigureAwait(false);
|
||||
var templates = unitOfWork.Repository<RoleTemplate, long>();
|
||||
var existing = (await templates.ListAsync(Query.For<RoleTemplate>(), cancellationToken).ConfigureAwait(false)).Items
|
||||
.ToDictionary(t => t.Code, StringComparer.Ordinal);
|
||||
await unitOfWork.InTransactionAsync(
|
||||
async ct =>
|
||||
{
|
||||
var order = 0;
|
||||
foreach (var definition in PredefinedRoles.All)
|
||||
{
|
||||
var json = JsonSerializer.Serialize(definition.Permissions);
|
||||
order += 10;
|
||||
if (!existing.TryGetValue(definition.Code, out var template))
|
||||
{
|
||||
await templates.InsertAsync(
|
||||
new RoleTemplate { Code = definition.Code, Name = definition.Name, Description = definition.Description, Permissions = json, SortOrder = order },
|
||||
ct).ConfigureAwait(false);
|
||||
}
|
||||
else if (template.Permissions != json || template.Name != definition.Name || template.Description != definition.Description)
|
||||
{
|
||||
template.Name = definition.Name;
|
||||
template.Description = definition.Description;
|
||||
template.Permissions = json;
|
||||
template.SortOrder = order;
|
||||
await templates.UpdateAsync(template, ct).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
},
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Copies the templates into a company: missing predefined roles are created, existing ones are brought in line
|
||||
/// with their template (they are not modifiable, so the template wins).
|
||||
/// </summary>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>A task.</returns>
|
||||
public async Task SyncPredefinedRolesAsync(string companyCode, CancellationToken cancellationToken = default)
|
||||
{
|
||||
IReadOnlyList<RoleTemplate> templates;
|
||||
await using (var system = await factory.CreateAsync(DatabaseScope.System, cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
templates = (await system.Repository<RoleTemplate, long>().ListAsync(Query.For<RoleTemplate>().OrderBy(t => t.SortOrder), cancellationToken)
|
||||
.ConfigureAwait(false)).Items;
|
||||
}
|
||||
|
||||
await using var unitOfWork = await factory.CreateAsync(DatabaseScope.Company(companyCode), cancellationToken).ConfigureAwait(false);
|
||||
var roles = unitOfWork.Repository<Role, long>();
|
||||
var grants = unitOfWork.Repository<RoleGrant, long>();
|
||||
await unitOfWork.InTransactionAsync(
|
||||
async ct =>
|
||||
{
|
||||
foreach (var template in templates)
|
||||
{
|
||||
var code = template.Code;
|
||||
var role = await roles.FindAsync(Query.For<Role>().Where(r => r.Code == code), ct).ConfigureAwait(false);
|
||||
if (role is null)
|
||||
{
|
||||
role = new Role { Code = code, Name = template.Name, Description = template.Description, IsPredefined = true, TemplateCode = code };
|
||||
role.Id = await roles.InsertAsync(role, ct).ConfigureAwait(false);
|
||||
}
|
||||
else if (!role.IsPredefined)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var wanted = JsonSerializer.Deserialize<List<string>>(template.Permissions) ?? [];
|
||||
await ReplaceGrantsAsync(grants, role.Id, wanted, ct).ConfigureAwait(false);
|
||||
}
|
||||
},
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
await permissions.InvalidateAsync(companyCode, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>The roles of a company with their permissions.</summary>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The roles, predefined first.</returns>
|
||||
public async Task<IReadOnlyList<RoleWithPermissions>> ListAsync(string companyCode, CancellationToken cancellationToken = default)
|
||||
{
|
||||
await using var unitOfWork = await factory.CreateAsync(DatabaseScope.Company(companyCode), cancellationToken).ConfigureAwait(false);
|
||||
var roles = (await unitOfWork.Repository<Role, long>().ListAsync(Query.For<Role>().OrderByDescending(r => r.IsPredefined).OrderBy(r => r.Name), cancellationToken)
|
||||
.ConfigureAwait(false)).Items;
|
||||
var grants = (await unitOfWork.Repository<RoleGrant, long>().ListAsync(Query.For<RoleGrant>(), cancellationToken).ConfigureAwait(false)).Items
|
||||
.ToLookup(g => g.RoleId);
|
||||
return [.. roles.Select(r => new RoleWithPermissions(r, [.. grants[r.Id].Select(g => g.Permission).Order(StringComparer.Ordinal)]))];
|
||||
}
|
||||
|
||||
/// <summary>Clones a role into a new, modifiable one.</summary>
|
||||
/// <param name="actor">Who acts.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="sourceCode">The role to clone.</param>
|
||||
/// <param name="newCode">The new code.</param>
|
||||
/// <param name="newName">The new name.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The new role.</returns>
|
||||
public async Task<Role> CloneAsync(Actor actor, string companyCode, string sourceCode, string newCode, string newName, CancellationToken cancellationToken = default)
|
||||
{
|
||||
await DemandManageAsync(actor, companyCode, cancellationToken).ConfigureAwait(false);
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(newName);
|
||||
var code = NormalizeCode(newCode);
|
||||
await using var unitOfWork = await factory.CreateAsync(DatabaseScope.Company(companyCode), cancellationToken).ConfigureAwait(false);
|
||||
var roles = unitOfWork.Repository<Role, long>();
|
||||
var grants = unitOfWork.Repository<RoleGrant, long>();
|
||||
var source = await roles.FindAsync(Query.For<Role>().Where(r => r.Code == sourceCode), cancellationToken).ConfigureAwait(false)
|
||||
?? throw new KeyNotFoundException($"No role has code {sourceCode}.");
|
||||
var sourceId = source.Id;
|
||||
var patterns = (await grants.ListAsync(Query.For<RoleGrant>().Where(g => g.RoleId == sourceId), cancellationToken).ConfigureAwait(false)).Items
|
||||
.Select(g => g.Permission).ToList();
|
||||
if (!await permissions.CoversAsync(actor, patterns, cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
throw new AccessDeniedException(SecurityErrors.PermissionDenied, "A role cannot grant more than the permissions of who creates it.");
|
||||
}
|
||||
|
||||
var role = new Role { Code = code, Name = newName.Trim(), Description = source.Description, IsPredefined = false, TemplateCode = source.Code };
|
||||
await unitOfWork.InTransactionAsync(
|
||||
async ct =>
|
||||
{
|
||||
if (await roles.CountAsync(Query.For<Role>().Where(r => r.Code == code), ct).ConfigureAwait(false) > 0)
|
||||
{
|
||||
throw new ValidationFailedException(["role_code_taken"]);
|
||||
}
|
||||
|
||||
role.Id = await roles.InsertAsync(role, ct).ConfigureAwait(false);
|
||||
await ReplaceGrantsAsync(grants, role.Id, patterns, ct).ConfigureAwait(false);
|
||||
},
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
await audit.WriteAsync(new SecurityEvent("role.cloned", actor.UserName, companyCode, code, new { from = source.Code }), cancellationToken).ConfigureAwait(false);
|
||||
return role;
|
||||
}
|
||||
|
||||
/// <summary>Sets the permissions of a cloned role. Predefined roles are refused.</summary>
|
||||
/// <param name="actor">Who acts.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="roleCode">The role.</param>
|
||||
/// <param name="patterns">The new permission patterns.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>A task.</returns>
|
||||
public async Task SetPermissionsAsync(Actor actor, string companyCode, string roleCode, IReadOnlyList<string> patterns, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(patterns);
|
||||
await DemandManageAsync(actor, companyCode, cancellationToken).ConfigureAwait(false);
|
||||
if (patterns.Any(p => p != "*" && !PermissionPattern.IsCode(p.Replace("*", "x", StringComparison.Ordinal))))
|
||||
{
|
||||
throw new ValidationFailedException(["permission_invalid"]);
|
||||
}
|
||||
|
||||
if (!await permissions.CoversAsync(actor, patterns, cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
throw new AccessDeniedException(SecurityErrors.PermissionDenied, "A role cannot grant more than the permissions of who changes it.");
|
||||
}
|
||||
|
||||
await using var unitOfWork = await factory.CreateAsync(DatabaseScope.Company(companyCode), cancellationToken).ConfigureAwait(false);
|
||||
var role = await unitOfWork.Repository<Role, long>().FindAsync(Query.For<Role>().Where(r => r.Code == roleCode), cancellationToken).ConfigureAwait(false)
|
||||
?? throw new KeyNotFoundException($"No role has code {roleCode}.");
|
||||
if (role.IsPredefined)
|
||||
{
|
||||
throw new ValidationFailedException(["role_predefined"]);
|
||||
}
|
||||
|
||||
await unitOfWork.InTransactionAsync(ct => ReplaceGrantsAsync(unitOfWork.Repository<RoleGrant, long>(), role.Id, patterns, ct), cancellationToken).ConfigureAwait(false);
|
||||
await permissions.InvalidateAsync(companyCode, cancellationToken).ConfigureAwait(false);
|
||||
await audit.WriteAsync(new SecurityEvent("role.permissions-changed", actor.UserName, companyCode, roleCode, new { patterns }), cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>Checks that the actor may manage users and roles of a company.</summary>
|
||||
/// <param name="actor">The actor.</param>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>A task.</returns>
|
||||
/// <exception cref="AccessDeniedException">The actor may not.</exception>
|
||||
internal async Task DemandManageAsync(Actor actor, string companyCode, CancellationToken cancellationToken)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(actor);
|
||||
if (actor.IsInstanceAccount)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (!string.Equals(actor.CompanyCode, CompanyCodes.Normalize(companyCode), StringComparison.Ordinal))
|
||||
{
|
||||
throw new AccessDeniedException(SecurityErrors.PermissionDenied, "A company user works only in its own company.");
|
||||
}
|
||||
|
||||
await permissions.DemandAsync(actor, "company.users.manage", cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private static string NormalizeCode(string code)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(code);
|
||||
var normalized = code.Trim().ToUpperInvariant();
|
||||
return normalized.Length is >= 2 and <= 50 && normalized.All(c => char.IsAsciiLetterOrDigit(c) || c == '_')
|
||||
? normalized
|
||||
: throw new ValidationFailedException(["role_code_invalid"]);
|
||||
}
|
||||
|
||||
private static async Task ReplaceGrantsAsync(IRepository<RoleGrant, long> grants, long roleId, IEnumerable<string> patterns, CancellationToken cancellationToken)
|
||||
{
|
||||
var current = (await grants.ListAsync(Query.For<RoleGrant>().Where(g => g.RoleId == roleId), cancellationToken).ConfigureAwait(false)).Items;
|
||||
var wanted = patterns.Distinct(StringComparer.Ordinal).ToHashSet(StringComparer.Ordinal);
|
||||
foreach (var grant in current.Where(g => !wanted.Contains(g.Permission)))
|
||||
{
|
||||
await grants.DeleteAsync(grant.Id, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
foreach (var pattern in wanted.Except(current.Select(g => g.Permission)))
|
||||
{
|
||||
await grants.InsertAsync(new RoleGrant { RoleId = roleId, Permission = pattern }, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user