From bfe9dc6e565a134f25877d2076554ad95a9a2649 Mon Sep 17 00:00:00 2001 From: Arnaud Dartois Date: Mon, 10 Aug 2026 10:35:15 +0200 Subject: [PATCH] =?UTF-8?q?fix(auth):=20API=20key=20accept=C3=A9e=20en=20B?= =?UTF-8?q?earer=20sur=20les=20hubs=20SignalR?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Le client SignalR .NET envoie le token d'accès en header Authorization: Bearer sur le POST negotiate HTTP (les WebSockets ne peuvent pas poser de header custom) ; le navigateur l'envoie en query string access_token. ConfigHub étant [Authorize(AuthenticationSchemes="ApiKey")], le handler ApiKey doit lire les deux sur /hubs. Le fallback reste scoped aux hubs : sur les endpoints API, un Bearer non-JWT renvoie toujours 401. Tests : +2 intégration (Bearer sur ConfigHub OK, Bearer hors /hubs 401). --- .../Security/ApiKeyAuthenticationHandler.cs | 21 +++++--- .../Scenarios/SignalRHubScenarios.cs | 51 +++++++++++++++++++ 2 files changed, 66 insertions(+), 6 deletions(-) diff --git a/src/Heimdall.Infrastructure/Security/ApiKeyAuthenticationHandler.cs b/src/Heimdall.Infrastructure/Security/ApiKeyAuthenticationHandler.cs index a87df15..bf88111 100644 --- a/src/Heimdall.Infrastructure/Security/ApiKeyAuthenticationHandler.cs +++ b/src/Heimdall.Infrastructure/Security/ApiKeyAuthenticationHandler.cs @@ -35,17 +35,26 @@ public class ApiKeyAuthenticationHandler : AuthenticationHandler HandleAuthenticateAsync() { // X-API-Key header only (pas de Bearer — réservé au handler JWT). - // SignalR WebSocket clients cannot set custom headers, so the API key - // is also accepted via the access_token query string on hub paths - // (same convention as the JwtBearer handler). + // SignalR clients cannot set custom headers on WebSocket connections: + // the .NET client sends the access token as `Authorization: Bearer` + // on the HTTP negotiate POST, and browsers send it as the + // `access_token` query string. Accept both on hub paths (same + // convention as the JwtBearer handler's OnMessageReceived). var apiKey = Request.Headers["X-API-Key"].FirstOrDefault(); if (string.IsNullOrEmpty(apiKey)) { var path = Request.Path; - var queryToken = Request.Query["access_token"].FirstOrDefault(); - if (!string.IsNullOrEmpty(queryToken) && path.StartsWithSegments("/hubs")) - apiKey = queryToken; + if (path.StartsWithSegments("/hubs")) + { + var queryToken = Request.Query["access_token"].FirstOrDefault(); + var bearer = Request.Headers.Authorization.FirstOrDefault(); + if (!string.IsNullOrEmpty(queryToken)) + apiKey = queryToken; + else if (!string.IsNullOrEmpty(bearer) && + bearer.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase)) + apiKey = bearer["Bearer ".Length..].Trim(); + } } if (string.IsNullOrEmpty(apiKey) || apiKey.Length < 8) diff --git a/tests/Heimdall.IntegrationTests/Scenarios/SignalRHubScenarios.cs b/tests/Heimdall.IntegrationTests/Scenarios/SignalRHubScenarios.cs index 49b5ee6..9e3b5c6 100644 --- a/tests/Heimdall.IntegrationTests/Scenarios/SignalRHubScenarios.cs +++ b/tests/Heimdall.IntegrationTests/Scenarios/SignalRHubScenarios.cs @@ -157,6 +157,57 @@ public class SignalRHubScenarios : PostgresTestBase response.StatusCode.ShouldBe(HttpStatusCode.Unauthorized); } + [Fact] + public async Task ConfigHub_ApiKeyInBearerHeader_ReturnsOk() + { + // The .NET SignalR client sends the access token as `Authorization: + // Bearer ` on the HTTP negotiate POST (WebSocket can't set + // custom headers). ConfigHub is ApiKey-only, so the ApiKey handler + // must read the Bearer value on hub paths. + var admin = await Factory.CreateAdminClientAsync(); + + var siteResponse = await admin.PostAsJsonAsync("api/sites", new + { + name = "ConfigHub BearerSite", + timezone = "UTC" + }); + var siteContent = await siteResponse.Content.ReadFromJsonAsync(); + var siteId = siteContent.GetProperty("id").GetGuid(); + var tokenResponse = await admin.PostAsync($"api/sites/{siteId}/tokens", null); + var tokenContent = await tokenResponse.Content.ReadFromJsonAsync(); + var token = tokenContent.GetProperty("token").GetString()!; + var registerResponse = await admin.PostAsJsonAsync("api/agents/register", new + { + token, + hostname = "confighub-bearer-agent", + version = "1.0.0-test" + }); + var agentContent = await registerResponse.Content.ReadFromJsonAsync(); + var apiKey = agentContent.GetProperty("apiKey").GetString()!; + + var client = Factory.CreateClient(); + client.DefaultRequestHeaders.Authorization = + new AuthenticationHeaderValue("Bearer", apiKey); + var response = await client.PostAsync( + "/hubs/config/negotiate?negotiateVersion=1", null); + + response.StatusCode.ShouldBeOneOf(HttpStatusCode.OK, HttpStatusCode.Redirect); + } + + [Fact] + public async Task ConfigHub_ApiKeyInBearerHeader_OnNonHubPath_Returns401() + { + // The Bearer fallback must be scoped to /hubs — an API key sent as + // Bearer on a regular API endpoint must not authenticate (it would + // clash with the JWT scheme otherwise). + var admin = await Factory.CreateAdminClientAsync(); + var client = Factory.CreateClient(); + client.DefaultRequestHeaders.Authorization = + new AuthenticationHeaderValue("Bearer", "some-api-key-that-is-long-enough"); + var response = await client.GetAsync("/api/sites"); + response.StatusCode.ShouldBe(HttpStatusCode.Unauthorized); + } + [Fact] public async Task EventsHub_ApiKeyInQueryString_StillRequiresJwt() {