Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow for bulk updating AuthRequest database objects #4053

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
6b6ec51
Declare a new repository interface method
addisonbeck May 3, 2024
60667eb
Stub out method implementations to enable unit testing
addisonbeck May 3, 2024
9f9509e
Assert a happy path integration test
addisonbeck May 3, 2024
e8ff955
Establish a user defined SQL type for Auth Requests
addisonbeck May 3, 2024
0237032
Establish a new stored procedure
addisonbeck May 3, 2024
25c760d
Apply a SQL server migration script
addisonbeck May 3, 2024
038f746
Enable converting an `IEnumerable<AuthRequest>` to a `DataTable`
addisonbeck May 3, 2024
69aad92
Implement `Dapper/../AuthRequestRepository.UpdateMany()`
addisonbeck May 3, 2024
9d5b27e
Implement `EntityFramework/../AuthRequestRepository.UpdateMany()`
addisonbeck May 6, 2024
39c2643
Merge branch 'main' into ac/addison/ac-2301/service-bulk-device-appro…
addisonbeck May 13, 2024
a8e53d8
Assert that `UpdateManyAsync` can not create any new auth requests
addisonbeck May 13, 2024
cea0589
Use a json object as stored procedure input
addisonbeck May 13, 2024
407d25a
Merge branch 'main' into ac/addison/ac-2301/service-bulk-device-appro…
addisonbeck May 20, 2024
632e3fa
Fix the build
addisonbeck May 20, 2024
582409d
Continuing to troubleshoot the build
addisonbeck May 20, 2024
d816ce1
Move `AuthRequest_UpdateMany` to the Auth folder
addisonbeck May 20, 2024
c6660d8
Remove extra comment
addisonbeck May 20, 2024
7f444b7
Delete type that never got used
addisonbeck May 20, 2024
5034ace
intentionally break a test
addisonbeck May 20, 2024
6b9d2e3
Unbreak it
addisonbeck May 20, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions src/Core/Auth/Repositories/IAuthRequestRepository.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,5 @@ public interface IAuthRequestRepository : IRepository<AuthRequest, Guid>
Task<ICollection<AuthRequest>> GetManyByUserIdAsync(Guid userId);
Task<ICollection<OrganizationAdminAuthRequest>> GetManyPendingByOrganizationIdAsync(Guid organizationId);
Task<ICollection<OrganizationAdminAuthRequest>> GetManyAdminApprovalRequestsByManyIdsAsync(Guid organizationId, IEnumerable<Guid> ids);
Task UpdateManyAsync(IEnumerable<AuthRequest> authRequests);
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System.Data;
using System.Text.Json;
using Bit.Core.Auth.Entities;
using Bit.Core.Auth.Models.Data;
using Bit.Core.Repositories;
Expand Down Expand Up @@ -74,4 +75,20 @@
return results.ToList();
}
}

public async Task UpdateManyAsync(IEnumerable<AuthRequest> authRequests)
{

Check warning on line 80 in src/Infrastructure.Dapper/Auth/Repositories/AuthRequestRepository.cs

View check run for this annotation

Codecov / codecov/patch

src/Infrastructure.Dapper/Auth/Repositories/AuthRequestRepository.cs#L80

Added line #L80 was not covered by tests
if (!authRequests.Any())
{
return;

Check warning on line 83 in src/Infrastructure.Dapper/Auth/Repositories/AuthRequestRepository.cs

View check run for this annotation

Codecov / codecov/patch

src/Infrastructure.Dapper/Auth/Repositories/AuthRequestRepository.cs#L82-L83

Added lines #L82 - L83 were not covered by tests
}

using (var connection = new SqlConnection(ConnectionString))
{
var results = await connection.ExecuteAsync(
$"[dbo].[AuthRequest_UpdateMany]",
new { jsonData = JsonSerializer.Serialize(authRequests) },
commandType: CommandType.StoredProcedure);
}
}

Check warning on line 93 in src/Infrastructure.Dapper/Auth/Repositories/AuthRequestRepository.cs

View check run for this annotation

Codecov / codecov/patch

src/Infrastructure.Dapper/Auth/Repositories/AuthRequestRepository.cs#L86-L93

