do sessions in memory and also fix glaring security hole

This commit is contained in:
john 2025-06-01 23:28:00 +02:00
parent 7b6c155a73
commit f48b421500
31 changed files with 441 additions and 440 deletions

View file

@ -3,6 +3,7 @@ using Femto.Common.Infrastructure;
using Femto.Common.Infrastructure.DbConnection;
using Femto.Common.Infrastructure.Outbox;
using Femto.Common.Integration;
using Femto.Modules.Auth.Application.Services;
using Femto.Modules.Auth.Data;
using Femto.Modules.Auth.Infrastructure;
using MediatR;
@ -24,16 +25,25 @@ public static class AuthStartup
)
{
var hostBuilder = Host.CreateDefaultBuilder();
hostBuilder.ConfigureServices(services =>
ConfigureServices(services, connectionString, eventBus, loggerFactory)
);
var host = hostBuilder.Build();
rootContainer.AddScoped(_ => new ScopeBinding<IAuthModule>(host.Services.CreateScope()));
rootContainer.AddScoped(services =>
services.GetRequiredService<ScopeBinding<IAuthModule>>().GetService()
rootContainer.AddKeyedScoped<ScopeBinding>(
"AuthServiceScope",
(s, o) =>
{
var scope = host.Services.CreateScope();
return new ScopeBinding(scope);
}
);
rootContainer.ExposeScopedService<IAuthModule>();
rootContainer.ExposeScopedService<IAuthService>();
rootContainer.AddHostedService(services => new AuthApplication(host));
eventBus.Subscribe(
(evt, cancellationToken) => EventSubscriber(evt, host.Services, cancellationToken)
@ -66,7 +76,7 @@ public static class AuthStartup
{
options.WaitForJobsToComplete = true;
});
// #endif
services.AddOutbox<AuthContext, OutboxMessageHandler>();
services.AddMediatR(c => c.RegisterServicesFromAssembly(typeof(AuthStartup).Assembly));
@ -74,8 +84,10 @@ public static class AuthStartup
services.ConfigureDomainServices<AuthContext>();
services.AddSingleton(publisher);
services.AddSingleton<SessionStorage>();
services.AddScoped<IAuthModule, AuthModule>();
services.AddScoped<IAuthService, AuthService>();
}
private static async Task EventSubscriber(
@ -107,3 +119,14 @@ public static class AuthStartup
}
}
}
internal static class AuthServiceCollectionExtensions
{
public static void ExposeScopedService<T>(this IServiceCollection container)
where T : class
{
container.AddScoped<T>(services =>
services.GetRequiredKeyedService<ScopeBinding>("AuthServiceScope").GetService<T>()
);
}
}

View file

@ -0,0 +1,6 @@
using Femto.Common.Domain;
using Femto.Modules.Auth.Application.Dto;
namespace Femto.Modules.Auth.Application.Interface.GetUserInfo;
public record GetUserInfoCommand(Guid ForUser) : ICommand<UserInfo?>;

View file

@ -0,0 +1,27 @@
using Femto.Common.Domain;
using Femto.Modules.Auth.Application.Dto;
using Femto.Modules.Auth.Data;
using Microsoft.EntityFrameworkCore;
namespace Femto.Modules.Auth.Application.Interface.GetUserInfo;
internal class GetUserInfoCommandHandler(AuthContext context)
: ICommandHandler<GetUserInfoCommand, UserInfo?>
{
public async Task<UserInfo?> Handle(
GetUserInfoCommand request,
CancellationToken cancellationToken
)
{
var user = await context.Users.SingleOrDefaultAsync(
u => u.Id == request.ForUser,
cancellationToken
);
if (user is null)
return null;
return new UserInfo(user);
}
}

View file

@ -1,6 +0,0 @@
using Femto.Common.Domain;
using Femto.Modules.Auth.Application.Dto;
namespace Femto.Modules.Auth.Application.Interface.Login;
public record LoginCommand(string Username, string Password) : ICommand<LoginResult>;

View file

@ -1,31 +0,0 @@
using Femto.Common.Domain;
using Femto.Modules.Auth.Application.Dto;
using Femto.Modules.Auth.Data;
using Femto.Modules.Auth.Models;
using Microsoft.EntityFrameworkCore;
namespace Femto.Modules.Auth.Application.Interface.Login;
internal class LoginCommandHandler(AuthContext context)
: ICommandHandler<LoginCommand, LoginResult>
{
public async Task<LoginResult> Handle(LoginCommand request, CancellationToken cancellationToken)
{
var user = await context.Users.SingleOrDefaultAsync(
u => u.Username == request.Username,
cancellationToken
);
if (user is null)
throw new DomainError("invalid credentials");
if (!user.HasPassword(request.Password))
throw new DomainError("invalid credentials");
var session = Session.Strong(user.Id);
await context.AddAsync(session, cancellationToken);
return new(new SessionDto(session), new UserInfo(user));
}
}

