diff --git a/.gitea/workflows/continuous_integration.yaml b/.gitea/workflows/continuous_integration.yaml index 8674d2a..a135c8c 100644 --- a/.gitea/workflows/continuous_integration.yaml +++ b/.gitea/workflows/continuous_integration.yaml @@ -11,6 +11,10 @@ on: description: 'Deploy to Production' type: boolean default: false + deploy_asf_test: + description: 'Deploy ASF test (Andrea Slop Fotografie)' + type: boolean + default: false pull_request: types: [opened, synchronize, reopened] push: @@ -514,3 +518,111 @@ jobs: service_name: ${{ needs.config.outputs.service_name_production }} health_check_url: ${{ needs.config.outputs.health_check_url_production }} run_db_backup: true + + # ========================================================================================== + # Andrea Slop Fotografie (ASF) test host. Deliberately SEPARATE jobs: nothing above (the + # SlpSoftware jobs, the env block, deploy-scp.yaml) is changed, a failure here never blocks the + # SlpSoftware deploy and vice versa. + # + # Everything below is switched on by ONE Gitea variable, ASF_TEST_DEPLOY_ENABLED == 'true'. + # While it is unset (or anything else) all three jobs are skipped and the pipeline behaves + # exactly as before. Secrets cannot be tested in an `if:`, hence an explicit variable; it is set + # only after the Pi and the other ASF_* variables exist. + # Runs: on every push to master (like the SlpSoftware test deploy) or manually with the + # "Deploy ASF test" box ticked. Test only: there is no production path for ASF. + # ========================================================================================== + config-asf: + if: ${{ vars.ASF_TEST_DEPLOY_ENABLED == 'true' }} + runs-on: ubuntu-latest + outputs: + deploy_path: ${{ steps.set.outputs.deploy_path }} + service_name: ${{ steps.set.outputs.service_name }} + health_check_url: ${{ steps.set.outputs.health_check_url }} + steps: + - id: set + env: + DEPLOY_PATH: ${{ vars.DEPLOY_PATH_ASF_TEST }} + SERVICE_NAME: ${{ vars.SERVICE_NAME_ASF_TEST }} + HEALTH_CHECK_URL: ${{ vars.HEALTH_CHECK_URL_ASF_TEST }} + run: | + for v in DEPLOY_PATH SERVICE_NAME HEALTH_CHECK_URL; do + if [ -z "${!v}" ]; then + echo "The Gitea variable for $v (…_ASF_TEST) is not set; set it or switch ASF_TEST_DEPLOY_ENABLED off." + exit 1 + fi + done + echo "deploy_path=$DEPLOY_PATH" >> "$GITHUB_OUTPUT" + echo "service_name=$SERVICE_NAME" >> "$GITHUB_OUTPUT" + echo "health_check_url=$HEALTH_CHECK_URL" >> "$GITHUB_OUTPUT" + + publish-asf-test: + needs: [changes, backend-build, backend-test, vulnerability-scan, frontend-build, frontend-test, frontend-lint] + # Same gate handling as publish-test (see there for why always() and explicit results), plus the + # ASF switch, and built only when it will actually be deployed. + if: | + always() && + vars.ASF_TEST_DEPLOY_ENABLED == 'true' && + needs.changes.result == 'success' && + needs.backend-build.result != 'failure' && needs.backend-build.result != 'cancelled' && + needs.backend-test.result != 'failure' && needs.backend-test.result != 'cancelled' && + needs.vulnerability-scan.result != 'failure' && needs.vulnerability-scan.result != 'cancelled' && + needs.frontend-build.result != 'failure' && needs.frontend-build.result != 'cancelled' && + needs.frontend-test.result != 'failure' && needs.frontend-test.result != 'cancelled' && + needs.frontend-lint.result != 'failure' && needs.frontend-lint.result != 'cancelled' && + (needs.changes.outputs.backend == 'true' || needs.changes.outputs.frontend == 'true') && + ((github.event_name == 'workflow_dispatch' && github.event.inputs.deploy_asf_test == 'true') || + (github.event_name == 'push' && github.ref == 'refs/heads/master')) + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-dotnet@v4 + with: + dotnet-version: ${{ env.DOTNET_VERSION }} + - uses: actions/setup-node@v3 + with: + node-version: ${{ env.NODE_VERSION }} + - uses: pnpm/action-setup@v4 + with: + version: ${{ env.PNPM_VERSION }} + + # Admin SPA with the ASF theme and Dutch as the default language. Lands in wwwroot/admin + # BEFORE dotnet publish, for the same reason as in publish-test. No Umami for the admin. + - name: Build admin frontend (ASF theme) + working-directory: frontend + env: + VITE_APP_ENV: test + VITE_APP_TITLE: Andrea Slop Fotografie + VITE_THEME: asf + VITE_DEFAULT_LANGUAGE: nl + VITE_SENTRY_DSN: ${{ vars.VITE_SENTRY_DSN_ASF }} + run: | + pnpm install --frozen-lockfile + pnpm build + mkdir -p ../src/SlpModularCms.Api.AndreaSlopFotografie/wwwroot/admin + cp -r dist/. ../src/SlpModularCms.Api.AndreaSlopFotografie/wwwroot/admin/ + + - name: Publish (ASF test) + working-directory: src/SlpModularCms.Api.AndreaSlopFotografie + run: > + dotnet publish -c Release -r ${{ env.PUBLISH_RID }} --self-contained false + -o ${{ github.workspace }}/app-asf-test + + - name: Upload publish artifact + uses: actions/upload-artifact@v3 + with: + name: app-asf-test + path: app-asf-test + retention-days: 1 + + deploy-asf-test: + needs: [publish-asf-test, config-asf] + if: vars.ASF_TEST_DEPLOY_ENABLED == 'true' && ((github.event_name == 'workflow_dispatch' && github.event.inputs.deploy_asf_test == 'true') || (github.event_name == 'push' && github.ref == 'refs/heads/master')) + uses: ./.gitea/workflows/deploy-scp.yaml + secrets: inherit + with: + artifact_name: app-asf-test + environment: test + deploy_path: ${{ needs.config-asf.outputs.deploy_path }} + service_name: ${{ needs.config-asf.outputs.service_name }} + health_check_url: ${{ needs.config-asf.outputs.health_check_url }} + run_db_backup: false diff --git a/README.md b/README.md index 7047424..0d5e758 100644 --- a/README.md +++ b/README.md @@ -6,6 +6,7 @@ Een modulaire monolith CMS gebouwd met .NET 10. - `src/SlpModularCms.Api`: De host applicatie en API shell (lokale ontwikkeling / dev-host). - `src/SlpModularCms.Api.SlpSoftware`: Tweede Client-project, de daadwerkelijk gedeployde API voor `test.slpsoftware.nl`/`slpsoftware.nl` (CI/CD-cutover vanaf `SlpModularCms.Api`). Host dezelfde modules als `SlpModularCms.Api` via dezelfde gedeelde `CmsHost`-compositie (zie hieronder), plus de `Offerings`-module. Heeft een eigen, geïsoleerde lokale ontwikkeldatabase — zie `appsettings.Development.json` in dat project. +- `src/SlpModularCms.Api.AndreaSlopFotografie`: Derde Client-project voor Andrea Slop Fotografie (testomgeving `test.andreaslop.nl`). Host alleen de modules `Identity` en `Availability` (geen `Master`, geen `Offerings`) en serveert de voorgerenderde website uit `wwwroot/web/` (`WebsiteMode.PrerenderedPages`) plus de admin met het thema `asf` op `/admin`. Lokaal op poort `5200`, eigen database (`appsettings.Development.json`). Bijbehorende tests: `SlpModularCms.Api.AndreaSlopFotografie.Tests` (de pipelinetests daarin hebben net als `Api.Tests` een bereikbare MariaDB nodig). - `src/SlpModularCms.Core`: Kern functionaliteiten, data modellen en interfaces. Bevat ook `Core/Hosting/CmsHost.cs` — de gedeelde service- en pipeline-compositie die elk Client-project (`Api`, `Api.SlpSoftware`) vanuit zijn eigen dunne `Program.cs` aanroept, zodat beide projecten niet uit elkaar kunnen groeien. - `src/SlpModularCms.Modules.*`: Onafhankelijke functionele modules. - `frontend/`: De CMS admin web-UI (Vite + React + TypeScript). Bewust buiten `src/` gehouden om de .NET solution schoon te houden. @@ -65,7 +66,7 @@ De API gebruikt een beveiligde flow voor authenticatie: ### Belangrijke NFR Details: - **CORS**: Alleen toegestane origins uit `appsettings.json → Cors:AllowedOrigins` worden geaccepteerd. De frontend moet draaien op een van deze origins. - **Cookies**: De `refreshToken` cookie is `httpOnly`, `SameSite=Strict` en heeft het pad `/api/v1/auth`. -- **Rate Limiting**: Login endpoints hebben rate limiting (Fixed window 5/min, Sliding window 20/min). +- **Rate Limiting**: Login endpoints hebben rate limiting (Fixed window 5/min, Sliding window 20/min). De limieten gelden **per clientadres**. Achter een reverse proxy is dat alleen het echte bezoekersadres als `ForwardedHeaders__KnownProxies__0` (en volgende) het IP van de proxy bevat; zonder die instelling worden `X-Forwarded-*`-headers genegeerd en delen alle bezoekers het adres van de proxy (één bucket, het gedrag van vóór deze optie). Alleen de opgegeven proxies worden vertrouwd (één hop); een onparseerbaar of wildcard-adres (`0.0.0.0`, `::`) laat de host bij **opstarten** falen. - **Error Handling**: Foutmeldingen volgen de RFC 9457 `ProblemDetails` standaard. ## Frontend Development (CMS Admin UI) @@ -89,6 +90,8 @@ De frontend leest de API-basis-URL uit een environment-variabele (zie `frontend/ ``` VITE_API_BASE_URL=http://localhost:5000 ``` +Per site kan de admin bij het bouwen een thema en standaardtaal krijgen: `VITE_THEME=asf` kiest `frontend/themes/asf/theme.css` (alleen CSS-variabelen, zelf gehoste lettertypen via `@fontsource`, plus een eigen favicon; een onbekende themanaam laat de build falen, leeg of afwezig = het standaardthema) en `VITE_DEFAULT_LANGUAGE=nl` (of `en`) bepaalt de taal zolang de gebruiker nog niets koos; een opgeslagen keuze wint altijd. + Kopieer `.env.example` naar `.env.local` en pas de waarde aan indien nodig. Optioneel kan met `VITE_ENABLE_MSW=true` de MSW-mockbackend in de browser worden ingeschakeld voor frontend-ontwikkeling zonder draaiende API. ### Vereiste backend @@ -322,6 +325,8 @@ In productie moeten gevoelige instellingen worden doorgegeven via Environment Va - `JwtSettings__Issuer` - `JwtSettings__Audience` - `MasterModule__MasterUrl` — publieke URL van deze master-instantie (alleen relevant als de Master CMS Module actief is) +- `ForwardedHeaders__KnownProxies__0`, ... — IP-adres(sen) van de reverse proxy voor deze host (optioneel; zie Rate Limiting hierboven). De proxy moet `X-Forwarded-For` en `X-Forwarded-Proto` doorgeven +- `Identity__Setup__Token` — optioneel beschermingstoken voor het aanmaken van de eerste beheerder (`POST /api/v1/Setup/owner` verwacht dan de header `X-Setup-Token`; `GET /api/v1/Setup/status` meldt `tokenRequired`). Minstens 32 willekeurige tekens; alleen-witruimte laat de host falen bij opstarten. Beide setup-endpoints vallen onder de `login`-limiter en een geweigerd token wordt gelogd als beveiligingsgebeurtenis `setup_token_rejected` (event-id 5007, nooit met het token zelf). Verwijder de variabele zodra de eerste beheerder bestaat - `Observability__SentryDsn` — leeg is een normale, ondersteunde staat: Sentry wordt dan overgeslagen en alleen console-logging blijft actief - `SecurityHeaders__AllowedScriptOrigins__0`, `SecurityHeaders__AllowedConnectOrigins__0`, ... — externe origins die de CSP van `/admin` en `/api/v1` mag toestaan (bijv. de Umami-scripthost en Sentry's ingest-endpoint). Zie `appsettings.json → SecurityHeaders` voor de volledige optiesvorm; een onbekende `PathPolicies`-policy-naam laat de applicatie bij **opstarten** falen, niet pas bij de eerste request diff --git a/SlpModularCms.sln b/SlpModularCms.sln index 5f95c28..aa999db 100644 --- a/SlpModularCms.sln +++ b/SlpModularCms.sln @@ -38,6 +38,10 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SlpModularCms.Modules.Offer EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SlpModularCms.Modules.Offerings.Tests", "src\SlpModularCms.Modules.Offerings.Tests\SlpModularCms.Modules.Offerings.Tests.csproj", "{BF1054BD-DBD7-4D78-B99A-73FDC1362EA5}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SlpModularCms.Api.AndreaSlopFotografie", "src\SlpModularCms.Api.AndreaSlopFotografie\SlpModularCms.Api.AndreaSlopFotografie.csproj", "{759EE53D-EECA-4054-A17F-4172B0EC2015}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SlpModularCms.Api.AndreaSlopFotografie.Tests", "src\SlpModularCms.Api.AndreaSlopFotografie.Tests\SlpModularCms.Api.AndreaSlopFotografie.Tests.csproj", "{DF0FDCFD-2601-4D60-A7F5-198D39DBE57B}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -60,6 +64,18 @@ Global {8A35AF71-50C0-4D5F-83CF-A0FA115B6619}.Release|x64.Build.0 = Release|Any CPU {8A35AF71-50C0-4D5F-83CF-A0FA115B6619}.Release|x86.ActiveCfg = Release|Any CPU {8A35AF71-50C0-4D5F-83CF-A0FA115B6619}.Release|x86.Build.0 = Release|Any CPU + {BCBB1ABB-6C22-4F81-BB06-D4FE81B4BED3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {BCBB1ABB-6C22-4F81-BB06-D4FE81B4BED3}.Debug|Any CPU.Build.0 = Debug|Any CPU + {BCBB1ABB-6C22-4F81-BB06-D4FE81B4BED3}.Debug|x64.ActiveCfg = Debug|Any CPU + {BCBB1ABB-6C22-4F81-BB06-D4FE81B4BED3}.Debug|x64.Build.0 = Debug|Any CPU + {BCBB1ABB-6C22-4F81-BB06-D4FE81B4BED3}.Debug|x86.ActiveCfg = Debug|Any CPU + {BCBB1ABB-6C22-4F81-BB06-D4FE81B4BED3}.Debug|x86.Build.0 = Debug|Any CPU + {BCBB1ABB-6C22-4F81-BB06-D4FE81B4BED3}.Release|Any CPU.ActiveCfg = Release|Any CPU + {BCBB1ABB-6C22-4F81-BB06-D4FE81B4BED3}.Release|Any CPU.Build.0 = Release|Any CPU + {BCBB1ABB-6C22-4F81-BB06-D4FE81B4BED3}.Release|x64.ActiveCfg = Release|Any CPU + {BCBB1ABB-6C22-4F81-BB06-D4FE81B4BED3}.Release|x64.Build.0 = Release|Any CPU + {BCBB1ABB-6C22-4F81-BB06-D4FE81B4BED3}.Release|x86.ActiveCfg = Release|Any CPU + {BCBB1ABB-6C22-4F81-BB06-D4FE81B4BED3}.Release|x86.Build.0 = Release|Any CPU {A5FD67AC-1458-4D90-90F6-B361DB938048}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {A5FD67AC-1458-4D90-90F6-B361DB938048}.Debug|Any CPU.Build.0 = Debug|Any CPU {A5FD67AC-1458-4D90-90F6-B361DB938048}.Debug|x64.ActiveCfg = Debug|Any CPU @@ -156,18 +172,6 @@ Global {D9F06019-5B34-4D94-8E74-82F378196BDE}.Release|x64.Build.0 = Release|Any CPU {D9F06019-5B34-4D94-8E74-82F378196BDE}.Release|x86.ActiveCfg = Release|Any CPU {D9F06019-5B34-4D94-8E74-82F378196BDE}.Release|x86.Build.0 = Release|Any CPU - {BCBB1ABB-6C22-4F81-BB06-D4FE81B4BED3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {BCBB1ABB-6C22-4F81-BB06-D4FE81B4BED3}.Debug|Any CPU.Build.0 = Debug|Any CPU - {BCBB1ABB-6C22-4F81-BB06-D4FE81B4BED3}.Debug|x64.ActiveCfg = Debug|Any CPU - {BCBB1ABB-6C22-4F81-BB06-D4FE81B4BED3}.Debug|x64.Build.0 = Debug|Any CPU - {BCBB1ABB-6C22-4F81-BB06-D4FE81B4BED3}.Debug|x86.ActiveCfg = Debug|Any CPU - {BCBB1ABB-6C22-4F81-BB06-D4FE81B4BED3}.Debug|x86.Build.0 = Debug|Any CPU - {BCBB1ABB-6C22-4F81-BB06-D4FE81B4BED3}.Release|Any CPU.ActiveCfg = Release|Any CPU - {BCBB1ABB-6C22-4F81-BB06-D4FE81B4BED3}.Release|Any CPU.Build.0 = Release|Any CPU - {BCBB1ABB-6C22-4F81-BB06-D4FE81B4BED3}.Release|x64.ActiveCfg = Release|Any CPU - {BCBB1ABB-6C22-4F81-BB06-D4FE81B4BED3}.Release|x64.Build.0 = Release|Any CPU - {BCBB1ABB-6C22-4F81-BB06-D4FE81B4BED3}.Release|x86.ActiveCfg = Release|Any CPU - {BCBB1ABB-6C22-4F81-BB06-D4FE81B4BED3}.Release|x86.Build.0 = Release|Any CPU {9843F0E6-6FC2-4774-B2CD-8B99AB926149}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {9843F0E6-6FC2-4774-B2CD-8B99AB926149}.Debug|Any CPU.Build.0 = Debug|Any CPU {9843F0E6-6FC2-4774-B2CD-8B99AB926149}.Debug|x64.ActiveCfg = Debug|Any CPU @@ -216,26 +220,52 @@ Global {BF1054BD-DBD7-4D78-B99A-73FDC1362EA5}.Release|x64.Build.0 = Release|Any CPU {BF1054BD-DBD7-4D78-B99A-73FDC1362EA5}.Release|x86.ActiveCfg = Release|Any CPU {BF1054BD-DBD7-4D78-B99A-73FDC1362EA5}.Release|x86.Build.0 = Release|Any CPU + {759EE53D-EECA-4054-A17F-4172B0EC2015}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {759EE53D-EECA-4054-A17F-4172B0EC2015}.Debug|Any CPU.Build.0 = Debug|Any CPU + {759EE53D-EECA-4054-A17F-4172B0EC2015}.Debug|x64.ActiveCfg = Debug|Any CPU + {759EE53D-EECA-4054-A17F-4172B0EC2015}.Debug|x64.Build.0 = Debug|Any CPU + {759EE53D-EECA-4054-A17F-4172B0EC2015}.Debug|x86.ActiveCfg = Debug|Any CPU + {759EE53D-EECA-4054-A17F-4172B0EC2015}.Debug|x86.Build.0 = Debug|Any CPU + {759EE53D-EECA-4054-A17F-4172B0EC2015}.Release|Any CPU.ActiveCfg = Release|Any CPU + {759EE53D-EECA-4054-A17F-4172B0EC2015}.Release|Any CPU.Build.0 = Release|Any CPU + {759EE53D-EECA-4054-A17F-4172B0EC2015}.Release|x64.ActiveCfg = Release|Any CPU + {759EE53D-EECA-4054-A17F-4172B0EC2015}.Release|x64.Build.0 = Release|Any CPU + {759EE53D-EECA-4054-A17F-4172B0EC2015}.Release|x86.ActiveCfg = Release|Any CPU + {759EE53D-EECA-4054-A17F-4172B0EC2015}.Release|x86.Build.0 = Release|Any CPU + {DF0FDCFD-2601-4D60-A7F5-198D39DBE57B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {DF0FDCFD-2601-4D60-A7F5-198D39DBE57B}.Debug|Any CPU.Build.0 = Debug|Any CPU + {DF0FDCFD-2601-4D60-A7F5-198D39DBE57B}.Debug|x64.ActiveCfg = Debug|Any CPU + {DF0FDCFD-2601-4D60-A7F5-198D39DBE57B}.Debug|x64.Build.0 = Debug|Any CPU + {DF0FDCFD-2601-4D60-A7F5-198D39DBE57B}.Debug|x86.ActiveCfg = Debug|Any CPU + {DF0FDCFD-2601-4D60-A7F5-198D39DBE57B}.Debug|x86.Build.0 = Debug|Any CPU + {DF0FDCFD-2601-4D60-A7F5-198D39DBE57B}.Release|Any CPU.ActiveCfg = Release|Any CPU + {DF0FDCFD-2601-4D60-A7F5-198D39DBE57B}.Release|Any CPU.Build.0 = Release|Any CPU + {DF0FDCFD-2601-4D60-A7F5-198D39DBE57B}.Release|x64.ActiveCfg = Release|Any CPU + {DF0FDCFD-2601-4D60-A7F5-198D39DBE57B}.Release|x64.Build.0 = Release|Any CPU + {DF0FDCFD-2601-4D60-A7F5-198D39DBE57B}.Release|x86.ActiveCfg = Release|Any CPU + {DF0FDCFD-2601-4D60-A7F5-198D39DBE57B}.Release|x86.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection GlobalSection(NestedProjects) = preSolution {8A35AF71-50C0-4D5F-83CF-A0FA115B6619} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B} + {BCBB1ABB-6C22-4F81-BB06-D4FE81B4BED3} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B} {A5FD67AC-1458-4D90-90F6-B361DB938048} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B} {71C6F408-CCFD-4607-A5E2-BE83C8F74217} = {2F43D186-C7D5-4AB1-B821-4D595CA2ECB3} - {30D8F44D-4B6E-4980-8D1F-29D1A64F438C} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B} {BABECABB-E664-4BC5-9B5F-F645D19F1B12} = {30D8F44D-4B6E-4980-8D1F-29D1A64F438C} - {ABAC72E0-DFA2-4E98-8A39-BDB1023861AB} = {30D8F44D-4B6E-4980-8D1F-29D1A64F438C} - {6B35C24D-B3AC-4B8C-9F5B-E0351E4C05C8} = {30D8F44D-4B6E-4980-8D1F-29D1A64F438C} - {77DF6642-7863-4D67-BAEE-217EC2D99894} = {2F43D186-C7D5-4AB1-B821-4D595CA2ECB3} {3D0192D6-6893-4295-A508-077D60D15D6E} = {77DF6642-7863-4D67-BAEE-217EC2D99894} + {ABAC72E0-DFA2-4E98-8A39-BDB1023861AB} = {30D8F44D-4B6E-4980-8D1F-29D1A64F438C} {50951BA1-EC62-49BE-86F5-1CCB76342552} = {77DF6642-7863-4D67-BAEE-217EC2D99894} + {6B35C24D-B3AC-4B8C-9F5B-E0351E4C05C8} = {30D8F44D-4B6E-4980-8D1F-29D1A64F438C} {D9F06019-5B34-4D94-8E74-82F378196BDE} = {77DF6642-7863-4D67-BAEE-217EC2D99894} - {BCBB1ABB-6C22-4F81-BB06-D4FE81B4BED3} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B} + {30D8F44D-4B6E-4980-8D1F-29D1A64F438C} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B} + {77DF6642-7863-4D67-BAEE-217EC2D99894} = {2F43D186-C7D5-4AB1-B821-4D595CA2ECB3} {9843F0E6-6FC2-4774-B2CD-8B99AB926149} = {D72703E6-B021-4360-B1EE-0E99999B5899} {623A9526-9511-4B3E-957D-0D7E7E3D782B} = {2F43D186-C7D5-4AB1-B821-4D595CA2ECB3} {43DE02A5-DD13-42D1-9BF9-434E706B8500} = {30D8F44D-4B6E-4980-8D1F-29D1A64F438C} {BF1054BD-DBD7-4D78-B99A-73FDC1362EA5} = {77DF6642-7863-4D67-BAEE-217EC2D99894} + {759EE53D-EECA-4054-A17F-4172B0EC2015} = {D72703E6-B021-4360-B1EE-0E99999B5899} + {DF0FDCFD-2601-4D60-A7F5-198D39DBE57B} = {2F43D186-C7D5-4AB1-B821-4D595CA2ECB3} EndGlobalSection EndGlobal diff --git a/frontend/.env.example b/frontend/.env.example index af74910..9c9a5e5 100644 --- a/frontend/.env.example +++ b/frontend/.env.example @@ -45,3 +45,12 @@ VITE_UMAMI_WEBSITE_ID= # VITE_API_BASE_URL=https://localhost:7223 # VITE_APP_TITLE=SlpModularCms (SlpSoftware) # and run `pnpm dev:slpsoftware` (uses --mode slpsoftware, port 5175) instead of `pnpm dev`. + +# --- Local SlpModularCms.Api.AndreaSlopFotografie dev setup (themed admin) --- +# Copy this file to `.env.asf.local` with: +# VITE_API_BASE_URL=https://localhost:7200 +# VITE_APP_TITLE=Andrea Slop Fotografie +# VITE_THEME=asf +# VITE_DEFAULT_LANGUAGE=nl +# and run `pnpm dev:asf` (uses --mode asf, port 5176). VITE_THEME selects frontend/themes/ +# (unset = the default look); VITE_DEFAULT_LANGUAGE ('nl' | 'en') applies until a user picks a language. diff --git a/frontend/package.json b/frontend/package.json index 0107569..b0f4b4e 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -7,6 +7,7 @@ "dev": "vite", "dev:slave": "vite --mode slave --port 5174", "dev:slpsoftware": "vite --mode slpsoftware --port 5175", + "dev:asf": "vite --mode asf --port 5176", "dev:all": "concurrently -n master,slave -c blue,magenta \"pnpm dev\" \"pnpm dev:slave\"", "build": "tsc -b && vite build", "lint": "eslint .", @@ -21,6 +22,8 @@ "@dnd-kit/core": "^6.3.1", "@dnd-kit/sortable": "^10.0.0", "@dnd-kit/utilities": "^3.2.2", + "@fontsource/jost": "5.3.0", + "@fontsource/marcellus": "5.3.0", "@hookform/resolvers": "^5.4.0", "@radix-ui/react-dialog": "^1.1.17", "@radix-ui/react-dropdown-menu": "^2.1.18", diff --git a/frontend/pnpm-lock.yaml b/frontend/pnpm-lock.yaml index 494d830..5c80a73 100644 --- a/frontend/pnpm-lock.yaml +++ b/frontend/pnpm-lock.yaml @@ -17,6 +17,12 @@ importers: '@dnd-kit/utilities': specifier: ^3.2.2 version: 3.2.2(react@19.2.7) + '@fontsource/jost': + specifier: 5.3.0 + version: 5.3.0 + '@fontsource/marcellus': + specifier: 5.3.0 + version: 5.3.0 '@hookform/resolvers': specifier: ^5.4.0 version: 5.4.0(react-hook-form@7.79.0(react@19.2.7)) @@ -380,6 +386,12 @@ packages: '@floating-ui/utils@0.2.11': resolution: {integrity: sha512-RiB/yIh78pcIxl6lLMG0CgBXAZ2Y0eVHqMPYugu+9U0AeT6YBeiJpf7lbdJNIugFP5SIjwNRgo4DhR1Qxi26Gg==} + '@fontsource/jost@5.3.0': + resolution: {integrity: sha512-lORv5y49hSoLVxjGb0qNuBzXvnaNYI3B94200uGPGJFei8fao6d6LLz2ziWbOZubGfZnibzuT6GVNX8fBw8WQQ==} + + '@fontsource/marcellus@5.3.0': + resolution: {integrity: sha512-cMnanjpiPIC7Rq4GXIA/Zal5WLSoDV5Mc681tMkWsWfKHXnRnLGlhuGeBnLF6HrqtFkiSdiuy4NCSPfOrz266w==} + '@hookform/resolvers@5.4.0': resolution: {integrity: sha512-EIsqr/t/qbinPIhGjMdtvutIN1Kk4uwbROE9/UQ93CAVGR7GkA7Y92+fX80OzXi/OB67jVFYwKGO1WzkxmkFZw==} peerDependencies: @@ -2626,6 +2638,10 @@ snapshots: '@floating-ui/utils@0.2.11': {} + '@fontsource/jost@5.3.0': {} + + '@fontsource/marcellus@5.3.0': {} + '@hookform/resolvers@5.4.0(react-hook-form@7.79.0(react@19.2.7))': dependencies: '@standard-schema/utils': 0.3.0 diff --git a/frontend/src/features/setup/mocks/handlers.ts b/frontend/src/features/setup/mocks/handlers.ts index 675f4e7..9ca8480 100644 --- a/frontend/src/features/setup/mocks/handlers.ts +++ b/frontend/src/features/setup/mocks/handlers.ts @@ -49,6 +49,22 @@ export const setupUninitializedHandlers = [ ), ]; +/** Override: setup requires the token; only 'correct-token' is accepted (401 otherwise, like the host). */ +export const setupTokenRequiredHandlers = [ + http.get(`${API_BASE}/api/v1/Setup/status`, () => + HttpResponse.json({ initialized: false, tokenRequired: true }), + ), + http.post(`${API_BASE}/api/v1/Setup/owner`, ({ request }) => { + if (request.headers.get('X-Setup-Token') !== 'correct-token') { + return HttpResponse.json( + { title: 'Setup token ontbreekt of is onjuist.', status: 401 }, + { status: 401 }, + ); + } + return HttpResponse.json({ message: 'System initialized' }, { status: 201 }); + }), +]; + /** Override: POST /Setup/owner returns 409 — system already initialized. */ export const setupConflictHandlers = [ ...setupUninitializedHandlers, diff --git a/frontend/src/features/setup/pages/SetupPage.test.tsx b/frontend/src/features/setup/pages/SetupPage.test.tsx index a8c9371..0c9e9d0 100644 --- a/frontend/src/features/setup/pages/SetupPage.test.tsx +++ b/frontend/src/features/setup/pages/SetupPage.test.tsx @@ -3,7 +3,7 @@ import { screen } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import { renderApp, mockGuest } from '@/test/utils'; import { server } from '@/mocks/server'; -import { setupUninitializedHandlers, setupConflictHandlers } from '@/mocks/index'; +import { setupUninitializedHandlers, setupConflictHandlers, setupTokenRequiredHandlers } from '@/mocks/index'; import { _resetSetupStatusCache } from '@/router'; // Each test starts with a fresh setup status cache so the MSW handler controls @@ -105,4 +105,70 @@ describe('SetupPage', () => { expect(await screen.findByTestId('login-form-submit-button')).toBeInTheDocument(); }); + + describe('setup token', () => { + const fillValidForm = async (user: ReturnType) => { + await user.type(await screen.findByTestId('setup-name-input'), 'Alice Owner'); + await user.type(screen.getByTestId('setup-email-input'), 'alice@example.com'); + await user.type(screen.getByTestId('setup-password-input'), 'ValidPass1!'); + await user.type(screen.getByTestId('setup-confirmPassword-input'), 'ValidPass1!'); + }; + + it('does not show a token field when the host does not require one', async () => { + server.use(...setupUninitializedHandlers); + mockGuest(); + renderApp('/setup'); + + await screen.findByTestId('setup-name-input'); + expect(screen.queryByTestId('setup-token-input')).not.toBeInTheDocument(); + }); + + it('shows the token field when the host requires one', async () => { + server.use(...setupTokenRequiredHandlers); + mockGuest(); + renderApp('/setup'); + + expect(await screen.findByTestId('setup-token-input')).toBeInTheDocument(); + }); + + it('blocks submission without a token', async () => { + server.use(...setupTokenRequiredHandlers); + mockGuest(); + const user = userEvent.setup(); + renderApp('/setup'); + + await fillValidForm(user); + await user.click(screen.getByTestId('setup-submit-button')); + + expect(await screen.findByTestId('setup-token-error')).toBeInTheDocument(); + expect(screen.queryByTestId('setup-success')).not.toBeInTheDocument(); + }); + + it('shows a clear message for a wrong token and stays on the page', async () => { + server.use(...setupTokenRequiredHandlers); + mockGuest(); + const user = userEvent.setup(); + renderApp('/setup'); + + await fillValidForm(user); + await user.type(screen.getByTestId('setup-token-input'), 'wrong-token'); + await user.click(screen.getByTestId('setup-submit-button')); + + expect(await screen.findByTestId('form-error-banner')).toBeInTheDocument(); + expect(screen.getByTestId('setup-form')).toBeInTheDocument(); + }); + + it('sends the token in X-Setup-Token and completes setup', async () => { + server.use(...setupTokenRequiredHandlers); + mockGuest(); + const user = userEvent.setup(); + renderApp('/setup'); + + await fillValidForm(user); + await user.type(screen.getByTestId('setup-token-input'), 'correct-token'); + await user.click(screen.getByTestId('setup-submit-button')); + + expect(await screen.findByTestId('setup-success')).toBeInTheDocument(); + }); + }); }); diff --git a/frontend/src/features/setup/pages/SetupPage.tsx b/frontend/src/features/setup/pages/SetupPage.tsx index e277c57..35b327e 100644 --- a/frontend/src/features/setup/pages/SetupPage.tsx +++ b/frontend/src/features/setup/pages/SetupPage.tsx @@ -13,7 +13,7 @@ import { FieldError } from '@/components/ui/FieldError'; import { useSetup } from '@/features/setup/services/useSetup'; import { ProblemDetailsError, NetworkError } from '@/lib/api-client'; import { changeLanguage } from '@/i18n/config'; -import { _markSystemInitialized } from '@/router'; +import { _markSystemInitialized, isSetupTokenRequired } from '@/router'; interface FormError { message: string; @@ -26,6 +26,9 @@ export function SetupPage() { const [successMessage, setSuccessMessage] = useState(false); const setupMutation = useSetup(); + const tokenRequired = isSetupTokenRequired(); + const [setupToken, setSetupToken] = useState(''); + const [tokenMissing, setTokenMissing] = useState(false); const { register, @@ -46,9 +49,14 @@ export function SetupPage() { const onSubmit = handleSubmit(async (values) => { setServerError(null); + if (tokenRequired && setupToken.trim() === '') { + setTokenMissing(true); + return; + } + setTokenMissing(false); try { const { confirmPassword: _, ...payload } = values; - await setupMutation.mutateAsync(payload); + await setupMutation.mutateAsync(payload, tokenRequired ? setupToken.trim() : undefined); await changeLanguage(values.language); _markSystemInitialized(); setSuccessMessage(true); @@ -56,7 +64,9 @@ export function SetupPage() { navigate({ to: '/login' }); }, 2000); } catch (err) { - if (err instanceof ProblemDetailsError) { + if (err instanceof ProblemDetailsError && err.status === 401) { + setServerError({ message: t('setup.tokenInvalid') }); + } else if (err instanceof ProblemDetailsError) { setServerError({ message: err.problem.detail || err.message || t('errors.generic') }); } else if (err instanceof NetworkError) { setServerError({ message: t('errors.network') }); @@ -99,6 +109,23 @@ export function SetupPage() { onDismiss={() => setServerError(null)} /> + {tokenRequired && ( +
+ + setSetupToken(e.target.value)} + /> +

