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;
/// A role with its permission patterns.
/// The role.
/// The patterns.
public sealed record RoleWithPermissions(Role Role, IReadOnlyList Permissions);
///
/// Roles (SPEC ยง7.2): the eight predefined roles live as templates in sys_roles_templates and are copied into each
/// company, where they can be cloned but not changed. Users with company.users.manage manage roles never above
/// their own permissions.
///
public sealed class RoleService(IUnitOfWorkFactory factory, PermissionService permissions, ISecurityAuditLog audit)
{
/// Writes or updates the predefined templates in the system database (bootstrap and every start).
/// Cancellation.
/// A task.
public async Task SeedTemplatesAsync(CancellationToken cancellationToken = default)
{
await using var unitOfWork = await factory.CreateAsync(DatabaseScope.System, cancellationToken).ConfigureAwait(false);
var templates = unitOfWork.Repository();
var existing = (await templates.ListAsync(Query.For(), 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);
}
///
/// 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).
///
/// The company.
/// Cancellation.
/// A task.
public async Task SyncPredefinedRolesAsync(string companyCode, CancellationToken cancellationToken = default)
{
IReadOnlyList templates;
await using (var system = await factory.CreateAsync(DatabaseScope.System, cancellationToken).ConfigureAwait(false))
{
templates = (await system.Repository().ListAsync(Query.For().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();
var grants = unitOfWork.Repository();
await unitOfWork.InTransactionAsync(
async ct =>
{
foreach (var template in templates)
{
var code = template.Code;
var role = await roles.FindAsync(Query.For().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>(template.Permissions) ?? [];
await ReplaceGrantsAsync(grants, role.Id, wanted, ct).ConfigureAwait(false);
}
},
cancellationToken).ConfigureAwait(false);
await permissions.InvalidateAsync(companyCode, cancellationToken).ConfigureAwait(false);
}
/// The roles of a company with their permissions.
/// The company.
/// Cancellation.
/// The roles, predefined first.
public async Task> ListAsync(string companyCode, CancellationToken cancellationToken = default)
{
await using var unitOfWork = await factory.CreateAsync(DatabaseScope.Company(companyCode), cancellationToken).ConfigureAwait(false);
var roles = (await unitOfWork.Repository().ListAsync(Query.For().OrderByDescending(r => r.IsPredefined).OrderBy(r => r.Name), cancellationToken)
.ConfigureAwait(false)).Items;
var grants = (await unitOfWork.Repository().ListAsync(Query.For(), 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)]))];
}
/// Clones a role into a new, modifiable one.
/// Who acts.
/// The company.
/// The role to clone.
/// The new code.
/// The new name.
/// Cancellation.
/// The new role.
public async Task 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();
var grants = unitOfWork.Repository();
var source = await roles.FindAsync(Query.For().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().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().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;
}
/// Sets the permissions of a cloned role. Predefined roles are refused.
/// Who acts.
/// The company.
/// The role.
/// The new permission patterns.
/// Cancellation.
/// A task.
public async Task SetPermissionsAsync(Actor actor, string companyCode, string roleCode, IReadOnlyList 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().FindAsync(Query.For().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(), 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);
}
/// Checks that the actor may manage users and roles of a company.
/// The actor.
/// The company.
/// Cancellation.
/// A task.
/// The actor may not.
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 grants, long roleId, IEnumerable patterns, CancellationToken cancellationToken)
{
var current = (await grants.ListAsync(Query.For().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);
}
}
}