Skip to content
Merged
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
5 changes: 3 additions & 2 deletions src/Directory.Packages.props
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
<PackageVersion Include="Aspire.Hosting.SqlServer" Version="9.5.2" />
<PackageVersion Include="Aspire.Hosting.PostgreSQL" Version="9.5.2" />
<PackageVersion Include="Azure.Core" Version="1.47.1" />
<PackageVersion Include="Azure.Identity" Version="1.15.0" />
<PackageVersion Include="Azure.Identity" Version="1.17.1" />
<PackageVersion Include="Azure.Monitor.Ingestion" Version="1.1.2" />
<PackageVersion Include="Azure.Security.KeyVault.Secrets" Version="4.6.0" />
<PackageVersion Include="CommandLineParser" Version="2.9.1" />
Expand All @@ -34,6 +34,7 @@
<PackageVersion Include="Microsoft.AspNetCore.Mvc.Testing" Version="8.0.10" />
<PackageVersion Include="Microsoft.AspNetCore.TestHost" Version="8.0.10" />
<PackageVersion Include="Microsoft.Azure.Cosmos" Version="3.38.1" />
<PackageVersion Include="Microsoft.Azure.StackExchangeRedis" Version="3.3.1" />
<PackageVersion Include="Microsoft.Extensions.Caching.Memory" Version="8.0.1" />
<PackageVersion Include="Microsoft.Extensions.Caching.Abstractions" Version="9.0.0" />
<PackageVersion Include="Microsoft.Extensions.Primitives" Version="9.0.0" />
Expand All @@ -46,7 +47,7 @@
<PackageVersion Include="OpenTelemetry.Instrumentation.Runtime" Version="1.9.0" />
<!--When updating Microsoft.Data.SqlClient, update license URL in scripts/notice-generation.ps1-->
<PackageVersion Include="Microsoft.Data.SqlClient" Version="5.2.3" />
<PackageVersion Include="Microsoft.Extensions.Configuration.Binder" Version="8.0.1" />
<PackageVersion Include="Microsoft.Extensions.Configuration.Binder" Version="8.0.2" />
<PackageVersion Include="Microsoft.Extensions.Configuration.Json" Version="9.0.0" />
<PackageVersion Include="Microsoft.Extensions.Logging.ApplicationInsights" Version="2.22.0" />
<PackageVersion Include="Microsoft.IdentityModel.JsonWebTokens" Version="8.1.2" />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -173,7 +173,15 @@ public async Task TestInvalidToken_BadAudience()
Assert.AreEqual(expected: (int)HttpStatusCode.Unauthorized, actual: postMiddlewareContext.Response.StatusCode);
Assert.IsFalse(postMiddlewareContext.User.Identity.IsAuthenticated);
StringValues headerValue = GetChallengeHeader(postMiddlewareContext);
Assert.IsTrue(headerValue[0].Contains("invalid_token") && headerValue[0].Contains($"The audience '{BAD_AUDIENCE}' is invalid"));

// Microsoft.IdentityModel.Tokens version 8.8+ scrubs the Audience from the error message
// This behavior can be disabled with AppContext.SetSwitch("Switch.Microsoft.IdentityModel.DoNotScrubExceptions", true);
// See https://aka.ms/identitymodel/app-context-switches
string expectedAudienceInErrorMessage = AppContext.TryGetSwitch("Switch.Microsoft.IdentityModel.DoNotScrubExceptions", out bool isExceptionScrubbingDisabled) && isExceptionScrubbingDisabled
? BAD_AUDIENCE
: "(null)";

Assert.IsTrue(headerValue[0].Contains("invalid_token") && headerValue[0].Contains($"The audience '{expectedAudienceInErrorMessage}' is invalid"));
}

/// <summary>
Expand Down
32 changes: 32 additions & 0 deletions src/Service.Tests/UnitTests/StartupTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

using Microsoft.VisualStudio.TestTools.UnitTesting;
using StackExchange.Redis;

