cc nasazeni
This commit is contained in:
@@ -0,0 +1,54 @@
|
||||
using Microsoft.OpenApi.Any;
|
||||
using Microsoft.OpenApi.Models;
|
||||
using Swashbuckle.AspNetCore.SwaggerGen;
|
||||
using Idoklad.Controllers;
|
||||
using Idoklad.Credentials;
|
||||
|
||||
namespace Idoklad.Infrastructure;
|
||||
|
||||
/// <summary>
|
||||
/// Documents the per-request credential headers in Swagger for every operation that talks to
|
||||
/// iDoklad. The headers are marked optional because the service can fall back to environment
|
||||
/// defaults, but the description makes the requirement and secret handling explicit.
|
||||
/// </summary>
|
||||
public sealed class CredentialHeadersOperationFilter : IOperationFilter
|
||||
{
|
||||
public void Apply(OpenApiOperation operation, OperationFilterContext context)
|
||||
{
|
||||
// Metadata endpoints (health/version/status) do not talk to iDoklad and need no credentials.
|
||||
if (context.MethodInfo.DeclaringType == typeof(MetaController))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
operation.Parameters ??= new List<OpenApiParameter>();
|
||||
|
||||
AddHeader(operation, CredentialConstants.ClientIdHeader,
|
||||
"iDoklad OAuth2 ClientId (client credentials flow). Overrides the IDOKLAD_CLIENT_ID environment default. Required if no environment default is configured.");
|
||||
|
||||
AddHeader(operation, CredentialConstants.ClientSecretHeader,
|
||||
"iDoklad OAuth2 ClientSecret (SENSITIVE). Must be sent in this header over TLS only — never in the URL or body. Overrides the IDOKLAD_CLIENT_SECRET environment default. Required if no environment default is configured.");
|
||||
|
||||
AddHeader(operation, CredentialConstants.ApplicationIdHeader,
|
||||
"iDoklad ApplicationId from the developer portal. Overrides the IDOKLAD_APPLICATION_ID environment default. Required by the client credentials flow if no environment default is configured.");
|
||||
|
||||
AddHeader(operation, CredentialConstants.LanguageHeader,
|
||||
"Optional response language override for the iDoklad API: Cz, Sk or En.", example: "Cz");
|
||||
}
|
||||
|
||||
private static void AddHeader(OpenApiOperation operation, string name, string description, string? example = null)
|
||||
{
|
||||
operation.Parameters.Add(new OpenApiParameter
|
||||
{
|
||||
Name = name,
|
||||
In = ParameterLocation.Header,
|
||||
Required = false,
|
||||
Description = description,
|
||||
Schema = new OpenApiSchema
|
||||
{
|
||||
Type = "string",
|
||||
Example = example is null ? null : new OpenApiString(example),
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
using System.Net;
|
||||
using IdokladSdk.Exceptions;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Idoklad.Client;
|
||||
using Idoklad.Credentials;
|
||||
|
||||
namespace Idoklad.Infrastructure;
|
||||
|
||||
/// <summary>
|
||||
/// Translates domain exceptions into JSON <see cref="ProblemDetails"/> responses:
|
||||
/// missing credentials become 401, and upstream iDoklad failures surface the upstream status.
|
||||
/// </summary>
|
||||
public sealed class ExceptionHandlingMiddleware
|
||||
{
|
||||
private readonly RequestDelegate _next;
|
||||
private readonly ILogger<ExceptionHandlingMiddleware> _logger;
|
||||
|
||||
public ExceptionHandlingMiddleware(RequestDelegate next, ILogger<ExceptionHandlingMiddleware> logger)
|
||||
{
|
||||
_next = next;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
public async Task InvokeAsync(HttpContext context)
|
||||
{
|
||||
try
|
||||
{
|
||||
await _next(context);
|
||||
}
|
||||
catch (MissingCredentialsException ex)
|
||||
{
|
||||
await WriteProblem(context, HttpStatusCode.Unauthorized, ex.Message, new Dictionary<string, object?>
|
||||
{
|
||||
["missingHeaders"] = ex.MissingHeaders,
|
||||
});
|
||||
}
|
||||
catch (IdokladApiException ex)
|
||||
{
|
||||
// Never log decoded credentials; only the upstream status and message.
|
||||
_logger.LogWarning("iDoklad API call failed: {Status} {ErrorCode} {Message}", ex.StatusCode, ex.ErrorCode, ex.Message);
|
||||
await WriteProblem(context, ex.StatusCode, ex.Message, new Dictionary<string, object?>
|
||||
{
|
||||
["idokladErrorCode"] = ex.ErrorCode.ToString(),
|
||||
});
|
||||
}
|
||||
catch (IdokladAuthenticationException ex)
|
||||
{
|
||||
// OAuth2 token acquisition failed (bad client id/secret/application id).
|
||||
_logger.LogWarning("iDoklad authentication failed: {Error}", ex.AuthenticationError?.Error ?? ex.Message);
|
||||
await WriteProblem(context, HttpStatusCode.Unauthorized, ex.AuthenticationError?.ErrorDescription ?? ex.Message, new Dictionary<string, object?>
|
||||
{
|
||||
["idokladError"] = ex.AuthenticationError?.Error,
|
||||
});
|
||||
}
|
||||
catch (IdokladBaseException ex)
|
||||
{
|
||||
// Other SDK-level failures (malformed responses, batch errors, etc.).
|
||||
_logger.LogWarning("iDoklad SDK error: {Message}", ex.Message);
|
||||
await WriteProblem(context, HttpStatusCode.BadGateway, ex.Message, null);
|
||||
}
|
||||
catch (HttpRequestException ex)
|
||||
{
|
||||
// The iDoklad API / identity server is unreachable.
|
||||
_logger.LogWarning(ex, "iDoklad API unreachable.");
|
||||
await WriteProblem(context, HttpStatusCode.BadGateway, "iDoklad API is unreachable.", null);
|
||||
}
|
||||
catch (ArgumentException ex)
|
||||
{
|
||||
// Thrown by the SDK when required credential fields are blank/invalid.
|
||||
await WriteProblem(context, HttpStatusCode.BadRequest, ex.Message, null);
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task WriteProblem(HttpContext context, HttpStatusCode status, string detail, IDictionary<string, object?>? extensions)
|
||||
{
|
||||
if (context.Response.HasStarted)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var problem = new ProblemDetails
|
||||
{
|
||||
Status = (int)status,
|
||||
Title = ReasonPhrase(status),
|
||||
Detail = detail,
|
||||
};
|
||||
|
||||
if (extensions is not null)
|
||||
{
|
||||
foreach (var (key, value) in extensions)
|
||||
{
|
||||
problem.Extensions[key] = value;
|
||||
}
|
||||
}
|
||||
|
||||
context.Response.Clear();
|
||||
context.Response.StatusCode = (int)status;
|
||||
context.Response.ContentType = "application/problem+json";
|
||||
await context.Response.WriteAsJsonAsync(problem);
|
||||
}
|
||||
|
||||
private static string ReasonPhrase(HttpStatusCode status) => status switch
|
||||
{
|
||||
HttpStatusCode.Unauthorized => "Unauthorized",
|
||||
HttpStatusCode.BadRequest => "Bad Request",
|
||||
HttpStatusCode.BadGateway => "Upstream iDoklad API error",
|
||||
_ => status.ToString(),
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user