aboutsummaryrefslogtreecommitdiff
path: root/plugins/VNLib.Plugins.Essentials.Accounts/src/SecurityProvider/AccountSecProvider.cs
blob: 2e0c25971260e46abc8b1e637aa0bb569fc60ed2 (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
/*
* Copyright (c) 2024 Vaughn Nugent
* 
* Library: VNLib
* Package: VNLib.Plugins.Essentials.Accounts
* File: AccountSecProvider.cs 
*
* AccountSecProvider.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/.
*/


/*
 * Implements the IAccountSecurityProvider interface to provide the shared
 * service to the host application for securing user/account based connections
 * via authorization.
 * 
 * This system is technically configurable and optionally loadable
 */

using System;
using System.Threading.Tasks;

using VNLib.Net.Http;
using VNLib.Utils;
using VNLib.Utils.Logging;
using VNLib.Plugins.Essentials.Users;
using VNLib.Plugins.Essentials.Sessions;
using VNLib.Plugins.Essentials.Middleware;
using VNLib.Plugins.Essentials.Extensions;
using VNLib.Plugins.Extensions.Loading;

namespace VNLib.Plugins.Essentials.Accounts.SecurityProvider
{

    [ConfigurationName("account_security", Required = false)]
    [MiddlewareImpl(MiddlewareImplOptions.SecurityCritical)]
    internal sealed class AccountSecProvider : IAccountSecurityProvider, IHttpMiddleware
    {
        private readonly AccountSecConfig _config;
        private readonly SingleCookieController _statusCookie;
        private readonly ClientWebAuthManager _authManager;
        private readonly ILogProvider _logger;

        public AccountSecProvider(PluginBase plugin)
            :this(plugin, new AccountSecConfig())
        { }

        public AccountSecProvider(PluginBase plugin, IConfigScope config)
            :this(
                 plugin,
                 config.DeserialzeAndValidate<AccountSecConfig>()
            )
        { }

        private AccountSecProvider(PluginBase plugin, AccountSecConfig config)
        {
            //Parse config if defined
            _config = config;

            //Status cookie handler
            _statusCookie = new(_config.ClientStatusCookieName, _config.AuthorizationValidFor)
            {
                Domain = _config.CookieDomain,
                Path = _config.CookiePath,
                SameSite = CookieSameSite.Strict,
                HttpOnly = false,   //allow javascript to read this cookie
                Secure = true
            };

            _logger = plugin.Log.CreateScope("Acnt-Sec");

            _authManager = new(config, _logger);
        }

        /*
         * Middleware handler for reconciling client cookies for all connections
         */

        ///<inheritdoc/>
        ValueTask<FileProcessArgs> IHttpMiddleware.ProcessAsync(HttpEntity entity)
        {

            ref readonly SessionInfo session = ref entity.Session;

            //Session must be set and web based for checks
            if (session.IsSet && session.SessionType == SessionType.Web)
            {
                //Make sure the session has not expired yet                
                if (OnMwCheckSessionExpired(entity, in session))
                {
                    //Expired
                    ExpireCookies(entity, true);
                    
                    //Verbose because this is a normal occurance
                    if (_logger.IsEnabled(LogLevel.Verbose))
                    {
                        _logger.Verbose("Session {id} expired", session.SessionID[..8]);
                    }
                }
                else
                {
                    //See if the session might be elevated
                    if (!ClientWebAuthManager.IsSessionElevated(in session))
                    {
                        //If the session stored a user-agent, make sure it matches the connection
                        if (session.UserAgent != null && !session.UserAgent.Equals(entity.Server.UserAgent, StringComparison.Ordinal))
                        {
                            _logger.Debug("Denied authorized connection from {ip} because user-agent changed", entity.TrustedRemoteIp);
                            return ValueTask.FromResult(FileProcessArgs.Deny);
                        }
                    }

                    //If the session is new, or not supposed to be logged in, clear the login cookies if they were set
                    if (session.IsNew || string.IsNullOrEmpty(session.Token))
                    {
                        //Do not force clear cookies (saves bandwidth)
                        ExpireCookies(entity, false);
                    }
                }
            }

            //Always continue otherwise
            return ValueTask.FromResult(FileProcessArgs.Continue);
        }

        /*
         * Verify sessions on new connections to ensure they have not expired 
         * and need to be regnerated or invalidated. If they are expired
         * we need to cleanup any internal security flags/keys
         */
        private bool OnMwCheckSessionExpired(HttpEntity entity, ref readonly SessionInfo session)
        {
            if (session.Created.AddSeconds(_config.WebSessionValidForSeconds) < entity.RequestedTimeUtc)
            {
                //Invalidate the session, so its technically valid for this request, but will be cleared on this handle close cycle
                entity.Session.Invalidate();

                //Clear auth specifc cookies
                _authManager.DestroyAuthorization(entity);
                return true;
            }

            //Not expired
            return false;
        }

        #region Interface Impl

        ///<inheritdoc/>
        IClientAuthorization IAccountSecurityProvider.AuthorizeClient(HttpEntity entity, IClientSecInfo clientInfo, IUser user)
        {
            //Validate client info
            ArgumentNullException.ThrowIfNull(user);
            ArgumentNullException.ThrowIfNull(clientInfo);
            ArgumentNullException.ThrowIfNull(clientInfo.PublicKey, nameof(clientInfo.PublicKey));
            ArgumentNullException.ThrowIfNull(clientInfo.ClientId, nameof(clientInfo.ClientId));

            if (!entity.Session.IsSet || entity.Session.IsNew || entity.Session.SessionType != SessionType.Web)
            {
                throw new ArgumentException("The session is no configured for authorization");
            }

            ClientAuthData cad = ClientAuthData.FromSecInfo(clientInfo);

            string clientData = _authManager.AuthorizeConnection(entity, in cad);

            //set client status cookie via handler
            _statusCookie.SetCookie(entity, user.IsLocalAccount() ? "1" : "2");

            //Return the new authorzation
            return new EncryptedTokenAuthorization(clientData);
        }

        ///<inheritdoc/>
        IClientAuthorization IAccountSecurityProvider.ReAuthorizeClient(HttpEntity entity)
        {
            //Confirm session is configured
            if (!entity.Session.IsSet || entity.Session.IsNew || entity.Session.SessionType != SessionType.Web)
            {
                throw new InvalidOperationException("The session is not configured for authorization");
            }

            string clientData = string.Empty;

            //recover the client's public key
            if (!_authManager.TryReAuthorizeConnection(entity, ref clientData))
            {
                throw new InvalidOperationException("The user does not have the required public key token stored");
            }

            return new EncryptedTokenAuthorization(clientData);
        }

        ///<inheritdoc/>
        void IAccountSecurityProvider.InvalidateLogin(HttpEntity entity)
        {
            //Client should also destroy the session
            ExpireCookies(entity, true);

            //Clear known security keys
            _authManager.DestroyAuthorization(entity);
        }

        ///<inheritdoc/>
        bool IAccountSecurityProvider.IsClientAuthorized(HttpEntity entity, AuthorzationCheckLevel level)
        {
            //Session must be loaded and not-new for an authorization to exist
            if(!entity.Session.IsSet || entity.Session.IsNew)
            {
                return false;
            }

            return level switch
            {
                //Accept the client token or the cookie as any/medium 
                AuthorzationCheckLevel.Any or AuthorzationCheckLevel.Medium => _authManager.HasMinimalAuthorization(entity),
                //Critical requires that the client cookie is set and the token is set
                AuthorzationCheckLevel.Critical => _authManager.VerifyConnectionOTP(entity),
                //Default to false condition
                _ => false,
            };
        }

        ///<inheritdoc/>
        ERRNO IAccountSecurityProvider.TryEncryptClientData(HttpEntity entity, ReadOnlySpan<byte> data, Span<byte> outputBuffer)
        {
            string pubKey = string.Empty;

            //Recover the signed public key, already does session checks
            return _authManager.TryGetEncryptionPubkey(entity, ref pubKey) ? RsaClientDataEncryption.TryEncrypt(pubKey, data, outputBuffer) : ERRNO.E_FAIL;
        }

        ///<inheritdoc/>
        ERRNO IAccountSecurityProvider.TryEncryptClientData(IClientSecInfo entity, ReadOnlySpan<byte> data, Span<byte> outputBuffer)
        {
            //Use the public key supplied by the csecinfo 
            return RsaClientDataEncryption.TryEncrypt(entity.PublicKey, data, outputBuffer);
        }     

        #endregion   

        private void ExpireCookies(HttpEntity entity, bool force)
        {
            _statusCookie.ExpireCookie(entity, force);
            _authManager.ExpireCookies(entity, force);
        }

        private sealed class EncryptedTokenAuthorization(string ClientAuthToken) : IClientAuthorization
        {
            ///<inheritdoc/>
            public object GetClientAuthData() => ClientAuthToken;

            ///<inheritdoc/>
            public string GetClientAuthDataString() => ClientAuthToken;            
        }
    }
}