diff --git a/.github/workflows/container.yml b/.github/workflows/container.yml new file mode 100644 index 0000000..f986dcb --- /dev/null +++ b/.github/workflows/container.yml @@ -0,0 +1,139 @@ +name: Docker Build & Publish + +on: + release: + types: [published] + push: + tags: ['v*'] + +permissions: + contents: read + packages: write + attestations: write + id-token: write + +env: + REGISTRY: ghcr.io + IMAGE_NAME: authkits/authkit.server + LOCAL_TAG: authkit-server:test + +jobs: + build: + name: Build Image + runs-on: ubuntu-latest + steps: + - name: Checkout code + uses: actions/checkout@v4 + + - name: Set up QEMU + uses: docker/setup-qemu-action@v3 + + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@v3 + + - name: Build image (local, no push) + uses: docker/build-push-action@v6 + with: + context: . + file: ./Dockerfile + load: true + tags: ${{ env.LOCAL_TAG }} + cache-from: type=gha + cache-to: type=gha,mode=max + + - name: Save image artifact + run: docker save ${{ env.LOCAL_TAG }} | gzip > /tmp/image.tar.gz + + - name: Upload image artifact + uses: actions/upload-artifact@v4 + with: + name: docker-image + path: /tmp/image.tar.gz + retention-days: 1 + + test: + name: Smoke Test + runs-on: ubuntu-latest + needs: build + steps: + - name: Download image artifact + uses: actions/download-artifact@v4 + with: + name: docker-image + path: /tmp + + - name: Load image + run: docker load < /tmp/image.tar.gz + + - name: Run container + run: docker run -d -p 8080:80 --name authkit ${{ env.LOCAL_TAG }} + + - name: Wait for startup + run: sleep 15 + + - name: Verify container is running + run: | + STATE=$(docker inspect -f '{{.State.Running}}' authkit) + if [ "$STATE" != "true" ]; then + echo "Container is not running" + docker logs authkit + exit 1 + fi + + - name: Show logs + if: always() + run: docker logs authkit + + - name: HTTP smoke check + run: | + curl -fsS http://localhost:8080/ -o /dev/null \ + && echo "HTTP OK" \ + || echo "No HTTP endpoint (non-fatal)" + + - name: Stop container + if: always() + run: docker stop authkit || true + + publish: + name: Publish to GHCR + runs-on: ubuntu-latest + needs: test + steps: + - name: Checkout code + uses: actions/checkout@v4 + + - name: Set up QEMU + uses: docker/setup-qemu-action@v3 + + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@v3 + + - name: Log in to GHCR + uses: docker/login-action@v3 + with: + registry: ${{ env.REGISTRY }} + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + + - name: Extract metadata + id: meta + uses: docker/metadata-action@v5 + with: + images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }} + tags: | + type=semver,pattern={{version}} + type=semver,pattern={{major}}.{{minor}} + type=raw,value=latest + + - name: Build and push image + uses: docker/build-push-action@v6 + with: + context: . + file: ./Dockerfile + push: true + platforms: linux/amd64,linux/arm64 + tags: ${{ steps.meta.outputs.tags }} + labels: ${{ steps.meta.outputs.labels }} + cache-from: type=gha + provenance: true + sbom: true diff --git a/.github/workflows/plugin-validation.yml b/.github/workflows/plugin-validation.yml new file mode 100644 index 0000000..da9ae5e --- /dev/null +++ b/.github/workflows/plugin-validation.yml @@ -0,0 +1,58 @@ +name: Plugin Contract Validation + +on: + push: + branches: [main, development] + tags: ['v*'] + paths: + - 'src/Plugins/**' + - 'tools/PluginContractValidator/**' + - '.github/workflows/plugin-validation.yml' + pull_request: + branches: [main, development] + paths: + - 'src/Plugins/**' + - 'tools/PluginContractValidator/**' + - '.github/workflows/plugin-validation.yml' + workflow_dispatch: + +env: + DOTNET_VERSION: '10.0.x' + VALIDATOR_PROJECT: 'tools/PluginContractValidator/PluginContractValidator.csproj' + PLUGINS_STAGING: 'out/plugins' + +permissions: + contents: read + +jobs: + validate: + name: Validate Plugin Contracts + runs-on: ubuntu-latest + steps: + - name: Checkout code + uses: actions/checkout@v4 + + - name: Setup .NET SDK + uses: actions/setup-dotnet@v4 + with: + dotnet-version: ${{ env.DOTNET_VERSION }} + + - name: Publish plugins + run: | + mkdir -p "${{ env.PLUGINS_STAGING }}" + for proj in $(find src/Plugins -name '*.csproj' \ + -not -path '*/Abstractions/*' \ + -not -path '*/obj/*' \ + -not -path '*/bin/*'); do + name=$(basename "$proj" .csproj) + echo "Publishing plugin: $name" + dotnet publish "$proj" -c Release -o "${{ env.PLUGINS_STAGING }}/$name" --nologo + done + + - name: Build contract validator + run: dotnet build "${{ env.VALIDATOR_PROJECT }}" -c Release --nologo + + - name: Run contract validation + run: | + VALIDATOR_DLL="tools/PluginContractValidator/bin/Release/net10.0/PluginContractValidator.dll" + dotnet "$VALIDATOR_DLL" "${{ github.workspace }}/${{ env.PLUGINS_STAGING }}" diff --git a/.github/workflows/security.yml b/.github/workflows/security.yml new file mode 100644 index 0000000..9d0f1d1 --- /dev/null +++ b/.github/workflows/security.yml @@ -0,0 +1,204 @@ +name: Security Scan + +on: + push: + branches: [main, development] + pull_request: + branches: [main, development] + schedule: + - cron: '0 2 * * 1' + workflow_dispatch: + +env: + DOTNET_VERSION: '10.0.x' + SOLUTION_FILE: 'AuthKit.slnx' + +permissions: + contents: read + security-events: write + packages: read + id-token: write + attestations: write + +jobs: + dependency-review: + name: Dependency Review + runs-on: ubuntu-latest + steps: + - name: Checkout code + uses: actions/checkout@v4 + + - name: Setup .NET SDK + uses: actions/setup-dotnet@v4 + with: + dotnet-version: ${{ env.DOTNET_VERSION }} + + - name: Restore dependencies + run: dotnet restore ${{ env.SOLUTION_FILE }} + + - name: Run NuGet vulnerability scan + run: | + dotnet tool install --global NuGetAuditor + export PATH="$PATH:$HOME/.dotnet/tools" + NuGetAuditor audit --format json --output audit-results.json + + - name: Upload vulnerability results + uses: github/codeql-action/upload-sarif@v3 + if: always() + with: + sarif_file: audit-results.json + category: nuget-audit + + codeql-analysis: + name: CodeQL Analysis + runs-on: ubuntu-latest + steps: + - name: Checkout code + uses: actions/checkout@v4 + + - name: Initialize CodeQL + uses: github/codeql-action/init@v3 + with: + languages: csharp + queries: security-extended,security-and-quality + + - name: Setup .NET SDK + uses: actions/setup-dotnet@v4 + with: + dotnet-version: ${{ env.DOTNET_VERSION }} + + - name: Build solution + run: dotnet build ${{ env.SOLUTION_FILE }} --configuration Release --no-restore + + - name: Perform CodeQL Analysis + uses: github/codeql-action/analyze@v3 + with: + category: "/language:csharp" + + secret-scan: + name: Secret Scan + runs-on: ubuntu-latest + steps: + - name: Checkout code + uses: actions/checkout@v4 + with: + fetch-depth: 0 + + - name: Run TruffleHog + uses: trufflesecurity/trufflehog@main + with: + path: ./ + base: main + head: HEAD + + license-check: + name: License Compliance + runs-on: ubuntu-latest + if: github.ref == 'refs/heads/main' + steps: + - name: Checkout code + uses: actions/checkout@v4 + + - name: Setup .NET SDK + uses: actions/setup-dotnet@v4 + with: + dotnet-version: ${{ env.DOTNET_VERSION }} + + - name: Restore dependencies + run: dotnet restore ${{ env.SOLUTION_FILE }} + + - name: Check licenses + run: | + dotnet tool install --global dotnet-license-scanner + export PATH="$PATH:$HOME/.dotnet/tools" + dotnet-license-scanner scan --solution ${{ env.SOLUTION_FILE }} --output licenses.json --fail-on-unapproved + + - name: Upload license report + uses: actions/upload-artifact@v4 + if: always() + with: + name: license-report + path: licenses.json + + sbom-generation: + name: Generate SBOM + runs-on: ubuntu-latest + if: github.ref == 'refs/heads/main' + permissions: + id-token: write + contents: write + attestations: write + steps: + - name: Checkout code + uses: actions/checkout@v4 + + - name: Setup .NET SDK + uses: actions/setup-dotnet@v4 + with: + dotnet-version: ${{ env.DOTNET_VERSION }} + + - name: Restore dependencies + run: dotnet restore ${{ env.SOLUTION_FILE }} + + - name: Build solution + run: dotnet build ${{ env.SOLUTION_FILE }} --configuration Release --no-restore + + - name: Generate SBOM + uses: ansible/sbom-action@v1 + with: + path: . + format: spdx-json + output-file: sbom.spdx.json + + - name: Upload SBOM + uses: actions/upload-artifact@v4 + with: + name: sbom + path: sbom.spdx.json + + - name: Attest SBOM + uses: actions/attest-sbom@v2 + with: + sbom-path: sbom.spdx.json + + container-scan: + name: Container Scan + runs-on: ubuntu-latest + if: github.ref == 'refs/heads/main' && hashFiles('**/Dockerfile') != '' + steps: + - name: Checkout code + uses: actions/checkout@v4 + + - name: Build Docker image + run: | + docker build -t authkit-server:latest -f Dockerfile . + + - name: Run Trivy vulnerability scanner + uses: aquasecurity/trivy-action@master + with: + image-ref: 'authkit-server:latest' + format: 'sarif' + output: 'trivy-results.sarif' + severity: 'CRITICAL,HIGH,MEDIUM' + + - name: Upload Trivy results + uses: github/codeql-action/upload-sarif@v3 + if: always() + with: + sarif_file: trivy-results.sarif + category: container-scan + + dotnet-format: + name: Code Style Check + runs-on: ubuntu-latest + steps: + - name: Checkout code + uses: actions/checkout@v4 + + - name: Setup .NET SDK + uses: actions/setup-dotnet@v4 + with: + dotnet-version: ${{ env.DOTNET_VERSION }} + + - name: Check code formatting + run: dotnet format ${{ env.SOLUTION_FILE }} --verify-no-changes --verbosity diagnostic diff --git a/.gitignore b/.gitignore index c6484b1..2df1e29 100644 --- a/.gitignore +++ b/.gitignore @@ -1,7 +1,9 @@ /certs/devcert.pfx +.obsidian/ bin/ obj/ /plugins/ +/out/ .idea/ .env /net-commander diff --git a/AuthKit.slnx b/AuthKit.slnx index 1b00431..ad60a5d 100644 --- a/AuthKit.slnx +++ b/AuthKit.slnx @@ -11,6 +11,9 @@ + + + diff --git a/Taskfile.docker.yml b/Taskfile.docker.yml new file mode 100644 index 0000000..1284fce --- /dev/null +++ b/Taskfile.docker.yml @@ -0,0 +1,33 @@ +version: '3' + +tasks: + build: + desc: Build the Docker image locally (no push) + cmds: + - docker build -t {{.IMAGE}}:dev -f Dockerfile . + + run: + desc: Run the container locally on :8080 + deps: [build] + cmds: + - docker run --rm -p 8080:80 --name authkit-local {{.IMAGE}}:dev + + test: + desc: Smoke test the built image (start, log, stop) + deps: [build] + cmds: + - | + docker run -d -p 8080:80 --name authkit-smoke {{.IMAGE}}:dev + sleep 15 + docker logs authkit-smoke + curl -fsS http://localhost:8080/ >/dev/null && echo "HTTP OK" || echo "no HTTP endpoint (non-fatal)" + docker stop authkit-smoke || true + + publish: + desc: Build multi-arch image and push to GHCR + preconditions: + - sh: command -v docker >/dev/null && docker buildx version >/dev/null 2>&1 + msg: "docker and docker buildx are required" + prompt: "Push {{.REGISTRY}}/{{.IMAGE}}:{{.VERSION}} to GHCR? Requires docker login." + cmds: + - docker buildx build --push --platform linux/amd64,linux/arm64 -t {{.REGISTRY}}/{{.IMAGE}}:latest -t {{.REGISTRY}}/{{.IMAGE}}:{{.VERSION}} -f Dockerfile . diff --git a/Taskfile.yml b/Taskfile.yml new file mode 100644 index 0000000..45a1e33 --- /dev/null +++ b/Taskfile.yml @@ -0,0 +1,131 @@ +version: '3' + +env: + DOTNET_CLI_TELEMETRY_OPTOUT: '1' + DOTNET_NOLOGO: '1' + DOTNET_SKIP_FIRST_TIME_EXPERIENCE: '1' + REGISTRY: ghcr.io + IMAGE: authkits/authkit.server + +vars: + SOLUTION: AuthKit.slnx + HOST_PROJECT: src/Host/Host.csproj + PLUGINS_DIR: src/Plugins + VALIDATOR: + sh: echo tools/PluginContractValidator + VERSION: + sh: git describe --tags --always 2>/dev/null || echo dev + +tasks: + default: + desc: List all available tasks + cmds: + - task --list + silent: true + + restore: + desc: Restore NuGet dependencies + preconditions: + - sh: command -v dotnet >/dev/null + msg: "dotnet SDK is required (https://dot.net)" + sources: + - '**/*.csproj' + - '{{.SOLUTION}}' + - Directory.Packages.props + generates: + - '**/obj/project.assets.json' + cmds: + - dotnet restore {{.SOLUTION}} + + build: + desc: Build the solution in Release + deps: [restore] + sources: + - 'src/**/*.cs' + - '**/*.csproj' + generates: + - 'src/Host/bin/**' + cmds: + - dotnet build {{.SOLUTION}} --configuration Release --no-restore + + test: + desc: Run the test suite + deps: [build] + cmds: + - dotnet test {{.SOLUTION}} --configuration Release --no-build + + test:watch: + desc: Run tests and re-run on file changes + deps: [build] + watch: true + cmds: + - dotnet test {{.SOLUTION}} --configuration Release --no-build + + format: + desc: Verify code formatting (fails if changes required) + cmds: + - dotnet format {{.SOLUTION}} --verify-no-changes + + format:fix: + desc: Apply code formatting in place + cmds: + - dotnet format {{.SOLUTION}} + + security:audit: + desc: List vulnerable NuGet packages (incl. transitive) + cmds: + - dotnet list {{.SOLUTION}} package --vulnerable --include-transitive + + security:outdated: + desc: List outdated NuGet packages + cmds: + - dotnet list {{.SOLUTION}} package --outdated + + plugins:publish: + desc: Publish all plugins to out/plugins/ + preconditions: + - sh: command -v dotnet >/dev/null + msg: "dotnet SDK is required (https://dot.net)" + cmds: + - | + mkdir -p out/plugins + for proj in $(find {{.PLUGINS_DIR}} -name '*.csproj' \ + -not -path '*/Abstractions/*' \ + -not -path '*/obj/*' \ + -not -path '*/bin/*'); do + name=$(basename "$proj" .csproj) + echo "Publishing plugin: $name" + dotnet publish "$proj" --configuration Release --output "out/plugins/$name" --nologo + done + + plugins:validate: + desc: Validate plugin contracts against the loaded assemblies + deps: [plugins:publish] + cmds: + - dotnet build {{.VALIDATOR}} --configuration Release --nologo + - | + DLL=$(find {{.VALIDATOR}}/bin/Release -name PluginContractValidator.dll | head -n1) + dotnet "$DLL" "$(pwd)/out/plugins" + + ci: + desc: Run the full local CI pipeline + deps: + - build + - test + - format + - plugins:validate + aliases: + - precommit + + clean: + desc: Remove build output and staging directories + cmds: + - dotnet clean {{.SOLUTION}} --nologo + - cmd: rm -rf out + platforms: [linux, darwin] + - cmd: Remove-Item -Recurse -Force out -ErrorAction SilentlyContinue + platforms: [windows] + +includes: + docker: + taskfile: ./Taskfile.docker.yml diff --git a/tools/PluginContractValidator/PluginAssemblyLoader.cs b/tools/PluginContractValidator/PluginAssemblyLoader.cs new file mode 100644 index 0000000..1e20ea8 --- /dev/null +++ b/tools/PluginContractValidator/PluginAssemblyLoader.cs @@ -0,0 +1,129 @@ +using System.Reflection; +using System.Runtime.Loader; +using AuthKit.Plugins.Abstractions; + +namespace PluginContractValidator.Loading; + +/// +/// Loads a plugin entry assembly using the same isolation model as the AuthKit host. +/// +/// +/// +/// Each plugin resolves its own dependencies through an +/// attached to . The resolver stays attached for the +/// lifetime of the process so that lazily-loaded dependencies (for example, types referenced +/// inside CheckHealthAsync) continue to resolve, exactly as in the host. +/// +/// +/// A plugin directory is expected to contain an entry assembly whose file name matches the +/// directory name. Directories without a matching assembly, or assemblies without a public, +/// non-abstract implementation with a parameterless constructor, +/// are reported as load errors rather than thrown. +/// +/// +public sealed class PluginAssemblyLoader : IPluginLoader +{ + private static readonly List Resolvers = new(); + private static readonly object Gate = new(); + private static Func? _handler; + + /// + /// Loads the plugin entry assembly and activates its implementation. + /// + /// The full path to the plugin's entry assembly. + /// + /// A containing the loaded plugin, or the errors that + /// prevented loading. + /// + public PluginLoadResult Load(string entryDll) + { + var errors = new List(); + + try + { + var resolver = new AssemblyDependencyResolver(entryDll); + AttachResolver(resolver); + + Assembly assembly; + try + { + assembly = AssemblyLoadContext.Default.LoadFromAssemblyPath(entryDll); + } + catch (Exception ex) + { + errors.Add($"dependency loading failed: {ex.Message}"); + return new PluginLoadResult(null, errors); + } + + Type? pluginType; + try + { + pluginType = assembly.GetTypes() + .FirstOrDefault(t => t is { IsPublic: true, IsAbstract: false } + && typeof(IAuthKitPlugin).IsAssignableFrom(t) + && t.GetConstructor(Type.EmptyTypes) is not null); + } + catch (Exception ex) + { + errors.Add($"type discovery failed: {ex.Message}"); + return new PluginLoadResult(null, errors); + } + + if (pluginType is null) + { + errors.Add("no public, non-abstract IAuthKitPlugin implementation with a parameterless constructor"); + return new PluginLoadResult(null, errors); + } + + IAuthKitPlugin instance; + try + { + instance = (IAuthKitPlugin)Activator.CreateInstance(pluginType)!; + } + catch (Exception ex) + { + errors.Add($"activation failed: {ex.Message}"); + return new PluginLoadResult(null, errors); + } + + return new PluginLoadResult(new LoadedPlugin(instance, assembly), errors); + } + catch (Exception ex) + { + errors.Add($"unexpected error: {ex.Message}"); + return new PluginLoadResult(null, errors); + } + } + + /// + /// Registers a dependency resolver for , ensuring it + /// is attached exactly once for the lifetime of the process. + /// + /// The dependency resolver associated with a loaded plugin assembly. + private static void AttachResolver(AssemblyDependencyResolver resolver) + { + lock (Gate) + { + Resolvers.Add(resolver); + + if (_handler is null) + { + _handler = (context, name) => + { + for (var i = Resolvers.Count - 1; i >= 0; i--) + { + var path = Resolvers[i].ResolveAssemblyToPath(name); + if (path is not null) + { + return context.LoadFromAssemblyPath(path); + } + } + + return null; + }; + + AssemblyLoadContext.Default.Resolving += _handler; + } + } + } +} diff --git a/tools/PluginContractValidator/PluginContractValidator.csproj b/tools/PluginContractValidator/PluginContractValidator.csproj new file mode 100644 index 0000000..6c2d3cb --- /dev/null +++ b/tools/PluginContractValidator/PluginContractValidator.csproj @@ -0,0 +1,17 @@ + + + Exe + net10.0 + enable + enable + false + PluginContractValidator + PluginContractValidator + + + + + + + + diff --git a/tools/PluginContractValidator/Program.cs b/tools/PluginContractValidator/Program.cs new file mode 100644 index 0000000..5590622 --- /dev/null +++ b/tools/PluginContractValidator/Program.cs @@ -0,0 +1,66 @@ +using PluginContractValidator; +using PluginContractValidator.Loading; +using PluginContractValidator.Rules; + +var pluginsRoot = args.Length > 0 ? args[0] : "src/Plugins"; + +if (!Directory.Exists(pluginsRoot)) +{ + Console.Error.WriteLine($"Plugins root not found: {pluginsRoot}"); + return 1; +} + +IPluginLoader loader = new PluginAssemblyLoader(); +ContractValidator validator = new ContractValidator(new IPluginContractRule[] +{ + new MetadataRule(), + new RegistrationRule(), + new SecuritySchemesRule(), + new MiddlewareRule(), + new HealthRule(), +}); + +var failures = 0; + +foreach (var pluginDir in Directory.GetDirectories(pluginsRoot)) +{ + var pluginName = Path.GetFileName(pluginDir.TrimEnd(Path.DirectorySeparatorChar)); + var entryDll = Path.Combine(pluginDir, $"{pluginName}.dll"); + + if (!File.Exists(entryDll)) + { + Console.WriteLine($"[SKIP] {pluginName}: entry assembly '{entryDll}' not found"); + continue; + } + + var loadResult = loader.Load(entryDll); + if (!loadResult.Succeeded) + { + failures++; + Console.WriteLine($"[FAIL] {pluginName}"); + foreach (var error in loadResult.Errors) + { + Console.WriteLine($" - {error}"); + } + + continue; + } + + var errors = await validator.ValidateAsync(loadResult.Plugin!); + + if (errors.Count == 0) + { + Console.WriteLine($"[PASS] {pluginName} v{loadResult.Plugin!.Instance.Version}"); + } + else + { + failures++; + Console.WriteLine($"[FAIL] {pluginName}"); + foreach (var error in errors) + { + Console.WriteLine($" - {error}"); + } + } +} + +return failures == 0 ? 0 : 1; diff --git a/tools/PluginContractValidator/src/ContractValidator.cs b/tools/PluginContractValidator/src/ContractValidator.cs new file mode 100644 index 0000000..62cf69f --- /dev/null +++ b/tools/PluginContractValidator/src/ContractValidator.cs @@ -0,0 +1,36 @@ +namespace PluginContractValidator; + +/// +/// Runs every registered against a loaded plugin and +/// aggregates the resulting contract violations. +/// +/// +/// Rules are executed sequentially; each rule's violations are collected into a single +/// combined list so the caller sees every problem at once. +/// +/// The contract rules to execute for each plugin. +public sealed class ContractValidator(IEnumerable rules) +{ + private readonly IEnumerable _rules = rules; + + /// + /// Validates the supplied plugin against all registered rules. + /// + /// The loaded plugin to validate. + /// A token that can be used to cancel the validation. + /// The aggregated, read-only list of contract violations. + public async Task> ValidateAsync( + LoadedPlugin plugin, + CancellationToken cancellationToken = default) + { + var errors = new List(); + + foreach (var rule in _rules) + { + cancellationToken.ThrowIfCancellationRequested(); + errors.AddRange(await rule.ValidateAsync(plugin, cancellationToken)); + } + + return errors; + } +} diff --git a/tools/PluginContractValidator/src/IPluginContractRule.cs b/tools/PluginContractValidator/src/IPluginContractRule.cs new file mode 100644 index 0000000..b71559f --- /dev/null +++ b/tools/PluginContractValidator/src/IPluginContractRule.cs @@ -0,0 +1,26 @@ +namespace PluginContractValidator; + +/// +/// Validates single contract concern of loaded plugin. +/// +/// +/// Rules are composed by and executed independently, so a +/// failure in one concern does not prevent the others from being evaluated. +/// +public interface IPluginContractRule +{ + /// + /// Gets a human-readable name of the validated contract concern (for example, "Metadata"). + /// + string Name { get; } + + /// + /// Validates the plugin and returns the list of contract violations. + /// + /// The loaded plugin to validate. + /// A token that can be used to cancel the validation. + /// + /// A read-only list of violation messages. An empty list means the rule passed. + /// + Task> ValidateAsync(LoadedPlugin plugin, CancellationToken cancellationToken = default); +} diff --git a/tools/PluginContractValidator/src/IPluginLoader.cs b/tools/PluginContractValidator/src/IPluginLoader.cs new file mode 100644 index 0000000..60f40c1 --- /dev/null +++ b/tools/PluginContractValidator/src/IPluginLoader.cs @@ -0,0 +1,20 @@ +using AuthKit.Plugins.Abstractions; + +namespace PluginContractValidator; + +/// +/// Loads a plugin entry assembly and instantiates its implementation. +/// +public interface IPluginLoader +{ + /// + /// Loads the plugin entry assembly located at and activates its + /// implementation. + /// + /// The full path to the plugin's entry assembly (named after its directory). + /// + /// A describing the loaded plugin, or the errors encountered + /// while loading it. + /// + PluginLoadResult Load(string entryDll); +} diff --git a/tools/PluginContractValidator/src/LoadedPlugin.cs b/tools/PluginContractValidator/src/LoadedPlugin.cs new file mode 100644 index 0000000..78d9e11 --- /dev/null +++ b/tools/PluginContractValidator/src/LoadedPlugin.cs @@ -0,0 +1,28 @@ +using System.Reflection; +using AuthKit.Plugins.Abstractions; + +namespace PluginContractValidator; + +/// +/// Represents a plugin assembly that has been successfully loaded and instantiated +/// by the validation host. +/// +/// +/// The wrapper keeps both the activated instance and the +/// it was loaded from, so that individual contract rules can +/// inspect runtime metadata without re-loading the assembly. +/// +/// The activated plugin instance implementing . +/// The assembly the plugin type was loaded from. +public sealed class LoadedPlugin(IAuthKitPlugin instance, Assembly assembly) +{ + /// + /// Gets the activated plugin instance implementing . + /// + public IAuthKitPlugin Instance { get; } = instance; + + /// + /// Gets the assembly the plugin type was loaded from. + /// + public Assembly Assembly { get; } = assembly; +} diff --git a/tools/PluginContractValidator/src/PluginLoadResult.cs b/tools/PluginContractValidator/src/PluginLoadResult.cs new file mode 100644 index 0000000..ff8f8dd --- /dev/null +++ b/tools/PluginContractValidator/src/PluginLoadResult.cs @@ -0,0 +1,18 @@ +namespace PluginContractValidator; + +/// +/// Encapsulates the outcome of attempting to load a plugin assembly. +/// +/// +/// When loading fails, is null and +/// contains the human-readable reasons for the failure. +/// +/// The loaded plugin, or null when loading failed. +/// The list of contract or loading violations encountered. +public sealed record PluginLoadResult(LoadedPlugin? Plugin, IReadOnlyList Errors) +{ + /// + /// Gets a value indicating whether the plugin was loaded successfully. + /// + public bool Succeeded => Plugin is not null; +} diff --git a/tools/PluginContractValidator/src/Rules/HealthRule.cs b/tools/PluginContractValidator/src/Rules/HealthRule.cs new file mode 100644 index 0000000..fb2619c --- /dev/null +++ b/tools/PluginContractValidator/src/Rules/HealthRule.cs @@ -0,0 +1,44 @@ +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 new file mode 100644 index 0000000..f7cc9fc --- /dev/null +++ b/tools/PluginContractValidator/src/Rules/MetadataRule.cs @@ -0,0 +1,51 @@ +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 new file mode 100644 index 0000000..b553591 --- /dev/null +++ b/tools/PluginContractValidator/src/Rules/MiddlewareRule.cs @@ -0,0 +1,64 @@ +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/RegistrationRule.cs b/tools/PluginContractValidator/src/Rules/RegistrationRule.cs new file mode 100644 index 0000000..e5e897f --- /dev/null +++ b/tools/PluginContractValidator/src/Rules/RegistrationRule.cs @@ -0,0 +1,53 @@ +using AuthKit.Plugins.Abstractions; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; + +namespace PluginContractValidator.Rules; + +/// +/// Ensures ConfigureServices registers dependencies without throwing and that the +/// resulting service container can be built (dependency wiring is valid). +/// +public sealed class RegistrationRule : IPluginContractRule +{ + /// Gets the rule name ("Registration"). + public string Name => "Registration"; + + /// + /// Invokes against a fresh service collection + /// and then builds the to confirm the dependency graph is + /// constructible. + /// + /// The loaded plugin to validate. + /// A token that can be used to cancel the validation. + /// The list of registration violations; empty when registration succeeds. + public Task> ValidateAsync( + LoadedPlugin plugin, + CancellationToken cancellationToken = default) + { + var errors = new List(); + var services = new ServiceCollection(); + var configuration = new ConfigurationBuilder().Build(); + + try + { + plugin.Instance.ConfigureServices(services, configuration); + } + catch (Exception ex) + { + errors.Add($"registration: ConfigureServices threw: {ex.Message}"); + return Task.FromResult>(errors); + } + + try + { + services.BuildServiceProvider(); + } + catch (Exception ex) + { + errors.Add($"registration: service provider build failed (bad dependency wiring): {ex.Message}"); + } + + return Task.FromResult>(errors); + } +} diff --git a/tools/PluginContractValidator/src/Rules/SecuritySchemesRule.cs b/tools/PluginContractValidator/src/Rules/SecuritySchemesRule.cs new file mode 100644 index 0000000..ababa62 --- /dev/null +++ b/tools/PluginContractValidator/src/Rules/SecuritySchemesRule.cs @@ -0,0 +1,59 @@ +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); + } +}