Added lines #L86 - L93 were not covered by tests
}
Original file line number Diff line number Diff line change
Expand Up @@ -69,4 +69,29 @@
return orgUserAuthRequests;
}
}

public async Task UpdateManyAsync(IEnumerable<Core.Auth.Entities.AuthRequest> authRequests)
ike-kottlowski marked this conversation as resolved.
Show resolved Hide resolved
{

Check warning on line 74 in src/Infrastructure.EntityFramework/Auth/Repositories/AuthRequestRepository.cs

View check run for this annotation

Codecov / codecov/patch

src/Infrastructure.EntityFramework/Auth/Repositories/AuthRequestRepository.cs#L74

Added line #L74 was not covered by tests
if (!authRequests.Any())
{
return;

Check warning on line 77 in src/Infrastructure.EntityFramework/Auth/Repositories/AuthRequestRepository.cs

View check run for this annotation

Codecov / codecov/patch

src/Infrastructure.EntityFramework/Auth/Repositories/AuthRequestRepository.cs#L76-L77

Added lines #L76 - L77 were not covered by tests
}

var entities = new List<AuthRequest>();

Check warning on line 80 in src/Infrastructure.EntityFramework/Auth/Repositories/AuthRequestRepository.cs

View check run for this annotation

Codecov / codecov/patch

src/Infrastructure.EntityFramework/Auth/Repositories/AuthRequestRepository.cs#L80

Added line #L80 was not covered by tests
foreach (var authRequest in authRequests)
{

Check warning on line 82 in src/Infrastructure.EntityFramework/Auth/Repositories/AuthRequestRepository.cs

View check run for this annotation

Codecov / codecov/patch

src/Infrastructure.EntityFramework/Auth/Repositories/AuthRequestRepository.cs#L82

Added line #L82 was not covered by tests
if (!authRequest.Id.Equals(default))
{
var entity = Mapper.Map<AuthRequest>(authRequest);
entities.Add(entity);
}
}

Check warning on line 88 in src/Infrastructure.EntityFramework/Auth/Repositories/AuthRequestRepository.cs

View check run for this annotation

Codecov / codecov/patch

src/Infrastructure.EntityFramework/Auth/Repositories/AuthRequestRepository.cs#L84-L88

Added lines #L84 - L88 were not covered by tests

using (var scope = ServiceScopeFactory.CreateScope())
{
var dbContext = GetDatabaseContext(scope);
dbContext.UpdateRange(entities);
await dbContext.SaveChangesAsync();
}
}

Check warning on line 96 in src/Infrastructure.EntityFramework/Auth/Repositories/AuthRequestRepository.cs

View check run for this annotation

Codecov / codecov/patch

src/Infrastructure.EntityFramework/Auth/Repositories/AuthRequestRepository.cs#L90-L96

Added lines #L90 - L96 were not covered by tests
}
45 changes: 45 additions & 0 deletions src/Sql/Auth/dbo/Stored Procedures/AuthRequest_UpdateMany.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
CREATE PROCEDURE AuthRequest_UpdateMany
@jsonData NVARCHAR(MAX)
AS
BEGIN
UPDATE AR
SET
[Id] = ARI.[Id],
[UserId] = ARI.[UserId],
[Type] = ARI.[Type],
[RequestDeviceIdentifier] = ARI.[RequestDeviceIdentifier],
[RequestDeviceType] = ARI.[RequestDeviceType],
[RequestIpAddress] = ARI.[RequestIpAddress],
[ResponseDeviceId] = ARI.[ResponseDeviceId],
[AccessCode] = ARI.[AccessCode],
[PublicKey] = ARI.[PublicKey],
[Key] = ARI.[Key],
[MasterPasswordHash] = ARI.[MasterPasswordHash],
[Approved] = ARI.[Approved],
[CreationDate] = ARI.[CreationDate],
[ResponseDate] = ARI.[ResponseDate],
[AuthenticationDate] = ARI.[AuthenticationDate],
[OrganizationId] = ARI.[OrganizationId]
FROM
[dbo].[AuthRequest] AR
INNER JOIN
OPENJSON(@jsonData)
WITH (
Id UNIQUEIDENTIFIER '$.Id',
UserId UNIQUEIDENTIFIER '$.UserId',
Type SMALLINT '$.Type',
RequestDeviceIdentifier NVARCHAR(50) '$.RequestDeviceIdentifier',
RequestDeviceType SMALLINT '$.RequestDeviceType',
RequestIpAddress VARCHAR(50) '$.RequestIpAddress',
ResponseDeviceId UNIQUEIDENTIFIER '$.ResponseDeviceId',
AccessCode VARCHAR(25) '$.AccessCode',
PublicKey VARCHAR(MAX) '$.PublicKey',
[Key] VARCHAR(MAX) '$.Key',
MasterPasswordHash VARCHAR(MAX) '$.MasterPasswordHash',
Approved BIT '$.Approved',
CreationDate DATETIME2 '$.CreationDate',
ResponseDate DATETIME2 '$.ResponseDate',
AuthenticationDate DATETIME2 '$.AuthenticationDate',
OrganizationId UNIQUEIDENTIFIER '$.OrganizationId'
) ARI ON AR.Id = ARI.Id;
END
ike-kottlowski marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,113 @@ public class AuthRequestRepositoryTests
Assert.Equal(4, numberOfDeleted);
}

