1
0
mirror of https://github.com/bitwarden/server.git synced 2025-07-01 08:02:49 -05:00

[SG-167] Implement Passwordless Authentication via Notifications (#2276)

* [SG-549] Commit Initial AuthRequest Repository (#2174)

* Model Passwordless

* Scaffold database for Passwordless

* Implement SQL Repository

* [SG-167] Base Passwordless API (#2185)

* Implement Passwordless notifications

* Implement Controller

* Add documentation to BaseRequestValidator

* Register AuthRequestRepo

* Remove ExpirationDate from the AuthRequest table

* [SG-407] Create job to delete expired requests (#2187)

* chore: init

* remove exp date

* fix: log name

* [SG-167] Added fingerprint phrase to response model. (#2233)

* Remove FailedLoginAttempt logic

* Block unknown devices

* Add EF Support for passwordless

* Got SignalR working for responses

* Added delete job method to EF repo

* Implement a GetMany API endpoint for AuthRequests

* Ran dotnet format

* Fix a merge issues

* Redated migration scripts

* tried sorting sqlproj

* Remove FailedLoginAttempts from SQL

* Groom Postgres script

* Remove extra commas from migration script

* Correct isSpent()

* [SG-167] Adde identity validation for passwordless requests. Registered IAuthRepository.

* [SG-167] Added origin of the request to response model

* Use display name for device identifier in response

* Add datetime conversions back to postgres migration script

* [SG-655] Add anonymous endpoint for checking if a device & user combo match

* [review] Consolidate error conditions

Co-authored-by: Brandon Maharaj <107377945+BrandonM-Bitwarden@users.noreply.github.com>
Co-authored-by: André Filipe da Silva Bispo <andrefsbispo@hotmail.com>
Co-authored-by: André Bispo <abispo@bitwarden.com>
This commit is contained in:
Addison Beck
2022-09-26 13:21:13 -04:00
committed by GitHub
parent 7c3637c8ba
commit 02bea3c48d
56 changed files with 5853 additions and 61 deletions

View File

@ -0,0 +1,27 @@
using Bit.Core;
using Bit.Core.Jobs;
using Bit.Core.Repositories;
using Quartz;
namespace Bit.Admin.Jobs;
public class DeleteAuthRequestsJob : BaseJob
{
private readonly IAuthRequestRepository _authRepo;
public DeleteAuthRequestsJob(
IAuthRequestRepository authrepo,
ILogger<DeleteAuthRequestsJob> logger)
: base(logger)
{
_authRepo = authrepo;
}
protected async override Task ExecuteJobAsync(IJobExecutionContext context)
{
_logger.LogInformation(Constants.BypassFiltersEventId, "Execute job task: DeleteAuthRequestsJob: Start");
var count = await _authRepo.DeleteExpiredAsync();
_logger.LogInformation(Constants.BypassFiltersEventId, $"{count} records deleted from AuthRequests.");
_logger.LogInformation(Constants.BypassFiltersEventId, "Execute job task: DeleteAuthRequestsJob: End");
}
}

View File

@ -59,6 +59,11 @@ public class JobsHostedService : BaseJobsHostedService
.StartNow()
.WithCronSchedule("0 0 0 * * ?")
.Build();
var everyFifteenMinutesTrigger = TriggerBuilder.Create()
.WithIdentity("everyFifteenMinutesTrigger")
.StartNow()
.WithCronSchedule("0 */15 * ? * *")
.Build();
var jobs = new List<Tuple<Type, ITrigger>>
{
@ -67,7 +72,8 @@ public class JobsHostedService : BaseJobsHostedService
new Tuple<Type, ITrigger>(typeof(DatabaseUpdateStatisticsJob), everySaturdayAtMidnightTrigger),
new Tuple<Type, ITrigger>(typeof(DatabaseRebuildlIndexesJob), everySundayAtMidnightTrigger),
new Tuple<Type, ITrigger>(typeof(DeleteCiphersJob), everyDayAtMidnightUtc),
new Tuple<Type, ITrigger>(typeof(DatabaseExpiredSponsorshipsJob), everyMondayAtMidnightTrigger)
new Tuple<Type, ITrigger>(typeof(DatabaseExpiredSponsorshipsJob), everyMondayAtMidnightTrigger),
new Tuple<Type, ITrigger>(typeof(DeleteAuthRequestsJob), everyFifteenMinutesTrigger),
};
if (!_globalSettings.SelfHosted)
@ -91,5 +97,6 @@ public class JobsHostedService : BaseJobsHostedService
services.AddTransient<DatabaseExpiredSponsorshipsJob>();
services.AddTransient<DeleteSendsJob>();
services.AddTransient<DeleteCiphersJob>();
services.AddTransient<DeleteAuthRequestsJob>();
}
}

View File

@ -0,0 +1,145 @@
using Bit.Api.Models.Request;
using Bit.Api.Models.Response;
using Bit.Core.Context;
using Bit.Core.Entities;
using Bit.Core.Exceptions;
using Bit.Core.Repositories;
using Bit.Core.Services;
using Bit.Core.Settings;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace Bit.Api.Controllers;
[Route("auth-requests")]
[Authorize("Application")]
public class AuthRequestsController : Controller
{
private readonly IUserRepository _userRepository;
private readonly IDeviceRepository _deviceRepository;
private readonly IUserService _userService;
private readonly IAuthRequestRepository _authRequestRepository;
private readonly ICurrentContext _currentContext;
private readonly IPushNotificationService _pushNotificationService;
private readonly IGlobalSettings _globalSettings;
public AuthRequestsController(
IUserRepository userRepository,
IDeviceRepository deviceRepository,
IUserService userService,
IAuthRequestRepository authRequestRepository,
ICurrentContext currentContext,
IPushNotificationService pushNotificationService,
IGlobalSettings globalSettings)
{
_userRepository = userRepository;
_deviceRepository = deviceRepository;
_userService = userService;
_authRequestRepository = authRequestRepository;
_currentContext = currentContext;
_pushNotificationService = pushNotificationService;
_globalSettings = globalSettings;
}
[HttpGet("")]
public async Task<ListResponseModel<AuthRequestResponseModel>> Get()
{
var userId = _userService.GetProperUserId(User).Value;
var authRequests = await _authRequestRepository.GetManyByUserIdAsync(userId);
var responses = authRequests.Select(a => new AuthRequestResponseModel(a, _globalSettings.SelfHosted)).ToList();
return new ListResponseModel<AuthRequestResponseModel>(responses);
}
[HttpGet("{id}")]
public async Task<AuthRequestResponseModel> Get(string id)
{
var userId = _userService.GetProperUserId(User).Value;
var authRequest = await _authRequestRepository.GetByIdAsync(new Guid(id));
if (authRequest == null || authRequest.UserId != userId)
{
throw new NotFoundException();
}
return new AuthRequestResponseModel(authRequest, _globalSettings.SelfHosted);
}
[HttpGet("{id}/response")]
[AllowAnonymous]
public async Task<AuthRequestResponseModel> GetResponse(string id, [FromQuery] string code)
{
var authRequest = await _authRequestRepository.GetByIdAsync(new Guid(id));
if (authRequest == null || code != authRequest.AccessCode || authRequest.GetExpirationDate() < DateTime.UtcNow)
{
throw new NotFoundException();
}
return new AuthRequestResponseModel(authRequest, _globalSettings.SelfHosted);
}
[HttpPost("")]
[AllowAnonymous]
public async Task<AuthRequestResponseModel> Post([FromBody] AuthRequestCreateRequestModel model)
{
var user = await _userRepository.GetByEmailAsync(model.Email);
if (user == null)
{
throw new NotFoundException();
}
if (!_currentContext.DeviceType.HasValue)
{
throw new BadRequestException("Device type not provided.");
}
if (!_globalSettings.PasswordlessAuth.KnownDevicesOnly)
{
var d = await _deviceRepository.GetByIdentifierAsync(_currentContext.DeviceIdentifier);
if (d == null || d.UserId != user.Id)
{
throw new NotFoundException();
}
}
var authRequest = new AuthRequest
{
RequestDeviceIdentifier = model.DeviceIdentifier,
RequestDeviceType = _currentContext.DeviceType.Value,
RequestIpAddress = _currentContext.IpAddress,
AccessCode = model.AccessCode,
PublicKey = model.PublicKey,
UserId = user.Id,
Type = model.Type.Value,
RequestFingerprint = model.FingerprintPhrase
};
authRequest = await _authRequestRepository.CreateAsync(authRequest);
await _pushNotificationService.PushAuthRequestAsync(authRequest);
return new AuthRequestResponseModel(authRequest, _globalSettings.SelfHosted);
}
[HttpPut("{id}")]
public async Task<AuthRequestResponseModel> Put(string id, [FromBody] AuthRequestUpdateRequestModel model)
{
var userId = _userService.GetProperUserId(User).Value;
var authRequest = await _authRequestRepository.GetByIdAsync(new Guid(id));
if (authRequest == null || authRequest.UserId != userId || authRequest.GetExpirationDate() < DateTime.UtcNow)
{
throw new NotFoundException();
}
var device = await _deviceRepository.GetByIdentifierAsync(model.DeviceIdentifier);
if (device == null)
{
throw new BadRequestException("Invalid device.");
}
if (model.RequestApproved)
{
authRequest.Key = model.Key;
authRequest.MasterPasswordHash = model.MasterPasswordHash;
authRequest.ResponseDeviceId = device.Id;
authRequest.ResponseDate = DateTime.UtcNow;
await _authRequestRepository.ReplaceAsync(authRequest);
}
await _pushNotificationService.PushAuthRequestResponseAsync(authRequest);
return new AuthRequestResponseModel(authRequest, _globalSettings.SelfHosted);
}
}

View File

@ -16,15 +16,18 @@ public class DevicesController : Controller
private readonly IDeviceRepository _deviceRepository;
private readonly IDeviceService _deviceService;
private readonly IUserService _userService;
private readonly IUserRepository _userRepository;
public DevicesController(
IDeviceRepository deviceRepository,
IDeviceService deviceService,
IUserService userService)
IUserService userService,
IUserRepository userRepository)
{
_deviceRepository = deviceRepository;
_deviceService = deviceService;
_userService = userService;
_userRepository = userRepository;
}
[HttpGet("{id}")]
@ -126,4 +129,23 @@ public class DevicesController : Controller
await _deviceService.DeleteAsync(device);
}
[AllowAnonymous]
[HttpGet("knowndevice/{email}/{identifier}")]
public async Task<bool> GetByIdentifier(string email, string identifier)
{
if (string.IsNullOrWhiteSpace(email) || string.IsNullOrWhiteSpace(identifier))
{
throw new BadRequestException("Please provide an email and device identifier");
}
var user = await _userRepository.GetByEmailAsync(email);
if (user == null)
{
return false;
}
var device = await _deviceRepository.GetByIdentifierAsync(identifier, user.Id);
return device != null;
}
}

