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:
JiriUhlir
2026-10-20 10:47:17 +02:00
parent 63547942af
commit 295edb1bd1
25 changed files with 351 additions and 404 deletions
@@ -1,3 +1,4 @@
using SmsSluzba.Api.Auth;
using SmsSluzba.Api.Contracts;
using SmsSluzba.Api.Gateway;
@@ -14,12 +15,14 @@ internal static class AccountEndpoints
.Produces<CreditResponse>()
.ProducesProblem(StatusCodes.Status401Unauthorized)
.ProducesProblem(StatusCodes.Status502BadGateway)
.ProducesProblem(StatusCodes.Status503ServiceUnavailable)
.ProducesProblem(StatusCodes.Status504GatewayTimeout);
return group;
}
private static Task<IResult> GetCreditAsync(SmsGatewayClient gateway, CancellationToken ct) =>
GatewayProblems.RunAsync(async () => Results.Ok(await gateway.GetCreditAsync(ct)));
private static Task<IResult> GetCreditAsync(SmsGatewayClient gateway, HttpContext httpContext, CancellationToken ct)
{
var credentials = GatewayCredentialsFilter.Get(httpContext);
return GatewayProblems.RunAsync(async () => Results.Ok(await gateway.GetCreditAsync(credentials, ct)));
}
}
+17 -6
View File
@@ -1,3 +1,4 @@
using SmsSluzba.Api.Auth;
using SmsSluzba.Api.Contracts;
using SmsSluzba.Api.Gateway;
using SmsSluzba.Api.Problems;
@@ -17,12 +18,11 @@ internal static class EventEndpoints
.WithName("GetEvents")
.WithTags(Tag)
.WithSummary("Příchozí SMS, odpovědi a doručenky")
.WithDescription("Brána vrací stejnou událost znovu, dokud ji nepotvrdíte přes POST /v1/events/confirm. Fronta je jedna pro celý účet, události má stahovat jen jedna aplikace.")
.WithDescription("Brána vrací stejnou událost znovu, dokud ji nepotvrdíte přes POST /v1/events/confirm. Fronta je jedna pro každý API přístup.")
.Produces<EventsResponse>()
.ProducesProblem(StatusCodes.Status400BadRequest)
.ProducesProblem(StatusCodes.Status401Unauthorized)
.ProducesProblem(StatusCodes.Status502BadGateway)
.ProducesProblem(StatusCodes.Status503ServiceUnavailable)
.ProducesProblem(StatusCodes.Status504GatewayTimeout);
group.MapPost("/events/confirm", ConfirmAsync)
@@ -36,7 +36,12 @@ internal static class EventEndpoints
return group;
}
private static async Task<IResult> GetEventsAsync(string? types, int? count, SmsGatewayClient gateway, CancellationToken ct)
private static async Task<IResult> GetEventsAsync(
string? types,
int? count,
SmsGatewayClient gateway,
HttpContext httpContext,
CancellationToken ct)
{
var query = GatewayEventQuery.Parse(types);
if (query is null)
@@ -51,11 +56,16 @@ internal static class EventEndpoints
return ApiProblems.Validation($"Parametr 'count' musí být 1 až {MaxBatchSize}.");
}
var credentials = GatewayCredentialsFilter.Get(httpContext);
return await GatewayProblems.RunAsync(async () =>
Results.Ok(new EventsResponse(await gateway.GetEventsAsync(query, size, ct))));
Results.Ok(new EventsResponse(await gateway.GetEventsAsync(credentials, query, size, ct))));
}
private static async Task<IResult> ConfirmAsync(ConfirmEventsRequest request, SmsGatewayClient gateway, CancellationToken ct)
private static async Task<IResult> ConfirmAsync(
ConfirmEventsRequest request,
SmsGatewayClient gateway,
HttpContext httpContext,
CancellationToken ct)
{
if (request.Events is not { Count: > 0 } events)
{
@@ -80,13 +90,14 @@ internal static class EventEndpoints
items.Add((item.Type, item.Id.Trim(), gatewayType));
}
var credentials = GatewayCredentialsFilter.Get(httpContext);
var confirmed = new List<ConfirmedEvent>();
var failed = new List<FailedEvent>();
foreach (var (type, id, gatewayType) in items)
{
try
{
await gateway.ConfirmAsync(gatewayType, id, ct);
await gateway.ConfirmAsync(credentials, gatewayType, id, ct);
confirmed.Add(new ConfirmedEvent(type, id));
}
catch (GatewayException ex)
@@ -12,7 +12,7 @@ internal static class GatewayProblems
GatewayErrorKind.InvalidRecipient => ApiErrors.InvalidRecipient,
GatewayErrorKind.MissingText => ApiErrors.MissingText,
GatewayErrorKind.Rejected => ApiErrors.ProviderRejected,
GatewayErrorKind.AuthFailed or GatewayErrorKind.AuthBlocked => ApiErrors.ProviderAuthBlocked,
GatewayErrorKind.AuthFailed or GatewayErrorKind.AuthBlocked => ApiErrors.InvalidCredentials,
GatewayErrorKind.InsufficientCredit => ApiErrors.InsufficientCredit,
GatewayErrorKind.Timeout => ApiErrors.ProviderTimeout,
_ => ApiErrors.ProviderUnavailable,
@@ -18,13 +18,12 @@ internal static class MessageEndpoints
.WithName("SendMessage")
.WithTags(Tag)
.WithSummary("Odešle SMS")
.WithDescription("Každé úspěšné volání odešle a zaplatí jednu SMS. Po chybě 502 nebo 504 je stav neznámý, odeslání neopakujte automaticky.")
.WithDescription("Každé úspěšné volání odešle a zaplatí jednu SMS. Po chybě 500, 502 nebo 504 je stav neznámý, odeslání neopakujte automaticky.")
.Produces<SendMessageResponse>()
.ProducesProblem(StatusCodes.Status400BadRequest)
.ProducesProblem(StatusCodes.Status401Unauthorized)
.ProducesProblem(StatusCodes.Status402PaymentRequired)
.ProducesProblem(StatusCodes.Status502BadGateway)
.ProducesProblem(StatusCodes.Status503ServiceUnavailable)
.ProducesProblem(StatusCodes.Status504GatewayTimeout);
group.MapGet("/messages/{id}/delivery-report", GetDeliveryReportAsync)
@@ -35,7 +34,6 @@ internal static class MessageEndpoints
.ProducesProblem(StatusCodes.Status401Unauthorized)
.ProducesProblem(StatusCodes.Status404NotFound)
.ProducesProblem(StatusCodes.Status502BadGateway)
.ProducesProblem(StatusCodes.Status503ServiceUnavailable)
.ProducesProblem(StatusCodes.Status504GatewayTimeout);
return group;
@@ -64,34 +62,39 @@ internal static class MessageEndpoints
return ApiProblems.Result(ApiErrors.TextTooLong, $"Text má {length} znaků, maximum je {SmsText.MaxLength}.");
}
var credentials = GatewayCredentialsFilter.Get(httpContext);
var recipient = request.To.Trim();
var client = ApiClientRegistry.GetCurrent(httpContext);
var logger = loggerFactory.CreateLogger(LoggerCategory);
return await GatewayProblems.RunAsync(async () =>
{
var result = await gateway.SendAsync(recipient, request.Text, request.DeliveryReport, request.SendAt, ct);
var result = await gateway.SendAsync(credentials, recipient, request.Text, request.DeliveryReport, request.SendAt, ct);
logger.LogInformation(
"SMS {MessageId} for {Recipient} accepted by gateway, client {Client}, parts {Parts}, price {Price}",
"SMS {MessageId} for {Recipient} accepted by gateway, login {Login}, parts {Parts}, price {Price}",
result.Id,
LogMask.Phone(recipient),
client,
credentials.Login,
result.Parts,
result.Price);
return Results.Ok(result);
});
}
private static async Task<IResult> GetDeliveryReportAsync(string id, SmsGatewayClient gateway, CancellationToken ct)
private static async Task<IResult> GetDeliveryReportAsync(
string id,
SmsGatewayClient gateway,
HttpContext httpContext,
CancellationToken ct)
{
if (string.IsNullOrWhiteSpace(id))
{
return ApiProblems.Validation("Chybí id zprávy.");
}
var credentials = GatewayCredentialsFilter.Get(httpContext);
return await GatewayProblems.RunAsync(async () =>
{
var report = await gateway.GetDeliveryReportAsync(id.Trim(), ct);
var report = await gateway.GetDeliveryReportAsync(credentials, id.Trim(), ct);
return report is null ? ApiProblems.Result(ApiErrors.DeliveryReportNotFound) : Results.Ok(report);
});
}
@@ -1,13 +1,9 @@
using SmsSluzba.Api.Contracts;
using SmsSluzba.Api.Gateway;
namespace SmsSluzba.Api.Endpoints;
internal static class SystemEndpoints
{
private const string GatewayOk = "ok";
private const string GatewayBlocked = "blocked";
public static IEndpointRouteBuilder MapSystemEndpoints(this IEndpointRouteBuilder app)
{
app.MapGet("/", () => Results.Json(new
@@ -18,10 +14,7 @@ internal static class SystemEndpoints
}))
.ExcludeFromDescription();
// Stays 200 even when the gateway login is blocked: a failing health check would make AppFactory
// restart the container, and every restart would try the wrong password again.
app.MapGet("/health", (GatewayAuthGuard authGuard) =>
Results.Ok(new HealthResponse("ok", authGuard.IsBlocked ? GatewayBlocked : GatewayOk)))
app.MapGet("/health", () => Results.Ok(new HealthResponse("ok")))
.WithName("Health")
.WithTags("Služba")
.WithSummary("Stav služby, nevolá SMS bránu")