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
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
|
// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com>
// SPDX-License-Identifier: AGPL-3.0-or-later WITH AdditionRef-Progmasoft-Patent-Grant-1.1
using Microsoft.AspNetCore.Identity;
namespace Progmasoft.Progmaweb.Api.Accounts;
/// <summary>Registration and sign-in rules of the account service.</summary>
/// <param name="store">Store that keeps accounts.</param>
/// <param name="timeProvider">Clock used for creation times.</param>
internal sealed class AccountService(
IAccountStore store,
TimeProvider timeProvider)
{
/// <summary>An account that never exists; the subject of the dummy verification.</summary>
private static readonly AccountRecord DummyAccount = new(
Guid.Empty,
"Missing00",
"MISSING00",
"missing@example.invalid",
"MISSING@EXAMPLE.INVALID",
null,
string.Empty,
DateTimeOffset.UnixEpoch);
/// <summary>
/// A hash that no submitted password matches. Verifying against it makes a sign-in with an unknown address cost
/// as much as one with a wrong password.
/// </summary>
private static readonly string DummyPasswordHash =
new PasswordHasher<AccountRecord>().HashPassword(DummyAccount, "not-the-provided-password");
/// <summary>Hashes and verifies passwords with the ASP.NET Core Identity algorithm.</summary>
private readonly PasswordHasher<AccountRecord> passwordHasher = new();
/// <summary>Creates a password account and opens a session for it.</summary>
/// <param name="request">The registration body.</param>
/// <param name="sessions">Session service.</param>
/// <param name="cancellationToken">Cancels the operation.</param>
/// <returns>
/// The signed-in account and no errors, or no account and the messages of each refused field, keyed by
/// <c>accountName</c>, <c>email</c>, <c>password</c> and <c>acceptPolicies</c>.
/// </returns>
public async ValueTask<(AuthenticatedAccount? Authentication, Dictionary<string, string[]> Errors)> RegisterAsync(
RegisterAccountRequest request,
SessionService sessions,
CancellationToken cancellationToken)
{
Dictionary<string, string[]> errors = ValidateRegistration(request, out string accountName,
out string email, out string normalizedEmail);
if (errors.Count != 0)
{
return (null, errors);
}
DateTimeOffset now = timeProvider.GetUtcNow();
AccountRecord provisional = new(
Guid.NewGuid(),
accountName,
AccountNamePolicy.NormalizeForLookup(accountName),
email,
normalizedEmail,
null,
string.Empty,
now,
PolicyAcceptance.CurrentVersion,
now);
string passwordHash = passwordHasher.HashPassword(provisional, request.Password!);
AccountRecord account = provisional with { PasswordHash = passwordHash };
CreateAccountResult result = await store.CreateAsync(account, cancellationToken);
if (result.Status is CreateAccountStatus.AccountNameUnavailable)
{
return (null, new Dictionary<string, string[]> { ["accountName"] = ["That account name is unavailable."] });
}
if (result.Status is CreateAccountStatus.EmailUnavailable)
{
return (null, new Dictionary<string, string[]> { ["email"] = ["That email address is already registered."] });
}
// The store returns the account as it keeps it, which is what every later read returns.
AuthenticatedAccount authentication = await sessions.CreateAsync(result.Account ?? account, cancellationToken);
return (authentication, errors);
}
/// <summary>Signs in with email address and password.</summary>
/// <remarks>
/// An unknown address costs one password verification against a private dummy hash, so the response time does not
/// reveal whether an address is registered.
/// </remarks>
/// <param name="request">The login body.</param>
/// <param name="sessions">Session service.</param>
/// <param name="cancellationToken">Cancels the operation.</param>
/// <returns>The signed-in account, or <see langword="null"/> when the credentials are refused.</returns>
public async ValueTask<AuthenticatedAccount?> LoginAsync(
LoginAccountRequest request,
SessionService sessions,
CancellationToken cancellationToken)
{
AccountRecord? account = await VerifyPasswordAsync(request.Email, request.Password, cancellationToken);
return account is null ? null : await sessions.CreateAsync(account, cancellationToken);
}
/// <summary>Checks an email address and password without opening a session.</summary>
/// <remarks>
/// Progmasoft Credentials signs the account in with its own cookie and must not open a session of the account
/// site. The verification is the one <see cref="LoginAsync"/> uses, with the same cost for an unknown address.
/// </remarks>
/// <param name="email">Email address as entered.</param>
/// <param name="password">Password as entered.</param>
/// <param name="cancellationToken">Cancels the operation.</param>
/// <returns>The account, or <see langword="null"/> when the credentials are refused.</returns>
public async ValueTask<AccountRecord?> VerifyPasswordAsync(
string? email,
string? password,
CancellationToken cancellationToken)
{
if (!EmailAddressPolicy.TryNormalize(email, out _, out string normalizedEmail, out _) ||
password is null || password.Length > PasswordPolicy.MaximumLength)
{
return null;
}
AccountRecord? account = await store.FindByEmailAsync(normalizedEmail, cancellationToken);
if (account is null || account.PasswordHash is null)
{
// Reuse one private hash so an unknown email follows one expensive verification, like a bad password.
_ = passwordHasher.VerifyHashedPassword(DummyAccount, DummyPasswordHash, password);
return null;
}
PasswordVerificationResult verification =
passwordHasher.VerifyHashedPassword(account, account.PasswordHash, password);
return verification is PasswordVerificationResult.Failed ? null : account;
}
/// <summary>Finds an account by its identifier, for a Credentials session that names it.</summary>
/// <param name="id">Identifier of the account.</param>
/// <param name="cancellationToken">Cancels the operation.</param>
/// <returns>The account, or <see langword="null"/> when it no longer exists.</returns>
public ValueTask<AccountRecord?> FindAsync(Guid id, CancellationToken cancellationToken) =>
store.FindByIdAsync(id, cancellationToken);
/// <summary>Signs in with a Google identity, creating the account on first use.</summary>
/// <remarks>
/// An identity that is already linked signs in to its account. A new identity creates an account under the
/// requested name. A new identity whose email address belongs to an existing account is refused: password
/// registrations do not verify the address, so linking by address could hand an account to someone else.
/// </remarks>
/// <param name="providerSubject">Subject identifier Google issued for the identity.</param>
/// <param name="providerEmail">Email address Google reported for the identity.</param>
/// <param name="requestedAccountName">Account name to create for a new identity; may be <see langword="null"/>.</param>
/// <param name="acceptedPolicies">
/// Version of the policies the person accepted before leaving for Google; a new identity creates an account only
/// when it is <see cref="PolicyAcceptance.CurrentVersion"/>.
/// </param>
/// <param name="sessions">Session service.</param>
/// <param name="cancellationToken">Cancels the operation.</param>
/// <returns>The signed-in account, or no account and the reason.</returns>
public async ValueTask<(AuthenticatedAccount? Authentication, GoogleAccountFailure Failure)>
AuthenticateGoogleAsync(
string? providerSubject,
string? providerEmail,
string? requestedAccountName,
string? acceptedPolicies,
SessionService sessions,
CancellationToken cancellationToken)
{
if (string.IsNullOrWhiteSpace(providerSubject) ||
!EmailAddressPolicy.TryNormalize(providerEmail, out string email, out string normalizedEmail, out _))
{
return (null, GoogleAccountFailure.ProviderRejected);
}
AccountRecord? knownGoogleAccount =
await store.FindByGoogleSubjectAsync(providerSubject, cancellationToken);
if (knownGoogleAccount is not null)
{
return (await sessions.CreateAsync(knownGoogleAccount, cancellationToken), GoogleAccountFailure.None);
}
AccountRecord? existing = await store.FindByEmailAsync(normalizedEmail, cancellationToken);
if (existing is not null)
{
// Password registrations do not verify ownership of the supplied email address yet. Automatically
// linking a verified Google identity by email would therefore let two unrelated people share an
// account (and any already-issued sessions) when one of them registered the other's address.
return (null, GoogleAccountFailure.ProviderRejected);
}
if (requestedAccountName is null)
{
return (null, GoogleAccountFailure.AccountNameRequired);
}
if (!AccountNamePolicy.TryNormalize(requestedAccountName, out string accountName, out _))
{
return (null, GoogleAccountFailure.InvalidAccountName);
}
if (acceptedPolicies != PolicyAcceptance.CurrentVersion)
{
return (null, GoogleAccountFailure.PoliciesRequired);
}
DateTimeOffset now = timeProvider.GetUtcNow();
AccountRecord account = new(
Guid.NewGuid(),
accountName,
AccountNamePolicy.NormalizeForLookup(accountName),
email,
normalizedEmail,
providerSubject,
null,
now,
PolicyAcceptance.CurrentVersion,
now);
CreateAccountResult result = await store.CreateAsync(account, cancellationToken);
if (result.Status is CreateAccountStatus.AccountNameUnavailable)
{
return (null, GoogleAccountFailure.AccountNameUnavailable);
}
if (result.Status is CreateAccountStatus.EmailUnavailable)
{
// Any different identity can win the email race, including an unverified password registration.
return (null, GoogleAccountFailure.ProviderRejected);
}
if (result.Status is CreateAccountStatus.GoogleSubjectUnavailable)
{
AccountRecord? concurrent = await store.FindByGoogleSubjectAsync(providerSubject, cancellationToken);
return concurrent is null
? (null, GoogleAccountFailure.ProviderRejected)
: (await sessions.CreateAsync(concurrent, cancellationToken), GoogleAccountFailure.None);
}
return (await sessions.CreateAsync(result.Account ?? account, cancellationToken), GoogleAccountFailure.None);
}
/// <summary>
/// Creates the account of a reserved name, which public registration refuses. Only trusted operations tooling
/// calls this; see <see cref="AccountCommand"/>.
/// </summary>
/// <param name="accountName">The reserved name, as it is to be spelled.</param>
/// <param name="email">The email address of the account.</param>
/// <param name="password">The password, which the operator typed.</param>
/// <param name="cancellationToken">Cancels the operation.</param>
/// <returns>The created account, or the message that says why it was refused.</returns>
public async ValueTask<(AccountRecord? Account, string? Error)> ProvisionReservedAsync(
string? accountName,
string? email,
string? password,
CancellationToken cancellationToken)
{
if (!AccountNamePolicy.TryNormalizeReserved(accountName, out string name, out string nameError))
{
return (null, nameError);
}
if (!EmailAddressPolicy.TryNormalize(email, out string address, out string normalizedEmail, out string emailError))
{
return (null, emailError);
}
if (!PasswordPolicy.TryValidate(password, out string passwordError))
{
return (null, passwordError);
}
AccountRecord provisional = new(
Guid.NewGuid(),
name,
AccountNamePolicy.NormalizeForLookup(name),
address,
normalizedEmail,
null,
string.Empty,
timeProvider.GetUtcNow());
AccountRecord account = provisional with { PasswordHash = passwordHasher.HashPassword(provisional, password!) };
CreateAccountResult result = await store.CreateAsync(account, cancellationToken);
return result.Status switch
{
CreateAccountStatus.AccountNameUnavailable => (null, $"The account '{name}' exists already."),
CreateAccountStatus.EmailUnavailable => (null, "That email address is already registered."),
_ => (result.Account ?? account, null)
};
}
/// <summary>Validates every field of a registration and collects the messages of the refused ones.</summary>
/// <param name="request">The registration body.</param>
/// <param name="accountName">The canonical account name.</param>
/// <param name="email">The email address as entered, trimmed.</param>
/// <param name="normalizedEmail">The email address in its lookup form.</param>
/// <returns>Messages keyed by field name; empty when the registration is valid.</returns>
private static Dictionary<string, string[]> ValidateRegistration(
RegisterAccountRequest request,
out string accountName,
out string email,
out string normalizedEmail)
{
Dictionary<string, string[]> errors = [];
if (!AccountNamePolicy.TryNormalize(request.AccountName, out accountName, out string accountNameError))
{
errors["accountName"] = [accountNameError];
}
if (!EmailAddressPolicy.TryNormalize(request.Email, out email, out normalizedEmail, out string emailError))
{
errors["email"] = [emailError];
}
if (!PasswordPolicy.TryValidate(request.Password, out string passwordError))
{
errors["password"] = [passwordError];
}
if (request.AcceptPolicies is not true)
{
errors["acceptPolicies"] = [PolicyAcceptance.RequiredMessage];
}
return errors;
}
}
/// <summary>Reason a sign-in with Google did not produce a session.</summary>
internal enum GoogleAccountFailure
{
/// <summary>The sign-in succeeded.</summary>
None,
/// <summary>
/// The identity cannot be used: Google reported no usable subject or address, or the address belongs to another
/// account.
/// </summary>
ProviderRejected,
/// <summary>The identity is new and no account name was supplied.</summary>
AccountNameRequired,
/// <summary>The supplied account name breaks <see cref="AccountNamePolicy"/>.</summary>
InvalidAccountName,
/// <summary>The supplied account name is taken.</summary>
AccountNameUnavailable,
/// <summary>The identity is new and the person did not accept the current policies.</summary>
PoliciesRequired
}
|