aboutsummaryrefslogtreecommitdiff
path: root/plugins/VNLib.Plugins.Essentials.Accounts/src/AccountsEntryPoint.cs
blob: 5f171cdd7a410d24c37e4c3cc6c914eda88bc4d4 (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
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
/*
* Copyright (c) 2023 Vaughn Nugent
* 
* Library: VNLib
* Package: VNLib.Plugins.Essentials.Accounts
* File: AccountsEntryPoint.cs 
*
* AccountsEntryPoint.cs is part of VNLib.Plugins.Essentials.Accounts which is part of the larger 
* VNLib collection of libraries and utilities.
*
* VNLib.Plugins.Essentials.Accounts 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 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.Text.Json;
using System.ComponentModel.Design;

using FluentValidation.Results;

using VNLib.Utils;
using VNLib.Utils.Memory;
using VNLib.Utils.Logging;
using VNLib.Plugins.Attributes;
using VNLib.Plugins.Essentials.Users;
using VNLib.Plugins.Essentials.Middleware;
using VNLib.Plugins.Essentials.Accounts.MFA;
using VNLib.Plugins.Essentials.Accounts.Endpoints;
using VNLib.Plugins.Essentials.Accounts.SecurityProvider;
using VNLib.Plugins.Extensions.Loading;
using VNLib.Plugins.Extensions.Loading.Users;
using VNLib.Plugins.Extensions.Loading.Routing;

namespace VNLib.Plugins.Essentials.Accounts
{
    public sealed class AccountsEntryPoint : PluginBase
    {

        public override string PluginName => "Essentials.Accounts";

        private bool SetupMode => HostArgs.HasArgument("--account-setup");

        private AccountSecProvider? _securityProvider;

        [ServiceConfigurator]
        public void ConfigureServices(IServiceContainer services)
        {
            //Export the built in security provider and add it as a middleware item as well
            if (_securityProvider != null)
            {
                services.AddService(typeof(IAccountSecurityProvider), _securityProvider);
                
                //Export as middleware
                services.AddService(typeof(IHttpMiddleware[]), new IHttpMiddleware[] { _securityProvider });
            }
        }

        protected override void OnLoad()
        {
            //Add optional endpoint routing

            if (this.HasConfigForType<LoginEndpoint>())
            {
                this.Route<LoginEndpoint>();
                this.Route<LogoutEndpoint>();
            }

            if (this.HasConfigForType<KeepAliveEndpoint>())
            {
                this.Route<KeepAliveEndpoint>();
            }

            if (this.HasConfigForType<ProfileEndpoint>())
            {
                this.Route<ProfileEndpoint>();
            }

            if (this.HasConfigForType<PasswordChangeEndpoint>())
            {
                this.Route<PasswordChangeEndpoint>();
            }

            if (this.HasConfigForType<MFAEndpoint>())
            {
                this.Route<MFAEndpoint>();
            }

            if (this.HasConfigForType<PkiLoginEndpoint>())
            {
                this.Route<PkiLoginEndpoint>();
            }

            //Only export the account security service if the configuration element is defined
            if (this.HasConfigForType<AccountSecProvider>())
            {
                //Inint the security provider
                _securityProvider = this.GetOrCreateSingleton<AccountSecProvider>();

                Log.Information("Configuring the account security provider service");
            }

            if (SetupMode)
            {
                Log.Warn("Setup mode is enabled, this is not recommended for production use");
            }

            //Write loaded to log
            Log.Information("Plugin loaded");
        }

     

        protected override void OnUnLoad()
        {
            //Write closing messsage and dispose the log
            Log.Information("Plugin unloaded");
        }
      
        protected override async void ProcessHostCommand(string cmd)
        {
            //Only process commands if the plugin is in setup mode
            if (!SetupMode)
            {
                return;
            }
            try
            {
                //Create argument parser
                ArgumentList args = new(cmd.Split(' '));

                IUserManager Users = this.GetOrCreateSingleton<UserManager>();
                IPasswordHashingProvider Passwords = this.GetOrCreateSingleton<ManagedPasswordHashing>();

                string? username = args.GetArgument("-u");
                string? password = args.GetArgument("-p");

                if (args.Count < 3)
                {
                    Log.Warn("Not enough arguments, use the help command to view available commands");
                    return;
                }

                switch (args[2].ToLower(null))
                {
                    case "help":
                        const string help = @"
    
Command help for {name}

Usage: p {name} <command> [options]

Commands:
    create -u <username> -p <password>                              Create a new user
    reset-password -u <username> -p <password> -l <priv level>      Reset a user's password
    delete -u <username>                                            Delete a user
    disable-mfa -u <username>                                       Disable a user's MFA configuration
    enable-totp -u <username> -s <base32 secret>                    Enable TOTP MFA for a user
    set-privilege -u <username> -l <priv level>                     Set a user's privilege level
    add-pubkey -u <username>                                        Add a JWK public key to a user's profile
    help                                                            Display this help message
";
                        Log.Information(help, PluginName);
                        break;
                    //Create new user
                    case "create":  
                        {
                            if (username == null || password == null)
                            {
                                Log.Warn("You are missing required argument values. Format 'create -u <username> -p <password>'");
                                break;
                            }

                            string? privilege = args.GetArgument("-l");

                            if(!ulong.TryParse(privilege, out ulong privLevel))
                            {
                                privLevel = AccountUtil.MINIMUM_LEVEL;
                            }

                            //Hash the password
                            using PrivateString passHash = Passwords.Hash(password);
                            //Create the user
                            using IUser user = await Users.CreateUserAsync(username, passHash, privLevel); 
                            
                            //Set active flag
                            user.Status = UserStatus.Active;
                            //Set local account
                            user.SetAccountOrigin(AccountUtil.LOCAL_ACCOUNT_ORIGIN);

                            await user.ReleaseAsync();

                            Log.Information("Successfully created user {id}", username);
                        }
                        break;
                    case "reset-password":
                        {
                            if (username == null || password == null)
                            {
                                Log.Warn("You are missing required argument values. Format 'create -u <username> -p <password>'");
                                break;
                            }

                            //Hash the password
                            using PrivateString passHash = Passwords.Hash(password);

                            //Get the user
                            using IUser? user = await Users.GetUserFromEmailAsync(username);

                            if(user == null)
                            {
                                Log.Warn("The specified user does not exist");
                                break;
                            }
                                
                            //Set the password
                            await Users.UpdatePassAsync(user, passHash);
                            
                            Log.Information("Successfully reset password for {id}", username);
                        }
                        break;
                    case "delete":
                        {
                            if(username == null)
                            {
                                Log.Warn("You are missing required argument values. Format 'delete -u <username>'");
                                break;
                            }

                            //Get user
                            using IUser? user = await Users.GetUserFromEmailAsync(username);
                            
                            if (user == null)
                            {
                                Log.Warn("The specified user does not exist");
                                break;
                            }
                            
                            //delete user
                            user.Delete();
                            //Release user
                            await user.ReleaseAsync();

                            Log.Information("Successfully deleted user {id}", username);
                        }
                        break;
                    case "disable-mfa":
                        {
                            if (username == null)
                            {
                                Log.Warn("You are missing required argument values. Format 'disable-mfa -u <username>'");
                                break;
                            }

                            //Get user
                            using IUser? user = await Users.GetUserFromEmailAsync(username);

                            if (user == null)
                            {
                                Log.Warn("The specified user does not exist");
                                break;
                            }

                            user.MFADisable();
                            await user.ReleaseAsync();

                            Log.Information("Successfully disabled MFA for {id}", username);
                        }
                        break;
                    case "enable-totp":
                        {
                            string? secret = args.GetArgument("-s");

                            if (username == null || secret == null)
                            {
                                Log.Warn("You are missing required argument values. Format 'enable-totp -u <username> -s <secret>'");
                                break;
                            }

                            //Get user
                            using IUser? user = await Users.GetUserFromEmailAsync(username);

                            if (user == null)
                            {
                                Log.Warn("The specified user does not exist");
                                break;
                            }

                            try
                            {
                                byte[] sec = VnEncoding.FromBase32String(secret) ?? throw new Exception("");
                            }
                            catch
                            {
                                Log.Error("Your TOTP secret is not valid base32");
                                break;
                            }

                            //Update the totp secret and flush changes
                            user.MFASetTOTPSecret(secret);
                            await user.ReleaseAsync();

                            Log.Information("Successfully set TOTP secret for {id}", username);
                        }
                        break;
                    case "add-pubkey":
                        {

                            if (string.IsNullOrWhiteSpace(username))
                            {
                                Log.Warn("You are missing required argument values. Format 'add-pubkey -u <username>");
                                break;
                            }

                            Console.WriteLine("Enter public key JWK...");

                            //Wait for pubkey
                            string? pubkeyJwk = Console.ReadLine();

                            if(string.IsNullOrWhiteSpace(pubkeyJwk))
                            {
                                Log.Warn("No public key supplied.");
                                break;
                            }

                            //Get user
                            using IUser? user = await Users.GetUserFromEmailAsync(username);

                            if (user == null)
                            {
                                Log.Warn("The specified user does not exist");
                                break;
                            }

                            PkiAuthPublicKey? pubkey = JsonSerializer.Deserialize<PkiAuthPublicKey>(pubkeyJwk);
                            if (pubkey == null)
                            {
                                Log.Error("You public key is not a JSON object");
                                break;
                            }

                            //Validate
                            ValidationResult res = PkiLoginEndpoint.UserJwkValidator.Validate(pubkey);
                            if (!res.IsValid)
                            {
                                Log.Error("The public key JWK is not valid:\n{errors}", res.ToDictionary());
                                break;
                            }


                            //Add/update the public key and flush changes
                            user.PKIAddPublicKey(pubkey);
                            await user.ReleaseAsync();

                            Log.Information("Successfully set TOTP secret for {id}", username);
                        }
                        break;
                    case "set-privilege":
                        {
                            if (username == null)
                            {
                                Log.Warn("You are missing required argument values. Format 'set-privilege -u <username> -l <privilege level>'");
                                break;
                            }

                            string? privilege = args.GetArgument("-l");
                            if (!ulong.TryParse(privilege, out ulong privLevel))
                            {
                                Log.Warn("You are missing required argument values. Format 'set-privilege -u <username> -l <privilege level>'");
                                break;
                            }

                            //Get user
                            using IUser? user = await Users.GetUserFromEmailAsync(username);
                            if (user == null)
                            {
                                Log.Warn("The specified user does not exist");
                                break;
                            }

                            user.Privileges = privLevel;
                            await user.ReleaseAsync();
                            Log.Information("Successfully set privilege level for {id}", username);
                        }
                        break;
                    default:
                        Log.Warn("Uknown command, use the help command");
                        break;
                }
            }
            catch (UserExistsException)
            {
                Log.Error("User already exists");
            }
            catch(UserCreationFailedException)
            {
                Log.Error("Failed to create the new user");
            }
            catch (ArgumentOutOfRangeException)
            {
                Log.Error("You are missing required command arguments");
            }
            catch(Exception ex)
            {
                Log.Error(ex);    
            }
        }
    }
}