Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adding basepath to the config #6963

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -58,4 +58,4 @@ This project has adopted the code of conduct defined by the [Contributor Covenan

## License

The code in this repo is licensed under the [MIT](LICENSE.TXT) license.
The code in this repo is licensed under the [MIT](LICENSE.TXT) license.
1 change: 1 addition & 0 deletions src/Aspire.Dashboard/Configuration/DashboardOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ namespace Aspire.Dashboard.Configuration;
public sealed class DashboardOptions
{
public string? ApplicationName { get; set; }
public string PathBase { get; set; } = "/";
public OtlpOptions Otlp { get; set; } = new();
public FrontendOptions Frontend { get; set; } = new();
public ResourceServiceClientOptions ResourceServiceClient { get; set; } = new();
Expand Down
15 changes: 15 additions & 0 deletions src/Aspire.Dashboard/Configuration/ValidateDashboardOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,21 @@ public ValidateOptionsResult Validate(string? name, DashboardOptions options)
}
}

// Validate the Path base and make sure it starts and ends with a forward slash.

if (options.PathBase != null)
{
if (!options.PathBase.StartsWith("/", StringComparison.Ordinal))
{
errorMessages.Add($"{nameof(DashboardOptions.PathBase)} must start with a forward slash.");
}

if (!options.PathBase.EndsWith("/", StringComparison.Ordinal))
{
errorMessages.Add($"{nameof(DashboardOptions.PathBase)} must end with a forward slash.");
}
}

return errorMessages.Count > 0
? ValidateOptionsResult.Fail(errorMessages)
: ValidateOptionsResult.Success;
Expand Down
12 changes: 6 additions & 6 deletions src/Aspire.Dashboard/DashboardEndpointsBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

