Skip to content

Commit

Permalink
Disallow ambiguous matches in reverse proxy
Browse files Browse the repository at this point in the history
  • Loading branch information
serialseb committed Sep 15, 2023
1 parent ba06f2e commit a3b1159
Showing 1 changed file with 16 additions and 8 deletions.
24 changes: 16 additions & 8 deletions src/OpenRasta.Plugins.ReverseProxy/ReverseProxy.cs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,17 @@ public ReverseProxy(TimeSpan requestTimeout, bool convertForwardedHeaders, strin

public async Task<ReverseProxyResponse> Send(ICommunicationContext context, string target)
{
var proxyTargetUri = GetProxyTargetUri(context.PipelineData.SelectedResource.Results.Single(), target);
var resource = context.PipelineData.SelectedResource;

var matched = resource.Results.Where(uri => uri.ResourceModel.ResourceKey.Equals(resource.ResourceKey)).ToList();
var targetTemplate = new UriTemplate(target);
if (matched.Count > 1)
{
throw new InvalidOperationException("Found more than one destination URI template");
}

var baseUri = new Uri(new Uri(target), "/");
var proxyTargetUri = GetProxyTargetUri(matched[0], targetTemplate, baseUri);

var requestMessage = new HttpRequestMessage(new HttpMethod(context.Request.HttpMethod), proxyTargetUri)
{
Expand All @@ -48,14 +58,13 @@ public async Task<ReverseProxyResponse> Send(ICommunicationContext context, stri
var viaIdentifier = AppendViaHeaderToRequest(context, requestMessage);



var cts = new CancellationTokenSource();
cts.CancelAfter(_timeout);
var timeoutToken = cts.Token;


ReverseProxyResponse reverseProxyResponse;

try
{
_onSend?.Invoke(context, requestMessage);
Expand All @@ -75,7 +84,7 @@ public async Task<ReverseProxyResponse> Send(ICommunicationContext context, stri
}
catch (HttpRequestException e)
{
context.ServerErrors.Add(new Error {Exception = e, Title = $"Reverse Proxy failed to connect."});
context.ServerErrors.Add(new Error { Exception = e, Title = $"Reverse Proxy failed to connect." });
reverseProxyResponse = new ReverseProxyResponse(requestMessage, via: null, error: e, statusCode: 502);
}

Expand Down Expand Up @@ -162,15 +171,14 @@ void appendParameter(string key, string value)
request.Headers.Add("forwarded", CurrentForwarded(context));
}

static Uri GetProxyTargetUri(TemplatedUriMatch requestUriMatch, string target,
static Uri GetProxyTargetUri(TemplatedUriMatch requestUriMatch, UriTemplate targetTemplate,
Uri baseUri,
Action<UriBuilder> overrideUri = null)
{
var destinationBaseUri = new Uri(new Uri(target), "/");
var targetTemplate = new UriTemplate(target);
var requestQs = requestUriMatch;

var targetUri = targetTemplate.BindByName(
destinationBaseUri,
baseUri,
new NameValueCollection
{
requestQs.Match.PathSegmentVariables,
Expand Down

0 comments on commit a3b1159

Please sign in to comment.