diff --git a/.dockerignore b/.dockerignore index 306001a..b724ef9 100644 --- a/.dockerignore +++ b/.dockerignore @@ -1,3 +1,7 @@ -bin/ -obj/ +**/bin/ +**/obj/ .git/ +.vs/ +tests/ +documentation/ +.env diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..621b08d --- /dev/null +++ b/.editorconfig @@ -0,0 +1,21 @@ +root = true + +[*] +charset = utf-8 +insert_final_newline = true +trim_trailing_whitespace = true +indent_style = space +indent_size = 4 + +[*.{json,xml,csproj,props,slnx,yml,yaml}] +indent_size = 2 + +[*.md] +trim_trailing_whitespace = false +indent_size = 2 + +[*.cs] +csharp_style_namespace_declarations = file_scoped:warning +csharp_style_var_for_built_in_types = true:suggestion +csharp_style_var_when_type_is_apparent = true:suggestion +dotnet_sort_system_directives_first = true diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..1f91637 --- /dev/null +++ b/.env.example @@ -0,0 +1,15 @@ +# 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/.gitignore b/.gitignore new file mode 100644 index 0000000..aa00e94 --- /dev/null +++ b/.gitignore @@ -0,0 +1,7 @@ +bin/ +obj/ +.vs/ +.vscode/ +*.user +TestResults/ +.env diff --git a/Directory.Build.props b/Directory.Build.props new file mode 100644 index 0000000..70a0152 --- /dev/null +++ b/Directory.Build.props @@ -0,0 +1,13 @@ + + + net10.0 + enable + enable + true + + NU1901;NU1902;NU1903;NU1904 + true + latest + true + + diff --git a/Directory.Packages.props b/Directory.Packages.props new file mode 100644 index 0000000..3c0ba30 --- /dev/null +++ b/Directory.Packages.props @@ -0,0 +1,13 @@ + + + true + + + + + + + + + + diff --git a/Dockerfile b/Dockerfile index aa9256f..5b6feaf 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,11 +1,14 @@ -FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build +FROM mcr.microsoft.com/dotnet/sdk:10.0 AS build WORKDIR /src -COPY . . -RUN dotnet publish "SmsSluzba.csproj" -c Release -o /app/publish +COPY global.json Directory.Build.props Directory.Packages.props ./ +COPY src/SmsSluzba.Api/SmsSluzba.Api.csproj src/SmsSluzba.Api/packages.lock.json src/SmsSluzba.Api/ +RUN dotnet restore src/SmsSluzba.Api/SmsSluzba.Api.csproj --locked-mode +COPY src/ src/ +RUN dotnet publish src/SmsSluzba.Api/SmsSluzba.Api.csproj -c Release -o /app/publish --no-restore -FROM mcr.microsoft.com/dotnet/aspnet:8.0 +FROM mcr.microsoft.com/dotnet/aspnet:10.0 WORKDIR /app ENV ASPNETCORE_URLS=http://+:8080 EXPOSE 8080 COPY --from=build /app/publish . -ENTRYPOINT ["dotnet", "SmsSluzba.dll"] +ENTRYPOINT ["dotnet", "SmsSluzba.Api.dll"] diff --git a/Program.cs b/Program.cs deleted file mode 100644 index c4c41a4..0000000 --- a/Program.cs +++ /dev/null @@ -1,22 +0,0 @@ -var builder = WebApplication.CreateBuilder(args); -var app = builder.Build(); - -var rootPath = Environment.GetEnvironmentVariable("ROOT_PATH"); -if (!string.IsNullOrWhiteSpace(rootPath)) -{ - app.UsePathBase(rootPath); -} - -app.MapGet("/", () => Results.Json(new -{ - name = "SMS Služba", - service = "sms-sluzba", - status = "ok" -})); - -app.MapGet("/health", () => Results.Json(new -{ - status = "ok" -})); - -app.Run(); diff --git a/README.md b/README.md index 9d67e08..3e0a328 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,40 @@ # SMS Služba -.NET API služba vytvořená přes CSBot Services Portal. +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. + +## Spuštění + +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 | + +Bez povinných hodnot služba nenastartuje a vypíše, co chybí. ## Endpointy -- GET / -- GET /health +- `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 + +## Dokumentace + +- [documentation/integration.md](documentation/integration.md): návod pro napojení aplikací, závazný popis API +- [documentation/design.md](documentation/design.md): návrh a rozhodnutí +- [documentation/status.md](documentation/status.md): aktuální stav a záznam změn diff --git a/SmsSluzba.csproj b/SmsSluzba.csproj deleted file mode 100644 index 24ec0e8..0000000 --- a/SmsSluzba.csproj +++ /dev/null @@ -1,7 +0,0 @@ - - - net8.0 - enable - enable - - diff --git a/SmsSluzba.slnx b/SmsSluzba.slnx new file mode 100644 index 0000000..07effc3 --- /dev/null +++ b/SmsSluzba.slnx @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/documentation/design.md b/documentation/design.md new file mode 100644 index 0000000..12d8240 --- /dev/null +++ b/documentation/design.md @@ -0,0 +1,104 @@ +# Návrh: SMS služba (prostředník k SMS-Služba.cz) + +Stav: **návrh ke schválení**. + +## 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. + +Co služba **nedělá**: databáze, fronta, plánovač, webhooky, retry odeslání, vlastní historie. + +## 2. Jak funguje + +Každý požadavek se synchronně přeloží na jedno volání brány a výsledek se vrátí jako JSON. + +| Naše API | Volání brány | +|---|---| +| `POST /v1/messages` | `POST receiver` (XML `outgoing_message`) | +| `GET /v1/messages/{id}/delivery-report` | `GET sender?act=get_delivery_report&id=` | +| `GET /v1/events?types=&count=` | `GET sender?query_*=1&count=` (max 30) | +| `POST /v1/events/confirm` | `GET confirm?type=&id=` pro každou položku | +| `GET /v1/account/credit` | `GET info/credit` | +| `GET /health` | nic, brána se nevolá (aby health check nespotřebovával přihlášení) | +| `GET /docs` | Swagger UI s prefixem z `ROOT_PATH` | + +### Odeslání + +Požadavek `{ to, text, deliveryReport?, sendAt? }`. Odpověď `200 { id, recipient, sendAt, parts, price, credit }`, kde `id` je id zprávy u brány (řetězec typu `420777123456-20080404153039854`). Podle něj si aplikace později stáhne doručenku. Přesné formáty požadavků, odpovědí a chybových kódů jsou v [integration.md](integration.md), ta je pro implementaci závazná. + +Před voláním se kontroluje jen to, co brána neohlásí sama: neprázdný text a délka do 459 znaků (brána delší text potichu ořízne). Číslo kontroluje brána (`400;1`). `sendAt` se převede na formát `YYYYMMDDHHMMSS` v čase Europe/Prague. + +Odeslání se **nikdy neopakuje automaticky**, protože opakování by mohlo poslat SMS dvakrát. Při timeoutu služba vrátí `504` s upozorněním, že stav je neznámý. + +### Události (příchozí SMS, odpovědi, doručenky) + +`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. + +## 3. Chyby + +Kódy brány chodí v těle jako `....`. Služba je převede na `ProblemDetails` (RFC 7807) s původním kódem v poli `providerCode`: + +| Kód brány | Naše odpověď | +|---|---| +| 400;1 neplatné číslo | 400 | +| 400;2 chybí text | 400 | +| 400 neznámá akce (a jiné 400;x) | 400 `provider_rejected` | +| 401 špatné přihlášení, 401;1 účet blokován | 503 a blokace volání (viz níže) | +| 402 nedostatek kreditu | 402 | +| 503 chyba brány, síťová chyba | 502 | +| timeout | 504 | + +**Blokace při 401:** opakované špatné přihlášení zablokuje účet. Po první odpovědi `401` nebo `401;1` služba přestane bránu volat a všechny požadavky vrací `503`, dokud se neopraví heslo a container nerestartuje. Stav je jen v paměti, restart je zároveň reset. + +## 4. Bezpečnost + +- Přihlašovací údaje k bráně jen z proměnných prostředí (AppFactory secrets). +- V logu se `password` v URL maskuje (`password=***`), text SMS se neloguje, čísla se maskují (`+420724***234`). +- Každá volající aplikace má vlastní klíč v hlavičce `X-Api-Key`. Klíče jsou v proměnné prostředí `API_KEYS` jako `nazev=klic`, porovnávají se v konstantním čase a v logu se objeví jen název aplikace. Služba je dostupná z veřejné URL, takže bez klíče by mohl SMS posílat kdokoli. + +## 5. Konfigurace + +| Proměnná | Povinná | Výchozí | +|---|---|---| +| `ROOT_PATH` | ne | nastavuje AppFactory | +| `SMSSLUZBA_LOGIN` | ano | | +| `SMSSLUZBA_PASSWORD` | ano | | +| `SMSSLUZBA_BASE_URL` | ne | `https://smsgateapi.sms-sluzba.cz/apixml30/` | +| `SMSSLUZBA_TIMEOUT_SECONDS` | ne | `30` | +| `API_KEYS` | ano | klíče aplikací, např. `eshop=klic1;cms=klic2` | + +Bez povinných hodnot služba nenastartuje a vypíše, co chybí (bez hodnot). + +## 6. Struktura + +Malá služba, takže jeden projekt se složkami podle vrstev: + +```text +SmsSluzba.slnx, global.json, Directory.Build.props, Directory.Packages.props, .editorconfig +Dockerfile (.NET 10, port 8080 beze změny) +.env.example, README.md, AGENTS.md +documentation/ +src/SmsSluzba.Api/ + Program.cs skládání služeb a middleware + Config/ čtení a kontrola proměnných prostředí + Auth/ kontrola X-Api-Key, název aplikace podle klíče + Contracts/ JSON požadavky a odpovědi (jediné místo, kde typy API existují) + Endpoints/ mapování /v1, /health, převod chyb brány na odpovědi + Gateway/ HTTP klient brány, tvorba a čtení XML, kódy, časy, blokace 401, logování s maskou hesla + Logging/ maskování hesla a čísel + Messages/ výpočet délky SMS + OpenApi/ dokument OpenAPI (server z ROOT_PATH, schéma X-Api-Key) + Problems/ kódy chyb a ProblemDetails +tests/SmsSluzba.Api.Tests/ XML, kódy, časy, konfigurace, endpointy přes WebApplicationFactory + s podvrženým HTTP handlerem místo brány +``` + +`/health` vrací 200 i při blokaci přihlášení (v těle `gateway: "blocked"`). Kdyby vracel chybu, AppFactory by container restartoval a každý restart by znovu zkusil špatné heslo. + +## 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? +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 new file mode 100644 index 0000000..ff99441 --- /dev/null +++ b/documentation/integration.md @@ -0,0 +1,301 @@ +# Napojení na SMS službu + +Návod pro vývojáře a AI asistenty, kteří napojují svou aplikaci na interní SMS službu. Obsahuje vše potřebné, zdrojový kód služby není třeba číst. + +## 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. + +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. + +## Konfigurace ve vaší aplikaci + +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= +``` + +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. + +Klíč přiděluje správce SMS služby, každá aplikace má vlastní. + +## Autentizace + +Každý požadavek na `/v1/...` musí mít hlavičku: + +```text +X-Api-Key: +``` + +Chybějící nebo neplatný klíč vrací `401` s kódem `unauthorized`. + +## 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. +- 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. + +## Endpointy + +### Odeslání SMS + +```http +POST {SMS_SERVICE_URL}/v1/messages +X-Api-Key: ... +Content-Type: application/json + +{ + "to": "+420603123456", + "text": "Vase objednavka 1234 byla odeslana.", + "deliveryReport": true, + "sendAt": "2026-10-21T08:00:00+02:00" +} +``` + +| Pole | Povinné | Popis | +|---|---|---| +| `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. | +| `sendAt` | ne | Odložené odeslání. Bez uvedení se zpráva odešle hned. | + +Odpověď `200`: + +```json +{ + "id": "420603123456-20261020120000123", + "recipient": "+420603123456", + "sendAt": "2026-10-20T10:00:00Z", + "parts": 1, + "price": 0.68, + "credit": 453.49 +} +``` + +Uložte si `id`, slouží k dohledání doručenky. `price` je cena zprávy, `credit` je zbývající kredit po odeslání. Obojí je v Kč bez DPH. Kromě `id` může brána kterékoli pole vynechat, pak je v odpovědi `null`. + +Pravidla pro text: + +- Zprávy se posílají v 7bitové sadě GSM. Brána diakritiku převádí sama (`č` na `c`), ale pro jistotu ji neposílejte. +- Jedna SMS má 160 znaků. Delší text se dělí na části po 153 znacích, nejvýš 3 části (459 znaků). Každá část se platí. +- Znaky `€ [ ] { } \ ^ ~ |` zabírají 2 pozice. +- Text delší než 459 znaků služba odmítne (`400`, `text_too_long`). + +### Doručenka ke zprávě + +```http +GET {SMS_SERVICE_URL}/v1/messages/{id}/delivery-report +X-Api-Key: ... +``` + +`{id}` je `id` z odpovědi na odeslání, URL-enkódované. Odpověď `200`: + +```json +{ + "messageId": "420603123456-20261020120000123", + "status": 0, + "description": "Doručeno", + "deliveredAt": "2026-10-20T10:00:23Z" +} +``` + +`status` je číselný stav od brány (nebo `null`, když brána pošle něco jiného než číslo): `0` znamená doručeno. Ostatní hodnoty brána nedokumentuje, takže je berte jako "nedoručeno nebo zatím nedoručeno" a pro člověka zobrazte `description`. Když brána doručenku ještě nemá, služba vrátí `404` s kódem `delivery_report_not_found`. + +### Události: příchozí SMS, odpovědi, doručenky + +```http +GET {SMS_SERVICE_URL}/v1/events?types=incoming,deliveryReport&count=30 +X-Api-Key: ... +``` + +| Parametr | Výchozí | Popis | +|---|---|---| +| `types` | `incoming,deliveryReport` | Čárkou oddělený výběr z `incoming` (příchozí SMS a odpovědi), `deliveryReport`, `outgoing` (odeslané zprávy, jen pro synchronizaci). | +| `count` | `30` | Kolik událostí vrátit, 1 až 30. | + +Odpověď `200`: + +```json +{ + "events": [ + { + "type": "incoming", + "id": "420777123456-20261020072509664", + "from": "+420777123456", + "to": "5517", + "text": "Dobry den, mam dotaz", + "sentAt": "2026-10-20T05:25:42Z" + }, + { + "type": "answer", + "id": "420777123456-20261020072509665", + "from": "+420777123456", + "to": "5517", + "text": "ANO", + "sentAt": "2026-10-20T05:26:10Z", + "inReplyTo": "420777123456-20261020053039854" + }, + { + "type": "deliveryReport", + "id": "420603123456-20261020120000123", + "messageId": "420603123456-20261020120000123", + "status": 0, + "description": "Doručeno", + "deliveredAt": "2026-10-20T10:00:23Z" + }, + { + "type": "outgoing", + "id": "420603123456-20261020120000124", + "to": "+420603123456", + "text": "Vase objednavka 1235 byla odeslana.", + "sendAt": "2026-10-20T10:01:00Z", + "source": "api" + } + ] +} +``` + +- `answer` je odpověď na vaši dřívější zprávu, `inReplyTo` je `id` té zprávy. +- U `deliveryReport` je `messageId` id odeslané zprávy. +- U `outgoing` je `source` buď `api`, nebo `portal`. +- Prázdný seznam znamená, že nic nového není. + +### Potvrzení převzetí událostí + +Brána vrací tutéž událost znovu, dokud ji nepotvrdíte. Potvrzujte **až po uložení nebo zpracování** u vás. + +```http +POST {SMS_SERVICE_URL}/v1/events/confirm +X-Api-Key: ... +Content-Type: application/json + +{ + "events": [ + { "type": "incoming", "id": "420777123456-20261020072509664" }, + { "type": "deliveryReport", "id": "420603123456-20261020120000123" } + ] +} +``` + +Hodnoty `type` jsou stejné jako v `GET /v1/events`. Najednou lze potvrdit nejvýš 30 událostí. Neznámý `type` nebo prázdné `id` vrátí `400` a nepotvrdí se nic. Odpověď `200`: + +```json +{ + "confirmed": [ + { "type": "incoming", "id": "420777123456-20261020072509664" } + ], + "failed": [ + { "type": "deliveryReport", "id": "420603123456-20261020120000123", "code": "provider_unavailable" } + ] +} +``` + +Položky z `failed` zkuste potvrdit znovu příště. Potvrzení se dá bezpečně opakovat. + +### Kredit + +```http +GET {SMS_SERVICE_URL}/v1/account/credit +X-Api-Key: ... +``` + +Odpověď `200`, částky v Kč bez DPH: + +```json +{ + "credit": 454.17, + "priceCzSms": 0.68, + "priceSkSms": 0.78, + "priceOtherSms": 1.80 +} +``` + +### 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`). + +## Chyby + +Chyby mají formát RFC 7807 (`Content-Type: application/problem+json`): + +```json +{ + "title": "Neplatné telefonní číslo", + "status": 400, + "code": "invalid_recipient", + "detail": "Chybne telefonni cislo 77716085", + "providerCode": "400;1", + "traceId": "00-..." +} +``` + +Rozhodujte se podle `code`, ne podle textu. Při hlášení problému správci pošlete `traceId`. + +| HTTP | `code` | Význam | Co má aplikace dělat | +|---|---|---|---| +| 400 | `validation_failed` | Chybí nebo je špatně pole požadavku. | Opravit požadavek, neopakovat. | +| 400 | `invalid_recipient` | Neplatné číslo. | Neopakovat, nahlásit uživateli. | +| 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. | +| 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. | +| 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 `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`. +- 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. + +## Příklady (curl) + +```bash +curl -X POST "$SMS_SERVICE_URL/v1/messages" \ + -H "X-Api-Key: $SMS_SERVICE_API_KEY" \ + -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/events?types=incoming,deliveryReport&count=30" \ + -H "X-Api-Key: $SMS_SERVICE_API_KEY" + +curl -X POST "$SMS_SERVICE_URL/v1/events/confirm" \ + -H "X-Api-Key: $SMS_SERVICE_API_KEY" \ + -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" +``` + +## 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í. +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`. +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`. diff --git a/documentation/status.md b/documentation/status.md new file mode 100644 index 0000000..026320e --- /dev/null +++ b/documentation/status.md @@ -0,0 +1,35 @@ +# Stav projektu + +## 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`). + +## 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. + +## 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. +- `Endpoints/`: `/v1` endpointy, `GatewayProblems.cs` převod chyb brány na kódy API. +- `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`). + +## Známé odchylky od zásad + +- Jeden projekt místo vrstev Domain / Application / Infrastructure / Api. Služba je malá a nemá doménovou logiku, vrstvy jsou jako složky (zásady to u malé služby připouštějí). +- Logy jsou anglicky, texty pro volající (chyby API, Swagger) česky. + +## Záznam změn + +- 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/global.json b/global.json new file mode 100644 index 0000000..512142d --- /dev/null +++ b/global.json @@ -0,0 +1,6 @@ +{ + "sdk": { + "version": "10.0.100", + "rollForward": "latestFeature" + } +} diff --git a/src/SmsSluzba.Api/Auth/ApiClientRegistry.cs b/src/SmsSluzba.Api/Auth/ApiClientRegistry.cs new file mode 100644 index 0000000..63fd819 --- /dev/null +++ b/src/SmsSluzba.Api/Auth/ApiClientRegistry.cs @@ -0,0 +1,42 @@ +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 new file mode 100644 index 0000000..7f2f795 --- /dev/null +++ b/src/SmsSluzba.Api/Auth/ApiKeyFilter.cs @@ -0,0 +1,21 @@ +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/Config/AppSettings.cs b/src/SmsSluzba.Api/Config/AppSettings.cs new file mode 100644 index 0000000..b7ec1d7 --- /dev/null +++ b/src/SmsSluzba.Api/Config/AppSettings.cs @@ -0,0 +1,7 @@ +namespace SmsSluzba.Api.Config; + +internal sealed record AppSettings(string? RootPath, GatewaySettings Gateway, IReadOnlyList ApiClients); + +internal sealed record GatewaySettings(Uri BaseUrl, string Login, string Password, TimeSpan Timeout); + +internal sealed record ApiClient(string Name, string Key); diff --git a/src/SmsSluzba.Api/Config/AppSettingsLoader.cs b/src/SmsSluzba.Api/Config/AppSettingsLoader.cs new file mode 100644 index 0000000..f631e76 --- /dev/null +++ b/src/SmsSluzba.Api/Config/AppSettingsLoader.cs @@ -0,0 +1,139 @@ +using System.Globalization; + +namespace SmsSluzba.Api.Config; + +/// Reads and validates all environment configuration in one place. +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/"; + + // The integration guide tells callers to wait at least 35 s, so the gateway wait must stay below that. + private const int DefaultTimeoutSeconds = 30; + + 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); + } + + private static string Required(IConfiguration configuration, string key, List errors) + { + var value = configuration[key]; + if (string.IsNullOrWhiteSpace(value)) + { + errors.Add($"Chybí {key}."); + return string.Empty; + } + + return value.Trim(); + } + + private static Uri ParseBaseUrl(string? value, List errors) + { + var raw = string.IsNullOrWhiteSpace(value) ? DefaultBaseUrl : value.Trim(); + if (!raw.EndsWith('/')) + { + // Relative gateway paths are resolved against this URL, which requires a trailing slash. + raw += "/"; + } + + if (!Uri.TryCreate(raw, UriKind.Absolute, out var uri) || uri.Scheme != Uri.UriSchemeHttps) + { + errors.Add($"{BaseUrlKey} musí být absolutní https adresa."); + return new Uri(DefaultBaseUrl); + } + + return uri; + } + + private static TimeSpan ParseTimeout(string? value, List errors) + { + if (string.IsNullOrWhiteSpace(value)) + { + return TimeSpan.FromSeconds(DefaultTimeoutSeconds); + } + + if (!int.TryParse(value.Trim(), NumberStyles.None, CultureInfo.InvariantCulture, out var seconds) || seconds < 1) + { + errors.Add($"{TimeoutKey} musí být kladné celé číslo."); + 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)) + { + return null; + } + + var path = "/" + value.Trim().Trim('/'); + return path == "/" ? null : path; + } +} diff --git a/src/SmsSluzba.Api/Contracts/AccountContracts.cs b/src/SmsSluzba.Api/Contracts/AccountContracts.cs new file mode 100644 index 0000000..58f7b43 --- /dev/null +++ b/src/SmsSluzba.Api/Contracts/AccountContracts.cs @@ -0,0 +1,5 @@ +namespace SmsSluzba.Api.Contracts; + +internal sealed record CreditResponse(decimal Credit, decimal PriceCzSms, decimal PriceSkSms, decimal PriceOtherSms); + +internal sealed record HealthResponse(string Status, string Gateway); diff --git a/src/SmsSluzba.Api/Contracts/EventContracts.cs b/src/SmsSluzba.Api/Contracts/EventContracts.cs new file mode 100644 index 0000000..80c5454 --- /dev/null +++ b/src/SmsSluzba.Api/Contracts/EventContracts.cs @@ -0,0 +1,51 @@ +using System.Text.Json.Serialization; + +namespace SmsSluzba.Api.Contracts; + +internal static class EventTypes +{ + public const string Incoming = "incoming"; + public const string Answer = "answer"; + public const string DeliveryReport = "deliveryReport"; + public const string Outgoing = "outgoing"; +} + +[JsonPolymorphic(TypeDiscriminatorPropertyName = "type")] +[JsonDerivedType(typeof(IncomingSmsEvent), EventTypes.Incoming)] +[JsonDerivedType(typeof(AnswerSmsEvent), EventTypes.Answer)] +[JsonDerivedType(typeof(DeliveryReportSmsEvent), EventTypes.DeliveryReport)] +[JsonDerivedType(typeof(OutgoingSmsEvent), EventTypes.Outgoing)] +internal abstract record SmsEvent(string Id); + +internal sealed record IncomingSmsEvent(string Id, string? From, string? To, string? Text, DateTimeOffset? SentAt) + : SmsEvent(Id); + +internal sealed record AnswerSmsEvent( + string Id, + string? From, + string? To, + string? Text, + DateTimeOffset? SentAt, + string? InReplyTo) : SmsEvent(Id); + +internal sealed record DeliveryReportSmsEvent( + string Id, + string MessageId, + int? Status, + string? Description, + DateTimeOffset? DeliveredAt) : SmsEvent(Id); + +internal sealed record OutgoingSmsEvent(string Id, string? To, string? Text, DateTimeOffset? SendAt, string Source) + : SmsEvent(Id); + +internal sealed record EventsResponse(IReadOnlyList Events); + +internal sealed record ConfirmEventsRequest(IReadOnlyList? Events); + +internal sealed record EventReference(string? Type, string? Id); + +internal sealed record ConfirmedEvent(string Type, string Id); + +internal sealed record FailedEvent(string Type, string Id, string Code); + +internal sealed record ConfirmEventsResponse(IReadOnlyList Confirmed, IReadOnlyList Failed); diff --git a/src/SmsSluzba.Api/Contracts/MessageContracts.cs b/src/SmsSluzba.Api/Contracts/MessageContracts.cs new file mode 100644 index 0000000..31b90f1 --- /dev/null +++ b/src/SmsSluzba.Api/Contracts/MessageContracts.cs @@ -0,0 +1,17 @@ +namespace SmsSluzba.Api.Contracts; + +internal sealed record SendMessageRequest(string? To, string? Text, bool? DeliveryReport, DateTimeOffset? SendAt); + +internal sealed record SendMessageResponse( + string Id, + string? Recipient, + DateTimeOffset? SendAt, + int? Parts, + decimal? Price, + decimal? Credit); + +internal sealed record DeliveryReportResponse( + string MessageId, + int? Status, + string? Description, + DateTimeOffset? DeliveredAt); diff --git a/src/SmsSluzba.Api/Endpoints/AccountEndpoints.cs b/src/SmsSluzba.Api/Endpoints/AccountEndpoints.cs new file mode 100644 index 0000000..b7f4cd0 --- /dev/null +++ b/src/SmsSluzba.Api/Endpoints/AccountEndpoints.cs @@ -0,0 +1,25 @@ +using SmsSluzba.Api.Contracts; +using SmsSluzba.Api.Gateway; + +namespace SmsSluzba.Api.Endpoints; + +internal static class AccountEndpoints +{ + public static RouteGroupBuilder MapAccountEndpoints(this RouteGroupBuilder group) + { + group.MapGet("/account/credit", GetCreditAsync) + .WithName("GetCredit") + .WithTags("Účet") + .WithSummary("Kredit a ceny SMS (Kč bez DPH)") + .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))); +} diff --git a/src/SmsSluzba.Api/Endpoints/EventEndpoints.cs b/src/SmsSluzba.Api/Endpoints/EventEndpoints.cs new file mode 100644 index 0000000..07d6d1b --- /dev/null +++ b/src/SmsSluzba.Api/Endpoints/EventEndpoints.cs @@ -0,0 +1,101 @@ +using SmsSluzba.Api.Contracts; +using SmsSluzba.Api.Gateway; +using SmsSluzba.Api.Problems; + +namespace SmsSluzba.Api.Endpoints; + +internal static class EventEndpoints +{ + private const string Tag = "Události"; + + // The gateway returns at most 30 messages per call; confirmations use the same batch size. + private const int MaxBatchSize = 30; + + public static RouteGroupBuilder MapEventEndpoints(this RouteGroupBuilder group) + { + group.MapGet("/events", GetEventsAsync) + .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.") + .Produces() + .ProducesProblem(StatusCodes.Status400BadRequest) + .ProducesProblem(StatusCodes.Status401Unauthorized) + .ProducesProblem(StatusCodes.Status502BadGateway) + .ProducesProblem(StatusCodes.Status503ServiceUnavailable) + .ProducesProblem(StatusCodes.Status504GatewayTimeout); + + group.MapPost("/events/confirm", ConfirmAsync) + .WithName("ConfirmEvents") + .WithTags(Tag) + .WithSummary("Potvrdí převzetí událostí") + .Produces() + .ProducesProblem(StatusCodes.Status400BadRequest) + .ProducesProblem(StatusCodes.Status401Unauthorized); + + return group; + } + + private static async Task GetEventsAsync(string? types, int? count, SmsGatewayClient gateway, CancellationToken ct) + { + var query = GatewayEventQuery.Parse(types); + if (query is null) + { + return ApiProblems.Validation( + $"Neplatný parametr 'types'. Povolené hodnoty: {EventTypes.Incoming}, {EventTypes.DeliveryReport}, {EventTypes.Outgoing}."); + } + + var size = count ?? MaxBatchSize; + if (size is < 1 or > MaxBatchSize) + { + return ApiProblems.Validation($"Parametr 'count' musí být 1 až {MaxBatchSize}."); + } + + return await GatewayProblems.RunAsync(async () => + Results.Ok(new EventsResponse(await gateway.GetEventsAsync(query, size, ct)))); + } + + private static async Task ConfirmAsync(ConfirmEventsRequest request, SmsGatewayClient gateway, CancellationToken ct) + { + if (request.Events is not { Count: > 0 } events) + { + return ApiProblems.Validation("Seznam 'events' je prázdný."); + } + + if (events.Count > MaxBatchSize) + { + return ApiProblems.Validation($"Najednou lze potvrdit nejvýš {MaxBatchSize} událostí."); + } + + var items = new List<(string Type, string Id, string GatewayType)>(events.Count); + foreach (var item in events) + { + if (item.Type is null + || GatewayEventQuery.ConfirmTypeFor(item.Type) is not { } gatewayType + || string.IsNullOrWhiteSpace(item.Id)) + { + return ApiProblems.Validation($"Neplatná položka: type '{item.Type}', id '{item.Id}'."); + } + + items.Add((item.Type, item.Id.Trim(), gatewayType)); + } + + var confirmed = new List(); + var failed = new List(); + foreach (var (type, id, gatewayType) in items) + { + try + { + await gateway.ConfirmAsync(gatewayType, id, ct); + confirmed.Add(new ConfirmedEvent(type, id)); + } + catch (GatewayException ex) + { + // Already logged by SmsGatewayClient; the caller retries the failed items later. + failed.Add(new FailedEvent(type, id, GatewayProblems.ErrorFor(ex.Kind).Code)); + } + } + + return Results.Ok(new ConfirmEventsResponse(confirmed, failed)); + } +} diff --git a/src/SmsSluzba.Api/Endpoints/GatewayProblems.cs b/src/SmsSluzba.Api/Endpoints/GatewayProblems.cs new file mode 100644 index 0000000..b24f0e0 --- /dev/null +++ b/src/SmsSluzba.Api/Endpoints/GatewayProblems.cs @@ -0,0 +1,41 @@ +using SmsSluzba.Api.Gateway; +using SmsSluzba.Api.Problems; + +namespace SmsSluzba.Api.Endpoints; + +internal static class GatewayProblems +{ + private const string UnknownStateDetail = "Stav není známý, brána mohla požadavek přijmout. Odeslání SMS neopakujte automaticky."; + + public static ApiError ErrorFor(GatewayErrorKind kind) => kind switch + { + GatewayErrorKind.InvalidRecipient => ApiErrors.InvalidRecipient, + GatewayErrorKind.MissingText => ApiErrors.MissingText, + GatewayErrorKind.Rejected => ApiErrors.ProviderRejected, + GatewayErrorKind.AuthFailed or GatewayErrorKind.AuthBlocked => ApiErrors.ProviderAuthBlocked, + GatewayErrorKind.InsufficientCredit => ApiErrors.InsufficientCredit, + GatewayErrorKind.Timeout => ApiErrors.ProviderTimeout, + _ => ApiErrors.ProviderUnavailable, + }; + + public static IResult ToResult(GatewayException ex) + { + var error = ErrorFor(ex.Kind); + var detail = ex.ProviderMessage ?? (error.Status is 502 or 504 ? UnknownStateDetail : null); + return ApiProblems.Result(error, detail, ex.ProviderCode); + } + + /// Runs a gateway call and turns a gateway failure into a problem response. + public static async Task RunAsync(Func> call) + { + try + { + return await call(); + } + catch (GatewayException ex) + { + // Already logged by SmsGatewayClient. + return ToResult(ex); + } + } +} diff --git a/src/SmsSluzba.Api/Endpoints/MessageEndpoints.cs b/src/SmsSluzba.Api/Endpoints/MessageEndpoints.cs new file mode 100644 index 0000000..7f850de --- /dev/null +++ b/src/SmsSluzba.Api/Endpoints/MessageEndpoints.cs @@ -0,0 +1,98 @@ +using SmsSluzba.Api.Auth; +using SmsSluzba.Api.Contracts; +using SmsSluzba.Api.Gateway; +using SmsSluzba.Api.Logging; +using SmsSluzba.Api.Messages; +using SmsSluzba.Api.Problems; + +namespace SmsSluzba.Api.Endpoints; + +internal static class MessageEndpoints +{ + private const string Tag = "Zprávy"; + private const string LoggerCategory = "SmsSluzba.Api.Messages"; + + public static RouteGroupBuilder MapMessageEndpoints(this RouteGroupBuilder group) + { + group.MapPost("/messages", SendAsync) + .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.") + .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) + .WithName("GetDeliveryReport") + .WithTags(Tag) + .WithSummary("Doručenka k odeslané zprávě") + .Produces() + .ProducesProblem(StatusCodes.Status401Unauthorized) + .ProducesProblem(StatusCodes.Status404NotFound) + .ProducesProblem(StatusCodes.Status502BadGateway) + .ProducesProblem(StatusCodes.Status503ServiceUnavailable) + .ProducesProblem(StatusCodes.Status504GatewayTimeout); + + return group; + } + + private static async Task SendAsync( + SendMessageRequest request, + SmsGatewayClient gateway, + HttpContext httpContext, + ILoggerFactory loggerFactory, + CancellationToken ct) + { + if (string.IsNullOrWhiteSpace(request.To)) + { + return ApiProblems.Validation("Pole 'to' je povinné."); + } + + if (string.IsNullOrWhiteSpace(request.Text)) + { + return ApiProblems.Result(ApiErrors.MissingText, "Pole 'text' je povinné."); + } + + var length = SmsText.CountLength(request.Text); + if (length > SmsText.MaxLength) + { + return ApiProblems.Result(ApiErrors.TextTooLong, $"Text má {length} znaků, maximum je {SmsText.MaxLength}."); + } + + 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); + logger.LogInformation( + "SMS {MessageId} for {Recipient} accepted by gateway, client {Client}, parts {Parts}, price {Price}", + result.Id, + LogMask.Phone(recipient), + client, + result.Parts, + result.Price); + return Results.Ok(result); + }); + } + + private static async Task GetDeliveryReportAsync(string id, SmsGatewayClient gateway, CancellationToken ct) + { + if (string.IsNullOrWhiteSpace(id)) + { + return ApiProblems.Validation("Chybí id zprávy."); + } + + return await GatewayProblems.RunAsync(async () => + { + var report = await gateway.GetDeliveryReportAsync(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 new file mode 100644 index 0000000..76c7489 --- /dev/null +++ b/src/SmsSluzba.Api/Endpoints/SystemEndpoints.cs @@ -0,0 +1,32 @@ +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 + { + name = "SMS Služba", + service = "sms-sluzba", + status = "ok", + })) + .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))) + .WithName("Health") + .WithTags("Služba") + .WithSummary("Stav služby, nevolá SMS bránu") + .Produces(); + + return app; + } +} diff --git a/src/SmsSluzba.Api/Gateway/GatewayAuthGuard.cs b/src/SmsSluzba.Api/Gateway/GatewayAuthGuard.cs new file mode 100644 index 0000000..fed54cd --- /dev/null +++ b/src/SmsSluzba.Api/Gateway/GatewayAuthGuard.cs @@ -0,0 +1,32 @@ +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. +/// +internal sealed class GatewayAuthGuard(ILogger logger) +{ + private int _blocked; + private string? _providerCode; + + public bool IsBlocked => Volatile.Read(ref _blocked) == 1; + + public void ThrowIfBlocked() + { + if (IsBlocked) + { + throw new GatewayException(GatewayErrorKind.AuthBlocked, _providerCode, "Volání SMS brány jsou zastavená po chybě přihlášení."); + } + } + + public void Block(string? providerCode) + { + _providerCode = providerCode; + if (Interlocked.Exchange(ref _blocked, 1) == 0) + { + logger.LogCritical( + "SMS gateway rejected the credentials (provider code {ProviderCode}). All gateway calls are stopped until the service restarts with corrected credentials.", + providerCode); + } + } +} diff --git a/src/SmsSluzba.Api/Gateway/GatewayEventQuery.cs b/src/SmsSluzba.Api/Gateway/GatewayEventQuery.cs new file mode 100644 index 0000000..2007e37 --- /dev/null +++ b/src/SmsSluzba.Api/Gateway/GatewayEventQuery.cs @@ -0,0 +1,51 @@ +using SmsSluzba.Api.Contracts; + +namespace SmsSluzba.Api.Gateway; + +/// Which event kinds to download from the gateway sender endpoint. +internal sealed record GatewayEventQuery(bool Incoming, bool DeliveryReports, bool Outgoing) +{ + public static readonly GatewayEventQuery Default = new(Incoming: true, DeliveryReports: true, Outgoing: false); + + /// Null when the list contains an unknown type. + public static GatewayEventQuery? Parse(string? types) + { + if (string.IsNullOrWhiteSpace(types)) + { + return Default; + } + + var incoming = false; + var deliveryReports = false; + var outgoing = false; + foreach (var type in types.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)) + { + switch (type) + { + case EventTypes.Incoming: + case EventTypes.Answer: + incoming = true; + break; + case EventTypes.DeliveryReport: + deliveryReports = true; + break; + case EventTypes.Outgoing: + outgoing = true; + break; + default: + return null; + } + } + + return incoming || deliveryReports || outgoing ? new GatewayEventQuery(incoming, deliveryReports, outgoing) : null; + } + + /// Gateway confirm type for an API event type, or null for an unknown type. + public static string? ConfirmTypeFor(string apiType) => apiType switch + { + EventTypes.Incoming or EventTypes.Answer => "incoming_message", + EventTypes.DeliveryReport => "delivery_report", + EventTypes.Outgoing => "outgoing_message", + _ => null, + }; +} diff --git a/src/SmsSluzba.Api/Gateway/GatewayException.cs b/src/SmsSluzba.Api/Gateway/GatewayException.cs new file mode 100644 index 0000000..8a8c712 --- /dev/null +++ b/src/SmsSluzba.Api/Gateway/GatewayException.cs @@ -0,0 +1,40 @@ +namespace SmsSluzba.Api.Gateway; + +internal enum GatewayErrorKind +{ + InvalidRecipient, + MissingText, + Rejected, + AuthFailed, + AuthBlocked, + InsufficientCredit, + Unavailable, + InvalidResponse, + Timeout, +} + +/// +/// Gateway call failure. The exception message never contains the provider message, because that +/// message can include the recipient number and the exception ends up in logs. +/// +internal sealed class GatewayException : Exception +{ + public GatewayException(GatewayErrorKind kind, string? providerCode = null, string? providerMessage = null, Exception? inner = null) + : base($"SMS gateway error: {kind}", inner) + { + Kind = kind; + ProviderCode = providerCode; + ProviderMessage = providerMessage; + } + + public GatewayException(GatewayErrorKind kind, Exception inner) + : this(kind, null, null, inner) + { + } + + public GatewayErrorKind Kind { get; } + + public string? ProviderCode { get; } + + public string? ProviderMessage { get; } +} diff --git a/src/SmsSluzba.Api/Gateway/GatewayResponse.cs b/src/SmsSluzba.Api/Gateway/GatewayResponse.cs new file mode 100644 index 0000000..25ccde8 --- /dev/null +++ b/src/SmsSluzba.Api/Gateway/GatewayResponse.cs @@ -0,0 +1,37 @@ +using System.Globalization; +using System.Net; +using System.Xml.Linq; + +namespace SmsSluzba.Api.Gateway; + +internal static class GatewayResponse +{ + /// + /// Turns a raw gateway response into an XML document or a . + /// The status code can come in the body, in the HTTP status, or in both; the body wins because it is more specific. + /// + /// The parsed document, or null for a successful response without an XML body. + public static XDocument? Interpret(HttpStatusCode httpStatus, string body) + { + var document = string.IsNullOrWhiteSpace(body) ? null : GatewayXml.TryParse(body); + + if (document?.Root is { Name.LocalName: "status" } status) + { + var code = status.Element("id")?.Value.Trim() ?? string.Empty; + if (GatewayStatus.Classify(code) is { } kind) + { + throw new GatewayException(kind, code, status.Element("message")?.Value.Trim()); + } + } + + var numericStatus = (int)httpStatus; + if (numericStatus is < 200 or >= 300) + { + throw new GatewayException( + GatewayStatus.ClassifyHttp(httpStatus), + numericStatus.ToString(CultureInfo.InvariantCulture)); + } + + return document; + } +} diff --git a/src/SmsSluzba.Api/Gateway/GatewayStatus.cs b/src/SmsSluzba.Api/Gateway/GatewayStatus.cs new file mode 100644 index 0000000..3ed92c2 --- /dev/null +++ b/src/SmsSluzba.Api/Gateway/GatewayStatus.cs @@ -0,0 +1,30 @@ +using System.Net; + +namespace SmsSluzba.Api.Gateway; + +/// Status codes from chapter 4 of the SMS Gate API XML 3.0 specification. +internal static class GatewayStatus +{ + public const string Ok = "200"; + + /// Null when the code means success. + public static GatewayErrorKind? Classify(string code) => code switch + { + Ok => null, + "400;1" => GatewayErrorKind.InvalidRecipient, + "400;2" => GatewayErrorKind.MissingText, + "401" or "401;1" => GatewayErrorKind.AuthFailed, + "402" => GatewayErrorKind.InsufficientCredit, + "503" => GatewayErrorKind.Unavailable, + _ when code.StartsWith("400", StringComparison.Ordinal) => GatewayErrorKind.Rejected, + _ => GatewayErrorKind.Unavailable, + }; + + public static GatewayErrorKind ClassifyHttp(HttpStatusCode status) => status switch + { + HttpStatusCode.BadRequest => GatewayErrorKind.Rejected, + HttpStatusCode.Unauthorized => GatewayErrorKind.AuthFailed, + HttpStatusCode.PaymentRequired => GatewayErrorKind.InsufficientCredit, + _ => GatewayErrorKind.Unavailable, + }; +} diff --git a/src/SmsSluzba.Api/Gateway/GatewayTime.cs b/src/SmsSluzba.Api/Gateway/GatewayTime.cs new file mode 100644 index 0000000..6a0f55e --- /dev/null +++ b/src/SmsSluzba.Api/Gateway/GatewayTime.cs @@ -0,0 +1,27 @@ +using System.Globalization; + +namespace SmsSluzba.Api.Gateway; + +internal static class GatewayTime +{ + private const string Format = "yyyyMMddHHmmss"; + + // The specification does not name a time zone. The gateway is a Czech service, so Prague local time + // is assumed (open question in documentation/design.md). + private static readonly TimeZoneInfo GatewayZone = TimeZoneInfo.FindSystemTimeZoneById("Europe/Prague"); + + public static string ToGateway(DateTimeOffset value) => + TimeZoneInfo.ConvertTime(value, GatewayZone).ToString(Format, CultureInfo.InvariantCulture); + + /// UTC time, or null when the value is missing or not in the gateway format. + public static DateTimeOffset? FromGateway(string? value) + { + if (string.IsNullOrWhiteSpace(value) + || !DateTime.TryParseExact(value.Trim(), Format, CultureInfo.InvariantCulture, DateTimeStyles.None, out var local)) + { + return null; + } + + return new DateTimeOffset(local, GatewayZone.GetUtcOffset(local)).ToUniversalTime(); + } +} diff --git a/src/SmsSluzba.Api/Gateway/GatewayXml.cs b/src/SmsSluzba.Api/Gateway/GatewayXml.cs new file mode 100644 index 0000000..b5cdeb4 --- /dev/null +++ b/src/SmsSluzba.Api/Gateway/GatewayXml.cs @@ -0,0 +1,168 @@ +using System.Globalization; +using System.Xml; +using System.Xml.Linq; +using SmsSluzba.Api.Contracts; + +namespace SmsSluzba.Api.Gateway; + +internal sealed record ParsedEvents(IReadOnlyList Events, IReadOnlyList SkippedTypes); + +/// Builds and reads the XML documents of the SMS Gate API XML 3.0. +internal static class GatewayXml +{ + // dr_request values defined by the gateway. + private const string DeliveryReportRequested = "20"; + private const string DeliveryReportNotRequested = "0"; + + private const string SourceApi = "api"; + private const string SourcePortal = "portal"; + + private static readonly XmlReaderSettings ReaderSettings = new() { DtdProcessing = DtdProcessing.Prohibit }; + + public static string BuildOutgoingMessage(string recipient, string text, bool? deliveryReport, DateTimeOffset? sendAt) + { + var root = new XElement("outgoing_message"); + if (deliveryReport is { } requested) + { + root.Add(new XElement("dr_request", requested ? DeliveryReportRequested : DeliveryReportNotRequested)); + } + + root.Add(new XElement("text", text), new XElement("recipient", recipient)); + + if (sendAt is { } at) + { + root.Add(new XElement("send_at", GatewayTime.ToGateway(at))); + } + + var declaration = new XDeclaration("1.0", "UTF-8", null); + return declaration + Environment.NewLine + root.ToString(SaveOptions.DisableFormatting); + } + + /// Null when the body is not XML (for example an error page of a proxy); the caller then decides by HTTP status. + public static XDocument? TryParse(string body) + { + try + { + using var stringReader = new StringReader(body); + using var xmlReader = XmlReader.Create(stringReader, ReaderSettings); + return XDocument.Load(xmlReader); + } + catch (XmlException) + { + return null; + } + } + + public static SendMessageResponse ParseSendResult(XDocument document) + { + var root = document.Root; + var message = root?.Element("message"); + if (root is null || message is null) + { + throw Invalid("send result without "); + } + + return new SendMessageResponse( + Id: RequiredText(message, "id"), + Recipient: OptionalText(message, "recipient"), + SendAt: GatewayTime.FromGateway(OptionalText(message, "send_at")), + Parts: ParseInt(OptionalText(message, "parts")), + Price: ParseDecimal(OptionalText(message, "price")), + Credit: ParseDecimal(OptionalText(root, "credit"))); + } + + public static ParsedEvents ParseEvents(XDocument document) + { + var events = new List(); + var skipped = new List(); + + foreach (var message in document.Root?.Elements("message") ?? Enumerable.Empty()) + { + var type = OptionalText(message, "type") ?? string.Empty; + SmsEvent? parsed = type switch + { + "incoming_message" => new IncomingSmsEvent( + RequiredText(message, "id"), + OptionalText(message, "sender"), + OptionalText(message, "recipient"), + OptionalText(message, "text"), + GatewayTime.FromGateway(OptionalText(message, "sent_at"))), + "answer_message" => new AnswerSmsEvent( + RequiredText(message, "id"), + OptionalText(message, "sender"), + OptionalText(message, "recipient"), + OptionalText(message, "text"), + GatewayTime.FromGateway(OptionalText(message, "sent_at")), + OptionalText(message, "in_reply_to")), + "delivery_report" => ParseDeliveryReport(message), + "gate_outgoing_message" => ParseOutgoing(message, SourcePortal), + "api_outgoing_message" => ParseOutgoing(message, SourceApi), + _ => null, + }; + + if (parsed is null) + { + skipped.Add(type); + } + else + { + events.Add(parsed); + } + } + + return new ParsedEvents(events, skipped); + } + + public static CreditResponse ParseCredit(XDocument document) + { + var root = document.Root ?? throw Invalid("empty credit document"); + return new CreditResponse( + RequiredDecimal(root, "credit"), + RequiredDecimal(root, "price_cz_sms"), + RequiredDecimal(root, "price_sk_sms"), + RequiredDecimal(root, "price_other_sms")); + } + + private static DeliveryReportSmsEvent ParseDeliveryReport(XElement message) + { + // The id of a delivery report is the id of the outgoing message it belongs to. + var id = RequiredText(message, "id"); + return new DeliveryReportSmsEvent( + id, + id, + ParseInt(OptionalText(message, "status")), + OptionalText(message, "description"), + GatewayTime.FromGateway(OptionalText(message, "delivery_timestamp"))); + } + + private static OutgoingSmsEvent ParseOutgoing(XElement message, string source) => + new( + RequiredText(message, "id"), + OptionalText(message, "recipient"), + OptionalText(message, "text"), + GatewayTime.FromGateway(OptionalText(message, "send_at")), + source); + + private static string? OptionalText(XElement parent, string name) + { + var value = parent.Element(name)?.Value.Trim(); + return string.IsNullOrEmpty(value) ? null : value; + } + + private static string RequiredText(XElement parent, string name) => + OptionalText(parent, name) ?? throw Invalid($"missing <{name}>"); + + private static int? ParseInt(string? value) => + int.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out var result) ? result : null; + + private static decimal? ParseDecimal(string? value) => + decimal.TryParse(value?.Replace(',', '.'), NumberStyles.Number, CultureInfo.InvariantCulture, out var result) + ? result + : null; + + private static decimal RequiredDecimal(XElement parent, string name) => + ParseDecimal(OptionalText(parent, name)) ?? throw Invalid($"missing or invalid <{name}>"); + + private static GatewayException Invalid(string reason) => + new(GatewayErrorKind.InvalidResponse, inner: new FormatException("Unexpected gateway XML: " + reason)); +} diff --git a/src/SmsSluzba.Api/Gateway/RedactingLoggingHandler.cs b/src/SmsSluzba.Api/Gateway/RedactingLoggingHandler.cs new file mode 100644 index 0000000..c7cb966 --- /dev/null +++ b/src/SmsSluzba.Api/Gateway/RedactingLoggingHandler.cs @@ -0,0 +1,38 @@ +using System.Diagnostics; +using SmsSluzba.Api.Logging; + +namespace SmsSluzba.Api.Gateway; + +/// +/// Logs gateway calls with the password masked. Replaces the default HttpClient logging, +/// which writes the full URL including the password query parameter. +/// +internal sealed class RedactingLoggingHandler(ILogger logger) : DelegatingHandler +{ + protected override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + { + var started = Stopwatch.GetTimestamp(); + try + { + var response = await base.SendAsync(request, cancellationToken); + logger.LogDebug( + "Gateway {Method} {Url} responded {StatusCode} in {ElapsedMs} ms", + request.Method, + LogMask.Url(request.RequestUri), + (int)response.StatusCode, + Stopwatch.GetElapsedTime(started).TotalMilliseconds); + return response; + } + catch (Exception ex) when (ex is HttpRequestException or TaskCanceledException) + { + logger.LogWarning( + "Gateway {Method} {Url} failed after {ElapsedMs} ms: {ErrorType} {ErrorMessage}", + request.Method, + LogMask.Url(request.RequestUri), + Stopwatch.GetElapsedTime(started).TotalMilliseconds, + ex.GetType().Name, + ex.Message); + throw; + } + } +} diff --git a/src/SmsSluzba.Api/Gateway/SmsGatewayClient.cs b/src/SmsSluzba.Api/Gateway/SmsGatewayClient.cs new file mode 100644 index 0000000..b847076 --- /dev/null +++ b/src/SmsSluzba.Api/Gateway/SmsGatewayClient.cs @@ -0,0 +1,171 @@ +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. +/// +internal sealed class SmsGatewayClient( + HttpClient http, + GatewaySettings settings, + GatewayAuthGuard authGuard, + ILogger logger) +{ + private const string ReceiverPath = "receiver"; + private const string SenderPath = "sender"; + private const string ConfirmPath = "confirm"; + private const string CreditPath = "info/credit"; + private const string Enabled = "1"; + + public Task SendAsync( + string recipient, + string text, + bool? deliveryReport, + DateTimeOffset? sendAt, + CancellationToken ct) => + ExecuteAsync("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); + return GatewayXml.ParseSendResult(RequireDocument(document)); + }); + + public Task> GetEventsAsync(GatewayEventQuery query, int count, CancellationToken ct) => + ExecuteAsync>("events", async () => + { + var parameters = new List> + { + new("count", count.ToString(CultureInfo.InvariantCulture)), + }; + if (query.Incoming) + { + parameters.Add(new("query_incoming", Enabled)); + } + + if (query.DeliveryReports) + { + parameters.Add(new("query_delivery_report", Enabled)); + } + + if (query.Outgoing) + { + parameters.Add(new("query_outgoing", Enabled)); + } + + var document = await CallAsync(HttpMethod.Get, SenderPath, parameters, null, ct); + if (document is null) + { + return []; + } + + var parsed = GatewayXml.ParseEvents(document); + foreach (var type in parsed.SkippedTypes) + { + logger.LogWarning("Gateway returned an event of unknown type {EventType}; it is not passed on to callers", type); + } + + return parsed.Events; + }); + + public Task GetDeliveryReportAsync(string messageId, CancellationToken ct) => + ExecuteAsync("delivery-report", async () => + { + var document = await CallAsync(HttpMethod.Get, SenderPath, [new("act", "get_delivery_report"), new("id", messageId)], null, ct); + if (document is null) + { + return null; + } + + var report = GatewayXml.ParseEvents(document).Events.OfType().FirstOrDefault(); + return report is null + ? null + : new DeliveryReportResponse(report.MessageId, report.Status, report.Description, report.DeliveredAt); + }); + + public Task ConfirmAsync(string gatewayType, string id, CancellationToken ct) => + ExecuteAsync("confirm", async () => + { + await CallAsync(HttpMethod.Get, ConfirmPath, [new("type", gatewayType), new("id", id)], null, ct); + return true; + }); + + public Task GetCreditAsync(CancellationToken ct) => + ExecuteAsync("credit", async () => + { + var document = await CallAsync(HttpMethod.Get, CreditPath, [], null, ct); + return GatewayXml.ParseCredit(RequireDocument(document)); + }); + + private async Task ExecuteAsync(string operation, Func> call) + { + try + { + return await call(); + } + catch (GatewayException ex) + { + if (ex.Kind == GatewayErrorKind.AuthFailed) + { + authGuard.Block(ex.ProviderCode); + } + else + { + logger.LogWarning( + ex.InnerException, + "Gateway {Operation} failed: {Kind}, provider code {ProviderCode}", + operation, + ex.Kind, + ex.ProviderCode); + } + + throw; + } + } + + private async Task CallAsync( + HttpMethod method, + string path, + IReadOnlyList> parameters, + HttpContent? content, + CancellationToken ct) + { + authGuard.ThrowIfBlocked(); + + using var request = new HttpRequestMessage(method, BuildUri(path, parameters)) { Content = content }; + try + { + using var response = await http.SendAsync(request, ct); + var body = await response.Content.ReadAsStringAsync(ct); + return GatewayResponse.Interpret(response.StatusCode, body); + } + catch (TaskCanceledException ex) when (!ct.IsCancellationRequested) + { + throw new GatewayException(GatewayErrorKind.Timeout, ex); + } + catch (HttpRequestException ex) + { + throw new GatewayException(GatewayErrorKind.Unavailable, ex); + } + } + + private Uri BuildUri(string path, IReadOnlyList> parameters) + { + var query = new List> + { + new("login", settings.Login), + new("password", settings.Password), + }; + query.AddRange(parameters); + + var queryString = string.Join('&', query.Select(p => $"{Uri.EscapeDataString(p.Key)}={Uri.EscapeDataString(p.Value)}")); + return new Uri($"{path}?{queryString}", UriKind.Relative); + } + + private static XDocument RequireDocument(XDocument? document) => + document ?? throw new GatewayException(GatewayErrorKind.InvalidResponse, inner: new FormatException("Gateway returned no XML body.")); +} diff --git a/src/SmsSluzba.Api/Logging/LogMask.cs b/src/SmsSluzba.Api/Logging/LogMask.cs new file mode 100644 index 0000000..2beb23d --- /dev/null +++ b/src/SmsSluzba.Api/Logging/LogMask.cs @@ -0,0 +1,44 @@ +using System.Text.RegularExpressions; + +namespace SmsSluzba.Api.Logging; + +internal static partial class LogMask +{ + private const string Mask = "***"; + + // Number of trailing digits kept visible so support can match a number without exposing it. + private const int VisibleSuffix = 3; + + // Shortest number that still keeps a meaningful prefix after masking. + private const int MinMaskableLength = 9; + + [GeneratedRegex("(?<=[?&]password=)[^&]*", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant)] + private static partial Regex PasswordValue(); + + public static string Url(Uri? uri) + { + if (uri is null) + { + return string.Empty; + } + + var text = uri.IsAbsoluteUri ? uri.AbsoluteUri : uri.OriginalString; + return PasswordValue().Replace(text, Mask); + } + + public static string Phone(string? number) + { + if (string.IsNullOrWhiteSpace(number)) + { + return string.Empty; + } + + var value = number.Trim(); + if (value.Length < MinMaskableLength) + { + return Mask; + } + + return value[..(value.Length - (2 * VisibleSuffix))] + Mask + value[^VisibleSuffix..]; + } +} diff --git a/src/SmsSluzba.Api/Messages/SmsText.cs b/src/SmsSluzba.Api/Messages/SmsText.cs new file mode 100644 index 0000000..556d9ff --- /dev/null +++ b/src/SmsSluzba.Api/Messages/SmsText.cs @@ -0,0 +1,21 @@ +namespace SmsSluzba.Api.Messages; + +internal static class SmsText +{ + // The gateway truncates longer texts: at most 3 concatenated parts of 153 GSM characters. + public const int MaxLength = 459; + + // GSM 03.38 extension table: each of these is sent as escape + character, so it takes two positions. + private const string GsmExtensionCharacters = "€[]{}\\^~|"; + + public static int CountLength(string text) + { + var length = 0; + foreach (var rune in text.EnumerateRunes()) + { + length += rune.IsBmp && GsmExtensionCharacters.Contains((char)rune.Value, StringComparison.Ordinal) ? 2 : 1; + } + + return length; + } +} diff --git a/src/SmsSluzba.Api/OpenApi/OpenApiSetup.cs b/src/SmsSluzba.Api/OpenApi/OpenApiSetup.cs new file mode 100644 index 0000000..f920b7a --- /dev/null +++ b/src/SmsSluzba.Api/OpenApi/OpenApiSetup.cs @@ -0,0 +1,55 @@ +using Microsoft.OpenApi; +using SmsSluzba.Api.Auth; + +namespace SmsSluzba.Api.OpenApi; + +internal static class OpenApiSetup +{ + public const string DocumentPath = "/openapi/v1.json"; + private const string ApiKeySchemeId = "ApiKey"; + private const string ProtectedPathPrefix = "/v1/"; + + public static IServiceCollection AddSmsOpenApi(this IServiceCollection services, string? rootPath) => + services.AddOpenApi(options => options.AddDocumentTransformer((document, _, _) => + { + document.Info = new OpenApiInfo + { + 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.", + }; + + // 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 ?? "/" }]; + + 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.", + }; + + foreach (var (path, item) in document.Paths) + { + if (!path.StartsWith(ProtectedPathPrefix, StringComparison.Ordinal)) + { + continue; + } + + foreach (var operation in item.Operations?.Values ?? Enumerable.Empty()) + { + operation.Security ??= []; + operation.Security.Add(new OpenApiSecurityRequirement + { + [new OpenApiSecuritySchemeReference(ApiKeySchemeId, document)] = [], + }); + } + } + + return Task.CompletedTask; + })); +} diff --git a/src/SmsSluzba.Api/Problems/ApiErrors.cs b/src/SmsSluzba.Api/Problems/ApiErrors.cs new file mode 100644 index 0000000..c9267af --- /dev/null +++ b/src/SmsSluzba.Api/Problems/ApiErrors.cs @@ -0,0 +1,32 @@ +namespace SmsSluzba.Api.Problems; + +/// Stable error code returned to callers in the code field of a problem response. +internal sealed record ApiError(string Code, int Status, string Title); + +/// All error codes of the public API. Must match documentation/integration.md. +internal static class ApiErrors +{ + public static readonly ApiError ValidationFailed = new("validation_failed", 400, "Neplatný požadavek"); + public static readonly ApiError InvalidRecipient = new("invalid_recipient", 400, "Neplatné telefonní číslo"); + 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 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/Problems/ApiProblems.cs b/src/SmsSluzba.Api/Problems/ApiProblems.cs new file mode 100644 index 0000000..9e8f236 --- /dev/null +++ b/src/SmsSluzba.Api/Problems/ApiProblems.cs @@ -0,0 +1,35 @@ +namespace SmsSluzba.Api.Problems; + +internal static class ApiProblems +{ + public const string CodeKey = "code"; + public const string ProviderCodeKey = "providerCode"; + + public static IResult Result(ApiError error, string? detail = null, string? providerCode = null) + { + var extensions = new Dictionary { [CodeKey] = error.Code }; + if (providerCode is not null) + { + extensions[ProviderCodeKey] = providerCode; + } + + return Results.Problem(detail: detail, statusCode: error.Status, title: error.Title, extensions: extensions); + } + + public static IResult Validation(string detail) => Result(ApiErrors.ValidationFailed, detail); + + /// Every problem response carries a code, including those created by the framework. + public static void Configure(ProblemDetailsOptions options) => + options.CustomizeProblemDetails = context => + { + var problem = context.ProblemDetails; + if (problem.Extensions.ContainsKey(CodeKey)) + { + return; + } + + var fallback = ApiErrors.ForStatus(problem.Status); + problem.Extensions[CodeKey] = fallback.Code; + problem.Title = fallback.Title; + }; +} diff --git a/src/SmsSluzba.Api/Program.cs b/src/SmsSluzba.Api/Program.cs new file mode 100644 index 0000000..00372b9 --- /dev/null +++ b/src/SmsSluzba.Api/Program.cs @@ -0,0 +1,70 @@ +using SmsSluzba.Api.Auth; +using SmsSluzba.Api.Config; +using SmsSluzba.Api.Endpoints; +using SmsSluzba.Api.Gateway; +using SmsSluzba.Api.OpenApi; +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 + .AddHttpClient(http => + { + http.BaseAddress = settings.Gateway.BaseUrl; + http.Timeout = settings.Gateway.Timeout; + }) + // The default HttpClient logging writes full URLs, which contain the gateway password. + .RemoveAllLoggers() + .AddHttpMessageHandler(); +builder.Services.AddProblemDetails(ApiProblems.Configure); +// Invalid JSON is a 400 in every environment, not an exception turned into 500 in Development. +builder.Services.Configure(options => options.ThrowOnBadRequest = false); +builder.Services.AddSmsOpenApi(settings.RootPath); + +var app = builder.Build(); + +if (settings.RootPath is not null) +{ + app.UsePathBase(settings.RootPath); +} + +app.UseExceptionHandler(); +app.UseStatusCodePages(); +// Explicit UseRouting after UsePathBase, otherwise routes would be matched before the prefix is removed. +app.UseRouting(); + +// Swagger UI redirects /docs to an absolute /docs/index.html, which drops the proxy prefix when +// Caddy strips it. A relative redirect keeps the browser under /apps/. +app.Use(async (context, next) => +{ + if (context.Request.Path.Equals("/docs", StringComparison.OrdinalIgnoreCase)) + { + context.Response.Redirect("docs/index.html"); + return; + } + + await next(); +}); + +app.MapOpenApi(OpenApiSetup.DocumentPath); +app.UseSwaggerUI(options => +{ + options.RoutePrefix = "docs"; + 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"); +}); + +app.MapSystemEndpoints(); + +var v1 = app.MapGroup("/v1").AddEndpointFilter(); +v1.MapMessageEndpoints(); +v1.MapEventEndpoints(); +v1.MapAccountEndpoints(); + +app.Run(); diff --git a/src/SmsSluzba.Api/SmsSluzba.Api.csproj b/src/SmsSluzba.Api/SmsSluzba.Api.csproj new file mode 100644 index 0000000..96f6266 --- /dev/null +++ b/src/SmsSluzba.Api/SmsSluzba.Api.csproj @@ -0,0 +1,14 @@ + + + SmsSluzba.Api + + + + + + + + + + + diff --git a/appsettings.json b/src/SmsSluzba.Api/appsettings.json similarity index 53% rename from appsettings.json rename to src/SmsSluzba.Api/appsettings.json index 10f68b8..49830b4 100644 --- a/appsettings.json +++ b/src/SmsSluzba.Api/appsettings.json @@ -2,7 +2,8 @@ "Logging": { "LogLevel": { "Default": "Information", - "Microsoft.AspNetCore": "Warning" + "Microsoft.AspNetCore": "Warning", + "System.Net.Http.HttpClient": "Warning" } }, "AllowedHosts": "*" diff --git a/src/SmsSluzba.Api/packages.lock.json b/src/SmsSluzba.Api/packages.lock.json new file mode 100644 index 0000000..74bb359 --- /dev/null +++ b/src/SmsSluzba.Api/packages.lock.json @@ -0,0 +1,27 @@ +{ + "version": 2, + "dependencies": { + "net10.0": { + "Microsoft.AspNetCore.OpenApi": { + "type": "Direct", + "requested": "[10.0.13, )", + "resolved": "10.0.13", + "contentHash": "XVuqUBGjVUVyb4DXR5BrSkrW0Br7sYKq39f723ILhQLlFHCyhAgWe1PkJBc42R/5mKBIgHiKVSY+PN5/4XtcQw==", + "dependencies": { + "Microsoft.OpenApi": "[2.12.2, 3.0.0)" + } + }, + "Swashbuckle.AspNetCore.SwaggerUI": { + "type": "Direct", + "requested": "[9.0.6, )", + "resolved": "9.0.6", + "contentHash": "WGsw/Yop9b16miq8TQd4THxuEgkP5cH3+DX93BrX9m0OdPcKNtg2nNm77WQSAsA+Se+M0bTiu8bUyrruRSeS5g==" + }, + "Microsoft.OpenApi": { + "type": "Transitive", + "resolved": "2.12.2", + "contentHash": "ZkT7qiJe0Kj0+DTZOZo+xrDy1kNmdsWFQVPIQLNx9ZJ0T9cB2LG7r+Bi60so8/+yg1nkS7QCPadrzsTG4VPKrA==" + } + } + } +} \ No newline at end of file diff --git a/tests/SmsSluzba.Api.Tests/Api/ApiTests.cs b/tests/SmsSluzba.Api.Tests/Api/ApiTests.cs new file mode 100644 index 0000000..ce0843d --- /dev/null +++ b/tests/SmsSluzba.Api.Tests/Api/ApiTests.cs @@ -0,0 +1,245 @@ +using System.Net; +using System.Net.Http.Json; +using System.Text.Json; +using System.Xml.Linq; +using Microsoft.AspNetCore.Mvc.Testing; + +namespace SmsSluzba.Api.Tests.Api; + +public sealed class ApiTests : IDisposable +{ + private const string SendSuccessXml = """ + + + 420603123456-20261020120000123 + Test + 20261020120000 + +420603123456 + 1 + 0.68 + + 453.49 + + """; + + private readonly FakeGatewayHandler _gateway = new(); + private readonly SmsApiFactory _factory; + private readonly HttpClient _client; + + public ApiTests() + { + _factory = new SmsApiFactory(_gateway); + _client = _factory.CreateClient(); + _client.DefaultRequestHeaders.Add("X-Api-Key", SmsApiFactory.ApiKey); + } + + public void Dispose() + { + _client.Dispose(); + _factory.Dispose(); + _gateway.Dispose(); + } + + [Fact] + public async Task Health_WithoutApiKey_ReturnsOk() + { + using var anonymous = _factory.CreateClient(); + + var response = await anonymous.GetAsync(new Uri("/health", UriKind.Relative)); + + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Empty(_gateway.Requests); + } + + [Fact] + public async Task V1_WithWrongApiKey_Returns401WithCode() + { + 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.Empty(_gateway.Requests); + } + + [Fact] + public async Task SendMessage_Success_ReturnsGatewayResultAndSendsXml() + { + _gateway.Enqueue(SendSuccessXml); + + var response = await _client.PostAsJsonAsync("/v1/messages", new { to = "+420603123456", text = "Test & co", deliveryReport = true }); + + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + var json = await ReadJson(response); + Assert.Equal("420603123456-20261020120000123", json.GetProperty("id").GetString()); + Assert.Equal(1, json.GetProperty("parts").GetInt32()); + Assert.Equal(0.68m, json.GetProperty("price").GetDecimal()); + 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); + var sent = XDocument.Parse(body!).Root!; + Assert.Equal("Test & co", sent.Element("text")?.Value); + Assert.Equal("20", sent.Element("dr_request")?.Value); + } + + [Fact] + public async Task SendMessage_InvalidRecipient_Returns400WithProviderCode() + { + _gateway.Enqueue("400;1Chybne telefonni cislo 77716085"); + + var response = await _client.PostAsJsonAsync("/v1/messages", new { to = "77716085", text = "Test" }); + + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + var json = await ReadJson(response); + Assert.Equal("invalid_recipient", json.GetProperty("code").GetString()); + Assert.Equal("400;1", json.GetProperty("providerCode").GetString()); + } + + [Fact] + public async Task SendMessage_TextTooLong_DoesNotCallGateway() + { + var response = await _client.PostAsJsonAsync("/v1/messages", new { to = "+420603123456", text = new string('a', 460) }); + + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + Assert.Equal("text_too_long", (await ReadJson(response)).GetProperty("code").GetString()); + Assert.Empty(_gateway.Requests); + } + + [Fact] + public async Task SendMessage_InvalidJson_Returns400WithCode() + { + using var content = new StringContent("{not json", System.Text.Encoding.UTF8, "application/json"); + + var response = await _client.PostAsync(new Uri("/v1/messages", UriKind.Relative), content); + + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + Assert.Equal("validation_failed", (await ReadJson(response)).GetProperty("code").GetString()); + } + + [Fact] + public async Task SendMessage_Timeout_Returns504() + { + _gateway.EnqueueException(new TaskCanceledException("timeout", new TimeoutException())); + + var response = await _client.PostAsJsonAsync("/v1/messages", new { to = "+420603123456", text = "Test" }); + + Assert.Equal(HttpStatusCode.GatewayTimeout, response.StatusCode); + Assert.Equal("provider_timeout", (await ReadJson(response)).GetProperty("code").GetString()); + } + + [Fact] + public async Task AuthFailure_StopsAllFurtherGatewayCalls() + { + _gateway.Enqueue("401Chybne prihlaseni"); + + var first = await _client.PostAsJsonAsync("/v1/messages", new { to = "+420603123456", text = "Test" }); + var second = await _client.GetAsync(new Uri("/v1/account/credit", UriKind.Relative)); + var health = await ReadJson(await _client.GetAsync(new Uri("/health", 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); + } + + [Fact] + public async Task GetEvents_ReturnsTypedEventsAndQueriesGateway() + { + _gateway.Enqueue(""" + + answer_messagein-2ANOout-1+4207771234565517 + delivery_reportout-10Doručeno + + """); + + var response = await _client.GetAsync(new Uri("/v1/events?count=10", UriKind.Relative)); + + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + var events = (await ReadJson(response)).GetProperty("events"); + Assert.Equal("answer", events[0].GetProperty("type").GetString()); + Assert.Equal("out-1", events[0].GetProperty("inReplyTo").GetString()); + Assert.Equal("deliveryReport", events[1].GetProperty("type").GetString()); + Assert.Equal("out-1", events[1].GetProperty("messageId").GetString()); + + var query = Assert.Single(_gateway.Requests).Uri.Query; + Assert.Contains("query_incoming=1", query, StringComparison.Ordinal); + Assert.Contains("query_delivery_report=1", query, StringComparison.Ordinal); + Assert.DoesNotContain("query_outgoing", query, StringComparison.Ordinal); + Assert.Contains("count=10", query, StringComparison.Ordinal); + } + + [Fact] + public async Task ConfirmEvents_MapsTypesAndReportsFailures() + { + _gateway.Enqueue("200OK"); + _gateway.Enqueue("503Chyba brany"); + + var response = await _client.PostAsJsonAsync("/v1/events/confirm", new + { + events = new[] + { + new { type = "answer", id = "in-2" }, + new { type = "deliveryReport", id = "out-1" }, + }, + }); + + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + var json = await ReadJson(response); + Assert.Equal("in-2", json.GetProperty("confirmed")[0].GetProperty("id").GetString()); + Assert.Equal("provider_unavailable", json.GetProperty("failed")[0].GetProperty("code").GetString()); + Assert.Contains("type=incoming_message", _gateway.Requests[0].Uri.Query, StringComparison.Ordinal); + Assert.Contains("type=delivery_report", _gateway.Requests[1].Uri.Query, StringComparison.Ordinal); + } + + [Fact] + public async Task ConfirmEvents_UnknownType_Returns400WithoutGatewayCall() + { + var response = await _client.PostAsJsonAsync("/v1/events/confirm", new { events = new[] { new { type = "sms", id = "1" } } }); + + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + Assert.Empty(_gateway.Requests); + } + + [Fact] + public async Task DeliveryReport_NotAvailable_Returns404() + { + _gateway.Enqueue(""); + + var response = await _client.GetAsync(new Uri("/v1/messages/out-1/delivery-report", UriKind.Relative)); + + Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); + Assert.Equal("delivery_report_not_found", (await ReadJson(response)).GetProperty("code").GetString()); + Assert.Contains("act=get_delivery_report", Assert.Single(_gateway.Requests).Uri.Query, StringComparison.Ordinal); + } + + [Fact] + public async Task OpenApi_DescribesApiKeyAndRelativeServer() + { + 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 _)); + } + + [Fact] + public async Task Docs_RedirectsRelatively() + { + using var client = _factory.CreateClient(new WebApplicationFactoryClientOptions { AllowAutoRedirect = false }); + + var response = await client.GetAsync(new Uri("/docs", UriKind.Relative)); + + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Equal("docs/index.html", response.Headers.Location?.OriginalString); + } + + private static async Task ReadJson(HttpResponseMessage response) => + JsonDocument.Parse(await response.Content.ReadAsStringAsync()).RootElement.Clone(); +} diff --git a/tests/SmsSluzba.Api.Tests/Api/FakeGatewayHandler.cs b/tests/SmsSluzba.Api.Tests/Api/FakeGatewayHandler.cs new file mode 100644 index 0000000..ef97231 --- /dev/null +++ b/tests/SmsSluzba.Api.Tests/Api/FakeGatewayHandler.cs @@ -0,0 +1,33 @@ +using System.Net; +using System.Text; + +namespace SmsSluzba.Api.Tests.Api; + +/// Stands in for the SMS gateway: returns queued responses and records every request. +internal sealed class FakeGatewayHandler : HttpMessageHandler +{ + private readonly Queue> _responses = new(); + + public List<(Uri Uri, string? Body)> Requests { get; } = []; + + public void Enqueue(string body, HttpStatusCode status = HttpStatusCode.OK) => + _responses.Enqueue(() => new HttpResponseMessage(status) + { + Content = new StringContent(body, Encoding.UTF8, "application/xml"), + }); + + public void EnqueueException(Exception exception) => _responses.Enqueue(() => throw exception); + + protected override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + { + var body = request.Content is null ? null : await request.Content.ReadAsStringAsync(cancellationToken); + Requests.Add((request.RequestUri!, body)); + + if (_responses.Count == 0) + { + throw new InvalidOperationException("Unexpected gateway call: " + request.RequestUri); + } + + return _responses.Dequeue()(); + } +} diff --git a/tests/SmsSluzba.Api.Tests/Api/SmsApiFactory.cs b/tests/SmsSluzba.Api.Tests/Api/SmsApiFactory.cs new file mode 100644 index 0000000..c40e6b1 --- /dev/null +++ b/tests/SmsSluzba.Api.Tests/Api/SmsApiFactory.cs @@ -0,0 +1,23 @@ +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; + +internal sealed class SmsApiFactory(FakeGatewayHandler gateway) : WebApplicationFactory +{ + public const string ApiKey = "test-key-eshop"; + public const string GatewayPassword = "gateway-password"; + + protected override void ConfigureWebHost(IWebHostBuilder builder) + { + builder.UseSetting(AppSettingsLoader.LoginKey, "gateway-login"); + builder.UseSetting(AppSettingsLoader.PasswordKey, GatewayPassword); + builder.UseSetting(AppSettingsLoader.ApiKeysKey, "eshop=" + ApiKey); + 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 new file mode 100644 index 0000000..38815b7 --- /dev/null +++ b/tests/SmsSluzba.Api.Tests/Config/AppSettingsLoaderTests.cs @@ -0,0 +1,68 @@ +using Microsoft.Extensions.Configuration; +using SmsSluzba.Api.Config; + +namespace SmsSluzba.Api.Tests.Config; + +public class AppSettingsLoaderTests +{ + [Fact] + public void Load_ValidConfiguration_AppliesDefaultsAndNormalizesRootPath() + { + 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", + })); + + 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", + }))); + } + + private static IConfiguration Build(Dictionary values) => + new ConfigurationBuilder().AddInMemoryCollection(values).Build(); +} diff --git a/tests/SmsSluzba.Api.Tests/Gateway/GatewayEventQueryTests.cs b/tests/SmsSluzba.Api.Tests/Gateway/GatewayEventQueryTests.cs new file mode 100644 index 0000000..2048ae4 --- /dev/null +++ b/tests/SmsSluzba.Api.Tests/Gateway/GatewayEventQueryTests.cs @@ -0,0 +1,40 @@ +using SmsSluzba.Api.Gateway; + +namespace SmsSluzba.Api.Tests.Gateway; + +public class GatewayEventQueryTests +{ + [Fact] + public void Parse_Empty_ReturnsDefault() + { + Assert.Equal(GatewayEventQuery.Default, GatewayEventQuery.Parse(null)); + } + + [Fact] + public void Parse_List_SetsFlags() + { + var query = GatewayEventQuery.Parse("deliveryReport, outgoing"); + + Assert.NotNull(query); + Assert.False(query.Incoming); + Assert.True(query.DeliveryReports); + Assert.True(query.Outgoing); + } + + [Fact] + public void Parse_UnknownType_ReturnsNull() + { + Assert.Null(GatewayEventQuery.Parse("incoming,sms")); + } + + [Theory] + [InlineData("incoming", "incoming_message")] + [InlineData("answer", "incoming_message")] + [InlineData("deliveryReport", "delivery_report")] + [InlineData("outgoing", "outgoing_message")] + [InlineData("other", null)] + public void ConfirmTypeFor_MapsApiTypes(string apiType, string? expected) + { + Assert.Equal(expected, GatewayEventQuery.ConfirmTypeFor(apiType)); + } +} diff --git a/tests/SmsSluzba.Api.Tests/Gateway/GatewayResponseTests.cs b/tests/SmsSluzba.Api.Tests/Gateway/GatewayResponseTests.cs new file mode 100644 index 0000000..20a254a --- /dev/null +++ b/tests/SmsSluzba.Api.Tests/Gateway/GatewayResponseTests.cs @@ -0,0 +1,62 @@ +using System.Net; +using SmsSluzba.Api.Gateway; + +namespace SmsSluzba.Api.Tests.Gateway; + +public class GatewayResponseTests +{ + [Theory] + [InlineData("400;1", nameof(GatewayErrorKind.InvalidRecipient))] + [InlineData("400;2", nameof(GatewayErrorKind.MissingText))] + [InlineData("400", nameof(GatewayErrorKind.Rejected))] + [InlineData("401", nameof(GatewayErrorKind.AuthFailed))] + [InlineData("401;1", nameof(GatewayErrorKind.AuthFailed))] + [InlineData("402", nameof(GatewayErrorKind.InsufficientCredit))] + [InlineData("503", nameof(GatewayErrorKind.Unavailable))] + [InlineData("999", nameof(GatewayErrorKind.Unavailable))] + public void Interpret_StatusInBody_ThrowsMappedKind(string code, string expectedKind) + { + var body = $"{code}Popis"; + + var ex = Assert.Throws(() => GatewayResponse.Interpret(HttpStatusCode.OK, body)); + + Assert.Equal(expectedKind, ex.Kind.ToString()); + Assert.Equal(code, ex.ProviderCode); + Assert.Equal("Popis", ex.ProviderMessage); + } + + [Theory] + [InlineData(HttpStatusCode.BadRequest, nameof(GatewayErrorKind.Rejected))] + [InlineData(HttpStatusCode.Unauthorized, nameof(GatewayErrorKind.AuthFailed))] + [InlineData(HttpStatusCode.PaymentRequired, nameof(GatewayErrorKind.InsufficientCredit))] + [InlineData(HttpStatusCode.BadGateway, nameof(GatewayErrorKind.Unavailable))] + public void Interpret_HttpErrorWithoutXml_ThrowsMappedKind(HttpStatusCode status, string expectedKind) + { + var ex = Assert.Throws(() => GatewayResponse.Interpret(status, "error200OK"); + + Assert.NotNull(document); + } + + [Fact] + public void Interpret_EmptySuccess_ReturnsNull() + { + Assert.Null(GatewayResponse.Interpret(HttpStatusCode.OK, string.Empty)); + } + + [Fact] + public void Interpret_ErrorCodeInBodyWinsOverHttpStatus() + { + var ex = Assert.Throws(() => + GatewayResponse.Interpret(HttpStatusCode.BadRequest, "400;1x")); + + Assert.Equal(GatewayErrorKind.InvalidRecipient, ex.Kind); + } +} diff --git a/tests/SmsSluzba.Api.Tests/Gateway/GatewayTimeTests.cs b/tests/SmsSluzba.Api.Tests/Gateway/GatewayTimeTests.cs new file mode 100644 index 0000000..b717270 --- /dev/null +++ b/tests/SmsSluzba.Api.Tests/Gateway/GatewayTimeTests.cs @@ -0,0 +1,33 @@ +using SmsSluzba.Api.Gateway; + +namespace SmsSluzba.Api.Tests.Gateway; + +public class GatewayTimeTests +{ + [Fact] + public void FromGateway_Winter_UsesCet() + { + Assert.Equal(new DateTimeOffset(2026, 1, 20, 11, 0, 0, TimeSpan.Zero), GatewayTime.FromGateway("20260120120000")); + } + + [Fact] + public void FromGateway_Summer_UsesCest() + { + Assert.Equal(new DateTimeOffset(2026, 7, 20, 10, 0, 0, TimeSpan.Zero), GatewayTime.FromGateway("20260720120000")); + } + + [Theory] + [InlineData(null)] + [InlineData("")] + [InlineData("2026-01-20")] + public void FromGateway_InvalidValue_ReturnsNull(string? value) + { + Assert.Null(GatewayTime.FromGateway(value)); + } + + [Fact] + public void ToGateway_ConvertsUtcToPragueTime() + { + Assert.Equal("20260120120000", GatewayTime.ToGateway(new DateTimeOffset(2026, 1, 20, 11, 0, 0, TimeSpan.Zero))); + } +} diff --git a/tests/SmsSluzba.Api.Tests/Gateway/GatewayXmlTests.cs b/tests/SmsSluzba.Api.Tests/Gateway/GatewayXmlTests.cs new file mode 100644 index 0000000..ee0532a --- /dev/null +++ b/tests/SmsSluzba.Api.Tests/Gateway/GatewayXmlTests.cs @@ -0,0 +1,187 @@ +using System.Xml.Linq; +using SmsSluzba.Api.Contracts; +using SmsSluzba.Api.Gateway; + +namespace SmsSluzba.Api.Tests.Gateway; + +public class GatewayXmlTests +{ + [Fact] + public void BuildOutgoingMessage_EscapesTextAndWritesOptionalElements() + { + var sendAt = new DateTimeOffset(2026, 10, 21, 8, 0, 0, TimeSpan.FromHours(2)); + + var xml = GatewayXml.BuildOutgoingMessage("+420603123456", "A & B ", true, sendAt); + + Assert.StartsWith("", root.Element("text")?.Value); + Assert.Equal("+420603123456", root.Element("recipient")?.Value); + Assert.Equal("20261021080000", root.Element("send_at")?.Value); + } + + [Fact] + public void BuildOutgoingMessage_WithoutOptionalValues_OmitsElements() + { + var root = XDocument.Parse(GatewayXml.BuildOutgoingMessage("603123456", "Test", null, null)).Root!; + + Assert.Null(root.Element("dr_request")); + Assert.Null(root.Element("send_at")); + } + + [Fact] + public void BuildOutgoingMessage_DeliveryReportFalse_WritesZero() + { + var root = XDocument.Parse(GatewayXml.BuildOutgoingMessage("603123456", "Test", false, null)).Root!; + + Assert.Equal("0", root.Element("dr_request")?.Value); + } + + [Fact] + public void ParseSendResult_ReadsAllFields() + { + var document = XDocument.Parse(""" + + + + 420777123456-20080404153039854 + text zpravy + 20080404153038 + +420777123456 + 1 + 0.80 + + 168.85 + + """); + + var result = GatewayXml.ParseSendResult(document); + + Assert.Equal("420777123456-20080404153039854", result.Id); + Assert.Equal("+420777123456", result.Recipient); + Assert.Equal(new DateTimeOffset(2008, 4, 4, 13, 30, 38, TimeSpan.Zero), result.SendAt); + Assert.Equal(1, result.Parts); + Assert.Equal(0.80m, result.Price); + Assert.Equal(168.85m, result.Credit); + } + + [Fact] + public void ParseSendResult_WithoutId_ThrowsInvalidResponse() + { + var document = XDocument.Parse("1"); + + var ex = Assert.Throws(() => GatewayXml.ParseSendResult(document)); + Assert.Equal(GatewayErrorKind.InvalidResponse, ex.Kind); + } + + [Fact] + public void ParseEvents_ReadsAllTypesAndSkipsUnknown() + { + var document = XDocument.Parse(""" + + + incoming_message + in-1 + dotaz + 20260120072542 + +420777123456 + 5517 + + + answer_message + in-2 + ANO + 20260120072542 + out-1 + +420777123456 + 5517 + + + delivery_report + out-1 + 20260120114428 + 0 + Doručeno + + + gate_outgoing_message + out-2 + z portalu + 20260120065600 + +420777123456 + + + api_outgoing_message + out-3 + z api + 20260120065600 + +420777123456 + + + something_new + x-1 + + + """); + + var parsed = GatewayXml.ParseEvents(document); + + Assert.Equal(5, parsed.Events.Count); + var incoming = Assert.IsType(parsed.Events[0]); + Assert.Equal("+420777123456", incoming.From); + Assert.Equal("5517", incoming.To); + Assert.Equal(new DateTimeOffset(2026, 1, 20, 6, 25, 42, TimeSpan.Zero), incoming.SentAt); + + var answer = Assert.IsType(parsed.Events[1]); + Assert.Equal("out-1", answer.InReplyTo); + + var report = Assert.IsType(parsed.Events[2]); + Assert.Equal("out-1", report.MessageId); + Assert.Equal(0, report.Status); + Assert.Equal("Doručeno", report.Description); + + Assert.Equal("portal", Assert.IsType(parsed.Events[3]).Source); + Assert.Equal("api", Assert.IsType(parsed.Events[4]).Source); + Assert.Equal(new[] { "something_new" }, parsed.SkippedTypes); + } + + [Fact] + public void ParseEvents_EmptyDocument_ReturnsNoEvents() + { + var parsed = GatewayXml.ParseEvents(XDocument.Parse("")); + + Assert.Empty(parsed.Events); + } + + [Fact] + public void ParseCredit_ReadsAllPrices() + { + var document = XDocument.Parse(""" + + 454.17 + 0.68 + 0.78 + 1.80 + + """); + + var credit = GatewayXml.ParseCredit(document); + + Assert.Equal(new CreditResponse(454.17m, 0.68m, 0.78m, 1.80m), credit); + } + + [Fact] + public void TryParse_NonXml_ReturnsNull() + { + Assert.Null(GatewayXml.TryParse("Bad gateway")); + } + + [Fact] + public void TryParse_Dtd_IsRejected() + { + Assert.Null(GatewayXml.TryParse("]>&a;")); + } +} diff --git a/tests/SmsSluzba.Api.Tests/Logging/LogMaskTests.cs b/tests/SmsSluzba.Api.Tests/Logging/LogMaskTests.cs new file mode 100644 index 0000000..930aff3 --- /dev/null +++ b/tests/SmsSluzba.Api.Tests/Logging/LogMaskTests.cs @@ -0,0 +1,24 @@ +using SmsSluzba.Api.Logging; + +namespace SmsSluzba.Api.Tests.Logging; + +public class LogMaskTests +{ + [Fact] + public void Url_MasksPassword() + { + var masked = LogMask.Url(new Uri("https://gate.example/apixml30/sender?login=a&password=tajne%26heslo&count=30")); + + Assert.Equal("https://gate.example/apixml30/sender?login=a&password=***&count=30", masked); + } + + [Theory] + [InlineData("+420724123234", "+420724***234")] + [InlineData("724123234", "724***234")] + [InlineData("5517", "***")] + [InlineData(null, "")] + public void Phone_KeepsPrefixAndSuffix(string? number, string expected) + { + Assert.Equal(expected, LogMask.Phone(number)); + } +} diff --git a/tests/SmsSluzba.Api.Tests/Messages/SmsTextTests.cs b/tests/SmsSluzba.Api.Tests/Messages/SmsTextTests.cs new file mode 100644 index 0000000..b93d9ee --- /dev/null +++ b/tests/SmsSluzba.Api.Tests/Messages/SmsTextTests.cs @@ -0,0 +1,22 @@ +using SmsSluzba.Api.Messages; + +namespace SmsSluzba.Api.Tests.Messages; + +public class SmsTextTests +{ + [Theory] + [InlineData("Ahoj", 4)] + [InlineData("Příliš žluťoučký", 16)] + [InlineData("Cena 10 €", 10)] + [InlineData("[a]{b}", 10)] + public void CountLength_CountsExtensionCharactersTwice(string text, int expected) + { + Assert.Equal(expected, SmsText.CountLength(text)); + } + + [Fact] + public void CountLength_MaximumText_FitsLimit() + { + Assert.Equal(SmsText.MaxLength, SmsText.CountLength(new string('a', SmsText.MaxLength))); + } +} diff --git a/tests/SmsSluzba.Api.Tests/SmsSluzba.Api.Tests.csproj b/tests/SmsSluzba.Api.Tests/SmsSluzba.Api.Tests.csproj new file mode 100644 index 0000000..f991e84 --- /dev/null +++ b/tests/SmsSluzba.Api.Tests/SmsSluzba.Api.Tests.csproj @@ -0,0 +1,21 @@ + + + false + true + + + + + + + + + + + + + + + + + diff --git a/tests/SmsSluzba.Api.Tests/packages.lock.json b/tests/SmsSluzba.Api.Tests/packages.lock.json new file mode 100644 index 0000000..595ae90 --- /dev/null +++ b/tests/SmsSluzba.Api.Tests/packages.lock.json @@ -0,0 +1,430 @@ +{ + "version": 2, + "dependencies": { + "net10.0": { + "Microsoft.AspNetCore.Mvc.Testing": { + "type": "Direct", + "requested": "[10.0.13, )", + "resolved": "10.0.13", + "contentHash": "AiQkwLuYCtZoWD1lm6ll/tqVf+u1GVdVJw+EEBQnCOgdofcwpMCnZ6h8HEwD04rOdmF1v+pVfGzr9HFCmq3zdw==", + "dependencies": { + "Microsoft.AspNetCore.TestHost": "10.0.13", + "Microsoft.Extensions.DependencyModel": "10.0.13", + "Microsoft.Extensions.Hosting": "10.0.13" + } + }, + "Microsoft.NET.Test.Sdk": { + "type": "Direct", + "requested": "[17.14.1, )", + "resolved": "17.14.1", + "contentHash": "HJKqKOE+vshXra2aEHpi2TlxYX7Z9VFYkr+E5rwEvHC8eIXiyO+K9kNm8vmNom3e2rA56WqxU+/N9NJlLGXsJQ==", + "dependencies": { + "Microsoft.CodeCoverage": "17.14.1", + "Microsoft.TestPlatform.TestHost": "17.14.1" + } + }, + "xunit": { + "type": "Direct", + "requested": "[2.9.3, )", + "resolved": "2.9.3", + "contentHash": "TlXQBinK35LpOPKHAqbLY4xlEen9TBafjs0V5KnA4wZsoQLQJiirCR4CbIXvOH8NzkW4YeJKP5P/Bnrodm0h9Q==", + "dependencies": { + "xunit.analyzers": "1.18.0", + "xunit.assert": "2.9.3", + "xunit.core": "[2.9.3]" + } + }, + "xunit.runner.visualstudio": { + "type": "Direct", + "requested": "[3.1.4, )", + "resolved": "3.1.4", + "contentHash": "5mj99LvCqrq3CNi06xYdyIAXOEh+5b33F2nErCzI5zWiDdLHXiPXEWFSUAF8zlIv0ZWqjZNCwHTQeAPYbF3pCg==" + }, + "Microsoft.AspNetCore.TestHost": { + "type": "Transitive", + "resolved": "10.0.13", + "contentHash": "8xzbDfEOWg5GRp5byA42Axr4TbockbxCvdHTYk27ZIdst79DO0CLBp/Zw5sduK2goRii7of4EeuTjG/yPH4tsg==" + }, + "Microsoft.CodeCoverage": { + "type": "Transitive", + "resolved": "17.14.1", + "contentHash": "pmTrhfFIoplzFVbhVwUquT+77CbGH+h4/3mBpdmIlYtBi9nAB+kKI6dN3A/nV4DFi3wLLx/BlHIPK+MkbQ6Tpg==" + }, + "Microsoft.Extensions.Configuration": { + "type": "Transitive", + "resolved": "10.0.13", + "contentHash": "inhujYI/nikhmLxYI6ZEcaCgZ28ipJsKMPPxxr2XWf3vM0Q2P+E9R3hDHABZOLBxzD3gjpgcbSH/+hd2+gvI2A==", + "dependencies": { + "Microsoft.Extensions.Configuration.Abstractions": "10.0.13", + "Microsoft.Extensions.Primitives": "10.0.13" + } + }, + "Microsoft.Extensions.Configuration.Abstractions": { + "type": "Transitive", + "resolved": "10.0.13", + "contentHash": "DY4C2qzTt2lOIY3VoscBH/TCwTolI5DKOfgJLuI+k1QUvRNT5vTMS58AOerNiihdVRStO0wEpLeRWA8jytzHBQ==", + "dependencies": { + "Microsoft.Extensions.Primitives": "10.0.13" + } + }, + "Microsoft.Extensions.Configuration.Binder": { + "type": "Transitive", + "resolved": "10.0.13", + "contentHash": "yJJl/b0+W+GEWbu+7viw6C3h2BoNkB69Vlz7s/4e+hm4mYbJqfhdcDSi9sCXJw47blsBaiQd3UDPgDtop92+ug==", + "dependencies": { + "Microsoft.Extensions.Configuration": "10.0.13", + "Microsoft.Extensions.Configuration.Abstractions": "10.0.13" + } + }, + "Microsoft.Extensions.Configuration.CommandLine": { + "type": "Transitive", + "resolved": "10.0.13", + "contentHash": "RwdNZ9JdGs8eZmeL5qRe7ugp0Irk3KVkWpC/w1c8kjJwu1R4HvCXYz9kwHZxn45WiaRBG5lphQKtqnBaJOQC+Q==", + "dependencies": { + "Microsoft.Extensions.Configuration": "10.0.13", + "Microsoft.Extensions.Configuration.Abstractions": "10.0.13" + } + }, + "Microsoft.Extensions.Configuration.EnvironmentVariables": { + "type": "Transitive", + "resolved": "10.0.13", + "contentHash": "qJK2dm9/AxyPVfqqBaZtjkUFl2hnBR/CQnMJtSO5LdEoyATMqvZjeQVY+8l0oa6PM6qlVe28iMEyXIRQ0wyZjA==", + "dependencies": { + "Microsoft.Extensions.Configuration": "10.0.13", + "Microsoft.Extensions.Configuration.Abstractions": "10.0.13" + } + }, + "Microsoft.Extensions.Configuration.FileExtensions": { + "type": "Transitive", + "resolved": "10.0.13", + "contentHash": "kwC1DY55CsqPmDtJAz+7alD3G+gJcM+XwHSZrcRO8mJGYB9hRq1qC6ZH8DL0SPW9WtJ/Bae5ikzPic8SxSv6Vw==", + "dependencies": { + "Microsoft.Extensions.Configuration": "10.0.13", + "Microsoft.Extensions.Configuration.Abstractions": "10.0.13", + "Microsoft.Extensions.FileProviders.Abstractions": "10.0.13", + "Microsoft.Extensions.FileProviders.Physical": "10.0.13", + "Microsoft.Extensions.Primitives": "10.0.13" + } + }, + "Microsoft.Extensions.Configuration.Json": { + "type": "Transitive", + "resolved": "10.0.13", + "contentHash": "acCWM2+WR67kBAz6gAhD2zG+IZH9Q2VpKv5le7Msiu0vAMsnnLXpnV3BAzxd8/i+uOEo/dfb2XRYTynRVTDvEg==", + "dependencies": { + "Microsoft.Extensions.Configuration": "10.0.13", + "Microsoft.Extensions.Configuration.Abstractions": "10.0.13", + "Microsoft.Extensions.Configuration.FileExtensions": "10.0.13", + "Microsoft.Extensions.FileProviders.Abstractions": "10.0.13" + } + }, + "Microsoft.Extensions.Configuration.UserSecrets": { + "type": "Transitive", + "resolved": "10.0.13", + "contentHash": "kQ/Tx972unP+ueQL8SSninthIj6w6XP2o0VnJPFC5HQIimPMwEN704MOspEgDkmm4FUL5SuxLEU0bNiW4HEZFA==", + "dependencies": { + "Microsoft.Extensions.Configuration.Abstractions": "10.0.13", + "Microsoft.Extensions.Configuration.Json": "10.0.13", + "Microsoft.Extensions.FileProviders.Abstractions": "10.0.13", + "Microsoft.Extensions.FileProviders.Physical": "10.0.13" + } + }, + "Microsoft.Extensions.DependencyInjection": { + "type": "Transitive", + "resolved": "10.0.13", + "contentHash": "4tnWU9vrU/A8NwYe9Z6wvieZ0EBb/uM82LAT+edNhdepOBWREZ7M7mzb941EIDPJaeOFdbVrDd5+7s9e89U6bQ==", + "dependencies": { + "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.13" + } + }, + "Microsoft.Extensions.DependencyInjection.Abstractions": { + "type": "Transitive", + "resolved": "10.0.13", + "contentHash": "G2GrGWNAPZBsii2F6AU8n+JT2tC1/I0Ml/e9ZyNCgPjf3hZqronP7o0X91aAynCmVeae8KkSIUNXXeXCNRmdVQ==" + }, + "Microsoft.Extensions.DependencyModel": { + "type": "Transitive", + "resolved": "10.0.13", + "contentHash": "6TyllZsToy3S/Ziu67GddljRTttuVJ8bbrbVUrsdHqH5678Oax5MpaEubxLoPoWLvgUBYo4KfcAig0mkBtktXQ==" + }, + "Microsoft.Extensions.Diagnostics": { + "type": "Transitive", + "resolved": "10.0.13", + "contentHash": "J9ODOrffj1mK3Et69elNsLGRguesPxvThTdVpFmQX7fLNPhIOgqHQfLdGnTBEwNAV3yf8yiyVlpDZNw2qN87Nw==", + "dependencies": { + "Microsoft.Extensions.Configuration": "10.0.13", + "Microsoft.Extensions.Diagnostics.Abstractions": "10.0.13", + "Microsoft.Extensions.Options.ConfigurationExtensions": "10.0.13" + } + }, + "Microsoft.Extensions.Diagnostics.Abstractions": { + "type": "Transitive", + "resolved": "10.0.13", + "contentHash": "oZzqZze8ed1fLS20HtIrkPxQXGRG/koq09srIw2ptnDHm9RHfwB++d35hosB/cXc55TH7Pshv85O0txongjCIg==", + "dependencies": { + "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.13", + "Microsoft.Extensions.Options": "10.0.13" + } + }, + "Microsoft.Extensions.FileProviders.Abstractions": { + "type": "Transitive", + "resolved": "10.0.13", + "contentHash": "BZDwtN3uoWRghDi5lRRZPDjMMCg2Ds7J6YEYjqka/TLjqnzquEpXyvchrIMeoubwT1ns23ow6PPeAoBHJO81Rw==", + "dependencies": { + "Microsoft.Extensions.Primitives": "10.0.13" + } + }, + "Microsoft.Extensions.FileProviders.Physical": { + "type": "Transitive", + "resolved": "10.0.13", + "contentHash": "U7HkgGCNPICN5k7NVK6dmLsSPSPeO/EbNcuxOl/5qdC9Ahjp9UZWKOvlnUC+rYurmoxIlwyv9e5j0BaQlTOELA==", + "dependencies": { + "Microsoft.Extensions.FileProviders.Abstractions": "10.0.13", + "Microsoft.Extensions.FileSystemGlobbing": "10.0.13", + "Microsoft.Extensions.Primitives": "10.0.13" + } + }, + "Microsoft.Extensions.FileSystemGlobbing": { + "type": "Transitive", + "resolved": "10.0.13", + "contentHash": "vQVzmAbnzlhXSXA2caYnlxtG9GXxEwtj5bODiWLu06A6iqeJmfBtlfKjuOSJGRy0/CFaNUrm7u9nxEUlljc2Rg==" + }, + "Microsoft.Extensions.Hosting": { + "type": "Transitive", + "resolved": "10.0.13", + "contentHash": "Q+hmPoDqeHipHyJcY7mDCQiLDUcn9jIgjoCThcgaOgjLTTT3ApTe8p6M2+twsDyfKuuCsKhSNlnNjaaggtXxRA==", + "dependencies": { + "Microsoft.Extensions.Configuration": "10.0.13", + "Microsoft.Extensions.Configuration.Abstractions": "10.0.13", + "Microsoft.Extensions.Configuration.Binder": "10.0.13", + "Microsoft.Extensions.Configuration.CommandLine": "10.0.13", + "Microsoft.Extensions.Configuration.EnvironmentVariables": "10.0.13", + "Microsoft.Extensions.Configuration.FileExtensions": "10.0.13", + "Microsoft.Extensions.Configuration.Json": "10.0.13", + "Microsoft.Extensions.Configuration.UserSecrets": "10.0.13", + "Microsoft.Extensions.DependencyInjection": "10.0.13", + "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.13", + "Microsoft.Extensions.Diagnostics": "10.0.13", + "Microsoft.Extensions.FileProviders.Abstractions": "10.0.13", + "Microsoft.Extensions.FileProviders.Physical": "10.0.13", + "Microsoft.Extensions.Hosting.Abstractions": "10.0.13", + "Microsoft.Extensions.Logging": "10.0.13", + "Microsoft.Extensions.Logging.Abstractions": "10.0.13", + "Microsoft.Extensions.Logging.Configuration": "10.0.13", + "Microsoft.Extensions.Logging.Console": "10.0.13", + "Microsoft.Extensions.Logging.Debug": "10.0.13", + "Microsoft.Extensions.Logging.EventLog": "10.0.13", + "Microsoft.Extensions.Logging.EventSource": "10.0.13", + "Microsoft.Extensions.Options": "10.0.13" + } + }, + "Microsoft.Extensions.Hosting.Abstractions": { + "type": "Transitive", + "resolved": "10.0.13", + "contentHash": "zIrbe9vkIFXxW3mOApIOWXw+xMwX7Cgsptr3ZSlglJt4hW2qp4fB/JU1NHgAevteBNH4PicvU9DsFPHxlnnloA==", + "dependencies": { + "Microsoft.Extensions.Configuration.Abstractions": "10.0.13", + "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.13", + "Microsoft.Extensions.Diagnostics.Abstractions": "10.0.13", + "Microsoft.Extensions.FileProviders.Abstractions": "10.0.13", + "Microsoft.Extensions.Logging.Abstractions": "10.0.13" + } + }, + "Microsoft.Extensions.Logging": { + "type": "Transitive", + "resolved": "10.0.13", + "contentHash": "fqbiPy4nUp4H2XHKAVQXKN2y3T2h4cFIx1DAAgE6iY9OHkN/OA1cKFi+geJKRWGuX6pS5SFbsjIPWHJqrxE0eg==", + "dependencies": { + "Microsoft.Extensions.DependencyInjection": "10.0.13", + "Microsoft.Extensions.Logging.Abstractions": "10.0.13", + "Microsoft.Extensions.Options": "10.0.13" + } + }, + "Microsoft.Extensions.Logging.Abstractions": { + "type": "Transitive", + "resolved": "10.0.13", + "contentHash": "aSZEhEig4fvNiw2zs8Z6NyDlniKtq6YjcF3DyHuqTEHcZ2VKA/6itMPZ+dW+yWABWExlDcQwwdbqX1Rcb7W8WQ==", + "dependencies": { + "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.13" + } + }, + "Microsoft.Extensions.Logging.Configuration": { + "type": "Transitive", + "resolved": "10.0.13", + "contentHash": "OyYJOaE9WbBx1Hp+Dd2zrqeFM0JwH5M/x0VL6tNUv3V18vIAVpix8UjhvY9eW/iXpguEHy68JO/Z9YkBOwftIw==", + "dependencies": { + "Microsoft.Extensions.Configuration": "10.0.13", + "Microsoft.Extensions.Configuration.Abstractions": "10.0.13", + "Microsoft.Extensions.Configuration.Binder": "10.0.13", + "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.13", + "Microsoft.Extensions.Logging": "10.0.13", + "Microsoft.Extensions.Logging.Abstractions": "10.0.13", + "Microsoft.Extensions.Options": "10.0.13", + "Microsoft.Extensions.Options.ConfigurationExtensions": "10.0.13" + } + }, + "Microsoft.Extensions.Logging.Console": { + "type": "Transitive", + "resolved": "10.0.13", + "contentHash": "i9rn0rHkiCxfNVbf4DRG7LOFcKPy/BioAxS07w6daWvIpLNRjskqDJcGGaYVFWndsq0iTRaS8Msry0t5fRYQug==", + "dependencies": { + "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.13", + "Microsoft.Extensions.Logging": "10.0.13", + "Microsoft.Extensions.Logging.Abstractions": "10.0.13", + "Microsoft.Extensions.Logging.Configuration": "10.0.13", + "Microsoft.Extensions.Options": "10.0.13" + } + }, + "Microsoft.Extensions.Logging.Debug": { + "type": "Transitive", + "resolved": "10.0.13", + "contentHash": "yBig0DNMq+3UgliwxYlUC48dg0fPqvqI5B3ljzmLTrpR6maoKTOO5i9QnPgQUmQoaQWZMgu74fuF6oSDihb6pg==", + "dependencies": { + "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.13", + "Microsoft.Extensions.Logging": "10.0.13", + "Microsoft.Extensions.Logging.Abstractions": "10.0.13" + } + }, + "Microsoft.Extensions.Logging.EventLog": { + "type": "Transitive", + "resolved": "10.0.13", + "contentHash": "OAK40lXhgMuvyNwvzW3fxLvvucN8yr5XS7dQRcPmtnPf+Pt1lpbMgao5T4Wa6VdFagtIeDZNgPtV5Ig4xstziQ==", + "dependencies": { + "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.13", + "Microsoft.Extensions.Logging": "10.0.13", + "Microsoft.Extensions.Logging.Abstractions": "10.0.13", + "Microsoft.Extensions.Options": "10.0.13", + "System.Diagnostics.EventLog": "10.0.13" + } + }, + "Microsoft.Extensions.Logging.EventSource": { + "type": "Transitive", + "resolved": "10.0.13", + "contentHash": "SxJu3oczk+TJtHvpgAmCVzEkzx69/obA6GZCbGrbqYqc981YOAyfEprySBdFX7Yc5qatHJKHNTlpGeeBAQkZcA==", + "dependencies": { + "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.13", + "Microsoft.Extensions.Logging": "10.0.13", + "Microsoft.Extensions.Logging.Abstractions": "10.0.13", + "Microsoft.Extensions.Options": "10.0.13", + "Microsoft.Extensions.Primitives": "10.0.13" + } + }, + "Microsoft.Extensions.Options": { + "type": "Transitive", + "resolved": "10.0.13", + "contentHash": "tmMJgdrE4uhf1JcNs9CV9moAHW+hmDuvgMiPpnQxarKaUxqI2eN33sYK5S4l9Uw+rG9PJvlm4qPxMhvolTDTaQ==", + "dependencies": { + "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.13", + "Microsoft.Extensions.Primitives": "10.0.13" + } + }, + "Microsoft.Extensions.Options.ConfigurationExtensions": { + "type": "Transitive", + "resolved": "10.0.13", + "contentHash": "xVO5HhATc09WXuS/RaDmx8ZeWS0mTpT1L0tkEDMSBHtAnNpNsDr0ge0wIO2jinCWWqpq5dL1tRTzpYNVlvyqLw==", + "dependencies": { + "Microsoft.Extensions.Configuration.Abstractions": "10.0.13", + "Microsoft.Extensions.Configuration.Binder": "10.0.13", + "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.13", + "Microsoft.Extensions.Options": "10.0.13", + "Microsoft.Extensions.Primitives": "10.0.13" + } + }, + "Microsoft.Extensions.Primitives": { + "type": "Transitive", + "resolved": "10.0.13", + "contentHash": "ZjTwxzhiw2TMEzIbUDkMF0dfDB2I4NQgIfKD0ELu9/5Mk+SRGdKZcD0/lvBrRCAPo6KN2r0BW86MRancoyJkoA==" + }, + "Microsoft.OpenApi": { + "type": "Transitive", + "resolved": "2.12.2", + "contentHash": "ZkT7qiJe0Kj0+DTZOZo+xrDy1kNmdsWFQVPIQLNx9ZJ0T9cB2LG7r+Bi60so8/+yg1nkS7QCPadrzsTG4VPKrA==" + }, + "Microsoft.TestPlatform.ObjectModel": { + "type": "Transitive", + "resolved": "17.14.1", + "contentHash": "xTP1W6Mi6SWmuxd3a+jj9G9UoC850WGwZUps1Wah9r1ZxgXhdJfj1QqDLJkFjHDCvN42qDL2Ps5KjQYWUU0zcQ==" + }, + "Microsoft.TestPlatform.TestHost": { + "type": "Transitive", + "resolved": "17.14.1", + "contentHash": "d78LPzGKkJwsJXAQwsbJJ7LE7D1wB+rAyhHHAaODF+RDSQ0NgMjDFkSA1Djw18VrxO76GlKAjRUhl+H8NL8Z+Q==", + "dependencies": { + "Microsoft.TestPlatform.ObjectModel": "17.14.1", + "Newtonsoft.Json": "13.0.3" + } + }, + "Newtonsoft.Json": { + "type": "Transitive", + "resolved": "13.0.3", + "contentHash": "HrC5BXdl00IP9zeV+0Z848QWPAoCr9P3bDEZguI+gkLcBKAOxix/tLEAAHC+UvDNPv4a2d18lOReHMOagPa+zQ==" + }, + "System.Diagnostics.EventLog": { + "type": "Transitive", + "resolved": "10.0.13", + "contentHash": "DkNjtQyPR5Ud/zHnWHdsOuKbFRL9nIC92Q76z0NmHVDoQm40toLtsGFTIWq7toBoVa6fo/DInL3PLxY3Asixyw==" + }, + "xunit.abstractions": { + "type": "Transitive", + "resolved": "2.0.3", + "contentHash": "pot1I4YOxlWjIb5jmwvvQNbTrZ3lJQ+jUGkGjWE3hEFM0l5gOnBWS+H3qsex68s5cO52g+44vpGzhAt+42vwKg==" + }, + "xunit.analyzers": { + "type": "Transitive", + "resolved": "1.18.0", + "contentHash": "OtFMHN8yqIcYP9wcVIgJrq01AfTxijjAqVDy/WeQVSyrDC1RzBWeQPztL49DN2syXRah8TYnfvk035s7L95EZQ==" + }, + "xunit.assert": { + "type": "Transitive", + "resolved": "2.9.3", + "contentHash": "/Kq28fCE7MjOV42YLVRAJzRF0WmEqsmflm0cfpMjGtzQ2lR5mYVj1/i0Y8uDAOLczkL3/jArrwehfMD0YogMAA==" + }, + "xunit.core": { + "type": "Transitive", + "resolved": "2.9.3", + "contentHash": "BiAEvqGvyme19wE0wTKdADH+NloYqikiU0mcnmiNyXaF9HyHmE6sr/3DC5vnBkgsWaE6yPyWszKSPSApWdRVeQ==", + "dependencies": { + "xunit.extensibility.core": "[2.9.3]", + "xunit.extensibility.execution": "[2.9.3]" + } + }, + "xunit.extensibility.core": { + "type": "Transitive", + "resolved": "2.9.3", + "contentHash": "kf3si0YTn2a8J8eZNb+zFpwfoyvIrQ7ivNk5ZYA5yuYk1bEtMe4DxJ2CF/qsRgmEnDr7MnW1mxylBaHTZ4qErA==", + "dependencies": { + "xunit.abstractions": "2.0.3" + } + }, + "xunit.extensibility.execution": { + "type": "Transitive", + "resolved": "2.9.3", + "contentHash": "yMb6vMESlSrE3Wfj7V6cjQ3S4TXdXpRqYeNEI3zsX31uTsGMJjEw6oD5F5u1cHnMptjhEECnmZSsPxB6ChZHDQ==", + "dependencies": { + "xunit.extensibility.core": "[2.9.3]" + } + }, + "smssluzba.api": { + "type": "Project", + "dependencies": { + "Microsoft.AspNetCore.OpenApi": "[10.0.13, )", + "Swashbuckle.AspNetCore.SwaggerUI": "[9.0.6, )" + } + }, + "Microsoft.AspNetCore.OpenApi": { + "type": "CentralTransitive", + "requested": "[10.0.13, )", + "resolved": "10.0.13", + "contentHash": "XVuqUBGjVUVyb4DXR5BrSkrW0Br7sYKq39f723ILhQLlFHCyhAgWe1PkJBc42R/5mKBIgHiKVSY+PN5/4XtcQw==", + "dependencies": { + "Microsoft.OpenApi": "[2.12.2, 3.0.0)" + } + }, + "Swashbuckle.AspNetCore.SwaggerUI": { + "type": "CentralTransitive", + "requested": "[9.0.6, )", + "resolved": "9.0.6", + "contentHash": "WGsw/Yop9b16miq8TQd4THxuEgkP5cH3+DX93BrX9m0OdPcKNtg2nNm77WQSAsA+Se+M0bTiu8bUyrruRSeS5g==" + } + } + } +} \ No newline at end of file