<# .SYNOPSIS Creates a key vault and a secret in your subscription and gives the EasyLife 365 app access to the secret. .DESCRIPTION EasyLife 365 setup script. Use case: identity/credential-renewal-secret (a renewed client secret). Version: v1. Source: https://docs.easylife365.cloud/downloads/identity/credential-renewal-secret/v1/create.ps1 In the subscription you are signed in to, the script: 1. looks up the service principal of the EasyLife 365 app (-AppId) in your tenant; 2. creates the resource group -ResourceGroupName in -Region, when the key vault and the group don't exist yet; 3. creates the key vault -VaultName: standard tier, Azure role-based access control, soft delete kept 90 days. An existing vault must use Azure role-based access control: on access policies the script stops; 4. creates the secret -SecretName with a random value, through Azure Resource Manager. The value goes straight into the vault and is never shown. The script doesn't need a role that reads or writes secrets for this; 5. assigns the role "Key Vault Secrets Officer" to the service principal, on that secret only. You can run it again: whatever exists already is left as it is and listed as skipped. An existing secret keeps its value. The script never changes the settings of an existing resource and never deletes anything. Run it as someone who can create resources in the subscription and give access there: Owner, or Contributor together with User Access Administrator or Role Based Access Control Administrator. Needs PowerShell 7 or Windows PowerShell 5.1 with the modules Az.Accounts and Az.Resources, signed in with Connect-AzAccount. Azure Cloud Shell has everything. .PARAMETER VaultName The key vault: 3 to 24 letters, digits and hyphens, starting with a letter, ending with a letter or digit, with no two hyphens in a row. Unique in Azure. .PARAMETER SecretName The secret: 1 to 127 letters, digits and hyphens. A name that starts with a hyphen works as it is, unless it is also the start of a parameter name of this script (for example -S or -App) or of a common parameter such as -Verbose (for example -V or -E): then quote it, -SecretName '-S'. .PARAMETER Region The Azure region of a new key vault, for example westeurope. .PARAMETER AppId The application (client) ID of the EasyLife 365 app in your tenant. EasyLife 365 Admin shows it in the command. .PARAMETER ResourceGroupName Optional. The resource group of a new key vault. Default: rg-easylife365. Created in -Region when it's missing. .PARAMETER Subscription Optional. The subscription ID or name. Without it the script uses the current subscription and asks you to confirm it. .PARAMETER Yes Optional. Uses the current subscription without asking. .EXAMPLE ./create.ps1 -VaultName contoso-renewal -SecretName app-secret -Region westeurope -AppId 00000000-0000-0000-0000-000000000000 #> [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidUsingWriteHost', '', Justification = 'The script talks to the person who runs it.')] param( [Parameter(Mandatory = $true)][string]$VaultName, [Parameter(Mandatory = $true)][string]$SecretName, [Parameter(Mandatory = $true)][string]$Region, [Parameter(Mandatory = $true)][string]$AppId, [string]$ResourceGroupName = 'rg-easylife365', [string]$Subscription, [switch]$Yes ) $ErrorActionPreference = 'Stop' $role = 'Key Vault Secrets Officer' $apiVersion = '2023-07-01' $created = New-Object System.Collections.Generic.List[string] $skipped = New-Object System.Collections.Generic.List[string] # Every value is checked before anything is sent to Azure. if ($VaultName -notmatch '^[A-Za-z][A-Za-z0-9-]{1,22}[A-Za-z0-9]$' -or $VaultName.Contains('--')) { throw '-VaultName must be 3 to 24 letters, digits and hyphens, start with a letter, end with a letter or digit, and have no two hyphens in a row.' } if ($SecretName -notmatch '^[A-Za-z0-9-]{1,127}$') { throw '-SecretName must be 1 to 127 letters, digits and hyphens.' } if ($Region -notmatch '^[A-Za-z0-9]{2,40}$') { throw '-Region must be the name of an Azure region, for example westeurope.' } if ($AppId -notmatch '^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{12}$') { throw '-AppId must be the application (client) ID, a GUID such as 00000000-0000-0000-0000-000000000000.' } if ($ResourceGroupName -notmatch '^[-\w\._\(\)]{1,90}$') { throw '-ResourceGroupName is not a valid resource group name.' } $context = Get-AzContext if (-not $context) { throw 'Sign in first with Connect-AzAccount.' } if ($Subscription) { $context = Set-AzContext -Subscription $Subscription -Scope Process } Write-Host "Subscription: $($context.Subscription.Name) ($($context.Subscription.Id))" if (-not $Subscription -and -not $Yes) { $answer = Read-Host 'Create the resources in this subscription? [y/N]' if ($answer -ne 'y') { throw 'Stopped. Nothing was created. Pass -Subscription to choose another subscription.' } } # The service principal exists once an administrator has consented to the EasyLife 365 app in your tenant. $servicePrincipal = Get-AzADServicePrincipal -ApplicationId $AppId -ErrorAction SilentlyContinue | Select-Object -First 1 if (-not $servicePrincipal) { throw "Stopped. Nothing was created. There is no service principal for the app $AppId in this tenant. Check that you're signed in to the right tenant, and that an administrator has consented to the EasyLife 365 app." } Write-Host "EasyLife 365 app: $($servicePrincipal.DisplayName), app ID $AppId, service principal $($servicePrincipal.Id)" # EasyLife 365 works with Azure role-based access control only. A vault on access policies is never changed here. function Assert-RoleBasedAccess([string]$VaultId) { $vault = Get-AzResource -ResourceId $VaultId -ExpandProperties if ($vault.Properties.enableRbacAuthorization -ne $true) { throw "Stopped. The key vault $VaultName uses access policies. EasyLife 365 works with Azure role-based access control only. Switch the vault's permission model to Azure role-based access control (Access configuration in the Azure portal), or use another vault, then run the script again. The script changes nothing on this vault." } } $vault = Get-AzResource -ResourceType 'Microsoft.KeyVault/vaults' -Name $VaultName | Select-Object -First 1 if ($vault) { Assert-RoleBasedAccess $vault.ResourceId $skipped.Add("key vault $VaultName (exists in resource group $($vault.ResourceGroupName))") } else { if (Get-AzResourceGroup -Name $ResourceGroupName -ErrorAction SilentlyContinue) { $skipped.Add("resource group $ResourceGroupName (exists)") } else { New-AzResourceGroup -Name $ResourceGroupName -Location $Region | Out-Null $created.Add("resource group $ResourceGroupName") } Write-Host "Creating the key vault $VaultName ..." $properties = @{ tenantId = $context.Tenant.Id sku = @{ family = 'A'; name = 'standard' } enableRbacAuthorization = $true enableSoftDelete = $true softDeleteRetentionInDays = 90 accessPolicies = @() } New-AzResource -ResourceGroupName $ResourceGroupName -ResourceType 'Microsoft.KeyVault/vaults' -Name $VaultName ` -Location $Region -ApiVersion $apiVersion -Properties $properties -Force | Out-Null $created.Add("key vault $VaultName") $vault = Get-AzResource -ResourceType 'Microsoft.KeyVault/vaults' -Name $VaultName -ResourceGroupName $ResourceGroupName Assert-RoleBasedAccess $vault.ResourceId } # The secret is read and created through Azure Resource Manager, so the person running the script needs no data role. $secretPath = "$($vault.ResourceId)/secrets/$SecretName`?api-version=$apiVersion" $existing = Invoke-AzRestMethod -Method GET -Path $secretPath if ($existing.StatusCode -eq 200) { $skipped.Add("secret $SecretName (exists, its value is kept)") } elseif ($existing.StatusCode -eq 404) { $bytes = New-Object byte[] 32 $random = [System.Security.Cryptography.RandomNumberGenerator]::Create() $random.GetBytes($bytes) $random.Dispose() $payload = @{ properties = @{ value = [Convert]::ToBase64String($bytes) } } | ConvertTo-Json -Compress $response = Invoke-AzRestMethod -Method PUT -Path $secretPath -Payload $payload $payload = $null $bytes = $null if ($response.StatusCode -notin 200, 201) { throw "Azure didn't create the secret $SecretName (HTTP $($response.StatusCode)): $($response.Content)" } $created.Add("secret $SecretName (with a random value)") } else { throw "Azure didn't answer whether the secret $SecretName exists (HTTP $($existing.StatusCode)): $($existing.Content)" } $scope = "$($vault.ResourceId)/secrets/$SecretName" $assignment = Get-AzRoleAssignment -ObjectId $servicePrincipal.Id -RoleDefinitionName $role -Scope $scope | Where-Object { $_.Scope -eq $scope } | Select-Object -First 1 if ($assignment) { $skipped.Add("role $role for the EasyLife 365 app on the secret (assigned)") } else { New-AzRoleAssignment -ObjectId $servicePrincipal.Id -RoleDefinitionName $role -Scope $scope | Out-Null $created.Add("role $role for the EasyLife 365 app on the secret") } Write-Host '' foreach ($item in $created) { Write-Host "Created: $item" } foreach ($item in $skipped) { Write-Host "Skipped: $item" } if ($created.Count -eq 0) { Write-Host 'Nothing changed: everything was in place already.' } Write-Host '' Write-Host "Secret: $scope" Write-Host 'Next: go back to EasyLife 365 Admin and test the connection. A new role can take a few minutes to apply.'