.well-known stapling via createWithIdentV2

This commit is contained in:
Loporrit
2025-06-28 14:28:38 +00:00
parent f706707182
commit 3f45f1865b
4 changed files with 82 additions and 57 deletions

Submodule MareAPI updated: fef2365280...4e4b2dab17

View File

@@ -2,6 +2,7 @@
using MareSynchronos.API.Data; using MareSynchronos.API.Data;
using MareSynchronos.API.Data.Extensions; using MareSynchronos.API.Data.Extensions;
using MareSynchronos.API.Dto; using MareSynchronos.API.Dto;
using MareSynchronos.API.Dto.CharaData;
using MareSynchronos.API.Dto.User; using MareSynchronos.API.Dto.User;
using MareSynchronos.API.SignalR; using MareSynchronos.API.SignalR;
using MareSynchronos.MareConfiguration; using MareSynchronos.MareConfiguration;

View File

@@ -63,18 +63,50 @@ public class HubFactory : MediatorSubscriberBase
return BuildHubConnection(_cachedConfig, ct); return BuildHubConnection(_cachedConfig, ct);
} }
public async Task<HubConnectionConfig> ResolveHubConfig() private async Task<HubConnectionConfig> ResolveHubConfig()
{ {
var uri = new Uri(_serverConfigurationManager.CurrentApiUrl); var stapledWellKnown = _tokenProvider.GetStapledWellKnown(_serverConfigurationManager.CurrentApiUrl);
var httpScheme = uri.Scheme.ToLowerInvariant() switch var apiUrl = new Uri(_serverConfigurationManager.CurrentApiUrl);
HubConnectionConfig defaultConfig;
if (_cachedConfig != null && _serverConfigurationManager.CurrentApiUrl == _cachedConfigFor)
{
defaultConfig = _cachedConfig;
}
else
{
defaultConfig = new HubConnectionConfig
{
HubUrl = _serverConfigurationManager.CurrentApiUrl.TrimEnd('/') + IMareHub.Path,
Transports = []
};
}
if (_serverConfigurationManager.CurrentApiUrl == ApiController.LoporritServiceUri)
defaultConfig.HubUrl = ApiController.LoporritServiceHubUri;
string jsonResponse;
if (stapledWellKnown != null)
{
jsonResponse = stapledWellKnown;
Logger.LogTrace("Using stapled hub config for {url}", _serverConfigurationManager.CurrentApiUrl);
}
else
{
try
{
var httpScheme = apiUrl.Scheme.ToLowerInvariant() switch
{ {
"ws" => "http", "ws" => "http",
"wss" => "https", "wss" => "https",
_ => uri.Scheme _ => apiUrl.Scheme
}; };
var wellKnownUrl = $"{httpScheme}://{uri.Host}/.well-known/loporrit/client"; var wellKnownUrl = $"{httpScheme}://{apiUrl.Host}/.well-known/loporrit/client";
Logger.LogTrace("Fetching hub config for {uri} via {wk}", _serverConfigurationManager.CurrentApiUrl, wellKnownUrl);
using var httpClient = new HttpClient( using var httpClient = new HttpClient(
new HttpClientHandler new HttpClientHandler
@@ -87,32 +119,6 @@ public class HubFactory : MediatorSubscriberBase
var ver = Assembly.GetExecutingAssembly().GetName().Version; var ver = Assembly.GetExecutingAssembly().GetName().Version;
httpClient.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue("MareSynchronos", ver!.Major + "." + ver!.Minor + "." + ver!.Build)); httpClient.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue("MareSynchronos", ver!.Major + "." + ver!.Minor + "." + ver!.Build));
HubConnectionConfig defaultConfig;
if (_cachedConfig != null && _serverConfigurationManager.CurrentApiUrl == _cachedConfigFor)
{
defaultConfig = _cachedConfig;
}
else if (_serverConfigurationManager.CurrentApiUrl == ApiController.LoporritServiceUri)
{
defaultConfig = new HubConnectionConfig
{
HubUrl = ApiController.LoporritServiceHubUri,
SkipNegotiation = true,
Transports = ["websockets"]
};
}
else
{
defaultConfig = new HubConnectionConfig
{
HubUrl = uri.AbsoluteUri.TrimEnd('/') + IMareHub.Path,
Transports = []
};
}
try
{
// Make a GET request to the loporrit endpoint // Make a GET request to the loporrit endpoint
var response = await httpClient.GetAsync(wellKnownUrl).ConfigureAwait(false); var response = await httpClient.GetAsync(wellKnownUrl).ConfigureAwait(false);
@@ -124,7 +130,17 @@ public class HubFactory : MediatorSubscriberBase
if (contentType == null || contentType != "application/json") if (contentType == null || contentType != "application/json")
return defaultConfig; return defaultConfig;
var jsonResponse = await response.Content.ReadAsStringAsync().ConfigureAwait(false); jsonResponse = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
}
catch (HttpRequestException ex)
{
Logger.LogWarning(ex, "HTTP request failed for .well-known");
return defaultConfig;
}
}
try
{
var config = JsonSerializer.Deserialize<HubConnectionConfig>( var config = JsonSerializer.Deserialize<HubConnectionConfig>(
jsonResponse, jsonResponse,
new JsonSerializerOptions new JsonSerializerOptions
@@ -137,17 +153,12 @@ public class HubFactory : MediatorSubscriberBase
return defaultConfig; return defaultConfig;
if (string.IsNullOrEmpty(config.HubUrl)) if (string.IsNullOrEmpty(config.HubUrl))
config.HubUrl ??= defaultConfig.HubUrl; config.HubUrl = defaultConfig.HubUrl;
config.Transports ??= []; config.Transports ??= [];
return config; return config;
} }
catch (HttpRequestException ex)
{
Logger.LogWarning(ex, "HTTP request failed for .well-known");
return defaultConfig;
}
catch (JsonException ex) catch (JsonException ex)
{ {
Logger.LogWarning(ex, "Invalid JSON in .well-known response"); Logger.LogWarning(ex, "Invalid JSON in .well-known response");

View File

@@ -4,10 +4,12 @@ using MareSynchronos.Services;
using MareSynchronos.Services.Mediator; using MareSynchronos.Services.Mediator;
using MareSynchronos.Services.ServerConfiguration; using MareSynchronos.Services.ServerConfiguration;
using MareSynchronos.Utils; using MareSynchronos.Utils;
using MareSynchronos.API.Dto;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using System.Collections.Concurrent; using System.Collections.Concurrent;
using System.IdentityModel.Tokens.Jwt; using System.IdentityModel.Tokens.Jwt;
using System.Net.Http.Headers; using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Reflection; using System.Reflection;
namespace MareSynchronos.WebAPI.SignalR; namespace MareSynchronos.WebAPI.SignalR;
@@ -19,6 +21,7 @@ public sealed class TokenProvider : IDisposable, IMediatorSubscriber
private readonly ILogger<TokenProvider> _logger; private readonly ILogger<TokenProvider> _logger;
private readonly ServerConfigurationManager _serverManager; private readonly ServerConfigurationManager _serverManager;
private readonly ConcurrentDictionary<JwtIdentifier, string> _tokenCache = new(); private readonly ConcurrentDictionary<JwtIdentifier, string> _tokenCache = new();
private readonly ConcurrentDictionary<string, string?> _wellKnownCache = new();
public TokenProvider(ILogger<TokenProvider> logger, ServerConfigurationManager serverManager, DalamudUtilService dalamudUtil, MareMediator mareMediator) public TokenProvider(ILogger<TokenProvider> logger, ServerConfigurationManager serverManager, DalamudUtilService dalamudUtil, MareMediator mareMediator)
{ {
@@ -32,11 +35,13 @@ public sealed class TokenProvider : IDisposable, IMediatorSubscriber
{ {
_lastJwtIdentifier = null; _lastJwtIdentifier = null;
_tokenCache.Clear(); _tokenCache.Clear();
_wellKnownCache.Clear();
}); });
Mediator.Subscribe<DalamudLoginMessage>(this, (_) => Mediator.Subscribe<DalamudLoginMessage>(this, (_) =>
{ {
_lastJwtIdentifier = null; _lastJwtIdentifier = null;
_tokenCache.Clear(); _tokenCache.Clear();
_wellKnownCache.Clear();
}); });
_httpClient.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue("MareSynchronos", ver!.Major + "." + ver!.Minor + "." + ver!.Build)); _httpClient.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue("MareSynchronos", ver!.Major + "." + ver!.Minor + "." + ver!.Build));
} }
@@ -54,14 +59,13 @@ public sealed class TokenProvider : IDisposable, IMediatorSubscriber
public async Task<string> GetNewToken(JwtIdentifier identifier, CancellationToken token) public async Task<string> GetNewToken(JwtIdentifier identifier, CancellationToken token)
{ {
Uri tokenUri; Uri tokenUri;
string response = string.Empty;
HttpResponseMessage result; HttpResponseMessage result;
try try
{ {
_logger.LogDebug("GetNewToken: Requesting"); _logger.LogDebug("GetNewToken: Requesting");
tokenUri = MareAuth.AuthFullPath(new Uri(_serverManager.CurrentApiUrl tokenUri = MareAuth.AuthV2FullPath(new Uri(_serverManager.CurrentApiUrl
.Replace("wss://", "https://", StringComparison.OrdinalIgnoreCase) .Replace("wss://", "https://", StringComparison.OrdinalIgnoreCase)
.Replace("ws://", "http://", StringComparison.OrdinalIgnoreCase))); .Replace("ws://", "http://", StringComparison.OrdinalIgnoreCase)));
var secretKey = _serverManager.GetSecretKey(out _)!; var secretKey = _serverManager.GetSecretKey(out _)!;
@@ -72,13 +76,16 @@ public sealed class TokenProvider : IDisposable, IMediatorSubscriber
new KeyValuePair<string, string>("charaIdent", await _dalamudUtil.GetPlayerNameHashedAsync().ConfigureAwait(false)), new KeyValuePair<string, string>("charaIdent", await _dalamudUtil.GetPlayerNameHashedAsync().ConfigureAwait(false)),
}), token).ConfigureAwait(false); }), token).ConfigureAwait(false);
response = await result.Content.ReadAsStringAsync().ConfigureAwait(false); var response = await result.Content.ReadFromJsonAsync<AuthReplyDto>().ConfigureAwait(false) ?? new();
result.EnsureSuccessStatusCode(); result.EnsureSuccessStatusCode();
_tokenCache[identifier] = response; _tokenCache[identifier] = response.Token;
_wellKnownCache[_serverManager.CurrentApiUrl] = response.WellKnown;
return response.Token;
} }
catch (HttpRequestException ex) catch (HttpRequestException ex)
{ {
_tokenCache.TryRemove(identifier, out _); _tokenCache.TryRemove(identifier, out _);
_wellKnownCache.TryRemove(_serverManager.CurrentApiUrl, out _);
_logger.LogError(ex, "GetNewToken: Failure to get token"); _logger.LogError(ex, "GetNewToken: Failure to get token");
@@ -86,13 +93,10 @@ public sealed class TokenProvider : IDisposable, IMediatorSubscriber
{ {
Mediator.Publish(new NotificationMessage("Error refreshing token", "Your authentication token could not be renewed. Try reconnecting manually.", NotificationType.Error)); Mediator.Publish(new NotificationMessage("Error refreshing token", "Your authentication token could not be renewed. Try reconnecting manually.", NotificationType.Error));
Mediator.Publish(new DisconnectedMessage()); Mediator.Publish(new DisconnectedMessage());
throw new MareAuthFailureException(response);
} }
throw; throw;
} }
return response;
} }
private async Task<JwtIdentifier?> GetIdentifier() private async Task<JwtIdentifier?> GetIdentifier()
@@ -153,4 +157,13 @@ public sealed class TokenProvider : IDisposable, IMediatorSubscriber
_logger.LogTrace("GetOrUpdate: Getting new token"); _logger.LogTrace("GetOrUpdate: Getting new token");
return await GetNewToken(jwtIdentifier, ct).ConfigureAwait(false); return await GetNewToken(jwtIdentifier, ct).ConfigureAwait(false);
} }
public string? GetStapledWellKnown(string apiUrl)
{
_wellKnownCache.TryGetValue(apiUrl, out var wellKnown);
// Treat an empty string as null -- it won't decode as JSON anyway
if (string.IsNullOrEmpty(wellKnown))
return null;
return wellKnown;
}
} }