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
Jump to file
Failed to load files.
Loading
Diff view
Diff view
194 changes: 152 additions & 42 deletions .github/scripts/setup/Initialize-Product.ps1

Large diffs are not rendered by default.

57 changes: 57 additions & 0 deletions .github/scripts/setup/Setup-Session.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
function Read-SetupStore {
$root = if ($IsWindows) {
Join-Path ([Environment]::GetFolderPath('ApplicationData')) 'Microsoft/UserSecrets'
}
else {
Join-Path $HOME '.microsoft/usersecrets'
}
$path = Join-Path (Join-Path $root $script:setupStoreId) 'secrets.json'
if (-not (Test-Path -LiteralPath $path)) { return @{} }
return Get-Content -LiteralPath $path -Raw | ConvertFrom-Json -AsHashtable
}

function Write-SetupStore([hashtable]$Values) {
$Values | ConvertTo-Json -Compress -Depth 10 | dotnet user-secrets set --id $script:setupStoreId | Out-Null
if ($LASTEXITCODE -ne 0) { throw 'Unable to save setup state. Values were not printed.' }
}

function Start-SetupSession([string]$RepositoryRoot, [string]$CompanyName, [string]$ProductName, [string]$Environment, [string]$Instance) {
$identity = "$RepositoryRoot|$CompanyName|$ProductName|$Environment|$Instance"
if ($IsWindows) { $identity = $identity.ToLowerInvariant() }
$hash = [Convert]::ToHexString([System.Security.Cryptography.SHA256]::HashData([System.Text.Encoding]::UTF8.GetBytes($identity))).ToLowerInvariant()
$script:setupStoreId = "product-setup-$hash"
$stored = Read-SetupStore
$active = [string]$stored['ActiveSession']
if ($active -and $active -notmatch '^[0-9a-f]{32}$') { throw 'The setup session identifier is invalid.' }
if (-not $active) {
$active = [guid]::NewGuid().ToString('N')
Write-SetupStore @{ 'ActiveSession' = $active }
}
$script:setupSessionId = $active
$script:setupState = @{}
$prefix = "Session:${active}:"
foreach ($key in $stored.Keys) {
if ($key.StartsWith($prefix, [StringComparison]::OrdinalIgnoreCase)) {
$script:setupState[$key.Substring($prefix.Length)] = $stored[$key]
}
}
}

function Save-SetupValue([string]$Name, [string]$Value) {
if ([string]::IsNullOrWhiteSpace($Value)) { throw "$Name cannot be empty." }
if ($script:setupState[$Name] -ceq $Value) { return }
Write-SetupStore @{ "Session:$($script:setupSessionId):$Name" = $Value }
$script:setupState[$Name] = $Value
}