[DatabaseTheory, DatabaseData]
public async Task UpdateManyAsync_Works(
IAuthRequestRepository authRequestRepository,
IUserRepository userRepository)
{
// Create two distinct real users for foreign key requirements
var user1 = await userRepository.CreateAsync(new User
{
Name = "First Test User",
Email = $"test+{Guid.NewGuid()}@email.com",
ApiKey = "TEST",
SecurityStamp = "stamp",
});

var user2 = await userRepository.CreateAsync(new User
{
Name = "Second Test User",
Email = $"test+{Guid.NewGuid()}@email.com",
ApiKey = "TEST",
SecurityStamp = "stamp",
});

var user3 = await userRepository.CreateAsync(new User
{
Name = "Third Test User",
Email = $"test+{Guid.NewGuid()}@email.com",
ApiKey = "TEST",
SecurityStamp = "stamp",
});

// Create two different and still valid (not expired or responded to) auth requests
var authRequests = new List<AuthRequest>
{
await authRequestRepository.CreateAsync(CreateAuthRequest(user1.Id, AuthRequestType.AdminApproval, DateTime.UtcNow.AddMinutes(-5))),
await authRequestRepository.CreateAsync(CreateAuthRequest(user3.Id, AuthRequestType.AdminApproval, DateTime.UtcNow.AddMinutes(-7))),
await authRequestRepository.CreateAsync(CreateAuthRequest(user2.Id, AuthRequestType.AdminApproval, DateTime.UtcNow.AddMinutes(-10))),
// This last auth request is not created manually, and will be
// used to make sure entity framework's `UpdateRange` method
// doesn't create requests too.
CreateAuthRequest(user2.Id, AuthRequestType.AdminApproval, DateTime.UtcNow.AddMinutes(-11))
};

// Update some properties on two auth request, but leave the other one
// alone to be a control value
var authRequestToBeUpdated1 = authRequests[0];
var authRequestToBeUpdated2 = authRequests[1];
var authRequestNotToBeUpdated = authRequests[2];
authRequests[0].Approved = true;
authRequests[0].ResponseDate = DateTime.UtcNow.AddMinutes(-1);
authRequests[0].Key = "UPDATED_KEY_1";
authRequests[0].MasterPasswordHash = "UPDATED_MASTERPASSWORDHASH_1";

authRequests[1].Approved = false;
authRequests[1].ResponseDate = DateTime.UtcNow.AddMinutes(-2);

// Run the method being tested
await authRequestRepository.UpdateManyAsync(authRequests);

// Define what "Equality" really means in this context
// This includes stripping milliseconds off of dates, because we can't
// reliably compare that deep
static DateTime? TrimMilliseconds(DateTime? dt)
{
if (!dt.HasValue)
{
return null;
}
return new DateTime(dt.Value.Year, dt.Value.Month, dt.Value.Day, dt.Value.Hour, dt.Value.Minute, dt.Value.Second, 0, dt.Value.Kind);
}

bool AuthRequestEquals(AuthRequest x, AuthRequest y)
{
return
x.Id == y.Id &&
x.UserId == y.UserId &&
x.Type == y.Type &&
x.RequestDeviceIdentifier == y.RequestDeviceIdentifier &&
x.RequestDeviceType == y.RequestDeviceType &&
x.RequestIpAddress == y.RequestIpAddress &&
x.ResponseDeviceId == y.ResponseDeviceId &&
x.AccessCode == y.AccessCode &&
x.PublicKey == y.PublicKey &&
x.Key == y.Key &&
x.MasterPasswordHash == y.MasterPasswordHash &&
x.Approved == y.Approved &&
TrimMilliseconds(x.CreationDate) == TrimMilliseconds(y.CreationDate) &&
TrimMilliseconds(x.ResponseDate) == TrimMilliseconds(y.ResponseDate) &&
TrimMilliseconds(x.AuthenticationDate) == TrimMilliseconds(y.AuthenticationDate) &&
x.OrganizationId == y.OrganizationId;
}

// Assert that the unchanged auth request is still unchanged
var skippedAuthRequest = await authRequestRepository.GetByIdAsync(authRequestNotToBeUpdated.Id);
Assert.True(AuthRequestEquals(skippedAuthRequest, authRequestNotToBeUpdated));

// Assert that the values updated on the changed auth requests were updated, and no others
var updatedAuthRequest1 = await authRequestRepository.GetByIdAsync(authRequestToBeUpdated1.Id);
Assert.True(AuthRequestEquals(authRequestToBeUpdated1, updatedAuthRequest1));
var updatedAuthRequest2 = await authRequestRepository.GetByIdAsync(authRequestToBeUpdated2.Id);
Assert.True(AuthRequestEquals(authRequestToBeUpdated2, updatedAuthRequest2));

// Assert that the auth request we never created is not created by
// the update method.
var uncreatedAuthRequest = await authRequestRepository.GetByIdAsync(authRequests[3].Id);
Assert.Null(uncreatedAuthRequest);
}