View file

@ -1,7 +0,0 @@
using Femto.Common;
using Femto.Common.Domain;
using Femto.Modules.Auth.Application.Dto;
namespace Femto.Modules.Auth.Application.Interface.RefreshUserSession;
public record RefreshUserCommand(Guid ForUser, CurrentUser CurrentUser) : ICommand<RefreshUserSessionResult>;

View file

@ -1,46 +0,0 @@
using Femto.Common.Domain;
using Femto.Common.Infrastructure.DbConnection;
using Femto.Modules.Auth.Application.Dto;
using Femto.Modules.Auth.Data;
using Femto.Modules.Auth.Errors;
using Femto.Modules.Auth.Models;
using Microsoft.EntityFrameworkCore;
namespace Femto.Modules.Auth.Application.Interface.RefreshUserSession;
internal class RefreshUserSessionCommandHandler(AuthContext context)
: ICommandHandler<RefreshUserCommand, RefreshUserSessionResult>
{
public async Task<RefreshUserSessionResult> Handle(
RefreshUserCommand request,
CancellationToken cancellationToken
)
{
if (request.CurrentUser.Id != request.ForUser)
throw new DomainError("invalid request");
var user = await context.Users.SingleOrDefaultAsync(
u => u.Id == request.ForUser,
cancellationToken
);
if (user is null)
throw new DomainError("invalid request");
var session = await context.Sessions.SingleOrDefaultAsync(
s => s.Id == request.CurrentUser.SessionId && s.Expires > DateTimeOffset.UtcNow,
cancellationToken
);
if (session is null)
throw new InvalidSessionError();
if (session.ShouldRefresh)
{
session = Session.Weak(user.Id);
await context.AddAsync(session, cancellationToken);
}
return new(new SessionDto(session), new UserInfo(user));
}
}

View file

@ -3,4 +3,4 @@ using Femto.Modules.Auth.Application.Dto;
namespace Femto.Modules.Auth.Application.Interface.Register;
public record RegisterCommand(string Username, string Password, string SignupCode) : ICommand<RegisterResult>;
public record RegisterCommand(string Username, string Password, string SignupCode) : ICommand<UserInfo>;

View file

@ -7,16 +7,12 @@ using Microsoft.EntityFrameworkCore;
namespace Femto.Modules.Auth.Application.Interface.Register;
internal class RegisterCommandHandler(AuthContext context)
: ICommandHandler<RegisterCommand, RegisterResult>
: ICommandHandler<RegisterCommand, UserInfo>
{
public async Task<RegisterResult> Handle(
RegisterCommand request,
CancellationToken cancellationToken
)
public async Task<UserInfo> Handle(RegisterCommand request, CancellationToken cancellationToken)
{
var now = DateTimeOffset.UtcNow;
var code = await context
.SignupCodes.Where(c => c.Code == request.SignupCode)
.Where(c => c.ExpiresAt == null || c.ExpiresAt > now)
@ -26,18 +22,22 @@ internal class RegisterCommandHandler(AuthContext context)
if (code is null)
throw new DomainError("invalid signup code");
var usernameTaken = await context.Users.AnyAsync(
u => u.Username == request.Username,
cancellationToken
);
if (usernameTaken)
throw new DomainError("username taken");
var user = new UserIdentity(request.Username);
await context.AddAsync(user, cancellationToken);
user.SetPassword(request.Password);
var session = Session.Strong(user.Id);
await context.AddAsync(session, cancellationToken);
code.Redeem(user.Id);
return new(new SessionDto(session), new UserInfo(user));
return new UserInfo(user);
}
}

View file

@ -1,10 +0,0 @@
using Femto.Common.Domain;
using Femto.Modules.Auth.Application.Dto;
namespace Femto.Modules.Auth.Application.Interface.ValidateSession;
/// <summary>
/// Validate an existing session, and then return either the current session, or a new one in case the expiry is further in the future
/// </summary>
/// <param name="SessionId"></param>
public record ValidateSessionCommand(string SessionId, UserInfo User, string? RememberMe) : ICommand<ValidateSessionResult>;

View file

