Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
86814e4
feat: add plugin contract validation tool
rian-be Sep 3, 2026
89c847f
refactor: relocate security scheme contracts and update references
rian-be Sep 3, 2026
97f3883
feat: add plugin validation and extension utilities
rian-be Sep 3, 2026
f47fa6d
feat: add plugin metadata and semantic version types
rian-be Sep 3, 2026
f437028
refactor: expand plugin contract metadata
rian-be Sep 3, 2026
ab55125
feat: add DevTokens plugin manifest metadata
rian-be Sep 3, 2026
7722144
refactor: validate plugin manifests and host compatibility
rian-be Sep 3, 2026
df912da
refactor: integrate plugin version compatibility
rian-be Sep 3, 2026
3d928b5
docs: add ADR-017 for plugin contract architecture
rian-be Sep 4, 2026
0bf78fe
Ref: Centralize plugin metadata via attributes
rian-be Sep 8, 2026
f09601f
feat(manifest): introduce plugin metadata and type resolver providers
rian-be Sep 8, 2026
73ce3ff
feat(manifest): add assembly based manifest generation
rian-be Sep 8, 2026
efdf210
feat(manifest): introduce example AuthKit plugin
rian-be Sep 8, 2026
f1ad36f
feat(manifest): introduce manifest generator tool
rian-be Sep 8, 2026
6920cbd
feat(plugin): introduce metadata attribute and manifest generation
rian-be Sep 8, 2026
c66382a
refactor(plugin): migrate metadata to attributes
rian-be Sep 8, 2026
40e942e
Merge branch 'development' into plugin-contract-with-metadata-model
rian-be Sep 8, 2026
0a68d99
feat(tools): add PluginContractValidator project
rian-be Sep 8, 2026
9291c07
Merge branch 'plugin-contract-with-metadata-model' of https://github.…
rian-be Sep 8, 2026
916cae7
refactor(validator): rename to AuthKit namespace
rian-be Sep 8, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions AuthKit.sln.DotSettings
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
<wpf:ResourceDictionary xml:space="preserve" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:s="clr-namespace:System;assembly=mscorlib" xmlns:ss="urn:shemas-jetbrains-com:settings-storage-xaml" xmlns:wpf="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<s:Boolean x:Key="/Default/UserDictionary/Words/=creds/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=devtokens/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=jwks/@EntryIndexedValue">True</s:Boolean></wpf:ResourceDictionary>
2 changes: 1 addition & 1 deletion AuthKit.slnx
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
<Project Path="src/Plugins/Solutions/DevTokens/DevTokens.csproj" />
</Folder>
<Folder Name="/Tools/">
<Project Path="tools/PluginContractValidator/PluginContractValidator.csproj" />
<Project Path="tools/AuthKit.PluginContractValidator/AuthKit.PluginContractValidator.csproj" />
</Folder>
<Project Path="src/Core/Core.csproj" />
<Project Path="src/Host/Host.csproj" />
Expand Down
12 changes: 11 additions & 1 deletion Directory.Packages.props
Original file line number Diff line number Diff line change
Expand Up @@ -2,28 +2,38 @@
<PropertyGroup>
<ManagePackageVersionsCentrally>true</ManagePackageVersionsCentrally>
</PropertyGroup>

<ItemGroup>
<PackageVersion Include="FluentValidation" Version="12.0.0" />
<PackageVersion Include="Google.Protobuf" Version="3.32.0" />
<PackageVersion Include="Grpc.AspNetCore" Version="2.71.0" />
<PackageVersion Include="Grpc.Core.Api" Version="2.71.0" />
<PackageVersion Include="Grpc.Tools" Version="2.72.0" />
<PackageVersion Include="Marten" Version="8.13.2" />

<PackageVersion Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="10.0.0-rc.2.25502.107" />
<PackageVersion Include="Microsoft.AspNetCore.Authorization" Version="10.0.0-rc.2.25502.107" />
<PackageVersion Include="Microsoft.AspNetCore.Http.Abstractions" Version="2.3.0" />

<PackageVersion Include="Microsoft.Extensions.Configuration" Version="10.0.0" />
<PackageVersion Include="Microsoft.Extensions.Configuration.Abstractions" Version="10.0.0" />
<PackageVersion Include="Microsoft.Extensions.DependencyInjection" Version="10.0.0" />
<PackageVersion Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="10.0.0" />

<PackageVersion Include="Microsoft.IdentityModel.JsonWebTokens" Version="8.14.0" />
<PackageVersion Include="Microsoft.IdentityModel.Tokens" Version="8.14.0" />

<PackageVersion Include="Scrutor" Version="6.1.0" />

<PackageVersion Include="Swashbuckle.AspNetCore.Annotations" Version="9.0.6" />
<PackageVersion Include="Swashbuckle.AspNetCore.Swagger" Version="9.0.6" />
<PackageVersion Include="Swashbuckle.AspNetCore.SwaggerGen" Version="9.0.6" />
<PackageVersion Include="Swashbuckle.AspNetCore.SwaggerUI" Version="9.0.6" />

<PackageVersion Include="System.IdentityModel.Tokens.Jwt" Version="8.14.0" />

<PackageVersion Include="WolverineFx" Version="5.0.0" />
<PackageVersion Include="WolverineFx.FluentValidation" Version="5.0.0" />
<PackageVersion Include="WolverineFx.Marten" Version="5.0.0" />
</ItemGroup>
</Project>
</Project>
2 changes: 2 additions & 0 deletions Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -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"]
190 changes: 190 additions & 0 deletions Docs/ADR/017-Plugin-Contract-and-Dynamic-Loading-Architecture.md
Original file line number Diff line number Diff line change
@@ -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<string> Tags` - free-form classification, null/whitespace elements invalid. Defaults to `Array.Empty<string>`.
- `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<string> DependsOn` - declares plugin `Id` values (never display names). Defaults to `Array.Empty<string>`.

### 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<string> 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<string> 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<br/>plugin.json / manifest"] --> B["IPluginDiscoverer"]
B --> C["DiscoveredPlugin<br/>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<br/>+ dependency resolver"]
F --> G["LoadedPlugin<br/>Manifest + Instance"]
G --> H["Plugin Contract<br/>Validation"]
G -->|No manifest| L["ACTIVATION"]
H --> I["Manifest ↔ Runtime<br/>Consistency Check"]
I --> J["PluginMetadata<br/>Immutable Runtime Snapshot"]
J --> K["Dependency Resolution<br/>+ 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.
24 changes: 19 additions & 5 deletions src/Host/Configuration/KestrelConfiguration.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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();
}

Expand Down Expand Up @@ -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();
}

Expand All @@ -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;
});
});
Expand Down
1 change: 1 addition & 0 deletions src/Host/Configuration/RestfulConfiguration.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using AuthKit.Plugins.Abstractions;
using AuthKit.Plugins.Abstractions.Contracts.SecuritySchemes;
using Host.Plugins;
using Microsoft.OpenApi.Models;

Expand Down
4 changes: 2 additions & 2 deletions src/Host/Plugins/LoadedPlugin.cs
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
using System.Reflection;
using AuthKit.Plugins.Abstractions;
using AuthKit.Plugins.Abstractions.Contracts;

namespace Host.Plugins;

/// <summary>
/// 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.
/// </summary>
/// <remarks>
Expand Down
Loading
Loading