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/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/Dockerfile b/Dockerfile index 70f2fac..2ef19b7 100644 --- a/Dockerfile +++ b/Dockerfile @@ -30,9 +30,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/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/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/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/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..858dbc2 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,186 @@ 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, "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 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..a956c76 100644 --- a/src/Plugins/Abstractions/AuthKit.Plugins.Abstractions.csproj +++ b/src/Plugins/Abstractions/AuthKit.Plugins.Abstractions.csproj @@ -4,9 +4,18 @@ preview enable enable + false + false + + + + + + +
diff --git a/src/Plugins/Abstractions/Contracts/IAuthKitPlugin.cs b/src/Plugins/Abstractions/Contracts/IAuthKitPlugin.cs new file mode 100644 index 0000000..bb4652c --- /dev/null +++ b/src/Plugins/Abstractions/Contracts/IAuthKitPlugin.cs @@ -0,0 +1,267 @@ +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; +using System.Reflection; + +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 => Metadata.Id; + + /// + /// 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 => Metadata.Name; + + /// + /// Gets an optional human-readable display name for UIs. + /// + /// + /// The host UI should display DisplayName ?? Name when presenting + /// the plugin to users. + /// + string? DisplayName => Metadata.DisplayName; + + /// + /// 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 => Metadata.Description; + + /// + /// 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 => SemanticVersion.Parse(Metadata.Version); + + /// + /// Optional author metadata, visible in catalogs and diagnostics. + /// + string? Author => Metadata.Author; + + /// + /// Optional SPDX-style license string (no validation performed by host). + /// + string? License => Metadata.License; + + /// + /// Optional absolute URI pointing to the license text. + /// + string? LicenseUrl => Metadata.LicenseUrl; + + /// + /// Optional absolute HTTP/HTTPS URI pointing to a plugin homepage. + /// + string? Homepage => Metadata.Homepage; + + /// + /// Optional absolute HTTP/HTTPS URI pointing to the plugin repository. + /// + string? RepositoryUrl => Metadata.RepositoryUrl; + + /// + /// 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 => Metadata.Tags; + + /// + /// 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 => Metadata.Priority; + + /// + /// 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 => Metadata.IsEnabled; + + /// + /// 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 => _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. + /// + /// 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 => string.IsNullOrEmpty(Metadata.MinHostVersion) ? null : SemanticVersion.Parse(Metadata.MinHostVersion); + + /// + /// 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 => Metadata.DependsOn; + + /// + /// 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/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/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/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 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/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(); -} diff --git a/src/Plugins/Abstractions/Models/PluginManifest.cs b/src/Plugins/Abstractions/Models/PluginManifest.cs new file mode 100644 index 0000000..85872a0 --- /dev/null +++ b/src/Plugins/Abstractions/Models/PluginManifest.cs @@ -0,0 +1,187 @@ +using AuthKit.Plugins.Abstractions.Contracts; +using AuthKit.Plugins.Abstractions.Contracts.Plugins; + +namespace AuthKit.Plugins.Abstractions.Models; + +/// +/// 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; } + + /// + /// 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; } + + /// + /// Gets the optional classification tags associated with the plugin. + /// + /// + /// + /// 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; } = []; + + /// + /// Gets the priority used when ordering activation among dependency ready plugins. + /// + /// + /// + /// 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; } + + /// + /// Gets value indicating whether the plugin is enabled. + /// + /// + /// 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; + + /// + /// Gets the capabilities exposed by the plugin. + /// + /// + /// + /// 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 ISet Capabilities { get; init; } = + new HashSet(StringComparer.OrdinalIgnoreCase); + + /// + /// Gets the minimum host version required to load the plugin. + /// + /// + /// + /// 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; } + + /// + /// Gets the identifiers of plugins required by this plugin. + /// + /// + /// + /// 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; } = []; +} 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 diff --git a/src/Plugins/Solutions/DevTokens/DevTokensPlugin.cs b/src/Plugins/Solutions/DevTokens/DevTokensPlugin.cs index a2023f4..661847f 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.Plugins; +using AuthKit.Plugins.Abstractions.Contracts.SecuritySchemes; using FluentValidation; using DevTokens.Interfaces; using DevTokens.Middleware; @@ -31,24 +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 { - /// - /// Gets the unique name of the plugin. - /// - public string Name => "DevTokens"; - - /// - /// Gets the current version of the plugin. - /// - public string Version => "1.0.0"; - - /// - /// Gets a description of the functionality provided by the plugin. - /// - public string Description => - "Issues and validates developer tokens for SDK access."; - /// /// Registers developer token services, repositories, validators, /// and authorization components in the dependency injection container. 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/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/PluginContractValidator/PluginContractValidator.csproj b/tools/AuthKit.ManifestGenerator/CLI/AuthKit.ManifestGenerator.CLI.csproj similarity index 52% rename from tools/PluginContractValidator/PluginContractValidator.csproj rename to tools/AuthKit.ManifestGenerator/CLI/AuthKit.ManifestGenerator.CLI.csproj index 612873d..49dcc40 100644 --- a/tools/PluginContractValidator/PluginContractValidator.csproj +++ b/tools/AuthKit.ManifestGenerator/CLI/AuthKit.ManifestGenerator.CLI.csproj @@ -1,15 +1,15 @@ + - Exe net10.0 enable enable - false - PluginContractValidator - PluginContractValidator + 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/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 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 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..5c5872e --- /dev/null +++ b/tools/AuthKit.ManifestGenerator/Taskfile.yml @@ -0,0 +1,43 @@ +version: '3' + +vars: + 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 # Disables .NET CLI telemetry + +tasks: + default: + desc: Lists available tasks + cmds: + - task --list + + build: + 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: Cleans the entire project (deletes build artifacts) + cmds: + - dotnet clean {{.CORE_PROJECT}} --configuration {{.CONFIGURATION}} + - dotnet clean {{.CLI_PROJECT}} --configuration {{.CONFIGURATION}} + + run: + desc: Runs the AuthKit.ManifestGenerator CLI + deps: + - 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: Generates an example manifest + deps: + - run 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 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 83% rename from tools/PluginContractValidator/PluginAssemblyLoader.cs rename to tools/AuthKit.PluginContractValidator/PluginAssemblyLoader.cs index 1e20ea8..cfb566b 100644 --- a/tools/PluginContractValidator/PluginAssemblyLoader.cs +++ b/tools/AuthKit.PluginContractValidator/PluginAssemblyLoader.cs @@ -1,8 +1,13 @@ +using System; +using System.Collections.Generic; +using System.Linq; using System.Reflection; using System.Runtime.Loader; -using AuthKit.Plugins.Abstractions; +using System.Threading; +using AuthKit.PluginContractValidator.Core; +using AuthKit.Plugins.Abstractions.Contracts; -namespace PluginContractValidator.Loading; +namespace AuthKit.PluginContractValidator; /// /// Loads a plugin entry assembly using the same isolation model as the AuthKit host. @@ -11,7 +16,7 @@ namespace PluginContractValidator.Loading; /// /// 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 +/// lifetime of the process so that lazily loaded dependencies (for example, types referenced /// inside CheckHealthAsync) continue to resolve, exactly as in the host. /// /// @@ -24,7 +29,7 @@ namespace PluginContractValidator.Loading; public sealed class PluginAssemblyLoader : IPluginLoader { private static readonly List Resolvers = new(); - private static readonly object Gate = new(); + private static readonly Lock Gate = new(); private static Func? _handler; /// @@ -105,25 +110,23 @@ private static void AttachResolver(AssemblyDependencyResolver resolver) lock (Gate) { Resolvers.Add(resolver); - - if (_handler is null) + if (_handler is not null) return; + + _handler = (context, name) => { - _handler = (context, name) => + for (var i = Resolvers.Count - 1; i >= 0; i--) { - for (var i = Resolvers.Count - 1; i >= 0; i--) + var path = Resolvers[i].ResolveAssemblyToPath(name); + if (path is not null) { - var path = Resolvers[i].ResolveAssemblyToPath(name); - if (path is not null) - { - return context.LoadFromAssemblyPath(path); - } + return context.LoadFromAssemblyPath(path); } + } - return null; - }; + return null; + }; - AssemblyLoadContext.Default.Resolving += _handler; - } + AssemblyLoadContext.Default.Resolving += _handler; } } } diff --git a/tools/PluginContractValidator/Program.cs b/tools/AuthKit.PluginContractValidator/Program.cs similarity index 86% rename from tools/PluginContractValidator/Program.cs rename to tools/AuthKit.PluginContractValidator/Program.cs index 5590622..987e3ca 100644 --- a/tools/PluginContractValidator/Program.cs +++ b/tools/AuthKit.PluginContractValidator/Program.cs @@ -1,6 +1,8 @@ -using PluginContractValidator; -using PluginContractValidator.Loading; -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"; @@ -11,14 +13,13 @@ } IPluginLoader loader = new PluginAssemblyLoader(); -ContractValidator validator = new ContractValidator(new IPluginContractRule[] -{ +var validator = new ContractValidator([ new MetadataRule(), new RegistrationRule(), new SecuritySchemesRule(), new MiddlewareRule(), - new HealthRule(), -}); + new HealthRule() +]); var failures = 0; diff --git a/tools/PluginContractValidator/src/ContractValidator.cs b/tools/AuthKit.PluginContractValidator/src/Core/ContractValidator.cs similarity index 87% rename from tools/PluginContractValidator/src/ContractValidator.cs rename to tools/AuthKit.PluginContractValidator/src/Core/ContractValidator.cs index 62cf69f..0406228 100644 --- a/tools/PluginContractValidator/src/ContractValidator.cs +++ b/tools/AuthKit.PluginContractValidator/src/Core/ContractValidator.cs @@ -1,4 +1,8 @@ -namespace PluginContractValidator; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; + +namespace AuthKit.PluginContractValidator.Core; /// /// Runs every registered against a loaded plugin and @@ -11,8 +15,6 @@ namespace PluginContractValidator; /// 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. /// @@ -25,7 +27,7 @@ public async Task> ValidateAsync( { var errors = new List(); - foreach (var rule in _rules) + foreach (var rule in rules) { cancellationToken.ThrowIfCancellationRequested(); errors.AddRange(await rule.ValidateAsync(plugin, cancellationToken)); diff --git a/tools/PluginContractValidator/src/IPluginContractRule.cs b/tools/AuthKit.PluginContractValidator/src/Core/IPluginContractRule.cs similarity index 80% rename from tools/PluginContractValidator/src/IPluginContractRule.cs rename to tools/AuthKit.PluginContractValidator/src/Core/IPluginContractRule.cs index b71559f..2df1d1b 100644 --- a/tools/PluginContractValidator/src/IPluginContractRule.cs +++ b/tools/AuthKit.PluginContractValidator/src/Core/IPluginContractRule.cs @@ -1,4 +1,8 @@ -namespace PluginContractValidator; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; + +namespace AuthKit.PluginContractValidator.Core; /// /// Validates single contract concern of loaded plugin. @@ -10,7 +14,7 @@ namespace PluginContractValidator; public interface IPluginContractRule { /// - /// Gets a human-readable name of the validated contract concern (for example, "Metadata"). + /// Gets a name of the validated contract concern (for example, "Metadata"). /// string Name { get; } diff --git a/tools/PluginContractValidator/src/IPluginLoader.cs b/tools/AuthKit.PluginContractValidator/src/Core/IPluginLoader.cs similarity index 74% rename from tools/PluginContractValidator/src/IPluginLoader.cs rename to tools/AuthKit.PluginContractValidator/src/Core/IPluginLoader.cs index 60f40c1..f0892d8 100644 --- a/tools/PluginContractValidator/src/IPluginLoader.cs +++ b/tools/AuthKit.PluginContractValidator/src/Core/IPluginLoader.cs @@ -1,9 +1,9 @@ -using AuthKit.Plugins.Abstractions; +using AuthKit.Plugins.Abstractions.Contracts; -namespace PluginContractValidator; +namespace AuthKit.PluginContractValidator.Core; /// -/// Loads a plugin entry assembly and instantiates its implementation. +/// Loads plugin entry assembly and instantiates its implementation. /// public interface IPluginLoader { diff --git a/tools/PluginContractValidator/src/LoadedPlugin.cs b/tools/AuthKit.PluginContractValidator/src/Core/LoadedPlugin.cs similarity index 91% rename from tools/PluginContractValidator/src/LoadedPlugin.cs rename to tools/AuthKit.PluginContractValidator/src/Core/LoadedPlugin.cs index 78d9e11..4c16fa1 100644 --- a/tools/PluginContractValidator/src/LoadedPlugin.cs +++ b/tools/AuthKit.PluginContractValidator/src/Core/LoadedPlugin.cs @@ -1,7 +1,7 @@ using System.Reflection; -using AuthKit.Plugins.Abstractions; +using AuthKit.Plugins.Abstractions.Contracts; -namespace PluginContractValidator; +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/AuthKit.PluginContractValidator/src/Rules/HealthRule.cs b/tools/AuthKit.PluginContractValidator/src/Rules/HealthRule.cs new file mode 100644 index 0000000..4eb2a76 --- /dev/null +++ b/tools/AuthKit.PluginContractValidator/src/Rules/HealthRule.cs @@ -0,0 +1,68 @@ +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; + +namespace AuthKit.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/AuthKit.PluginContractValidator/src/Rules/MetadataRule.cs b/tools/AuthKit.PluginContractValidator/src/Rules/MetadataRule.cs new file mode 100644 index 0000000..bdcb933 --- /dev/null +++ b/tools/AuthKit.PluginContractValidator/src/Rules/MetadataRule.cs @@ -0,0 +1,35 @@ +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using AuthKit.PluginContractValidator.Core; +using AuthKit.Plugins.Abstractions.Contracts; + +namespace AuthKit.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/AuthKit.PluginContractValidator/src/Rules/MiddlewareRule.cs b/tools/AuthKit.PluginContractValidator/src/Rules/MiddlewareRule.cs new file mode 100644 index 0000000..a620089 --- /dev/null +++ b/tools/AuthKit.PluginContractValidator/src/Rules/MiddlewareRule.cs @@ -0,0 +1,84 @@ +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; + +namespace AuthKit.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/AuthKit.PluginContractValidator/src/Rules/RegistrationRule.cs similarity index 75% rename from tools/PluginContractValidator/src/Rules/RegistrationRule.cs rename to tools/AuthKit.PluginContractValidator/src/Rules/RegistrationRule.cs index e5e897f..5563a50 100644 --- a/tools/PluginContractValidator/src/Rules/RegistrationRule.cs +++ b/tools/AuthKit.PluginContractValidator/src/Rules/RegistrationRule.cs @@ -1,8 +1,13 @@ -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 Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; -namespace PluginContractValidator.Rules; +namespace AuthKit.PluginContractValidator.Rules; /// /// Ensures ConfigureServices registers dependencies without throwing and that the @@ -15,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/AuthKit.PluginContractValidator/src/Rules/SecuritySchemesRule.cs b/tools/AuthKit.PluginContractValidator/src/Rules/SecuritySchemesRule.cs new file mode 100644 index 0000000..c9c3474 --- /dev/null +++ b/tools/AuthKit.PluginContractValidator/src/Rules/SecuritySchemesRule.cs @@ -0,0 +1,61 @@ +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using AuthKit.PluginContractValidator.Core; +using AuthKit.Plugins.Abstractions.Contracts; +using AuthKit.Plugins.Abstractions.Contracts.SecuritySchemes; + +namespace AuthKit.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 diff --git a/tools/PluginContractValidator/src/Rules/HealthRule.cs b/tools/PluginContractValidator/src/Rules/HealthRule.cs deleted file mode 100644 index fb2619c..0000000 --- a/tools/PluginContractValidator/src/Rules/HealthRule.cs +++ /dev/null @@ -1,44 +0,0 @@ -using AuthKit.Plugins.Abstractions; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; - -namespace PluginContractValidator.Rules; - -/// -/// Ensures CheckHealthAsync does not throw when invoked against a built service -/// provider (the host treats a throwing health check as a contract violation). -/// -public sealed class HealthRule : IPluginContractRule -{ - /// Gets the rule name ("Health"). - public string Name => "Health"; - - /// - /// Builds a service provider from the plugin's registered services and invokes - /// , capturing any thrown exception as a violation. - /// - /// The loaded plugin to validate. - /// A token that can be used to cancel the validation. - /// The list of health check violations; empty when the check completes without throwing. - public async Task> ValidateAsync( - LoadedPlugin plugin, - CancellationToken cancellationToken = default) - { - var errors = new List(); - var services = new ServiceCollection(); - var configuration = new ConfigurationBuilder().Build(); - plugin.Instance.ConfigureServices(services, configuration); - - try - { - await using var provider = services.BuildServiceProvider(); - await plugin.Instance.CheckHealthAsync(provider); - } - catch (Exception ex) - { - errors.Add($"health: CheckHealthAsync threw (must not throw): {ex.Message}"); - } - - return errors; - } -} diff --git a/tools/PluginContractValidator/src/Rules/MetadataRule.cs b/tools/PluginContractValidator/src/Rules/MetadataRule.cs deleted file mode 100644 index f7cc9fc..0000000 --- a/tools/PluginContractValidator/src/Rules/MetadataRule.cs +++ /dev/null @@ -1,51 +0,0 @@ -using System.Text.RegularExpressions; -using AuthKit.Plugins.Abstractions; - -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 -{ - private static readonly Regex SemVer = - new(@"^\d+\.\d+\.\d+(-[0-9A-Za-z-.]+)?$", RegexOptions.Compiled); - - /// Gets the rule name ("Metadata"). - public string Name => "Metadata"; - - /// - /// Validates the plugin's metadata. - /// - /// The loaded plugin to validate. - /// A token that can be used to cancel the validation. - /// The list of metadata violations; empty when the metadata is valid. - public Task> ValidateAsync( - LoadedPlugin plugin, - CancellationToken cancellationToken = default) - { - var pluginInstance = plugin.Instance; - var errors = new List(); - - if (string.IsNullOrWhiteSpace(pluginInstance.Name)) - { - errors.Add("metadata: Name is null or empty"); - } - - if (string.IsNullOrWhiteSpace(pluginInstance.Version)) - { - errors.Add("metadata: Version is null or empty"); - } - else if (!SemVer.IsMatch(pluginInstance.Version)) - { - errors.Add($"metadata: Version '{pluginInstance.Version}' is not SemVer (expected major.minor.patch[-prerelease])"); - } - - return Task.FromResult>(errors); - } -} diff --git a/tools/PluginContractValidator/src/Rules/MiddlewareRule.cs b/tools/PluginContractValidator/src/Rules/MiddlewareRule.cs deleted file mode 100644 index b553591..0000000 --- a/tools/PluginContractValidator/src/Rules/MiddlewareRule.cs +++ /dev/null @@ -1,64 +0,0 @@ -using AuthKit.Plugins.Abstractions; -using Microsoft.AspNetCore.Http; - -namespace PluginContractValidator.Rules; - -/// -/// Ensures a contributed middleware type follows the ASP.NET Core middleware convention. -/// -/// -/// The middleware type must expose a constructor accepting -/// and an InvokeAsync(HttpContext, ...) method that returns -/// , mirroring the conventional ASP.NET Core middleware shape. -/// -public sealed class MiddlewareRule : IPluginContractRule -{ - /// Gets the rule name ("Middleware"). - public string Name => "Middleware"; - - /// - /// Validates the middleware type contributed by , - /// if any. - /// - /// The loaded plugin to validate. - /// A token that can be used to cancel the validation. - /// - /// The list of middleware violations; empty when the middleware is valid or absent. - /// - 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); - } - - var hasRequestDelegateCtor = middlewareType.GetConstructors() - .Any(c => c.GetParameters().Any(p => p.ParameterType == typeof(RequestDelegate))); - - if (!hasRequestDelegateCtor) - { - errors.Add($"middleware: MiddlewareType '{middlewareType.Name}' does not have a constructor accepting RequestDelegate"); - } - - var invoke = middlewareType.GetMethod("InvokeAsync"); - if (invoke is null || invoke.ReturnType != typeof(Task)) - { - errors.Add($"middleware: MiddlewareType '{middlewareType.Name}' must expose InvokeAsync returning Task"); - } - else - { - var parameters = invoke.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); - } -} diff --git a/tools/PluginContractValidator/src/Rules/SecuritySchemesRule.cs b/tools/PluginContractValidator/src/Rules/SecuritySchemesRule.cs deleted file mode 100644 index ababa62..0000000 --- a/tools/PluginContractValidator/src/Rules/SecuritySchemesRule.cs +++ /dev/null @@ -1,59 +0,0 @@ -using AuthKit.Plugins.Abstractions; - -namespace PluginContractValidator.Rules; - -/// -/// Ensures contributed OpenAPI security schemes are well-formed. -/// -/// -/// The rule verifies that the dictionary returned by -/// is not null and that each key -/// 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(); - if (schemes is null) - { - errors.Add("security schemes: GetSecuritySchemes returned null"); - return Task.FromResult>(errors); - } - - foreach (var pair in schemes) - { - if (pair.Value is null) - { - errors.Add($"security schemes: scheme '{pair.Key}' has a null descriptor"); - } - else 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); - } -}