first
This commit is contained in:
@@ -0,0 +1,70 @@
|
||||
using Microsoft.OpenApi.Any;
|
||||
using Microsoft.OpenApi.Models;
|
||||
using Swashbuckle.AspNetCore.SwaggerGen;
|
||||
using Csob.Controllers;
|
||||
using Csob.Credentials;
|
||||
|
||||
namespace Csob.Infrastructure;
|
||||
|
||||
/// <summary>
|
||||
/// Documents the per-request credential headers in Swagger. Metadata endpoints need none; the
|
||||
/// OAuth helper needs the certificate + client id/secret; every other (AISP/PISP/consent) endpoint
|
||||
/// needs the certificate + access token + API key + TPP name. Headers are marked optional at the
|
||||
/// schema level (the service validates them at runtime) but the descriptions state what is required.
|
||||
/// </summary>
|
||||
public sealed class CredentialHeadersOperationFilter : IOperationFilter
|
||||
{
|
||||
public void Apply(OpenApiOperation operation, OperationFilterContext context)
|
||||
{
|
||||
var declaringType = context.MethodInfo.DeclaringType;
|
||||
|
||||
// Metadata endpoints (health/version/status) do not talk to ČSOB.
|
||||
if (declaringType == typeof(MetaController))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
operation.Parameters ??= new List<OpenApiParameter>();
|
||||
|
||||
AddHeader(operation, CredentialConstants.CertificateHeader,
|
||||
"eIDAS client certificate (QWAC) as a Base64-encoded PFX/PKCS#12 bundle incl. private key and chain. Used for mutual TLS to ČSOB. SENSITIVE — TLS only.");
|
||||
AddHeader(operation, CredentialConstants.CertificatePasswordHeader,
|
||||
"Passphrase protecting the PFX in X-CSOB-Certificate (omit if the PFX has no password). SENSITIVE.");
|
||||
|
||||
if (declaringType == typeof(OAuthController))
|
||||
{
|
||||
AddHeader(operation, CredentialConstants.ClientIdHeader,
|
||||
"OAuth2 client id of the registered TPP application. Required.");
|
||||
AddHeader(operation, CredentialConstants.ClientSecretHeader,
|
||||
"OAuth2 client secret of the registered TPP application. Required for token/refresh. SENSITIVE.");
|
||||
return;
|
||||
}
|
||||
|
||||
AddHeader(operation, CredentialConstants.AccessTokenHeader,
|
||||
"OAuth2 Bearer access token obtained for the PSU. Forwarded as 'Authorization: Bearer'. Required. SENSITIVE.");
|
||||
AddHeader(operation, CredentialConstants.ApiKeyHeader,
|
||||
"ČSOB application API key. Forwarded as 'APIKEY'. Required.");
|
||||
AddHeader(operation, CredentialConstants.TppNameHeader,
|
||||
"TPP organisation name. Forwarded as 'TPP-Name'. Required.");
|
||||
AddHeader(operation, CredentialConstants.UserInvolvedHeader,
|
||||
"Optional. 'true' if the PSU is online for this request (forwarded as 'User-Involved'). Defaults to false.", example: "false");
|
||||
AddHeader(operation, CredentialConstants.UserIpAddressHeader,
|
||||
"Optional. PSU IP address (forwarded as 'User-IP-Address').");
|
||||
}
|
||||
|
||||
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,127 @@
|
||||
using System.Net;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text.Json.Nodes;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Csob.Client;
|
||||
using Csob.Credentials;
|
||||
|
||||
namespace Csob.Infrastructure;
|
||||
|
||||
/// <summary>
|
||||
/// Translates domain exceptions into JSON <see cref="ProblemDetails"/> responses. Credentials are
|
||||
/// never logged — only upstream status codes and error codes (the upstream's own payload). Errors
|
||||
/// are always logged (no silent failures).
|
||||
/// </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 (CryptographicException ex)
|
||||
{
|
||||
// Invalid Base64 PFX or wrong passphrase in the certificate header. Do not log the value.
|
||||
_logger.LogWarning("Client certificate could not be loaded: {Message}", ex.Message);
|
||||
await WriteProblem(context, HttpStatusCode.BadRequest,
|
||||
"The provided client certificate could not be loaded. Check X-CSOB-Certificate (Base64 PFX) and X-CSOB-Certificate-Password.", null);
|
||||
}
|
||||
catch (CsobApiException ex)
|
||||
{
|
||||
_logger.LogWarning("ČSOB PSD2 API call failed: {Status} {Codes}", (int)ex.StatusCode, string.Join(",", ex.ErrorCodes));
|
||||
await WriteProblem(context, ex.StatusCode, ex.Message, new Dictionary<string, object?>
|
||||
{
|
||||
["csobErrorCodes"] = ex.ErrorCodes,
|
||||
["upstreamBody"] = ParseBody(ex.RawBody),
|
||||
});
|
||||
}
|
||||
catch (TaskCanceledException) when (!context.RequestAborted.IsCancellationRequested)
|
||||
{
|
||||
_logger.LogWarning("ČSOB PSD2 API call timed out.");
|
||||
await WriteProblem(context, HttpStatusCode.GatewayTimeout, "The ČSOB PSD2 API did not respond in time.", null);
|
||||
}
|
||||
catch (HttpRequestException ex)
|
||||
{
|
||||
// Network failure, or the mutual-TLS handshake was rejected (e.g. wrong/expired eIDAS certificate).
|
||||
_logger.LogWarning(ex, "ČSOB PSD2 API unreachable or TLS handshake failed.");
|
||||
await WriteProblem(context, HttpStatusCode.BadGateway,
|
||||
"The ČSOB PSD2 API is unreachable or the mutual-TLS handshake failed.", null);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Unhandled error while processing the request.");
|
||||
await WriteProblem(context, HttpStatusCode.InternalServerError, "An unexpected error occurred.", null);
|
||||
}
|
||||
}
|
||||
|
||||
private static JsonNode? ParseBody(string? rawBody)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(rawBody))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
return JsonNode.Parse(rawBody);
|
||||
}
|
||||
catch (System.Text.Json.JsonException)
|
||||
{
|
||||
return JsonValue.Create(rawBody);
|
||||
}
|
||||
}
|
||||
|
||||
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 ČSOB PSD2 API error",
|
||||
HttpStatusCode.GatewayTimeout => "Upstream ČSOB PSD2 API timeout",
|
||||
_ => status.ToString(),
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user