Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/Exceptionless.Core/Bootstrapper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -182,6 +182,7 @@ public static void RegisterServices(IServiceCollection services, AppOptions appO
services.AddSingleton<ILockProvider>(s => s.GetRequiredService<CacheLockProvider>());
services.AddTransient<StripeEventHandler>();
services.AddSingleton<IStripeBillingClient, StripeBillingClient>();
services.AddSingleton<AuthService>();
services.AddSingleton<BillingManager>();
services.AddSingleton<BillingPlans>();
services.AddSingleton<EventPostService>();
Expand Down
196 changes: 196 additions & 0 deletions src/Exceptionless.Core/Services/AuthService.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,196 @@
using Exceptionless.DateTimeExtensions;
using Foundatio.Caching;
using Microsoft.Extensions.Logging;

namespace Exceptionless.Core.Services;

/// <summary>
/// Coordinates password checks and temporary failures across authentication callers.
/// </summary>
public sealed class AuthService
{
private const int UserFailureLimit = 5;
private const int IpAddressFailureLimit = 15;
private static readonly TimeSpan AttemptWindow = TimeSpan.FromMinutes(15);
private readonly ScopedCacheClient _cache;
private readonly ILogger<AuthService> _logger;
private readonly TimeProvider _timeProvider;

public AuthService(ICacheClient cacheClient, TimeProvider timeProvider, ILogger<AuthService> logger)
{
ArgumentNullException.ThrowIfNull(cacheClient);
ArgumentNullException.ThrowIfNull(timeProvider);
ArgumentNullException.ThrowIfNull(logger);

_cache = new ScopedCacheClient(cacheClient, "Auth");
_timeProvider = timeProvider;
_logger = logger;
}

public async Task<LoginAttempt?> TryBeginLoginAsync(string emailAddress, string? ipAddress, CancellationToken cancellationToken = default)
{
ArgumentException.ThrowIfNullOrWhiteSpace(emailAddress);

if (ipAddress is not null)
ArgumentException.ThrowIfNullOrWhiteSpace(ipAddress);

cancellationToken.ThrowIfCancellationRequested();

var expiresUtc = GetWindowExpiration();
string[] userCacheKeys = GetUserCacheKeys(emailAddress, expiresUtc);
var failures = await _cache.GetAllAsync<string>(userCacheKeys);
var observedFailures = failures.Where(pair => pair.Value.HasValue && pair.Value.Value.StartsWith("failed:", StringComparison.Ordinal))
.Select(pair => new KeyValuePair<string, string>(pair.Key, pair.Value.Value)).ToArray();
string reservation = $"pending:{Guid.NewGuid():N}";
var reservedCacheKeys = new List<string>(2);
try
{
string? userCacheKey = await ReserveCacheKeyAsync(userCacheKeys, reservation, expiresUtc);
if (userCacheKey is null)
return null;

reservedCacheKeys.Add(userCacheKey);

if (ipAddress is not null)
{
string? ipAddressCacheKey = await ReserveCacheKeyAsync(GetIpAddressCacheKeys(ipAddress, expiresUtc), reservation, expiresUtc);
if (ipAddressCacheKey is null)
{
await ReleaseCacheKeysAsync(reservedCacheKeys, reservation);
return null;
}

reservedCacheKeys.Add(ipAddressCacheKey);
}

cancellationToken.ThrowIfCancellationRequested();

string[] cacheKeys = reservedCacheKeys.ToArray();

return new LoginAttempt(expiresUtc, cacheKeys, reservation, observedFailures, () => ReleaseCacheKeysAsync(cacheKeys, reservation));
}
catch
{
await ReleaseCacheKeysAsync(reservedCacheKeys, reservation);

throw;
}
}

public async Task RecordLoginFailureAsync(LoginAttempt attempt)
{
ArgumentNullException.ThrowIfNull(attempt);

var remaining = attempt.ExpiresUtc - _timeProvider.GetUtcNow().UtcDateTime;
if (remaining <= TimeSpan.Zero)
return;

// Pending checks and completed failures share the fixed-window admission budget.
// Reservations expire at the boundary even if a check is still running.
await Task.WhenAll(attempt.CacheKeys.Select(cacheKey => _cache.ReplaceIfEqualAsync(cacheKey, $"failed:{attempt.Reservation}", attempt.Reservation, remaining)));
}

public async Task RecordLoginSuccessAsync(LoginAttempt attempt)
{
ArgumentNullException.ThrowIfNull(attempt);

await ReleaseCacheKeysAsync(attempt.CacheKeys, attempt.Reservation);
await RemoveFailuresAsync(attempt.ObservedFailures);
}

public async Task ClearUserLoginAttemptsAsync(string emailAddress)
{
ArgumentException.ThrowIfNullOrWhiteSpace(emailAddress);

var failures = await _cache.GetAllAsync<string>(GetUserCacheKeys(emailAddress, GetWindowExpiration()));
// Recovery clears completed failures while checks underway retain admission.
await RemoveFailuresAsync(failures.Where(pair => pair.Value.HasValue && pair.Value.Value.StartsWith("failed:", StringComparison.Ordinal))
.Select(pair => new KeyValuePair<string, string>(pair.Key, pair.Value.Value)));
}

/// <summary>
/// Atomically reserves the first available cache entry until the captured window expires.
/// </summary>
/// <param name="cacheKeys">The entries belonging to one user's or IP address's admission budget.</param>
/// <param name="reservation">The unique value used to conditionally release or charge the entry.</param>
/// <param name="expiresUtc">The expiration captured before reserving either admission budget.</param>
/// <returns>The reserved cache key, or <see langword="null"/> when the admission budget is exhausted.</returns>
private async Task<string?> ReserveCacheKeyAsync(string[] cacheKeys, string reservation, DateTime expiresUtc)
{
foreach (string cacheKey in cacheKeys)
if (await _cache.AddAsync(cacheKey, reservation, expiresUtc))
return cacheKey;

return null;
}

/// <summary>
/// Releases every entry still owned by the reservation. Cleanup failures are logged and remain
/// charged until expiration, so disposal cannot replace an in-flight error or cancellation.
/// </summary>
private async Task ReleaseCacheKeysAsync(IEnumerable<string> cacheKeys, string reservation)
{
foreach (string cacheKey in cacheKeys)
{
try
{
await _cache.RemoveIfEqualAsync(cacheKey, reservation);
}
catch (Exception ex)
{
_logger.LogError(ex, "Error releasing login admission reservation: {Message}", ex.Message);
}
}
}

private Task RemoveFailuresAsync(IEnumerable<KeyValuePair<string, string>> failures)
=> Task.WhenAll(failures.Select(failure => _cache.RemoveIfEqualAsync(failure.Key, failure.Value)));

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Require atomic compare-and-delete for admission slots

When concurrent successful logins observed the same prior failure, both call this removal; if a third login reserves that slot between the provider's comparison and deletion, the stale remover can delete the third login's reservation. The checked-in Foundatio 13.0.4 stack still has unresolved conditional-operation concurrency (upstream #570), while the new tests exercise only InMemoryCacheClient, so the five-user/fifteen-IP bounds are not established for the deployed provider. Use a provider-level atomic compare-and-delete primitive (or an equivalent lock) before relying on these entries for login admission.

Useful? React with 👍 / 👎.


private DateTime GetWindowExpiration() => _timeProvider.GetUtcNow().UtcDateTime.Floor(AttemptWindow).Add(AttemptWindow);

/// <summary>
/// Gets the user admission cache keys for the captured window, normalizing email casing and whitespace.
/// </summary>
/// <param name="emailAddress">The email identity shared by interactive and Basic password authentication.</param>
/// <param name="expiresUtc">The captured window expiration, also used by the IP admission budget.</param>
/// <returns>The five cache entries sharing the user's fixed-window admission budget.</returns>
private static string[] GetUserCacheKeys(string emailAddress, DateTime expiresUtc)
{
string normalizedEmailAddress = emailAddress.Trim().ToLowerInvariant();

return Enumerable.Range(0, UserFailureLimit).Select(index => $"user:{normalizedEmailAddress}:attempts:{expiresUtc.Ticks}:{index}").ToArray();
}

/// <summary>
/// Gets the IP admission cache keys for the same captured window as the user reservation.
/// </summary>
/// <param name="ipAddress">The client IP address supplied by the authentication caller.</param>
/// <param name="expiresUtc">The same captured expiration used by the user admission budget.</param>
/// <returns>The fifteen cache entries sharing the IP address's fixed-window admission budget.</returns>
private static string[] GetIpAddressCacheKeys(string ipAddress, DateTime expiresUtc)
=> Enumerable.Range(0, IpAddressFailureLimit).Select(index => $"ip:{ipAddress}:attempts:{expiresUtc.Ticks}:{index}").ToArray();

/// <summary>
/// Owns one login admission reservation and releases unfinished entries when disposed.
/// </summary>
public sealed class LoginAttempt : IAsyncDisposable
{
private readonly Func<Task> _releaseAsync;

internal LoginAttempt(DateTime expiresUtc, string[] cacheKeys, string reservation, KeyValuePair<string, string>[] observedFailures, Func<Task> releaseAsync)
{
_releaseAsync = releaseAsync;
ExpiresUtc = expiresUtc;
CacheKeys = cacheKeys;
Reservation = reservation;
ObservedFailures = observedFailures;
}

internal DateTime ExpiresUtc { get; }
internal string[] CacheKeys { get; }
internal string Reservation { get; }
internal KeyValuePair<string, string>[] ObservedFailures { get; }

public ValueTask DisposeAsync() => new(_releaseAsync());
}
}
44 changes: 14 additions & 30 deletions src/Exceptionless.Web/Api/Handlers/AuthHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
using Exceptionless.Core.Mail;
using Exceptionless.Core.Models;
using Exceptionless.Core.Repositories;
using Exceptionless.Core.Services;
using Exceptionless.DateTimeExtensions;
using Exceptionless.Web.Api.Messages;
using Exceptionless.Web.Extensions;
Expand All @@ -30,6 +31,7 @@ public class AuthHandler(
IOAuthTokenRepository oauthTokenRepository,
IOAuthProviderClient oauthProviderClient,
ICacheClient cacheClient,
AuthService authService,
IMailer mailer,
IDomainLoginProvider domainLoginProvider,
TimeProvider timeProvider,
Expand All @@ -46,21 +48,11 @@ public async Task<Result<TokenResult>> Handle(LoginMessage message)
string email = model.Email.Trim().ToLowerInvariant();
using var _ = logger.BeginScope(new ExceptionlessState().Tag("Login").Identity(email).SetHttpContext(httpContext));

string userLoginAttemptsCacheKey = $"user:{email}:attempts";
long userLoginAttempts = await _cache.IncrementAsync(userLoginAttemptsCacheKey, 1, timeProvider.GetUtcNow().UtcDateTime.Ceiling(TimeSpan.FromMinutes(15)));

string ipLoginAttemptsCacheKey = $"ip:{httpContext.Request.GetClientIpAddress()}:attempts";
long ipLoginAttempts = await _cache.IncrementAsync(ipLoginAttemptsCacheKey, 1, timeProvider.GetUtcNow().UtcDateTime.Ceiling(TimeSpan.FromMinutes(15)));

if (userLoginAttempts > 5)
{
logger.LogError("Login denied for {EmailAddress} for the {UserLoginAttempts} time", email, userLoginAttempts);
return Result.Unauthorized("Login denied.");
}

if (ipLoginAttempts > 15)
string? ipAddress = httpContext.Request.GetClientIpAddress();
await using var loginAttempt = await authService.TryBeginLoginAsync(email, ipAddress, httpContext.RequestAborted);
if (loginAttempt is null)
{
logger.LogError("Login denied for {EmailAddress} for the {IPLoginAttempts} time", httpContext.Request.GetClientIpAddress(), ipLoginAttempts);
logger.LogError("Login denied for {EmailAddress}", email);
return Result.Unauthorized("Login denied.");
}

Expand All @@ -77,12 +69,14 @@ public async Task<Result<TokenResult>> Handle(LoginMessage message)

if (user is null)
{
await authService.RecordLoginFailureAsync(loginAttempt);
logger.LogError("Login failed for {EmailAddress}: User not found", email);
return Result.Unauthorized("Login failed.");
}

if (!user.IsActive)
{
await authService.RecordLoginFailureAsync(loginAttempt);
logger.LogError("Login failed for {EmailAddress}: The user is inactive", user.EmailAddress);
return Result.Unauthorized("Login failed.");
}
Expand All @@ -91,27 +85,29 @@ public async Task<Result<TokenResult>> Handle(LoginMessage message)
{
if (String.IsNullOrEmpty(user.Salt))
{
await authService.RecordLoginFailureAsync(loginAttempt);
logger.LogError("Login failed for {EmailAddress}: The user has no salt defined", user.EmailAddress);
return Result.Unauthorized("Login failed.");
}

if (!user.IsCorrectPassword(model.Password))
{
await authService.RecordLoginFailureAsync(loginAttempt);
logger.LogError("Login failed for {EmailAddress}: Invalid Password", user.EmailAddress);
return Result.Unauthorized("Login failed.");
}
}
else if (!IsValidActiveDirectoryLogin(email, model.Password))
{
await authService.RecordLoginFailureAsync(loginAttempt);
logger.LogError("Domain login failed for {EmailAddress}: Invalid Password or Account", user.EmailAddress);
return Result.Unauthorized("Login failed.");
}

if (!String.IsNullOrEmpty(model.InviteToken))
await AddInvitedUserToOrganizationAsync(model.InviteToken, user, httpContext);

await _cache.RemoveAsync(userLoginAttemptsCacheKey);
await _cache.DecrementAsync(ipLoginAttemptsCacheKey, 1, timeProvider.GetUtcNow().UtcDateTime.Ceiling(TimeSpan.FromMinutes(15)));
await authService.RecordLoginSuccessAsync(loginAttempt);

logger.UserLoggedIn(user.EmailAddress);
return new TokenResult { Token = await GetOrCreateAuthenticationTokenAsync(user) };
Expand Down Expand Up @@ -362,13 +358,7 @@ public async Task<Result<TokenResult>> Handle(ChangePassword message)
await ChangePasswordAsync(user, model.Password!, nameof(ChangePasswordAsync), httpContext);
await ResetUserTokensAsync(user, nameof(ChangePasswordAsync), httpContext);

string userLoginAttemptsCacheKey = $"user:{user.EmailAddress}:attempts";
await _cache.RemoveAsync(userLoginAttemptsCacheKey);

string ipLoginAttemptsCacheKey = $"ip:{httpContext.Request.GetClientIpAddress()}:attempts";
long attempts = await _cache.DecrementAsync(ipLoginAttemptsCacheKey, 1, timeProvider.GetUtcNow().UtcDateTime.Ceiling(TimeSpan.FromMinutes(15)));
if (attempts <= 0)
await _cache.RemoveAsync(ipLoginAttemptsCacheKey);
await authService.ClearUserLoginAttemptsAsync(user.EmailAddress);

logger.UserChangedPassword(user.EmailAddress);
return new TokenResult { Token = await GetOrCreateAuthenticationTokenAsync(user) };
Expand Down Expand Up @@ -464,13 +454,7 @@ public async Task<Result> Handle(ResetPassword message)
await ChangePasswordAsync(user, model.Password!, "ResetPasswordAsync", httpContext);
await ResetUserTokensAsync(user, "ResetPasswordAsync", httpContext);

string userLoginAttemptsCacheKey = $"user:{user.EmailAddress}:attempts";
await _cache.RemoveAsync(userLoginAttemptsCacheKey);

string ipLoginAttemptsCacheKey = $"ip:{httpContext.Request.GetClientIpAddress()}:attempts";
long attempts = await _cache.DecrementAsync(ipLoginAttemptsCacheKey, 1, timeProvider.GetUtcNow().UtcDateTime.Ceiling(TimeSpan.FromMinutes(15)));
if (attempts <= 0)
await _cache.RemoveAsync(ipLoginAttemptsCacheKey);
await authService.ClearUserLoginAttemptsAsync(user.EmailAddress);

logger.UserResetPassword(user.EmailAddress);
return Result.Success();
Expand Down
20 changes: 13 additions & 7 deletions src/Exceptionless.Web/Extensions/HttpExtensions.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Net.Http.Headers;
using System.Security.Claims;
using System.Text;
using Exceptionless.Core.Authorization;
Expand Down Expand Up @@ -164,19 +165,24 @@ public static ICollection<string> GetAssociatedOrganizationIds(this HttpRequest
ArgumentNullException.ThrowIfNull(request);

string? authHeader = request.Headers.TryGetAndReturn("Authorization");
if (authHeader is null || !authHeader.StartsWith("basic", StringComparison.OrdinalIgnoreCase))
if (!AuthenticationHeaderValue.TryParse(authHeader, out var header)
|| !String.Equals(header.Scheme, "Basic", StringComparison.OrdinalIgnoreCase)
|| String.IsNullOrWhiteSpace(header.Parameter))
return null;

string token = authHeader.Substring(6).Trim();
string credentialString = Encoding.UTF8.GetString(Convert.FromBase64String(token));
string[] credentials = credentialString.Split(':', StringSplitOptions.RemoveEmptyEntries);
if (credentials.Length != 2)
byte[] credentialBytes = new byte[header.Parameter.Length];
if (!Convert.TryFromBase64String(header.Parameter, credentialBytes, out int bytesWritten))
return null;

string credentialString = Encoding.UTF8.GetString(credentialBytes, 0, bytesWritten);
int separator = credentialString.IndexOf(':');
if (separator <= 0 || String.IsNullOrWhiteSpace(credentialString[..separator]))
return null;

return new AuthInfo
{
Username = credentials[0],
Password = credentials[1]
Username = credentialString[..separator],
Password = credentialString[(separator + 1)..]
};
}

Expand Down
Loading
Loading