aboutsummaryrefslogtreecommitdiff
path: root/VNLib.Plugins.Essentials.Accounts.Registration/src/Endpoints/RegistrationEntpoint.cs
blob: 19d7ffad3aca059fd3b24a70479abb93e3d3b570 (plain)
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
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
/*
* Copyright (c) 2022 Vaughn Nugent
* 
* Library: VNLib
* Package: VNLib.Plugins.Essentials.Accounts.Registration
* File: RegistrationEntpoint.cs 
*
* RegistrationEntpoint.cs is part of VNLib.Plugins.Essentials.Accounts.Registration which is part of the larger 
* VNLib collection of libraries and utilities.
*
* VNLib.Plugins.Essentials.Accounts.Registration is free software: you can redistribute it and/or modify 
* it under the terms of the GNU Affero General Public License as 
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* VNLib.Plugins.Essentials.Accounts.Registration is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program.  If not, see https://www.gnu.org/licenses/.
*/

using System;
using System.Net;
using System.Text.Json;
using System.Threading.Tasks;
using System.Security.Cryptography;

using FluentValidation;

using Emails.Transactional.Client;
using Emails.Transactional.Client.Exceptions;

using VNLib.Hashing;
using VNLib.Utils.Memory;
using VNLib.Utils.Logging;
using VNLib.Utils.Extensions;
using VNLib.Hashing.IdentityUtility;
using VNLib.Net.Rest.Client;
using VNLib.Net.Rest.Client.OAuth2;
using VNLib.Plugins.Essentials.Users;
using VNLib.Plugins.Essentials.Endpoints;
using VNLib.Plugins.Essentials.Extensions;
using VNLib.Plugins.Extensions.Loading;
using VNLib.Plugins.Extensions.Loading.Sql;
using VNLib.Plugins.Extensions.Loading.Events;
using VNLib.Plugins.Extensions.Loading.Users;
using VNLib.Plugins.Extensions.Validation;
using VNLib.Plugins.Essentials.Accounts.Registration.TokenRevocation;
using static VNLib.Plugins.Essentials.Accounts.AccountManager;


namespace VNLib.Plugins.Essentials.Accounts.Registration.Endpoints
{

    [ConfigurationName("registration")]
    internal sealed class RegistrationEntpoint : UnprotectedWebEndpoint, IIntervalScheduleable
    {
        /// <summary>
        /// Generates a CNG random buffer to use as a nonce
        /// </summary>
        private static string EntropyNonce => RandomHash.GetRandomHex(16);

        const string FAILED_AUTH_ERR = "Your registration does not exist, you should try to regisiter again.";
        const string REG_ERR_MESSAGE = "Please check your email inbox.";

        private HMAC SigAlg => new HMACSHA256(RegSignatureKey.Result);
       
        private readonly IUserManager Users;
        private readonly IValidator<string> RegJwtValdidator;
        private readonly PasswordHashing Passwords;
        private readonly RevokedTokenStore RevokedTokens;
        private readonly EmailSystemConfig Emails;
        private readonly Task<byte[]> RegSignatureKey;
        private readonly TimeSpan RegExpiresSec;

        /// <summary>
        /// Creates back-end functionality for a "registration" or "sign-up" page that integrates with the <see cref="AccountManager"/> plugin
        /// </summary>
        /// <param name="Path">The path identifier</param>
        /// <exception cref="ArgumentException"></exception>
        public RegistrationEntpoint(PluginBase plugin, IReadOnlyDictionary<string, JsonElement> config)
        {
            string? path = config["path"].GetString();

            InitPathAndLog(path, plugin.Log);

            RegExpiresSec = config["reg_expires_sec"].GetTimeSpan(TimeParseType.Seconds);

            //Init reg jwt validator
            RegJwtValdidator = GetJwtValidator();

            Passwords = plugin.GetPasswords();
            Users = plugin.GetUserManager();
            RevokedTokens = new(plugin.GetContextOptions());
            Emails = new(plugin);

            //Begin the async op to get the signature key from the vault
            RegSignatureKey = plugin.TryGetSecretAsync("reg_sig_key").ContinueWith((ts) => {

                _ = ts.Result ?? throw new KeyNotFoundException("Missing required key 'reg_sig_key' in 'registration' configuration");
                return Convert.FromBase64String(ts.Result);
            });

            //Register timeout for cleanup
            _ = plugin.ScheduleInterval(this, TimeSpan.FromSeconds(60));
        }