View File

@ -0,0 +1,32 @@
using System.ComponentModel.DataAnnotations;
using Bit.Core.Enums;
using Newtonsoft.Json;
namespace Bit.Api.Models.Request;
public class AuthRequestCreateRequestModel
{
[Required]
public string Email { get; set; }
[Required]
public string PublicKey { get; set; }
[Required]
public string DeviceIdentifier { get; set; }
[Required]
[StringLength(25)]
public string AccessCode { get; set; }
[Required]
public AuthRequestType? Type { get; set; }
[Required]
public string FingerprintPhrase { get; set; }
}
public class AuthRequestUpdateRequestModel
{
public string Key { get; set; }
public string MasterPasswordHash { get; set; }
[Required]
public string DeviceIdentifier { get; set; }
[Required]
public bool RequestApproved { get; set; }
}

View File

@ -0,0 +1,43 @@
using System.ComponentModel.DataAnnotations;
using System.Reflection;
using Bit.Core.Entities;
using Bit.Core.Enums;
using Bit.Core.Models.Api;
namespace Bit.Api.Models.Response;
public class AuthRequestResponseModel : ResponseModel
{
public AuthRequestResponseModel(AuthRequest authRequest, bool isSelfHosted, string obj = "auth-request")
: base(obj)
{
if (authRequest == null)
{
throw new ArgumentNullException(nameof(authRequest));
}
Id = authRequest.Id.ToString();
PublicKey = authRequest.PublicKey;
RequestDeviceType = authRequest.RequestDeviceType.GetType().GetMember(authRequest.RequestDeviceType.ToString())
.FirstOrDefault()?.GetCustomAttribute<DisplayAttribute>()?.GetName();
RequestIpAddress = authRequest.RequestIpAddress;
RequestFingerprint = authRequest.RequestFingerprint;
Key = authRequest.Key;
MasterPasswordHash = authRequest.MasterPasswordHash;
CreationDate = authRequest.CreationDate;
RequestApproved = !string.IsNullOrWhiteSpace(Key) &&
(authRequest.Type == AuthRequestType.Unlock || !string.IsNullOrWhiteSpace(MasterPasswordHash));
Origin = Origin = isSelfHosted ? "SelfHosted" : "bitwarden.com";
}
public string Id { get; set; }
public string PublicKey { get; set; }
public string RequestDeviceType { get; set; }
public string RequestIpAddress { get; set; }
public string RequestFingerprint { get; set; }
public string Key { get; set; }
public string MasterPasswordHash { get; set; }
public DateTime CreationDate { get; set; }
public bool RequestApproved { get; set; }
public string Origin { get; set; }
}

