From 204e3a11fa8fcce549a0de2db782f0d0c20b4966 Mon Sep 17 00:00:00 2001 From: vnugent Date: Sat, 19 Aug 2023 23:48:07 -0400 Subject: Accounts middleware development updates --- .../src/AccountsEntryPoint.cs | 6 +- .../src/SecurityProvider/AccountSecProvider.cs | 47 +++--- .../src/Model/Route.cs | 10 +- .../src/Model/RoutingContext.cs | 2 +- .../src/Model/XmlRouteStore.cs | 6 +- .../src/RouteComparer.cs | 2 +- .../src/Router.cs | 18 +-- .../src/sample.routes.xml | 4 +- .../src/Endpoints/Auth0.cs | 177 --------------------- .../src/SocialEntryPoint.cs | 7 - .../src/SocialOauthBase.cs | 7 +- 11 files changed, 58 insertions(+), 228 deletions(-) delete mode 100644 plugins/VNLib.Plugins.Essentials.SocialOauth/src/Endpoints/Auth0.cs (limited to 'plugins') diff --git a/plugins/VNLib.Plugins.Essentials.Accounts/src/AccountsEntryPoint.cs b/plugins/VNLib.Plugins.Essentials.Accounts/src/AccountsEntryPoint.cs index 8055d26..f61647f 100644 --- a/plugins/VNLib.Plugins.Essentials.Accounts/src/AccountsEntryPoint.cs +++ b/plugins/VNLib.Plugins.Essentials.Accounts/src/AccountsEntryPoint.cs @@ -31,6 +31,7 @@ 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.Endpoints; using VNLib.Plugins.Extensions.Loading; using VNLib.Plugins.Extensions.Loading.Users; @@ -44,7 +45,7 @@ namespace VNLib.Plugins.Essentials.Accounts public override string PluginName => "Essentials.Accounts"; - private IAccountSecurityProvider? _securityProvider; + private AccountSecProvider? _securityProvider; [ServiceConfigurator] public void ConfigureServices(IServiceContainer services) @@ -53,6 +54,9 @@ namespace VNLib.Plugins.Essentials.Accounts if (_securityProvider != null) { services.AddService(typeof(IAccountSecurityProvider), _securityProvider); + + //Export as middleware + services.AddService(typeof(IHttpMiddleware[]), new IHttpMiddleware[] { _securityProvider }); } } diff --git a/plugins/VNLib.Plugins.Essentials.Accounts/src/SecurityProvider/AccountSecProvider.cs b/plugins/VNLib.Plugins.Essentials.Accounts/src/SecurityProvider/AccountSecProvider.cs index f8b0401..41c7e93 100644 --- a/plugins/VNLib.Plugins.Essentials.Accounts/src/SecurityProvider/AccountSecProvider.cs +++ b/plugins/VNLib.Plugins.Essentials.Accounts/src/SecurityProvider/AccountSecProvider.cs @@ -33,6 +33,7 @@ using System; using System.Text.Json; +using System.Threading.Tasks; using System.Security.Cryptography; using System.Diagnostics.CodeAnalysis; using System.Text.Json.Serialization; @@ -47,14 +48,16 @@ using VNLib.Utils.Memory; using VNLib.Utils.Extensions; 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; using VNLib.Plugins.Extensions.Validation; namespace VNLib.Plugins.Essentials.Accounts.SecurityProvider { + [ConfigurationName("account_security", Required = false)] - internal class AccountSecProvider : IAccountSecurityProvider + internal class AccountSecProvider : IAccountSecurityProvider, IHttpMiddleware { private const int PUB_KEY_JWT_NONCE_SIZE = 16; @@ -82,6 +85,20 @@ namespace VNLib.Plugins.Essentials.Accounts.SecurityProvider _config = config.DeserialzeAndValidate(); } + /* + * Middleware handler for reconciling client cookies for all connections + */ + + /// + public ValueTask ProcessAsync(HttpEntity entity) + { + //Reconcile cookies on every request we enabled + ReconcileCookies(entity); + //Always continue + return ValueTask.FromResult(HttpMiddlewareResult.Continue); + } + + #region Interface Impl IClientAuthorization IAccountSecurityProvider.AuthorizeClient(HttpEntity entity, IClientSecInfo clientInfo, IUser user) @@ -149,9 +166,6 @@ namespace VNLib.Plugins.Essentials.Accounts.SecurityProvider return false; } - //Reconcile cookies on request - ReconcileCookies(entity); - return level switch { //Accept the client token or the cookie as any/medium @@ -229,29 +243,20 @@ namespace VNLib.Plugins.Essentials.Accounts.SecurityProvider private ClientSecurityToken GenerateToken(ReadOnlySpan publicKey) { - static ReadOnlySpan PublicKey(ReadOnlySpan publicKey, Span buffer) - { - ERRNO result = VnEncoding.TryFromBase64Chars(publicKey, buffer); - return buffer.Slice(0, result); - } - //Alloc buffer for encode/decode using IMemoryHandle buffer = MemoryUtil.SafeAllocNearestPage(4000, true); try { - using RSA rsa = RSA.Create(); - - //Import the client's public key - rsa.ImportSubjectPublicKeyInfo(PublicKey(publicKey, buffer.Span), out _); - Span secretBuffer = buffer.Span[.._config.TokenKeySize]; Span outputBuffer = buffer.Span[_config.TokenKeySize..]; //Computes a random shared key RandomHash.GetRandomBytes(secretBuffer); - //Encyrpt the private key to send to client - if (!rsa.TryEncrypt(secretBuffer, outputBuffer, ClientEncryptonPadding, out int bytesEncrypted)) + ERRNO bytesEncrypted = TryEncryptClientData(publicKey, secretBuffer, outputBuffer); + + //Encyrpt the secret key to send to client + if (!bytesEncrypted) { throw new InternalBufferTooSmallException("The internal buffer used to store the encrypted token is too small"); } @@ -260,8 +265,8 @@ namespace VNLib.Plugins.Essentials.Accounts.SecurityProvider return new() { //Client token is the encrypted private key - ClientToken = Convert.ToBase64String(outputBuffer[..bytesEncrypted]), - //Store public key as the server token + ClientToken = Convert.ToBase64String(outputBuffer[..(int)bytesEncrypted]), + //Server token is the raw secret ServerToken = VnEncoding.ToBase32String(secretBuffer) }; } @@ -348,6 +353,7 @@ namespace VNLib.Plugins.Essentials.Accounts.SecurityProvider return isValid; } + #endregion #region Cookies @@ -480,7 +486,7 @@ namespace VNLib.Plugins.Essentials.Accounts.SecurityProvider { if (base64PubKey.IsEmpty) { - return false; + return ERRNO.E_FAIL; } //Alloc a buffer for decoding the public key @@ -688,6 +694,7 @@ namespace VNLib.Plugins.Essentials.Accounts.SecurityProvider return true; } + #endregion diff --git a/plugins/VNLib.Plugins.Essentials.Content.Routing/src/Model/Route.cs b/plugins/VNLib.Plugins.Essentials.Content.Routing/src/Model/Route.cs index acceb0c..789d72f 100644 --- a/plugins/VNLib.Plugins.Essentials.Content.Routing/src/Model/Route.cs +++ b/plugins/VNLib.Plugins.Essentials.Content.Routing/src/Model/Route.cs @@ -46,15 +46,15 @@ namespace VNLib.Plugins.Essentials.Content.Routing.Model public string MatchPath { get; set; } - [Column("Privilage")] - public long _privilage + [Column("Privilege")] + public long _privilege { - get => (long)Privilage; - set => Privilage = (ulong)value; + get => (long)Privilege; + set => Privilege = (ulong)value; } [NotMapped] - public ulong Privilage { get; set; } + public ulong Privilege { get; set; } public string? Alternate { get; set; } = string.Empty; diff --git a/plugins/VNLib.Plugins.Essentials.Content.Routing/src/Model/RoutingContext.cs b/plugins/VNLib.Plugins.Essentials.Content.Routing/src/Model/RoutingContext.cs index 4edb892..185b2f2 100644 --- a/plugins/VNLib.Plugins.Essentials.Content.Routing/src/Model/RoutingContext.cs +++ b/plugins/VNLib.Plugins.Essentials.Content.Routing/src/Model/RoutingContext.cs @@ -66,7 +66,7 @@ namespace VNLib.Plugins.Essentials.Content.Routing.Model .Next() //Default to read-on - .WithColumn(r => r.Privilage) + .WithColumn(r => r.Privilege) .WithDefault(Accounts.AccountUtil.READ_MSK) .AllowNull(false) .Next() diff --git a/plugins/VNLib.Plugins.Essentials.Content.Routing/src/Model/XmlRouteStore.cs b/plugins/VNLib.Plugins.Essentials.Content.Routing/src/Model/XmlRouteStore.cs index 5420996..2dcc25c 100644 --- a/plugins/VNLib.Plugins.Essentials.Content.Routing/src/Model/XmlRouteStore.cs +++ b/plugins/VNLib.Plugins.Essentials.Content.Routing/src/Model/XmlRouteStore.cs @@ -117,13 +117,13 @@ namespace VNLib.Plugins.Essentials.Content.Routing.Model } //read priv level attribute - string? privAtr = routeEl.Attributes["privilage"]?.Value; - _ = privAtr ?? throw new XmlException("Missing required attribute 'priv' in route element"); + string? privAtr = routeEl.Attributes["privilege"]?.Value; + _ = privAtr ?? throw new XmlException("Missing required attribute 'privilege' in route element"); //Try to get the priv level enum value if (ulong.TryParse(privAtr, out ulong priv)) { - route.Privilage = priv; + route.Privilege = priv; } else { diff --git a/plugins/VNLib.Plugins.Essentials.Content.Routing/src/RouteComparer.cs b/plugins/VNLib.Plugins.Essentials.Content.Routing/src/RouteComparer.cs index e214e14..bd9f3b3 100644 --- a/plugins/VNLib.Plugins.Essentials.Content.Routing/src/RouteComparer.cs +++ b/plugins/VNLib.Plugins.Essentials.Content.Routing/src/RouteComparer.cs @@ -68,7 +68,7 @@ namespace VNLib.Plugins.Essentials.Content.Routing if (val == 0) { //Higher privilage routine is greater than lower privilage - val = (x.Privilage & LEVEL_MSK) > (y.Privilage & LEVEL_MSK) ? 1 : -1; + val = (x.Privilege & LEVEL_MSK) > (y.Privilege & LEVEL_MSK) ? 1 : -1; } //If both contain (or are) wildcards, then they are equal return val; diff --git a/plugins/VNLib.Plugins.Essentials.Content.Routing/src/Router.cs b/plugins/VNLib.Plugins.Essentials.Content.Routing/src/Router.cs index 3d3a1a6..59a88c1 100644 --- a/plugins/VNLib.Plugins.Essentials.Content.Routing/src/Router.cs +++ b/plugins/VNLib.Plugins.Essentials.Content.Routing/src/Router.cs @@ -63,19 +63,19 @@ namespace VNLib.Plugins.Essentials.Content.Routing public async ValueTask RouteAsync(HttpEntity entity) { //Default to read-only privilages - ulong privilage = AccountUtil.READ_MSK; + ulong privileges = AccountUtil.READ_MSK; //Only select privilages for logged-in users, this is a medium security check since we may not have all data available if (entity.Session.IsSet && entity.IsClientAuthorized(AuthorzationCheckLevel.Medium)) { - privilage = entity.Session.Privilages; + privileges = entity.Session.Privilages; } //Get the routing table for the current host ReadOnlyCollection routes = await RouteTable.GetOrAdd(entity.RequestedRoot, LoadRoutesAsync); //Find the proper routine for the connection - Route? selected = SelectBestRoute(routes, entity.RequestedRoot.Hostname, entity.Server.Path, privilage); + Route? selected = SelectBestRoute(routes, entity.RequestedRoot.Hostname, entity.Server.Path, privileges); //Get the arguments for the selected route, if not found allow the connection to continue return selected?.GetArgs(entity) ?? FileProcessArgs.Continue; @@ -113,9 +113,9 @@ namespace VNLib.Plugins.Essentials.Content.Routing /// The routes collection to read /// The connection hostname to filter routes for /// The connection url path to filter routes for - /// The calculated privialges of the connection + /// The calculated privialges of the connection /// The best route match for the connection if one is found, null otherwise - private static Route? SelectBestRoute(ReadOnlyCollection routes, string hostname, string path, ulong privilages) + private static Route? SelectBestRoute(ReadOnlyCollection routes, string hostname, string path, ulong privileges) { //Rent an array to sort routes for the current user Route[] matchArray = ArrayPool.Shared.Rent(routes.Count); @@ -124,7 +124,7 @@ namespace VNLib.Plugins.Essentials.Content.Routing //Search for routes that match for (int i = 0; i < routes.Count; i++) { - if (FastMatch(routes[i], hostname, path, privilages)) + if (FastMatch(routes[i], hostname, path, privileges)) { //Add to sort array matchArray[count++] = routes[i]; @@ -176,9 +176,9 @@ namespace VNLib.Plugins.Essentials.Content.Routing /// The route to test against /// The hostname to test /// The resource path to test - /// The privialge level to search for + /// The privialge level to search for /// True if the route can be matched to the resource and the privialge level - private static bool FastMatch(Route route, ReadOnlySpan hostname, ReadOnlySpan path, ulong privilages) + private static bool FastMatch(Route route, ReadOnlySpan hostname, ReadOnlySpan path, ulong privileges) { //Get span of hostname to stop string heap allocations during comparisons ReadOnlySpan routineHost = route.Hostname; @@ -209,7 +209,7 @@ namespace VNLib.Plugins.Essentials.Content.Routing } //Test if the level and group privilages match for the current routine - return (privilages & AccountUtil.LEVEL_MSK) >= (route.Privilage & AccountUtil.LEVEL_MSK) && (route.Privilage & AccountUtil.GROUP_MSK) == (privilages & AccountUtil.GROUP_MSK); + return (privileges & AccountUtil.LEVEL_MSK) >= (route.Privilege & AccountUtil.LEVEL_MSK) && (route.Privilege & AccountUtil.GROUP_MSK) == (privileges & AccountUtil.GROUP_MSK); } } } diff --git a/plugins/VNLib.Plugins.Essentials.Content.Routing/src/sample.routes.xml b/plugins/VNLib.Plugins.Essentials.Content.Routing/src/sample.routes.xml index 3c87aa7..bf7297f 100644 --- a/plugins/VNLib.Plugins.Essentials.Content.Routing/src/sample.routes.xml +++ b/plugins/VNLib.Plugins.Essentials.Content.Routing/src/sample.routes.xml @@ -17,7 +17,7 @@ Because this route has a more specific path than the catch all route it will be processed first --> - + * @@ -27,7 +27,7 @@ - + * diff --git a/plugins/VNLib.Plugins.Essentials.SocialOauth/src/Endpoints/Auth0.cs b/plugins/VNLib.Plugins.Essentials.SocialOauth/src/Endpoints/Auth0.cs deleted file mode 100644 index 259e830..0000000 --- a/plugins/VNLib.Plugins.Essentials.SocialOauth/src/Endpoints/Auth0.cs +++ /dev/null @@ -1,177 +0,0 @@ -/* -* Copyright (c) 2023 Vaughn Nugent -* -* Library: VNLib -* Package: VNLib.Plugins.Essentials.SocialOauth -* File: Auth0.cs -* -* Auth0.cs is part of VNLib.Plugins.Essentials.SocialOauth which is part of the larger -* VNLib collection of libraries and utilities. -* -* VNLib.Plugins.Essentials.SocialOauth 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.SocialOauth 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.Linq; -using System.Text.Json; -using System.Threading; -using System.Threading.Tasks; -using System.Collections.Generic; - -using RestSharp; - -using VNLib.Hashing; -using VNLib.Hashing.IdentityUtility; -using VNLib.Utils.Logging; -using VNLib.Plugins.Essentials.Accounts; -using VNLib.Plugins.Extensions.Loading; -using VNLib.Net.Rest.Client.Construction; - -namespace VNLib.Plugins.Essentials.SocialOauth.Endpoints -{ - - [ConfigurationName("auth0")] - internal sealed class Auth0 : SocialOauthBase - { - private readonly IAsyncLazy Auth0VerificationJwk; - - public Auth0(PluginBase plugin, IConfigScope config) : base(plugin, config) - { - string keyUrl = config["key_url"].GetString() ?? throw new KeyNotFoundException("Missing Auth0 'key_url' from config"); - - //Define the key endpoint - SiteAdapter.DefineSingleEndpoint() - .WithEndpoint() - .WithUrl(keyUrl) - .WithMethod(Method.Get) - .WithHeader("Accept", "application/json") - .OnResponse((r, res) => res.ThrowIfError()); - - //Get certificate on background thread - Auth0VerificationJwk = Task.Run(GetRsaCertificate).AsLazy(); - } - - private async Task GetRsaCertificate() - { - try - { - Log.Debug("Getting Auth0 signing keys"); - - //rent client from pool - RestResponse response = await SiteAdapter.ExecuteAsync(new GetKeyRequest()); - - //Get response as doc - using JsonDocument doc = JsonDocument.Parse(response.RawBytes); - - //Create a new jwk from each key element in the response - ReadOnlyJsonWebKey[] keys = doc.RootElement.GetProperty("keys") - .EnumerateArray() - .Select(static k => new ReadOnlyJsonWebKey(k)) - .ToArray(); - - Log.Debug("Found {count} Auth0 signing keys", keys.Length); - - return keys; - } - catch (Exception e) - { - Log.Error(e, "Failed to get Auth0 signing keys"); - throw; - } - } - - /* - * Auth0 uses the format "platoform|{user_id}" for the user id so it should match the - * external platofrm as github and discord endoints also - */ - - private static string GetUserIdFromPlatform(string userName) - { - return ManagedHash.ComputeHash(userName, HashAlg.SHA1, HashEncodingMode.Hexadecimal); - } - - - private static readonly Task EmptyLoginData = Task.FromResult(null); - - protected override Task GetLoginDataAsync(IOAuthAccessState clientAccess, CancellationToken cancellation) - { - //recover the identity token - using JsonWebToken jwt = JsonWebToken.Parse(clientAccess.IdToken); - - //Verify the token against the first signing key - if (!jwt.VerifyFromJwk(Auth0VerificationJwk.Value[0])) - { - return EmptyLoginData; - } - - using JsonDocument userData = jwt.GetPayload(); - - int iat = userData.RootElement.GetProperty("iat").GetInt32(); - int exp = userData.RootElement.GetProperty("exp").GetInt32(); - - string userId = userData.RootElement.GetProperty("sub").GetString() ?? throw new Exception("Missing sub in jwt"); - string audience = userData.RootElement.GetProperty("aud").GetString() ?? throw new Exception("Missing aud in jwt"); - string issuer = userData.RootElement.GetProperty("iss").GetString() ?? throw new Exception("Missing iss in jwt"); - - if(exp < DateTimeOffset.UtcNow.ToUnixTimeSeconds()) - { - //Expired - return EmptyLoginData; - } - - //Verify audience matches client id - if (!Config.ClientID.Value.Equals(audience, StringComparison.Ordinal)) - { - //Invalid audience - return EmptyLoginData; - } - - return Task.FromResult(new UserLoginData() - { - UserId = GetUserIdFromPlatform(userId) - }); - } - - /* - * Account data may be recovered from the identity token - * and it happens after a call to GetLoginData so - * we do not need to re-verify the token - */ - protected override Task GetAccountDataAsync(IOAuthAccessState clientAccess, CancellationToken cancellationToken) - { - using JsonWebToken jwt = JsonWebToken.Parse(clientAccess.IdToken); - - //verify signature - - using JsonDocument userData = jwt.GetPayload(); - - if (!userData.RootElement.GetProperty("email_verified").GetBoolean()) - { - return Task.FromResult(null); - } - - string fullName = userData.RootElement.GetProperty("name").GetString() ?? " "; - - return Task.FromResult(new AccountData() - { - EmailAddress = userData.RootElement.GetProperty("email").GetString(), - First = fullName.Split(' ').FirstOrDefault(), - Last = fullName.Split(' ').LastOrDefault(), - }); - } - - private sealed record class GetKeyRequest() - { } - } -} diff --git a/plugins/VNLib.Plugins.Essentials.SocialOauth/src/SocialEntryPoint.cs b/plugins/VNLib.Plugins.Essentials.SocialOauth/src/SocialEntryPoint.cs index 05152b2..83e45c8 100644 --- a/plugins/VNLib.Plugins.Essentials.SocialOauth/src/SocialEntryPoint.cs +++ b/plugins/VNLib.Plugins.Essentials.SocialOauth/src/SocialEntryPoint.cs @@ -51,13 +51,6 @@ namespace VNLib.Plugins.Essentials.SocialOauth this.Route(); Log.Information("Github social OAuth authentication loaded"); } - - if (this.HasConfigForType()) - { - //Add the auth0 login endpoint - this.Route(); - Log.Information("Auth0 social OAuth authentication loaded"); - } } diff --git a/plugins/VNLib.Plugins.Essentials.SocialOauth/src/SocialOauthBase.cs b/plugins/VNLib.Plugins.Essentials.SocialOauth/src/SocialOauthBase.cs index f36dc39..38281d4 100644 --- a/plugins/VNLib.Plugins.Essentials.SocialOauth/src/SocialOauthBase.cs +++ b/plugins/VNLib.Plugins.Essentials.SocialOauth/src/SocialOauthBase.cs @@ -146,6 +146,7 @@ namespace VNLib.Plugins.Essentials.SocialOauth return val; } + private static IValidator GetNonceValidator() { InlineValidator val = new(); @@ -281,7 +282,8 @@ namespace VNLib.Plugins.Essentials.SocialOauth protected override async ValueTask GetAsync(HttpEntity entity) { //Make sure state and code parameters are available - if (entity.QueryArgs.TryGetNonEmptyValue("state", out string? state) && entity.QueryArgs.TryGetNonEmptyValue("code", out string? code)) + if (entity.QueryArgs.TryGetNonEmptyValue("state", out string? state) + && entity.QueryArgs.TryGetNonEmptyValue("code", out string? code)) { //Disable refer headers when nonce is set entity.Server.Headers["Referrer-Policy"] = "no-referrer"; @@ -633,7 +635,8 @@ namespace VNLib.Plugins.Essentials.SocialOauth Secure = true, HttpOnly = true, ValidFor = Config.InitClaimValidFor, - SameSite = CookieSameSite.SameSite + SameSite = CookieSameSite.SameSite, + Path = this.Path }; entity.Server.SetCookie(in cookie); -- cgit