        private static IValidator<string> GetJwtValidator()
        {
            InlineValidator<string> val = new();

            val.RuleFor(static s => s)
                .NotEmpty()
                //Must contain 2 periods for jwt limitation
                .Must(static s => s.Count(s => s == '.') == 2)
                //Guard length
                .Length(20, 500)
                .IllegalCharacters();
            return val;
        }
        

        protected override async ValueTask<VfReturnType> PostAsync(HttpEntity entity)
        {
            ValErrWebMessage webm = new();
            //Get the json request data from client
            using JsonDocument? request = await entity.GetJsonFromFileAsync();

            if(webm.Assert(request != null, "No request data present"))
            {
                entity.CloseResponseJson(HttpStatusCode.BadRequest, webm);
                return VfReturnType.VirtualSkip;
            }

            //Get the jwt string from client
            string? regJwt = request.RootElement.GetPropString("token");
            using PrivateString? password = (PrivateString?)request.RootElement.GetPropString("password");

            //validate inputs
            {
                if (webm.Assert(regJwt != null, FAILED_AUTH_ERR))
                {
                    entity.CloseResponse(webm);
                    return VfReturnType.VirtualSkip;
                }
                
                if (webm.Assert(password != null, "You must specify a password."))
                {
                    entity.CloseResponse(webm);
                    return VfReturnType.VirtualSkip;
                }
                //validate new password
                if(!AccountValidations.PasswordValidator.Validate((string)password, webm))
                {
                    entity.CloseResponse(webm);
                    return VfReturnType.VirtualSkip;
                }
                //Validate jwt
                if (webm.Assert(RegJwtValdidator.Validate(regJwt).IsValid, FAILED_AUTH_ERR))
                {
                    entity.CloseResponse(webm);
                    return VfReturnType.VirtualSkip;
                }
            }

            //Verify jwt has not been revoked            
            if(await RevokedTokens.IsRevokedAsync(regJwt, entity.EventCancellation))
            {
                webm.Result = FAILED_AUTH_ERR;
                entity.CloseResponse(webm);
                return VfReturnType.VirtualSkip;
            }

            string emailAddress;
            try
            {
                //get jwt
                using JsonWebToken jwt = JsonWebToken.Parse(regJwt);
                //verify signature
                using (HMAC hmac = SigAlg)
                {
                    bool verified = jwt.Verify(hmac);

                    if (webm.Assert(verified, FAILED_AUTH_ERR))
                    {
                        entity.CloseResponse(webm);
                        return VfReturnType.VirtualSkip;
                    }
                }

                //recover iat and email address
                using JsonDocument reg = jwt.GetPayload();
                emailAddress = reg.RootElement.GetPropString("email")!;
                DateTimeOffset iat = DateTimeOffset.FromUnixTimeSeconds(reg.RootElement.GetProperty("iat").GetInt64());

                //Verify IAT against expiration at second resolution
                if (webm.Assert(iat.Add(RegExpiresSec) > DateTimeOffset.UtcNow, FAILED_AUTH_ERR))
                {
                    entity.CloseResponse(webm);
                    return VfReturnType.VirtualSkip;
                }
            }
            catch (FormatException fe)
            {
                Log.Debug(fe);
                webm.Result = FAILED_AUTH_ERR;
                entity.CloseResponse(webm);
                return VfReturnType.VirtualSkip;
            }
           

            //Always hash the new password, even if failed
            using PrivateString passHash = Passwords.Hash(password);

            try
            {
                //Generate userid from email
                string uid = GetRandomUserId();

                //Create the new user
                using IUser user = await Users.CreateUserAsync(uid, emailAddress, MINIMUM_LEVEL, passHash, entity.EventCancellation);

                //Set active status
                user.Status = UserStatus.Active;
                //set local account origin
                user.SetAccountOrigin(LOCAL_ACCOUNT_ORIGIN);
                
                //set user verification 
                await user.ReleaseAsync();

                //Revoke token now complete
                _ = RevokedTokens.RevokeAsync(regJwt, CancellationToken.None).ConfigureAwait(false);

                webm.Result = "Successfully created your new account. You may now log in";
                webm.Success = true;
                entity.CloseResponse(webm);
                return VfReturnType.VirtualSkip;
            }
            //Capture creation failed, this may be a replay
            catch (UserExistsException)
            {
            }
            catch(UserCreationFailedException)
            {
            }

            webm.Result = FAILED_AUTH_ERR;
            entity.CloseResponse(webm);
            return VfReturnType.VirtualSkip;
        } 
      