using Aspire.Dashboard.Configuration;
using Aspire.Dashboard.Model;
using Aspire.Dashboard.Utils;
using Aspire.Dashboard.Utils;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.AspNetCore.Localization;
Expand All @@ -18,28 +18,28 @@ public static void MapDashboardApi(this IEndpointRouteBuilder endpoints, Dashboa
{
if (dashboardOptions.Frontend.AuthMode == FrontendAuthMode.BrowserToken)
{
endpoints.MapPost("/api/validatetoken", async (string token, HttpContext httpContext, IOptionsMonitor<DashboardOptions> dashboardOptions) =>
endpoints.MapPost($"{DashboardUrls.BasePath}api/validatetoken", async (string token, HttpContext httpContext, IOptionsMonitor<DashboardOptions> dashboardOptions) =>
{
return await ValidateTokenMiddleware.TryAuthenticateAsync(token, httpContext, dashboardOptions).ConfigureAwait(false);
});

#if DEBUG
// Available in local debug for testing.
endpoints.MapGet("/api/signout", async (HttpContext httpContext) =>
endpoints.MapGet($"{DashboardUrls.BasePath}api/signout", async (HttpContext httpContext) =>
{
await Microsoft.AspNetCore.Authentication.AuthenticationHttpContextExtensions.SignOutAsync(
httpContext,
CookieAuthenticationDefaults.AuthenticationScheme).ConfigureAwait(false);
httpContext.Response.Redirect("/");
httpContext.Response.Redirect($"{DashboardUrls.BasePath}");
});
#endif
}
else if (dashboardOptions.Frontend.AuthMode == FrontendAuthMode.OpenIdConnect)
{
endpoints.MapPost("/authentication/logout", () => TypedResults.SignOut(authenticationSchemes: [CookieAuthenticationDefaults.AuthenticationScheme, OpenIdConnectDefaults.AuthenticationScheme]));
endpoints.MapPost($"{DashboardUrls.BasePath}authentication/logout", () => TypedResults.SignOut(authenticationSchemes: [CookieAuthenticationDefaults.AuthenticationScheme, OpenIdConnectDefaults.AuthenticationScheme]));
}

endpoints.MapGet("/api/set-language", async (string? language, string? redirectUrl, [FromHeader(Name = "Accept-Language")] string? acceptLanguage, HttpContext httpContext) =>
endpoints.MapGet($"{DashboardUrls.BasePath}api/set-language", async (string? language, string? redirectUrl, [FromHeader(Name = "Accept-Language")] string? acceptLanguage, HttpContext httpContext) =>
{
if (string.IsNullOrEmpty(redirectUrl))
{
Expand Down
8 changes: 6 additions & 2 deletions src/Aspire.Dashboard/DashboardWebApplication.cs
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,7 @@ public DashboardWebApplication(
}
else
{
DashboardUrls.SetBasePath(dashboardOptions.PathBase);
_validationFailures = Array.Empty<string>();
}

Expand Down Expand Up @@ -335,7 +336,7 @@ public DashboardWebApplication(
// https://learn.microsoft.com/dotnet/core/tools/dotnet-environment-variables#dotnet_running_in_container-and-dotnet_running_in_containers
var isContainer = _app.Configuration.GetBool("DOTNET_RUNNING_IN_CONTAINER") ?? false;

LoggingHelpers.WriteDashboardUrl(_logger, frontendEndpointInfo.GetResolvedAddress(replaceIPAnyWithLocalhost: true), options.Frontend.BrowserToken, isContainer);
LoggingHelpers.WriteDashboardUrl(_logger, frontendEndpointInfo.GetResolvedAddress(replaceIPAnyWithLocalhost: true) + DashboardUrls.BasePath, options.Frontend.BrowserToken, isContainer);
}
}
});
Expand Down Expand Up @@ -369,7 +370,7 @@ public DashboardWebApplication(
// Configure the HTTP request pipeline.
if (!_app.Environment.IsDevelopment())
{
_app.UseExceptionHandler("/error");
_app.UseExceptionHandler($"{DashboardUrls.BasePath}error");
if (isAllHttps)
{
_app.UseHsts();
Expand Down Expand Up @@ -416,6 +417,9 @@ public DashboardWebApplication(
_app.MapGrpcService<OtlpGrpcLogsService>();

_app.MapDashboardApi(dashboardOptions);

_app.UsePathBase(dashboardOptions.PathBase);

}

private ILogger<DashboardWebApplication> GetLogger()
Expand Down
2 changes: 1 addition & 1 deletion src/Aspire.Dashboard/Model/ValidateTokenMiddleware.cs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ public ValidateTokenMiddleware(RequestDelegate next, IOptionsMonitor<DashboardOp

public async Task InvokeAsync(HttpContext context)
{
if (context.Request.Path.Equals("/login", StringComparisons.UrlPath))
if (context.Request.Path.Equals($"{DashboardUrls.BasePath}login", StringComparisons.UrlPath))
{
if (_options.CurrentValue.Frontend.AuthMode != FrontendAuthMode.BrowserToken)
{
Expand Down
2 changes: 2 additions & 0 deletions src/Aspire.Dashboard/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -123,3 +123,5 @@ Limits are per-resource. For example, a `MaxLogCount` value of 10,000 configures
### Other

- `Dashboard:ApplicationName` specifies the application name to be displayed in the UI. This applies only when no resource service URL is specified. When a resource service exists, the service specifies the application name.

- `Dashboard:PathBase` specifies the path base utilized by [PathMiddleware](https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.builder.usepathbaseextensions.usepathbase) to control how links are handled behind a reverse proxy
28 changes: 16 additions & 12 deletions src/Aspire.Dashboard/Utils/DashboardUrls.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,11 @@ internal static class DashboardUrls
public const string StructuredLogsBasePath = "structuredlogs";
public const string TracesBasePath = "traces";

public static string BasePath { get; private set; } = "/";

public static string ResourcesUrl(string? resource = null)
{
var url = "/";
var url = BasePath;
if (resource != null)
{
url = QueryHelpers.AddQueryString(url, "resource", resource);
Expand All @@ -26,10 +28,10 @@ public static string ResourcesUrl(string? resource = null)

public static string ConsoleLogsUrl(string? resource = null, bool? hideTimestamp = null)
{
var url = $"/{ConsoleLogBasePath}";
var url = $"{BasePath}{ConsoleLogBasePath}";
if (resource != null)
{
url += $"/resource/{Uri.EscapeDataString(resource)}";
url += $"{BasePath}resource/{Uri.EscapeDataString(resource)}";
}
if (hideTimestamp ?? false)
{
Expand All @@ -41,10 +43,10 @@ public static string ConsoleLogsUrl(string? resource = null, bool? hideTimestamp

public static string MetricsUrl(string? resource = null, string? meter = null, string? instrument = null, int? duration = null, string? view = null)
{
var url = $"/{MetricsBasePath}";
var url = $"{BasePath}{MetricsBasePath}";
if (resource != null)
{
url += $"/resource/{Uri.EscapeDataString(resource)}";
url += $"{BasePath}resource/{Uri.EscapeDataString(resource)}";
}
if (meter is not null)
{
Expand All @@ -69,10 +71,10 @@ public static string MetricsUrl(string? resource = null, string? meter = null, s

public static string StructuredLogsUrl(string? resource = null, string? logLevel = null, string? filters = null, string? traceId = null, string? spanId = null)
{
var url = $"/{StructuredLogsBasePath}";
var url = $"{BasePath}{StructuredLogsBasePath}";
if (resource != null)
{
url += $"/resource/{Uri.EscapeDataString(resource)}";
url += $"{BasePath}resource/{Uri.EscapeDataString(resource)}";
}
if (logLevel != null)
{
Expand All @@ -99,10 +101,10 @@ public static string StructuredLogsUrl(string? resource = null, string? logLevel

public static string TracesUrl(string? resource = null, string? filters = null)
{
var url = $"/{TracesBasePath}";
var url = $"{BasePath}{TracesBasePath}";
if (resource != null)
{
url += $"/resource/{Uri.EscapeDataString(resource)}";
url += $"{BasePath}resource/{Uri.EscapeDataString(resource)}";
}
if (filters != null)
{
Expand All @@ -117,7 +119,7 @@ public static string TracesUrl(string? resource = null, string? filters = null)

public static string TraceDetailUrl(string traceId, string? spanId = null)
{
var url = $"/{TracesBasePath}/detail/{Uri.EscapeDataString(traceId)}";
var url = $"{BasePath}{TracesBasePath}/detail/{Uri.EscapeDataString(traceId)}";
if (spanId != null)
{
url = QueryHelpers.AddQueryString(url, "spanId", spanId);
Expand All @@ -128,7 +130,7 @@ public static string TraceDetailUrl(string traceId, string? spanId = null)

public static string LoginUrl(string? returnUrl = null, string? token = null)
{
var url = "/login";
var url = $"{BasePath}login";
if (returnUrl != null)
{
url = QueryHelpers.AddQueryString(url, "returnUrl", returnUrl);
Expand All @@ -143,10 +145,12 @@ public static string LoginUrl(string? returnUrl = null, string? token = null)

public static string SetLanguageUrl(string language, string redirectUrl)
{
var url = "/api/set-language";
var url = $"{BasePath}api/set-language";
url = QueryHelpers.AddQueryString(url, "language", language);
url = QueryHelpers.AddQueryString(url, "redirectUrl", redirectUrl);

return url;
}

internal static void SetBasePath(string pathBase) => BasePath = pathBase;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This doesn't seem like an optimal way to update BasePath to me. If DashboardUrls is going to store this state, it should be turned into a service and injected.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I am following the SetLanguageUrl method above

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It’s different, as SetLanguageUrl does not set state. It only returns the url for the set language url path.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

OK. Is this something that will block the feature from being accepted?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

See the comment below, DashboardUrls shouldn't be changed at all

}
3 changes: 2 additions & 1 deletion src/Shared/LoggingHelpers.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
// The .NET Foundation licenses this file to you under the MIT license.

using Aspire.Hosting.Utils;
using Aspire.Dashboard.Utils;
using Microsoft.Extensions.Logging;

namespace Aspire.Hosting;
Expand All @@ -20,7 +21,7 @@ public static void WriteDashboardUrl(ILogger logger, string? dashboardUrls, stri
var message = !isContainer
? "Login to the dashboard at {DashboardLoginUrl}"
: "Login to the dashboard at {DashboardLoginUrl}. The URL may need changes depending on how network access to the container is configured.";
logger.LogInformation(message, $"{firstDashboardUrl.GetLeftPart(UriPartial.Authority)}/login?t={token}");
logger.LogInformation(message, $"{firstDashboardUrl.GetLeftPart(UriPartial.Path)}login?t={token}");
}
}
}
52 changes: 52 additions & 0 deletions tests/Aspire.Dashboard.Tests/DashboardOptionsTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -276,4 +276,56 @@ public void OpenIdConnectOptions_NoUserNameClaimType()
}

#endregion

#region Path Base options

[Fact]
public void PathBaseOptions_InvalidPathBase()
{
var options = GetValidOptions();
options.PathBase = "invalid";
var result = new ValidateDashboardOptions().Validate(null, options);
Assert.False(result.Succeeded);
Assert.Equal("PathBase must start with a forward slash.; PathBase must end with a forward slash.", result.FailureMessage);
}

[Fact]
public void PathBaseOptions_InvalidPathBase_Missing_TrailingSlash()
{
var options = GetValidOptions();
options.PathBase = "/invalid";
var result = new ValidateDashboardOptions().Validate(null, options);
Assert.False(result.Succeeded);
Assert.Equal("PathBase must end with a forward slash.", result.FailureMessage);
}

[Fact]
public void PathBaseOptions_ValidPathBase()
{
var options = GetValidOptions();
options.PathBase = "/valid/";
var result = new ValidateDashboardOptions().Validate(null, options);
Assert.True(result.Succeeded);
}

[Fact]
public void PathBaseOptions_Not_Set_PathBase_Defaults_To_Slash()
{
var options = GetValidOptions();
Assert.Equal("/", options.PathBase);
var result = new ValidateDashboardOptions().Validate(null, options);

Assert.True(result.Succeeded);
}
[Fact]
public void PathBaseOptions_InvalidPathBase_Missing_LeadingSlash()
{
var options = GetValidOptions();
options.PathBase = "invalid/";
var result = new ValidateDashboardOptions().Validate(null, options);
Assert.False(result.Succeeded);
Assert.Equal("PathBase must start with a forward slash.", result.FailureMessage);
}

#endregion
}
Loading