View File

@ -0,0 +1,41 @@
using System.ComponentModel.DataAnnotations;
using Bit.Core.Utilities;
namespace Bit.Core.Entities;
public class AuthRequest : ITableObject<Guid>
{
public Guid Id { get; set; }
public Guid UserId { get; set; }
public Enums.AuthRequestType Type { get; set; }
[MaxLength(50)]
public string RequestDeviceIdentifier { get; set; }
public Enums.DeviceType RequestDeviceType { get; set; }
[MaxLength(50)]
public string RequestIpAddress { get; set; }
public string RequestFingerprint { get; set; }
public Guid? ResponseDeviceId { get; set; }
[MaxLength(25)]
public string AccessCode { get; set; }
public string PublicKey { get; set; }
public string Key { get; set; }
public string MasterPasswordHash { get; set; }
public DateTime CreationDate { get; set; } = DateTime.UtcNow;
public DateTime? ResponseDate { get; set; }
public DateTime? AuthenticationDate { get; set; }
public void SetNewId()
{
Id = CoreHelpers.GenerateComb();
}
public bool IsSpent()
{
return ResponseDate.HasValue || AuthenticationDate.HasValue || GetExpirationDate() < DateTime.UtcNow;
}
public DateTime GetExpirationDate()
{
return CreationDate.AddMinutes(15);
}
}

View File

@ -0,0 +1,7 @@
namespace Bit.Core.Enums;
public enum AuthRequestType : byte
{
AuthenticateAndUnlock = 0,
Unlock = 1
}

View File

@ -20,4 +20,7 @@ public enum PushType : byte
SyncSendCreate = 12,
SyncSendUpdate = 13,
SyncSendDelete = 14,
AuthRequest = 15,
AuthRequestResponse = 16,
}

View File

