From 86814e447715bd4557c3f727a0701ff838345580 Mon Sep 17 00:00:00 2001 From: "Rian.be" Date: Thu, 3 Sep 2026 20:52:06 +0200 Subject: [PATCH 01/18] feat: add plugin contract validation tool --- .../PluginAssemblyLoader.cs | 128 ++++++++++++++++++ tools/PluginContractValidator/Program.cs | 65 +++++++++ .../src/Core/ContractValidator.cs | 34 +++++ .../src/Core/IPluginContractRule.cs | 26 ++++ .../src/Core/IPluginLoader.cs | 20 +++ .../src/Core/LoadedPlugin.cs | 28 ++++ .../src/Core/PluginLoadResult.cs | 18 +++ .../src/Rules/HealthRule.cs | 64 +++++++++ .../src/Rules/MetadataRule.cs | 32 +++++ .../src/Rules/MiddlewareRule.cs | 80 +++++++++++ .../src/Rules/RegistrationRule.cs | 54 ++++++++ .../src/Rules/SecuritySchemesRule.cs | 57 ++++++++ 12 files changed, 606 insertions(+) create mode 100644 tools/PluginContractValidator/PluginAssemblyLoader.cs create mode 100644 tools/PluginContractValidator/Program.cs create mode 100644 tools/PluginContractValidator/src/Core/ContractValidator.cs create mode 100644 tools/PluginContractValidator/src/Core/IPluginContractRule.cs create mode 100644 tools/PluginContractValidator/src/Core/IPluginLoader.cs create mode 100644 tools/PluginContractValidator/src/Core/LoadedPlugin.cs create mode 100644 tools/PluginContractValidator/src/Core/PluginLoadResult.cs create mode 100644 tools/PluginContractValidator/src/Rules/HealthRule.cs create mode 100644 tools/PluginContractValidator/src/Rules/MetadataRule.cs create mode 100644 tools/PluginContractValidator/src/Rules/MiddlewareRule.cs create mode 100644 tools/PluginContractValidator/src/Rules/RegistrationRule.cs create mode 100644 tools/PluginContractValidator/src/Rules/SecuritySchemesRule.cs diff --git a/tools/PluginContractValidator/PluginAssemblyLoader.cs b/tools/PluginContractValidator/PluginAssemblyLoader.cs new file mode 100644 index 0000000..42fa10b --- /dev/null +++ b/tools/PluginContractValidator/PluginAssemblyLoader.cs @@ -0,0 +1,128 @@ +using System.Reflection; +using System.Runtime.Loader; +using AuthKit.Plugins.Abstractions.Contracts; +using PluginContractValidator.Core; + +namespace PluginContractValidator; + +/// +/// Loads a plugin entry assembly using the same isolation model as the AuthKit host. +/// +/// +/// +/// Each plugin resolves its own dependencies through an +/// attached to . The resolver stays attached for the +/// lifetime of the process so that lazily loaded dependencies (for example, types referenced +/// inside CheckHealthAsync) continue to resolve, exactly as in the host. +/// +/// +/// A plugin directory is expected to contain an entry assembly whose file name matches the +/// directory name. Directories without a matching assembly, or assemblies without a public, +/// non-abstract implementation with a parameterless constructor, +/// are reported as load errors rather than thrown. +/// +/// +public sealed class PluginAssemblyLoader : IPluginLoader +{ + private static readonly List Resolvers = new(); + private static readonly Lock Gate = new(); + private static Func? _handler; + + /// + /// Loads the plugin entry assembly and activates its implementation. + /// + /// The full path to the plugin's entry assembly. + /// + /// A containing the loaded plugin, or the errors that + /// prevented loading. + /// + public PluginLoadResult Load(string entryDll) + { + var errors = new List(); + + try + { + var resolver = new AssemblyDependencyResolver(entryDll); + AttachResolver(resolver); + + Assembly assembly; + try + { + assembly = AssemblyLoadContext.Default.LoadFromAssemblyPath(entryDll); + } + catch (Exception ex) + { + errors.Add($"dependency loading failed: {ex.Message}"); + return new PluginLoadResult(null, errors); + } + + Type? pluginType; + try + { + pluginType = assembly.GetTypes() + .FirstOrDefault(t => t is { IsPublic: true, IsAbstract: false } + && typeof(IAuthKitPlugin).IsAssignableFrom(t) + && t.GetConstructor(Type.EmptyTypes) is not null); + } + catch (Exception ex) + { + errors.Add($"type discovery failed: {ex.Message}"); + return new PluginLoadResult(null, errors); + } + + if (pluginType is null) + { + errors.Add("no public, non-abstract IAuthKitPlugin implementation with a parameterless constructor"); + return new PluginLoadResult(null, errors); + } + + IAuthKitPlugin instance; + try + { + instance = (IAuthKitPlugin)Activator.CreateInstance(pluginType)!; + } + catch (Exception ex) + { + errors.Add($"activation failed: {ex.Message}"); + return new PluginLoadResult(null, errors); + } + + return new PluginLoadResult(new LoadedPlugin(instance, assembly), errors); + } + catch (Exception ex) + { + errors.Add($"unexpected error: {ex.Message}"); + return new PluginLoadResult(null, errors); + } + } + + /// + /// Registers a dependency resolver for , ensuring it + /// is attached exactly once for the lifetime of the process. + /// + /// The dependency resolver associated with a loaded plugin assembly. + private static void AttachResolver(AssemblyDependencyResolver resolver) + { + lock (Gate) + { + Resolvers.Add(resolver); + if (_handler is not null) return; + + _handler = (context, name) => + { + for (var i = Resolvers.Count - 1; i >= 0; i--) + { + var path = Resolvers[i].ResolveAssemblyToPath(name); + if (path is not null) + { + return context.LoadFromAssemblyPath(path); + } + } + + return null; + }; + + AssemblyLoadContext.Default.Resolving += _handler; + } + } +} diff --git a/tools/PluginContractValidator/Program.cs b/tools/PluginContractValidator/Program.cs new file mode 100644 index 0000000..e362f14 --- /dev/null +++ b/tools/PluginContractValidator/Program.cs @@ -0,0 +1,65 @@ +using PluginContractValidator; +using PluginContractValidator.Core; +using PluginContractValidator.Rules; + +var pluginsRoot = args.Length > 0 ? args[0] : "src/Plugins"; + +if (!Directory.Exists(pluginsRoot)) +{ + Console.Error.WriteLine($"Plugins root not found: {pluginsRoot}"); + return 1; +} + +IPluginLoader loader = new PluginAssemblyLoader(); +var validator = new ContractValidator([ + new MetadataRule(), + new RegistrationRule(), + new SecuritySchemesRule(), + new MiddlewareRule(), + new HealthRule() +]); + +var failures = 0; + +foreach (var pluginDir in Directory.GetDirectories(pluginsRoot)) +{ + var pluginName = Path.GetFileName(pluginDir.TrimEnd(Path.DirectorySeparatorChar)); + var entryDll = Path.Combine(pluginDir, $"{pluginName}.dll"); + + if (!File.Exists(entryDll)) + { + Console.WriteLine($"[SKIP] {pluginName}: entry assembly '{entryDll}' not found"); + continue; + } + + var loadResult = loader.Load(entryDll); + if (!loadResult.Succeeded) + { + failures++; + Console.WriteLine($"[FAIL] {pluginName}"); + foreach (var error in loadResult.Errors) + { + Console.WriteLine($" - {error}"); + } + + continue; + } + + var errors = await validator.ValidateAsync(loadResult.Plugin!); + + if (errors.Count == 0) + { + Console.WriteLine($"[PASS] {pluginName} v{loadResult.Plugin!.Instance.Version}"); + } + else + { + failures++; + Console.WriteLine($"[FAIL] {pluginName}"); + foreach (var error in errors) + { + Console.WriteLine($" - {error}"); + } + } +} + +return failures == 0 ? 0 : 1; diff --git a/tools/PluginContractValidator/src/Core/ContractValidator.cs b/tools/PluginContractValidator/src/Core/ContractValidator.cs new file mode 100644 index 0000000..e096251 --- /dev/null +++ b/tools/PluginContractValidator/src/Core/ContractValidator.cs @@ -0,0 +1,34 @@ +namespace PluginContractValidator.Core; + +/// +/// Runs every registered against a loaded plugin and +/// aggregates the resulting contract violations. +/// +/// +/// Rules are executed sequentially; each rule's violations are collected into a single +/// combined list so the caller sees every problem at once. +/// +/// The contract rules to execute for each plugin. +public sealed class ContractValidator(IEnumerable rules) +{ + /// + /// Validates the supplied plugin against all registered rules. + /// + /// The loaded plugin to validate. + /// A token that can be used to cancel the validation. + /// The aggregated, read-only list of contract violations. + public async Task> ValidateAsync( + LoadedPlugin plugin, + CancellationToken cancellationToken = default) + { + var errors = new List(); + + foreach (var rule in rules) + { + cancellationToken.ThrowIfCancellationRequested(); + errors.AddRange(await rule.ValidateAsync(plugin, cancellationToken)); + } + + return errors; + } +} diff --git a/tools/PluginContractValidator/src/Core/IPluginContractRule.cs b/tools/PluginContractValidator/src/Core/IPluginContractRule.cs new file mode 100644 index 0000000..b5bd61b --- /dev/null +++ b/tools/PluginContractValidator/src/Core/IPluginContractRule.cs @@ -0,0 +1,26 @@ +namespace PluginContractValidator.Core; + +/// +/// Validates single contract concern of loaded plugin. +/// +/// +/// Rules are composed by and executed independently, so a +/// failure in one concern does not prevent the others from being evaluated. +/// +public interface IPluginContractRule +{ + /// + /// Gets a name of the validated contract concern (for example, "Metadata"). + /// + string Name { get; } + + /// + /// Validates the plugin and returns the list of contract violations. + /// + /// The loaded plugin to validate. + /// A token that can be used to cancel the validation. + /// + /// A read-only list of violation messages. An empty list means the rule passed. + /// + Task> ValidateAsync(LoadedPlugin plugin, CancellationToken cancellationToken = default); +} diff --git a/tools/PluginContractValidator/src/Core/IPluginLoader.cs b/tools/PluginContractValidator/src/Core/IPluginLoader.cs new file mode 100644 index 0000000..840f6a6 --- /dev/null +++ b/tools/PluginContractValidator/src/Core/IPluginLoader.cs @@ -0,0 +1,20 @@ +using AuthKit.Plugins.Abstractions.Contracts; + +namespace PluginContractValidator.Core; + +/// +/// Loads a plugin entry assembly and instantiates its implementation. +/// +public interface IPluginLoader +{ + /// + /// Loads the plugin entry assembly located at and activates its + /// implementation. + /// + /// The full path to the plugin's entry assembly (named after its directory). + /// + /// A describing the loaded plugin, or the errors encountered + /// while loading it. + /// + PluginLoadResult Load(string entryDll); +} diff --git a/tools/PluginContractValidator/src/Core/LoadedPlugin.cs b/tools/PluginContractValidator/src/Core/LoadedPlugin.cs new file mode 100644 index 0000000..0344c1f --- /dev/null +++ b/tools/PluginContractValidator/src/Core/LoadedPlugin.cs @@ -0,0 +1,28 @@ +using System.Reflection; +using AuthKit.Plugins.Abstractions.Contracts; + +namespace PluginContractValidator.Core; + +/// +/// Represents a plugin assembly that has been successfully loaded and instantiated +/// by the validation host. +/// +/// +/// The wrapper keeps both the activated instance and the +/// it was loaded from, so that individual contract rules can +/// inspect runtime metadata without re-loading the assembly. +/// +/// The activated plugin instance implementing . +/// The assembly the plugin type was loaded from. +public sealed class LoadedPlugin(IAuthKitPlugin instance, Assembly assembly) +{ + /// + /// Gets the activated plugin instance implementing . + /// + public IAuthKitPlugin Instance { get; } = instance; + + /// + /// Gets the assembly the plugin type was loaded from. + /// + public Assembly Assembly { get; } = assembly; +} diff --git a/tools/PluginContractValidator/src/Core/PluginLoadResult.cs b/tools/PluginContractValidator/src/Core/PluginLoadResult.cs new file mode 100644 index 0000000..884f18f --- /dev/null +++ b/tools/PluginContractValidator/src/Core/PluginLoadResult.cs @@ -0,0 +1,18 @@ +namespace PluginContractValidator.Core; + +/// +/// Encapsulates the outcome of attempting to load a plugin assembly. +/// +/// +/// When loading fails, is null and +/// contains the human-readable reasons for the failure. +/// +/// The loaded plugin, or null when loading failed. +/// The list of contract or loading violations encountered. +public sealed record PluginLoadResult(LoadedPlugin? Plugin, IReadOnlyList Errors) +{ + /// + /// Gets a value indicating whether the plugin was loaded successfully. + /// + public bool Succeeded => Plugin is not null; +} diff --git a/tools/PluginContractValidator/src/Rules/HealthRule.cs b/tools/PluginContractValidator/src/Rules/HealthRule.cs new file mode 100644 index 0000000..7d4e55a --- /dev/null +++ b/tools/PluginContractValidator/src/Rules/HealthRule.cs @@ -0,0 +1,64 @@ +using AuthKit.Plugins.Abstractions.Contracts; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using PluginContractValidator.Core; + +namespace PluginContractValidator.Rules; + +/// +/// Ensures the plugin can configure its services and that +/// CheckHealthAsync completes without throwing. +/// +/// +/// The rule builds an isolated service provider from the services registered +/// by the plugin and invokes . +/// Any exception during service configuration or health checking is reported +/// as a contract violation. +/// +public sealed class HealthRule : IPluginContractRule +{ + /// Gets the rule name ("Health"). + public string Name => "Health"; + + /// + /// Validates plugin service configuration and health checking. + /// + /// The loaded plugin to validate. + /// + /// A token that can be used to cancel the validation. + /// + /// + /// The list of health-related violations; empty when service configuration + /// and the health check complete without throwing. + /// + public async Task> ValidateAsync( + LoadedPlugin plugin, + CancellationToken cancellationToken = default) + { + var errors = new List(); + var services = new ServiceCollection(); + var configuration = new ConfigurationBuilder().Build(); + + try + { + plugin.Instance.ConfigureServices(services, configuration); + } + catch (Exception ex) + { + errors.Add($"health: ConfigureServices threw: {ex.Message}"); + return errors; + } + + try + { + await using var provider = services.BuildServiceProvider(); + await plugin.Instance.CheckHealthAsync(provider); + } + catch (Exception ex) + { + errors.Add($"health: CheckHealthAsync threw: {ex.Message}"); + } + + return errors; + } +} \ No newline at end of file diff --git a/tools/PluginContractValidator/src/Rules/MetadataRule.cs b/tools/PluginContractValidator/src/Rules/MetadataRule.cs new file mode 100644 index 0000000..17562ce --- /dev/null +++ b/tools/PluginContractValidator/src/Rules/MetadataRule.cs @@ -0,0 +1,32 @@ +using AuthKit.Plugins.Abstractions.Contracts; +using PluginContractValidator.Core; + +namespace PluginContractValidator.Rules; + +/// +/// Ensures plugin metadata (Name, Version) is present and well-formed. +/// +/// +/// The rule verifies that is non-empty and that +/// follows the SemVer +/// (major.minor.patch[-prerelease]) format expected by the host. +/// +public sealed class MetadataRule : IPluginContractRule +{ + public string Name => "Metadata"; + + public Task> ValidateAsync( + LoadedPlugin plugin, + CancellationToken cancellationToken = default) + { + var errors = new List(); + var instance = plugin.Instance; + + if (string.IsNullOrWhiteSpace(instance.Name)) + { + errors.Add("metadata: Name is null or empty"); + } + + return Task.FromResult>(errors); + } +} \ No newline at end of file diff --git a/tools/PluginContractValidator/src/Rules/MiddlewareRule.cs b/tools/PluginContractValidator/src/Rules/MiddlewareRule.cs new file mode 100644 index 0000000..a0ce298 --- /dev/null +++ b/tools/PluginContractValidator/src/Rules/MiddlewareRule.cs @@ -0,0 +1,80 @@ +using AuthKit.Plugins.Abstractions; +using AuthKit.Plugins.Abstractions.Contracts; +using Microsoft.AspNetCore.Http; +using PluginContractValidator.Core; + +namespace PluginContractValidator.Rules; + +/// +/// Ensures a contributed middleware type follows the AuthKit middleware convention. +/// +/// +/// The middleware type must expose a constructor accepting +/// and a public InvokeAsync method +/// whose first parameter is and whose return type is +/// . +/// +public sealed class MiddlewareRule : IPluginContractRule +{ + /// Gets the rule name ("Middleware"). + public string Name => "Middleware"; + + /// + /// Validates the middleware type contributed by + /// , if any. + /// + public Task> ValidateAsync( + LoadedPlugin plugin, + CancellationToken cancellationToken = default) + { + var errors = new List(); + var middlewareType = plugin.Instance.MiddlewareType; + + if (middlewareType is null) + return Task.FromResult>(errors); + + if (!HasRequestDelegateConstructor(middlewareType)) + { + errors.Add($"middleware: MiddlewareType '{middlewareType.Name}' " + + "must have constructor accepting RequestDelegate."); + } + + var invokeMethod = middlewareType.GetMethod( + "InvokeAsync", + System.Reflection.BindingFlags.Public | + System.Reflection.BindingFlags.Instance); + + if (invokeMethod is null) + { + errors.Add($"middleware: MiddlewareType '{middlewareType.Name}' " + + "must expose public instance InvokeAsync method."); + + return Task.FromResult>(errors); + } + + if (invokeMethod.ReturnType != typeof(Task)) + { + errors.Add($"middleware: InvokeAsync on '{middlewareType.Name}' " + + "must return Task."); + } + + var parameters = invokeMethod.GetParameters(); + + if (parameters.Length == 0 || + parameters[0].ParameterType != typeof(HttpContext)) + { + errors.Add($"middleware: InvokeAsync on '{middlewareType.Name}' " + + "must take HttpContext as its first parameter."); + } + + return Task.FromResult>(errors); + } + + private static bool HasRequestDelegateConstructor(Type middlewareType) + { + return middlewareType + .GetConstructors() + .Any(constructor => constructor.GetParameters() + .Any(parameter => parameter.ParameterType == typeof(RequestDelegate))); + } +} \ No newline at end of file diff --git a/tools/PluginContractValidator/src/Rules/RegistrationRule.cs b/tools/PluginContractValidator/src/Rules/RegistrationRule.cs new file mode 100644 index 0000000..d89a0d1 --- /dev/null +++ b/tools/PluginContractValidator/src/Rules/RegistrationRule.cs @@ -0,0 +1,54 @@ +using AuthKit.Plugins.Abstractions.Contracts; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using PluginContractValidator.Core; + +namespace PluginContractValidator.Rules; + +/// +/// Ensures ConfigureServices registers dependencies without throwing and that the +/// resulting service container can be built (dependency wiring is valid). +/// +public sealed class RegistrationRule : IPluginContractRule +{ + /// Gets the rule name ("Registration"). + public string Name => "Registration"; + + /// + /// Invokes against a fresh service collection + /// and then builds the to confirm the dependency graph is + /// constructible. + /// + /// The loaded plugin to validate. + /// A token that can be used to cancel the validation. + /// The list of registration violations; empty when registration succeeds. + public Task> ValidateAsync( + LoadedPlugin plugin, + CancellationToken cancellationToken = default) + { + var errors = new List(); + var services = new ServiceCollection(); + var configuration = new ConfigurationBuilder().Build(); + + try + { + plugin.Instance.ConfigureServices(services, configuration); + } + catch (Exception ex) + { + errors.Add($"registration: ConfigureServices threw: {ex.Message}"); + return Task.FromResult>(errors); + } + + try + { + services.BuildServiceProvider(); + } + catch (Exception ex) + { + errors.Add($"registration: service provider build failed (bad dependency wiring): {ex.Message}"); + } + + return Task.FromResult>(errors); + } +} diff --git a/tools/PluginContractValidator/src/Rules/SecuritySchemesRule.cs b/tools/PluginContractValidator/src/Rules/SecuritySchemesRule.cs new file mode 100644 index 0000000..d4bea2c --- /dev/null +++ b/tools/PluginContractValidator/src/Rules/SecuritySchemesRule.cs @@ -0,0 +1,57 @@ +using AuthKit.Plugins.Abstractions; +using AuthKit.Plugins.Abstractions.Contracts; +using PluginContractValidator.Core; + +namespace PluginContractValidator.Rules; + +/// +/// Ensures contributed OpenAPI security schemes are present and consistently keyed. +/// +/// +/// The rule verifies that each key in the dictionary returned by +/// matches the Name of its +/// . +/// +public sealed class SecuritySchemesRule : IPluginContractRule +{ + /// + /// Gets the rule name ("SecuritySchemes"). + /// + public string Name => "SecuritySchemes"; + + /// + /// Validates the security schemes contributed by the plugin. + /// + /// The loaded plugin to validate. + /// + /// A token that can be used to cancel the validation. + /// + /// + /// The list of security-scheme violations; empty when the schemes are valid. + /// + public Task> ValidateAsync( + LoadedPlugin plugin, + CancellationToken cancellationToken = default) + { + var errors = new List(); + + try + { + var schemes = plugin.Instance.GetSecuritySchemes(); + + foreach (var pair in schemes) + { + if (pair.Key != pair.Value.Name) + { + errors.Add($"security schemes: key '{pair.Key}' does not match descriptor Name '{pair.Value.Name}'"); + } + } + } + catch (Exception ex) + { + errors.Add($"security schemes: GetSecuritySchemes threw: {ex.Message}"); + } + + return Task.FromResult>(errors); + } +} \ No newline at end of file From 89c847f75f2fc4b06a1d484092e4456dde4856ad Mon Sep 17 00:00:00 2001 From: "Rian.be" Date: Thu, 3 Sep 2026 20:57:09 +0200 Subject: [PATCH 02/18] refactor: relocate security scheme contracts and update references --- AuthKit.sln.DotSettings | 1 + src/Host/Configuration/RestfulConfiguration.cs | 1 + .../SecuritySchemes}/AuthKitSecuritySchemeDescriptor.cs | 6 +++--- .../SecuritySchemes}/AuthKitSecuritySchemeType.cs | 4 +++- tools/PluginContractValidator/src/Core/IPluginLoader.cs | 2 +- 5 files changed, 9 insertions(+), 5 deletions(-) rename src/Plugins/Abstractions/{ => Contracts/SecuritySchemes}/AuthKitSecuritySchemeDescriptor.cs (90%) rename src/Plugins/Abstractions/{ => Contracts/SecuritySchemes}/AuthKitSecuritySchemeType.cs (93%) diff --git a/AuthKit.sln.DotSettings b/AuthKit.sln.DotSettings index 5aebc62..be949ca 100644 --- a/AuthKit.sln.DotSettings +++ b/AuthKit.sln.DotSettings @@ -1,3 +1,4 @@  True + True True \ No newline at end of file diff --git a/src/Host/Configuration/RestfulConfiguration.cs b/src/Host/Configuration/RestfulConfiguration.cs index c020451..d0bea77 100644 --- a/src/Host/Configuration/RestfulConfiguration.cs +++ b/src/Host/Configuration/RestfulConfiguration.cs @@ -1,4 +1,5 @@ using AuthKit.Plugins.Abstractions; +using AuthKit.Plugins.Abstractions.Contracts.SecuritySchemes; using Host.Plugins; using Microsoft.OpenApi.Models; diff --git a/src/Plugins/Abstractions/AuthKitSecuritySchemeDescriptor.cs b/src/Plugins/Abstractions/Contracts/SecuritySchemes/AuthKitSecuritySchemeDescriptor.cs similarity index 90% rename from src/Plugins/Abstractions/AuthKitSecuritySchemeDescriptor.cs rename to src/Plugins/Abstractions/Contracts/SecuritySchemes/AuthKitSecuritySchemeDescriptor.cs index 0167bec..f23243f 100644 --- a/src/Plugins/Abstractions/AuthKitSecuritySchemeDescriptor.cs +++ b/src/Plugins/Abstractions/Contracts/SecuritySchemes/AuthKitSecuritySchemeDescriptor.cs @@ -1,12 +1,12 @@ -namespace AuthKit.Plugins.Abstractions; +namespace AuthKit.Plugins.Abstractions.Contracts.SecuritySchemes; /// -/// Describes security scheme exposed by an AuthKit authentication plugin. +/// Describes a security scheme exposed by an AuthKit authentication plugin. /// /// /// /// provides transport-agnostic -/// metadata describing how client authenticates when communicating with +/// metadata describing how a client authenticates when communicating with /// service protected by AuthKit. /// /// diff --git a/src/Plugins/Abstractions/AuthKitSecuritySchemeType.cs b/src/Plugins/Abstractions/Contracts/SecuritySchemes/AuthKitSecuritySchemeType.cs similarity index 93% rename from src/Plugins/Abstractions/AuthKitSecuritySchemeType.cs rename to src/Plugins/Abstractions/Contracts/SecuritySchemes/AuthKitSecuritySchemeType.cs index ca82ca3..5b296a8 100644 --- a/src/Plugins/Abstractions/AuthKitSecuritySchemeType.cs +++ b/src/Plugins/Abstractions/Contracts/SecuritySchemes/AuthKitSecuritySchemeType.cs @@ -1,3 +1,5 @@ +using AuthKit.Plugins.Abstractions.Contracts.SecuritySchemes; + namespace AuthKit.Plugins.Abstractions; /// @@ -43,7 +45,7 @@ public enum AuthKitSecuritySchemeType /// /// /// OAuth 2.0 schemes describe authorization flows in which a client - /// obtains an access token from an authorization server and presents + /// gets an access token from an authorization server and presents /// that token when accessing protected resources. /// OAuth2, diff --git a/tools/PluginContractValidator/src/Core/IPluginLoader.cs b/tools/PluginContractValidator/src/Core/IPluginLoader.cs index 840f6a6..1c36a62 100644 --- a/tools/PluginContractValidator/src/Core/IPluginLoader.cs +++ b/tools/PluginContractValidator/src/Core/IPluginLoader.cs @@ -3,7 +3,7 @@ namespace PluginContractValidator.Core; /// -/// Loads a plugin entry assembly and instantiates its implementation. +/// Loads plugin entry assembly and instantiates its implementation. /// public interface IPluginLoader { From 97f3883d6b4fc1480eb1a247b0005d1763940cb3 Mon Sep 17 00:00:00 2001 From: "Rian.be" Date: Thu, 3 Sep 2026 21:16:03 +0200 Subject: [PATCH 03/18] feat: add plugin validation and extension utilities --- .../Abstractions/Contracts/PluginValidator.cs | 144 ++++++++++++++++++ .../Contracts/Plugins/PluginExtensions.cs | 59 +++++++ .../Plugins/PluginMetadataExtensions.cs | 41 +++++ 3 files changed, 244 insertions(+) create mode 100644 src/Plugins/Abstractions/Contracts/PluginValidator.cs create mode 100644 src/Plugins/Abstractions/Contracts/Plugins/PluginExtensions.cs create mode 100644 src/Plugins/Abstractions/Contracts/Plugins/PluginMetadataExtensions.cs diff --git a/src/Plugins/Abstractions/Contracts/PluginValidator.cs b/src/Plugins/Abstractions/Contracts/PluginValidator.cs new file mode 100644 index 0000000..5789c18 --- /dev/null +++ b/src/Plugins/Abstractions/Contracts/PluginValidator.cs @@ -0,0 +1,144 @@ +using AuthKit.Plugins.Abstractions.Models; + +namespace AuthKit.Plugins.Abstractions.Contracts; + +/// +/// Provides validation logic for plugin consistency between manifest and instance. +/// +public static class PluginValidator +{ + /// + /// Validates that a tag is not null or whitespace. + /// + /// The tag to validate. + /// Thrown if the tag is null or whitespace. + private static void ValidateTag(string tag) + { + if (string.IsNullOrWhiteSpace(tag)) + { + throw new ArgumentException("Tags cannot be null or whitespace.", nameof(tag)); + } + } + + /// + /// Validates that all tags in a list are valid (non-null and non-whitespace). + /// + /// The list of tags to validate. + /// Thrown if any tag is null or whitespace. + public static void ValidateTags(IReadOnlyList tags) + { + if (tags == null) + { + throw new ArgumentNullException(nameof(tags), "Tags list cannot be null."); + } + + foreach (var tag in tags) + { + ValidateTag(tag); + } + } + + /// + /// Validates that a plugin ID is not empty and follows the expected format. + /// + /// The plugin ID to validate. + /// Thrown if the plugin ID is null, empty, or whitespace. + private static void ValidatePluginId(string pluginId) + { + if (string.IsNullOrWhiteSpace(pluginId)) + { + throw new ArgumentException("Plugin ID cannot be null, empty, or whitespace.", nameof(pluginId)); + } + } + + /// + /// Validates that a list of dependency IDs is valid. + /// + /// The list of dependency IDs to validate. + /// The ID of the plugin being validated (to check for self-dependency). + /// Thrown if any dependency ID is invalid or if there are duplicates. + /// Thrown if there is a self-dependency. + public static void ValidateDependsOn(IReadOnlyList dependsOn, string pluginId) + { + if (dependsOn == null) + { + throw new ArgumentNullException(nameof(dependsOn), "Dependencies list cannot be null."); + } + + // Check for duplicates + var uniqueDependencies = new HashSet(StringComparer.OrdinalIgnoreCase); + foreach (var dependencyId in dependsOn) + { + ValidatePluginId(dependencyId); + + if (!uniqueDependencies.Add(dependencyId)) + { + throw new ArgumentException("Duplicate dependency ID found: "+ dependencyId); + } + } + + // Check for self-dependency + if (dependsOn.Contains(pluginId, StringComparer.OrdinalIgnoreCase)) + { + throw new InvalidOperationException("Plugin cannot depend on itself."); + } + } + + /// + /// Validates that the plugin manifest and instance are consistent. + /// + /// The plugin manifest. + /// The plugin instance. + /// Thrown if either manifest or plugin is null. + /// Thrown if the manifest and instance are inconsistent. + public static void ValidateConsistency(PluginManifest manifest, IAuthKitPlugin plugin) + { + if (manifest == null) + { + throw new ArgumentNullException(nameof(manifest), "Plugin manifest cannot be null."); + } + + if (plugin == null) + { + throw new ArgumentNullException(nameof(plugin), "Plugin instance cannot be null."); + } + + // Check if IsEnabled matches + if (manifest.IsEnabled != plugin.IsEnabled) + { + throw new InvalidOperationException( + "Manifest and plugin instance disagree on IsEnabled."); + } + + // Check if Capabilities match (case-insensitive comparison) + if (!manifest.Capabilities.SetEquals(plugin.Capabilities)) + { + throw new InvalidOperationException( + "Manifest and plugin instance have inconsistent capabilities."); + } + + // Check if MinHostVersion matches + if (manifest.MinHostVersion != plugin.MinHostVersion) + { + throw new InvalidOperationException( + "Manifest and plugin instance disagree on MinHostVersion."); + } + + // Check if DependsOn matches (case-insensitive comparison) + if (manifest.DependsOn.Count != plugin.DependsOn.Count) + { + throw new InvalidOperationException( + "Manifest and plugin instance have different number of dependencies."); + } + + // Compare each dependency case-insensitively + var manifestDependsOnSet = new HashSet(manifest.DependsOn, StringComparer.OrdinalIgnoreCase); + var pluginDependsOnSet = new HashSet(plugin.DependsOn, StringComparer.OrdinalIgnoreCase); + + if (!manifestDependsOnSet.SetEquals(pluginDependsOnSet)) + { + throw new InvalidOperationException( + "Manifest and plugin instance have inconsistent dependencies."); + } + } +} \ No newline at end of file diff --git a/src/Plugins/Abstractions/Contracts/Plugins/PluginExtensions.cs b/src/Plugins/Abstractions/Contracts/Plugins/PluginExtensions.cs new file mode 100644 index 0000000..04126fc --- /dev/null +++ b/src/Plugins/Abstractions/Contracts/Plugins/PluginExtensions.cs @@ -0,0 +1,59 @@ +using AuthKit.Plugins.Abstractions.Models; + +namespace AuthKit.Plugins.Abstractions.Contracts.Plugins; + +/// +/// Extension methods for plugin capabilities and metadata. +/// +public static class PluginExtensions +{ + /// + /// Checks if the plugin supports the specified capability. + /// + /// The plugin instance. + /// The ability to check. + /// true if the plugin supports the capability; otherwise, false. + /// + /// The comparison is case-insensitive. + /// + public static bool Supports(this IAuthKitPlugin plugin, string capability) => + plugin == null + ? throw new ArgumentNullException(nameof(plugin)) + : plugin.Capabilities.Contains(capability, StringComparer.OrdinalIgnoreCase); + + /// + /// Checks if the plugin manifest supports the specified capability. + /// + /// The plugin manifest. + /// The ability to check. + /// true if the manifest supports the capability; otherwise, false. + /// + /// The comparison is case-insensitive. + /// + public static bool Supports(this PluginManifest manifest, string capability) => + manifest == null + ? throw new ArgumentNullException(nameof(manifest)) + : manifest.Capabilities.Contains(capability, StringComparer.OrdinalIgnoreCase); + + /// + /// Checks if the plugin has the specified dependency. + /// + /// The plugin instance. + /// The dependency ID to check. + /// true if the plugin depends on the specified dependency; otherwise, false. + public static bool HasDependency(this IAuthKitPlugin plugin, string dependencyId) => + plugin == null + ? throw new ArgumentNullException(nameof(plugin)) + : plugin.DependsOn.Contains(dependencyId, StringComparer.OrdinalIgnoreCase); + + /// + /// Checks if the plugin manifest has the specified dependency. + /// + /// The plugin manifest. + /// The dependency ID to check. + /// true if the manifest declares the specified dependency; otherwise, false. + public static bool HasDependency(this PluginManifest manifest, string dependencyId) => + manifest == null + ? throw new ArgumentNullException(nameof(manifest)) + : manifest.DependsOn.Contains(dependencyId, StringComparer.OrdinalIgnoreCase); +} \ No newline at end of file diff --git a/src/Plugins/Abstractions/Contracts/Plugins/PluginMetadataExtensions.cs b/src/Plugins/Abstractions/Contracts/Plugins/PluginMetadataExtensions.cs new file mode 100644 index 0000000..63faedc --- /dev/null +++ b/src/Plugins/Abstractions/Contracts/Plugins/PluginMetadataExtensions.cs @@ -0,0 +1,41 @@ +using System.Collections.Immutable; +using AuthKit.Plugins.Abstractions.Models; + +namespace AuthKit.Plugins.Abstractions.Contracts.Plugins; + +/// +/// Provides extension methods for working with plugin metadata. +/// +public static class PluginMetadataExtensions +{ + /// + /// Creates an immutable snapshot of the plugin's metadata. + /// + /// The plugin instance. + /// An immutable record. + /// Thrown if the plugin is null. + public static PluginMetadata GetMetadata(this IAuthKitPlugin plugin) + { + ArgumentNullException.ThrowIfNull(plugin); + + return new PluginMetadata + { + Id = plugin.Id, + Name = plugin.Name, + Description = plugin.Description ?? string.Empty, + Version = plugin.Version, + Author = plugin.Author, + License = plugin.License, + LicenseUrl = plugin.LicenseUrl, + Homepage = plugin.Homepage, + RepositoryUrl = plugin.RepositoryUrl, + Tags = plugin.Tags.ToArray(), + Priority = plugin.Priority, + IsEnabled = plugin.IsEnabled, + MinHostVersion = plugin.MinHostVersion, + DependsOn = plugin.DependsOn.ToArray(), + Capabilities = plugin.Capabilities.ToImmutableHashSet(StringComparer.OrdinalIgnoreCase), + DisplayName = plugin.DisplayName + }; + } +} \ No newline at end of file From f47fa6d0b61ff1641490f759a04f06532251b1cc Mon Sep 17 00:00:00 2001 From: "Rian.be" Date: Thu, 3 Sep 2026 21:16:53 +0200 Subject: [PATCH 04/18] feat: add plugin metadata and semantic version types --- .../Abstractions/Models/PluginManifest.cs | 85 +++++ .../Abstractions/Models/PluginMetadata.cs | 95 ++++++ .../Abstractions/Models/SemanticVersion.cs | 318 ++++++++++++++++++ .../Models/SemanticVersionJsonConverter.cs | 44 +++ 4 files changed, 542 insertions(+) create mode 100644 src/Plugins/Abstractions/Models/PluginManifest.cs create mode 100644 src/Plugins/Abstractions/Models/PluginMetadata.cs create mode 100644 src/Plugins/Abstractions/Models/SemanticVersion.cs create mode 100644 src/Plugins/Abstractions/Models/SemanticVersionJsonConverter.cs diff --git a/src/Plugins/Abstractions/Models/PluginManifest.cs b/src/Plugins/Abstractions/Models/PluginManifest.cs new file mode 100644 index 0000000..2180060 --- /dev/null +++ b/src/Plugins/Abstractions/Models/PluginManifest.cs @@ -0,0 +1,85 @@ +using System.Collections.Immutable; +using AuthKit.Plugins.Abstractions.Contracts; +using AuthKit.Plugins.Abstractions.Contracts.Plugins; + +namespace AuthKit.Plugins.Abstractions.Models; + +/// +/// Projection of plugin metadata available before activation. +/// This surface mirrors selected runtime members of . +/// +public sealed record PluginManifest +{ + public string Id { get; init; } = string.Empty; + public string Name { get; init; } = string.Empty; + public string? DisplayName { get; init; } + public string? Description { get; init; } + public SemanticVersion Version { get; init; } = new(0,0,0); + public string? Author { get; init; } + public string? License { get; init; } + public string? LicenseUrl { get; init; } + public string? Homepage { get; init; } + public string? RepositoryUrl { get; init; } + + /// + /// Optional classification tags for UI filtering. Defaults to empty. + /// Null or whitespace elements are invalid and should be rejected during validation. + /// Used for filtering plugins in UIs and catalogs. + /// + /// + /// Tags are case-sensitive strings without controlled vocabulary. + /// Example: ["security", "auth", "audit"]. + /// + public IReadOnlyList Tags { get; init; } = []; + /// + /// Priority used for activation ordering among dependency-ready plugins. + /// Lower values are activated earlier, higher values later. + /// + /// + /// The ordering algorithm is: topological sort where, among the set of currently + /// dependency-ready plugins, the next plugin is chosen by Priority ascending. + /// Dependency order (G7) wins over Priority. + /// Example: A (p. 100) → B (p-100, DependsOn A), C (p. 0) ⇒ order: A, C, B. + /// + public int Priority { get; init; } + /// + /// Indicates whether the plugin is enabled. Defaults to true. + /// + /// + /// If false, the plugin is skipped before loading (no consistency check runs for it). + /// For plugins accepted by the preload gate and subsequently loaded, + /// manifest.IsEnabled == instance.IsEnabled is part of consistency validation. + /// + public bool IsEnabled { get; init; } = true; + /// + /// Features/capabilities exposed by the plugin. Contract + /// requires Case insensitive comparison. Defaults to an empty set. + /// + /// + /// Used for pre-activation capability checks and post-load consistency validation. + /// Host checks capabilities using the extension method. + /// Example: manifest.Supports("auth"). + /// + public IReadOnlySet Capabilities { get; init; } = ImmutableHashSet.Create(StringComparer.OrdinalIgnoreCase); + + /// + /// Minimum host version required to load this plugin. + /// + /// + /// If the host version is lower than , the plugin is rejected. + /// Uses SemanticVersion 2.0.0 for version comparison. + /// + public SemanticVersion? MinHostVersion { get; init; } + + /// + /// List of plugin IDs this plugin depends on. + /// + /// + /// Each entry must be a valid plugin ID. The host validates: + /// - No self-dependencies (plugin cannot depend on itself). + /// - No duplicate dependencies. + /// - All dependencies exist among discovered plugins. + /// - No dependency cycles. + /// + public IReadOnlyList DependsOn { get; init; } = []; +} \ No newline at end of file diff --git a/src/Plugins/Abstractions/Models/PluginMetadata.cs b/src/Plugins/Abstractions/Models/PluginMetadata.cs new file mode 100644 index 0000000..52d74bf --- /dev/null +++ b/src/Plugins/Abstractions/Models/PluginMetadata.cs @@ -0,0 +1,95 @@ +using System.Collections.Immutable; +using AuthKit.Plugins.Abstractions.Contracts; + +namespace AuthKit.Plugins.Abstractions.Models; + +/// +/// Represents an immutable runtime snapshot of plugin metadata. +/// +/// +/// This record aggregates all metadata from +/// and . It is created after the plugin is loaded +/// and provides a consistent, immutable view of the plugin's metadata. +/// +public sealed record PluginMetadata +{ + /// + /// Gets the stable, host-unique identifier of the plugin. + /// + public required string Id { get; init; } + + /// + /// Gets the unique name of the plugin. + /// + public required string Name { get; init; } + + /// + /// Gets the human-readable description of the plugin. + /// + public required string Description { get; init; } + + /// + /// Gets the version of the plugin as a semantic version (SemVer 2.0.0). + /// + public required SemanticVersion Version { get; init; } + + /// + /// Optional author metadata. + /// + public string? Author { get; init; } + + /// + /// Optional SPDX-style license string. + /// + public string? License { get; init; } + + /// + /// Optional absolute URI pointing to the license text. + /// + public string? LicenseUrl { get; init; } + + /// + /// Optional absolute HTTP/HTTPS URI pointing to a plugin homepage. + /// + public string? Homepage { get; init; } + + /// + /// Optional absolute HTTP/HTTPS URI pointing to the plugin repository. + /// + public string? RepositoryUrl { get; init; } + + /// + /// Optional classification tags for UI filtering. + /// + public IReadOnlyList Tags { get; init; } = Array.Empty(); + + /// + /// Priority used for activation ordering. + /// + public int Priority { get; init; } + + /// + /// Indicates whether the plugin is enabled. + /// + public bool IsEnabled { get; init; } = true; + + /// + /// Minimum host version required to load this plugin. + /// + public SemanticVersion? MinHostVersion { get; init; } + + /// + /// List of plugin IDs this plugin depends on. + /// + public IReadOnlyList DependsOn { get; init; } = Array.Empty(); + + /// + /// Features/capabilities exposed by the plugin. + /// + public IReadOnlySet Capabilities { get; init; } = ImmutableHashSet.Create(StringComparer.OrdinalIgnoreCase); + + /// + /// Optional human-readable display name for UIs. + /// + public string? DisplayName { get; init; } +} \ No newline at end of file diff --git a/src/Plugins/Abstractions/Models/SemanticVersion.cs b/src/Plugins/Abstractions/Models/SemanticVersion.cs new file mode 100644 index 0000000..d5212b8 --- /dev/null +++ b/src/Plugins/Abstractions/Models/SemanticVersion.cs @@ -0,0 +1,318 @@ +using System.Text.Json.Serialization; + +namespace AuthKit.Plugins.Abstractions.Models; + +/// +/// Immutable Semantic Versioning 2.0.0 value type. +/// +/// +/// Build metadata does not affect equality or precedence, as defined by +/// Semantic Versioning 2.0.0. +/// +[JsonConverter(typeof(SemanticVersionJsonConverter))] +public readonly record struct SemanticVersion : IComparable +{ + public int Major { get; } + public int Minor { get; } + public int Patch { get; } + + public string? PreRelease { get; } + public string? Build { get; } + + public SemanticVersion( + int major, + int minor, + int patch, + string? preRelease = null, + string? build = null) + { + ArgumentOutOfRangeException.ThrowIfNegative(major); + ArgumentOutOfRangeException.ThrowIfNegative(minor); + ArgumentOutOfRangeException.ThrowIfNegative(patch); + + ValidateIdentifiers(preRelease, nameof(preRelease)); + ValidateIdentifiers(build, nameof(build)); + + Major = major; + Minor = minor; + Patch = patch; + PreRelease = preRelease; + Build = build; + } + + public override string ToString() + { + var value = $"{Major}.{Minor}.{Patch}"; + + if (PreRelease is not null) + value += $"-{PreRelease}"; + + if (Build is not null) + value += $"+{Build}"; + + return value; + } + + public static bool TryParse( + string? input, + out SemanticVersion version) + { + version = default; + + if (string.IsNullOrWhiteSpace(input)) + return false; + + var value = input.Trim(); + + var buildSeparator = value.IndexOf('+'); + var build = buildSeparator >= 0 + ? value[(buildSeparator + 1)..] + : null; + + if (buildSeparator >= 0) + value = value[..buildSeparator]; + + var preReleaseSeparator = value.IndexOf('-'); + var preRelease = preReleaseSeparator >= 0 + ? value[(preReleaseSeparator + 1)..] + : null; + + if (preReleaseSeparator >= 0) + value = value[..preReleaseSeparator]; + + var parts = value.Split('.'); + + if (parts.Length != 3) + return false; + + if (!TryParseCore(parts[0], out var major) || + !TryParseCore(parts[1], out var minor) || + !TryParseCore(parts[2], out var patch)) + { + return false; + } + + if (!ValidateIdentifiers(preRelease) || + !ValidateIdentifiers(build)) + { + return false; + } + + version = new SemanticVersion( + major, + minor, + patch, + preRelease, + build); + + return true; + } + + public static SemanticVersion Parse(string input) + { + if (!TryParse(input, out var version)) + throw new FormatException( + $"Invalid semantic version: '{input}'"); + + return version; + } + + public int CompareTo(SemanticVersion other) + { + var result = Major.CompareTo(other.Major); + + if (result != 0) + return result; + + result = Minor.CompareTo(other.Minor); + + if (result != 0) + return result; + + result = Patch.CompareTo(other.Patch); + + if (result != 0) + return result; + + return ComparePreRelease(PreRelease, other.PreRelease); + } + + public bool Equals(SemanticVersion other) + { + return Major == other.Major && + Minor == other.Minor && + Patch == other.Patch && + string.Equals( + PreRelease, + other.PreRelease, + StringComparison.Ordinal); + } + + public override int GetHashCode() + { + return HashCode.Combine( + Major, + Minor, + Patch, + PreRelease); + } + + public static bool operator <( + SemanticVersion left, + SemanticVersion right) => + left.CompareTo(right) < 0; + + public static bool operator <=(SemanticVersion left, SemanticVersion right) => + left.CompareTo(right) <= 0; + + public static bool operator >(SemanticVersion left, SemanticVersion right) => + left.CompareTo(right) > 0; + + public static bool operator >=(SemanticVersion left, SemanticVersion right) => + left.CompareTo(right) >= 0; + + private static int ComparePreRelease( + string? left, + string? right) + { + // A release version has higher precedence than a prerelease. + if (left is null && right is null) + return 0; + + if (left is null) + return 1; + + if (right is null) + return -1; + + var leftParts = left.Split('.'); + var rightParts = right.Split('.'); + + var length = Math.Min( + leftParts.Length, + rightParts.Length); + + for (var i = 0; i < length; i++) + { + var result = CompareIdentifier( + leftParts[i], + rightParts[i]); + + if (result != 0) + return result; + } + + return leftParts.Length.CompareTo(rightParts.Length); + } + + private static int CompareIdentifier( + string left, + string right) + { + var leftNumeric = IsNumeric(left); + var rightNumeric = IsNumeric(right); + + return leftNumeric switch + { + true when rightNumeric => CompareNumericIdentifiers(left, right), + true => -1, + _ => rightNumeric ? 1 : string.CompareOrdinal(left, right) + }; + } + + private static int CompareNumericIdentifiers( + string left, + string right) + { + // Both identifiers are valid numeric identifiers without leading zeros, + // so length comparison is enough before ordinal comparison. + var result = left.Length.CompareTo(right.Length); + + return result != 0 + ? result + : string.CompareOrdinal(left, right); + } + + private static bool TryParseCore( + string value, + out int result) + { + result = 0; + + switch (value.Length) + { + case 0: + case > 1 when value[0] == '0': + return false; + default: + return int.TryParse( + value, + out result); + } + } + + private static void ValidateIdentifiers(string? value, + string parameterName) + { + if (!ValidateIdentifiers(value)) + throw new ArgumentException( + $"Invalid SemVer identifier: '{value}'.", + parameterName); + } + + private static bool ValidateIdentifiers(string? value) + { + if (value is null) + return true; + + if (value.Length == 0) + return false; + + var identifiers = value.Split('.'); + + foreach (var identifier in identifiers) + { + if (identifier.Length == 0) + return false; + + var numeric = true; + + foreach (var c in identifier) + { + if (c is >= '0' and <= '9') + continue; + + numeric = false; + + if (c is not + (>= '0' and <= '9') and + not (>= 'A' and <= 'Z') and + not (>= 'a' and <= 'z') and + not '-') + { + return false; + } + } + + if (numeric && + identifier.Length > 1 && + identifier[0] == '0') + { + return false; + } + } + + return true; + } + + private static bool IsNumeric(string value) + { + foreach (var c in value) + { + if (c is < '0' or > '9') + return false; + } + + return true; + } +} diff --git a/src/Plugins/Abstractions/Models/SemanticVersionJsonConverter.cs b/src/Plugins/Abstractions/Models/SemanticVersionJsonConverter.cs new file mode 100644 index 0000000..002e2a7 --- /dev/null +++ b/src/Plugins/Abstractions/Models/SemanticVersionJsonConverter.cs @@ -0,0 +1,44 @@ +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace AuthKit.Plugins.Abstractions.Models; + +/// +/// Converter for type. +/// Parses JSON string into value and +/// writes the semantic version string back to JSON. +/// +/// +/// Build metadata does not affect equality or precedence, as defined by +/// Semantic Versioning 2.0.0. +/// +public sealed class SemanticVersionJsonConverter : JsonConverter +{ + /// + /// Parses JSON string into value. + /// + /// The reader to read from. + /// The type to convert to. + /// Serializer options. + /// The parsed value. + /// Thrown if the reader token is not a string. + public override SemanticVersion Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + if (reader.TokenType == JsonTokenType.String) + { + var s = reader.GetString()!; + return SemanticVersion.Parse(s); + } + + throw new JsonException("Expected JSON string for SemanticVersion"); + } + + /// + /// Writes the value as JSON string. + /// + /// The writer to write to. + /// The value to write. + /// Serializer options. + public override void Write(Utf8JsonWriter writer, SemanticVersion value, JsonSerializerOptions options) => + writer.WriteStringValue(value.ToString()); +} \ No newline at end of file From f4370288dcf819b045411c1158aff5084ec456bf Mon Sep 17 00:00:00 2001 From: "Rian.be" Date: Thu, 3 Sep 2026 21:18:13 +0200 Subject: [PATCH 05/18] refactor: expand plugin contract metadata --- .../Abstractions/Contracts/IAuthKitPlugin.cs | 257 ++++++++++++++++++ src/Plugins/Abstractions/IAuthKitPlugin.cs | 141 ---------- 2 files changed, 257 insertions(+), 141 deletions(-) create mode 100644 src/Plugins/Abstractions/Contracts/IAuthKitPlugin.cs delete mode 100644 src/Plugins/Abstractions/IAuthKitPlugin.cs diff --git a/src/Plugins/Abstractions/Contracts/IAuthKitPlugin.cs b/src/Plugins/Abstractions/Contracts/IAuthKitPlugin.cs new file mode 100644 index 0000000..045d48b --- /dev/null +++ b/src/Plugins/Abstractions/Contracts/IAuthKitPlugin.cs @@ -0,0 +1,257 @@ +using AuthKit.Plugins.Abstractions.Contracts.Plugins; +using AuthKit.Plugins.Abstractions.Contracts.SecuritySchemes; +using AuthKit.Plugins.Abstractions.Models; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Configuration; +using Microsoft.AspNetCore.Http; + +namespace AuthKit.Plugins.Abstractions.Contracts; + +/// +/// Defines the contract implemented by an AuthKit plugin. +/// +/// +/// +/// AuthKit plugins are discovered and loaded dynamically by the host at startup. +/// A plugin does not need to be directly referenced by the host project. +/// +/// +/// The plugin contract allows an extension to contribute services, middleware, +/// health checks, and OpenAPI security scheme metadata to the host application. +/// +/// +/// Plugin implementations should keep their integration with the host limited +/// to the abstractions exposed by this contract and should register any +/// plugin-specific dependencies through . +/// +/// +public interface IAuthKitPlugin +{ + /// + /// Gets the stable, host-unique identifier of the plugin. + /// + /// + /// The ID is an author-declared identifier (e.g. "authkit.devtokens"), + /// is expected to be non-empty and stable across restarts. The host is + /// responsible for validating format and uniqueness before activation. + /// + string Id { get; } + + /// + /// Gets the unique name of the plugin. + /// + /// + /// The name is used to identify the plugin in host diagnostics, + /// startup output, and other plugin-related metadata. + /// + string Name { get; } + + /// + /// Gets an optional human-readable display name for UIs. + /// + /// + /// The host UI should display DisplayName ?? Name when presenting + /// the plugin to users. + /// + string? DisplayName => null; + + /// + /// Gets an optional human-readable description of the plugin. + /// + /// + /// The host may display the description in startup output, + /// diagnostics, administrative interfaces, or other status surfaces. + /// + string? Description => null; + + /// + /// Gets the version of the plugin as a semantic version (SemVer 2.0.0). + /// + /// + /// The Version replaces the previous string-based version and exposes + /// full semantic version semantics (parsing, equality, precedence). + /// + SemanticVersion Version { get; } + + /// + /// Optional author metadata, visible in catalogs and diagnostics. + /// + string? Author => null; + + /// + /// Optional SPDX-style license string (no validation performed by host). + /// + string? License => null; + + /// + /// Optional absolute URI pointing to the license text. + /// + string? LicenseUrl => null; + + /// + /// Optional absolute HTTP/HTTPS URI pointing to a plugin homepage. + /// + string? Homepage => null; + + /// + /// Optional absolute HTTP/HTTPS URI pointing to the plugin repository. + /// + string? RepositoryUrl => null; + + /// + /// Optional classification tags for UI filtering. Defaults to empty. + /// Null or whitespace elements are invalid and should be rejected during validation. + /// Used for filtering plugins in UIs and catalogs. + /// + /// + /// Tags are case-sensitive strings without controlled vocabulary. + /// Example: ["security", "auth", "audit"]. + /// + IReadOnlyList Tags => Array.Empty(); + + /// + /// Priority used for activation ordering among dependency-ready plugins. + /// Lower values are activated earlier, higher values later. + /// Defaults to 0. + /// + /// + /// The ordering algorithm is: topological sort where, among the set of currently + /// dependency-ready plugins, the next plugin is chosen by Priority ascending. + /// Dependency order (G7) wins over Priority. + /// Example: A (p. 100) → B (p-100, DependsOn A), C (p. 0) ⇒ order: A, C, B. + /// + int Priority => 0; + + /// + /// Indicates whether the plugin is enabled. Defaults to true. + /// + /// + /// If false, the plugin is skipped before loading (no consistency check runs for it). + /// For plugins accepted by the preload gate and subsequently loaded, + /// manifest.IsEnabled == instance.IsEnabled is part of consistency validation. + /// + bool IsEnabled => true; + + /// + /// Features/capabilities exposed by the plugin. Contract + /// requires Case-insensitive comparison. Defaults to an immutable empty set. + /// + /// + /// Used for pre-activation capability checks (via ) and + /// post-load consistency validation. Host checks capabilities using the + /// extension method. + /// Example: plugin.Supports("auth"). + /// + IReadOnlySet Capabilities => EmptyCapabilities; + + // Shared immutable empty capabilities set with OrdinalIgnoreCase comparer + private static readonly IReadOnlySet EmptyCapabilities = + System.Collections.Immutable.ImmutableHashSet.Create(StringComparer.OrdinalIgnoreCase); + + /// + /// Registers the plugin's services in the host dependency injection container. + /// + /// The host's dependency injection service collection. + /// The host application configuration. + /// + /// + /// This method is called while the host application is being configured, + /// before the application is built. + /// + /// + /// Plugins should register all services required by their functionality + /// through this method rather than creating their own dependency injection + /// container. + /// + /// + void ConfigureServices( + IServiceCollection services, + IConfiguration configuration); + + /// + /// Performs an optional health check for the plugin. + /// + /// The root service provider of the host application. + /// + /// true when the plugin is currently able to serve requests; + /// otherwise, false. + /// + /// + /// + /// The host may invoke this method as part of its health endpoint. + /// Plugins can resolve the services they require from + /// to verify the availability of their + /// dependencies. + /// + /// + /// A plugin should return false when a required dependency is + /// unavailable, such as when its database or external service cannot + /// currently be reached. + /// + /// + /// The default implementation reports the plugin as healthy. Plugins + /// that do not require custom health validation therefore do not need + /// to implement this member. + /// + /// + Task CheckHealthAsync(IServiceProvider services) => + Task.FromResult(true); + + /// + /// Gets the optional ASP.NET Core middleware type contributed by the plugin. + /// + /// + /// + /// When specified, the host inserts the middleware into its request + /// processing pipeline at the plugin middleware slot. + /// + /// + /// The middleware type must follow the conventional ASP.NET Core middleware + /// pattern, including a constructor accepting + /// and an InvokeAsync method accepting . + /// Additional dependencies may be supplied through dependency injection. + /// + /// + /// The default value is null, indicating that the plugin does not + /// contribute middleware. + /// + /// + Type? MiddlewareType => null; + + /// + /// Gets the minimum host version required to load this plugin. + /// + /// + /// If the host version is lower than , the plugin is rejected. + /// + SemanticVersion? MinHostVersion => null; + + /// + /// Gets the list of plugin IDs this plugin depends on. + /// + /// + /// Each entry must be a valid plugin ID. The host validates that: + /// - Dependencies exist among discovered plugins. + /// - There are no self-dependencies. + /// - There are no duplicate dependencies. + /// - There are no dependency cycles. + /// + IReadOnlyList DependsOn => Array.Empty(); + + /// + /// Gets the OpenAPI security schemes contributed by the plugin. + /// + /// + /// + /// The host exposes security schemes returned by this method as + /// part of its Swagger/OpenAPI security metadata. + /// + /// + /// Plugins that do not contribute to security schemes can rely on the default + /// empty collection. + /// + /// + /// readonly dictionary keyed by the security scheme name. + IReadOnlyDictionary GetSecuritySchemes() => + new Dictionary(); +} diff --git a/src/Plugins/Abstractions/IAuthKitPlugin.cs b/src/Plugins/Abstractions/IAuthKitPlugin.cs deleted file mode 100644 index f20698f..0000000 --- a/src/Plugins/Abstractions/IAuthKitPlugin.cs +++ /dev/null @@ -1,141 +0,0 @@ -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; - -namespace AuthKit.Plugins.Abstractions; - -/// -/// Defines the contract implemented by an AuthKit plugin. -/// -/// -/// -/// AuthKit plugins are discovered and loaded dynamically by the host at startup. -/// A plugin does not need to be directly referenced by the host project. -/// -/// -/// The plugin contract allows an extension to contribute services, middleware, -/// health checks, and OpenAPI security scheme metadata to the host application. -/// -/// -/// Plugin implementations should keep their integration with the host limited -/// to the abstractions exposed by this contract and should register any -/// plugin-specific dependencies through . -/// -/// -public interface IAuthKitPlugin -{ - /// - /// Gets the unique name of the plugin. - /// - /// - /// The name is used to identify the plugin in host diagnostics, - /// startup output, and other plugin-related metadata. - /// - string Name { get; } - - /// - /// Gets the version of the plugin. - /// - /// - /// The version is exposed as plugin metadata and may be used by the host - /// for diagnostics, compatibility checks, or administrative surfaces. - /// - string Version { get; } - - /// - /// Gets an optional human-readable description of the plugin. - /// - /// - /// The description may be displayed by the host in startup output, - /// diagnostics, administrative interfaces, or other status surfaces. - /// - string? Description => null; - - /// - /// Registers the plugin's services in the host dependency injection container. - /// - /// The host's dependency injection service collection. - /// The host application configuration. - /// - /// - /// This method is called while the host application is being configured, - /// before the application is built. - /// - /// - /// Plugins should register all services required by their functionality - /// through this method rather than creating their own dependency injection - /// container. - /// - /// - void ConfigureServices( - IServiceCollection services, - IConfiguration configuration); - - /// - /// Performs an optional health check for the plugin. - /// - /// The root service provider of the host application. - /// - /// true when the plugin is currently able to serve requests; - /// otherwise, false. - /// - /// - /// - /// The host may invoke this method as part of its health endpoint. - /// Plugins can resolve the services they require from - /// to verify the availability of their - /// dependencies. - /// - /// - /// A plugin should return false when a required dependency is - /// unavailable, such as when its database or external service cannot - /// currently be reached. - /// - /// - /// The default implementation reports the plugin as healthy. Plugins - /// that do not require custom health validation therefore do not need - /// to implement this member. - /// - /// - Task CheckHealthAsync(IServiceProvider services) => - Task.FromResult(true); - - /// - /// Gets the optional ASP.NET Core middleware type contributed by the plugin. - /// - /// - /// - /// When specified, the host inserts the middleware into its request - /// processing pipeline at the plugin middleware slot. - /// - /// - /// The middleware type must follow the conventional ASP.NET Core middleware - /// pattern, including a constructor accepting - /// and an InvokeAsync method accepting . - /// Additional dependencies may be supplied through dependency injection. - /// - /// - /// The default value is null, indicating that the plugin does not - /// contribute middleware. - /// - /// - Type? MiddlewareType => null; - - /// - /// Gets the OpenAPI security schemes contributed by the plugin. - /// - /// - /// A read-only dictionary keyed by security scheme name. - /// - /// - /// - /// Security schemes returned by this method are exposed by the host as - /// part of its Swagger/OpenAPI security metadata. - /// - /// - /// Plugins that do not contribute security schemes can rely on the default - /// empty collection. - /// - /// - IReadOnlyDictionary GetSecuritySchemes() => - new Dictionary(); -} From ab5512555e12734718d82a5033edf0841eefba7b Mon Sep 17 00:00:00 2001 From: "Rian.be" Date: Thu, 3 Sep 2026 21:19:37 +0200 Subject: [PATCH 06/18] feat: add DevTokens plugin manifest metadata --- src/Plugins/Solutions/DevTokens/DevTokens.csproj | 3 +++ .../Solutions/DevTokens/DevTokensPlugin.cs | 16 ++++++++++++++-- .../Solutions/DevTokens/plugin.manifest.json | 16 ++++++++++++++++ 3 files changed, 33 insertions(+), 2 deletions(-) create mode 100644 src/Plugins/Solutions/DevTokens/plugin.manifest.json diff --git a/src/Plugins/Solutions/DevTokens/DevTokens.csproj b/src/Plugins/Solutions/DevTokens/DevTokens.csproj index 34c0378..0c6c4d4 100644 --- a/src/Plugins/Solutions/DevTokens/DevTokens.csproj +++ b/src/Plugins/Solutions/DevTokens/DevTokens.csproj @@ -19,4 +19,7 @@ + + + diff --git a/src/Plugins/Solutions/DevTokens/DevTokensPlugin.cs b/src/Plugins/Solutions/DevTokens/DevTokensPlugin.cs index a2023f4..eadb064 100644 --- a/src/Plugins/Solutions/DevTokens/DevTokensPlugin.cs +++ b/src/Plugins/Solutions/DevTokens/DevTokensPlugin.cs @@ -1,6 +1,8 @@ -using DevTokens.DeveloperTokens; using DevTokens.Options; using AuthKit.Plugins.Abstractions; +using AuthKit.Plugins.Abstractions.Contracts; +using AuthKit.Plugins.Abstractions.Contracts.SecuritySchemes; +using AuthKit.Plugins.Abstractions.Models; using FluentValidation; using DevTokens.Interfaces; using DevTokens.Middleware; @@ -33,15 +35,19 @@ namespace DevTokens; /// public sealed class DevTokensPlugin : IAuthKitPlugin { + public string Id => "authkit.devtokens"; + /// /// Gets the unique name of the plugin. /// public string Name => "DevTokens"; + public string? DisplayName => "Developer Tokens"; + /// /// Gets the current version of the plugin. /// - public string Version => "1.0.0"; + public SemanticVersion Version => new(1, 0, 0); /// /// Gets a description of the functionality provided by the plugin. @@ -49,6 +55,12 @@ public sealed class DevTokensPlugin : IAuthKitPlugin public string Description => "Issues and validates developer tokens for SDK access."; + public string? Author => "AuthKit Contributors"; + public string? License => "MIT"; + public string? LicenseUrl => "https://opensource.org/licenses/MIT"; + public string? Homepage => "https://example.org/devtokens"; + public string? RepositoryUrl => "https://example.org/devtokens.git"; + /// /// Registers developer token services, repositories, validators, /// and authorization components in the dependency injection container. diff --git a/src/Plugins/Solutions/DevTokens/plugin.manifest.json b/src/Plugins/Solutions/DevTokens/plugin.manifest.json new file mode 100644 index 0000000..393c2ad --- /dev/null +++ b/src/Plugins/Solutions/DevTokens/plugin.manifest.json @@ -0,0 +1,16 @@ +{ + "Id": "authkit.devtokens", + "Name": "DevTokens", + "DisplayName": "Developer Tokens", + "Description": "Issues and validates developer tokens for SDK access.", + "Version": "1.0.0", + "Author": "AuthKit Contributors", + "License": "MIT", + "LicenseUrl": "https://opensource.org/licenses/MIT", + "Homepage": "https://example.org/devtokens", + "RepositoryUrl": "https://example.org/devtokens.git", + "Tags": ["devtokens", "auth"], + "Priority": 0, + "IsEnabled": true, + "DependsOn": [] +} From 772214418a84e0f140bb0356576daf7ee817873d Mon Sep 17 00:00:00 2001 From: "Rian.be" Date: Thu, 3 Sep 2026 21:28:30 +0200 Subject: [PATCH 07/18] refactor: validate plugin manifests and host compatibility --- src/Host/Plugins/LoadedPlugin.cs | 4 +- src/Host/Plugins/PluginLoader.cs | 217 +++++++++++++++++++++++++------ 2 files changed, 180 insertions(+), 41 deletions(-) diff --git a/src/Host/Plugins/LoadedPlugin.cs b/src/Host/Plugins/LoadedPlugin.cs index 2f69cd3..02e4aa6 100644 --- a/src/Host/Plugins/LoadedPlugin.cs +++ b/src/Host/Plugins/LoadedPlugin.cs @@ -1,10 +1,10 @@ using System.Reflection; -using AuthKit.Plugins.Abstractions; +using AuthKit.Plugins.Abstractions.Contracts; namespace Host.Plugins; /// -/// Represents plugin loaded from disk together with its contract instance, +/// Represents a plugin loaded from disk together with its contract instance, /// assembly, and source directory. /// /// diff --git a/src/Host/Plugins/PluginLoader.cs b/src/Host/Plugins/PluginLoader.cs index 452be07..6fb1252 100644 --- a/src/Host/Plugins/PluginLoader.cs +++ b/src/Host/Plugins/PluginLoader.cs @@ -1,10 +1,12 @@ +using System.Reflection; using System.Runtime.Loader; -using AuthKit.Plugins.Abstractions; +using AuthKit.Plugins.Abstractions.Contracts; +using AuthKit.Plugins.Abstractions.Models; namespace Host.Plugins; /// -/// Discovers and loads AuthKit plugins from specified directory during host startup. +/// Discovers and loads AuthKit plugins from a specified directory during host startup. /// /// /// @@ -28,15 +30,17 @@ public static class PluginLoader /// /// Discovers and loads all valid AuthKit plugins from the specified root directory. /// - /// The root directory containing one subdirectory per plugin. - /// The logger used to report plugin discovery, loading, and validation results. + /// The root directory containing one subdirectory per plugin. + /// The logger used to report plugin discovery, loading, and validation results. + /// The version of the host application. /// A readonly collection containing all successfully loaded plugins. /// /// Each plugin directory is expected to contain an entry assembly whose file name /// matches the directory name. Directories without matching assembly or assemblies /// without valid implementation are skipped. + /// Plugins requiring a higher host version than are rejected. /// - public static IReadOnlyList LoadPlugins(string pluginsRootPath, ILogger logger) + public static IReadOnlyList LoadPlugins(string pluginsRootPath, ILogger logger, SemanticVersion hostVersion) { if (!Directory.Exists(pluginsRootPath)) { @@ -48,52 +52,187 @@ public static IReadOnlyList LoadPlugins(string pluginsRootPath, IL foreach (var pluginDir in Directory.GetDirectories(pluginsRootPath)) { - var pluginName = Path.GetFileName(pluginDir); - var entryDllPath = Path.Combine(pluginDir, $"{pluginName}.dll"); + if (TryLoadPlugin(pluginDir, logger, hostVersion, loaded, out var plugin)) + { + loaded.Add(plugin); + logger.LogInformation("Loaded plugin '{Name}' v{Version} from {Dir}", plugin.Plugin.Name, plugin.Plugin.Version.ToString(), pluginDir); + } + } + + return loaded; + } + + private static bool TryLoadPlugin( + string pluginDir, + ILogger logger, + SemanticVersion hostVersion, + IReadOnlyCollection alreadyLoaded, + out LoadedPlugin loadedPlugin) + { + loadedPlugin = null!; + + var pluginName = Path.GetFileName(pluginDir); + var entryDllPath = Path.Combine(pluginDir, $"{pluginName}.dll"); - if (!File.Exists(entryDllPath)) + if (!File.Exists(entryDllPath)) + { + logger.LogError( + "Skipping plugin folder '{Dir}': expected entry assembly '{Dll}' not found.", + pluginDir, entryDllPath); + return false; + } + + try + { + var manifest = TryReadManifest(pluginDir, pluginName, logger); + + if (manifest is not null && !ManifestIsUsable(manifest, pluginDir, alreadyLoaded, logger)) + return false; + + var assembly = LoadAssembly(entryDllPath); + var pluginType = FindPluginType(assembly); + + if (pluginType is null) { logger.LogError( - "Skipping plugin folder '{Dir}': expected entry assembly '{Dll}' not found.", - pluginDir, entryDllPath); - continue; + "Skipping plugin assembly '{Dll}': no public, non-abstract IAuthKitPlugin implementation with a parameterless constructor found.", + entryDllPath); + return false; } - try - { - var resolver = new AssemblyDependencyResolver(entryDllPath); - AssemblyLoadContext.Default.Resolving += (context, name) => - { - var path = resolver.ResolveAssemblyToPath(name); - return path is not null ? context.LoadFromAssemblyPath(path) : null; - }; + var plugin = (IAuthKitPlugin)Activator.CreateInstance(pluginType)!; - var assembly = AssemblyLoadContext.Default.LoadFromAssemblyPath(entryDllPath); + if (!string.IsNullOrWhiteSpace(plugin.Id) && + alreadyLoaded.Any(lp => string.Equals(lp.Plugin.Id, plugin.Id, StringComparison.Ordinal))) + { + logger.LogError("Skipping plugin '{Dir}': duplicate plugin Id '{Id}' detected.", pluginDir, plugin.Id); + return false; + } - var pluginType = assembly.GetTypes() - .FirstOrDefault(t => t is { IsPublic: true, IsAbstract: false } - && typeof(IAuthKitPlugin).IsAssignableFrom(t) - && t.GetConstructor(Type.EmptyTypes) is not null); + // Without manifest, MinHostVersion (if declared on the instance) is the only + // compatibility check available. With a manifest, this is covered by ValidateConsistency below. + if (manifest is null && plugin.MinHostVersion is not null && hostVersion < plugin.MinHostVersion) + { + logger.LogError( + "Skipping plugin '{Dir}': host version {HostVersion} is lower than required minimum {MinVersion}.", + pluginDir, hostVersion.ToString(), plugin.MinHostVersion.ToString()); + return false; + } - if (pluginType is null) + if (manifest is not null) + { + try + { + PluginValidator.ValidateConsistency(manifest, plugin); + } + catch (Exception ex) { - logger.LogError( - "Skipping plugin assembly '{Dll}': no public, non-abstract IAuthKitPlugin implementation with a parameterless constructor found.", - entryDllPath); - continue; + logger.LogError(ex, "Skipping plugin '{Dir}': manifest/instance consistency check failed.", pluginDir); + return false; } + } - var plugin = (IAuthKitPlugin)Activator.CreateInstance(pluginType)!; - loaded.Add(new LoadedPlugin(plugin, assembly, pluginDir)); + loadedPlugin = new LoadedPlugin(plugin, assembly, pluginDir); + return true; + } + catch (Exception ex) + { + logger.LogError(ex, "Failed to load plugin from '{Dir}'.", pluginDir); + return false; + } + } - logger.LogInformation("Loaded plugin '{Name}' v{Version} from {Dir}", plugin.Name, plugin.Version, pluginDir); - } - catch (Exception ex) - { - logger.LogError(ex, "Failed to load plugin from '{Dir}'.", pluginDir); - } + private static PluginManifest? TryReadManifest(string pluginDir, string pluginName, ILogger logger) + { + string[] manifestCandidates = + [ + Path.Combine(pluginDir, "plugin.manifest.json"), + Path.Combine(pluginDir, "manifest.json"), + Path.Combine(pluginDir, $"{pluginName}.manifest.json") + ]; + + var manifestPath = manifestCandidates.FirstOrDefault(File.Exists); + if (manifestPath is null) + return null; + + try + { + var json = File.ReadAllText(manifestPath); + return System.Text.Json.JsonSerializer.Deserialize( + json, new System.Text.Json.JsonSerializerOptions { PropertyNameCaseInsensitive = true }); + } + catch (Exception ex) + { + logger.LogError(ex, "Failed to parse manifest {Manifest} for plugin {Dir}", manifestPath, pluginDir); + return null; } + } - return loaded; + private static bool ManifestIsUsable( + PluginManifest manifest, + string pluginDir, + IReadOnlyCollection alreadyLoaded, + ILogger logger) + { + try + { + PluginValidator.ValidateTags(manifest.Tags); + } + catch (Exception ex) + { + logger.LogError(ex, "Skipping plugin '{Dir}': invalid tags in manifest.", pluginDir); + return false; + } + + try + { + PluginValidator.ValidateDependsOn(manifest.DependsOn, manifest.Id); + } + catch (Exception ex) + { + logger.LogError(ex, "Skipping plugin '{Dir}': invalid dependencies in manifest.", pluginDir); + return false; + } + + if (!manifest.IsEnabled) + { + logger.LogInformation("Skipping plugin '{Dir}': manifest indicates IsEnabled=false.", pluginDir); + return false; + } + + if (!string.IsNullOrWhiteSpace(manifest.Id) && + alreadyLoaded.Any(lp => string.Equals(lp.Plugin.Id, manifest.Id, StringComparison.Ordinal))) + { + logger.LogError("Skipping plugin '{Dir}': duplicate plugin Id '{Id}' detected in manifest.", pluginDir, manifest.Id); + return false; + } + + return true; } -} + + private static Assembly LoadAssembly(string entryDllPath) + { + var resolver = new AssemblyDependencyResolver(entryDllPath); + Func handler = (context, name) => + { + var path = resolver.ResolveAssemblyToPath(name); + return path is not null ? context.LoadFromAssemblyPath(path) : null; + }; + + AssemblyLoadContext.Default.Resolving += handler; + try + { + return AssemblyLoadContext.Default.LoadFromAssemblyPath(entryDllPath); + } + finally + { + AssemblyLoadContext.Default.Resolving -= handler; + } + } + + private static Type? FindPluginType(Assembly assembly) => + assembly.GetTypes().FirstOrDefault(t => + t is { IsPublic: true, IsAbstract: false } && + typeof(IAuthKitPlugin).IsAssignableFrom(t) && + t.GetConstructor(Type.EmptyTypes) is not null); +} \ No newline at end of file From df912da79fcbfc825740c688cc435e07b7c9d77c Mon Sep 17 00:00:00 2001 From: "Rian.be" Date: Thu, 3 Sep 2026 21:29:20 +0200 Subject: [PATCH 08/18] refactor: integrate plugin version compatibility --- Dockerfile | 2 ++ src/Host/Program.cs | 9 ++++++++- .../Abstractions/AuthKit.Plugins.Abstractions.csproj | 12 ++++++++++++ 3 files changed, 22 insertions(+), 1 deletion(-) diff --git a/Dockerfile b/Dockerfile index d1c00dc..fcd1e7a 100644 --- a/Dockerfile +++ b/Dockerfile @@ -28,9 +28,11 @@ FROM build AS publish WORKDIR /src RUN dotnet publish "src/Host/Host.csproj" -c Release -o /app/publish RUN dotnet publish "src/Plugins/Solutions/DevTokens/DevTokens.csproj" -c Release -o /app/publish/plugins/DevTokens +COPY src/Plugins/Solutions/DevTokens/plugin.manifest.json /app/publish/plugins/DevTokens/plugin.manifest.json FROM base AS final WORKDIR /app COPY --from=publish /app/publish . +COPY --from=publish /app/publish/plugins ./plugins VOLUME /root/certs ENTRYPOINT ["dotnet", "Host.dll"] diff --git a/src/Host/Program.cs b/src/Host/Program.cs index 7446931..d20eec8 100644 --- a/src/Host/Program.cs +++ b/src/Host/Program.cs @@ -1,6 +1,9 @@ using Host.Configuration; using Host.Plugins; using Host.Cli; +using AuthKit.Plugins.Abstractions; +using System.Reflection; +using AuthKit.Plugins.Abstractions.Models; var builder = WebApplication.CreateBuilder(args); @@ -9,7 +12,11 @@ ?? Path.Combine(AppContext.BaseDirectory, "plugins"); var pluginLogger = LoggerFactory.Create(logging => logging.AddConsole()).CreateLogger("PluginLoader"); -var plugins = PluginLoader.LoadPlugins(pluginsPath, pluginLogger); +var hostVersion = SemanticVersion.Parse(Assembly.GetEntryAssembly()! + .GetCustomAttribute()! + .InformationalVersion!.Split('+')[0]); + +var plugins = PluginLoader.LoadPlugins(pluginsPath, pluginLogger, hostVersion); // === Core Config === builder.Services.AddSingleton(plugins); diff --git a/src/Plugins/Abstractions/AuthKit.Plugins.Abstractions.csproj b/src/Plugins/Abstractions/AuthKit.Plugins.Abstractions.csproj index d327ce9..3c18293 100644 --- a/src/Plugins/Abstractions/AuthKit.Plugins.Abstractions.csproj +++ b/src/Plugins/Abstractions/AuthKit.Plugins.Abstractions.csproj @@ -4,9 +4,21 @@ preview enable enable + false + false + + + + + + + + ..\..\..\..\..\..\..\..\.nuget\packages\microsoft.aspnetcore.http.abstractions\2.3.0\lib\netstandard2.0\Microsoft.AspNetCore.Http.Abstractions.dll + + From 3d928b532a90622665ce689faf07f2a12e376b73 Mon Sep 17 00:00:00 2001 From: "Rian.be" Date: Fri, 4 Sep 2026 14:12:06 +0200 Subject: [PATCH 09/18] docs: add ADR-017 for plugin contract architecture --- ...ntract-and-Dynamic-Loading-Architecture.md | 190 ++++++++++++++++++ .../Solutions/DevTokens/DevTokensPlugin.cs | 12 +- 2 files changed, 196 insertions(+), 6 deletions(-) create mode 100644 Docs/ADR/017-Plugin-Contract-and-Dynamic-Loading-Architecture.md diff --git a/Docs/ADR/017-Plugin-Contract-and-Dynamic-Loading-Architecture.md b/Docs/ADR/017-Plugin-Contract-and-Dynamic-Loading-Architecture.md new file mode 100644 index 0000000..8c5634f --- /dev/null +++ b/Docs/ADR/017-Plugin-Contract-and-Dynamic-Loading-Architecture.md @@ -0,0 +1,190 @@ +# ADR-017: Plugin Contract and Dynamic Loading Architecture + +## Context + +The `AuthKit.Host` project requires dynamic plugin discovery and loading at startup, before the DI container and infrastructure (Wolverine, Marten) are fully configured. The existing `IAuthKitPlugin` interface only exposed `Name`, `Version` (as string), and `Description`, which was insufficient for proper plugin lifecycle management, compatibility checking, and dependency resolution. + +The `PluginLoader.LoadPlugins()` method signature changed from 2 to 3 required parameters (`pluginsRootPath, ILogger logger, SemanticVersion hostVersion`), causing a compile error that needed to be fixed by extracting the host version from assembly metadata. + +## Problem + +1. **Compile error**: `PluginLoader.LoadPlugins(pluginsPath, pluginLogger)` called with 2 arguments but method requires 3 required parameters +2. **No host version awareness**: Plugins could not be rejected based on minimum host version requirements (`MinHostVersion` gate G3) +3. **No manifest support**: No pre-activation validation of plugin metadata (tags, dependencies, enabled status, consistency checks) +4. **No stable plugin identification**: No unique `Id` field for deduplication, dependency resolution, and host uniqueness +5. **No capability classification**: No `Capabilities` set for pre-activation host checks + +## Decision + +### A1. Plugin Id (`IAuthKitPlugin.Id`) +- Added `string Id { get; }` to `IAuthKitPlugin` interface +- Plugin authors declare stable identifiers (e.g., `authkit.devtokens`) +- Host validates format and uniqueness before activation +- **Rejected**: Using `Guid` as `Id` (poor readability in manifests, logs, CLI, and config) + +### A2. Strongly-typed Version (`IAuthKitPlugin.Version`) +- Replaced `string Version` with `SemanticVersion Version` +- SemVer 2.0.0 parsing, equality, and comparison with correct precedence +- Build metadata ignored for precedence (`1.0.0+abc == 1.0.0+xyz`) +- **Breaking change**: Existing `string Version => "1.2.3"` implementations must migrate to `SemanticVersion Version` + +### A3-A8. Descriptive Metadata Surface +- `string? Author`, `string? License`, `string? LicenseUrl`, `string? Homepage`, `string? RepositoryUrl` +- `IReadOnlyList Tags` - free-form classification, null/whitespace elements invalid. Defaults to `Array.Empty`. +- `int Priority` - lower value = earlier activation among otherwise independent plugins. Dependencies always take precedence over `Priority`. Defaults to `0`. +- `bool IsEnabled` - defaults to `true`. When `IsEnabled` is provided by a manifest, disabled plugins are skipped before assembly activation. +- `string? DisplayName` - UI shows `DisplayName ?? Name` fallback rule. Defaults to `null`. +- `IReadOnlyList DependsOn` - declares plugin `Id` values (never display names). Defaults to `Array.Empty`. + +### A9. MinHostVersion +- **Deferred**: `MinHostVersion` is not part of the current plugin contract but is planned for future implementation. +- **Note**: Host compatibility checks (G3) are not currently enforced. This feature will be reintroduced when `MinHostVersion` is added to the contract in a future iteration. + +### A10. DependsOn +- `IReadOnlyList DependsOn` - declares plugin `Id` values (never display names) +- **Cycle Detection**: Cycles in dependencies are detected using a **Depth-First Search (DFS)** algorithm with a `visiting` set to track the current traversal path. If a cycle is detected, all plugins involved in the cycle are rejected as a startup error. +- **Priority Resolution**: The `Priority` field (A3-A8) resolves ties **only within a valid topological order** and does not override dependency edges (`DependsOn`). +- G7 validates: missing → startup error, self → reject, duplicate → reject, cycle → startup error + +### A11. Capabilities +- `IReadOnlySet Capabilities` - case-insensitive ordinal set equality. Defaults to an immutable empty set. +- Used for pre-activation host capability checks and runtime contract validation. + +### A12. PluginMetadata +- Immutable runtime snapshot via `PluginMetadataExtensions.GetMetadata()` +- Aggregates the plugin contract metadata into a single immutable runtime snapshot +- Consistency check between manifest and runtime instance (G2) mismatch → reject +- **Note**: Consistency validation focuses on non-version-related metadata (e.g., `Tags`, `DependsOn`, `Capabilities`). + +### A13. DisplayName +- `string? DisplayName` provides a human-readable plugin name for UI and diagnostics. +- Falls back to `Name` when not specified. + +### B. PluginManifest Pre-Activation Projection +- `PluginManifest` mirrors selected runtime members of `IAuthKitPlugin` for pre-activation use (G2) +- Searched from plugin directories: `plugin.manifest.json`, `manifest.json`, `{pluginName}.manifest.json` +- **Manifest Future Direction**: While manifests are currently optional for backward compatibility, the long-term goal is to enforce mandatory manifests for full consistency validation (G2). Plugins without manifests load without validation, which may lead to unexpected behavior in future releases. +- If manifest not found: `manifest` is `null`, plugin loads without consistency validation (fallback path) +- If manifest found: validated tags, depends-on, IsEnabled, duplicate Id check +- Consistency check between manifest and runtime instance after loading. + +### C. Validation and Loading + +#### Pre-activation validation (when manifest exists) +1. **Plugin discovery**: Scan `pluginsRootPath` for subdirectories +2. **Entry assembly check**: Each directory must contain `{pluginName}.dll` +3. **Manifest parsing**: Try `plugin.manifest.json` → `manifest.json` → `{pluginName}.manifest.json` + +**Note**: The host derives its `SemanticVersion` from assembly metadata and passes it explicitly to `PluginLoader`. This value is currently informational and is not used for plugin compatibility validation. Compatibility gating via `MinHostVersion` is deferred. + +5. **Pre-activation validation** (when manifest exists): + - Validate manifest syntax and structure + - Validate `Tags` + - Validate `DependsOn` (missing, self, duplicate, cycle) + - Validate `IsEnabled` + - Validate duplicate `Id` + - Disabled plugins (`IsEnabled = false`) are skipped before assembly activation. + +6. **Assembly loading**: `AssemblyLoadContext.Default.LoadFromAssemblyPath()` with dependency resolver + +#### Runtime validation (after assembly loading) +7. **Plugin instantiation**: `Activator.CreateInstance(pluginType)` → `IAuthKitPlugin` +8. **Duplicate `Id` check at load-time** +9. **Consistency validation** between manifest and runtime instance (if manifest exists) + - Validates non-version-related metadata (e.g., `Tags`, `DependsOn`, `Capabilities`). +10. **Create `PluginMetadata`** as an immutable snapshot of the runtime contract +11. **Activate the plugin** + +**Notes:** +- `MinHostVersion` is planned for future implementation to enforce host-version compatibility (G3). +- Manifest consistency validation focuses on non-version-related metadata, including `Tags`, `DependsOn`, and `Capabilities`. +- Manifests remain optional for backward compatibility; plugins without manifests follow the fallback loading path without consistency validation. + +### Tags +#PluginContract #DynamicLoading #G2 #G7 + +### Date +2026-09-04 + +### Scope +Plugins + +### Previous +ADR-016: Using Marten and Wolverine as the host infrastructure + +### Next +N/A (latest in collection) + +## Consequences + +### Positive +- Plugins can be referenced by stable unique identifier (`Id`) +- Plugin metadata can be validated before activation when a manifest is available +- Disabled plugins can be skipped before assembly activation when declared by manifest +- Plugin contract metadata is available as an immutable `PluginMetadata` snapshot +- Dependency declarations can be validated and resolved deterministically +- Manifest/runtime inconsistencies can be detected before activation +- Plugin metadata is available before DI container setup +- New contributors can understand the plugin contract and loading decisions + +### Negative +- `Version` change from `string` to `SemanticVersion` is breaking (requires migration) +- Plugins without a manifest still load without manifest/runtime consistency validation +- Host-version compatibility (`MinHostVersion`) is planned for future implementation +- Manifest enforcement is deferred to a future iteration +- More compile-time and contract validation is required for plugin authors + +### Consequences Diagram + +```mermaid +flowchart TD + A["Plugin directory
plugin.json / manifest"] --> B["IPluginDiscoverer"] + B --> C["DiscoveredPlugin
Manifest + Location"] + C --> D{"Pre-activation Gate"} + D -->|Disabled| X["SKIP"] + D -->|Invalid manifest| Y["REJECT"] + D -->|Duplicate Id| Y + D -->|Accepted| E["IPluginLoader"] + E --> F["AssemblyLoadContext.Default
+ dependency resolver"] + F --> G["LoadedPlugin
Manifest + Instance"] + G --> H["Plugin Contract
Validation"] + G -->|No manifest| L["ACTIVATION"] + H --> I["Manifest ↔ Runtime
Consistency Check"] + I --> J["PluginMetadata
Immutable Runtime Snapshot"] + J --> K["Dependency Resolution
+ Ordering"] + K --> L + I -.->|Mismatch| Y + H -.->|Invalid contract| Y + K -.->|Missing / self / duplicate / cycle| Y + + subgraph Discovery["DISCOVERY"] + B + C + end + + subgraph Validation["VALIDATION"] + D + H + I + K + end + + subgraph Loading["LOADING"] + E + F + G + end + + subgraph Runtime["RUNTIME"] + J + L + end +``` + +**Diagram Explanation**: +- **Discovery**: `IPluginDiscoverer` scans plugin directories and parses manifests. +- **Pre-activation Gate**: Validates manifest syntax, `Tags`, `DependsOn`, `IsEnabled`, and duplicate `Id`. +- **Loading**: Loads assemblies and instantiates `IAuthKitPlugin`. +- **Validation**: Ensures contract consistency between manifest and runtime instance. +- **Dependency Resolution**: Validates and orders plugins based on `DependsOn` and `Priority`. +- **Activation**: Final step after successful validation and resolution. \ No newline at end of file diff --git a/src/Plugins/Solutions/DevTokens/DevTokensPlugin.cs b/src/Plugins/Solutions/DevTokens/DevTokensPlugin.cs index eadb064..1490232 100644 --- a/src/Plugins/Solutions/DevTokens/DevTokensPlugin.cs +++ b/src/Plugins/Solutions/DevTokens/DevTokensPlugin.cs @@ -42,7 +42,7 @@ public sealed class DevTokensPlugin : IAuthKitPlugin ///
public string Name => "DevTokens"; - public string? DisplayName => "Developer Tokens"; + public string DisplayName => "Developer Tokens"; /// /// Gets the current version of the plugin. @@ -55,11 +55,11 @@ public sealed class DevTokensPlugin : IAuthKitPlugin public string Description => "Issues and validates developer tokens for SDK access."; - public string? Author => "AuthKit Contributors"; - public string? License => "MIT"; - public string? LicenseUrl => "https://opensource.org/licenses/MIT"; - public string? Homepage => "https://example.org/devtokens"; - public string? RepositoryUrl => "https://example.org/devtokens.git"; + public string Author => "AuthKit Contributors"; + public string License => "MIT"; + public string LicenseUrl => "https://opensource.org/licenses/MIT"; + public string Homepage => "https://example.org/devtokens"; + public string RepositoryUrl => "https://example.org/devtokens.git"; /// /// Registers developer token services, repositories, validators, From 0bf78fe41aa0af57c3fec4ced532bebdfc352952 Mon Sep 17 00:00:00 2001 From: "Rian.be" Date: Tue, 8 Sep 2026 18:33:25 +0200 Subject: [PATCH 10/18] Ref: Centralize plugin metadata via attributes --- .../Configuration/KestrelConfiguration.cs | 24 ++++++++--- src/Host/Plugins/PluginLoader.cs | 1 - .../AuthKit.Plugins.Abstractions.csproj | 7 +--- .../Abstractions/Contracts/IAuthKitPlugin.cs | 42 ++++++++++++------- 4 files changed, 47 insertions(+), 27 deletions(-) diff --git a/src/Host/Configuration/KestrelConfiguration.cs b/src/Host/Configuration/KestrelConfiguration.cs index 85470df..25e9d92 100644 --- a/src/Host/Configuration/KestrelConfiguration.cs +++ b/src/Host/Configuration/KestrelConfiguration.cs @@ -31,7 +31,8 @@ public static void ConfigureKestrelServer(this IWebHostBuilder webHost) ConfigureListeners(webHost, certPath, certPassword, portRest, portGrpc); Console.ForegroundColor = ConsoleColor.Green; - Console.WriteLine($"✅ Kestrel configured: REST={portRest}, gRPC={portGrpc}, Cert={certPath}"); + var protocol = File.Exists(certPath) ? "HTTPS" : "HTTP"; + Console.WriteLine($"✅ Kestrel configured ({protocol}): REST={portRest}, gRPC={portGrpc}, Cert={certPath}"); Console.ResetColor(); } @@ -64,8 +65,8 @@ private static void ValidateCertificate(string certPath, string certPassword) { if (!File.Exists(certPath)) { - Console.ForegroundColor = ConsoleColor.Red; - Console.WriteLine($"❌ Certificate not found at: {certPath}"); + Console.ForegroundColor = ConsoleColor.Yellow; + Console.WriteLine($"⚠️ Certificate not found at: {certPath}. Falling back to HTTP."); Console.ResetColor(); } @@ -92,19 +93,32 @@ private static void ConfigureListeners( int portRest, int portGrpc) { + bool useHttps = File.Exists(certPath); + webHost.ConfigureKestrel(options => { // REST (HTTP/1 + HTTP/2) options.ListenAnyIP(portRest, listenOptions => { - listenOptions.UseHttps(certPath, certPassword); + if (useHttps) + { + listenOptions.UseHttps(certPath, certPassword); + } listenOptions.Protocols = HttpProtocols.Http1AndHttp2; }); // gRPC (HTTP/2 only) options.ListenAnyIP(portGrpc, listenOptions => { - listenOptions.UseHttps(certPath, certPassword); + if (useHttps) + { + listenOptions.UseHttps(certPath, certPassword); + } + else + { + // gRPC requires HTTP/2, which on some platforms requires HTTPS or specific configuration + // for ClearText. + } listenOptions.Protocols = HttpProtocols.Http2; }); }); diff --git a/src/Host/Plugins/PluginLoader.cs b/src/Host/Plugins/PluginLoader.cs index 6fb1252..858dbc2 100644 --- a/src/Host/Plugins/PluginLoader.cs +++ b/src/Host/Plugins/PluginLoader.cs @@ -146,7 +146,6 @@ private static bool TryLoadPlugin( { string[] manifestCandidates = [ - Path.Combine(pluginDir, "plugin.manifest.json"), Path.Combine(pluginDir, "manifest.json"), Path.Combine(pluginDir, $"{pluginName}.manifest.json") ]; diff --git a/src/Plugins/Abstractions/AuthKit.Plugins.Abstractions.csproj b/src/Plugins/Abstractions/AuthKit.Plugins.Abstractions.csproj index 3c18293..a956c76 100644 --- a/src/Plugins/Abstractions/AuthKit.Plugins.Abstractions.csproj +++ b/src/Plugins/Abstractions/AuthKit.Plugins.Abstractions.csproj @@ -10,15 +10,12 @@ + - - - ..\..\..\..\..\..\..\..\.nuget\packages\microsoft.aspnetcore.http.abstractions\2.3.0\lib\netstandard2.0\Microsoft.AspNetCore.Http.Abstractions.dll - - + diff --git a/src/Plugins/Abstractions/Contracts/IAuthKitPlugin.cs b/src/Plugins/Abstractions/Contracts/IAuthKitPlugin.cs index 045d48b..bb4652c 100644 --- a/src/Plugins/Abstractions/Contracts/IAuthKitPlugin.cs +++ b/src/Plugins/Abstractions/Contracts/IAuthKitPlugin.cs @@ -4,6 +4,7 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Configuration; using Microsoft.AspNetCore.Http; +using System.Reflection; namespace AuthKit.Plugins.Abstractions.Contracts; @@ -35,7 +36,7 @@ public interface IAuthKitPlugin /// is expected to be non-empty and stable across restarts. The host is /// responsible for validating format and uniqueness before activation. /// - string Id { get; } + string Id => Metadata.Id; /// /// Gets the unique name of the plugin. @@ -44,7 +45,7 @@ public interface IAuthKitPlugin /// The name is used to identify the plugin in host diagnostics, /// startup output, and other plugin-related metadata. /// - string Name { get; } + string Name => Metadata.Name; /// /// Gets an optional human-readable display name for UIs. @@ -53,7 +54,7 @@ public interface IAuthKitPlugin /// The host UI should display DisplayName ?? Name when presenting /// the plugin to users. /// - string? DisplayName => null; + string? DisplayName => Metadata.DisplayName; /// /// Gets an optional human-readable description of the plugin. @@ -62,7 +63,7 @@ public interface IAuthKitPlugin /// The host may display the description in startup output, /// diagnostics, administrative interfaces, or other status surfaces. /// - string? Description => null; + string? Description => Metadata.Description; /// /// Gets the version of the plugin as a semantic version (SemVer 2.0.0). @@ -71,32 +72,32 @@ public interface IAuthKitPlugin /// The Version replaces the previous string-based version and exposes /// full semantic version semantics (parsing, equality, precedence). /// - SemanticVersion Version { get; } + SemanticVersion Version => SemanticVersion.Parse(Metadata.Version); /// /// Optional author metadata, visible in catalogs and diagnostics. /// - string? Author => null; + string? Author => Metadata.Author; /// /// Optional SPDX-style license string (no validation performed by host). /// - string? License => null; + string? License => Metadata.License; /// /// Optional absolute URI pointing to the license text. /// - string? LicenseUrl => null; + string? LicenseUrl => Metadata.LicenseUrl; /// /// Optional absolute HTTP/HTTPS URI pointing to a plugin homepage. /// - string? Homepage => null; + string? Homepage => Metadata.Homepage; /// /// Optional absolute HTTP/HTTPS URI pointing to the plugin repository. /// - string? RepositoryUrl => null; + string? RepositoryUrl => Metadata.RepositoryUrl; /// /// Optional classification tags for UI filtering. Defaults to empty. @@ -107,7 +108,7 @@ public interface IAuthKitPlugin /// Tags are case-sensitive strings without controlled vocabulary. /// Example: ["security", "auth", "audit"]. /// - IReadOnlyList Tags => Array.Empty(); + IReadOnlyList Tags => Metadata.Tags; /// /// Priority used for activation ordering among dependency-ready plugins. @@ -120,7 +121,7 @@ public interface IAuthKitPlugin /// Dependency order (G7) wins over Priority. /// Example: A (p. 100) → B (p-100, DependsOn A), C (p. 0) ⇒ order: A, C, B. /// - int Priority => 0; + int Priority => Metadata.Priority; /// /// Indicates whether the plugin is enabled. Defaults to true. @@ -130,7 +131,7 @@ public interface IAuthKitPlugin /// For plugins accepted by the preload gate and subsequently loaded, /// manifest.IsEnabled == instance.IsEnabled is part of consistency validation. /// - bool IsEnabled => true; + bool IsEnabled => Metadata.IsEnabled; /// /// Features/capabilities exposed by the plugin. Contract @@ -142,12 +143,21 @@ public interface IAuthKitPlugin /// extension method. /// Example: plugin.Supports("auth"). /// - IReadOnlySet Capabilities => EmptyCapabilities; + IReadOnlySet Capabilities => _capabilities ??= + System.Collections.Immutable.ImmutableHashSet.CreateRange(StringComparer.OrdinalIgnoreCase, Metadata.Capabilities); + + /// + /// Gets the metadata associated with the plugin. + /// + PluginMetadataAttribute Metadata => GetType().GetCustomAttribute() + ?? throw new InvalidOperationException($"Plugin {GetType().Name} is missing [PluginMetadata] attribute."); // Shared immutable empty capabilities set with OrdinalIgnoreCase comparer private static readonly IReadOnlySet EmptyCapabilities = System.Collections.Immutable.ImmutableHashSet.Create(StringComparer.OrdinalIgnoreCase); + private static IReadOnlySet? _capabilities; + /// /// Registers the plugin's services in the host dependency injection container. /// @@ -224,7 +234,7 @@ Task CheckHealthAsync(IServiceProvider services) => /// /// If the host version is lower than , the plugin is rejected. /// - SemanticVersion? MinHostVersion => null; + SemanticVersion? MinHostVersion => string.IsNullOrEmpty(Metadata.MinHostVersion) ? null : SemanticVersion.Parse(Metadata.MinHostVersion); /// /// Gets the list of plugin IDs this plugin depends on. @@ -236,7 +246,7 @@ Task CheckHealthAsync(IServiceProvider services) => /// - There are no duplicate dependencies. /// - There are no dependency cycles. /// - IReadOnlyList DependsOn => Array.Empty(); + IReadOnlyList DependsOn => Metadata.DependsOn; /// /// Gets the OpenAPI security schemes contributed by the plugin. From f09601f3521278a5e16c331d6e9e2ddb1ecd29ec Mon Sep 17 00:00:00 2001 From: "Rian.be" Date: Tue, 8 Sep 2026 19:31:25 +0200 Subject: [PATCH 11/18] feat(manifest): introduce plugin metadata and type resolver providers --- .../SemanticVersionJsonConverter.cs | 77 +++++++++++++++ .../Core/Providers/IPluginMetadataProvider.cs | 32 ++++++ .../Core/Providers/IPluginTypeResolver.cs | 30 ++++++ .../Core/Providers/PluginMetadataProvider.cs | 97 +++++++++++++++++++ .../Core/Providers/PluginTypeResolver.cs | 63 ++++++++++++ 5 files changed, 299 insertions(+) create mode 100644 tools/AuthKit.ManifestGenerator/Core/Generators/SemanticVersionJsonConverter.cs create mode 100644 tools/AuthKit.ManifestGenerator/Core/Providers/IPluginMetadataProvider.cs create mode 100644 tools/AuthKit.ManifestGenerator/Core/Providers/IPluginTypeResolver.cs create mode 100644 tools/AuthKit.ManifestGenerator/Core/Providers/PluginMetadataProvider.cs create mode 100644 tools/AuthKit.ManifestGenerator/Core/Providers/PluginTypeResolver.cs diff --git a/tools/AuthKit.ManifestGenerator/Core/Generators/SemanticVersionJsonConverter.cs b/tools/AuthKit.ManifestGenerator/Core/Generators/SemanticVersionJsonConverter.cs new file mode 100644 index 0000000..a3c876f --- /dev/null +++ b/tools/AuthKit.ManifestGenerator/Core/Generators/SemanticVersionJsonConverter.cs @@ -0,0 +1,77 @@ +using System.Text.Json; +using System.Text.Json.Serialization; +using AuthKit.Plugins.Abstractions.Models; + +namespace AuthKit.ManifestGenerator.Core.Generators; + +/// +/// Provides JSON serialization and deserialization support for +/// values. +/// +/// +/// +/// The converter represents semantic versions as their standard string +/// representation in generated JSON manifests. +/// +/// +/// During deserialization, the converter validates the input using +/// . +/// Invalid values result in a . +/// +/// +public sealed class SemanticVersionJsonConverter : JsonConverter +{ + /// + /// Reads and parses a value from JSON. + /// + /// + /// The JSON reader used to read the semantic version value. + /// + /// + /// The type being converted. + /// + /// + /// The serializer options used for the conversion. + /// + /// + /// The parsed value. + /// + /// + /// Thrown when the JSON value does not contain a valid semantic version. + /// + public override SemanticVersion Read( + ref Utf8JsonReader reader, + Type typeToConvert, + JsonSerializerOptions options) + { + var value = reader.GetString(); + + if (SemanticVersion.TryParse(value, out var version)) + { + return version; + } + + throw new JsonException( + "Invalid SemanticVersion format."); + } + + /// + /// Writes a value to JSON. + /// + /// + /// The JSON writer used to write the converted value. + /// + /// + /// The semantic version to serialize. + /// + /// + /// The serializer options used for the conversion. + /// + public override void Write( + Utf8JsonWriter writer, + SemanticVersion value, + JsonSerializerOptions options) + { + writer.WriteStringValue(value.ToString()); + } +} \ No newline at end of file diff --git a/tools/AuthKit.ManifestGenerator/Core/Providers/IPluginMetadataProvider.cs b/tools/AuthKit.ManifestGenerator/Core/Providers/IPluginMetadataProvider.cs new file mode 100644 index 0000000..4fe538b --- /dev/null +++ b/tools/AuthKit.ManifestGenerator/Core/Providers/IPluginMetadataProvider.cs @@ -0,0 +1,32 @@ +using System; +using AuthKit.Plugins.Abstractions.Models; + +namespace AuthKit.ManifestGenerator.Core.Providers; + +/// +/// Defines the contract for retrieving plugin manifest metadata from plugin type. +/// +/// +/// +/// Implementations are responsible for inspecting the specified plugin type +/// and constructing containing the metadata +/// exposed by the plugin. +/// +/// +/// The provider separates plugin metadata discovery from manifest generation, +/// allowing the discovered metadata to be consumed by different manifest +/// generation workflows. +/// +/// +public interface IPluginMetadataProvider +{ + /// + /// Retrieves the manifest metadata associated with the specified plugin type. + /// + /// + /// The representing plugin from which manifest + /// metadata is retrieved. + /// + /// A containing metadata associated with specified plugin type. + PluginManifest GetPluginManifest(Type pluginType); +} \ No newline at end of file diff --git a/tools/AuthKit.ManifestGenerator/Core/Providers/IPluginTypeResolver.cs b/tools/AuthKit.ManifestGenerator/Core/Providers/IPluginTypeResolver.cs new file mode 100644 index 0000000..6b6dfbd --- /dev/null +++ b/tools/AuthKit.ManifestGenerator/Core/Providers/IPluginTypeResolver.cs @@ -0,0 +1,30 @@ +using System; + +namespace AuthKit.ManifestGenerator.Core.Providers; + +/// +/// Defines the contract for resolving plugin type from plugin assembly. +/// +/// +/// +/// Implementations are responsible for loading the specified assembly and +/// identifying the type that represents the plugin implementation. +/// +/// +/// The resolver separates plugin type discovery from manifest generation, +/// allowing the resolved plugin type to be consumed by metadata providers +/// and other components without coupling them to assembly loading logic. +/// +/// +public interface IPluginTypeResolver +{ + /// + /// Resolves the plugin type from the specified assembly. + /// + /// The path to the plugin assembly from which the plugin type is resolved. + /// + /// The representing the plugin implementation found + /// in the specified assembly. + /// + Type GetPluginType(string assemblyPath); +} \ No newline at end of file diff --git a/tools/AuthKit.ManifestGenerator/Core/Providers/PluginMetadataProvider.cs b/tools/AuthKit.ManifestGenerator/Core/Providers/PluginMetadataProvider.cs new file mode 100644 index 0000000..7f4c64d --- /dev/null +++ b/tools/AuthKit.ManifestGenerator/Core/Providers/PluginMetadataProvider.cs @@ -0,0 +1,97 @@ +using System; +using System.Collections.Immutable; +using System.Reflection; +using AuthKit.Plugins.Abstractions.Contracts.Plugins; +using AuthKit.Plugins.Abstractions.Models; + +namespace AuthKit.ManifestGenerator.Core.Providers; + +/// +/// Provides plugin manifest metadata by inspecting plugin type decorated +/// with . +/// +/// +/// +/// The provider reads metadata declared through +/// and maps it to instance used by the manifest +/// generation pipeline. +/// +/// +/// Semantic versions declared by the plugin are parsed into +/// instances. Optional host version requirements +/// are parsed when valid value is provided. +/// +/// +public class PluginMetadataProvider : IPluginMetadataProvider +{ + /// + /// Retrieves the manifest metadata associated with the specified plugin type. + /// + /// The representing the plugin from which metadata is retrieved. + /// A containing the metadata declared by the plugin. + /// Thrown when is . + /// Thrown when the specified plugin type is not decorated with . + public PluginManifest GetPluginManifest(Type pluginType) + { + if (pluginType == null) + { + throw new ArgumentNullException(nameof(pluginType)); + } + + var attribute = pluginType.GetCustomAttribute(); + + if (attribute == null) + { + throw new InvalidOperationException( + "PluginMetadataAttribute not found on plugin type. " + + "Ensure the plugin class is decorated with [PluginMetadata]."); + } + + return MapToPluginManifest(attribute); + } + + /// + /// Maps plugin metadata declared by + /// to instance. + /// + /// The containing the plugin metadata. + /// A Populated with metadata declared by specified attribute. + /// Thrown when the plugin version is not a valid semantic version. + private static PluginManifest MapToPluginManifest(PluginMetadataAttribute attribute) + { + if (!SemanticVersion.TryParse(attribute.Version, out var version)) + { + throw new ArgumentException( + $"Version '{attribute.Version}' is not a valid semantic version."); + } + + SemanticVersion? minHostVersion = null; + + if (!string.IsNullOrEmpty(attribute.MinHostVersion) && + SemanticVersion.TryParse(attribute.MinHostVersion, out var parsedMinHost)) + { + minHostVersion = parsedMinHost; + } + + return new PluginManifest + { + Id = attribute.Id, + Name = attribute.Name, + DisplayName = attribute.DisplayName, + Description = attribute.Description, + Version = version, + Author = attribute.Author ?? string.Empty, + License = attribute.License ?? string.Empty, + LicenseUrl = attribute.LicenseUrl ?? string.Empty, + Homepage = attribute.Homepage ?? string.Empty, + RepositoryUrl = attribute.RepositoryUrl ?? string.Empty, + Tags = attribute.Tags, + DependsOn = attribute.DependsOn, + Capabilities = attribute.Capabilities.ToImmutableHashSet( + StringComparer.OrdinalIgnoreCase), + Priority = attribute.Priority, + IsEnabled = attribute.IsEnabled, + MinHostVersion = minHostVersion + }; + } +} \ No newline at end of file diff --git a/tools/AuthKit.ManifestGenerator/Core/Providers/PluginTypeResolver.cs b/tools/AuthKit.ManifestGenerator/Core/Providers/PluginTypeResolver.cs new file mode 100644 index 0000000..2a14e8c --- /dev/null +++ b/tools/AuthKit.ManifestGenerator/Core/Providers/PluginTypeResolver.cs @@ -0,0 +1,63 @@ +using System; +using System.Linq; +using System.Reflection; +using AuthKit.Plugins.Abstractions.Contracts; + +namespace AuthKit.ManifestGenerator.Core.Providers; + +/// +/// Resolves concrete plugin types from plugin assemblies. +/// +/// +/// +/// The resolver loads the specified assembly and searches for concrete, +/// non abstract class implementing . +/// +/// +/// The resolved type is used by the manifest generation pipeline to inspect +/// plugin metadata without requiring the plugin to be instantiated. +/// +/// +public sealed class PluginTypeResolver : IPluginTypeResolver +{ + /// + /// Resolves the plugin type from the specified assembly. + /// + /// The path to the assembly containing the plugin implementation. + /// + /// The concrete implementing + /// found in the specified assembly. + /// + /// + /// Thrown when is + /// , empty, or consists only of whitespace. + /// + /// + /// Thrown when the assembly cannot be loaded or does not contain + /// concrete implementation of . + /// + public Type GetPluginType(string assemblyPath) + { + ArgumentException.ThrowIfNullOrWhiteSpace(assemblyPath); + + try + { + var assembly = Assembly.LoadFrom(assemblyPath); + + return assembly.GetTypes() + .FirstOrDefault(type => + type.IsClass && + !type.IsAbstract && + typeof(IAuthKitPlugin).IsAssignableFrom(type)) + ?? throw new InvalidOperationException( + $"No concrete {nameof(IAuthKitPlugin)} implementation was found " + + $"in assembly '{assembly.FullName}'."); + } + catch (Exception ex) when (ex is not InvalidOperationException) + { + throw new InvalidOperationException( + $"Failed to load plugin assembly '{assemblyPath}'.", + ex); + } + } +} \ No newline at end of file From 73ce3ff876d210024c9928b6ec8f893a8001bd6d Mon Sep 17 00:00:00 2001 From: "Rian.be" Date: Tue, 8 Sep 2026 19:39:26 +0200 Subject: [PATCH 12/18] feat(manifest): add assembly based manifest generation --- .../Core/Generators/IManifestGenerator.cs | 35 +++ .../Core/Generators/ManifestGenerator.cs | 249 ++++++++++++++++++ 2 files changed, 284 insertions(+) create mode 100644 tools/AuthKit.ManifestGenerator/Core/Generators/IManifestGenerator.cs create mode 100644 tools/AuthKit.ManifestGenerator/Core/Generators/ManifestGenerator.cs diff --git a/tools/AuthKit.ManifestGenerator/Core/Generators/IManifestGenerator.cs b/tools/AuthKit.ManifestGenerator/Core/Generators/IManifestGenerator.cs new file mode 100644 index 0000000..c996e13 --- /dev/null +++ b/tools/AuthKit.ManifestGenerator/Core/Generators/IManifestGenerator.cs @@ -0,0 +1,35 @@ +using AuthKit.Plugins.Abstractions.Models; + +namespace AuthKit.ManifestGenerator.Core.Generators; + +/// +/// Defines the contract for generating plugin manifest files from plugin +/// assemblies or existing instances. +/// +/// +/// +/// Implementations are responsible for producing serialized plugin manifest +/// and writing it to the specified output path. +/// +/// +/// A manifest can be generated either by inspecting a plugin assembly and +/// discovering its metadata, or by serializing an already constructed +/// instance. +/// +/// +public interface IManifestGenerator +{ + /// + /// Generates plugin manifest by inspecting the specified plugin assembly. + /// + /// The path to the plugin assembly from which manifest metadata is discovered. + /// The path where the generated manifest file is written. + void Generate(string pluginAssemblyPath, string outputManifestPath); + + /// + /// Generates plugin manifest from the specified manifest model. + /// + /// The plugin manifest containing the metadata to be serialized. + /// The path where the generated manifest file is written. + void Generate(PluginManifest pluginManifest, string outputManifestPath); +} \ No newline at end of file diff --git a/tools/AuthKit.ManifestGenerator/Core/Generators/ManifestGenerator.cs b/tools/AuthKit.ManifestGenerator/Core/Generators/ManifestGenerator.cs new file mode 100644 index 0000000..cf7d884 --- /dev/null +++ b/tools/AuthKit.ManifestGenerator/Core/Generators/ManifestGenerator.cs @@ -0,0 +1,249 @@ +using System; +using System.IO; +using System.Text.Json; +using System.Text.Json.Serialization; +using AuthKit.Plugins.Abstractions.Models; +using AuthKit.ManifestGenerator.Core.Providers; + +namespace AuthKit.ManifestGenerator.Core.Generators; + +/// +/// Generates serialized plugin manifests from plugin assemblies or existing +/// instances. +/// +/// +/// +/// The generator resolves the plugin type from the specified assembly and +/// retrieves its manifest metadata through the configured +/// . +/// +/// +/// Generated manifests are serialized to JSON with indentation enabled and +/// include a custom converter for values. +/// +/// +public class ManifestGenerator : IManifestGenerator +{ + private readonly IPluginTypeResolver _pluginTypeResolver; + private readonly IPluginMetadataProvider _pluginMetadataProvider; + + /// + /// Initializes a new instance of the class. + /// + /// + /// The resolver responsible for discovering the plugin type from an assembly. + /// + /// + /// The provider responsible for retrieving manifest metadata from the + /// resolved plugin type. + /// + /// + /// Thrown when or + /// is . + /// + public ManifestGenerator( + IPluginTypeResolver pluginTypeResolver, + IPluginMetadataProvider pluginMetadataProvider) + { + _pluginTypeResolver = pluginTypeResolver + ?? throw new ArgumentNullException(nameof(pluginTypeResolver)); + + _pluginMetadataProvider = pluginMetadataProvider + ?? throw new ArgumentNullException(nameof(pluginMetadataProvider)); + } + + /// + /// Generates a plugin manifest by inspecting the specified plugin assembly. + /// + /// + /// The path to the plugin assembly from which the plugin type and metadata + /// are resolved. + /// + /// + /// The path where the generated JSON manifest is written. + /// + /// + /// Thrown when no plugin type can be resolved from the specified assembly + /// or when the generated manifest cannot be written to the output path. + /// + public void Generate( + string pluginAssemblyPath, + string outputManifestPath) + { + Console.WriteLine( + "Generating manifest for plugin at: {0}", + pluginAssemblyPath); + + Console.WriteLine( + "Output manifest path: {0}", + outputManifestPath); + + var pluginType = _pluginTypeResolver.GetPluginType(pluginAssemblyPath); + + if (pluginType == null) + { + throw new InvalidOperationException("Plugin type not found."); + } + + var manifest = _pluginMetadataProvider.GetPluginManifest(pluginType); + + Console.WriteLine("\n--- Plugin Manifest ---"); + Console.WriteLine("Id: {0}", manifest.Id); + Console.WriteLine("Name: {0}", manifest.Name); + Console.WriteLine( + "DisplayName: {0}", + manifest.DisplayName ?? "(not set)"); + Console.WriteLine("Description: {0}", manifest.Description); + Console.WriteLine("Version: {0}", manifest.Version); + Console.WriteLine( + "Author: {0}", + manifest.Author ?? "(not set)"); + Console.WriteLine( + "License: {0}", + manifest.License ?? "(not set)"); + Console.WriteLine( + "LicenseUrl: {0}", + manifest.LicenseUrl ?? "(not set)"); + Console.WriteLine( + "Homepage: {0}", + manifest.Homepage ?? "(not set)"); + Console.WriteLine( + "RepositoryUrl: {0}", + manifest.RepositoryUrl ?? "(not set)"); + Console.WriteLine( + "Tags: {0}", + string.Join(", ", manifest.Tags)); + Console.WriteLine( + "DependsOn: {0}", + string.Join(", ", manifest.DependsOn)); + Console.WriteLine( + "Capabilities: {0}", + string.Join(", ", manifest.Capabilities)); + Console.WriteLine("Priority: {0}", manifest.Priority); + Console.WriteLine("IsEnabled: {0}", manifest.IsEnabled); + Console.WriteLine( + "MinHostVersion: {0}", + manifest.MinHostVersion?.ToString() ?? "(not set)"); + + SaveManifestToFile(manifest, outputManifestPath); + } + + /// + /// Generates a plugin manifest from the specified manifest model. + /// + /// + /// The plugin manifest containing the metadata to serialize. + /// + /// + /// The path where the generated JSON manifest is written. + /// + /// + /// Thrown when the generated manifest cannot be written to the output path. + /// + public void Generate( + PluginManifest pluginManifest, + string outputManifestPath) + { + Console.WriteLine("Generating manifest for plugin."); + + Console.WriteLine( + "Output manifest path: {0}", + outputManifestPath); + + Console.WriteLine("\n--- Plugin Manifest ---"); + Console.WriteLine("Id: {0}", pluginManifest.Id); + Console.WriteLine("Name: {0}", pluginManifest.Name); + Console.WriteLine( + "DisplayName: {0}", + pluginManifest.DisplayName ?? "(not set)"); + Console.WriteLine( + "Description: {0}", + pluginManifest.Description); + Console.WriteLine("Version: {0}", pluginManifest.Version); + Console.WriteLine( + "Author: {0}", + pluginManifest.Author ?? "(not set)"); + Console.WriteLine( + "License: {0}", + pluginManifest.License ?? "(not set)"); + Console.WriteLine( + "LicenseUrl: {0}", + pluginManifest.LicenseUrl ?? "(not set)"); + Console.WriteLine( + "Homepage: {0}", + pluginManifest.Homepage ?? "(not set)"); + Console.WriteLine( + "RepositoryUrl: {0}", + pluginManifest.RepositoryUrl ?? "(not set)"); + Console.WriteLine( + "Tags: {0}", + string.Join(", ", pluginManifest.Tags)); + Console.WriteLine( + "DependsOn: {0}", + string.Join(", ", pluginManifest.DependsOn)); + Console.WriteLine( + "Capabilities: {0}", + string.Join(", ", pluginManifest.Capabilities)); + Console.WriteLine( + "Priority: {0}", + pluginManifest.Priority); + Console.WriteLine( + "IsEnabled: {0}", + pluginManifest.IsEnabled); + Console.WriteLine( + "MinHostVersion: {0}", + pluginManifest.MinHostVersion?.ToString() ?? "(not set)"); + + SaveManifestToFile(pluginManifest, outputManifestPath); + } + + /// + /// Serializes the specified plugin manifest and writes it to the output file. + /// + /// + /// The plugin manifest to serialize. + /// + /// + /// The path where the serialized manifest is written. + /// + /// + /// Thrown when the manifest cannot be serialized or written to the specified + /// output path. + /// + private static void SaveManifestToFile( + PluginManifest manifest, + string outputManifestPath) + { + try + { + var jsonOptions = new JsonSerializerOptions + { + WriteIndented = true + }; + + jsonOptions.Converters.Add( + new SemanticVersionJsonConverter()); + + var json = JsonSerializer.Serialize( + manifest, + jsonOptions); + + File.WriteAllText( + outputManifestPath, + json); + + Console.WriteLine( + "\n--- Manifest Generated Successfully ---"); + + Console.WriteLine( + "Manifest saved to: {0}", + outputManifestPath); + } + catch (Exception ex) + { + throw new InvalidOperationException( + "Failed to save manifest to file.", + ex); + } + } +} \ No newline at end of file From efdf210b6f4adf02e804990d923840fae71cca18 Mon Sep 17 00:00:00 2001 From: "Rian.be" Date: Tue, 8 Sep 2026 20:01:04 +0200 Subject: [PATCH 13/18] feat(manifest): introduce example AuthKit plugin --- .../ExamplePlugin/ExamplePlugin.csproj | 8 ++ .../ExamplePlugin/PluginMetadataAttribute.cs | 100 +++++++++++++++ .../examples/ExamplePlugin/Program.cs | 77 ++++++++++++ .../examples/ExamplePlugin/SemanticVersion.cs | 118 ++++++++++++++++++ 4 files changed, 303 insertions(+) create mode 100644 tools/AuthKit.ManifestGenerator/examples/ExamplePlugin/ExamplePlugin.csproj create mode 100644 tools/AuthKit.ManifestGenerator/examples/ExamplePlugin/PluginMetadataAttribute.cs create mode 100644 tools/AuthKit.ManifestGenerator/examples/ExamplePlugin/Program.cs create mode 100644 tools/AuthKit.ManifestGenerator/examples/ExamplePlugin/SemanticVersion.cs diff --git a/tools/AuthKit.ManifestGenerator/examples/ExamplePlugin/ExamplePlugin.csproj b/tools/AuthKit.ManifestGenerator/examples/ExamplePlugin/ExamplePlugin.csproj new file mode 100644 index 0000000..876c3c3 --- /dev/null +++ b/tools/AuthKit.ManifestGenerator/examples/ExamplePlugin/ExamplePlugin.csproj @@ -0,0 +1,8 @@ + + + net10.0 + enable + enable + + + \ No newline at end of file diff --git a/tools/AuthKit.ManifestGenerator/examples/ExamplePlugin/PluginMetadataAttribute.cs b/tools/AuthKit.ManifestGenerator/examples/ExamplePlugin/PluginMetadataAttribute.cs new file mode 100644 index 0000000..92d9613 --- /dev/null +++ b/tools/AuthKit.ManifestGenerator/examples/ExamplePlugin/PluginMetadataAttribute.cs @@ -0,0 +1,100 @@ +using System; + +namespace ExamplePlugin; + +/// +/// Specifies metadata used to identify and describe an AuthKit plugin. +/// +/// +/// +/// The attribute is applied to a plugin implementation and provides the +/// metadata required by the manifest generation pipeline. +/// +/// +/// The plugin identifier, version, tags, capabilities, and dependencies are +/// supplied explicitly. When an optional display name or plugin name is not +/// provided, the plugin identifier is used as the default name. +/// +/// +[AttributeUsage(AttributeTargets.Class)] +public class PluginMetadataAttribute : Attribute +{ + /// + /// Gets the unique identifier of the plugin. + /// + public string Id { get; } + + /// + /// Gets the name of the plugin. + /// + public string Name { get; } + + /// + /// Gets the optional display name of the plugin. + /// + public string? DisplayName { get; } + + /// + /// Gets the description of the plugin. + /// + public string Description { get; } + + /// + /// Gets the semantic version of the plugin. + /// + public string Version { get; } + + /// + /// Gets the tags associated with the plugin. + /// + public string[] Tags { get; } + + /// + /// Gets the identifiers of plugins that this plugin depends on. + /// + public string[] DependsOn { get; } + + /// + /// Gets the capabilities provided by the plugin. + /// + public string[] Capabilities { get; } + + /// + /// Initializes a new instance of the class. + /// + /// + /// The unique identifier of the plugin. + /// + /// The semantic version of the plugin. + /// The tags associated with the plugin. + /// The capabilities provided by the plugin. + /// The identifiers of plugins required by this plugin. + /// The optional name of the plugin. When omitted, + /// is used as the plugin name. + /// + /// The optional user facing display name of the plugin. + /// The description of the plugin. + /// Thrown when the description, tags, or capabilities are not provided. + public PluginMetadataAttribute( + string id, + string version, + string[] tags, + string[] capabilities, + string[] dependsOn, + string? name = null, + string? displayName = null, + string? description = null) + { + Id = id; + Name = name ?? id; + DisplayName = displayName; + Description = description + ?? throw new ArgumentException("Description cannot be empty."); + Version = version; + Tags = tags + ?? throw new ArgumentException("Tags cannot be empty."); + DependsOn = dependsOn ?? Array.Empty(); + Capabilities = capabilities + ?? throw new ArgumentException("Capabilities cannot be empty."); + } +} diff --git a/tools/AuthKit.ManifestGenerator/examples/ExamplePlugin/Program.cs b/tools/AuthKit.ManifestGenerator/examples/ExamplePlugin/Program.cs new file mode 100644 index 0000000..3bc1e4b --- /dev/null +++ b/tools/AuthKit.ManifestGenerator/examples/ExamplePlugin/Program.cs @@ -0,0 +1,77 @@ +using System; +using System.Threading.Tasks; +using AuthKit.Plugins.Abstractions.Contracts; +using AuthKit.Plugins.Abstractions.Models; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; + +namespace ExamplePlugin; + +/// +/// Provides minimal example implementation of an AuthKit plugin. +/// +/// +/// +/// The plugin demonstrates the basic structure required to implement +/// and declare plugin metadata using +/// . +/// +/// +/// This implementation does not register any additional services and always +/// reports healthy state when its health check is executed. +/// +/// +[PluginMetadata( + Id = "example-plugin", + Name = "Example Plugin", + Description = "An example plugin for AuthKit.", + Version = "1.0.0", + Tags = new[] { "example" }, + Capabilities = new[] { "example" }, + DependsOn = new string[0] +)] +public class ExamplePlugin : IAuthKitPlugin +{ + /// + /// Gets the unique identifier of the plugin. + /// + public string Id => "example-plugin"; + + /// + /// Gets the name of the plugin. + /// + public string Name => "Example Plugin"; + + /// + /// Gets the description of the plugin. + /// + public string Description => "An example plugin for AuthKit."; + + /// + /// Gets the semantic version of the plugin. + /// + public SemanticVersion Version => new(1, 0, 0); + + /// + /// Registers services required by the plugin. + /// + /// The used to register plugin services. + /// The containing the application configuration. + public void ConfigureServices( + IServiceCollection services, + IConfiguration configuration) + { + // Register services here. + } + + /// + /// Performs a health check for the plugin. + /// + /// The used to resolve services required for the health check. + /// + /// A task containing when the plugin is healthy; + /// otherwise, . + /// + public Task CheckHealthAsync(IServiceProvider services) + => Task.FromResult(true); +} diff --git a/tools/AuthKit.ManifestGenerator/examples/ExamplePlugin/SemanticVersion.cs b/tools/AuthKit.ManifestGenerator/examples/ExamplePlugin/SemanticVersion.cs new file mode 100644 index 0000000..b3e89e8 --- /dev/null +++ b/tools/AuthKit.ManifestGenerator/examples/ExamplePlugin/SemanticVersion.cs @@ -0,0 +1,118 @@ +namespace ExamplePlugin; + +/// +/// Represents semantic version consisting of major, minor, and patch +/// version components. +/// +/// +/// +/// The version components are compared in hierarchical order: major first, +/// followed by minor and patch. A higher major, minor, or patch component +/// represents higher version. +/// +/// +/// Equality is based on all three version components. The textual +/// representation follows the major.minor.patch format. +/// +/// +public readonly struct SemanticVersion : + IComparable, + IEquatable +{ + /// + /// Gets the major version component. + /// + public int Major { get; } + + /// + /// Gets the minor version component. + /// + public int Minor { get; } + + /// + /// Gets the patch version component. + /// + public int Patch { get; } + + /// + /// Initializes new instance of the struct. + /// + /// The major version component. + /// The minor version component. + /// The patch version component. + public SemanticVersion(int major, int minor, int patch) + { + Major = major; + Minor = minor; + Patch = patch; + } + + /// + /// Compares this version with another semantic version. + /// + /// + /// The to compare with this instance. + /// + /// + /// A value less than zero if this version precedes + /// , zero if both versions are equal, or a value + /// greater than zero if this version follows . + /// + public int CompareTo(SemanticVersion other) + { + if (Major != other.Major) + { + return Major.CompareTo(other.Major); + } + + if (Minor != other.Minor) + { + return Minor.CompareTo(other.Minor); + } + + return Patch.CompareTo(other.Patch); + } + + /// + /// Determines whether this version is equal to another semantic version. + /// + /// + /// The to compare with this instance. + /// + /// + /// when all version components are equal; + /// otherwise, . + /// + public bool Equals(SemanticVersion other) + { + return Major == other.Major && + Minor == other.Minor && + Patch == other.Patch; + } + + /// + /// Determines whether this version is equal to the specified object. + /// + /// The object to compare with this version. + /// + /// when is a + /// with identical version components; + /// otherwise, . + /// + public override bool Equals(object? obj) + => obj is SemanticVersion other && Equals(other); + + /// + /// Returns the hash code for this semantic version. + /// + /// A hash code based on the major, minor, and patch version components. + public override int GetHashCode() + => HashCode.Combine(Major, Minor, Patch); + + /// + /// Returns the string representation of this semantic version. + /// + /// The version formatted as major.minor.patch. + public override string ToString() + => $"{Major}.{Minor}.{Patch}"; +} \ No newline at end of file From f1ad36f426d85c6a0dd5c37cb9ba9e87782cc97d Mon Sep 17 00:00:00 2001 From: "Rian.be" Date: Tue, 8 Sep 2026 20:58:42 +0200 Subject: [PATCH 14/18] feat(manifest): introduce manifest generator tool --- .../AuthKit.ManifestGenerator.csproj | 31 ++++++++++ .../CLI/AuthKit.ManifestGenerator.CLI.csproj | 15 +++++ .../AuthKit.ManifestGenerator/CLI/Program.cs | 61 +++++++++++++++++++ .../AuthKit.ManifestGenerator.Core.csproj | 22 +++++++ .../Core/ServiceCollectionExtensions.cs | 50 +++++++++++++++ tools/AuthKit.ManifestGenerator/Taskfile.yml | 43 +++++++++++++ 6 files changed, 222 insertions(+) create mode 100644 tools/AuthKit.ManifestGenerator/AuthKit.ManifestGenerator.csproj create mode 100644 tools/AuthKit.ManifestGenerator/CLI/AuthKit.ManifestGenerator.CLI.csproj create mode 100644 tools/AuthKit.ManifestGenerator/CLI/Program.cs create mode 100644 tools/AuthKit.ManifestGenerator/Core/AuthKit.ManifestGenerator.Core.csproj create mode 100644 tools/AuthKit.ManifestGenerator/Core/ServiceCollectionExtensions.cs create mode 100644 tools/AuthKit.ManifestGenerator/Taskfile.yml diff --git a/tools/AuthKit.ManifestGenerator/AuthKit.ManifestGenerator.csproj b/tools/AuthKit.ManifestGenerator/AuthKit.ManifestGenerator.csproj new file mode 100644 index 0000000..969b4f3 --- /dev/null +++ b/tools/AuthKit.ManifestGenerator/AuthKit.ManifestGenerator.csproj @@ -0,0 +1,31 @@ + + + + net10.0 + enable + enable + false + true + false + false + false + true + + + + + + + + + + + + + + + + NU1008;NU1507 + + + diff --git a/tools/AuthKit.ManifestGenerator/CLI/AuthKit.ManifestGenerator.CLI.csproj b/tools/AuthKit.ManifestGenerator/CLI/AuthKit.ManifestGenerator.CLI.csproj new file mode 100644 index 0000000..49dcc40 --- /dev/null +++ b/tools/AuthKit.ManifestGenerator/CLI/AuthKit.ManifestGenerator.CLI.csproj @@ -0,0 +1,15 @@ + + + + net10.0 + enable + enable + Exe + + + + + + + + diff --git a/tools/AuthKit.ManifestGenerator/CLI/Program.cs b/tools/AuthKit.ManifestGenerator/CLI/Program.cs new file mode 100644 index 0000000..90fde27 --- /dev/null +++ b/tools/AuthKit.ManifestGenerator/CLI/Program.cs @@ -0,0 +1,61 @@ +using System; +using System.IO; +using System.Threading.Tasks; +using AuthKit.ManifestGenerator.Core; +using AuthKit.ManifestGenerator.Core.Generators; +using Microsoft.Extensions.DependencyInjection; + +namespace AuthKit.ManifestGenerator.CLI; + +class Program +{ + static async Task Main(string[] args) + { + if (args.Length < 2) + { + Console.WriteLine("Usage: dotnet run -- --input --output "); + return 1; + } + + string? input = null; + string? output = null; + + for (int i = 0; i < args.Length; i++) + { + if (args[i] == "--input" || args[i] == "-i") + { + input = args[i + 1]; + } + else if (args[i] == "--output" || args[i] == "-o") + { + output = args[i + 1]; + } + } + + if (input == null || output == null) + { + Console.WriteLine("Error: Missing required arguments."); + Console.WriteLine("Usage: dotnet run -- --input --output "); + return 1; + } + + var serviceCollection = new ServiceCollection(); + serviceCollection.AddManifestGeneratorServices(); + var serviceProvider = serviceCollection.BuildServiceProvider(); + + var manifestGenerator = serviceProvider.GetRequiredService(); + try + { + manifestGenerator.Generate(input, output); + Console.WriteLine("\n--- Success ---"); + Console.WriteLine("Manifest generated successfully."); + return 0; + } + catch (Exception ex) + { + Console.WriteLine("\n--- Error ---"); + Console.WriteLine("Failed to generate manifest: {0}", ex.Message); + return 1; + } + } +} diff --git a/tools/AuthKit.ManifestGenerator/Core/AuthKit.ManifestGenerator.Core.csproj b/tools/AuthKit.ManifestGenerator/Core/AuthKit.ManifestGenerator.Core.csproj new file mode 100644 index 0000000..5682030 --- /dev/null +++ b/tools/AuthKit.ManifestGenerator/Core/AuthKit.ManifestGenerator.Core.csproj @@ -0,0 +1,22 @@ + + + + net10.0 + enable + enable + false + + + + + + + + + + + + + + + diff --git a/tools/AuthKit.ManifestGenerator/Core/ServiceCollectionExtensions.cs b/tools/AuthKit.ManifestGenerator/Core/ServiceCollectionExtensions.cs new file mode 100644 index 0000000..02652b1 --- /dev/null +++ b/tools/AuthKit.ManifestGenerator/Core/ServiceCollectionExtensions.cs @@ -0,0 +1,50 @@ +using System; +using Microsoft.Extensions.DependencyInjection; +using AuthKit.ManifestGenerator.Core.Generators; +using AuthKit.ManifestGenerator.Core.Providers; + +namespace AuthKit.ManifestGenerator.Core; + +/// +/// Provides extension methods for registering manifest generator services +/// with an . +/// +/// +/// +/// The registered services provide the core functionality required to discover +/// plugin types, retrieve plugin metadata, and generate plugin manifests. +/// +/// +/// All manifest generator services are registered with a transient lifetime, +/// allowing each operation to receive fresh service instances from the +/// dependency injection container. +/// +/// +public static class ServiceCollectionExtensions +{ + /// + /// Registers the services required for plugin manifest generation. + /// + /// + /// The to which the manifest generator + /// services are registered. + /// + /// + /// The same instance so that additional + /// service registrations can be chained. + /// + /// + /// Thrown when is . + /// + public static IServiceCollection AddManifestGeneratorServices( + this IServiceCollection services) + { + ArgumentNullException.ThrowIfNull(services); + + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + + return services; + } +} \ No newline at end of file diff --git a/tools/AuthKit.ManifestGenerator/Taskfile.yml b/tools/AuthKit.ManifestGenerator/Taskfile.yml new file mode 100644 index 0000000..3fcd73f --- /dev/null +++ b/tools/AuthKit.ManifestGenerator/Taskfile.yml @@ -0,0 +1,43 @@ +version: '3' + +vars: + PROJECT_ROOT: . + CORE_PROJECT: Core/AuthKit.ManifestGenerator.Core.csproj + CLI_PROJECT: CLI/AuthKit.ManifestGenerator.CLI.csproj + CONFIGURATION: Debug + EXAMPLE_INPUT: examples/example.dll + EXAMPLE_OUTPUT: examples/manifest.json + +env: + DOTNET_CLI_TELEMETRY_OPTOUT: 1 + +tasks: + default: + desc: Wyświetla dostępne zadania + cmds: + - task --list + + build: + desc: Buduje cały projekt bez przywracania pakietów + cmds: + - dotnet build {{.CORE_PROJECT}} --configuration {{.CONFIGURATION}} --no-restore + - dotnet build {{.CLI_PROJECT}} --configuration {{.CONFIGURATION}} --no-restore + + clean: + desc: Czyści cały projekt + cmds: + - dotnet clean {{.CORE_PROJECT}} --configuration {{.CONFIGURATION}} + - dotnet clean {{.CLI_PROJECT}} --configuration {{.CONFIGURATION}} + + run: + desc: Uruchamia CLI AuthKit.ManifestGenerator + deps: + - build + cmds: + - mkdir -p examples + - dotnet run --project {{.CLI_PROJECT}} --configuration {{.CONFIGURATION}} --no-build -- --input {{.EXAMPLE_INPUT}} --output {{.EXAMPLE_OUTPUT}} + + example: + desc: Generuje przykładowy manifest + deps: + - run \ No newline at end of file From 6920cbd12dcbc7fd273173b2be3d336a9a98bb22 Mon Sep 17 00:00:00 2001 From: "Rian.be" Date: Tue, 8 Sep 2026 21:09:11 +0200 Subject: [PATCH 15/18] feat(plugin): introduce metadata attribute and manifest generation --- .../Plugins/PluginMetadataAttribute.cs | 42 ++++++++++++++ src/Plugins/Solutions/DevTokens/Taskfile.yml | 56 +++++++++++++++++++ tools/AuthKit.ManifestGenerator/Taskfile.yml | 28 +++++----- 3 files changed, 112 insertions(+), 14 deletions(-) create mode 100644 src/Plugins/Abstractions/Contracts/Plugins/PluginMetadataAttribute.cs create mode 100644 src/Plugins/Solutions/DevTokens/Taskfile.yml diff --git a/src/Plugins/Abstractions/Contracts/Plugins/PluginMetadataAttribute.cs b/src/Plugins/Abstractions/Contracts/Plugins/PluginMetadataAttribute.cs new file mode 100644 index 0000000..0c7e762 --- /dev/null +++ b/src/Plugins/Abstractions/Contracts/Plugins/PluginMetadataAttribute.cs @@ -0,0 +1,42 @@ +namespace AuthKit.Plugins.Abstractions.Contracts.Plugins; + +/// +/// Atrubut metadanych pluginu AuthKit. +/// +[AttributeUsage(AttributeTargets.Class)] +public class PluginMetadataAttribute( + string id, + string version, + string[] tags, + string[]? dependsOn, + string[] capabilities, + string? name = null, + string? displayName = null, + string? description = null, + string? author = null, + string? license = null, + string? licenseUrl = null, + string? homepage = null, + string? repositoryUrl = null, + int priority = 0, + bool isEnabled = true, + string? minHostVersion = null) + : Attribute +{ + public string Id { get; } = id; + public string Name { get; } = name ?? id; + public string? DisplayName { get; } = displayName; + public string Description { get; } = description ?? throw new ArgumentException("Description cannot be empty."); + public string Version { get; } = version; + public string? Author { get; } = author; + public string? License { get; } = license; + public string? LicenseUrl { get; } = licenseUrl; + public string? Homepage { get; } = homepage; + public string? RepositoryUrl { get; } = repositoryUrl; + public string[] Tags { get; } = tags ?? throw new ArgumentException("Tags cannot be empty."); + public string[] DependsOn { get; } = dependsOn ?? []; + public string[] Capabilities { get; } = capabilities ?? throw new ArgumentException("Capabilities cannot be empty."); + public int Priority { get; } = priority; + public bool IsEnabled { get; } = isEnabled; + public string? MinHostVersion { get; } = minHostVersion; +} \ No newline at end of file diff --git a/src/Plugins/Solutions/DevTokens/Taskfile.yml b/src/Plugins/Solutions/DevTokens/Taskfile.yml new file mode 100644 index 0000000..e056a9c --- /dev/null +++ b/src/Plugins/Solutions/DevTokens/Taskfile.yml @@ -0,0 +1,56 @@ +version: '3' + +vars: + PROJECT_NAME: DevTokens # Name of the project + CONFIGURATION: Debug # Build configuration (Debug/Release) + TARGET_FRAMEWORK: net10.0 # Target .NET framework + OUTPUT_DIR: bin/{{.CONFIGURATION}}/{{.TARGET_FRAMEWORK}} # Output directory for builds + PROJECT_FILE: '{{.PROJECT_NAME}}.csproj' # Path to the project file + ASSEMBLY_FILE: '{{.USER_WORKING_DIR}}/{{.OUTPUT_DIR}}/{{.PROJECT_NAME}}.dll' # Path to the compiled DLL + MANIFEST_OUTPUT: '{{.USER_WORKING_DIR}}/manifest.json' # Output path for the generated manifest + MANIFEST_GENERATOR: ../../../../tools/AuthKit.ManifestGenerator # Path to the manifest generator tool + +env: + DOTNET_CLI_TELEMETRY_OPTOUT: '1' # Disables .NET CLI telemetry + +tasks: + default: + desc: Lists available tasks + cmds: + - task --list + + build: + desc: Builds the DevTokens project without restoring NuGet packages + cmds: + - dotnet build {{.PROJECT_FILE}} --configuration {{.CONFIGURATION}} --no-restore + + clean: + desc: Cleans the DevTokens project (deletes build artifacts) + cmds: + - dotnet clean {{.PROJECT_FILE}} --configuration {{.CONFIGURATION}} + + generate-manifest: + desc: Generates a manifest for DevTokens using AuthKit.ManifestGenerator + deps: + - build # Ensures the project is built before generating the manifest + - build-manifest-generator # Ensures the manifest generator is built + cmds: + - cd {{.MANIFEST_GENERATOR}} && dotnet run --project CLI/AuthKit.ManifestGenerator.CLI.csproj --configuration {{.CONFIGURATION}} --no-build -- --input {{.ASSEMBLY_FILE}} --output {{.MANIFEST_OUTPUT}} + - echo "Manifest generated at {{.MANIFEST_OUTPUT}}" + + build-manifest-generator: + desc: Builds the AuthKit.ManifestGenerator tool + cmds: + - cd {{.MANIFEST_GENERATOR}} && dotnet build --configuration {{.CONFIGURATION}} --no-restore + + validate: + desc: Cleans and builds the project + cmds: + - task: clean + - task: build + + ci: + desc: Full validation of the project and manifest generation (CI-friendly) + cmds: + - task: validate + - task: generate-manifest diff --git a/tools/AuthKit.ManifestGenerator/Taskfile.yml b/tools/AuthKit.ManifestGenerator/Taskfile.yml index 3fcd73f..5c5872e 100644 --- a/tools/AuthKit.ManifestGenerator/Taskfile.yml +++ b/tools/AuthKit.ManifestGenerator/Taskfile.yml @@ -1,43 +1,43 @@ version: '3' vars: - PROJECT_ROOT: . - CORE_PROJECT: Core/AuthKit.ManifestGenerator.Core.csproj - CLI_PROJECT: CLI/AuthKit.ManifestGenerator.CLI.csproj - CONFIGURATION: Debug - EXAMPLE_INPUT: examples/example.dll - EXAMPLE_OUTPUT: examples/manifest.json + PROJECT_ROOT: . # Root directory of the project + CORE_PROJECT: Core/AuthKit.ManifestGenerator.Core.csproj # Path to the Core project + CLI_PROJECT: CLI/AuthKit.ManifestGenerator.CLI.csproj # Path to the CLI project + CONFIGURATION: Debug # Build configuration (Debug/Release) + EXAMPLE_INPUT: examples/example.dll # Example input DLL file + EXAMPLE_OUTPUT: examples/manifest.json # Output manifest file env: - DOTNET_CLI_TELEMETRY_OPTOUT: 1 + DOTNET_CLI_TELEMETRY_OPTOUT: 1 # Disables .NET CLI telemetry tasks: default: - desc: Wyświetla dostępne zadania + desc: Lists available tasks cmds: - task --list build: - desc: Buduje cały projekt bez przywracania pakietów + desc: Builds the entire project without restoring packages cmds: - dotnet build {{.CORE_PROJECT}} --configuration {{.CONFIGURATION}} --no-restore - dotnet build {{.CLI_PROJECT}} --configuration {{.CONFIGURATION}} --no-restore clean: - desc: Czyści cały projekt + desc: Cleans the entire project (deletes build artifacts) cmds: - dotnet clean {{.CORE_PROJECT}} --configuration {{.CONFIGURATION}} - dotnet clean {{.CLI_PROJECT}} --configuration {{.CONFIGURATION}} run: - desc: Uruchamia CLI AuthKit.ManifestGenerator + desc: Runs the AuthKit.ManifestGenerator CLI deps: - - build + - build # Ensures the project is built before running cmds: - mkdir -p examples - dotnet run --project {{.CLI_PROJECT}} --configuration {{.CONFIGURATION}} --no-build -- --input {{.EXAMPLE_INPUT}} --output {{.EXAMPLE_OUTPUT}} example: - desc: Generuje przykładowy manifest + desc: Generates an example manifest deps: - - run \ No newline at end of file + - run From c66382a96d28e766ca17bc2490b82bc021c47b46 Mon Sep 17 00:00:00 2001 From: "Rian.be" Date: Tue, 8 Sep 2026 21:13:41 +0200 Subject: [PATCH 16/18] refactor(plugin): migrate metadata to attributes --- .../Abstractions/Models/PluginManifest.cs | 172 ++++++++++++++---- .../Solutions/DevTokens/DevTokens.csproj | 3 - .../Solutions/DevTokens/DevTokensPlugin.cs | 43 ++--- .../Solutions/DevTokens/plugin.manifest.json | 16 -- 4 files changed, 153 insertions(+), 81 deletions(-) delete mode 100644 src/Plugins/Solutions/DevTokens/plugin.manifest.json diff --git a/src/Plugins/Abstractions/Models/PluginManifest.cs b/src/Plugins/Abstractions/Models/PluginManifest.cs index 2180060..85872a0 100644 --- a/src/Plugins/Abstractions/Models/PluginManifest.cs +++ b/src/Plugins/Abstractions/Models/PluginManifest.cs @@ -1,85 +1,187 @@ -using System.Collections.Immutable; using AuthKit.Plugins.Abstractions.Contracts; using AuthKit.Plugins.Abstractions.Contracts.Plugins; namespace AuthKit.Plugins.Abstractions.Models; /// -/// Projection of plugin metadata available before activation. -/// This surface mirrors selected runtime members of . +/// Represents projection of plugin metadata available before plugin activation. /// +/// +/// +/// The manifest exposes metadata required by the host to inspect, validate, +/// order, and prepare plugin before its runtime instance is activated. +/// +/// +/// The manifest mirrors selected runtime metadata exposed by +/// while remaining independent of a plugin instance. +/// This allows the host to perform pre-activation validation without loading +/// or activating the plugin. +/// +/// +/// Manifest metadata is also used after activation to validate consistency +/// between the declared manifest and the corresponding runtime plugin instance. +/// +/// public sealed record PluginManifest { + /// + /// Gets the unique identifier of the plugin. + /// public string Id { get; init; } = string.Empty; + + /// + /// Gets the technical name of the plugin. + /// public string Name { get; init; } = string.Empty; + + /// + /// Gets the optional user-facing display name of the plugin. + /// public string? DisplayName { get; init; } + + /// + /// Gets the optional description of the plugin. + /// public string? Description { get; init; } - public SemanticVersion Version { get; init; } = new(0,0,0); + + /// + /// Gets the semantic version of the plugin. + /// + public SemanticVersion Version { get; init; } = new(0, 0, 0); + + /// + /// Gets the optional author or publisher of the plugin. + /// public string? Author { get; init; } + + /// + /// Gets the optional license identifier or name associated with the plugin. + /// public string? License { get; init; } + + /// + /// Gets the optional URL containing information about the plugin license. + /// public string? LicenseUrl { get; init; } + + /// + /// Gets the optional homepage URL of the plugin. + /// public string? Homepage { get; init; } + + /// + /// Gets the optional source repository URL of the plugin. + /// public string? RepositoryUrl { get; init; } /// - /// Optional classification tags for UI filtering. Defaults to empty. - /// Null or whitespace elements are invalid and should be rejected during validation. - /// Used for filtering plugins in UIs and catalogs. + /// Gets the optional classification tags associated with the plugin. /// /// - /// Tags are case-sensitive strings without controlled vocabulary. - /// Example: ["security", "auth", "audit"]. + /// + /// Tags are free form, case-sensitive strings intended for plugin + /// classification, filtering, and discovery in user interfaces and + /// plugin catalogs. + /// + /// + /// The collection defaults to an empty set. Null, empty, or whitespace only + /// elements are invalid and should be rejected during manifest validation. + /// + /// + /// Example tags include security, auth, and audit. + /// /// public IReadOnlyList Tags { get; init; } = []; + /// - /// Priority used for activation ordering among dependency-ready plugins. - /// Lower values are activated earlier, higher values later. + /// Gets the priority used when ordering activation among dependency ready plugins. /// /// - /// The ordering algorithm is: topological sort where, among the set of currently - /// dependency-ready plugins, the next plugin is chosen by Priority ascending. - /// Dependency order (G7) wins over Priority. - /// Example: A (p. 100) → B (p-100, DependsOn A), C (p. 0) ⇒ order: A, C, B. + /// + /// Lower priority values cause plugin to be activated earlier, while + /// higher values cause it to be activated later. + /// + /// + /// Priority is applied only among plugins whose dependencies are already + /// satisfied. Dependency ordering therefore takes precedence over priority. + /// + /// + /// The activation algorithm performs topological ordering and selects + /// the dependency ready plugin with the lowest priority value. + /// /// public int Priority { get; init; } + /// - /// Indicates whether the plugin is enabled. Defaults to true. + /// Gets value indicating whether the plugin is enabled. /// /// - /// If false, the plugin is skipped before loading (no consistency check runs for it). - /// For plugins accepted by the preload gate and subsequently loaded, - /// manifest.IsEnabled == instance.IsEnabled is part of consistency validation. + /// The property defaults to . + /// + /// A disabled plugin is skipped before loading and does not participate + /// in plugin consistency validation. + /// + /// + /// For plugins that pass the preload gate and are subsequently loaded, + /// the manifest value is expected to match the corresponding runtime + /// IsEnabled value. + /// /// public bool IsEnabled { get; init; } = true; + /// - /// Features/capabilities exposed by the plugin. Contract - /// requires Case insensitive comparison. Defaults to an empty set. + /// Gets the capabilities exposed by the plugin. /// /// - /// Used for pre-activation capability checks and post-load consistency validation. - /// Host checks capabilities using the extension method. - /// Example: manifest.Supports("auth"). + /// + /// Capability identifiers are compared case-insensitively and default + /// to an empty set. + /// + /// + /// Capabilities are used for pre activation capability checks and for + /// consistency validation after the plugin has been loaded. + /// + /// + /// The + /// extension method can be used to determine whether the plugin declares + /// a specific capability. + /// /// - public IReadOnlySet Capabilities { get; init; } = ImmutableHashSet.Create(StringComparer.OrdinalIgnoreCase); + public ISet Capabilities { get; init; } = + new HashSet(StringComparer.OrdinalIgnoreCase); /// - /// Minimum host version required to load this plugin. + /// Gets the minimum host version required to load the plugin. /// /// - /// If the host version is lower than , the plugin is rejected. - /// Uses SemanticVersion 2.0.0 for version comparison. + /// + /// A plugin is rejected during pre activation validation when the host + /// version is lower than . + /// + /// + /// Version compatibility is evaluated using + /// comparison semantics. + /// /// public SemanticVersion? MinHostVersion { get; init; } /// - /// List of plugin IDs this plugin depends on. + /// Gets the identifiers of plugins required by this plugin. /// /// - /// Each entry must be a valid plugin ID. The host validates: - /// - No self-dependencies (plugin cannot depend on itself). - /// - No duplicate dependencies. - /// - All dependencies exist among discovered plugins. - /// - No dependency cycles. + /// + /// Each dependency must reference a valid plugin identifier discovered + /// by the host. + /// + /// + /// During validation, the host ensures that a plugin does not depend on + /// itself, does not declare duplicate dependencies, and references only + /// plugins that exist in the discovered plugin set. + /// + /// + /// The dependency graph must also be acyclic. Dependency cycles prevent + /// a valid activation order from being established. + /// /// public IReadOnlyList DependsOn { get; init; } = []; -} \ No newline at end of file +} diff --git a/src/Plugins/Solutions/DevTokens/DevTokens.csproj b/src/Plugins/Solutions/DevTokens/DevTokens.csproj index 0c6c4d4..34c0378 100644 --- a/src/Plugins/Solutions/DevTokens/DevTokens.csproj +++ b/src/Plugins/Solutions/DevTokens/DevTokens.csproj @@ -19,7 +19,4 @@ - - - diff --git a/src/Plugins/Solutions/DevTokens/DevTokensPlugin.cs b/src/Plugins/Solutions/DevTokens/DevTokensPlugin.cs index 1490232..661847f 100644 --- a/src/Plugins/Solutions/DevTokens/DevTokensPlugin.cs +++ b/src/Plugins/Solutions/DevTokens/DevTokensPlugin.cs @@ -1,8 +1,8 @@ using DevTokens.Options; using AuthKit.Plugins.Abstractions; using AuthKit.Plugins.Abstractions.Contracts; +using AuthKit.Plugins.Abstractions.Contracts.Plugins; using AuthKit.Plugins.Abstractions.Contracts.SecuritySchemes; -using AuthKit.Plugins.Abstractions.Models; using FluentValidation; using DevTokens.Interfaces; using DevTokens.Middleware; @@ -33,34 +33,23 @@ namespace DevTokens; /// infrastructure. /// /// +[PluginMetadata( + id: "authkit.devtokens", + version: "1.0.0", + tags: ["auth", "tokens", "sdk"], + dependsOn: [], + capabilities: ["auth"], + name: "DevTokens", + displayName: "Developer Tokens", + description: "Issues and validates developer tokens for SDK access.", + author: "AuthKit Contributors", + license: "MIT", + licenseUrl: "https://opensource.org/licenses/MIT", + homepage: "https://example.org/devtokens", + repositoryUrl: "https://example.org/devtokens.git" +)] public sealed class DevTokensPlugin : IAuthKitPlugin { - public string Id => "authkit.devtokens"; - - /// - /// Gets the unique name of the plugin. - /// - public string Name => "DevTokens"; - - public string DisplayName => "Developer Tokens"; - - /// - /// Gets the current version of the plugin. - /// - public SemanticVersion Version => new(1, 0, 0); - - /// - /// Gets a description of the functionality provided by the plugin. - /// - public string Description => - "Issues and validates developer tokens for SDK access."; - - public string Author => "AuthKit Contributors"; - public string License => "MIT"; - public string LicenseUrl => "https://opensource.org/licenses/MIT"; - public string Homepage => "https://example.org/devtokens"; - public string RepositoryUrl => "https://example.org/devtokens.git"; - /// /// Registers developer token services, repositories, validators, /// and authorization components in the dependency injection container. diff --git a/src/Plugins/Solutions/DevTokens/plugin.manifest.json b/src/Plugins/Solutions/DevTokens/plugin.manifest.json deleted file mode 100644 index 393c2ad..0000000 --- a/src/Plugins/Solutions/DevTokens/plugin.manifest.json +++ /dev/null @@ -1,16 +0,0 @@ -{ - "Id": "authkit.devtokens", - "Name": "DevTokens", - "DisplayName": "Developer Tokens", - "Description": "Issues and validates developer tokens for SDK access.", - "Version": "1.0.0", - "Author": "AuthKit Contributors", - "License": "MIT", - "LicenseUrl": "https://opensource.org/licenses/MIT", - "Homepage": "https://example.org/devtokens", - "RepositoryUrl": "https://example.org/devtokens.git", - "Tags": ["devtokens", "auth"], - "Priority": 0, - "IsEnabled": true, - "DependsOn": [] -} From 0a68d994b4098288fa9c1f99f885d12322ca082f Mon Sep 17 00:00:00 2001 From: "Rian.be" Date: Tue, 8 Sep 2026 21:24:16 +0200 Subject: [PATCH 17/18] feat(tools): add PluginContractValidator project --- .../PluginContractValidator/PluginAssemblyLoader.cs | 2 +- .../PluginContractValidator.csproj | 13 +++++++++++++ 2 files changed, 14 insertions(+), 1 deletion(-) create mode 100644 tools/PluginContractValidator/PluginContractValidator.csproj diff --git a/tools/PluginContractValidator/PluginAssemblyLoader.cs b/tools/PluginContractValidator/PluginAssemblyLoader.cs index 42fa10b..4624735 100644 --- a/tools/PluginContractValidator/PluginAssemblyLoader.cs +++ b/tools/PluginContractValidator/PluginAssemblyLoader.cs @@ -107,7 +107,7 @@ private static void AttachResolver(AssemblyDependencyResolver resolver) { Resolvers.Add(resolver); if (_handler is not null) return; - + _handler = (context, name) => { for (var i = Resolvers.Count - 1; i >= 0; i--) diff --git a/tools/PluginContractValidator/PluginContractValidator.csproj b/tools/PluginContractValidator/PluginContractValidator.csproj new file mode 100644 index 0000000..f01b5ea --- /dev/null +++ b/tools/PluginContractValidator/PluginContractValidator.csproj @@ -0,0 +1,13 @@ + + + Exe + net10.0 + AuthKit.PluginContractValidator + + + + + + + + \ No newline at end of file From 916cae7c50cec9cf959ba4c9249b3de133254db5 Mon Sep 17 00:00:00 2001 From: "Rian.be" Date: Tue, 8 Sep 2026 22:07:43 +0200 Subject: [PATCH 18/18] refactor(validator): rename to AuthKit namespace --- AuthKit.slnx | 2 +- Directory.Packages.props | 12 ++++++- .../AuthKit.PluginContractValidator.csproj | 19 ++++++++++ .../PluginAssemblyLoader.cs | 10 ++++-- .../Program.cs | 8 +++-- .../src/Core/ContractValidator.cs | 6 +++- .../src/Core/IPluginContractRule.cs | 6 +++- .../src/Core/IPluginLoader.cs | 2 +- .../src/Core/LoadedPlugin.cs | 2 +- .../src/Core}/PluginLoadResult.cs | 4 ++- .../src/Rules/HealthRule.cs | 10 ++++-- .../src/Rules/MetadataRule.cs | 9 +++-- .../src/Rules/MiddlewareRule.cs | 12 ++++--- .../src/Rules/RegistrationRule.cs | 17 ++++++--- .../src/Rules/SecuritySchemesRule.cs | 12 ++++--- .../PluginContractValidator.csproj | 13 ------- .../src/ContractValidator.cs | 36 ------------------- .../src/Core/PluginLoadResult.cs | 18 ---------- .../src/IPluginContractRule.cs | 26 -------------- .../src/IPluginLoader.cs | 20 ----------- .../src/LoadedPlugin.cs | 28 --------------- 21 files changed, 99 insertions(+), 173 deletions(-) create mode 100644 tools/AuthKit.PluginContractValidator/AuthKit.PluginContractValidator.csproj rename tools/{PluginContractValidator => AuthKit.PluginContractValidator}/PluginAssemblyLoader.cs (96%) rename tools/{PluginContractValidator => AuthKit.PluginContractValidator}/Program.cs (90%) rename tools/{PluginContractValidator => AuthKit.PluginContractValidator}/src/Core/ContractValidator.cs (90%) rename tools/{PluginContractValidator => AuthKit.PluginContractValidator}/src/Core/IPluginContractRule.cs (87%) rename tools/{PluginContractValidator => AuthKit.PluginContractValidator}/src/Core/IPluginLoader.cs (93%) rename tools/{PluginContractValidator => AuthKit.PluginContractValidator}/src/Core/LoadedPlugin.cs (95%) rename tools/{PluginContractValidator/src => AuthKit.PluginContractValidator/src/Core}/PluginLoadResult.cs (89%) rename tools/{PluginContractValidator => AuthKit.PluginContractValidator}/src/Rules/HealthRule.cs (91%) rename tools/{PluginContractValidator => AuthKit.PluginContractValidator}/src/Rules/MetadataRule.cs (83%) rename tools/{PluginContractValidator => AuthKit.PluginContractValidator}/src/Rules/MiddlewareRule.cs (92%) rename tools/{PluginContractValidator => AuthKit.PluginContractValidator}/src/Rules/RegistrationRule.cs (77%) rename tools/{PluginContractValidator => AuthKit.PluginContractValidator}/src/Rules/SecuritySchemesRule.cs (87%) delete mode 100644 tools/PluginContractValidator/PluginContractValidator.csproj delete mode 100644 tools/PluginContractValidator/src/ContractValidator.cs delete mode 100644 tools/PluginContractValidator/src/Core/PluginLoadResult.cs delete mode 100644 tools/PluginContractValidator/src/IPluginContractRule.cs delete mode 100644 tools/PluginContractValidator/src/IPluginLoader.cs delete mode 100644 tools/PluginContractValidator/src/LoadedPlugin.cs diff --git a/AuthKit.slnx b/AuthKit.slnx index ad60a5d..9a470a1 100644 --- a/AuthKit.slnx +++ b/AuthKit.slnx @@ -12,7 +12,7 @@ - + diff --git a/Directory.Packages.props b/Directory.Packages.props index 67c0ae6..047cab9 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -2,6 +2,7 @@ true + @@ -9,21 +10,30 @@ + + + + + + + + + - + \ No newline at end of file diff --git a/tools/AuthKit.PluginContractValidator/AuthKit.PluginContractValidator.csproj b/tools/AuthKit.PluginContractValidator/AuthKit.PluginContractValidator.csproj new file mode 100644 index 0000000..0889449 --- /dev/null +++ b/tools/AuthKit.PluginContractValidator/AuthKit.PluginContractValidator.csproj @@ -0,0 +1,19 @@ + + + + Exe + net10.0 + AuthKit.PluginContractValidator + + + + + + + + + + + + + \ No newline at end of file diff --git a/tools/PluginContractValidator/PluginAssemblyLoader.cs b/tools/AuthKit.PluginContractValidator/PluginAssemblyLoader.cs similarity index 96% rename from tools/PluginContractValidator/PluginAssemblyLoader.cs rename to tools/AuthKit.PluginContractValidator/PluginAssemblyLoader.cs index 4624735..cfb566b 100644 --- a/tools/PluginContractValidator/PluginAssemblyLoader.cs +++ b/tools/AuthKit.PluginContractValidator/PluginAssemblyLoader.cs @@ -1,9 +1,13 @@ +using System; +using System.Collections.Generic; +using System.Linq; using System.Reflection; using System.Runtime.Loader; +using System.Threading; +using AuthKit.PluginContractValidator.Core; using AuthKit.Plugins.Abstractions.Contracts; -using PluginContractValidator.Core; -namespace PluginContractValidator; +namespace AuthKit.PluginContractValidator; /// /// Loads a plugin entry assembly using the same isolation model as the AuthKit host. @@ -107,7 +111,7 @@ private static void AttachResolver(AssemblyDependencyResolver resolver) { Resolvers.Add(resolver); if (_handler is not null) return; - + _handler = (context, name) => { for (var i = Resolvers.Count - 1; i >= 0; i--) diff --git a/tools/PluginContractValidator/Program.cs b/tools/AuthKit.PluginContractValidator/Program.cs similarity index 90% rename from tools/PluginContractValidator/Program.cs rename to tools/AuthKit.PluginContractValidator/Program.cs index e362f14..987e3ca 100644 --- a/tools/PluginContractValidator/Program.cs +++ b/tools/AuthKit.PluginContractValidator/Program.cs @@ -1,6 +1,8 @@ -using PluginContractValidator; -using PluginContractValidator.Core; -using PluginContractValidator.Rules; +using System; +using System.IO; +using AuthKit.PluginContractValidator; +using AuthKit.PluginContractValidator.Core; +using AuthKit.PluginContractValidator.Rules; var pluginsRoot = args.Length > 0 ? args[0] : "src/Plugins"; diff --git a/tools/PluginContractValidator/src/Core/ContractValidator.cs b/tools/AuthKit.PluginContractValidator/src/Core/ContractValidator.cs similarity index 90% rename from tools/PluginContractValidator/src/Core/ContractValidator.cs rename to tools/AuthKit.PluginContractValidator/src/Core/ContractValidator.cs index e096251..0406228 100644 --- a/tools/PluginContractValidator/src/Core/ContractValidator.cs +++ b/tools/AuthKit.PluginContractValidator/src/Core/ContractValidator.cs @@ -1,4 +1,8 @@ -namespace PluginContractValidator.Core; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; + +namespace AuthKit.PluginContractValidator.Core; /// /// Runs every registered against a loaded plugin and diff --git a/tools/PluginContractValidator/src/Core/IPluginContractRule.cs b/tools/AuthKit.PluginContractValidator/src/Core/IPluginContractRule.cs similarity index 87% rename from tools/PluginContractValidator/src/Core/IPluginContractRule.cs rename to tools/AuthKit.PluginContractValidator/src/Core/IPluginContractRule.cs index b5bd61b..2df1d1b 100644 --- a/tools/PluginContractValidator/src/Core/IPluginContractRule.cs +++ b/tools/AuthKit.PluginContractValidator/src/Core/IPluginContractRule.cs @@ -1,4 +1,8 @@ -namespace PluginContractValidator.Core; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; + +namespace AuthKit.PluginContractValidator.Core; /// /// Validates single contract concern of loaded plugin. diff --git a/tools/PluginContractValidator/src/Core/IPluginLoader.cs b/tools/AuthKit.PluginContractValidator/src/Core/IPluginLoader.cs similarity index 93% rename from tools/PluginContractValidator/src/Core/IPluginLoader.cs rename to tools/AuthKit.PluginContractValidator/src/Core/IPluginLoader.cs index 1c36a62..f0892d8 100644 --- a/tools/PluginContractValidator/src/Core/IPluginLoader.cs +++ b/tools/AuthKit.PluginContractValidator/src/Core/IPluginLoader.cs @@ -1,6 +1,6 @@ using AuthKit.Plugins.Abstractions.Contracts; -namespace PluginContractValidator.Core; +namespace AuthKit.PluginContractValidator.Core; /// /// Loads plugin entry assembly and instantiates its implementation. diff --git a/tools/PluginContractValidator/src/Core/LoadedPlugin.cs b/tools/AuthKit.PluginContractValidator/src/Core/LoadedPlugin.cs similarity index 95% rename from tools/PluginContractValidator/src/Core/LoadedPlugin.cs rename to tools/AuthKit.PluginContractValidator/src/Core/LoadedPlugin.cs index 0344c1f..4c16fa1 100644 --- a/tools/PluginContractValidator/src/Core/LoadedPlugin.cs +++ b/tools/AuthKit.PluginContractValidator/src/Core/LoadedPlugin.cs @@ -1,7 +1,7 @@ using System.Reflection; using AuthKit.Plugins.Abstractions.Contracts; -namespace PluginContractValidator.Core; +namespace AuthKit.PluginContractValidator.Core; /// /// Represents a plugin assembly that has been successfully loaded and instantiated diff --git a/tools/PluginContractValidator/src/PluginLoadResult.cs b/tools/AuthKit.PluginContractValidator/src/Core/PluginLoadResult.cs similarity index 89% rename from tools/PluginContractValidator/src/PluginLoadResult.cs rename to tools/AuthKit.PluginContractValidator/src/Core/PluginLoadResult.cs index ff8f8dd..56acc7e 100644 --- a/tools/PluginContractValidator/src/PluginLoadResult.cs +++ b/tools/AuthKit.PluginContractValidator/src/Core/PluginLoadResult.cs @@ -1,4 +1,6 @@ -namespace PluginContractValidator; +using System.Collections.Generic; + +namespace AuthKit.PluginContractValidator.Core; /// /// Encapsulates the outcome of attempting to load a plugin assembly. diff --git a/tools/PluginContractValidator/src/Rules/HealthRule.cs b/tools/AuthKit.PluginContractValidator/src/Rules/HealthRule.cs similarity index 91% rename from tools/PluginContractValidator/src/Rules/HealthRule.cs rename to tools/AuthKit.PluginContractValidator/src/Rules/HealthRule.cs index e6fedd0..4eb2a76 100644 --- a/tools/PluginContractValidator/src/Rules/HealthRule.cs +++ b/tools/AuthKit.PluginContractValidator/src/Rules/HealthRule.cs @@ -1,9 +1,13 @@ +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using AuthKit.PluginContractValidator.Core; using AuthKit.Plugins.Abstractions.Contracts; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; -using PluginContractValidator.Core; -namespace PluginContractValidator.Rules; +namespace AuthKit.PluginContractValidator.Rules; /// /// Ensures the plugin can configure its services and that @@ -61,4 +65,4 @@ public async Task> ValidateAsync( return errors; } -} +} \ No newline at end of file diff --git a/tools/PluginContractValidator/src/Rules/MetadataRule.cs b/tools/AuthKit.PluginContractValidator/src/Rules/MetadataRule.cs similarity index 83% rename from tools/PluginContractValidator/src/Rules/MetadataRule.cs rename to tools/AuthKit.PluginContractValidator/src/Rules/MetadataRule.cs index 6542155..bdcb933 100644 --- a/tools/PluginContractValidator/src/Rules/MetadataRule.cs +++ b/tools/AuthKit.PluginContractValidator/src/Rules/MetadataRule.cs @@ -1,7 +1,10 @@ +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using AuthKit.PluginContractValidator.Core; using AuthKit.Plugins.Abstractions.Contracts; -using PluginContractValidator.Core; -namespace PluginContractValidator.Rules; +namespace AuthKit.PluginContractValidator.Rules; /// /// Ensures plugin metadata (Name, Version) is present and well-formed. @@ -29,4 +32,4 @@ public Task> ValidateAsync( return Task.FromResult>(errors); } -} +} \ No newline at end of file diff --git a/tools/PluginContractValidator/src/Rules/MiddlewareRule.cs b/tools/AuthKit.PluginContractValidator/src/Rules/MiddlewareRule.cs similarity index 92% rename from tools/PluginContractValidator/src/Rules/MiddlewareRule.cs rename to tools/AuthKit.PluginContractValidator/src/Rules/MiddlewareRule.cs index abf296b..a620089 100644 --- a/tools/PluginContractValidator/src/Rules/MiddlewareRule.cs +++ b/tools/AuthKit.PluginContractValidator/src/Rules/MiddlewareRule.cs @@ -1,9 +1,13 @@ -using AuthKit.Plugins.Abstractions; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using AuthKit.PluginContractValidator.Core; using AuthKit.Plugins.Abstractions.Contracts; using Microsoft.AspNetCore.Http; -using PluginContractValidator.Core; -namespace PluginContractValidator.Rules; +namespace AuthKit.PluginContractValidator.Rules; /// /// Ensures a contributed middleware type follows the AuthKit middleware convention. @@ -77,4 +81,4 @@ private static bool HasRequestDelegateConstructor(Type middlewareType) .Any(constructor => constructor.GetParameters() .Any(parameter => parameter.ParameterType == typeof(RequestDelegate))); } -} +} \ No newline at end of file diff --git a/tools/PluginContractValidator/src/Rules/RegistrationRule.cs b/tools/AuthKit.PluginContractValidator/src/Rules/RegistrationRule.cs similarity index 77% rename from tools/PluginContractValidator/src/Rules/RegistrationRule.cs rename to tools/AuthKit.PluginContractValidator/src/Rules/RegistrationRule.cs index d89a0d1..5563a50 100644 --- a/tools/PluginContractValidator/src/Rules/RegistrationRule.cs +++ b/tools/AuthKit.PluginContractValidator/src/Rules/RegistrationRule.cs @@ -1,9 +1,13 @@ +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using AuthKit.PluginContractValidator.Core; using AuthKit.Plugins.Abstractions.Contracts; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; -using PluginContractValidator.Core; -namespace PluginContractValidator.Rules; +namespace AuthKit.PluginContractValidator.Rules; /// /// Ensures ConfigureServices registers dependencies without throwing and that the @@ -16,11 +20,14 @@ public sealed class RegistrationRule : IPluginContractRule /// /// Invokes against a fresh service collection - /// and then builds the to confirm the dependency graph is + /// and then builds the to confirm the dependency graph is /// constructible. /// - /// The loaded plugin to validate. - /// A token that can be used to cancel the validation. + /// + /// + /// The loaded plugin to validate. + /// A token that can be used to cancel the validation. + /// /// The list of registration violations; empty when registration succeeds. public Task> ValidateAsync( LoadedPlugin plugin, diff --git a/tools/PluginContractValidator/src/Rules/SecuritySchemesRule.cs b/tools/AuthKit.PluginContractValidator/src/Rules/SecuritySchemesRule.cs similarity index 87% rename from tools/PluginContractValidator/src/Rules/SecuritySchemesRule.cs rename to tools/AuthKit.PluginContractValidator/src/Rules/SecuritySchemesRule.cs index ec99db7..c9c3474 100644 --- a/tools/PluginContractValidator/src/Rules/SecuritySchemesRule.cs +++ b/tools/AuthKit.PluginContractValidator/src/Rules/SecuritySchemesRule.cs @@ -1,8 +1,12 @@ -using AuthKit.Plugins.Abstractions; +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using AuthKit.PluginContractValidator.Core; using AuthKit.Plugins.Abstractions.Contracts; -using PluginContractValidator.Core; +using AuthKit.Plugins.Abstractions.Contracts.SecuritySchemes; -namespace PluginContractValidator.Rules; +namespace AuthKit.PluginContractValidator.Rules; /// /// Ensures contributed OpenAPI security schemes are present and consistently keyed. @@ -54,4 +58,4 @@ public Task> ValidateAsync( return Task.FromResult>(errors); } -} +} \ No newline at end of file diff --git a/tools/PluginContractValidator/PluginContractValidator.csproj b/tools/PluginContractValidator/PluginContractValidator.csproj deleted file mode 100644 index f01b5ea..0000000 --- a/tools/PluginContractValidator/PluginContractValidator.csproj +++ /dev/null @@ -1,13 +0,0 @@ - - - Exe - net10.0 - AuthKit.PluginContractValidator - - - - - - - - \ No newline at end of file diff --git a/tools/PluginContractValidator/src/ContractValidator.cs b/tools/PluginContractValidator/src/ContractValidator.cs deleted file mode 100644 index 62cf69f..0000000 --- a/tools/PluginContractValidator/src/ContractValidator.cs +++ /dev/null @@ -1,36 +0,0 @@ -namespace PluginContractValidator; - -/// -/// Runs every registered against a loaded plugin and -/// aggregates the resulting contract violations. -/// -/// -/// Rules are executed sequentially; each rule's violations are collected into a single -/// combined list so the caller sees every problem at once. -/// -/// The contract rules to execute for each plugin. -public sealed class ContractValidator(IEnumerable rules) -{ - private readonly IEnumerable _rules = rules; - - /// - /// Validates the supplied plugin against all registered rules. - /// - /// The loaded plugin to validate. - /// A token that can be used to cancel the validation. - /// The aggregated, read-only list of contract violations. - public async Task> ValidateAsync( - LoadedPlugin plugin, - CancellationToken cancellationToken = default) - { - var errors = new List(); - - foreach (var rule in _rules) - { - cancellationToken.ThrowIfCancellationRequested(); - errors.AddRange(await rule.ValidateAsync(plugin, cancellationToken)); - } - - return errors; - } -} diff --git a/tools/PluginContractValidator/src/Core/PluginLoadResult.cs b/tools/PluginContractValidator/src/Core/PluginLoadResult.cs deleted file mode 100644 index 884f18f..0000000 --- a/tools/PluginContractValidator/src/Core/PluginLoadResult.cs +++ /dev/null @@ -1,18 +0,0 @@ -namespace PluginContractValidator.Core; - -/// -/// Encapsulates the outcome of attempting to load a plugin assembly. -/// -/// -/// When loading fails, is null and -/// contains the human-readable reasons for the failure. -/// -/// The loaded plugin, or null when loading failed. -/// The list of contract or loading violations encountered. -public sealed record PluginLoadResult(LoadedPlugin? Plugin, IReadOnlyList Errors) -{ - /// - /// Gets a value indicating whether the plugin was loaded successfully. - /// - public bool Succeeded => Plugin is not null; -} diff --git a/tools/PluginContractValidator/src/IPluginContractRule.cs b/tools/PluginContractValidator/src/IPluginContractRule.cs deleted file mode 100644 index b71559f..0000000 --- a/tools/PluginContractValidator/src/IPluginContractRule.cs +++ /dev/null @@ -1,26 +0,0 @@ -namespace PluginContractValidator; - -/// -/// Validates single contract concern of loaded plugin. -/// -/// -/// Rules are composed by and executed independently, so a -/// failure in one concern does not prevent the others from being evaluated. -/// -public interface IPluginContractRule -{ - /// - /// Gets a human-readable name of the validated contract concern (for example, "Metadata"). - /// - string Name { get; } - - /// - /// Validates the plugin and returns the list of contract violations. - /// - /// The loaded plugin to validate. - /// A token that can be used to cancel the validation. - /// - /// A read-only list of violation messages. An empty list means the rule passed. - /// - Task> ValidateAsync(LoadedPlugin plugin, CancellationToken cancellationToken = default); -} diff --git a/tools/PluginContractValidator/src/IPluginLoader.cs b/tools/PluginContractValidator/src/IPluginLoader.cs deleted file mode 100644 index 60f40c1..0000000 --- a/tools/PluginContractValidator/src/IPluginLoader.cs +++ /dev/null @@ -1,20 +0,0 @@ -using AuthKit.Plugins.Abstractions; - -namespace PluginContractValidator; - -/// -/// Loads a plugin entry assembly and instantiates its implementation. -/// -public interface IPluginLoader -{ - /// - /// Loads the plugin entry assembly located at and activates its - /// implementation. - /// - /// The full path to the plugin's entry assembly (named after its directory). - /// - /// A describing the loaded plugin, or the errors encountered - /// while loading it. - /// - PluginLoadResult Load(string entryDll); -} diff --git a/tools/PluginContractValidator/src/LoadedPlugin.cs b/tools/PluginContractValidator/src/LoadedPlugin.cs deleted file mode 100644 index 78d9e11..0000000 --- a/tools/PluginContractValidator/src/LoadedPlugin.cs +++ /dev/null @@ -1,28 +0,0 @@ -using System.Reflection; -using AuthKit.Plugins.Abstractions; - -namespace PluginContractValidator; - -/// -/// Represents a plugin assembly that has been successfully loaded and instantiated -/// by the validation host. -/// -/// -/// The wrapper keeps both the activated instance and the -/// it was loaded from, so that individual contract rules can -/// inspect runtime metadata without re-loading the assembly. -/// -/// The activated plugin instance implementing . -/// The assembly the plugin type was loaded from. -public sealed class LoadedPlugin(IAuthKitPlugin instance, Assembly assembly) -{ - /// - /// Gets the activated plugin instance implementing . - /// - public IAuthKitPlugin Instance { get; } = instance; - - /// - /// Gets the assembly the plugin type was loaded from. - /// - public Assembly Assembly { get; } = assembly; -}