-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Expand file tree
/
Copy pathUsersControllerConcurrencyTests.cs
More file actions
167 lines (142 loc) · 6.84 KB
/
Copy pathUsersControllerConcurrencyTests.cs
File metadata and controls
167 lines (142 loc) · 6.84 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
using Bit.Core;
using Bit.Core.Billing.Enums;
using Bit.Core.Enums;
using Bit.Core.Services;
using Bit.Infrastructure.EntityFramework.Repositories;
using Bit.IntegrationTestCommon;
using Bit.Scim.IntegrationTest.Factories;
using Bit.Scim.Models;
using Bit.Scim.Utilities;
using NSubstitute;
using Xunit;
namespace Bit.Scim.IntegrationTest.Controllers.v2;
/// <summary>
/// Verifies seat-count integrity when SCIM invite requests run concurrently.
/// Runs against every supported real RDBMS (SqlServer, Postgres, MySql) when its
/// connection string is configured via BW_TEST_DATABASES__N__*. SQLite is excluded
/// because it serializes writes globally and cannot reproduce the read-modify-write
/// race on Organization.Seats.
/// </summary>
public class UsersControllerConcurrencyTests
{
private static readonly Lazy<IReadOnlyDictionary<SupportedDatabaseProviders, string>> _configuredConnections =
new(LoadConfiguredConnections);
[SkippableTheory]
[MemberData(nameof(DatabaseProviders))]
public async Task Post_ConcurrentInvites_DoNotOvershootMaxAutoscaleSeats(
SupportedDatabaseProviders providerType)
{
var baseConnectionString = _configuredConnections.Value.GetValueOrDefault(providerType);
Skip.If(baseConnectionString is null,
$"{providerType}: not configured (set BW_TEST_DATABASES__N__TYPE/CONNECTIONSTRING).");
const short startingSeats = 3;
const int availableSeats = 2;
const int concurrentInvites = 6;
const string testDatabaseName = "vault_test_scim";
ITestDatabase testDatabase = providerType switch
{
SupportedDatabaseProviders.SqlServer => new SqlServerTestDatabase(baseConnectionString!, testDatabaseName),
SupportedDatabaseProviders.Postgres => new PostgresTestDatabase(baseConnectionString!, testDatabaseName),
SupportedDatabaseProviders.MySql => new MySqlTestDatabase(baseConnectionString!, testDatabaseName),
_ => throw new InvalidOperationException($"Unsupported provider: {providerType}"),
};
var factory = new ScimApplicationFactory
{
TestDatabase = testDatabase
};
factory.SubstituteService((IFeatureService f) => f.IsEnabled(FeatureFlagKeys.ScimInviteUserOptimization)
.Returns(true));
try
{
factory.ReinitializeDbForTests(factory.GetDatabaseContext());
using (var setupScope = factory.Services.CreateScope())
{
var setupContext = setupScope.ServiceProvider.GetRequiredService<DatabaseContext>();
var org = setupContext.Organizations.Single(o => o.Id == ScimApplicationFactory.TestOrganizationId1);
org.PlanType = PlanType.EnterpriseAnnually;
org.Plan = "Enterprise (Annually)";
org.Seats = startingSeats;
org.MaxAutoscaleSeats = startingSeats + availableSeats;
await setupContext.SaveChangesAsync();
}
var inputs = Enumerable.Range(0, concurrentInvites).Select(BuildInvite).ToArray();
var responses = await Task.WhenAll(
inputs.Select(input =>
factory.UsersPostAsync(ScimApplicationFactory.TestOrganizationId1, input)));
var successfulInvites = responses.Count(r => r.Response.StatusCode == StatusCodes.Status201Created);
using var verifyScope = factory.Services.CreateScope();
var verifyContext = verifyScope.ServiceProvider.GetRequiredService<DatabaseContext>();
var finalOrg = verifyContext.Organizations
.Single(o => o.Id == ScimApplicationFactory.TestOrganizationId1);
var finalActiveUserCount = verifyContext.OrganizationUsers
.Count(ou => ou.OrganizationId == ScimApplicationFactory.TestOrganizationId1 && ou.Status >= 0);
Assert.All(responses, r => Assert.True(r.Response.StatusCode < 500,
$"Expected non-5xx status, got {r.Response.StatusCode}"));
Assert.Equal(startingSeats + successfulInvites, finalOrg.Seats);
Assert.Equal(startingSeats + successfulInvites, finalActiveUserCount);
Assert.True(finalOrg.Seats <= finalOrg.MaxAutoscaleSeats,
$"Seats {finalOrg.Seats} exceeded MaxAutoscaleSeats {finalOrg.MaxAutoscaleSeats}");
}
finally
{
await factory.DisposeAsync();
}
}
public static IEnumerable<object?[]> DatabaseProviders()
{
yield return [SupportedDatabaseProviders.SqlServer];
yield return [SupportedDatabaseProviders.Postgres];
yield return [SupportedDatabaseProviders.MySql];
}
private static Dictionary<SupportedDatabaseProviders, string> LoadConfiguredConnections()
{
var config = new ConfigurationBuilder()
.AddUserSecrets(typeof(Bit.Identity.Startup).Assembly, optional: true)
.AddEnvironmentVariables("BW_TEST_")
.Build();
var configured = new Dictionary<SupportedDatabaseProviders, string>();
// Preferred source: BW_TEST_DATABASES__N__* env vars (set by test-database.yml in CI)
for (var i = 0; ; i++)
{
var rawType = config[$"DATABASES:{i}:TYPE"];
var connectionString = config[$"DATABASES:{i}:CONNECTIONSTRING"];
if (rawType is null && connectionString is null)
{
break;
}
if (rawType is null || connectionString is null)
{
continue;
}
if (Enum.TryParse<SupportedDatabaseProviders>(rawType, ignoreCase: true, out var type))
{
configured.TryAdd(type, connectionString);
}
}
// Fallback for local dev: Identity user secrets (globalSettings:<provider>:connectionString)
TryAddFromUserSecrets(SupportedDatabaseProviders.SqlServer, "globalSettings:sqlServer:connectionString");
TryAddFromUserSecrets(SupportedDatabaseProviders.Postgres, "globalSettings:postgreSql:connectionString");
TryAddFromUserSecrets(SupportedDatabaseProviders.MySql, "globalSettings:mySql:connectionString");
return configured;
void TryAddFromUserSecrets(SupportedDatabaseProviders type, string key)
{
if (configured.ContainsKey(type))
{
return;
}
var value = config[key];
if (!string.IsNullOrWhiteSpace(value))
{
configured[type] = value;
}
}
}
private static ScimUserRequestModel BuildInvite(int i) => new()
{
DisplayName = $"Concurrent User {i}",
Emails = [new() { Primary = true, Type = "work", Value = $"concurrent-{i}@example.com" }],
ExternalId = $"CONC-{i}",
Active = true,
Schemas = [ScimConstants.Scim2SchemaUser]
};
}