        private static readonly IReadOnlyDictionary<string, string> JWT_HEADER = new Dictionary<string, string>()
        {
            { "typ", "JWT" },
            { "alg", "HS256" }
        };

        protected override async ValueTask<VfReturnType> PutAsync(HttpEntity entity)
        {
            ValErrWebMessage webm = new();
            
            //Get the request
            RegRequestMessage? request = await entity.GetJsonFromFileAsync<RegRequestMessage>();
            if (webm.Assert(request != null, "Request is invalid"))
            {
                entity.CloseResponseJson(HttpStatusCode.BadRequest, webm);
                return VfReturnType.VirtualSkip;
            }

            //Validate the request
            if (!AccountValidations.RegRequestValidator.Validate(request, webm))
            {
                entity.CloseResponseJson(HttpStatusCode.UnprocessableEntity, webm);
                return VfReturnType.VirtualSkip;
            }

            //Create psudo contant time delay
            Task delay = Task.Delay(200);

            //See if a user account already exists
            using (IUser? user = await Users.GetUserFromEmailAsync(request.UserName!, entity.EventCancellation))
            {
                if (user != null)
                {
                    goto Exit;
                }
            }
          
            //Get exact timestamp
            DateTimeOffset timeStamp = DateTimeOffset.UtcNow;

            //generate random nonce for entropy
            string entropy = EntropyNonce;

            //Init client jwt
            string jwtData;
            using (JsonWebToken emailJwt = new())
            {
                
                emailJwt.WriteHeader(JWT_HEADER);

                //Init new claim stack, include the same iat time, nonce for entropy, and descriptor storage id
                emailJwt.InitPayloadClaim(3)
                    .AddClaim("iat", timeStamp.ToUnixTimeSeconds())
                    .AddClaim("n", entropy)
                    .AddClaim("email", request.UserName)
                    .CommitClaims();

                //sign the jwt
                using (HMAC hmac = SigAlg)
                {
                    emailJwt.Sign(hmac);
                }
                //Compile to encoded string
                jwtData = emailJwt.Compile();
            }

            string regUrl = $"https://{entity.Server.RequestUri.Authority}{Path}?t={jwtData}";

            //Send email to user in background task and do not await it
            _ = SendRegEmailAsync(request.UserName!, regUrl).ConfigureAwait(false);

        Exit:
            //await sort of constant time delay
            await delay;

            //Notify user
            webm.Result = REG_ERR_MESSAGE;
            webm.Success = true;

            entity.CloseResponse(webm);
            return VfReturnType.VirtualSkip;
        }
      

        private async Task SendRegEmailAsync(string emailAddress, string url)
        {
            try
            {
                //Get a new registration template
                EmailTransactionRequest emailTemplate = Emails.GetRegistrationMessage();
                //Add the user's to address
                emailTemplate.AddToAddress(emailAddress);
                emailTemplate.AddVariable("username", emailAddress);
                //Set the security code variable string
                emailTemplate.AddVariable("reg_url", url);
                emailTemplate.AddVariable("date", DateTimeOffset.UtcNow.ToString("f"));
                
                //Get a new client contract
                using ClientContract client = Emails.RestClientPool.Lease();
                //Send the email
                TransactionResult result = await client.Resource.SendEmailAsync(emailTemplate);
                if (!result.Success)
                {
                    Log.Debug("Registration email failed to send, SMTP status code: {smtp}", result.SmtpStatus);
                }
                else
                {
                    Log.Verbose("Registration email sent to user. Status {smtp}", result.SmtpStatus);
                }
            }
            catch (ValidationFailedException vf)
            {
                //This should only occur if there is a bug in our reigration code that allowed an invalid value pass
                Log.Debug(vf, "Registration email failed to send to user because data validation failed");
            }
            catch (InvalidAuthorizationException iae)
            {
                Log.Warn(iae, "Registration email failed to send due to an authentication error");
            }
            catch (OAuth2AuthenticationException o2e)
            {
                Log.Warn(o2e, "Registration email failed to send due to an authentication error");
            }
            catch (Exception ex)
            {
                Log.Error(ex);
            }
        }

        async Task IIntervalScheduleable.OnIntervalAsync(ILogProvider log, CancellationToken cancellationToken)
        {
            //Cleanup tokens
            await RevokedTokens.CleanTableAsync(RegExpiresSec, cancellationToken);
        }
    }
}