diff --git a/aidlc-docs/features/contact-forms-module/aidlc-state.md b/aidlc-docs/features/contact-forms-module/aidlc-state.md index a7ddf1b..d62d076 100644 --- a/aidlc-docs/features/contact-forms-module/aidlc-state.md +++ b/aidlc-docs/features/contact-forms-module/aidlc-state.md @@ -5,7 +5,7 @@ - **Feature Slug**: contact-forms-module - **Project Type**: Brownfield - **Start Date**: 2026-11-09 -- **Current Stage**: CONSTRUCTION - CMS-U3b and CMS-U4 Code Generation Part 1 (plans awaiting approval by Redesign - SLS) +- **Current Stage**: CONSTRUCTION - CMS-U3b built and committed; CMS-U4 in progress - **Branch**: feature/contact-forms-module (worktree ..SlpModularCms-contact-forms, from master d9cc539; main checkout stays on feature/identity-email-notifications — never switch it) ## Workspace State diff --git a/aidlc-docs/features/contact-forms-module/construction/cms-u3b-openapi-export/code/summary.md b/aidlc-docs/features/contact-forms-module/construction/cms-u3b-openapi-export/code/summary.md new file mode 100644 index 0000000..0d981bb --- /dev/null +++ b/aidlc-docs/features/contact-forms-module/construction/cms-u3b-openapi-export/code/summary.md @@ -0,0 +1,25 @@ +# CMS-U3b openapi-export: code summary + +## Result +Committed `openapi/slpsoftware.v1.json`: the OpenAPI 3.1 document of the SlpSoftware host (Offerings, Contact, Identity, Availability, Master, System). **Convention: one file per host, named after the host** (`openapi/slpsoftware.v1.json` now, `openapi/andreaslopfotografie.v1.json` when that host exists on the base branch). It is the single source from which the frontend client (`cms-client`) generates its types. + +Regenerate after an intended API change: `UPDATE_OPENAPI=1 dotnet test --filter OpenApiSnapshot` (needs the database like the other pipeline tests). Without the variable the same test fails when the served document differs from the file, with that command in its message (drift detection was verified by changing one value in the file). + +Normalized form (so the diff is meaningful): no `servers` (derived from the request host), object keys in ordinal order everywhere, 2-space indentation, LF, trailing newline. Reviewed for hosts, addresses and secrets; the tests assert there are none. + +## Contact contract in the document (module-level, Core untouched) +`ContactOpenApiDocumentTransformer`, registered from `ContactModule` through the named options of document `v1`: +- Reusable `components.responses`: `Validation` (400, problem+json, schema `ValidationProblem` with `errors` = map of field name -> array of `required|tooLong|invalid|expired`), `TooLarge` (413), `RateLimited` (429 with the `Retry-After` header); schemas `Problem`, `ValidationProblem`. +- `POST /api/v1/contact-messages`: required header `Idempotency-Key` (uuid); request body required, exactly one `ContactMessageRequest` (`required`: name, email, subject, message, hpCheck, token; `maxLength` 100/254/100/2000/0, plain `string` types; `captchaToken` nullable); responses 202, 400, 404 (form closed), 413, 429. +- `GET /api/v1/contact-messages/token`: 200 (`ContactTokenResponse`), 404 (form closed), 429. +- The contact controller is not an `[ApiController]` (own error shape), so it carries `[ApiExplorerSettings(IgnoreApi = false)]` to appear in the document; `[ProducesResponseType]` attributes (with explicit content types) drive its operations. + +## Notes +- Microsoft.OpenApi 2.x model: everything above could be expressed through the document transformer; nothing had to be faked. Minor generator quirks kept as generated (e.g. nullable unions elsewhere in the document). +- The document is of the host as composed: operations of every loaded module appear. Routes that are closed at runtime (`Contact:Enabled=false`) are still documented; the 404 "form closed" response says so. + +## Side fix found while doing this +Problem details of the 400 answer are explicitly `application/problem+json` again after a class-level `[Produces]` experiment was rejected (it overrides the content type); covered by the existing pipeline test and a new controller assertion. + +## Verification (real output) +Build 0 errors. Contact.Tests 117 passed (4 new OpenApiSnapshot tests: equality with the committed file, contract content incl. header/required/maxLength/reusable responses/error codes, no hosts/addresses/secrets, deterministic normalization), Core 205, Availability 95, Offerings 86, Identity 37, Master 57, Api.Tests 4; temporary MariaDB used and removed afterwards. diff --git a/aidlc-docs/features/contact-forms-module/construction/plans/cms-u3b-openapi-export-code-generation-plan.md b/aidlc-docs/features/contact-forms-module/construction/plans/cms-u3b-openapi-export-code-generation-plan.md index ca129a4..75e646e 100644 --- a/aidlc-docs/features/contact-forms-module/construction/plans/cms-u3b-openapi-export-code-generation-plan.md +++ b/aidlc-docs/features/contact-forms-module/construction/plans/cms-u3b-openapi-export-code-generation-plan.md @@ -8,22 +8,22 @@ Phase 1, right after CMS-U3. Contract: "the definitive OpenAPI document is gener - `.NET 10`'s OpenAPI uses `Microsoft.OpenApi` 2.x types; the transformers are written against that model (risk noted below). ## Behaviour -1. **Committed file** `openapi/cms-api.v1.json` (repo root), the OpenAPI document of the SlpSoftware host (Offerings, Contact, Identity, Availability, Master, System). Written deterministically: `servers` removed (it is derived from the request host), keys in the order the generator emits, 2-space indentation, LF line endings, trailing newline. +1. **Committed file** `openapi/slpsoftware.v1.json` (repo root), the OpenAPI document of the SlpSoftware host (Offerings, Contact, Identity, Availability, Master, System). Written deterministically: `servers` removed (it is derived from the request host), keys in the order the generator emits, 2-space indentation, LF line endings, trailing newline. 2. **Snapshot test** (pipeline test, needs the database like the other pipeline tests): fetches `/openapi/v1.json` from the real host, normalizes it the same way, and compares it with the committed file; any drift fails the test with a message that names `UPDATE_OPENAPI=1`. With `UPDATE_OPENAPI=1` the test rewrites the file instead (and still passes), so regenerating is one command: `UPDATE_OPENAPI=1 dotnet test --filter OpenApiSnapshot`. 3. **Contact contract details in the document** (module-level transformers): - Reusable `components.responses`: `Validation` (400, `application/problem+json`, `ValidationProblem` with `errors` map of arrays of the codes `required|tooLong|invalid|expired`), `TooLarge` (413), `RateLimited` (429 with the `Retry-After` header, `Problem`), plus schemas `Problem` and `ValidationProblem`; referenced by the contact operations. - `POST /api/v1/contact-messages`: required header parameter `Idempotency-Key` (uuid); request body schema marks `name, email, subject, message, hpCheck, token` as required with the contract's `maxLength` values (100, 254, 100, 2000, 0 for `hpCheck`), `captchaToken` nullable; responses 202/400/413/429 (404 is documented as "form closed"). - `GET /api/v1/contact-messages/token`: 200 (`ContactToken`: `token`, `minSeconds`, `captcha` nullable object) and 429; 404 "form closed". - Attributes (`[ProducesResponseType]`) on the public contact actions drive the operations; the transformers only add what attributes cannot express (components, header, required/maxLength). -4. **cms-client note**: the file is the single source for generated types; the Andrea host will get its own file when it exists on the base branch (name per host, e.g. `openapi/andrea.v1.json`); this unit documents the convention in the file's README line in the summary. +4. **cms-client note**: the file is the single source for generated types; the Andrea host will get `openapi/andreaslopfotografie.v1.json` when it exists on the base branch (name = host name); this unit documents the convention in the file's README line in the summary. ## Steps -- [ ] **Step 1 — Attributes**: `[ProducesResponseType]` on `GetToken` and `Submit` (and `[ProducesResponseType<...>]` for the offerings list is already inferred by return types; nothing else is touched). -- [ ] **Step 2 — Transformers** in `Modules.Contact/OpenApi/`: `ContactOpenApiDocumentTransformer` (components), `ContactOpenApiOperationTransformer` (header, response refs), `ContactOpenApiSchemaTransformer` (required/maxLength). Registered from `ContactModule.RegisterServices` via `services.Configure("v1", ...)`. -- [ ] **Step 3 — Snapshot test + helper** in `Contact.Tests/Pipeline/OpenApiSnapshotTests.cs`: normalization (drop `servers`, stable formatting), repo-root lookup (walk up to `SlpModularCms.sln`), `UPDATE_OPENAPI=1` rewrite, a failing message with the exact regeneration command. Plus unit assertions on the fetched document (not only equality with the file): the contract details in item 3 exist (header required, reusable responses present, required fields and maxLength), so a regenerated file cannot silently lose them. -- [ ] **Step 4 — Generate and commit** `openapi/cms-api.v1.json`; review it (no PII, no secrets, no host names, no example addresses). -- [ ] **Step 5 — Verification (automatic)**: build; Contact.Tests (pipeline against a temporary MariaDB); full solution tests; real output. The test is run twice: once with `UPDATE_OPENAPI=1`, once without (must pass unchanged). -- [ ] **Step 6 — Docs/commit**: summary (how to regenerate, how the frontend consumes it, convention per host); one commit; no push. +- [x] **Step 1 — Attributes**: `[ProducesResponseType]` on `GetToken` and `Submit` (and `[ProducesResponseType<...>]` for the offerings list is already inferred by return types; nothing else is touched). +- [x] **Step 2 — Transformers** in `Modules.Contact/OpenApi/`: `ContactOpenApiDocumentTransformer` (components), `ContactOpenApiOperationTransformer` (header, response refs), `ContactOpenApiSchemaTransformer` (required/maxLength). Registered from `ContactModule.RegisterServices` via `services.Configure("v1", ...)`. +- [x] **Step 3 — Snapshot test + helper** in `Contact.Tests/Pipeline/OpenApiSnapshotTests.cs`: normalization (drop `servers`, stable formatting), repo-root lookup (walk up to `SlpModularCms.sln`), `UPDATE_OPENAPI=1` rewrite, a failing message with the exact regeneration command. Plus unit assertions on the fetched document (not only equality with the file): the contract details in item 3 exist (header required, reusable responses present, required fields and maxLength), so a regenerated file cannot silently lose them. +- [x] **Step 4 — Generate and commit** `openapi/slpsoftware.v1.json`; review it (no PII, no secrets, no host names, no example addresses). +- [x] **Step 5 — Verification (automatic)**: build; Contact.Tests (pipeline against a temporary MariaDB); full solution tests; real output. The test is run twice: once with `UPDATE_OPENAPI=1`, once without (must pass unchanged). +- [x] **Step 6 — Docs/commit**: summary (how to regenerate, how the frontend consumes it, convention per host); one commit; no push. ## Explicitly NOT touched Core (`AddOpenApi`, `MapOpenApi`), any endpoint behaviour, other modules' controllers (their operations simply appear in the document as generated), the Andrea host (not on the base branch), frontend. @@ -31,4 +31,4 @@ Core (`AddOpenApi`, `MapOpenApi`), any endpoint behaviour, other modules' contro ## Risks / open points - The Microsoft.OpenApi 2.x model differs from 1.x examples found online; if a detail cannot be expressed through the transformer API, the unit documents it in the summary instead of faking it, and the test asserts what the document really contains. - The file will be large (the whole host API). It is committed as is; reviewers diff it like code. -- Needs SLS confirmation: file name `openapi/cms-api.v1.json` for the SlpSoftware host (per-host naming convention proposed above). +- Needs SLS confirmation: file name per host: `openapi/slpsoftware.v1.json` (approved). diff --git a/openapi/slpsoftware.v1.json b/openapi/slpsoftware.v1.json new file mode 100644 index 0000000..b6b6248 --- /dev/null +++ b/openapi/slpsoftware.v1.json @@ -0,0 +1,1573 @@ +{ + "components": { + "responses": { + "RateLimited": { + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + }, + "description": "Too many requests. Retry after the number of seconds in the Retry-After header.", + "headers": { + "Retry-After": { + "description": "Seconds to wait before retrying.", + "schema": { + "format": "int32", + "type": "integer" + } + } + } + }, + "TooLarge": { + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + }, + "description": "The request body is too large." + }, + "Validation": { + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/ValidationProblem" + } + } + }, + "description": "Validation failed (also an expired, forged or other-site token as errors.token=[\"expired\"], a missing or non-UUID Idempotency-Key, and an unreadable body as errors.body=[\"invalid\"])." + } + }, + "schemas": { + "AvailabilityStatus": { + "type": "integer" + }, + "ChangePasswordRequest": { + "properties": { + "currentPassword": { + "type": "string" + }, + "newPassword": { + "type": "string" + } + }, + "required": [ + "currentPassword", + "newPassword" + ], + "type": "object" + }, + "ChangeRoleRequest": { + "properties": { + "newRole": { + "type": "string" + } + }, + "required": [ + "newRole" + ], + "type": "object" + }, + "CompleteSetupRequest": { + "properties": { + "password": { + "type": "string" + }, + "token": { + "type": "string" + } + }, + "required": [ + "token", + "password" + ], + "type": "object" + }, + "ContactCaptchaInfo": { + "properties": { + "provider": { + "type": "string" + }, + "siteKey": { + "type": "string" + } + }, + "required": [ + "provider", + "siteKey" + ], + "type": "object" + }, + "ContactMessageRequest": { + "properties": { + "captchaToken": { + "type": [ + "null", + "string" + ] + }, + "email": { + "maxLength": 254, + "type": "string" + }, + "hpCheck": { + "maxLength": 0, + "type": "string" + }, + "message": { + "maxLength": 2000, + "type": "string" + }, + "name": { + "maxLength": 100, + "type": "string" + }, + "subject": { + "maxLength": 100, + "type": "string" + }, + "token": { + "type": "string" + } + }, + "required": [ + "name", + "email", + "subject", + "message", + "hpCheck", + "token" + ], + "type": "object" + }, + "ContactTokenResponse": { + "properties": { + "captcha": { + "oneOf": [ + { + "type": "null" + }, + { + "$ref": "#/components/schemas/ContactCaptchaInfo" + } + ] + }, + "minSeconds": { + "format": "int32", + "pattern": "^-?(?:0|[1-9]\\d*)$", + "type": [ + "integer", + "string" + ] + }, + "token": { + "type": "string" + } + }, + "required": [ + "token", + "minSeconds", + "captcha" + ], + "type": "object" + }, + "CreateCmsInstanceRequest": { + "properties": { + "apiKey": { + "type": "string" + }, + "name": { + "type": "string" + }, + "url": { + "type": "string" + } + }, + "required": [ + "name", + "url", + "apiKey" + ], + "type": "object" + }, + "CreateOfferingRequest": { + "properties": { + "categoryId": { + "format": "uuid", + "type": [ + "null", + "string" + ] + }, + "ctaLabel": { + "type": "string" + }, + "description": { + "type": "string" + }, + "featured": { + "default": false, + "type": "boolean" + }, + "features": { + "items": { + "type": "string" + }, + "type": "array" + }, + "price": { + "type": "string" + }, + "priceNote": { + "type": "string" + }, + "slug": { + "type": [ + "null", + "string" + ] + }, + "title": { + "type": "string" + } + }, + "required": [ + "title", + "description", + "price", + "priceNote", + "features", + "ctaLabel" + ], + "type": "object" + }, + "CreateOwnerRequest": { + "properties": { + "email": { + "type": "string" + }, + "name": { + "type": "string" + }, + "password": { + "type": "string" + } + }, + "required": [ + "name", + "email", + "password" + ], + "type": "object" + }, + "InviteUserRequest": { + "properties": { + "email": { + "type": "string" + }, + "role": { + "type": "string" + } + }, + "required": [ + "email", + "role" + ], + "type": "object" + }, + "LoginRequest": { + "properties": { + "email": { + "type": "string" + }, + "password": { + "type": "string" + } + }, + "required": [ + "email", + "password" + ], + "type": "object" + }, + "OfferingCategoryRequest": { + "properties": { + "name": { + "type": "string" + } + }, + "required": [ + "name" + ], + "type": "object" + }, + "Problem": { + "description": "RFC 9457 problem details. Only the standard members are sent; nothing about the limiter, the policy or the caller.", + "properties": { + "status": { + "format": "int32", + "type": "integer" + }, + "title": { + "type": "string" + }, + "type": { + "type": "string" + } + }, + "type": "object" + }, + "ProblemDetails": { + "properties": { + "detail": { + "type": [ + "null", + "string" + ] + }, + "instance": { + "type": [ + "null", + "string" + ] + }, + "status": { + "format": "int32", + "pattern": "^-?(?:0|[1-9]\\d*)$", + "type": [ + "null", + "integer", + "string" + ] + }, + "title": { + "type": [ + "null", + "string" + ] + }, + "type": { + "type": [ + "null", + "string" + ] + } + }, + "type": "object" + }, + "PushStatusRequest": { + "properties": { + "disableMessage": { + "type": [ + "null", + "string" + ] + }, + "isAvailable": { + "type": "boolean" + } + }, + "required": [ + "isAvailable", + "disableMessage" + ], + "type": "object" + }, + "ReceivedResponse": { + "properties": { + "status": { + "type": "string" + } + }, + "required": [ + "status" + ], + "type": "object" + }, + "RegisterMasterRequest": { + "properties": { + "masterUrl": { + "type": "string" + } + }, + "required": [ + "masterUrl" + ], + "type": "object" + }, + "ReorderOfferingsRequest": { + "properties": { + "orderedIds": { + "items": { + "format": "uuid", + "type": "string" + }, + "type": "array" + } + }, + "required": [ + "orderedIds" + ], + "type": "object" + }, + "SetUserActiveRequest": { + "properties": { + "isActive": { + "type": "boolean" + } + }, + "required": [ + "isActive" + ], + "type": "object" + }, + "UpdateOfferingRequest": { + "properties": { + "categoryId": { + "format": "uuid", + "type": [ + "null", + "string" + ] + }, + "ctaLabel": { + "type": "string" + }, + "description": { + "type": "string" + }, + "featured": { + "default": false, + "type": "boolean" + }, + "features": { + "items": { + "type": "string" + }, + "type": "array" + }, + "price": { + "type": "string" + }, + "priceNote": { + "type": "string" + }, + "slug": { + "type": [ + "null", + "string" + ] + }, + "title": { + "type": "string" + } + }, + "required": [ + "title", + "description", + "price", + "priceNote", + "features", + "ctaLabel" + ], + "type": "object" + }, + "UpdateProfileRequest": { + "properties": { + "email": { + "type": "string" + }, + "name": { + "type": "string" + } + }, + "required": [ + "name", + "email" + ], + "type": "object" + }, + "UpdateStatusRequest": { + "properties": { + "newStatus": { + "$ref": "#/components/schemas/AvailabilityStatus" + }, + "reason": { + "type": [ + "null", + "string" + ] + } + }, + "required": [ + "newStatus", + "reason" + ], + "type": "object" + }, + "ValidationProblem": { + "description": "A 400 answer. 'errors' maps the JSON field name (name, email, subject, message, token, idempotencyKey, body) to its error codes; the client maps codes to texts.", + "properties": { + "errors": { + "additionalProperties": { + "items": { + "enum": [ + "required", + "tooLong", + "invalid", + "expired" + ], + "type": "string" + }, + "type": "array" + }, + "type": "object" + }, + "status": { + "format": "int32", + "type": "integer" + }, + "title": { + "type": "string" + }, + "type": { + "type": "string" + } + }, + "type": "object" + }, + "ValidationProblemDetails": { + "properties": { + "detail": { + "type": [ + "null", + "string" + ] + }, + "errors": { + "additionalProperties": { + "items": { + "type": "string" + }, + "type": "array" + }, + "type": "object" + }, + "instance": { + "type": [ + "null", + "string" + ] + }, + "status": { + "format": "int32", + "pattern": "^-?(?:0|[1-9]\\d*)$", + "type": [ + "null", + "integer", + "string" + ] + }, + "title": { + "type": [ + "null", + "string" + ] + }, + "type": { + "type": [ + "null", + "string" + ] + } + }, + "type": "object" + } + } + }, + "info": { + "title": "SlpModularCms.Api.SlpSoftware | v1", + "version": "1.0.0" + }, + "openapi": "3.1.1", + "paths": { + "/api/v1/Availability/admin/status": { + "post": { + "requestBody": { + "content": { + "application/*+json": { + "schema": { + "$ref": "#/components/schemas/UpdateStatusRequest" + } + }, + "application/json": { + "schema": { + "$ref": "#/components/schemas/UpdateStatusRequest" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/UpdateStatusRequest" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "OK" + } + }, + "tags": [ + "Availability" + ] + } + }, + "/api/v1/Availability/status": { + "get": { + "responses": { + "200": { + "description": "OK" + } + }, + "tags": [ + "Availability" + ] + } + }, + "/api/v1/CmsInstances": { + "get": { + "responses": { + "200": { + "description": "OK" + } + }, + "tags": [ + "CmsInstance" + ] + }, + "post": { + "requestBody": { + "content": { + "application/*+json": { + "schema": { + "$ref": "#/components/schemas/CreateCmsInstanceRequest" + } + }, + "application/json": { + "schema": { + "$ref": "#/components/schemas/CreateCmsInstanceRequest" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/CreateCmsInstanceRequest" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "OK" + } + }, + "tags": [ + "CmsInstance" + ] + } + }, + "/api/v1/CmsInstances/{id}/status": { + "put": { + "parameters": [ + { + "in": "path", + "name": "id", + "required": true, + "schema": { + "format": "uuid", + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/*+json": { + "schema": { + "$ref": "#/components/schemas/UpdateStatusRequest" + } + }, + "application/json": { + "schema": { + "$ref": "#/components/schemas/UpdateStatusRequest" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/UpdateStatusRequest" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "OK" + } + }, + "tags": [ + "CmsInstance" + ] + } + }, + "/api/v1/Invitation/complete": { + "post": { + "requestBody": { + "content": { + "application/*+json": { + "schema": { + "$ref": "#/components/schemas/CompleteSetupRequest" + } + }, + "application/json": { + "schema": { + "$ref": "#/components/schemas/CompleteSetupRequest" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/CompleteSetupRequest" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "OK" + } + }, + "tags": [ + "Invitation" + ] + } + }, + "/api/v1/Invitation/validate": { + "get": { + "parameters": [ + { + "in": "query", + "name": "token", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK" + } + }, + "tags": [ + "Invitation" + ] + } + }, + "/api/v1/Master/register": { + "post": { + "requestBody": { + "content": { + "application/*+json": { + "schema": { + "$ref": "#/components/schemas/RegisterMasterRequest" + } + }, + "application/json": { + "schema": { + "$ref": "#/components/schemas/RegisterMasterRequest" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/RegisterMasterRequest" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "OK" + } + }, + "tags": [ + "Master" + ] + } + }, + "/api/v1/Master/registered-url": { + "get": { + "responses": { + "200": { + "description": "OK" + } + }, + "tags": [ + "Master" + ] + } + }, + "/api/v1/Master/status": { + "post": { + "requestBody": { + "content": { + "application/*+json": { + "schema": { + "$ref": "#/components/schemas/PushStatusRequest" + } + }, + "application/json": { + "schema": { + "$ref": "#/components/schemas/PushStatusRequest" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/PushStatusRequest" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "OK" + } + }, + "tags": [ + "Master" + ] + } + }, + "/api/v1/Setup/owner": { + "post": { + "requestBody": { + "content": { + "application/*+json": { + "schema": { + "$ref": "#/components/schemas/CreateOwnerRequest" + } + }, + "application/json": { + "schema": { + "$ref": "#/components/schemas/CreateOwnerRequest" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/CreateOwnerRequest" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "OK" + } + }, + "tags": [ + "Setup" + ] + } + }, + "/api/v1/Setup/status": { + "get": { + "responses": { + "200": { + "description": "OK" + } + }, + "tags": [ + "Setup" + ] + } + }, + "/api/v1/SlaveStatus": { + "get": { + "responses": { + "200": { + "description": "OK" + } + }, + "tags": [ + "SlaveStatus" + ] + } + }, + "/api/v1/System/capabilities": { + "get": { + "responses": { + "200": { + "description": "OK" + } + }, + "tags": [ + "System" + ] + } + }, + "/api/v1/Users": { + "get": { + "responses": { + "200": { + "description": "OK" + } + }, + "tags": [ + "Users" + ] + } + }, + "/api/v1/Users/invite": { + "post": { + "requestBody": { + "content": { + "application/*+json": { + "schema": { + "$ref": "#/components/schemas/InviteUserRequest" + } + }, + "application/json": { + "schema": { + "$ref": "#/components/schemas/InviteUserRequest" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/InviteUserRequest" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "OK" + } + }, + "tags": [ + "Users" + ] + } + }, + "/api/v1/Users/me": { + "put": { + "requestBody": { + "content": { + "application/*+json": { + "schema": { + "$ref": "#/components/schemas/UpdateProfileRequest" + } + }, + "application/json": { + "schema": { + "$ref": "#/components/schemas/UpdateProfileRequest" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/UpdateProfileRequest" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "OK" + } + }, + "tags": [ + "Users" + ] + } + }, + "/api/v1/Users/{userId}": { + "delete": { + "parameters": [ + { + "in": "path", + "name": "userId", + "required": true, + "schema": { + "format": "uuid", + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK" + } + }, + "tags": [ + "Users" + ] + } + }, + "/api/v1/Users/{userId}/active": { + "put": { + "parameters": [ + { + "in": "path", + "name": "userId", + "required": true, + "schema": { + "format": "uuid", + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/*+json": { + "schema": { + "$ref": "#/components/schemas/SetUserActiveRequest" + } + }, + "application/json": { + "schema": { + "$ref": "#/components/schemas/SetUserActiveRequest" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/SetUserActiveRequest" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "OK" + } + }, + "tags": [ + "Users" + ] + } + }, + "/api/v1/Users/{userId}/role": { + "put": { + "parameters": [ + { + "in": "path", + "name": "userId", + "required": true, + "schema": { + "format": "uuid", + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/*+json": { + "schema": { + "$ref": "#/components/schemas/ChangeRoleRequest" + } + }, + "application/json": { + "schema": { + "$ref": "#/components/schemas/ChangeRoleRequest" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/ChangeRoleRequest" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "OK" + } + }, + "tags": [ + "Users" + ] + } + }, + "/api/v1/auth/change-password": { + "post": { + "requestBody": { + "content": { + "application/*+json": { + "schema": { + "$ref": "#/components/schemas/ChangePasswordRequest" + } + }, + "application/json": { + "schema": { + "$ref": "#/components/schemas/ChangePasswordRequest" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/ChangePasswordRequest" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "OK" + } + }, + "tags": [ + "Auth" + ] + } + }, + "/api/v1/auth/login": { + "post": { + "requestBody": { + "content": { + "application/*+json": { + "schema": { + "$ref": "#/components/schemas/LoginRequest" + } + }, + "application/json": { + "schema": { + "$ref": "#/components/schemas/LoginRequest" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/LoginRequest" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "OK" + } + }, + "tags": [ + "Auth" + ] + } + }, + "/api/v1/auth/refresh": { + "post": { + "responses": { + "200": { + "description": "OK" + } + }, + "tags": [ + "Auth" + ] + } + }, + "/api/v1/auth/revoke": { + "post": { + "responses": { + "200": { + "description": "OK" + } + }, + "tags": [ + "Auth" + ] + } + }, + "/api/v1/contact-messages": { + "post": { + "parameters": [ + { + "description": "A UUID chosen by the client per attempt series. A replay within 24 hours is answered with the same 202 without storing the message twice.", + "in": "header", + "name": "Idempotency-Key", + "required": true, + "schema": { + "format": "uuid", + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ContactMessageRequest" + } + } + }, + "required": true + }, + "responses": { + "202": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ReceivedResponse" + } + } + }, + "description": "Accepted" + }, + "400": { + "$ref": "#/components/responses/Validation" + }, + "404": { + "description": "The contact form is closed on this site (the website shows its mailto fallback)." + }, + "413": { + "$ref": "#/components/responses/TooLarge" + }, + "429": { + "$ref": "#/components/responses/RateLimited" + } + }, + "tags": [ + "ContactMessages" + ] + } + }, + "/api/v1/contact-messages/token": { + "get": { + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ContactTokenResponse" + } + } + }, + "description": "OK" + }, + "404": { + "description": "The contact form is closed on this site (the website shows its mailto fallback)." + }, + "429": { + "$ref": "#/components/responses/RateLimited" + } + }, + "tags": [ + "ContactMessages" + ] + } + }, + "/api/v1/offerings": { + "get": { + "responses": { + "200": { + "description": "OK" + } + }, + "tags": [ + "Offerings" + ] + }, + "post": { + "requestBody": { + "content": { + "application/*+json": { + "schema": { + "$ref": "#/components/schemas/CreateOfferingRequest" + } + }, + "application/json": { + "schema": { + "$ref": "#/components/schemas/CreateOfferingRequest" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/CreateOfferingRequest" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "OK" + } + }, + "tags": [ + "Offerings" + ] + } + }, + "/api/v1/offerings/categories": { + "get": { + "responses": { + "200": { + "description": "OK" + } + }, + "tags": [ + "OfferingCategories" + ] + }, + "post": { + "requestBody": { + "content": { + "application/*+json": { + "schema": { + "$ref": "#/components/schemas/OfferingCategoryRequest" + } + }, + "application/json": { + "schema": { + "$ref": "#/components/schemas/OfferingCategoryRequest" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/OfferingCategoryRequest" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "OK" + } + }, + "tags": [ + "OfferingCategories" + ] + } + }, + "/api/v1/offerings/categories/{id}": { + "delete": { + "parameters": [ + { + "in": "path", + "name": "id", + "required": true, + "schema": { + "format": "uuid", + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK" + } + }, + "tags": [ + "OfferingCategories" + ] + }, + "put": { + "parameters": [ + { + "in": "path", + "name": "id", + "required": true, + "schema": { + "format": "uuid", + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/*+json": { + "schema": { + "$ref": "#/components/schemas/OfferingCategoryRequest" + } + }, + "application/json": { + "schema": { + "$ref": "#/components/schemas/OfferingCategoryRequest" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/OfferingCategoryRequest" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "OK" + } + }, + "tags": [ + "OfferingCategories" + ] + } + }, + "/api/v1/offerings/order": { + "put": { + "requestBody": { + "content": { + "application/*+json": { + "schema": { + "$ref": "#/components/schemas/ReorderOfferingsRequest" + } + }, + "application/json": { + "schema": { + "$ref": "#/components/schemas/ReorderOfferingsRequest" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/ReorderOfferingsRequest" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "OK" + } + }, + "tags": [ + "Offerings" + ] + } + }, + "/api/v1/offerings/{id}": { + "delete": { + "parameters": [ + { + "in": "path", + "name": "id", + "required": true, + "schema": { + "format": "uuid", + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK" + } + }, + "tags": [ + "Offerings" + ] + }, + "put": { + "parameters": [ + { + "in": "path", + "name": "id", + "required": true, + "schema": { + "format": "uuid", + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/*+json": { + "schema": { + "$ref": "#/components/schemas/UpdateOfferingRequest" + } + }, + "application/json": { + "schema": { + "$ref": "#/components/schemas/UpdateOfferingRequest" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/UpdateOfferingRequest" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "OK" + } + }, + "tags": [ + "Offerings" + ] + } + }, + "/health": { + "get": { + "operationId": "HealthCheck", + "responses": { + "200": { + "description": "OK" + } + }, + "tags": [ + "SlpModularCms.Api.SlpSoftware" + ] + } + } + }, + "tags": [ + { + "name": "SlpModularCms.Api.SlpSoftware" + }, + { + "name": "System" + }, + { + "name": "Availability" + }, + { + "name": "Master" + }, + { + "name": "ContactMessages" + }, + { + "name": "Auth" + }, + { + "name": "Invitation" + }, + { + "name": "Setup" + }, + { + "name": "Users" + }, + { + "name": "CmsInstance" + }, + { + "name": "SlaveStatus" + }, + { + "name": "OfferingCategories" + }, + { + "name": "Offerings" + } + ] +} diff --git a/src/SlpModularCms.Modules.Contact.Tests/ContactControllerTests.cs b/src/SlpModularCms.Modules.Contact.Tests/ContactControllerTests.cs index 05d2831..fcca3b1 100644 --- a/src/SlpModularCms.Modules.Contact.Tests/ContactControllerTests.cs +++ b/src/SlpModularCms.Modules.Contact.Tests/ContactControllerTests.cs @@ -88,7 +88,7 @@ public class ContactMessagesControllerTests var result = await Create(new ContactOptions { Enabled = true, ProblemTypeBase = "https://example.test/problems/" }) .Submit(new ContactMessageRequest(null, null, null, null, null, null, null), CancellationToken.None); - var problem = result.Should().BeOfType().Subject.Value.Should().BeOfType().Subject; + var problem = result.Should().BeOfType().Subject.Value.Should().BeOfType().Subject; problem.Status.Should().Be(400); problem.Type.Should().Be("https://example.test/problems/validation"); problem.Errors["email"].Should().Equal("invalid"); @@ -102,7 +102,7 @@ public class ContactMessagesControllerTests var result = await Create().Submit(null, CancellationToken.None); - ((ValidationProblemDetails)((BadRequestObjectResult)result).Value!).Type.Should().Be("about:blank"); + ((ValidationProblemDetails)((ObjectResult)result).Value!).Type.Should().Be("about:blank"); } [Fact] diff --git a/src/SlpModularCms.Modules.Contact.Tests/Pipeline/OpenApiSnapshotTests.cs b/src/SlpModularCms.Modules.Contact.Tests/Pipeline/OpenApiSnapshotTests.cs new file mode 100644 index 0000000..1658e75 --- /dev/null +++ b/src/SlpModularCms.Modules.Contact.Tests/Pipeline/OpenApiSnapshotTests.cs @@ -0,0 +1,160 @@ +using System.Text.Encodings.Web; +using System.Text.Json; +using System.Text.Json.Nodes; +using FluentAssertions; + +namespace SlpModularCms.Modules.Contact.Tests.Pipeline; + +/// +/// Keeps the committed OpenAPI document of the SlpSoftware host (openapi/slpsoftware.v1.json) +/// equal to what the real, composed host serves, and checks the contact contract inside it. +/// +/// +/// The document is the single source from which the frontend client (cms-client) +/// generates its types. To regenerate after an intended API change run: +/// UPDATE_OPENAPI=1 dotnet test --filter OpenApiSnapshot. +/// +public class OpenApiSnapshotTests(DisabledContactHostFactory factory) : IClassFixture +{ + private const string FileName = "slpsoftware.v1.json"; + + private static string RepositoryRoot() + { + var directory = new DirectoryInfo(AppContext.BaseDirectory); + while (directory is not null && !File.Exists(Path.Combine(directory.FullName, "SlpModularCms.sln"))) + { + directory = directory.Parent; + } + + return directory?.FullName ?? throw new InvalidOperationException("SlpModularCms.sln not found above the test output."); + } + + private static string SnapshotPath() => Path.Combine(RepositoryRoot(), "openapi", FileName); + + private async Task FetchAsync() + { + var response = await factory.CreateClient().GetAsync("/openapi/v1.json"); + response.IsSuccessStatusCode.Should().BeTrue(); + return await response.Content.ReadAsStringAsync(); + } + + /// + /// A stable form: no request-derived servers, every object's keys in ordinal order (the + /// generator's order depends on assembly discovery), 2-space indentation, LF, trailing newline. + /// + internal static string Normalize(string json) + { + var root = JsonNode.Parse(json)!.AsObject(); + root.Remove("servers"); + + var text = Sort(root)!.ToJsonString(new JsonSerializerOptions + { + WriteIndented = true, + Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping, + }); + + return text.Replace("\r\n", "\n") + "\n"; + } + + private static JsonNode? Sort(JsonNode? node) => node switch + { + JsonObject obj => new JsonObject(obj + .OrderBy(p => p.Key, StringComparer.Ordinal) + .Select(p => new KeyValuePair(p.Key, Sort(p.Value)))), + JsonArray array => new JsonArray(array.Select(Sort).ToArray()), + _ => node?.DeepClone(), + }; + + [Fact] + public async Task TheCommittedDocument_EqualsWhatTheHostServes() + { + var current = Normalize(await FetchAsync()); + var path = SnapshotPath(); + + if (Environment.GetEnvironmentVariable("UPDATE_OPENAPI") == "1") + { + Directory.CreateDirectory(Path.GetDirectoryName(path)!); + await File.WriteAllTextAsync(path, current, new System.Text.UTF8Encoding(false)); + return; + } + + File.Exists(path).Should().BeTrue($"{path} is missing. Generate it with: UPDATE_OPENAPI=1 dotnet test --filter OpenApiSnapshot"); + var committed = (await File.ReadAllTextAsync(path)).Replace("\r\n", "\n"); + + committed.Should().Be( + current, + "the OpenAPI document changed. If that is intended, regenerate the committed file with: " + + "UPDATE_OPENAPI=1 dotnet test --filter OpenApiSnapshot"); + } + + [Fact] + public async Task TheDocument_ContainsTheContactContract() + { + var doc = JsonNode.Parse(Normalize(await FetchAsync()))!; + var paths = doc["paths"]!.AsObject(); + + paths.Select(p => p.Key).Should().Contain(["/api/v1/contact-messages", "/api/v1/contact-messages/token"]); + + // POST /contact-messages + var post = doc["paths"]!["/api/v1/contact-messages"]!["post"]!; + var header = post["parameters"]!.AsArray().Single(p => p!["name"]!.GetValue() == "Idempotency-Key")!; + header["in"]!.GetValue().Should().Be("header"); + header["required"]!.GetValue().Should().BeTrue(); + header["schema"]!["format"]!.GetValue().Should().Be("uuid"); + + post["requestBody"]!["required"]!.GetValue().Should().BeTrue(); + post["requestBody"]!["content"]!["application/json"]!["schema"]!["$ref"]!.GetValue() + .Should().EndWith("/ContactMessageRequest"); + + post["responses"]!.AsObject().Select(p => p.Key).Should().BeEquivalentTo(["202", "400", "404", "413", "429"]); + post["responses"]!["400"]!["$ref"]!.GetValue().Should().EndWith("/Validation"); + post["responses"]!["413"]!["$ref"]!.GetValue().Should().EndWith("/TooLarge"); + post["responses"]!["429"]!["$ref"]!.GetValue().Should().EndWith("/RateLimited"); + + // GET /contact-messages/token + var token = doc["paths"]!["/api/v1/contact-messages/token"]!["get"]!; + token["responses"]!.AsObject().Select(p => p.Key).Should().BeEquivalentTo(["200", "404", "429"]); + + // Request schema: the contract's required fields and limits. + var request = doc["components"]!["schemas"]!["ContactMessageRequest"]!; + request["required"]!.AsArray().Select(n => n!.GetValue()) + .Should().BeEquivalentTo(["name", "email", "subject", "message", "hpCheck", "token"]); + var properties = request["properties"]!; + properties["name"]!["maxLength"]!.GetValue().Should().Be(100); + properties["email"]!["maxLength"]!.GetValue().Should().Be(254); + properties["subject"]!["maxLength"]!.GetValue().Should().Be(100); + properties["message"]!["maxLength"]!.GetValue().Should().Be(2000); + properties["hpCheck"]!["maxLength"]!.GetValue().Should().Be(0); + + // Reusable responses. + var responses = doc["components"]!["responses"]!; + responses["RateLimited"]!["headers"]!["Retry-After"].Should().NotBeNull(); + responses["Validation"]!["content"]!["application/problem+json"].Should().NotBeNull(); + responses["TooLarge"]!["content"]!["application/problem+json"].Should().NotBeNull(); + + var codes = doc["components"]!["schemas"]!["ValidationProblem"]!["properties"]!["errors"]!["additionalProperties"]!["items"]!["enum"]! + .AsArray().Select(n => n!.GetValue()); + codes.Should().BeEquivalentTo(["required", "tooLong", "invalid", "expired"]); + } + + [Fact] + public async Task TheDocument_HoldsNoHostNamesAddressesOrSecrets() + { + var text = Normalize(await FetchAsync()); + + text.Should().NotContain("127.0.0.1").And.NotContain("localhost"); + text.Should().NotContain("@", "no e-mail addresses (not even examples)"); + text.ToLowerInvariant().Should().NotContain("secret\":").And.NotContain("password\":\""); + JsonNode.Parse(text)!.AsObject().ContainsKey("servers").Should().BeFalse(); + } + + [Fact] + public void Normalize_IsDeterministic_RegardlessOfKeyOrder() + { + const string a = """{"servers":[{"url":"http://x"}],"b":1,"a":{"z":1,"y":[{"d":1,"c":2}]}}"""; + const string b = """{"a":{"y":[{"c":2,"d":1}],"z":1},"b":1}"""; + + Normalize(a).Should().Be(Normalize(b)); + Normalize(a).Should().EndWith("\n").And.NotContain("\r"); + } +} diff --git a/src/SlpModularCms.Modules.Contact/ContactModule.cs b/src/SlpModularCms.Modules.Contact/ContactModule.cs index 06ac096..dc8312a 100644 --- a/src/SlpModularCms.Modules.Contact/ContactModule.cs +++ b/src/SlpModularCms.Modules.Contact/ContactModule.cs @@ -1,6 +1,7 @@ using System.Diagnostics.CodeAnalysis; using System.Threading.RateLimiting; using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.OpenApi; using Microsoft.AspNetCore.RateLimiting; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Migrations; @@ -13,6 +14,7 @@ using SlpModularCms.Core.Modules; using SlpModularCms.Modules.Contact.Config; using SlpModularCms.Modules.Contact.Controllers; using SlpModularCms.Modules.Contact.Data; +using SlpModularCms.Modules.Contact.OpenApi; using SlpModularCms.Modules.Contact.Repositories; using SlpModularCms.Modules.Contact.Services; @@ -47,6 +49,10 @@ public class ContactModule : IModule services.AddScoped(); services.AddHostedService(); + // The contact details of the OpenAPI document (named options of document 'v1', so the shared + // AddOpenApi() call in Core stays untouched). + services.Configure("v1", openApi => openApi.AddDocumentTransformer()); + // Rate-limit policies live in this module so the shared limiter setup stays untouched. // The bucket key comes from one function; see ContactRateLimitPartition. services.AddOptions() diff --git a/src/SlpModularCms.Modules.Contact/Controllers/ContactMessagesController.cs b/src/SlpModularCms.Modules.Contact/Controllers/ContactMessagesController.cs index 246199d..f0306bf 100644 --- a/src/SlpModularCms.Modules.Contact/Controllers/ContactMessagesController.cs +++ b/src/SlpModularCms.Modules.Contact/Controllers/ContactMessagesController.cs @@ -15,6 +15,7 @@ namespace SlpModularCms.Modules.Contact.Controllers; /// bound must produce our own problem shape, never the framework's, and must not echo values. /// The management routes (list, read, delete, resend) are added with the admin unit. /// +[ApiExplorerSettings(IgnoreApi = false)] // not an [ApiController], so visibility must be explicit for the OpenAPI document [Route("contact-messages")] [ServiceFilter(typeof(ContactRouteFilter))] public class ContactMessagesController( @@ -30,6 +31,9 @@ public class ContactMessagesController( [AllowAnonymous] [PublicSiteEndpoint] [EnableRateLimiting(TokenPolicy)] + [ProducesResponseType(typeof(ContactTokenResponse), StatusCodes.Status200OK, "application/json")] + [ProducesResponseType(StatusCodes.Status404NotFound)] + [ProducesResponseType(StatusCodes.Status429TooManyRequests)] public IActionResult GetToken() { var settings = options.Value; @@ -44,6 +48,12 @@ public class ContactMessagesController( [AllowAnonymous] [PublicSiteEndpoint] [EnableRateLimiting(FormPolicy)] + [Consumes("application/json")] + [ProducesResponseType(typeof(ReceivedResponse), StatusCodes.Status202Accepted, "application/json")] + [ProducesResponseType(typeof(ValidationProblemDetails), StatusCodes.Status400BadRequest, "application/problem+json")] + [ProducesResponseType(StatusCodes.Status404NotFound)] + [ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status413PayloadTooLarge, "application/problem+json")] + [ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status429TooManyRequests, "application/problem+json")] public async Task Submit([FromBody] ContactMessageRequest? request, CancellationToken cancellationToken) { var key = Request.Headers[IdempotencyKeyHeader].FirstOrDefault(); @@ -53,7 +63,12 @@ public class ContactMessagesController( return result switch { - SubmissionResult.Invalid invalid => BadRequest(Problem(invalid.Errors)), + SubmissionResult.Invalid invalid => new ObjectResult(Problem(invalid.Errors)) + { + StatusCode = StatusCodes.Status400BadRequest, + // Explicit content type: problem details are served as problem+json, not as plain json. + ContentTypes = { "application/problem+json" }, + }, _ => new ObjectResult(new ReceivedResponse("received")) { StatusCode = StatusCodes.Status202Accepted }, }; } diff --git a/src/SlpModularCms.Modules.Contact/OpenApi/ContactOpenApiDocumentTransformer.cs b/src/SlpModularCms.Modules.Contact/OpenApi/ContactOpenApiDocumentTransformer.cs new file mode 100644 index 0000000..7b89045 --- /dev/null +++ b/src/SlpModularCms.Modules.Contact/OpenApi/ContactOpenApiDocumentTransformer.cs @@ -0,0 +1,176 @@ +using System.Net.Http; +using Microsoft.AspNetCore.OpenApi; +using Microsoft.OpenApi; +using SlpModularCms.Modules.Contact.Controllers; +using SlpModularCms.Modules.Contact.Services; + +namespace SlpModularCms.Modules.Contact.OpenApi; + +/// +/// Adds what attributes cannot express to the generated OpenAPI document: the reusable problem +/// responses of the contact contract, the required Idempotency-Key header, and the +/// required fields / maximum lengths of the request body. It only touches the contact +/// operations and schemas; everything else in the document is left as generated. +/// +public sealed class ContactOpenApiDocumentTransformer : IOpenApiDocumentTransformer +{ + public const string RoutePath = "/api/v1/contact-messages"; + public const string TokenPath = "/api/v1/contact-messages/token"; + + private static readonly string[] Codes = ["required", "tooLong", "invalid", "expired"]; + + public Task TransformAsync(OpenApiDocument document, OpenApiDocumentTransformerContext context, CancellationToken cancellationToken) + { + AddComponents(document); + + if (document.Paths.TryGetValue(RoutePath, out var route) && route.Operations is not null + && route.Operations.TryGetValue(HttpMethod.Post, out var submit)) + { + DescribeSubmit(document, submit); + } + + if (document.Paths.TryGetValue(TokenPath, out var token) && token.Operations is not null + && token.Operations.TryGetValue(HttpMethod.Get, out var getToken)) + { + getToken.Responses ??= []; + getToken.Responses["404"] = new OpenApiResponse { Description = "The contact form is closed on this site (the website shows its mailto fallback)." }; + getToken.Responses["429"] = new OpenApiResponseReference("RateLimited", document); + } + + return Task.CompletedTask; + } + + private static void AddComponents(OpenApiDocument document) + { + document.Components ??= new OpenApiComponents(); + document.Components.Schemas ??= new Dictionary(); + document.Components.Responses ??= new Dictionary(); + + document.Components.Schemas["Problem"] = new OpenApiSchema + { + Type = JsonSchemaType.Object, + Description = "RFC 9457 problem details. Only the standard members are sent; nothing about the limiter, the policy or the caller.", + Properties = new Dictionary + { + ["type"] = new OpenApiSchema { Type = JsonSchemaType.String }, + ["title"] = new OpenApiSchema { Type = JsonSchemaType.String }, + ["status"] = new OpenApiSchema { Type = JsonSchemaType.Integer, Format = "int32" }, + }, + }; + + document.Components.Schemas["ValidationProblem"] = new OpenApiSchema + { + Type = JsonSchemaType.Object, + Description = "A 400 answer. 'errors' maps the JSON field name (name, email, subject, message, token, idempotencyKey, body) to its error codes; the client maps codes to texts.", + Properties = new Dictionary + { + ["type"] = new OpenApiSchema { Type = JsonSchemaType.String }, + ["title"] = new OpenApiSchema { Type = JsonSchemaType.String }, + ["status"] = new OpenApiSchema { Type = JsonSchemaType.Integer, Format = "int32" }, + ["errors"] = new OpenApiSchema + { + Type = JsonSchemaType.Object, + AdditionalProperties = new OpenApiSchema + { + Type = JsonSchemaType.Array, + Items = new OpenApiSchema + { + Type = JsonSchemaType.String, + Enum = Codes.Select(c => (System.Text.Json.Nodes.JsonNode)System.Text.Json.Nodes.JsonValue.Create(c)!).ToList(), + }, + }, + }, + }, + }; + + document.Components.Responses["Validation"] = ProblemResponse( + "Validation failed (also an expired, forged or other-site token as errors.token=[\"expired\"], a missing or non-UUID Idempotency-Key, and an unreadable body as errors.body=[\"invalid\"]).", + "ValidationProblem", document); + document.Components.Responses["TooLarge"] = ProblemResponse("The request body is too large.", "Problem", document); + document.Components.Responses["RateLimited"] = new OpenApiResponse + { + Description = "Too many requests. Retry after the number of seconds in the Retry-After header.", + Headers = new Dictionary + { + ["Retry-After"] = new OpenApiHeader + { + Description = "Seconds to wait before retrying.", + Schema = new OpenApiSchema { Type = JsonSchemaType.Integer, Format = "int32" }, + }, + }, + Content = new Dictionary + { + ["application/problem+json"] = new() { Schema = new OpenApiSchemaReference("Problem", document) }, + }, + }; + } + + private static OpenApiResponse ProblemResponse(string description, string schema, OpenApiDocument document) => new() + { + Description = description, + Content = new Dictionary + { + ["application/problem+json"] = new() { Schema = new OpenApiSchemaReference(schema, document) }, + }, + }; + + private static void DescribeSubmit(OpenApiDocument document, OpenApiOperation submit) + { + submit.Parameters ??= []; + submit.Parameters.Add(new OpenApiParameter + { + Name = ContactMessagesController.IdempotencyKeyHeader, + In = ParameterLocation.Header, + Required = true, + Description = "A UUID chosen by the client per attempt series. A replay within 24 hours is answered with the same 202 without storing the message twice.", + Schema = new OpenApiSchema { Type = JsonSchemaType.String, Format = "uuid" }, + }); + + submit.Responses ??= []; + submit.Responses["400"] = new OpenApiResponseReference("Validation", document); + submit.Responses["404"] = new OpenApiResponse { Description = "The contact form is closed on this site (the website shows its mailto fallback)." }; + submit.Responses["413"] = new OpenApiResponseReference("TooLarge", document); + submit.Responses["429"] = new OpenApiResponseReference("RateLimited", document); + + // The body is required and is exactly one JSON object. (The action parameter is nullable + // on purpose, which the generator would otherwise show as 'null or object'.) + submit.RequestBody = new OpenApiRequestBody + { + Required = true, + Content = new Dictionary + { + ["application/json"] = new() { Schema = new OpenApiSchemaReference(nameof(Models.ContactMessageRequest), document) }, + }, + }; + + // The body schema: our model is nullable on purpose (a missing field is reported as the + // code 'required' in our own shape), so the contract's requirements are documented here. + if (document.Components?.Schemas is { } schemas + && schemas.TryGetValue(nameof(Models.ContactMessageRequest), out var schemaRef) + && schemaRef is OpenApiSchema request) + { + request.Required = new HashSet { "name", "email", "subject", "message", "hpCheck", "token" }; + SetMax(request, "name", ContactValidator.NameMax); + SetMax(request, "email", ContactValidator.EmailMax); + SetMax(request, "subject", ContactValidator.SubjectMax); + SetMax(request, "message", ContactValidator.MessageMax); + SetMax(request, "hpCheck", 0); + if (request.Properties is not null && request.Properties.TryGetValue("token", out var tokenProperty) + && tokenProperty is OpenApiSchema tokenSchema) + { + tokenSchema.Type = JsonSchemaType.String; + } + } + } + + private static void SetMax(OpenApiSchema request, string property, int max) + { + if (request.Properties is not null && request.Properties.TryGetValue(property, out var p) && p is OpenApiSchema schema) + { + // Required by the contract, so a plain string for generated client types (the C# model + // is nullable only so that a missing field can be reported in our own error shape). + schema.Type = JsonSchemaType.String; + schema.MaxLength = max; + } + } +}