using Khaemhat.Core.Caching; using Khaemhat.Core.Security; using Khaemhat.Data; using Khaemhat.Data.Companies; using Khaemhat.Data.Querying; using Khaemhat.Infrastructure.Security; namespace Khaemhat.Application.Security; /// /// Who a session belongs to: an instance account (sys_sessions) or a user of a company (user_sessions in /// that company's database). /// /// The company whose database holds the user; for instance accounts. /// The account. public sealed record SessionOwner(string? CompanyDatabase, long UserId) { /// Whether the owner is an instance account. public bool IsInstanceAccount => CompanyDatabase is null; } /// What a valid session says about its user, resolved at each request and cached briefly. /// The session row. /// The owner. /// The sign-in state. /// The user name. /// The name shown. /// The level. /// The company the session works in. /// For administrators linked to a user of : that user. /// When the session expires unless used. /// Whether the cookie survives the browser. public sealed record SessionIdentity( long SessionId, SessionOwner Owner, SessionState State, string UserName, string DisplayName, UserLevel Level, string? CompanyCode, long? LinkedUserId, DateTime ExpiresAt, bool Persistent) { /// The actor for the services. /// The actor. public Actor ToActor() => Owner.IsInstanceAccount ? new Actor(UserName, Level, Owner.UserId, LinkedUserId, CompanyCode) : new Actor(UserName, UserLevel.Standard, null, Owner.UserId, CompanyCode); } /// A session as listed to its user or to administrators. /// The session row. /// The sign-in time. /// The last request. /// The client address. /// The browser. /// The company. public sealed record SessionSummary(long Id, DateTime CreatedAt, DateTime LastSeenAt, string? IpAddress, string? UserAgent, string? CompanyCode); /// /// Sign-in sessions (SPEC §7.3). The cookie value is <scope>.<token>: the scope says which database /// holds the row (_ for the system database, otherwise the company code) and the token is 256 random bits, of which /// only the SHA-256 hash is stored. Expiry is sliding; revocation takes effect at the next request. /// public sealed class SessionStore { private const string SystemScope = "_"; private const string CacheArea = "sessions"; private static readonly TimeSpan TouchInterval = TimeSpan.FromMinutes(1); private static readonly TimeSpan CacheTime = TimeSpan.FromSeconds(30); private readonly IUnitOfWorkFactory _factory; private readonly ICompanyRegistry _companies; private readonly ICacheProvider _cache; private readonly SecurityPolicyOptions _policy; private readonly TimeProvider _clock; /// Creates the store. /// Opens the databases. /// The company registry. /// The cache of resolved sessions. /// Session lifetimes. /// The clock. public SessionStore(IUnitOfWorkFactory factory, ICompanyRegistry companies, ICacheProvider cache, SecurityPolicyOptions policy, TimeProvider clock) { ArgumentNullException.ThrowIfNull(factory); ArgumentNullException.ThrowIfNull(companies); ArgumentNullException.ThrowIfNull(cache); ArgumentNullException.ThrowIfNull(policy); ArgumentNullException.ThrowIfNull(clock); _factory = factory; _companies = companies; _cache = cache; _policy = policy; _clock = clock; } private DateTime Now => DateTime.SpecifyKind(Data.Execution.DataAccessContext.Truncate(_clock.GetUtcNow().UtcDateTime), DateTimeKind.Utc); /// Creates a session. /// The owner. /// The sign-in state. /// The company the session works in. /// The client address. /// The browser. /// "Remember me on this device". /// Cancellation. /// The cookie value. public async Task CreateAsync( SessionOwner owner, SessionState state, string? companyCode, string? ipAddress, string? userAgent, bool persistent, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(owner); var token = SecureTokenGenerator.Create(); var now = Now; SessionRecord session = owner.IsInstanceAccount ? new SystemSession() : new UserSession(); session.TokenHash = SecureTokenGenerator.Hash(token); session.UserId = owner.UserId; session.State = state; session.CompanyCode = companyCode; session.IpAddress = Clip(ipAddress, 64); session.UserAgent = Clip(userAgent, 400); session.Persistent = persistent; session.LastSeenAt = now; session.ExpiresAt = now + Lifetime(state, persistent); await using var unitOfWork = await OpenAsync(owner, cancellationToken).ConfigureAwait(false); if (session is SystemSession system) { await unitOfWork.Repository().InsertAsync(system, cancellationToken).ConfigureAwait(false); } else { await unitOfWork.Repository().InsertAsync((UserSession)session, cancellationToken).ConfigureAwait(false); } return (owner.CompanyDatabase ?? SystemScope) + "." + token; } /// Finds the valid session of a cookie (not revoked, not expired) and slides its expiry. /// The cookie value. /// Cancellation. /// The session row and owner, or . public async Task<(SessionRecord Session, SessionOwner Owner)?> FindAsync(string? cookie, CancellationToken cancellationToken = default) { if (!TryParse(cookie, out var owner, out var hash)) { return null; } await using var unitOfWork = await OpenAsync(owner, cancellationToken).ConfigureAwait(false); var session = owner.IsInstanceAccount ? await unitOfWork.Repository().FindAsync(Query.For().Where(s => s.TokenHash == hash), cancellationToken).ConfigureAwait(false) : (SessionRecord?)await unitOfWork.Repository().FindAsync(Query.For().Where(s => s.TokenHash == hash), cancellationToken).ConfigureAwait(false); var now = Now; if (session is null || session.RevokedAt is not null || session.ExpiresAt <= now) { return null; } if (now - session.LastSeenAt >= TouchInterval) { session.LastSeenAt = now; session.ExpiresAt = now + Lifetime(session.State, session.Persistent); await SaveAsync(unitOfWork, session, cancellationToken).ConfigureAwait(false); } return (session, owner with { UserId = session.UserId }); } /// Moves a session to another sign-in state and gives it a new token (the old cookie stops working). /// The current cookie value. /// The new state. /// Cancellation. /// The new cookie value, or when the session is not valid. public async Task AdvanceAsync(string cookie, SessionState state, CancellationToken cancellationToken = default) { if (await FindAsync(cookie, cancellationToken).ConfigureAwait(false) is not var (session, owner)) { return null; } var token = SecureTokenGenerator.Create(); var now = Now; session.TokenHash = SecureTokenGenerator.Hash(token); session.State = state; session.LastSeenAt = now; session.ExpiresAt = now + Lifetime(state, session.Persistent); await using var unitOfWork = await OpenAsync(owner, cancellationToken).ConfigureAwait(false); await SaveAsync(unitOfWork, session, cancellationToken).ConfigureAwait(false); await ForgetAsync(cookie, cancellationToken).ConfigureAwait(false); return (owner.CompanyDatabase ?? SystemScope) + "." + token; } /// Changes the company a session of an instance account works in. /// The cookie value. /// The company, or . /// Cancellation. /// A task. public async Task SetCompanyAsync(string cookie, string? companyCode, CancellationToken cancellationToken = default) { if (await FindAsync(cookie, cancellationToken).ConfigureAwait(false) is not var (session, owner) || !owner.IsInstanceAccount) { throw new AccessDeniedException(SecurityErrors.PermissionDenied, "Only instance accounts choose the company."); } session.CompanyCode = companyCode is null ? null : CompanyCodes.Normalize(companyCode); await using var unitOfWork = await OpenAsync(owner, cancellationToken).ConfigureAwait(false); await SaveAsync(unitOfWork, session, cancellationToken).ConfigureAwait(false); await ForgetAsync(cookie, cancellationToken).ConfigureAwait(false); } /// Revokes the session of a cookie (sign-out). /// The cookie value. /// Why. /// Cancellation. /// The owner of the revoked session, or . public async Task RevokeAsync(string? cookie, string reason, CancellationToken cancellationToken = default) { if (await FindAsync(cookie, cancellationToken).ConfigureAwait(false) is not var (session, owner)) { return null; } await RevokeAsync(owner, session.Id, reason, cancellationToken).ConfigureAwait(false); await ForgetAsync(cookie!, cancellationToken).ConfigureAwait(false); return owner; } /// Revokes one session of an owner (from the list of sessions). /// The owner. /// The session row. /// Why. /// Cancellation. /// Whether a session was revoked. public async Task RevokeAsync(SessionOwner owner, long sessionId, string reason, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(owner); var revoked = await RevokeWhereAsync(owner, s => s.Id == sessionId && s.UserId == owner.UserId, reason, cancellationToken).ConfigureAwait(false); return revoked > 0; } /// Revokes every session of an owner, except one (password change, administrator action). /// The owner. /// Why. /// The session to keep. /// Cancellation. /// The number of sessions revoked. public Task RevokeAllAsync(SessionOwner owner, string reason, long? exceptSessionId = null, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(owner); var keep = exceptSessionId ?? 0; return RevokeWhereAsync(owner, s => s.UserId == owner.UserId && s.Id != keep, reason, cancellationToken); } /// /// Revokes every session of the users of a company (maintenance, disabling): instance accounts keep theirs, also when /// they work in that company. /// /// The company. /// Why. /// Cancellation. /// The number of sessions revoked. public async Task RevokeCompanyAsync(string companyCode, string reason, CancellationToken cancellationToken = default) { var now = Now; var why = Clip(reason, 100); int count; await using (var unitOfWork = await _factory.CreateAsync(DatabaseScope.Company(companyCode), cancellationToken).ConfigureAwait(false)) { count = await unitOfWork.ExecuteAsync( SqlFragment.Of($"UPDATE {SqlFragment.Identifier("user_sessions")} SET revoked_at = {now}, revoked_reason = {why} WHERE revoked_at IS NULL"), cancellationToken).ConfigureAwait(false); } if (count > 0) { await _cache.PublishInvalidationAsync(CacheKeys.Prefix(null, CacheArea), cancellationToken).ConfigureAwait(false); } return count; } /// Whether a signed-in session is still valid (the periodic check of open Blazor circuits). /// The owner. /// The session row. /// Cancellation. /// while the session is active, not revoked and not expired. public async Task IsActiveAsync(SessionOwner owner, long sessionId, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(owner); var now = Now; await using var unitOfWork = await OpenAsync(owner, cancellationToken).ConfigureAwait(false); var userId = owner.UserId; return owner.IsInstanceAccount ? await unitOfWork.Repository().CountAsync( Query.For().Where(s => s.Id == sessionId && s.UserId == userId && s.RevokedAt == null && s.ExpiresAt > now && s.State == SessionState.Active), cancellationToken).ConfigureAwait(false) > 0 : await unitOfWork.Repository().CountAsync( Query.For().Where(s => s.Id == sessionId && s.UserId == userId && s.RevokedAt == null && s.ExpiresAt > now && s.State == SessionState.Active), cancellationToken).ConfigureAwait(false) > 0; } /// The active sessions of an owner. /// The owner. /// Cancellation. /// The sessions, most recent first. public async Task> ListAsync(SessionOwner owner, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(owner); var now = Now; var userId = owner.UserId; await using var unitOfWork = await OpenAsync(owner, cancellationToken).ConfigureAwait(false); IEnumerable sessions = owner.IsInstanceAccount ? (await unitOfWork.Repository().ListAsync( Query.For().Where(s => s.UserId == userId && s.RevokedAt == null && s.ExpiresAt > now).OrderByDescending(s => s.LastSeenAt), cancellationToken) .ConfigureAwait(false)).Items : (await unitOfWork.Repository().ListAsync( Query.For().Where(s => s.UserId == userId && s.RevokedAt == null && s.ExpiresAt > now).OrderByDescending(s => s.LastSeenAt), cancellationToken) .ConfigureAwait(false)).Items; return [.. sessions.Select(s => new SessionSummary(s.Id, s.CreatedAt, s.LastSeenAt, s.IpAddress, s.UserAgent, s.CompanyCode))]; } /// Whether an owner has signed in before from the same browser (to warn about new devices). /// The owner. /// The browser. /// The session just created. /// Cancellation. /// if a previous session used the same browser. public async Task IsKnownDeviceAsync(SessionOwner owner, string? userAgent, long exceptSessionId, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(owner); var agent = Clip(userAgent, 400); var userId = owner.UserId; await using var unitOfWork = await OpenAsync(owner, cancellationToken).ConfigureAwait(false); return owner.IsInstanceAccount ? await unitOfWork.Repository().CountAsync( Query.For().Where(s => s.UserId == userId && s.UserAgent == agent && s.Id != exceptSessionId && s.State == SessionState.Active), cancellationToken) .ConfigureAwait(false) > 0 : await unitOfWork.Repository().CountAsync( Query.For().Where(s => s.UserId == userId && s.UserAgent == agent && s.Id != exceptSessionId && s.State == SessionState.Active), cancellationToken) .ConfigureAwait(false) > 0; } /// /// The users with an active session across the system database and every company (the concurrent-user limit of the /// licence, SPEC §7.3). /// /// Cancellation. /// The owners with at least one active session. public async Task> ActiveOwnersAsync(CancellationToken cancellationToken = default) { var now = Now; var owners = new HashSet(); await using (var system = await _factory.CreateAsync(DatabaseScope.System, cancellationToken).ConfigureAwait(false)) { var rows = await system.QueryAsync( SqlFragment.Of($"SELECT DISTINCT user_id FROM {SqlFragment.Identifier("sys_sessions")} WHERE revoked_at IS NULL AND expires_at > {now} AND state = {nameof(SessionState.Active)}"), cancellationToken).ConfigureAwait(false); owners.UnionWith(rows.Select(id => new SessionOwner(null, id))); } foreach (var company in await _companies.ListAsync(cancellationToken).ConfigureAwait(false)) { if (company.Status is Core.Instance.CompanyStatus.Disabled) { continue; } await using var unitOfWork = await _factory.CreateAsync(DatabaseScope.Company(company.Code), cancellationToken).ConfigureAwait(false); var rows = await unitOfWork.QueryAsync( SqlFragment.Of($"SELECT DISTINCT user_id FROM {SqlFragment.Identifier("user_sessions")} WHERE revoked_at IS NULL AND expires_at > {now} AND state = {nameof(SessionState.Active)}"), cancellationToken).ConfigureAwait(false); owners.UnionWith(rows.Select(id => new SessionOwner(company.Code, id))); } return owners; } /// Deletes sessions expired or revoked more than ago (the cleanup job). /// The database. /// How long to keep them for the history. /// Cancellation. /// The rows deleted. public async Task PurgeAsync(DatabaseScope scope, TimeSpan age, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(scope); var limit = Now - age; var table = scope.IsSystem ? "sys_sessions" : "user_sessions"; await using var unitOfWork = await _factory.CreateAsync(scope, cancellationToken).ConfigureAwait(false); return await unitOfWork.ExecuteAsync( SqlFragment.Of($"DELETE FROM {SqlFragment.Identifier(table)} WHERE expires_at < {limit} OR revoked_at < {limit}"), cancellationToken).ConfigureAwait(false); } /// The cache key of a cookie's resolved identity. /// The cookie value. /// The key. public static string CacheKey(string cookie) => CacheKeys.For(null, CacheArea, SecureTokenGenerator.Hash(cookie ?? string.Empty)); /// Forgets the cached identity of a cookie. /// The cookie value. /// Cancellation. /// A task. public ValueTask ForgetAsync(string cookie, CancellationToken cancellationToken = default) => _cache.RemoveAsync(CacheKey(cookie), cancellationToken); /// How long a resolved identity may stay cached (revocations by id also clear the whole area). public static TimeSpan IdentityCacheTime => CacheTime; private async Task RevokeWhereAsync(SessionOwner owner, System.Linq.Expressions.Expression> filter, string reason, CancellationToken cancellationToken) { var now = Now; var predicate = filter.Compile(); await using var unitOfWork = await OpenAsync(owner, cancellationToken).ConfigureAwait(false); var userId = owner.UserId; IEnumerable sessions = owner.IsInstanceAccount ? (await unitOfWork.Repository().ListAsync(Query.For().Where(s => s.UserId == userId && s.RevokedAt == null), cancellationToken).ConfigureAwait(false)).Items : (await unitOfWork.Repository().ListAsync(Query.For().Where(s => s.UserId == userId && s.RevokedAt == null), cancellationToken).ConfigureAwait(false)).Items; var count = 0; foreach (var session in sessions.Where(predicate)) { session.RevokedAt = now; session.RevokedReason = Clip(reason, 100); await SaveAsync(unitOfWork, session, cancellationToken).ConfigureAwait(false); count++; } if (count > 0) { // The identity cache is keyed by cookie, which is unknown here: drop the whole area (entries live 30 seconds). await _cache.PublishInvalidationAsync(CacheKeys.Prefix(null, CacheArea), cancellationToken).ConfigureAwait(false); } return count; } private static async Task SaveAsync(IUnitOfWork unitOfWork, SessionRecord session, CancellationToken cancellationToken) { if (session is SystemSession system) { await unitOfWork.Repository().UpdateAsync(system, cancellationToken).ConfigureAwait(false); } else { await unitOfWork.Repository().UpdateAsync((UserSession)session, cancellationToken).ConfigureAwait(false); } } private TimeSpan Lifetime(SessionState state, bool persistent) => state != SessionState.Active ? _policy.PendingStepLifetime : persistent ? _policy.PersistentSessionLifetime : _policy.SessionLifetime; private Task OpenAsync(SessionOwner owner, CancellationToken cancellationToken) => _factory.CreateAsync(owner.IsInstanceAccount ? DatabaseScope.System : DatabaseScope.Company(owner.CompanyDatabase!), cancellationToken); private static bool TryParse(string? cookie, out SessionOwner owner, out string hash) { owner = new SessionOwner(null, 0); hash = string.Empty; var dot = cookie?.IndexOf('.', StringComparison.Ordinal) ?? -1; if (dot <= 0 || cookie!.Length - dot < 40) { return false; } var scope = cookie[..dot]; if (scope != SystemScope && !CompanyCodes.IsValid(scope)) { return false; } owner = new SessionOwner(scope == SystemScope ? null : scope, 0); hash = SecureTokenGenerator.Hash(cookie[(dot + 1)..]); return true; } private static string? Clip(string? value, int length) => value is null || value.Length <= length ? value : value[..length]; }