From 295edb1bd170e3b956eb6b8c3b06ffdf09382260 Mon Sep 17 00:00:00 2001 From: JiriUhlir <149317995+JiriUhlir@users.noreply.github.com> Date: Tue, 20 Oct 2026 10:47:17 +0200 Subject: [PATCH] =?UTF-8?q?Oprava=20nasazen=C3=AD:=20slu=C5=BEba=20startuj?= =?UTF-8?q?e=20bez=20konfigurace,=20p=C5=99ihl=C3=A1=C5=A1en=C3=AD=20p?= =?UTF-8?q?=C5=99es=20hlavi=C4=8Dky?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Služba padala při startu kvůli povinným SMSSLUZBA_LOGIN, SMSSLUZBA_PASSWORD a API_KEYS, proto v AppFactory nefungovalo /health ani /docs (502). - vlastní API klíče služby zrušeny, login a heslo API přístupu SMS-Služby posílá každá aplikace v hlavičkách X-Sms-Login a X-Sms-Password - všechna konfigurace je volitelná, neplatná hodnota jen zaloguje varování - po odmítnutí přihlášení se blokují jen ty konkrétní údaje - Swagger: Authorize pro obě hlavičky, relativní server i bez ROOT_PATH - návod pro napojení aplikací a dokumentace podle nového přihlášení --- .env.example | 11 +-- README.md | 26 +++--- documentation/design.md | 41 +++++---- documentation/integration.md | 83 +++++++++-------- documentation/status.md | 19 ++-- src/SmsSluzba.Api/Auth/ApiClientRegistry.cs | 42 --------- src/SmsSluzba.Api/Auth/ApiKeyFilter.cs | 21 ----- .../Auth/GatewayCredentialsFilter.cs | 33 +++++++ src/SmsSluzba.Api/Config/AppSettings.cs | 7 +- src/SmsSluzba.Api/Config/AppSettingsLoader.cs | 89 +++---------------- .../Contracts/AccountContracts.cs | 2 +- .../Endpoints/AccountEndpoints.cs | 9 +- src/SmsSluzba.Api/Endpoints/EventEndpoints.cs | 23 +++-- .../Endpoints/GatewayProblems.cs | 2 +- .../Endpoints/MessageEndpoints.cs | 21 +++-- .../Endpoints/SystemEndpoints.cs | 9 +- src/SmsSluzba.Api/Gateway/GatewayAuthGuard.cs | 31 ++++--- .../Gateway/GatewayCredentials.cs | 14 +++ src/SmsSluzba.Api/Gateway/SmsGatewayClient.cs | 73 ++++++++------- src/SmsSluzba.Api/OpenApi/OpenApiSetup.cs | 41 ++++++--- src/SmsSluzba.Api/Problems/ApiErrors.cs | 5 +- src/SmsSluzba.Api/Program.cs | 11 ++- tests/SmsSluzba.Api.Tests/Api/ApiTests.cs | 58 +++++++----- .../SmsSluzba.Api.Tests/Api/SmsApiFactory.cs | 13 +-- .../Config/AppSettingsLoaderTests.cs | 71 +++++---------- 25 files changed, 351 insertions(+), 404 deletions(-) delete mode 100644 src/SmsSluzba.Api/Auth/ApiClientRegistry.cs delete mode 100644 src/SmsSluzba.Api/Auth/ApiKeyFilter.cs create mode 100644 src/SmsSluzba.Api/Auth/GatewayCredentialsFilter.cs create mode 100644 src/SmsSluzba.Api/Gateway/GatewayCredentials.cs diff --git a/.env.example b/.env.example index 1f91637..4b26681 100644 --- a/.env.example +++ b/.env.example @@ -1,15 +1,10 @@ +# Služba nepotřebuje žádnou konfiguraci. Login a heslo k SMS bráně posílá každá aplikace +# v hlavičkách X-Sms-Login a X-Sms-Password (viz documentation/integration.md). + # Prefix za reverse proxy, nastavuje AppFactory (např. /apps/sms-sluzba). Lokálně prázdné. ROOT_PATH= -# Přihlášení k SMS bráně: API přístup z portálu sms-sluzba.cz (Nastavení, API a Shoptet SMS). Secret. -SMSSLUZBA_LOGIN= -SMSSLUZBA_PASSWORD= - # Volitelné. Výchozí https://smsgateapi.sms-sluzba.cz/apixml30/ SMSSLUZBA_BASE_URL= # Volitelné. Jak dlouho čekat na bránu, výchozí 30 sekund. SMSSLUZBA_TIMEOUT_SECONDS= - -# Klíče aplikací, které službu volají. Formát nazev=klic, více oddělit středníkem. Secret. -# Příklad: eshop=dlouhy-nahodny-klic;cms=jiny-dlouhy-klic -API_KEYS= diff --git a/README.md b/README.md index 3e0a328..c86d4fc 100644 --- a/README.md +++ b/README.md @@ -1,37 +1,33 @@ # SMS Služba -Interní prostředník nad SMS bránou SMS-Služba.cz (API XML 3.0). Ostatní aplikace volají jednoduché JSON API s vlastním API klíčem a nemusí řešit XML ani přihlášení k bráně. Služba nic neukládá, historii drží brána. +Interní prostředník nad SMS bránou SMS-Služba.cz (API XML 3.0). Ostatní aplikace volají jednoduché JSON API a posílají login a heslo svého API přístupu u SMS-Služby v hlavičkách `X-Sms-Login` a `X-Sms-Password`. Služba je předá bráně a převede XML na JSON. Nemá vlastní účet, klíče ani úložiště. ## Spuštění +Služba nepotřebuje žádnou konfiguraci a nastartuje i bez proměnných prostředí. Container poslouchá na portu 8080. + Lokálně (.NET SDK 10): ```bash -cp .env.example .env # vyplnit hodnoty, .env se necommituje dotnet run --project src/SmsSluzba.Api ``` -`dotnet run` soubor `.env` nečte, proměnné je potřeba nastavit v prostředí. V AppFactory se nastavují v portálu jako variables a secrets. Container poslouchá na portu 8080. - Testy: `dotnet test SmsSluzba.slnx`. Testy nevolají skutečnou bránu. ## Proměnné prostředí -| Proměnná | Povinná | Popis | -|---|---|---| -| `SMSSLUZBA_LOGIN` | ano | Login API přístupu z portálu sms-sluzba.cz | -| `SMSSLUZBA_PASSWORD` | ano | Heslo API přístupu (secret) | -| `API_KEYS` | ano | Klíče aplikací, `nazev=klic;nazev2=klic2` (secret) | -| `SMSSLUZBA_BASE_URL` | ne | Výchozí `https://smsgateapi.sms-sluzba.cz/apixml30/` | -| `SMSSLUZBA_TIMEOUT_SECONDS` | ne | Čekání na bránu, výchozí 30 | -| `ROOT_PATH` | ne | Prefix za proxy, nastavuje AppFactory | +Všechny jsou volitelné. -Bez povinných hodnot služba nenastartuje a vypíše, co chybí. +| Proměnná | Popis | +|---|---| +| `ROOT_PATH` | Prefix za proxy, nastavuje AppFactory | +| `SMSSLUZBA_BASE_URL` | Výchozí `https://smsgateapi.sms-sluzba.cz/apixml30/` | +| `SMSSLUZBA_TIMEOUT_SECONDS` | Čekání na bránu, výchozí 30 | ## Endpointy -- `GET /health`, `GET /docs` (Swagger UI), `GET /openapi/v1.json` -- `/v1/...` s hlavičkou `X-Api-Key`: odeslání SMS, doručenka, události, potvrzení událostí, kredit +- `GET /health`, `GET /docs` (Swagger UI, přihlášení přes Authorize), `GET /openapi/v1.json` +- `/v1/...` s hlavičkami `X-Sms-Login` a `X-Sms-Password`: odeslání SMS, doručenka, události, potvrzení událostí, kredit ## Dokumentace diff --git a/documentation/design.md b/documentation/design.md index 12d8240..98a1e70 100644 --- a/documentation/design.md +++ b/documentation/design.md @@ -1,12 +1,12 @@ # Návrh: SMS služba (prostředník k SMS-Služba.cz) -Stav: **návrh ke schválení**. +Stav: **implementováno**. ## 1. Účel -Tenký prostředník nad SMS-Služba.cz (API XML 3.0). Ostatní aplikace volají jednoduché JSON API a nemusí řešit XML, přihlášení k bráně ani její stavové kódy. Služba nic neukládá: historii zpráv, doručenky a frontu příchozích zpráv drží poskytovatel. +Tenký prostředník nad SMS-Služba.cz (API XML 3.0). Ostatní aplikace volají jednoduché JSON API a nemusí řešit XML ani stavové kódy brány. Každá aplikace má vlastní API přístup u SMS-Služby a jeho login a heslo posílá v hlavičkách `X-Sms-Login` a `X-Sms-Password`. Služba je jen přepošle bráně, sama žádný účet ani klíče nemá. Služba nic neukládá: historii zpráv, doručenky a frontu příchozích zpráv drží poskytovatel. -Co služba **nedělá**: databáze, fronta, plánovač, webhooky, retry odeslání, vlastní historie. +Co služba **nedělá**: databáze, fronta, plánovač, webhooky, retry odeslání, vlastní historie, vlastní ověřování volajících (ověřuje je brána podle loginu a hesla). ## 2. Jak funguje @@ -34,7 +34,7 @@ Odeslání se **nikdy neopakuje automaticky**, protože opakování by mohlo pos `GET /v1/events` vrátí seznam událostí jako JSON, typ podle pole `type`: `incoming`, `answer` (s `inReplyTo`), `deliveryReport` (`messageId`, `deliveredAt`, `status`, `description`), `outgoing`. Brána vrací událost znovu, dokud ji někdo nepotvrdí. Potvrzení proto dělá volající aplikace sama přes `POST /v1/events/confirm` (`[{ type, id }]`) až po zpracování. Služba převod typů pro `confirm` zajistí (`answer` na `incoming_message`, `outgoing` na `outgoing_message`). -Pozor: brána má pro účet jednu frontu událostí. Když budou události stahovat dvě aplikace, každou událost dostane ta, která se zeptá dřív. +Pozor: brána má pro každý API přístup jednu frontu událostí. Když budou události stahovat dvě aplikace, každou událost dostane ta, která se zeptá dřív. ## 3. Chyby @@ -45,31 +45,30 @@ Kódy brány chodí v těle jako `..../openapi/v1.json`), takže `Try it out` drží prefix i bez konfigurace. Swagger UI se načítá relativně (`../openapi/v1.json`) a `/docs` přesměrovává relativně na `docs/index.html`, protože Swashbuckle přesměrovává absolutně a za Caddy by prefix ztratil. ## 7. Otevřené otázky -1. **Stahování událostí:** fronta u brány je jedna pro celý účet. Návod pro aplikace ([integration.md](integration.md)) proto určuje, že události stahuje jen jedna aplikace. Kterou? +1. **Stahování událostí:** fronta u brány je jedna pro každý API přístup. Když login a heslo sdílí víc aplikací, má události stahovat jen jedna z nich. 2. **Stavy doručenky:** PDF uvádí jen `0 = Doručeno`. Služba proto vrací číselný `status` a text `description` beze změny, nic dál z nich nevyvozuje. 3. **Časová zóna časů brány:** PDF ji neuvádí, předpokládám Europe/Prague. diff --git a/documentation/integration.md b/documentation/integration.md index ff99441..0ce7303 100644 --- a/documentation/integration.md +++ b/documentation/integration.md @@ -4,39 +4,41 @@ Návod pro vývojáře a AI asistenty, kteří napojují svou aplikaci na intern ## Co služba dělá -SMS služba je interní prostředník nad bránou SMS-Služba.cz. Vaše aplikace volá jednoduché JSON API, služba to předá bráně a vrátí výsledek. Přihlášení k bráně, XML a stavové kódy řeší služba. +SMS služba je interní prostředník nad bránou SMS-Služba.cz. Vaše aplikace volá jednoduché JSON API a k tomu posílá login a heslo svého API přístupu u SMS-Služby. Služba je předá bráně, převede XML na JSON a vrátí výsledek. XML a stavové kódy brány řeší služba. -Služba nic neukládá. Neexistuje u ní historie zpráv, fronta ani opakování. Co si potřebujete pamatovat (id odeslaných zpráv, stav doručení), ukládá vaše aplikace. +Služba nemá vlastní účet ani vlastní klíče a nic neukládá. Historie zpráv a kredit patří k API přístupu, jehož login a heslo pošlete. Co si potřebujete pamatovat (id odeslaných zpráv, stav doručení), ukládá vaše aplikace. ## Konfigurace ve vaší aplikaci -Do `.env` vaší aplikace přidejte: +Každá aplikace má vlastní API přístup v portálu sms-sluzba.cz (Nastavení, API a Shoptet SMS, Přidat API přístup). Do `.env` vaší aplikace přidejte: ```dotenv # Adresa SMS služby (bez lomítka na konci) SMS_SERVICE_URL=https://services.csbot.cz/apps/sms-sluzba -# API klíč přidělený vaší aplikaci, je to secret -SMS_SERVICE_API_KEY= +# Login a heslo API přístupu vaší aplikace u SMS-Služby, jsou to secrets +SMS_SERVICE_LOGIN= +SMS_SERVICE_PASSWORD= ``` -Do `.env.example` přidejte stejné názvy bez hodnot. Klíč nikdy nepatří do kódu, do repozitáře ani do logu. Hodnoty čtěte na jednom místě v konfiguraci aplikace. Když chybí, aplikace má při startu skončit s jasnou chybou. +Do `.env.example` přidejte stejné názvy bez hodnot. Login ani heslo nikdy nepatří do kódu, do repozitáře ani do logu. Hodnoty čtěte na jednom místě v konfiguraci aplikace. Když chybí, aplikace má při startu skončit s jasnou chybou. -Klíč přiděluje správce SMS služby, každá aplikace má vlastní. +## Přihlášení -## Autentizace - -Každý požadavek na `/v1/...` musí mít hlavičku: +Každý požadavek na `/v1/...` musí mít hlavičky: ```text -X-Api-Key: +X-Sms-Login: +X-Sms-Password: ``` -Chybějící nebo neplatný klíč vrací `401` s kódem `unauthorized`. +- Chybí-li některá hlavička, služba vrátí `401` s kódem `missing_credentials` a bránu nevolá. +- Odmítne-li brána login nebo heslo, služba vrátí `401` s kódem `invalid_credentials`. +- Opakované špatné přihlášení u brány **zablokuje API přístup**. Služba proto po prvním odmítnutí tytéž údaje bráně znovu neposílá a hned vrací `invalid_credentials`. Po opravě loginu nebo hesla v `.env` vaší aplikace funguje volání hned. Pokud byl jen odblokován účet a údaje zůstaly stejné, je potřeba restart SMS služby. ## Formáty - Tělo požadavků i odpovědí je JSON v UTF-8 (`Content-Type: application/json`), názvy polí jsou v camelCase. -- Časy jsou v ISO 8601. Odpovědi je vrací v UTC (`2026-10-20T10:00:00Z`). V požadavcích je přijímají s posunem (`2026-10-20T12:00:00+02:00`) i v UTC. +- Časy jsou v ISO 8601. Odpovědi je vrací v UTC (`2026-10-20T10:00:00Z`). V požadavcích jsou přijímány s posunem (`2026-10-20T12:00:00+02:00`) i v UTC. - Telefonní čísla v mezinárodním formátu `+420603123456`. Pro česká čísla služba přijme i `00420603123456` a `603123456`. - `id` zprávy je řetězec ve tvaru `420777123456-20261020120000123`. Ukládejte ho jako text (max 64 znaků) a nic z něj neparsujte. @@ -46,7 +48,8 @@ Chybějící nebo neplatný klíč vrací `401` s kódem `unauthorized`. ```http POST {SMS_SERVICE_URL}/v1/messages -X-Api-Key: ... +X-Sms-Login: ... +X-Sms-Password: ... Content-Type: application/json { @@ -61,7 +64,7 @@ Content-Type: application/json |---|---|---| | `to` | ano | Číslo příjemce. | | `text` | ano | Text zprávy, max 459 znaků. | -| `deliveryReport` | ne | `true` = vyžádat doručenku. Bez uvedení platí nastavení účtu u brány. | +| `deliveryReport` | ne | `true` = vyžádat doručenku. Bez uvedení platí nastavení API přístupu u brány. | | `sendAt` | ne | Odložené odeslání. Bez uvedení se zpráva odešle hned. | Odpověď `200`: @@ -90,7 +93,8 @@ Pravidla pro text: ```http GET {SMS_SERVICE_URL}/v1/messages/{id}/delivery-report -X-Api-Key: ... +X-Sms-Login: ... +X-Sms-Password: ... ``` `{id}` je `id` z odpovědi na odeslání, URL-enkódované. Odpověď `200`: @@ -110,7 +114,8 @@ X-Api-Key: ... ```http GET {SMS_SERVICE_URL}/v1/events?types=incoming,deliveryReport&count=30 -X-Api-Key: ... +X-Sms-Login: ... +X-Sms-Password: ... ``` | Parametr | Výchozí | Popis | @@ -171,7 +176,8 @@ Brána vrací tutéž událost znovu, dokud ji nepotvrdíte. Potvrzujte **až po ```http POST {SMS_SERVICE_URL}/v1/events/confirm -X-Api-Key: ... +X-Sms-Login: ... +X-Sms-Password: ... Content-Type: application/json { @@ -201,7 +207,8 @@ Položky z `failed` zkuste potvrdit znovu příště. Potvrzení se dá bezpečn ```http GET {SMS_SERVICE_URL}/v1/account/credit -X-Api-Key: ... +X-Sms-Login: ... +X-Sms-Password: ... ``` Odpověď `200`, částky v Kč bez DPH: @@ -217,7 +224,7 @@ Odpověď `200`, částky v Kč bez DPH: ### Stav služby -`GET {SMS_SERVICE_URL}/health` vrací `200`, když služba běží. Nepotřebuje klíč a nevolá bránu. Odpověď `{ "status": "ok", "gateway": "ok" }`. Hodnota `gateway: "blocked"` znamená, že brána odmítla přihlášení a služba ji přestala volat (viz `provider_auth_blocked`). +`GET {SMS_SERVICE_URL}/health` vrací `200` a `{ "status": "ok" }`, když služba běží. Nepotřebuje přihlášení a nevolá bránu. ## Chyby @@ -243,26 +250,26 @@ Rozhodujte se podle `code`, ne podle textu. Při hlášení problému správci p | 400 | `missing_text` | Prázdný text. | Neopakovat. | | 400 | `text_too_long` | Text nad 459 znaků. | Zkrátit. | | 400 | `provider_rejected` | Brána požadavek odmítla z jiného důvodu (např. neznámé id). SMS neodešla. | Neopakovat. | -| 401 | `unauthorized` | Chybí nebo je neplatný `X-Api-Key`. | Zkontrolovat `.env`, neopakovat. | +| 401 | `missing_credentials` | Chybí hlavička `X-Sms-Login` nebo `X-Sms-Password`. | Zkontrolovat `.env`, neopakovat. | +| 401 | `invalid_credentials` | Brána odmítla login nebo heslo. | Neopakovat, opravit `.env`. Další pokusy by mohly zablokovat API přístup. | | 402 | `insufficient_credit` | U brány došel kredit. | Neopakovat, upozornit správce. | | 404 | `delivery_report_not_found` | Doručenka zatím není. | Zeptat se později. | -| 502 | `provider_unavailable` | Brána hlásí chybu nebo není dostupná. | U `GET` a `confirm` opakovat s odstupem. U odeslání viz níže. | | 404 | `not_found` | Neexistující adresa. | Opravit URL. | | 500 | `internal_error` | Chyba ve službě. | Opakovat jen `GET`, nahlásit `traceId` správci. | -| 503 | `provider_auth_blocked` | Služba se nedokáže přihlásit k bráně, volání jsou zastavená. | Neopakovat, upozornit správce. | +| 502 | `provider_unavailable` | Brána hlásí chybu nebo není dostupná. | U `GET` a `confirm` opakovat s odstupem. U odeslání viz níže. | | 504 | `provider_timeout` | Brána neodpověděla včas. | U odeslání viz níže. | ## Pravidla pro odesílání - Služba odeslání **nikdy neopakuje** a nemá ochranu proti duplicitám. Každé úspěšné volání `POST /v1/messages` znamená jednu odeslanou a zaplacenou SMS. -- Po `400`, `401`, `402` a `503` SMS určitě neodešla. +- Po `400`, `401` a `402` SMS určitě neodešla. - Po `500`, `502` a `504` je stav **neznámý**: brána mohla zprávu přijmout. Neposílejte ji automaticky znovu. Zalogujte to, a pokud je zpráva důležitá, nechte o opakování rozhodnout člověka nebo použijte `GET /v1/events?types=outgoing`. - Volání `POST /v1/messages` nespouštějte víckrát pro stejnou událost ve vaší aplikaci (dvojklik, opakované zpracování fronty). Hlídejte to na své straně. - Timeout HTTP klienta nastavte aspoň na 35 s (služba čeká na bránu až 30 s). ## Pravidla pro události -- Brána má pro celý účet **jednu společnou frontu událostí**. Události má stahovat jen jedna aplikace, která je k tomu určená. Ostatní aplikace `GET /v1/events` nevolají. Doručenku ke své zprávě si zjistí přes `GET /v1/messages/{id}/delivery-report`. +- Brána má pro každý API přístup **jednu frontu událostí**. Když stejný login a heslo používá víc aplikací, každou událost dostane jen ta, která se zeptá dřív. Události má proto pro daný API přístup stahovat jen jedna aplikace. - Stahujte v intervalu (např. každých 15 až 60 s). Když přijde plných 30 událostí, ptejte se hned znovu, dokud nepřijde méně. - Zpracování musí být idempotentní podle dvojice `type` + `id`. Stejná událost může přijít víckrát, když se potvrzení nepovede. - Postup jednoho cyklu: stáhnout, uložit nebo zpracovat, potvrdit. @@ -270,32 +277,32 @@ Rozhodujte se podle `code`, ne podle textu. Při hlášení problému správci p ## Příklady (curl) ```bash -curl -X POST "$SMS_SERVICE_URL/v1/messages" \ - -H "X-Api-Key: $SMS_SERVICE_API_KEY" \ +AUTH=(-H "X-Sms-Login: $SMS_SERVICE_LOGIN" -H "X-Sms-Password: $SMS_SERVICE_PASSWORD") + +curl -X POST "$SMS_SERVICE_URL/v1/messages" "${AUTH[@]}" \ -H "Content-Type: application/json" \ -d '{"to":"+420603123456","text":"Test","deliveryReport":true}' -curl "$SMS_SERVICE_URL/v1/messages/420603123456-20261020120000123/delivery-report" \ - -H "X-Api-Key: $SMS_SERVICE_API_KEY" +curl "$SMS_SERVICE_URL/v1/messages/420603123456-20261020120000123/delivery-report" "${AUTH[@]}" -curl "$SMS_SERVICE_URL/v1/events?types=incoming,deliveryReport&count=30" \ - -H "X-Api-Key: $SMS_SERVICE_API_KEY" +curl "$SMS_SERVICE_URL/v1/events?types=incoming,deliveryReport&count=30" "${AUTH[@]}" -curl -X POST "$SMS_SERVICE_URL/v1/events/confirm" \ - -H "X-Api-Key: $SMS_SERVICE_API_KEY" \ +curl -X POST "$SMS_SERVICE_URL/v1/events/confirm" "${AUTH[@]}" \ -H "Content-Type: application/json" \ -d '{"events":[{"type":"incoming","id":"420777123456-20261020072509664"}]}' -curl "$SMS_SERVICE_URL/v1/account/credit" -H "X-Api-Key: $SMS_SERVICE_API_KEY" +curl "$SMS_SERVICE_URL/v1/account/credit" "${AUTH[@]}" ``` ## Doporučená implementace v aplikaci 1. Jeden modul nebo třída `SmsClient` s metodami `send`, `getDeliveryReport`, `getEvents`, `confirmEvents`, `getCredit`. Zbytek aplikace volá jen ji. -2. `SMS_SERVICE_URL` a `SMS_SERVICE_API_KEY` se čtou v konfiguraci aplikace a do `SmsClient` se předávají. +2. `SMS_SERVICE_URL`, `SMS_SERVICE_LOGIN` a `SMS_SERVICE_PASSWORD` se čtou v konfiguraci aplikace a do `SmsClient` se předávají. `SmsClient` posílá login a heslo v hlavičkách u každého požadavku. 3. Odpovědi validovat na hranici (např. `zod`, `pydantic`, typované DTO) a chyby převádět podle `code` na vlastní typy chyb. -4. Do logu nepsat API klíč ani text SMS. Telefonní číslo maskovat. -5. U odesílání nepoužívat obecný retry HTTP klienta. Retry jen pro `GET` a `confirm`. +4. Do logu nepsat heslo ani text SMS. Telefonní číslo maskovat. +5. U odesílání nepoužívat obecný retry HTTP klienta. Retry jen pro `GET` a `confirm`, nikdy po `401`. 6. V testech volat mock `SmsClient`, ne skutečnou službu, protože každé odeslání stojí peníze. -Interaktivní dokumentace API (Swagger) je na `{SMS_SERVICE_URL}/docs`. +## Vyzkoušení ve Swaggeru + +Interaktivní dokumentace je na `{SMS_SERVICE_URL}/docs`. Tlačítkem **Authorize** zadejte login (`X-Sms-Login`) a heslo (`X-Sms-Password`) API přístupu. Pak u endpointu použijte **Try it out**. Pozor: `POST /v1/messages` i ze Swaggeru skutečně odešle a zaplatí SMS. diff --git a/documentation/status.md b/documentation/status.md index 026320e..084988c 100644 --- a/documentation/status.md +++ b/documentation/status.md @@ -2,22 +2,23 @@ ## Aktuální stav -- Služba je napsaná podle [design.md](design.md) a [integration.md](integration.md): bezstavový prostředník bez databáze, .NET 10. -- Build bez varování, 67 testů prošlo. Lokálně ověřeno s `ROOT_PATH`: `/health` s prefixem i bez, `/docs` přesměrovává relativně, OpenAPI má server z `ROOT_PATH`. -- Neověřeno proti skutečné bráně a v AppFactory (`/apps//docs`, `Try it out`). +- Služba je hotová podle [design.md](design.md) a [integration.md](integration.md): bezstavový prostředník bez databáze, .NET 10. +- Služba nemá vlastní secrets ani konfiguraci. Login a heslo API přístupu SMS-Služby posílá každá aplikace v hlavičkách `X-Sms-Login` a `X-Sms-Password`. +- Ověřeno: build bez varování, 66 testů prošlo. Docker image spuštěný bez jakékoli konfigurace, s `ROOT_PATH` i bez něj, s odříznutým i ponechaným prefixem: `/health` 200, `/docs` přesměruje relativně, `/docs/index.html` 200, OpenAPI server `/apps/sms-sluzba`, Authorize nabízí obě hlavičky. +- Neověřeno proti skutečné bráně (žádné přihlašovací údaje k dispozici). ## Další krok -1. Nastavit v AppFactory `SMSSLUZBA_LOGIN`, `SMSSLUZBA_PASSWORD`, `API_KEYS`. Bez nich služba nenastartuje. -2. Ověřit `/apps//health`, `/docs` a `Try it out`, pak první SMS přes `POST /v1/messages`. -3. Určit, která aplikace stahuje události. +1. Po nasazení ověřit `https://services.csbot.cz/apps/sms-sluzba/health` a `/docs`, v Authorize zadat login a heslo API přístupu a zkusit `GET /v1/account/credit` (nic neplatí). ## Mapa kódu - `src/SmsSluzba.Api/Program.cs`: skládání služeb a middleware. -- `Config/AppSettingsLoader.cs`: jediné místo, kde se čtou proměnné prostředí. -- `Gateway/SmsGatewayClient.cs`: všechna volání brány. `GatewayXml.cs` tvorba a čtení XML, `GatewayResponse.cs` a `GatewayStatus.cs` stavové kódy, `GatewayAuthGuard.cs` blokace po 401, `RedactingLoggingHandler.cs` log bez hesla. +- `Config/AppSettingsLoader.cs`: jediné místo, kde se čtou proměnné prostředí. Nikdy nevyhazuje výjimku. +- `Auth/GatewayCredentialsFilter.cs`: čte login a heslo z hlaviček. +- `Gateway/SmsGatewayClient.cs`: všechna volání brány. `GatewayXml.cs` tvorba a čtení XML, `GatewayResponse.cs` a `GatewayStatus.cs` stavové kódy, `GatewayAuthGuard.cs` blokace odmítnutých údajů, `RedactingLoggingHandler.cs` log bez hesla. - `Endpoints/`: `/v1` endpointy, `GatewayProblems.cs` převod chyb brány na kódy API. +- `OpenApi/OpenApiSetup.cs`: OpenAPI server a hlavičky pro Authorize. - `Problems/ApiErrors.cs`: seznam kódů chyb, musí odpovídat [integration.md](integration.md). - `Contracts/`: JSON typy API. - `tests/SmsSluzba.Api.Tests/`: jednotkové testy a testy endpointů s podvrženou bránou (`Api/FakeGatewayHandler.cs`). @@ -29,7 +30,7 @@ ## Záznam změn +- 2026-10-20: Oprava nasazení: služba padala při startu kvůli povinným `SMSSLUZBA_LOGIN`, `SMSSLUZBA_PASSWORD` a `API_KEYS`, proto v AppFactory nefungovalo `/health` ani `/docs` (502). Vlastní klíče služby zrušeny, login a heslo SMS-Služby posílá každá aplikace v hlavičkách. Konfigurace je celá volitelná. Swagger má Authorize pro obě hlavičky a relativní server i bez `ROOT_PATH`. - 2026-10-20: Ověření: opraveno přesměrování `/docs` (Swagger UI přesměrovával absolutně a za proxy by ztratil prefix), špatný JSON vrací 400 i ve vývojovém režimu, balíčky na 10.0.13 (opravená zranitelnost Microsoft.OpenApi). - 2026-10-20: Implementace služby (endpointy, klient brány, blokace po 401, maskování hesla v logu, OpenAPI s prefixem, testy). Šablona .NET 8 v kořeni nahrazena projektem v `src/`. -- 2026-10-20: Návod pro napojení aplikací (integration.md). Každá aplikace má vlastní API klíč (`API_KEYS` ve službě, `SMS_SERVICE_API_KEY` v `.env` aplikace). - 2026-10-20: Návrh přepracován na bezstavového prostředníka (bez DB, workerů a webhooků). Historii a frontu událostí drží poskytovatel. diff --git a/src/SmsSluzba.Api/Auth/ApiClientRegistry.cs b/src/SmsSluzba.Api/Auth/ApiClientRegistry.cs deleted file mode 100644 index 63fd819..0000000 --- a/src/SmsSluzba.Api/Auth/ApiClientRegistry.cs +++ /dev/null @@ -1,42 +0,0 @@ -using System.Security.Cryptography; -using System.Text; -using SmsSluzba.Api.Config; - -namespace SmsSluzba.Api.Auth; - -/// Resolves the calling application from its API key. -internal sealed class ApiClientRegistry(IEnumerable clients) -{ - private const string CurrentClientItemKey = "SmsSluzba.ApiClient"; - private const string UnknownClient = "unknown"; - - // Keys are compared as SHA-256 hashes so every comparison has the same length and runs in constant time. - private readonly (string Name, byte[] KeyHash)[] _clients = clients.Select(c => (c.Name, Hash(c.Key))).ToArray(); - - public string? FindName(string? key) - { - if (string.IsNullOrEmpty(key)) - { - return null; - } - - var hash = Hash(key); - string? match = null; - foreach (var client in _clients) - { - // No early exit, so the response time does not reveal which entry matched. - if (CryptographicOperations.FixedTimeEquals(client.KeyHash, hash)) - { - match = client.Name; - } - } - - return match; - } - - public static void SetCurrent(HttpContext context, string name) => context.Items[CurrentClientItemKey] = name; - - public static string GetCurrent(HttpContext context) => context.Items[CurrentClientItemKey] as string ?? UnknownClient; - - private static byte[] Hash(string value) => SHA256.HashData(Encoding.UTF8.GetBytes(value)); -} diff --git a/src/SmsSluzba.Api/Auth/ApiKeyFilter.cs b/src/SmsSluzba.Api/Auth/ApiKeyFilter.cs deleted file mode 100644 index 7f2f795..0000000 --- a/src/SmsSluzba.Api/Auth/ApiKeyFilter.cs +++ /dev/null @@ -1,21 +0,0 @@ -using SmsSluzba.Api.Problems; - -namespace SmsSluzba.Api.Auth; - -internal sealed class ApiKeyFilter(ApiClientRegistry registry) : IEndpointFilter -{ - public const string HeaderName = "X-Api-Key"; - - public async ValueTask InvokeAsync(EndpointFilterInvocationContext context, EndpointFilterDelegate next) - { - var httpContext = context.HttpContext; - var clientName = registry.FindName(httpContext.Request.Headers[HeaderName].ToString()); - if (clientName is null) - { - return ApiProblems.Result(ApiErrors.Unauthorized); - } - - ApiClientRegistry.SetCurrent(httpContext, clientName); - return await next(context); - } -} diff --git a/src/SmsSluzba.Api/Auth/GatewayCredentialsFilter.cs b/src/SmsSluzba.Api/Auth/GatewayCredentialsFilter.cs new file mode 100644 index 0000000..42876d5 --- /dev/null +++ b/src/SmsSluzba.Api/Auth/GatewayCredentialsFilter.cs @@ -0,0 +1,33 @@ +using SmsSluzba.Api.Gateway; +using SmsSluzba.Api.Problems; + +namespace SmsSluzba.Api.Auth; + +/// Reads the caller's SMS-Sluzba.cz credentials from request headers; the service has none of its own. +internal sealed class GatewayCredentialsFilter : IEndpointFilter +{ + public const string LoginHeader = "X-Sms-Login"; + public const string PasswordHeader = "X-Sms-Password"; + + private const string ItemKey = "SmsSluzba.GatewayCredentials"; + + public async ValueTask InvokeAsync(EndpointFilterInvocationContext context, EndpointFilterDelegate next) + { + var headers = context.HttpContext.Request.Headers; + var login = headers[LoginHeader].ToString().Trim(); + var password = headers[PasswordHeader].ToString(); + if (login.Length == 0 || password.Length == 0) + { + return ApiProblems.Result( + ApiErrors.MissingCredentials, + $"Pošlete login a heslo API přístupu SMS-Služby v hlavičkách {LoginHeader} a {PasswordHeader}."); + } + + context.HttpContext.Items[ItemKey] = new GatewayCredentials(login, password); + return await next(context); + } + + public static GatewayCredentials Get(HttpContext httpContext) => + httpContext.Items[ItemKey] as GatewayCredentials + ?? throw new InvalidOperationException("GatewayCredentialsFilter did not run for this endpoint."); +} diff --git a/src/SmsSluzba.Api/Config/AppSettings.cs b/src/SmsSluzba.Api/Config/AppSettings.cs index b7ec1d7..78b625d 100644 --- a/src/SmsSluzba.Api/Config/AppSettings.cs +++ b/src/SmsSluzba.Api/Config/AppSettings.cs @@ -1,7 +1,6 @@ namespace SmsSluzba.Api.Config; -internal sealed record AppSettings(string? RootPath, GatewaySettings Gateway, IReadOnlyList ApiClients); +/// Invalid optional values that were replaced by defaults; logged at startup. +internal sealed record AppSettings(string? RootPath, GatewaySettings Gateway, IReadOnlyList Warnings); -internal sealed record GatewaySettings(Uri BaseUrl, string Login, string Password, TimeSpan Timeout); - -internal sealed record ApiClient(string Name, string Key); +internal sealed record GatewaySettings(Uri BaseUrl, TimeSpan Timeout); diff --git a/src/SmsSluzba.Api/Config/AppSettingsLoader.cs b/src/SmsSluzba.Api/Config/AppSettingsLoader.cs index f631e76..fb342a3 100644 --- a/src/SmsSluzba.Api/Config/AppSettingsLoader.cs +++ b/src/SmsSluzba.Api/Config/AppSettingsLoader.cs @@ -2,15 +2,15 @@ using System.Globalization; namespace SmsSluzba.Api.Config; -/// Reads and validates all environment configuration in one place. +/// +/// Reads environment configuration in one place. Every value is optional: the service must start +/// without any configuration so that /health and /docs always work in AppFactory. +/// internal static class AppSettingsLoader { public const string RootPathKey = "ROOT_PATH"; - public const string LoginKey = "SMSSLUZBA_LOGIN"; - public const string PasswordKey = "SMSSLUZBA_PASSWORD"; public const string BaseUrlKey = "SMSSLUZBA_BASE_URL"; public const string TimeoutKey = "SMSSLUZBA_TIMEOUT_SECONDS"; - public const string ApiKeysKey = "API_KEYS"; // Endpoint from the SMS Gate API XML 3.0 specification. private const string DefaultBaseUrl = "https://smsgateapi.sms-sluzba.cz/apixml30/"; @@ -20,40 +20,20 @@ internal static class AppSettingsLoader public static AppSettings Load(IConfiguration configuration) { - var errors = new List(); - - var login = Required(configuration, LoginKey, errors); - var password = Required(configuration, PasswordKey, errors); - var baseUrl = ParseBaseUrl(configuration[BaseUrlKey], errors); - var timeout = ParseTimeout(configuration[TimeoutKey], errors); - var clients = ParseApiKeys(configuration[ApiKeysKey], errors); - - if (errors.Count > 0) - { - throw new InvalidOperationException("Neplatná konfigurace služby: " + string.Join(" ", errors)); - } - - return new AppSettings( - NormalizeRootPath(configuration[RootPathKey]), - new GatewaySettings(baseUrl, login, password, timeout), - clients); + var warnings = new List(); + var baseUrl = ParseBaseUrl(configuration[BaseUrlKey], warnings); + var timeout = ParseTimeout(configuration[TimeoutKey], warnings); + return new AppSettings(NormalizeRootPath(configuration[RootPathKey]), new GatewaySettings(baseUrl, timeout), warnings); } - private static string Required(IConfiguration configuration, string key, List errors) + private static Uri ParseBaseUrl(string? value, List warnings) { - var value = configuration[key]; if (string.IsNullOrWhiteSpace(value)) { - errors.Add($"Chybí {key}."); - return string.Empty; + return new Uri(DefaultBaseUrl); } - return value.Trim(); - } - - private static Uri ParseBaseUrl(string? value, List errors) - { - var raw = string.IsNullOrWhiteSpace(value) ? DefaultBaseUrl : value.Trim(); + var raw = value.Trim(); if (!raw.EndsWith('/')) { // Relative gateway paths are resolved against this URL, which requires a trailing slash. @@ -62,14 +42,14 @@ internal static class AppSettingsLoader if (!Uri.TryCreate(raw, UriKind.Absolute, out var uri) || uri.Scheme != Uri.UriSchemeHttps) { - errors.Add($"{BaseUrlKey} musí být absolutní https adresa."); + warnings.Add($"{BaseUrlKey} není absolutní https adresa, použije se {DefaultBaseUrl}."); return new Uri(DefaultBaseUrl); } return uri; } - private static TimeSpan ParseTimeout(string? value, List errors) + private static TimeSpan ParseTimeout(string? value, List warnings) { if (string.IsNullOrWhiteSpace(value)) { @@ -78,54 +58,13 @@ internal static class AppSettingsLoader if (!int.TryParse(value.Trim(), NumberStyles.None, CultureInfo.InvariantCulture, out var seconds) || seconds < 1) { - errors.Add($"{TimeoutKey} musí být kladné celé číslo."); + warnings.Add($"{TimeoutKey} není kladné celé číslo, použije se {DefaultTimeoutSeconds}."); return TimeSpan.FromSeconds(DefaultTimeoutSeconds); } return TimeSpan.FromSeconds(seconds); } - private static List ParseApiKeys(string? value, List errors) - { - var clients = new List(); - if (string.IsNullOrWhiteSpace(value)) - { - errors.Add($"Chybí {ApiKeysKey}."); - return clients; - } - - var entries = value.Split(';', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); - for (var i = 0; i < entries.Length; i++) - { - var separator = entries[i].IndexOf('=', StringComparison.Ordinal); - var name = separator > 0 ? entries[i][..separator].Trim() : string.Empty; - var key = separator > 0 ? entries[i][(separator + 1)..].Trim() : string.Empty; - - // Errors name the position, never the value, because the value is a secret. - if (name.Length == 0 || key.Length == 0) - { - errors.Add($"{ApiKeysKey}: položka {i + 1} nemá tvar nazev=klic."); - continue; - } - - if (clients.Exists(c => c.Name == name)) - { - errors.Add($"{ApiKeysKey}: název {name} je uveden vícekrát."); - continue; - } - - if (clients.Exists(c => c.Key == key)) - { - errors.Add($"{ApiKeysKey}: aplikace {name} má stejný klíč jako jiná aplikace."); - continue; - } - - clients.Add(new ApiClient(name, key)); - } - - return clients; - } - private static string? NormalizeRootPath(string? value) { if (string.IsNullOrWhiteSpace(value)) diff --git a/src/SmsSluzba.Api/Contracts/AccountContracts.cs b/src/SmsSluzba.Api/Contracts/AccountContracts.cs index 58f7b43..32c3e7b 100644 --- a/src/SmsSluzba.Api/Contracts/AccountContracts.cs +++ b/src/SmsSluzba.Api/Contracts/AccountContracts.cs @@ -2,4 +2,4 @@ namespace SmsSluzba.Api.Contracts; internal sealed record CreditResponse(decimal Credit, decimal PriceCzSms, decimal PriceSkSms, decimal PriceOtherSms); -internal sealed record HealthResponse(string Status, string Gateway); +internal sealed record HealthResponse(string Status); diff --git a/src/SmsSluzba.Api/Endpoints/AccountEndpoints.cs b/src/SmsSluzba.Api/Endpoints/AccountEndpoints.cs index b7f4cd0..437488b 100644 --- a/src/SmsSluzba.Api/Endpoints/AccountEndpoints.cs +++ b/src/SmsSluzba.Api/Endpoints/AccountEndpoints.cs @@ -1,3 +1,4 @@ +using SmsSluzba.Api.Auth; using SmsSluzba.Api.Contracts; using SmsSluzba.Api.Gateway; @@ -14,12 +15,14 @@ internal static class AccountEndpoints .Produces() .ProducesProblem(StatusCodes.Status401Unauthorized) .ProducesProblem(StatusCodes.Status502BadGateway) - .ProducesProblem(StatusCodes.Status503ServiceUnavailable) .ProducesProblem(StatusCodes.Status504GatewayTimeout); return group; } - private static Task GetCreditAsync(SmsGatewayClient gateway, CancellationToken ct) => - GatewayProblems.RunAsync(async () => Results.Ok(await gateway.GetCreditAsync(ct))); + private static Task GetCreditAsync(SmsGatewayClient gateway, HttpContext httpContext, CancellationToken ct) + { + var credentials = GatewayCredentialsFilter.Get(httpContext); + return GatewayProblems.RunAsync(async () => Results.Ok(await gateway.GetCreditAsync(credentials, ct))); + } } diff --git a/src/SmsSluzba.Api/Endpoints/EventEndpoints.cs b/src/SmsSluzba.Api/Endpoints/EventEndpoints.cs index 07d6d1b..5318596 100644 --- a/src/SmsSluzba.Api/Endpoints/EventEndpoints.cs +++ b/src/SmsSluzba.Api/Endpoints/EventEndpoints.cs @@ -1,3 +1,4 @@ +using SmsSluzba.Api.Auth; using SmsSluzba.Api.Contracts; using SmsSluzba.Api.Gateway; using SmsSluzba.Api.Problems; @@ -17,12 +18,11 @@ internal static class EventEndpoints .WithName("GetEvents") .WithTags(Tag) .WithSummary("Příchozí SMS, odpovědi a doručenky") - .WithDescription("Brána vrací stejnou událost znovu, dokud ji nepotvrdíte přes POST /v1/events/confirm. Fronta je jedna pro celý účet, události má stahovat jen jedna aplikace.") + .WithDescription("Brána vrací stejnou událost znovu, dokud ji nepotvrdíte přes POST /v1/events/confirm. Fronta je jedna pro každý API přístup.") .Produces() .ProducesProblem(StatusCodes.Status400BadRequest) .ProducesProblem(StatusCodes.Status401Unauthorized) .ProducesProblem(StatusCodes.Status502BadGateway) - .ProducesProblem(StatusCodes.Status503ServiceUnavailable) .ProducesProblem(StatusCodes.Status504GatewayTimeout); group.MapPost("/events/confirm", ConfirmAsync) @@ -36,7 +36,12 @@ internal static class EventEndpoints return group; } - private static async Task GetEventsAsync(string? types, int? count, SmsGatewayClient gateway, CancellationToken ct) + private static async Task GetEventsAsync( + string? types, + int? count, + SmsGatewayClient gateway, + HttpContext httpContext, + CancellationToken ct) { var query = GatewayEventQuery.Parse(types); if (query is null) @@ -51,11 +56,16 @@ internal static class EventEndpoints return ApiProblems.Validation($"Parametr 'count' musí být 1 až {MaxBatchSize}."); } + var credentials = GatewayCredentialsFilter.Get(httpContext); return await GatewayProblems.RunAsync(async () => - Results.Ok(new EventsResponse(await gateway.GetEventsAsync(query, size, ct)))); + Results.Ok(new EventsResponse(await gateway.GetEventsAsync(credentials, query, size, ct)))); } - private static async Task ConfirmAsync(ConfirmEventsRequest request, SmsGatewayClient gateway, CancellationToken ct) + private static async Task ConfirmAsync( + ConfirmEventsRequest request, + SmsGatewayClient gateway, + HttpContext httpContext, + CancellationToken ct) { if (request.Events is not { Count: > 0 } events) { @@ -80,13 +90,14 @@ internal static class EventEndpoints items.Add((item.Type, item.Id.Trim(), gatewayType)); } + var credentials = GatewayCredentialsFilter.Get(httpContext); var confirmed = new List(); var failed = new List(); foreach (var (type, id, gatewayType) in items) { try { - await gateway.ConfirmAsync(gatewayType, id, ct); + await gateway.ConfirmAsync(credentials, gatewayType, id, ct); confirmed.Add(new ConfirmedEvent(type, id)); } catch (GatewayException ex) diff --git a/src/SmsSluzba.Api/Endpoints/GatewayProblems.cs b/src/SmsSluzba.Api/Endpoints/GatewayProblems.cs index b24f0e0..b716b3b 100644 --- a/src/SmsSluzba.Api/Endpoints/GatewayProblems.cs +++ b/src/SmsSluzba.Api/Endpoints/GatewayProblems.cs @@ -12,7 +12,7 @@ internal static class GatewayProblems GatewayErrorKind.InvalidRecipient => ApiErrors.InvalidRecipient, GatewayErrorKind.MissingText => ApiErrors.MissingText, GatewayErrorKind.Rejected => ApiErrors.ProviderRejected, - GatewayErrorKind.AuthFailed or GatewayErrorKind.AuthBlocked => ApiErrors.ProviderAuthBlocked, + GatewayErrorKind.AuthFailed or GatewayErrorKind.AuthBlocked => ApiErrors.InvalidCredentials, GatewayErrorKind.InsufficientCredit => ApiErrors.InsufficientCredit, GatewayErrorKind.Timeout => ApiErrors.ProviderTimeout, _ => ApiErrors.ProviderUnavailable, diff --git a/src/SmsSluzba.Api/Endpoints/MessageEndpoints.cs b/src/SmsSluzba.Api/Endpoints/MessageEndpoints.cs index 7f850de..3aca62d 100644 --- a/src/SmsSluzba.Api/Endpoints/MessageEndpoints.cs +++ b/src/SmsSluzba.Api/Endpoints/MessageEndpoints.cs @@ -18,13 +18,12 @@ internal static class MessageEndpoints .WithName("SendMessage") .WithTags(Tag) .WithSummary("Odešle SMS") - .WithDescription("Každé úspěšné volání odešle a zaplatí jednu SMS. Po chybě 502 nebo 504 je stav neznámý, odeslání neopakujte automaticky.") + .WithDescription("Každé úspěšné volání odešle a zaplatí jednu SMS. Po chybě 500, 502 nebo 504 je stav neznámý, odeslání neopakujte automaticky.") .Produces() .ProducesProblem(StatusCodes.Status400BadRequest) .ProducesProblem(StatusCodes.Status401Unauthorized) .ProducesProblem(StatusCodes.Status402PaymentRequired) .ProducesProblem(StatusCodes.Status502BadGateway) - .ProducesProblem(StatusCodes.Status503ServiceUnavailable) .ProducesProblem(StatusCodes.Status504GatewayTimeout); group.MapGet("/messages/{id}/delivery-report", GetDeliveryReportAsync) @@ -35,7 +34,6 @@ internal static class MessageEndpoints .ProducesProblem(StatusCodes.Status401Unauthorized) .ProducesProblem(StatusCodes.Status404NotFound) .ProducesProblem(StatusCodes.Status502BadGateway) - .ProducesProblem(StatusCodes.Status503ServiceUnavailable) .ProducesProblem(StatusCodes.Status504GatewayTimeout); return group; @@ -64,34 +62,39 @@ internal static class MessageEndpoints return ApiProblems.Result(ApiErrors.TextTooLong, $"Text má {length} znaků, maximum je {SmsText.MaxLength}."); } + var credentials = GatewayCredentialsFilter.Get(httpContext); var recipient = request.To.Trim(); - var client = ApiClientRegistry.GetCurrent(httpContext); var logger = loggerFactory.CreateLogger(LoggerCategory); return await GatewayProblems.RunAsync(async () => { - var result = await gateway.SendAsync(recipient, request.Text, request.DeliveryReport, request.SendAt, ct); + var result = await gateway.SendAsync(credentials, recipient, request.Text, request.DeliveryReport, request.SendAt, ct); logger.LogInformation( - "SMS {MessageId} for {Recipient} accepted by gateway, client {Client}, parts {Parts}, price {Price}", + "SMS {MessageId} for {Recipient} accepted by gateway, login {Login}, parts {Parts}, price {Price}", result.Id, LogMask.Phone(recipient), - client, + credentials.Login, result.Parts, result.Price); return Results.Ok(result); }); } - private static async Task GetDeliveryReportAsync(string id, SmsGatewayClient gateway, CancellationToken ct) + private static async Task GetDeliveryReportAsync( + string id, + SmsGatewayClient gateway, + HttpContext httpContext, + CancellationToken ct) { if (string.IsNullOrWhiteSpace(id)) { return ApiProblems.Validation("Chybí id zprávy."); } + var credentials = GatewayCredentialsFilter.Get(httpContext); return await GatewayProblems.RunAsync(async () => { - var report = await gateway.GetDeliveryReportAsync(id.Trim(), ct); + var report = await gateway.GetDeliveryReportAsync(credentials, id.Trim(), ct); return report is null ? ApiProblems.Result(ApiErrors.DeliveryReportNotFound) : Results.Ok(report); }); } diff --git a/src/SmsSluzba.Api/Endpoints/SystemEndpoints.cs b/src/SmsSluzba.Api/Endpoints/SystemEndpoints.cs index 76c7489..5f688d5 100644 --- a/src/SmsSluzba.Api/Endpoints/SystemEndpoints.cs +++ b/src/SmsSluzba.Api/Endpoints/SystemEndpoints.cs @@ -1,13 +1,9 @@ using SmsSluzba.Api.Contracts; -using SmsSluzba.Api.Gateway; namespace SmsSluzba.Api.Endpoints; internal static class SystemEndpoints { - private const string GatewayOk = "ok"; - private const string GatewayBlocked = "blocked"; - public static IEndpointRouteBuilder MapSystemEndpoints(this IEndpointRouteBuilder app) { app.MapGet("/", () => Results.Json(new @@ -18,10 +14,7 @@ internal static class SystemEndpoints })) .ExcludeFromDescription(); - // Stays 200 even when the gateway login is blocked: a failing health check would make AppFactory - // restart the container, and every restart would try the wrong password again. - app.MapGet("/health", (GatewayAuthGuard authGuard) => - Results.Ok(new HealthResponse("ok", authGuard.IsBlocked ? GatewayBlocked : GatewayOk))) + app.MapGet("/health", () => Results.Ok(new HealthResponse("ok"))) .WithName("Health") .WithTags("Služba") .WithSummary("Stav služby, nevolá SMS bránu") diff --git a/src/SmsSluzba.Api/Gateway/GatewayAuthGuard.cs b/src/SmsSluzba.Api/Gateway/GatewayAuthGuard.cs index fed54cd..eb66638 100644 --- a/src/SmsSluzba.Api/Gateway/GatewayAuthGuard.cs +++ b/src/SmsSluzba.Api/Gateway/GatewayAuthGuard.cs @@ -1,31 +1,34 @@ +using System.Collections.Concurrent; + namespace SmsSluzba.Api.Gateway; /// -/// Stops all gateway calls after the gateway rejects the credentials, because repeated failed logins -/// block the account. Kept in memory only: a restart (usually after fixing the password) resets it. +/// Stops gateway calls with credentials the gateway has rejected, because repeated failed logins +/// block the account. Only the rejected login/password pair is stopped; corrected credentials pass. +/// Kept in memory, a restart clears it. /// internal sealed class GatewayAuthGuard(ILogger logger) { - private int _blocked; - private string? _providerCode; + private readonly ConcurrentDictionary _rejected = new(StringComparer.Ordinal); - public bool IsBlocked => Volatile.Read(ref _blocked) == 1; - - public void ThrowIfBlocked() + public void ThrowIfRejected(GatewayCredentials credentials) { - if (IsBlocked) + if (_rejected.TryGetValue(credentials.Fingerprint, out var providerCode)) { - throw new GatewayException(GatewayErrorKind.AuthBlocked, _providerCode, "Volání SMS brány jsou zastavená po chybě přihlášení."); + throw new GatewayException( + GatewayErrorKind.AuthBlocked, + providerCode, + "Brána tyto přihlašovací údaje už odmítla. Aby se účet nezablokoval, služba je bráně znovu neposílá. Opravte login nebo heslo."); } } - public void Block(string? providerCode) + public void Reject(GatewayCredentials credentials, string? providerCode) { - _providerCode = providerCode; - if (Interlocked.Exchange(ref _blocked, 1) == 0) + if (_rejected.TryAdd(credentials.Fingerprint, providerCode)) { - logger.LogCritical( - "SMS gateway rejected the credentials (provider code {ProviderCode}). All gateway calls are stopped until the service restarts with corrected credentials.", + logger.LogWarning( + "SMS gateway rejected credentials for login {Login} (provider code {ProviderCode}); further calls with them are stopped", + credentials.Login, providerCode); } } diff --git a/src/SmsSluzba.Api/Gateway/GatewayCredentials.cs b/src/SmsSluzba.Api/Gateway/GatewayCredentials.cs new file mode 100644 index 0000000..9e25ab7 --- /dev/null +++ b/src/SmsSluzba.Api/Gateway/GatewayCredentials.cs @@ -0,0 +1,14 @@ +using System.Security.Cryptography; +using System.Text; + +namespace SmsSluzba.Api.Gateway; + +/// Login and password of the caller's own API access at SMS-Sluzba.cz, forwarded to the gateway. +internal sealed record GatewayCredentials(string Login, string Password) +{ + /// Identifies the login/password pair without keeping the password itself. + public string Fingerprint { get; } = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(Login + "\n" + Password))); + + // The generated record ToString would print the password. + public override string ToString() => $"GatewayCredentials {{ Login = {Login} }}"; +} diff --git a/src/SmsSluzba.Api/Gateway/SmsGatewayClient.cs b/src/SmsSluzba.Api/Gateway/SmsGatewayClient.cs index b847076..02b1270 100644 --- a/src/SmsSluzba.Api/Gateway/SmsGatewayClient.cs +++ b/src/SmsSluzba.Api/Gateway/SmsGatewayClient.cs @@ -1,20 +1,16 @@ using System.Globalization; using System.Text; using System.Xml.Linq; -using SmsSluzba.Api.Config; using SmsSluzba.Api.Contracts; namespace SmsSluzba.Api.Gateway; /// -/// Typed client of the SMS-Sluzba.cz API XML 3.0. Every failure surfaces as . -/// No call is retried here: sending is not idempotent and a retry could send and charge an SMS twice. +/// Typed client of the SMS-Sluzba.cz API XML 3.0. Every call uses the caller's own credentials. +/// Every failure surfaces as . No call is retried here: sending is not +/// idempotent and a retry could send and charge an SMS twice. /// -internal sealed class SmsGatewayClient( - HttpClient http, - GatewaySettings settings, - GatewayAuthGuard authGuard, - ILogger logger) +internal sealed class SmsGatewayClient(HttpClient http, GatewayAuthGuard authGuard, ILogger logger) { private const string ReceiverPath = "receiver"; private const string SenderPath = "sender"; @@ -23,20 +19,26 @@ internal sealed class SmsGatewayClient( private const string Enabled = "1"; public Task SendAsync( + GatewayCredentials credentials, string recipient, string text, bool? deliveryReport, DateTimeOffset? sendAt, CancellationToken ct) => - ExecuteAsync("send", async () => + ExecuteAsync(credentials, "send", async () => { var xml = GatewayXml.BuildOutgoingMessage(recipient, text, deliveryReport, sendAt); - var document = await CallAsync(HttpMethod.Post, ReceiverPath, [], new StringContent(xml, Encoding.UTF8, "text/xml"), ct); + var content = new StringContent(xml, Encoding.UTF8, "text/xml"); + var document = await CallAsync(credentials, HttpMethod.Post, ReceiverPath, [], content, ct); return GatewayXml.ParseSendResult(RequireDocument(document)); }); - public Task> GetEventsAsync(GatewayEventQuery query, int count, CancellationToken ct) => - ExecuteAsync>("events", async () => + public Task> GetEventsAsync( + GatewayCredentials credentials, + GatewayEventQuery query, + int count, + CancellationToken ct) => + ExecuteAsync>(credentials, "events", async () => { var parameters = new List> { @@ -57,7 +59,7 @@ internal sealed class SmsGatewayClient( parameters.Add(new("query_outgoing", Enabled)); } - var document = await CallAsync(HttpMethod.Get, SenderPath, parameters, null, ct); + var document = await CallAsync(credentials, HttpMethod.Get, SenderPath, parameters, null, ct); if (document is null) { return []; @@ -72,10 +74,16 @@ internal sealed class SmsGatewayClient( return parsed.Events; }); - public Task GetDeliveryReportAsync(string messageId, CancellationToken ct) => - ExecuteAsync("delivery-report", async () => + public Task GetDeliveryReportAsync(GatewayCredentials credentials, string messageId, CancellationToken ct) => + ExecuteAsync(credentials, "delivery-report", async () => { - var document = await CallAsync(HttpMethod.Get, SenderPath, [new("act", "get_delivery_report"), new("id", messageId)], null, ct); + var document = await CallAsync( + credentials, + HttpMethod.Get, + SenderPath, + [new("act", "get_delivery_report"), new("id", messageId)], + null, + ct); if (document is null) { return null; @@ -87,21 +95,21 @@ internal sealed class SmsGatewayClient( : new DeliveryReportResponse(report.MessageId, report.Status, report.Description, report.DeliveredAt); }); - public Task ConfirmAsync(string gatewayType, string id, CancellationToken ct) => - ExecuteAsync("confirm", async () => + public Task ConfirmAsync(GatewayCredentials credentials, string gatewayType, string id, CancellationToken ct) => + ExecuteAsync(credentials, "confirm", async () => { - await CallAsync(HttpMethod.Get, ConfirmPath, [new("type", gatewayType), new("id", id)], null, ct); + await CallAsync(credentials, HttpMethod.Get, ConfirmPath, [new("type", gatewayType), new("id", id)], null, ct); return true; }); - public Task GetCreditAsync(CancellationToken ct) => - ExecuteAsync("credit", async () => + public Task GetCreditAsync(GatewayCredentials credentials, CancellationToken ct) => + ExecuteAsync(credentials, "credit", async () => { - var document = await CallAsync(HttpMethod.Get, CreditPath, [], null, ct); + var document = await CallAsync(credentials, HttpMethod.Get, CreditPath, [], null, ct); return GatewayXml.ParseCredit(RequireDocument(document)); }); - private async Task ExecuteAsync(string operation, Func> call) + private async Task ExecuteAsync(GatewayCredentials credentials, string operation, Func> call) { try { @@ -111,14 +119,15 @@ internal sealed class SmsGatewayClient( { if (ex.Kind == GatewayErrorKind.AuthFailed) { - authGuard.Block(ex.ProviderCode); + authGuard.Reject(credentials, ex.ProviderCode); } else { logger.LogWarning( ex.InnerException, - "Gateway {Operation} failed: {Kind}, provider code {ProviderCode}", + "Gateway {Operation} for login {Login} failed: {Kind}, provider code {ProviderCode}", operation, + credentials.Login, ex.Kind, ex.ProviderCode); } @@ -128,15 +137,16 @@ internal sealed class SmsGatewayClient( } private async Task CallAsync( + GatewayCredentials credentials, HttpMethod method, string path, IReadOnlyList> parameters, HttpContent? content, CancellationToken ct) { - authGuard.ThrowIfBlocked(); + authGuard.ThrowIfRejected(credentials); - using var request = new HttpRequestMessage(method, BuildUri(path, parameters)) { Content = content }; + using var request = new HttpRequestMessage(method, BuildUri(credentials, path, parameters)) { Content = content }; try { using var response = await http.SendAsync(request, ct); @@ -153,12 +163,15 @@ internal sealed class SmsGatewayClient( } } - private Uri BuildUri(string path, IReadOnlyList> parameters) + private static Uri BuildUri( + GatewayCredentials credentials, + string path, + IReadOnlyList> parameters) { var query = new List> { - new("login", settings.Login), - new("password", settings.Password), + new("login", credentials.Login), + new("password", credentials.Password), }; query.AddRange(parameters); diff --git a/src/SmsSluzba.Api/OpenApi/OpenApiSetup.cs b/src/SmsSluzba.Api/OpenApi/OpenApiSetup.cs index f920b7a..9746fbe 100644 --- a/src/SmsSluzba.Api/OpenApi/OpenApiSetup.cs +++ b/src/SmsSluzba.Api/OpenApi/OpenApiSetup.cs @@ -6,9 +6,14 @@ namespace SmsSluzba.Api.OpenApi; internal static class OpenApiSetup { public const string DocumentPath = "/openapi/v1.json"; - private const string ApiKeySchemeId = "ApiKey"; + private const string LoginSchemeId = "SmsLogin"; + private const string PasswordSchemeId = "SmsPassword"; private const string ProtectedPathPrefix = "/v1/"; + // Without ROOT_PATH the server is resolved relative to the document URL (/openapi/v1.json), + // which gives / behind any proxy prefix, so "Try it out" never drops /apps/. + private const string RelativeServerUrl = ".."; + public static IServiceCollection AddSmsOpenApi(this IServiceCollection services, string? rootPath) => services.AddOpenApi(options => options.AddDocumentTransformer((document, _, _) => { @@ -16,22 +21,23 @@ internal static class OpenApiSetup { Title = "SMS služba", Version = "v1", - Description = "Prostředník nad SMS-Služba.cz. Návod pro napojení aplikací je v documentation/integration.md.", + Description = "Prostředník nad SMS-Služba.cz. Endpointy /v1 vyžadují login a heslo API přístupu SMS-Služby " + + $"v hlavičkách {GatewayCredentialsFilter.LoginHeader} a {GatewayCredentialsFilter.PasswordHeader} " + + "(tlačítko Authorize). Návod pro napojení aplikací je v documentation/integration.md.", }; - // Behind the AppFactory proxy the request host is internal and the prefix is stripped, - // so a relative server with ROOT_PATH keeps "Try it out" on /apps/. - document.Servers = [new OpenApiServer { Url = rootPath ?? "/" }]; + // Behind the AppFactory proxy the request host is internal and the prefix is stripped, so the + // server must never come from the incoming request. + document.Servers = [new OpenApiServer { Url = rootPath ?? RelativeServerUrl }]; document.Components ??= new OpenApiComponents(); document.Components.SecuritySchemes ??= new Dictionary(); - document.Components.SecuritySchemes[ApiKeySchemeId] = new OpenApiSecurityScheme - { - Type = SecuritySchemeType.ApiKey, - Name = ApiKeyFilter.HeaderName, - In = ParameterLocation.Header, - Description = "API klíč aplikace.", - }; + document.Components.SecuritySchemes[LoginSchemeId] = HeaderScheme( + GatewayCredentialsFilter.LoginHeader, + "Login API přístupu SMS-Služby."); + document.Components.SecuritySchemes[PasswordSchemeId] = HeaderScheme( + GatewayCredentialsFilter.PasswordHeader, + "Heslo API přístupu SMS-Služby."); foreach (var (path, item) in document.Paths) { @@ -45,11 +51,20 @@ internal static class OpenApiSetup operation.Security ??= []; operation.Security.Add(new OpenApiSecurityRequirement { - [new OpenApiSecuritySchemeReference(ApiKeySchemeId, document)] = [], + [new OpenApiSecuritySchemeReference(LoginSchemeId, document)] = [], + [new OpenApiSecuritySchemeReference(PasswordSchemeId, document)] = [], }); } } return Task.CompletedTask; })); + + private static OpenApiSecurityScheme HeaderScheme(string headerName, string description) => new() + { + Type = SecuritySchemeType.ApiKey, + Name = headerName, + In = ParameterLocation.Header, + Description = description, + }; } diff --git a/src/SmsSluzba.Api/Problems/ApiErrors.cs b/src/SmsSluzba.Api/Problems/ApiErrors.cs index c9267af..c1f1678 100644 --- a/src/SmsSluzba.Api/Problems/ApiErrors.cs +++ b/src/SmsSluzba.Api/Problems/ApiErrors.cs @@ -11,20 +11,19 @@ internal static class ApiErrors public static readonly ApiError MissingText = new("missing_text", 400, "Chybí text zprávy"); public static readonly ApiError TextTooLong = new("text_too_long", 400, "Text zprávy je příliš dlouhý"); public static readonly ApiError ProviderRejected = new("provider_rejected", 400, "SMS brána požadavek odmítla"); - public static readonly ApiError Unauthorized = new("unauthorized", 401, "Chybí nebo je neplatný API klíč"); + public static readonly ApiError MissingCredentials = new("missing_credentials", 401, "Chybí přihlašovací údaje k SMS bráně"); + public static readonly ApiError InvalidCredentials = new("invalid_credentials", 401, "SMS brána odmítla přihlašovací údaje"); public static readonly ApiError InsufficientCredit = new("insufficient_credit", 402, "Nedostatek kreditu u SMS brány"); public static readonly ApiError NotFound = new("not_found", 404, "Nenalezeno"); public static readonly ApiError DeliveryReportNotFound = new("delivery_report_not_found", 404, "Doručenka zatím není k dispozici"); public static readonly ApiError Internal = new("internal_error", 500, "Neočekávaná chyba služby"); public static readonly ApiError ProviderUnavailable = new("provider_unavailable", 502, "SMS brána není dostupná"); - public static readonly ApiError ProviderAuthBlocked = new("provider_auth_blocked", 503, "Služba se nemůže přihlásit k SMS bráně"); public static readonly ApiError ProviderTimeout = new("provider_timeout", 504, "SMS brána neodpověděla včas"); /// Fallback for responses produced by the framework (bad JSON, unknown route, unhandled exception). public static ApiError ForStatus(int? status) => status switch { 400 => ValidationFailed, - 401 => Unauthorized, 404 => NotFound, >= 500 => Internal, _ => new ApiError("request_failed", status ?? 400, "Požadavek nelze zpracovat"), diff --git a/src/SmsSluzba.Api/Program.cs b/src/SmsSluzba.Api/Program.cs index 00372b9..7457cb9 100644 --- a/src/SmsSluzba.Api/Program.cs +++ b/src/SmsSluzba.Api/Program.cs @@ -8,8 +8,6 @@ using SmsSluzba.Api.Problems; var builder = WebApplication.CreateBuilder(args); var settings = AppSettingsLoader.Load(builder.Configuration); -builder.Services.AddSingleton(settings.Gateway); -builder.Services.AddSingleton(new ApiClientRegistry(settings.ApiClients)); builder.Services.AddSingleton(); builder.Services.AddTransient(); builder.Services @@ -28,6 +26,11 @@ builder.Services.AddSmsOpenApi(settings.RootPath); var app = builder.Build(); +foreach (var warning in settings.Warnings) +{ + app.Logger.LogWarning("Configuration: {Warning}", warning); +} + if (settings.RootPath is not null) { app.UsePathBase(settings.RootPath); @@ -58,11 +61,13 @@ app.UseSwaggerUI(options => options.DocumentTitle = "SMS služba"; // Relative to /docs/index.html, so the document is loaded under the proxy prefix as well. options.SwaggerEndpoint(".." + OpenApiSetup.DocumentPath, "SMS služba v1"); + // Keeps the credentials entered via Authorize after a page reload. + options.EnablePersistAuthorization(); }); app.MapSystemEndpoints(); -var v1 = app.MapGroup("/v1").AddEndpointFilter(); +var v1 = app.MapGroup("/v1").AddEndpointFilter(); v1.MapMessageEndpoints(); v1.MapEventEndpoints(); v1.MapAccountEndpoints(); diff --git a/tests/SmsSluzba.Api.Tests/Api/ApiTests.cs b/tests/SmsSluzba.Api.Tests/Api/ApiTests.cs index ce0843d..53240f9 100644 --- a/tests/SmsSluzba.Api.Tests/Api/ApiTests.cs +++ b/tests/SmsSluzba.Api.Tests/Api/ApiTests.cs @@ -29,8 +29,7 @@ public sealed class ApiTests : IDisposable public ApiTests() { _factory = new SmsApiFactory(_gateway); - _client = _factory.CreateClient(); - _client.DefaultRequestHeaders.Add("X-Api-Key", SmsApiFactory.ApiKey); + _client = CreateClient(SmsApiFactory.Login, SmsApiFactory.Password); } public void Dispose() @@ -41,7 +40,7 @@ public sealed class ApiTests : IDisposable } [Fact] - public async Task Health_WithoutApiKey_ReturnsOk() + public async Task Health_WithoutAnyConfiguration_ReturnsOk() { using var anonymous = _factory.CreateClient(); @@ -52,20 +51,19 @@ public sealed class ApiTests : IDisposable } [Fact] - public async Task V1_WithWrongApiKey_Returns401WithCode() + public async Task V1_WithoutCredentials_Returns401WithoutGatewayCall() { using var anonymous = _factory.CreateClient(); - anonymous.DefaultRequestHeaders.Add("X-Api-Key", "wrong"); var response = await anonymous.GetAsync(new Uri("/v1/account/credit", UriKind.Relative)); Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); - Assert.Equal("unauthorized", (await ReadJson(response)).GetProperty("code").GetString()); + Assert.Equal("missing_credentials", (await ReadJson(response)).GetProperty("code").GetString()); Assert.Empty(_gateway.Requests); } [Fact] - public async Task SendMessage_Success_ReturnsGatewayResultAndSendsXml() + public async Task SendMessage_Success_ForwardsCallerCredentialsAndXml() { _gateway.Enqueue(SendSuccessXml); @@ -79,8 +77,9 @@ public sealed class ApiTests : IDisposable Assert.Equal(453.49m, json.GetProperty("credit").GetDecimal()); var (uri, body) = Assert.Single(_gateway.Requests); - Assert.EndsWith("/apixml30/receiver", uri.AbsolutePath, StringComparison.Ordinal); - Assert.Contains("password=" + SmsApiFactory.GatewayPassword, uri.Query, StringComparison.Ordinal); + Assert.Equal("/apixml30/receiver", uri.AbsolutePath); + Assert.Contains("login=" + SmsApiFactory.Login, uri.Query, StringComparison.Ordinal); + Assert.Contains("password=" + SmsApiFactory.Password, uri.Query, StringComparison.Ordinal); var sent = XDocument.Parse(body!).Root!; Assert.Equal("Test & co", sent.Element("text")?.Value); Assert.Equal("20", sent.Element("dr_request")?.Value); @@ -132,19 +131,22 @@ public sealed class ApiTests : IDisposable } [Fact] - public async Task AuthFailure_StopsAllFurtherGatewayCalls() + public async Task RejectedCredentials_AreNotSentAgain_OtherCredentialsStillWork() { _gateway.Enqueue("401Chybne prihlaseni"); + _gateway.Enqueue("1111"); + using var other = CreateClient("cms-login", "cms-password"); - var first = await _client.PostAsJsonAsync("/v1/messages", new { to = "+420603123456", text = "Test" }); + var first = await _client.GetAsync(new Uri("/v1/account/credit", UriKind.Relative)); var second = await _client.GetAsync(new Uri("/v1/account/credit", UriKind.Relative)); - var health = await ReadJson(await _client.GetAsync(new Uri("/health", UriKind.Relative))); + var otherApp = await other.GetAsync(new Uri("/v1/account/credit", UriKind.Relative)); - Assert.Equal(HttpStatusCode.ServiceUnavailable, first.StatusCode); - Assert.Equal(HttpStatusCode.ServiceUnavailable, second.StatusCode); - Assert.Equal("provider_auth_blocked", (await ReadJson(second)).GetProperty("code").GetString()); - Assert.Equal("blocked", health.GetProperty("gateway").GetString()); - Assert.Single(_gateway.Requests); + Assert.Equal(HttpStatusCode.Unauthorized, first.StatusCode); + Assert.Equal("invalid_credentials", (await ReadJson(first)).GetProperty("code").GetString()); + Assert.Equal(HttpStatusCode.Unauthorized, second.StatusCode); + Assert.Equal(HttpStatusCode.OK, otherApp.StatusCode); + Assert.Equal(2, _gateway.Requests.Count); + Assert.Contains("login=cms-login", _gateway.Requests[1].Uri.Query, StringComparison.Ordinal); } [Fact] @@ -218,15 +220,17 @@ public sealed class ApiTests : IDisposable } [Fact] - public async Task OpenApi_DescribesApiKeyAndRelativeServer() + public async Task OpenApi_DescribesCredentialHeadersAndRelativeServer() { var json = await ReadJson(await _client.GetAsync(new Uri("/openapi/v1.json", UriKind.Relative))); - Assert.Equal("/", json.GetProperty("servers")[0].GetProperty("url").GetString()); - var scheme = json.GetProperty("components").GetProperty("securitySchemes").GetProperty("ApiKey"); - Assert.Equal("X-Api-Key", scheme.GetProperty("name").GetString()); - var send = json.GetProperty("paths").GetProperty("/v1/messages").GetProperty("post"); - Assert.True(send.GetProperty("security")[0].TryGetProperty("ApiKey", out _)); + Assert.Equal("..", json.GetProperty("servers")[0].GetProperty("url").GetString()); + var schemes = json.GetProperty("components").GetProperty("securitySchemes"); + Assert.Equal("X-Sms-Login", schemes.GetProperty("SmsLogin").GetProperty("name").GetString()); + Assert.Equal("X-Sms-Password", schemes.GetProperty("SmsPassword").GetProperty("name").GetString()); + var requirement = json.GetProperty("paths").GetProperty("/v1/messages").GetProperty("post").GetProperty("security")[0]; + Assert.True(requirement.TryGetProperty("SmsLogin", out _)); + Assert.True(requirement.TryGetProperty("SmsPassword", out _)); } [Fact] @@ -240,6 +244,14 @@ public sealed class ApiTests : IDisposable Assert.Equal("docs/index.html", response.Headers.Location?.OriginalString); } + private HttpClient CreateClient(string login, string password) + { + var client = _factory.CreateClient(); + client.DefaultRequestHeaders.Add("X-Sms-Login", login); + client.DefaultRequestHeaders.Add("X-Sms-Password", password); + return client; + } + private static async Task ReadJson(HttpResponseMessage response) => JsonDocument.Parse(await response.Content.ReadAsStringAsync()).RootElement.Clone(); } diff --git a/tests/SmsSluzba.Api.Tests/Api/SmsApiFactory.cs b/tests/SmsSluzba.Api.Tests/Api/SmsApiFactory.cs index c40e6b1..1534d32 100644 --- a/tests/SmsSluzba.Api.Tests/Api/SmsApiFactory.cs +++ b/tests/SmsSluzba.Api.Tests/Api/SmsApiFactory.cs @@ -2,22 +2,17 @@ using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc.Testing; using Microsoft.AspNetCore.TestHost; using Microsoft.Extensions.DependencyInjection; -using SmsSluzba.Api.Config; using SmsSluzba.Api.Gateway; namespace SmsSluzba.Api.Tests.Api; +/// Runs the service without any configuration, exactly as a fresh AppFactory container does. internal sealed class SmsApiFactory(FakeGatewayHandler gateway) : WebApplicationFactory { - public const string ApiKey = "test-key-eshop"; - public const string GatewayPassword = "gateway-password"; + public const string Login = "eshop-login"; + public const string Password = "eshop-password"; - protected override void ConfigureWebHost(IWebHostBuilder builder) - { - builder.UseSetting(AppSettingsLoader.LoginKey, "gateway-login"); - builder.UseSetting(AppSettingsLoader.PasswordKey, GatewayPassword); - builder.UseSetting(AppSettingsLoader.ApiKeysKey, "eshop=" + ApiKey); + protected override void ConfigureWebHost(IWebHostBuilder builder) => builder.ConfigureTestServices(services => services.AddHttpClient().ConfigurePrimaryHttpMessageHandler(() => gateway)); - } } diff --git a/tests/SmsSluzba.Api.Tests/Config/AppSettingsLoaderTests.cs b/tests/SmsSluzba.Api.Tests/Config/AppSettingsLoaderTests.cs index 38815b7..1ea815d 100644 --- a/tests/SmsSluzba.Api.Tests/Config/AppSettingsLoaderTests.cs +++ b/tests/SmsSluzba.Api.Tests/Config/AppSettingsLoaderTests.cs @@ -6,61 +6,36 @@ namespace SmsSluzba.Api.Tests.Config; public class AppSettingsLoaderTests { [Fact] - public void Load_ValidConfiguration_AppliesDefaultsAndNormalizesRootPath() + public void Load_EmptyConfiguration_UsesDefaults() + { + var settings = AppSettingsLoader.Load(Build(new())); + + Assert.Null(settings.RootPath); + Assert.Equal(new Uri("https://smsgateapi.sms-sluzba.cz/apixml30/"), settings.Gateway.BaseUrl); + Assert.Equal(TimeSpan.FromSeconds(30), settings.Gateway.Timeout); + Assert.Empty(settings.Warnings); + } + + [Fact] + public void Load_RootPath_IsNormalized() + { + var settings = AppSettingsLoader.Load(Build(new() { ["ROOT_PATH"] = "apps/sms-sluzba/" })); + + Assert.Equal("/apps/sms-sluzba", settings.RootPath); + } + + [Fact] + public void Load_InvalidOptionalValues_FallBackToDefaultsWithWarnings() { var settings = AppSettingsLoader.Load(Build(new() { - ["ROOT_PATH"] = "apps/sms-sluzba/", - ["SMSSLUZBA_LOGIN"] = "login", - ["SMSSLUZBA_PASSWORD"] = "password", - ["API_KEYS"] = "eshop=key-one; cms=key-two", + ["SMSSLUZBA_BASE_URL"] = "http://example.com/", + ["SMSSLUZBA_TIMEOUT_SECONDS"] = "abc", })); - Assert.Equal("/apps/sms-sluzba", settings.RootPath); Assert.Equal(new Uri("https://smsgateapi.sms-sluzba.cz/apixml30/"), settings.Gateway.BaseUrl); Assert.Equal(TimeSpan.FromSeconds(30), settings.Gateway.Timeout); - Assert.Equal(new[] { "eshop", "cms" }, settings.ApiClients.Select(c => c.Name)); - } - - [Fact] - public void Load_InvalidConfiguration_ListsProblemsWithoutSecretValues() - { - var ex = Assert.Throws(() => AppSettingsLoader.Load(Build(new() - { - ["SMSSLUZBA_PASSWORD"] = "password", - ["SMSSLUZBA_TIMEOUT_SECONDS"] = "abc", - ["API_KEYS"] = "eshop=very-secret-key;broken", - }))); - - Assert.Contains("SMSSLUZBA_LOGIN", ex.Message, StringComparison.Ordinal); - Assert.Contains("SMSSLUZBA_TIMEOUT_SECONDS", ex.Message, StringComparison.Ordinal); - Assert.Contains("položka 2", ex.Message, StringComparison.Ordinal); - Assert.DoesNotContain("very-secret-key", ex.Message, StringComparison.Ordinal); - } - - [Fact] - public void Load_DuplicateKey_Fails() - { - var ex = Assert.Throws(() => AppSettingsLoader.Load(Build(new() - { - ["SMSSLUZBA_LOGIN"] = "login", - ["SMSSLUZBA_PASSWORD"] = "password", - ["API_KEYS"] = "eshop=same;cms=same", - }))); - - Assert.Contains("cms", ex.Message, StringComparison.Ordinal); - } - - [Fact] - public void Load_HttpBaseUrl_Fails() - { - Assert.Throws(() => AppSettingsLoader.Load(Build(new() - { - ["SMSSLUZBA_LOGIN"] = "login", - ["SMSSLUZBA_PASSWORD"] = "password", - ["SMSSLUZBA_BASE_URL"] = "http://example.com/", - ["API_KEYS"] = "eshop=key", - }))); + Assert.Equal(2, settings.Warnings.Count); } private static IConfiguration Build(Dictionary values) =>