@ -1,111 +0,0 @@
using Femto.Common.Domain;
using Femto.Common.Infrastructure.DbConnection;
using Femto.Modules.Auth.Application.Dto;
using Femto.Modules.Auth.Data;
using Femto.Modules.Auth.Errors;
using Femto.Modules.Auth.Models;
using Microsoft.EntityFrameworkCore;
namespace Femto.Modules.Auth.Application.Interface.ValidateSession;
internal class ValidateSessionCommandHandler(AuthContext context)
: ICommandHandler<ValidateSessionCommand, ValidateSessionResult>
{
public async Task<ValidateSessionResult> Handle(
ValidateSessionCommand request,
CancellationToken cancellationToken
)
{
try
{
return new ValidateSessionResult(await DoSessionValidation(request, cancellationToken));
}
finally
{
await context.SaveChangesAsync(cancellationToken);
}
}
private async Task<SessionDto> DoSessionValidation(
ValidateSessionCommand request,
CancellationToken cancellationToken
)
{
var now = DateTimeOffset.UtcNow;
var session = await context.Sessions.SingleOrDefaultAsync(
s => s.Id == request.SessionId,
cancellationToken
);
var rememberMe = request.RememberMe;
if (session is null)
{
(session, rememberMe) = await this.TryAuthenticateWithRememberMeToken(
request.User,
request.RememberMe,
cancellationToken
);
}
if (session.UserId != request.User.Id)
{
context.Remove(session);
throw new InvalidSessionError();
}
if (session.Expires < now)
{
context.Remove(session);
throw new InvalidSessionError();
}
if (session.ShouldRefresh)
{
context.Remove(session);
session = Session.Weak(session.UserId);
await context.AddAsync(session, cancellationToken);
}
return new SessionDto(session, rememberMe);
}
private async Task<(Session, string)> TryAuthenticateWithRememberMeToken(
UserInfo user,
string? rememberMeToken,
CancellationToken cancellationToken
)
{
if (rememberMeToken is null)
throw new InvalidSessionError();
var parts = rememberMeToken.Split('.');
if (parts.Length != 2)
throw new InvalidSessionError();
var selector = parts[0];
var verifier = parts[1];
var longTermSession = await context.LongTermSessions.SingleOrDefaultAsync(
s => s.Selector == selector,
cancellationToken
);
if (longTermSession is null)
throw new InvalidSessionError();
context.Remove(longTermSession);
if (!longTermSession.Validate(verifier))
throw new InvalidSessionError();
var session = Session.Weak(user.Id);
await context.AddAsync(session, cancellationToken);
(longTermSession, rememberMeToken) = LongTermSession.Create(user.Id);
await context.AddAsync(longTermSession, cancellationToken);
return (session, rememberMeToken);
}
}

View file

