< Summary

Information
Class: Anichron.API.Services.TokenService
Assembly: Anichron.API
File(s): /home/runner/work/anichron/anichron/src/Anichron.API/Services/TokenService.cs
Tag: 19_45211875487
Line coverage
100%
Covered lines: 69
Uncovered lines: 0
Coverable lines: 69
Total lines: 123
Line coverage: 100%
Branch coverage
100%
Covered branches: 30
Total branches: 30
Branch coverage: 100%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
.ctor(...)100%11100%
get_JustRotatedWindow()100%11100%
IssueAsync()100%11100%
RefreshAsync(...)100%11100%
RefreshAsync()100%2020100%
JustRotatedInto(...)100%66100%
RevokeEverySessionAsync()100%11100%
NewSessionAsync()100%11100%
RevokeAsync()100%44100%
MarkAllSessionsRevokedAsync(...)100%11100%
GenerateRefreshToken()100%11100%
HashToken(...)100%11100%

File(s)

/home/runner/work/anichron/anichron/src/Anichron.API/Services/TokenService.cs

#LineLine coverage
 1using Anichron.API.Security;
 2using Anichron.API.Settings;
 3using Anichron.Core.Data;
 4using Anichron.Core.Data.Repository;
 5using Anichron.Core.Domain;
 6using Microsoft.Extensions.Options;
 7using System.Security.Cryptography;
 8
 9namespace Anichron.API.Services;
 10
 11public interface ITokenService
 12{
 13    Task<AuthTokens> IssueAsync(User user, CancellationToken ct);
 14    Task<ServiceResult<AuthTokens, IRefreshError>> RefreshAsync(string rawToken, CancellationToken ct);
 15    Task RevokeAsync(string rawToken, CancellationToken ct);
 16    Task MarkAllSessionsRevokedAsync(Guid userId, Instant revokedAt, CancellationToken ct);
 17}
 18
 2919public sealed class TokenService(
 2920    IRefreshTokenRepository tokens,
 2921    IUserStorageConfigRepository storageConfigs,
 2922    IUnitOfWork unitOfWork,
 2923    IClock clock,
 2924    IGuidFactory guidFactory,
 2925    IOptions<JwtSettings> options,
 2926    IJwtFactory jwtFactory) : ITokenService
 27{
 628    private static Duration JustRotatedWindow => Duration.FromSeconds(30);
 29
 2930    private readonly JwtSettings settings = options.Value;
 31
 32    public async Task<AuthTokens> IssueAsync(User user, CancellationToken ct)
 733    {
 734        var (stored, issued) = await NewSessionAsync(user, ct);
 735        tokens.Add(stored);
 736        return issued;
 737    }
 38
 39    public Task<ServiceResult<AuthTokens, IRefreshError>> RefreshAsync(string rawToken, CancellationToken ct)
 1840        => RefreshAsync(HashToken(rawToken), retryALostRotation: true, ct);
 41
 42    private async Task<ServiceResult<AuthTokens, IRefreshError>> RefreshAsync(
 43        string tokenHash, bool retryALostRotation, CancellationToken ct)
 2044    {
 2045        var now = clock.GetCurrentInstant();
 46
 2047        var stored = await tokens.FindByHashWithUserAsync(tokenHash, ct);
 48
 2049        if (stored is null)
 150            return new RefreshTokenInvalid();
 51
 1952        var rotating = stored.RevokedAt is { } revokedAt ? JustRotatedInto(stored, revokedAt, now) : stored;
 1953        if (rotating is null)
 354            return await RevokeEverySessionAsync(stored.UserId, now, ct);
 55
 1656        if (stored.ExpiresAt <= now)
 257            return new RefreshTokenInvalid();
 58
 1459        if (stored.User.IsDisabled)
 260            return new AccountDisabled();
 61
 1262        if (stored.User.LockedUntil is { } lockedUntil && lockedUntil > now)
 163            return new AccountLocked(Math.Max(1, (int)Math.Ceiling((lockedUntil - now).TotalSeconds)));
 64
 1165        var (successor, issued) = await NewSessionAsync(stored.User, ct);
 1166        if (await tokens.RotateAsync(rotating.Id, successor, ct) == TokenRotation.Rotated)
 667            return issued;
 68
 469        if (retryALostRotation && rotating == stored)
 270            return await RefreshAsync(tokenHash, retryALostRotation: false, ct);
 71
 272        return await RevokeEverySessionAsync(stored.UserId, now, ct);
 1973    }
 74
 75    private static RefreshToken? JustRotatedInto(RefreshToken stored, Instant revokedAt, Instant now)
 876        => stored.ReplacedBy is { RevokedAt: null } successor && now - revokedAt <= JustRotatedWindow ? successor : null
 77
 78    private async Task<ServiceResult<AuthTokens, IRefreshError>> RevokeEverySessionAsync(Guid userId, Instant now, Cance
 579    {
 580        await tokens.RevokeAllActiveByUserIdAsync(userId, now, ct);
 581        return new RefreshTokenInvalid();
 582    }
 83
 84    private async Task<(RefreshToken Stored, AuthTokens Issued)> NewSessionAsync(User user, CancellationToken ct)
 1885    {
 1886        var rawToken = GenerateRefreshToken();
 1887        var now = clock.GetCurrentInstant();
 88
 1889        var stored = new RefreshToken
 1890        {
 1891            Id = guidFactory.NewGuid(),
 1892            UserId = user.Id,
 1893            TokenHash = HashToken(rawToken),
 1894            CreatedAt = now,
 1895            ExpiresAt = now.Plus(Duration.FromDays(settings.RefreshTokenDays)),
 1896        };
 97
 1898        var hasStorageConfig = await storageConfigs.AnyActiveByUserIdAsync(user.Id, ct);
 1899        return (stored, new AuthTokens(jwtFactory.Create(user), rawToken, settings.AccessTokenLifetime, user, hasStorage
 18100    }
 101
 102    public async Task RevokeAsync(string rawToken, CancellationToken ct)
 3103    {
 3104        var tokenHash = HashToken(rawToken);
 3105        var stored = await tokens.FindByHashAsync(tokenHash, ct);
 3106        if (stored is null)
 1107            return;
 2108        if (stored.RevokedAt.HasValue)
 1109            return;
 110
 1111        stored.RevokedAt = clock.GetCurrentInstant();
 1112        await unitOfWork.SaveChangesAsync(ct);
 3113    }
 114
 115    public Task MarkAllSessionsRevokedAsync(Guid userId, Instant revokedAt, CancellationToken ct)
 1116        => tokens.RevokeAllActiveByUserIdAsync(userId, revokedAt, ct);
 117
 118    private static string GenerateRefreshToken()
 18119        => Convert.ToBase64String(RandomNumberGenerator.GetBytes(64));
 120
 121    private static string HashToken(string rawToken)
 39122        => Convert.ToBase64String(SHA256.HashData(Convert.FromBase64String(rawToken)));
 123}