-
Notifications
You must be signed in to change notification settings - Fork 739
Azure PostgreSQL client #8230
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
Merged
Merged
Azure PostgreSQL client #8230
Changes from 9 commits
Commits
Show all changes
23 commits
Select commit
Hold shift + click to select a range
d628a49
Create Azure Npgsql client integration
sebastienros 89b721d
Reuse code from npgsql and add tests
sebastienros a4635f3
Update component metadata
sebastienros 7cceac6
Fix tests on CI
sebastienros f4cf620
Fix markdown
sebastienros 6e9ebad
Improvements on non-azure database support
sebastienros c4a4d33
Refactor Npgsql usage
sebastienros bcf8d18
Removing playground app and refactoring
sebastienros 8a6fa32
Update src/Components/Aspire.Azure.Npgsql/AssemblyInfo.cs
sebastienros 81dbd63
Remove config schema metadata
sebastienros 2b5c479
Remove unnecessary file references
sebastienros 21fc9de
Merge remote-tracking branch 'upstream/main' into sebros/azurenpgsql
eerhardt 2ee5339
Comment copies
sebastienros 2f49ff8
Support getting the PrinicipalName for a user assigned managed identity
eerhardt ee2ee64
Merge remote-tracking branch 'upstream/sebros/azurenpgsql' into sebro…
eerhardt 4f70984
Merge remote-tracking branch 'upstream/main' into sebros/azurenpgsql
eerhardt 25d52db
Merge remote-tracking branch 'origin/sebros/azurenpgsql' into sebros/…
sebastienros 35cbaef
Fix test
sebastienros 1e3b0bd
Remove custom log categories
sebastienros 7091de2
Handle username token extraction failures
sebastienros 9d7e4d2
Fix code blocks
sebastienros 3ea164b
Address PR feedback
eerhardt 32fb819
Fix test project
eerhardt File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
26 changes: 26 additions & 0 deletions
26
src/Components/Aspire.Azure.Npgsql/Aspire.Azure.Npgsql.csproj
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,26 @@ | ||
| <Project Sdk="Microsoft.NET.Sdk"> | ||
|
|
||
| <PropertyGroup> | ||
| <TargetFramework>$(DefaultTargetFramework)</TargetFramework> | ||
| <IsPackable>true</IsPackable> | ||
| <PackageTags>$(ComponentAzurePackageTags) postgresql postgres npgsql sql</PackageTags> | ||
| <Description>A client for Azure Database for PostgreSQL that integrates with Aspire, including health checks, logging and telemetry.</Description> | ||
| <PackageIconFullPath>$(SharedDir)AzurePostgreSQL_256x.png</PackageIconFullPath> | ||
| <EnablePackageValidation>false</EnablePackageValidation> | ||
| <NoWarn>$(NoWarn);SYSLIB1100;SYSLIB1101</NoWarn> | ||
| </PropertyGroup> | ||
|
|
||
| <ItemGroup> | ||
| <Compile Include="..\Common\ConfigurationSchemaAttributes.cs" Link="ConfigurationSchemaAttributes.cs" /> | ||
| <Compile Include="..\Common\HealthChecksExtensions.cs" Link="HealthChecksExtensions.cs" /> | ||
| <Compile Include="..\Common\ConnectionStringValidation.cs" Link="ConnectionStringValidation.cs" /> | ||
| <Compile Include="..\Aspire.Npgsql\NpgsqlCommon.cs" Link="NpgsqlCommon.cs" /> | ||
| <Compile Include="..\Aspire.Npgsql\AssemblyInfo.LoggingCategories.cs" Link="AssemblyInfo.LoggingCategories.cs" /> | ||
| </ItemGroup> | ||
|
|
||
| <ItemGroup> | ||
| <PackageReference Include="Microsoft.Extensions.Azure" /> | ||
| <ProjectReference Include="..\Aspire.Npgsql\Aspire.Npgsql.csproj" /> | ||
| </ItemGroup> | ||
|
|
||
| </Project> | ||
179 changes: 179 additions & 0 deletions
179
src/Components/Aspire.Azure.Npgsql/AspireAzureNpgsqlExtensions.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,179 @@ | ||
| // Licensed to the .NET Foundation under one or more agreements. | ||
| // The .NET Foundation licenses this file to you under the MIT license. | ||
|
|
||
| #pragma warning disable IDE0130 // Namespace "Microsoft.Extensions.Hosting" does not match folder structure | ||
|
|
||
| using System.Diagnostics; | ||
| using System.Text.Json; | ||
| using Aspire.Azure.Npgsql; | ||
| using Aspire.Npgsql; | ||
| using Azure.Core; | ||
| using Azure.Identity; | ||
| using Microsoft.Extensions.DependencyInjection; | ||
| using Npgsql; | ||
|
|
||
| namespace Microsoft.Extensions.Hosting; | ||
|
|
||
| /// <summary> | ||
| /// Extension methods for connecting to an Azure Database for PostgreSQL with Npgsql client | ||
| /// </summary> | ||
| public static class AspireAzureNpgsqlExtensions | ||
| { | ||
| private const string AzureDatabaseForPostgresSqlScope = "https://ossrdbms-aad.database.windows.net/.default"; | ||
|
|
||
| private static readonly TokenRequestContext s_databaseForPostgresSqlTokenRequestContext = new([AzureDatabaseForPostgresSqlScope]); | ||
|
|
||
| /// <summary> | ||
| /// Registers <see cref="NpgsqlDataSource"/> service for connecting PostgreSQL database with Npgsql client. | ||
| /// Configures health check, logging and telemetry for the Npgsql client. | ||
| /// </summary> | ||
| /// <param name="builder">The <see cref="IHostApplicationBuilder" /> to read config from and add services to.</param> | ||
| /// <param name="connectionName">A name used to retrieve the connection string from the ConnectionStrings configuration section.</param> | ||
| /// <param name="configureSettings">An optional delegate that can be used for customizing options. It's invoked after the settings are read from the configuration.</param> | ||
| /// <param name="configureDataSourceBuilder">An optional delegate that can be used for customizing the <see cref="NpgsqlDataSourceBuilder"/>.</param> | ||
| /// <remarks>Reads the configuration from "Aspire:Npgsql" section.</remarks> | ||
| /// <exception cref="ArgumentNullException">Thrown if mandatory <paramref name="builder"/> is null.</exception> | ||
| /// <exception cref="InvalidOperationException">Thrown when mandatory <see cref="NpgsqlSettings.ConnectionString"/> is not provided or the <see cref="AzureNpgsqlSettings.Credential"/> is invalid.</exception> | ||
| public static void AddAzureNpgsqlDataSource(this IHostApplicationBuilder builder, string connectionName, Action<AzureNpgsqlSettings>? configureSettings = null, Action<NpgsqlDataSourceBuilder>? configureDataSourceBuilder = null) | ||
| { | ||
| ArgumentNullException.ThrowIfNull(builder); | ||
| ArgumentException.ThrowIfNullOrEmpty(connectionName); | ||
|
|
||
| AzureNpgsqlSettings? azureSettings = null; | ||
|
|
||
| builder.AddNpgsqlDataSource(connectionName, settings => azureSettings = ConfigureSettings(configureSettings, settings), dataSourceBuilder => | ||
| { | ||
| Debug.Assert(azureSettings != null); | ||
|
|
||
| ConfigureDataSourceBuilder(azureSettings, dataSourceBuilder); | ||
|
|
||
| configureDataSourceBuilder?.Invoke(dataSourceBuilder); | ||
| }); | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Registers <see cref="NpgsqlDataSource"/> as a keyed service for given <paramref name="name"/> for connecting PostgreSQL database with Npgsql client. | ||
| /// Configures health check, logging and telemetry for the Npgsql client. | ||
| /// </summary> | ||
| /// <param name="builder">The <see cref="IHostApplicationBuilder" /> to read config from and add services to.</param> | ||
| /// <param name="name">The name of the component, which is used as the <see cref="ServiceDescriptor.ServiceKey"/> of the service and also to retrieve the connection string from the ConnectionStrings configuration section.</param> | ||
| /// <param name="configureSettings">An optional method that can be used for customizing options. It's invoked after the settings are read from the configuration.</param> | ||
| /// <param name="configureDataSourceBuilder">An optional delegate that can be used for customizing the <see cref="NpgsqlDataSourceBuilder"/>.</param> | ||
| /// <remarks>Reads the configuration from "Aspire:Npgsql:{name}" section.</remarks> | ||
| /// <exception cref="ArgumentNullException">Thrown when <paramref name="builder"/> or <paramref name="name"/> is null.</exception> | ||
| /// <exception cref="ArgumentException">Thrown if mandatory <paramref name="name"/> is empty.</exception> | ||
| /// <exception cref="InvalidOperationException">Thrown when mandatory <see cref="NpgsqlSettings.ConnectionString"/> is not provided or the <see cref="AzureNpgsqlSettings.Credential"/> is invalid.</exception> | ||
| public static void AddKeyedAzureNpgsqlDataSource(this IHostApplicationBuilder builder, string name, Action<AzureNpgsqlSettings>? configureSettings = null, Action<NpgsqlDataSourceBuilder>? configureDataSourceBuilder = null) | ||
| { | ||
| ArgumentNullException.ThrowIfNull(builder); | ||
| ArgumentException.ThrowIfNullOrEmpty(name); | ||
|
|
||
| AzureNpgsqlSettings? azureSettings = null; | ||
|
|
||
| builder.AddKeyedNpgsqlDataSource(name, settings => azureSettings = ConfigureSettings(configureSettings, settings), dataSourceBuilder => | ||
| { | ||
| Debug.Assert(azureSettings != null); | ||
|
|
||
| ConfigureDataSourceBuilder(azureSettings, dataSourceBuilder); | ||
|
|
||
| configureDataSourceBuilder?.Invoke(dataSourceBuilder); | ||
| }); | ||
| } | ||
|
|
||
| private static AzureNpgsqlSettings ConfigureSettings(Action<AzureNpgsqlSettings>? userConfigureSettings, NpgsqlSettings settings) | ||
| { | ||
| var azureSettings = new AzureNpgsqlSettings(); | ||
| CopySettings(settings, azureSettings); | ||
| userConfigureSettings?.Invoke(azureSettings); | ||
| CopySettings(azureSettings, settings); | ||
sebastienros marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| return azureSettings; | ||
| } | ||
| private static void CopySettings(NpgsqlSettings source, NpgsqlSettings destination) | ||
| { | ||
| destination.ConnectionString = source.ConnectionString; | ||
| destination.DisableHealthChecks = source.DisableHealthChecks; | ||
| destination.DisableMetrics = source.DisableMetrics; | ||
| destination.DisableTracing = source.DisableTracing; | ||
| } | ||
|
|
||
| private static void ConfigureDataSourceBuilder(AzureNpgsqlSettings settings, NpgsqlDataSourceBuilder dataSourceBuilder) | ||
| { | ||
| // The connection string required the username to be provided. Since it will depend on the Managed Identity that is used | ||
| // we attempt to get the username from the access token. | ||
|
|
||
| var credential = settings.Credential ?? new DefaultAzureCredential(); | ||
|
|
||
| if (string.IsNullOrEmpty(dataSourceBuilder.ConnectionStringBuilder.Username)) | ||
| { | ||
| var token = credential.GetToken(s_databaseForPostgresSqlTokenRequestContext, default); | ||
|
|
||
| if (TryGetUsernameFromToken(token.Token, out var username)) | ||
| { | ||
| dataSourceBuilder.ConnectionStringBuilder.Username = username; | ||
| } | ||
| else | ||
| { | ||
| throw new InvalidOperationException("Could not determine username from token claims"); | ||
| } | ||
| } | ||
|
|
||
| if (string.IsNullOrEmpty(dataSourceBuilder.ConnectionStringBuilder.Password)) | ||
| { | ||
| // The token is not cached since it it refreshed for each new physical connection, or when it has expired. | ||
|
|
||
| dataSourceBuilder.UsePasswordProvider( | ||
| passwordProvider: _ => credential.GetToken(s_databaseForPostgresSqlTokenRequestContext, default).Token, | ||
| passwordProviderAsync: async (_, ct) => (await credential.GetTokenAsync(s_databaseForPostgresSqlTokenRequestContext, default).ConfigureAwait(false)).Token | ||
| ); | ||
| } | ||
| } | ||
|
|
||
| private static bool TryGetUsernameFromToken(string jwtToken, out string? username) | ||
| { | ||
| username = null; | ||
|
|
||
| // Split the token into its parts (Header, Payload, Signature) | ||
| var tokenParts = jwtToken.Split('.'); | ||
| if (tokenParts.Length != 3) | ||
| { | ||
| return false; | ||
| } | ||
|
|
||
| // The payload is the second part, Base64Url encoded | ||
| var payload = tokenParts[1]; | ||
|
|
||
| // Add padding if necessary | ||
| payload = AddBase64Padding(payload); | ||
|
|
||
| // Decode the payload from Base64Url | ||
| var decodedBytes = Convert.FromBase64String(payload); | ||
|
|
||
| // Parse the decoded payload as JSON | ||
| var reader = new Utf8JsonReader(decodedBytes); | ||
| var payloadJson = JsonElement.ParseValue(ref reader); | ||
|
|
||
| // Try to get the username from 'upn', 'preferred_username', or 'unique_name' claims | ||
eerhardt marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| if (payloadJson.TryGetProperty("upn", out var upn)) | ||
| { | ||
| username = upn.GetString(); | ||
| } | ||
| else if (payloadJson.TryGetProperty("preferred_username", out var preferredUsername)) | ||
| { | ||
| username = preferredUsername.GetString(); | ||
| } | ||
| else if (payloadJson.TryGetProperty("unique_name", out var uniqueName)) | ||
| { | ||
| username = uniqueName.GetString(); | ||
| } | ||
|
|
||
| return username != null; | ||
| } | ||
|
|
||
| private static string AddBase64Padding(string base64) => (base64.Length % 4) switch | ||
sebastienros marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| { | ||
| 2 => base64 + "==", | ||
| 3 => base64 + "=", | ||
| _ => base64, | ||
| }; | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,8 @@ | ||
| // Licensed to the .NET Foundation under one or more agreements. | ||
| // The .NET Foundation licenses this file to you under the MIT license. | ||
|
|
||
| using Aspire; | ||
| using Aspire.Npgsql; | ||
| using Azure.Core; | ||
|
|
||
| [assembly: ConfigurationSchema("Aspire:Npgsql", typeof(NpgsqlSettings))] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,18 @@ | ||
| // Licensed to the .NET Foundation under one or more agreements. | ||
| // The .NET Foundation licenses this file to you under the MIT license. | ||
|
|
||
| using Aspire.Npgsql; | ||
| using Azure.Core; | ||
|
|
||
| namespace Aspire.Azure.Npgsql; | ||
|
|
||
| /// <summary> | ||
| /// Provides the client configuration settings for connecting to an Azure Database for PostgreSQL using Npgsql. | ||
| /// </summary> | ||
| public sealed class AzureNpgsqlSettings : NpgsqlSettings | ||
| { | ||
| /// <summary> | ||
| /// Gets or sets the credential used to authenticate to the Azure Database for PostgreSQL namespace. | ||
| /// </summary> | ||
| public TokenCredential? Credential { get; set; } | ||
| } |
54 changes: 54 additions & 0 deletions
54
src/Components/Aspire.Azure.Npgsql/ConfigurationSchema.json
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,54 @@ | ||
| { | ||
| "definitions": { | ||
| "logLevel": { | ||
| "properties": { | ||
| "Npgsql": { | ||
| "$ref": "#/definitions/logLevelThreshold" | ||
| }, | ||
| "Npgsql.Command": { | ||
| "$ref": "#/definitions/logLevelThreshold" | ||
| }, | ||
| "Npgsql.Connection": { | ||
| "$ref": "#/definitions/logLevelThreshold" | ||
| }, | ||
| "Npgsql.Copy": { | ||
| "$ref": "#/definitions/logLevelThreshold" | ||
| }, | ||
| "Npgsql.Exception": { | ||
| "$ref": "#/definitions/logLevelThreshold" | ||
| }, | ||
| "Npgsql.Replication": { | ||
| "$ref": "#/definitions/logLevelThreshold" | ||
| }, | ||
| "Npgsql.Transaction": { | ||
| "$ref": "#/definitions/logLevelThreshold" | ||
| } | ||
| } | ||
| } | ||
| }, | ||
| "type": "object", | ||
| "properties": { | ||
| "Aspire": { | ||
| "type": "object", | ||
| "properties": { | ||
| "Npgsql": { | ||
| "type": "object", | ||
| "properties": { | ||
| "ConnectionString": { | ||
| "type": "string" | ||
| }, | ||
| "DisableHealthChecks": { | ||
| "type": "boolean" | ||
| }, | ||
| "DisableMetrics": { | ||
| "type": "boolean" | ||
| }, | ||
| "DisableTracing": { | ||
| "type": "boolean" | ||
| } | ||
| } | ||
| } | ||
| } | ||
| } | ||
| } | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.