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,468 @@
|
||||
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;
|
||||
|
||||
/// <summary>
|
||||
/// Who a session belongs to: an instance account (<c>sys_sessions</c>) or a user of a company (<c>user_sessions</c> in
|
||||
/// that company's database).
|
||||
/// </summary>
|
||||
/// <param name="CompanyDatabase">The company whose database holds the user; <see langword="null"/> for instance accounts.</param>
|
||||
/// <param name="UserId">The account.</param>
|
||||
public sealed record SessionOwner(string? CompanyDatabase, long UserId)
|
||||
{
|
||||
/// <summary>Whether the owner is an instance account.</summary>
|
||||
public bool IsInstanceAccount => CompanyDatabase is null;
|
||||
}
|
||||
|
||||
/// <summary>What a valid session says about its user, resolved at each request and cached briefly.</summary>
|
||||
/// <param name="SessionId">The session row.</param>
|
||||
/// <param name="Owner">The owner.</param>
|
||||
/// <param name="State">The sign-in state.</param>
|
||||
/// <param name="UserName">The user name.</param>
|
||||
/// <param name="DisplayName">The name shown.</param>
|
||||
/// <param name="Level">The level.</param>
|
||||
/// <param name="CompanyCode">The company the session works in.</param>
|
||||
/// <param name="LinkedUserId">For administrators linked to a user of <paramref name="CompanyCode"/>: that user.</param>
|
||||
/// <param name="ExpiresAt">When the session expires unless used.</param>
|
||||
/// <param name="Persistent">Whether the cookie survives the browser.</param>
|
||||
public sealed record SessionIdentity(
|
||||
long SessionId, SessionOwner Owner, SessionState State, string UserName, string DisplayName, UserLevel Level,
|
||||
string? CompanyCode, long? LinkedUserId, DateTime ExpiresAt, bool Persistent)
|
||||
{
|
||||
/// <summary>The actor for the services.</summary>
|
||||
/// <returns>The actor.</returns>
|
||||
public Actor ToActor() => Owner.IsInstanceAccount
|
||||
? new Actor(UserName, Level, Owner.UserId, LinkedUserId, CompanyCode)
|
||||
: new Actor(UserName, UserLevel.Standard, null, Owner.UserId, CompanyCode);
|
||||
}
|
||||
|
||||
/// <summary>A session as listed to its user or to administrators.</summary>
|
||||
/// <param name="Id">The session row.</param>
|
||||
/// <param name="CreatedAt">The sign-in time.</param>
|
||||
/// <param name="LastSeenAt">The last request.</param>
|
||||
/// <param name="IpAddress">The client address.</param>
|
||||
/// <param name="UserAgent">The browser.</param>
|
||||
/// <param name="CompanyCode">The company.</param>
|
||||
public sealed record SessionSummary(long Id, DateTime CreatedAt, DateTime LastSeenAt, string? IpAddress, string? UserAgent, string? CompanyCode);
|
||||
|
||||
/// <summary>
|
||||
/// Sign-in sessions (SPEC §7.3). The cookie value is <c><scope>.<token></c>: the scope says which database
|
||||
/// holds the row (<c>_</c> 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.
|
||||
/// </summary>
|
||||
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;
|
||||
|
||||
/// <summary>Creates the store.</summary>
|
||||
/// <param name="factory">Opens the databases.</param>
|
||||
/// <param name="companies">The company registry.</param>
|
||||
/// <param name="cache">The cache of resolved sessions.</param>
|
||||
/// <param name="policy">Session lifetimes.</param>
|
||||
/// <param name="clock">The clock.</param>
|
||||
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);
|
||||
|
||||
/// <summary>Creates a session.</summary>
|
||||
/// <param name="owner">The owner.</param>
|
||||
/// <param name="state">The sign-in state.</param>
|
||||
/// <param name="companyCode">The company the session works in.</param>
|
||||
/// <param name="ipAddress">The client address.</param>
|
||||
/// <param name="userAgent">The browser.</param>
|
||||
/// <param name="persistent">"Remember me on this device".</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The cookie value.</returns>
|
||||
public async Task<string> 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<SystemSession, long>().InsertAsync(system, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
else
|
||||
{
|
||||
await unitOfWork.Repository<UserSession, long>().InsertAsync((UserSession)session, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
return (owner.CompanyDatabase ?? SystemScope) + "." + token;
|
||||
}
|
||||
|
||||
/// <summary>Finds the valid session of a cookie (not revoked, not expired) and slides its expiry.</summary>
|
||||
/// <param name="cookie">The cookie value.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The session row and owner, or <see langword="null"/>.</returns>
|
||||
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<SystemSession, long>().FindAsync(Query.For<SystemSession>().Where(s => s.TokenHash == hash), cancellationToken).ConfigureAwait(false)
|
||||
: (SessionRecord?)await unitOfWork.Repository<UserSession, long>().FindAsync(Query.For<UserSession>().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 });
|
||||
}
|
||||
|
||||
/// <summary>Moves a session to another sign-in state and gives it a new token (the old cookie stops working).</summary>
|
||||
/// <param name="cookie">The current cookie value.</param>
|
||||
/// <param name="state">The new state.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The new cookie value, or <see langword="null"/> when the session is not valid.</returns>
|
||||
public async Task<string?> 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;
|
||||
}
|
||||
|
||||
/// <summary>Changes the company a session of an instance account works in.</summary>
|
||||
/// <param name="cookie">The cookie value.</param>
|
||||
/// <param name="companyCode">The company, or <see langword="null"/>.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>A task.</returns>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>Revokes the session of a cookie (sign-out).</summary>
|
||||
/// <param name="cookie">The cookie value.</param>
|
||||
/// <param name="reason">Why.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The owner of the revoked session, or <see langword="null"/>.</returns>
|
||||
public async Task<SessionOwner?> 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;
|
||||
}
|
||||
|
||||
/// <summary>Revokes one session of an owner (from the list of sessions).</summary>
|
||||
/// <param name="owner">The owner.</param>
|
||||
/// <param name="sessionId">The session row.</param>
|
||||
/// <param name="reason">Why.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>Whether a session was revoked.</returns>
|
||||
public async Task<bool> 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;
|
||||
}
|
||||
|
||||
/// <summary>Revokes every session of an owner, except one (password change, administrator action).</summary>
|
||||
/// <param name="owner">The owner.</param>
|
||||
/// <param name="reason">Why.</param>
|
||||
/// <param name="exceptSessionId">The session to keep.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The number of sessions revoked.</returns>
|
||||
public Task<int> 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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Revokes every session of the users of a company (maintenance, disabling): instance accounts keep theirs, also when
|
||||
/// they work in that company.
|
||||
/// </summary>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="reason">Why.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The number of sessions revoked.</returns>
|
||||
public async Task<int> 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;
|
||||
}
|
||||
|
||||
/// <summary>Whether a signed-in session is still valid (the periodic check of open Blazor circuits).</summary>
|
||||
/// <param name="owner">The owner.</param>
|
||||
/// <param name="sessionId">The session row.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns><see langword="true"/> while the session is active, not revoked and not expired.</returns>
|
||||
public async Task<bool> 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<SystemSession, long>().CountAsync(
|
||||
Query.For<SystemSession>().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<UserSession, long>().CountAsync(
|
||||
Query.For<UserSession>().Where(s => s.Id == sessionId && s.UserId == userId && s.RevokedAt == null && s.ExpiresAt > now && s.State == SessionState.Active),
|
||||
cancellationToken).ConfigureAwait(false) > 0;
|
||||
}
|
||||
|
||||
/// <summary>The active sessions of an owner.</summary>
|
||||
/// <param name="owner">The owner.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The sessions, most recent first.</returns>
|
||||
public async Task<IReadOnlyList<SessionSummary>> 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<SessionRecord> sessions = owner.IsInstanceAccount
|
||||
? (await unitOfWork.Repository<SystemSession, long>().ListAsync(
|
||||
Query.For<SystemSession>().Where(s => s.UserId == userId && s.RevokedAt == null && s.ExpiresAt > now).OrderByDescending(s => s.LastSeenAt), cancellationToken)
|
||||
.ConfigureAwait(false)).Items
|
||||
: (await unitOfWork.Repository<UserSession, long>().ListAsync(
|
||||
Query.For<UserSession>().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))];
|
||||
}
|
||||
|
||||
/// <summary>Whether an owner has signed in before from the same browser (to warn about new devices).</summary>
|
||||
/// <param name="owner">The owner.</param>
|
||||
/// <param name="userAgent">The browser.</param>
|
||||
/// <param name="exceptSessionId">The session just created.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns><see langword="true"/> if a previous session used the same browser.</returns>
|
||||
public async Task<bool> 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<SystemSession, long>().CountAsync(
|
||||
Query.For<SystemSession>().Where(s => s.UserId == userId && s.UserAgent == agent && s.Id != exceptSessionId && s.State == SessionState.Active), cancellationToken)
|
||||
.ConfigureAwait(false) > 0
|
||||
: await unitOfWork.Repository<UserSession, long>().CountAsync(
|
||||
Query.For<UserSession>().Where(s => s.UserId == userId && s.UserAgent == agent && s.Id != exceptSessionId && s.State == SessionState.Active), cancellationToken)
|
||||
.ConfigureAwait(false) > 0;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The users with an active session across the system database and every company (the concurrent-user limit of the
|
||||
/// licence, SPEC §7.3).
|
||||
/// </summary>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The owners with at least one active session.</returns>
|
||||
public async Task<IReadOnlySet<SessionOwner>> ActiveOwnersAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
var now = Now;
|
||||
var owners = new HashSet<SessionOwner>();
|
||||
await using (var system = await _factory.CreateAsync(DatabaseScope.System, cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
var rows = await system.QueryAsync<long>(
|
||||
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<long>(
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>Deletes sessions expired or revoked more than <paramref name="age"/> ago (the cleanup job).</summary>
|
||||
/// <param name="scope">The database.</param>
|
||||
/// <param name="age">How long to keep them for the history.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The rows deleted.</returns>
|
||||
public async Task<int> 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);
|
||||
}
|
||||
|
||||
/// <summary>The cache key of a cookie's resolved identity.</summary>
|
||||
/// <param name="cookie">The cookie value.</param>
|
||||
/// <returns>The key.</returns>
|
||||
public static string CacheKey(string cookie) => CacheKeys.For(null, CacheArea, SecureTokenGenerator.Hash(cookie ?? string.Empty));
|
||||
|
||||
/// <summary>Forgets the cached identity of a cookie.</summary>
|
||||
/// <param name="cookie">The cookie value.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>A task.</returns>
|
||||
public ValueTask ForgetAsync(string cookie, CancellationToken cancellationToken = default) => _cache.RemoveAsync(CacheKey(cookie), cancellationToken);
|
||||
|
||||
/// <summary>How long a resolved identity may stay cached (revocations by id also clear the whole area).</summary>
|
||||
public static TimeSpan IdentityCacheTime => CacheTime;
|
||||
|
||||
private async Task<int> RevokeWhereAsync(SessionOwner owner, System.Linq.Expressions.Expression<Func<SessionRecord, bool>> 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<SessionRecord> sessions = owner.IsInstanceAccount
|
||||
? (await unitOfWork.Repository<SystemSession, long>().ListAsync(Query.For<SystemSession>().Where(s => s.UserId == userId && s.RevokedAt == null), cancellationToken).ConfigureAwait(false)).Items
|
||||
: (await unitOfWork.Repository<UserSession, long>().ListAsync(Query.For<UserSession>().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<SystemSession, long>().UpdateAsync(system, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
else
|
||||
{
|
||||
await unitOfWork.Repository<UserSession, long>().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<IUnitOfWork> 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];
|
||||
}
|
||||
Reference in new issue
Block a user