diff options
| author | JP Dillingham <jpdillingham@gmail.com> | 2022-05-07 15:44:28 -0500 |
|---|---|---|
| committer | JP Dillingham <jpdillingham@gmail.com> | 2022-05-07 15:44:28 -0500 |
| commit | 35091805ce75a0d1a17d9a0c1d5faeea6be925fe (patch) | |
| tree | 0fa2b9a98bebca4aef355c4ac121f5a24b6c4614 /src/slskd | |
| parent | 581fa92428ec49f63421119a7bfcfef4e46df80a (diff) | |
| parent | b8f0e6f28ab3f189a47eb373b1efbb45abb9ccc8 (diff) | |
| download | slskd-35091805ce75a0d1a17d9a0c1d5faeea6be925fe.tar.gz | |
Merge remote-tracking branch 'origin/master' into search-list
Diffstat (limited to 'src/slskd')
| -rw-r--r-- | src/slskd/Common/Middleware/HTMLInjectionMiddleware.cs | 118 | ||||
| -rw-r--r-- | src/slskd/Common/Middleware/HTMLRewriteMiddleware.cs | 124 | ||||
| -rw-r--r-- | src/slskd/Common/Middleware/StrictUrlBaseMiddleware.cs | 80 | ||||
| -rw-r--r-- | src/slskd/Core/API/Controllers/ApplicationController.cs | 7 | ||||
| -rw-r--r-- | src/slskd/Options.cs | 1 | ||||
| -rw-r--r-- | src/slskd/Program.cs | 91 |
6 files changed, 367 insertions, 54 deletions
diff --git a/src/slskd/Common/Middleware/HTMLInjectionMiddleware.cs b/src/slskd/Common/Middleware/HTMLInjectionMiddleware.cs new file mode 100644 index 00000000..217b2bce --- /dev/null +++ b/src/slskd/Common/Middleware/HTMLInjectionMiddleware.cs @@ -0,0 +1,118 @@ +// <copyright file="HTMLInjectionMiddleware.cs" company="slskd Team"> +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// </copyright> + +namespace slskd +{ + using System; + using System.IO; + using System.Linq; + using System.Threading.Tasks; + using Microsoft.AspNetCore.Builder; + using Microsoft.AspNetCore.Http; + + /// <summary> + /// Adds the <see cref="HTMLInjectionMiddleware"/>. + /// </summary> + public static class HTMLInjectionMiddlewareExtensions + { + /// <summary> + /// Injects the specified <paramref name="html"/> into html files. + /// </summary> + /// <param name="builder"></param> + /// <param name="html"></param> + /// <returns></returns> + public static IApplicationBuilder UseHTMLInjection(this IApplicationBuilder builder, string html) + { + return builder.UseMiddleware<HTMLInjectionMiddleware>(html); + } + } + + /// <summary> + /// Injects content into html files. + /// </summary> + public class HTMLInjectionMiddleware + { + /// <summary> + /// Initializes a new instance of the <see cref="HTMLInjectionMiddleware"/> class. + /// </summary> + /// <param name="next"></param> + /// <param name="html"></param> + public HTMLInjectionMiddleware(RequestDelegate next, string html) + { + Next = next; + HTML = html; + } + + private string HTML { get; } + private RequestDelegate Next { get; } + + /// <summary> + /// Executes this middleware, returning the contents of the requested HTML file with the specified HTML appended. + /// </summary> + /// <param name="context"></param> + /// <returns></returns> + public async Task InvokeAsync(HttpContext context) + { + context.Request.Headers.TryGetValue("accept", out var accept); + var requestedTypes = accept.ToString().Split(','); + + var injectableTypes = new[] { "text/html", "application/xhtml + xml", "application/xml" }; + + var isApiRoute = context.Request.Path.ToString().StartsWith("/api"); + var isGET = context.Request.Method == "GET"; + + var isInjectableType = requestedTypes + .Intersect(injectableTypes, StringComparer.InvariantCultureIgnoreCase) + .Any(); + + if (!isApiRoute && isGET && isInjectableType) + { + var originalStream = context.Response.Body; + + // swap the response body out with a memory stream so we can manipulate it later + // the downstream middleware will write the response to it + var stream = new MemoryStream(); + context.Response.Body = stream; + + await Next.Invoke(context); + + if (context.Response.StatusCode == 200) + { + // something downstream responded with a 200, meaning there's data in the body + // we need to read it, so we can reset then play it back with the appended HTML + context.Response.Body.Seek(0, SeekOrigin.Begin); + var body = await new StreamReader(context.Response.Body).ReadToEndAsync(); + + context.Response.Clear(); + await context.Response.WriteAsync(body + HTML); + } + + // rewind the stream we injected to the beginning, then replay the data to the + // original stream + stream.Seek(0, SeekOrigin.Begin); + await stream.CopyToAsync(originalStream); + + // swap the original stream back in + context.Response.Body = originalStream; + } + else + { + await Next.Invoke(context); + } + } + } +} diff --git a/src/slskd/Common/Middleware/HTMLRewriteMiddleware.cs b/src/slskd/Common/Middleware/HTMLRewriteMiddleware.cs new file mode 100644 index 00000000..a15ba1e0 --- /dev/null +++ b/src/slskd/Common/Middleware/HTMLRewriteMiddleware.cs @@ -0,0 +1,124 @@ +// <copyright file="HTMLRewriteMiddleware.cs" company="slskd Team"> +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// </copyright> + +namespace slskd +{ + using System; + using System.IO; + using System.Linq; + using System.Text.RegularExpressions; + using System.Threading.Tasks; + using Microsoft.AspNetCore.Builder; + using Microsoft.AspNetCore.Http; + + /// <summary> + /// Adds the <see cref="HTMLRewriteMiddleware"/>. + /// </summary> + public static class HTMLRewriteMiddlewareExtensions + { + /// <summary> + /// Replaces the specified <paramref name="pattern"/> with the specified <paramref name="replacement"/>. + /// </summary> + /// <param name="builder"></param> + /// <param name="pattern"></param> + /// <param name="replacement"></param> + /// <returns></returns> + public static IApplicationBuilder UseHTMLRewrite(this IApplicationBuilder builder, string pattern, string replacement) + { + return builder.UseMiddleware<HTMLRewriteMiddleware>(pattern, replacement); + } + } + + /// <summary> + /// Replaces parts of HTML files. + /// </summary> + public class HTMLRewriteMiddleware + { + /// <summary> + /// Initializes a new instance of the <see cref="HTMLRewriteMiddleware"/> class. + /// </summary> + /// <param name="next"></param> + /// <param name="pattern"></param> + /// <param name="replacement"></param> + public HTMLRewriteMiddleware(RequestDelegate next, string pattern, string replacement) + { + Next = next; + Pattern = pattern; + Replacement = replacement; + } + + private string Pattern { get; } + private string Replacement { get; } + private RequestDelegate Next { get; } + + /// <summary> + /// Executes this middleware, returning the contents of the requested HTML file with the specified replacesments made. + /// </summary> + /// <param name="context"></param> + /// <returns></returns> + public async Task InvokeAsync(HttpContext context) + { + context.Request.Headers.TryGetValue("accept", out var accept); + var requestedTypes = accept.ToString().Split(','); + + var rewriteableType = new[] { "text/html", "application/xhtml + xml", "application/xml" }; + + var isApiRoute = context.Request.Path.ToString().StartsWith("/api"); + var isGET = context.Request.Method == "GET"; + + var isRewriteableType = requestedTypes + .Intersect(rewriteableType, StringComparer.InvariantCultureIgnoreCase) + .Any(); + + if (!isApiRoute && isGET && isRewriteableType) + { + var originalStream = context.Response.Body; + + // swap the response body out with a memory stream so we can manipulate it later + // the downstream middleware will write the response to it + var stream = new MemoryStream(); + context.Response.Body = stream; + + await Next.Invoke(context); + + if (context.Response.StatusCode == 200) + { + // something downstream responded with a 200, meaning there's data in the body + // we need to read it, so we can reset then play it back with the appended HTML + context.Response.Body.Seek(0, SeekOrigin.Begin); + var body = await new StreamReader(context.Response.Body).ReadToEndAsync(); + + context.Response.Clear(); + + await context.Response.WriteAsync(Regex.Replace(body, Pattern, Replacement)); + } + + // rewind the stream we injected to the beginning, then replay the data to the + // original stream + stream.Seek(0, SeekOrigin.Begin); + await stream.CopyToAsync(originalStream); + + // swap the original stream back in + context.Response.Body = originalStream; + } + else + { + await Next.Invoke(context); + } + } + } +} diff --git a/src/slskd/Common/Middleware/StrictUrlBaseMiddleware.cs b/src/slskd/Common/Middleware/StrictUrlBaseMiddleware.cs new file mode 100644 index 00000000..7efdd171 --- /dev/null +++ b/src/slskd/Common/Middleware/StrictUrlBaseMiddleware.cs @@ -0,0 +1,80 @@ +// <copyright file="StrictUrlBaseMiddleware.cs" company="slskd Team"> +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// </copyright> + +namespace slskd +{ + using System.Threading.Tasks; + using Microsoft.AspNetCore.Builder; + using Microsoft.AspNetCore.Http; + using Serilog; + + /// <summary> + /// Adds the <see cref="StrictUrlBaseMiddleware"/>. + /// </summary> + public static class StrictUrlBaseMiddlewareExtensions + { + /// <summary> + /// Ensures that routes are prefixed with <paramref name="urlBase"/>. + /// </summary> + /// <param name="builder"></param> + /// <param name="urlBase"></param> + /// <returns></returns> + public static IApplicationBuilder EnforceUrlBase( + this IApplicationBuilder builder, string urlBase) + { + return builder.UseMiddleware<StrictUrlBaseMiddleware>(urlBase); + } + } + + /// <summary> + /// Ensures that routes are prefixed with UrlBase. + /// </summary> + public class StrictUrlBaseMiddleware + { + /// <summary> + /// Initializes a new instance of the <see cref="StrictUrlBaseMiddleware"/> class. + /// </summary> + /// <param name="next"></param> + /// <param name="urlBase"></param> + public StrictUrlBaseMiddleware(RequestDelegate next, string urlBase) + { + Next = next; + UrlBase = urlBase; + } + + private ILogger Log { get; } = Serilog.Log.ForContext<StrictUrlBaseMiddleware>(); + private RequestDelegate Next { get; } + private string UrlBase { get; } + + /// <summary> + /// Executes this middleware, returning a 404 response if the path is not prefixed with UrlBase. + /// </summary> + /// <param name="context"></param> + /// <returns></returns> + public async Task InvokeAsync(HttpContext context) + { + if (!context.Request.Path.ToString().StartsWith(UrlBase)) + { + Log.Debug("Request to {Path} rejected with 404; URL Base {UrlBase} is strictly enforced", context.Request.Path.ToString(), UrlBase); + context.Response.StatusCode = 404; + return; + } + + await Next(context); + } + } +}
\ No newline at end of file diff --git a/src/slskd/Core/API/Controllers/ApplicationController.cs b/src/slskd/Core/API/Controllers/ApplicationController.cs index 19360fe1..cd03d96f 100644 --- a/src/slskd/Core/API/Controllers/ApplicationController.cs +++ b/src/slskd/Core/API/Controllers/ApplicationController.cs @@ -15,6 +15,8 @@ // along with this program. If not, see https://www.gnu.org/licenses/. // </copyright> +using Microsoft.Extensions.Options; + namespace slskd.Core.API { using System; @@ -37,15 +39,18 @@ namespace slskd.Core.API public ApplicationController( IHostApplicationLifetime lifetime, IApplication application, + IOptionsMonitor<Options> optionsMonitor, IStateMonitor<State> applicationStateMonitor) { Lifetime = lifetime; Application = application; + OptionsMonitor = optionsMonitor; ApplicationStateMonitor = applicationStateMonitor; } private IApplication Application { get; } private IStateMonitor<State> ApplicationStateMonitor { get; } + private IOptionsMonitor<Options> OptionsMonitor { get; } private IHostApplicationLifetime Lifetime { get; } /// <summary> @@ -109,7 +114,7 @@ namespace slskd.Core.API /// <returns></returns> [HttpGet("version/latest")] [Authorize] - public async Task<IActionResult> CheckVersion([FromQuery]bool forceCheck = false) + public async Task<IActionResult> CheckVersion([FromQuery] bool forceCheck = false) { if (forceCheck) { diff --git a/src/slskd/Options.cs b/src/slskd/Options.cs index 00ae670e..a1493ca4 100644 --- a/src/slskd/Options.cs +++ b/src/slskd/Options.cs @@ -965,6 +965,7 @@ namespace slskd [EnvironmentVariable("CONTENT_PATH")] [Description("path to static web content")] [StringLength(255, MinimumLength = 1)] + [DirectoryExists] [RequiresRestart] public string ContentPath { get; init; } = "wwwroot"; diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index e21bf52e..94cd0eba 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -603,57 +603,34 @@ namespace slskd var urlBase = OptionsAtStartup.Web.UrlBase; urlBase = urlBase.StartsWith("/") ? urlBase : "/" + urlBase; + // 404 if a custom urlBase is set, but the request doesn't include it. + // this is necessary to make sure the development-time and run-time behavior + // are consistent. + app.EnforceUrlBase(urlBase); + + // use urlBase. this effectively just removes urlBase from the path, which is + // why the enforcement behavior exists above (the actually requested path becomes ambiguous) + // inject urlBase into any html files we serve, and rewrite links to ./static or /static to + // prepend the url base. app.UsePathBase(urlBase); - app.Use((context, next) => - { - context.Response.OnStarting(() => - { - // the UI needs to be aware of what the URL base is, - // so that react-router can use explicit paths. - context.Response.Headers.Add("X-URL-Base", urlBase); - return Task.CompletedTask; - }); - - return next(); - }); - + app.UseHTMLRewrite("((\\.)?\\/static)", $"{(urlBase == "/" ? string.Empty : urlBase)}/static"); + app.UseHTMLInjection($"<script>window.urlBase=\"{urlBase}\"</script>"); Log.Information("Using base url {UrlBase}", urlBase); - // remove any errant double forward slashes which may have been introduced by manipulating the path base - app.Use(async (context, next) => - { - var path = context.Request.Path.ToString(); - - if (path.StartsWith("//")) - { - context.Request.Path = new string(path.Skip(1).ToArray()); - } - - await next(); - }); - // serve static content from the configured path FileServerOptions fileServerOptions = default; - var contentPath = Path.GetFullPath(OptionsAtStartup.Web.ContentPath); - if (!System.IO.Directory.Exists(contentPath)) - { - Log.Warning($"Static content disabled; cannot find content path '{contentPath}'"); - } - else + fileServerOptions = new FileServerOptions { - fileServerOptions = new FileServerOptions - { - FileProvider = new PhysicalFileProvider(contentPath), - RequestPath = string.Empty, - EnableDirectoryBrowsing = false, - EnableDefaultFiles = true, - }; - - app.UseFileServer(fileServerOptions); - Log.Information("Serving static content from {ContentPath}", contentPath); - } + FileProvider = new PhysicalFileProvider(contentPath), + RequestPath = string.Empty, + EnableDirectoryBrowsing = false, + EnableDefaultFiles = true, + }; + + app.UseFileServer(fileServerOptions); + Log.Information("Serving static content from {ContentPath}", contentPath); if (OptionsAtStartup.Feature.Prometheus) { @@ -685,6 +662,18 @@ namespace slskd } }); + // if this is an /api route and no API controller was matched, give up and return a 404. + app.Use(async (context, next) => + { + if (context.Request.Path.StartsWithSegments("/api")) + { + context.Response.StatusCode = 404; + return; + } + + await next(); + }); + if (OptionsAtStartup.Feature.Swagger) { app.UseSwagger(); @@ -694,12 +683,12 @@ namespace slskd Log.Information("Publishing Swagger documentation to /swagger"); } - // if we made it this far and the route still wasn't matched, return the index unless it's an api route. this is - // required so that SPA routing (React Router, etc) can work properly + // if we made it this far, the caller is either looking for a route that was synthesized with a SPA router, or is genuinely confused. + // if the request is for a directory, modify the request to redirect it to the index, otherwise leave it alone and let it 404 in the next + // middleware app.Use(async (context, next) => { - // exclude API routes which are not matched or return a 404 - if (!context.Request.Path.StartsWithSegments("/api")) + if (Path.GetExtension(context.Request.Path.ToString()) == string.Empty) { context.Request.Path = "/"; } @@ -707,12 +696,8 @@ namespace slskd await next(); }); - // finally, hit the fileserver again. if the path was modified to return the index above, the index document will be - // returned. otherwise it will throw a final 404 back to the client. - if (System.IO.Directory.Exists(contentPath)) - { - app.UseFileServer(fileServerOptions); - } + // either serve the index, or 404 + app.UseFileServer(fileServerOptions); return app; } |
