From 485accc1e17420ae02310fe5ca864704599bd5af Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 28 Aug 2022 22:24:34 -0500 Subject: fix bug causing html to be injected in prometheus metrics --- .../Common/Middleware/HTMLInjectionMiddleware.cs | 25 +++++++++++++++++----- 1 file changed, 20 insertions(+), 5 deletions(-) (limited to 'src/slskd/Common/Middleware/HTMLInjectionMiddleware.cs') diff --git a/src/slskd/Common/Middleware/HTMLInjectionMiddleware.cs b/src/slskd/Common/Middleware/HTMLInjectionMiddleware.cs index 3e2c003a..5a073b54 100644 --- a/src/slskd/Common/Middleware/HTMLInjectionMiddleware.cs +++ b/src/slskd/Common/Middleware/HTMLInjectionMiddleware.cs @@ -18,6 +18,7 @@ namespace slskd { using System; + using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; @@ -34,8 +35,9 @@ namespace slskd /// /// /// + /// /// - public static IApplicationBuilder UseHTMLInjection(this IApplicationBuilder builder, string html) + public static IApplicationBuilder UseHTMLInjection(this IApplicationBuilder builder, string html, IEnumerable excludedRoutes) { return builder.UseMiddleware(html); } @@ -51,14 +53,17 @@ namespace slskd /// /// /// - public HTMLInjectionMiddleware(RequestDelegate next, string html) + /// + public HTMLInjectionMiddleware(RequestDelegate next, string html, IEnumerable excludedRoutes) { Next = next; HTML = html; + ExcludedRoutes = excludedRoutes; } private string HTML { get; } private RequestDelegate Next { get; } + private IEnumerable ExcludedRoutes { get; } /// /// Executes this middleware, returning the contents of the requested HTML file with the specified HTML appended. @@ -74,10 +79,10 @@ namespace slskd .Intersect(injectableTypes, StringComparer.InvariantCultureIgnoreCase) .Any(); - var isApiRoute = context.Request.Path.ToString().StartsWith("/api"); + var isExcludedRoute = ExcludedRoutes.Any(route => context.Request.Path.ToString().StartsWith(route)); var isGET = context.Request.Method == "GET"; - if (!isApiRoute && isGET && isInjectableType) + if (!isExcludedRoute && isGET && isInjectableType) { var originalStream = context.Response.Body; @@ -106,7 +111,17 @@ namespace slskd context.Response.Headers.Add(header); } - await context.Response.WriteAsync(body + HTML); + // check the response content type to make sure it's still injectable. the server might return something other + // than what was requested. if it's no longer injectable, don't inject. + var isInjectableResponseType = injectableTypes.Any(injectableType => context.Response.Headers.ContentType.Contains(injectableType)); + if (!isInjectableResponseType) + { + await context.Response.WriteAsync(body); + } + else + { + await context.Response.WriteAsync(body + HTML); + } } // rewind the stream we injected to the beginning, then replay the data to the -- cgit v1.2.3