@ -20,6 +20,7 @@ public class ResourceOwnerPasswordValidator : BaseRequestValidator<ResourceOwner
private readonly IUserService _userService;
private readonly ICurrentContext _currentContext;
private readonly ICaptchaValidationService _captchaValidationService;
private readonly IAuthRequestRepository _authRequestRepository;
public ResourceOwnerPasswordValidator(
UserManager<User> userManager,
IDeviceRepository deviceRepository,
@ -36,6 +37,7 @@ public class ResourceOwnerPasswordValidator : BaseRequestValidator<ResourceOwner
GlobalSettings globalSettings,
IPolicyRepository policyRepository,
ICaptchaValidationService captchaValidationService,
IAuthRequestRepository authRequestRepository,
IUserRepository userRepository)
: base(userManager, deviceRepository, deviceService, userService, eventService,
organizationDuoWebTokenProvider, organizationRepository, organizationUserRepository,
@ -46,6 +48,7 @@ public class ResourceOwnerPasswordValidator : BaseRequestValidator<ResourceOwner
_userService = userService;
_currentContext = currentContext;
_captchaValidationService = captchaValidationService;
_authRequestRepository = authRequestRepository;
}
public async Task ValidateAsync(ResourceOwnerPasswordValidationContext context)
@ -104,12 +107,31 @@ public class ResourceOwnerPasswordValidator : BaseRequestValidator<ResourceOwner
return false;
}
if (!await _userService.CheckPasswordAsync(validatorContext.User, context.Password))
var authRequestId = context.Request.Raw["AuthRequest"]?.ToString()?.ToLowerInvariant();
if (!string.IsNullOrWhiteSpace(authRequestId) && Guid.TryParse(authRequestId, out var authRequestGuid))
{
var authRequest = await _authRequestRepository.GetByIdAsync(authRequestGuid);
if (authRequest != null)
{
var requestAge = DateTime.UtcNow - authRequest.CreationDate;
if (requestAge < TimeSpan.FromHours(1) && !authRequest.AuthenticationDate.HasValue &&
CoreHelpers.FixedTimeEquals(authRequest.AccessCode, context.Password))
{
authRequest.AuthenticationDate = DateTime.UtcNow;
await _authRequestRepository.ReplaceAsync(authRequest);
return true;
}
}
return false;
}
return true;
else
{
if (!await _userService.CheckPasswordAsync(validatorContext.User, context.Password))
{
return false;
}
return true;
}
}
protected override Task SetSuccessResult(ResourceOwnerPasswordValidationContext context, User user,

View File

@ -44,3 +44,9 @@ public class SyncSendPushNotification
public Guid UserId { get; set; }
public DateTime RevisionDate { get; set; }
}
public class AuthRequestPushNotification
{
public Guid UserId { get; set; }
public Guid Id { get; set; }
}

View File

@ -0,0 +1,9 @@
using Bit.Core.Entities;
namespace Bit.Core.Repositories;
public interface IAuthRequestRepository : IRepository<AuthRequest, Guid>
{
Task<int> DeleteExpiredAsync();
Task<ICollection<AuthRequest>> GetManyByUserIdAsync(Guid userId);
}

View File

@ -19,6 +19,8 @@ public interface IPushNotificationService
Task PushSyncSendCreateAsync(Send send);
Task PushSyncSendUpdateAsync(Send send);
Task PushSyncSendDeleteAsync(Send send);
Task PushAuthRequestAsync(AuthRequest authRequest);
Task PushAuthRequestResponseAsync(AuthRequest authRequest);
Task SendPayloadToUserAsync(string userId, PushType type, object payload, string identifier, string deviceId = null);
Task SendPayloadToOrganizationAsync(string orgId, PushType type, object payload, string identifier,
string deviceId = null);

View File