private static AuthRequest CreateAuthRequest(Guid userId, AuthRequestType authRequestType, DateTime creationDate, bool? approved = null, DateTime? responseDate = null)
{
return new AuthRequest
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
CREATE PROCEDURE AuthRequest_UpdateMany
@jsonData NVARCHAR(MAX)
AS
BEGIN
UPDATE AR
SET
[Id] = ARI.[Id],
[UserId] = ARI.[UserId],
[Type] = ARI.[Type],
[RequestDeviceIdentifier] = ARI.[RequestDeviceIdentifier],
[RequestDeviceType] = ARI.[RequestDeviceType],
[RequestIpAddress] = ARI.[RequestIpAddress],
[ResponseDeviceId] = ARI.[ResponseDeviceId],
[AccessCode] = ARI.[AccessCode],
[PublicKey] = ARI.[PublicKey],
[Key] = ARI.[Key],
[MasterPasswordHash] = ARI.[MasterPasswordHash],
[Approved] = ARI.[Approved],
[CreationDate] = ARI.[CreationDate],
[ResponseDate] = ARI.[ResponseDate],
[AuthenticationDate] = ARI.[AuthenticationDate],
[OrganizationId] = ARI.[OrganizationId]
FROM
[dbo].[AuthRequest] AR
INNER JOIN
OPENJSON(@jsonData)
WITH (
Id UNIQUEIDENTIFIER '$.Id',
UserId UNIQUEIDENTIFIER '$.UserId',
Type SMALLINT '$.Type',
RequestDeviceIdentifier NVARCHAR(50) '$.RequestDeviceIdentifier',
RequestDeviceType SMALLINT '$.RequestDeviceType',
RequestIpAddress VARCHAR(50) '$.RequestIpAddress',
ResponseDeviceId UNIQUEIDENTIFIER '$.ResponseDeviceId',
AccessCode VARCHAR(25) '$.AccessCode',
PublicKey VARCHAR(MAX) '$.PublicKey',
[Key] VARCHAR(MAX) '$.Key',
MasterPasswordHash VARCHAR(MAX) '$.MasterPasswordHash',
Approved BIT '$.Approved',
CreationDate DATETIME2 '$.CreationDate',
ResponseDate DATETIME2 '$.ResponseDate',
AuthenticationDate DATETIME2 '$.AuthenticationDate',
OrganizationId UNIQUEIDENTIFIER '$.OrganizationId'
) ARI ON AR.Id = ARI.Id;
END