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
The table of contents is too big for display.
Diff view
Diff view
  •  
  •  
  •  
17 changes: 16 additions & 1 deletion .azure/scripts/New-EntraDotnetSolution.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,9 @@ param(
[string]$E2EAppRegistrationName = "",
[string]$E2EProjectPath = "",

# Additional application roles for the existing E2E/automation identity.
[string[]]$E2EAdditionalApiRoles = @(),

[string]$ApiProjectPath = "",

# Secrets are gated to prevent credential sprawl
Expand All @@ -69,6 +72,12 @@ if ($IncludeE2E -and [string]::IsNullOrWhiteSpace($E2EAppRegistrationName)) {
Write-Error "FATAL: -IncludeE2E requires -E2EAppRegistrationName."
exit 1
}
if ($E2EAdditionalApiRoles.Count -gt 0 -and -not $IncludeE2E) {
throw "Additional automation API roles require -IncludeE2E."
}
if (@($E2EAdditionalApiRoles | Where-Object { [string]::IsNullOrWhiteSpace($_) }).Count -gt 0) {
throw "Additional automation API roles must not be empty."
}

# ── .NET SDK (needed for user-secrets); modules are handled by the registration script ─
$dotnetInstalled = & dotnet --list-sdks 2>$null | Select-String "^$DotNetVersion\."
Expand Down Expand Up @@ -100,11 +109,16 @@ Write-Host ""
Write-Host "──────────────────────────────────────────────────"
Write-Host " Step 1: API App Registration (resource server)"
Write-Host "──────────────────────────────────────────────────"
$api = Invoke-Registration -Label 'API' -Arguments @{
$apiArgs = @{
Type = 'Api'
TenantId = $TenantId
AppRegistrationName = $ApiAppRegistrationName
}
if ($E2EAdditionalApiRoles.Count -gt 0) {
$apiArgs.ApplicationRoles = @(@('Asset.Automation') + $E2EAdditionalApiRoles | Select-Object -Unique)
$apiArgs.StrictApplicationRoles = $E2EAdditionalApiRoles
}
$api = Invoke-Registration -Label 'API' -Arguments $apiArgs
Save-DotnetUserSecrets -Label 'API' -ProjectPath $ApiProjectPath -ShowSecrets:$ShowSecrets -Secrets @{
"EntraExternalId:Instance" = $EntraInstanceUrl
"EntraExternalId:TenantId" = $TenantId
Expand Down Expand Up @@ -163,6 +177,7 @@ if ($IncludeE2E) {
TenantId = $TenantId
AppRegistrationName = $E2EAppRegistrationName
ApiAppId = $api.AppId
ApiRole = @(@('Asset.Automation') + $E2EAdditionalApiRoles | Select-Object -Unique)
ProjectName = (Get-DotnetProjectName $E2EProjectPath)
SkipPrerequisites = $true
}
Expand Down
4 changes: 2 additions & 2 deletions .azure/scripts/dotnet/Sync-DotnetUserSecretKeyVault.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,11 @@ Existing values are overwritten with the latest ones.

.EXAMPLE
# Publish the Web project's user-secrets (single line, safe to paste):
pwsh -File ./dotnet/Sync-DotnetUserSecretKeyVault.ps1 -Direction ToKeyVault -TenantId "<tenant-id>" -SubscriptionId "<subscription-id>" -KeyVaultName "my-kv" -ProductName "compass" -ProjectName "Web" -ProjectPath "./src/Presentation.Web"
pwsh -File ./dotnet/Sync-DotnetUserSecretKeyVault.ps1 -Direction ToKeyVault -TenantId "<tenant-id>" -SubscriptionId "<subscription-id>" -KeyVaultName "my-kv" -ProductName "agentstart" -ProjectName "Web" -ProjectPath "./src/Presentation.Web"

.EXAMPLE
# Restore them on a new machine (single line, safe to paste):
pwsh -File ./dotnet/Sync-DotnetUserSecretKeyVault.ps1 -Direction FromKeyVault -TenantId "<tenant-id>" -SubscriptionId "<subscription-id>" -KeyVaultName "my-kv" -ProductName "compass" -ProjectName "Web" -ProjectPath "./src/Presentation.Web"
pwsh -File ./dotnet/Sync-DotnetUserSecretKeyVault.ps1 -Direction FromKeyVault -TenantId "<tenant-id>" -SubscriptionId "<subscription-id>" -KeyVaultName "my-kv" -ProductName "agentstart" -ProjectName "Web" -ProjectPath "./src/Presentation.Web"

.NOTES
- Requires the .NET SDK and the Az.Accounts and Az.KeyVault modules.
Expand Down
49 changes: 41 additions & 8 deletions .azure/scripts/entra/New-EntraAppRegistration.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -51,12 +51,13 @@ param(
# Web and E2E: the API registration they call. Required for E2E, optional for Web.
[string]$ApiAppId,
[string[]]$ApiScopes = @('access_as_user', 'assets.read', 'assets.edit', 'assets.delete'),
[string]$ApiRole = 'Asset.Automation',
[string[]]$ApiRole = @('Asset.Automation'),

# Api: what the resource server exposes.
[string[]]$Scopes = @('access_as_user', 'assets.read', 'assets.edit', 'assets.delete'),
[string[]]$UserRoles,
[string[]]$ApplicationRoles,
[string[]]$StrictApplicationRoles = @(),
[ValidateSet(1, 2)][int]$AccessTokenVersion = 2,

# Web: sign-in configuration.
Expand Down Expand Up @@ -103,6 +104,9 @@ if (-not $PSBoundParameters.ContainsKey('AccessTokenClaims')) {
if ($Type -eq 'E2E' -and [string]::IsNullOrWhiteSpace($ApiAppId)) {
throw "-ApiAppId is required for -Type E2E."
}
if ($Type -eq 'E2E' -and (@($ApiRole).Count -eq 0 -or @($ApiRole | Where-Object { [string]::IsNullOrWhiteSpace($_) }).Count -gt 0)) {
throw "At least one nonempty API application role is required for -Type E2E."
}
if ($Type -eq 'Api' -and $SecretOnly) {
throw "A resource server does not need a client secret; -SecretOnly is not valid for -Type Api."
}
Expand Down Expand Up @@ -196,6 +200,17 @@ function New-RoleSpec([string]$Value, [string]$MemberType) {
return @{ Id = [guid]::NewGuid(); Value = $Value; DisplayName = $t[0]; Description = $t[1]; IsEnabled = $true; AllowedMemberTypes = @($MemberType) }
}

function Assert-StrictApplicationRoles([object[]]$ExistingRoles, [string[]]$RequiredRoles, [string[]]$UserRoleValues) {
foreach ($strictRole in $RequiredRoles) {
$matchingRoles = @($ExistingRoles | Where-Object { $_.Value -eq $strictRole })
if ($strictRole -in $UserRoleValues -or ($matchingRoles | Where-Object {
-not $_.IsEnabled -or @($_.AllowedMemberTypes).Count -ne 1 -or 'Application' -notin $_.AllowedMemberTypes
})) {
throw "Role '$strictRole' must be enabled and restricted to application members. Correct the existing role before continuing."
}
}
}

function ConvertTo-ClaimSpec($c) {
$spec = @{ name = $c.Name }
if ($c.Source) { $spec.source = $c.Source }
Expand Down Expand Up @@ -244,6 +259,24 @@ function Get-MergedResourceAccess($app, [string]$ResourceAppId, [object[]]$Wante
return @($byResource.Keys | ForEach-Object { @{ ResourceAppId = $_; ResourceAccess = @($byResource[$_]) } })
}

function Get-ApiApplicationRoles($api, [string[]]$RoleNames, [string]$ResourceAppId) {
foreach ($name in ($RoleNames | Select-Object -Unique)) {
$role = $api.AppRoles | Where-Object {
$_.Value -eq $name -and $_.IsEnabled -and $_.AllowedMemberTypes -contains 'Application'
} | Select-Object -First 1
if (-not $role) { throw "Enabled application role '$name' not found on API '$ResourceAppId'." }
$role
}
}

function Get-MissingApiRoleAssignments([object[]]$Roles, [object[]]$Assignments, $ResourceId) {
foreach ($role in $Roles) {
if (-not ($Assignments | Where-Object { $_.AppRoleId -eq $role.Id -and $_.ResourceId -eq $ResourceId })) {
$role
}
}
}

# ── Resolve the API this registration depends on ──────────────────────────────
$apiReg = $null
if ($Type -ne 'Api' -and -not [string]::IsNullOrWhiteSpace($ApiAppId)) {
Expand Down Expand Up @@ -298,6 +331,7 @@ if (-not $SecretOnly) {

if ($Type -in 'Api', 'Web') {
$existingRoles = @(@($app.AppRoles) | Where-Object { $_ } | ForEach-Object { ConvertTo-RoleSpec $_ })
Assert-StrictApplicationRoles $existingRoles $StrictApplicationRoles $UserRoles
$existingRoleValues = @($existingRoles | ForEach-Object { $_.Value })
$newRoles = @()
$newRoles += @($UserRoles | Where-Object { $_ -and $_ -notin $existingRoleValues } | ForEach-Object { New-RoleSpec $_ 'User' })
Expand Down Expand Up @@ -347,9 +381,9 @@ if (-not $SecretOnly) {
}

if ($Type -eq 'E2E') {
$role = $apiReg.AppRoles | Where-Object { $_.Value -eq $ApiRole -and $_.AllowedMemberTypes -contains 'Application' } | Select-Object -First 1
if (-not $role) { throw "Application role '$ApiRole' not found on API '$ApiAppId'. Create the API with -ApplicationRoles '$ApiRole' first." }
$merged = Get-MergedResourceAccess $app $ApiAppId @(@{ Id = $role.Id; Type = 'Role' })
$roles = @(Get-ApiApplicationRoles $apiReg $ApiRole $ApiAppId)
$wantedRoles = @($roles | ForEach-Object { @{ Id = $_.Id; Type = 'Role' } })
$merged = Get-MergedResourceAccess $app $ApiAppId $wantedRoles
if ($merged) { Update-MgApplication -ApplicationId $app.Id -RequiredResourceAccess $merged; $app = Wait-ForApplication $app.Id }
}

Expand All @@ -367,10 +401,9 @@ if (-not $SecretOnly) {

if ($Type -eq 'E2E') {
$apiSp = Get-OrNew-ServicePrincipal $ApiAppId
$assigned = Get-MgServicePrincipalAppRoleAssignment -ServicePrincipalId $sp.Id -ErrorAction SilentlyContinue |
Where-Object { $_.AppRoleId -eq $role.Id -and $_.ResourceId -eq $apiSp.Id }
if (-not $assigned) {
Write-Host "Granting '$ApiRole' to the E2E service principal..."
$assigned = @(Get-MgServicePrincipalAppRoleAssignment -ServicePrincipalId $sp.Id -All -ErrorAction Stop)
foreach ($role in @(Get-MissingApiRoleAssignments $roles $assigned $apiSp.Id)) {
Write-Host "Granting '$($role.Value)' to the automation service principal..."
New-MgServicePrincipalAppRoleAssignment -ServicePrincipalId $sp.Id -PrincipalId $sp.Id -ResourceId $apiSp.Id -AppRoleId $role.Id | Out-Null
}
}
Expand Down
127 changes: 125 additions & 2 deletions .azure/scripts/tests/New-EntraAppRegistration.Tests.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ BeforeAll {
$path = Join-Path $PSScriptRoot '..\entra\New-EntraAppRegistration.ps1'
$script:registrationPath = $path
$ast = [System.Management.Automation.Language.Parser]::ParseFile($path, [ref]$null, [ref]$null)
$wanted = 'ConvertTo-ScopeSpec', 'New-ScopeSpec', 'ConvertTo-RoleSpec', 'New-RoleSpec', 'ConvertTo-ClaimSpec', 'Get-MergedOptionalClaims', 'Get-MergedResourceAccess'
$wanted = 'ConvertTo-ScopeSpec', 'New-ScopeSpec', 'ConvertTo-RoleSpec', 'New-RoleSpec', 'Assert-StrictApplicationRoles', 'ConvertTo-ClaimSpec', 'Get-MergedOptionalClaims', 'Get-MergedResourceAccess', 'Get-ApiApplicationRoles', 'Get-MissingApiRoleAssignments'

# Definitions only: the script itself signs in to Entra, so run just its pure helper functions and lookup tables.
$assignments = $ast.FindAll({ param($n) $n -is [System.Management.Automation.Language.AssignmentStatementAst] -and $n.Left.Extent.Text -in '$knownText', '$knownRoles' }, $false)
Expand All @@ -27,7 +27,6 @@ BeforeAll {
return @($IdTokenClaims.Count, $AccessTokenClaims.Count)
}
}

Describe 'identifier URI under strict mode' {
It 'handles an existing registration with no identifier URI' {
Set-StrictMode -Version Latest
Expand Down Expand Up @@ -147,3 +146,127 @@ Describe 'spec builders' {
(ConvertTo-RoleSpec $r).Value | Should -Be 'X'
}
}

Describe 'strict application roles' {
It 'accepts a missing role or an enabled application-only role' {
{ Assert-StrictApplicationRoles @() @('Product.Install') @() } | Should -Not -Throw
$role = @{ Value = 'Product.Install'; IsEnabled = $true; AllowedMemberTypes = @('Application') }
{ Assert-StrictApplicationRoles @($role) @('Product.Install') @() } | Should -Not -Throw
}

It 'rejects roles that permit users or are disabled' {
$role = @{ Value = 'Product.Install'; IsEnabled = $true; AllowedMemberTypes = @('Application', 'User') }
{ Assert-StrictApplicationRoles @($role) @('Product.Install') @() } | Should -Throw
$role.AllowedMemberTypes = @('Application')
$role.IsEnabled = $false
{ Assert-StrictApplicationRoles @($role) @('Product.Install') @() } | Should -Throw
{ Assert-StrictApplicationRoles @() @('Product.Install') @('Product.Install') } | Should -Throw
}

Describe 'shared automation application roles' {
BeforeEach {
$script:api = [pscustomobject]@{
AppRoles = @(
[pscustomobject]@{ Id = 'automation'; Value = 'Asset.Automation'; IsEnabled = $true; AllowedMemberTypes = @('Application') }
[pscustomobject]@{ Id = 'install'; Value = 'Product.Install'; IsEnabled = $true; AllowedMemberTypes = @('Application') }
)
}
}

It 'resolves both roles and preserves unrelated resource permissions' {
$roles = @(Get-ApiApplicationRoles $api @('Asset.Automation', 'Product.Install') 'api')
$roles.Value | Should -Be @('Asset.Automation', 'Product.Install')
$app = [pscustomobject]@{ RequiredResourceAccess = @(
[pscustomobject]@{ ResourceAppId = 'other'; ResourceAccess = @([pscustomobject]@{ Id = 'other-id'; Type = 'Scope' }) }
[pscustomobject]@{ ResourceAppId = 'api'; ResourceAccess = @([pscustomobject]@{ Id = 'automation'; Type = 'Role' }) }
) }
$wanted = @($roles | ForEach-Object { @{ Id = $_.Id; Type = 'Role' } })
$merged = Get-MergedResourceAccess $app 'api' $wanted
@(($merged | Where-Object ResourceAppId -EQ 'api').ResourceAccess.Id) | Should -Be @('automation', 'install')
@(($merged | Where-Object ResourceAppId -EQ 'other').ResourceAccess.Id) | Should -Be @('other-id')
}

It 'adds only missing assignments and is idempotent on rerun' {
$roles = @(Get-ApiApplicationRoles $api @('Asset.Automation', 'Product.Install') 'api')
$existing = @([pscustomobject]@{ AppRoleId = 'automation'; ResourceId = 'api-sp' })
@(Get-MissingApiRoleAssignments $roles $existing 'api-sp').Value | Should -Be @('Product.Install')
$existing += [pscustomobject]@{ AppRoleId = 'install'; ResourceId = 'api-sp' }
@(Get-MissingApiRoleAssignments $roles $existing 'api-sp').Count | Should -Be 0
}

It 'grants both roles to the same service principal without duplicating them' {
$roleAssignmentBlock = $ast.Find({
param($node)
$node -is [System.Management.Automation.Language.IfStatementAst] -and
$node.Extent.Text.StartsWith("if (`$Type -eq 'E2E')") -and
$node.Extent.Text.Contains('New-MgServicePrincipalAppRoleAssignment')
}, $true)
$Type = 'E2E'
$ApiAppId = 'api'
$roles = @(Get-ApiApplicationRoles $api @('Asset.Automation', 'Product.Install') 'api')
$sp = [pscustomobject]@{ Id = 'automation-sp' }
$script:assignedRoles = @()
$script:grantCount = 0
function Get-OrNew-ServicePrincipal { param($AppId) return [pscustomobject]@{ Id = 'api-sp' } }
function Get-MgServicePrincipalAppRoleAssignment {
param($ServicePrincipalId, [switch]$All)
return $script:assignedRoles
}
function New-MgServicePrincipalAppRoleAssignment {
param($ServicePrincipalId, $PrincipalId, $ResourceId, $AppRoleId)
if ($ServicePrincipalId -ne 'automation-sp' -or $PrincipalId -ne 'automation-sp') {
throw 'Roles must be assigned to the existing automation principal.'
}
$script:grantCount++
$script:assignedRoles += [pscustomobject]@{ AppRoleId = $AppRoleId; ResourceId = $ResourceId }
}

Invoke-Expression $roleAssignmentBlock.Extent.Text
Invoke-Expression $roleAssignmentBlock.Extent.Text
$script:grantCount | Should -Be 2
@($script:assignedRoles.AppRoleId) | Should -Be @('automation', 'install')
}

It 'fails if a requested role is missing or disabled' {
{ Get-ApiApplicationRoles $api @('Asset.Automation', 'missing') 'api' } | Should -Throw '*missing*'
$api.AppRoles[1].IsEnabled = $false
{ Get-ApiApplicationRoles $api @('Asset.Automation', 'Product.Install') 'api' } | Should -Throw '*Product.Install*'
}

It 'requires E2E when extra automation roles are requested' {
$scriptPath = Join-Path $PSScriptRoot '..\New-EntraDotnetSolution.ps1'
{ & $scriptPath -EntraInstanceUrl 'https://example.invalid' -TenantId 'synthetic' -ApiAppRegistrationName 'api' -E2EAdditionalApiRoles 'Product.Install' } |
Should -Throw '*require -IncludeE2E*'
}

It 'requests both roles on the API and the existing E2E registration' {
$scriptPath = Join-Path $PSScriptRoot '..\New-EntraDotnetSolution.ps1'
$solutionAst = [System.Management.Automation.Language.Parser]::ParseFile($scriptPath, [ref]$null, [ref]$null)
$apiArgs = @{}
$E2EAdditionalApiRoles = @('Product.Install')
$apiRoleMapping = $solutionAst.Find({
param($node)
$node -is [System.Management.Automation.Language.IfStatementAst] -and
$node.Extent.Text.StartsWith('if ($E2EAdditionalApiRoles.Count -gt 0)') -and
$node.Extent.Text.Contains('$apiArgs.ApplicationRoles')
}, $true)
Invoke-Expression $apiRoleMapping.Extent.Text
$apiArgs.ApplicationRoles | Should -Be @('Asset.Automation', 'Product.Install')
$apiArgs.StrictApplicationRoles | Should -Be @('Product.Install')

$e2eArgsAssignment = $solutionAst.Find({
param($node)
$node -is [System.Management.Automation.Language.AssignmentStatementAst] -and
$node.Left.Extent.Text -eq '$e2eArgs'
}, $true)
$TenantId = 'synthetic'
$E2EAppRegistrationName = 'existing-e2e'
$E2EProjectPath = 'existing-project'
$api = [pscustomobject]@{ AppId = 'api' }
function Get-DotnetProjectName { param($ProjectPath) return $ProjectPath }
Invoke-Expression $e2eArgsAssignment.Extent.Text
$e2eArgs.AppRegistrationName | Should -Be 'existing-e2e'
$e2eArgs.ApiRole | Should -Be @('Asset.Automation', 'Product.Install')
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@ using '../templates/workload-digitalproduct.bicep'

// Phase 1 (mode 1, standalone): plan, Log Analytics, App Insights, web, API and SQL all live in this RG.
// RG: {product}-{env}-{region}-{instance}-rg. Set SQL_ENTRA_ADMIN_GROUP_OBJECT_ID and AZURE_TENANT_ID to workload-tenant IDs before deployment.
// Deploy: az deployment group create -g agent-dev-wus2-100-rg -f .azure/templates/workload-digitalproduct.bicep -p .azure/variables/workload-digitalproduct-standalone-dev.bicepparam
// Deploy: az deployment group create -g agentstart-dev-wus2-100-rg -f .azure/templates/workload-digitalproduct.bicep -p .azure/variables/workload-digitalproduct-standalone-dev.bicepparam

var productIac = 'agent'
var productIac = 'agentstart'
var environmentIac = 'dev'
var regionIac = 'wus2'
var instanceIac = '100'
Expand Down
Loading
Loading