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;
/// The per-user flags of SPEC §7.2.
/// Sees only the customers assigned to the user.
/// Sees costs and margins.
/// Can export.
/// Can use the API.
public sealed record UserFlags(bool OwnCustomersOnly, bool CanSeeCosts, bool CanExport, bool CanUseApi)
{
/// Everything allowed: instance accounts.
public static UserFlags Unrestricted { get; } = new(false, true, true, true);
}
/// What a user may do in a company, before the licence is applied. Cached per user.
/// Instance accounts: every permission.
/// The patterns granted by roles and overrides.
/// The patterns denied by overrides (they win).
/// The per-user flags.
public sealed record EffectivePermissions(bool AllAccess, IReadOnlyList Granted, IReadOnlyList Denied, UserFlags Flags)
{
/// Every permission.
public static EffectivePermissions All { get; } = new(true, ["*"], [], UserFlags.Unrestricted);
/// No permission.
public static EffectivePermissions None { get; } = new(false, [], [], new UserFlags(true, false, false, false));
/// Whether the roles and overrides allow a code (the licence is checked by ).
/// The permission code.
/// if allowed.
public bool Allows(string code) =>
AllAccess || (!Denied.Any(d => PermissionPattern.Matches(d, code)) && Granted.Any(g => PermissionPattern.Matches(g, code)));
}
/// The outcome of a permission check: is permission_denied, module_not_licensed or license_read_only.
/// Whether the action is allowed.
/// The reason otherwise.
public sealed record PermissionCheck(bool Allowed, string? Error)
{
/// Allowed.
public static PermissionCheck Ok { get; } = new(true, null);
}
///
/// 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
/// module_not_licensed; past the licence grace only .read permissions remain. Results are cached per user
/// under kh:{company}:permissions: and invalidated when roles or users change.
///
public sealed class PermissionService(IUnitOfWorkFactory factory, ICacheProvider cache, ILicenseGate licenses, ModuleRegistry modules)
{
/// The error when the licence is expired beyond the grace period.
public const string LicenseReadOnly = "license_read_only";
private const string Area = "permissions";
private static readonly TimeSpan CacheTime = TimeSpan.FromMinutes(10);
/// The permissions of an actor in its company.
/// The actor.
/// Cancellation.
/// The permissions.
public async Task 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(LoadAsync(company, userId, ct)),
CacheTime,
cancellationToken).ConfigureAwait(false);
}
/// Checks one permission, licence included.
/// The actor.
/// The permission code.
/// Cancellation.
/// The outcome.
public async Task 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);
}
/// Throws when the actor may not perform the action.
/// The actor.
/// The permission code.
/// Cancellation.
/// A task.
/// The permission is missing or the module is not licensed.
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.");
}
}
/// Whether the actor holds every permission a set of patterns would grant (roles are never above one's own).
/// The actor.
/// The patterns.
/// Cancellation.
/// when nothing in the patterns exceeds the actor.
public async Task CoversAsync(Actor actor, IEnumerable 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));
}
/// Forgets the cached permissions of a company, here and on the other instances.
/// The company.
/// Cancellation.
/// A task.
public ValueTask InvalidateAsync(string companyCode, CancellationToken cancellationToken = default) =>
cache.PublishInvalidationAsync(CacheKeys.Prefix(CompanyCodes.Normalize(companyCode), Area), cancellationToken);
private async Task 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().GetAsync(userId, cancellationToken).ConfigureAwait(false);
if (user is not { IsActive: true })
{
return EffectivePermissions.None;
}
var roleIds = (await unitOfWork.Repository()
.ListAsync(Query.For().Where(r => r.UserId == userId), cancellationToken).ConfigureAwait(false)).Items.Select(r => r.RoleId).ToArray();
var granted = roleIds.Length == 0
? []
: (await unitOfWork.Repository()
.ListAsync(Query.For().Where(g => roleIds.Contains(g.RoleId)), cancellationToken).ConfigureAwait(false)).Items
.Select(g => g.Permission).ToList();
var overrides = (await unitOfWork.Repository()
.ListAsync(Query.For().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));
}
}