@ -1,9 +1,7 @@
using Femto.Common.Domain;
using MediatR;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace Femto.Modules.Auth.Application;
namespace Femto.Modules.Auth.Application.Services;
internal class AuthModule(IMediator mediator) : IAuthModule
{

View file

@ -0,0 +1,79 @@
using Femto.Common.Domain;
using Femto.Modules.Auth.Application.Dto;
using Femto.Modules.Auth.Data;
using Femto.Modules.Auth.Infrastructure;
using Femto.Modules.Auth.Models;
using Microsoft.EntityFrameworkCore;
namespace Femto.Modules.Auth.Application.Services;
internal class AuthService(AuthContext context, SessionStorage storage) : IAuthService
{
public async Task<UserInfo?> GetUserWithCredentials(
string username,
string password,
CancellationToken cancellationToken = default
)
{
return await context
.Users.Where(u => u.Username == username)
.Select(u => new UserInfo(u.Id, u.Username, u.Roles.Select(r => r.Role).ToList()))
.SingleOrDefaultAsync(cancellationToken);
}
public Task<UserInfo?> GetUserWithId(Guid? userId, CancellationToken cancellationToken)
{
return context
.Users.Where(u => u.Id == userId)
.Select(u => new UserInfo(u.Id, u.Username, u.Roles.Select(r => r.Role).ToList()))
.SingleOrDefaultAsync(cancellationToken);
}
public async Task<Session> CreateStrongSession(Guid userId)
{
var session = new Session(userId, true);
await storage.AddSession(session);
return session;
}
public async Task<Session> CreateWeakSession(Guid userId)
{
var session = new Session(userId, false);
await storage.AddSession(session);
return session;
}
public Task<Session?> GetSession(string sessionId)
{
return storage.GetSession(sessionId);
}
public async Task DeleteSession(string sessionId)
{
await storage.DeleteSession(sessionId);
}
public async Task<LongTermSession> CreateLongTermSession(Guid userId, bool isStrong)
{
throw new NotImplementedException();
}
public async Task<LongTermSession> DeleteLongTermSession(string sessionId)
{
throw new NotImplementedException();
}
public async Task<LongTermSession> RefreshLongTermSession(string sessionId)
{
throw new NotImplementedException();
}
public async Task<ValidateSessionResult> ValidateLongTermSession(string sessionId)
{
throw new NotImplementedException();
}
}

View file

@ -1,6 +1,6 @@
using Femto.Common.Domain;
namespace Femto.Modules.Auth.Application;
namespace Femto.Modules.Auth.Application.Services;
public interface IAuthModule
{

View file

@ -0,0 +1,14 @@
using Femto.Modules.Auth.Application.Dto;
using Femto.Modules.Auth.Models;
namespace Femto.Modules.Auth.Application.Services;
public interface IAuthService
{
public Task<UserInfo?> GetUserWithCredentials(string username, string password, CancellationToken cancellationToken = default);
public Task<UserInfo?> GetUserWithId(Guid? userId, CancellationToken cancellationToken = default);
public Task<Session> CreateStrongSession(Guid userId);
public Task<Session> CreateWeakSession(Guid userId);
public Task<Session?> GetSession(string sessionId);
public Task DeleteSession(string sessionId);
}

View file

@ -7,7 +7,6 @@ namespace Femto.Modules.Auth.Data;
internal class AuthContext(DbContextOptions<AuthContext> options) : DbContext(options), IOutboxContext
{
public virtual DbSet<UserIdentity> Users { get; set; }
public virtual DbSet<Session> Sessions { get; set; }
public virtual DbSet<SignupCode> SignupCodes { get; set; }
public virtual DbSet<LongTermSession> LongTermSessions { get; set; }
public virtual DbSet<OutboxEntry> Outbox { get; set; }

View file

@ -19,8 +19,6 @@ internal class UserIdentityTypeConfiguration : IEntityTypeConfiguration<UserIden
}
);
builder.OwnsMany(u => u.Sessions).WithOwner().HasForeignKey("user_id");
builder
.OwnsMany(u => u.Roles, entity =>
{

View file

@ -0,0 +1,30 @@
using Femto.Modules.Auth.Models;
using Microsoft.Extensions.Caching.Memory;
namespace Femto.Modules.Auth.Infrastructure;
internal class SessionStorage(MemoryCacheOptions? options = null)
{
private readonly IMemoryCache _storage = new MemoryCache(options ?? new MemoryCacheOptions());
public Task<Session?> GetSession(string id)
{
return Task.FromResult(this._storage.Get<Session>(id));
}
public Task AddSession(Session session)
{
using var entry = this._storage.CreateEntry(session.Id);
entry.Value = session;
entry.SetAbsoluteExpiration(session.Expires);
return Task.CompletedTask;
}
public Task DeleteSession(string id)
{
this._storage.Remove(id);
return Task.CompletedTask;
}
}

View file

@ -0,0 +1,14 @@
using static System.Security.Cryptography.RandomNumberGenerator;
namespace Femto.Modules.Auth.Models;
public class Session(Guid userId, bool isStrong)
{
public string Id { get; } = Convert.ToBase64String(GetBytes(32));
public Guid UserId { get; } = userId;
public DateTimeOffset Expires { get; } = DateTimeOffset.UtcNow + TimeSpan.FromMinutes(15);
public bool ExpiresSoon => this.Expires < DateTimeOffset.UtcNow + TimeSpan.FromMinutes(5);
public bool IsStronglyAuthenticated { get; } = isStrong;
public bool IsExpired => this.Expires < DateTimeOffset.UtcNow;
}

View file

@ -1,9 +1,6 @@
using System.Text;
using System.Text.Unicode;
using Femto.Common.Domain;
using Femto.Modules.Auth.Contracts;
using Femto.Modules.Auth.Models.Events;
using Geralt;
namespace Femto.Modules.Auth.Models;
@ -15,8 +12,6 @@ internal class UserIdentity : Entity
public Password? Password { get; private set; }
public ICollection<Session> Sessions { get; private set; } = [];
public ICollection<UserRole> Roles { get; private set; } = [];
private UserIdentity() { }

View file

@ -1,33 +0,0 @@
using static System.Security.Cryptography.RandomNumberGenerator;
namespace Femto.Modules.Auth.Models;
internal class Session
{
private static TimeSpan SessionTimeout { get; } = TimeSpan.FromMinutes(30);
private static TimeSpan ExpiryBuffer { get; } = TimeSpan.FromMinutes(5);
public string Id { get; private set; }
public Guid UserId { get; private set; }
public DateTimeOffset Expires { get; private set; }
public bool ExpiresSoon => Expires < DateTimeOffset.UtcNow + ExpiryBuffer;
// true if this session was created with remember me token
// otherwise false
// required to be true to do things like change password etc.
public bool IsStronglyAuthenticated { get; private set; }
public bool ShouldRefresh => this.Expires < DateTimeOffset.UtcNow + ExpiryBuffer;
private Session() { }
public static Session Strong(Guid userId) => new(userId, true);
public static Session Weak(Guid userId) => new(userId, false);
private Session(Guid userId, bool isStrong)
{
this.Id = Convert.ToBase64String(GetBytes(32));
this.UserId = userId;
this.Expires = DateTimeOffset.UtcNow + SessionTimeout;
this.IsStronglyAuthenticated = isStrong;
}
}