function Complete-SetupSession {
$stored = Read-SetupStore
if ($stored['ActiveSession'] -cne $script:setupSessionId) { throw 'The active setup session changed; no setup state was removed.' }
$prefix = "Session:$($script:setupSessionId):"
foreach ($key in @($stored.Keys | Where-Object { $_.StartsWith($prefix, [StringComparison]::OrdinalIgnoreCase) })) {
dotnet user-secrets remove $key --id $script:setupStoreId | Out-Null
if ($LASTEXITCODE -ne 0) { throw 'Unable to clean this setup session. Remaining state was preserved for retry.' }
}
dotnet user-secrets remove 'ActiveSession' --id $script:setupStoreId | Out-Null
if ($LASTEXITCODE -ne 0) { throw 'Unable to complete setup session cleanup.' }
}
65 changes: 65 additions & 0 deletions .github/scripts/tests/SetupLifecycle.Tests.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
Describe 'Cloud setup session lifecycle' {
It 'resumes Prepare through Complete without prompting or touching older application entries' {
$initializer = Join-Path $PSScriptRoot '..\setup\Initialize-Product.ps1'
$root = Join-Path $TestDrive ([guid]::NewGuid().ToString('N'))
foreach ($directory in @('src/Presentation.Api/Properties', 'src/Presentation.Web/Properties', '.azure/scripts/lib', '.github/scripts/cd', '.github/scripts/repo')) {
New-Item -ItemType Directory -Force (Join-Path $root $directory) | Out-Null
}
foreach ($file in @('Contoso.Product.slnx', 'src/Presentation.Api/Presentation.Api.csproj', 'src/Presentation.Web/Presentation.Web.csproj')) {
Set-Content (Join-Path $root $file) 'synthetic fixture'
}
$launch = '{"profiles":{"SelfHost":{"applicationUrl":"https://localhost:7443"}}}'
Set-Content (Join-Path $root 'src/Presentation.Api/Properties/launchSettings.json') $launch
Set-Content (Join-Path $root 'src/Presentation.Web/Properties/launchSettings.json') $launch
Set-Content (Join-Path $root '.azure/scripts/lib/Dotnet.Common.ps1') @'
function Get-DotnetUserSecrets { param($ProjectPath) return $global:SetupLifecycleStores[$ProjectPath].Clone() }
function Set-DotnetUserSecrets { param($ProjectPath, $Secrets) foreach ($key in $Secrets.Keys) { $global:SetupLifecycleStores[$ProjectPath][$key] = $Secrets[$key] }; return $true }
function Get-DotnetProjectName { param($ProjectPath) return 'synthetic' }
'@
Set-Content (Join-Path $root '.azure/scripts/New-EntraDotnetSolution.ps1') ''
Set-Content (Join-Path $root '.github/scripts/repo/Set-GithubDeploymentEnvironments.ps1') ''
Set-Content (Join-Path $root '.github/scripts/repo/New-GithubSecret.ps1') 'throw "No existing secret should be uploaded."'
Set-Content (Join-Path $root '.github/scripts/cd/New-Github-Azure-Federation.ps1') '[pscustomobject]@{ ClientId = "synthetic-federation" }'
Set-Content (Join-Path $root '.github/scripts/cd/Get-WorkloadDeployment.ps1') @'
[pscustomobject]@{ apiEndpoint = 'https://api.example.test'; webEndpoint = 'https://web.example.test'; applicationInsightsResourceId = $null; sqlServerKind = 'SqlAuth' }
'@
$api = "$root/src/Presentation.Api/Presentation.Api.csproj"
$web = "$root/src/Presentation.Web/Presentation.Web.csproj"
$global:SetupLifecycleStores = @{
$api = @{ 'EntraExternalId:ClientId' = 'synthetic-api'; 'EntraExternalId:TenantId' = '11111111-1111-1111-1111-111111111111'; 'EntraExternalId:Instance' = 'https://signin.example.test'; 'AzureOpenAI:Endpoint' = 'https://ai.example.test'; 'AzureOpenAI:ApiKey' = 'synthetic-ai'; 'Setup:development:101:WorkloadTenantId' = 'legacy-value' }
$web = @{ 'EntraExternalId:ClientId' = 'synthetic-web'; 'EntraExternalId:ClientSecret' = 'synthetic-web-secret' }
}
function gh { }
function az { }
Mock gh {
$global:LASTEXITCODE = 0
if ($args[0] -eq 'secret' -and $args[1] -eq 'list') {
return @('AZURE_CLIENT_ID', 'AZURE_TENANT_ID', 'AZURE_SUBSCRIPTION_ID', 'EEID_INSTANCE', 'EEID_TENANT_ID', 'API_CLIENT_ID', 'WEB_CLIENT_ID', 'WEB_CLIENT_SECRET', 'AZURE_OPENAI_ENDPOINT', 'AZURE_OPENAI_APIKEY', 'SQL_SERVER_AUTHENTICATION', 'SQL_ENTRA_ADMIN_GROUP_OBJECT_ID')
}
}
Mock az { $global:LASTEXITCODE = 0 }
Mock Read-Host { throw 'Resume must not prompt.' }
Mock Get-Command { [pscustomobject]@{ Name = 'Available' } } -ParameterFilter { ($Name -join ',') -in @('dotnet', 'git', 'az', 'gh') }
$identity = "$root|Contoso|Product|development|101"
if ($IsWindows) { $identity = $identity.ToLowerInvariant() }
$hash = [Convert]::ToHexString([System.Security.Cryptography.SHA256]::HashData([Text.Encoding]::UTF8.GetBytes($identity))).ToLowerInvariant()
$base = if ($IsWindows) { Join-Path ([Environment]::GetFolderPath('ApplicationData')) 'Microsoft/UserSecrets' } else { Join-Path $HOME '.microsoft/usersecrets' }
$folder = Join-Path $base "product-setup-$hash"
$file = Join-Path $folder 'secrets.json'
try {
& $initializer -RepositoryRoot $root -CompanyName Contoso -ProductName Product -Mode Cloud -Stage Prepare -Environment development -Instance 101 -SignInTenantId '11111111-1111-1111-1111-111111111111' -SignInInstanceUrl 'https://signin.example.test' -WorkloadTenantId 'synthetic-workload' -SubscriptionId 'synthetic-subscription' -GitHubOwner 'synthetic-owner' -GitHubRepository 'synthetic-repo' -ResourceGroupName 'synthetic-group' -AzureOpenAIEndpoint 'https://ai.example.test'
$saved = Get-Content -LiteralPath $file -Raw | ConvertFrom-Json -AsHashtable
$saved.ContainsKey('ActiveSession') | Should -BeTrue
& $initializer -RepositoryRoot $root -CompanyName Contoso -ProductName Product -Mode Cloud -Stage Complete -Environment development -Instance 101
$remaining = Get-Content -LiteralPath $file -Raw | ConvertFrom-Json -AsHashtable
$remaining.Count | Should -Be 0
$global:SetupLifecycleStores[$api]['Setup:development:101:WorkloadTenantId'] | Should -Be 'legacy-value'
Should -Invoke Read-Host -Times 0 -Exactly
}
finally {
if (Test-Path -LiteralPath $file) { Remove-Item -LiteralPath $file }
if (Test-Path -LiteralPath $folder) { Remove-Item -LiteralPath $folder }
Remove-Variable -Name SetupLifecycleStores -Scope Global
}
}
}
52 changes: 52 additions & 0 deletions .github/scripts/tests/SetupSession.Tests.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
BeforeAll {
. (Join-Path $PSScriptRoot '..\setup\Setup-Session.ps1')
}

