From c4126a3c8c38fc7d1f52390f1f79afb551f11fe7 Mon Sep 17 00:00:00 2001 From: Blair L Murri Date: Mon, 3 Feb 2025 11:51:40 -0800 Subject: [PATCH] Validate provided user assigned managed identity (#832) --- src/deploy-cromwell-on-azure/Deployer.cs | 22 ++++++++++++++++++---- 1 file changed, 18 insertions(+), 4 deletions(-) diff --git a/src/deploy-cromwell-on-azure/Deployer.cs b/src/deploy-cromwell-on-azure/Deployer.cs index 6f1d924b..50b9fcd2 100644 --- a/src/deploy-cromwell-on-azure/Deployer.cs +++ b/src/deploy-cromwell-on-azure/Deployer.cs @@ -585,8 +585,20 @@ await Execute("Validating existing Azure resources...", async () => if (!string.IsNullOrWhiteSpace(configuration.IdentityResourceId)) { - ConsoleEx.WriteLine($"Using existing user-assigned managed identity: {configuration.IdentityResourceId}"); - managedIdentity = await GetUserManagedIdentityAsync(configuration.IdentityResourceId); + var identityResourceId = ResourceIdentifier.Parse(configuration.IdentityResourceId); + + if (!UserAssignedIdentityResource.CreateResourceIdentifier(identityResourceId.SubscriptionId, identityResourceId.ResourceGroupName, identityResourceId.Name).Equals(identityResourceId) + // https://learn.microsoft.com/azure/azure-resource-manager/management/resource-name-rules#microsoftmanagedidentity + // https://learn.microsoft.com/entra/identity/managed-identities-azure-resources/how-manage-user-assigned-managed-identities?pivots=identity-mi-methods-azp#create-a-user-assigned-managed-identity + || identityResourceId.Name.Length < 3 || identityResourceId.Name.Length > 24 + || !char.IsAsciiLetterOrDigit(identityResourceId.Name[0]) + || !identityResourceId.Name.Skip(1).All(@char => char.IsAsciiLetterOrDigit(@char) || '-' == @char || '_' == @char)) + { + throw new ValidationException($"{nameof(configuration.IdentityResourceId)} is invalid. It must be a user assigned managed identity with a valid name that isn't longer than 24 characters.", false); + } + + ConsoleEx.WriteLine($"Using existing user-assigned managed identity: {identityResourceId}"); + managedIdentity = await GetUserManagedIdentityAsync(identityResourceId); } else { @@ -2040,10 +2052,12 @@ private Task CreateUserManagedIdentityAsync() }); } - private async Task GetUserManagedIdentityAsync(string resourceId) + private async Task GetUserManagedIdentityAsync(ResourceIdentifier resourceId) { + ArgumentNullException.ThrowIfNull(resourceId); + return await armSubscription.GetUserAssignedIdentitiesAsync(cts.Token) - .SingleOrDefaultAsync(id => string.Equals(id.Id.ToString(), resourceId, StringComparison.OrdinalIgnoreCase), cts.Token); + .SingleAsync(id => resourceId.Equals(id.Id), cts.Token); } private async Task DeleteResourceGroupAsync(CancellationToken cancellationToken)