diff --git a/src/.dockerignore b/.dockerignore similarity index 68% rename from src/.dockerignore rename to .dockerignore index 17a5ec5e..5e25fa11 100644 --- a/src/.dockerignore +++ b/.dockerignore @@ -1,39 +1,41 @@ **/.classpath **/.dockerignore **/.env -**/.git +**/.git/ **/.gitignore +**/.idea/ +**/.opencode/ **/.project **/.settings **/.toolstarget -**/.vs -**/.vscode +**/.dsh/ +**/.vs/ +**/.vscode/ **/*.*proj.user **/*.dbmdl **/*.jfm +**/*.suo +**/*.user **/azds.yaml -**/bin -**/charts +**/bin/ +**/charts/ **/docker-compose* **/Dockerfile* -**/node_modules +**/node_modules/ **/npm-debug.log -**/obj +**/obj/ **/secrets.dev.yaml **/values.dev.yaml LICENSE README.md -!**/.gitignore -!.git/HEAD -!.git/config -!.git/packed-refs -!.git/refs/heads/** +docs/ +tests/ -# AI +# AI instruction files. **/AGENTS.[Mm][Dd] **/agents.[Mm][Dd] **/SKILL.[Mm][Dd] **/skill.[Mm][Dd] -# Six Labors license key file: must always be present for build-time license validation +# Six Labors license key file: must always be present for build-time license validation. !**/sixlabors.lic diff --git a/.github/workflows/publish-release.yml b/.github/workflows/publish-release.yml new file mode 100644 index 00000000..08a39e04 --- /dev/null +++ b/.github/workflows/publish-release.yml @@ -0,0 +1,153 @@ +name: Publish Release + +# Runs only when the repository owner creates a release/x.y.z branch. The protected "release" environment supplies the Six Labors license and the pull request token, and requires approval. +# The repository ruleset restricts who can create release branches. + +on: + create: + +permissions: + contents: read + +jobs: + publish: + if: github.event.ref_type == 'branch' && startsWith(github.ref_name, 'release/') && github.actor == github.repository_owner + runs-on: ubuntu-latest + timeout-minutes: 90 + environment: release + permissions: + contents: read + steps: + - uses: actions/checkout@v4 + with: + ref: ${{ github.ref }} + fetch-depth: 0 + - name: Validate release branch name + env: + RELEASE_BRANCH: ${{ github.ref_name }} + run: | + if [[ ! "$RELEASE_BRANCH" =~ ^release/[0-9]+\.[0-9]+\.[0-9]+$ ]]; then + echo "Invalid release branch name. Use release/x.y.z." >&2 + exit 1 + fi + - name: Fetch master for the recording guard + run: git fetch --no-tags origin master:refs/remotes/origin/master + - name: Set up .NET + uses: actions/setup-dotnet@v4 + with: + dotnet-version: '10.0.100' + - name: Restore Six Labors license + shell: bash + env: + SIXLABORS_LICENSE_KEY: ${{ secrets.SIXLABORS_LICENSE_KEY }} + run: printf '%s\n' "$SIXLABORS_LICENSE_KEY" > src/Nemera.Domain/sixlabors.lic + - name: Publish, verify, and record official release + env: + SixLaborsLicenseKey: ${{ secrets.SIXLABORS_LICENSE_KEY }} + RELEASE_BRANCH: ${{ github.ref_name }} + run: dotnet msbuild build/build.proj -t:RecordBundledPlugins -p:Configuration=Release -p:OfficialReleaseBuild=true -p:AllowBundledPluginsRecording=true -p:ReleaseBranch="$RELEASE_BRANCH" + # Reuse the verified publish output, so the images contain exactly the plugin binaries whose hashes were recorded. + - name: Build release images + env: + RELEASE_BRANCH: ${{ github.ref_name }} + run: | + release_version="${RELEASE_BRANCH#release/}" + dotnet msbuild build/build.proj -t:Docker -p:Configuration=Release -p:OfficialReleaseBuild=true -p:ReusePublishedBundledPlugins=true -p:Version="$release_version" + - name: Upload release server files + uses: actions/upload-artifact@v4 + with: + name: release-api + path: bin/api/publish + if-no-files-found: error + - name: Upload release web files + uses: actions/upload-artifact@v4 + with: + name: release-web + path: bin/web/publish + if-no-files-found: error + - name: Upload bundled plugin manifest + uses: actions/upload-artifact@v4 + with: + name: bundled-plugins-manifest + path: build/BundledPlugins.manifest + if-no-files-found: error + + # The record job runs separately because it needs the pull request token to write to master, while the publish job stays read-only. + record-manifest: + needs: publish + runs-on: ubuntu-latest + environment: release + permissions: + contents: read + steps: + # Use the PAT rather than GITHUB_TOKEN, so the pull request opened below triggers the normal CI workflows. + - uses: actions/checkout@v4 + with: + ref: master + fetch-depth: 0 + token: ${{ secrets.RELEASE_PR_TOKEN }} + - name: Validate release branch name + env: + RELEASE_BRANCH: ${{ github.ref_name }} + run: | + if [[ ! "$RELEASE_BRANCH" =~ ^release/[0-9]+\.[0-9]+\.[0-9]+$ ]]; then + echo "Invalid release branch name. Use release/x.y.z." >&2 + exit 1 + fi + - name: Download bundled plugin manifest + uses: actions/download-artifact@v4 + with: + name: bundled-plugins-manifest + path: recorded-manifest + # Merge into master's current file instead of overwriting it, so hashes recorded by earlier releases survive when master advanced after this branch was cut. + - name: Merge the released manifest into master + run: | + python3 - <<'PY' + from pathlib import Path + + master_path = Path("build/BundledPlugins.manifest") + artifact_path = Path("recorded-manifest/BundledPlugins.manifest") + master_text = master_path.read_text() + existing_entries = { + line.strip().lower() + for line in master_text.splitlines() + if line.strip() and not line.strip().startswith("#") + } + new_entries = [] + for line in artifact_path.read_text().splitlines(): + entry = line.strip() + if not entry or entry.startswith("#") or entry.lower() in existing_entries: + continue + existing_entries.add(entry.lower()) + new_entries.append(entry) + if new_entries: + separator = "" if master_text.endswith("\n") else "\n" + master_path.write_text(master_text + separator + "\n".join(new_entries) + "\n") + PY + - name: Create record-release pull request + env: + GH_TOKEN: ${{ secrets.RELEASE_PR_TOKEN }} + RELEASE_BRANCH: ${{ github.ref_name }} + run: | + release_version="${RELEASE_BRANCH#release/}" + git config user.name "github-actions[bot]" + git config user.email "41898282+github-actions[bot]@users.noreply.github.com" + branch="other/record-release-$release_version" + git checkout -b "$branch" + git add build/BundledPlugins.manifest + # The list is append-only. Fail loudly if a merge or a rerun staged a deletion instead of relying on review to catch it. + if [[ -n "$(git diff --cached --numstat -- build/BundledPlugins.manifest | awk '$2 != 0')" ]]; then + echo "The bundled plugin trust manifest diff removes lines. The list is append-only." >&2 + exit 1 + fi + if git diff --cached --quiet; then + echo "The bundled plugin manifest is already up to date." + exit 0 + fi + git commit -m "Records bundled plugin hashes for $release_version" + git push --force-with-lease --set-upstream origin "$branch" + gh pr create \ + --base master \ + --head "$branch" \ + --title "Records bundled plugin hashes for $release_version" \ + --body "This pull request records the published plugin hashes of the $release_version release in the bundled plugin trust list. The release artifacts already embed the current release's official plugin manifest. Merge this pull request to keep the $release_version plugin binaries Official in future releases. Run All Tests and the branch validators should pass before merging." diff --git a/.github/workflows/run-tests.yml b/.github/workflows/run-tests.yml index 6f7387dd..353c1c5b 100644 --- a/.github/workflows/run-tests.yml +++ b/.github/workflows/run-tests.yml @@ -14,11 +14,11 @@ jobs: matrix: os: [ubuntu-latest, windows-latest, macOS-latest] steps: - - uses: actions/checkout@v2 + - uses: actions/checkout@v4 - name: Set up .NET - uses: actions/setup-dotnet@v1 + uses: actions/setup-dotnet@v4 with: - dotnet-version: '10.0.x' + dotnet-version: '10.0.100' - name: Raise file watcher limits # The test hosts create a Razor file watcher per static asset, and the default limit of 128 inotify instances # is reached when several hosts run in parallel. @@ -26,7 +26,9 @@ jobs: run: sudo sysctl -w fs.inotify.max_user_instances=1024 fs.inotify.max_user_watches=524288 - name: Restore Six Labors license shell: bash - run: printf '%s\n' "${{ secrets.SIXLABORS_LICENSE_KEY }}" > src/Nemera.Domain/sixlabors.lic + env: + SIXLABORS_LICENSE_KEY: ${{ secrets.SIXLABORS_LICENSE_KEY }} + run: printf '%s\n' "$SIXLABORS_LICENSE_KEY" > src/Nemera.Domain/sixlabors.lic - name: Restore dependencies run: dotnet restore src/Nemera.slnx - name: Build diff --git a/.github/workflows/validate-branch-name.yml b/.github/workflows/validate-branch-name.yml index ed7c8625..6a09f0de 100644 --- a/.github/workflows/validate-branch-name.yml +++ b/.github/workflows/validate-branch-name.yml @@ -10,15 +10,21 @@ jobs: runs-on: ubuntu-latest steps: - name: Check branch name + env: + BRANCH_NAME: ${{ github.ref_name }} run: | - branch_name=${{ github.ref_name }} - if [[ $branch_name == "master" ]]; then + branch_name="$BRANCH_NAME" + if [[ "$branch_name" == "master" ]]; then echo "Branch is master, skipping check." exit 0 fi - if ! [[ $branch_name =~ ^(feature|bugfix|hotfix|documentation|refactor|other)/ ]]; then + if [[ "$branch_name" =~ ^release/[0-9]+\.[0-9]+\.[0-9]+$ ]]; then + echo "Branch name '$branch_name' follows the release naming convention." + exit 0 + fi + if ! [[ "$branch_name" =~ ^(feature|bugfix|hotfix|documentation|refactor|other)/ ]]; then echo "Branch name '$branch_name' does not follow the naming convention." - echo "It should start with one of: feature/, bugfix/, hotfix/, documentation/, refactor/, or other/" - echo "Example: feature/my-feature-name or bugfix/fix-issue-123" + echo "It should start with one of: feature/, bugfix/, hotfix/, documentation/, refactor/, other/, or be a release/x.y.z branch." + echo "Example: feature/my-feature-name, bugfix/fix-issue-123, or release/1.2.3" exit 1 - fi \ No newline at end of file + fi diff --git a/.github/workflows/validate-pull-request-source-branch.yml b/.github/workflows/validate-pull-request-source-branch.yml index 3c28e6bc..a43948b8 100644 --- a/.github/workflows/validate-pull-request-source-branch.yml +++ b/.github/workflows/validate-pull-request-source-branch.yml @@ -10,11 +10,17 @@ jobs: runs-on: ubuntu-latest steps: - name: Check source branch name + env: + BRANCH_NAME: ${{ github.head_ref }} run: | - branch_name=${{ github.head_ref }} - if ! [[ $branch_name =~ ^(feature|bugfix|hotfix|documentation|refactor|other)/ ]]; then + branch_name="$BRANCH_NAME" + if [[ "$branch_name" =~ ^release/[0-9]+\.[0-9]+\.[0-9]+$ ]]; then + echo "Branch name '$branch_name' follows the release naming convention." + exit 0 + fi + if ! [[ "$branch_name" =~ ^(feature|bugfix|hotfix|documentation|refactor|other)/ ]]; then echo "Error: Branch name '$branch_name' does not follow the naming convention." - echo "It should start with one of: feature/, bugfix/, hotfix/, documentation/, refactor/, or other/" + echo "It should start with one of: feature/, bugfix/, hotfix/, documentation/, refactor/, other/, or be a release/x.y.z branch." exit 1 fi - echo "Branch name '$branch_name' follows the correct naming convention." \ No newline at end of file + echo "Branch name '$branch_name' follows the correct naming convention." diff --git a/AGENTS.md b/AGENTS.md index 58b167c6..ddb54c48 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -32,6 +32,7 @@ These rules apply to every agent, on every task, in this repository. For C# code ## Completing the work +- Test scope: decide once whether the change needs targeted tests or the full test suite. If the full suite is needed, run it once. If only targeted tests are needed, run only those. Never run targeted tests and then rerun the full suite for the same change, because that doubles the wait without adding coverage. - Never deliver an incomplete job while presenting it as done. A task is only done when every part of it is implemented, wired up, and verified to the same standard as the rest of the repository. - If a task is genuinely larger than what can be completed in a single pass, do not silently do a fraction of it and call it finished. Choose one of these, explicitly: - Delegate to subagents, one per subtask or workstream, and act as the coordinator/orchestrator: keep your own context for planning, dispatch, integration and verification, and let the subagents produce the bulk of the work. diff --git a/Directory.Build.props b/Directory.Build.props new file mode 100644 index 00000000..066585c9 --- /dev/null +++ b/Directory.Build.props @@ -0,0 +1,6 @@ + + + + $(MSBuildThisFileDirectory) + + diff --git a/README.md b/README.md index 3071ce24..69c5fd89 100644 --- a/README.md +++ b/README.md @@ -36,6 +36,7 @@ For those with technical curiosities, here are some goodies to browse through: 7. [4.3 Code scheduled jobs diagram](./docs/technical/architecture/4.3%20code-scheduler-diagram.svg) - To regenerate the diagrams after editing a `.puml` file, follow the [diagram rendering instructions](./docs/technical/architecture/README.md). - Also for Software Architects, you might want to take a look at the Architecture Decision Log, where you may find important stories from the past of Nemera's development, like [this one](./docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0001.md), and others like it. +- The release process, required GitHub environment, secrets and credential rotation are documented in [Releasing](./docs/technical/RELEASING.md). ## Telemetry and Observability diff --git a/build/BundledPlugins.deny.manifest b/build/BundledPlugins.deny.manifest new file mode 100644 index 00000000..7722ede5 --- /dev/null +++ b/build/BundledPlugins.deny.manifest @@ -0,0 +1,4 @@ +# Bundled plugin revocation list. +# Each line revokes one plugin binary: |. +# The reader removes these hashes from the historical and current trust lists, so a revoked binary is no longer marked Official. +# Remove an entry to restore trust in that hash. The historical trust list remains append-only. diff --git a/build/BundledPlugins.manifest b/build/BundledPlugins.manifest new file mode 100644 index 00000000..056b03f1 --- /dev/null +++ b/build/BundledPlugins.manifest @@ -0,0 +1,4 @@ +# Bundled plugin trust list. +# Each line identifies one shipped plugin binary: |. +# The release workflow appends a line for every released plugin binary. Never remove an existing line, so older bundled versions remain Official. +# Use BundledPlugins.deny.manifest to revoke a hash without removing its trust-list entry. diff --git a/build/BundledPlugins.props b/build/BundledPlugins.props new file mode 100644 index 00000000..b0c3dc2e --- /dev/null +++ b/build/BundledPlugins.props @@ -0,0 +1,19 @@ + + + + $(MSBuildThisFileDirectory)BundledPlugins.manifest + $(MSBuildThisFileDirectory)BundledPlugins.deny.manifest + + + + + + + + + + + + + + diff --git a/build/build.proj b/build/build.proj new file mode 100644 index 00000000..0643f1ed --- /dev/null +++ b/build/build.proj @@ -0,0 +1,204 @@ + + + + + $([System.IO.Path]::GetFullPath('$(MSBuildThisFileDirectory)..')) + $(RepoRoot)/src/Nemera.slnx + Debug + $(RepoRoot)/bin/api/publish + $(RepoRoot)/bin/web/publish + $(RepoRoot)/bin/api/BundledPlugins.current.manifest + $(MSBuildThisFileDirectory)obj/BundledPlugins.slnx + <_OfficialReleaseBuild Condition="'$(OfficialReleaseBuild)' == ''">false + <_OfficialReleaseBuild Condition="'$(OfficialReleaseBuild)' != ''">$(OfficialReleaseBuild) + <_DockerDependsOn>Build + <_DockerDependsOn Condition="'$(_OfficialReleaseBuild)' == 'true'">ValidateDockerRelease;VerifyPublishedBundledPlugins + + + + + + true + + + + + + + + + + + + + + + + + + <_BundledPluginSolutionLine Include="<Solution>" /> + <_BundledPluginSolutionLine Include="@(BundledPluginProject->' <Project Path="%(FullPath)" />')" /> + <_BundledPluginSolutionLine Include="</Solution>" /> + + + + + + + + + + + + + + + + + + + + + + + + + + + + <_BundledPluginApiTargetDirectory Include="@(_BundledPluginApiTargetPath->'%(RootDir)%(Directory)')" /> + + + <_DeployedBundledPluginsDirectory>@(_BundledPluginApiTargetDirectory)plugins + + + <_DeployedBundledPluginAssembly Include="$(_DeployedBundledPluginsDirectory)/Nemera.Plugins.*.dll" /> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + <_PublishedBundledPluginAssembly Include="$(ApiPublishDirectory)/plugins/Nemera.Plugins.*.dll" /> + + + + + + + + + + <_PublishedBundledPlugins>true + + + + + + + + + + + + <_ImageVersion Condition="'$(Version)' != ''">$(Version) + <_ImageVersion Condition="'$(Version)' == ''">latest + <_DockerApiDockerfile Condition="'$(_OfficialReleaseBuild)' == 'true'">$(RepoRoot)/src/Nemera.Presentation.Api/Dockerfile.release + <_DockerApiDockerfile Condition="'$(_OfficialReleaseBuild)' != 'true'">$(RepoRoot)/src/Nemera.Presentation.Api/Dockerfile + <_DockerApiContext Condition="'$(_OfficialReleaseBuild)' == 'true'">$(ApiPublishDirectory) + <_DockerApiContext Condition="'$(_OfficialReleaseBuild)' != 'true'">$(RepoRoot) + <_DockerWebDockerfile Condition="'$(_OfficialReleaseBuild)' == 'true'">$(RepoRoot)/src/Nemera.Presentation.Web/Dockerfile.release + <_DockerWebDockerfile Condition="'$(_OfficialReleaseBuild)' != 'true'">$(RepoRoot)/src/Nemera.Presentation.Web/Dockerfile + <_DockerWebContext Condition="'$(_OfficialReleaseBuild)' == 'true'">$(WebPublishDirectory) + <_DockerWebContext Condition="'$(_OfficialReleaseBuild)' != 'true'">$(RepoRoot) + + + + + + + + + + + <_ReleaseBranchIsValid>false + <_ReleaseBranchIsValid Condition="'$(ReleaseBranch)' != '' And $(ReleaseBranch.StartsWith('release/'))">true + + + + + + + + + + + + + + + + + + + + + <_BundledPluginPublishedAssembly Include="$(ApiPublishDirectory)/plugins/Nemera.Plugins.*.dll" /> + + + + + + + + + + + <_NewBundledPluginManifestLine Include="@(_RecordedBundledPluginHash->'%(Filename)%(Extension)|%(FileHash)')" /> + <_CombinedBundledPluginManifestLine Include="@(_ExistingBundledPluginManifestLine);@(_NewBundledPluginManifestLine)" /> + + + + + + + + + + + + diff --git a/docs/CONTRIBUTING.md b/docs/CONTRIBUTING.md index a0bb2582..a8ceffe9 100644 --- a/docs/CONTRIBUTING.md +++ b/docs/CONTRIBUTING.md @@ -657,3 +657,6 @@ public void Add_WhenCalledWithVariousInputs_ShouldReturnExpectedSum(int a, int b ### Security Testing - Include tests that verify security measures (e.g., authentication, authorization) + +## Releasing +Releases are cut only by the repository owner. The required GitHub environment, release branch ruleset, secrets, credential rotation and troubleshooting steps are documented in [Releasing](./technical/RELEASING.md). diff --git a/docs/manual/installation/index.md b/docs/manual/installation/index.md index 113e31fc..c56eda0b 100644 --- a/docs/manual/installation/index.md +++ b/docs/manual/installation/index.md @@ -86,6 +86,8 @@ Use a release package or installer when one is available, or, with the .NET 10 S dotnet build Nemera.slnx ``` +The official release artifacts include the PDF plugin's native libraries for Linux x64 and ARM64 (including Alpine x64), macOS Intel and Apple Silicon, and Windows x64 and ARM64. The single release download works on those platforms; the plugin loads the native libraries that match the host at runtime. + Run the API and the web client from the installed release package or from the published build. In development, their addresses come from each project's `launchSettings.json` (`http://localhost:5214` and `http://localhost:5012`). When you run a published build directly on a host, set the addresses yourself, either with `ASPNETCORE_URLS` or with `ASPNETCORE_HTTP_PORTS`: ```bash diff --git a/docs/manual/plugins/index.md b/docs/manual/plugins/index.md index 66ad2929..1fd1a673 100644 --- a/docs/manual/plugins/index.md +++ b/docs/manual/plugins/index.md @@ -44,9 +44,9 @@ The `Needs web` column is worth pausing on: the providers marked `yes` reach out ## Installing a plugin -Plugins are managed from the administration area, on the Plugins page, which only administrators can open. To install one, upload either a single `.dll` assembly or a `.zip` archive that holds the assembly together with any dependencies it needs. +Plugins are managed from the administration area, on the Plugins page, which only administrators can open. To install one, upload either a single `.dll` assembly or a `.zip` archive that holds the assembly together with any managed dependency assemblies it needs. Only `.dll` entries are installed from the archive; dependency manifests, native `.so` and `.dylib` libraries, and the original directory structure are not. -The uploaded files are placed in the plugin storage directory, `plugins` by default, and are picked up at the **next startup of the API**. In other words, after installing a plugin, restart the API server for it to take effect. Installing is a supervised operation: the archive is unpacked into a flat set of assemblies inside the plugin directory, and any directory component in the upload is stripped, so a crafted archive cannot write outside that directory. +The uploaded files are placed in the plugin storage directory, `plugins` by default, and are picked up at the **next startup of the API**. In other words, after installing a plugin, restart the API server for it to take effect. Installing is a supervised operation: the archive is unpacked into a flat set of `.dll` files inside the plugin directory, and any directory component in the upload is stripped, so a crafted archive cannot write outside that directory. Once installed and restarted, the plugin appears on the Plugins page with its name, author, version and description. @@ -59,6 +59,12 @@ Each plugin is listed with one of two states: Nemera reconciles the list at every startup. A plugin that is no longer present in the storage directory is forgotten, together with the per library settings that referenced it. +Every official release of Nemera embeds the SHA-256 checksum of each bundled plugin's main assembly, plus an append-only list of checksums from earlier official releases. A plugin whose main assembly matches an entry is marked **Official**. The checksum covers only that main assembly; the libraries and native files shipped next to it are not checksummed. The list keeps older bundled versions recognized, so shipping a new version does not make an older one unofficial. A checksum can be revoked through the project's deny list; a revoked binary is no longer marked Official, but it still loads. + +The **Official** mark is meaningful only when Nemera itself came from an official release published by the project. If you built Nemera yourself or are running a modified build, that build does not generate the current release's trust entries, so a plugin you rebuild locally is not marked Official unless it matches a binary from an earlier official release. Nemera does not call home to check plugin checksums against a server-side list, because that would conflict with the project's no outbound calls policy. The release channel is the trust anchor instead. + +The **Official** mark is informational. It never prevents a plugin from loading, and plugins always work whether they are marked or not. + ## Uninstalling a plugin There is no uninstall button. To remove a plugin, delete its assembly (and any files that came with it) from the plugin storage directory and restart the API. The plugin then disappears from the list, and the settings that enabled it for your libraries are cleaned up. @@ -81,7 +87,7 @@ The shipped plugins use these settings for practical things, such as the base ad ## Writing your own plugin -Anyone can write a plugin, and it is the intended way to teach Nemera about a new source or a new format. A plugin is a .NET assembly targeting the same framework as the server, referencing the `Nemera.Plugins.Contracts` project. To be a plugin it implements `IPlugin`, which describes it and lists its settings, and `IPluginServiceRegistrator`, which wires its services up. To contribute a capability it also implements one or more of `IMetadataProvider`, `IArtworkProvider` and `IBookReader`. Package the built assembly, and any dependencies, into a ZIP and install it like any other plugin. +Anyone can write a plugin, and it is the intended way to teach Nemera about a new source or a new format. A plugin is a .NET assembly targeting the same framework as the server, referencing the `Nemera.Plugins.Contracts` project. To be a plugin it implements `IPlugin`, which describes it and lists its settings, and `IPluginServiceRegistrator`, which wires its services up. To contribute a capability it also implements one or more of `IMetadataProvider`, `IArtworkProvider` and `IBookReader`. Package the built assembly, and any managed dependency assemblies, into a ZIP and install it like any other plugin. Only `.dll` files are installed from an archive, so the upload flow does not support plugins that need native `.so` or `.dylib` libraries. ## Security diff --git a/docs/technical/RELEASING.md b/docs/technical/RELEASING.md new file mode 100644 index 00000000..1b069105 --- /dev/null +++ b/docs/technical/RELEASING.md @@ -0,0 +1,188 @@ +# Releasing + +## Contents + +- [Overview](#overview) +- [Required GitHub settings](#required-github-settings) + - [Release branch ruleset](#release-branch-ruleset) + - [Release environment](#release-environment) + - [Secrets](#secrets) +- [Workflows](#workflows) +- [Cutting a release](#cutting-a-release) +- [Revoking a bundled plugin hash](#revoking-a-bundled-plugin-hash) +- [Rotating credentials](#rotating-credentials) +- [Troubleshooting](#troubleshooting) + +## Overview + +Releases are cut only by the repository owner. There is one official build, and it runs on the release branch. + +1. The owner creates a `release/x.y.z` branch from `master`. +2. The `Publish Release` workflow builds and publishes the official artifacts with `OfficialReleaseBuild=true`. +3. The same workflow verifies the published API assembly against the published plugin binaries, records the release's plugin hashes in the append-only trust list, builds the release images from the verified publish output, and opens a pull request to `master`. +4. The owner downloads the official artifacts and creates the GitHub release and tag. +5. The owner merges the trust-list pull request. The current release already embeds its own official plugin manifest, so this pull request keeps the release's plugin binaries Official in future releases. + +The full test suite runs on normal pull requests to `master`. The release build does not rerun the full suite. It runs the manifest verification tests for the official build, publishes, verifies the published API assembly against the published plugin binaries, records the hashes and builds the release images from the verified publish output. + +The repository pins the .NET SDK in `global.json`. The workflows install that exact SDK, and the Docker build stage uses the matching `10.0.100` SDK image, so root-level and container builds use the same toolchain. + +The `release-api` artifact is a single framework-dependent publish built on `ubuntu-latest`. The bundled plugin deployment keeps the PDF plugin's native libraries for the supported runtime identifiers: `win-x64`, `win-arm64`, `linux-x64`, `linux-arm64`, `linux-musl-x64`, `osx-x64` and `osx-arm64`. The macOS packages also keep their shared SkiaSharp library in the `osx` fallback folder, which the build retains automatically even though no device reports that identifier. The list is defined by `BundledPluginRuntimeIdentifiers` in `plugins/Directory.Build.props`, and the PDF plugin validates its required native libraries for every identifier in it, accepting a library from either the identifier's own folder or its OS family fallback. The plugin resolves the matching native library at runtime from its dependency manifest. The release Docker images copy that same publish output. + +The presentation host does not compile against the concrete plugin projects, and it does not own the bundled plugin catalog. The plugin projects are part of the solution and copy their outputs to the API plugin folder. `build.proj` owns the release catalog: it builds and hashes the plugin binaries, writes the current manifest, passes that manifest to the API publish, and copies the binaries into the published plugin folder. Adding or removing a bundled plugin changes the release catalog and the solution, not the host project. + +## Required GitHub settings + +### Release branch ruleset + +Create a repository ruleset under **Settings > Rules > Rulesets > New branch ruleset**: + +- Target branches: `refs/heads/release/*`. +- Enable **Restrict creations**, **Restrict updates**, **Restrict deletions**, and **Block force pushes**. +- Bypass list: add only the owner's user account. Do not add the repository admin role if more than one administrator exists. + +This prevents write collaborators from creating or pushing release branches. The ruleset enforces who can create the branch. The owner can create it from the GitHub Branches page or by pushing it. + +The `Publish Release` workflow runs only when a branch matching `release/x.y.z` is created, and only when the actor is the repository owner. + +### Release environment + +Create an environment under **Settings > Environments > New environment** named `release`: + +- Required reviewers: the owner. +- Deployment branches: allow `master` and `release/*`. A `create` event runs on the branch that was created, so the `publish` job runs on the release branch; the `record-manifest` job checks out `master` in that same release-branch run. +- Environment secrets: + - `SIXLABORS_LICENSE_KEY` + - `RELEASE_PR_TOKEN` + +The `publish` job uses the license secret and has a read-only token. The `record-manifest` job uses the pull request token and does not have the license secret. The environment approval is the gate for both jobs. + +### Secrets + +#### SIXLABORS_LICENSE_KEY + +This is the Six Labors license key content. + +- The value to be put in the secret is the content of the license file, or the value already stored in the existing repository secret used by `Run All Tests`. +- `Run All Tests` uses the repository secret `SIXLABORS_LICENSE_KEY`. +- `Publish Release` uses the environment secret `SIXLABORS_LICENSE_KEY` in the `release` environment. +- `Publish Release` also exposes the secret as the `SixLaborsLicenseKey` MSBuild environment property, so every project that references ImageSharp validates the license, not only `Nemera.Domain`. + +If the key is missing or expired, the build fails with a message such as `No Six Labors license found` or an expired license error. + +#### RELEASE_PR_TOKEN + +This is a fine-grained GitHub personal access token owned by the repository owner. + +Create it under **Settings > Developer settings > Personal access tokens > Fine-grained tokens > Generate new token**: + +- Resource owner: the owner's account. +- Repository access: only `BinaryAlley/Nemera`. +- Permissions: + - `Contents: Read and write` + - `Pull requests: Read and write` + - `Metadata: Read-only` is added automatically. +- Expiration: set an explicit date, for example 90 days, and add a calendar reminder. + +Copy the generated `github_pat_...` value immediately. GitHub shows it only once. Store it as the `RELEASE_PR_TOKEN` environment secret in the `release` environment. + +Why a personal access token is needed: pull requests created with the workflow `GITHUB_TOKEN` do not trigger `pull_request` workflows. The trust-list pull request must run `Run All Tests` and the branch validators, so the `record-manifest` job pushes and creates the pull request with this token. + +The token is used only by the `record-manifest` job. It is not available to the build job, and the build job's token is read-only. The `record-manifest` checkout uses the token as its git token, so the persisted git credential is the PAT and both `git push` and `gh pr create` authenticate with it. + +## Workflows + +- `Publish Release` runs when the owner creates a `release/x.y.z` branch. It has two jobs: + - `publish`: builds and publishes the official artifacts with `OfficialReleaseBuild=true`, runs the manifest verification tests, verifies the published API assembly against the published plugin binaries, records the released plugin hashes, builds the release images from the verified publish output, and uploads the `release-api`, `release-web` and `bundled-plugins-manifest` artifacts. It has the license secret and a read-only token. + - `record-manifest`: downloads the manifest artifact, appends only the release entries that are missing from master's current trust list, and opens the `other/record-release-x.y.z` pull request to `master` with the `RELEASE_PR_TOKEN`. It does not have the license secret. +- `Run All Tests` runs on pull requests to `master` and uses the repository `SIXLABORS_LICENSE_KEY` secret. +- `Branch Push Naming Convention Check` and `Pull Request Source Branch Validation Check` allow `feature/`, `bugfix/`, `hotfix/`, `documentation/`, `refactor/`, `other/`, and `release/x.y.z`. + +The release branch is built from `master` after the normal pull request checks have passed. The release build does not rerun the full test suite. It runs the manifest verification tests, because that is the only part of the build that changes when the official plugin manifest and the official release marker are embedded. It then verifies the published API assembly against the published plugin binaries before recording hashes or building images. The trust-list pull request runs the full suite before it can be merged. + +Recording is CI-only. The publish job checks that the worktree is clean and that `HEAD` matches `origin/master` before it appends to the trust list. A local `RecordBundledPlugins` run is rejected by the guard. + +The trust list `build/BundledPlugins.manifest` is append-only. Never remove existing entries. The record job uses master's current file as the base and appends only the entries that are missing from it, skipping duplicates, so the record pull request diff contains additions only. Use the release workflow, which calls `RecordBundledPlugins`, instead of editing the file by hand. The deny list `build/BundledPlugins.deny.manifest` is the revocation path: add an entry to stop trusting a hash, and remove the entry to restore trust. + +## Cutting a release + +1. Ensure that everything you want in the release is on `master`, that the previous release's trust-list pull request is merged, and that the normal pull request checks have passed. +2. Verify that `SIXLABORS_LICENSE_KEY` and `RELEASE_PR_TOKEN` are present and current in the `release` environment, and that the repository `SIXLABORS_LICENSE_KEY` secret is current. +3. Create the `release/x.y.z` branch from the current `master` as the owner. The publish job requires the branch to point at the current `origin/master`. The check is exact: if anything merges to `master` before the job runs, the job fails and the branch must be recreated from the new `master`. +4. Approve the `release` environment for the `publish` and `record-manifest` jobs. +5. Wait for `Publish Release` to publish and verify the official artifacts, record the trust list and build the release images. +6. Download the `release-api` and `release-web` artifacts. +7. Create the GitHub release and tag manually from those artifacts. The workflow does not create the release. +8. Wait for `Run All Tests` and both branch validators on the `other/record-release-1.2.3` pull request. Review the trust-list diff and merge it. +9. The workflow builds the release images from the verified publish output to validate the image definitions, but it does not upload them. Build the images you ship from the downloaded artifacts, so they contain exactly the plugin binaries whose hashes were recorded: + ```bash + docker build -t nemera-api:1.2.3 -f src/Nemera.Presentation.Api/Dockerfile.release + docker build -t nemera-web:1.2.3 -f src/Nemera.Presentation.Web/Dockerfile.release + ``` + To publish, verify and build in one local step instead, run: + ```bash + dotnet msbuild build/build.proj -t:Docker -p:Configuration=Release -p:OfficialReleaseBuild=true -p:Version=1.2.3 + ``` + That target publishes from source, verifies the publish output and builds the images from it. Those images are not the exact released artifacts unless the build is byte-identical, so prefer the downloaded artifacts for the images you ship. + +The local equivalent of the official build is verification only. Recording is CI-only. The release workflow checks that the checkout is clean and that `HEAD` matches `origin/master` exactly before it appends to the trust list. + +```bash +dotnet msbuild build/build.proj -t:VerifyPublishedBundledPlugins -p:Configuration=Release -p:OfficialReleaseBuild=true +``` + +For a local Release build, set `SixLaborsLicenseKey` to the content of `src/Nemera.Domain/sixlabors.lic` first. The file alone is only discovered by `Nemera.Domain`, and projects that reference ImageSharp through it fail license validation otherwise. + +## Revoking a bundled plugin hash + +The main trust list is append-only, so revoke a bad hash instead of removing it: + +1. Add a `|` line to `build/BundledPlugins.deny.manifest`. +2. Merge the change to `master`. +3. The next build embeds the deny list. The reader removes the hash from both the historical and the current trust lists, so a plugin with that hash is no longer marked Official. It still loads. + +The deny list is intentionally not append-only. Remove the line to restore trust if the revocation was a mistake. + +## Rotating credentials + +### Six Labors license + +When the license is renewed or replaced: + +1. Put the new value in the repository secret `SIXLABORS_LICENSE_KEY` used by `Run All Tests`. +2. Put the same value in the environment secret `SIXLABORS_LICENSE_KEY` in the `release` environment. +3. Re-run the failed workflow. + +The local `src/Nemera.Domain/sixlabors.lic` file is only a local copy. Update it for local Release builds, but never commit it. + +### RELEASE_PR_TOKEN + +When the token expires, is revoked or is compromised: + +1. Generate a new fine-grained token with the same repository access and permissions. +2. Replace the `RELEASE_PR_TOKEN` environment secret in the `release` environment. +3. Re-create the release branch or re-run the failed `Publish Release` workflow, depending on where it failed. +4. Revoke the old token. + +If the token is compromised, also review recent branches, pull requests and workflow runs. The token has only `Contents` and `Pull requests` write access to this repository. + +## Troubleshooting + +| Symptom | Cause | Fix | +| --- | --- | --- | +| `Publish Release` does not run | The created ref is not a `release/x.y.z` branch, or the actor is not the repository owner. | Create the branch as the owner using the three-part version. | +| The workflow waits for approval | The `release` environment has required reviewers. | Approve the `publish` and `record-manifest` jobs as the owner. | +| `No Six Labors license found` | The secret is missing or empty. | Check the repository secret and the `release` environment secret. | +| Six Labors license expired | The license key is no longer valid. | Renew it, update both secrets and re-run. | +| `git push` or `gh pr create` fails with 401 or 403 | `RELEASE_PR_TOKEN` is missing, expired or lacks `Contents` or `Pull requests` write, or the `record-manifest` checkout does not use it as the git token. | Generate a new token if needed, update the environment secret, and ensure the `record-manifest` checkout passes it as `token`. | +| The trust-list pull request has no CI | It was created with `GITHUB_TOKEN` instead of the PAT. | Verify that the `record-manifest` job uses `RELEASE_PR_TOKEN` and that the secret is current. | +| A release branch is rejected by the ruleset | The branch was not created by the owner. | Create it as the owner. The bypass list must contain only the owner's account. | +| The branch validator rejects a release branch | The branch is not `release/x.y.z`. | Use three numeric parts, for example `release/1.2.3`. | +| The branch validator rejects the trust-list pull request | The branch prefix is not allowed. | The workflow uses `other/record-release-x.y.z`, which is allowed. | +| `Official` is false in a release | The build did not use `OfficialReleaseBuild=true`, or the plugin binary does not match the trust manifest. | Use the `Publish Release` workflow, or pass `-p:OfficialReleaseBuild=true` with `Configuration=Release`. | +| `RecordBundledPlugins` fails | Recording is attempted outside GitHub Actions, from a dirty worktree, from a commit that is not the current `origin/master`, or without `Configuration=Release` and `OfficialReleaseBuild=true`. | Use the `Publish Release` workflow. Commit or stash changes, merge the previous trust-list pull request, and recreate the release branch from `master`, if the guard reports a tree or history problem. | +| `RecordBundledPlugins` fails because `master` moved | The release branch no longer matches the current `origin/master`. | Recreate the `release/x.y.z` branch from the new `master` and approve the new run. | +| The record-list pull request removes trust-list lines | The merge step was skipped, or master's current manifest was replaced with an older artifact. | The record job only appends missing entries and fails if the staged diff removes a line. Rerun the workflow. | +| A known good plugin is not Official | A deny-list entry matches its hash. | Remove the matching line from `build/BundledPlugins.deny.manifest`. | +| `VerifyPublishedBundledPlugins` fails | The manifest embedded in the published API assembly does not match the published plugin binaries. | Re-run the release build from the same commit. Do not mix artifacts from different builds. | +| The release image build fails with an official configuration error | `Docker` was called with `OfficialReleaseBuild=true` and a configuration other than `Release`. | Pass `-p:Configuration=Release`. | diff --git a/docs/technical/api/plugins/Api.Plugins.md b/docs/technical/api/plugins/Api.Plugins.md index ae186cac..122861c2 100644 --- a/docs/technical/api/plugins/Api.Plugins.md +++ b/docs/technical/api/plugins/Api.Plugins.md @@ -66,6 +66,8 @@ GET api/v1/plugins 200 Ok ``` +`isOfficial` is true when the plugin's main assembly matches a checksum from the append-only list of previous official releases, after the checksums in the deny list are removed. The checksum covers only the plugin's main assembly; the libraries and native files shipped next to it are not checksummed. An official release build also embeds and trusts the checksums of its own bundled plugins; a non-official build does not trust its own plugin binaries. A plugin that does not match, or whose checksum is denied, still loads and runs. The flag is informational only and never affects loading. + ```json [ { @@ -76,6 +78,7 @@ GET api/v1/plugins "description": "Retrieves artist, album and track metadata from MusicBrainz.", "loadStatus": "Loaded", "loadError": null, + "isOfficial": true, "settings": { "BaseUrl": "https://musicbrainz.org/ws/2/", "DoesAllowPrivateBaseUrl": "false", diff --git a/src/global.json b/global.json similarity index 97% rename from src/global.json rename to global.json index f5215a6e..59ce830c 100644 --- a/src/global.json +++ b/global.json @@ -3,4 +3,4 @@ "version": "10.0.100", "rollForward": "disable" } -} \ No newline at end of file +} diff --git a/plugins/Directory.Build.props b/plugins/Directory.Build.props index ff7ed375..ea80d1ac 100644 --- a/plugins/Directory.Build.props +++ b/plugins/Directory.Build.props @@ -1,6 +1,11 @@ + + + $(RepoRoot)bin/plugins/ + + win-x64;win-arm64;linux-x64;linux-arm64;linux-musl-x64;osx-x64;osx-arm64 true true $(WarningsAsErrors);CS1591 diff --git a/plugins/Directory.Build.targets b/plugins/Directory.Build.targets new file mode 100644 index 00000000..084e02e8 --- /dev/null +++ b/plugins/Directory.Build.targets @@ -0,0 +1,18 @@ + + + + + <_PluginsDestination Condition="'$(NemeraPluginsOutputDirectory)' != ''">$(NemeraPluginsOutputDirectory) + <_PluginsDestination Condition="'$(NemeraPluginsOutputDirectory)' == ''">$(RepoRoot)bin/api/$(Configuration)/$(TargetFramework)/plugins/ + + + + + + + <_PluginsReferenceCopyLocalPath Include="@(ReferenceCopyLocalPaths)" /> + + + + + diff --git a/plugins/Nemera.Plugins.Calibre/Nemera.Plugins.Calibre.csproj b/plugins/Nemera.Plugins.Calibre/Nemera.Plugins.Calibre.csproj index 319b8c36..40781974 100644 --- a/plugins/Nemera.Plugins.Calibre/Nemera.Plugins.Calibre.csproj +++ b/plugins/Nemera.Plugins.Calibre/Nemera.Plugins.Calibre.csproj @@ -3,7 +3,6 @@ net10.0 disable enable - $(SolutionDir)..\bin\plugins\ false @@ -12,8 +11,8 @@ - - + + diff --git a/plugins/Nemera.Plugins.CoverArtArchive/Nemera.Plugins.CoverArtArchive.csproj b/plugins/Nemera.Plugins.CoverArtArchive/Nemera.Plugins.CoverArtArchive.csproj index 7eda6857..6709ec4f 100644 --- a/plugins/Nemera.Plugins.CoverArtArchive/Nemera.Plugins.CoverArtArchive.csproj +++ b/plugins/Nemera.Plugins.CoverArtArchive/Nemera.Plugins.CoverArtArchive.csproj @@ -3,7 +3,6 @@ net10.0 disable enable - $(SolutionDir)..\bin\plugins\ false true @@ -13,9 +12,9 @@ - - - + + + diff --git a/plugins/Nemera.Plugins.Epub/Nemera.Plugins.Epub.csproj b/plugins/Nemera.Plugins.Epub/Nemera.Plugins.Epub.csproj index 319b8c36..40781974 100644 --- a/plugins/Nemera.Plugins.Epub/Nemera.Plugins.Epub.csproj +++ b/plugins/Nemera.Plugins.Epub/Nemera.Plugins.Epub.csproj @@ -3,7 +3,6 @@ net10.0 disable enable - $(SolutionDir)..\bin\plugins\ false @@ -12,8 +11,8 @@ - - + + diff --git a/plugins/Nemera.Plugins.ID3/Nemera.Plugins.ID3.csproj b/plugins/Nemera.Plugins.ID3/Nemera.Plugins.ID3.csproj index 9a902cdb..1368a2cc 100644 --- a/plugins/Nemera.Plugins.ID3/Nemera.Plugins.ID3.csproj +++ b/plugins/Nemera.Plugins.ID3/Nemera.Plugins.ID3.csproj @@ -3,7 +3,6 @@ net10.0 disable enable - $(SolutionDir)..\bin\plugins\ false true @@ -13,9 +12,9 @@ - - - + + + diff --git a/plugins/Nemera.Plugins.LocalMusicArtwork/Nemera.Plugins.LocalMusicArtwork.csproj b/plugins/Nemera.Plugins.LocalMusicArtwork/Nemera.Plugins.LocalMusicArtwork.csproj index c07342fe..0a6d2fb9 100644 --- a/plugins/Nemera.Plugins.LocalMusicArtwork/Nemera.Plugins.LocalMusicArtwork.csproj +++ b/plugins/Nemera.Plugins.LocalMusicArtwork/Nemera.Plugins.LocalMusicArtwork.csproj @@ -3,7 +3,6 @@ net10.0 disable enable - $(SolutionDir)..\bin\plugins\ false true @@ -13,9 +12,9 @@ - - - + + + diff --git a/plugins/Nemera.Plugins.MusicBrainz/Nemera.Plugins.MusicBrainz.csproj b/plugins/Nemera.Plugins.MusicBrainz/Nemera.Plugins.MusicBrainz.csproj index 7eda6857..6709ec4f 100644 --- a/plugins/Nemera.Plugins.MusicBrainz/Nemera.Plugins.MusicBrainz.csproj +++ b/plugins/Nemera.Plugins.MusicBrainz/Nemera.Plugins.MusicBrainz.csproj @@ -3,7 +3,6 @@ net10.0 disable enable - $(SolutionDir)..\bin\plugins\ false true @@ -13,9 +12,9 @@ - - - + + + diff --git a/plugins/Nemera.Plugins.OpenLibrary/Nemera.Plugins.OpenLibrary.csproj b/plugins/Nemera.Plugins.OpenLibrary/Nemera.Plugins.OpenLibrary.csproj index 9f9896f3..af2e28e3 100644 --- a/plugins/Nemera.Plugins.OpenLibrary/Nemera.Plugins.OpenLibrary.csproj +++ b/plugins/Nemera.Plugins.OpenLibrary/Nemera.Plugins.OpenLibrary.csproj @@ -3,7 +3,6 @@ net10.0 disable enable - $(SolutionDir)..\bin\plugins\ false @@ -12,8 +11,8 @@ - - + + diff --git a/plugins/Nemera.Plugins.Pdf/Nemera.Plugins.Pdf.csproj b/plugins/Nemera.Plugins.Pdf/Nemera.Plugins.Pdf.csproj index 6d1b55ba..de5827da 100644 --- a/plugins/Nemera.Plugins.Pdf/Nemera.Plugins.Pdf.csproj +++ b/plugins/Nemera.Plugins.Pdf/Nemera.Plugins.Pdf.csproj @@ -3,7 +3,6 @@ net10.0 disable enable - $(SolutionDir)..\bin\plugins\ false true @@ -12,21 +11,71 @@ - - - - - + + - <_CurrentRidNatives Include="$(OutDir)runtimes\$(NETCoreSdkRuntimeIdentifier)\native\*" /> + <_SupportedPdfRuntime Include="$(BundledPluginRuntimeIdentifiers)" /> + <_WindowsPdfRuntime Include="@(_SupportedPdfRuntime)" Condition="$([System.String]::Copy('%(Identity)').StartsWith('win-'))"> + win + + <_LinuxPdfRuntime Include="@(_SupportedPdfRuntime)" Condition="$([System.String]::Copy('%(Identity)').StartsWith('linux-'))"> + linux + + <_MacOsPdfRuntime Include="@(_SupportedPdfRuntime)" Condition="$([System.String]::Copy('%(Identity)').StartsWith('osx-'))"> + osx + + <_UnknownPdfRuntime Include="@(_SupportedPdfRuntime)" /> + <_UnknownPdfRuntime Remove="@(_WindowsPdfRuntime);@(_LinuxPdfRuntime);@(_MacOsPdfRuntime)" /> + <_PdfFamilyRuntime Include="win" Condition="'@(_WindowsPdfRuntime)' != ''" /> + <_PdfFamilyRuntime Include="linux" Condition="'@(_LinuxPdfRuntime)' != ''" /> + <_PdfFamilyRuntime Include="linux-musl" Condition="'@(_LinuxPdfRuntime)' != ''" /> + <_PdfFamilyRuntime Include="osx" Condition="'@(_MacOsPdfRuntime)' != ''" /> - - - + + + + + + + + + + + + <_CopiedRuntimeDirectory Include="$([System.IO.Directory]::GetDirectories('$(_PluginsDestination)runtimes'))" /> + <_CopiedPdfRuntimeDirectory Include="@(_CopiedRuntimeDirectory)" Condition="Exists('%(Identity)/native/pdfium.dll') Or Exists('%(Identity)/native/libpdfium.so') Or Exists('%(Identity)/native/libpdfium.dylib') Or Exists('%(Identity)/native/libSkiaSharp.dll') Or Exists('%(Identity)/native/libSkiaSharp.so') Or Exists('%(Identity)/native/libSkiaSharp.dylib')" /> + <_CopiedPdfRuntimeDirectory Remove="@(_SupportedPdfRuntime)" MatchOnMetadata="Filename" /> + <_CopiedPdfRuntimeDirectory Remove="@(_PdfFamilyRuntime)" MatchOnMetadata="Filename" /> + <_RootPdfNativeFile Include="$(_PluginsDestination)pdfium.dll;$(_PluginsDestination)libpdfium.so;$(_PluginsDestination)libpdfium.dylib;$(_PluginsDestination)libSkiaSharp.dll;$(_PluginsDestination)libSkiaSharp.so;$(_PluginsDestination)libSkiaSharp.dylib" /> + + + + + + + + + + <_MissingPdfNativeLibrary Include="@(_WindowsPdfRuntime)" Condition="!Exists('$(_PluginsDestination)runtimes/%(Identity)/native/pdfium.dll') And !Exists('$(_PluginsDestination)runtimes/%(PdfFamily)/native/pdfium.dll')"> + pdfium.dll + + <_MissingPdfNativeLibrary Include="@(_WindowsPdfRuntime)" Condition="!Exists('$(_PluginsDestination)runtimes/%(Identity)/native/libSkiaSharp.dll') And !Exists('$(_PluginsDestination)runtimes/%(PdfFamily)/native/libSkiaSharp.dll')"> + libSkiaSharp.dll + + <_MissingPdfNativeLibrary Include="@(_LinuxPdfRuntime)" Condition="!Exists('$(_PluginsDestination)runtimes/%(Identity)/native/libpdfium.so') And !Exists('$(_PluginsDestination)runtimes/%(PdfFamily)/native/libpdfium.so')"> + libpdfium.so + + <_MissingPdfNativeLibrary Include="@(_LinuxPdfRuntime)" Condition="!Exists('$(_PluginsDestination)runtimes/%(Identity)/native/libSkiaSharp.so') And !Exists('$(_PluginsDestination)runtimes/%(PdfFamily)/native/libSkiaSharp.so')"> + libSkiaSharp.so + + <_MissingPdfNativeLibrary Include="@(_MacOsPdfRuntime)" Condition="!Exists('$(_PluginsDestination)runtimes/%(Identity)/native/libpdfium.dylib') And !Exists('$(_PluginsDestination)runtimes/%(PdfFamily)/native/libpdfium.dylib')"> + libpdfium.dylib + + <_MissingPdfNativeLibrary Include="@(_MacOsPdfRuntime)" Condition="!Exists('$(_PluginsDestination)runtimes/%(Identity)/native/libSkiaSharp.dylib') And !Exists('$(_PluginsDestination)runtimes/%(PdfFamily)/native/libSkiaSharp.dylib')"> + libSkiaSharp.dylib + + + diff --git a/src/Directory.Build.props b/src/Directory.Build.props index bf383816..0f7e2492 100644 --- a/src/Directory.Build.props +++ b/src/Directory.Build.props @@ -1,6 +1,9 @@ + + + $(RepoRoot)bin/api/ true true $(WarningsAsErrors);CS1591 diff --git a/src/Nemera.Application/Common/Infrastructure/Plugins/IPluginManager.cs b/src/Nemera.Application/Common/Infrastructure/Plugins/IPluginManager.cs index 16a3db00..601613f8 100644 --- a/src/Nemera.Application/Common/Infrastructure/Plugins/IPluginManager.cs +++ b/src/Nemera.Application/Common/Infrastructure/Plugins/IPluginManager.cs @@ -23,4 +23,11 @@ public interface IPluginManager /// The unique identifier of the plugin. /// The plugin, or when no plugin with the provided Id was loaded. IPlugin? GetPlugin(Guid pluginId); + + /// + /// Determines whether the loaded plugin identified by matches a trusted bundled plugin binary. + /// + /// The unique identifier of the plugin. + /// when the plugin is official, otherwise. + bool IsOfficial(Guid pluginId); } diff --git a/src/Nemera.Application/Common/Mapping/Plugins/PluginEntityMapping.cs b/src/Nemera.Application/Common/Mapping/Plugins/PluginEntityMapping.cs index b313544b..46f6a2c6 100644 --- a/src/Nemera.Application/Common/Mapping/Plugins/PluginEntityMapping.cs +++ b/src/Nemera.Application/Common/Mapping/Plugins/PluginEntityMapping.cs @@ -16,9 +16,11 @@ public static class PluginEntityMapping /// Converts to . /// /// The repository entity to be converted. + /// Whether the plugin matches a trusted bundled plugin binary. /// The converted response. - public static PluginResponse ToResponse(this PluginEntity pluginEntity) + public static PluginResponse ToResponse(this PluginEntity pluginEntity, bool isOfficial) { + // Official status is supplied by the caller because it is derived from the running plugin manager, not from the persisted entity. return new PluginResponse( pluginEntity.Id, pluginEntity.Name, @@ -27,7 +29,8 @@ public static class PluginEntityMapping pluginEntity.Description, pluginEntity.LoadStatus, pluginEntity.LoadError, - pluginEntity.ToSettings() + pluginEntity.ToSettings(), + isOfficial ); } diff --git a/src/Nemera.Application/Core/Plugins/Queries/GetPlugins/GetPluginsQueryHandler.cs b/src/Nemera.Application/Core/Plugins/Queries/GetPlugins/GetPluginsQueryHandler.cs index 61342bbf..ea0e3fca 100644 --- a/src/Nemera.Application/Core/Plugins/Queries/GetPlugins/GetPluginsQueryHandler.cs +++ b/src/Nemera.Application/Core/Plugins/Queries/GetPlugins/GetPluginsQueryHandler.cs @@ -1,13 +1,14 @@ #region ========================================================================= USING ===================================================================================== -using Nemera.Domain.Common.Primitives; using Nemera.Application.Common.CQRS; using Nemera.Application.Common.DataAccess.Entities.Plugins; using Nemera.Application.Common.DataAccess.Repositories.Plugins; using Nemera.Application.Common.DataAccess.UoW; using Nemera.Application.Common.DTO.Filtering; using Nemera.Application.Common.DTO.Pagination; +using Nemera.Application.Common.Infrastructure.Plugins; using Nemera.Application.Common.Mapping.Plugins; using Nemera.Contracts.Responses.Plugins; +using Nemera.Domain.Common.Primitives; using System.Collections.Generic; using System.Linq; using System.Threading; @@ -22,14 +23,17 @@ namespace Nemera.Application.Core.Plugins.Queries.GetPlugins; public class GetPluginsQueryHandler : IQueryHandler>> { private readonly IUnitOfWork _unitOfWork; + private readonly IPluginManager _pluginManager; /// /// Initializes a new instance of the class. /// /// Injected unit of work for interacting with the data access layer repositories. - public GetPluginsQueryHandler(IUnitOfWork unitOfWork) + /// Injected manager of the plugins loaded by the host application. + public GetPluginsQueryHandler(IUnitOfWork unitOfWork, IPluginManager pluginManager) { _unitOfWork = unitOfWork; + _pluginManager = pluginManager; } /// @@ -43,6 +47,7 @@ public class GetPluginsQueryHandler : IQueryHandler>> HandleAsync(GetPluginsQuery query, CancellationToken cancellationToken) { Result> getPluginsResult = await _unitOfWork.PluginRepository.GetAllAsync(cancellationToken: cancellationToken).ConfigureAwait(false); - return getPluginsResult.Match(plugins => Result.From>([.. plugins.Data.Select(plugin => plugin.ToResponse())]), errors => errors); + // Official status comes from the loaded plugin binaries, not from the persisted entity, so it is resolved for each response. + return getPluginsResult.Match(plugins => Result.From>([.. plugins.Data.Select(plugin => plugin.ToResponse(_pluginManager.IsOfficial(plugin.Id)))]), errors => errors); } } diff --git a/src/Nemera.Application/Nemera.Application.csproj b/src/Nemera.Application/Nemera.Application.csproj index fe71a3c5..190ec2ca 100644 --- a/src/Nemera.Application/Nemera.Application.csproj +++ b/src/Nemera.Application/Nemera.Application.csproj @@ -3,7 +3,6 @@ net10.0 disable enable - $(SolutionDir)..\bin\api\ false diff --git a/src/Nemera.Contracts/Nemera.Contracts.csproj b/src/Nemera.Contracts/Nemera.Contracts.csproj index b9bf0b4d..4e12dff8 100644 --- a/src/Nemera.Contracts/Nemera.Contracts.csproj +++ b/src/Nemera.Contracts/Nemera.Contracts.csproj @@ -3,7 +3,6 @@ net10.0 disable enable - $(SolutionDir)..\bin\api\ false diff --git a/src/Nemera.Contracts/Responses/Plugins/PluginResponse.cs b/src/Nemera.Contracts/Responses/Plugins/PluginResponse.cs index 795e2350..5cdc89e0 100644 --- a/src/Nemera.Contracts/Responses/Plugins/PluginResponse.cs +++ b/src/Nemera.Contracts/Responses/Plugins/PluginResponse.cs @@ -10,6 +10,9 @@ namespace Nemera.Contracts.Responses.Plugins; /// /// Represents a detected plugin. /// +/// +/// IsOfficial is computed from the loaded plugin binaries when the response is built. It is not stored with the plugin entity, because replacing a plugin binary must change the badge without a database migration. +/// /// The unique identifier of the plugin. /// The display name of the plugin. /// The author of the plugin. @@ -18,6 +21,7 @@ namespace Nemera.Contracts.Responses.Plugins; /// The load status of the plugin. /// The error message when the plugin failed to load, if applicable. /// The settings of the plugin. +/// Whether the plugin matches a trusted bundled plugin binary. [DebuggerDisplay("Name: {Name}")] public sealed record PluginResponse( Guid Id, @@ -27,5 +31,6 @@ public sealed record PluginResponse( string Description, PluginLoadStatus LoadStatus, string? LoadError, - IReadOnlyDictionary? Settings + IReadOnlyDictionary? Settings, + bool IsOfficial ); diff --git a/src/Nemera.DataAccess/Nemera.DataAccess.csproj b/src/Nemera.DataAccess/Nemera.DataAccess.csproj index 99734cf6..8f876e53 100644 --- a/src/Nemera.DataAccess/Nemera.DataAccess.csproj +++ b/src/Nemera.DataAccess/Nemera.DataAccess.csproj @@ -3,7 +3,6 @@ net10.0 disable enable - $(SolutionDir)..\bin\api\ false diff --git a/src/Nemera.Domain.SharedKernel/Nemera.Domain.SharedKernel.csproj b/src/Nemera.Domain.SharedKernel/Nemera.Domain.SharedKernel.csproj index 5203e19b..5144dd50 100644 --- a/src/Nemera.Domain.SharedKernel/Nemera.Domain.SharedKernel.csproj +++ b/src/Nemera.Domain.SharedKernel/Nemera.Domain.SharedKernel.csproj @@ -3,7 +3,6 @@ net10.0 disable enable - $(SolutionDir)..\bin\api\ false diff --git a/src/Nemera.Domain/Nemera.Domain.csproj b/src/Nemera.Domain/Nemera.Domain.csproj index a056e911..87b5253a 100644 --- a/src/Nemera.Domain/Nemera.Domain.csproj +++ b/src/Nemera.Domain/Nemera.Domain.csproj @@ -3,7 +3,6 @@ net10.0 disable enable - $(SolutionDir)..\bin\api\ false diff --git a/src/Nemera.Infrastructure/Common/DependencyInjection/InfrastructureLayerServices.cs b/src/Nemera.Infrastructure/Common/DependencyInjection/InfrastructureLayerServices.cs index 60e7c282..c63a995b 100644 --- a/src/Nemera.Infrastructure/Common/DependencyInjection/InfrastructureLayerServices.cs +++ b/src/Nemera.Infrastructure/Common/DependencyInjection/InfrastructureLayerServices.cs @@ -1,4 +1,7 @@ #region ========================================================================= USING ===================================================================================== +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; using Nemera.Application.Common.DomainEvents; using Nemera.Application.Common.Infrastructure.Authentication; using Nemera.Application.Common.Infrastructure.Authorization; @@ -8,8 +11,8 @@ using Nemera.Application.Common.Infrastructure.Authorization.Policies.Over18; using Nemera.Application.Common.Infrastructure.Models.DTO.Configuration; using Nemera.Application.Common.Infrastructure.Plugins; using Nemera.Application.Common.Infrastructure.Reading; -using Nemera.Application.Common.Infrastructure.Security; using Nemera.Application.Common.Infrastructure.Scheduling; +using Nemera.Application.Common.Infrastructure.Security; using Nemera.Application.Common.Infrastructure.Themes; using Nemera.Application.Common.Infrastructure.Time; using Nemera.Application.Common.Infrastructure.Validation; @@ -34,14 +37,14 @@ using Nemera.Infrastructure.Core.Authorization.Policies.Common.Factory; using Nemera.Infrastructure.Core.Authorization.Policies.ConsumptionActivity; using Nemera.Infrastructure.Core.Authorization.Policies.LibraryOwnership; using Nemera.Infrastructure.Core.Authorization.Policies.Over18; +using Nemera.Infrastructure.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artwork; +using Nemera.Infrastructure.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback; using Nemera.Infrastructure.Core.MediaLibrary.Management.Scanning.Cancellation; using Nemera.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Audio.Music; using Nemera.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common; using Nemera.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.WrittenContent.Books; using Nemera.Infrastructure.Core.MediaLibrary.Management.Scanning.Progress; using Nemera.Infrastructure.Core.MediaLibrary.Management.Scanning.Queue; -using Nemera.Infrastructure.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artwork; -using Nemera.Infrastructure.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback; using Nemera.Infrastructure.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Artwork; using Nemera.Infrastructure.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading; using Nemera.Infrastructure.Core.Plugins; @@ -52,9 +55,6 @@ using Nemera.Infrastructure.Core.Security; using Nemera.Infrastructure.Core.Themes; using Nemera.Infrastructure.Core.Time; using Nemera.Plugins.Contracts.Core.Plugins; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; @@ -77,8 +77,9 @@ public static class InfrastructureLayerServices /// /// The service collection to add the services to. /// The configuration used to read the application configuration. + /// The trusted checksums of the bundled plugin assemblies, keyed by assembly file name. /// The updated . - public static IServiceCollection AddInfrastructureLayerServices(this IServiceCollection services, IConfiguration configuration) + public static IServiceCollection AddInfrastructureLayerServices(this IServiceCollection services, IConfiguration configuration, IReadOnlyDictionary> bundledPluginChecksums) { // Scan the current assembly for validators and add them to the DI container. IEnumerable concreteTypes = Assembly.GetExecutingAssembly() @@ -89,7 +90,7 @@ public static class InfrastructureLayerServices foreach (Type contract in implementation.GetInterfaces()) if (contract.IsGenericType && contract.GetGenericTypeDefinition() == typeof(IValidator<>)) services.AddSingleton(contract, implementation); - + services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); @@ -190,10 +191,15 @@ public static class InfrastructureLayerServices services.AddSingleton(); // Plugins: load the plugin assemblies from the plugins directory, register their services and provide the plugin manager. + // The trust list only labels plugins as Official. It never gates loading, so a plugin with an unknown or missing hash still works. string pluginsDirectorySetting = configuration.GetSection(PluginsSettingsDto.SECTION_NAME)["Directory"] ?? "plugins"; string pluginsDirectory = Path.Combine(AppContext.BaseDirectory, pluginsDirectorySetting); - PluginLoadResultDto pluginLoadResult = PluginLoader.LoadPlugins(pluginsDirectory, services); - services.AddSingleton(new PluginManager(pluginLoadResult.Plugins, pluginLoadResult.LoadContexts)); + PluginLoadResultDto pluginLoadResult = PluginLoader.LoadPlugins(pluginsDirectory, services, bundledPluginChecksums); + IReadOnlySet officialPluginIds = pluginLoadResult.LoadedPlugins + .Where(plugin => plugin.IsOfficial) + .Select(plugin => plugin.PluginId) + .ToHashSet(); + services.AddSingleton(new PluginManager(pluginLoadResult.Plugins, pluginLoadResult.LoadContexts, officialPluginIds)); services.AddScoped(); services.AddScoped(); services.AddScoped(); @@ -201,6 +207,7 @@ public static class InfrastructureLayerServices serviceProvider.GetRequiredService(), serviceProvider.GetRequiredService(), pluginLoadResult.Errors, + pluginLoadResult.Warnings, serviceProvider.GetRequiredService>())); services.AddHostedService(serviceProvider => serviceProvider.GetRequiredService()); diff --git a/src/Nemera.Infrastructure/Common/Models/DTO/Plugins/LoadedPluginMetadataDto.cs b/src/Nemera.Infrastructure/Common/Models/DTO/Plugins/LoadedPluginMetadataDto.cs new file mode 100644 index 00000000..aca086ec --- /dev/null +++ b/src/Nemera.Infrastructure/Common/Models/DTO/Plugins/LoadedPluginMetadataDto.cs @@ -0,0 +1,22 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Nemera.Infrastructure.Common.Models.DTO.Plugins; + +/// +/// Data transfer object for the trust metadata of a loaded plugin. +/// +/// +/// The Official flag is computed at load time from the plugin binary's SHA-256 hash against the embedded trust list. It is not persisted, because a plugin binary can be replaced and because each release ships a different trust list. +/// +/// The unique identifier of the plugin. +/// The file name of the plugin assembly. +/// Whether the plugin assembly matches a trusted bundled plugin binary. +[DebuggerDisplay("AssemblyFileName: {AssemblyFileName}, IsOfficial: {IsOfficial}")] +internal sealed record LoadedPluginMetadataDto( + Guid PluginId, + string AssemblyFileName, + bool IsOfficial +); diff --git a/src/Nemera.Infrastructure/Common/Models/DTO/Plugins/PluginLoadResultDto.cs b/src/Nemera.Infrastructure/Common/Models/DTO/Plugins/PluginLoadResultDto.cs index 256253a0..7e978255 100644 --- a/src/Nemera.Infrastructure/Common/Models/DTO/Plugins/PluginLoadResultDto.cs +++ b/src/Nemera.Infrastructure/Common/Models/DTO/Plugins/PluginLoadResultDto.cs @@ -16,8 +16,12 @@ namespace Nemera.Infrastructure.Common.Models.DTO.Plugins; /// when a lazily resolved dependency is first used. /// /// The errors that occurred while loading the plugins. +/// The trust metadata of the successfully loaded plugins. +/// The warnings that occurred while loading the plugins, such as a trust status that could not be verified or a dependency manifest that could not be read. internal sealed record PluginLoadResultDto( IReadOnlyList Plugins, IReadOnlyList LoadContexts, - IReadOnlyList Errors + IReadOnlyList Errors, + IReadOnlyList LoadedPlugins, + IReadOnlyList Warnings ); diff --git a/src/Nemera.Infrastructure/Core/Plugins/PluginDetectionSyncJob.cs b/src/Nemera.Infrastructure/Core/Plugins/PluginDetectionSyncJob.cs index 7a64a184..53cea4d6 100644 --- a/src/Nemera.Infrastructure/Core/Plugins/PluginDetectionSyncJob.cs +++ b/src/Nemera.Infrastructure/Core/Plugins/PluginDetectionSyncJob.cs @@ -1,4 +1,7 @@ #region ========================================================================= USING ===================================================================================== +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; using Nemera.Application.Common.DataAccess.Entities.MediaLibrary.Management; using Nemera.Application.Common.DataAccess.Entities.Plugins; using Nemera.Application.Common.DataAccess.UoW; @@ -9,9 +12,6 @@ using Nemera.Domain.Common.Primitives; using Nemera.Domain.SharedKernel.Common.Enums.Plugins; using Nemera.Infrastructure.Common.Models.DTO.Plugins; using Nemera.Plugins.Contracts.Core.Plugins; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Hosting; -using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Linq; @@ -31,6 +31,7 @@ internal sealed class PluginDetectionSyncJob : BackgroundService private readonly IServiceScopeFactory _serviceScopeFactory; private readonly IPluginManager _pluginManager; private readonly IReadOnlyList _loadErrors; + private readonly IReadOnlyList _warnings; private readonly ILogger _logger; /// @@ -39,12 +40,14 @@ internal sealed class PluginDetectionSyncJob : BackgroundService /// Injected factory for creating scopes in which services are requested. /// Injected manager of the plugins loaded by the host application. /// The errors that occurred while loading the plugins. + /// The warnings that occurred while loading the plugins. /// Injected logger used for logging. - public PluginDetectionSyncJob(IServiceScopeFactory serviceScopeFactory, IPluginManager pluginManager, IReadOnlyList loadErrors, ILogger logger) + public PluginDetectionSyncJob(IServiceScopeFactory serviceScopeFactory, IPluginManager pluginManager, IReadOnlyList loadErrors, IReadOnlyList warnings, ILogger logger) { _serviceScopeFactory = serviceScopeFactory; _pluginManager = pluginManager; _loadErrors = loadErrors; + _warnings = warnings; _logger = logger; } @@ -59,6 +62,11 @@ internal sealed class PluginDetectionSyncJob : BackgroundService if (_logger.IsEnabled(LogLevel.Warning)) _logger.LogWarning("Plugin load failure: {LoadError}", loadError.ErrorMessage); + // Warnings are informational and never stop the host. They cover trust verification and dependency resolution problems. + foreach (string warning in _warnings) + if (_logger.IsEnabled(LogLevel.Warning)) + _logger.LogWarning("Plugin warning: {Warning}", warning); + await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope(); IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetRequiredService(); diff --git a/src/Nemera.Infrastructure/Core/Plugins/PluginLoadContext.cs b/src/Nemera.Infrastructure/Core/Plugins/PluginLoadContext.cs index 347a0ed7..f4fab103 100644 --- a/src/Nemera.Infrastructure/Core/Plugins/PluginLoadContext.cs +++ b/src/Nemera.Infrastructure/Core/Plugins/PluginLoadContext.cs @@ -1,26 +1,51 @@ #region ========================================================================= USING ===================================================================================== +using System; using System.IO; using System.Reflection; +using System.Runtime.InteropServices; using System.Runtime.Loader; #endregion namespace Nemera.Infrastructure.Core.Plugins; /// -/// Assembly load context of a single plugin, resolving the shared host assemblies from the default context and the plugin local dependencies from the plugin directory. +/// Assembly load context of a single plugin, resolving the shared host assemblies from the default context, and the plugin local dependencies and native libraries from its dependency manifest. /// internal sealed class PluginLoadContext : AssemblyLoadContext { private readonly string _pluginDirectory; + private readonly AssemblyDependencyResolver? _dependencyResolver; + + /// + /// Gets a value indicating whether the plugin assembly has no dependency manifest next to it. + /// + public bool IsDependencyManifestMissing { get; } + + /// + /// Gets the error that occurred while reading the dependency manifest, or when no error occurred. + /// + public string? DependencyManifestError { get; } /// /// Initializes a new instance of the class. /// - /// The directory where the plugin assemblies and their dependencies are located. + /// The path of the plugin assembly whose dependencies and native libraries are resolved from its adjacent dependency manifest. /// The name of the load context. - public PluginLoadContext(string pluginDirectory, string name) : base(name, isCollectible: true) + public PluginLoadContext(string pluginAssemblyPath, string name) : base(name, isCollectible: true) { - _pluginDirectory = pluginDirectory; + _pluginDirectory = Path.GetDirectoryName(pluginAssemblyPath) ?? throw new ArgumentException("The plugin assembly path has no directory.", nameof(pluginAssemblyPath)); + IsDependencyManifestMissing = !File.Exists(Path.ChangeExtension(pluginAssemblyPath, ".deps.json")); + try + { + _dependencyResolver = new AssemblyDependencyResolver(pluginAssemblyPath); + } + catch (Exception exception) + { + // The plugin can still load its managed dependencies through the directory fallback, but the native libraries under the shared runtimes folder cannot be resolved without a readable dependency manifest, + // so the error is recorded and the loader reports it for the plugin that it belongs to. + _dependencyResolver = null; + DependencyManifestError = exception.Message; + } } /// @@ -49,4 +74,19 @@ internal sealed class PluginLoadContext : AssemblyLoadContext return null; } + + /// + /// Loads the native library whose name is specified, using the plugin's dependency manifest to select the library of the current runtime. + /// + /// The name of the native library to load. + /// The handle of the loaded native library. + protected override IntPtr LoadUnmanagedDll(string unmanagedDllName) + { + // The dependency resolver selects the native library for the current RID from the plugin's deps.json. When it has no match, + // fall back to the default resolution so system libraries still load. + string? nativeLibraryPath = _dependencyResolver?.ResolveUnmanagedDllToPath(unmanagedDllName); + return nativeLibraryPath is null + ? base.LoadUnmanagedDll(unmanagedDllName) + : NativeLibrary.Load(nativeLibraryPath); + } } diff --git a/src/Nemera.Infrastructure/Core/Plugins/PluginLoader.cs b/src/Nemera.Infrastructure/Core/Plugins/PluginLoader.cs index a18e088b..16699a2c 100644 --- a/src/Nemera.Infrastructure/Core/Plugins/PluginLoader.cs +++ b/src/Nemera.Infrastructure/Core/Plugins/PluginLoader.cs @@ -1,12 +1,13 @@ #region ========================================================================= USING ===================================================================================== +using Microsoft.Extensions.DependencyInjection; using Nemera.Infrastructure.Common.Models.DTO.Plugins; using Nemera.Plugins.Contracts.Core.Plugins; -using Microsoft.Extensions.DependencyInjection; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; +using System.Security.Cryptography; #endregion namespace Nemera.Infrastructure.Core.Plugins; @@ -21,20 +22,23 @@ internal static class PluginLoader /// /// The directory where the plugin assemblies are located. /// The service collection to which the plugin services are added. + /// The trusted checksums of the bundled plugin assemblies, keyed by assembly file name. /// The result of loading the plugins. - public static PluginLoadResultDto LoadPlugins(string pluginsDirectory, IServiceCollection services) + public static PluginLoadResultDto LoadPlugins(string pluginsDirectory, IServiceCollection services, IReadOnlyDictionary> bundledPluginChecksums) { List plugins = []; List loadContexts = []; List errors = []; + List loadedPlugins = []; + List warnings = []; if (!Directory.Exists(pluginsDirectory)) - return new PluginLoadResultDto(plugins, loadContexts, errors); + return new PluginLoadResultDto(plugins, loadContexts, errors, loadedPlugins, warnings); foreach (string assemblyPath in Directory.EnumerateFiles(pluginsDirectory, "*.dll")) { // A failing plugin must not prevent the other plugins from loading, so each assembly is isolated in its own load context. - PluginLoadContext loadContext = new(pluginsDirectory, Path.GetFileNameWithoutExtension(assemblyPath)); + PluginLoadContext loadContext = new(assemblyPath, Path.GetFileNameWithoutExtension(assemblyPath)); try { Assembly assembly = loadContext.LoadFromAssemblyPath(assemblyPath); @@ -52,9 +56,25 @@ internal static class PluginLoader if (plugin is IPluginServiceRegistrator serviceRegistrator) serviceRegistrator.RegisterServices(services); plugins.Add(plugin); + // The trust manifest is a list of known bundled binaries, so a plugin remains Official only while its assembly matches one of them. + string assemblyFileName = Path.GetFileName(assemblyPath); + (string? checksum, string? checksumError) = GetSha256(assemblyPath); + bool isOfficial = checksum is not null + && bundledPluginChecksums.TryGetValue(assemblyFileName, out IReadOnlySet? trustedChecksums) + && trustedChecksums.Contains(checksum); + // A checksum failure must not prevent the plugin from loading. It only means the Official badge cannot be verified. + if (checksum is null) + warnings.Add($"The SHA-256 checksum of plugin assembly '{assemblyFileName}' could not be computed, so its Official status cannot be verified: {checksumError}"); + loadedPlugins.Add(new LoadedPluginMetadataDto(plugin.Id, assemblyFileName, isOfficial)); // A collectible load context is only kept alive by a direct reference to the context object itself, so the context of a loaded plugin is held for the lifetime // of the host, keeping the plugin assemblies (and any lazily resolved dependency, like a book reader library) from being unloaded by the garbage collector. loadContexts.Add(loadContext); + // Uploaded plugins normally have no dependency manifest because the installer stores only assemblies. Only a bundled + // (Official) plugin is expected to have one, so a missing manifest is a warning only for that case. + if (loadContext.DependencyManifestError is not null) + warnings.Add($"The dependency manifest of plugin assembly '{assemblyFileName}' could not be read, so its native libraries cannot be resolved from the plugin folder: {loadContext.DependencyManifestError}"); + else if (loadContext.IsDependencyManifestMissing && isOfficial) + warnings.Add($"The bundled plugin assembly '{assemblyFileName}' has no dependency manifest next to it, so its native libraries cannot be resolved from the plugin folder."); break; // Only one plugin descriptor per assembly. } } @@ -75,7 +95,29 @@ internal static class PluginLoader } } - return new PluginLoadResultDto(plugins, loadContexts, errors); + return new PluginLoadResultDto(plugins, loadContexts, errors, loadedPlugins, warnings); + } + + /// + /// Computes the SHA-256 checksum of the file at , in the uppercase hexadecimal form the bundled plugin trust manifest uses. + /// + /// The path of the file to hash. + /// The checksum and a error message, or a checksum and the error message when the file cannot be read. + private static (string? Checksum, string? ErrorMessage) GetSha256(string path) + { + try + { + using (FileStream fileStream = new(path, FileMode.Open, FileAccess.Read, FileShare.Read)) + return (Convert.ToHexString(SHA256.HashData(fileStream)), null); + } + catch (IOException exception) + { + return (null, exception.Message); + } + catch (UnauthorizedAccessException exception) + { + return (null, exception.Message); + } } /// @@ -88,12 +130,14 @@ internal static class PluginLoader { try { - using FileStream fileStream = new(path, FileMode.Open, FileAccess.Read, FileShare.Read); - Span signature = stackalloc byte[2]; - if (fileStream.Read(signature) < signature.Length) - return false; - // The DOS signature "MZ" is the header every PE image starts with, whether it is a managed assembly or a native library. - return signature[0] == (byte)'M' && signature[1] == (byte)'Z'; + using (FileStream fileStream = new(path, FileMode.Open, FileAccess.Read, FileShare.Read)) + { + Span signature = stackalloc byte[2]; + if (fileStream.Read(signature) < signature.Length) + return false; + // The DOS signature "MZ" is the header every PE image starts with, whether it is a managed assembly or a native library. + return signature[0] == (byte)'M' && signature[1] == (byte)'Z'; + } } catch (IOException) { diff --git a/src/Nemera.Infrastructure/Core/Plugins/PluginManager.cs b/src/Nemera.Infrastructure/Core/Plugins/PluginManager.cs index 4d75760a..949b6d78 100644 --- a/src/Nemera.Infrastructure/Core/Plugins/PluginManager.cs +++ b/src/Nemera.Infrastructure/Core/Plugins/PluginManager.cs @@ -14,6 +14,7 @@ namespace Nemera.Infrastructure.Core.Plugins; internal sealed class PluginManager : IPluginManager { private readonly IReadOnlyDictionary _pluginsById; + private readonly IReadOnlySet _officialPluginIds; // The load contexts of the loaded plugins are held for the lifetime of the host, because a collectible load context is only kept alive by a direct reference to the // context object itself, and the garbage collector would otherwise unload the plugin assemblies mid-request, when a lazily resolved dependency is first used. private readonly IReadOnlyList _loadContexts; @@ -23,9 +24,11 @@ internal sealed class PluginManager : IPluginManager /// /// The plugins that were loaded successfully. /// The load contexts of the loaded plugins, kept referenced for the lifetime of the host. - public PluginManager(IEnumerable plugins, IReadOnlyList loadContexts) + /// The Ids of the loaded plugins whose assemblies match a trusted bundled plugin binary. + public PluginManager(IEnumerable plugins, IReadOnlyList loadContexts, IReadOnlySet officialPluginIds) { _pluginsById = plugins.ToDictionary(plugin => plugin.Id); + _officialPluginIds = officialPluginIds; _loadContexts = loadContexts; } @@ -47,4 +50,14 @@ internal sealed class PluginManager : IPluginManager { return _pluginsById.GetValueOrDefault(pluginId); } + + /// + /// Determines whether the loaded plugin identified by matches a trusted bundled plugin binary. + /// + /// The unique identifier of the plugin. + /// when the plugin is official, otherwise. + public bool IsOfficial(Guid pluginId) + { + return _officialPluginIds.Contains(pluginId); + } } diff --git a/src/Nemera.Infrastructure/Nemera.Infrastructure.csproj b/src/Nemera.Infrastructure/Nemera.Infrastructure.csproj index e1d5afab..2a457735 100644 --- a/src/Nemera.Infrastructure/Nemera.Infrastructure.csproj +++ b/src/Nemera.Infrastructure/Nemera.Infrastructure.csproj @@ -3,7 +3,6 @@ net10.0 disable enable - $(SolutionDir)..\bin\api\ false True diff --git a/src/Nemera.Plugins.Contracts/Nemera.Plugins.Contracts.csproj b/src/Nemera.Plugins.Contracts/Nemera.Plugins.Contracts.csproj index 245c26ff..02677b97 100644 --- a/src/Nemera.Plugins.Contracts/Nemera.Plugins.Contracts.csproj +++ b/src/Nemera.Plugins.Contracts/Nemera.Plugins.Contracts.csproj @@ -3,7 +3,6 @@ net10.0 disable enable - $(SolutionDir)..\bin\api\ false diff --git a/src/Nemera.Presentation.Api/Core/Endpoints/Plugins/GetPlugins/GetPluginsEndpointSummary.cs b/src/Nemera.Presentation.Api/Core/Endpoints/Plugins/GetPlugins/GetPluginsEndpointSummary.cs index abef41f9..199438a2 100644 --- a/src/Nemera.Presentation.Api/Core/Endpoints/Plugins/GetPlugins/GetPluginsEndpointSummary.cs +++ b/src/Nemera.Presentation.Api/Core/Endpoints/Plugins/GetPlugins/GetPluginsEndpointSummary.cs @@ -31,6 +31,7 @@ public class GetPluginsEndpointSummary : Summary(r => r.LoadStatus, "The load status of the plugin."); ResponseParam(r => r.LoadError, "The error message when the plugin failed to load, if applicable."); ResponseParam(r => r.Settings, "The settings of the plugin."); + ResponseParam(r => r.IsOfficial, "Whether the plugin matches a trusted bundled plugin binary."); Response(200, "The list of detected plugins is returned.", example: new PluginResponse[] { @@ -46,7 +47,8 @@ public class GetPluginsEndpointSummary : Summary +/// Reads the trust manifests of the bundled plugin binaries embedded in the API assembly. +/// +internal static class BundledPluginManifestReader +{ + /// + /// The resource name of the append-only trust list of previously released bundled plugin binaries. + /// + private const string HISTORICAL_MANIFEST_RESOURCE_NAME = "Nemera.Presentation.Api.BundledPlugins.historical.manifest"; + + /// + /// The resource name of the trust list generated for the current build's bundled plugin binaries. + /// + private const string CURRENT_MANIFEST_RESOURCE_NAME = "Nemera.Presentation.Api.BundledPlugins.current.manifest"; + + /// + /// The resource name of the list of bundled plugin checksums that are no longer trusted. + /// + private const string DENY_MANIFEST_RESOURCE_NAME = "Nemera.Presentation.Api.BundledPlugins.deny.manifest"; + + /// + /// Reads the trusted SHA-256 checksums of the bundled plugin binaries from the embedded trust manifests. + /// The current build's manifest is read only for an official release build, so a local build cannot certify its own plugins. + /// Denied checksums are removed from the historical and current trust lists. + /// + /// A dictionary that maps each bundled plugin assembly file name to the checksums it is allowed to have. + public static IReadOnlyDictionary> ReadExpectedChecksums() + { + // The historical list is always embedded, because it carries the hashes of earlier releases and those binaries must stay trusted after an upgrade. + using (Stream historicalManifestStream = GetManifestResourceStream(HISTORICAL_MANIFEST_RESOURCE_NAME)) + { + // The deny list is always embedded too, so revoking a hash does not depend on the release being rebuilt. + using (Stream denyManifestStream = GetManifestResourceStream(DENY_MANIFEST_RESOURCE_NAME)) + { + // A normal build cannot certify its own plugins. Only an official release build embeds the current manifest, + // so a developer cannot make a locally built plugin appear Official just by building the project. + if (!IsOfficialReleaseBuild()) + return ReadExpectedChecksums(historicalManifestStream, null, denyManifestStream); + using (Stream currentManifestStream = GetManifestResourceStream(CURRENT_MANIFEST_RESOURCE_NAME)) + return ReadExpectedChecksums(historicalManifestStream, currentManifestStream, denyManifestStream); + } + } + } + + /// + /// Reads the trusted SHA-256 checksums of the bundled plugin binaries from the provided trust manifest streams. + /// + /// The stream that contains the append-only trust list of previously released bundled plugin binaries. + /// The stream that contains the trust list generated for the current build's bundled plugin binaries, or when the build is not an official release build. + /// The stream that contains the checksums that are no longer trusted, or when no deny list is available. + /// A dictionary that maps each bundled plugin assembly file name to the checksums it is allowed to have. + internal static IReadOnlyDictionary> ReadExpectedChecksums(Stream historicalManifestStream, Stream? currentManifestStream = null, Stream? denyManifestStream = null) + { + // Assembly file names are compared case-insensitively because the plugins directory is case-insensitive on Windows. + Dictionary> checksumsByAssemblyFileName = new(StringComparer.OrdinalIgnoreCase); + // The historical list comes first so the current release can add hashes without replacing the earlier ones. + ReadManifest(historicalManifestStream, HISTORICAL_MANIFEST_RESOURCE_NAME, checksumsByAssemblyFileName); + if (currentManifestStream is not null) + ReadManifest(currentManifestStream, CURRENT_MANIFEST_RESOURCE_NAME, checksumsByAssemblyFileName); + // Revocation is applied last so a denied hash wins over every trust list, including the current release's own entries. + if (denyManifestStream is not null) + RemoveDeniedChecksums(denyManifestStream, checksumsByAssemblyFileName); + // The loader only reads the trust list, so the result exposes the sets as read-only even though they were built as mutable sets. + Dictionary> expectedChecksums = new(StringComparer.OrdinalIgnoreCase); + foreach (KeyValuePair> checksums in checksumsByAssemblyFileName) + expectedChecksums[checksums.Key] = checksums.Value; + return expectedChecksums; + } + + /// + /// Removes the checksums of the deny list from the accumulated trust list. + /// + /// The stream that contains the checksums that are no longer trusted. + /// The dictionary that accumulates the trust list entries. + private static void RemoveDeniedChecksums(Stream denyManifestStream, Dictionary> checksumsByAssemblyFileName) + { + // The deny list is parsed on its own first, so an entry for an unknown or retired assembly can be ignored without failing the whole manifest. + Dictionary> deniedChecksumsByAssemblyFileName = new(StringComparer.OrdinalIgnoreCase); + ReadManifest(denyManifestStream, DENY_MANIFEST_RESOURCE_NAME, deniedChecksumsByAssemblyFileName); + foreach (KeyValuePair> deniedChecksums in deniedChecksumsByAssemblyFileName) + { + // A deny entry for an assembly that is not trusted anywhere is harmless. + if (!checksumsByAssemblyFileName.TryGetValue(deniedChecksums.Key, out HashSet? assemblyChecksums)) + continue; + assemblyChecksums.ExceptWith(deniedChecksums.Value); + // An assembly with no trusted hashes left is removed, so the result never carries an empty trust set. + if (assemblyChecksums.Count == 0) + checksumsByAssemblyFileName.Remove(deniedChecksums.Key); + } + } + + /// + /// Determines whether the API assembly was produced by an official release build. + /// + /// when the assembly carries the official release marker, otherwise. + private static bool IsOfficialReleaseBuild() + { + // The official build injects this marker from the OFFICIAL_RELEASE_BUILD compilation symbol. build.proj defines the symbol only for the + // official release flow, so a normal build has no marker and does not embed a current manifest of its own binaries. + return typeof(BundledPluginManifestReader).Assembly + .GetCustomAttributes() + .Any(attribute => attribute.Key == "OfficialReleaseBuild" && attribute.Value == "true"); + } + + /// + /// Opens an embedded trust manifest resource. + /// + /// The name of the embedded manifest resource. + /// The stream that contains the manifest. + private static Stream GetManifestResourceStream(string resourceName) + { + // The historical and deny manifests are required for every build. A missing resource means the packaging step is broken, + // and failing fast is safer than starting with an empty trust list that marks every bundled plugin as not Official. + return typeof(BundledPluginManifestReader).Assembly.GetManifestResourceStream(resourceName) + ?? throw new InvalidOperationException($"The bundled plugin manifest resource '{resourceName}' is missing."); + } + + /// + /// Reads one trust manifest and adds its entries to . + /// + /// The stream that contains the manifest. + /// The name of the manifest resource, used in error messages. + /// The dictionary that accumulates the trust list entries. + private static void ReadManifest(Stream manifestStream, string resourceName, Dictionary> checksumsByAssemblyFileName) + { + // Each entry is "assembly-file-name|sha256". Blank lines and lines starting with # are ignored, so the checked-in list can carry release notes. + using (StreamReader reader = new(manifestStream)) + { + int lineNumber = 0; + string? line; + while ((line = reader.ReadLine()) is not null) + { + lineNumber++; + string trimmedLine = line.Trim(); + if (trimmedLine.Length == 0 || trimmedLine.StartsWith('#')) + continue; + // A malformed entry is a build error rather than a skipped line, because silently ignoring it could hide a plugin that the release intended to trust. + string[] parts = trimmedLine.Split('|'); + if (parts.Length != 2) + throw new InvalidOperationException($"The bundled plugin manifest resource '{resourceName}' contains an invalid entry at line {lineNumber}."); + string assemblyFileName = parts[0].Trim(); + string checksum = parts[1].Trim(); + // A SHA-256 checksum is 64 hexadecimal characters. The length check gives a clearer error than the conversion below. + if (assemblyFileName.Length == 0 || checksum.Length != 64) + throw new InvalidOperationException($"The bundled plugin manifest resource '{resourceName}' contains an invalid entry at line {lineNumber}."); + int checksumLength; + try + { + checksumLength = Convert.FromHexString(checksum).Length; + } + catch (FormatException exception) + { + throw new InvalidOperationException($"The bundled plugin manifest resource '{resourceName}' contains an invalid checksum at line {lineNumber}.", exception); + } + // The byte count is checked as well, so a future change to the length check cannot let a non-SHA-256 value through. + if (checksumLength != 32) + throw new InvalidOperationException($"The bundled plugin manifest resource '{resourceName}' contains an invalid checksum at line {lineNumber}."); + // The historical and current manifests can list the same hash. The set makes that duplicate harmless. + if (!checksumsByAssemblyFileName.TryGetValue(assemblyFileName, out HashSet? assemblyChecksums)) + { + assemblyChecksums = new HashSet(StringComparer.OrdinalIgnoreCase); + checksumsByAssemblyFileName[assemblyFileName] = assemblyChecksums; + } + assemblyChecksums.Add(checksum); + } + } + } +} diff --git a/src/Nemera.Presentation.Api/Core/Plugins/OfficialReleaseBuildAssemblyInfo.cs b/src/Nemera.Presentation.Api/Core/Plugins/OfficialReleaseBuildAssemblyInfo.cs new file mode 100644 index 00000000..b9bccd70 --- /dev/null +++ b/src/Nemera.Presentation.Api/Core/Plugins/OfficialReleaseBuildAssemblyInfo.cs @@ -0,0 +1,5 @@ +// The official release marker tells the trust manifest reader and the manifest tests that this is an official release build. +// The OFFICIAL_RELEASE_BUILD symbol is defined by build/build.proj only for the official release build, so a normal local build cannot produce it. +#if OFFICIAL_RELEASE_BUILD +[assembly: System.Reflection.AssemblyMetadata("OfficialReleaseBuild", "true")] +#endif diff --git a/src/Nemera.Presentation.Api/Dockerfile b/src/Nemera.Presentation.Api/Dockerfile index 795ded2d..0ba7d002 100644 --- a/src/Nemera.Presentation.Api/Dockerfile +++ b/src/Nemera.Presentation.Api/Dockerfile @@ -14,34 +14,33 @@ WORKDIR /app EXPOSE 5214 # ==== Stage 1: Build stage -FROM mcr.microsoft.com/dotnet/sdk:10.0 AS build +FROM mcr.microsoft.com/dotnet/sdk:10.0.100 AS build ARG BUILD_CONFIGURATION=Release WORKDIR /src # Restore NuGet packages (keeping this section separate from the rest of the project files allows Docker to cache the restored packages). -COPY ["AssemblyInfo_Shared.cs", "."] -COPY ["Nemera.Presentation.Api/Nemera.Presentation.Api.csproj", "Nemera.Presentation.Api/"] -COPY ["Nemera.Application/Nemera.Application.csproj", "Nemera.Application/"] -COPY ["Nemera.Contracts/Nemera.Contracts.csproj", "Nemera.Contracts/"] -COPY ["Nemera.Domain/Nemera.Domain.csproj", "Nemera.Domain/"] -COPY ["Nemera.Domain.SharedKernel/Nemera.Domain.SharedKernel.csproj", "Nemera.Domain.SharedKernel/"] -COPY ["Nemera.Infrastructure/Nemera.Infrastructure.csproj", "Nemera.Infrastructure/"] -COPY ["Nemera.DataAccess/Nemera.DataAccess.csproj", "Nemera.DataAccess/"] -COPY ["Nemera.Plugins.Contracts/Nemera.Plugins.Contracts.csproj", "Nemera.Plugins.Contracts/"] +COPY ["Directory.Build.props", "."] +COPY ["Directory.Packages.props", "."] +COPY ["global.json", "."] +COPY ["src/AssemblyInfo_Shared.cs", "src/"] +COPY ["src/Directory.Build.props", "src/"] +COPY ["src/Nemera.Presentation.Api/Nemera.Presentation.Api.csproj", "src/Nemera.Presentation.Api/"] +COPY ["src/Nemera.Application/Nemera.Application.csproj", "src/Nemera.Application/"] +COPY ["src/Nemera.Contracts/Nemera.Contracts.csproj", "src/Nemera.Contracts/"] +COPY ["src/Nemera.Domain/Nemera.Domain.csproj", "src/Nemera.Domain/"] +COPY ["src/Nemera.Domain.SharedKernel/Nemera.Domain.SharedKernel.csproj", "src/Nemera.Domain.SharedKernel/"] +COPY ["src/Nemera.Infrastructure/Nemera.Infrastructure.csproj", "src/Nemera.Infrastructure/"] +COPY ["src/Nemera.DataAccess/Nemera.DataAccess.csproj", "src/Nemera.DataAccess/"] +COPY ["src/Nemera.Plugins.Contracts/Nemera.Plugins.Contracts.csproj", "src/Nemera.Plugins.Contracts/"] -RUN dotnet restore "./Nemera.Presentation.Api/Nemera.Presentation.Api.csproj" /p:BaseOutputPath=/app/publish/ +RUN dotnet restore "./src/Nemera.Presentation.Api/Nemera.Presentation.Api.csproj" /p:BaseOutputPath=/app/publish/ # Build the project. -COPY ["Nemera.Presentation.Api/", "Nemera.Presentation.Api/"] -COPY ["Nemera.Application/", "Nemera.Application/"] -COPY ["Nemera.Contracts/", "Nemera.Contracts/"] -COPY ["Nemera.Domain/", "Nemera.Domain/"] -COPY ["Nemera.Infrastructure/", "Nemera.Infrastructure/"] -COPY ["Nemera.DataAccess/", "Nemera.DataAccess/"] -COPY . . -WORKDIR /src/Nemera.Presentation.Api +COPY ["src/", "src/"] +COPY ["build/", "build/"] +WORKDIR /src/src/Nemera.Presentation.Api RUN dotnet build "./Nemera.Presentation.Api.csproj" -c $BUILD_CONFIGURATION -o /app/build /p:BaseOutputPath=/app/publish/ @@ -50,7 +49,10 @@ FROM build AS publish ARG BUILD_CONFIGURATION=Release -RUN dotnet publish "./Nemera.Presentation.Api.csproj" -c $BUILD_CONFIGURATION -o /app/publish /p:UseAppHost=false /p:BaseOutputPath=/app/publish/ +RUN dotnet publish "./Nemera.Presentation.Api.csproj" -c $BUILD_CONFIGURATION -o /app/publish /p:UseAppHost=false /p:BaseOutputPath=/app/publish/ -p:BundledPluginsPredeployed=true +# Build the bundled plugins into the publish folder, so the image contains the same plugin binaries as the verified release artifact. +COPY ["plugins/", "/src/plugins/"] +RUN dotnet msbuild "/src/build/build.proj" -t:BuildBundledPlugins -p:Configuration=$BUILD_CONFIGURATION -p:NemeraPluginsOutputDirectory=/app/publish/plugins/ # ==== Stage 3: Run stage #FROM mcr.microsoft.com/dotnet/aspnet:10.0 AS runtime @@ -58,7 +60,8 @@ FROM base AS final WORKDIR /app -COPY --from=publish /app/publish . +# The app user must own the published files, because the plugin installer writes into /app/plugins. +COPY --from=publish --chown=app:app /app/publish . # The HTTP port is controlled per run mode: launchSettings.json for local development, ASPNETCORE_HTTP_PORTS here for # Docker, and for a published DLL run directly on a host, ASPNETCORE_URLS (or ASPNETCORE_HTTP_PORTS) must be set. ENV ASPNETCORE_HTTP_PORTS=5214 @@ -66,4 +69,4 @@ EXPOSE 5214 ENTRYPOINT ["dotnet", "Nemera.Presentation.Api.dll"] # To build this Docker image, run the following command from the root of the project (location of the .slnx solution file): -# docker build --no-cache -t nemera-api -f Nemera.Presentation.Api/Dockerfile . +# docker build --no-cache -t nemera-api -f src/Nemera.Presentation.Api/Dockerfile . diff --git a/src/Nemera.Presentation.Api/Dockerfile.release b/src/Nemera.Presentation.Api/Dockerfile.release new file mode 100644 index 00000000..4f759867 --- /dev/null +++ b/src/Nemera.Presentation.Api/Dockerfile.release @@ -0,0 +1,21 @@ +# This image ships the published release artifacts, so the recorded plugin hashes and the image contents are the same files. +# Build it with the published API directory as the context: +# docker build -t nemera-api -f src/Nemera.Presentation.Api/Dockerfile.release bin/api/publish +FROM mcr.microsoft.com/dotnet/aspnet:10.0 AS final + +# Curl is used by the container healthcheck to probe the /health endpoints. +# FFmpeg is used by the API server to remux or transcode audio the browser cannot play directly. +RUN apt-get update \ + && apt-get install -y --no-install-recommends curl ffmpeg \ + && rm -rf /var/lib/apt/lists/* \ + && mkdir -p /app /logs && chown -R app:app /app /logs + +USER app +WORKDIR /app + +# The app user must own the published files, because the plugin installer writes into /app/plugins. +COPY --chown=app:app . . + +ENV ASPNETCORE_HTTP_PORTS=5214 +EXPOSE 5214 +ENTRYPOINT ["dotnet", "Nemera.Presentation.Api.dll"] diff --git a/src/Nemera.Presentation.Api/Nemera.Presentation.Api.csproj b/src/Nemera.Presentation.Api/Nemera.Presentation.Api.csproj index 348e8329..32017ce3 100644 --- a/src/Nemera.Presentation.Api/Nemera.Presentation.Api.csproj +++ b/src/Nemera.Presentation.Api/Nemera.Presentation.Api.csproj @@ -3,7 +3,6 @@ net10.0 enable disable - $(SolutionDir)..\bin\api\ false 37d55c87-4374-4971-82e9-012fcaad1853 Linux @@ -11,10 +10,13 @@ nemera-api ..\docker-compose.dcproj + + $(DefineConstants);OFFICIAL_RELEASE_BUILD + en - + @@ -69,4 +71,31 @@ + + + + <_BundledPluginsCurrentManifestPath Condition="$([System.IO.Path]::IsPathRooted('$(BundledPluginsCurrentManifest)'))">$(BundledPluginsCurrentManifest) + <_BundledPluginsCurrentManifestPath Condition="!$([System.IO.Path]::IsPathRooted('$(BundledPluginsCurrentManifest)'))">$([System.IO.Path]::GetFullPath('$(MSBuildThisFileDirectory)..\..\$(BundledPluginsCurrentManifest)')) + + + + + + + + + + + + + + + + + + + <_BundledPluginPublishFile Include="$(TargetDir)plugins/**/*" /> + + + diff --git a/src/Nemera.Presentation.Api/Program.cs b/src/Nemera.Presentation.Api/Program.cs index e3f3ff22..e1fc3b1b 100644 --- a/src/Nemera.Presentation.Api/Program.cs +++ b/src/Nemera.Presentation.Api/Program.cs @@ -1,5 +1,16 @@ #region ========================================================================= USING ===================================================================================== using FastEndpoints; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Diagnostics.HealthChecks; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Http; +using Microsoft.Data.Sqlite; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Diagnostics.HealthChecks; +using Microsoft.Extensions.FileProviders; +using Microsoft.Extensions.Logging; using Nemera.Application.Common.DependencyInjection; using Nemera.DataAccess.Common.DependencyInjection; using Nemera.DataAccess.Core.UoW; @@ -13,20 +24,11 @@ using Nemera.Infrastructure.Core.Scheduling.Notifications; using Nemera.Presentation.Api.Common.DependencyInjection; using Nemera.Presentation.Api.Common.Middlewares; using Nemera.Presentation.Api.Common.Utilities; -using Microsoft.AspNetCore.Builder; -using Microsoft.AspNetCore.Diagnostics.HealthChecks; -using Microsoft.AspNetCore.Hosting; -using Microsoft.AspNetCore.Http; -using Microsoft.Data.Sqlite; -using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Diagnostics.HealthChecks; -using Microsoft.Extensions.FileProviders; -using Microsoft.Extensions.Logging; +using Nemera.Presentation.Api.Core.Plugins; using Scalar.AspNetCore; using Serilog; using System; +using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; @@ -55,7 +57,9 @@ public class Program builder.Services.AddPresentationApiLayerServices(builder.Configuration); builder.Services.AddPresentationApiTelemetryServices(builder.Configuration, builder.Environment); builder.Services.AddApplicationLayerServices(); - builder.Services.AddInfrastructureLayerServices(builder.Configuration); + // The trust list only labels plugins as Official. It is read once at startup and never prevents a plugin from loading. + IReadOnlyDictionary> bundledPluginChecksums = BundledPluginManifestReader.ReadExpectedChecksums(); + builder.Services.AddInfrastructureLayerServices(builder.Configuration, bundledPluginChecksums); builder.Services.AddDataAccessLayerServices(); builder.Services.AddDomainLayerServices(); @@ -179,7 +183,7 @@ public class Program // Ensure the default file system structure is present. using (IServiceScope scope = app.Services.CreateScope()) { - IServiceProvider services = scope.ServiceProvider; + IServiceProvider services = scope.ServiceProvider; IFileSystemStructureSeedService context = services.GetRequiredService(); Result setDefaultDirectoriesResult = context.SetDefaultDirectories(mediaRootPath); if (setDefaultDirectoriesResult.IsFailure) diff --git a/src/Nemera.Presentation.Api/Properties/AssemblyInfo.cs b/src/Nemera.Presentation.Api/Properties/AssemblyInfo.cs index 0e52db31..126fa099 100644 --- a/src/Nemera.Presentation.Api/Properties/AssemblyInfo.cs +++ b/src/Nemera.Presentation.Api/Properties/AssemblyInfo.cs @@ -17,4 +17,5 @@ using System.Runtime.InteropServices; [assembly: Guid("D910C582-3905-4DD3-8BCA-0CB30852704E")] [assembly: InternalsVisibleTo("Nemera.Presentation.Api.UnitTests")] +[assembly: InternalsVisibleTo("Nemera.Presentation.Api.IntegrationTests")] [assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")] diff --git a/src/Nemera.Presentation.Web/Common/DTO/Plugins/PluginDto.cs b/src/Nemera.Presentation.Web/Common/DTO/Plugins/PluginDto.cs index e569a91b..19d89d4d 100644 --- a/src/Nemera.Presentation.Web/Common/DTO/Plugins/PluginDto.cs +++ b/src/Nemera.Presentation.Web/Common/DTO/Plugins/PluginDto.cs @@ -52,4 +52,9 @@ public class PluginDto /// Gets or sets the settings of the plugin. /// public Dictionary? Settings { get; set; } + + /// + /// Gets or sets whether the plugin matches a trusted bundled plugin binary. + /// + public bool IsOfficial { get; set; } } diff --git a/src/Nemera.Presentation.Web/Core/Resources/Views/Admin/Plugins.ar-SA.resx b/src/Nemera.Presentation.Web/Core/Resources/Views/Admin/Plugins.ar-SA.resx index 2fbceac6..ae5f5175 100644 --- a/src/Nemera.Presentation.Web/Core/Resources/Views/Admin/Plugins.ar-SA.resx +++ b/src/Nemera.Presentation.Web/Core/Resources/Views/Admin/Plugins.ar-SA.resx @@ -165,4 +165,7 @@ فشل الرفع + + رسمي + diff --git a/src/Nemera.Presentation.Web/Core/Resources/Views/Admin/Plugins.de-DE.resx b/src/Nemera.Presentation.Web/Core/Resources/Views/Admin/Plugins.de-DE.resx index 2cca8bf9..3c38e377 100644 --- a/src/Nemera.Presentation.Web/Core/Resources/Views/Admin/Plugins.de-DE.resx +++ b/src/Nemera.Presentation.Web/Core/Resources/Views/Admin/Plugins.de-DE.resx @@ -165,4 +165,7 @@ Upload fehlgeschlagen + + Offiziell + diff --git a/src/Nemera.Presentation.Web/Core/Resources/Views/Admin/Plugins.en-US.resx b/src/Nemera.Presentation.Web/Core/Resources/Views/Admin/Plugins.en-US.resx index bcb5046c..8797a403 100644 --- a/src/Nemera.Presentation.Web/Core/Resources/Views/Admin/Plugins.en-US.resx +++ b/src/Nemera.Presentation.Web/Core/Resources/Views/Admin/Plugins.en-US.resx @@ -165,4 +165,7 @@ Upload failed + + Official + diff --git a/src/Nemera.Presentation.Web/Core/Resources/Views/Admin/Plugins.es-ES.resx b/src/Nemera.Presentation.Web/Core/Resources/Views/Admin/Plugins.es-ES.resx index d1b73867..5efa1ca8 100644 --- a/src/Nemera.Presentation.Web/Core/Resources/Views/Admin/Plugins.es-ES.resx +++ b/src/Nemera.Presentation.Web/Core/Resources/Views/Admin/Plugins.es-ES.resx @@ -165,4 +165,7 @@ Error al subir + + Oficial + diff --git a/src/Nemera.Presentation.Web/Core/Resources/Views/Admin/Plugins.fr-FR.resx b/src/Nemera.Presentation.Web/Core/Resources/Views/Admin/Plugins.fr-FR.resx index b7e3b8c6..26367ea8 100644 --- a/src/Nemera.Presentation.Web/Core/Resources/Views/Admin/Plugins.fr-FR.resx +++ b/src/Nemera.Presentation.Web/Core/Resources/Views/Admin/Plugins.fr-FR.resx @@ -165,4 +165,7 @@ Échec du téléversement + + Officiel + diff --git a/src/Nemera.Presentation.Web/Core/Resources/Views/Admin/Plugins.it-IT.resx b/src/Nemera.Presentation.Web/Core/Resources/Views/Admin/Plugins.it-IT.resx index 688bb738..8edce33d 100644 --- a/src/Nemera.Presentation.Web/Core/Resources/Views/Admin/Plugins.it-IT.resx +++ b/src/Nemera.Presentation.Web/Core/Resources/Views/Admin/Plugins.it-IT.resx @@ -165,4 +165,7 @@ Caricamento non riuscito + + Ufficiale + diff --git a/src/Nemera.Presentation.Web/Core/Resources/Views/Admin/Plugins.ja-JP.resx b/src/Nemera.Presentation.Web/Core/Resources/Views/Admin/Plugins.ja-JP.resx index 95ae8459..e2421355 100644 --- a/src/Nemera.Presentation.Web/Core/Resources/Views/Admin/Plugins.ja-JP.resx +++ b/src/Nemera.Presentation.Web/Core/Resources/Views/Admin/Plugins.ja-JP.resx @@ -165,4 +165,7 @@ アップロードに失敗しました + + 公式 + diff --git a/src/Nemera.Presentation.Web/Core/Resources/Views/Admin/Plugins.resx b/src/Nemera.Presentation.Web/Core/Resources/Views/Admin/Plugins.resx index bcb5046c..8797a403 100644 --- a/src/Nemera.Presentation.Web/Core/Resources/Views/Admin/Plugins.resx +++ b/src/Nemera.Presentation.Web/Core/Resources/Views/Admin/Plugins.resx @@ -165,4 +165,7 @@ Upload failed + + Official + diff --git a/src/Nemera.Presentation.Web/Core/Resources/Views/Admin/Plugins.ro-RO.resx b/src/Nemera.Presentation.Web/Core/Resources/Views/Admin/Plugins.ro-RO.resx index 95936b8e..0872ae4b 100644 --- a/src/Nemera.Presentation.Web/Core/Resources/Views/Admin/Plugins.ro-RO.resx +++ b/src/Nemera.Presentation.Web/Core/Resources/Views/Admin/Plugins.ro-RO.resx @@ -165,4 +165,7 @@ Încărcarea a eșuat + + Oficial + diff --git a/src/Nemera.Presentation.Web/Core/Resources/Views/Admin/Plugins.uk-UA.resx b/src/Nemera.Presentation.Web/Core/Resources/Views/Admin/Plugins.uk-UA.resx index 05d801a4..d03aa695 100644 --- a/src/Nemera.Presentation.Web/Core/Resources/Views/Admin/Plugins.uk-UA.resx +++ b/src/Nemera.Presentation.Web/Core/Resources/Views/Admin/Plugins.uk-UA.resx @@ -165,4 +165,7 @@ Не вдалося завантажити + + Офіційний + diff --git a/src/Nemera.Presentation.Web/Core/Resources/Views/Admin/Plugins.zh-CN.resx b/src/Nemera.Presentation.Web/Core/Resources/Views/Admin/Plugins.zh-CN.resx index a4310439..2491da80 100644 --- a/src/Nemera.Presentation.Web/Core/Resources/Views/Admin/Plugins.zh-CN.resx +++ b/src/Nemera.Presentation.Web/Core/Resources/Views/Admin/Plugins.zh-CN.resx @@ -165,4 +165,7 @@ 上传失败 + + 官方 + diff --git a/src/Nemera.Presentation.Web/Core/Views/Admin/Plugins.cshtml b/src/Nemera.Presentation.Web/Core/Views/Admin/Plugins.cshtml index a87b1e6b..c960b8e6 100644 --- a/src/Nemera.Presentation.Web/Core/Views/Admin/Plugins.cshtml +++ b/src/Nemera.Presentation.Web/Core/Views/Admin/Plugins.cshtml @@ -50,7 +50,14 @@ @foreach (PluginDto plugin in Model) { - @plugin.Name + + @plugin.Name + @* Only a loaded plugin can carry the Official badge; a failed plugin has no trusted binary to describe. *@ + @if (plugin.LoadStatus == PluginLoadStatus.Loaded && plugin.IsOfficial) + { + @_localizer["Official"] + } + @plugin.Author @plugin.Version @plugin.Description diff --git a/src/Nemera.Presentation.Web/Dockerfile b/src/Nemera.Presentation.Web/Dockerfile index 43ee0fa1..8af6040c 100644 --- a/src/Nemera.Presentation.Web/Dockerfile +++ b/src/Nemera.Presentation.Web/Dockerfile @@ -11,22 +11,25 @@ EXPOSE 5012 # ==== Stage 1: Build stage -FROM mcr.microsoft.com/dotnet/sdk:10.0 AS build +FROM mcr.microsoft.com/dotnet/sdk:10.0.100 AS build ARG BUILD_CONFIGURATION=Release WORKDIR /src # Restore NuGet packages (keeping this section separate from the rest of the project files allows Docker to cache the restored packages). -COPY ["AssemblyInfo_Shared.cs", "."] -COPY ["Nemera.Presentation.Web/Nemera.Presentation.Web.csproj", "Nemera.Presentation.Web/"] +COPY ["Directory.Build.props", "."] +COPY ["Directory.Packages.props", "."] +COPY ["global.json", "."] +COPY ["src/AssemblyInfo_Shared.cs", "src/"] +COPY ["src/Directory.Build.props", "src/"] +COPY ["src/Nemera.Presentation.Web/Nemera.Presentation.Web.csproj", "src/Nemera.Presentation.Web/"] -RUN dotnet restore "./Nemera.Presentation.Web/Nemera.Presentation.Web.csproj" /p:BaseOutputPath=/app/publish/ +RUN dotnet restore "./src/Nemera.Presentation.Web/Nemera.Presentation.Web.csproj" /p:BaseOutputPath=/app/publish/ # Build the project. -COPY ["Nemera.Presentation.Web/", "Nemera.Presentation.Web/"] -COPY . . -WORKDIR /src/Nemera.Presentation.Web +COPY ["src/", "src/"] +WORKDIR /src/src/Nemera.Presentation.Web RUN dotnet build "./Nemera.Presentation.Web.csproj" -c $BUILD_CONFIGURATION -o /app/build /p:BaseOutputPath=/app/publish/ @@ -43,7 +46,7 @@ FROM base AS final WORKDIR /app -COPY --from=publish /app/publish . +COPY --from=publish --chown=app:app /app/publish . # The HTTP port is controlled per run mode: launchSettings.json for local development, ASPNETCORE_HTTP_PORTS here for # Docker, and for a published DLL run directly on a host, ASPNETCORE_URLS (or ASPNETCORE_HTTP_PORTS) must be set. ENV ASPNETCORE_HTTP_PORTS=5012 @@ -51,4 +54,4 @@ EXPOSE 5012 ENTRYPOINT ["dotnet", "Nemera.Presentation.Web.dll"] # To build this Docker image, run the following command from the root of the project (location of the .slnx solution file): -# docker build --no-cache -t nemera-web -f Nemera.Presentation.Web/Dockerfile . +# docker build --no-cache -t nemera-web -f src/Nemera.Presentation.Web/Dockerfile . diff --git a/src/Nemera.Presentation.Web/Dockerfile.release b/src/Nemera.Presentation.Web/Dockerfile.release new file mode 100644 index 00000000..17e1350b --- /dev/null +++ b/src/Nemera.Presentation.Web/Dockerfile.release @@ -0,0 +1,19 @@ +# This image ships the published release artifacts, so the image contents are the same files the release workflow exported. +# Build it with the published Web directory as the context: +# docker build -t nemera-web -f src/Nemera.Presentation.Web/Dockerfile.release bin/web/publish +FROM mcr.microsoft.com/dotnet/aspnet:10.0 AS final + +# Curl is used by the container healthcheck to probe the /health endpoints. +RUN apt-get update \ + && apt-get install -y --no-install-recommends curl \ + && rm -rf /var/lib/apt/lists/* \ + && mkdir /logs && chown -R app:app /logs + +USER app +WORKDIR /app + +COPY --chown=app:app . . + +ENV ASPNETCORE_HTTP_PORTS=5012 +EXPOSE 5012 +ENTRYPOINT ["dotnet", "Nemera.Presentation.Web.dll"] diff --git a/src/Nemera.Presentation.Web/Nemera.Presentation.Web.csproj b/src/Nemera.Presentation.Web/Nemera.Presentation.Web.csproj index e057c9a7..663123fe 100644 --- a/src/Nemera.Presentation.Web/Nemera.Presentation.Web.csproj +++ b/src/Nemera.Presentation.Web/Nemera.Presentation.Web.csproj @@ -3,7 +3,7 @@ net10.0 enable disable - $(SolutionDir)..\bin\web\ + $(RepoRoot)bin/web/ false $(WarningsNotAsErrors);EXTEXP0018 10a94da9-18ed-4c70-a9da-b461e08958c4 diff --git a/src/Nemera.Presentation.Web/wwwroot/css/site.css b/src/Nemera.Presentation.Web/wwwroot/css/site.css index 88fff820..97fed65b 100644 --- a/src/Nemera.Presentation.Web/wwwroot/css/site.css +++ b/src/Nemera.Presentation.Web/wwwroot/css/site.css @@ -2516,3 +2516,17 @@ html.audio-player-initializing .audio-player-container { animation: none; } } + +/* Informational badge for a loaded bundled plugin whose binary matches the release trust list. */ +.plugin-official-badge { + display: inline-block; + margin-left: 0.4rem; + padding: 0 0.35rem; + border: 1px solid currentColor; + border-radius: 2px; + font-size: 0.7em; + line-height: 1.4; + letter-spacing: 0.05em; + text-transform: uppercase; + vertical-align: middle; +} diff --git a/src/Nemera.slnx b/src/Nemera.slnx index 7e91c260..7319ce62 100644 --- a/src/Nemera.slnx +++ b/src/Nemera.slnx @@ -31,7 +31,9 @@ - + + + @@ -359,6 +361,16 @@ + + + + + + + + + + diff --git a/src/docker-compose.dcproj b/src/docker-compose.dcproj index a54dad6c..2f96d378 100644 --- a/src/docker-compose.dcproj +++ b/src/docker-compose.dcproj @@ -6,6 +6,10 @@ False d4c61542-fc91-47fa-b1d2-11cc99617454 + + + $(RepoRoot)bin/docker-compose/$(Configuration)/ + docker-compose.yml @@ -14,6 +18,6 @@ docker-compose.yml - + - \ No newline at end of file + diff --git a/src/docker-compose.override.yml b/src/docker-compose.override.yml index 0d4c8d31..8aafc2f2 100644 --- a/src/docker-compose.override.yml +++ b/src/docker-compose.override.yml @@ -2,8 +2,8 @@ services: nemera-api: container_name: nemera-api build: - context: . - dockerfile: Nemera.Presentation.Api/Dockerfile + context: .. + dockerfile: src/Nemera.Presentation.Api/Dockerfile environment: - ASPNETCORE_ENVIRONMENT=Development - ASPNETCORE_HTTP_PORTS=5214 @@ -18,8 +18,8 @@ services: nemera-web: container_name: nemera-web build: - context: . - dockerfile: Nemera.Presentation.Web/Dockerfile + context: .. + dockerfile: src/Nemera.Presentation.Web/Dockerfile environment: - ASPNETCORE_ENVIRONMENT=Development - ASPNETCORE_HTTP_PORTS=5012 diff --git a/src/docker-compose.yml b/src/docker-compose.yml index 5ff30ac4..ebe0474f 100644 --- a/src/docker-compose.yml +++ b/src/docker-compose.yml @@ -3,8 +3,8 @@ services: container_name: nemera-api image: ${DOCKER_REGISTRY-}nemera-api build: - context: . - dockerfile: Nemera.Presentation.Api/Dockerfile + context: .. + dockerfile: src/Nemera.Presentation.Api/Dockerfile environment: - LOG_PATH=/logs - OTEL_EXPORTER_OTLP_ENDPOINT=http://otel-collector:4317 @@ -26,8 +26,8 @@ services: container_name: nemera-web image: ${DOCKER_REGISTRY-}nemera-web build: - context: . - dockerfile: Nemera.Presentation.Web/Dockerfile + context: .. + dockerfile: src/Nemera.Presentation.Web/Dockerfile environment: - LOG_PATH=/logs - OTEL_EXPORTER_OTLP_ENDPOINT=http://otel-collector:4317 diff --git a/tests/Common/Nemera.Application.Fixtures/Nemera.Application.Fixtures.csproj b/tests/Common/Nemera.Application.Fixtures/Nemera.Application.Fixtures.csproj index fce392f0..88501cb4 100644 --- a/tests/Common/Nemera.Application.Fixtures/Nemera.Application.Fixtures.csproj +++ b/tests/Common/Nemera.Application.Fixtures/Nemera.Application.Fixtures.csproj @@ -4,7 +4,6 @@ net10.0 disable enable - $(SolutionDir)..\bin\api\ false false false diff --git a/tests/Common/Nemera.Contracts.Fixtures/Core/Responses/Plugins/PluginResponseFixture.cs b/tests/Common/Nemera.Contracts.Fixtures/Core/Responses/Plugins/PluginResponseFixture.cs index 0e89f217..57398bf1 100644 --- a/tests/Common/Nemera.Contracts.Fixtures/Core/Responses/Plugins/PluginResponseFixture.cs +++ b/tests/Common/Nemera.Contracts.Fixtures/Core/Responses/Plugins/PluginResponseFixture.cs @@ -29,6 +29,7 @@ public class PluginResponseFixture /// Optional. The load status of the plugin. /// Optional. The error message when the plugin failed to load. /// Optional. The settings of the plugin. + /// Optional. Whether the plugin matches a trusted bundled plugin binary. /// The created . public PluginResponse Create( Guid? id = null, @@ -38,7 +39,8 @@ public class PluginResponseFixture string? description = null, PluginLoadStatus? loadStatus = null, string? loadError = null, - IReadOnlyDictionary? settings = null) + IReadOnlyDictionary? settings = null, + bool isOfficial = false) { return new PluginResponse( id ?? Guid.NewGuid(), @@ -51,7 +53,8 @@ public class PluginResponseFixture settings ?? new Dictionary { [_faker.Lorem.Word()] = _faker.Lorem.Word() - } + }, + isOfficial ); } diff --git a/tests/Common/Nemera.Contracts.Fixtures/Nemera.Contracts.Fixtures.csproj b/tests/Common/Nemera.Contracts.Fixtures/Nemera.Contracts.Fixtures.csproj index 911089e0..151e3711 100644 --- a/tests/Common/Nemera.Contracts.Fixtures/Nemera.Contracts.Fixtures.csproj +++ b/tests/Common/Nemera.Contracts.Fixtures/Nemera.Contracts.Fixtures.csproj @@ -4,7 +4,6 @@ net10.0 disable enable - $(SolutionDir)..\bin\api\ false false false diff --git a/tests/Common/Nemera.Domain.Fixtures/Nemera.Domain.Fixtures.csproj b/tests/Common/Nemera.Domain.Fixtures/Nemera.Domain.Fixtures.csproj index a8a09097..09ad966b 100644 --- a/tests/Common/Nemera.Domain.Fixtures/Nemera.Domain.Fixtures.csproj +++ b/tests/Common/Nemera.Domain.Fixtures/Nemera.Domain.Fixtures.csproj @@ -4,7 +4,6 @@ net10.0 disable enable - $(SolutionDir)..\bin\api\ false false false diff --git a/tests/Common/Nemera.Domain.SharedKernel.Fixtures/Nemera.Domain.SharedKernel.Fixtures.csproj b/tests/Common/Nemera.Domain.SharedKernel.Fixtures/Nemera.Domain.SharedKernel.Fixtures.csproj index 131f0d3e..0080a84d 100644 --- a/tests/Common/Nemera.Domain.SharedKernel.Fixtures/Nemera.Domain.SharedKernel.Fixtures.csproj +++ b/tests/Common/Nemera.Domain.SharedKernel.Fixtures/Nemera.Domain.SharedKernel.Fixtures.csproj @@ -4,7 +4,6 @@ net10.0 disable enable - $(SolutionDir)..\bin\api\ false false false diff --git a/tests/Common/Nemera.Infrastructure.Fixtures/Nemera.Infrastructure.Fixtures.csproj b/tests/Common/Nemera.Infrastructure.Fixtures/Nemera.Infrastructure.Fixtures.csproj index 68c7d371..2590dcdb 100644 --- a/tests/Common/Nemera.Infrastructure.Fixtures/Nemera.Infrastructure.Fixtures.csproj +++ b/tests/Common/Nemera.Infrastructure.Fixtures/Nemera.Infrastructure.Fixtures.csproj @@ -4,7 +4,6 @@ net10.0 disable enable - $(SolutionDir)..\bin\api\ false false false diff --git a/tests/Common/Nemera.Plugins.Calibre.Fixtures/Nemera.Plugins.Calibre.Fixtures.csproj b/tests/Common/Nemera.Plugins.Calibre.Fixtures/Nemera.Plugins.Calibre.Fixtures.csproj index 45e69727..414535c2 100644 --- a/tests/Common/Nemera.Plugins.Calibre.Fixtures/Nemera.Plugins.Calibre.Fixtures.csproj +++ b/tests/Common/Nemera.Plugins.Calibre.Fixtures/Nemera.Plugins.Calibre.Fixtures.csproj @@ -4,7 +4,6 @@ net10.0 disable enable - $(SolutionDir)..\bin\api\ false false false diff --git a/tests/Common/Nemera.Plugins.Contracts.Fixtures/Nemera.Plugins.Contracts.Fixtures.csproj b/tests/Common/Nemera.Plugins.Contracts.Fixtures/Nemera.Plugins.Contracts.Fixtures.csproj index 4a3688b4..dcbf0294 100644 --- a/tests/Common/Nemera.Plugins.Contracts.Fixtures/Nemera.Plugins.Contracts.Fixtures.csproj +++ b/tests/Common/Nemera.Plugins.Contracts.Fixtures/Nemera.Plugins.Contracts.Fixtures.csproj @@ -4,7 +4,6 @@ net10.0 disable enable - $(SolutionDir)..\bin\api\ false false false diff --git a/tests/Common/Nemera.Plugins.CoverArtArchive.Fixtures/Nemera.Plugins.CoverArtArchive.Fixtures.csproj b/tests/Common/Nemera.Plugins.CoverArtArchive.Fixtures/Nemera.Plugins.CoverArtArchive.Fixtures.csproj index 05aa21f3..2800bad1 100644 --- a/tests/Common/Nemera.Plugins.CoverArtArchive.Fixtures/Nemera.Plugins.CoverArtArchive.Fixtures.csproj +++ b/tests/Common/Nemera.Plugins.CoverArtArchive.Fixtures/Nemera.Plugins.CoverArtArchive.Fixtures.csproj @@ -4,7 +4,6 @@ net10.0 disable enable - $(SolutionDir)..\bin\api\ false false false diff --git a/tests/Common/Nemera.Plugins.Epub.Fixtures/Nemera.Plugins.Epub.Fixtures.csproj b/tests/Common/Nemera.Plugins.Epub.Fixtures/Nemera.Plugins.Epub.Fixtures.csproj index e619621c..d9542728 100644 --- a/tests/Common/Nemera.Plugins.Epub.Fixtures/Nemera.Plugins.Epub.Fixtures.csproj +++ b/tests/Common/Nemera.Plugins.Epub.Fixtures/Nemera.Plugins.Epub.Fixtures.csproj @@ -4,7 +4,6 @@ net10.0 disable enable - $(SolutionDir)..\bin\api\ false false false diff --git a/tests/Common/Nemera.Plugins.ID3.Fixtures/Nemera.Plugins.ID3.Fixtures.csproj b/tests/Common/Nemera.Plugins.ID3.Fixtures/Nemera.Plugins.ID3.Fixtures.csproj index a6095fd1..1c832fd7 100644 --- a/tests/Common/Nemera.Plugins.ID3.Fixtures/Nemera.Plugins.ID3.Fixtures.csproj +++ b/tests/Common/Nemera.Plugins.ID3.Fixtures/Nemera.Plugins.ID3.Fixtures.csproj @@ -4,7 +4,6 @@ net10.0 disable enable - $(SolutionDir)..\bin\api\ false false false diff --git a/tests/Common/Nemera.Plugins.LocalMusicArtwork.Fixtures/Nemera.Plugins.LocalMusicArtwork.Fixtures.csproj b/tests/Common/Nemera.Plugins.LocalMusicArtwork.Fixtures/Nemera.Plugins.LocalMusicArtwork.Fixtures.csproj index c4b35cf2..20489e32 100644 --- a/tests/Common/Nemera.Plugins.LocalMusicArtwork.Fixtures/Nemera.Plugins.LocalMusicArtwork.Fixtures.csproj +++ b/tests/Common/Nemera.Plugins.LocalMusicArtwork.Fixtures/Nemera.Plugins.LocalMusicArtwork.Fixtures.csproj @@ -4,7 +4,6 @@ net10.0 disable enable - $(SolutionDir)..\bin\api\ false false false diff --git a/tests/Common/Nemera.Plugins.MusicBrainz.Fixtures/Nemera.Plugins.MusicBrainz.Fixtures.csproj b/tests/Common/Nemera.Plugins.MusicBrainz.Fixtures/Nemera.Plugins.MusicBrainz.Fixtures.csproj index 101e7571..d480fc7f 100644 --- a/tests/Common/Nemera.Plugins.MusicBrainz.Fixtures/Nemera.Plugins.MusicBrainz.Fixtures.csproj +++ b/tests/Common/Nemera.Plugins.MusicBrainz.Fixtures/Nemera.Plugins.MusicBrainz.Fixtures.csproj @@ -4,7 +4,6 @@ net10.0 disable enable - $(SolutionDir)..\bin\api\ false false false diff --git a/tests/Common/Nemera.Plugins.OpenLibrary.Fixtures/Nemera.Plugins.OpenLibrary.Fixtures.csproj b/tests/Common/Nemera.Plugins.OpenLibrary.Fixtures/Nemera.Plugins.OpenLibrary.Fixtures.csproj index 09aeb3cf..3918461d 100644 --- a/tests/Common/Nemera.Plugins.OpenLibrary.Fixtures/Nemera.Plugins.OpenLibrary.Fixtures.csproj +++ b/tests/Common/Nemera.Plugins.OpenLibrary.Fixtures/Nemera.Plugins.OpenLibrary.Fixtures.csproj @@ -4,7 +4,6 @@ net10.0 disable enable - $(SolutionDir)..\bin\api\ false false false diff --git a/tests/Common/Nemera.Plugins.Pdf.Fixtures/Nemera.Plugins.Pdf.Fixtures.csproj b/tests/Common/Nemera.Plugins.Pdf.Fixtures/Nemera.Plugins.Pdf.Fixtures.csproj index 244b3801..55969ee1 100644 --- a/tests/Common/Nemera.Plugins.Pdf.Fixtures/Nemera.Plugins.Pdf.Fixtures.csproj +++ b/tests/Common/Nemera.Plugins.Pdf.Fixtures/Nemera.Plugins.Pdf.Fixtures.csproj @@ -4,7 +4,6 @@ net10.0 disable enable - $(SolutionDir)..\bin\api\ false false false @@ -18,7 +17,6 @@ - diff --git a/tests/Common/Nemera.Presentation.Api.Fixtures/Core/Plugins/BundledPluginFileHashFixture.cs b/tests/Common/Nemera.Presentation.Api.Fixtures/Core/Plugins/BundledPluginFileHashFixture.cs new file mode 100644 index 00000000..f2411d85 --- /dev/null +++ b/tests/Common/Nemera.Presentation.Api.Fixtures/Core/Plugins/BundledPluginFileHashFixture.cs @@ -0,0 +1,27 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Security.Cryptography; +#endregion + +namespace Nemera.Presentation.Api.Fixtures.Core.Plugins; + +/// +/// Fixture class for computing the SHA-256 checksums of bundled plugin files. +/// +[ExcludeFromCodeCoverage] +public class BundledPluginFileHashFixture +{ + /// + /// Computes the SHA-256 checksum of the file at , in the uppercase hexadecimal form the trust manifest uses. + /// + /// The path of the file to hash. + /// The uppercase hexadecimal SHA-256 checksum. + public string Create(string path) + { + // Convert.ToHexString returns uppercase hexadecimal, which is the form the trust manifest uses. + using (FileStream fileStream = new(path, FileMode.Open, FileAccess.Read, FileShare.Read)) + return Convert.ToHexString(SHA256.HashData(fileStream)); + } +} diff --git a/tests/Common/Nemera.Presentation.Api.Fixtures/Nemera.Presentation.Api.Fixtures.csproj b/tests/Common/Nemera.Presentation.Api.Fixtures/Nemera.Presentation.Api.Fixtures.csproj index 0f35defe..00751bd2 100644 --- a/tests/Common/Nemera.Presentation.Api.Fixtures/Nemera.Presentation.Api.Fixtures.csproj +++ b/tests/Common/Nemera.Presentation.Api.Fixtures/Nemera.Presentation.Api.Fixtures.csproj @@ -4,7 +4,6 @@ net10.0 disable enable - $(SolutionDir)..\bin\api\ false false false diff --git a/tests/Common/Nemera.Presentation.Web.Fixtures/Common/DTO/Plugins/PluginDtoFixture.cs b/tests/Common/Nemera.Presentation.Web.Fixtures/Common/DTO/Plugins/PluginDtoFixture.cs index 41c04126..6cebca46 100644 --- a/tests/Common/Nemera.Presentation.Web.Fixtures/Common/DTO/Plugins/PluginDtoFixture.cs +++ b/tests/Common/Nemera.Presentation.Web.Fixtures/Common/DTO/Plugins/PluginDtoFixture.cs @@ -26,8 +26,9 @@ public class PluginDtoFixture /// Optional author of the plugin. /// Optional version of the plugin. /// Optional load status of the plugin. + /// Optional. Whether the plugin matches a trusted bundled plugin binary. /// A configured instance. - public PluginDto Create(Guid? id = null, string? name = null, string? author = null, string? version = null, PluginLoadStatus? loadStatus = null) + public PluginDto Create(Guid? id = null, string? name = null, string? author = null, string? version = null, PluginLoadStatus? loadStatus = null, bool isOfficial = false) { return new PluginDto { @@ -38,7 +39,8 @@ public class PluginDtoFixture Description = _faker.Lorem.Sentence(), LoadStatus = loadStatus ?? PluginLoadStatus.Loaded, LoadError = null, - Settings = null + Settings = null, + IsOfficial = isOfficial }; } diff --git a/tests/Common/Nemera.Presentation.Web.Fixtures/Nemera.Presentation.Web.Fixtures.csproj b/tests/Common/Nemera.Presentation.Web.Fixtures/Nemera.Presentation.Web.Fixtures.csproj index 95c7daf0..5e7e6549 100644 --- a/tests/Common/Nemera.Presentation.Web.Fixtures/Nemera.Presentation.Web.Fixtures.csproj +++ b/tests/Common/Nemera.Presentation.Web.Fixtures/Nemera.Presentation.Web.Fixtures.csproj @@ -4,7 +4,6 @@ net10.0 disable enable - $(SolutionDir)..\bin\web\ false false false diff --git a/tests/Common/Nemera.TestPlugin/Nemera.TestPlugin.csproj b/tests/Common/Nemera.TestPlugin/Nemera.TestPlugin.csproj index e7baf917..9513f787 100644 --- a/tests/Common/Nemera.TestPlugin/Nemera.TestPlugin.csproj +++ b/tests/Common/Nemera.TestPlugin/Nemera.TestPlugin.csproj @@ -4,7 +4,6 @@ net10.0 disable enable - $(SolutionDir)..\bin\api\ false false false diff --git a/tests/Directory.Build.props b/tests/Directory.Build.props new file mode 100644 index 00000000..55c4e6d6 --- /dev/null +++ b/tests/Directory.Build.props @@ -0,0 +1,8 @@ + + + + + + $(RepoRoot)bin/tests/$(MSBuildProjectName)/ + + diff --git a/tests/IntegrationTests/Nemera.Infrastructure.IntegrationTests/Core/Plugins/PluginLoadContextTests.cs b/tests/IntegrationTests/Nemera.Infrastructure.IntegrationTests/Core/Plugins/PluginLoadContextTests.cs index 84363f7d..a2d5a316 100644 --- a/tests/IntegrationTests/Nemera.Infrastructure.IntegrationTests/Core/Plugins/PluginLoadContextTests.cs +++ b/tests/IntegrationTests/Nemera.Infrastructure.IntegrationTests/Core/Plugins/PluginLoadContextTests.cs @@ -19,7 +19,7 @@ public class PluginLoadContextTests { // Arrange using TemporaryPluginDirectory temporaryPluginDirectory = new(); - PluginLoadContext sut = new(temporaryPluginDirectory.Path, "test-context"); + PluginLoadContext sut = new(Path.Combine(temporaryPluginDirectory.Path, "Plugin.dll"), "test-context"); // Act Assembly result = sut.LoadFromAssemblyName(typeof(object).Assembly.GetName()); @@ -35,7 +35,7 @@ public class PluginLoadContextTests // Arrange using TemporaryPluginDirectory temporaryPluginDirectory = new(); string destinationPath = temporaryPluginDirectory.CopyDll(Path.Combine(AppContext.BaseDirectory, "Nemera.TestPlugin.dll"), "PluginLocalDependency.dll"); - PluginLoadContext sut = new(temporaryPluginDirectory.Path, "test-context"); + PluginLoadContext sut = new(destinationPath, "test-context"); MethodInfo loadMethod = typeof(PluginLoadContext).GetMethod("Load", BindingFlags.Instance | BindingFlags.NonPublic)!; // Act @@ -52,7 +52,7 @@ public class PluginLoadContextTests { // Arrange using TemporaryPluginDirectory temporaryPluginDirectory = new(); - PluginLoadContext sut = new(temporaryPluginDirectory.Path, "test-context"); + PluginLoadContext sut = new(Path.Combine(temporaryPluginDirectory.Path, "Missing.dll"), "test-context"); // Act Action act = () => sut.LoadFromAssemblyName(new AssemblyName($"Definitely.Not.Resolvable.{Guid.NewGuid()}")); diff --git a/tests/IntegrationTests/Nemera.Infrastructure.IntegrationTests/Core/Plugins/PluginLoaderTests.cs b/tests/IntegrationTests/Nemera.Infrastructure.IntegrationTests/Core/Plugins/PluginLoaderTests.cs index e9643741..38da030a 100644 --- a/tests/IntegrationTests/Nemera.Infrastructure.IntegrationTests/Core/Plugins/PluginLoaderTests.cs +++ b/tests/IntegrationTests/Nemera.Infrastructure.IntegrationTests/Core/Plugins/PluginLoaderTests.cs @@ -1,12 +1,18 @@ #region ========================================================================= USING ===================================================================================== +using Microsoft.Extensions.DependencyInjection; +using Nemera.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading; using Nemera.Infrastructure.Common.Models.DTO.Plugins; using Nemera.Infrastructure.Core.Plugins; using Nemera.Plugins.Contracts.Core.Plugins; -using Microsoft.Extensions.DependencyInjection; +using Nemera.Plugins.Contracts.Core.Reading; +using Nemera.Plugins.Pdf.Fixtures.Core.Pdf; using System; +using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.IO; -using System.Linq; +using System.Security.Cryptography; +using System.Threading; +using System.Threading.Tasks; #endregion namespace Nemera.Infrastructure.IntegrationTests.Core.Plugins; @@ -17,6 +23,46 @@ namespace Nemera.Infrastructure.IntegrationTests.Core.Plugins; [ExcludeFromCodeCoverage] public class PluginLoaderTests { + private static readonly IReadOnlyDictionary> s_emptyBundledPluginChecksums = new Dictionary>(); + + /// + /// The unique identifier of the bundled PDF plugin used by the deployed plugin loading test. + /// + private static readonly Guid s_pdfPluginId = new("c2f9b8f0-5a4b-4e3d-8b2f-7e4a9c1d3e5f"); + + [Fact] + public async Task LoadPlugins_WhenLoadingTheBundledPdfPlugin_ShouldRenderAPdfPage() + { + // Arrange + string repositoryRoot = FindRepositoryRoot(); + DirectoryInfo testOutputDirectory = new(AppContext.BaseDirectory); + string configuration = testOutputDirectory.Parent?.Name + ?? throw new InvalidOperationException("The test configuration could not be determined from the test output directory."); + string targetFramework = testOutputDirectory.Name; + string pluginsDirectory = Path.Combine(repositoryRoot, "bin", "api", configuration, targetFramework, "plugins"); + Assert.True(Directory.Exists(pluginsDirectory), $"The deployed plugins directory '{pluginsDirectory}' does not exist. Build the solution before running this test so the bundled plugins are deployed."); + using TemporaryPluginDirectory temporaryDirectory = new(); + string pdfPath = Path.Combine(temporaryDirectory.Path, "minimal.pdf"); + TestPdfFileFactory.CreateMinimalPdf(pdfPath); + IServiceCollection services = new ServiceCollection(); + + // Act + PluginLoadResultDto result = PluginLoader.LoadPlugins(pluginsDirectory, services, s_emptyBundledPluginChecksums); + using ServiceProvider serviceProvider = services.BuildServiceProvider(); + IBookReader pdfReader = serviceProvider.GetRequiredKeyedService(s_pdfPluginId); + string workingDirectory = Path.Combine(temporaryDirectory.Path, "work"); + ReadingDocumentDto document = await pdfReader.OpenAsync(pdfPath, workingDirectory, shouldRenderPdfAsImages: false, CancellationToken.None); + byte[] pageImage = await pdfReader.GetResourceAsync(pdfPath, workingDirectory, "page:1", CancellationToken.None); + + // Assert + Assert.Empty(result.Errors); + Assert.Empty(result.Warnings); + Assert.Contains(result.Plugins, plugin => plugin.Id == s_pdfPluginId); + Assert.NotEmpty(result.LoadedPlugins); + Assert.Single(document.Spine); + Assert.NotEmpty(pageImage); + } + [Fact] public void LoadPlugins_WhenDirectoryDoesNotExist_ShouldReturnNoPluginsAndNoErrors() { @@ -25,11 +71,12 @@ public class PluginLoaderTests IServiceCollection services = new ServiceCollection(); // Act - PluginLoadResultDto result = PluginLoader.LoadPlugins(nonExistentDirectory, services); + PluginLoadResultDto result = PluginLoader.LoadPlugins(nonExistentDirectory, services, s_emptyBundledPluginChecksums); // Assert Assert.Empty(result.Plugins); Assert.Empty(result.Errors); + Assert.Empty(result.LoadedPlugins); } [Fact] @@ -41,7 +88,7 @@ public class PluginLoaderTests IServiceCollection services = new ServiceCollection(); // Act - PluginLoadResultDto result = PluginLoader.LoadPlugins(temporaryPluginDirectory.Path, services); + PluginLoadResultDto result = PluginLoader.LoadPlugins(temporaryPluginDirectory.Path, services, s_emptyBundledPluginChecksums); // Assert Assert.Empty(result.Plugins); @@ -60,7 +107,7 @@ public class PluginLoaderTests IServiceCollection services = new ServiceCollection(); // Act - PluginLoadResultDto result = PluginLoader.LoadPlugins(temporaryPluginDirectory.Path, services); + PluginLoadResultDto result = PluginLoader.LoadPlugins(temporaryPluginDirectory.Path, services, s_emptyBundledPluginChecksums); // Assert Assert.Empty(result.Plugins); @@ -77,7 +124,7 @@ public class PluginLoaderTests IServiceCollection services = new ServiceCollection(); // Act - PluginLoadResultDto result = PluginLoader.LoadPlugins(temporaryPluginDirectory.Path, services); + PluginLoadResultDto result = PluginLoader.LoadPlugins(temporaryPluginDirectory.Path, services, s_emptyBundledPluginChecksums); // Assert Assert.Empty(result.Plugins); @@ -93,14 +140,16 @@ public class PluginLoaderTests IServiceCollection services = new ServiceCollection(); // Act - PluginLoadResultDto result = PluginLoader.LoadPlugins(temporaryPluginDirectory.Path, services); + PluginLoadResultDto result = PluginLoader.LoadPlugins(temporaryPluginDirectory.Path, services, s_emptyBundledPluginChecksums); // Assert IPlugin loadedPlugin = Assert.Single(result.Plugins); Assert.Empty(result.Errors); + // A plugin that is not Official is expected to come from an uploaded assembly without a dependency manifest, so the loader does not warn. + Assert.Empty(result.Warnings); Assert.Equal(Guid.Parse("7B5A3E5D-9B7F-4A1E-8D9C-2F3A4B5C6D7E"), loadedPlugin.Id); Assert.Equal("Test Plugin", loadedPlugin.Name); - Assert.Contains(services, descriptor => descriptor.ImplementationInstance as string == "plugin-services-registered"); + Assert.Contains(services, descriptor => (descriptor.ImplementationInstance as string) == "plugin-services-registered"); } [Fact] @@ -112,7 +161,7 @@ public class PluginLoaderTests IServiceCollection services = new ServiceCollection(); // Act - PluginLoadResultDto result = PluginLoader.LoadPlugins(temporaryPluginDirectory.Path, services); + PluginLoadResultDto result = PluginLoader.LoadPlugins(temporaryPluginDirectory.Path, services, s_emptyBundledPluginChecksums); // Assert Assert.Single(result.Plugins); @@ -121,6 +170,130 @@ public class PluginLoaderTests Assert.Single(result.LoadContexts); } + [Fact] + public void LoadPlugins_WhenPluginDependencyManifestIsInvalid_ShouldLoadPluginAndRecordWarning() + { + // Arrange + using TemporaryPluginDirectory temporaryPluginDirectory = new(); + temporaryPluginDirectory.CopyDll(GetTestPluginAssemblyPath()); + temporaryPluginDirectory.CreateFile("Nemera.TestPlugin.deps.json", "{ this is not a valid dependency manifest"); + IServiceCollection services = new ServiceCollection(); + + // Act + PluginLoadResultDto result = PluginLoader.LoadPlugins(temporaryPluginDirectory.Path, services, s_emptyBundledPluginChecksums); + + // Assert + Assert.Single(result.Plugins); + Assert.Empty(result.Errors); + string warning = Assert.Single(result.Warnings); + Assert.Contains("Nemera.TestPlugin.dll", warning); + Assert.Contains("dependency manifest", warning); + } + + [Fact] + public void LoadPlugins_WhenOfficialPluginHasNoDependencyManifest_ShouldLoadPluginAndRecordWarning() + { + // Arrange + using TemporaryPluginDirectory temporaryPluginDirectory = new(); + string assemblyPath = GetTestPluginAssemblyPath(); + temporaryPluginDirectory.CopyDll(assemblyPath); + IReadOnlyDictionary> bundledPluginChecksums = + CreateBundledPluginChecksums("Nemera.TestPlugin.dll", ComputeChecksum(assemblyPath)); + IServiceCollection services = new ServiceCollection(); + + // Act + PluginLoadResultDto result = PluginLoader.LoadPlugins(temporaryPluginDirectory.Path, services, bundledPluginChecksums); + + // Assert + Assert.Single(result.Plugins); + Assert.Empty(result.Errors); + string warning = Assert.Single(result.Warnings); + Assert.Contains("Nemera.TestPlugin.dll", warning); + Assert.Contains("no dependency manifest", warning); + } + + [Fact] + public void LoadPlugins_WhenBundledPluginChecksumMatches_ShouldLoadPluginAndMarkItOfficial() + { + // Arrange + using TemporaryPluginDirectory temporaryPluginDirectory = new(); + string assemblyPath = GetTestPluginAssemblyPath(); + temporaryPluginDirectory.CopyDll(assemblyPath); + IReadOnlyDictionary> bundledPluginChecksums = + CreateBundledPluginChecksums("Nemera.TestPlugin.dll", ComputeChecksum(assemblyPath)); + IServiceCollection services = new ServiceCollection(); + + // Act + PluginLoadResultDto result = PluginLoader.LoadPlugins(temporaryPluginDirectory.Path, services, bundledPluginChecksums); + + // Assert + IPlugin loadedPlugin = Assert.Single(result.Plugins); + Assert.Equal(Guid.Parse("7B5A3E5D-9B7F-4A1E-8D9C-2F3A4B5C6D7E"), loadedPlugin.Id); + Assert.Empty(result.Errors); + LoadedPluginMetadataDto metadata = Assert.Single(result.LoadedPlugins); + Assert.Equal("Nemera.TestPlugin.dll", metadata.AssemblyFileName); + Assert.True(metadata.IsOfficial); + } + + [Fact] + public void LoadPlugins_WhenBundledPluginChecksumDoesNotMatch_ShouldLoadPluginWithoutMarkingItOfficial() + { + // Arrange + using TemporaryPluginDirectory temporaryPluginDirectory = new(); + temporaryPluginDirectory.CopyDll(GetTestPluginAssemblyPath()); + IReadOnlyDictionary> bundledPluginChecksums = + CreateBundledPluginChecksums("Nemera.TestPlugin.dll", new string('0', 64)); + IServiceCollection services = new ServiceCollection(); + + // Act + PluginLoadResultDto result = PluginLoader.LoadPlugins(temporaryPluginDirectory.Path, services, bundledPluginChecksums); + + // Assert + Assert.Single(result.Plugins); + Assert.Empty(result.Errors); + LoadedPluginMetadataDto metadata = Assert.Single(result.LoadedPlugins); + Assert.False(metadata.IsOfficial); + } + + [Fact] + public void LoadPlugins_WhenPluginIsNotInTheBundledManifest_ShouldLoadPluginWithoutMarkingItOfficial() + { + // Arrange + using TemporaryPluginDirectory temporaryPluginDirectory = new(); + temporaryPluginDirectory.CopyDll(GetTestPluginAssemblyPath()); + IServiceCollection services = new ServiceCollection(); + + // Act + PluginLoadResultDto result = PluginLoader.LoadPlugins(temporaryPluginDirectory.Path, services, s_emptyBundledPluginChecksums); + + // Assert + Assert.Single(result.Plugins); + Assert.Empty(result.Errors); + LoadedPluginMetadataDto metadata = Assert.Single(result.LoadedPlugins); + Assert.False(metadata.IsOfficial); + } + + [Fact] + public void LoadPlugins_WhenBundledManifestListsMultipleChecksums_ShouldMarkTheMatchingOneOfficial() + { + // Arrange + using TemporaryPluginDirectory temporaryPluginDirectory = new(); + string assemblyPath = GetTestPluginAssemblyPath(); + temporaryPluginDirectory.CopyDll(assemblyPath); + IReadOnlyDictionary> bundledPluginChecksums = + CreateBundledPluginChecksums("Nemera.TestPlugin.dll", new string('0', 64), ComputeChecksum(assemblyPath)); + IServiceCollection services = new ServiceCollection(); + + // Act + PluginLoadResultDto result = PluginLoader.LoadPlugins(temporaryPluginDirectory.Path, services, bundledPluginChecksums); + + // Assert + Assert.Single(result.Plugins); + Assert.Empty(result.Errors); + LoadedPluginMetadataDto metadata = Assert.Single(result.LoadedPlugins); + Assert.True(metadata.IsOfficial); + } + [Fact] public void LoadPlugins_WhenDirectoryContainsManagedDependencyAssemblyAlongsideAPlugin_ShouldSkipTheDependencyAndLoadOnlyThePlugin() { @@ -134,7 +307,7 @@ public class PluginLoaderTests IServiceCollection services = new ServiceCollection(); // Act - PluginLoadResultDto result = PluginLoader.LoadPlugins(temporaryPluginDirectory.Path, services); + PluginLoadResultDto result = PluginLoader.LoadPlugins(temporaryPluginDirectory.Path, services, s_emptyBundledPluginChecksums); // Assert IPlugin loadedPlugin = Assert.Single(result.Plugins); @@ -154,7 +327,7 @@ public class PluginLoaderTests IServiceCollection services = new ServiceCollection(); // Act - PluginLoadResultDto result = PluginLoader.LoadPlugins(temporaryPluginDirectory.Path, services); + PluginLoadResultDto result = PluginLoader.LoadPlugins(temporaryPluginDirectory.Path, services, s_emptyBundledPluginChecksums); // Assert Assert.Empty(result.Plugins); @@ -173,7 +346,7 @@ public class PluginLoaderTests IServiceCollection services = new ServiceCollection(); // Act - PluginLoadResultDto result = PluginLoader.LoadPlugins(temporaryPluginDirectory.Path, services); + PluginLoadResultDto result = PluginLoader.LoadPlugins(temporaryPluginDirectory.Path, services, s_emptyBundledPluginChecksums); // Assert Assert.Empty(result.Plugins); @@ -192,7 +365,7 @@ public class PluginLoaderTests IServiceCollection services = new ServiceCollection(); // Act - PluginLoadResultDto result = PluginLoader.LoadPlugins(temporaryPluginDirectory.Path, services); + PluginLoadResultDto result = PluginLoader.LoadPlugins(temporaryPluginDirectory.Path, services, s_emptyBundledPluginChecksums); // Assert Assert.Empty(result.Plugins); @@ -224,6 +397,47 @@ public class PluginLoaderTests return Path.Combine(AppContext.BaseDirectory, "Microsoft.AspNetCore.SignalR.Core.dll"); } + /// + /// Creates a bundled plugin trust list containing one assembly with the provided checksums. + /// + /// The file name of the bundled plugin assembly. + /// The checksums the assembly is allowed to have. + /// The bundled plugin trust list. + private static IReadOnlyDictionary> CreateBundledPluginChecksums(string assemblyFileName, params string[] checksums) + { + return new Dictionary>(StringComparer.OrdinalIgnoreCase) + { + [assemblyFileName] = new HashSet(checksums, StringComparer.OrdinalIgnoreCase) + }; + } + + /// + /// Computes the SHA-256 checksum of the file at , in the hexadecimal form the bundled plugin trust manifest uses. + /// + /// The path of the file to hash. + /// The uppercase hexadecimal SHA-256 checksum. + private static string ComputeChecksum(string path) + { + using (FileStream fileStream = new(path, FileMode.Open, FileAccess.Read, FileShare.Read)) + return Convert.ToHexString(SHA256.HashData(fileStream)); + } + + /// + /// Locates the repository root from the test output directory. + /// + /// The absolute path of the repository root. + private static string FindRepositoryRoot() + { + DirectoryInfo? directory = new(AppContext.BaseDirectory); + while (directory is not null) + { + if (File.Exists(Path.Combine(directory.FullName, "src", "Nemera.slnx"))) + return directory.FullName; + directory = directory.Parent; + } + throw new InvalidOperationException("The repository root could not be located from the test output directory."); + } + /// /// Test helper managing a temporary plugins directory, deleted when the test finishes. /// diff --git a/tests/IntegrationTests/Nemera.Infrastructure.IntegrationTests/Nemera.Infrastructure.IntegrationTests.csproj b/tests/IntegrationTests/Nemera.Infrastructure.IntegrationTests/Nemera.Infrastructure.IntegrationTests.csproj index 39797329..6e411380 100644 --- a/tests/IntegrationTests/Nemera.Infrastructure.IntegrationTests/Nemera.Infrastructure.IntegrationTests.csproj +++ b/tests/IntegrationTests/Nemera.Infrastructure.IntegrationTests/Nemera.Infrastructure.IntegrationTests.csproj @@ -44,6 +44,7 @@ + diff --git a/tests/IntegrationTests/Nemera.Presentation.Api.IntegrationTests/Common/Setup/BundledPluginManifestTestPaths.cs b/tests/IntegrationTests/Nemera.Presentation.Api.IntegrationTests/Common/Setup/BundledPluginManifestTestPaths.cs new file mode 100644 index 00000000..48b3468a --- /dev/null +++ b/tests/IntegrationTests/Nemera.Presentation.Api.IntegrationTests/Common/Setup/BundledPluginManifestTestPaths.cs @@ -0,0 +1,190 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics.CodeAnalysis; +using System.IO; +#endregion + +namespace Nemera.Presentation.Api.IntegrationTests.Common.Setup; + +/// +/// Locates the files and directories used by the bundled plugin manifest tests. +/// +/// +/// The tests run from a configuration and target framework folder under bin/tests, so the repository root is found by walking up to the solution instead of hardcoding a machine-specific path. +/// +[ExcludeFromCodeCoverage] +public static class BundledPluginManifestTestPaths +{ + /// + /// The name of the directory that holds the build scripts. + /// + public const string BUILD_DIRECTORY_NAME = "build"; + + /// + /// The name of the directory that holds the build outputs. + /// + public const string BIN_DIRECTORY_NAME = "bin"; + + /// + /// The name of the directory that holds the solution. + /// + public const string SOLUTION_DIRECTORY_NAME = "src"; + + /// + /// The file name of the solution. + /// + public const string SOLUTION_FILE_NAME = "Nemera.slnx"; + + /// + /// The name of the append-only bundled plugin trust manifest. + /// + public const string BUNDLED_PLUGINS_MANIFEST_FILE_NAME = "BundledPlugins.manifest"; + + /// + /// The name of the bundled plugin revocation manifest. + /// + public const string BUNDLED_PLUGINS_DENY_MANIFEST_FILE_NAME = "BundledPlugins.deny.manifest"; + + /// + /// The name of the bundled plugin release catalog. + /// + public const string BUNDLED_PLUGINS_PROPS_FILE_NAME = "BundledPlugins.props"; + + /// + /// The name of the directory that holds the plugin projects. + /// + public const string PLUGINS_PROJECT_DIRECTORY_NAME = "plugins"; + + /// + /// The name of the API output directory under the repository bin directory. + /// + public const string API_OUTPUT_DIRECTORY_NAME = "api"; + + /// + /// The name of the directory that holds the deployed plugin assemblies. + /// + public const string PLUGINS_DIRECTORY_NAME = "plugins"; + + /// + /// The file name of the published API assembly. + /// + public const string PUBLISHED_API_ASSEMBLY_FILE_NAME = "Nemera.Presentation.Api.dll"; + + /// + /// The search pattern of the bundled plugin assemblies. + /// + public const string PLUGIN_ASSEMBLY_SEARCH_PATTERN = "Nemera.Plugins.*.dll"; + + /// + /// The search pattern of the plugin project files. + /// + public const string PLUGIN_PROJECT_SEARCH_PATTERN = "*.csproj"; + + /// + /// The extension of the bundled plugin assemblies. + /// + public const string PLUGIN_ASSEMBLY_EXTENSION = ".dll"; + + /// + /// Locates the repository root from the test output directory. + /// + /// The absolute path of the repository root. + public static string GetRepositoryRoot() + { + // Walk up from the test output directory until the solution file is found. This works regardless of how many folders the output is nested under bin. + DirectoryInfo? directory = new(AppContext.BaseDirectory); + while (directory is not null) + { + if (File.Exists(Path.Combine(directory.FullName, SOLUTION_DIRECTORY_NAME, SOLUTION_FILE_NAME))) + return directory.FullName; + directory = directory.Parent; + } + throw new InvalidOperationException("The repository root could not be located from the test output directory."); + } + + /// + /// Locates the append-only bundled plugin trust manifest. + /// + /// The absolute path of the repository root. + /// The absolute path of the trust manifest. + public static string GetBundledPluginsManifestPath(string repositoryRoot) + { + return Path.Combine(repositoryRoot, BUILD_DIRECTORY_NAME, BUNDLED_PLUGINS_MANIFEST_FILE_NAME); + } + + /// + /// Locates the bundled plugin revocation manifest. + /// + /// The absolute path of the repository root. + /// The absolute path of the revocation manifest. + public static string GetBundledPluginsDenyManifestPath(string repositoryRoot) + { + return Path.Combine(repositoryRoot, BUILD_DIRECTORY_NAME, BUNDLED_PLUGINS_DENY_MANIFEST_FILE_NAME); + } + + /// + /// Locates the bundled plugin release catalog. + /// + /// The absolute path of the repository root. + /// The absolute path of the release catalog. + public static string GetBundledPluginsPropsPath(string repositoryRoot) + { + return Path.Combine(repositoryRoot, BUILD_DIRECTORY_NAME, BUNDLED_PLUGINS_PROPS_FILE_NAME); + } + + /// + /// Locates the solution file. + /// + /// The absolute path of the repository root. + /// The absolute path of the solution file. + public static string GetSolutionPath(string repositoryRoot) + { + return Path.Combine(repositoryRoot, SOLUTION_DIRECTORY_NAME, SOLUTION_FILE_NAME); + } + + /// + /// Locates the directory that holds the plugin projects. + /// + /// The absolute path of the repository root. + /// The absolute path of the plugin project directory. + public static string GetPluginsProjectDirectory(string repositoryRoot) + { + return Path.Combine(repositoryRoot, PLUGINS_PROJECT_DIRECTORY_NAME); + } + + /// + /// Locates the plugins directory of the API build output for the current test configuration. + /// + /// The absolute path of the repository root. + /// The absolute path of the deployed plugins directory, whether or not it exists. + public static string GetDeployedPluginsDirectory(string repositoryRoot) + { + // The test output folder is bin/tests///, so its parent names the configuration + // and its own name is the target framework. The API output mirrors that layout under bin/api. + DirectoryInfo testOutputDirectory = new(AppContext.BaseDirectory); + string configuration = testOutputDirectory.Parent?.Name + ?? throw new InvalidOperationException("The test configuration could not be determined from the test output directory."); + string targetFramework = testOutputDirectory.Name; + return Path.Combine(repositoryRoot, BIN_DIRECTORY_NAME, API_OUTPUT_DIRECTORY_NAME, configuration, targetFramework, PLUGINS_DIRECTORY_NAME); + } + + /// + /// Locates the published API assembly in the publish output directory. + /// + /// The absolute path of the publish output directory. + /// The absolute path of the published API assembly. + public static string GetPublishedApiAssemblyPath(string publishDirectory) + { + return Path.Combine(publishDirectory, PUBLISHED_API_ASSEMBLY_FILE_NAME); + } + + /// + /// Locates the published plugins directory in the publish output directory. + /// + /// The absolute path of the publish output directory. + /// The absolute path of the published plugins directory. + public static string GetPublishedPluginsDirectory(string publishDirectory) + { + return Path.Combine(publishDirectory, PLUGINS_DIRECTORY_NAME); + } +} diff --git a/tests/IntegrationTests/Nemera.Presentation.Api.IntegrationTests/Common/Setup/DeployedBundledPluginsFactAttribute.cs b/tests/IntegrationTests/Nemera.Presentation.Api.IntegrationTests/Common/Setup/DeployedBundledPluginsFactAttribute.cs new file mode 100644 index 00000000..22841932 --- /dev/null +++ b/tests/IntegrationTests/Nemera.Presentation.Api.IntegrationTests/Common/Setup/DeployedBundledPluginsFactAttribute.cs @@ -0,0 +1,47 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Linq; +using Xunit; +#endregion + +namespace Nemera.Presentation.Api.IntegrationTests.Common.Setup; + +/// +/// Marks a test that only runs when the API assembly was produced by an official release build and the deployed bundled plugins are present. +/// +[AttributeUsage(AttributeTargets.Method)] +[ExcludeFromCodeCoverage] +public sealed class DeployedBundledPluginsFactAttribute : FactAttribute +{ + /// + /// Gets the reason to skip the test. If set, the test will be skipped instead of executed. + /// + public override string Skip + { + get + { + // xUnit evaluates Skip during discovery. Missing deployed plugins mean the solution was not built, which is normal locally, + // so the test is skipped with a reason instead of failing. + if (!OfficialReleaseBuildDetector.IsOfficialReleaseBuild()) + return "The API assembly was not produced by an official release build."; + try + { + string repositoryRoot = BundledPluginManifestTestPaths.GetRepositoryRoot(); + string pluginsDirectory = BundledPluginManifestTestPaths.GetDeployedPluginsDirectory(repositoryRoot); + // The deployed folder is produced by the solution build. If it is missing or empty there is no artifact to verify, + // so the test is skipped and the reason points at the path that was expected. + if (!Directory.Exists(pluginsDirectory)) + return $"The deployed bundled plugins directory '{pluginsDirectory}' does not exist."; + if (!Directory.EnumerateFiles(pluginsDirectory, BundledPluginManifestTestPaths.PLUGIN_ASSEMBLY_SEARCH_PATTERN).Any()) + return $"The deployed bundled plugins directory '{pluginsDirectory}' does not contain any bundled plugin assemblies."; + return string.Empty; + } + catch (InvalidOperationException exception) + { + return exception.Message; + } + } + } +} diff --git a/tests/IntegrationTests/Nemera.Presentation.Api.IntegrationTests/Common/Setup/EnvironmentVariableFactAttribute.cs b/tests/IntegrationTests/Nemera.Presentation.Api.IntegrationTests/Common/Setup/EnvironmentVariableFactAttribute.cs new file mode 100644 index 00000000..ee4676c2 --- /dev/null +++ b/tests/IntegrationTests/Nemera.Presentation.Api.IntegrationTests/Common/Setup/EnvironmentVariableFactAttribute.cs @@ -0,0 +1,42 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics.CodeAnalysis; +using Xunit; +#endregion + +namespace Nemera.Presentation.Api.IntegrationTests.Common.Setup; + +/// +/// Marks a test that only runs when the named environment variable is set. +/// +[AttributeUsage(AttributeTargets.Method)] +[ExcludeFromCodeCoverage] +public sealed class EnvironmentVariableFactAttribute : FactAttribute +{ + /// + /// The name of the environment variable that must be set for the test to run. + /// + /// + /// The name is stored because Skip is evaluated later, during test discovery. + /// + private readonly string _environmentVariableName; + + /// + /// Initializes a new instance of the class. + /// + /// The name of the environment variable that must be set for the test to run. + public EnvironmentVariableFactAttribute(string environmentVariableName) + { + _environmentVariableName = environmentVariableName; + } + + /// + /// Gets the reason to skip the test. If set, the test will be skipped instead of executed. + /// + /// + /// The published-artifact verification is opt-in: build/build.proj sets the variable only when it checks a publish output. Without it, the test would inspect a directory that does not exist, so it is skipped with a reason instead. + /// + public override string Skip => string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable(_environmentVariableName)) + ? $"The environment variable '{_environmentVariableName}' is not set." + : string.Empty; +} diff --git a/tests/IntegrationTests/Nemera.Presentation.Api.IntegrationTests/Common/Setup/OfficialReleaseBuildDetector.cs b/tests/IntegrationTests/Nemera.Presentation.Api.IntegrationTests/Common/Setup/OfficialReleaseBuildDetector.cs new file mode 100644 index 00000000..82e03fda --- /dev/null +++ b/tests/IntegrationTests/Nemera.Presentation.Api.IntegrationTests/Common/Setup/OfficialReleaseBuildDetector.cs @@ -0,0 +1,28 @@ +#region ========================================================================= USING ===================================================================================== +using Nemera.Presentation.Api; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Reflection; +#endregion + +namespace Nemera.Presentation.Api.IntegrationTests.Common.Setup; + +/// +/// Determines whether the API assembly was produced by an official release build. +/// +[ExcludeFromCodeCoverage] +public static class OfficialReleaseBuildDetector +{ + /// + /// Determines whether the API assembly was produced by an official release build. + /// + /// when the assembly carries the official release marker, otherwise. + public static bool IsOfficialReleaseBuild() + { + // The marker is injected by OfficialReleaseBuildAssemblyInfo.cs when the official build defines OFFICIAL_RELEASE_BUILD. + // The tests inspect Program's assembly rather than their own, because the test assembly is not the shipped API assembly. + return typeof(Program).Assembly + .GetCustomAttributes() + .Any(attribute => attribute.Key == "OfficialReleaseBuild" && attribute.Value == "true"); + } +} diff --git a/tests/IntegrationTests/Nemera.Presentation.Api.IntegrationTests/Common/Setup/OfficialReleaseFactAttribute.cs b/tests/IntegrationTests/Nemera.Presentation.Api.IntegrationTests/Common/Setup/OfficialReleaseFactAttribute.cs new file mode 100644 index 00000000..70a883ee --- /dev/null +++ b/tests/IntegrationTests/Nemera.Presentation.Api.IntegrationTests/Common/Setup/OfficialReleaseFactAttribute.cs @@ -0,0 +1,25 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics.CodeAnalysis; +using Xunit; +#endregion + +namespace Nemera.Presentation.Api.IntegrationTests.Common.Setup; + +/// +/// Marks a test that only runs when the API assembly was produced by an official release build. +/// +[AttributeUsage(AttributeTargets.Method)] +[ExcludeFromCodeCoverage] +public sealed class OfficialReleaseFactAttribute : FactAttribute +{ + /// + /// Gets the reason to skip the test. If set, the test will be skipped instead of executed. + /// + /// + /// xUnit evaluates Skip during test discovery, so the attribute decides at runtime whether the test runs. A normal test run skips official-only tests instead of failing them. + /// + public override string Skip => OfficialReleaseBuildDetector.IsOfficialReleaseBuild() + ? string.Empty + : "The API assembly was not produced by an official release build."; +} diff --git a/tests/IntegrationTests/Nemera.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/GetPlugins/GetPluginsEndpointTests.cs b/tests/IntegrationTests/Nemera.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/GetPlugins/GetPluginsEndpointTests.cs index 9e03a800..867543fa 100644 --- a/tests/IntegrationTests/Nemera.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/GetPlugins/GetPluginsEndpointTests.cs +++ b/tests/IntegrationTests/Nemera.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/GetPlugins/GetPluginsEndpointTests.cs @@ -1,14 +1,15 @@ #region ========================================================================= USING ===================================================================================== +using Microsoft.Extensions.DependencyInjection; using Nemera.Application.Common.DataAccess.Entities.Plugins; using Nemera.Application.Fixtures.Common.DataAccess.Entities.Plugins; using Nemera.DataAccess.Core.UoW; using Nemera.Domain.SharedKernel.Common.Enums.Plugins; using Nemera.Presentation.Api.Core.Endpoints.Plugins.GetPlugins; using Nemera.Presentation.Api.IntegrationTests.Common.Setup; -using Microsoft.Extensions.DependencyInjection; using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; +using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Json; @@ -66,9 +67,16 @@ public class GetPluginsEndpointTests : IClassFixture? plugins = await response.Content.ReadFromJsonAsync>(_jsonOptions); + string content = await response.Content.ReadAsStringAsync(); + List? plugins = JsonSerializer.Deserialize>(content, _jsonOptions); Assert.NotNull(plugins); Assert.Contains(plugins!, plugin => plugin.Id == pluginId && plugin.Name == "Test Plugin"); + using (JsonDocument document = JsonDocument.Parse(content)) + { + JsonElement seededPlugin = document.RootElement.EnumerateArray().Single(element => element.GetProperty("id").GetGuid() == pluginId); + Assert.True(seededPlugin.TryGetProperty("isOfficial", out JsonElement isOfficial)); + Assert.False(isOfficial.GetBoolean()); + } } [Fact] diff --git a/tests/IntegrationTests/Nemera.Presentation.Api.IntegrationTests/Core/Plugins/BundledPluginManifestReaderTests.cs b/tests/IntegrationTests/Nemera.Presentation.Api.IntegrationTests/Core/Plugins/BundledPluginManifestReaderTests.cs new file mode 100644 index 00000000..1132816f --- /dev/null +++ b/tests/IntegrationTests/Nemera.Presentation.Api.IntegrationTests/Core/Plugins/BundledPluginManifestReaderTests.cs @@ -0,0 +1,375 @@ +#region ========================================================================= USING ===================================================================================== +using Nemera.Presentation.Api.Core.Plugins; +using Nemera.Presentation.Api.Fixtures.Core.Plugins; +using Nemera.Presentation.Api.IntegrationTests.Common.Setup; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Linq; +using System.Reflection; +using System.Runtime.Loader; +using System.Xml.Linq; +#endregion + +namespace Nemera.Presentation.Api.IntegrationTests.Core.Plugins; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class BundledPluginManifestReaderTests +{ + /// + /// The resource name of the append-only trust list of previously released bundled plugin binaries. + /// + private const string HISTORICAL_MANIFEST_RESOURCE_NAME = "Nemera.Presentation.Api.BundledPlugins.historical.manifest"; + + /// + /// The resource name of the trust list generated for the current build's bundled plugin binaries. + /// + private const string CURRENT_MANIFEST_RESOURCE_NAME = "Nemera.Presentation.Api.BundledPlugins.current.manifest"; + + /// + /// The resource name of the list of bundled plugin checksums that are no longer trusted. + /// + private const string DENY_MANIFEST_RESOURCE_NAME = "Nemera.Presentation.Api.BundledPlugins.deny.manifest"; + + /// + /// The environment variable that points the published artifact verification at the publish output directory. + /// + private const string PUBLISH_DIRECTORY_ENVIRONMENT_VARIABLE = "NEMERA_API_PUBLISH_DIRECTORY"; + + /// + /// The fixture that computes the SHA-256 checksums of the bundled plugin files. + /// + private readonly BundledPluginFileHashFixture _bundledPluginFileHashFixture = new(); + + [Fact] + public void HistoricalManifest_WhenBuilt_ShouldBeEmbeddedUnchanged() + { + // Arrange + string repositoryRoot = BundledPluginManifestTestPaths.GetRepositoryRoot(); + string sourceManifestPath = BundledPluginManifestTestPaths.GetBundledPluginsManifestPath(repositoryRoot); + string sourceManifest = File.ReadAllText(sourceManifestPath); + string embeddedManifest = ReadManifestResource(HISTORICAL_MANIFEST_RESOURCE_NAME); + + // Act + // The checked-in file and the embedded copy can use different line endings, so normalize both before comparing. + string normalizedSourceManifest = NormalizeLineEndings(sourceManifest); + string normalizedEmbeddedManifest = NormalizeLineEndings(embeddedManifest); + + // Assert + Assert.Equal(normalizedSourceManifest, normalizedEmbeddedManifest); + } + + [Fact] + public void DenyManifest_WhenBuilt_ShouldBeEmbeddedUnchanged() + { + // Arrange + string repositoryRoot = BundledPluginManifestTestPaths.GetRepositoryRoot(); + string sourceManifestPath = BundledPluginManifestTestPaths.GetBundledPluginsDenyManifestPath(repositoryRoot); + string sourceManifest = File.ReadAllText(sourceManifestPath); + string embeddedManifest = ReadManifestResource(DENY_MANIFEST_RESOURCE_NAME); + + // Act + // The checked-in file and the embedded copy can use different line endings, so normalize both before comparing. + string normalizedSourceManifest = NormalizeLineEndings(sourceManifest); + string normalizedEmbeddedManifest = NormalizeLineEndings(embeddedManifest); + + // Assert + Assert.Equal(normalizedSourceManifest, normalizedEmbeddedManifest); + } + + [Fact] + public void HistoricalManifest_WhenParsed_ShouldContainEveryNonCommentEntry() + { + // Arrange + string repositoryRoot = BundledPluginManifestTestPaths.GetRepositoryRoot(); + string sourceManifestPath = BundledPluginManifestTestPaths.GetBundledPluginsManifestPath(repositoryRoot); + string sourceManifest = File.ReadAllText(sourceManifestPath); + + // Act + using (FileStream manifestStream = new(sourceManifestPath, FileMode.Open, FileAccess.Read, FileShare.Read)) + { + IReadOnlyDictionary> actualChecksums = BundledPluginManifestReader.ReadExpectedChecksums(manifestStream); + + // Assert + // Every non-comment, non-blank line must produce one checksum; the count catches silently skipped entries. + Assert.Equal(CountManifestEntries(sourceManifest), CountChecksums(actualChecksums)); + Assert.All(actualChecksums, entry => + { + Assert.False(string.IsNullOrWhiteSpace(entry.Key)); + Assert.NotEmpty(entry.Value); + }); + } + } + + [Fact] + public void DenyManifest_WhenParsedWithTheSameEntriesTrusted_ShouldRemoveEveryCheckedInEntry() + { + // Arrange + string repositoryRoot = BundledPluginManifestTestPaths.GetRepositoryRoot(); + string sourceManifestPath = BundledPluginManifestTestPaths.GetBundledPluginsDenyManifestPath(repositoryRoot); + string sourceManifest = File.ReadAllText(sourceManifestPath); + + // Act + // Using the deny list as the trust list proves that every deny entry revokes a matching trusted entry. + using (FileStream trustStream = new(sourceManifestPath, FileMode.Open, FileAccess.Read, FileShare.Read)) + { + IReadOnlyDictionary> trustedChecksums = BundledPluginManifestReader.ReadExpectedChecksums(trustStream); + using (FileStream historicalStream = new(sourceManifestPath, FileMode.Open, FileAccess.Read, FileShare.Read)) + { + using (FileStream denyStream = new(sourceManifestPath, FileMode.Open, FileAccess.Read, FileShare.Read)) + { + IReadOnlyDictionary> remainingChecksums = BundledPluginManifestReader.ReadExpectedChecksums(historicalStream, null, denyStream); + + // Assert + Assert.Equal(CountManifestEntries(sourceManifest), CountChecksums(trustedChecksums)); + Assert.Empty(remainingChecksums); + } + } + } + } + + [Fact] + public void BundledPluginCatalog_WhenCheckedIn_ShouldMatchTheSolutionAndPluginProjects() + { + // Arrange + string repositoryRoot = BundledPluginManifestTestPaths.GetRepositoryRoot(); + string solutionPath = BundledPluginManifestTestPaths.GetSolutionPath(repositoryRoot); + string catalogPath = BundledPluginManifestTestPaths.GetBundledPluginsPropsPath(repositoryRoot); + string pluginsDirectory = BundledPluginManifestTestPaths.GetPluginsProjectDirectory(repositoryRoot); + // The solution, the release catalog and the project folders on disk must agree. Drift here means a plugin would be built or published inconsistently. + string[] solutionPluginProjects = ReadSolutionPluginProjects(solutionPath); + string[] catalogPluginProjects = ReadCatalogPluginProjects(catalogPath); + string[] diskPluginProjects = [.. Directory.EnumerateFiles(pluginsDirectory, BundledPluginManifestTestPaths.PLUGIN_PROJECT_SEARCH_PATTERN, SearchOption.AllDirectories)]; + + // Act + string[] normalizedSolutionProjects = NormalizeAndSort(solutionPluginProjects); + string[] normalizedCatalogProjects = NormalizeAndSort(catalogPluginProjects); + string[] normalizedDiskProjects = NormalizeAndSort(diskPluginProjects); + + // Assert + Assert.Equal(normalizedSolutionProjects, normalizedDiskProjects, StringComparer.OrdinalIgnoreCase); + Assert.Equal(normalizedCatalogProjects, normalizedDiskProjects, StringComparer.OrdinalIgnoreCase); + } + + [Fact] + public void CurrentManifest_WhenBuilt_ShouldBePresentOnlyForOfficialReleaseBuilds() + { + // Act + // A normal build must not embed a current manifest, otherwise it could certify its own locally built plugins. + bool hasCurrentManifest = HasManifestResource(CURRENT_MANIFEST_RESOURCE_NAME); + + // Assert + Assert.Equal(OfficialReleaseBuildDetector.IsOfficialReleaseBuild(), hasCurrentManifest); + } + + [OfficialReleaseFact] + public void CurrentManifest_WhenOfficialReleaseBuild_ShouldContainEveryBundledPluginProject() + { + // Arrange + string repositoryRoot = BundledPluginManifestTestPaths.GetRepositoryRoot(); + string pluginsProjectDirectory = BundledPluginManifestTestPaths.GetPluginsProjectDirectory(repositoryRoot); + // Every plugin project under plugins must contribute exactly one assembly hash to the current manifest. + string[] bundledPluginAssemblyNames = [.. Directory.EnumerateFiles(pluginsProjectDirectory, BundledPluginManifestTestPaths.PLUGIN_PROJECT_SEARCH_PATTERN, SearchOption.AllDirectories) + .Select(projectPath => Path.GetFileNameWithoutExtension(projectPath) + BundledPluginManifestTestPaths.PLUGIN_ASSEMBLY_EXTENSION)]; + + // Act + IReadOnlyDictionary> currentManifestEntries = ReadCurrentManifest(); + + // Assert + Assert.NotEmpty(bundledPluginAssemblyNames); + Assert.Equal(bundledPluginAssemblyNames.Length, currentManifestEntries.Count); + Assert.All(currentManifestEntries, entry => Assert.Single(entry.Value)); + foreach (string assemblyName in bundledPluginAssemblyNames) + Assert.Contains(assemblyName, currentManifestEntries.Keys, StringComparer.OrdinalIgnoreCase); + } + + [DeployedBundledPluginsFact] + public void CurrentManifest_WhenOfficialReleaseBuild_ShouldMatchTheDeployedPluginAssemblies() + { + // Arrange + string repositoryRoot = BundledPluginManifestTestPaths.GetRepositoryRoot(); + string pluginsDirectory = BundledPluginManifestTestPaths.GetDeployedPluginsDirectory(repositoryRoot); + + // Act + IReadOnlyDictionary> currentManifestEntries = ReadCurrentManifest(); + + // Assert + // The embedded hashes must describe the binaries that were actually deployed, not merely the ones that were built. + foreach (KeyValuePair> entry in currentManifestEntries) + { + string assemblyPath = Path.Combine(pluginsDirectory, entry.Key); + Assert.True(File.Exists(assemblyPath), $"The bundled plugin assembly '{entry.Key}' is missing from '{pluginsDirectory}'."); + string actualSha256 = _bundledPluginFileHashFixture.Create(assemblyPath); + string expectedSha256 = Assert.Single(entry.Value); + Assert.Equal(expectedSha256, actualSha256, ignoreCase: true); + } + } + + [EnvironmentVariableFact(PUBLISH_DIRECTORY_ENVIRONMENT_VARIABLE)] + public void PublishedBundledPluginManifest_WhenPublishDirectoryIsProvided_ShouldMatchThePublishedPluginAssemblies() + { + // Arrange + string publishDirectory = Environment.GetEnvironmentVariable(PUBLISH_DIRECTORY_ENVIRONMENT_VARIABLE) + ?? throw new InvalidOperationException($"The environment variable '{PUBLISH_DIRECTORY_ENVIRONMENT_VARIABLE}' is not set."); + string publishedApiAssemblyPath = BundledPluginManifestTestPaths.GetPublishedApiAssemblyPath(publishDirectory); + string publishedPluginsDirectory = BundledPluginManifestTestPaths.GetPublishedPluginsDirectory(publishDirectory); + // Load the published API assembly in its own context, so the test reads the exact shipped binary without loading it into the test process. + AssemblyLoadContext loadContext = new("PublishedBundledPluginManifestVerification", isCollectible: true); + try + { + Assembly publishedApiAssembly = loadContext.LoadFromAssemblyPath(publishedApiAssemblyPath); + // The published assembly must embed the current manifest. A missing resource means the official publish step did not run. + using (Stream manifestStream = publishedApiAssembly.GetManifestResourceStream(CURRENT_MANIFEST_RESOURCE_NAME) + ?? throw new InvalidOperationException("The published API assembly does not embed the current bundled plugin manifest.")) + { + // Act + IReadOnlyDictionary> publishedManifestEntries = BundledPluginManifestReader.ReadExpectedChecksums(manifestStream); + + // Assert + Assert.NotEmpty(publishedManifestEntries); + // The manifest and the published plugin folder must agree exactly: every entry has a file, and the counts match. + string[] publishedPluginAssemblyFileNames = [.. Directory.EnumerateFiles(publishedPluginsDirectory, BundledPluginManifestTestPaths.PLUGIN_ASSEMBLY_SEARCH_PATTERN) + .Select(Path.GetFileName) + .OfType()]; + Assert.Equal(publishedManifestEntries.Count, publishedPluginAssemblyFileNames.Length); + foreach (KeyValuePair> entry in publishedManifestEntries) + { + Assert.Contains(entry.Key, publishedPluginAssemblyFileNames, StringComparer.OrdinalIgnoreCase); + string publishedAssemblyPath = Path.Combine(publishedPluginsDirectory, entry.Key); + Assert.True(File.Exists(publishedAssemblyPath), $"The published plugin assembly '{entry.Key}' is missing from '{publishedPluginsDirectory}'."); + string actualSha256 = _bundledPluginFileHashFixture.Create(publishedAssemblyPath); + string expectedSha256 = Assert.Single(entry.Value); + Assert.Equal(expectedSha256, actualSha256, ignoreCase: true); + } + } + } + finally + { + // Unload the collectible context so the published assembly does not stay locked for later test runs. + loadContext.Unload(); + } + } + + /// + /// Reads the embedded current bundled plugin trust manifest through the production reader. + /// + /// A dictionary that maps each bundled plugin assembly file name to the checksums it is allowed to have. + private static IReadOnlyDictionary> ReadCurrentManifest() + { + using (Stream manifestStream = typeof(Program).Assembly.GetManifestResourceStream(CURRENT_MANIFEST_RESOURCE_NAME) + ?? throw new InvalidOperationException($"The embedded manifest resource '{CURRENT_MANIFEST_RESOURCE_NAME}' is missing.")) + return BundledPluginManifestReader.ReadExpectedChecksums(manifestStream); + } + + /// + /// Determines whether the API assembly contains the named embedded manifest resource. + /// + /// The name of the embedded manifest resource. + /// when the resource exists, otherwise. + private static bool HasManifestResource(string resourceName) + { + using (Stream? stream = typeof(Program).Assembly.GetManifestResourceStream(resourceName)) + return stream is not null; + } + + /// + /// Reads an embedded manifest resource from the API assembly. + /// + /// The name of the embedded manifest resource. + /// The text of the manifest. + private static string ReadManifestResource(string resourceName) + { + using (Stream stream = typeof(Program).Assembly.GetManifestResourceStream(resourceName) + ?? throw new InvalidOperationException($"The embedded manifest resource '{resourceName}' is missing.")) + using (StreamReader reader = new(stream)) + return reader.ReadToEnd(); + } + + /// + /// Reads the plugin project paths declared in the solution. + /// + /// The absolute path of the solution file. + /// The absolute paths of the plugin projects declared under the plugins solution folder. + private static string[] ReadSolutionPluginProjects(string solutionPath) + { + string solutionDirectory = Path.GetDirectoryName(solutionPath) + ?? throw new InvalidOperationException($"The solution directory could not be determined from '{solutionPath}'."); + // Only projects under the /plugins/ solution folder are bundled plugins. Test and fixture projects are not part of the release. + return [.. XDocument.Load(solutionPath) + .Root! + .Elements("Folder") + .Where(folder => string.Equals((string?)folder.Attribute("Name"), "/plugins/", StringComparison.Ordinal)) + .Elements("Project") + .Select(project => (string?)project.Attribute("Path")) + .OfType() + .Select(path => Path.GetFullPath(Path.Combine(solutionDirectory, path)))]; + } + + /// + /// Reads the plugin project paths declared in the bundled plugin release catalog. + /// + /// The absolute path of the release catalog. + /// The absolute paths of the bundled plugin projects. + private static string[] ReadCatalogPluginProjects(string catalogPath) + { + string catalogDirectory = Path.GetDirectoryName(catalogPath) + ?? throw new InvalidOperationException($"The catalog directory could not be determined from '{catalogPath}'."); + string msbuildThisFileDirectory = catalogDirectory + Path.DirectorySeparatorChar; + // The catalog stores MSBuild-relative paths, so expand $(MSBuildThisFileDirectory) before resolving them. + return [.. XDocument.Load(catalogPath) + .Descendants("BundledPluginProject") + .Select(project => (string?)project.Attribute("Include")) + .OfType() + .Select(path => path.Replace("$(MSBuildThisFileDirectory)", msbuildThisFileDirectory, StringComparison.Ordinal)) + .Select(path => Path.GetFullPath(path))]; + } + + /// + /// Normalizes and sorts project paths for comparison. + /// + /// The project paths to normalize. + /// The distinct, sorted project paths. + private static string[] NormalizeAndSort(IEnumerable paths) + { + // Paths are compared case-insensitively because Windows paths are case-insensitive, and the order of the items does not matter. + return [.. paths.Distinct(StringComparer.OrdinalIgnoreCase).OrderBy(path => path, StringComparer.OrdinalIgnoreCase)]; + } + + /// + /// Counts the non-comment, non-blank entries of a manifest. + /// + /// The manifest text. + /// The number of entries. + private static int CountManifestEntries(string manifest) + { + // The parser ignores comments and blank lines, so the expected count uses the same rule. + return manifest.Split('\n') + .Select(line => line.Trim()) + .Count(line => line.Length > 0 && !line.StartsWith('#')); + } + + /// + /// Counts the checksums parsed for every assembly. + /// + /// The parsed checksums. + /// The number of checksums. + private static int CountChecksums(IReadOnlyDictionary> checksums) + { + return checksums.Values.Sum(assemblyChecksums => assemblyChecksums.Count); + } + + /// + /// Normalizes the line endings of a manifest text, so the source file and the embedded copy compare identically on every platform. + /// + /// The manifest text to normalize. + /// The manifest text with LF line endings. + private static string NormalizeLineEndings(string manifest) + { + // The checked-in file can use CRLF on Windows while the embedded copy is read as text, so compare with LF endings. + return manifest.Replace("\r\n", "\n", StringComparison.Ordinal); + } +} diff --git a/tests/SecurityTests/Nemera.Presentation.Api.SecurityTests/Core/MediaLibrary/Artwork/BookArtworkServiceSecurityTests.cs b/tests/SecurityTests/Nemera.Presentation.Api.SecurityTests/Core/MediaLibrary/Artwork/BookArtworkServiceSecurityTests.cs index bdcbabf0..cae64e41 100644 --- a/tests/SecurityTests/Nemera.Presentation.Api.SecurityTests/Core/MediaLibrary/Artwork/BookArtworkServiceSecurityTests.cs +++ b/tests/SecurityTests/Nemera.Presentation.Api.SecurityTests/Core/MediaLibrary/Artwork/BookArtworkServiceSecurityTests.cs @@ -1,4 +1,7 @@ #region ========================================================================= USING ===================================================================================== +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Options; using Nemera.Application.Common.Infrastructure.Models.DTO.Configuration; using Nemera.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Artwork; using Nemera.Application.Fixtures.Common.Infrastructure.Models.DTO.Configuration; @@ -13,9 +16,6 @@ using Nemera.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.File using Nemera.Domain.Fixtures.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; using Nemera.Domain.SharedKernel.Common.Enums.PhotoLibrary; using Nemera.Infrastructure.Common.DependencyInjection; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Options; using NSubstitute; using System.Diagnostics.CodeAnalysis; using System.Net; @@ -57,7 +57,7 @@ public class BookArtworkServiceSecurityTests mockConfiguration.GetSection(Arg.Any()).Returns(Substitute.For()); ServiceCollection services = new(); - services.AddInfrastructureLayerServices(mockConfiguration); + services.AddInfrastructureLayerServices(mockConfiguration, new Dictionary>()); services.AddScoped(_ => mockEnvironmentContext); // The real path service is used, so that the sanitization of hostile segment names is exercised. services.AddScoped(_ => CreateRealPathService()); diff --git a/tests/UnitTests/Nemera.Application.UnitTests/Common/Mapping/Plugins/PluginEntityMappingTests.cs b/tests/UnitTests/Nemera.Application.UnitTests/Common/Mapping/Plugins/PluginEntityMappingTests.cs index 745ec6b2..6ca9d3f8 100644 --- a/tests/UnitTests/Nemera.Application.UnitTests/Common/Mapping/Plugins/PluginEntityMappingTests.cs +++ b/tests/UnitTests/Nemera.Application.UnitTests/Common/Mapping/Plugins/PluginEntityMappingTests.cs @@ -26,7 +26,7 @@ public class PluginEntityMappingTests IReadOnlyDictionary? expectedSettings = JsonSerializer.Deserialize>(entity.SettingsJson!); // Act - PluginResponse result = entity.ToResponse(); + PluginResponse result = entity.ToResponse(isOfficial: true); // Assert Assert.NotNull(result); @@ -38,6 +38,20 @@ public class PluginEntityMappingTests Assert.Equal(entity.LoadStatus, result.LoadStatus); Assert.Equal(entity.LoadError, result.LoadError); Assert.Equal(expectedSettings, result.Settings); + Assert.True(result.IsOfficial); + } + + [Fact] + public void ToResponse_WhenPluginIsNotOfficial_ShouldSetIsOfficialFalse() + { + // Arrange + PluginEntity entity = _pluginEntityFixture.Create(); + + // Act + PluginResponse result = entity.ToResponse(isOfficial: false); + + // Assert + Assert.False(result.IsOfficial); } [Fact] diff --git a/tests/UnitTests/Nemera.Application.UnitTests/Core/Plugins/Queries/GetPlugins/GetPluginsQueryHandlerTests.cs b/tests/UnitTests/Nemera.Application.UnitTests/Core/Plugins/Queries/GetPlugins/GetPluginsQueryHandlerTests.cs index 958ecc9e..f0579c54 100644 --- a/tests/UnitTests/Nemera.Application.UnitTests/Core/Plugins/Queries/GetPlugins/GetPluginsQueryHandlerTests.cs +++ b/tests/UnitTests/Nemera.Application.UnitTests/Core/Plugins/Queries/GetPlugins/GetPluginsQueryHandlerTests.cs @@ -3,7 +3,7 @@ using Nemera.Application.Common.DataAccess.Entities.Plugins; using Nemera.Application.Common.DataAccess.Repositories.Plugins; using Nemera.Application.Common.DataAccess.UoW; using Nemera.Application.Common.DTO.Filtering; -using Nemera.Application.Common.DTO.Pagination; +using Nemera.Application.Common.Infrastructure.Plugins; using Nemera.Application.Core.Plugins.Queries.GetPlugins; using Nemera.Application.Fixtures.Common.DataAccess.Entities.Plugins; using Nemera.Application.Fixtures.Common.DTO.Pagination; @@ -27,6 +27,7 @@ public class GetPluginsQueryHandlerTests { private readonly IUnitOfWork _mockUnitOfWork; private readonly IPluginRepository _mockPluginRepository; + private readonly IPluginManager _mockPluginManager; private readonly GetPluginsQueryHandler _sut; private readonly GetPluginsQueryFixture _getPluginsQueryFixture = new(); private readonly PluginEntityFixture _pluginEntityFixture = new(); @@ -41,7 +42,8 @@ public class GetPluginsQueryHandlerTests _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockPluginRepository = Substitute.For(); _mockUnitOfWork.PluginRepository.Returns(_mockPluginRepository); - _sut = new GetPluginsQueryHandler(_mockUnitOfWork); + _mockPluginManager = Substitute.For(); + _sut = new GetPluginsQueryHandler(_mockUnitOfWork, _mockPluginManager); } [Fact] @@ -62,6 +64,42 @@ public class GetPluginsQueryHandlerTests Assert.Equal(plugins[0].Id, result.Value[0].Id); } + [Fact] + public async Task HandleAsync_WhenPluginIsOfficial_ShouldReturnItAsOfficial() + { + // Arrange + PluginEntity plugin = _pluginEntityFixture.Create(); + _mockPluginRepository.GetAllAsync(cancellationToken: Arg.Any()) + .Returns(Result.From(_paginatedResultDtoFixture.Create(data: [plugin], currentPage: 1, perPage: 1, count: 1, numberOfPages: 1))); + _mockPluginManager.IsOfficial(plugin.Id).Returns(true); + + // Act + Result> result = await _sut.HandleAsync(_getPluginsQueryFixture.Create(), CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + PluginResponse response = Assert.Single(result.Value); + Assert.True(response.IsOfficial); + } + + [Fact] + public async Task HandleAsync_WhenPluginIsNotOfficial_ShouldReturnItAsNotOfficial() + { + // Arrange + PluginEntity plugin = _pluginEntityFixture.Create(); + _mockPluginRepository.GetAllAsync(cancellationToken: Arg.Any()) + .Returns(Result.From(_paginatedResultDtoFixture.Create(data: [plugin], currentPage: 1, perPage: 1, count: 1, numberOfPages: 1))); + _mockPluginManager.IsOfficial(plugin.Id).Returns(false); + + // Act + Result> result = await _sut.HandleAsync(_getPluginsQueryFixture.Create(), CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + PluginResponse response = Assert.Single(result.Value); + Assert.False(response.IsOfficial); + } + [Fact] public async Task HandleAsync_WhenRepositoryReturnsError_ShouldReturnError() { diff --git a/tests/UnitTests/Nemera.Infrastructure.UnitTests/Common/DependencyInjection/InfrastructureLayerServicesTests.cs b/tests/UnitTests/Nemera.Infrastructure.UnitTests/Common/DependencyInjection/InfrastructureLayerServicesTests.cs index a4ac4808..1c9d4625 100644 --- a/tests/UnitTests/Nemera.Infrastructure.UnitTests/Common/DependencyInjection/InfrastructureLayerServicesTests.cs +++ b/tests/UnitTests/Nemera.Infrastructure.UnitTests/Common/DependencyInjection/InfrastructureLayerServicesTests.cs @@ -1,4 +1,7 @@ #region ========================================================================= USING ===================================================================================== +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; using Nemera.Application.Common.DomainEvents; using Nemera.Application.Common.Infrastructure.Authorization.Policies.ConsumptionActivity; using Nemera.Application.Common.Infrastructure.Models.DTO.Configuration; @@ -18,9 +21,6 @@ using Nemera.Infrastructure.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback using Nemera.Infrastructure.Core.Security; using Nemera.Infrastructure.Core.Time; using Nemera.Plugins.Contracts.Core.Plugins; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Hosting; using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; @@ -35,6 +35,8 @@ namespace Nemera.Infrastructure.UnitTests.Common.DependencyInjection; [ExcludeFromCodeCoverage] public class InfrastructureLayerServicesTests { + private static readonly IReadOnlyDictionary> s_emptyBundledPluginChecksums = new Dictionary>(); + [Fact] public void AddInfrastructureLayerServices_WhenCalled_ShouldRegisterCoreInfrastructureServices() { @@ -43,7 +45,7 @@ public class InfrastructureLayerServicesTests IConfiguration configuration = CreateConfiguration(); // Act - services.AddInfrastructureLayerServices(configuration); + services.AddInfrastructureLayerServices(configuration, s_emptyBundledPluginChecksums); // Assert Assert.Contains(services, descriptor => descriptor.ServiceType == typeof(IFileHashService) && descriptor.ImplementationType == typeof(FileHashService)); @@ -68,7 +70,7 @@ public class InfrastructureLayerServicesTests IConfiguration configuration = CreateConfiguration(); // Act - services.AddInfrastructureLayerServices(configuration); + services.AddInfrastructureLayerServices(configuration, s_emptyBundledPluginChecksums); // Assert Assert.Contains(services, descriptor => descriptor.ServiceType == typeof(IValidator)); @@ -82,7 +84,7 @@ public class InfrastructureLayerServicesTests // Arrange IServiceCollection services = new ServiceCollection(); IConfiguration configuration = CreateConfiguration(); - services.AddInfrastructureLayerServices(configuration); + services.AddInfrastructureLayerServices(configuration, s_emptyBundledPluginChecksums); // A plugin registers its typed client after the infrastructure layer, so the defaults must reach it too. services.AddHttpClient("plugin-client"); using ServiceProvider serviceProvider = services.BuildServiceProvider(); diff --git a/tests/UnitTests/Nemera.Infrastructure.UnitTests/Core/Plugins/PluginDetectionSyncJobTests.cs b/tests/UnitTests/Nemera.Infrastructure.UnitTests/Core/Plugins/PluginDetectionSyncJobTests.cs index ce374bfb..48d5f848 100644 --- a/tests/UnitTests/Nemera.Infrastructure.UnitTests/Core/Plugins/PluginDetectionSyncJobTests.cs +++ b/tests/UnitTests/Nemera.Infrastructure.UnitTests/Core/Plugins/PluginDetectionSyncJobTests.cs @@ -1,11 +1,13 @@ #region ========================================================================= USING ===================================================================================== +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; using Nemera.Application.Common.DataAccess.Entities.MediaLibrary.Management; using Nemera.Application.Common.DataAccess.Entities.Plugins; using Nemera.Application.Common.DataAccess.Repositories.MediaLibrary; using Nemera.Application.Common.DataAccess.Repositories.Plugins; using Nemera.Application.Common.DataAccess.UoW; using Nemera.Application.Common.DTO.Filtering; -using Nemera.Application.Common.DTO.Pagination; using Nemera.Application.Common.Infrastructure.Plugins; using Nemera.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; using Nemera.Application.Fixtures.Common.DataAccess.Entities.Plugins; @@ -17,13 +19,9 @@ using Nemera.Infrastructure.Common.Models.DTO.Plugins; using Nemera.Infrastructure.Core.Plugins; using Nemera.Infrastructure.Fixtures.Common.Models.DTO.Plugins; using Nemera.Plugins.Contracts.Core.Plugins; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Hosting; -using Microsoft.Extensions.Logging; using NSubstitute; using System; using System.Collections.Generic; -using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Reflection; @@ -149,6 +147,26 @@ public class PluginDetectionSyncJobTests Arg.Any>()); } + [Fact] + public async Task StartAsync_WhenWarningsExist_ShouldLogThemAsWarnings() + { + // Arrange + _mockLogger.IsEnabled(Arg.Any()).Returns(true); + _mockPluginManager.GetPlugins().Returns([]); + PluginDetectionSyncJob sut = CreateSut(warnings: ["The SHA-256 checksum of plugin assembly 'LockedPlugin.dll' could not be computed."]); + + // Act + await StartAndWaitForExecutionAsync(sut); + + // Assert + _mockLogger.Received(1).Log( + LogLevel.Warning, + Arg.Any(), + Arg.Is(state => state.ToString()!.Contains("Plugin warning")), + Arg.Any(), + Arg.Any>()); + } + [Fact] public async Task StartAsync_WhenNoPluginsAreLoaded_ShouldOnlySaveChanges() { @@ -287,10 +305,11 @@ public class PluginDetectionSyncJobTests /// Creates the system under test wired to the mocked dependencies. /// /// The plugin load errors to feed to the job, when any. + /// The plugin load warnings to feed to the job, when any. /// The created job instance. - private PluginDetectionSyncJob CreateSut(IReadOnlyList? loadErrors = null) + private PluginDetectionSyncJob CreateSut(IReadOnlyList? loadErrors = null, IReadOnlyList? warnings = null) { - return new PluginDetectionSyncJob(_mockServiceScopeFactory, _mockPluginManager, loadErrors ?? [], _mockLogger); + return new PluginDetectionSyncJob(_mockServiceScopeFactory, _mockPluginManager, loadErrors ?? [], warnings ?? [], _mockLogger); } /// diff --git a/tests/UnitTests/Nemera.Infrastructure.UnitTests/Core/Plugins/PluginManagerTests.cs b/tests/UnitTests/Nemera.Infrastructure.UnitTests/Core/Plugins/PluginManagerTests.cs index acfe5f67..b6e8e11a 100644 --- a/tests/UnitTests/Nemera.Infrastructure.UnitTests/Core/Plugins/PluginManagerTests.cs +++ b/tests/UnitTests/Nemera.Infrastructure.UnitTests/Core/Plugins/PluginManagerTests.cs @@ -15,16 +15,18 @@ namespace Nemera.Infrastructure.UnitTests.Core.Plugins; [ExcludeFromCodeCoverage] public class PluginManagerTests { + private PluginManager _sut = new([], [], new HashSet()); + [Fact] public void GetPlugins_WhenCalled_ShouldReturnAllLoadedPlugins() { // Arrange IPlugin firstPlugin = CreatePlugin(Guid.NewGuid(), "First Plugin"); IPlugin secondPlugin = CreatePlugin(Guid.NewGuid(), "Second Plugin"); - PluginManager sut = new([firstPlugin, secondPlugin], []); + _sut = new([firstPlugin, secondPlugin], [], new HashSet()); // Act - IReadOnlyList result = sut.GetPlugins(); + IReadOnlyList result = _sut.GetPlugins(); // Assert Assert.Equal(2, result.Count); @@ -36,10 +38,10 @@ public class PluginManagerTests public void GetPlugins_WhenNoPluginsWereLoaded_ShouldReturnEmptyList() { // Arrange - PluginManager sut = new([], []); + _sut = new([], [], new HashSet()); // Act - IReadOnlyList result = sut.GetPlugins(); + IReadOnlyList result = _sut.GetPlugins(); // Assert Assert.Empty(result); @@ -51,10 +53,10 @@ public class PluginManagerTests // Arrange Guid pluginId = Guid.NewGuid(); IPlugin expectedPlugin = CreatePlugin(pluginId, "Expected Plugin"); - PluginManager sut = new([expectedPlugin, CreatePlugin(Guid.NewGuid(), "Other Plugin")], []); + _sut = new([expectedPlugin, CreatePlugin(Guid.NewGuid(), "Other Plugin")], [], new HashSet()); // Act - IPlugin? result = sut.GetPlugin(pluginId); + IPlugin? result = _sut.GetPlugin(pluginId); // Assert Assert.Same(expectedPlugin, result); @@ -64,15 +66,43 @@ public class PluginManagerTests public void GetPlugin_WhenPluginWithIdWasNotLoaded_ShouldReturnNull() { // Arrange - PluginManager sut = new([CreatePlugin(Guid.NewGuid(), "Loaded Plugin")], []); + _sut = new([CreatePlugin(Guid.NewGuid(), "Loaded Plugin")], [], new HashSet()); // Act - IPlugin? result = sut.GetPlugin(Guid.NewGuid()); + IPlugin? result = _sut.GetPlugin(Guid.NewGuid()); // Assert Assert.Null(result); } + [Fact] + public void IsOfficial_WhenPluginIsInTheOfficialSet_ShouldReturnTrue() + { + // Arrange + Guid pluginId = Guid.NewGuid(); + _sut = new([CreatePlugin(pluginId, "Official Plugin")], [], new HashSet { pluginId }); + + // Act + bool result = _sut.IsOfficial(pluginId); + + // Assert + Assert.True(result); + } + + [Fact] + public void IsOfficial_WhenPluginIsNotInTheOfficialSet_ShouldReturnFalse() + { + // Arrange + Guid pluginId = Guid.NewGuid(); + _sut = new([CreatePlugin(pluginId, "Unofficial Plugin")], [], new HashSet()); + + // Act + bool result = _sut.IsOfficial(pluginId); + + // Assert + Assert.False(result); + } + /// /// Creates a mocked plugin with the provided identity. /// diff --git a/tests/UnitTests/Nemera.Presentation.Api.UnitTests/Core/Plugins/BundledPluginManifestReaderTests.cs b/tests/UnitTests/Nemera.Presentation.Api.UnitTests/Core/Plugins/BundledPluginManifestReaderTests.cs new file mode 100644 index 00000000..a5b4a493 --- /dev/null +++ b/tests/UnitTests/Nemera.Presentation.Api.UnitTests/Core/Plugins/BundledPluginManifestReaderTests.cs @@ -0,0 +1,241 @@ +#region ========================================================================= USING ===================================================================================== +using Nemera.Presentation.Api.Core.Plugins; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Text; +#endregion + +namespace Nemera.Presentation.Api.UnitTests.Core.Plugins; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class BundledPluginManifestReaderTests +{ + /// + /// The name of the bundled plugin assembly used by the tests. + /// + private const string ASSEMBLY_FILE_NAME = "Nemera.Plugins.Epub.dll"; + + /// + /// The name of another bundled plugin assembly used by the tests. + /// + private const string OTHER_ASSEMBLY_FILE_NAME = "Nemera.Plugins.Pdf.dll"; + + /// + /// A valid SHA-256 checksum used by the tests. + /// + private const string CHECKSUM = "0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF"; + + /// + /// Another valid SHA-256 checksum used by the tests. + /// + private const string OTHER_CHECKSUM = "FEDCBA9876543210FEDCBA9876543210FEDCBA9876543210FEDCBA9876543210"; + + [Fact] + public void ReadExpectedChecksums_WhenManifestContainsCommentsAndBlankLines_ShouldIgnoreThem() + { + // Arrange + string manifest = string.Join(Environment.NewLine, "# Bundled plugin trust list.", string.Empty, $" {ASSEMBLY_FILE_NAME} | {CHECKSUM} "); + + // Act + IReadOnlyDictionary> actualChecksums = ReadHistoricalManifest(manifest); + + // Assert + KeyValuePair> entry = Assert.Single(actualChecksums); + Assert.Equal(ASSEMBLY_FILE_NAME, entry.Key); + Assert.True(entry.Value.SetEquals([CHECKSUM])); + } + + [Fact] + public void ReadExpectedChecksums_WhenAssemblyIsListedMultipleTimes_ShouldMergeItsChecksums() + { + // Arrange + string manifest = string.Join(Environment.NewLine, + $"{ASSEMBLY_FILE_NAME}|{CHECKSUM}", + // The second line uses the uppercase spelling to prove that assembly names are merged case-insensitively. + $"{ASSEMBLY_FILE_NAME.ToUpperInvariant()}|{OTHER_CHECKSUM}"); + + // Act + IReadOnlyDictionary> actualChecksums = ReadHistoricalManifest(manifest); + + // Assert + KeyValuePair> entry = Assert.Single(actualChecksums); + Assert.Equal(ASSEMBLY_FILE_NAME, entry.Key); + Assert.True(entry.Value.SetEquals([CHECKSUM, OTHER_CHECKSUM])); + } + + [Fact] + public void ReadExpectedChecksums_WhenCurrentManifestIsProvided_ShouldMergeBothManifests() + { + // Arrange + string historicalManifest = $"{ASSEMBLY_FILE_NAME}|{CHECKSUM}"; + string currentManifest = $"{OTHER_ASSEMBLY_FILE_NAME}|{OTHER_CHECKSUM}"; + + // Act + IReadOnlyDictionary> actualChecksums = ReadManifests(historicalManifest, currentManifest); + + // Assert + Assert.Equal(2, actualChecksums.Count); + Assert.True(actualChecksums[ASSEMBLY_FILE_NAME].SetEquals([CHECKSUM])); + Assert.True(actualChecksums[OTHER_ASSEMBLY_FILE_NAME].SetEquals([OTHER_CHECKSUM])); + } + + [Fact] + public void ReadExpectedChecksums_WhenDenyManifestRevokesOneChecksum_ShouldKeepTheOther() + { + // Arrange + string historicalManifest = string.Join(Environment.NewLine, + $"{ASSEMBLY_FILE_NAME}|{CHECKSUM}", + $"{ASSEMBLY_FILE_NAME}|{OTHER_CHECKSUM}"); + string denyManifest = $"{ASSEMBLY_FILE_NAME}|{CHECKSUM}"; + + // Act + IReadOnlyDictionary> actualChecksums = ReadManifests(historicalManifest, string.Empty, denyManifest); + + // Assert + KeyValuePair> entry = Assert.Single(actualChecksums); + Assert.True(entry.Value.SetEquals([OTHER_CHECKSUM])); + } + + [Fact] + public void ReadExpectedChecksums_WhenDenyManifestRevokesEveryChecksum_ShouldRemoveTheAssembly() + { + // Arrange + string historicalManifest = $"{ASSEMBLY_FILE_NAME}|{CHECKSUM}"; + string denyManifest = $"{ASSEMBLY_FILE_NAME}|{CHECKSUM}"; + + // Act + IReadOnlyDictionary> actualChecksums = ReadManifests(historicalManifest, string.Empty, denyManifest); + + // Assert + Assert.Empty(actualChecksums); + } + + [Fact] + public void ReadExpectedChecksums_WhenDenyManifestTargetsAnotherAssembly_ShouldKeepTheTrustedAssembly() + { + // Arrange + string historicalManifest = $"{ASSEMBLY_FILE_NAME}|{CHECKSUM}"; + string denyManifest = $"{OTHER_ASSEMBLY_FILE_NAME}|{OTHER_CHECKSUM}"; + + // Act + IReadOnlyDictionary> actualChecksums = ReadManifests(historicalManifest, string.Empty, denyManifest); + + // Assert + KeyValuePair> entry = Assert.Single(actualChecksums); + Assert.Equal(ASSEMBLY_FILE_NAME, entry.Key); + Assert.True(entry.Value.SetEquals([CHECKSUM])); + } + + [Fact] + public void ReadExpectedChecksums_WhenDenyManifestRevokesACurrentManifestChecksum_ShouldRemoveIt() + { + // Arrange + string historicalManifest = $"{ASSEMBLY_FILE_NAME}|{CHECKSUM}"; + string currentManifest = $"{ASSEMBLY_FILE_NAME}|{OTHER_CHECKSUM}"; + // Revocation must apply to the current release's hashes as well as to historical ones. + string denyManifest = $"{ASSEMBLY_FILE_NAME}|{OTHER_CHECKSUM}"; + + // Act + IReadOnlyDictionary> actualChecksums = ReadManifests(historicalManifest, currentManifest, denyManifest); + + // Assert + KeyValuePair> entry = Assert.Single(actualChecksums); + Assert.True(entry.Value.SetEquals([CHECKSUM])); + } + + [Fact] + public void ReadExpectedChecksums_WhenAssemblyFileNameIsEmpty_ShouldThrowInvalidOperationException() + { + // Arrange + string manifest = $"|{CHECKSUM}"; + + // Act & Assert + InvalidOperationException exception = Assert.Throws(() => ReadHistoricalManifest(manifest)); + Assert.Contains("line 1", exception.Message); + } + + [Theory] + [InlineData(ASSEMBLY_FILE_NAME)] // Missing the separator and the checksum. + [InlineData(ASSEMBLY_FILE_NAME + "|" + CHECKSUM + "|extra")] // More than one separator. + public void ReadExpectedChecksums_WhenEntryDoesNotHaveTwoFields_ShouldThrowInvalidOperationException(string manifest) + { + // Act & Assert + InvalidOperationException exception = Assert.Throws(() => ReadHistoricalManifest(manifest)); + Assert.Contains("line 1", exception.Message); + } + + [Theory] + [InlineData(63)] // Truncated checksum. + [InlineData(65)] // Checksum with an extra character. + public void ReadExpectedChecksums_WhenChecksumDoesNotHave64Characters_ShouldThrowInvalidOperationException(int checksumLength) + { + // Arrange + string checksum = checksumLength < CHECKSUM.Length ? CHECKSUM[..checksumLength] : CHECKSUM + "0"; + string manifest = $"{ASSEMBLY_FILE_NAME}|{checksum}"; + + // Act & Assert + InvalidOperationException exception = Assert.Throws(() => ReadHistoricalManifest(manifest)); + Assert.Contains("line 1", exception.Message); + } + + [Fact] + public void ReadExpectedChecksums_WhenChecksumIsNotHexadecimal_ShouldThrowInvalidOperationException() + { + // Arrange + string checksum = new('Z', 64); + string manifest = $"{ASSEMBLY_FILE_NAME}|{checksum}"; + + // Act & Assert + InvalidOperationException exception = Assert.Throws(() => ReadHistoricalManifest(manifest)); + Assert.Contains("line 1", exception.Message); + } + + /// + /// Reads a historical trust manifest through the production reader. + /// + /// The manifest text. + /// The checksums parsed from the manifest. + private static IReadOnlyDictionary> ReadHistoricalManifest(string manifest) + { + using (MemoryStream manifestStream = CreateManifestStream(manifest)) + return BundledPluginManifestReader.ReadExpectedChecksums(manifestStream); + } + + /// + /// Reads a historical and a current trust manifest through the production reader. + /// + /// The historical manifest text. + /// The current manifest text. + /// The optional deny manifest text. + /// The checksums parsed from both manifests. + private static IReadOnlyDictionary> ReadManifests(string historicalManifest, string currentManifest, string? denyManifest = null) + { + using (MemoryStream historicalManifestStream = CreateManifestStream(historicalManifest)) + { + using (MemoryStream currentManifestStream = CreateManifestStream(currentManifest)) + { + // A null deny manifest means the test only exercises the historical and current merge. + if (denyManifest is null) + return BundledPluginManifestReader.ReadExpectedChecksums(historicalManifestStream, currentManifestStream); + using (MemoryStream denyManifestStream = CreateManifestStream(denyManifest)) + return BundledPluginManifestReader.ReadExpectedChecksums(historicalManifestStream, currentManifestStream, denyManifestStream); + } + } + } + + /// + /// Creates a stream that contains the provided trust manifest. + /// + /// The manifest text. + /// A stream over the UTF-8 encoded manifest text. + private static MemoryStream CreateManifestStream(string manifest) + { + // The production reader consumes a stream, so the tests use an in-memory UTF-8 stream instead of writing temporary files. + return new(Encoding.UTF8.GetBytes(manifest)); + } +}