@ -130,6 +130,27 @@ public class AzureQueuePushNotificationService : IPushNotificationService
await SendMessageAsync(type, message, false);
}
public async Task PushAuthRequestAsync(AuthRequest authRequest)
{
await PushAuthRequestAsync(authRequest, PushType.AuthRequest);
}
public async Task PushAuthRequestResponseAsync(AuthRequest authRequest)
{
await PushAuthRequestAsync(authRequest, PushType.AuthRequestResponse);
}
private async Task PushAuthRequestAsync(AuthRequest authRequest, PushType type)
{
var message = new AuthRequestPushNotification
{
Id = authRequest.Id,
UserId = authRequest.UserId
};
await SendMessageAsync(type, message, true);
}
public async Task PushSyncSendCreateAsync(Send send)
{
await PushSendAsync(send, PushType.SyncSendCreate);

View File

@ -133,6 +133,18 @@ public class MultiServicePushNotificationService : IPushNotificationService
return Task.FromResult(0);
}
public Task PushAuthRequestAsync(AuthRequest authRequest)
{
PushToServices((s) => s.PushAuthRequestAsync(authRequest));
return Task.FromResult(0);
}
public Task PushAuthRequestResponseAsync(AuthRequest authRequest)
{
PushToServices((s) => s.PushAuthRequestResponseAsync(authRequest));
return Task.FromResult(0);
}
public Task PushSyncSendDeleteAsync(Send send)
{
PushToServices((s) => s.PushSyncSendDeleteAsync(send));

View File

@ -167,6 +167,27 @@ public class NotificationHubPushNotificationService : IPushNotificationService
}
}
public async Task PushAuthRequestAsync(AuthRequest authRequest)
{
await PushAuthRequestAsync(authRequest, PushType.AuthRequest);
}
public async Task PushAuthRequestResponseAsync(AuthRequest authRequest)
{
await PushAuthRequestAsync(authRequest, PushType.AuthRequestResponse);
}
private async Task PushAuthRequestAsync(AuthRequest authRequest, PushType type)
{
var message = new AuthRequestPushNotification
{
Id = authRequest.Id,
UserId = authRequest.UserId
};
await SendPayloadToUserAsync(authRequest.UserId, type, message, true);
}
private async Task SendPayloadToUserAsync(Guid userId, PushType type, object payload, bool excludeCurrentContext)
{
await SendPayloadToUserAsync(userId.ToString(), type, payload, GetContextIdentifier(excludeCurrentContext));

View File

@ -137,6 +137,27 @@ public class NotificationsApiPushNotificationService : BaseIdentityClientService
await SendMessageAsync(type, message, false);
}
public async Task PushAuthRequestAsync(AuthRequest authRequest)
{
await PushAuthRequestAsync(authRequest, PushType.AuthRequest);
}
public async Task PushAuthRequestResponseAsync(AuthRequest authRequest)
{
await PushAuthRequestAsync(authRequest, PushType.AuthRequestResponse);
}
private async Task PushAuthRequestAsync(AuthRequest authRequest, PushType type)
{
var message = new AuthRequestPushNotification
{
Id = authRequest.Id,
UserId = authRequest.UserId
};
await SendMessageAsync(type, message, true);
}
public async Task PushSyncSendCreateAsync(Send send)
{
await PushSendAsync(send, PushType.SyncSendCreate);

View File

@ -167,6 +167,27 @@ public class RelayPushNotificationService : BaseIdentityClientService, IPushNoti
}
}
public async Task PushAuthRequestAsync(AuthRequest authRequest)
{
await PushAuthRequestAsync(authRequest, PushType.AuthRequest);
}
public async Task PushAuthRequestResponseAsync(AuthRequest authRequest)
{
await PushAuthRequestAsync(authRequest, PushType.AuthRequestResponse);
}
private async Task PushAuthRequestAsync(AuthRequest authRequest, PushType type)
{
var message = new AuthRequestPushNotification
{
Id = authRequest.Id,
UserId = authRequest.UserId
};
await SendPayloadToUserAsync(authRequest.UserId, type, message, true);
}
private async Task SendPayloadToUserAsync(Guid userId, PushType type, object payload, bool excludeCurrentContext)
{
var request = new PushSendRequestModel

View File

@ -81,6 +81,16 @@ public class NoopPushNotificationService : IPushNotificationService
return Task.FromResult(0);
}
public Task PushAuthRequestAsync(AuthRequest authRequest)
{
return Task.FromResult(0);
}
public Task PushAuthRequestResponseAsync(AuthRequest authRequest)
{
return Task.FromResult(0);
}
public Task SendPayloadToUserAsync(string userId, PushType type, object payload, string identifier,
string deviceId = null)
{

View File

@ -71,6 +71,7 @@ public class GlobalSettings : IGlobalSettings
public virtual ITwoFactorAuthSettings TwoFactorAuth { get; set; } = new TwoFactorAuthSettings();
public virtual DistributedIpRateLimitingSettings DistributedIpRateLimiting { get; set; } =
new DistributedIpRateLimitingSettings();
public virtual IPasswordlessAuthSettings PasswordlessAuth { get; set; } = new PasswordlessAuthSettings();
public string BuildExternalUri(string explicitValue, string name)
{
@ -453,6 +454,7 @@ public class GlobalSettings : IGlobalSettings
get => string.IsNullOrWhiteSpace(_apiUri) ? "https://api.bitwarden.com" : _apiUri;
set => _apiUri = value;
}
}
public class AmazonSettings
@ -519,4 +521,8 @@ public class GlobalSettings : IGlobalSettings
public int SlidingWindowSeconds { get; set; } = 120;
}
public class PasswordlessAuthSettings : IPasswordlessAuthSettings
{
public bool KnownDevicesOnly { get; set; } = true;
}
}

View File

@ -15,4 +15,5 @@ public interface IGlobalSettings
IBaseServiceUriSettings BaseServiceUri { get; set; }
ITwoFactorAuthSettings TwoFactorAuth { get; set; }
ISsoSettings Sso { get; set; }
IPasswordlessAuthSettings PasswordlessAuth { get; set; }
}

View File

@ -0,0 +1,6 @@
namespace Bit.Core.Settings;
public interface IPasswordlessAuthSettings
{
bool KnownDevicesOnly { get; set; }
}

View File

