Path: redb-route/redb.Route.Http/HttpEndpointOptions.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Http/HttpEndpointOptions.cs
----
using redb.Route.Abstractions;
using redb.Route.Core;
namespace redb.Route.Http;
///
/// Options for the HTTP endpoint. Shared by both producer and consumer.
/// Use URI parameters to configure: http:host:port/path?method=POST&timeout=30000
///
[LenientProperties]
public class HttpEndpointOptions : EndpointOptions
{
// ── Common ──────────────────────────────────────────
/// HTTP method. Default: GET for producer, all methods accepted for consumer.
public HttpMethod Method { get; set; } = HttpMethod.GET;
/// Request/response timeout in milliseconds. Default: 30000 (30s). Producer only.
public int Timeout { get; set; } = 30_000;
/// Content-Type header value for outgoing requests/responses. Default: application/json.
public string ContentType { get; set; } = "application/json";
// ── Producer (HttpClient) ───────────────────────────
/// Throw an exception on HTTP 4xx/5xx responses. Default: true.
public bool ThrowOnError { get; set; } = true;
///
/// Do not map the exchange headers to request headers at all; only the fields the producer sets itself go out.
/// Default: false. Apache Camel's skipRequestHeaders.
///
[EndpointRole(EndpointRole.Producer)]
public bool SkipRequestHeaders { get; set; }
///
/// Do not let the control headers on the exchange — redbHttp.Method, redbHttp.Query — steer the
/// request; the endpoint's own options decide. Default: false. Set it on a producer whose exchange may carry
/// headers of other hops (a message received from a broker keeps every header it came with). Apache Camel's
/// skipControlHeaders.
///
[EndpointRole(EndpointRole.Producer)]
public bool SkipControlHeaders { get; set; }
///
/// A registry reference (#name) to an that decides
/// which headers this endpoint carries, in place of : the request and
/// response headers of a producer, the request and response headers of a consumer. The protocol fields
/// () and, on a consumer, received redbHttp.* and response-only
/// fields are never carried, whatever the strategy says.
///
[RegistryReference(typeof(IHeaderFilterStrategy))]
public string? HeaderFilterStrategy { get; set; }
/// Authentication scheme. Default: None.
[EndpointRole(EndpointRole.Producer)]
public HttpAuthScheme AuthScheme { get; set; } = HttpAuthScheme.None;
/// Username for Basic auth.
[EndpointRole(EndpointRole.Producer)]
public string? Username { get; set; }
/// Password for Basic auth.
[Sensitive]
[EndpointRole(EndpointRole.Producer)]
public string? Password { get; set; }
/// Bearer token value (or expression) for Bearer auth.
[Sensitive]
[EndpointRole(EndpointRole.Producer)]
public DynamicValue? AuthToken { get; set; }
// ── Inbound authentication (consumer only) ──
///
/// Consumer only: how an inbound request proves who it is. Basic checks the Authorization header
/// against / ; Bearer hands the token to the
/// named by . A refused request gets 401 with
/// WWW-Authenticate and never reaches the route. Default None.
///
[EndpointRole(EndpointRole.Consumer)]
public HttpAuthScheme InboundAuth { get; set; } = HttpAuthScheme.None;
/// Consumer only: the user name inboundAuth=basic accepts.
[EndpointRole(EndpointRole.Consumer)]
public string? InboundUsername { get; set; }
/// Consumer only: the password inboundAuth=basic accepts. Take it from configuration ({{…}}).
[Sensitive]
[EndpointRole(EndpointRole.Consumer)]
public string? InboundPassword { get; set; }
/// Consumer only: the realm named in WWW-Authenticate. Default redb.
[EndpointRole(EndpointRole.Consumer)]
public string InboundRealm { get; set; } = "redb";
/// Consumer only: registry name of the for inboundAuth=bearer, #name or name.
[EndpointRole(EndpointRole.Consumer)]
[RegistryReference(typeof(IHttpTokenValidator))]
public string? TokenValidator { get; set; }
///
/// Named from the route registry. Lets Basic/Bearer
/// credentials and the TLS certificate password live in the registry instead of the endpoint
/// URI, so they never reach logs or dashboards.
///
[RegistryReference(typeof(HttpConnectionFactory))]
public string? ConnectionFactory { get; set; }
/// Follow HTTP redirects. Default: true.
public bool FollowRedirects { get; set; } = true;
/// Maximum number of automatic redirects. Default: 50.
public int MaxRedirects { get; set; } = 50;
///
/// Do not map the response headers to exchange headers; the status, URL and content type are still set.
/// Default: false. Apache Camel's skipResponseHeaders.
///
[EndpointRole(EndpointRole.Producer)]
public bool SkipResponseHeaders { get; set; }
/// Preserve the Host header from the original request. Default: false.
public bool PreserveHostHeader { get; set; }
// ── Consumer (Kestrel) ──────────────────────────────
/// Bind host for the embedded HTTP server. Default: 0.0.0.0.
public string Host { get; set; } = "0.0.0.0";
/// Bind port for the embedded HTTP server. Default: 8080.
public int Port { get; set; } = 8080;
///
/// Comma-separated list of allowed HTTP methods for the consumer.
/// Default: empty (all methods accepted).
/// Example: "POST,PUT"
///
public string? Methods { get; set; }
/// Enable CORS for all origins. Default: false.
public bool Cors { get; set; }
///
/// CORS allowed origins (comma-separated). Default: * when CORS is enabled.
/// Example: "https://example.com,https://app.example.com"
/// NOTE: browsers do NOT understand a comma-separated Access-Control-Allow-Origin
/// header. When this property contains multiple origins, the consumer middleware will echo
/// back the request's Origin header IF it appears in the list, otherwise the request
/// is treated as not allowed (no CORS headers emitted, browser preflight fails).
/// For multi-origin scenarios prefer for full control.
///
public string? CorsOrigins { get; set; }
///
/// Optional per-request CORS-origin resolver. When set, takes precedence over
/// . The delegate receives the incoming
/// and returns either:
///
/// - a specific origin string (e.g. "https://app.example.com") — echoed back
/// in Access-Control-Allow-Origin;
/// - "*" — wildcard (browsers reject this combination with credentials);
/// - null — origin not allowed; no CORS headers will be emitted.
///
/// The delegate must be cheap and thread-safe; it runs on every CORS-eligible request.
/// Cannot be configured via URI parameters; set this in DI via the global
/// or programmatically on the endpoint options.
///
public Func? CorsOriginsResolver { get; set; }
///
/// Enable Access-Control-Allow-Credentials header. Default: false.
/// When true, the resolved origin must be a specific value (not *) — browsers reject
/// the combination. The runtime middleware enforces this regardless of how the origin was
/// resolved (static or ).
///
public bool CorsCredentials { get; set; }
/// Maximum request body size in bytes. Default: 10 MB (10485760). 0 = unlimited.
public long MaxRequestBodySize { get; set; } = 10 * 1024 * 1024;
// ── Admission limit (HTTP_CONCURRENCY_LIMITS_PLAN) ──
///
/// Maximum concurrent executions of this consumer's pipeline. 0 (default) = unlimited —
/// Kestrel runs as many as requests arrive. Overflow beyond the limit and
/// is shed with before any
/// pipeline work (load shedding, not backpressure).
///
public int MaxConcurrentRequests { get; set; }
///
/// How many requests over the limit WAIT for a permit (FIFO) instead of being rejected.
/// 0 (default) = reject immediately once the permits are taken.
///
public int RequestQueueLimit { get; set; }
/// Status code for a shed request. Default 429 Too Many Requests.
public int RejectStatusCode { get; set; } = 429;
/// Value of the Retry-After header on a shed request; 0 = do not send it. Default 1.
public int RetryAfterSeconds { get; set; } = 1;
/// HTTP protocol version for the consumer. Default: Http1And2.
public HttpProtocol Protocol { get; set; } = HttpProtocol.Http1And2;
/// Enable HTTPS for the consumer. Default: false.
public bool Ssl { get; set; }
/// Path to PFX certificate file for HTTPS. Required when ssl=true.
public string? SslCertPath { get; set; }
/// Password for the PFX certificate.
[Sensitive]
public string? SslCertPassword { get; set; }
///
/// Response status code for successful processing. Default: 200.
///
public int ResponseCode { get; set; } = 200;
///
/// If true, the consumer returns the exchange Out body as the HTTP response (InOut pattern).
/// If false, returns an empty 200 OK (InOnly pattern). Default: false.
///
public bool InOut { get; set; }
///
/// If true, enables streaming of request body instead of buffering.
/// Useful for large payloads. Default: false.
///
public bool StreamRequest { get; set; }
///
/// If true, the producer sets the exchange Out body to a Stream instead of byte[].
/// The stream is closed automatically by Exchange.DisposeAsync(). Default: false.
///
public bool StreamResponse { get; set; }
// ── Named Parameters ────────────────────────────────────────────
private IReadOnlyDictionary? _explicitParameters;
///
/// Named parameter bindings from .Param() calls.
/// Extracted from URI parameters with param. prefix.
/// Used to resolve {name} placeholders in the URL path at runtime.
/// Values may contain ${...} expressions resolved before substitution.
///
internal IReadOnlyDictionary ExplicitParameters =>
_explicitParameters ??= ParseExplicitParameters();
private IReadOnlyDictionary ParseExplicitParameters()
{
var dict = new Dictionary(StringComparer.OrdinalIgnoreCase);
foreach (var (key, value) in UnmappedParameters)
{
if (key.StartsWith("param.", StringComparison.OrdinalIgnoreCase))
dict[key["param.".Length..]] = value;
}
return dict;
}
/// Inbound authentication must be complete and unambiguous: a half-declared check would look closed and be open.
private void ValidateInboundAuth()
{
switch (InboundAuth)
{
case HttpAuthScheme.None:
if (InboundUsername is not null || InboundPassword is not null || TokenValidator is not null)
throw new ArgumentException(
"inboundUsername, inboundPassword and tokenValidator take effect only with inboundAuth=basic or " +
"inboundAuth=bearer; without it the endpoint would accept every caller while looking protected.");
break;
case HttpAuthScheme.Basic:
if (string.IsNullOrEmpty(InboundUsername) || string.IsNullOrEmpty(InboundPassword))
throw new ArgumentException("inboundAuth=basic needs inboundUsername and inboundPassword.");
if (TokenValidator is not null)
throw new ArgumentException("tokenValidator checks bearer tokens; inboundAuth=basic does not use it.");
break;
case HttpAuthScheme.Bearer:
if (string.IsNullOrWhiteSpace(TokenValidator))
throw new ArgumentException("inboundAuth=bearer needs tokenValidator=#name, a registered IHttpTokenValidator.");
if (InboundUsername is not null || InboundPassword is not null)
throw new ArgumentException("inboundUsername and inboundPassword belong to inboundAuth=basic.");
break;
}
// The realm is written into a quoted-string of WWW-Authenticate.
if (string.IsNullOrEmpty(InboundRealm) || InboundRealm.Any(c => c is '"' or '\\' || char.IsControl(c)))
throw new ArgumentException("inboundRealm must be non-empty, without quotes, backslashes or control characters.");
}
///
/// Options renamed to Apache Camel's names, with the meaning reversed. The HTTP options take parameters they have
/// no property for (), so an old name would be dropped without a word and
/// its endpoint would quietly do the opposite of what it says: it is refused instead.
///
private static readonly Dictionary RenamedOptions = new(StringComparer.OrdinalIgnoreCase)
{
["bridgeHeaders"] = "'bridgeHeaders' is replaced by Apache Camel's 'skipRequestHeaders', with the meaning reversed: " +
"bridgeHeaders=false is skipRequestHeaders=true; bridgeHeaders=true is the default and needs no option.",
["copyResponseHeaders"] = "'copyResponseHeaders' is replaced by Apache Camel's 'skipResponseHeaders', with the meaning " +
"reversed: copyResponseHeaders=false is skipResponseHeaders=true; copyResponseHeaders=true " +
"is the default and needs no option.",
};
///
public override void Validate()
{
foreach (var key in UnmappedParameters.Keys)
{
if (RenamedOptions.TryGetValue(key, out var replacement))
throw new ArgumentException(replacement, key);
}
if (Timeout < 0)
throw new ArgumentException("Timeout must be >= 0.");
if (Port is < 0 or > 65535)
throw new ArgumentException("Port must be between 0 and 65535.");
if (MaxRedirects < 0)
throw new ArgumentException("MaxRedirects must be >= 0.");
if (MaxRequestBodySize < 0)
throw new ArgumentException("MaxRequestBodySize must be >= 0.");
ConcurrencyLimitOptions.ValidateShape(MaxConcurrentRequests, RequestQueueLimit, RejectStatusCode, RetryAfterSeconds);
if (ResponseCode is < 100 or > 599)
throw new ArgumentException("ResponseCode must be between 100 and 599.");
if (AuthScheme == HttpAuthScheme.Basic && (string.IsNullOrEmpty(Username) || string.IsNullOrEmpty(Password)))
throw new ArgumentException("Username and Password are required when AuthScheme=Basic.");
ValidateInboundAuth();
// No SslCertPath check here on purpose. The certificate may legitimately come from a named
// connection factory or from the host default (HttpHostingOptions.Tls), the way a Camel
// endpoint resolves from global SSLContextParameters. The invariant "TLS asked for and no
// certificate resolves" is enforced once, at the bind, by SharedHttpServerManager — the
// only place that can see all three sources.
// CORS configuration must be explicit. When Cors=true, the caller MUST supply either
// a static whitelist (CorsOrigins, including "*" for public endpoints) or a resolver
// (CorsOriginsResolver). The legacy implicit "*" fallback is a footgun that browsers
// silently downgrade in combination with credentials, so we surface the misconfiguration
// at startup instead.
if (Cors && string.IsNullOrEmpty(CorsOrigins) && CorsOriginsResolver is null)
throw new ArgumentException(
"Cors=true requires CorsOrigins (use \"*\" for public endpoints) or CorsOriginsResolver to be set.");
// CorsCredentials + wildcard guard: only enforceable at config time when no resolver
// is set. With a resolver, the same constraint is enforced per-request inside the
// CORS middleware (see HttpConsumer.Start) — the resolver may legitimately return a
// specific origin even when CorsOrigins is null/empty.
if (CorsCredentials && CorsOriginsResolver is null && string.IsNullOrEmpty(CorsOrigins))
throw new ArgumentException("CorsOrigins or CorsOriginsResolver must be set when CorsCredentials=true (wildcard * is not allowed by browsers in combination with credentials).");
}
}