diff options
Diffstat (limited to 'Libs/VNLib.Plugins.Essentials.Sessions.OAuth')
4 files changed, 40 insertions, 79 deletions
diff --git a/Libs/VNLib.Plugins.Essentials.Sessions.OAuth/O2SessionProviderEntry.cs b/Libs/VNLib.Plugins.Essentials.Sessions.OAuth/O2SessionProviderEntry.cs index f4462a4..7e72714 100644 --- a/Libs/VNLib.Plugins.Essentials.Sessions.OAuth/O2SessionProviderEntry.cs +++ b/Libs/VNLib.Plugins.Essentials.Sessions.OAuth/O2SessionProviderEntry.cs @@ -27,12 +27,14 @@ using System.Text.Json; using VNLib.Net.Http; using VNLib.Utils.Logging; using VNLib.Utils.Extensions; -using VNLib.Data.Caching.Extensions; +using VNLib.Data.Caching; +using VNLib.Plugins.Sessions.Cache.Client; using VNLib.Plugins.Essentials.Oauth.Tokens; using VNLib.Plugins.Essentials.Oauth.Applications; using VNLib.Plugins.Essentials.Sessions.OAuth; using VNLib.Plugins.Essentials.Sessions.Runtime; using VNLib.Plugins.Essentials.Sessions.OAuth.Endpoints; +using VNLib.Plugins.Extensions.VNCache; using VNLib.Plugins.Extensions.Loading; using VNLib.Plugins.Extensions.Loading.Routing; using VNLib.Plugins.Extensions.Loading.Sql; @@ -44,7 +46,6 @@ namespace VNLib.Plugins.Essentials.Sessions.Oauth public sealed class O2SessionProviderEntry : IRuntimeSessionProvider { - const string VNCACHE_CONFIG_KEY = "vncache"; const string OAUTH2_CONFIG_KEY = "oauth2"; private OAuth2SessionProvider? _sessions; @@ -63,14 +64,11 @@ namespace VNLib.Plugins.Essentials.Sessions.Oauth void IRuntimeSessionProvider.Load(PluginBase plugin, ILogProvider localized) { - //Try get vncache config element - IReadOnlyDictionary<string, JsonElement> cacheConfig = plugin.GetConfig(VNCACHE_CONFIG_KEY); - - IReadOnlyDictionary<string, JsonElement> oauth2Config = plugin.GetConfig(OAUTH2_CONFIG_KEY); + IReadOnlyDictionary<string, JsonElement> oauth2Config = plugin.GetConfigForType<OAuth2SessionProvider>(); //Optional application jwt token Task<JsonDocument?> jwtTokenSecret = plugin.TryGetSecretAsync("application_token_key") - .ContinueWith(static t => t.Result == null ? null : t.Result.GetJsonDocument(), TaskScheduler.Default); + .ContinueWith(static t => t.Result?.GetJsonDocument(), TaskScheduler.Default); //Access token endpoint is optional if (oauth2Config.TryGetValue("token_path", out JsonElement el)) @@ -89,74 +87,38 @@ namespace VNLib.Plugins.Essentials.Sessions.Oauth plugin.Route<RevocationEndpoint>(); } - //Run - _ = plugin.DeferTask(() => CacheWokerDoWorkAsync(plugin, localized, cacheConfig, oauth2Config), 100); - - } + int cacheLimit = oauth2Config["cache_size"].GetInt32(); + int maxTokensPerApp = oauth2Config["max_tokens_per_app"].GetInt32(); + int sessionIdSize = (int)oauth2Config["access_token_size"].GetUInt32(); + TimeSpan tokenValidFor = oauth2Config["token_valid_for_sec"].GetTimeSpan(TimeParseType.Seconds); + TimeSpan cleanupInterval = oauth2Config["gc_interval_sec"].GetTimeSpan(TimeParseType.Seconds); + string sessionIdPrefix = oauth2Config["cache_prefix"].GetString() ?? throw new KeyNotFoundException($"Missing required key 'cache_prefix' in '{OAUTH2_CONFIG_KEY}' config"); - private async Task<IOAuth2TokenResult?> CreateTokenDelegateAsync(HttpEntity entity, UserApplication app, CancellationToken cancellation) - { - return await _sessions!.CreateAccessTokenAsync(entity, app, cancellation).ConfigureAwait(false); - } + //init the id provider + OAuth2SessionIdProvider idProv = new(sessionIdPrefix, maxTokensPerApp, sessionIdSize, tokenValidFor); - /* - * Starts and monitors the VNCache connection - */ + //Get shared global-cache + IGlobalCacheProvider globalCache = plugin.GetGlobalCache(); - private async Task CacheWokerDoWorkAsync(PluginBase plugin, ILogProvider localized, - IReadOnlyDictionary<string, JsonElement> cacheConfig, - IReadOnlyDictionary<string, JsonElement> oauth2Config) - { - //Init cache client - using VnCacheClient cache = new(plugin.IsDebug() ? localized : null, Utils.Memory.Memory.Shared); - - try - { - int cacheLimit = oauth2Config["cache_size"].GetInt32(); - int maxTokensPerApp = oauth2Config["max_tokens_per_app"].GetInt32(); - int sessionIdSize = (int)oauth2Config["access_token_size"].GetUInt32(); - TimeSpan tokenValidFor = oauth2Config["token_valid_for_sec"].GetTimeSpan(TimeParseType.Seconds); - TimeSpan cleanupInterval = oauth2Config["gc_interval_sec"].GetTimeSpan(TimeParseType.Seconds); - string sessionIdPrefix = oauth2Config["cache_prefix"].GetString() ?? throw new KeyNotFoundException($"Missing required key 'cache_prefix' in '{OAUTH2_CONFIG_KEY}' config"); - - //init the id provider - OAuth2SessionIdProvider idProv = new(sessionIdPrefix, maxTokensPerApp, sessionIdSize, tokenValidFor); - - //Try loading config - await cache.LoadConfigAsync(plugin, cacheConfig); + //Create cache store from global cache + GlobalCacheStore cacheStore = new(globalCache); - //Init session provider now that client is loaded - _sessions = new(cache.Resource!, cacheLimit, 100, idProv, plugin.GetContextOptions()); + //Init session provider now that client is loaded + _sessions = new(cacheStore, cacheLimit, 100, idProv, plugin.GetContextOptions()); - //Schedule cleanup interval with the plugin scheduler - plugin.ScheduleInterval(_sessions, cleanupInterval); + //Schedule cleanup interval with the plugin scheduler + plugin.ScheduleInterval(_sessions, cleanupInterval); - localized.Information("Session provider loaded"); + //Wait and cleanup expired sessions + _ = plugin.DeferTask(() => _sessions.CleanupExpiredSessionsAsync(localized, plugin.UnloadToken), 1000); - //Run and wait for exit - await cache.RunAsync(localized, plugin.UnloadToken); + localized.Information("Session provider loaded"); - } - catch (OperationCanceledException) - {} - catch (KeyNotFoundException e) - { - localized.Error("Missing required configuration variable for VnCache client: {0}", e.Message); - } - catch(FBMServerNegiationException fne) - { - localized.Error("Failed to negotiate connection with cache server {reason}", fne.Message); - } - catch (Exception ex) - { - localized.Error(ex, "Cache client error occured in session provider"); - } - finally - { - _sessions = null; - } + } - localized.Information("Cache client exited"); + private async Task<IOAuth2TokenResult?> CreateTokenDelegateAsync(HttpEntity entity, UserApplication app, CancellationToken cancellation) + { + return await _sessions!.CreateAccessTokenAsync(entity, app, cancellation).ConfigureAwait(false); } } }
\ No newline at end of file diff --git a/Libs/VNLib.Plugins.Essentials.Sessions.OAuth/OAuth2Session.cs b/Libs/VNLib.Plugins.Essentials.Sessions.OAuth/OAuth2Session.cs index 539799c..e9a69cd 100644 --- a/Libs/VNLib.Plugins.Essentials.Sessions.OAuth/OAuth2Session.cs +++ b/Libs/VNLib.Plugins.Essentials.Sessions.OAuth/OAuth2Session.cs @@ -25,7 +25,6 @@ using System; using VNLib.Net.Http; -using VNLib.Net.Messaging.FBM.Client; using VNLib.Plugins.Sessions.Cache.Client; using VNLib.Plugins.Sessions.Cache.Client.Exceptions; @@ -44,10 +43,10 @@ namespace VNLib.Plugins.Essentials.Sessions.OAuth /// Initalizes a new <see cref="OAuth2Session"/> /// </summary> /// <param name="sessionId">The session id (or token)</param> - /// <param name="client">The <see cref="FBMClient"/> used as the backing cache provider</param> + /// <param name="client">The <see cref="IRemoteCacheStore"/> used as the backing cache provider</param> /// <param name="backgroundTimeOut">The ammount of time to wait for a background operation (delete, update, get)</param> /// <param name="invalidCache">Called when the session has been marked as invalid and the close even hook is being executed</param> - public OAuth2Session(string sessionId, FBMClient client, TimeSpan backgroundTimeOut, Action<OAuth2Session> invalidCache) + public OAuth2Session(string sessionId, IRemoteCacheStore client, TimeSpan backgroundTimeOut, Action<OAuth2Session> invalidCache) : base(sessionId, client, backgroundTimeOut) { InvalidateCache = invalidCache; diff --git a/Libs/VNLib.Plugins.Essentials.Sessions.OAuth/OAuth2SessionProvider.cs b/Libs/VNLib.Plugins.Essentials.Sessions.OAuth/OAuth2SessionProvider.cs index 106029f..dca7909 100644 --- a/Libs/VNLib.Plugins.Essentials.Sessions.OAuth/OAuth2SessionProvider.cs +++ b/Libs/VNLib.Plugins.Essentials.Sessions.OAuth/OAuth2SessionProvider.cs @@ -30,14 +30,13 @@ using Microsoft.EntityFrameworkCore; using VNLib.Net.Http; using VNLib.Utils; using VNLib.Utils.Logging; -using VNLib.Data.Caching; using VNLib.Data.Caching.Exceptions; -using VNLib.Net.Messaging.FBM.Client; using VNLib.Plugins.Sessions.Cache.Client; using VNLib.Plugins.Essentials.Oauth; using VNLib.Plugins.Essentials.Oauth.Tokens; using VNLib.Plugins.Essentials.Oauth.Applications; using VNLib.Plugins.Extensions.Loading.Events; +using VNLib.Plugins.Extensions.Loading; namespace VNLib.Plugins.Essentials.Sessions.OAuth { @@ -45,7 +44,8 @@ namespace VNLib.Plugins.Essentials.Sessions.OAuth /// <summary> /// Provides OAuth2 session management /// </summary> - internal sealed class OAuth2SessionProvider : SessionCacheClient, ISessionProvider, ITokenManager, IIntervalScheduleable + [ConfigurationName("oauth2")] + internal sealed class OAuth2SessionProvider : SessionCacheClient, ITokenManager, IIntervalScheduleable { private static readonly SessionHandle NotFoundHandle = new(null, FileProcessArgs.NotFound, null); @@ -57,7 +57,7 @@ namespace VNLib.Plugins.Essentials.Sessions.OAuth private readonly TokenStore TokenStore; private readonly uint MaxConnections; - public OAuth2SessionProvider(FBMClient client, int maxCacheItems, uint maxConnections, IOauthSessionIdFactory idFactory, DbContextOptions dbCtx) + public OAuth2SessionProvider(IRemoteCacheStore client, int maxCacheItems, uint maxConnections, IOauthSessionIdFactory idFactory, DbContextOptions dbCtx) : base(client, maxCacheItems) { factory = idFactory; @@ -66,7 +66,7 @@ namespace VNLib.Plugins.Essentials.Sessions.OAuth } ///<inheritdoc/> - protected override RemoteSession SessionCtor(string sessionId) => new OAuth2Session(sessionId, Client, BackgroundTimeout, InvalidatateCache); + protected override RemoteSession SessionCtor(string sessionId) => new OAuth2Session(sessionId, Store, BackgroundTimeout, InvalidatateCache); private void InvalidatateCache(OAuth2Session session) { @@ -97,7 +97,7 @@ namespace VNLib.Plugins.Essentials.Sessions.OAuth if (WaitingConnections > MaxConnections) { //Set 503 for temporary unavail - entity.CloseResponse(System.Net.HttpStatusCode.ServiceUnavailable); + entity.CloseResponse(HttpStatusCode.ServiceUnavailable); return new SessionHandle(null, FileProcessArgs.VirtualSkip, null); } @@ -202,7 +202,7 @@ namespace VNLib.Plugins.Essentials.Sessions.OAuth try { //Remove tokens by thier object id from cache - await base.Client.DeleteObjectAsync(token.Id, cancellationToken); + await base.Store.DeleteObjectAsync(token.Id, cancellationToken); } //Ignore if the object has already been removed catch (ObjectNotFoundException) diff --git a/Libs/VNLib.Plugins.Essentials.Sessions.OAuth/VNLib.Plugins.Essentials.Sessions.OAuth.csproj b/Libs/VNLib.Plugins.Essentials.Sessions.OAuth/VNLib.Plugins.Essentials.Sessions.OAuth.csproj index e9927b5..d6775c8 100644 --- a/Libs/VNLib.Plugins.Essentials.Sessions.OAuth/VNLib.Plugins.Essentials.Sessions.OAuth.csproj +++ b/Libs/VNLib.Plugins.Essentials.Sessions.OAuth/VNLib.Plugins.Essentials.Sessions.OAuth.csproj @@ -13,7 +13,8 @@ <Version>1.0.1.1</Version> <PackageProjectUrl>https://www.vaughnugent.com</PackageProjectUrl> <AnalysisLevel>latest-all</AnalysisLevel> - + <SignAssembly>True</SignAssembly> + <AssemblyOriginatorKeyFile>\\vaughnnugent.com\Internal\Folder Redirection\vman\Documents\Programming\Software\StrongNameingKey.snk</AssemblyOriginatorKeyFile> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'"> @@ -34,11 +35,10 @@ <ProjectReference Include="..\..\..\..\VNLib\Http\src\VNLib.Net.Http.csproj" /> <ProjectReference Include="..\..\..\..\VNLib\Plugins\src\VNLib.Plugins.csproj" /> <ProjectReference Include="..\..\..\..\VNLib\Utils\src\VNLib.Utils.csproj" /> - <ProjectReference Include="..\..\..\DataCaching\VNLib.Data.Caching.Extensions\VNLib.Data.Caching.Extensions.csproj" /> - <ProjectReference Include="..\..\..\DataCaching\VNLib.Data.Caching\src\VNLib.Data.Caching.csproj" /> <ProjectReference Include="..\..\..\Extensions\VNLib.Plugins.Extensions.Loading.Sql\VNLib.Plugins.Extensions.Loading.Sql.csproj" /> <ProjectReference Include="..\..\..\Extensions\VNLib.Plugins.Extensions.Loading\VNLib.Plugins.Extensions.Loading.csproj" /> <ProjectReference Include="..\..\..\Extensions\VNLib.Plugins.Extensions.Validation\VNLib.Plugins.Extensions.Validation.csproj" /> + <ProjectReference Include="..\..\..\Extensions\VNLib.Plugins.Extensions.VNCache\VNLib.Plugins.Extensions.VNCache.csproj" /> <ProjectReference Include="..\..\..\Oauth\Libs\VNLib.Plugins.Essentials.Oauth\VNLib.Plugins.Essentials.Oauth.csproj" /> <ProjectReference Include="..\..\..\PluginBase\VNLib.Plugins.PluginBase.csproj" /> <ProjectReference Include="..\VNLib.Plugins.Essentials.Sessions.Runtime\VNLib.Plugins.Essentials.Sessions.Runtime.csproj" /> |