Oprava nasazení: služba startuje bez konfigurace, přihlášení přes hlavičky
Služba padala při startu kvůli povinným SMSSLUZBA_LOGIN, SMSSLUZBA_PASSWORD a API_KEYS, proto v AppFactory nefungovalo /health ani /docs (502). - vlastní API klíče služby zrušeny, login a heslo API přístupu SMS-Služby posílá každá aplikace v hlavičkách X-Sms-Login a X-Sms-Password - všechna konfigurace je volitelná, neplatná hodnota jen zaloguje varování - po odmítnutí přihlášení se blokují jen ty konkrétní údaje - Swagger: Authorize pro obě hlavičky, relativní server i bez ROOT_PATH - návod pro napojení aplikací a dokumentace podle nového přihlášení
This commit is contained in:
@@ -29,8 +29,7 @@ public sealed class ApiTests : IDisposable
|
||||
public ApiTests()
|
||||
{
|
||||
_factory = new SmsApiFactory(_gateway);
|
||||
_client = _factory.CreateClient();
|
||||
_client.DefaultRequestHeaders.Add("X-Api-Key", SmsApiFactory.ApiKey);
|
||||
_client = CreateClient(SmsApiFactory.Login, SmsApiFactory.Password);
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
@@ -41,7 +40,7 @@ public sealed class ApiTests : IDisposable
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Health_WithoutApiKey_ReturnsOk()
|
||||
public async Task Health_WithoutAnyConfiguration_ReturnsOk()
|
||||
{
|
||||
using var anonymous = _factory.CreateClient();
|
||||
|
||||
@@ -52,20 +51,19 @@ public sealed class ApiTests : IDisposable
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task V1_WithWrongApiKey_Returns401WithCode()
|
||||
public async Task V1_WithoutCredentials_Returns401WithoutGatewayCall()
|
||||
{
|
||||
using var anonymous = _factory.CreateClient();
|
||||
anonymous.DefaultRequestHeaders.Add("X-Api-Key", "wrong");
|
||||
|
||||
var response = await anonymous.GetAsync(new Uri("/v1/account/credit", UriKind.Relative));
|
||||
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
Assert.Equal("unauthorized", (await ReadJson(response)).GetProperty("code").GetString());
|
||||
Assert.Equal("missing_credentials", (await ReadJson(response)).GetProperty("code").GetString());
|
||||
Assert.Empty(_gateway.Requests);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SendMessage_Success_ReturnsGatewayResultAndSendsXml()
|
||||
public async Task SendMessage_Success_ForwardsCallerCredentialsAndXml()
|
||||
{
|
||||
_gateway.Enqueue(SendSuccessXml);
|
||||
|
||||
@@ -79,8 +77,9 @@ public sealed class ApiTests : IDisposable
|
||||
Assert.Equal(453.49m, json.GetProperty("credit").GetDecimal());
|
||||
|
||||
var (uri, body) = Assert.Single(_gateway.Requests);
|
||||
Assert.EndsWith("/apixml30/receiver", uri.AbsolutePath, StringComparison.Ordinal);
|
||||
Assert.Contains("password=" + SmsApiFactory.GatewayPassword, uri.Query, StringComparison.Ordinal);
|
||||
Assert.Equal("/apixml30/receiver", uri.AbsolutePath);
|
||||
Assert.Contains("login=" + SmsApiFactory.Login, uri.Query, StringComparison.Ordinal);
|
||||
Assert.Contains("password=" + SmsApiFactory.Password, uri.Query, StringComparison.Ordinal);
|
||||
var sent = XDocument.Parse(body!).Root!;
|
||||
Assert.Equal("Test & co", sent.Element("text")?.Value);
|
||||
Assert.Equal("20", sent.Element("dr_request")?.Value);
|
||||
@@ -132,19 +131,22 @@ public sealed class ApiTests : IDisposable
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AuthFailure_StopsAllFurtherGatewayCalls()
|
||||
public async Task RejectedCredentials_AreNotSentAgain_OtherCredentialsStillWork()
|
||||
{
|
||||
_gateway.Enqueue("<status><id>401</id><message>Chybne prihlaseni</message></status>");
|
||||
_gateway.Enqueue("<info><credit>1</credit><price_cz_sms>1</price_cz_sms><price_sk_sms>1</price_sk_sms><price_other_sms>1</price_other_sms></info>");
|
||||
using var other = CreateClient("cms-login", "cms-password");
|
||||
|
||||
var first = await _client.PostAsJsonAsync("/v1/messages", new { to = "+420603123456", text = "Test" });
|
||||
var first = await _client.GetAsync(new Uri("/v1/account/credit", UriKind.Relative));
|
||||
var second = await _client.GetAsync(new Uri("/v1/account/credit", UriKind.Relative));
|
||||
var health = await ReadJson(await _client.GetAsync(new Uri("/health", UriKind.Relative)));
|
||||
var otherApp = await other.GetAsync(new Uri("/v1/account/credit", UriKind.Relative));
|
||||
|
||||
Assert.Equal(HttpStatusCode.ServiceUnavailable, first.StatusCode);
|
||||
Assert.Equal(HttpStatusCode.ServiceUnavailable, second.StatusCode);
|
||||
Assert.Equal("provider_auth_blocked", (await ReadJson(second)).GetProperty("code").GetString());
|
||||
Assert.Equal("blocked", health.GetProperty("gateway").GetString());
|
||||
Assert.Single(_gateway.Requests);
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, first.StatusCode);
|
||||
Assert.Equal("invalid_credentials", (await ReadJson(first)).GetProperty("code").GetString());
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, second.StatusCode);
|
||||
Assert.Equal(HttpStatusCode.OK, otherApp.StatusCode);
|
||||
Assert.Equal(2, _gateway.Requests.Count);
|
||||
Assert.Contains("login=cms-login", _gateway.Requests[1].Uri.Query, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -218,15 +220,17 @@ public sealed class ApiTests : IDisposable
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task OpenApi_DescribesApiKeyAndRelativeServer()
|
||||
public async Task OpenApi_DescribesCredentialHeadersAndRelativeServer()
|
||||
{
|
||||
var json = await ReadJson(await _client.GetAsync(new Uri("/openapi/v1.json", UriKind.Relative)));
|
||||
|
||||
Assert.Equal("/", json.GetProperty("servers")[0].GetProperty("url").GetString());
|
||||
var scheme = json.GetProperty("components").GetProperty("securitySchemes").GetProperty("ApiKey");
|
||||
Assert.Equal("X-Api-Key", scheme.GetProperty("name").GetString());
|
||||
var send = json.GetProperty("paths").GetProperty("/v1/messages").GetProperty("post");
|
||||
Assert.True(send.GetProperty("security")[0].TryGetProperty("ApiKey", out _));
|
||||
Assert.Equal("..", json.GetProperty("servers")[0].GetProperty("url").GetString());
|
||||
var schemes = json.GetProperty("components").GetProperty("securitySchemes");
|
||||
Assert.Equal("X-Sms-Login", schemes.GetProperty("SmsLogin").GetProperty("name").GetString());
|
||||
Assert.Equal("X-Sms-Password", schemes.GetProperty("SmsPassword").GetProperty("name").GetString());
|
||||
var requirement = json.GetProperty("paths").GetProperty("/v1/messages").GetProperty("post").GetProperty("security")[0];
|
||||
Assert.True(requirement.TryGetProperty("SmsLogin", out _));
|
||||
Assert.True(requirement.TryGetProperty("SmsPassword", out _));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -240,6 +244,14 @@ public sealed class ApiTests : IDisposable
|
||||
Assert.Equal("docs/index.html", response.Headers.Location?.OriginalString);
|
||||
}
|
||||
|
||||
private HttpClient CreateClient(string login, string password)
|
||||
{
|
||||
var client = _factory.CreateClient();
|
||||
client.DefaultRequestHeaders.Add("X-Sms-Login", login);
|
||||
client.DefaultRequestHeaders.Add("X-Sms-Password", password);
|
||||
return client;
|
||||
}
|
||||
|
||||
private static async Task<JsonElement> ReadJson(HttpResponseMessage response) =>
|
||||
JsonDocument.Parse(await response.Content.ReadAsStringAsync()).RootElement.Clone();
|
||||
}
|
||||
|
||||
@@ -2,22 +2,17 @@ using Microsoft.AspNetCore.Hosting;
|
||||
using Microsoft.AspNetCore.Mvc.Testing;
|
||||
using Microsoft.AspNetCore.TestHost;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using SmsSluzba.Api.Config;
|
||||
using SmsSluzba.Api.Gateway;
|
||||
|
||||
namespace SmsSluzba.Api.Tests.Api;
|
||||
|
||||
/// <summary>Runs the service without any configuration, exactly as a fresh AppFactory container does.</summary>
|
||||
internal sealed class SmsApiFactory(FakeGatewayHandler gateway) : WebApplicationFactory<Program>
|
||||
{
|
||||
public const string ApiKey = "test-key-eshop";
|
||||
public const string GatewayPassword = "gateway-password";
|
||||
public const string Login = "eshop-login";
|
||||
public const string Password = "eshop-password";
|
||||
|
||||
protected override void ConfigureWebHost(IWebHostBuilder builder)
|
||||
{
|
||||
builder.UseSetting(AppSettingsLoader.LoginKey, "gateway-login");
|
||||
builder.UseSetting(AppSettingsLoader.PasswordKey, GatewayPassword);
|
||||
builder.UseSetting(AppSettingsLoader.ApiKeysKey, "eshop=" + ApiKey);
|
||||
protected override void ConfigureWebHost(IWebHostBuilder builder) =>
|
||||
builder.ConfigureTestServices(services =>
|
||||
services.AddHttpClient<SmsGatewayClient>().ConfigurePrimaryHttpMessageHandler(() => gateway));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,61 +6,36 @@ namespace SmsSluzba.Api.Tests.Config;
|
||||
public class AppSettingsLoaderTests
|
||||
{
|
||||
[Fact]
|
||||
public void Load_ValidConfiguration_AppliesDefaultsAndNormalizesRootPath()
|
||||
public void Load_EmptyConfiguration_UsesDefaults()
|
||||
{
|
||||
var settings = AppSettingsLoader.Load(Build(new()));
|
||||
|
||||
Assert.Null(settings.RootPath);
|
||||
Assert.Equal(new Uri("https://smsgateapi.sms-sluzba.cz/apixml30/"), settings.Gateway.BaseUrl);
|
||||
Assert.Equal(TimeSpan.FromSeconds(30), settings.Gateway.Timeout);
|
||||
Assert.Empty(settings.Warnings);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Load_RootPath_IsNormalized()
|
||||
{
|
||||
var settings = AppSettingsLoader.Load(Build(new() { ["ROOT_PATH"] = "apps/sms-sluzba/" }));
|
||||
|
||||
Assert.Equal("/apps/sms-sluzba", settings.RootPath);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Load_InvalidOptionalValues_FallBackToDefaultsWithWarnings()
|
||||
{
|
||||
var settings = AppSettingsLoader.Load(Build(new()
|
||||
{
|
||||
["ROOT_PATH"] = "apps/sms-sluzba/",
|
||||
["SMSSLUZBA_LOGIN"] = "login",
|
||||
["SMSSLUZBA_PASSWORD"] = "password",
|
||||
["API_KEYS"] = "eshop=key-one; cms=key-two",
|
||||
["SMSSLUZBA_BASE_URL"] = "http://example.com/",
|
||||
["SMSSLUZBA_TIMEOUT_SECONDS"] = "abc",
|
||||
}));
|
||||
|
||||
Assert.Equal("/apps/sms-sluzba", settings.RootPath);
|
||||
Assert.Equal(new Uri("https://smsgateapi.sms-sluzba.cz/apixml30/"), settings.Gateway.BaseUrl);
|
||||
Assert.Equal(TimeSpan.FromSeconds(30), settings.Gateway.Timeout);
|
||||
Assert.Equal(new[] { "eshop", "cms" }, settings.ApiClients.Select(c => c.Name));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Load_InvalidConfiguration_ListsProblemsWithoutSecretValues()
|
||||
{
|
||||
var ex = Assert.Throws<InvalidOperationException>(() => 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<InvalidOperationException>(() => 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<InvalidOperationException>(() => AppSettingsLoader.Load(Build(new()
|
||||
{
|
||||
["SMSSLUZBA_LOGIN"] = "login",
|
||||
["SMSSLUZBA_PASSWORD"] = "password",
|
||||
["SMSSLUZBA_BASE_URL"] = "http://example.com/",
|
||||
["API_KEYS"] = "eshop=key",
|
||||
})));
|
||||
Assert.Equal(2, settings.Warnings.Count);
|
||||
}
|
||||
|
||||
private static IConfiguration Build(Dictionary<string, string?> values) =>
|
||||
|
||||
Reference in New Issue
Block a user