@ -34,6 +34,7 @@ public static class DapperServiceCollectionExtensions
services.AddSingleton<IUserRepository, UserRepository>();
services.AddSingleton<IOrganizationApiKeyRepository, OrganizationApiKeyRepository>();
services.AddSingleton<IOrganizationConnectionRepository, OrganizationConnectionRepository>();
services.AddSingleton<IAuthRequestRepository, AuthRequestRepository>();
if (selfHosted)
{

View File

@ -0,0 +1,43 @@
using System.Data;
using System.Data.SqlClient;
using Bit.Core.Entities;
using Bit.Core.Repositories;
using Bit.Core.Settings;
using Dapper;
namespace Bit.Infrastructure.Dapper.Repositories;
public class AuthRequestRepository : Repository<AuthRequest, Guid>, IAuthRequestRepository
{
public AuthRequestRepository(GlobalSettings globalSettings)
: this(globalSettings.SqlServer.ConnectionString, globalSettings.SqlServer.ReadOnlyConnectionString)
{ }
public AuthRequestRepository(string connectionString, string readOnlyConnectionString)
: base(connectionString, readOnlyConnectionString)
{ }
public async Task<int> DeleteExpiredAsync()
{
using (var connection = new SqlConnection(ConnectionString))
{
return await connection.ExecuteAsync(
$"[{Schema}].[AuthRequest_DeleteIfExpired]",
null,
commandType: CommandType.StoredProcedure);
}
}
public async Task<ICollection<AuthRequest>> GetManyByUserIdAsync(Guid userId)
{
using (var connection = new SqlConnection(ConnectionString))
{
var results = await connection.QueryAsync<AuthRequest>(
"[{Schema}].[AuthRequest_ReadByUserId]",
new { UserId = userId },
commandType: CommandType.StoredProcedure);
return results.ToList();
}
}
}

View File

@ -56,6 +56,7 @@ public static class EntityFrameworkServiceCollectionExtensions
services.AddSingleton<IProviderRepository, ProviderRepository>();
services.AddSingleton<IProviderUserRepository, ProviderUserRepository>();
services.AddSingleton<IProviderOrganizationRepository, ProviderOrganizationRepository>();
services.AddSingleton<IAuthRequestRepository, AuthRequestRepository>();
if (selfHosted)
{

View File

@ -0,0 +1,17 @@
using AutoMapper;
namespace Bit.Infrastructure.EntityFramework.Models;
public class AuthRequest : Core.Entities.AuthRequest
{
public virtual User User { get; set; }
public virtual Device ResponseDevice { get; set; }
}
public class AuthRequestMapperProfile : Profile
{
public AuthRequestMapperProfile()
{
CreateMap<Core.Entities.AuthRequest, AuthRequest>().ReverseMap();
}
}

View File

@ -0,0 +1,35 @@
using AutoMapper;
using Bit.Core.Repositories;
using Bit.Infrastructure.EntityFramework.Models;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
namespace Bit.Infrastructure.EntityFramework.Repositories;
public class AuthRequestRepository : Repository<Core.Entities.AuthRequest, AuthRequest, Guid>, IAuthRequestRepository
{
public AuthRequestRepository(IServiceScopeFactory serviceScopeFactory, IMapper mapper)
: base(serviceScopeFactory, mapper, (DatabaseContext context) => context.AuthRequests)
{ }
public async Task<int> DeleteExpiredAsync()
{
using (var scope = ServiceScopeFactory.CreateScope())
{
var dbContext = GetDatabaseContext(scope);
var expiredRequests = await dbContext.AuthRequests.Where(a => a.CreationDate < DateTime.Now.AddMinutes(-15)).ToListAsync();
dbContext.AuthRequests.RemoveRange(expiredRequests);
await dbContext.SaveChangesAsync();
return 1;
}
}
public async Task<ICollection<Core.Entities.AuthRequest>> GetManyByUserIdAsync(Guid userId)
{
using (var scope = ServiceScopeFactory.CreateScope())
{
var dbContext = GetDatabaseContext(scope);
var userAuthRequests = await dbContext.AuthRequests.Where(a => a.UserId.Equals(userId)).ToListAsync();
return Mapper.Map<List<Core.Entities.AuthRequest>>(userAuthRequests);
}
}
}

View File

@ -39,6 +39,7 @@ public class DatabaseContext : DbContext
public DbSet<TaxRate> TaxRates { get; set; }
public DbSet<Transaction> Transactions { get; set; }
public DbSet<User> Users { get; set; }
public DbSet<AuthRequest> AuthRequests { get; set; }
protected override void OnModelCreating(ModelBuilder builder)
{
@ -70,6 +71,7 @@ public class DatabaseContext : DbContext
var eUser = builder.Entity<User>();
var eOrganizationApiKey = builder.Entity<OrganizationApiKey>();
var eOrganizationConnection = builder.Entity<OrganizationConnection>();
var eAuthRequest = builder.Entity<AuthRequest>();
eCipher.Property(c => c.Id).ValueGeneratedNever();
eCollection.Property(c => c.Id).ValueGeneratedNever();
@ -90,6 +92,7 @@ public class DatabaseContext : DbContext
eUser.Property(c => c.Id).ValueGeneratedNever();
eOrganizationApiKey.Property(c => c.Id).ValueGeneratedNever();
eOrganizationConnection.Property(c => c.Id).ValueGeneratedNever();
eAuthRequest.Property(ar => ar.Id).ValueGeneratedNever();
eCollectionCipher.HasKey(cc => new { cc.CollectionId, cc.CipherId });
eCollectionUser.HasKey(cu => new { cu.CollectionId, cu.OrganizationUserId });
@ -135,5 +138,6 @@ public class DatabaseContext : DbContext
eUser.ToTable(nameof(User));
eOrganizationApiKey.ToTable(nameof(OrganizationApiKey));
eOrganizationConnection.ToTable(nameof(OrganizationConnection));
eAuthRequest.ToTable(nameof(AuthRequest));
}
}

View File

@ -0,0 +1,19 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.SignalR;
namespace Bit.Notifications;
[AllowAnonymous]
public class AnonymousNotificationsHub : Microsoft.AspNetCore.SignalR.Hub, INotificationHub
{
public override async Task OnConnectedAsync()
{
var httpContext = Context.GetHttpContext();
var token = httpContext.Request.Query["Token"].FirstOrDefault();
if (!string.IsNullOrWhiteSpace(token))
{
await Groups.AddToGroupAsync(Context.ConnectionId, token);
}
await base.OnConnectedAsync();
}
}

View File

@ -9,6 +9,7 @@ public class AzureQueueHostedService : IHostedService, IDisposable
{
private readonly ILogger _logger;
private readonly IHubContext<NotificationsHub> _hubContext;
private readonly IHubContext<AnonymousNotificationsHub> _anonymousHubContext;
private readonly GlobalSettings _globalSettings;
private Task _executingTask;
@ -18,11 +19,13 @@ public class AzureQueueHostedService : IHostedService, IDisposable
public AzureQueueHostedService(
ILogger<AzureQueueHostedService> logger,
IHubContext<NotificationsHub> hubContext,
IHubContext<AnonymousNotificationsHub> anonymousHubContext,
GlobalSettings globalSettings)
{
_logger = logger;
_hubContext = hubContext;
_globalSettings = globalSettings;
_anonymousHubContext = anonymousHubContext;
}
public Task StartAsync(CancellationToken cancellationToken)
@ -62,7 +65,7 @@ public class AzureQueueHostedService : IHostedService, IDisposable
try
{
await HubHelpers.SendNotificationToHubAsync(
message.DecodeMessageText(), _hubContext, cancellationToken);
message.DecodeMessageText(), _hubContext, _anonymousHubContext, cancellationToken);
await _queueClient.DeleteMessageAsync(message.MessageId, message.PopReceipt);
}
catch (Exception e)

View File

@ -25,7 +25,7 @@ public class SendController : Controller
var notificationJson = await reader.ReadToEndAsync();
if (!string.IsNullOrWhiteSpace(notificationJson))
{
await HubHelpers.SendNotificationToHubAsync(notificationJson, _hubContext);
await HubHelpers.SendNotificationToHubAsync(notificationJson, _hubContext, null);
}
}
}