Describe 'Setup session' {
BeforeEach {
$script:fixtureStore = @{ 'Unrelated:Legacy' = 'synthetic-legacy' }
Mock Read-SetupStore { return $script:fixtureStore.Clone() }
Mock Write-SetupStore {
param($Values)
foreach ($key in $Values.Keys) { $script:fixtureStore[$key] = $Values[$key] }
}
Mock dotnet {
if ($args[0] -ne 'user-secrets' -or $args[1] -ne 'remove') { throw 'Unexpected secret-store operation.' }
[void]$script:fixtureStore.Remove([string]$args[2])
$global:LASTEXITCODE = 0
}
}

It 'resumes a failed or paused setup and removes only its own session entries on completion' {
Start-SetupSession 'synthetic-root' 'Contoso' 'Product' 'development' '101'
$session = $script:setupSessionId
Save-SetupValue 'WorkloadTenantId' 'synthetic-tenant'
Save-SetupValue 'Credential:synthetic-id' 'synthetic-secret'

Start-SetupSession 'synthetic-root' 'Contoso' 'Product' 'development' '101'
$script:setupSessionId | Should -Be $session
$script:setupState['WorkloadTenantId'] | Should -Be 'synthetic-tenant'
$script:setupState['Credential:synthetic-id'] | Should -Be 'synthetic-secret'

Complete-SetupSession
$script:fixtureStore.Count | Should -Be 1
$script:fixtureStore['Unrelated:Legacy'] | Should -Be 'synthetic-legacy'
Should -Invoke dotnet -Times 3 -Exactly
}

It 'does not remove state belonging to a different active session' {
Start-SetupSession 'synthetic-root' 'Contoso' 'Product' 'development' '101'
Save-SetupValue 'WorkloadTenantId' 'synthetic-tenant'
$script:fixtureStore['ActiveSession'] = [guid]::NewGuid().ToString('N')
{ Complete-SetupSession } | Should -Throw '*active setup session changed*'
Should -Invoke dotnet -Times 0 -Exactly
}

It 'preserves retry state when saving fails' {
Start-SetupSession 'synthetic-root' 'Contoso' 'Product' 'development' '101'
Mock Write-SetupStore { throw 'synthetic storage failure' }
{ Save-SetupValue 'WorkloadTenantId' 'synthetic-tenant' } | Should -Throw '*synthetic storage failure*'
$script:fixtureStore['ActiveSession'] | Should -Be $script:setupSessionId
Should -Invoke dotnet -Times 0 -Exactly
}
}
110 changes: 106 additions & 4 deletions .github/scripts/tests/WorkloadDeployment.Tests.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -481,19 +481,121 @@ Describe 'Root setup orchestration' {
{ Confirm-SqlAdministratorGroup -ObjectId '11111111-1111-1111-1111-111111111111' -TenantId 'tenant' } | Should -Throw '*Sign in to workload tenant*'
}

