From e2970af5e71d8c593347b12cbd69909f6bd3fd29 Mon Sep 17 00:00:00 2001 From: aristachauhan Date: Tue, 1 Dec 2026 21:10:04 +0000 Subject: [PATCH] add uri redirect and modify vault auth pathways --- .github/workflows/configure-azure.yml | 2 + .github/workflows/deploy-azure-appservice.yml | 2 + README.md | 20 ++- docs/GRAPH-DEVELOPMENT.md | 145 +++++++++++------- infrastructure/azure/README.md | 31 ++-- infrastructure/azure/deploy.sh | 3 +- infrastructure/azure/deployment-settings.json | 7 + .../Development/Graph/GraphClientFactory.cs | 27 +++- .../Development/Graph/GraphProbeSettings.cs | 31 ++-- server/Program.cs | 2 +- server/Services/SecretsService.cs | 31 +--- .../GraphAuthorizationCallbackTests.cs | 1 - .../Development/GraphConnectionTests.cs | 15 +- .../Development/GraphSecretStub.cs | 20 +++ .../Development/GraphTokenCacheTests.cs | 14 +- .../Services/SecretsServiceTests.cs | 61 +++----- 16 files changed, 231 insertions(+), 181 deletions(-) create mode 100644 tests/server.tests/Development/GraphSecretStub.cs diff --git a/.github/workflows/configure-azure.yml b/.github/workflows/configure-azure.yml index 7124423..73da50a 100644 --- a/.github/workflows/configure-azure.yml +++ b/.github/workflows/configure-azure.yml @@ -39,6 +39,7 @@ jobs: AUTH_DOMAIN: ${{ vars.AUTH_DOMAIN }} AUTH_INSTANCE: ${{ vars.AUTH_INSTANCE || 'https://login.microsoftonline.com/' }} AUTH_TENANT_ID: ${{ vars.AUTH_TENANT_ID }} + GRAPH__REDIRECT_URI: ${{ vars.GRAPH__REDIRECT_URI }} NOTIFICATION_BASE_URL: ${{ vars.NOTIFICATION_BASE_URL }} NOTIFICATION_DEFAULT_APP_NAME: ${{ vars.NOTIFICATION_DEFAULT_APP_NAME }} NOTIFICATION_DEFAULT_BUTTON_TEXT: ${{ vars.NOTIFICATION_DEFAULT_BUTTON_TEXT }} @@ -251,6 +252,7 @@ jobs: add_setting "Auth__Domain" "$AUTH_DOMAIN" add_setting "Auth__Instance" "$AUTH_INSTANCE" add_setting "Auth__TenantId" "$AUTH_TENANT_ID" + add_setting "Graph__RedirectUri" "$GRAPH__REDIRECT_URI" add_setting "Notification__BaseUrl" "$NOTIFICATION_BASE_URL" add_setting "Notification__DefaultAppName" "$NOTIFICATION_DEFAULT_APP_NAME" add_setting "Notification__DefaultButtonText" "$NOTIFICATION_DEFAULT_BUTTON_TEXT" diff --git a/.github/workflows/deploy-azure-appservice.yml b/.github/workflows/deploy-azure-appservice.yml index bd71fdb..dd4c273 100644 --- a/.github/workflows/deploy-azure-appservice.yml +++ b/.github/workflows/deploy-azure-appservice.yml @@ -218,6 +218,7 @@ jobs: AUTH_DOMAIN: ${{ vars.AUTH_DOMAIN }} AUTH_INSTANCE: ${{ vars.AUTH_INSTANCE || 'https://login.microsoftonline.com/' }} AUTH_TENANT_ID: ${{ vars.AUTH_TENANT_ID }} + GRAPH__REDIRECT_URI: ${{ vars.GRAPH__REDIRECT_URI }} NOTIFICATION_BASE_URL: ${{ vars.NOTIFICATION_BASE_URL }} NOTIFICATION_DEFAULT_APP_NAME: ${{ vars.NOTIFICATION_DEFAULT_APP_NAME }} NOTIFICATION_DEFAULT_BUTTON_TEXT: ${{ vars.NOTIFICATION_DEFAULT_BUTTON_TEXT }} @@ -284,6 +285,7 @@ jobs: add_setting "Auth__Domain" "$AUTH_DOMAIN" add_setting "Auth__Instance" "$AUTH_INSTANCE" add_setting "Auth__TenantId" "$AUTH_TENANT_ID" + add_setting "Graph__RedirectUri" "$GRAPH__REDIRECT_URI" add_setting "Notification__BaseUrl" "$NOTIFICATION_BASE_URL" add_setting "Notification__DefaultAppName" "$NOTIFICATION_DEFAULT_APP_NAME" add_setting "Notification__DefaultButtonText" "$NOTIFICATION_DEFAULT_BUTTON_TEXT" diff --git a/README.md b/README.md index f256738..c4431e4 100644 --- a/README.md +++ b/README.md @@ -204,13 +204,16 @@ mode, with no additional feature flag. ### Key Vault secrets -Graph reuses the existing `Azure__TenantId`, `Azure__ClientId`, and -`Azure__ClientSecret` settings. Its hosted MSAL cache is saved in the fixed Key Vault -secret `graph-calendar-token-cache`, created by the app after verified sign-in. -There are no separate Graph credential overrides or credential-secret references. -Configure `Graph__RedirectUri` for the separate calendar callback. Local development -uses file caching; see -[Graph credential setup](docs/GRAPH-DEVELOPMENT.md#key-vault-credentials-and-future-federation). +Graph reads its client secret directly from the environment Key Vault under the +fixed name `azure-client-secret`, including in local Development. Calendar IDs +use Booking's existing `Auth__TenantId` and `Auth__ClientId`. There are no separate +Graph ID overrides. Set the GitHub Environment variable +`GRAPH__REDIRECT_URI`; deployment maps it to `Graph__RedirectUri`. No client secret +or vault reference is passed through GitHub. Each calendar operation reads the +latest credential, so rotation needs no app deployment or restart. The hosted MSAL +cache is saved separately in `graph-calendar-token-cache`, created by the app after +verified sign-in; local Development keeps the token cache in files. See +[Graph credential setup](docs/GRAPH-DEVELOPMENT.md#hosted-setup-and-rotation). `ISecretsService` provides asynchronous reads and writes by secret name. Configure `Azure__KeyVaultUrl` when the service is needed. Azure deployment creates a vault in @@ -227,7 +230,8 @@ Azure__KeyVaultUrl="https://.vault.azure.net/" An operator must grant your user or developer security group **Key Vault Secrets Officer** on the test vault for reads and writes. See [local development access](infrastructure/azure/README.md#local-development-access) for setup. The service uses `DefaultAzureCredential` to authenticate with your Azure CLI -login locally and managed identity in Azure. +login locally. Hosted environments explicitly use `ManagedIdentityCredential`. +Calendar credentials and legacy `Azure__*` credentials do not change vault authentication. Local sign-in and unrelated features, including the Docker sandbox, can run without Key Vault settings because the client is created on demand. The sandbox does not inherit diff --git a/docs/GRAPH-DEVELOPMENT.md b/docs/GRAPH-DEVELOPMENT.md index 8e52fd2..857f3ab 100644 --- a/docs/GRAPH-DEVELOPMENT.md +++ b/docs/GRAPH-DEVELOPMENT.md @@ -30,69 +30,102 @@ callback preserves the original Booking session and correlation cookie. are rejected. The implementation discovers `/me/calendar` for the account that signs in. No calendar-email setting is required, and another user's shared calendar is not selected. -## Local configuration +## Calendar configuration -Reuse the application's existing Azure registration and credentials. Graph reads -`Azure__TenantId`, `Azure__ClientId`, and `Azure__ClientSecret` directly; there are -no separate Graph credential overrides or application-secret vault references. -The same registration must have the delegated calendar permission and approved -calendar callback from the prerequisites above. +Calendar authentication and Key Vault access use different identities. The calendar +uses Booking's existing login registration: `Auth__TenantId` and `Auth__ClientId` +supply its IDs. There are no separate Graph ID overrides. That registration must +have the delegated calendar permission and approved callback from the prerequisites +above. The deployment identity's `AZURE_CLIENT_ID` is unrelated. + +The application reads the calendar client secret directly from the environment's +Key Vault under the fixed name `azure-client-secret`. An operator stores the +Entra credential's **Value**, not its Secret ID, under that name. The credential +must belong to the registration selected by the calendar client and tenant IDs. +There is no client-secret environment variable, configurable secret-name setting, +or App Service Key Vault reference. | Setting | Value | | --- | --- | -| `Azure__TenantId` | Existing application tenant GUID | -| `Azure__ClientId` | Existing application client GUID | -| `Azure__ClientSecret` | Existing application secret value | +| `Azure__KeyVaultUrl` | Environment vault URL; supplied by Bicep in hosted environments | | `Graph__RedirectUri` | Registered calendar callback URI | - -The calendar callback is separate from Booking login's `/signin-oidc` callback. -Configure it through the existing private configuration mechanism. OS environment -variables take precedence. Local token persistence uses files and does not contact -Key Vault. - -Start normally with `npm start`, sign into Booking as an active site administrator, -stop emulating, and open `/admin`. The development panel also allows a read-only -connectivity check and an explicit test-meeting write. - -## Key Vault credentials and future federation - -Hosted connections reuse `Azure__TenantId`, `Azure__ClientId`, and -`Azure__ClientSecret` already configured in Azure App Service. The application -reads those settings at runtime; no separate Graph tenant/client settings or -client-secret entry in Key Vault are needed. Set `Graph__RedirectUri` to the -registered calendar callback for that environment. - -Only the mutable token cache needs a Key Vault secret. The application always uses -the fixed name `graph-calendar-token-cache` and creates it after verified Microsoft -sign-in. Neither the name nor the token contents need deployment parameters. The -application credential is not included in the cache secret. - -`Azure__KeyVaultUrl` selects the environment vault and is supplied by the existing -Bicep template. Because the Azure credential trio is configured, the existing -secrets service uses that service principal for vault access. It must have secret -read/write access to the environment vault; granting access only to the App -Service's managed identity does not authorize that service principal. The existing -secrets service remains unchanged. +| `Auth__TenantId` | Existing Booking login tenant GUID | +| `Auth__ClientId` | Existing Booking login client GUID | + +Calendar authentication reuses Booking’s existing login tenant and client IDs and reads the application client secret directly from Key Vault. Configuration validation reports +all invalid or missing calendar IDs, callback, and scopes together before trying +to access the vault. Vault access failures then produce safe configuration guidance. + +## Hosted setup and rotation + +1. Store the Entra client secret value in the environment vault as + `azure-client-secret`. +2. Set the GitHub Environment variable `GRAPH__REDIRECT_URI` to the registered + calendar callback. For test, use + `https://booking-test.ucdavis.edu/api/development-graph/callback`, registered + exactly as a Web redirect URI in Entra. +3. Keep the existing `AUTH_TENANT_ID` and `AUTH_CLIENT_ID` variables for the Booking + login registration. The calendar uses these same IDs; no additional ID + variables are required. +4. Deploy the updated application and runtime settings. Verify the connection in + `/admin` before creating a test meeting. + +Both **CI/CD** and **Configure Azure** apply nonempty runtime variable values to +App Service. The local deploy wrapper accepts the same variable names. Changing a +GitHub variable alone does not apply it; run a deployment workflow. Calendar +settings remain optional for deployments that do not use the calendar. No client +secret or reference needs to be added to GitHub. If previously configured, remove +the obsolete `GRAPH__CLIENT_SECRET_REFERENCE` GitHub variable and the +`Graph__ClientSecret` App Service setting; neither is read by the new code. + +Bicep already provisions the environment vault, the App Service system-assigned +managed identity, vault URL, and the identity's **Key Vault Secrets Officer** grant. +No additional Bicep parameters or role grants for the calendar registration are +needed. The application retrieves the credential through the same secrets service +used by Payments. There is no credential-value cache in the Graph client factory: +it requests the latest vault version each time it creates a Microsoft client. + +To rotate, create a replacement credential in Entra and save its value as a new +version of `azure-client-secret`. The next calendar operation reads that value; +no GitHub update, App Service reference refresh, app restart, or deployment is +required. An operation already in progress may still use the earlier value. Verify +calendar access before revoking the old credential. Key Vault does not create or +renew the Entra credential itself. Vault failure stops the operation; no old +credential or environment-variable fallback is used. + +## Local development + +Local calendar operations also read `azure-client-secret` from Key Vault. +Configure the test vault URL through your private configuration mechanism and +sign in with `az login`. Your user or developer security group needs vault secret +read access. No shared client secret needs to be kept in a local configuration +file. The Docker sandbox does not inherit your host's Azure CLI login; use the +backend running on your host when connecting to the real test vault. + +Set `Graph__RedirectUri` to the approved localhost callback. OS environment +variables take precedence. Start normally with `npm start`, sign into Booking as +an active site administrator, stop emulating, and open `/admin`. Local token +persistence uses files; only the application credential is retrieved from Key Vault. + +## Key Vault access and token cache + +Vault access is independent of calendar credentials. Hosted environments use +`ManagedIdentityCredential`; local Development uses `DefaultAzureCredential`, +including the developer's Azure CLI login. The secrets service ignores both the +legacy `Azure__*` credential trio and `Graph__*` application credentials. Payments +keys and calendar secrets therefore continue using the App Service identity when +calendar credentials are added or rotated. The calendar app registration does not +need Key Vault access. + +The mutable token cache uses the fixed secret name `graph-calendar-token-cache`, +created by the application after verified Microsoft sign-in. No placeholder cache +secret or cached token values need to be deployed. The app registration's secret +and the mutable token cache are separate vault secrets with separate purposes. +The application credential is never saved in the token cache. Federated application credentials remain a future replacement for -`IGraphClientFactory`. Federation does not by itself remove delegated calendar -consent, refresh tokens, or reconnect requirements. Deployment OIDC federation is -separate from runtime Graph authentication. - -## Hosted deployment through Bicep - -The existing template creates environment-specific vaults, grants the App Service -identity **Key Vault Secrets Officer** (read/write), and sets the vault URI. Graph -uses the existing Azure service-principal credentials as described above; ensure -that identity also has vault access. No additional Graph parameters are added to -`main.bicep`, `compute.bicep`, or `deploy.sh`. They do not provision a client-secret -entry, the token-cache secret, or token values for calendar authentication. - -Maintain the existing `Azure__TenantId`, `Azure__ClientId`, and `Azure__ClientSecret` -settings in App Service, and configure `Graph__RedirectUri` there for the approved -public HTTPS callback. Infrastructure deployments replace the settings managed by -their templates; preserve or reapply these runtime settings through your existing -configuration process when deploying infrastructure. +`IGraphClientFactory`. Deployment OIDC federation is separate from runtime calendar +authentication and does not remove delegated consent or reconnect requirements. The connection interface is available to site administrators in all environments; no enablement flag is required. Missing credentials, callback configuration, or diff --git a/infrastructure/azure/README.md b/infrastructure/azure/README.md index 377d0bf..20a2c85 100644 --- a/infrastructure/azure/README.md +++ b/infrastructure/azure/README.md @@ -56,18 +56,25 @@ The existing environment vault holds the delegated calendar's MSAL cache under the fixed secret name `graph-calendar-token-cache`. The application creates it after verified Microsoft sign-in; Bicep never handles cached token values. -Calendar authentication reuses the existing `Azure__TenantId`, `Azure__ClientId`, -and `Azure__ClientSecret` App Service settings. Configure `Graph__RedirectUri` in -App Service for the approved calendar callback. There are no additional Graph -parameters in `main.bicep`, `compute.bicep`, or the local deploy wrapper, and no -separate application-secret entry in Key Vault is required. Preserve or reapply -these runtime settings through your existing configuration process after -infrastructure deployments that replace App Service settings. - -The existing secrets service uses the configured Azure service principal to -access Key Vault. That identity needs secret read/write access to the environment -vault; the template's grant to the App Service managed identity alone is not -sufficient for service-principal authentication. +Calendar authentication reads the latest `azure-client-secret` directly from +the environment vault through the existing secrets service. An operator stores +the Entra application's client secret **Value** there. No client secret or Key +Vault reference is passed through GitHub or App Service settings. + +Set `GRAPH__REDIRECT_URI` to the registered calendar callback. Calendar IDs use +the existing Booking login settings (`AUTH_TENANT_ID` and `AUTH_CLIENT_ID`). +There are no separate Graph ID overrides. +**CI/CD**, **Configure Azure**, and the local deploy wrapper apply these runtime +settings. No new Bicep parameters are required. To rotate the credential, save the +replacement Entra secret value as a new version of `azure-client-secret`. +The next calendar operation reads it without deployment or restart. + +The secrets service always uses managed identity in hosted environments, independently +of the calendar credentials. Payments keys, the calendar credential, and calendar +tokens use this same vault identity; the calendar app registration does not need +vault permissions. Local Development uses `DefaultAzureCredential` with the +developer's Azure CLI login and also reads the calendar credential from the test +vault. The local token cache remains file-based. Test meetings with email invitations are allowed in the `Development` and `test` backend environments. They are hidden and blocked in `prod`; calendar connection diff --git a/infrastructure/azure/deploy.sh b/infrastructure/azure/deploy.sh index ad42a7c..ab07360 100755 --- a/infrastructure/azure/deploy.sh +++ b/infrastructure/azure/deploy.sh @@ -38,7 +38,7 @@ USAGE 'AGGIEENTERPRISE__CONSUMERKEY, AGGIEENTERPRISE__CONSUMERSECRET' \ ' AGGIEENTERPRISE__GRAPHQLURL, AGGIEENTERPRISE__SCOPEAPP' \ ' AGGIEENTERPRISE__SCOPEENV, AGGIEENTERPRISE__TOKENENDPOINT, AUTH_CALLBACK_PATH' \ - ' AUTH_CLIENT_ID, AUTH_DOMAIN, AUTH_INSTANCE, AUTH_TENANT_ID' \ + ' AUTH_CLIENT_ID, AUTH_DOMAIN, AUTH_INSTANCE, AUTH_TENANT_ID, GRAPH__REDIRECT_URI' \ ' NOTIFICATION_BASE_URL, NOTIFICATION_DEFAULT_APP_NAME' \ ' NOTIFICATION_DEFAULT_BUTTON_TEXT, OTEL_EXPORTER_OTLP_ENDPOINT' \ ' OTEL_EXPORTER_OTLP_HEADERS, OTEL_EXPORTER_OTLP_PROTOCOL' \ @@ -284,6 +284,7 @@ add_setting "Auth__ClientId" "${AUTH_CLIENT_ID:-}" add_setting "Auth__Domain" "${AUTH_DOMAIN:-}" add_setting "Auth__Instance" "${AUTH_INSTANCE:-https://login.microsoftonline.com/}" add_setting "Auth__TenantId" "${AUTH_TENANT_ID:-}" +add_setting "Graph__RedirectUri" "${GRAPH__REDIRECT_URI:-}" add_setting "Notification__BaseUrl" "${NOTIFICATION_BASE_URL:-}" add_setting "Notification__DefaultAppName" "${NOTIFICATION_DEFAULT_APP_NAME:-}" add_setting "Notification__DefaultButtonText" "${NOTIFICATION_DEFAULT_BUTTON_TEXT:-}" diff --git a/infrastructure/azure/deployment-settings.json b/infrastructure/azure/deployment-settings.json index 8061959..44b28d7 100644 --- a/infrastructure/azure/deployment-settings.json +++ b/infrastructure/azure/deployment-settings.json @@ -46,6 +46,13 @@ "valueType": "string", "description": "Environment portion of the Aggie Enterprise OAuth scope." }, + { + "githubName": "GRAPH__REDIRECT_URI", + "appServiceName": "Graph__RedirectUri", + "classification": "variable", + "valueType": "string", + "description": "Public HTTPS calendar callback URI registered as a Web redirect in Entra." + }, { "githubName": "PAYMENTS_BASE_URL", "appServiceName": "Payments__BaseUrl", diff --git a/server/Development/Graph/GraphClientFactory.cs b/server/Development/Graph/GraphClientFactory.cs index 0249ddc..f870c3f 100644 --- a/server/Development/Graph/GraphClientFactory.cs +++ b/server/Development/Graph/GraphClientFactory.cs @@ -1,4 +1,5 @@ using Microsoft.Identity.Client; +using Server.Services; namespace Server.Development.Graph; @@ -9,20 +10,34 @@ public interface IGraphClientFactory } /// Secret-based authentication today; replace this registration for future federated assertions. -public sealed class GraphClientFactory : IGraphClientFactory +public sealed class GraphClientFactory(ISecretsService secrets) : IGraphClientFactory { - public Task CreateAsync( + public const string ClientSecretName = "azure-client-secret"; + + public async Task CreateAsync( GraphProbeSettings settings, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); - var secret = settings.ClientSecret; + string secret; + try + { + // Read the latest version for each operation so rotation needs no app deployment. + secret = await secrets.GetSecretAsync(ClientSecretName, cancellationToken); + } + catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) { throw; } + catch (Exception) + { + throw new GraphProbeConfigurationException( + "Could not read azure-client-secret from Key Vault. Check Azure__KeyVaultUrl, the secret's existence, and vault permissions."); + } + if (string.IsNullOrWhiteSpace(secret)) - throw new GraphProbeConfigurationException("Azure__ClientSecret is empty. Configure a nonempty secret value before connecting the calendar."); + throw new GraphProbeConfigurationException("Store a nonempty Entra client secret value in Key Vault as azure-client-secret before connecting the calendar."); - return Task.FromResult(ConfidentialClientApplicationBuilder.Create(settings.ClientId) + return ConfidentialClientApplicationBuilder.Create(settings.ClientId) .WithClientSecret(secret) .WithRedirectUri(settings.RedirectUri.AbsoluteUri) .WithAuthority($"https://login.microsoftonline.com/{settings.TenantId}") - .Build()); + .Build(); } } diff --git a/server/Development/Graph/GraphProbeSettings.cs b/server/Development/Graph/GraphProbeSettings.cs index 6cdd090..e147a0b 100644 --- a/server/Development/Graph/GraphProbeSettings.cs +++ b/server/Development/Graph/GraphProbeSettings.cs @@ -1,17 +1,13 @@ namespace Server.Development.Graph; public sealed record GraphProbeSettings( - string TenantId, string ClientId, string[] Scopes, string ClientSecret, Uri RedirectUri) + string TenantId, string ClientId, string[] Scopes, Uri RedirectUri) { public override string ToString() => "Graph settings (credentials redacted)"; public static GraphProbeSettings Read(IConfiguration configuration, bool hosted = false) { - var secret = configuration["Azure:ClientSecret"]; - if (string.IsNullOrWhiteSpace(secret)) - { - throw new GraphProbeConfigurationException("Configure Azure__ClientSecret before connecting the calendar."); - } + var errors = new List(); var redirect = configuration["Graph:RedirectUri"]; if (!Uri.TryCreate(redirect, UriKind.Absolute, out var redirectUri) || (hosted ? redirectUri.Scheme != Uri.UriSchemeHttps || redirectUri.IsLoopback @@ -19,17 +15,21 @@ public static GraphProbeSettings Read(IConfiguration configuration, bool hosted !string.IsNullOrEmpty(redirectUri.UserInfo) || !string.IsNullOrEmpty(redirectUri.Query) || !string.IsNullOrEmpty(redirectUri.Fragment) || redirectUri.AbsolutePath == "/") { - throw new GraphProbeConfigurationException( + errors.Add( hosted ? "Configure Graph__RedirectUri with the approved public HTTPS calendar callback, registered exactly as a Web redirect URI in Entra." : "Configure Graph__RedirectUri with an approved localhost HTTP callback, such as http://localhost:5173/api/development-graph/callback, registered exactly as a Web redirect URI in Entra. No default is assumed."); } - // Reuse the application's existing Azure registration and credential. - var tenantId = configuration["Azure:TenantId"]; - var clientId = configuration["Azure:ClientId"]; - if (!Guid.TryParse(tenantId, out var tenant) || !Guid.TryParse(clientId, out var client)) + // Reuse Booking's login registration, never the deployment identity. + var tenantId = configuration["Auth:TenantId"]; + var clientId = configuration["Auth:ClientId"]; + if (!Guid.TryParse(tenantId, out var tenant)) { - throw new GraphProbeConfigurationException("Configure Azure__TenantId and Azure__ClientId as GUIDs."); + errors.Add("Configure Auth__TenantId as a GUID."); + } + if (!Guid.TryParse(clientId, out var client)) + { + errors.Add("Configure Auth__ClientId as a GUID."); } var configuredScopes = (configuration["Graph:Scopes"] ?? "Calendars.ReadWrite") @@ -41,13 +41,16 @@ public static GraphProbeSettings Read(IConfiguration configuration, bool hosted if (!configuredScopes.Contains("Calendars.ReadWrite", StringComparer.OrdinalIgnoreCase) || configuredScopes.Any(scope => !allowedScopes.Contains(scope, StringComparer.OrdinalIgnoreCase))) { - throw new GraphProbeConfigurationException( + errors.Add( "Graph__Scopes must contain Calendars.ReadWrite and may include only MSAL's standard openid, profile, and offline_access scopes. User.Read, shared-calendar scopes, and .default are not supported."); } + if (errors.Count > 0) + throw new GraphProbeConfigurationException(string.Join(" ", errors)); + // MSAL adds its reserved identity/refresh scopes itself. string[] scopes = ["https://graph.microsoft.com/Calendars.ReadWrite"]; - return new(tenant.ToString(), client.ToString(), scopes, secret, redirectUri); + return new(tenant.ToString(), client.ToString(), scopes, redirectUri!); } } diff --git a/server/Program.cs b/server/Program.cs index 69285a6..ab775ec 100644 --- a/server/Program.cs +++ b/server/Program.cs @@ -74,7 +74,7 @@ builder.Services.AddScoped(); builder.Services.AddRosettaClientWithFactory(options => builder.Configuration.GetSection("RosettaClient").Bind(options)); builder.Services.AddScoped(); - builder.Services.AddSecretsService(builder.Configuration); + builder.Services.AddSecretsService(builder.Configuration, hosted: !builder.Environment.IsDevelopment()); builder.Services.AddPaymentsService(builder.Configuration); builder.Services.AddAggieEnterpriseService(builder.Configuration); // add auth policies here diff --git a/server/Services/SecretsService.cs b/server/Services/SecretsService.cs index 0ed899d..e5a5fe4 100644 --- a/server/Services/SecretsService.cs +++ b/server/Services/SecretsService.cs @@ -40,10 +40,15 @@ public async Task SetSecretAsync(string secretName, string value, CancellationTo public static class SecretsServiceCollectionExtensions { - public static IServiceCollection AddSecretsService(this IServiceCollection services, IConfiguration configuration) + public static IServiceCollection AddSecretsService(this IServiceCollection services, IConfiguration configuration, + bool hosted = false) { + // Vault access is independent of the calendar's application credentials. + services.AddSingleton(_ => hosted + ? new ManagedIdentityCredential() + : new DefaultAzureCredential()); // Defer configuration validation and client creation until secrets are needed. - services.AddSingleton(_ => + services.AddSingleton(provider => { var vaultUrl = configuration["Azure:KeyVaultUrl"]; if (!Uri.TryCreate(vaultUrl, UriKind.Absolute, out var vaultUri) || vaultUri.Scheme != Uri.UriSchemeHttps) @@ -51,27 +56,7 @@ public static IServiceCollection AddSecretsService(this IServiceCollection servi throw new InvalidOperationException("Configure Azure:KeyVaultUrl with an HTTPS Key Vault URL before using the secrets service."); } - var tenantId = configuration["Azure:TenantId"]; - var clientId = configuration["Azure:ClientId"]; - var clientSecret = configuration["Azure:ClientSecret"]; - - TokenCredential credential; - if (tenantId != null || clientId != null || clientSecret != null) - { - if (string.IsNullOrWhiteSpace(tenantId) || string.IsNullOrWhiteSpace(clientId) || - string.IsNullOrWhiteSpace(clientSecret)) - { - throw new InvalidOperationException("Configure Azure:TenantId, Azure:ClientId, and Azure:ClientSecret together, or omit all three to use DefaultAzureCredential."); - } - - credential = new ClientSecretCredential(tenantId, clientId, clientSecret); - } - else - { - credential = new DefaultAzureCredential(); - } - - return new SecretClient(vaultUri, credential); + return new SecretClient(vaultUri, provider.GetRequiredService()); }); services.AddSingleton(provider => new SecretsService(() => provider.GetRequiredService())); return services; diff --git a/tests/server.tests/Development/GraphAuthorizationCallbackTests.cs b/tests/server.tests/Development/GraphAuthorizationCallbackTests.cs index 4964859..ccb1f92 100644 --- a/tests/server.tests/Development/GraphAuthorizationCallbackTests.cs +++ b/tests/server.tests/Development/GraphAuthorizationCallbackTests.cs @@ -46,7 +46,6 @@ public void Rejects_nonlocal_or_ambiguous_redirects(string redirect) { var configuration = new ConfigurationBuilder().AddInMemoryCollection(new Dictionary { - ["Azure:ClientSecret"] = "fake-secret", ["Graph:RedirectUri"] = redirect, }).Build(); var action = () => GraphProbeSettings.Read(configuration); diff --git a/tests/server.tests/Development/GraphConnectionTests.cs b/tests/server.tests/Development/GraphConnectionTests.cs index 8d99ca2..7a8eaf2 100644 --- a/tests/server.tests/Development/GraphConnectionTests.cs +++ b/tests/server.tests/Development/GraphConnectionTests.cs @@ -78,7 +78,6 @@ public async Task Plaintext_cache_is_unavailable_outside_development() [Theory] [InlineData("Graph:RedirectUri")] - [InlineData("Azure:ClientSecret")] public void Missing_required_configuration_stops_before_authentication(string missing) { var configuration = Configuration(); @@ -90,11 +89,10 @@ public void Missing_required_configuration_stops_before_authentication(string mi } [Fact] - public void Existing_azure_configuration_is_supported_for_confidential_authentication() + public void Graph_configuration_is_supported_for_confidential_authentication() { var settings = GraphProbeSettings.Read(Configuration()); - settings.ClientSecret.Should().Be("secret-value"); settings.ToString().Should().NotContain("secret-value"); settings.Scopes.Should().BeEquivalentTo( "https://graph.microsoft.com/Calendars.ReadWrite"); @@ -133,8 +131,8 @@ public void Configuration_rejects_unrelated_or_shared_write_scopes(string scopes } [Theory] - [InlineData("Azure:TenantId", "not-a-tenant")] - [InlineData("Azure:ClientId", "")] + [InlineData("Auth:TenantId", "not-a-tenant")] + [InlineData("Auth:ClientId", "")] public void Invalid_required_settings_fail_locally(string key, string value) { var configuration = Configuration(); @@ -145,15 +143,14 @@ public void Invalid_required_settings_fail_locally(string key, string value) action.Should().Throw(); } - private static IGraphClientFactory ClientFactory() => new GraphClientFactory(); + private static IGraphClientFactory ClientFactory() => new GraphClientFactory(new GraphSecretStub()); private static IConfigurationRoot Configuration() => new ConfigurationBuilder().AddInMemoryCollection( new Dictionary { ["Graph:RedirectUri"] = "http://localhost:5173/api/development-graph/callback", - ["Azure:TenantId"] = "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee", - ["Azure:ClientId"] = "aaaaaaaa-1111-2222-3333-444444444444", - ["Azure:ClientSecret"] = "secret-value", + ["Auth:TenantId"] = "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee", + ["Auth:ClientId"] = "aaaaaaaa-1111-2222-3333-444444444444", }).Build(); private sealed class TestEnvironment(string name) : IHostEnvironment diff --git a/tests/server.tests/Development/GraphSecretStub.cs b/tests/server.tests/Development/GraphSecretStub.cs new file mode 100644 index 0000000..6531390 --- /dev/null +++ b/tests/server.tests/Development/GraphSecretStub.cs @@ -0,0 +1,20 @@ +using Server.Services; + +namespace Server.Tests.Development; + +internal sealed class GraphSecretStub : ISecretsService +{ + public string Value { get; set; } = "synthetic-client-secret"; + public Exception? Failure { get; set; } + public List<(string Name, CancellationToken Token)> Reads { get; } = []; + + public Task GetSecretAsync(string secretName, CancellationToken cancellationToken = default) + { + Reads.Add((secretName, cancellationToken)); + cancellationToken.ThrowIfCancellationRequested(); + return Failure == null ? Task.FromResult(Value) : Task.FromException(Failure); + } + + public Task SetSecretAsync(string secretName, string value, CancellationToken cancellationToken = default) + => throw new InvalidOperationException("The calendar must not write its application credential."); +} diff --git a/tests/server.tests/Development/GraphTokenCacheTests.cs b/tests/server.tests/Development/GraphTokenCacheTests.cs index 64cb26e..fa18060 100644 --- a/tests/server.tests/Development/GraphTokenCacheTests.cs +++ b/tests/server.tests/Development/GraphTokenCacheTests.cs @@ -151,14 +151,15 @@ public async Task A_missing_cache_secret_is_a_disconnected_state_not_a_failure() } [Fact] - public async Task Hosted_connections_reuse_existing_azure_credentials_and_store_only_tokens_in_vault() + public async Task Hosted_connections_use_graph_credentials_and_store_only_tokens_in_vault() { var fixture = new Fixture(); - fixture.Configuration["Azure:ClientSecret"] = "existing-deployed-secret"; + var credentialSecrets = new GraphSecretStub { Value = "existing-deployed-secret" }; var settings = GraphProbeSettings.Read(fixture.Configuration, hosted: true); - var client = await new GraphClientFactory().CreateAsync(settings, default); + var client = await new GraphClientFactory(credentialSecrets).CreateAsync(settings, default); client.AppConfig.ClientSecret.Should().Be("existing-deployed-secret"); - fixture.Secrets.Reads.Should().Be(0, "application credentials come from configuration"); + credentialSecrets.Reads.Should().ContainSingle().Which.Name.Should().Be(GraphClientFactory.ClientSecretName); + fixture.Secrets.Reads.Should().Be(0, "the credential and token cache are separate secrets"); await fixture.ConnectAsync(); fixture.Secrets.Writes.Should().Be(1, "the verified token cache still belongs in Key Vault"); @@ -332,9 +333,8 @@ private sealed class Fixture public Verification Access { get; } public IConfigurationRoot Configuration { get; } = new ConfigurationBuilder().AddInMemoryCollection(new Dictionary { - ["Azure:TenantId"] = "11111111-1111-1111-1111-111111111111", - ["Azure:ClientId"] = "22222222-2222-2222-2222-222222222222", - ["Azure:ClientSecret"] = "synthetic-client-secret", + ["Auth:TenantId"] = "11111111-1111-1111-1111-111111111111", + ["Auth:ClientId"] = "22222222-2222-2222-2222-222222222222", ["Graph:RedirectUri"] = "https://booking.example.edu/api/development-graph/callback", }).Build(); public TestEnvironment Environment { get; } = new("test"); diff --git a/tests/server.tests/Services/SecretsServiceTests.cs b/tests/server.tests/Services/SecretsServiceTests.cs index 7fcebd4..f3eb7ef 100644 --- a/tests/server.tests/Services/SecretsServiceTests.cs +++ b/tests/server.tests/Services/SecretsServiceTests.cs @@ -1,4 +1,6 @@ using Azure; +using Azure.Core; +using Azure.Identity; using Azure.Security.KeyVault.Secrets; using FluentAssertions; using Microsoft.Extensions.Configuration; @@ -70,58 +72,31 @@ public async Task Invalid_vault_urls_are_rejected_on_use_without_exposing_the_va } [Theory] - [InlineData("Azure:TenantId", null)] - [InlineData("Azure:TenantId", "")] - [InlineData("Azure:TenantId", " \t")] - [InlineData("Azure:ClientId", null)] - [InlineData("Azure:ClientId", "")] - [InlineData("Azure:ClientId", " \t")] - [InlineData("Azure:ClientSecret", null)] - [InlineData("Azure:ClientSecret", "")] - [InlineData("Azure:ClientSecret", " \t")] - public void Incomplete_client_credentials_are_rejected_without_exposing_configuration_values( - string incompleteKey, string? incompleteValue) + [InlineData(true)] + [InlineData(false)] + public void Vault_authentication_does_not_depend_on_calendar_or_legacy_credentials(bool hosted) { var values = ClientCredentialValues(); - values[incompleteKey] = incompleteValue; + values["Azure:ClientSecret"] = null; + values["Graph:TenantId"] = TenantId; + values["Graph:ClientId"] = ClientId; + values["Graph:ClientSecret"] = ClientSecret; var services = new ServiceCollection(); - services.AddSecretsService(Configuration(values)); + services.AddSecretsService(Configuration(values), hosted: hosted); using var provider = BuildProvider(services); - var resolve = () => provider.GetRequiredService(); - var error = (resolve.Should().Throw()).Which; - - error.Message.Should().Contain("Azure:TenantId").And.Contain("Azure:ClientId") - .And.Contain("Azure:ClientSecret"); - error.ToString().Should().NotContain(ClientSecret).And.NotContain(TenantId) - .And.NotContain(ClientId); - error.InnerException.Should().BeNull(); - } - - [Theory] - [InlineData("Azure:TenantId", "")] - [InlineData("Azure:TenantId", " \t")] - [InlineData("Azure:ClientId", "")] - [InlineData("Azure:ClientId", " \t")] - [InlineData("Azure:ClientSecret", "")] - [InlineData("Azure:ClientSecret", " \t")] - public void Explicit_blank_credentials_are_rejected_instead_of_using_default_credentials( - string credentialKey, string credentialValue) - { - var services = new ServiceCollection(); - services.AddSecretsService(Configuration(new Dictionary - { - ["Azure:KeyVaultUrl"] = VaultUrl, - [credentialKey] = credentialValue, - })); - using var provider = BuildProvider(services); - var resolve = () => provider.GetRequiredService(); + var client = provider.GetRequiredService(); + var credential = provider.GetRequiredService(); - resolve.Should().Throw().Which.Message.Should().Contain(credentialKey); + client.VaultUri.Should().Be(new Uri(VaultUrl)); + if (hosted) + credential.Should().BeOfType(); + else + credential.Should().BeOfType(); } [Fact] - public void Complete_client_credentials_resolve_a_singleton_client_for_the_configured_vault() + public void Vault_client_is_a_singleton_even_when_legacy_credentials_are_present() { var services = new ServiceCollection(); services.AddSecretsService(Configuration(ClientCredentialValues()));