View File

@ -7,8 +7,12 @@ namespace Bit.Notifications;
public static class HubHelpers
{
public static async Task SendNotificationToHubAsync(string notificationJson,
IHubContext<NotificationsHub> hubContext, CancellationToken cancellationToken = default(CancellationToken))
public static async Task SendNotificationToHubAsync(
string notificationJson,
IHubContext<NotificationsHub> hubContext,
IHubContext<AnonymousNotificationsHub> anonymousHubContext,
CancellationToken cancellationToken = default(CancellationToken)
)
{
var notification = JsonSerializer.Deserialize<PushNotificationData<object>>(notificationJson);
switch (notification.Type)
@ -61,6 +65,20 @@ public static class HubHelpers
await hubContext.Clients.User(sendNotification.Payload.UserId.ToString())
.SendAsync("ReceiveMessage", sendNotification, cancellationToken);
break;
case PushType.AuthRequestResponse:
var authRequestResponseNotification =
JsonSerializer.Deserialize<PushNotificationData<AuthRequestPushNotification>>(
notificationJson);
await anonymousHubContext.Clients.Group(authRequestResponseNotification.Payload.Id.ToString())
.SendAsync("AuthRequestResponseRecieved", authRequestResponseNotification, cancellationToken);
break;
case PushType.AuthRequest:
var authRequestNotification =
JsonSerializer.Deserialize<PushNotificationData<AuthRequestPushNotification>>(
notificationJson);
await hubContext.Clients.User(authRequestNotification.Payload.UserId.ToString())
.SendAsync("ReceiveMessage", authRequestNotification, cancellationToken);
break;
default:
break;
}

View File

@ -0,0 +1,7 @@
namespace Bit.Notifications;
public interface INotificationHub
{
Task OnConnectedAsync();
Task OnDisconnectedAsync(Exception exception);
}

View File

@ -110,7 +110,12 @@ public class Startup
{
endpoints.MapHub<NotificationsHub>("/hub", options =>
{
options.ApplicationMaxBufferSize = 2048; // client => server messages are not even used
options.ApplicationMaxBufferSize = 2048;
options.TransportMaxBufferSize = 4096;
});
endpoints.MapHub<AnonymousNotificationsHub>("/anonymousHub", options =>
{
options.ApplicationMaxBufferSize = 2048;
options.TransportMaxBufferSize = 4096;
});
endpoints.MapDefaultControllerRoute();

View File

@ -73,6 +73,12 @@
<Build Include="dbo\Functions\PolicyApplicableToUser.sql" />
<Build Include="dbo\Functions\UserCipherDetails.sql" />
<Build Include="dbo\Functions\UserCollectionDetails.sql" />
<Build Include="dbo\Stored Procedures\AuthRequest_Create.sql" />
<Build Include="dbo\Stored Procedures\AuthRequest_DeleteById.sql" />
<Build Include="dbo\Stored Procedures\AuthRequest_DeleteIfExpired.sql" />
<Build Include="dbo\Stored Procedures\AuthRequest_ReadById.sql" />
<Build Include="dbo\Stored Procedures\AuthRequest_ReadByUserId.sql" />
<Build Include="dbo\Stored Procedures\AuthRequest_Update.sql" />
<Build Include="dbo\Stored Procedures\AzureSQLMaintenance.sql" />
<Build Include="dbo\Stored Procedures\CipherDetails_Create.sql" />
<Build Include="dbo\Stored Procedures\CipherDetails_CreateWithCollections.sql" />
@ -344,6 +350,7 @@
<Build Include="dbo\Stored Procedures\User_UpdateKeys.sql" />
<Build Include="dbo\Stored Procedures\User_UpdateRenewalReminderDate.sql" />
<Build Include="dbo\Stored Procedures\User_UpdateStorage.sql" />
<Build Include="dbo\Tables\AuthRequest.sql" />
<Build Include="dbo\Tables\Cipher.sql" />
<Build Include="dbo\Tables\Collection.sql" />
<Build Include="dbo\Tables\CollectionCipher.sql" />
@ -378,6 +385,7 @@
<Build Include="dbo\User Defined Types\OrganizationUserType.sql" />
<Build Include="dbo\User Defined Types\SelectionReadOnlyArray.sql" />
<Build Include="dbo\User Defined Types\TwoGuidIdArray.sql" />
<Build Include="dbo\Views\AuthRequestView.sql" />
<Build Include="dbo\Views\CipherView.sql" />
<Build Include="dbo\Views\CollectionView.sql" />
<Build Include="dbo\Views\DeviceView.sql" />

View File

@ -0,0 +1,57 @@
CREATE PROCEDURE [dbo].[AuthRequest_Create]
@Id UNIQUEIDENTIFIER OUTPUT,
@UserId UNIQUEIDENTIFIER,
@Type TINYINT,
@RequestDeviceIdentifier NVARCHAR(50),
@RequestDeviceType TINYINT,
@RequestIpAddress VARCHAR(50),
@RequestFingerprint VARCHAR(MAX),
@ResponseDeviceId UNIQUEIDENTIFIER,
@AccessCode VARCHAR(25),
@PublicKey VARCHAR(MAX),
@Key VARCHAR(MAX),
@MasterPasswordHash VARCHAR(MAX),
@CreationDate DATETIME2(7),
@ResponseDate DATETIME2(7),
@AuthenticationDate DATETIME2(7)
AS
BEGIN
SET NOCOUNT ON
INSERT INTO [dbo].[AuthRequest]
(
[Id],
[UserId],
[Type],
[RequestDeviceIdentifier],
[RequestDeviceType],
[RequestIpAddress],
[RequestFingerprint],
[ResponseDeviceId],
[AccessCode],
[PublicKey],
[Key],
[MasterPasswordHash],
[CreationDate],
[ResponseDate],
[AuthenticationDate]
)
VALUES
(
@Id,
@UserId,
@Type,
@RequestDeviceIdentifier,
@RequestDeviceType,
@RequestIpAddress,
@RequestFingerprint,
@ResponseDeviceId,
@AccessCode,
@PublicKey,
@Key,
@MasterPasswordHash,
@CreationDate,
@ResponseDate,
@AuthenticationDate
)
END

View File

@ -0,0 +1,12 @@
CREATE PROCEDURE [dbo].[AuthRequest_DeleteById]
@Id UNIQUEIDENTIFIER
AS
BEGIN
SET NOCOUNT ON
DELETE
FROM
[dbo].[AuthRequest]
WHERE
[Id] = @Id
END

View File

@ -0,0 +1,6 @@
CREATE PROCEDURE [dbo].[AuthRequest_DeleteIfExpired]
AS
BEGIN
SET NOCOUNT OFF
DELETE FROM [dbo].[AuthRequest] WHERE [CreationDate] < DATEADD(minute, -15, GETUTCDATE());
END

View File

@ -0,0 +1,13 @@
CREATE PROCEDURE [dbo].[AuthRequest_ReadById]
@Id UNIQUEIDENTIFIER
AS
BEGIN
SET NOCOUNT ON
SELECT
*
FROM
[dbo].[AuthRequestView]
WHERE
[Id] = @Id
END

View File

@ -0,0 +1,13 @@
CREATE PROCEDURE [dbo].[AuthRequest_ReadByUserId]
@UserId UNIQUEIDENTIFIER
AS
BEGIN
SET NOCOUNT ON
SELECT
*
FROM
[dbo].[AuthRequestView]
WHERE
[UserId] = @UserId
END

View File

@ -0,0 +1,22 @@
CREATE PROCEDURE [dbo].[AuthRequest_Update]
@Id UNIQUEIDENTIFIER OUTPUT,
@ResponseDeviceId UNIQUEIDENTIFIER,
@Key VARCHAR(MAX),
@MasterPasswordHash VARCHAR(MAX),
@ResponseDate DATETIME2(7),
@AuthenticationDate DATETIME2(7)
AS
BEGIN
SET NOCOUNT ON
UPDATE
[dbo].[AuthRequest]
SET
[ResponseDeviceId] = @ResponseDeviceId,
[Key] = @Key,
[MasterPasswordHash] = @MasterPasswordHash,
[ResponseDate] = @ResponseDate,
[AuthenticationDate] = @AuthenticationDate
WHERE
[Id] = @Id
END

View File

@ -0,0 +1,23 @@
CREATE TABLE [dbo].[AuthRequest] (
[Id] UNIQUEIDENTIFIER NOT NULL,
[UserId] UNIQUEIDENTIFIER NOT NULL,
[Type] SMALLINT NOT NULL,
[RequestDeviceIdentifier] NVARCHAR(50) NOT NULL,
[RequestDeviceType] SMALLINT NOT NULL,
[RequestIpAddress] VARCHAR(50) NOT NULL,
[RequestFingerprint] VARCHAR(MAX) NOT NULL,
[ResponseDeviceId] UNIQUEIDENTIFIER NULL,
[AccessCode] VARCHAR(25) NOT NULL,
[PublicKey] VARCHAR(MAX) NOT NULL,
[Key] VARCHAR(MAX) NULL,
[MasterPasswordHash] VARCHAR(MAX) NULL,
[CreationDate] DATETIME2 (7) NOT NULL,
[ResponseDate] DATETIME2 (7) NULL,
[AuthenticationDate] DATETIME2 (7) NULL,
CONSTRAINT [PK_AuthRequest] PRIMARY KEY CLUSTERED ([Id] ASC),
CONSTRAINT [FK_AuthRequest_User] FOREIGN KEY ([UserId]) REFERENCES [dbo].[User] ([Id]),
CONSTRAINT [FK_AuthRequest_ResponseDevice] FOREIGN KEY ([ResponseDeviceId]) REFERENCES [dbo].[Device] ([Id])
);
GO

View File

@ -0,0 +1,6 @@
CREATE VIEW [dbo].[AuthRequestView]
AS
SELECT
*
FROM
[dbo].[AuthRequest]