It 'verifies deployment before SQL provisioning and scopes state per environment and instance' {
It 'resumes setup inputs from its own session instead of old API state' {
$ast = [System.Management.Automation.Language.Parser]::ParseFile($initializer, [ref]$null, [ref]$null)
$definition = $ast.Find({ param($node) $node -is [System.Management.Automation.Language.FunctionDefinitionAst] -and $node.Name -eq 'Read-Setting' }, $true)
Invoke-Expression $definition.Extent.Text
$apiValues = @{ 'Setup:development:001:WorkloadTenantId' = 'old-tenant' }
$setupState = @{ WorkloadTenantId = 'session-tenant' }
function Save-SetupValue { param($Name, $Value) }
Mock Read-Host { 'new-tenant' }
Read-Setting 'WorkloadTenantId' '' | Should -Be 'session-tenant'
Read-Setting 'WorkloadTenantId' 'provided-tenant' | Should -Be 'provided-tenant'
$setupState.Clear()
Read-Setting 'WorkloadTenantId' '' | Should -Be 'new-tenant'
Should -Invoke Read-Host -Times 1 -Exactly
}

It 'repairs a changed registration and reuses a generated credential after a failed write' {
$ast = [System.Management.Automation.Language.Parser]::ParseFile($initializer, [ref]$null, [ref]$null)
$definition = $ast.Find({ param($node) $node -is [System.Management.Automation.Language.FunctionDefinitionAst] -and $node.Name -eq 'Invoke-SetupRegistrations' }, $true)
Invoke-Expression $definition.Extent.Text
$RepositoryRoot = $setupRoot
$apiProject = 'api'
$webProject = 'web'
$e2eProject = ''
$SignInTenantId = 'synthetic-tenant'
$registrationArguments = @{ WebAppRegistrationName = 'synthetic-web' }
$script:setupState = @{}
$global:SetupTestStores = @{
api = @{ 'EntraExternalId:ClientId' = 'synthetic-api' }
web = @{ 'EntraExternalId:ClientId' = 'old-id'; 'EntraExternalId:ClientSecret' = 'synthetic-old' }
}
$global:SetupTestGenerated = 0
$global:SetupTestWriteFails = $true
New-Item -ItemType Directory -Force (Join-Path $setupRoot '.azure/scripts/entra') | Out-Null
Set-Content (Join-Path $setupRoot '.azure/scripts/New-EntraDotnetSolution.ps1') '$global:SetupTestStores.web["EntraExternalId:ClientId"] = "new-id"'
Set-Content (Join-Path $setupRoot '.azure/scripts/entra/New-EntraAppRegistration.ps1') @'
param($Type, $TenantId, $AppRegistrationName, $SecretOnly, $SkipPrerequisites, $ProjectName)
$global:SetupTestGenerated++
[pscustomobject]@{ AppId = 'new-id'; Secret = 'synthetic-new' }
'@
function Get-DotnetUserSecrets { param($ProjectPath) return $global:SetupTestStores[$ProjectPath].Clone() }
function Get-DotnetProjectName { param($ProjectPath) return $ProjectPath }
function Save-SetupValue { param($Name, $Value) $script:setupState[$Name] = $Value }
function Save-Settings {
param($Project, $Values)
if ($global:SetupTestWriteFails) { throw 'synthetic write failure' }
foreach ($key in $Values.Keys) { $global:SetupTestStores[$Project][$key] = $Values[$key] }
}
try {
{ Invoke-SetupRegistrations } | Should -Throw '*synthetic write failure*'
$global:SetupTestStores.web['EntraExternalId:ClientSecret'] | Should -Be 'synthetic-old'
$script:setupState['WebRepairClientId'] | Should -Be 'new-id'
$global:SetupTestWriteFails = $false
{ Invoke-SetupRegistrations } | Should -Not -Throw
$global:SetupTestStores.web['EntraExternalId:ClientSecret'] | Should -Be 'synthetic-new'
$script:setupState['WebCredentialsChanged'] | Should -Be 'true'
$global:SetupTestGenerated | Should -Be 1
{ Invoke-SetupRegistrations } | Should -Not -Throw
$global:SetupTestGenerated | Should -Be 1

$script:setupState.Clear()
$global:SetupTestStores.api['EntraExternalId:TenantId'] = 'old-tenant'
$global:SetupTestStores.web['EntraExternalId:TenantId'] = 'old-tenant'
$global:SetupTestStores.web['EntraExternalId:ClientSecret'] = 'synthetic-old'
Set-Content (Join-Path $setupRoot '.azure/scripts/New-EntraDotnetSolution.ps1') '$global:SetupTestStores.api["EntraExternalId:TenantId"] = "new-tenant"; $global:SetupTestStores.web["EntraExternalId:TenantId"] = "new-tenant"'
{ Invoke-SetupRegistrations } | Should -Not -Throw
$global:SetupTestStores.web['EntraExternalId:ClientSecret'] | Should -Be 'synthetic-new'
$script:setupState['WebCredentialsChanged'] | Should -Be 'true'
$script:setupState['SignInConfigurationChanged'] | Should -Be 'true'
$global:SetupTestGenerated | Should -Be 2
{ Invoke-SetupRegistrations } | Should -Not -Throw
$global:SetupTestGenerated | Should -Be 2
}
finally {
Remove-Variable -Name SetupTestStores, SetupTestGenerated, SetupTestWriteFails -Scope Global
}
}

It 'uploads only missing secrets and credentials affected by registration changes' {
$ast = [System.Management.Automation.Language.Parser]::ParseFile($initializer, [ref]$null, [ref]$null)
$definition = $ast.Find({ param($node) $node -is [System.Management.Automation.Language.FunctionDefinitionAst] -and $node.Name -eq 'Publish-SetupSecrets' }, $true)
Invoke-Expression $definition.Extent.Text
$RepositoryRoot = $setupRoot
$GitHubOwner = 'synthetic-owner'
$GitHubRepository = 'synthetic-repo'
$Environment = 'development'
$global:SetupTestUpload = @{}
Set-Content (Join-Path $setupRoot '.github/scripts/repo/New-GithubSecret.ps1') @'
param($Owner, $Repo, $Environment, $Secrets)
$global:SetupTestUpload = $Secrets
'@
try {
$values = @{ EXISTING = 'synthetic-existing'; CHANGED = 'synthetic-updated'; MISSING = 'synthetic-new' }
Publish-SetupSecrets $values @('EXISTING', 'CHANGED') @('CHANGED')
@($global:SetupTestUpload.Keys | Sort-Object) | Should -Be @('CHANGED', 'MISSING')
$global:SetupTestUpload = @{}
Publish-SetupSecrets @{ EXISTING = 'synthetic-existing' } @('EXISTING') @()
$global:SetupTestUpload.Count | Should -Be 0
}
finally {
Remove-Variable -Name SetupTestUpload -Scope Global
}
}

It 'verifies deployment before SQL provisioning without persisting setup state in application stores' {
$source = Get-Content $initializer -Raw
$source.IndexOf('Get-WorkloadDeployment.ps1') | Should -BeLessThan $source.IndexOf('Set-AzureSqlManagedIdentityUsers.ps1')
$source | Should -Match 'Setup:\$\{Environment\}:\$\{Instance\}'
$source | Should -Not -Match 'Setup:\$\{Environment\}:\$\{Instance\}|Setup:SecretClientId'
$source | Should -Match 'Set-GithubDeploymentEnvironments.ps1'
$source | Should -Not -Match 'git (commit|push)|Remove-AzSql|DROP DATABASE'
}

It 'uses one configurable deployment identity across environments' {
$source = Get-Content $initializer -Raw
$source | Should -Match '\[string\]\$GitHubPrincipalName'
$source | Should -Match 'else \{ "github-\$product" \}'
$source | Should -Match '"\$\{setupPrefix\}:GitHubPrincipalName" = \$GitHubPrincipalName'
$source | Should -Match '\$setupState\[''GitHubPrincipalName''\]'
$source | Should -Match '-PrincipalName \$GitHubPrincipalName'
$source | Should -Match 'az ad app list --display-name \$GitHubPrincipalName'
}
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ Then run `agentstart-app.yml` with `runcd=true`. Entra-only SQL uses
`-SqlAuthentication EntraOnly`; resume as a member of its SQL administrator group.
Rerun the same commands for an existing installation. `-Mode Both` prepares local and cloud;
`-Environment production` selects production when its workflow/parameters are enabled;
`-Stage Check` is read-only. Missing secrets are prompted privately, never silently rotated.
`-Stage Check` is read-only. Missing registration credentials are added without revoking existing ones.
No commits, pushes, database resets, or authentication-mode conversions occur.

See [First-time setup](docs/first-time-setup.md) for phases and troubleshooting.
Expand Down
Loading
Loading