SMS služba: prostředník nad SMS-Služba.cz (API XML 3.0)

- JSON API /v1: odeslání SMS, doručenka, události, potvrzení událostí, kredit
- vlastní API klíč pro každou aplikaci (X-Api-Key, API_KEYS)
- po chybě přihlášení k bráně se volání zastaví, aby se účet nezablokoval
- heslo maskované v logu, odeslání se nikdy neopakuje automaticky
- /health, /docs a OpenAPI s prefixem z ROOT_PATH
- .NET 10, šablona .NET 8 nahrazena projektem v src/, testy v tests/
- dokumentace: návrh, stav a návod pro napojení aplikací
This commit is contained in:
JiriUhlir
2026-10-20 10:21:03 +02:00
parent 908d6c9954
commit 63547942af
57 changed files with 3233 additions and 40 deletions
+245
View File
@@ -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 = """
<messages>
<message>
<id>420603123456-20261020120000123</id>
<text>Test</text>
<send_at>20261020120000</send_at>
<recipient>+420603123456</recipient>
<parts>1</parts>
<price>0.68</price>
</message>
<credit>453.49</credit>
</messages>
""";
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("<status><id>400;1</id><message>Chybne telefonni cislo 77716085</message></status>");
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("<status><id>401</id><message>Chybne prihlaseni</message></status>");
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("""
<messages>
<message><type>answer_message</type><id>in-2</id><text>ANO</text><in_reply_to>out-1</in_reply_to><sender>+420777123456</sender><recipient>5517</recipient></message>
<message><type>delivery_report</type><id>out-1</id><status>0</status><description>Doručeno</description></message>
</messages>
""");
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("<status><id>200</id><message>OK</message></status>");
_gateway.Enqueue("<status><id>503</id><message>Chyba brany</message></status>");
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("<messages />");
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<JsonElement> ReadJson(HttpResponseMessage response) =>
JsonDocument.Parse(await response.Content.ReadAsStringAsync()).RootElement.Clone();
}
@@ -0,0 +1,33 @@
using System.Net;
using System.Text;
namespace SmsSluzba.Api.Tests.Api;
/// <summary>Stands in for the SMS gateway: returns queued responses and records every request.</summary>
internal sealed class FakeGatewayHandler : HttpMessageHandler
{
private readonly Queue<Func<HttpResponseMessage>> _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<HttpResponseMessage> 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()();
}
}
@@ -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<Program>
{
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<SmsGatewayClient>().ConfigurePrimaryHttpMessageHandler(() => gateway));
}
}