{t('setup.tokenHelp')}

+ {tokenMissing && } +
+ )} +
(null); - const mutateAsync = useCallback(async (data: SetupRequest): Promise => { + const mutateAsync = useCallback(async (data: SetupRequest, setupToken?: string): Promise => { setIsPending(true); setError(null); try { - const response = await api.post('/api/v1/Setup/owner', data); + // skipAuthRefresh: a rejected token is a 401, and nobody is signed in yet, so the + // client must not try (and fail) a session refresh that would signal an auth failure. + const response = await api.post('/api/v1/Setup/owner', data, { + skipAuthRefresh: true, + headers: setupToken ? { 'X-Setup-Token': setupToken } : undefined, + }); return response as SetupResponse; } catch (err) { const error = err instanceof Error ? err : new Error(String(err)); diff --git a/frontend/src/i18n/config.test.ts b/frontend/src/i18n/config.test.ts new file mode 100644 index 0000000..99bca14 --- /dev/null +++ b/frontend/src/i18n/config.test.ts @@ -0,0 +1,13 @@ +import { describe, expect, it } from 'vitest'; +import { languageDetection } from '@/i18n/config'; + +describe('languageDetection', () => { + it('without a default language keeps the old order: stored choice, then browser, fallback English', () => { + expect(languageDetection(undefined)).toEqual({ order: ['localStorage', 'navigator'], fallbackLng: 'en' }); + }); + + it('with a default language: stored choice first, then that default, and the browser is not consulted', () => { + expect(languageDetection('nl')).toEqual({ order: ['localStorage'], fallbackLng: 'nl' }); + expect(languageDetection('en')).toEqual({ order: ['localStorage'], fallbackLng: 'en' }); + }); +}); diff --git a/frontend/src/i18n/config.ts b/frontend/src/i18n/config.ts index d840b5b..9b25eb4 100644 --- a/frontend/src/i18n/config.ts +++ b/frontend/src/i18n/config.ts @@ -3,6 +3,7 @@ import { initReactI18next } from 'react-i18next'; import LanguageDetector from 'i18next-browser-languagedetector'; import enTranslation from './locales/en/translation.json'; import nlTranslation from './locales/nl/translation.json'; +import { getAppConfig } from '@/lib/config'; export const SUPPORTED_LANGUAGES = ['en', 'nl'] as const; export type SupportedLanguage = (typeof SUPPORTED_LANGUAGES)[number]; @@ -12,6 +13,18 @@ export const LANGUAGE_LABELS: Record = { nl: 'Nederlands', }; +/** + * Language resolution order: a stored user choice always wins; otherwise the build-time + * VITE_DEFAULT_LANGUAGE; otherwise the browser language (the behaviour before this option existed). + */ +export function languageDetection(defaultLanguage: SupportedLanguage | undefined) { + return defaultLanguage === undefined + ? { order: ['localStorage', 'navigator'], fallbackLng: 'en' } + : { order: ['localStorage'], fallbackLng: defaultLanguage }; +} + +const detectionSetup = languageDetection(getAppConfig().defaultLanguage); + // Both supported locales are bundled eagerly so the detected language is // available immediately on init — no async gap that would cause an English flash. void i18n @@ -22,12 +35,12 @@ void i18n en: { translation: enTranslation }, nl: { translation: nlTranslation }, }, - fallbackLng: 'en', + fallbackLng: detectionSetup.fallbackLng, supportedLngs: SUPPORTED_LANGUAGES as unknown as string[], nonExplicitSupportedLngs: true, interpolation: { escapeValue: false }, detection: { - order: ['localStorage', 'navigator'], + order: detectionSetup.order, caches: ['localStorage'], }, react: { useSuspense: false }, diff --git a/frontend/src/i18n/locales/en/translation.json b/frontend/src/i18n/locales/en/translation.json index e6165c0..bb2e696 100644 --- a/frontend/src/i18n/locales/en/translation.json +++ b/frontend/src/i18n/locales/en/translation.json @@ -43,6 +43,10 @@ "passwordLabel": "Password", "confirmPasswordLabel": "Confirm password", "languageLabel": "Language preference", + "tokenLabel": "Setup token", + "tokenHelp": "Required to create the first administrator. You received it from whoever installed this site.", + "tokenRequiredError": "Enter the setup token.", + "tokenInvalid": "The setup token is missing or incorrect.", "submitButton": "Create owner account", "successMessage": "Account created. You can now sign in." }, diff --git a/frontend/src/i18n/locales/nl/translation.json b/frontend/src/i18n/locales/nl/translation.json index 7dc00f6..99feb43 100644 --- a/frontend/src/i18n/locales/nl/translation.json +++ b/frontend/src/i18n/locales/nl/translation.json @@ -43,6 +43,10 @@ "passwordLabel": "Wachtwoord", "confirmPasswordLabel": "Wachtwoord bevestigen", "languageLabel": "Taalkeuze", + "tokenLabel": "Setup-token", + "tokenHelp": "Nodig om de eerste beheerder aan te maken. Je hebt het ontvangen van degene die deze site heeft geïnstalleerd.", + "tokenRequiredError": "Vul het setup-token in.", + "tokenInvalid": "Het setup-token ontbreekt of is onjuist.", "submitButton": "Owner-account aanmaken", "successMessage": "Account aangemaakt. Je kunt nu inloggen." }, diff --git a/frontend/src/lib/config.test.ts b/frontend/src/lib/config.test.ts index 4852d7e..ccbfd92 100644 --- a/frontend/src/lib/config.test.ts +++ b/frontend/src/lib/config.test.ts @@ -1,5 +1,5 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { getAppConfig, resetAppConfigCache } from '@/lib/config'; +import { getAppConfig, parseDefaultLanguage, resetAppConfigCache } from '@/lib/config'; /** * The empty-base case is the production configuration, and the one nobody runs locally — so it is @@ -81,3 +81,39 @@ describe('getAppConfig', () => { expect(config.umamiWebsiteId).toBeUndefined(); }); }); + +describe('parseDefaultLanguage', () => { + it.each([ + ['nl', 'nl'], + ['en', 'en'], + [' NL ', 'nl'], + ['EN', 'en'], + ])('accepts %j as %s', (input, expected) => { + expect(parseDefaultLanguage(input)).toBe(expected); + }); + + it.each([undefined, '', ' ', 'de', 'nl-NL', 'dutch'])('treats %j as no default', (input) => { + expect(parseDefaultLanguage(input)).toBeUndefined(); + }); +}); + +describe('getAppConfig defaultLanguage', () => { + afterEach(() => { + vi.unstubAllEnvs(); + resetAppConfigCache(); + }); + + it('reads VITE_DEFAULT_LANGUAGE', () => { + resetAppConfigCache(); + vi.stubEnv('VITE_DEFAULT_LANGUAGE', 'nl'); + + expect(getAppConfig().defaultLanguage).toBe('nl'); + }); + + it('is undefined when VITE_DEFAULT_LANGUAGE is absent', () => { + resetAppConfigCache(); + vi.stubEnv('VITE_DEFAULT_LANGUAGE', undefined as unknown as string); + + expect(getAppConfig().defaultLanguage).toBeUndefined(); + }); +}); diff --git a/frontend/src/lib/config.ts b/frontend/src/lib/config.ts index 23271d8..40096d3 100644 --- a/frontend/src/lib/config.ts +++ b/frontend/src/lib/config.ts @@ -21,10 +21,17 @@ const configSchema = z.object({ appEnv: z.string().optional(), umamiScriptUrl: z.string().optional(), umamiWebsiteId: z.string().optional(), + defaultLanguage: z.enum(['en', 'nl']).optional(), }); export type AppConfig = z.infer; +/** Only a supported language counts; anything else (typo, empty) means "no default" and falls back to the browser. */ +export function parseDefaultLanguage(value: string | undefined): 'en' | 'nl' | undefined { + const v = value?.trim().toLowerCase(); + return v === 'en' || v === 'nl' ? v : undefined; +} + let cached: AppConfig | null = null; export function getAppConfig(): AppConfig { @@ -43,6 +50,7 @@ export function getAppConfig(): AppConfig { appEnv: import.meta.env.VITE_APP_ENV, umamiScriptUrl: import.meta.env.VITE_UMAMI_SCRIPT_URL, umamiWebsiteId: import.meta.env.VITE_UMAMI_WEBSITE_ID, + defaultLanguage: parseDefaultLanguage(import.meta.env.VITE_DEFAULT_LANGUAGE), }; if (import.meta.env.DEV) { diff --git a/frontend/src/main.tsx b/frontend/src/main.tsx index e1f5e1c..a7342b4 100644 --- a/frontend/src/main.tsx +++ b/frontend/src/main.tsx @@ -3,6 +3,8 @@ import { createRoot } from 'react-dom/client'; import { RouterProvider } from '@tanstack/react-router'; import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; import './index.css'; +// Per-site admin theme chosen at build time (VITE_THEME); an empty file when none is selected. +import '@theme'; import './i18n/config'; import { AuthProvider } from '@/features/auth/context/AuthProvider'; import { useAuth } from '@/features/auth/context/auth-context'; diff --git a/frontend/src/mocks/index.ts b/frontend/src/mocks/index.ts index 26d9e97..846d606 100644 --- a/frontend/src/mocks/index.ts +++ b/frontend/src/mocks/index.ts @@ -12,7 +12,7 @@ export const handlers = [...authHandlers, ...userHandlers, ...setupHandlers, ... export { authHandlers } from '@/features/auth/mocks/handlers'; export { userHandlers } from '@/features/users/mocks/handlers'; -export { setupHandlers, setupUninitializedHandlers, setupConflictHandlers, setupNetworkErrorHandlers } from '@/features/setup/mocks/handlers'; +export { setupHandlers, setupUninitializedHandlers, setupConflictHandlers, setupTokenRequiredHandlers, setupNetworkErrorHandlers } from '@/features/setup/mocks/handlers'; export { invitationHandlers } from '@/features/invitation/mocks/handlers'; export { availabilityHandlers } from '@/features/availability/mocks/handlers'; export { cmsHandlers, resetMockCmsInstances, getMockCmsInstances } from '@/features/cms/mocks/handlers'; diff --git a/frontend/src/router.tsx b/frontend/src/router.tsx index 13e47ca..d09f4e7 100644 --- a/frontend/src/router.tsx +++ b/frontend/src/router.tsx @@ -31,10 +31,15 @@ async function fetchSetupStatus(): Promise { if (_setupStatusCache !== null) return _setupStatusCache; if (_setupStatusPromise === null) { _setupStatusPromise = api - .get<{ initialized?: boolean; Initialized?: boolean }>('/api/v1/Setup/status') + .get<{ initialized?: boolean; Initialized?: boolean; tokenRequired?: boolean; TokenRequired?: boolean }>( + '/api/v1/Setup/status', + ) .then((raw) => { // Backend may return PascalCase (Initialized) if no camelCase policy is set. - const s: SetupStatus = { initialized: raw.initialized ?? raw.Initialized ?? false }; + const s: SetupStatus = { + initialized: raw.initialized ?? raw.Initialized ?? false, + tokenRequired: raw.tokenRequired ?? raw.TokenRequired ?? false, + }; _setupStatusCache = s; return s; }) @@ -52,6 +57,11 @@ export function _resetSetupStatusCache(): void { _setupStatusPromise = null; } +/** Whether the setup page must ask for the setup token (known once the InitGuard fetched the status). */ +export function isSetupTokenRequired(): boolean { + return _setupStatusCache?.tokenRequired === true; +} + export function _markSystemInitialized(): void { _setupStatusCache = { initialized: true }; _setupStatusPromise = null; diff --git a/frontend/src/vite-env.d.ts b/frontend/src/vite-env.d.ts index 00becba..385b446 100644 --- a/frontend/src/vite-env.d.ts +++ b/frontend/src/vite-env.d.ts @@ -15,6 +15,10 @@ interface ImportMetaEnv { readonly VITE_SENTRY_DSN?: string; /** Build-time environment tag ('test' | 'production'). Both use `vite build`, so MODE alone cannot tell them apart. */ readonly VITE_APP_ENV?: string; + /** Admin theme folder under frontend/themes (e.g. 'asf'). Absent = the default look. Read by vite.config.ts at build time. */ + readonly VITE_THEME?: string; + /** Initial language when the user has not chosen one yet ('nl' | 'en'). Absent = browser language. */ + readonly VITE_DEFAULT_LANGUAGE?: string; /** Self-hosted Umami tracking script URL, e.g. https://analytics.example.com/script.js */ readonly VITE_UMAMI_SCRIPT_URL?: string; /** Umami website ID, created per environment in the Umami dashboard. */ @@ -28,3 +32,6 @@ interface ImportMeta { /** App version at build time (from package.json), injected via vite.config.ts `define`. Used as the Sentry `release` tag. */ declare const __APP_VERSION__: string; + +/** Alias to the selected theme stylesheet (see vite.config.ts and themes/). */ +declare module '@theme'; diff --git a/frontend/themes/asf/favicon.svg b/frontend/themes/asf/favicon.svg new file mode 100644 index 0000000..d6d2fc8 --- /dev/null +++ b/frontend/themes/asf/favicon.svg @@ -0,0 +1,4 @@ + + + ASF + diff --git a/frontend/themes/asf/theme.css b/frontend/themes/asf/theme.css new file mode 100644 index 0000000..f3a2a8b --- /dev/null +++ b/frontend/themes/asf/theme.css @@ -0,0 +1,115 @@ +/* + * Theme "asf" - Andrea Slop Fotografie. + * + * Re-declares the admin design tokens only (colours, radius, fonts); no layout or component changes. + * Colours are exactly those of the Andrea Slop Fotografie website (decision Q5 = B): no contrast + * adjustment was made, so a few pairs may fall below WCAG AA - see the hand-back note. + * + * Fonts are self-hosted through the @fontsource packages (the admin CSP is font-src 'self'). + * Selected at build time with VITE_THEME=asf. + */ +@import '@fontsource/jost/latin-400.css'; +@import '@fontsource/jost/latin-500.css'; +@import '@fontsource/jost/latin-600.css'; +@import '@fontsource/marcellus/latin-400.css'; + +:root { + /* Website palette */ + --asf-paper: #faf7f2; + --asf-paper-2: #f1ebe2; + --asf-paper-3: #e8e0d5; + --asf-ink: #232120; + --asf-ink-2: #55504b; + --asf-ink-3: #8a827a; + --asf-line: #e2dad0; + --asf-accent: #7f8b76; + --asf-accent-deep: #5f6a58; + --asf-accent-deeper: #475042; + --asf-sand: #d9cdbc; + --asf-error: #a4443a; + + --asf-font-heading: 'Marcellus', Georgia, 'Times New Roman', serif; + --asf-font-body: 'Jost', system-ui, 'Segoe UI', Roboto, sans-serif; + + --background: var(--asf-paper); + --foreground: var(--asf-ink); + + --card: var(--asf-paper-2); + --card-foreground: var(--asf-ink); + + --popover: var(--asf-paper-2); + --popover-foreground: var(--asf-ink); + + --primary: var(--asf-accent-deep); + --primary-foreground: var(--asf-paper); + + --secondary: var(--asf-paper-2); + --secondary-foreground: var(--asf-ink); + + --muted: var(--asf-paper-2); + --muted-foreground: var(--asf-ink-2); + + --accent: var(--asf-paper-3); + --accent-foreground: var(--asf-accent-deeper); + + --destructive: var(--asf-error); + --destructive-foreground: var(--asf-paper); + + --border: var(--asf-line); + --input: var(--asf-line); + --ring: var(--asf-accent-deep); + + --radius: 0.25rem; + + --font-sans: var(--asf-font-body); +} + +/* + * Dark mode: the website has no dark variant, so these values are derived from its palette (ink as + * background, paper as text, a slightly lighter accent #8a9681 so button text stays above 4.5:1). + */ +.dark { + --background: var(--asf-ink); + --foreground: var(--asf-paper); + + --card: #2d2a28; + --card-foreground: var(--asf-paper); + + --popover: #2d2a28; + --popover-foreground: var(--asf-paper); + + --primary: #8a9681; + --primary-foreground: var(--asf-ink); + + --secondary: #353130; + --secondary-foreground: var(--asf-paper); + + --muted: #353130; + --muted-foreground: var(--asf-sand); + + --accent: #353130; + --accent-foreground: var(--asf-paper-3); + + --destructive: #d9776b; + --destructive-foreground: var(--asf-ink); + + --border: #433e3b; + --input: #433e3b; + --ring: #8a9681; +} + +body { + font-family: var(--asf-font-body); +} + +h1, +h2, +h3, +h4, +h5, +h6, +[data-slot='card-title'], +[data-slot='dialog-title'] { + font-family: var(--asf-font-heading); + font-weight: 400; +} diff --git a/frontend/themes/none.css b/frontend/themes/none.css new file mode 100644 index 0000000..8d189a6 --- /dev/null +++ b/frontend/themes/none.css @@ -0,0 +1 @@ +/* Intentionally empty: used when VITE_THEME is unset, so the admin keeps its default look. */ diff --git a/frontend/themes/resolveTheme.test.ts b/frontend/themes/resolveTheme.test.ts new file mode 100644 index 0000000..7303828 --- /dev/null +++ b/frontend/themes/resolveTheme.test.ts @@ -0,0 +1,73 @@ +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { describe, expect, it } from 'vitest'; +import { availableThemes, resolveTheme } from './resolveTheme'; + +describe('resolveTheme', () => { + it.each([undefined, '', ' '])('maps %j to the empty module (the default admin)', (name) => { + const theme = resolveTheme(name); + + expect(path.basename(theme.css)).toBe('none.css'); + expect(theme.favicon).toBeNull(); + expect(fs.readFileSync(theme.css, 'utf-8')).not.toMatch(/--[a-z-]+\s*:/); + }); + + it('resolves the asf theme with its stylesheet and favicon', () => { + const theme = resolveTheme('asf'); + + expect(fs.existsSync(theme.css)).toBe(true); + expect(theme.css.replaceAll('\\', '/')).toMatch(/themes\/asf\/theme\.css$/); + expect(theme.favicon !== null && fs.existsSync(theme.favicon)).toBe(true); + }); + + it('lists the available themes', () => { + expect(availableThemes()).toContain('asf'); + }); + + it.each(['nope', '../asf', 'asf/../asf', '..', 'ASF', 'asf asf'])('rejects %j loudly, naming the real themes', (name) => { + expect(() => resolveTheme(name)).toThrow(/Unknown VITE_THEME .*Available themes: .*asf/); + }); + + it('reports (none) when no theme exists', () => { + const empty = fs.mkdtempSync(path.join(os.tmpdir(), 'themes-')); + try { + expect(() => resolveTheme('x', empty)).toThrow(/\(none\)/); + } finally { + fs.rmSync(empty, { recursive: true, force: true }); + } + }); +}); + +describe('asf theme tokens', () => { + const tokens = (css: string, block: string) => { + const m = css.match(new RegExp(`${block}\\s*\\{([^}]*)\\}`)); + return new Set([...(m?.[1] ?? '').matchAll(/(--[a-z-]+)\s*:/g)].map((x) => x[1])); + }; + const base = fs.readFileSync(path.resolve(__dirname, '../src/index.css'), 'utf-8'); + const theme = fs.readFileSync(path.resolve(__dirname, 'asf/theme.css'), 'utf-8'); + + it('overrides every existing light and dark design token and invents no structural one', () => { + for (const block of ['\\:root', '\\.dark']) { + const existing = tokens(base, block); + const themed = tokens(theme, block); + for (const t of existing) expect(themed, `${block} ${t}`).toContain(t); + // Anything beyond the existing tokens must be the theme's own --asf-* palette or the font token. + for (const t of themed) { + if (!existing.has(t)) expect(t).toMatch(/^--(asf-|font-sans$)/); + } + } + }); + + it('uses the website palette colours exactly', () => { + for (const hex of ['#faf7f2', '#f1ebe2', '#e8e0d5', '#232120', '#55504b', '#8a827a', '#e2dad0', '#7f8b76', '#5f6a58', '#475042', '#d9cdbc', '#a4443a']) { + expect(theme.toLowerCase()).toContain(hex); + } + }); + + it('self-hosts its fonts (no remote url)', () => { + expect(theme).not.toMatch(/https?:\/\//); + expect(theme).toContain('@fontsource/jost'); + expect(theme).toContain('@fontsource/marcellus'); + }); +}); diff --git a/frontend/themes/resolveTheme.ts b/frontend/themes/resolveTheme.ts new file mode 100644 index 0000000..fdd0457 --- /dev/null +++ b/frontend/themes/resolveTheme.ts @@ -0,0 +1,46 @@ +import fs from 'node:fs'; +import path from 'node:path'; + +export interface ResolvedTheme { + /** Absolute path of the CSS file to import (the empty module when no theme is selected). */ + css: string; + /** Absolute path of the theme favicon, or null when there is no theme or it ships none. */ + favicon: string | null; +} + +const THEMES_DIR = import.meta.dirname; + +/** Theme folders available next to this file (each holds a theme.css). */ +export function availableThemes(dir: string = THEMES_DIR): string[] { + return fs + .readdirSync(dir, { withFileTypes: true }) + .filter((e) => e.isDirectory() && fs.existsSync(path.join(dir, e.name, 'theme.css'))) + .map((e) => e.name) + .sort(); +} + +/** + * Resolves VITE_THEME to files. Unset or blank means "no theme": an empty CSS module, so the admin + * looks exactly as it always did. An unknown name is a build error, never a silent fallback, so a + * typo in the pipeline cannot ship an unthemed admin unnoticed. + */ +export function resolveTheme(name: string | undefined, dir: string = THEMES_DIR): ResolvedTheme { + const trimmed = (name ?? '').trim(); + if (trimmed === '') { + return { css: path.join(dir, 'none.css'), favicon: null }; + } + + // The name becomes a path segment: only known theme folders are accepted. + const known = availableThemes(dir); + if (!known.includes(trimmed)) { + throw new Error( + `Unknown VITE_THEME "${trimmed}". Available themes: ${known.length > 0 ? known.join(', ') : '(none)'}.`, + ); + } + + const favicon = path.join(dir, trimmed, 'favicon.svg'); + return { + css: path.join(dir, trimmed, 'theme.css'), + favicon: fs.existsSync(favicon) ? favicon : null, + }; +} diff --git a/frontend/tsconfig.node.json b/frontend/tsconfig.node.json index d3c52ea..86fd3e9 100644 --- a/frontend/tsconfig.node.json +++ b/frontend/tsconfig.node.json @@ -20,5 +20,5 @@ "erasableSyntaxOnly": true, "noFallthroughCasesInSwitch": true }, - "include": ["vite.config.ts"] + "include": ["vite.config.ts", "themes/resolveTheme.ts"] } diff --git a/frontend/vite.config.ts b/frontend/vite.config.ts index 6502da0..6606552 100644 --- a/frontend/vite.config.ts +++ b/frontend/vite.config.ts @@ -1,15 +1,51 @@ /// import path from 'node:path'; -import { defineConfig } from 'vite'; +import fs from 'node:fs'; +import { defineConfig, loadEnv, type Plugin } from 'vite'; import react from '@vitejs/plugin-react'; import tailwindcss from '@tailwindcss/vite'; import { version } from './package.json'; +import { resolveTheme } from './themes/resolveTheme'; + +/** VITE_THEME selects themes//theme.css at build time (unset = today's admin, unchanged). */ +function themeFor(mode: string) { + return resolveTheme({ ...loadEnv(mode, process.cwd(), 'VITE_'), ...process.env }.VITE_THEME); +} + +/** + * Per-site favicon (VITE_THEME): the page links the theme favicon instead of the default one. + * Build emits it as an asset; the dev server serves it from the theme folder. + */ +function themeFavicon(faviconPath: string | null): Plugin { + const publicName = 'favicon-theme.svg'; + return { + name: 'cms-theme-favicon', + // 'post': Vite has already prefixed the base path (/admin/) by then, so match any prefix. + transformIndexHtml: { + order: 'post', + handler(html) { + return faviconPath === null ? html : html.replace(/href="([^"]*)favicon\.svg"/, `href="$1${publicName}"`); + }, + }, + configureServer(server) { + if (faviconPath === null) return; + server.middlewares.use(`/${publicName}`, (_req, res) => { + res.setHeader('Content-Type', 'image/svg+xml'); + res.end(fs.readFileSync(faviconPath)); + }); + }, + generateBundle() { + if (faviconPath === null) return; + this.emitFile({ type: 'asset', fileName: publicName, source: fs.readFileSync(faviconPath) }); + }, + }; +} // https://vite.dev/config/ -export default defineConfig(({ command }) => ({ +export default defineConfig(({ command, mode }) => ({ // Production builds are deployed under /admin (see Program.cs); the dev server keeps serving from '/'. base: command === 'build' ? '/admin/' : '/', - plugins: [react(), tailwindcss()], + plugins: [react(), tailwindcss(), themeFavicon(themeFor(mode).favicon)], define: { // Injected at build time, used as the Sentry `release` tag (see src/lib/sentry.ts). __APP_VERSION__: JSON.stringify(version), @@ -17,6 +53,8 @@ export default defineConfig(({ command }) => ({ resolve: { alias: { '@': path.resolve(__dirname, './src'), + // The selected theme's CSS (or an empty file); imported once from main.tsx. + '@theme': themeFor(mode).css, }, }, server: { diff --git a/src/SlpModularCms.Api.AndreaSlopFotografie.Tests/HostConfigurationTests.cs b/src/SlpModularCms.Api.AndreaSlopFotografie.Tests/HostConfigurationTests.cs new file mode 100644 index 0000000..0faefb5 --- /dev/null +++ b/src/SlpModularCms.Api.AndreaSlopFotografie.Tests/HostConfigurationTests.cs @@ -0,0 +1,77 @@ +using FluentAssertions; +using Microsoft.Extensions.Configuration; + +namespace SlpModularCms.Api.AndreaSlopFotografie.Tests; + +/// +/// Guards the committed defaults of the Andrea Slop Fotografie host. These need no database, so they +/// run everywhere (unlike ). +/// +public class HostConfigurationTests +{ + private static IConfigurationRoot Load() + { + var dir = new DirectoryInfo(AppContext.BaseDirectory); + while (dir is not null && + !File.Exists(Path.Combine(dir.FullName, "SlpModularCms.Api.AndreaSlopFotografie", "appsettings.json"))) + { + dir = dir.Parent; + } + + dir.Should().NotBeNull("the host project must be found next to this test project"); + var path = Path.Combine(dir!.FullName, "SlpModularCms.Api.AndreaSlopFotografie", "appsettings.json"); + return new ConfigurationBuilder().AddJsonFile(path, optional: false).Build(); + } + + [Fact] + public void WebsiteIsNoIndex_ByDefault() + { + Load().GetValue("Website:NoIndex").Should().BeTrue(); + } + + [Fact] + public void DefaultPolicyIsStrictSite_AndAdminApiHealthStayStrict() + { + var config = Load(); + + config["SecurityHeaders:DefaultPolicy"].Should().Be("StrictSite"); + var rules = config.GetSection("SecurityHeaders:PathPolicies").GetChildren() + .ToDictionary(c => c["PathPrefix"]!, c => c["Policy"]!); + rules.Should().Contain(new KeyValuePair("/admin", "Strict")) + .And.Contain(new KeyValuePair("/api/v1", "Strict")) + .And.Contain(new KeyValuePair("/health", "Strict")); + } + + [Fact] + public void SiteOrigins_AreHttpsOnly_AndNotAddedToTheAdminLists() + { + var config = Load(); + var site = config.GetSection("SecurityHeaders:AllowedSiteScriptOrigins").Get()! + .Concat(config.GetSection("SecurityHeaders:AllowedSiteConnectOrigins").Get()!); + + site.Should().NotBeEmpty().And.OnlyContain(o => o.StartsWith("https://")); + config.GetSection("SecurityHeaders:AllowedScriptOrigins").Get().Should().BeEmpty(); + config.GetSection("SecurityHeaders:AllowedConnectOrigins").Get().Should().BeEmpty(); + } + + [Fact] + public void NoSecretsAreCommitted() + { + var config = Load(); + + config["JwtSettings:Secret"].Should().StartWith("<"); + config["ConnectionStrings:DefaultConnection"].Should().Contain(""); + config["Identity:Setup:Token"].Should().BeNullOrEmpty(); + config["Observability:SentryDsn"].Should().BeNullOrEmpty(); + config.GetSection("ForwardedHeaders:KnownProxies").Get().Should().BeNullOrEmpty(); + } + + [Fact] + public void Host_DoesNotReferenceMasterOrOfferingsModules() + { + var referenced = typeof(Program).Assembly.GetReferencedAssemblies().Select(a => a.Name); + + referenced.Should().NotContain("SlpModularCms.Modules.Offerings") + .And.NotContain("SlpModularCms.Modules.Master"); + } +} diff --git a/src/SlpModularCms.Api.AndreaSlopFotografie.Tests/HostPipelineTests.cs b/src/SlpModularCms.Api.AndreaSlopFotografie.Tests/HostPipelineTests.cs new file mode 100644 index 0000000..fdb2cc2 --- /dev/null +++ b/src/SlpModularCms.Api.AndreaSlopFotografie.Tests/HostPipelineTests.cs @@ -0,0 +1,74 @@ +using System.Net; +using System.Text.Json; +using FluentAssertions; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Mvc.Testing; + +namespace SlpModularCms.Api.AndreaSlopFotografie.Tests; + +/// Starts the real host in-memory (Development environment). +public class AsfWebApplicationFactory : WebApplicationFactory +{ + protected override void ConfigureWebHost(IWebHostBuilder builder) + { + builder.UseEnvironment("Development"); + } +} + +/// +/// Requires a reachable local MariaDB matching appsettings.Development.json of the host, +/// because CmsHost.ConfigurePipeline migrates the database before any endpoint answers +/// (same precondition as SlpModularCms.Api.Tests). +/// +public class HostPipelineTests : IClassFixture +{ + private readonly AsfWebApplicationFactory _factory; + + public HostPipelineTests(AsfWebApplicationFactory factory) => _factory = factory; + + [Fact] + public async Task Capabilities_ListIdentityAndAvailability_ButNotOfferingsOrMaster() + { + var response = await _factory.CreateClient().GetAsync("/api/v1/System/capabilities"); + + response.StatusCode.Should().Be(HttpStatusCode.OK); + using var doc = JsonDocument.Parse(await response.Content.ReadAsStringAsync()); + var modules = doc.RootElement.GetProperty("modules").EnumerateArray().Select(e => e.GetString()).ToList(); + modules.Should().Contain("Identity").And.Contain("Availability"); + modules.Should().NotContain("Offerings").And.NotContain("Master"); + } + + [Fact] + public async Task Health_IsReachable() + { + (await _factory.CreateClient().GetAsync("/health")).IsSuccessStatusCode.Should().BeTrue(); + } + + [Fact] + public async Task SetupStatus_ReportsNoTokenRequired_WhenNoneConfigured() + { + var response = await _factory.CreateClient().GetAsync("/api/v1/Setup/status"); + + response.StatusCode.Should().Be(HttpStatusCode.OK); + (await response.Content.ReadAsStringAsync()).Should().Contain("\"tokenRequired\":false"); + } + + [Fact] + public async Task UnknownWebsitePath_Returns404_WithTheSiteSecurityHeaders_AndNoIndex() + { + var response = await _factory.CreateClient().GetAsync("/some-page-that-does-not-exist"); + + response.StatusCode.Should().Be(HttpStatusCode.NotFound); + response.Headers.GetValues("Content-Security-Policy").Single() + .Should().Contain("https://analytics.slpsoftware.nl"); + response.Headers.GetValues("X-Robots-Tag").Single().Should().Be("noindex, nofollow"); + } + + [Fact] + public async Task RobotsTxt_DisallowsEverything_OnTheDefaultNoIndexConfiguration() + { + var body = await _factory.CreateClient().GetStringAsync("/robots.txt"); + + body.Should().Contain("Disallow: /"); + } +} diff --git a/src/SlpModularCms.Api.AndreaSlopFotografie.Tests/SlpModularCms.Api.AndreaSlopFotografie.Tests.csproj b/src/SlpModularCms.Api.AndreaSlopFotografie.Tests/SlpModularCms.Api.AndreaSlopFotografie.Tests.csproj new file mode 100644 index 0000000..3952e39 --- /dev/null +++ b/src/SlpModularCms.Api.AndreaSlopFotografie.Tests/SlpModularCms.Api.AndreaSlopFotografie.Tests.csproj @@ -0,0 +1,33 @@ + + + + net10.0 + enable + enable + false + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/SlpModularCms.Api.AndreaSlopFotografie/Program.cs b/src/SlpModularCms.Api.AndreaSlopFotografie/Program.cs new file mode 100644 index 0000000..8521d39 --- /dev/null +++ b/src/SlpModularCms.Api.AndreaSlopFotografie/Program.cs @@ -0,0 +1,21 @@ +using SlpModularCms.Core.Hosting; + +var builder = WebApplication.CreateBuilder(args); + +// Load local developer overrides +builder.Configuration.AddJsonFile("appsettings.local.json", optional: true, reloadOnChange: true); + +// Andrea Slop Fotografie serves a prerendered website from wwwroot/web (nginx-equivalent behaviour) +// instead of the SPA-style website mount the other clients use. +var hostOptions = new CmsHostOptions { WebsiteMode = WebsiteMode.PrerenderedPages }; + +var orchestrator = CmsHost.ConfigureServices(builder, hostOptions); + +var app = builder.Build(); + +CmsHost.ConfigurePipeline(app, orchestrator, hostOptions); + +app.Run(); + +// Exposed so the host regression tests can start the real application in-memory. +public partial class Program; diff --git a/src/SlpModularCms.Api.AndreaSlopFotografie/Properties/launchSettings.json b/src/SlpModularCms.Api.AndreaSlopFotografie/Properties/launchSettings.json new file mode 100644 index 0000000..79355ad --- /dev/null +++ b/src/SlpModularCms.Api.AndreaSlopFotografie/Properties/launchSettings.json @@ -0,0 +1,25 @@ +{ + "$schema": "https://json.schemastore.org/launchsettings.json", + "profiles": { + "http": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "applicationUrl": "http://localhost:5200", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + }, + "launchUrl": "scalar" + }, + "https": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "applicationUrl": "https://localhost:7200;http://localhost:5200", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + }, + "launchUrl": "scalar" + } + } +} diff --git a/src/SlpModularCms.Api.AndreaSlopFotografie/SlpModularCms.Api.AndreaSlopFotografie.csproj b/src/SlpModularCms.Api.AndreaSlopFotografie/SlpModularCms.Api.AndreaSlopFotografie.csproj new file mode 100644 index 0000000..431adb8 --- /dev/null +++ b/src/SlpModularCms.Api.AndreaSlopFotografie/SlpModularCms.Api.AndreaSlopFotografie.csproj @@ -0,0 +1,39 @@ + + + + net10.0 + enable + enable + + + + + + + + runtime; build; native; contentfiles; analyzers; buildtransitive + all + + + + + + + + + + + + + + diff --git a/src/SlpModularCms.Api.AndreaSlopFotografie/appsettings.Development.json b/src/SlpModularCms.Api.AndreaSlopFotografie/appsettings.Development.json new file mode 100644 index 0000000..df63239 --- /dev/null +++ b/src/SlpModularCms.Api.AndreaSlopFotografie/appsettings.Development.json @@ -0,0 +1,34 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "ConnectionStrings": { + // Own, isolated local dev database, separate from the other clients' local databases. + "DefaultConnection": "Server=127.0.0.1;Port=3306;Database=AndreaSlopFotografieDev;Uid=root;Pwd=" + }, + "JwtSettings": { + "Secret": "SuperSecretKeyForDevelopmentOnly_MustBeLongerThan32Bytes!", + "Issuer": "SlpModularCms", + "Audience": "SlpModularCmsPortal", + "ExpiryMinutes": 60, + "RefreshTokenExpiryDays": 7, + "CookieSameSite": "None" + }, + "Cors": { + // The admin dev server (`pnpm dev:asf`, see frontend/.env.example). + "AllowedOrigins": [ "http://localhost:5176", "https://localhost:5176" ] + }, + "RateLimiting": { + "Login": { + "PermitLimit": 500, + "WindowSeconds": 60 + }, + "Refresh": { + "PermitLimit": 500, + "WindowSeconds": 60 + } + } +} diff --git a/src/SlpModularCms.Api.AndreaSlopFotografie/appsettings.json b/src/SlpModularCms.Api.AndreaSlopFotografie/appsettings.json new file mode 100644 index 0000000..e47d5f1 --- /dev/null +++ b/src/SlpModularCms.Api.AndreaSlopFotografie/appsettings.json @@ -0,0 +1,101 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Information", + // Pinned at Warning deliberately. At Information, EF prints every SQL statement INCLUDING + // parameter values, and the login path passes a normalised email address through it. + "Microsoft.EntityFrameworkCore.Database.Command": "Warning" + } + }, + "AllowedHosts": "*", + // Secrets and per-environment values are NEVER committed here; the deployed host receives them as + // environment variables (ConnectionStrings__DefaultConnection, JwtSettings__Secret, ...). + "ConnectionStrings": { + "DefaultConnection": "Server=;Port=3306;Database=AndreaSlopFotografie;Uid=;Pwd=" + }, + "JwtSettings": { + "Secret": "", + "Issuer": "SlpModularCms", + "Audience": "SlpModularCmsPortal", + "ExpiryMinutes": 60, + "RefreshTokenExpiryDays": 7 + }, + "Availability": { + "CircuitBreakerSeconds": 30, + "StatusCacheSeconds": 1 + }, + "MasterPolling": { + "PollIntervalSeconds": 30, + "FailOpenAfterMinutes": 5, + "HttpTimeoutSeconds": 5 + }, + "Identity": { + "Setup": { + // Optional protection of the first-administrator setup. Supplied per environment as + // Identity__Setup__Token (at least 32 random characters) and removed once the first + // administrator exists. Empty = setup is not token-protected. + "Token": "" + } + }, + // Opt-in trust in the reverse proxy in front of this host. Supplied per environment as + // ForwardedHeaders__KnownProxies__0 (the proxy IP address). Empty = forwarded headers are ignored. + "ForwardedHeaders": { + "KnownProxies": [] + }, + "Website": { + // Secure default: every website response carries noindex and /robots.txt disallows all. A + // production instance must set Website__NoIndex=false explicitly. + "NoIndex": true + }, + "Cors": { + "AllowedOrigins": [] + }, + "RateLimiting": { + "Login": { + "PermitLimit": 5, + "WindowSeconds": 60 + }, + "Refresh": { + "PermitLimit": 20, + "WindowSeconds": 60 + }, + "SentryTunnel": { + "PermitLimit": 60, + "WindowSeconds": 60 + }, + "OfferingsPublic": { + "PermitLimit": 120, + "WindowSeconds": 60 + } + }, + "SecurityHeaders": { + "Enabled": true, + // The public website is the default; the CMS admin and API keep the strict policy. + "DefaultPolicy": "StrictSite", + "PathPolicies": [ + { "PathPrefix": "/admin", "Policy": "Strict" }, + { "PathPrefix": "/api/v1", "Policy": "Strict" }, + { "PathPrefix": "/health", "Policy": "Strict" } + ], + "AllowedScriptOrigins": [], + "AllowedConnectOrigins": [], + // Origins the website itself calls (analytics script + beacon, Sentry error reporting). Only + // the StrictSite policy gets them; the admin policies are not widened. The host and admin set + // up no Umami: the admin reports errors through the same-origin /sentry-tunnel. + "AllowedSiteScriptOrigins": [ "https://analytics.slpsoftware.nl" ], + "AllowedSiteConnectOrigins": [ + "https://analytics.slpsoftware.nl", + "https://o4511795618185216.ingest.de.sentry.io" + ] + }, + "Observability": { + // Supplied per environment as Observability__SentryDsn. Empty means Sentry is skipped + // entirely and console logging continues — a normal, supported state, not an error. + "SentryDsn": "", + // Falls back to ASPNETCORE_ENVIRONMENT when empty. + "Environment": "", + "TracesSampleRate": 0.1, + "TunnelMaxPayloadBytes": 204800 + } +} diff --git a/src/SlpModularCms.Core.Tests/Hosting/Observability/SecurityEventsTests.cs b/src/SlpModularCms.Core.Tests/Hosting/Observability/SecurityEventsTests.cs index bdfd748..758b73b 100644 --- a/src/SlpModularCms.Core.Tests/Hosting/Observability/SecurityEventsTests.cs +++ b/src/SlpModularCms.Core.Tests/Hosting/Observability/SecurityEventsTests.cs @@ -80,8 +80,9 @@ public class SecurityEventsTests SecurityEvents.AdminBypassRejected(logger, "/e", BypassRejectionReason.InvalidSignature); SecurityEvents.RateLimitTriggered(logger, "login", "/e"); SecurityEvents.MigrationFailure(logger, new InvalidOperationException("boom"), attempts: 5); + SecurityEvents.SetupTokenRejected(logger, "/Setup/owner"); - logger.Entries.Should().HaveCount(6); + logger.Entries.Should().HaveCount(7); logger.Entries.Should().OnlyContain(e => e.Level >= LogLevel.Warning); } @@ -96,10 +97,23 @@ public class SecurityEventsTests SecurityEvents.AdminBypassRejected(logger, "/e", BypassRejectionReason.Expired); SecurityEvents.RateLimitTriggered(logger, "login", "/e"); SecurityEvents.MigrationFailure(logger, new InvalidOperationException("boom"), attempts: 1); + SecurityEvents.SetupTokenRejected(logger, "/Setup/owner"); logger.Entries.Select(e => e.EventId.Id).Should().OnlyHaveUniqueItems(); } + [Fact] + public void SetupTokenRejected_ShouldCarryTheEventNameAndId() + { + var logger = new CapturingLogger(); + + SecurityEvents.SetupTokenRejected(logger, "/Setup/owner"); + + var entry = logger.Entries.Single(); + entry.Message.Should().Contain(SecurityEventNames.SetupTokenRejected); + entry.EventId.Id.Should().Be(5007); + } + [Fact] public void MigrationFailure_ShouldBeCritical() { diff --git a/src/SlpModularCms.Core.Tests/Hosting/Proxy/ForwardedHeadersTests.cs b/src/SlpModularCms.Core.Tests/Hosting/Proxy/ForwardedHeadersTests.cs new file mode 100644 index 0000000..903e9e2 --- /dev/null +++ b/src/SlpModularCms.Core.Tests/Hosting/Proxy/ForwardedHeadersTests.cs @@ -0,0 +1,218 @@ +using System.Net; +using FluentAssertions; +using FsCheck; +using FsCheck.Fluent; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.RateLimiting; +using Microsoft.AspNetCore.TestHost; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using SlpModularCms.Core.Hosting; +using SlpModularCms.Core.Hosting.Proxy; +using Xunit; + +namespace SlpModularCms.Core.Tests.Hosting.Proxy; + +public class ForwardedHeadersSettingsTests +{ + [Fact] + public void Parse_ValidAddresses_AreReturned() + { + var result = ForwardedHeadersSettings.ParseKnownProxies(["192.168.1.102", " ::1 "]); + + result.Should().Equal(IPAddress.Parse("192.168.1.102"), IPAddress.IPv6Loopback); + } + + [Fact] + public void Parse_NullOrEmpty_MeansNoProxies() + { + ForwardedHeadersSettings.ParseKnownProxies(null).Should().BeEmpty(); + ForwardedHeadersSettings.ParseKnownProxies([]).Should().BeEmpty(); + } + + [Theory] + [InlineData("not-an-ip")] + [InlineData("")] + [InlineData("192.168.1.0/24")] + [InlineData("0.0.0.0")] + [InlineData("::")] + public void Parse_InvalidOrWildcard_Throws(string entry) + { + var act = () => ForwardedHeadersSettings.ParseKnownProxies([entry]); + + act.Should().Throw(); + } + + // PBT: every concrete (non-wildcard) IPv4 address round-trips through the parser. + [Fact] + public void Parse_AnyConcreteIPv4_RoundTrips() + { + var arb = Gen.Choose(0, 255).ArrayOf(4) + .Where(o => o.Any(x => x != 0)) + .Select(o => string.Join('.', o)) + .ToArbitrary(); + + Prop.ForAll(arb, text => + ForwardedHeadersSettings.ParseKnownProxies([text]).Single().ToString() == text) + .QuickCheckThrowOnFailure(); + } +} + +public class ClientPartitionKeyTests +{ + private static HttpContext ContextFor(IPAddress? address) + { + var context = new DefaultHttpContext(); + context.Connection.RemoteIpAddress = address; + return context; + } + + [Fact] + public void UnknownAddress_UsesFallbackKey() + { + ClientPartitionKey.For(ContextFor(null)).Should().Be(ClientPartitionKey.Unknown); + } + + [Fact] + public void MappedIPv4_EqualsPlainIPv4() + { + var plain = ClientPartitionKey.For(ContextFor(IPAddress.Parse("203.0.113.9"))); + var mapped = ClientPartitionKey.For(ContextFor(IPAddress.Parse("::ffff:203.0.113.9"))); + + mapped.Should().Be(plain); + } + + // PBT: same address -> same key; different addresses -> different keys. + [Fact] + public void Key_IsInjectiveOverAddresses() + { + var addr = Gen.Choose(0, 255).ArrayOf(4) + .Select(o => new IPAddress(o.Select(x => (byte)x).ToArray())); + var arb = Gen.Two(addr).ToArbitrary(); + + Prop.ForAll(arb, pair => + { + var (a, b) = pair; + var ka = ClientPartitionKey.For(ContextFor(a)); + var kb = ClientPartitionKey.For(ContextFor(b)); + return a.Equals(b) == (ka == kb); + }).QuickCheckThrowOnFailure(); + } +} + +public class ForwardedHeadersPipelineTests : IAsyncDisposable +{ + private readonly List _apps = []; + + public async ValueTask DisposeAsync() + { + foreach (var app in _apps) + { + await app.DisposeAsync(); + } + } + + // A tiny host composing the real extensions: peer address is faked from a test header, + // then forwarded headers (opt-in), then the real limiter policy "login" (limit 2 per window). + private async Task StartAsync(string? knownProxy) + { + var builder = WebApplication.CreateBuilder(); + builder.WebHost.UseTestServer(); + var config = new Dictionary { ["RateLimiting:Login:PermitLimit"] = "2" }; + if (knownProxy is not null) + { + config["ForwardedHeaders:KnownProxies:0"] = knownProxy; + } + + builder.Configuration.AddInMemoryCollection(config); + builder.Services.AddCmsForwardedHeaders(builder.Configuration); + builder.Services.AddCmsRateLimiting(builder.Configuration); + + var app = builder.Build(); + app.Use((context, next) => + { + if (context.Request.Headers.TryGetValue("X-Test-Peer", out var peer)) + { + context.Connection.RemoteIpAddress = IPAddress.Parse(peer.ToString()); + } + + return next(); + }); + app.UseCmsForwardedHeaders(); + app.UseRateLimiter(); + app.MapGet("/who", (HttpContext c) => $"{c.Connection.RemoteIpAddress}|{c.Request.Scheme}") + .RequireRateLimiting("login"); + + await app.StartAsync(); + _apps.Add(app); + return app.GetTestClient(); + } + + private static HttpRequestMessage Request(string peer, string? xff = null, string? proto = null) + { + var request = new HttpRequestMessage(HttpMethod.Get, "/who"); + request.Headers.Add("X-Test-Peer", peer); + if (xff is not null) request.Headers.Add("X-Forwarded-For", xff); + if (proto is not null) request.Headers.Add("X-Forwarded-Proto", proto); + return request; + } + + [Fact] + public async Task NoProxyConfigured_ForwardedHeadersAreIgnored_AndCallersShareTheProxyBucket() + { + var client = await StartAsync(knownProxy: null); + + var first = await client.SendAsync(Request("10.0.0.1", xff: "198.51.100.1", proto: "https")); + (await first.Content.ReadAsStringAsync()).Should().Be("10.0.0.1|http"); + + (await client.SendAsync(Request("10.0.0.1", xff: "198.51.100.2"))).StatusCode.Should().Be(HttpStatusCode.OK); + // Third request from a "different visitor" behind the same peer: shared bucket, as before. + (await client.SendAsync(Request("10.0.0.1", xff: "198.51.100.3"))).StatusCode + .Should().Be(HttpStatusCode.TooManyRequests); + } + + [Fact] + public async Task TrustedProxy_RealClientAddressAndSchemeAreUsed_AndBucketsAreSeparate() + { + var client = await StartAsync(knownProxy: "10.0.0.1"); + + var first = await client.SendAsync(Request("10.0.0.1", xff: "198.51.100.1", proto: "https")); + (await first.Content.ReadAsStringAsync()).Should().Be("198.51.100.1|https"); + + (await client.SendAsync(Request("10.0.0.1", xff: "198.51.100.1"))).StatusCode.Should().Be(HttpStatusCode.OK); + (await client.SendAsync(Request("10.0.0.1", xff: "198.51.100.1"))).StatusCode + .Should().Be(HttpStatusCode.TooManyRequests); + + // A different visitor behind the same proxy is not throttled by the first one. + (await client.SendAsync(Request("10.0.0.1", xff: "198.51.100.2"))).StatusCode.Should().Be(HttpStatusCode.OK); + } + + [Fact] + public async Task UntrustedPeer_CannotSpoofItsAddress() + { + var client = await StartAsync(knownProxy: "10.0.0.1"); + + var response = await client.SendAsync(Request("203.0.113.50", xff: "198.51.100.1", proto: "https")); + + (await response.Content.ReadAsStringAsync()).Should().Be("203.0.113.50|http"); + // Rotating the spoofed header does not buy fresh buckets. + (await client.SendAsync(Request("203.0.113.50", xff: "198.51.100.2"))).StatusCode.Should().Be(HttpStatusCode.OK); + (await client.SendAsync(Request("203.0.113.50", xff: "198.51.100.3"))).StatusCode + .Should().Be(HttpStatusCode.TooManyRequests); + } + + [Fact] + public void WildcardProxy_FailsAtStartup() + { + var config = new ConfigurationBuilder() + .AddInMemoryCollection(new Dictionary { ["ForwardedHeaders:KnownProxies:0"] = "0.0.0.0" }) + .Build(); + + var act = () => new ServiceCollection().AddCmsForwardedHeaders(config); + + act.Should().Throw(); + } +} diff --git a/src/SlpModularCms.Core.Tests/Hosting/Website/WebsitePathResolverPropertyTests.cs b/src/SlpModularCms.Core.Tests/Hosting/Website/WebsitePathResolverPropertyTests.cs index d181b97..58272b7 100644 --- a/src/SlpModularCms.Core.Tests/Hosting/Website/WebsitePathResolverPropertyTests.cs +++ b/src/SlpModularCms.Core.Tests/Hosting/Website/WebsitePathResolverPropertyTests.cs @@ -116,8 +116,10 @@ public class WebsitePathResolverPropertyTests(ITestOutputHelper output) return true; } + // A browser follows the Location as a URL: split path and query there, and the server + // sees the path decoded again. var split = first.Location.IndexOf('?'); - var targetPath = split < 0 ? first.Location : first.Location[..split]; + var targetPath = Uri.UnescapeDataString(split < 0 ? first.Location : first.Location[..split]); var targetQuery = split < 0 ? null : first.Location[split..]; return WebsitePathResolver.Resolve(targetPath, targetQuery, Exists) is not WebsiteResolution.Redirect; diff --git a/src/SlpModularCms.Core.Tests/Hosting/Website/WebsitePathResolverTests.cs b/src/SlpModularCms.Core.Tests/Hosting/Website/WebsitePathResolverTests.cs index 660fb3b..0754fa3 100644 --- a/src/SlpModularCms.Core.Tests/Hosting/Website/WebsitePathResolverTests.cs +++ b/src/SlpModularCms.Core.Tests/Hosting/Website/WebsitePathResolverTests.cs @@ -92,6 +92,18 @@ public class WebsitePathResolverTests public void TrailingSlash_RedirectsToStrippedPath_EvenWhenTargetDoesNotExist(string path, string target) => Resolve(path).Should().Be(Redirect(target)); + // Regression (found by the property test): the Location is built from the DECODED path and must + // be re-encoded, or /a%3Fb/ would redirect to /a?b (another resource), '#' would start a + // fragment and non-ASCII would end up raw in a header value. + [Theory] + [InlineData("/a?b/", "/a%3Fb")] + [InlineData("/a#b/", "/a%23b")] + [InlineData("/café/", "/caf%C3%A9")] + [InlineData("/50%/", "/50%25")] + [InlineData("/blog/", "/blog")] + public void Redirect_Location_IsPercentEncoded(string decodedPath, string expectedLocation) => + Resolve(decodedPath).Should().Be(Redirect(expectedLocation)); + [Fact] public void TrailingSlash_KeepsQueryString() => Resolve("/onbekend/", "?a=1").Should().Be(Redirect("/onbekend?a=1")); diff --git a/src/SlpModularCms.Core/Hosting/CmsHost.cs b/src/SlpModularCms.Core/Hosting/CmsHost.cs index 9f565ce..d2b8f7e 100644 --- a/src/SlpModularCms.Core/Hosting/CmsHost.cs +++ b/src/SlpModularCms.Core/Hosting/CmsHost.cs @@ -5,6 +5,7 @@ using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using SlpModularCms.Core.Hosting.Health; using SlpModularCms.Core.Hosting.Observability; +using SlpModularCms.Core.Hosting.Proxy; using SlpModularCms.Core.Hosting.Security; using SlpModularCms.Core.Hosting.Website; using Scalar.AspNetCore; @@ -52,6 +53,7 @@ public static class CmsHost // 2. Add Core Infrastructure builder.Services.AddCoreInfrastructure(builder.Configuration); builder.Services.AddCmsCors(builder.Configuration); + builder.Services.AddCmsForwardedHeaders(builder.Configuration); builder.Services.AddCmsRateLimiting(builder.Configuration); builder.Services.AddCmsHealthChecks(); builder.Services.AddCmsSecurityHeaders(builder.Configuration); @@ -97,6 +99,12 @@ public static class CmsHost // what makes a liveness-only health check trustworthy. app.MigrateCoreDatabase(); + // Opt-in (ForwardedHeaders:KnownProxies): makes the real visitor address and scheme visible to + // everything below (rate limiter partitions, HTTPS redirection, logging). Not added at all when + // no proxy is configured. First in the pipeline so the exception handler and all later + // middleware already see the corrected values. + app.UseCmsForwardedHeaders(); + // 5. Global Exception Handling app.UseExceptionHandler(); diff --git a/src/SlpModularCms.Core/Hosting/Observability/SecurityEventProcessor.cs b/src/SlpModularCms.Core/Hosting/Observability/SecurityEventProcessor.cs index fe59d46..dd0912b 100644 --- a/src/SlpModularCms.Core/Hosting/Observability/SecurityEventProcessor.cs +++ b/src/SlpModularCms.Core/Hosting/Observability/SecurityEventProcessor.cs @@ -24,7 +24,8 @@ public sealed class SecurityEventProcessor : ISentryEventProcessor SecurityEventNames.MasterApiKeyRejected, SecurityEventNames.AdminBypassRejected, SecurityEventNames.RateLimitTriggered, - SecurityEventNames.MigrationFailure + SecurityEventNames.MigrationFailure, + SecurityEventNames.SetupTokenRejected }.ToFrozenSet(StringComparer.Ordinal); /// diff --git a/src/SlpModularCms.Core/Hosting/Proxy/ClientPartitionKey.cs b/src/SlpModularCms.Core/Hosting/Proxy/ClientPartitionKey.cs new file mode 100644 index 0000000..bbc2373 --- /dev/null +++ b/src/SlpModularCms.Core/Hosting/Proxy/ClientPartitionKey.cs @@ -0,0 +1,23 @@ +using Microsoft.AspNetCore.Http; + +namespace SlpModularCms.Core.Hosting.Proxy; + +/// +/// The key that separates rate-limit buckets per client. It is the remote address as seen by the +/// pipeline (the real visitor once forwarded headers are trusted, otherwise the direct peer). +/// +public static class ClientPartitionKey +{ + public const string Unknown = "(unknown)"; + + public static string For(HttpContext context) + { + var address = context.Connection.RemoteIpAddress; + if (address is null) + { + return Unknown; + } + + return (address.IsIPv4MappedToIPv6 ? address.MapToIPv4() : address).ToString(); + } +} diff --git a/src/SlpModularCms.Core/Hosting/Proxy/ForwardedHeadersExtensions.cs b/src/SlpModularCms.Core/Hosting/Proxy/ForwardedHeadersExtensions.cs new file mode 100644 index 0000000..7f598c0 --- /dev/null +++ b/src/SlpModularCms.Core/Hosting/Proxy/ForwardedHeadersExtensions.cs @@ -0,0 +1,45 @@ +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.HttpOverrides; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; + +namespace SlpModularCms.Core.Hosting.Proxy; + +public static class ForwardedHeadersExtensions +{ + /// + /// Validates the ForwardedHeaders section and configures the framework middleware to + /// trust only the listed proxies (default trust of loopback is cleared, one hop only). + /// Nothing is observable until finds a proxy configured. + /// + public static IServiceCollection AddCmsForwardedHeaders(this IServiceCollection services, IConfiguration configuration) + { + var settings = configuration.GetSection(ForwardedHeadersSettings.SectionName).Get() + ?? new ForwardedHeadersSettings(); + var proxies = ForwardedHeadersSettings.ParseKnownProxies(settings.KnownProxies); + + services.AddSingleton(new ForwardedHeadersState(proxies.Count > 0)); + services.Configure(options => + { + options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto; + options.ForwardLimit = 1; + options.KnownProxies.Clear(); + options.KnownIPNetworks.Clear(); + foreach (var proxy in proxies) + { + options.KnownProxies.Add(proxy); + } + }); + + return services; + } + + /// Adds the forwarded-headers middleware only when at least one proxy is configured. + public static IApplicationBuilder UseCmsForwardedHeaders(this IApplicationBuilder app) + { + var state = app.ApplicationServices.GetService(); + return state is { Enabled: true } ? app.UseForwardedHeaders() : app; + } +} + +internal sealed record ForwardedHeadersState(bool Enabled); diff --git a/src/SlpModularCms.Core/Hosting/Proxy/ForwardedHeadersSettings.cs b/src/SlpModularCms.Core/Hosting/Proxy/ForwardedHeadersSettings.cs new file mode 100644 index 0000000..c6fdc30 --- /dev/null +++ b/src/SlpModularCms.Core/Hosting/Proxy/ForwardedHeadersSettings.cs @@ -0,0 +1,43 @@ +using System.Net; + +namespace SlpModularCms.Core.Hosting.Proxy; + +/// +/// Opt-in trust in a reverse proxy (section ForwardedHeaders). With no known proxy +/// configured the host ignores X-Forwarded-* headers completely, exactly as before. +/// +public sealed class ForwardedHeadersSettings +{ + public const string SectionName = "ForwardedHeaders"; + + /// IP addresses of the reverse proxies whose X-Forwarded-For/-Proto are trusted. + public string[] KnownProxies { get; set; } = []; + + /// + /// Parses and validates the configured proxy addresses. + /// Throws for an unparsable entry or a wildcard + /// (any-address) entry: trusting every sender would let any client spoof its address. + /// + public static IReadOnlyList ParseKnownProxies(IEnumerable? entries) + { + var result = new List(); + foreach (var entry in entries ?? []) + { + if (!IPAddress.TryParse(entry?.Trim(), out var address)) + { + throw new InvalidOperationException( + $"{SectionName}:KnownProxies contains an entry that is not an IP address."); + } + + if (address.Equals(IPAddress.Any) || address.Equals(IPAddress.IPv6Any)) + { + throw new InvalidOperationException( + $"{SectionName}:KnownProxies must not contain an any-address entry (0.0.0.0 or ::)."); + } + + result.Add(address); + } + + return result; + } +} diff --git a/src/SlpModularCms.Core/Hosting/ServiceCollectionExtensions.cs b/src/SlpModularCms.Core/Hosting/ServiceCollectionExtensions.cs index d8fdd6a..db4c8ff 100644 --- a/src/SlpModularCms.Core/Hosting/ServiceCollectionExtensions.cs +++ b/src/SlpModularCms.Core/Hosting/ServiceCollectionExtensions.cs @@ -14,6 +14,7 @@ using Microsoft.IdentityModel.Tokens; using SlpModularCms.Core.Availability; using SlpModularCms.Core.Data; using SlpModularCms.Core.Exceptions; +using SlpModularCms.Core.Hosting.Proxy; using SlpModularCms.Core.Hosting.Security; using SlpModularCms.Core.Identity.Authorization; using SlpModularCms.Core.Identity.Entities; @@ -157,43 +158,58 @@ public static class ServiceCollectionExtensions return ValueTask.CompletedTask; }; - options.AddFixedWindowLimiter("login", opt => + // Every named policy is partitioned per client address (ClientPartitionKey). Behind a + // reverse proxy that is only meaningful once ForwardedHeaders:KnownProxies is set; + // without it all callers share the proxy address, i.e. one bucket, as before. + options.AddPolicy("login", context => { var settings = configuration.GetSection("RateLimiting:Login"); - opt.PermitLimit = settings.GetValue("PermitLimit", 5); - opt.Window = TimeSpan.FromSeconds(settings.GetValue("WindowSeconds", 60)); - opt.QueueLimit = 0; + return RateLimitPartition.GetFixedWindowLimiter(ClientPartitionKey.For(context), _ => new FixedWindowRateLimiterOptions + { + PermitLimit = settings.GetValue("PermitLimit", 5), + Window = TimeSpan.FromSeconds(settings.GetValue("WindowSeconds", 60)), + QueueLimit = 0 + }); }); - options.AddSlidingWindowLimiter("refresh", opt => + options.AddPolicy("refresh", context => { var settings = configuration.GetSection("RateLimiting:Refresh"); - opt.PermitLimit = settings.GetValue("PermitLimit", 20); - opt.Window = TimeSpan.FromSeconds(settings.GetValue("WindowSeconds", 60)); - opt.SegmentsPerWindow = 4; - opt.QueueLimit = 0; + return RateLimitPartition.GetSlidingWindowLimiter(ClientPartitionKey.For(context), _ => new SlidingWindowRateLimiterOptions + { + PermitLimit = settings.GetValue("PermitLimit", 20), + Window = TimeSpan.FromSeconds(settings.GetValue("WindowSeconds", 60)), + SegmentsPerWindow = 4, + QueueLimit = 0 + }); }); // Guards the anonymous Sentry tunnel. Generous, because a burst of browser errors is // exactly when reporting matters most, but bounded, because the endpoint makes an // outbound HTTPS request per call. - options.AddFixedWindowLimiter(SentryTunnelExtensions.RateLimiterName, opt => + options.AddPolicy(SentryTunnelExtensions.RateLimiterName, context => { var settings = configuration.GetSection("RateLimiting:SentryTunnel"); - opt.PermitLimit = settings.GetValue("PermitLimit", 60); - opt.Window = TimeSpan.FromSeconds(settings.GetValue("WindowSeconds", 60)); - opt.QueueLimit = 0; + return RateLimitPartition.GetFixedWindowLimiter(ClientPartitionKey.For(context), _ => new FixedWindowRateLimiterOptions + { + PermitLimit = settings.GetValue("PermitLimit", 60), + Window = TimeSpan.FromSeconds(settings.GetValue("WindowSeconds", 60)), + QueueLimit = 0 + }); }); // Guards the anonymous public offerings listing (NFR-OFF-01) against scraping. // Only the public GET carries this policy — admin mutation endpoints are already // behind AdminOnly authentication (Offerings NFR Requirements Q1 = A). - options.AddFixedWindowLimiter("offerings-public", opt => + options.AddPolicy("offerings-public", context => { var settings = configuration.GetSection("RateLimiting:OfferingsPublic"); - opt.PermitLimit = settings.GetValue("PermitLimit", 120); - opt.Window = TimeSpan.FromSeconds(settings.GetValue("WindowSeconds", 60)); - opt.QueueLimit = 0; + return RateLimitPartition.GetFixedWindowLimiter(ClientPartitionKey.For(context), _ => new FixedWindowRateLimiterOptions + { + PermitLimit = settings.GetValue("PermitLimit", 120), + Window = TimeSpan.FromSeconds(settings.GetValue("WindowSeconds", 60)), + QueueLimit = 0 + }); }); }); diff --git a/src/SlpModularCms.Core/Hosting/Website/WebsitePathResolver.cs b/src/SlpModularCms.Core/Hosting/Website/WebsitePathResolver.cs index 50448b4..239ecd0 100644 --- a/src/SlpModularCms.Core/Hosting/Website/WebsitePathResolver.cs +++ b/src/SlpModularCms.Core/Hosting/Website/WebsitePathResolver.cs @@ -1,3 +1,5 @@ +using Microsoft.AspNetCore.Http; + namespace SlpModularCms.Core.Hosting.Website; /// @@ -138,13 +140,13 @@ public static class WebsitePathResolver { return !hasTrailingSlash && name == pageName ? new WebsiteResolution.ServeFile(pageName + ".html") - : new WebsiteResolution.Redirect("/" + pageName + query); + : new WebsiteResolution.Redirect(EncodePath("/" + pageName) + query); } // R11 - trailing slashes are stripped by a 301, whether or not the target exists. if (hasTrailingSlash) { - return new WebsiteResolution.Redirect(stripped + query); + return new WebsiteResolution.Redirect(EncodePath(stripped) + query); } // R8 - paths that look like files are served as they are (never lower-cased) or not found. @@ -158,6 +160,13 @@ public static class WebsitePathResolver return fileExists(directoryIndex) ? new WebsiteResolution.ServeFile(directoryIndex) : notFound; } + /// + /// The input path is decoded, but a Location header must be a valid URL reference: without this a + /// request for /a%3Fb/ would redirect to /a?b (a different resource), a '#' would + /// start a fragment, and non-ASCII characters would end up raw in a header value. + /// + private static string EncodePath(string decodedPath) => new PathString(decodedPath).ToUriComponent(); + private static bool HasForbiddenCharacters(string path) { foreach (var c in path) diff --git a/src/SlpModularCms.Core/Observability/SecurityEvents.cs b/src/SlpModularCms.Core/Observability/SecurityEvents.cs index 82d6a9d..fdef3a0 100644 --- a/src/SlpModularCms.Core/Observability/SecurityEvents.cs +++ b/src/SlpModularCms.Core/Observability/SecurityEvents.cs @@ -11,10 +11,11 @@ public static class SecurityEventNames public const string AdminBypassRejected = "admin_bypass_rejected"; public const string RateLimitTriggered = "rate_limit_triggered"; public const string MigrationFailure = "migration_failure"; + public const string SetupTokenRejected = "setup_token_rejected"; } /// -/// The six security events that alert rules are built on. +/// The seven security events that alert rules are built on. /// /// /// Why source-generated rather than plain log calls: @@ -32,7 +33,7 @@ public static class SecurityEventNames /// would break the day someone improves the wording — silently, because a rule that matches /// nothing looks exactly like a rule with nothing to match. /// -/// All six sit at Warning or above by construction, so they cross the Sentry event +/// All seven sit at Warning or above by construction, so they cross the Sentry event /// threshold rather than depending on a coincidence of configuration. /// public static partial class SecurityEvents @@ -43,6 +44,7 @@ public static partial class SecurityEvents public const int AdminBypassRejectedEventId = 5004; public const int RateLimitTriggeredEventId = 5005; public const int MigrationFailureEventId = 5006; + public const int SetupTokenRejectedEventId = 5007; /// /// Repeated occurrences suggest an attack or a forgotten password. Carries whether the @@ -82,6 +84,19 @@ public static partial class SecurityEvents public static void MigrationFailure(ILogger logger, Exception exception, int attempts) => MigrationFailureCore(logger, exception, SecurityEventNames.MigrationFailure, attempts); + /// + /// Someone tried to create the first administrator without the right setup token. Never carries + /// the presented token. + /// + public static void SetupTokenRejected(ILogger logger, string endpoint) => + SetupTokenRejectedCore(logger, SecurityEventNames.SetupTokenRejected, endpoint); + + [LoggerMessage( + EventId = SetupTokenRejectedEventId, + Level = LogLevel.Warning, + Message = "Security event {SecurityEvent}: setup token rejected on {Endpoint}")] + private static partial void SetupTokenRejectedCore(ILogger logger, string securityEvent, string endpoint); + [LoggerMessage( EventId = FailedLoginEventId, Level = LogLevel.Warning, diff --git a/src/SlpModularCms.Modules.Identity.Tests/Controllers/SetupControllerTests.cs b/src/SlpModularCms.Modules.Identity.Tests/Controllers/SetupControllerTests.cs index 5ec4c36..c2679bf 100644 --- a/src/SlpModularCms.Modules.Identity.Tests/Controllers/SetupControllerTests.cs +++ b/src/SlpModularCms.Modules.Identity.Tests/Controllers/SetupControllerTests.cs @@ -1,44 +1,70 @@ using FluentAssertions; +using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; +using Microsoft.Extensions.Logging; using NSubstitute; using SlpModularCms.Core.Identity.Models; using SlpModularCms.Core.Identity.Services; +using SlpModularCms.Core.Observability; using SlpModularCms.Modules.Identity.Controllers; +using SlpModularCms.Modules.Identity.Setup; namespace SlpModularCms.Modules.Identity.Tests.Controllers; public class SetupControllerTests { private readonly ISetupService _setupService = Substitute.For(); + private readonly ISetupTokenValidator _validator = Substitute.For(); + private readonly ILogger _logger = Substitute.For>(); + + public SetupControllerTests() + { + _validator.IsAuthorized(Arg.Any()).Returns(true); + _logger.IsEnabled(Arg.Any()).Returns(true); + } + + private SetupController NewController(string? tokenHeader = null) + { + var controller = new SetupController(_setupService, _validator, _logger) + { + ControllerContext = new ControllerContext { HttpContext = new DefaultHttpContext() } + }; + if (tokenHeader is not null) + { + controller.HttpContext.Request.Headers[SetupController.TokenHeader] = tokenHeader; + } + + return controller; + } [Fact] public async Task GetStatus_ReturnsOk_WithInitializedTrue_WhenSystemIsSetUp() { _setupService.IsSystemInitializedAsync().Returns(true); - var controller = new SetupController(_setupService); + var controller = NewController(); var result = await controller.GetStatus(); var ok = result.Should().BeOfType().Subject; - ok.Value.Should().BeEquivalentTo(new { Initialized = true }); + ok.Value.Should().BeEquivalentTo(new { Initialized = true, TokenRequired = false }); } [Fact] public async Task GetStatus_ReturnsOk_WithInitializedFalse_WhenSystemIsNotSetUp() { _setupService.IsSystemInitializedAsync().Returns(false); - var controller = new SetupController(_setupService); + var controller = NewController(); var result = await controller.GetStatus(); var ok = result.Should().BeOfType().Subject; - ok.Value.Should().BeEquivalentTo(new { Initialized = false }); + ok.Value.Should().BeEquivalentTo(new { Initialized = false, TokenRequired = false }); } [Fact] public async Task CreateOwner_ReturnsOk_WithSuccessMessage() { - var controller = new SetupController(_setupService); + var controller = NewController(); var result = await controller.CreateOwner(new CreateOwnerRequest("Owner", "owner@test.com", "Password1!")); @@ -46,4 +72,65 @@ public class SetupControllerTests ok.Value.Should().BeEquivalentTo(new { Message = "Systeem succesvol geïnitialiseerd. De eerste eigenaar is aangemaakt." }); await _setupService.Received(1).CreateInitialOwnerAsync("Owner", "owner@test.com", "Password1!"); } + + [Fact] + public async Task GetStatus_ReportsTokenRequired_WhenConfigured() + { + _setupService.IsSystemInitializedAsync().Returns(false); + _validator.TokenRequired.Returns(true); + + var result = await NewController().GetStatus(); + + result.Should().BeOfType().Which.Value + .Should().BeEquivalentTo(new { Initialized = false, TokenRequired = true }); + } + + [Fact] + public async Task CreateOwner_WithRejectedToken_Returns401_AndNeverCreatesTheOwner() + { + _validator.IsAuthorized("wrong").Returns(false); + + var result = await NewController("wrong").CreateOwner(new CreateOwnerRequest("O", "o@test.com", "Password1!")); + + result.Should().BeOfType().Which.StatusCode.Should().Be(StatusCodes.Status401Unauthorized); + await _setupService.DidNotReceiveWithAnyArgs().CreateInitialOwnerAsync(default!, default!, default!); + } + + [Fact] + public async Task CreateOwner_MissingAndWrongToken_GiveIdenticalResponses() + { + _validator.IsAuthorized(Arg.Any()).Returns(false); + var request = new CreateOwnerRequest("O", "o@test.com", "Password1!"); + + var missing = (ObjectResult)await NewController().CreateOwner(request); + var wrong = (ObjectResult)await NewController("guess").CreateOwner(request); + + missing.StatusCode.Should().Be(wrong.StatusCode); + missing.Value.Should().BeEquivalentTo(wrong.Value); + } + + [Fact] + public async Task CreateOwner_WithRejectedToken_LogsSecurityEvent_WithoutTheToken() + { + _validator.IsAuthorized("super-secret-guess").Returns(false); + + await NewController("super-secret-guess").CreateOwner(new CreateOwnerRequest("O", "o@test.com", "Password1!")); + + var logged = _logger.ReceivedCalls() + .Where(c => c.GetMethodInfo().Name == nameof(ILogger.Log)) + .ToList(); + logged.Should().NotBeEmpty(); + logged.Select(c => c.GetArguments()[2]!.ToString()!) + .Should().OnlyContain(m => !m.Contains("super-secret-guess")); + logged.Select(c => c.GetArguments()[2]!.ToString()!) + .Should().Contain(m => m.Contains(SecurityEventNames.SetupTokenRejected)); + } + + [Fact] + public async Task CreateOwner_PassesTheHeaderValueToTheValidator() + { + await NewController("abc").CreateOwner(new CreateOwnerRequest("O", "o@test.com", "Password1!")); + + _validator.Received(1).IsAuthorized("abc"); + } } diff --git a/src/SlpModularCms.Modules.Identity.Tests/Setup/SetupTokenValidatorTests.cs b/src/SlpModularCms.Modules.Identity.Tests/Setup/SetupTokenValidatorTests.cs new file mode 100644 index 0000000..d57f8ae --- /dev/null +++ b/src/SlpModularCms.Modules.Identity.Tests/Setup/SetupTokenValidatorTests.cs @@ -0,0 +1,92 @@ +using FluentAssertions; +using FsCheck; +using FsCheck.Fluent; +using Microsoft.Extensions.Options; +using SlpModularCms.Modules.Identity.Setup; + +namespace SlpModularCms.Modules.Identity.Tests.Setup; + +public class SetupTokenValidatorTests +{ + private static SetupTokenValidator With(string? token) => + new(Options.Create(new SetupOptions { Token = token })); + + [Theory] + [InlineData(null)] + [InlineData("")] + public void NoTokenConfigured_NothingRequired_EverythingAuthorized(string? configured) + { + var validator = With(configured); + + validator.TokenRequired.Should().BeFalse(); + validator.IsAuthorized(null).Should().BeTrue(); + validator.IsAuthorized("anything").Should().BeTrue(); + } + + [Fact] + public void ExactToken_IsAuthorized() + { + var validator = With("correct-horse-battery-staple-0123456789"); + + validator.TokenRequired.Should().BeTrue(); + validator.IsAuthorized("correct-horse-battery-staple-0123456789").Should().BeTrue(); + } + + [Theory] + [InlineData(null)] + [InlineData("")] + [InlineData("correct-horse-battery-staple-0123456789 ")] + [InlineData("CORRECT-HORSE-BATTERY-STAPLE-0123456789")] + [InlineData("correct")] + public void MissingOrDifferentToken_IsRejected(string? provided) + { + With("correct-horse-battery-staple-0123456789").IsAuthorized(provided).Should().BeFalse(); + } + + [Theory] + [InlineData(" ")] + [InlineData(" \t")] + public void WhitespaceOnlyToken_FailsOptionsValidation(string token) + { + SetupOptions.IsValid(new SetupOptions { Token = token }).Should().BeFalse(); + } + + [Theory] + [InlineData(null)] + [InlineData("")] + [InlineData("abc")] + public void NullEmptyOrRealToken_PassesOptionsValidation(string? token) + { + SetupOptions.IsValid(new SetupOptions { Token = token }).Should().BeTrue(); + } + + // PBT: only the exact configured token passes; any other string fails; never throws. + [Fact] + public void Property_OnlyTheExactTokenIsAccepted() + { + var tokens = ArbMap.Default.ArbFor().Generator + .Select(s => s.Get) + .Where(s => !string.IsNullOrWhiteSpace(s)); + var arb = Gen.Two(tokens).ToArbitrary(); + + Prop.ForAll(arb, pair => + { + var (configured, provided) = pair; + var validator = With(configured); + return validator.IsAuthorized(configured) + && validator.IsAuthorized(provided) == (provided == configured); + }).QuickCheckThrowOnFailure(); + } + + [Fact] + public void Property_NeverThrows_ForArbitraryInput() + { + var validator = With("configured-token"); + + Prop.ForAll(ArbMap.Default.ArbFor(), input => + { + validator.IsAuthorized(input); + return true; + }).QuickCheckThrowOnFailure(); + } +} diff --git a/src/SlpModularCms.Modules.Identity.Tests/SlpModularCms.Modules.Identity.Tests.csproj b/src/SlpModularCms.Modules.Identity.Tests/SlpModularCms.Modules.Identity.Tests.csproj index df40f08..349a152 100644 --- a/src/SlpModularCms.Modules.Identity.Tests/SlpModularCms.Modules.Identity.Tests.csproj +++ b/src/SlpModularCms.Modules.Identity.Tests/SlpModularCms.Modules.Identity.Tests.csproj @@ -14,6 +14,7 @@ + diff --git a/src/SlpModularCms.Modules.Identity/Controllers/SetupController.cs b/src/SlpModularCms.Modules.Identity/Controllers/SetupController.cs index 722c14b..681c1b2 100644 --- a/src/SlpModularCms.Modules.Identity/Controllers/SetupController.cs +++ b/src/SlpModularCms.Modules.Identity/Controllers/SetupController.cs @@ -1,6 +1,11 @@ +using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.RateLimiting; +using Microsoft.Extensions.Logging; using SlpModularCms.Core.Identity.Models; using SlpModularCms.Core.Identity.Services; +using SlpModularCms.Core.Observability; +using SlpModularCms.Modules.Identity.Setup; namespace SlpModularCms.Modules.Identity.Controllers; @@ -8,23 +13,42 @@ namespace SlpModularCms.Modules.Identity.Controllers; [Route("[controller]")] public class SetupController : ControllerBase { - private readonly ISetupService _setupService; + public const string TokenHeader = "X-Setup-Token"; - public SetupController(ISetupService setupService) + private readonly ISetupService _setupService; + private readonly ISetupTokenValidator _tokenValidator; + private readonly ILogger _logger; + + public SetupController( + ISetupService setupService, + ISetupTokenValidator tokenValidator, + ILogger logger) { _setupService = setupService; + _tokenValidator = tokenValidator; + _logger = logger; } [HttpGet("status")] + [EnableRateLimiting("login")] public async Task GetStatus() { var initialized = await _setupService.IsSystemInitializedAsync(); - return Ok(new { Initialized = initialized }); + return Ok(new { Initialized = initialized, TokenRequired = _tokenValidator.TokenRequired }); } [HttpPost("owner")] + [EnableRateLimiting("login")] public async Task CreateOwner([FromBody] CreateOwnerRequest request) { + // Missing and wrong tokens give the identical response, so the endpoint reveals nothing about + // whether a token exists or how close a guess was. The token itself is never logged. + if (!_tokenValidator.IsAuthorized(Request.Headers[TokenHeader].ToString())) + { + SecurityEvents.SetupTokenRejected(_logger, Request.Path); + return Problem(title: "Setup token ontbreekt of is onjuist.", statusCode: StatusCodes.Status401Unauthorized); + } + await _setupService.CreateInitialOwnerAsync(request.Name, request.Email, request.Password); return Ok(new { Message = "Systeem succesvol geïnitialiseerd. De eerste eigenaar is aangemaakt." }); } diff --git a/src/SlpModularCms.Modules.Identity/IdentityModule.cs b/src/SlpModularCms.Modules.Identity/IdentityModule.cs index a0cddd5..cd49f4e 100644 --- a/src/SlpModularCms.Modules.Identity/IdentityModule.cs +++ b/src/SlpModularCms.Modules.Identity/IdentityModule.cs @@ -1,7 +1,9 @@ using System.Diagnostics.CodeAnalysis; using Microsoft.AspNetCore.Builder; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Options; using SlpModularCms.Core.Modules; +using SlpModularCms.Modules.Identity.Setup; namespace SlpModularCms.Modules.Identity; @@ -13,7 +15,11 @@ public class IdentityModule : IModule public void RegisterServices(IServiceCollection services) { - // Specifieke services voor deze module (indien niet al in Core) + services.AddOptions() + .BindConfiguration(SetupOptions.SectionName) + .Validate(SetupOptions.IsValid, "Identity:Setup:Token must not consist only of whitespace.") + .ValidateOnStart(); + services.AddSingleton(); } public void UseModule(IApplicationBuilder app) diff --git a/src/SlpModularCms.Modules.Identity/Setup/SetupOptions.cs b/src/SlpModularCms.Modules.Identity/Setup/SetupOptions.cs new file mode 100644 index 0000000..3c31d95 --- /dev/null +++ b/src/SlpModularCms.Modules.Identity/Setup/SetupOptions.cs @@ -0,0 +1,24 @@ +namespace SlpModularCms.Modules.Identity.Setup; + +/// +/// Optional protection of the first-administrator setup (section Identity:Setup). +/// With no token configured the setup endpoints behave exactly as before. +/// +public sealed class SetupOptions +{ + public const string SectionName = "Identity:Setup"; + + /// The secret the person creating the first administrator must present. Empty = not required. + public string? Token { get; set; } + + /// True when a token is configured and therefore required. + public bool TokenRequired => !string.IsNullOrEmpty(Token); + + /// + /// A token that is set but consists only of whitespace is a configuration mistake (it would look + /// protected but could be guessed trivially), so it is rejected at startup. Null or empty means + /// "no token". + /// + public static bool IsValid(SetupOptions options) => + string.IsNullOrEmpty(options.Token) || !string.IsNullOrWhiteSpace(options.Token); +} diff --git a/src/SlpModularCms.Modules.Identity/Setup/SetupTokenValidator.cs b/src/SlpModularCms.Modules.Identity/Setup/SetupTokenValidator.cs new file mode 100644 index 0000000..67b71b1 --- /dev/null +++ b/src/SlpModularCms.Modules.Identity/Setup/SetupTokenValidator.cs @@ -0,0 +1,52 @@ +using System.Security.Cryptography; +using System.Text; +using Microsoft.Extensions.Options; + +namespace SlpModularCms.Modules.Identity.Setup; + +/// Decides whether a request may create the first administrator. +public interface ISetupTokenValidator +{ + /// True when a setup token is configured. + bool TokenRequired { get; } + + /// + /// True when no token is required, or when equals the configured one. + /// Never throws for any input. + /// + bool IsAuthorized(string? provided); +} + +/// +/// Compares SHA-256 digests with a fixed-time comparison, so neither the length nor the content of +/// the configured token leaks through response timing. +/// +public sealed class SetupTokenValidator : ISetupTokenValidator +{ + private readonly byte[]? _expectedDigest; + + public SetupTokenValidator(IOptions options) + { + var token = options.Value.Token; + _expectedDigest = string.IsNullOrEmpty(token) ? null : Hash(token); + } + + public bool TokenRequired => _expectedDigest is not null; + + public bool IsAuthorized(string? provided) + { + if (_expectedDigest is null) + { + return true; + } + + if (string.IsNullOrEmpty(provided)) + { + return false; + } + + return CryptographicOperations.FixedTimeEquals(_expectedDigest, Hash(provided)); + } + + private static byte[] Hash(string value) => SHA256.HashData(Encoding.UTF8.GetBytes(value)); +}