namespace Azure.DataApiBuilder.Service.Tests.UnitTests
{
[TestClass]
public class StartupTests
{
[DataTestMethod]
[DataRow("localhost:6379", false, DisplayName = "Localhost endpoint without password should NOT use Entra auth.")]
[DataRow("127.0.0.1:6379", false, DisplayName = "IPv4 loopback without password should NOT use Entra auth.")]
[DataRow("[::1]:6379", false, DisplayName = "IPv6 loopback without password should NOT use Entra auth.")]
[DataRow("redis.example.com:6380", true, DisplayName = "Remote endpoint without password SHOULD use Entra auth.")]
[DataRow("redis.example.com:6380,password=secret", false, DisplayName = "Presence of password should NOT use Entra auth, even for remote endpoints.")]
[DataRow("localhost:6379,redis.example.com:6380", true, DisplayName = "Mixed endpoints (including remote) without password SHOULD use Entra auth.")]
[DataRow("localhost:6379,password=secret", false, DisplayName = "Localhost with password should NOT use Entra auth.")]
public void ShouldUseEntraAuthForRedis(string connectionString, bool expectedUseEntraAuth)
{
// Arrange
var options = ConfigurationOptions.Parse(connectionString);

// Act
bool result = Startup.ShouldUseEntraAuthForRedis(options);

// Assert
Assert.AreEqual(expectedUseEntraAuth, result);
}
}
}
1 change: 1 addition & 0 deletions src/Service/Azure.DataApiBuilder.Service.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@
<PackageReference Include="Microsoft.ApplicationInsights.AspNetCore" />
<PackageReference Include="Microsoft.Extensions.Logging.ApplicationInsights" />
<PackageReference Include="Microsoft.Azure.Cosmos" />
<PackageReference Include="Microsoft.Azure.StackExchangeRedis" />
<PackageReference Include="Microsoft.Data.SqlClient" />
<PackageReference Include="Microsoft.Extensions.Configuration.Binder" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" />
Expand Down
44 changes: 43 additions & 1 deletion src/Service/Startup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@

using System;
using System.IO.Abstractions;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
Expand Down Expand Up @@ -435,7 +437,7 @@ public void ConfigureServices(IServiceCollection services)
else
{
// NOTE: this is done to reuse the same connection multiplexer for both the cache and backplane
Task<ConnectionMultiplexer> connectionMultiplexerTask = ConnectionMultiplexer.ConnectAsync(level2CacheOptions.ConnectionString);
Task<IConnectionMultiplexer> connectionMultiplexerTask = CreateConnectionMultiplexerAsync(level2CacheOptions.ConnectionString);

fusionCacheBuilder
.WithSerializer(new FusionCacheSystemTextJsonSerializer())
Expand Down Expand Up @@ -473,6 +475,46 @@ public void ConfigureServices(IServiceCollection services)
services.AddControllers();
}

/// <summary>
/// Creates a ConnectionMultiplexer for Redis with support for Azure Entra authentication.
/// </summary>
/// <param name="connectionString">The Redis connection string.</param>
/// <returns>A task that represents the asynchronous operation. The task result contains the connected IConnectionMultiplexer.</returns>
private static async Task<IConnectionMultiplexer> CreateConnectionMultiplexerAsync(string connectionString)
{
ConfigurationOptions options = ConfigurationOptions.Parse(connectionString);

if (ShouldUseEntraAuthForRedis(options))
{
options = await options.ConfigureForAzureWithTokenCredentialAsync(new DefaultAzureCredential());
}

return await ConnectionMultiplexer.ConnectAsync(options);
}

/// <summary>
/// Determines whether Azure Entra authentication should be used.
/// Conditions:
/// - No password provided
/// - At least one endpoint is NOT localhost/loopback
/// </summary>
/// <param name="options">The Redis configuration options.</param>
/// <returns>True if Azure Entra authentication should be used; otherwise, false.</returns>
/// <remarks>Internal for testing.</remarks>
internal static bool ShouldUseEntraAuthForRedis(ConfigurationOptions options)
{
// Determine if an endpoint is localhost/loopback
static bool IsLocalhostEndpoint(EndPoint ep) => ep switch
{
DnsEndPoint dns => string.Equals(dns.Host, "localhost", StringComparison.OrdinalIgnoreCase),
IPEndPoint ip => IPAddress.IsLoopback(ip.Address),
_ => false,
};

return string.IsNullOrEmpty(options.Password)
&& options.EndPoints.Any(ep => !IsLocalhostEndpoint(ep));
}

/// <summary>
/// Configures HTTP response compression based on the runtime configuration.
/// Compression is applied at the middleware level and supports Gzip and Brotli.
Expand Down