From 689676807cce54384bee22a0b7c47ca5f5164989 Mon Sep 17 00:00:00 2001 From: spetersenms Date: Wed, 28 Oct 2026 17:11:53 +0100 Subject: [PATCH 01/12] Initial Deploy via Admin API 2.29 implementation. --- Actions/.Modules/settings.schema.json | 2 +- Actions/Deploy/Deploy.ps1 | 10 +- Actions/Deploy/Deploy.psm1 | 282 +++++++++++- Actions/Deploy/README.md | 8 + RELEASENOTES.md | 6 +- Scenarios/RegisterProductionEnvironment.md | 8 + Scenarios/RegisterSandboxEnvironment.md | 8 + Scenarios/settings.md | 2 +- Tests/Deploy.Action.Test.ps1 | 50 ++- Tests/Deploy.Module.Test.ps1 | 50 ++- Tests/PublishPTEApps.Test.ps1 | 483 +++++++++++++++++++++ Tests/UnpublishOldAppVersions.Test.ps1 | 42 ++ Workshop/ContinuousDeployment.md | 16 + 13 files changed, 940 insertions(+), 27 deletions(-) create mode 100644 Tests/PublishPTEApps.Test.ps1 diff --git a/Actions/.Modules/settings.schema.json b/Actions/.Modules/settings.schema.json index b5d8a1b6e8..7aaf7ee6fd 100644 --- a/Actions/.Modules/settings.schema.json +++ b/Actions/.Modules/settings.schema.json @@ -815,7 +815,7 @@ "unpublishOldVersions": { "type": "boolean", "default": false, - "description": "When set to true, AL-Go unpublishes old, uninstalled versions of the deployed apps from the environment after a successful deployment. Only applies to PTE deployments (Scope PTE) and is non-fatal. See https://aka.ms/ALGoSettings#deployto" + "description": "Optional boolean, default false. After successful Scope PTE deployment, unpublishes only selected apps' uninstalled versions older than the currently installed version on Business Central 25.4 through 28. On BC 29 and later, Business Central manages cleanup in the background, which may be delayed; timing and retained versions are not guaranteed. This setting does not control background cleanup: AL-Go warns and skips explicit unpublish without failing deployment. Cleanup failures are warnings; does not apply to Scope Dev or custom deployments. See https://aka.ms/ALGoSettings#deployto" } } } diff --git a/Actions/Deploy/Deploy.ps1 b/Actions/Deploy/Deploy.ps1 index c3f6d0527f..1c7ee2a0e6 100644 --- a/Actions/Deploy/Deploy.ps1 +++ b/Actions/Deploy/Deploy.ps1 @@ -193,7 +193,7 @@ else { Publish-BcContainerApp @parameters -useDevEndpoint -checkAlreadyInstalled -excludeRuntimePackages -replacePackageId } else { - # Use automation API for production environments (Publish-PerTenantExtensionApps) + # The shared AL-Go publisher selects the API based on the target environment version. $parameters = @{ "bcAuthContext" = $bcAuthContext "environment" = $deploymentSettings.EnvironmentName @@ -201,7 +201,7 @@ else { } if ($deploymentSettings.SyncMode) { if (@('Add','ForceSync') -notcontains $deploymentSettings.SyncMode) { - throw "Invalid SyncMode $($deploymentSettings.SyncMode) when deploying using the automation API. Valid values are Add and ForceSync." + throw "Invalid SyncMode $($deploymentSettings.SyncMode) when deploying Per Tenant Extensions. Valid values are Add and ForceSync." } Write-Host "Using $($deploymentSettings.SyncMode)" $syncMode = $deploymentSettings.SyncMode @@ -211,11 +211,11 @@ else { CheckInstalledApps -bcAuthContext $bcAuthContext -environment $deploymentSettings.EnvironmentName -appFiles $apps - Write-Host "Publishing apps using automation API" - Publish-PerTenantExtensionApps @parameters + Write-Host "Publishing Per Tenant Extensions" + PublishPTEApps @parameters if (($deploymentSettings['unpublishOldVersions'] -is [bool]) -and $deploymentSettings['unpublishOldVersions']) { - Write-Host "Unpublishing old app versions" + Write-Host "Checking cleanup of old app versions" UnpublishOldAppVersions -bcAuthContext $bcAuthContext -environment $deploymentSettings.EnvironmentName -appFiles $apps } } diff --git a/Actions/Deploy/Deploy.psm1 b/Actions/Deploy/Deploy.psm1 index 25148f03fc..0a73320101 100644 --- a/Actions/Deploy/Deploy.psm1 +++ b/Actions/Deploy/Deploy.psm1 @@ -205,7 +205,6 @@ function CheckIfAppNeedsInstallOrUpgrade { return $needsInstall, $needsUpgrade } -# Check if the apps are already installed and emit a warning if the installed version is higher than the version in the app file <# .SYNOPSIS Check installed apps against the provided app files and emit warnings if the installed version is higher than the version in the app file. @@ -242,6 +241,268 @@ function CheckInstalledApps { } } +<# + .SYNOPSIS + Resolve the target BC version from its installed Application extension. + .PARAMETER extensions + Extensions returned by the read-only environment API. + .PARAMETER environment + Target environment name, used in failure diagnostics. +#> +function GetPTEApplicationVersion { + Param( + [object[]] $extensions, + [string] $environment + ) + + $applications = @($extensions | Where-Object { $_.displayName -eq 'Application' -and $_.isInstalled }) + $version = $null + if ($applications.Count -eq 1) { + $application = $applications[0] | ConvertTo-HashTable -recurse + $parts = @('versionMajor', 'versionMinor', 'versionBuild', 'versionRevision' | ForEach-Object { + if ($application.ContainsKey($_)) { [string]$application[$_] } + }) + if ($parts.Count -eq 4 -and [version]::TryParse(($parts -join '.'), [ref]$version)) { + return $version + } + } + throw "Could not determine the Business Central version in environment $environment from a unique installed Application extension." +} + +<# + .SYNOPSIS + Upload a PTE for immediate installation through Admin Center API v2.29. + .DESCRIPTION + Sends multipart bytes on PowerShell 5 and 7 and disposes HTTP content and streams. + Upload errors are never retried because the service might already have accepted the package. + .PARAMETER bcAuthContext + Authentication context to renew before uploading. + .PARAMETER uri + Admin Center pteInstall URL for the target environment. + .PARAMETER appFile + App package to upload. + .PARAMETER syncMode + Admin Center schema sync mode, Add or ForceSync. +#> +function InvokePTEUpload { + Param( + [hashtable] $bcAuthContext, + [string] $uri, + [string] $appFile, + [ValidateSet('Add', 'ForceSync')] + [string] $syncMode + ) + + $authContext = Renew-BcAuthContext -bcAuthContext $bcAuthContext + if (!$authContext -or !$authContext['AccessToken']) { + throw "Authentication failed before PTE upload." + } + Write-Host "::add-mask::$($authContext.AccessToken)" + $headers = @{ Authorization = "Bearer $($authContext.AccessToken)" } + Add-Type -AssemblyName System.Net.Http + $multipart = $null + $fileStream = $null + $fileContent = $null + try { + $multipart = [System.Net.Http.MultipartFormDataContent]::new() + $fileStream = [System.IO.File]::OpenRead($appFile) + $fileContent = [System.Net.Http.StreamContent]::new($fileStream) + $fileContent.Headers.ContentType = [System.Net.Http.Headers.MediaTypeHeaderValue]::new('application/octet-stream') + $multipart.Add($fileContent, 'extensionFile', [System.IO.Path]::GetFileName($appFile)) + $fields = @{ + deploymentSchedule = 'Immediate' + syncMode = $syncMode + acceptIsvEula = 'true' + installOrUpdateNeededDependencies = 'false' + } + foreach ($field in $fields.Keys) { + $multipart.Add([System.Net.Http.StringContent]::new($fields[$field]), $field) + } + # Invoke-RestMethod supports a byte body on both Windows PowerShell and PowerShell Core. + $bytes = $multipart.ReadAsByteArrayAsync().GetAwaiter().GetResult() + Invoke-RestMethod -Method Post -Uri $uri -Headers $headers -Body $bytes ` + -ContentType $multipart.Headers.ContentType.ToString() -UseBasicParsing -TimeoutSec 300 -ErrorAction Stop + } + catch { + $details = $_.Exception.Message + if ($_.ErrorDetails) { $details += " $($_.ErrorDetails.Message)" } + throw "PTE upload failed for $([System.IO.Path]::GetFileName($appFile)): $details. The upload will not be replayed." + } + finally { + if ($multipart) { $multipart.Dispose() } + if ($fileContent) { $fileContent.Dispose() } + if ($fileStream) { $fileStream.Dispose() } + } +} + +<# + .SYNOPSIS + Wait for the exact Admin Center PTE operation to complete successfully. + .DESCRIPTION + Polls only the returned app and operation IDs. An accepted or scheduled immediate install + is not success. Only transient status-read errors are retried, never the upload. + .PARAMETER bcAuthContext + Authentication context to renew for each status request. + .PARAMETER appsUri + Admin Center apps URL for the target environment. + .PARAMETER operation + Upload response containing the operation id, appId and status. + .PARAMETER appId + Expected app ID from the package. + .PARAMETER timeoutSeconds + Maximum elapsed polling time. Defaults to 30 minutes. + .PARAMETER maxStatusRequests + Maximum number of status requests. Defaults to 360. + .PARAMETER pollIntervalSeconds + Delay between status requests. Defaults to five seconds. +#> +function WaitPTEOperation { + Param( + [hashtable] $bcAuthContext, + [string] $appsUri, + $operation, + [string] $appId, + [ValidateRange(1, 1800)] + [int] $timeoutSeconds = 1800, + [ValidateRange(1, 360)] + [int] $maxStatusRequests = 360, + [ValidateRange(0, 5)] + [int] $pollIntervalSeconds = 5 + ) + + $operation = $operation | ConvertTo-HashTable -recurse + if ($operation -isnot [hashtable] -or !$operation['id'] -or $operation['appId'] -ne $appId) { + throw "PTE upload returned missing or mismatched app/operation details for app $appId. The upload will not be replayed." + } + $operationId = [string]$operation['id'] + $operationUri = "$appsUri/$([Uri]::EscapeDataString($appId))/operations/$([Uri]::EscapeDataString($operationId))" + $timer = [System.Diagnostics.Stopwatch]::StartNew() + $transientErrors = 0 + $requests = 0 + while ($true) { + if ($operation -isnot [hashtable] -or $operation['id'] -ne $operationId -or + ($operation.ContainsKey('appId') -and $operation['appId'] -ne $appId)) { + throw "Missing or mismatched PTE operation $operationId for app $appId." + } + $status = [string]$operation['status'] + Write-Host "PTE operation $operationId for app ${appId}: $status" + switch ($status) { + 'succeeded' { return } + 'scheduled' {} + 'running' {} + default { + throw "PTE operation $operationId for app $appId did not succeed. Response: $($operation | ConvertTo-Json -Depth 20 -Compress)" + } + } + if ($requests -ge $maxStatusRequests -or $timer.Elapsed.TotalSeconds -ge $timeoutSeconds) { + break + } + Start-Sleep -Seconds $pollIntervalSeconds + if ($timer.Elapsed.TotalSeconds -ge $timeoutSeconds) { break } + # Renew outside the retry catch so authentication errors always fail immediately. + $bcAuthContext = Renew-BcAuthContext -bcAuthContext $bcAuthContext + if (!$bcAuthContext -or !$bcAuthContext['AccessToken']) { + throw "Authentication failed while reading PTE operation $operationId for app $appId." + } + Write-Host "::add-mask::$($bcAuthContext.AccessToken)" + $headers = @{ Authorization = "Bearer $($bcAuthContext.AccessToken)" } + $requests++ + try { + $requestTimeout = [int][Math]::Max(1, [Math]::Min(30, [Math]::Ceiling($timeoutSeconds - $timer.Elapsed.TotalSeconds))) + $operation = Invoke-RestMethod -Headers $headers -Method Get -Uri $operationUri ` + -UseBasicParsing -TimeoutSec $requestTimeout -ErrorAction Stop + $operation = $operation | ConvertTo-HashTable -recurse + $transientErrors = 0 + } + catch { + $statusCode = 0 + if ($_.Exception.PSObject.Properties['Response'] -and $_.Exception.Response) { + $statusCode = [int]$_.Exception.Response.StatusCode + } + $transient = $statusCode -in 408,429,500,502,503,504 -or + (!$statusCode -and ($_.Exception -is [System.Net.WebException] -or + $_.Exception -is [System.Net.Http.HttpRequestException] -or $_.Exception -is [System.TimeoutException])) + $details = $_.Exception.Message + if ($_.ErrorDetails) { $details += " $($_.ErrorDetails.Message)" } + if (!$transient -or ++$transientErrors -gt 5) { + throw "Unable to read PTE operation $operationId for app ${appId}: $details" + } + OutputWarning -message "Transient error reading PTE operation ${operationId}: $details. Retrying the status request." + } + } + throw "Timed out waiting for PTE operation $operationId for app $appId after $timeoutSeconds seconds or $maxStatusRequests status requests. The upload will not be replayed." +} + +<# + .SYNOPSIS + Publish primary apps or PTE dependencies using the target BC version. + .DESCRIPTION + Below BC 29, delegates publishing to the released BcContainerHelper Automation implementation. + On BC 29 and later, AL-Go installs packages immediately using Admin Center API v2.29 with + no legacy fallback. Existing helper utilities expand packages, exclude runtime packages and + order dependencies. Same or newer installed versions are skipped. + .PARAMETER bcAuthContext + Business Central authentication context. + .PARAMETER environment + Target Business Central environment name. + .PARAMETER appFiles + App packages or archives to publish. + .PARAMETER schemaSyncMode + Existing helper-compatible sync mode: Add or Force (mapped to ForceSync for Admin Center). + .PARAMETER applicationFamily + Admin Center application family. Defaults to BusinessCentral; not a workflow setting. +#> +function PublishPTEApps { + Param( + [hashtable] $bcAuthContext, + [string] $environment, + [string[]] $appFiles, + [ValidateSet('Add', 'Force')] + [string] $schemaSyncMode = 'Add', + [string] $applicationFamily = 'BusinessCentral' + ) + + $extensions = @(Get-BcInstalledExtensions -bcAuthContext $bcAuthContext -environment $environment) + $applicationVersion = GetPTEApplicationVersion -extensions $extensions -environment $environment + if ($applicationVersion -lt [version]'29.0.0.0') { + Write-Host "Target BC $applicationVersion - publishing PTEs using BcContainerHelper Automation API" + Publish-PerTenantExtensionApps -bcAuthContext $bcAuthContext -environment $environment -appFiles $appFiles -SchemaSyncMode $schemaSyncMode + return + } + Write-Host "Target BC $applicationVersion - publishing PTEs using AL-Go Admin Center API v2.29" + $appsUri = "$($bcContainerHelperConfig.apiBaseUrl.TrimEnd('/'))/admin/v2.29/applications/$([Uri]::EscapeDataString($applicationFamily))/environments/$([Uri]::EscapeDataString($environment))/apps" + $tempPath = NewTemporaryFolder + try { + $copiedApps = @(Copy-AppFilesToFolder -appFiles $appFiles -folder $tempPath) + $sortedApps = @(Sort-AppFilesByDependencies -appFiles $copiedApps -excludeRuntimePackages) + foreach ($appFile in $sortedApps) { + $appJson = Get-AppJsonFromAppFile -appFile $appFile + $appVersion = [version]$appJson.version + $installedVersions = @($extensions | Where-Object { $_.id -eq $appJson.id -and $_.isInstalled } | + ForEach-Object { [version]::new($_.versionMajor, $_.versionMinor, $_.versionBuild, $_.versionRevision) }) + if (@($installedVersions | Where-Object { $_ -ge $appVersion }).Count -gt 0) { + Write-Host "App $($appJson.name) v$appVersion or newer is already installed" + continue + } + $syncMode = if ($schemaSyncMode -eq 'Force') { 'ForceSync' } else { 'Add' } + $operation = InvokePTEUpload -bcAuthContext $bcAuthContext -uri "$appsUri/pteInstall" -appFile $appFile -syncMode $syncMode + WaitPTEOperation -bcAuthContext $bcAuthContext -appsUri $appsUri -operation $operation -appId $appJson.id + $extensions += @{ + id = $appJson.id + displayName = $appJson.name + isInstalled = $true + versionMajor = $appVersion.Major + versionMinor = $appVersion.Minor + versionBuild = $appVersion.Build + versionRevision = $appVersion.Revision + } + } + } + finally { + Remove-Item -LiteralPath $tempPath -Force -Recurse + } +} + <# .SYNOPSIS Unpublish old, uninstalled versions of the deployed apps from a Business Central environment. @@ -249,7 +510,11 @@ function CheckInstalledApps { After a new version of a Per Tenant Extension is installed, previous versions remain published (but uninstalled) and clutter Extension Management. This function unpublishes those old versions using the automation API v2.0 Microsoft.NAV.unpublish action. Only versions that are not installed AND older than a currently installed version - of the same app (matched by app id) are unpublished. This is only supported for PTE deployments (automation API). + of the same app (matched by app id) are unpublished. This is only supported for PTE deployments on BC 25.4 + through 28. On BC 29 and later, Business Central manages old-version cleanup in the background. + Explicit unpublish is not supported, so AL-Go skips its cleanup with a warning. Background cleanup may + be delayed; its timing and retained versions are not guaranteed. Read-only Automation API calls determine + the installed Application version. The function is non-fatal: any failure is reported as a warning and never fails the deployment. .PARAMETER bcAuthContext The Business Central authentication context. @@ -291,12 +556,11 @@ function UnpublishOldAppVersions { $companyUrl = "$automationApiUrl/companies($companyId)" $extensions = @((Invoke-RestMethod -Method Get -Uri "$companyUrl/extensions" -Headers $headers -UseBasicParsing).value) - $application = $extensions | Where-Object { $_.displayName -eq 'Application' -and $_.isInstalled } | Select-Object -First 1 - if (-not $application) { - OutputWarning -message "Could not determine the Business Central version in environment $environment - skipping unpublish of old app versions." + $applicationVersion = GetPTEApplicationVersion -extensions $extensions -environment $environment + if ($applicationVersion -ge [version]'29.0.0.0') { + OutputWarning -message "AL-Go cannot explicitly unpublish old PTE versions on Business Central 29 or later; environment $environment is running $applicationVersion. Business Central manages cleanup in the background, which may be delayed; cleanup timing and retained versions are not guaranteed. AL-Go cleanup was skipped; the deployment remains successful." return } - $applicationVersion = [version]::new($application.versionMajor, $application.versionMinor, $application.versionBuild, $application.versionRevision) if ($applicationVersion -lt [version]'25.4.0.0') { OutputWarning -message "Unpublishing old app versions requires Business Central 25.4 or later; environment $environment is running $applicationVersion." return @@ -310,7 +574,7 @@ function UnpublishOldAppVersions { continue } # Use the currently installed version as the cleanup threshold. The environment may have a newer - # version installed than the deployed artifact, which Publish-PerTenantExtensionApps treats as success. + # version installed than the deployed artifact, which PublishPTEApps treats as success. $installedVersions = @($matching | Where-Object { $_.isInstalled } | ForEach-Object { [version]::new($_.versionMajor, $_.versionMinor, $_.versionBuild, $_.versionRevision) }) if ($installedVersions.Count -eq 0) { # No installed version - nothing to clean up against @@ -398,7 +662,7 @@ function InstallOrUpgradeApps { } if ($PTEsToInstall) { # Install or upgrade PTEs - Publish-PerTenantExtensionApps -bcAuthContext $bcAuthContext -environment $environment -appFiles $PTEsToInstall -SchemaSyncMode $schemaSyncMode + PublishPTEApps -bcAuthContext $bcAuthContext -environment $environment -appFiles $PTEsToInstall -SchemaSyncMode $schemaSyncMode } } finally { @@ -472,3 +736,5 @@ function InstallUnknownDependencies { Write-Host "Unknown dependencies installed or upgraded" } } + +Export-ModuleMember -Function GetHeadRefFromPRId, GetAppsAndDependenciesFromArtifacts, CheckIfAppNeedsInstallOrUpgrade, CheckInstalledApps, PublishPTEApps, UnpublishOldAppVersions, InstallOrUpgradeApps, InstallUnknownDependencies diff --git a/Actions/Deploy/README.md b/Actions/Deploy/README.md index c0fe51d2bc..df782dc718 100644 --- a/Actions/Deploy/README.md +++ b/Actions/Deploy/README.md @@ -2,6 +2,14 @@ Deploy Apps to online environment +## PTE publishing + +PTE deployment installs apps in dependency order and skips app versions that are already installed or superseded by a newer installed version. Deployment waits for installation to complete; installation failures fail the deployment. + +BC 29+ S2S deployments require `AdminCenter.ReadWrite.All` application permission, tenant admin consent, and registration in the administration center's Authorized Microsoft Entra apps. Existing AUTHCONTEXT structures stay unchanged, and environment API permissions remain necessary. See [deployment authorization](../../Workshop/ContinuousDeployment.md#pte-deployment-authorization) for full requirements. + +`unpublishOldVersions` is an optional boolean in `DeployTo` (default `false`). It runs only after successful Scope PTE publishing. On BC 25.4 through 28, only selected apps' uninstalled versions older than the currently installed version are unpublished. On BC 29+, Business Central manages cleanup in the background, which may be delayed; timing and retained versions are not guaranteed. The setting does not control that background cleanup: AL-Go warns and skips explicit unpublish without failing deployment. Scope Dev, custom deployments, and container behavior are unchanged. + ## INPUT ### ENV variables diff --git a/RELEASENOTES.md b/RELEASENOTES.md index fc0c0933c6..b4ae501cb6 100644 --- a/RELEASENOTES.md +++ b/RELEASENOTES.md @@ -1,6 +1,10 @@ +### Additional authorization for PTE deployment to BC 29 and later + +**Action required for Scope PTE:** BC 29+ S2S deployments need the `AdminCenter.ReadWrite.All` application permission, tenant admin consent, and registration under the Business Central administration center's **Authorized Microsoft Entra apps**. Delegated users need appropriate administration center access. Keep the existing environment permissions and AUTHCONTEXT credential structure. These additional permissions are not required for earlier BC versions or Scope Dev. See [deployment authorization](Workshop/ContinuousDeployment.md#pte-deployment-authorization). Custom deployments and container behavior are unchanged. + ### New `unpublishOldVersions` setting for deployment -The `DeployTo` setting now supports an opt-in `unpublishOldVersions` boolean (default `false`). When enabled, AL-Go unpublishes old, uninstalled versions of the deployed apps from the environment after a successful deployment, keeping Extension Management clean. This only applies to PTE deployments (Scope PTE / automation API), uses the Automation API v2.0 `Microsoft.NAV.unpublish` action, and is non-fatal (failures are reported as warnings and never fail the deployment). +The `DeployTo` setting now supports an opt-in `unpublishOldVersions` boolean (default `false`). After successful Scope PTE deployment on BC 25.4 through 28, it removes only selected apps' uninstalled versions older than the currently installed version. On BC 29 and later, Business Central manages cleanup in the background, which may be delayed; timing and retained versions are not guaranteed. The setting does not control background cleanup: AL-Go warns and skips explicit unpublish without failing deployment. Cleanup failures remain warnings. ### Expanded AL-Go telemetry dashboard diff --git a/Scenarios/RegisterProductionEnvironment.md b/Scenarios/RegisterProductionEnvironment.md index 29b65afff8..01521d30ac 100644 --- a/Scenarios/RegisterProductionEnvironment.md +++ b/Scenarios/RegisterProductionEnvironment.md @@ -2,6 +2,14 @@ *Prerequisites: A completed ["Create a release of your application"](CreateRelease.md) scenario, an online production environment setup for S2S as specified in task 2 here: [Using Service to Service Authentication - Business Central | Microsoft Docs](https://go.microsoft.com/fwlink/?linkid=2217415&clcid=0x409), using the same Microsoft Entra application registration as scenario 3* +## PTE publishing authorization + +Before **Scope PTE** deployment to BC 29 or later using S2S, add the **AdminCenter.ReadWrite.All** application permission under **Dynamics 365 Business Central**, grant tenant admin consent, and register the client ID on the Business Central administration center's **Authorized Microsoft Entra apps** page. Existing app registrations may need this additional authorization. Keep the existing environment API permissions and the Microsoft Entra application registration and required permission sets inside the Business Central environment. These additional permissions are not required for deployment to earlier BC versions. + +The **AUTHCONTEXT** credential structure is unchanged, including `TenantID`, `ClientID`, and `ClientSecret` for S2S. See [deployment authorization](../Workshop/ContinuousDeployment.md#pte-deployment-authorization) and the official [Business Central administration center API authentication documentation](https://learn.microsoft.com/en-us/dynamics365/business-central/dev-itpro/administration/administration-center-api). + +## Register the environment + > [!NOTE] > For access to environments, environment secrets, and deployment branches in private or internal repositories, you must use GitHub Pro, GitHub Team, or GitHub Enterprise. (see [this](https://go.microsoft.com/fwlink/?linkid=2216857&clcid=0x409)). We are considering adding a secondary option for listing environments. diff --git a/Scenarios/RegisterSandboxEnvironment.md b/Scenarios/RegisterSandboxEnvironment.md index 0a40c6bbc5..de608e30ae 100644 --- a/Scenarios/RegisterSandboxEnvironment.md +++ b/Scenarios/RegisterSandboxEnvironment.md @@ -2,6 +2,14 @@ *Prerequisites: A completed ["Add a test app to an existing project"](Scenarios/AddATestApp.md) scenario, a Microsoft Entra application registration, and an online sandbox environment called QA with the setup for S2S as specified in task 1 and 2 [here](https://go.microsoft.com/fwlink/?linkid=2217415&clcid=0x409) completed.* +## PTE publishing authorization + +For **Scope PTE** S2S deployment to BC 29 or later, add the **AdminCenter.ReadWrite.All** application permission under **Dynamics 365 Business Central**, grant tenant admin consent, and register the application's client ID on the Business Central administration center's **Authorized Microsoft Entra apps** page. Existing app registrations may need this additional authorization. Retain the existing environment API permissions and Microsoft Entra application registration inside the environment, including the required permission sets. + +The **AUTHCONTEXT** credential structure below is unchanged. See [deployment authorization](../Workshop/ContinuousDeployment.md#pte-deployment-authorization) and the official [Business Central administration center API authentication documentation](https://learn.microsoft.com/en-us/dynamics365/business-central/dev-itpro/administration/administration-center-api). These additional permissions are not required for deployment to earlier BC versions or **Scope Dev**. + +## Register the environment + > [!NOTE] > For access to environments, environment secrets, and deployment branches in private or internal repositories, you must use GitHub Pro, GitHub Team, or GitHub Enterprise. (see [this](https://go.microsoft.com/fwlink/?linkid=2216857&clcid=0x409)). > If you are running a free GitHub SKU, you can use the [environments](https://aka.ms/algosettings#environments) setting and a secret with a name of the environment followed by` _AuthContext` instead of GitHub environments and environment secrets. diff --git a/Scenarios/settings.md b/Scenarios/settings.md index 7325ee3465..835a5859be 100644 --- a/Scenarios/settings.md +++ b/Scenarios/settings.md @@ -75,7 +75,7 @@ The repository settings are only read from the repository settings file (.github | githubRunnerShell | Specifies which shell is used for build jobs in workflows including a build job. The default is to use the same as defined in **shell**. If the shell setting isn't defined, **powershell** is the default, which results in using _PowerShell 5.1_. Use **pwsh** for _PowerShell 7_. | | environments | Array of logical environment names. You can specify environments in GitHub environments or in the repo settings file. If you specify environments in the settings file, you can create your AUTHCONTEXT secret using **\\_AUTHCONTEXT**. You can specify additional information about environments in a setting called **DeployTo\** | | DeliverTo\ | Structure with additional properties for the deliveryTarget specified. Some properties are deliveryTarget specific. The structure can contain the following properties:
**Branches** = an array of branch patterns, which are allowed to deliver to this deliveryTarget. (Default main)
**CreateContainerIfNotExist** = *[Only for DeliverToStorage]* Create Blob Storage Container if it doesn't already exist. (Default false)
| -| DeployTo\ | Structure with additional properties for the environment specified. `` refers to the GitHub environment name. The structure can contain the following properties:
**EnvironmentType** = specifies the type of environment. The environment type can be used to invoke a custom deployment. (Default SaaS)
**EnvironmentName** = specifies the "real" name of the environment if it differs from the GitHub environment.
**Branches** = an array of branch patterns, which are allowed to deploy to this environment. These branches can also be defined under the environment in GitHub settings and both settings are honored. If neither setting is defined, the default is the **main** branch only.
**Projects** = In multi-project repositories, this property can be a comma separated list of project patterns to deploy to this environment. (Default \*)
**DependencyInstallMode** = Determines how dependencies are deployed if `GenerateDependencyArtifact` is true. Default value is `install` to install dependencies if not already installed. Other values are `ignore` for ignoring dependencies and `upgrade` or `forceUpgrade` for upgrading dependencies.
**includeTestAppsInSandboxEnvironment** = deploys test apps and their dependencies if the environment type is sandbox (Default is `false`)
**excludeAppIds** = array of app ids to exclude from deployment. (Default is `[]`)
**Scope** = Determines the mechanism for deployment to the environment (Dev or PTE). If not specified, AL-Go for GitHub will always use the Dev Scope for AppSource Apps, but also for PTEs when deploying to sandbox environments when impersonation (refreshtoken) is used for authentication.
**SyncMode** = ForceSync if deployment to this environment should happen with ForceSync, else Add. If deploying to the development endpoint you can also specify Development or Clean. (Default Add)
**unpublishOldVersions** = When set to `true`, AL-Go will unpublish old, uninstalled versions of the deployed apps from the environment after a successful deployment, to keep Extension Management clean. Only applies to PTE deployments (Scope PTE / automation API) and is non-fatal (failures are reported as warnings). (Default false)
**BuildMode** = specifies which buildMode to use for the deployment. Default is to use the Default buildMode
**ContinuousDeployment** = true if this environment should be used for continuous deployment, else false. (Default: AL-Go will continuously deploy to sandbox environments or environments, which doesn't end in (PROD) or (FAT)
**runs-on** = specifies which runner to use when deploying to this environment. (Default is settings.runs-on)
**shell** = specifies which shell to use when deploying to this environment, pwsh or powershell. (Default is settings.shell)
**companyId** = Company Id from Business Central (for PowerPlatform connection)
**ppEnvironmentUrl** = Url of the PowerPlatform environment to deploy to
| +| DeployTo\ | Structure with additional properties for the environment specified. `` refers to the GitHub environment name. The structure can contain the following properties:
**EnvironmentType** = specifies the type of environment. The environment type can be used to invoke a custom deployment. (Default SaaS)
**EnvironmentName** = specifies the "real" name of the environment if it differs from the GitHub environment.
**Branches** = an array of branch patterns, which are allowed to deploy to this environment. These branches can also be defined under the environment in GitHub settings and both settings are honored. If neither setting is defined, the default is the **main** branch only.
**Projects** = In multi-project repositories, this property can be a comma separated list of project patterns to deploy to this environment. (Default \*)
**DependencyInstallMode** = Determines how dependencies are deployed if `GenerateDependencyArtifact` is true. Default value is `install` to install dependencies if not already installed. Other values are `ignore` for ignoring dependencies and `upgrade` or `forceUpgrade` for upgrading dependencies.
**includeTestAppsInSandboxEnvironment** = deploys test apps and their dependencies if the environment type is sandbox (Default is `false`)
**excludeAppIds** = array of app ids to exclude from deployment. (Default is `[]`)
**Scope** = Determines the mechanism for deployment to the environment (Dev or PTE). If not specified, AL-Go for GitHub will always use the Dev Scope for AppSource Apps, but also for PTEs when deploying to sandbox environments when impersonation (refreshtoken) is used for authentication. Scope PTE deployment to BC 29 or later requires additional [deployment authorization](../Workshop/ContinuousDeployment.md#pte-deployment-authorization).
**SyncMode** = ForceSync if deployment to this environment should happen with ForceSync, else Add. If deploying to the development endpoint you can also specify Development or Clean. (Default Add)
**unpublishOldVersions** = Optional boolean (`true` or `false`, default `false`), honored by the standard Deploy action in CI/CD and Publish To Environment for both templates after successful Scope PTE publishing. On BC 25.4 through 28, unpublishes only selected apps' uninstalled versions older than the currently installed version. On BC 29 and later, Business Central manages cleanup in the background, which may be delayed; timing and retained versions are not guaranteed. This setting does not control background cleanup: AL-Go warns and skips explicit unpublish without failing deployment. Cleanup failures are warnings; does not apply to Scope Dev or custom deployments.
**BuildMode** = specifies which buildMode to use for the deployment. Default is to use the Default buildMode
**ContinuousDeployment** = true if this environment should be used for continuous deployment, else false. (Default: AL-Go will continuously deploy to sandbox environments or environments, which doesn't end in (PROD) or (FAT)
**runs-on** = specifies which runner to use when deploying to this environment. (Default is settings.runs-on)
**shell** = specifies which shell to use when deploying to this environment, pwsh or powershell. (Default is settings.shell)
**companyId** = Company Id from Business Central (for PowerPlatform connection)
**ppEnvironmentUrl** = Url of the PowerPlatform environment to deploy to
| | alDoc | Structure with properties for the aldoc reference document generation. The structure can contain the following properties:
**continuousDeployment** = Determines if reference documentation will be deployed continuously as part of CI/CD. You can run the **Deploy Reference Documentation** workflow to deploy manually or on a schedule. (Default false)
**deployToGitHubPages** = Determines whether or not the reference documentation site should be deployed to GitHub Pages for the repository. In order to deploy to GitHub Pages, GitHub Pages must be enabled and set to GitHub Actuibs. (Default true)
**maxReleases** = Maximum number of releases to include in the reference documentation. (Default 3)
**groupByProject** = Determines whether projects in multi-project repositories are used as folders in reference documentation
**includeProjects** = An array of projects to include in the reference documentation. (Default all)
**excludeProjects** = An array of projects to exclude in the reference documentation. (Default none)
**header** = Header for the documentation site. (Default: Documentation for...)
**footer** = Footer for the documentation site. (Default: Made with...)
**defaultIndexMD** = Markdown for the landing page of the documentation site. (Default: Reference documentation...)
**defaultReleaseMD** = Markdown for the landing page of the release sites. (Default: Release reference documentation...)
*Note that in header, footer, defaultIndexMD and defaultReleaseMD you can use the following placeholders: {REPOSITORY}, {VERSION}, {INDEXTEMPLATERELATIVEPATH}, {RELEASENOTES}* | | useProjectDependencies | Determines whether your projects are built using a multi-stage built workflow or single stage. After setting useProjectDependencies to true, you need to run Update AL-Go System Files and your workflows including a build job will change to have multiple build jobs, depending on each other. The number of build jobs will be determined by the dependency depth in your projects.
You can change dependencies between your projects, but if the dependency **depth** changes, AL-Go will warn you that updates for your AL-Go System Files are available and you will need to run the workflow. | | CICDPushBranches | CICDPushBranches can be specified as an array of branches, which triggers a CI/CD workflow on commit. You need to run the Update AL-Go System Files workflow for the change to take effect.
Default is [ "main", "release/\*", "feature/\*" ]

**Supported release branch naming formats:**
When using release branches, AL-Go supports various naming conventions for matching previous releases during upgrade testing. The following formats are recognized:
• `releases/26` - matches releases with major version 26
• `releases/26.x` - matches releases with major version 26
• `releases/26x` - matches releases with major version 26
• `releases/v26` - matches releases with major version 26
• `releases/v26.x` - matches releases with major version 26
• `releases/v26x` - matches releases with major version 26
• `releases/26.3` - matches releases with major.minor version 26.3
The same patterns work with the singular `release/` prefix. | diff --git a/Tests/Deploy.Action.Test.ps1 b/Tests/Deploy.Action.Test.ps1 index f1517cd820..62a990042d 100644 --- a/Tests/Deploy.Action.Test.ps1 +++ b/Tests/Deploy.Action.Test.ps1 @@ -55,9 +55,11 @@ Describe "Deploy Action Tests" { Mock GetAppsAndDependenciesFromArtifacts { return @('/tmp/app1.app'), @() } Mock Sort-AppFilesByDependencies { } Mock CheckInstalledApps { } - Mock Publish-PerTenantExtensionApps { $script:publishPTECalled = $true } + Mock PublishPTEApps { $script:publishPTECalled = $true } + Mock Publish-PerTenantExtensionApps { throw "The action must use the shared AL-Go publisher" } Mock Publish-BcContainerApp { } Mock UnpublishOldAppVersions { $script:unpublishAfterPublish = $script:publishPTECalled } + Mock OutputWarning { } } AfterEach { @@ -69,7 +71,7 @@ Describe "Deploy Action Tests" { It 'Invokes cleanup after PTE publish when unpublishOldVersions is true' { InvokeDeploy -deploymentSettings @{ "EnvironmentType" = "SaaS"; "EnvironmentName" = "test"; "Branches" = @(); "Projects" = "*"; "DependencyInstallMode" = "ignore"; "SyncMode" = $null; "Scope" = "PTE"; "continuousDeployment" = $true; "includeTestAppsInSandboxEnvironment" = $false; "excludeAppIds" = @(); "unpublishOldVersions" = $true } - Assert-MockCalled Publish-PerTenantExtensionApps -Exactly 1 + Assert-MockCalled PublishPTEApps -Exactly 1 Assert-MockCalled UnpublishOldAppVersions -Exactly 1 $script:unpublishAfterPublish | Should -BeTrue } @@ -77,7 +79,48 @@ Describe "Deploy Action Tests" { It 'Does not invoke cleanup when unpublishOldVersions is not set (default)' { InvokeDeploy -deploymentSettings @{ "EnvironmentType" = "SaaS"; "EnvironmentName" = "test"; "Branches" = @(); "Projects" = "*"; "DependencyInstallMode" = "ignore"; "SyncMode" = $null; "Scope" = "PTE"; "continuousDeployment" = $true; "includeTestAppsInSandboxEnvironment" = $false; "excludeAppIds" = @() } - Assert-MockCalled Publish-PerTenantExtensionApps -Exactly 1 + Assert-MockCalled PublishPTEApps -Exactly 1 + Assert-MockCalled UnpublishOldAppVersions -Times 0 + Assert-MockCalled OutputWarning -Times 0 + } + + It 'Does not invoke cleanup or warn when unpublishOldVersions is false' { + InvokeDeploy -deploymentSettings @{ "EnvironmentType" = "SaaS"; "EnvironmentName" = "test"; "Branches" = @(); "Projects" = "*"; "DependencyInstallMode" = "ignore"; "SyncMode" = $null; "Scope" = "PTE"; "continuousDeployment" = $true; "includeTestAppsInSandboxEnvironment" = $false; "excludeAppIds" = @(); "unpublishOldVersions" = $false } + + Assert-MockCalled PublishPTEApps -Exactly 1 + Assert-MockCalled UnpublishOldAppVersions -Times 0 + Assert-MockCalled OutputWarning -Times 0 + } + + It 'Passes primary apps to the shared publisher using ' -TestCases @( + @{ syncMode = 'Add'; helperSyncMode = 'Add' }, + @{ syncMode = 'ForceSync'; helperSyncMode = 'Force' } + ) { + param($syncMode, $helperSyncMode) + $expectedSyncMode = $helperSyncMode + Mock PublishPTEApps { + $PesterBoundParameters.Keys | Should -Not -Contain 'schedule' + } + + InvokeDeploy -deploymentSettings @{ "EnvironmentType" = "SaaS"; "EnvironmentName" = "test"; "Branches" = @(); "Projects" = "*"; "DependencyInstallMode" = "ignore"; "SyncMode" = $syncMode; "Scope" = "PTE"; "continuousDeployment" = $true; "includeTestAppsInSandboxEnvironment" = $false; "excludeAppIds" = @() } + + Assert-MockCalled PublishPTEApps -Exactly 1 -ParameterFilter { + $environment -eq 'test' -and $bcAuthContext.tenantId -eq 'test-tenant' -and + $appFiles.Count -eq 1 -and $appFiles[0] -eq '/tmp/app1.app' -and $SchemaSyncMode -eq $expectedSyncMode + } + Assert-MockCalled Publish-BcContainerApp -Times 0 + Assert-MockCalled Publish-PerTenantExtensionApps -Times 0 + } + + It 'Does not retry publishing or invoke cleanup after shared publishing fails' { + Mock PublishPTEApps { throw "Publishing authorization failed" } + Mock OutputError { param($message) throw $message } + + { InvokeDeploy -deploymentSettings @{ "EnvironmentType" = "SaaS"; "EnvironmentName" = "test"; "Branches" = @(); "Projects" = "*"; "DependencyInstallMode" = "ignore"; "SyncMode" = $null; "Scope" = "PTE"; "continuousDeployment" = $true; "includeTestAppsInSandboxEnvironment" = $false; "excludeAppIds" = @(); "unpublishOldVersions" = $true } } | Should -Throw "*Publishing authorization failed*" + + Assert-MockCalled PublishPTEApps -Exactly 1 + Assert-MockCalled Publish-PerTenantExtensionApps -Times 0 + Assert-MockCalled Publish-BcContainerApp -Times 0 Assert-MockCalled UnpublishOldAppVersions -Times 0 } @@ -85,6 +128,7 @@ Describe "Deploy Action Tests" { InvokeDeploy -deploymentSettings @{ "EnvironmentType" = "SaaS"; "EnvironmentName" = "test"; "Branches" = @(); "Projects" = "*"; "DependencyInstallMode" = "ignore"; "SyncMode" = $null; "Scope" = "Dev"; "continuousDeployment" = $true; "includeTestAppsInSandboxEnvironment" = $false; "excludeAppIds" = @(); "unpublishOldVersions" = $true } Assert-MockCalled Publish-BcContainerApp -Exactly 1 + Assert-MockCalled PublishPTEApps -Times 0 Assert-MockCalled Publish-PerTenantExtensionApps -Times 0 Assert-MockCalled UnpublishOldAppVersions -Times 0 } diff --git a/Tests/Deploy.Module.Test.ps1 b/Tests/Deploy.Module.Test.ps1 index 91f0ace0b0..3ca1634bbf 100644 --- a/Tests/Deploy.Module.Test.ps1 +++ b/Tests/Deploy.Module.Test.ps1 @@ -160,7 +160,8 @@ InModuleScope Deploy { # Allows testing of private functions } Mock Sort-AppFilesByDependencies { } Mock Install-BcAppFromAppSource { return $true } - Mock Publish-PerTenantExtensionApps { return $true } + Mock PublishPTEApps { return $true } + Mock Publish-PerTenantExtensionApps { throw "Dependencies must use the shared AL-Go publisher" } Mock Write-Host { } } @@ -784,7 +785,7 @@ InModuleScope Deploy { # Allows testing of private functions Assert-MockCalled Install-BcAppFromAppSource -Exactly 1 -ParameterFilter { $appId -eq $script:appSourceApp1Id -and $acceptIsvEula -eq $true -and $installOrUpdateNeededDependencies -eq $true } - Assert-MockCalled Publish-PerTenantExtensionApps -Times 0 + Assert-MockCalled PublishPTEApps -Times 0 } It 'Publishes PTE apps when upgrade needed' { @@ -803,9 +804,27 @@ InModuleScope Deploy { # Allows testing of private functions InstallOrUpgradeApps -bcAuthContext $bcAuthContext -environment $environment -apps $apps -installMode $installMode Assert-MockCalled Install-BcAppFromAppSource -Times 0 - Assert-MockCalled Publish-PerTenantExtensionApps -Exactly 1 -ParameterFilter { - $appFiles.Count -eq 1 -and $SchemaSyncMode -eq "Add" + Assert-MockCalled PublishPTEApps -Exactly 1 -ParameterFilter { + $appFiles.Count -eq 1 -and $SchemaSyncMode -eq "Add" -and + $bcAuthContext.tenantId -eq "test-tenant" -and $environment -eq "test-env" + } + } + + It 'Delegates PTE dependency publishing without requesting deferred installation' { + Mock Get-ChildItem { + param($Path) + return @(@{ FullName = Join-Path $Path "PTEApp.app" }) + } + Mock PublishPTEApps { + $PesterBoundParameters.Keys | Should -Not -Contain 'schedule' + } + + InstallOrUpgradeApps -bcAuthContext @{ tenantId = "test-tenant" } -environment "test-env" -apps @("PTEApp.app") -installMode "upgrade" + + Assert-MockCalled PublishPTEApps -Exactly 1 -ParameterFilter { + $appFiles.Count -eq 1 -and $appFiles[0] -like "*PTEApp.app" -and $SchemaSyncMode -eq "Add" } + Assert-MockCalled Publish-PerTenantExtensionApps -Times 0 } It 'Uses Force schema sync mode when installMode is ForceUpgrade' { @@ -823,11 +842,26 @@ InModuleScope Deploy { # Allows testing of private functions InstallOrUpgradeApps -bcAuthContext $bcAuthContext -environment $environment -apps $apps -installMode $installMode - Assert-MockCalled Publish-PerTenantExtensionApps -Exactly 1 -ParameterFilter { + Assert-MockCalled PublishPTEApps -Exactly 1 -ParameterFilter { $SchemaSyncMode -eq "Force" } } + It 'Propagates shared publishing errors without retrying and cleans up temporary files' { + Mock Get-ChildItem { + param($Path) + return @(@{ FullName = Join-Path $Path "PTEApp.app" }) + } + Mock PublishPTEApps { throw "Publishing authorization failed" } + + { InstallOrUpgradeApps -bcAuthContext @{ tenantId = "test-tenant" } -environment "test-env" -apps @("PTEApp.app") -installMode "upgrade" } | Should -Throw "*Publishing authorization failed*" + + Assert-MockCalled PublishPTEApps -Exactly 1 + Assert-MockCalled Publish-PerTenantExtensionApps -Times 0 + Assert-MockCalled Install-BcAppFromAppSource -Times 0 + Assert-MockCalled Remove-Item -Exactly 1 -ParameterFilter { $Force -and $Recurse } + } + It 'Skips AppSource apps published in Dev scope when upgrade needed' { Mock Get-ChildItem { param($Path) @@ -863,7 +897,7 @@ InModuleScope Deploy { # Allows testing of private functions $appId -eq $script:appSourceApp1Id } # Should publish PTE apps - Assert-MockCalled Publish-PerTenantExtensionApps -Exactly 1 -ParameterFilter { + Assert-MockCalled PublishPTEApps -Exactly 1 -ParameterFilter { $appFiles.Count -eq 1 } } @@ -877,7 +911,7 @@ InModuleScope Deploy { # Allows testing of private functions InstallOrUpgradeApps -bcAuthContext $bcAuthContext -environment $environment -apps $apps -installMode $installMode Assert-MockCalled Install-BcAppFromAppSource -Times 0 - Assert-MockCalled Publish-PerTenantExtensionApps -Times 0 + Assert-MockCalled PublishPTEApps -Times 0 } It 'Handles empty apps array' { @@ -896,7 +930,7 @@ InModuleScope Deploy { # Allows testing of private functions $appFiles.Count -eq 0 } Assert-MockCalled Install-BcAppFromAppSource -Times 0 - Assert-MockCalled Publish-PerTenantExtensionApps -Times 0 + Assert-MockCalled PublishPTEApps -Times 0 } It 'Refreshes installed apps list after AppSource installation' { diff --git a/Tests/PublishPTEApps.Test.ps1 b/Tests/PublishPTEApps.Test.ps1 new file mode 100644 index 0000000000..6ec9fd8590 --- /dev/null +++ b/Tests/PublishPTEApps.Test.ps1 @@ -0,0 +1,483 @@ +Import-Module (Join-Path $PSScriptRoot '../Actions/Deploy/Deploy.psm1') -Force + +InModuleScope Deploy { + Describe "AL-Go PTE publishing" { + BeforeAll { + . (Join-Path $PSScriptRoot '../Actions/AL-Go-Helper.ps1') + DownloadAndImportBcContainerHelper -baseFolder ([System.IO.Path]::GetTempPath()) + Add-Type -AssemblyName System.Net.Http + $script:originalConfig = $bcContainerHelperConfig + } + + AfterAll { + $script:bcContainerHelperConfig = $script:originalConfig + } + + BeforeEach { + $script:bcContainerHelperConfig = @{ apiBaseUrl = 'https://api.example.test/' } + $script:application = @{ + id = 'application'; displayName = 'Application'; isInstalled = $true + versionMajor = 29; versionMinor = 0; versionBuild = 0; versionRevision = 0 + } + $script:extensions = @($script:application) + Mock Write-Host { } + Mock OutputWarning { } + Mock Renew-BcAuthContext { return @{ AccessToken = 'renewed-test-token' } } + Mock Invoke-RestMethod { throw "Unexpected HTTP request" } + Mock Get-BcInstalledExtensions { return $script:extensions } + Mock Publish-PerTenantExtensionApps { } + } + + Context "Shared router" { + BeforeEach { + Mock NewTemporaryFolder { return 'test-app-folder' } + Mock Copy-AppFilesToFolder { return @('App.app') } + Mock Sort-AppFilesByDependencies { return @('App.app') } + Mock Remove-Item { } + Mock Get-AppJsonFromAppFile { return @{ id = 'app-1'; name = 'App'; version = '2.0.0.0' } } + Mock InvokePTEUpload { return @{ id = 'operation-1'; appId = 'app-1'; status = 'running' } } + Mock WaitPTEOperation { } + } + + It 'Uses only the released helper for BC 28 and preserves Force and immediate defaults' { + $script:application.versionMajor = 28 + Mock Publish-PerTenantExtensionApps { + $PesterBoundParameters.Keys | Should -Not -Contain 'schedule' + $PesterBoundParameters.Keys | Should -Not -Contain 'applicationFamily' + } + + PublishPTEApps -bcAuthContext @{ tenantId = 'tenant' } -environment 'Sandbox' -appFiles @('Apps.zip') -schemaSyncMode Force + + Assert-MockCalled Publish-PerTenantExtensionApps -Exactly 1 -ParameterFilter { + $environment -eq 'Sandbox' -and $bcAuthContext.tenantId -eq 'tenant' -and + $appFiles[0] -eq 'Apps.zip' -and $schemaSyncMode -eq 'Force' + } + Assert-MockCalled InvokePTEUpload -Times 0 + Assert-MockCalled NewTemporaryFolder -Times 0 + Assert-MockCalled Invoke-RestMethod -Times 0 + } + + It 'Keeps API implementation helpers private and exposes the shared publisher' { + $exports = (Get-Module Deploy).ExportedFunctions.Keys + $exports | Should -Contain 'PublishPTEApps' + $exports | Should -Not -Contain 'InvokePTEUpload' + $exports | Should -Not -Contain 'WaitPTEOperation' + $exports | Should -Not -Contain 'GetPTEApplicationVersion' + } + + It 'Uses AL-Go Admin Center publishing for BC ' -TestCases @( + @{ major = 29 }, @{ major = 30 } + ) { + param($major) + $script:application.versionMajor = $major + + PublishPTEApps -bcAuthContext @{} -environment 'Sandbox' -appFiles @('Apps.zip') + + Assert-MockCalled Publish-PerTenantExtensionApps -Times 0 + Assert-MockCalled Copy-AppFilesToFolder -Exactly 1 -ParameterFilter { $appFiles[0] -eq 'Apps.zip' } + Assert-MockCalled Sort-AppFilesByDependencies -Exactly 1 -ParameterFilter { $excludeRuntimePackages } + Assert-MockCalled InvokePTEUpload -Exactly 1 -ParameterFilter { $syncMode -eq 'Add' } + Assert-MockCalled WaitPTEOperation -Exactly 1 -ParameterFilter { $appId -eq 'app-1' } + Assert-MockCalled Remove-Item -Exactly 1 -ParameterFilter { $LiteralPath -eq 'test-app-folder' -and $Recurse -and $Force } + } + + It 'Uses the configured base URL and escapes environment and application family' { + PublishPTEApps -bcAuthContext @{} -environment 'QA / East' -applicationFamily 'Family / US' -appFiles @('App.app') -schemaSyncMode Force + + Assert-MockCalled InvokePTEUpload -Exactly 1 -ParameterFilter { + $uri -eq 'https://api.example.test/admin/v2.29/applications/Family%20%2F%20US/environments/QA%20%2F%20East/apps/pteInstall' -and + $syncMode -eq 'ForceSync' + } + } + + It 'Does not mistake the package version for the target BC version' { + Mock Get-AppJsonFromAppFile { return @{ id = 'app-1'; name = 'App'; version = '28.0.0.0' } } + + PublishPTEApps -bcAuthContext @{} -environment 'Sandbox' -appFiles @('App.app') + + Assert-MockCalled InvokePTEUpload -Exactly 1 + Assert-MockCalled Publish-PerTenantExtensionApps -Times 0 + } + + It 'Fails explicitly before any publishing when the target version is ' -TestCases @( + @{ problem = 'missing' }, @{ problem = 'incomplete' }, @{ problem = 'invalid' }, @{ problem = 'ambiguous' } + ) { + param($problem) + switch ($problem) { + missing { $script:extensions = @() } + incomplete { $script:application.Remove('versionMinor') } + invalid { $script:application.versionMajor = 'unknown' } + ambiguous { $script:extensions += $script:application.Clone() } + } + + { PublishPTEApps -bcAuthContext @{} -environment 'Sandbox' -appFiles @('App.app') } | Should -Throw '*Could not determine the Business Central version*' + + Assert-MockCalled Publish-PerTenantExtensionApps -Times 0 + Assert-MockCalled InvokePTEUpload -Times 0 + } + + It 'Ignores uninstalled Application records when detecting the target version' { + $oldApplication = $script:application.Clone() + $oldApplication.isInstalled = $false + $oldApplication.versionMajor = 28 + $script:extensions = @($oldApplication, [PSCustomObject]$script:application) + + PublishPTEApps -bcAuthContext @{} -environment 'Sandbox' -appFiles @('App.app') + + Assert-MockCalled InvokePTEUpload -Exactly 1 + Assert-MockCalled Publish-PerTenantExtensionApps -Times 0 + } + + It 'Skips an installed version but not a newer uninstalled package' -TestCases @( + @{ version = 2 }, @{ version = 3 } + ) { + param($version) + $script:extensions += @{ + id = 'app-1'; displayName = 'App'; isInstalled = $true + versionMajor = $version; versionMinor = 0; versionBuild = 0; versionRevision = 0 + } + + PublishPTEApps -bcAuthContext @{} -environment 'Sandbox' -appFiles @('App.app') + + Assert-MockCalled InvokePTEUpload -Times 0 + Assert-MockCalled WaitPTEOperation -Times 0 + } + + It 'Upgrades an older installed app even if an uninstalled newer package is present' { + $script:extensions += @( + @{ id = 'app-1'; displayName = 'App'; isInstalled = $true; versionMajor = 1; versionMinor = 0; versionBuild = 0; versionRevision = 0 }, + @{ id = 'app-1'; displayName = 'App'; isInstalled = $false; versionMajor = 3; versionMinor = 0; versionBuild = 0; versionRevision = 0 } + ) + + PublishPTEApps -bcAuthContext @{} -environment 'Sandbox' -appFiles @('App.app') + + Assert-MockCalled InvokePTEUpload -Exactly 1 + Assert-MockCalled WaitPTEOperation -Exactly 1 + } + + It 'Completes each dependency before uploading its dependent app and skips runtime packages' { + Mock Copy-AppFilesToFolder { return @('Dependent.app', 'Runtime.app', 'Dependency.app') } + Mock Sort-AppFilesByDependencies { return @('Dependency.app', 'Dependent.app') } + Mock Get-AppJsonFromAppFile { + param($appFile) + return @{ id = $appFile; name = $appFile; version = '2.0.0.0' } + } + $script:events = @() + Mock InvokePTEUpload { + param($appFile) + $script:events += "upload:$appFile" + return @{ id = "operation-$appFile"; appId = $appFile; status = 'running' } + } + Mock WaitPTEOperation { + param($appId) + $script:events += "complete:$appId" + } + + PublishPTEApps -bcAuthContext @{} -environment 'Sandbox' -appFiles @('Apps.zip') + + ($script:events -join ',') | Should -Be 'upload:Dependency.app,complete:Dependency.app,upload:Dependent.app,complete:Dependent.app' + Assert-MockCalled Sort-AppFilesByDependencies -Exactly 1 -ParameterFilter { $excludeRuntimePackages -and $appFiles.Count -eq 3 } + Assert-MockCalled InvokePTEUpload -Times 0 -ParameterFilter { $appFile -eq 'Runtime.app' } + } + + It 'Remembers completed installs when another package for the same app is encountered' { + Mock Sort-AppFilesByDependencies { return @('App.app', 'Duplicate.app') } + + PublishPTEApps -bcAuthContext @{} -environment 'Sandbox' -appFiles @('App.app', 'Duplicate.app') + + Assert-MockCalled InvokePTEUpload -Exactly 1 + Assert-MockCalled WaitPTEOperation -Exactly 1 + } + + It 'Does not fall back or continue after failure' -TestCases @( + @{ step = 'upload' }, @{ step = 'polling' }, @{ step = 'authorization' } + ) { + param($step) + switch ($step) { + upload { Mock InvokePTEUpload { throw "Package upload failed" } } + polling { Mock WaitPTEOperation { throw "Installation failed" } } + authorization { Mock InvokePTEUpload { throw "403 Forbidden" } } + } + + { PublishPTEApps -bcAuthContext @{} -environment 'Sandbox' -appFiles @('App.app') } | Should -Throw + + Assert-MockCalled Publish-PerTenantExtensionApps -Times 0 + Assert-MockCalled InvokePTEUpload -Exactly 1 + Assert-MockCalled Remove-Item -Exactly 1 + } + } + + Context "Multipart upload" { + BeforeEach { + $script:packagePath = Join-Path $TestDrive 'Binary Package.app' + $script:packageBytes = [byte[]]@(0, 1, 127, 128, 255, 13, 10, 65, 66) + [System.IO.File]::WriteAllBytes($script:packagePath, $script:packageBytes) + } + + It 'Sends actual multipart fields and unchanged binary bytes using ' -TestCases @( + @{ syncMode = 'Add' }, @{ syncMode = 'ForceSync' } + ) { + param($syncMode) + $expectedSyncMode = $syncMode + Mock Invoke-RestMethod { + param($Body, $ContentType) + ,$Body | Should -BeOfType [byte[]] + $ContentType | Should -BeLike 'multipart/form-data; boundary=*' + $wireText = [System.Text.Encoding]::GetEncoding(28591).GetString($Body) + $wireText | Should -Match 'name="?deploymentSchedule"?\r\n\r\nImmediate\r\n' + $wireText | Should -Match ('name="?syncMode"?\r\n\r\n' + $expectedSyncMode + '\r\n') + $wireText | Should -Match 'name="?acceptIsvEula"?\r\n\r\ntrue\r\n' + $wireText | Should -Match 'name="?installOrUpdateNeededDependencies"?\r\n\r\nfalse\r\n' + $wireText | Should -Match 'name="?extensionFile"?; filename="Binary Package.app"' + $wireText | Should -Match 'Content-Type: application/octet-stream' + $wireText.Contains([System.Text.Encoding]::GetEncoding(28591).GetString($script:packageBytes)) | Should -BeTrue + return [PSCustomObject]@{ id = 'operation-1'; appId = 'app-1'; status = 'running' } + } + + $result = InvokePTEUpload -bcAuthContext @{} -uri 'https://api.example.test/apps/pteInstall' -appFile $script:packagePath -syncMode $syncMode + + $result.id | Should -Be 'operation-1' + Assert-MockCalled Renew-BcAuthContext -Exactly 1 + Assert-MockCalled Invoke-RestMethod -Exactly 1 -ParameterFilter { + $Method -eq 'Post' -and $TimeoutSec -eq 300 -and $ErrorAction -eq 'Stop' -and + $Headers.Authorization -eq 'Bearer renewed-test-token' + } + $stream = [System.IO.File]::Open($script:packagePath, 'Open', 'ReadWrite', 'None') + $stream.Dispose() + } + + It 'Disposes streams and never replays an ambiguous upload failure' { + Mock Invoke-RestMethod { throw [System.TimeoutException]::new('Upload timed out') } + + { InvokePTEUpload -bcAuthContext @{} -uri 'https://api.example.test/apps/pteInstall' -appFile $script:packagePath -syncMode Add } | Should -Throw '*Upload timed out*' + + Assert-MockCalled Invoke-RestMethod -Exactly 1 + $stream = [System.IO.File]::Open($script:packagePath, 'Open', 'ReadWrite', 'None') + $stream.Dispose() + } + + It 'Fails before upload if renewing authentication fails' { + Mock Renew-BcAuthContext { throw 'Authentication failed' } + + { InvokePTEUpload -bcAuthContext @{} -uri 'https://api.example.test/apps/pteInstall' -appFile $script:packagePath -syncMode Add } | Should -Throw '*Authentication failed*' + + Assert-MockCalled Invoke-RestMethod -Times 0 + } + + It 'Rejects a renewal response without an access token' { + Mock Renew-BcAuthContext { return @{} } + + { InvokePTEUpload -bcAuthContext @{} -uri 'https://api.example.test/apps/pteInstall' -appFile $script:packagePath -syncMode Add } | Should -Throw '*Authentication failed*' + + Assert-MockCalled Invoke-RestMethod -Times 0 + } + + It 'Preserves service upload diagnostics without replaying the upload' { + Mock Invoke-RestMethod { + $record = [System.Management.Automation.ErrorRecord]::new([System.Exception]::new('400 Bad Request'), 'InvalidPackage', 'InvalidData', $null) + $record.ErrorDetails = [System.Management.Automation.ErrorDetails]::new('Service rejected the package signature') + throw $record + } + + { InvokePTEUpload -bcAuthContext @{} -uri 'https://api.example.test/apps/pteInstall' -appFile $script:packagePath -syncMode Add } | Should -Throw '*400 Bad Request*Service rejected the package signature*not be replayed*' + + Assert-MockCalled Invoke-RestMethod -Exactly 1 + } + } + + Context "Exact operation polling" { + BeforeEach { + $script:operation = [PSCustomObject]@{ id = 'operation / 1'; appId = 'app-1'; status = 'running'; scheduleKind = 'immediate' } + Mock Start-Sleep { } + Mock Invoke-RestMethod { return [PSCustomObject]@{ id = 'operation / 1'; appId = 'app-1'; status = 'succeeded' } } + } + + It 'Accepts immediate success without polling' { + $script:operation.status = 'succeeded' + + WaitPTEOperation -bcAuthContext @{} -appsUri 'https://api.example.test/apps' -operation $script:operation -appId 'app-1' + + Assert-MockCalled Invoke-RestMethod -Times 0 + } + + It 'Polls only the exact returned operation and renews authentication' { + WaitPTEOperation -bcAuthContext @{} -appsUri 'https://api.example.test/apps' -operation $script:operation -appId 'app-1' + + Assert-MockCalled Invoke-RestMethod -Exactly 1 -ParameterFilter { + $Method -eq 'Get' -and $Uri -eq 'https://api.example.test/apps/app-1/operations/operation%20%2F%201' -and + $Headers.Authorization -eq 'Bearer renewed-test-token' -and $TimeoutSec -le 30 + } + Assert-MockCalled Renew-BcAuthContext -Exactly 1 + } + + It 'Does not count scheduled immediate installation as success' { + $script:operation.status = 'scheduled' + + WaitPTEOperation -bcAuthContext @{} -appsUri 'https://api.example.test/apps' -operation $script:operation -appId 'app-1' + + Assert-MockCalled Invoke-RestMethod -Exactly 1 + } + + It 'Fails explicitly for terminal or unknown status ' -TestCases @( + @{ status = 'failed' }, @{ status = 'canceled' }, @{ status = 'skipped' }, @{ status = 'unknown' }, @{ status = '' } + ) { + param($status) + $script:operation.status = $status + $script:operation | Add-Member -NotePropertyName errorMessage -NotePropertyValue 'Service diagnostic' + + { WaitPTEOperation -bcAuthContext @{} -appsUri 'https://api.example.test/apps' -operation $script:operation -appId 'app-1' } | Should -Throw '*operation / 1*Service diagnostic*' + + Assert-MockCalled Invoke-RestMethod -Times 0 + } + + It 'Rejects upload responses with missing or mismatched ' -TestCases @( + @{ detail = 'operationId' }, @{ detail = 'appId' }, @{ detail = 'wrongApp' }, @{ detail = 'empty' } + ) { + param($detail) + switch ($detail) { + operationId { $script:operation.id = '' } + appId { $script:operation.PSObject.Properties.Remove('appId') } + wrongApp { $script:operation.appId = 'another-app' } + empty { $script:operation = $null } + } + + { WaitPTEOperation -bcAuthContext @{} -appsUri 'https://api.example.test/apps' -operation $script:operation -appId 'app-1' } | Should -Throw '*missing or mismatched*' + + Assert-MockCalled Invoke-RestMethod -Times 0 + } + + It 'Rejects missing or unrelated status response ' -TestCases @( + @{ response = 'empty' }, @{ response = 'anotherOperation' }, @{ response = 'anotherApp' }, @{ response = 'collection' } + ) { + param($response) + $script:responseKind = $response + Mock Invoke-RestMethod { + switch ($script:responseKind) { + empty { return $null } + anotherOperation { return [PSCustomObject]@{ id = 'other'; status = 'succeeded' } } + anotherApp { return [PSCustomObject]@{ id = 'operation / 1'; appId = 'other'; status = 'succeeded' } } + collection { return [PSCustomObject]@{ value = @(@{ id = 'operation / 1'; status = 'succeeded' }) } } + } + } + + { WaitPTEOperation -bcAuthContext @{} -appsUri 'https://api.example.test/apps' -operation $script:operation -appId 'app-1' } | Should -Throw '*Missing or mismatched PTE operation*' + } + + It 'Retries transient status failures and then succeeds without any write' { + $script:reads = 0 + Mock Invoke-RestMethod { + $script:reads++ + if ($script:reads -lt 3) { throw [System.TimeoutException]::new('Temporary failure') } + return [PSCustomObject]@{ id = 'operation / 1'; appId = 'app-1'; status = 'succeeded' } + } + + WaitPTEOperation -bcAuthContext @{} -appsUri 'https://api.example.test/apps' -operation $script:operation -appId 'app-1' + + Assert-MockCalled Invoke-RestMethod -Exactly 3 -ParameterFilter { $Method -eq 'Get' } + Assert-MockCalled Invoke-RestMethod -Times 0 -ParameterFilter { $Method -ne 'Get' } + Assert-MockCalled OutputWarning -Exactly 2 + } + + It 'Stops after five consecutive transient retries' { + Mock Invoke-RestMethod { throw [System.TimeoutException]::new('Temporary failure') } + + { WaitPTEOperation -bcAuthContext @{} -appsUri 'https://api.example.test/apps' -operation $script:operation -appId 'app-1' } | Should -Throw '*Unable to read PTE operation*Temporary failure*' + + Assert-MockCalled Invoke-RestMethod -Exactly 6 + Assert-MockCalled OutputWarning -Exactly 5 + } + + It 'Retries HTTP but never HTTP authorization failures' -TestCases @( + @{ statusCode = 408; retry = $true }, + @{ statusCode = 429; retry = $true }, + @{ statusCode = 500; retry = $true }, + @{ statusCode = 502; retry = $true }, + @{ statusCode = 503; retry = $true }, + @{ statusCode = 504; retry = $true }, + @{ statusCode = 401; retry = $false }, + @{ statusCode = 403; retry = $false } + ) { + param($statusCode, $retry) + $script:httpStatus = $statusCode + $script:reads = 0 + Mock Invoke-RestMethod { + $script:reads++ + if ($script:reads -eq 1) { + $exception = [System.Exception]::new("HTTP $script:httpStatus") + $exception | Add-Member -NotePropertyName Response -NotePropertyValue ([PSCustomObject]@{ StatusCode = $script:httpStatus }) + throw $exception + } + return [PSCustomObject]@{ id = 'operation / 1'; appId = 'app-1'; status = 'succeeded' } + } + + if ($retry) { + WaitPTEOperation -bcAuthContext @{} -appsUri 'https://api.example.test/apps' -operation $script:operation -appId 'app-1' + Assert-MockCalled Invoke-RestMethod -Exactly 2 + Assert-MockCalled OutputWarning -Exactly 1 + } + else { + { WaitPTEOperation -bcAuthContext @{} -appsUri 'https://api.example.test/apps' -operation $script:operation -appId 'app-1' } | Should -Throw '*Unable to read PTE operation*' + Assert-MockCalled Invoke-RestMethod -Exactly 1 + Assert-MockCalled OutputWarning -Times 0 + } + } + + It 'Resets the consecutive retry budget after a successful running status read' { + $script:reads = 0 + Mock Invoke-RestMethod { + $script:reads++ + if ($script:reads -eq 6) { return [PSCustomObject]@{ id = 'operation / 1'; status = 'running' } } + if ($script:reads -eq 12) { return [PSCustomObject]@{ id = 'operation / 1'; status = 'succeeded' } } + throw [System.TimeoutException]::new('Transient timeout') + } + + WaitPTEOperation -bcAuthContext @{} -appsUri 'https://api.example.test/apps' -operation $script:operation -appId 'app-1' + + Assert-MockCalled Invoke-RestMethod -Exactly 12 + Assert-MockCalled OutputWarning -Exactly 10 + } + + It 'Does not retry non-transient errors or renew failures' { + Mock Renew-BcAuthContext { throw '403 Forbidden' } + + { WaitPTEOperation -bcAuthContext @{} -appsUri 'https://api.example.test/apps' -operation $script:operation -appId 'app-1' } | Should -Throw '*403 Forbidden*' + + Assert-MockCalled Invoke-RestMethod -Times 0 + Assert-MockCalled OutputWarning -Times 0 + } + + It 'Does not retry an authorization status-read failure' { + Mock Invoke-RestMethod { throw '401 Unauthorized' } + + { WaitPTEOperation -bcAuthContext @{} -appsUri 'https://api.example.test/apps' -operation $script:operation -appId 'app-1' } | Should -Throw '*Unable to read PTE operation*401 Unauthorized*' + + Assert-MockCalled Invoke-RestMethod -Exactly 1 + Assert-MockCalled OutputWarning -Times 0 + } + + It 'Bounds status attempts even when the operation remains scheduled' { + Mock Invoke-RestMethod { return [PSCustomObject]@{ id = 'operation / 1'; status = 'scheduled' } } + + { WaitPTEOperation -bcAuthContext @{} -appsUri 'https://api.example.test/apps' -operation $script:operation -appId 'app-1' -maxStatusRequests 2 } | Should -Throw '*Timed out*2 status requests*' + + Assert-MockCalled Invoke-RestMethod -Exactly 2 + } + + It 'Limits the default immediate polling to 360 status requests' { + Mock Invoke-RestMethod { return [PSCustomObject]@{ id = 'operation / 1'; status = 'running' } } + + { WaitPTEOperation -bcAuthContext @{} -appsUri 'https://api.example.test/apps' -operation $script:operation -appId 'app-1' } | Should -Throw '*Timed out*1800 seconds or 360 status requests*' + + Assert-MockCalled Invoke-RestMethod -Exactly 360 + } + + It 'Honors the elapsed timeout before another status request' { + Mock Start-Sleep { [System.Threading.Thread]::Sleep(1100) } + + { WaitPTEOperation -bcAuthContext @{} -appsUri 'https://api.example.test/apps' -operation $script:operation -appId 'app-1' -timeoutSeconds 1 } | Should -Throw '*Timed out*1 seconds*' + + Assert-MockCalled Invoke-RestMethod -Times 0 + } + } + } +} diff --git a/Tests/UnpublishOldAppVersions.Test.ps1 b/Tests/UnpublishOldAppVersions.Test.ps1 index 9220ef074b..bb2feeba30 100644 --- a/Tests/UnpublishOldAppVersions.Test.ps1 +++ b/Tests/UnpublishOldAppVersions.Test.ps1 @@ -63,6 +63,48 @@ InModuleScope Deploy { # Allows testing of private functions } } + It 'Explains delayed service-managed cleanup without any writes on BC .' -TestCases @( + @{ major = 29; minor = 0 }, + @{ major = 29; minor = 1 }, + @{ major = 30; minor = 0 } + ) { + param($major, $minor) + $script:applicationExtension.versionMajor = $major + $script:applicationExtension.versionMinor = $minor + + { UnpublishOldAppVersions -bcAuthContext @{ tenantId = "test-tenant" } -environment "test-env" -appFiles @("App1.app") } | Should -Not -Throw + + Assert-MockCalled OutputWarning -Exactly 1 -ParameterFilter { + $message -like "*cannot explicitly unpublish*Business Central manages cleanup in the background*may be delayed*timing and retained versions are not guaranteed*AL-Go cleanup was skipped*deployment remains successful*" + } + Assert-MockCalled Invoke-RestMethod -Times 0 -ParameterFilter { $Method -ne "Get" } + } + + It 'Preserves legacy cleanup on BC .' -TestCases @( + @{ major = 25; minor = 4 }, + @{ major = 28; minor = 9 } + ) { + param($major, $minor) + $script:applicationExtension.versionMajor = $major + $script:applicationExtension.versionMinor = $minor + + UnpublishOldAppVersions -bcAuthContext @{ tenantId = "test-tenant" } -environment "test-env" -appFiles @("App1.app") + + Assert-MockCalled OutputWarning -Times 0 + Assert-MockCalled Invoke-RestMethod -Exactly 1 -ParameterFilter { + $Method -eq "Post" -and $Uri -like "*extensions(pkg-app1-v1)/Microsoft.NAV.unpublish" + } + } + + It 'Warns without writes when the installed Application version is unknown' { + $script:applicationExtension.isInstalled = $false + + UnpublishOldAppVersions -bcAuthContext @{ tenantId = "test-tenant" } -environment "test-env" -appFiles @("App1.app") + + Assert-MockCalled OutputWarning -Exactly 1 -ParameterFilter { $message -like "*Could not determine the Business Central version*" } + Assert-MockCalled Invoke-RestMethod -Times 0 -ParameterFilter { $Method -ne "Get" } + } + It 'Uses the automation API v2.0 endpoint with a bearer token' { UnpublishOldAppVersions -bcAuthContext @{ tenantId = "test-tenant" } -environment "test-env" -appFiles @("App1.app") diff --git a/Workshop/ContinuousDeployment.md b/Workshop/ContinuousDeployment.md index 5591a5d49f..98c7864811 100644 --- a/Workshop/ContinuousDeployment.md +++ b/Workshop/ContinuousDeployment.md @@ -88,6 +88,22 @@ New-BcAuthContext -clientID $clientID -clientSecret $clientSecret -tenantID $ten Paste the value from the clipboard into the "Value" field of the **AuthContext** secret for the environment and you should be good to go. +## PTE deployment authorization + +For **Scope PTE** S2S deployment to **BC 29 or later**, add the **AdminCenter.ReadWrite.All** application permission under **Dynamics 365 Business Central**, grant **tenant admin consent**, and add the client ID to **Authorized Microsoft Entra apps** in the Business Central administration center. Existing app registrations that previously deployed successfully may need this additional authorization. Keep the environment API permissions, such as **Automation.ReadWrite.All** and **API.ReadWrite.All** where required, and the Microsoft Entra application registration and permission sets inside each Business Central environment. + +With delegated authentication (impersonation), **Scope PTE** deployment to **BC 29 or later** requires appropriate **Business Central administration center access** as well as the environment permissions. The existing **AUTHCONTEXT** credential structure and the commands above remain unchanged. See the official [Business Central administration center API documentation](https://learn.microsoft.com/en-us/dynamics365/business-central/dev-itpro/administration/administration-center-api) for authentication and authorization details. + +These additional permissions are not required for deployment to earlier BC versions or the sandbox development endpoint (**Scope Dev**). + +## Old published versions + +On **BC 29 and later**, Business Central manages old-version cleanup in the background. Older published versions may remain after deployment until background cleanup runs. Cleanup has been observed after an overnight interval, leaving the installed version and the latest uninstalled version; this is not a guaranteed nightly schedule or retention policy. + +The optional `DeployTo.unpublishOldVersions` boolean (default `false`) does not control background cleanup. When enabled on **BC 29 and later**, AL-Go warns and skips explicit unpublish without failing deployment. No additional cleanup setting is needed. + +On **BC 25.4 through 28**, enabling the setting removes only selected apps' uninstalled versions older than their currently installed version after successful **Scope PTE** publishing. Cleanup errors remain warnings, and the setting does not apply to Scope Dev or custom deployments. + ## Custom Deployments AL-Go can also be setup for custom deployment when you want to deploy to non-SaaS environments. More about this in the advanced section. From 114cdcdfb8f19deb6b869525b3f11047f5720ab2 Mon Sep 17 00:00:00 2001 From: spetersenms Date: Thu, 29 Oct 2026 13:52:52 +0100 Subject: [PATCH 02/12] Setting new API cutoff to BC30 and extending documentation --- Actions/.Modules/settings.schema.json | 2 +- Actions/Deploy/Deploy.psm1 | 21 +++++++++--------- Actions/Deploy/README.md | 4 ++-- RELEASENOTES.md | 10 ++++++--- Scenarios/RegisterProductionEnvironment.md | 2 +- Scenarios/RegisterSandboxEnvironment.md | 2 +- Scenarios/settings.md | 2 +- Tests/PublishPTEApps.Test.ps1 | 25 ++++++++++++++++++---- Tests/UnpublishOldAppVersions.Test.ps1 | 10 +++++---- Workshop/ContinuousDeployment.md | 10 ++++----- 10 files changed, 56 insertions(+), 32 deletions(-) diff --git a/Actions/.Modules/settings.schema.json b/Actions/.Modules/settings.schema.json index 7aaf7ee6fd..7d3bfc4b39 100644 --- a/Actions/.Modules/settings.schema.json +++ b/Actions/.Modules/settings.schema.json @@ -815,7 +815,7 @@ "unpublishOldVersions": { "type": "boolean", "default": false, - "description": "Optional boolean, default false. After successful Scope PTE deployment, unpublishes only selected apps' uninstalled versions older than the currently installed version on Business Central 25.4 through 28. On BC 29 and later, Business Central manages cleanup in the background, which may be delayed; timing and retained versions are not guaranteed. This setting does not control background cleanup: AL-Go warns and skips explicit unpublish without failing deployment. Cleanup failures are warnings; does not apply to Scope Dev or custom deployments. See https://aka.ms/ALGoSettings#deployto" + "description": "Optional boolean, default false. After successful Scope PTE deployment, unpublishes only selected apps' uninstalled versions older than the currently installed version on Business Central 25.4 through 29. On BC 30 and later, Business Central manages cleanup in the background, which may be delayed; timing and retained versions are not guaranteed. This setting does not control background cleanup: AL-Go warns and skips explicit unpublish without failing deployment. Cleanup failures are warnings; does not apply to Scope Dev or custom deployments. See https://aka.ms/ALGoSettings#deployto" } } } diff --git a/Actions/Deploy/Deploy.psm1 b/Actions/Deploy/Deploy.psm1 index 0a73320101..18a47e5b85 100644 --- a/Actions/Deploy/Deploy.psm1 +++ b/Actions/Deploy/Deploy.psm1 @@ -354,7 +354,7 @@ function InvokePTEUpload { .PARAMETER maxStatusRequests Maximum number of status requests. Defaults to 360. .PARAMETER pollIntervalSeconds - Delay between status requests. Defaults to five seconds. + Delay between status requests. Defaults to 30 seconds, capped by the remaining timeout. #> function WaitPTEOperation { Param( @@ -366,8 +366,8 @@ function WaitPTEOperation { [int] $timeoutSeconds = 1800, [ValidateRange(1, 360)] [int] $maxStatusRequests = 360, - [ValidateRange(0, 5)] - [int] $pollIntervalSeconds = 5 + [ValidateRange(0, 30)] + [int] $pollIntervalSeconds = 30 ) $operation = $operation | ConvertTo-HashTable -recurse @@ -397,7 +397,8 @@ function WaitPTEOperation { if ($requests -ge $maxStatusRequests -or $timer.Elapsed.TotalSeconds -ge $timeoutSeconds) { break } - Start-Sleep -Seconds $pollIntervalSeconds + $sleepSeconds = [Math]::Min($pollIntervalSeconds, [Math]::Max(0, $timeoutSeconds - $timer.Elapsed.TotalSeconds)) + Start-Sleep -Milliseconds ([int][Math]::Ceiling($sleepSeconds * 1000)) if ($timer.Elapsed.TotalSeconds -ge $timeoutSeconds) { break } # Renew outside the retry catch so authentication errors always fail immediately. $bcAuthContext = Renew-BcAuthContext -bcAuthContext $bcAuthContext @@ -437,8 +438,8 @@ function WaitPTEOperation { .SYNOPSIS Publish primary apps or PTE dependencies using the target BC version. .DESCRIPTION - Below BC 29, delegates publishing to the released BcContainerHelper Automation implementation. - On BC 29 and later, AL-Go installs packages immediately using Admin Center API v2.29 with + Below BC 30, delegates publishing to the released BcContainerHelper Automation implementation. + On BC 30 and later, AL-Go installs packages immediately using Admin Center API v2.29 with no legacy fallback. Existing helper utilities expand packages, exclude runtime packages and order dependencies. Same or newer installed versions are skipped. .PARAMETER bcAuthContext @@ -464,7 +465,7 @@ function PublishPTEApps { $extensions = @(Get-BcInstalledExtensions -bcAuthContext $bcAuthContext -environment $environment) $applicationVersion = GetPTEApplicationVersion -extensions $extensions -environment $environment - if ($applicationVersion -lt [version]'29.0.0.0') { + if ($applicationVersion -lt [version]'30.0.0.0') { Write-Host "Target BC $applicationVersion - publishing PTEs using BcContainerHelper Automation API" Publish-PerTenantExtensionApps -bcAuthContext $bcAuthContext -environment $environment -appFiles $appFiles -SchemaSyncMode $schemaSyncMode return @@ -511,7 +512,7 @@ function PublishPTEApps { and clutter Extension Management. This function unpublishes those old versions using the automation API v2.0 Microsoft.NAV.unpublish action. Only versions that are not installed AND older than a currently installed version of the same app (matched by app id) are unpublished. This is only supported for PTE deployments on BC 25.4 - through 28. On BC 29 and later, Business Central manages old-version cleanup in the background. + through 29. On BC 30 and later, Business Central manages old-version cleanup in the background. Explicit unpublish is not supported, so AL-Go skips its cleanup with a warning. Background cleanup may be delayed; its timing and retained versions are not guaranteed. Read-only Automation API calls determine the installed Application version. @@ -557,8 +558,8 @@ function UnpublishOldAppVersions { $extensions = @((Invoke-RestMethod -Method Get -Uri "$companyUrl/extensions" -Headers $headers -UseBasicParsing).value) $applicationVersion = GetPTEApplicationVersion -extensions $extensions -environment $environment - if ($applicationVersion -ge [version]'29.0.0.0') { - OutputWarning -message "AL-Go cannot explicitly unpublish old PTE versions on Business Central 29 or later; environment $environment is running $applicationVersion. Business Central manages cleanup in the background, which may be delayed; cleanup timing and retained versions are not guaranteed. AL-Go cleanup was skipped; the deployment remains successful." + if ($applicationVersion -ge [version]'30.0.0.0') { + OutputWarning -message "AL-Go cannot explicitly unpublish old PTE versions on Business Central 30 or later; environment $environment is running $applicationVersion. Business Central manages cleanup in the background, which may be delayed; cleanup timing and retained versions are not guaranteed. AL-Go cleanup was skipped; the deployment remains successful." return } if ($applicationVersion -lt [version]'25.4.0.0') { diff --git a/Actions/Deploy/README.md b/Actions/Deploy/README.md index df782dc718..0a2ee2ad89 100644 --- a/Actions/Deploy/README.md +++ b/Actions/Deploy/README.md @@ -6,9 +6,9 @@ Deploy Apps to online environment PTE deployment installs apps in dependency order and skips app versions that are already installed or superseded by a newer installed version. Deployment waits for installation to complete; installation failures fail the deployment. -BC 29+ S2S deployments require `AdminCenter.ReadWrite.All` application permission, tenant admin consent, and registration in the administration center's Authorized Microsoft Entra apps. Existing AUTHCONTEXT structures stay unchanged, and environment API permissions remain necessary. See [deployment authorization](../../Workshop/ContinuousDeployment.md#pte-deployment-authorization) for full requirements. +BC 30+ S2S deployments require `AdminCenter.ReadWrite.All` application permission, tenant admin consent, and registration in the administration center's Authorized Microsoft Entra apps. Existing AUTHCONTEXT structures stay unchanged, and environment API permissions remain necessary. See [deployment authorization](../../Workshop/ContinuousDeployment.md#pte-deployment-authorization) for full requirements. -`unpublishOldVersions` is an optional boolean in `DeployTo` (default `false`). It runs only after successful Scope PTE publishing. On BC 25.4 through 28, only selected apps' uninstalled versions older than the currently installed version are unpublished. On BC 29+, Business Central manages cleanup in the background, which may be delayed; timing and retained versions are not guaranteed. The setting does not control that background cleanup: AL-Go warns and skips explicit unpublish without failing deployment. Scope Dev, custom deployments, and container behavior are unchanged. +`unpublishOldVersions` is an optional boolean in `DeployTo` (default `false`). It runs only after successful Scope PTE publishing. On BC 25.4 through 29, only selected apps' uninstalled versions older than the currently installed version are unpublished. On BC 30+, Business Central manages cleanup in the background, which may be delayed; timing and retained versions are not guaranteed. The setting does not control that background cleanup: AL-Go warns and skips explicit unpublish without failing deployment. Scope Dev, custom deployments, and container behavior are unchanged. ## INPUT diff --git a/RELEASENOTES.md b/RELEASENOTES.md index b4ae501cb6..0ec5e6dd2f 100644 --- a/RELEASENOTES.md +++ b/RELEASENOTES.md @@ -1,10 +1,14 @@ -### Additional authorization for PTE deployment to BC 29 and later +### Breaking changes + +**PTE deployment to BC 30 and later requires additional authorization.** Earlier, environment-level deployment permissions were sufficient. Existing deployments to BC 30 or later will now fail if the required administration center access has not been granted. + +For S2S, add the `AdminCenter.ReadWrite.All` application permission, grant tenant admin consent, and register the client ID under the Business Central administration center's **Authorized Microsoft Entra apps**. Delegated users need appropriate administration center access. Keep the existing environment permissions and AUTHCONTEXT credential structure. See [deployment authorization](Workshop/ContinuousDeployment.md#pte-deployment-authorization). Deployments to BC 29 and earlier, Scope Dev, custom deployments, and container behavior are unchanged. -**Action required for Scope PTE:** BC 29+ S2S deployments need the `AdminCenter.ReadWrite.All` application permission, tenant admin consent, and registration under the Business Central administration center's **Authorized Microsoft Entra apps**. Delegated users need appropriate administration center access. Keep the existing environment permissions and AUTHCONTEXT credential structure. These additional permissions are not required for earlier BC versions or Scope Dev. See [deployment authorization](Workshop/ContinuousDeployment.md#pte-deployment-authorization). Custom deployments and container behavior are unchanged. +**Old-version cleanup changes on BC 30 and later.** Business Central manages cleanup in the background rather than AL-Go explicitly unpublishing old versions. Cleanup may be delayed; its timing and retained versions are not guaranteed. `unpublishOldVersions` does not control background cleanup: if enabled, AL-Go warns and skips explicit unpublish without failing deployment. ### New `unpublishOldVersions` setting for deployment -The `DeployTo` setting now supports an opt-in `unpublishOldVersions` boolean (default `false`). After successful Scope PTE deployment on BC 25.4 through 28, it removes only selected apps' uninstalled versions older than the currently installed version. On BC 29 and later, Business Central manages cleanup in the background, which may be delayed; timing and retained versions are not guaranteed. The setting does not control background cleanup: AL-Go warns and skips explicit unpublish without failing deployment. Cleanup failures remain warnings. +The `DeployTo` setting now supports an opt-in `unpublishOldVersions` boolean (default `false`). After successful Scope PTE deployment on BC 25.4 through 29, it removes only selected apps' uninstalled versions older than the currently installed version. Cleanup failures remain warnings. For BC 30 and later, see the cleanup behavior under **Breaking changes** above. ### Expanded AL-Go telemetry dashboard diff --git a/Scenarios/RegisterProductionEnvironment.md b/Scenarios/RegisterProductionEnvironment.md index 01521d30ac..059e52823b 100644 --- a/Scenarios/RegisterProductionEnvironment.md +++ b/Scenarios/RegisterProductionEnvironment.md @@ -4,7 +4,7 @@ ## PTE publishing authorization -Before **Scope PTE** deployment to BC 29 or later using S2S, add the **AdminCenter.ReadWrite.All** application permission under **Dynamics 365 Business Central**, grant tenant admin consent, and register the client ID on the Business Central administration center's **Authorized Microsoft Entra apps** page. Existing app registrations may need this additional authorization. Keep the existing environment API permissions and the Microsoft Entra application registration and required permission sets inside the Business Central environment. These additional permissions are not required for deployment to earlier BC versions. +Before **Scope PTE** deployment to BC 30 or later using S2S, add the **AdminCenter.ReadWrite.All** application permission under **Dynamics 365 Business Central**, grant tenant admin consent, and register the client ID on the Business Central administration center's **Authorized Microsoft Entra apps** page. Existing app registrations may need this additional authorization. Keep the existing environment API permissions and the Microsoft Entra application registration and required permission sets inside the Business Central environment. These additional permissions are not required for deployment to earlier BC versions. The **AUTHCONTEXT** credential structure is unchanged, including `TenantID`, `ClientID`, and `ClientSecret` for S2S. See [deployment authorization](../Workshop/ContinuousDeployment.md#pte-deployment-authorization) and the official [Business Central administration center API authentication documentation](https://learn.microsoft.com/en-us/dynamics365/business-central/dev-itpro/administration/administration-center-api). diff --git a/Scenarios/RegisterSandboxEnvironment.md b/Scenarios/RegisterSandboxEnvironment.md index de608e30ae..0bcd0b797c 100644 --- a/Scenarios/RegisterSandboxEnvironment.md +++ b/Scenarios/RegisterSandboxEnvironment.md @@ -4,7 +4,7 @@ ## PTE publishing authorization -For **Scope PTE** S2S deployment to BC 29 or later, add the **AdminCenter.ReadWrite.All** application permission under **Dynamics 365 Business Central**, grant tenant admin consent, and register the application's client ID on the Business Central administration center's **Authorized Microsoft Entra apps** page. Existing app registrations may need this additional authorization. Retain the existing environment API permissions and Microsoft Entra application registration inside the environment, including the required permission sets. +For **Scope PTE** S2S deployment to BC 30 or later, add the **AdminCenter.ReadWrite.All** application permission under **Dynamics 365 Business Central**, grant tenant admin consent, and register the application's client ID on the Business Central administration center's **Authorized Microsoft Entra apps** page. Existing app registrations may need this additional authorization. Retain the existing environment API permissions and Microsoft Entra application registration inside the environment, including the required permission sets. The **AUTHCONTEXT** credential structure below is unchanged. See [deployment authorization](../Workshop/ContinuousDeployment.md#pte-deployment-authorization) and the official [Business Central administration center API authentication documentation](https://learn.microsoft.com/en-us/dynamics365/business-central/dev-itpro/administration/administration-center-api). These additional permissions are not required for deployment to earlier BC versions or **Scope Dev**. diff --git a/Scenarios/settings.md b/Scenarios/settings.md index 835a5859be..003daaa82a 100644 --- a/Scenarios/settings.md +++ b/Scenarios/settings.md @@ -75,7 +75,7 @@ The repository settings are only read from the repository settings file (.github | githubRunnerShell | Specifies which shell is used for build jobs in workflows including a build job. The default is to use the same as defined in **shell**. If the shell setting isn't defined, **powershell** is the default, which results in using _PowerShell 5.1_. Use **pwsh** for _PowerShell 7_. | | environments | Array of logical environment names. You can specify environments in GitHub environments or in the repo settings file. If you specify environments in the settings file, you can create your AUTHCONTEXT secret using **\\_AUTHCONTEXT**. You can specify additional information about environments in a setting called **DeployTo\** | | DeliverTo\ | Structure with additional properties for the deliveryTarget specified. Some properties are deliveryTarget specific. The structure can contain the following properties:
**Branches** = an array of branch patterns, which are allowed to deliver to this deliveryTarget. (Default main)
**CreateContainerIfNotExist** = *[Only for DeliverToStorage]* Create Blob Storage Container if it doesn't already exist. (Default false)
| -| DeployTo\ | Structure with additional properties for the environment specified. `` refers to the GitHub environment name. The structure can contain the following properties:
**EnvironmentType** = specifies the type of environment. The environment type can be used to invoke a custom deployment. (Default SaaS)
**EnvironmentName** = specifies the "real" name of the environment if it differs from the GitHub environment.
**Branches** = an array of branch patterns, which are allowed to deploy to this environment. These branches can also be defined under the environment in GitHub settings and both settings are honored. If neither setting is defined, the default is the **main** branch only.
**Projects** = In multi-project repositories, this property can be a comma separated list of project patterns to deploy to this environment. (Default \*)
**DependencyInstallMode** = Determines how dependencies are deployed if `GenerateDependencyArtifact` is true. Default value is `install` to install dependencies if not already installed. Other values are `ignore` for ignoring dependencies and `upgrade` or `forceUpgrade` for upgrading dependencies.
**includeTestAppsInSandboxEnvironment** = deploys test apps and their dependencies if the environment type is sandbox (Default is `false`)
**excludeAppIds** = array of app ids to exclude from deployment. (Default is `[]`)
**Scope** = Determines the mechanism for deployment to the environment (Dev or PTE). If not specified, AL-Go for GitHub will always use the Dev Scope for AppSource Apps, but also for PTEs when deploying to sandbox environments when impersonation (refreshtoken) is used for authentication. Scope PTE deployment to BC 29 or later requires additional [deployment authorization](../Workshop/ContinuousDeployment.md#pte-deployment-authorization).
**SyncMode** = ForceSync if deployment to this environment should happen with ForceSync, else Add. If deploying to the development endpoint you can also specify Development or Clean. (Default Add)
**unpublishOldVersions** = Optional boolean (`true` or `false`, default `false`), honored by the standard Deploy action in CI/CD and Publish To Environment for both templates after successful Scope PTE publishing. On BC 25.4 through 28, unpublishes only selected apps' uninstalled versions older than the currently installed version. On BC 29 and later, Business Central manages cleanup in the background, which may be delayed; timing and retained versions are not guaranteed. This setting does not control background cleanup: AL-Go warns and skips explicit unpublish without failing deployment. Cleanup failures are warnings; does not apply to Scope Dev or custom deployments.
**BuildMode** = specifies which buildMode to use for the deployment. Default is to use the Default buildMode
**ContinuousDeployment** = true if this environment should be used for continuous deployment, else false. (Default: AL-Go will continuously deploy to sandbox environments or environments, which doesn't end in (PROD) or (FAT)
**runs-on** = specifies which runner to use when deploying to this environment. (Default is settings.runs-on)
**shell** = specifies which shell to use when deploying to this environment, pwsh or powershell. (Default is settings.shell)
**companyId** = Company Id from Business Central (for PowerPlatform connection)
**ppEnvironmentUrl** = Url of the PowerPlatform environment to deploy to
| +| DeployTo\ | Structure with additional properties for the environment specified. `` refers to the GitHub environment name. The structure can contain the following properties:
**EnvironmentType** = specifies the type of environment. The environment type can be used to invoke a custom deployment. (Default SaaS)
**EnvironmentName** = specifies the "real" name of the environment if it differs from the GitHub environment.
**Branches** = an array of branch patterns, which are allowed to deploy to this environment. These branches can also be defined under the environment in GitHub settings and both settings are honored. If neither setting is defined, the default is the **main** branch only.
**Projects** = In multi-project repositories, this property can be a comma separated list of project patterns to deploy to this environment. (Default \*)
**DependencyInstallMode** = Determines how dependencies are deployed if `GenerateDependencyArtifact` is true. Default value is `install` to install dependencies if not already installed. Other values are `ignore` for ignoring dependencies and `upgrade` or `forceUpgrade` for upgrading dependencies.
**includeTestAppsInSandboxEnvironment** = deploys test apps and their dependencies if the environment type is sandbox (Default is `false`)
**excludeAppIds** = array of app ids to exclude from deployment. (Default is `[]`)
**Scope** = Determines the mechanism for deployment to the environment (Dev or PTE). If not specified, AL-Go for GitHub will always use the Dev Scope for AppSource Apps, but also for PTEs when deploying to sandbox environments when impersonation (refreshtoken) is used for authentication. Scope PTE deployment to BC 30 or later requires additional [deployment authorization](../Workshop/ContinuousDeployment.md#pte-deployment-authorization).
**SyncMode** = ForceSync if deployment to this environment should happen with ForceSync, else Add. If deploying to the development endpoint you can also specify Development or Clean. (Default Add)
**unpublishOldVersions** = Optional boolean (`true` or `false`, default `false`), honored by the standard Deploy action in CI/CD and Publish To Environment for both templates after successful Scope PTE publishing. On BC 25.4 through 29, unpublishes only selected apps' uninstalled versions older than the currently installed version. On BC 30 and later, Business Central manages cleanup in the background, which may be delayed; timing and retained versions are not guaranteed. This setting does not control background cleanup: AL-Go warns and skips explicit unpublish without failing deployment. Cleanup failures are warnings; does not apply to Scope Dev or custom deployments.
**BuildMode** = specifies which buildMode to use for the deployment. Default is to use the Default buildMode
**ContinuousDeployment** = true if this environment should be used for continuous deployment, else false. (Default: AL-Go will continuously deploy to sandbox environments or environments, which doesn't end in (PROD) or (FAT)
**runs-on** = specifies which runner to use when deploying to this environment. (Default is settings.runs-on)
**shell** = specifies which shell to use when deploying to this environment, pwsh or powershell. (Default is settings.shell)
**companyId** = Company Id from Business Central (for PowerPlatform connection)
**ppEnvironmentUrl** = Url of the PowerPlatform environment to deploy to
| | alDoc | Structure with properties for the aldoc reference document generation. The structure can contain the following properties:
**continuousDeployment** = Determines if reference documentation will be deployed continuously as part of CI/CD. You can run the **Deploy Reference Documentation** workflow to deploy manually or on a schedule. (Default false)
**deployToGitHubPages** = Determines whether or not the reference documentation site should be deployed to GitHub Pages for the repository. In order to deploy to GitHub Pages, GitHub Pages must be enabled and set to GitHub Actuibs. (Default true)
**maxReleases** = Maximum number of releases to include in the reference documentation. (Default 3)
**groupByProject** = Determines whether projects in multi-project repositories are used as folders in reference documentation
**includeProjects** = An array of projects to include in the reference documentation. (Default all)
**excludeProjects** = An array of projects to exclude in the reference documentation. (Default none)
**header** = Header for the documentation site. (Default: Documentation for...)
**footer** = Footer for the documentation site. (Default: Made with...)
**defaultIndexMD** = Markdown for the landing page of the documentation site. (Default: Reference documentation...)
**defaultReleaseMD** = Markdown for the landing page of the release sites. (Default: Release reference documentation...)
*Note that in header, footer, defaultIndexMD and defaultReleaseMD you can use the following placeholders: {REPOSITORY}, {VERSION}, {INDEXTEMPLATERELATIVEPATH}, {RELEASENOTES}* | | useProjectDependencies | Determines whether your projects are built using a multi-stage built workflow or single stage. After setting useProjectDependencies to true, you need to run Update AL-Go System Files and your workflows including a build job will change to have multiple build jobs, depending on each other. The number of build jobs will be determined by the dependency depth in your projects.
You can change dependencies between your projects, but if the dependency **depth** changes, AL-Go will warn you that updates for your AL-Go System Files are available and you will need to run the workflow. | | CICDPushBranches | CICDPushBranches can be specified as an array of branches, which triggers a CI/CD workflow on commit. You need to run the Update AL-Go System Files workflow for the change to take effect.
Default is [ "main", "release/\*", "feature/\*" ]

**Supported release branch naming formats:**
When using release branches, AL-Go supports various naming conventions for matching previous releases during upgrade testing. The following formats are recognized:
• `releases/26` - matches releases with major version 26
• `releases/26.x` - matches releases with major version 26
• `releases/26x` - matches releases with major version 26
• `releases/v26` - matches releases with major version 26
• `releases/v26.x` - matches releases with major version 26
• `releases/v26x` - matches releases with major version 26
• `releases/26.3` - matches releases with major.minor version 26.3
The same patterns work with the singular `release/` prefix. | diff --git a/Tests/PublishPTEApps.Test.ps1 b/Tests/PublishPTEApps.Test.ps1 index 6ec9fd8590..803af99d3b 100644 --- a/Tests/PublishPTEApps.Test.ps1 +++ b/Tests/PublishPTEApps.Test.ps1 @@ -17,7 +17,7 @@ InModuleScope Deploy { $script:bcContainerHelperConfig = @{ apiBaseUrl = 'https://api.example.test/' } $script:application = @{ id = 'application'; displayName = 'Application'; isInstalled = $true - versionMajor = 29; versionMinor = 0; versionBuild = 0; versionRevision = 0 + versionMajor = 30; versionMinor = 0; versionBuild = 0; versionRevision = 0 } $script:extensions = @($script:application) Mock Write-Host { } @@ -39,8 +39,14 @@ InModuleScope Deploy { Mock WaitPTEOperation { } } - It 'Uses only the released helper for BC 28 and preserves Force and immediate defaults' { - $script:application.versionMajor = 28 + It 'Uses only the released helper for BC and preserves Force and immediate defaults' -TestCases @( + @{ major = 28 }, @{ major = 29 } + ) { + param($major) + $script:application.versionMajor = $major + $script:application.versionMinor = 9 + $script:application.versionBuild = 99999 + $script:application.versionRevision = 99999 Mock Publish-PerTenantExtensionApps { $PesterBoundParameters.Keys | Should -Not -Contain 'schedule' $PesterBoundParameters.Keys | Should -Not -Contain 'applicationFamily' @@ -66,7 +72,7 @@ InModuleScope Deploy { } It 'Uses AL-Go Admin Center publishing for BC ' -TestCases @( - @{ major = 29 }, @{ major = 30 } + @{ major = 30 }, @{ major = 31 } ) { param($major) $script:application.versionMajor = $major @@ -308,6 +314,16 @@ InModuleScope Deploy { $Headers.Authorization -eq 'Bearer renewed-test-token' -and $TimeoutSec -le 30 } Assert-MockCalled Renew-BcAuthContext -Exactly 1 + Assert-MockCalled Start-Sleep -Exactly 1 -ParameterFilter { $Milliseconds -eq 30000 } + } + + It 'Uses the requested shorter polling interval without changing the operation endpoint' { + WaitPTEOperation -bcAuthContext @{} -appsUri 'https://api.example.test/apps' -operation $script:operation -appId 'app-1' -pollIntervalSeconds 5 + + Assert-MockCalled Start-Sleep -Exactly 1 -ParameterFilter { $Milliseconds -eq 5000 } + Assert-MockCalled Invoke-RestMethod -Exactly 1 -ParameterFilter { + $Method -eq 'Get' -and $Uri -eq 'https://api.example.test/apps/app-1/operations/operation%20%2F%201' + } } It 'Does not count scheduled immediate installation as success' { @@ -477,6 +493,7 @@ InModuleScope Deploy { { WaitPTEOperation -bcAuthContext @{} -appsUri 'https://api.example.test/apps' -operation $script:operation -appId 'app-1' -timeoutSeconds 1 } | Should -Throw '*Timed out*1 seconds*' Assert-MockCalled Invoke-RestMethod -Times 0 + Assert-MockCalled Start-Sleep -Exactly 1 -ParameterFilter { $Milliseconds -gt 0 -and $Milliseconds -le 1000 } } } } diff --git a/Tests/UnpublishOldAppVersions.Test.ps1 b/Tests/UnpublishOldAppVersions.Test.ps1 index bb2feeba30..553b7da0f1 100644 --- a/Tests/UnpublishOldAppVersions.Test.ps1 +++ b/Tests/UnpublishOldAppVersions.Test.ps1 @@ -64,9 +64,9 @@ InModuleScope Deploy { # Allows testing of private functions } It 'Explains delayed service-managed cleanup without any writes on BC .' -TestCases @( - @{ major = 29; minor = 0 }, - @{ major = 29; minor = 1 }, - @{ major = 30; minor = 0 } + @{ major = 30; minor = 0 }, + @{ major = 30; minor = 1 }, + @{ major = 31; minor = 0 } ) { param($major, $minor) $script:applicationExtension.versionMajor = $major @@ -82,7 +82,9 @@ InModuleScope Deploy { # Allows testing of private functions It 'Preserves legacy cleanup on BC .' -TestCases @( @{ major = 25; minor = 4 }, - @{ major = 28; minor = 9 } + @{ major = 28; minor = 9 }, + @{ major = 29; minor = 0 }, + @{ major = 29; minor = 9 } ) { param($major, $minor) $script:applicationExtension.versionMajor = $major diff --git a/Workshop/ContinuousDeployment.md b/Workshop/ContinuousDeployment.md index 98c7864811..7abc4414d1 100644 --- a/Workshop/ContinuousDeployment.md +++ b/Workshop/ContinuousDeployment.md @@ -90,19 +90,19 @@ Paste the value from the clipboard into the "Value" field of the **AuthContext** ## PTE deployment authorization -For **Scope PTE** S2S deployment to **BC 29 or later**, add the **AdminCenter.ReadWrite.All** application permission under **Dynamics 365 Business Central**, grant **tenant admin consent**, and add the client ID to **Authorized Microsoft Entra apps** in the Business Central administration center. Existing app registrations that previously deployed successfully may need this additional authorization. Keep the environment API permissions, such as **Automation.ReadWrite.All** and **API.ReadWrite.All** where required, and the Microsoft Entra application registration and permission sets inside each Business Central environment. +For **Scope PTE** S2S deployment to **BC 30 or later**, add the **AdminCenter.ReadWrite.All** application permission under **Dynamics 365 Business Central**, grant **tenant admin consent**, and add the client ID to **Authorized Microsoft Entra apps** in the Business Central administration center. Existing app registrations that previously deployed successfully may need this additional authorization. Keep the environment API permissions, such as **Automation.ReadWrite.All** and **API.ReadWrite.All** where required, and the Microsoft Entra application registration and permission sets inside each Business Central environment. -With delegated authentication (impersonation), **Scope PTE** deployment to **BC 29 or later** requires appropriate **Business Central administration center access** as well as the environment permissions. The existing **AUTHCONTEXT** credential structure and the commands above remain unchanged. See the official [Business Central administration center API documentation](https://learn.microsoft.com/en-us/dynamics365/business-central/dev-itpro/administration/administration-center-api) for authentication and authorization details. +With delegated authentication (impersonation), **Scope PTE** deployment to **BC 30 or later** requires appropriate **Business Central administration center access** as well as the environment permissions. The existing **AUTHCONTEXT** credential structure and the commands above remain unchanged. See the official [Business Central administration center API documentation](https://learn.microsoft.com/en-us/dynamics365/business-central/dev-itpro/administration/administration-center-api) for authentication and authorization details. These additional permissions are not required for deployment to earlier BC versions or the sandbox development endpoint (**Scope Dev**). ## Old published versions -On **BC 29 and later**, Business Central manages old-version cleanup in the background. Older published versions may remain after deployment until background cleanup runs. Cleanup has been observed after an overnight interval, leaving the installed version and the latest uninstalled version; this is not a guaranteed nightly schedule or retention policy. +On **BC 30 and later**, Business Central manages old-version cleanup in the background. Older published versions may remain after deployment until background cleanup runs. Cleanup has been observed after an overnight interval, leaving the installed version and the latest uninstalled version; this is not a guaranteed nightly schedule or retention policy. -The optional `DeployTo.unpublishOldVersions` boolean (default `false`) does not control background cleanup. When enabled on **BC 29 and later**, AL-Go warns and skips explicit unpublish without failing deployment. No additional cleanup setting is needed. +The optional `DeployTo.unpublishOldVersions` boolean (default `false`) does not control background cleanup. When enabled on **BC 30 and later**, AL-Go warns and skips explicit unpublish without failing deployment. No additional cleanup setting is needed. -On **BC 25.4 through 28**, enabling the setting removes only selected apps' uninstalled versions older than their currently installed version after successful **Scope PTE** publishing. Cleanup errors remain warnings, and the setting does not apply to Scope Dev or custom deployments. +On **BC 25.4 through 29**, enabling the setting removes only selected apps' uninstalled versions older than their currently installed version after successful **Scope PTE** publishing. Cleanup errors remain warnings, and the setting does not apply to Scope Dev or custom deployments. ## Custom Deployments From df59a57a563c672aa684204289fe964f672d5819 Mon Sep 17 00:00:00 2001 From: spetersenms Date: Mon, 2 Nov 2026 16:20:28 +0100 Subject: [PATCH 03/12] Fixing failing tests. --- Tests/RunTests.Test.ps1 | 37 +++++++++++++++++++++++++++++-------- 1 file changed, 29 insertions(+), 8 deletions(-) diff --git a/Tests/RunTests.Test.ps1 b/Tests/RunTests.Test.ps1 index 8a95c02cd7..834629b878 100644 --- a/Tests/RunTests.Test.ps1 +++ b/Tests/RunTests.Test.ps1 @@ -4,16 +4,31 @@ param() $errorActionPreference = "Stop"; $ProgressPreference = "SilentlyContinue"; Set-StrictMode -Version 2.0 -. (Join-Path -Path $PSScriptRoot -ChildPath "../Actions/AL-Go-Helper.ps1" -Resolve) - -# Stub for the BcContainerHelper function so it can be mocked within the module scope -function Get-AppJsonFromAppFile { param($appFile) } -function Get-BcContainerEventLog { param($containerName, [switch] $doNotOpen) } - -Import-Module (Join-Path $PSScriptRoot '../Actions/RunTests/RunTests.psm1' -Resolve) -DisableNameChecking -Force - Describe 'RunTests.psm1 Tests' { BeforeAll { + . (Join-Path -Path $PSScriptRoot -ChildPath "../Actions/AL-Go-Helper.ps1" -Resolve) + # Module-scoped mocks need globally visible targets without helper autoload. + $script:stubbedGlobalCommands = @() + $stubDefinitions = @{ + 'ConvertTo-HashTable' = ${function:ConvertTo-HashTable} + 'Get-AppJsonFromAppFile' = { + param($appFile) + throw 'Get-AppJsonFromAppFile must be mocked by the test.' + } + 'Get-BcContainerEventLog' = { + param($containerName, [switch] $doNotOpen) + throw 'Get-BcContainerEventLog must be mocked by the test.' + } + } + foreach ($commandName in $stubDefinitions.Keys) { + $functionPath = "Function:\global:$commandName" + if (-not (Test-Path -LiteralPath $functionPath)) { + Set-Item -LiteralPath $functionPath -Value $stubDefinitions[$commandName] + $script:stubbedGlobalCommands += $commandName + } + } + Import-Module (Join-Path $PSScriptRoot '../Actions/RunTests/RunTests.psm1' -Resolve) -DisableNameChecking -Force + [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', 'testCredential', Justification = 'Used in tests')] $testCredential = New-Object System.Management.Automation.PSCredential("admin", (ConvertTo-SecureString "password" -AsPlainText -Force)) $script:compiledAppMetadataByPath = @{} @@ -60,6 +75,12 @@ Describe 'RunTests.psm1 Tests' { } } + AfterAll { + foreach ($commandName in $script:stubbedGlobalCommands) { + Remove-Item "Function:\global:$commandName" -Force -ErrorAction SilentlyContinue + } + } + BeforeEach { $script:eventLogSource = Join-Path $TestDrive "$([Guid]::NewGuid()).evtx" Set-Content -Path $script:eventLogSource -Value 'post-test-events' -Encoding UTF8 From d157cfcb1ee96e75160e237e66663a5b6fcd2eae Mon Sep 17 00:00:00 2001 From: spetersenms Date: Mon, 2 Nov 2026 16:43:14 +0100 Subject: [PATCH 04/12] Fixing documentation --- Actions/Deploy/README.md | 4 +--- RELEASENOTES.md | 2 +- Scenarios/RegisterSandboxEnvironment.md | 2 +- Workshop/ContinuousDeployment.md | 2 +- 4 files changed, 4 insertions(+), 6 deletions(-) diff --git a/Actions/Deploy/README.md b/Actions/Deploy/README.md index 0a2ee2ad89..c59d93438c 100644 --- a/Actions/Deploy/README.md +++ b/Actions/Deploy/README.md @@ -6,9 +6,7 @@ Deploy Apps to online environment PTE deployment installs apps in dependency order and skips app versions that are already installed or superseded by a newer installed version. Deployment waits for installation to complete; installation failures fail the deployment. -BC 30+ S2S deployments require `AdminCenter.ReadWrite.All` application permission, tenant admin consent, and registration in the administration center's Authorized Microsoft Entra apps. Existing AUTHCONTEXT structures stay unchanged, and environment API permissions remain necessary. See [deployment authorization](../../Workshop/ContinuousDeployment.md#pte-deployment-authorization) for full requirements. - -`unpublishOldVersions` is an optional boolean in `DeployTo` (default `false`). It runs only after successful Scope PTE publishing. On BC 25.4 through 29, only selected apps' uninstalled versions older than the currently installed version are unpublished. On BC 30+, Business Central manages cleanup in the background, which may be delayed; timing and retained versions are not guaranteed. The setting does not control that background cleanup: AL-Go warns and skips explicit unpublish without failing deployment. Scope Dev, custom deployments, and container behavior are unchanged. +`unpublishOldVersions` is an optional boolean in `DeployTo` (default `false`). It runs only after successful Scope PTE publishing. On BC 25.4 through 29, only selected apps' uninstalled versions older than the currently installed version are unpublished. On BC 30+, Business Central manages cleanup in the background, which may be delayed; timing and retained versions are not guaranteed. ## INPUT diff --git a/RELEASENOTES.md b/RELEASENOTES.md index 2cd84df5ee..4b9f465980 100644 --- a/RELEASENOTES.md +++ b/RELEASENOTES.md @@ -2,7 +2,7 @@ **PTE deployment to BC 30 and later requires additional authorization.** Earlier, environment-level deployment permissions were sufficient. Existing deployments to BC 30 or later will now fail if the required administration center access has not been granted. -For S2S, add the `AdminCenter.ReadWrite.All` application permission, grant tenant admin consent, and register the client ID under the Business Central administration center's **Authorized Microsoft Entra apps**. Delegated users need appropriate administration center access. Keep the existing environment permissions and AUTHCONTEXT credential structure. See [deployment authorization](Workshop/ContinuousDeployment.md#pte-deployment-authorization). Deployments to BC 29 and earlier, Scope Dev, custom deployments, and container behavior are unchanged. +For S2S, add the `AdminCenter.ReadWrite.All` application permission, grant tenant admin consent, and register the client ID under the Business Central administration center's **Authorized Microsoft Entra apps**. Delegated users need appropriate administration center access. Keep the existing environment permissions and AUTHCONTEXT credential structure. See [deployment authorization](Workshop/ContinuousDeployment.md#pte-deployment-authorization). These requirements also apply when a Scope Dev deployment installs or upgrades a PTE dependency on BC 30 or later. Primary-app publishing through the development endpoint does not itself require the additional authorization. Deployments to BC 29 and earlier, custom deployments, and container behavior are unchanged. **Old-version cleanup changes on BC 30 and later.** Business Central manages cleanup in the background rather than AL-Go explicitly unpublishing old versions. Cleanup may be delayed; its timing and retained versions are not guaranteed. `unpublishOldVersions` does not control background cleanup: if enabled, AL-Go warns and skips explicit unpublish without failing deployment. diff --git a/Scenarios/RegisterSandboxEnvironment.md b/Scenarios/RegisterSandboxEnvironment.md index 0bcd0b797c..a47a39e3f1 100644 --- a/Scenarios/RegisterSandboxEnvironment.md +++ b/Scenarios/RegisterSandboxEnvironment.md @@ -6,7 +6,7 @@ For **Scope PTE** S2S deployment to BC 30 or later, add the **AdminCenter.ReadWrite.All** application permission under **Dynamics 365 Business Central**, grant tenant admin consent, and register the application's client ID on the Business Central administration center's **Authorized Microsoft Entra apps** page. Existing app registrations may need this additional authorization. Retain the existing environment API permissions and Microsoft Entra application registration inside the environment, including the required permission sets. -The **AUTHCONTEXT** credential structure below is unchanged. See [deployment authorization](../Workshop/ContinuousDeployment.md#pte-deployment-authorization) and the official [Business Central administration center API authentication documentation](https://learn.microsoft.com/en-us/dynamics365/business-central/dev-itpro/administration/administration-center-api). These additional permissions are not required for deployment to earlier BC versions or **Scope Dev**. +The **AUTHCONTEXT** credential structure below is unchanged. See [deployment authorization](../Workshop/ContinuousDeployment.md#pte-deployment-authorization) and the official [Business Central administration center API authentication documentation](https://learn.microsoft.com/en-us/dynamics365/business-central/dev-itpro/administration/administration-center-api). These authorization requirements also apply when a **Scope Dev** deployment installs or upgrades a PTE dependency on BC 30 or later. Publishing primary apps through the development endpoint does not itself require these additional permissions. Deployment to earlier BC versions does not require them. ## Register the environment diff --git a/Workshop/ContinuousDeployment.md b/Workshop/ContinuousDeployment.md index 7abc4414d1..46a09bef26 100644 --- a/Workshop/ContinuousDeployment.md +++ b/Workshop/ContinuousDeployment.md @@ -94,7 +94,7 @@ For **Scope PTE** S2S deployment to **BC 30 or later**, add the **AdminCenter.Re With delegated authentication (impersonation), **Scope PTE** deployment to **BC 30 or later** requires appropriate **Business Central administration center access** as well as the environment permissions. The existing **AUTHCONTEXT** credential structure and the commands above remain unchanged. See the official [Business Central administration center API documentation](https://learn.microsoft.com/en-us/dynamics365/business-central/dev-itpro/administration/administration-center-api) for authentication and authorization details. -These additional permissions are not required for deployment to earlier BC versions or the sandbox development endpoint (**Scope Dev**). +These authorization requirements also apply when a **Scope Dev** deployment installs or upgrades a PTE dependency on **BC 30 or later**. Publishing primary apps through the sandbox development endpoint does not itself require these additional permissions. Deployment to earlier BC versions does not require them. ## Old published versions From e87d3f7cc7bf50395019e581683527cc55a15f27 Mon Sep 17 00:00:00 2001 From: spetersenms Date: Mon, 9 Nov 2026 16:36:05 +0100 Subject: [PATCH 05/12] Cleanup and moving Admin Api logic to separate module. --- Actions/.Modules/AdminCenterApi.psm1 | 272 +++++++++++ Actions/.Modules/settings.schema.json | 2 +- Actions/Deploy/Deploy.ps1 | 6 +- Actions/Deploy/Deploy.psm1 | 217 +++++---- Actions/Deploy/README.md | 6 +- RELEASENOTES.md | 12 +- Scenarios/RegisterProductionEnvironment.md | 2 +- Scenarios/RegisterSandboxEnvironment.md | 4 +- Scenarios/settings.md | 4 +- Tests/AdminCenterApi.Test.ps1 | 268 +++++++++++ Tests/Deploy.Action.Test.ps1 | 23 + Tests/Deploy.Module.Test.ps1 | 63 ++- Tests/PublishPTEApps.Test.ps1 | 503 ++++++++++++++++----- Tests/UnpublishOldAppVersions.Test.ps1 | 50 +- Workshop/ContinuousDeployment.md | 14 +- 15 files changed, 1201 insertions(+), 245 deletions(-) create mode 100644 Actions/.Modules/AdminCenterApi.psm1 create mode 100644 Tests/AdminCenterApi.Test.ps1 diff --git a/Actions/.Modules/AdminCenterApi.psm1 b/Actions/.Modules/AdminCenterApi.psm1 new file mode 100644 index 0000000000..5cbf792184 --- /dev/null +++ b/Actions/.Modules/AdminCenterApi.psm1 @@ -0,0 +1,272 @@ +$errorActionPreference = "Stop"; $ProgressPreference = "SilentlyContinue"; Set-StrictMode -Version 2.0 + +# Pin the contract AL-Go implements; update this with its callers and contract tests. +$adminCenterApiVersion = 'v2.29' + +<# + .SYNOPSIS + Build an AL-Go-owned Business Central Admin Center environment URL. + .PARAMETER applicationFamily + Application family containing the environment. + .PARAMETER environment + Target environment name. +#> +function Get-AdminCenterApiUrl { + Param( + [string] $applicationFamily = 'BusinessCentral', + [Parameter(Mandatory = $true)] + [string] $environment + ) + + return "https://api.businesscentral.dynamics.com/admin/$adminCenterApiVersion/applications/$([Uri]::EscapeDataString($applicationFamily))/environments/$([Uri]::EscapeDataString($environment))" +} + +<# + .SYNOPSIS + Read exception and service error messages without dumping response objects. + .PARAMETER errorRecord + Error containing exception and optional service response details. +#> +function Get-AdminCenterApiErrorMessage { + Param( + [Parameter(Mandatory = $true)] + [System.Management.Automation.ErrorRecord] $errorRecord + ) + + $messages = @($errorRecord.Exception.Message) + if ($errorRecord.ErrorDetails) { $messages += $errorRecord.ErrorDetails.Message } + $message = (@(foreach ($text in $messages) { + if ($text.TrimStart().StartsWith('{') -or $text.TrimStart().StartsWith('[')) { + try { + $details = $text | ConvertFrom-Json | ConvertTo-HashTable -recurse + if ($details -is [hashtable]) { + if ($details['error'] -is [hashtable]) { $details = $details['error'] } + foreach ($field in @('code', 'message', 'error_description')) { + if ($details[$field] -is [string]) { $details[$field] } + } + if ($details['error'] -is [string]) { $details['error'] } + } + } + catch { + 'Structured service error details could not be read.' + } + } + else { + $text + } + }) -join ' ') + return ($message -replace '[\r\n]+', ' ') +} + +<# + .SYNOPSIS + Send one authenticated Admin Center request without retries. + .DESCRIPTION + Preserves HTTP errors and records whether sending was attempted in Exception.Data. + .PARAMETER bcAuthContext + Authentication context to renew. + .PARAMETER environment + Target environment. + .PARAMETER path + Unescaped endpoint segments relative to the environment. + .PARAMETER method + HTTP method. + .PARAMETER body + Serialized request bytes, passed unchanged on PowerShell 5 and 7. + .PARAMETER contentType + Request content type. + .PARAMETER timeoutSeconds + Maximum duration of this request. + .PARAMETER applicationFamily + Target application family. +#> +function Invoke-AdminCenterApi { + Param( + [hashtable] $bcAuthContext, + [string] $environment, + [string[]] $path, + [ValidateSet('Get', 'Post')] + [string] $method = 'Get', + [byte[]] $body, + [string] $contentType, + [ValidateRange(1, 300)] + [int] $timeoutSeconds = 30, + [string] $applicationFamily = 'BusinessCentral' + ) + + $requestStarted = $false + try { + $uri = Get-AdminCenterApiUrl -environment $environment -applicationFamily $applicationFamily + $uri += '/' + (($path | ForEach-Object { [Uri]::EscapeDataString($_) }) -join '/') + $authContext = Renew-BcAuthContext -bcAuthContext $bcAuthContext + if (!$authContext -or !$authContext['AccessToken']) { throw 'Authentication failed before Admin Center request.' } + Write-Host "::add-mask::$($authContext.AccessToken)" + $parameters = @{ + Uri = $uri + Method = $method + Headers = @{ Authorization = "Bearer $($authContext.AccessToken)" } + UseBasicParsing = $true + TimeoutSec = $timeoutSeconds + ErrorAction = 'Stop' + } + if ($PSBoundParameters.ContainsKey('body')) { $parameters.Body = $body } + if ($PSBoundParameters.ContainsKey('contentType')) { $parameters.ContentType = $contentType } + $requestStarted = $true + Invoke-RestMethod @parameters + } + catch { + $_.Exception.Data['AdminCenterRequestStarted'] = $requestStarted + throw + } +} + +<# + .SYNOPSIS + Upload an app package for immediate PTE installation. + .DESCRIPTION + Builds and disposes multipart content using binary serialization supported on PowerShell 5 and 7. + Makes one upload attempt and preserves request-phase metadata on failure. + .PARAMETER bcAuthContext + Authentication context. + .PARAMETER environment + Target environment. + .PARAMETER appFile + App package to upload. + .PARAMETER syncMode + Admin Center schema synchronization mode, Add or ForceSync. + .PARAMETER applicationFamily + Target application family. +#> +function Install-AdminCenterPTE { + Param( + [hashtable] $bcAuthContext, + [string] $environment, + [string] $appFile, + [ValidateSet('Add', 'ForceSync')] + [string] $syncMode = 'Add', + [string] $applicationFamily = 'BusinessCentral' + ) + + $requestCalled = $false + $multipart = $null + try { + Add-Type -AssemblyName System.Net.Http + $multipart = [System.Net.Http.MultipartFormDataContent]::new() + $fileContent = [System.Net.Http.ByteArrayContent]::new([System.IO.File]::ReadAllBytes($appFile)) + $multipart.Add($fileContent, 'extensionFile', [System.IO.Path]::GetFileName($appFile)) + $fileContent.Headers.ContentType = [System.Net.Http.Headers.MediaTypeHeaderValue]::new('application/octet-stream') + $fields = @{ + deploymentSchedule = 'Immediate' + syncMode = $syncMode + acceptIsvEula = 'true' + installOrUpdateNeededDependencies = 'false' + } + foreach ($field in $fields.Keys) { + $multipart.Add([System.Net.Http.StringContent]::new($fields[$field]), $field) + } + $bytes = $multipart.ReadAsByteArrayAsync().GetAwaiter().GetResult() + $requestCalled = $true + Invoke-AdminCenterApi -bcAuthContext $bcAuthContext -environment $environment -applicationFamily $applicationFamily ` + -path @('apps', 'pteInstall') -method Post -body $bytes -contentType $multipart.Headers.ContentType.ToString() -timeoutSeconds 300 + } + catch { + if (!$requestCalled) { $_.Exception.Data['AdminCenterRequestStarted'] = $false } + throw + } + finally { + if ($multipart) { $multipart.Dispose() } + } +} + +<# + .SYNOPSIS + Read the exact app operation without polling or retrying. + .PARAMETER bcAuthContext + Authentication context. + .PARAMETER environment + Target environment. + .PARAMETER appId + App identifier. + .PARAMETER operationId + Operation identifier returned by installation. + .PARAMETER timeoutSeconds + Maximum duration of this status request. + .PARAMETER applicationFamily + Target application family. +#> +function Get-AdminCenterAppOperation { + Param( + [hashtable] $bcAuthContext, + [string] $environment, + [string] $appId, + [string] $operationId, + [ValidateRange(1, 30)] + [int] $timeoutSeconds = 30, + [string] $applicationFamily = 'BusinessCentral' + ) + + Invoke-AdminCenterApi -bcAuthContext $bcAuthContext -environment $environment -applicationFamily $applicationFamily ` + -path @('apps', $appId, 'operations', $operationId) -timeoutSeconds $timeoutSeconds +} + +<# + .SYNOPSIS + Read installed extensions from Admin Center in the deployment extension format. + .DESCRIPTION + Uses the observed id/name/version/state response and accepts the documented appId identity. + Returns installed apps only, with full version components for existing deployment checks. + Installed, UpdatePending and Updating all describe installed apps. The documented appType + is retained as publishedAs so deployment can preserve its Dev-scope dependency safeguard. + Missing or malformed installed-app data fails explicitly. + .PARAMETER bcAuthContext + Authentication context. + .PARAMETER environment + Target environment. + .PARAMETER applicationFamily + Target application family. +#> +function Get-AdminCenterInstalledExtensions { + Param( + [hashtable] $bcAuthContext, + [string] $environment, + [string] $applicationFamily = 'BusinessCentral' + ) + + $response = Invoke-AdminCenterApi -bcAuthContext $bcAuthContext -environment $environment -applicationFamily $applicationFamily -path @('apps') + $response = $response | ConvertTo-HashTable -recurse + if ($response -isnot [hashtable] -or !$response.ContainsKey('value') -or $response['value'] -isnot [array]) { + throw 'Admin Center installed-app response must contain an apps array.' + } + foreach ($app in $response['value']) { + if ($app -isnot [hashtable] -or $app['state'] -isnot [string] -or !$app['state'].Trim()) { + throw 'Admin Center app is missing its installation state.' + } + if ($app['state'] -notin 'installed', 'updatePending', 'updating') { + throw 'Admin Center app has an unsupported installation state.' + } + $id = if ($app['appId']) { $app['appId'] } else { $app['id'] } + $version = $null + if ($id -isnot [string] -or !$id.Trim() -or + ($app['appId'] -and $app['id'] -and $app['appId'] -ne $app['id']) -or + $app['name'] -isnot [string] -or !$app['name'].Trim() -or + $app['version'] -isnot [string] -or + ![version]::TryParse($app['version'], [ref]$version) -or $version.Revision -lt 0 -or + $app['appType'] -notin 'global', 'tenant', 'dev') { + throw 'Admin Center installed app has missing or invalid identity, name, full version or app type.' + } + [PSCustomObject]@{ + id = $id + displayName = $app['name'] + version = $version.ToString() + versionMajor = $version.Major + versionMinor = $version.Minor + versionBuild = $version.Build + versionRevision = $version.Revision + isInstalled = $true + state = $app['state'] + publishedAs = $app['appType'] + } + } +} + +Export-ModuleMember -Function Get-AdminCenterApiUrl, Get-AdminCenterApiErrorMessage, Invoke-AdminCenterApi, Install-AdminCenterPTE, Get-AdminCenterAppOperation, Get-AdminCenterInstalledExtensions diff --git a/Actions/.Modules/settings.schema.json b/Actions/.Modules/settings.schema.json index 34cf091e5a..937585222b 100644 --- a/Actions/.Modules/settings.schema.json +++ b/Actions/.Modules/settings.schema.json @@ -985,7 +985,7 @@ "unpublishOldVersions": { "type": "boolean", "default": false, - "description": "Optional boolean, default false. After successful Scope PTE deployment, unpublishes only selected apps' uninstalled versions older than the currently installed version on Business Central 25.4 through 29. On BC 30 and later, Business Central manages cleanup in the background, which may be delayed; timing and retained versions are not guaranteed. This setting does not control background cleanup: AL-Go warns and skips explicit unpublish without failing deployment. Cleanup failures are warnings; does not apply to Scope Dev or custom deployments. See https://aka.ms/ALGoSettings#deployto" + "description": "Optional boolean, default false. After successful Scope PTE deployment through Automation on Business Central 25.4 or later, including fallback, unpublishes only selected apps' uninstalled versions older than the currently installed version. Apps published through Admin Center anywhere in the action are excluded from explicit cleanup; Business Central manages their background cleanup, whose timing and retained versions are not guaranteed. On BC 29 and later, skipped apps without a recorded Automation success are also excluded. Mixed-path deployments clean only eligible Automation apps. This setting does not control background cleanup. Skipped cleanup and cleanup failures are warnings; does not apply to Scope Dev or custom deployments. See https://aka.ms/ALGoSettings#deployto" } } } diff --git a/Actions/Deploy/Deploy.ps1 b/Actions/Deploy/Deploy.ps1 index 1c7ee2a0e6..682913568a 100644 --- a/Actions/Deploy/Deploy.ps1 +++ b/Actions/Deploy/Deploy.ps1 @@ -167,8 +167,9 @@ else { Write-Host "::Warning::Ignoring environment $($deploymentSettings.EnvironmentName), which is a production environment, as deploying from a PR is only supported in sandbox environments" } else { + $publishingResults = @{} if ($dependencies) { - InstallOrUpgradeApps -bcAuthContext $bcAuthContext -environment $deploymentSettings.EnvironmentName -Apps $dependencies -installMode $deploymentSettings.DependencyInstallMode + InstallOrUpgradeApps -bcAuthContext $bcAuthContext -environment $deploymentSettings.EnvironmentName -Apps $dependencies -installMode $deploymentSettings.DependencyInstallMode -publishingResults $publishingResults } if ($unknownDependencies) { InstallUnknownDependencies -bcAuthContext $bcAuthContext -environment $deploymentSettings.EnvironmentName -Apps $unknownDependencies -installMode $deploymentSettings.DependencyInstallMode @@ -198,6 +199,7 @@ else { "bcAuthContext" = $bcAuthContext "environment" = $deploymentSettings.EnvironmentName "appFiles" = $apps + "publishingResults" = $publishingResults } if ($deploymentSettings.SyncMode) { if (@('Add','ForceSync') -notcontains $deploymentSettings.SyncMode) { @@ -216,7 +218,7 @@ else { if (($deploymentSettings['unpublishOldVersions'] -is [bool]) -and $deploymentSettings['unpublishOldVersions']) { Write-Host "Checking cleanup of old app versions" - UnpublishOldAppVersions -bcAuthContext $bcAuthContext -environment $deploymentSettings.EnvironmentName -appFiles $apps + UnpublishOldAppVersions -bcAuthContext $bcAuthContext -environment $deploymentSettings.EnvironmentName -appFiles $apps -publishingResults $publishingResults } } } diff --git a/Actions/Deploy/Deploy.psm1 b/Actions/Deploy/Deploy.psm1 index b23057a128..bd85026c88 100644 --- a/Actions/Deploy/Deploy.psm1 +++ b/Actions/Deploy/Deploy.psm1 @@ -1,4 +1,5 @@ . (Join-Path -Path $PSScriptRoot -ChildPath "..\AL-Go-Helper.ps1" -Resolve) +Import-Module (Join-Path $PSScriptRoot '..\.Modules\AdminCenterApi.psm1') -Force -DisableNameChecking <# .SYNOPSIS @@ -223,7 +224,7 @@ function CheckInstalledApps { ) OutputDebugFunctionCall - $installedApps = Get-BcInstalledExtensions -bcAuthContext $bcAuthContext -environment $environment | Where-Object { $_.isInstalled } + $installedApps = GetInstalledExtensions -bcAuthContext $bcAuthContext -environment $environment foreach($appFile in $appFiles) { # Get AppJson (works for full .app files, symbol files and also runtime packages) $appJson = Get-AppJsonFromAppFile -appFile $appFile @@ -271,68 +272,33 @@ function GetPTEApplicationVersion { <# .SYNOPSIS - Upload a PTE for immediate installation through Admin Center API v2.29. - .DESCRIPTION - Sends multipart bytes on PowerShell 5 and 7 and disposes HTTP content and streams. - Upload errors are never retried because the service might already have accepted the package. + Prefer Admin Center installed apps, falling back to the read-only Automation API. .PARAMETER bcAuthContext - Authentication context to renew before uploading. - .PARAMETER uri - Admin Center pteInstall URL for the target environment. - .PARAMETER appFile - App package to upload. - .PARAMETER syncMode - Admin Center schema sync mode, Add or ForceSync. + Business Central authentication context. + .PARAMETER environment + Target environment. + .PARAMETER requireApplicationVersion + Validate the unique installed Application version before accepting the Admin snapshot. #> -function InvokePTEUpload { +function GetInstalledExtensions { Param( [hashtable] $bcAuthContext, - [string] $uri, - [string] $appFile, - [ValidateSet('Add', 'ForceSync')] - [string] $syncMode + [string] $environment, + [switch] $requireApplicationVersion ) - $authContext = Renew-BcAuthContext -bcAuthContext $bcAuthContext - if (!$authContext -or !$authContext['AccessToken']) { - throw "Authentication failed before PTE upload." - } - Write-Host "::add-mask::$($authContext.AccessToken)" - $headers = @{ Authorization = "Bearer $($authContext.AccessToken)" } - Add-Type -AssemblyName System.Net.Http - $multipart = $null - $fileStream = $null - $fileContent = $null try { - $multipart = [System.Net.Http.MultipartFormDataContent]::new() - $fileStream = [System.IO.File]::OpenRead($appFile) - $fileContent = [System.Net.Http.StreamContent]::new($fileStream) - $fileContent.Headers.ContentType = [System.Net.Http.Headers.MediaTypeHeaderValue]::new('application/octet-stream') - $multipart.Add($fileContent, 'extensionFile', [System.IO.Path]::GetFileName($appFile)) - $fields = @{ - deploymentSchedule = 'Immediate' - syncMode = $syncMode - acceptIsvEula = 'true' - installOrUpdateNeededDependencies = 'false' - } - foreach ($field in $fields.Keys) { - $multipart.Add([System.Net.Http.StringContent]::new($fields[$field]), $field) + $extensions = @(Get-AdminCenterInstalledExtensions -bcAuthContext $bcAuthContext -environment $environment) + if ($requireApplicationVersion) { + GetPTEApplicationVersion -extensions $extensions -environment $environment | Out-Null } - # Invoke-RestMethod supports a byte body on both Windows PowerShell and PowerShell Core. - $bytes = $multipart.ReadAsByteArrayAsync().GetAwaiter().GetResult() - Invoke-RestMethod -Method Post -Uri $uri -Headers $headers -Body $bytes ` - -ContentType $multipart.Headers.ContentType.ToString() -UseBasicParsing -TimeoutSec 300 -ErrorAction Stop + return $extensions } catch { - $details = $_.Exception.Message - if ($_.ErrorDetails) { $details += " $($_.ErrorDetails.Message)" } - throw "PTE upload failed for $([System.IO.Path]::GetFileName($appFile)): $details. The upload will not be replayed." - } - finally { - if ($multipart) { $multipart.Dispose() } - if ($fileContent) { $fileContent.Dispose() } - if ($fileStream) { $fileStream.Dispose() } + $details = Get-AdminCenterApiErrorMessage -errorRecord $_ + Write-Host "Admin Center installed-app read failed: $details. Using the read-only Automation API. For access errors, see https://github.com/microsoft/AL-Go/blob/main/Workshop/ContinuousDeployment.md#pte-deployment-authorization" } + return Get-BcInstalledExtensions -bcAuthContext $bcAuthContext -environment $environment | Where-Object { $_.isInstalled } } <# @@ -343,8 +309,8 @@ function InvokePTEUpload { is not success. Only transient status-read errors are retried, never the upload. .PARAMETER bcAuthContext Authentication context to renew for each status request. - .PARAMETER appsUri - Admin Center apps URL for the target environment. + .PARAMETER environment + Target environment. .PARAMETER operation Upload response containing the operation id, appId and status. .PARAMETER appId @@ -359,7 +325,7 @@ function InvokePTEUpload { function WaitPTEOperation { Param( [hashtable] $bcAuthContext, - [string] $appsUri, + [string] $environment, $operation, [string] $appId, [ValidateRange(1, 1800)] @@ -375,7 +341,6 @@ function WaitPTEOperation { throw "PTE upload returned missing or mismatched app/operation details for app $appId. The upload will not be replayed." } $operationId = [string]$operation['id'] - $operationUri = "$appsUri/$([Uri]::EscapeDataString($appId))/operations/$([Uri]::EscapeDataString($operationId))" $timer = [System.Diagnostics.Stopwatch]::StartNew() $transientErrors = 0 $requests = 0 @@ -391,7 +356,18 @@ function WaitPTEOperation { 'scheduled' {} 'running' {} default { - throw "PTE operation $operationId for app $appId did not succeed. Response: $($operation | ConvertTo-Json -Depth 20 -Compress)" + $serviceError = @($operation['errorMessage']) + if ($operation['error'] -is [hashtable]) { + $serviceError += $operation['error']['message'] + } + $serviceError = @($serviceError | Where-Object { $_ -is [string] }) -join ' ' + $record = [System.Management.Automation.ErrorRecord]::new( + [System.Exception]::new("PTE operation $operationId for app $appId did not succeed ($status). $serviceError"), + 'PTEOperationFailed', 'InvalidResult', $null) + $details = Get-AdminCenterApiErrorMessage -errorRecord $record + $exception = [System.Exception]::new($details) + $exception.Data['PTEFallbackAllowed'] = $status -in 'failed','canceled','skipped' + throw $exception } } if ($requests -ge $maxStatusRequests -or $timer.Elapsed.TotalSeconds -ge $timeoutSeconds) { @@ -400,18 +376,11 @@ function WaitPTEOperation { $sleepSeconds = [Math]::Min($pollIntervalSeconds, [Math]::Max(0, $timeoutSeconds - $timer.Elapsed.TotalSeconds)) Start-Sleep -Milliseconds ([int][Math]::Ceiling($sleepSeconds * 1000)) if ($timer.Elapsed.TotalSeconds -ge $timeoutSeconds) { break } - # Renew outside the retry catch so authentication errors always fail immediately. - $bcAuthContext = Renew-BcAuthContext -bcAuthContext $bcAuthContext - if (!$bcAuthContext -or !$bcAuthContext['AccessToken']) { - throw "Authentication failed while reading PTE operation $operationId for app $appId." - } - Write-Host "::add-mask::$($bcAuthContext.AccessToken)" - $headers = @{ Authorization = "Bearer $($bcAuthContext.AccessToken)" } $requests++ try { $requestTimeout = [int][Math]::Max(1, [Math]::Min(30, [Math]::Ceiling($timeoutSeconds - $timer.Elapsed.TotalSeconds))) - $operation = Invoke-RestMethod -Headers $headers -Method Get -Uri $operationUri ` - -UseBasicParsing -TimeoutSec $requestTimeout -ErrorAction Stop + $operation = Get-AdminCenterAppOperation -bcAuthContext $bcAuthContext -environment $environment ` + -appId $appId -operationId $operationId -timeoutSeconds $requestTimeout $operation = $operation | ConvertTo-HashTable -recurse $transientErrors = 0 } @@ -420,11 +389,10 @@ function WaitPTEOperation { if ($_.Exception.PSObject.Properties['Response'] -and $_.Exception.Response) { $statusCode = [int]$_.Exception.Response.StatusCode } - $transient = $statusCode -in 408,429,500,502,503,504 -or + $transient = $_.Exception.Data['AdminCenterRequestStarted'] -ne $false -and ($statusCode -in 408,429,500,502,503,504 -or (!$statusCode -and ($_.Exception -is [System.Net.WebException] -or - $_.Exception -is [System.Net.Http.HttpRequestException] -or $_.Exception -is [System.TimeoutException])) - $details = $_.Exception.Message - if ($_.ErrorDetails) { $details += " $($_.ErrorDetails.Message)" } + $_.Exception -is [System.Net.Http.HttpRequestException] -or $_.Exception -is [System.TimeoutException]))) + $details = Get-AdminCenterApiErrorMessage -errorRecord $_ if (!$transient -or ++$transientErrors -gt 5) { throw "Unable to read PTE operation $operationId for app ${appId}: $details" } @@ -438,10 +406,13 @@ function WaitPTEOperation { .SYNOPSIS Publish primary apps or PTE dependencies using the target BC version. .DESCRIPTION - Below BC 30, delegates publishing to the released BcContainerHelper Automation implementation. - On BC 30 and later, AL-Go installs packages immediately using Admin Center API v2.29 with - no legacy fallback. Existing helper utilities expand packages, exclude runtime packages and - order dependencies. Same or newer installed versions are skipped. + Below BC 29, delegates publishing to the released BcContainerHelper Automation implementation. + On BC 29 and later, AL-Go prefers Admin Center publishing and falls back to Automation after + a confirmed failure. Unknown or running outcomes stop deployment to avoid duplicate writes. + Completed apps are not replayed. Existing helper utilities expand packages, exclude runtime + packages and order dependencies. Same or newer installed versions are skipped. + Installed apps and the Application version are read from Admin Center first. A failed + read or invalid Application version falls back to the read-only Automation API. .PARAMETER bcAuthContext Business Central authentication context. .PARAMETER environment @@ -450,8 +421,9 @@ function WaitPTEOperation { App packages or archives to publish. .PARAMETER schemaSyncMode Existing helper-compatible sync mode: Add or Force (mapped to ForceSync for Admin Center). - .PARAMETER applicationFamily - Admin Center application family. Defaults to BusinessCentral; not a workflow setting. + .PARAMETER publishingResults + Action-scoped map of app IDs to publishing paths, used for optional cleanup. + Any Admin Center success protects that app from explicit cleanup for the rest of the action. #> function PublishPTEApps { Param( @@ -460,22 +432,23 @@ function PublishPTEApps { [string[]] $appFiles, [ValidateSet('Add', 'Force')] [string] $schemaSyncMode = 'Add', - [string] $applicationFamily = 'BusinessCentral' + [hashtable] $publishingResults = @{} ) - $extensions = @(Get-BcInstalledExtensions -bcAuthContext $bcAuthContext -environment $environment) + $extensions = @(GetInstalledExtensions -bcAuthContext $bcAuthContext -environment $environment -requireApplicationVersion) $applicationVersion = GetPTEApplicationVersion -extensions $extensions -environment $environment - if ($applicationVersion -lt [version]'30.0.0.0') { + if ($applicationVersion -lt [version]'29.0.0.0') { Write-Host "Target BC $applicationVersion - publishing PTEs using BcContainerHelper Automation API" Publish-PerTenantExtensionApps -bcAuthContext $bcAuthContext -environment $environment -appFiles $appFiles -SchemaSyncMode $schemaSyncMode return } - Write-Host "Target BC $applicationVersion - publishing PTEs using AL-Go Admin Center API v2.29" - $appsUri = "$($bcContainerHelperConfig.apiBaseUrl.TrimEnd('/'))/admin/v2.29/applications/$([Uri]::EscapeDataString($applicationFamily))/environments/$([Uri]::EscapeDataString($environment))/apps" + Write-Host "Target BC $applicationVersion - publishing PTEs using AL-Go Admin Center API" $tempPath = NewTemporaryFolder try { $copiedApps = @(Copy-AppFilesToFolder -appFiles $appFiles -folder $tempPath) $sortedApps = @(Sort-AppFilesByDependencies -appFiles $copiedApps -excludeRuntimePackages) + $useLegacy = $false + $completedExtensions = @() foreach ($appFile in $sortedApps) { $appJson = Get-AppJsonFromAppFile -appFile $appFile $appVersion = [version]$appJson.version @@ -483,12 +456,51 @@ function PublishPTEApps { ForEach-Object { [version]::new($_.versionMajor, $_.versionMinor, $_.versionBuild, $_.versionRevision) }) if (@($installedVersions | Where-Object { $_ -ge $appVersion }).Count -gt 0) { Write-Host "App $($appJson.name) v$appVersion or newer is already installed" + if (!$publishingResults.ContainsKey($appJson.id)) { $publishingResults[$appJson.id] = 'Skipped' } continue } - $syncMode = if ($schemaSyncMode -eq 'Force') { 'ForceSync' } else { 'Add' } - $operation = InvokePTEUpload -bcAuthContext $bcAuthContext -uri "$appsUri/pteInstall" -appFile $appFile -syncMode $syncMode - WaitPTEOperation -bcAuthContext $bcAuthContext -appsUri $appsUri -operation $operation -appId $appJson.id - $extensions += @{ + if (!$useLegacy) { + try { + $uploadReturned = $false + $syncMode = if ($schemaSyncMode -eq 'Force') { 'ForceSync' } else { 'Add' } + $operation = Install-AdminCenterPTE -bcAuthContext $bcAuthContext -environment $environment -appFile $appFile -syncMode $syncMode + $uploadReturned = $true + WaitPTEOperation -bcAuthContext $bcAuthContext -environment $environment -operation $operation -appId $appJson.id + } + catch { + $statusCode = 0 + if ($_.Exception.PSObject.Properties['Response'] -and $_.Exception.Response) { + $statusCode = [int]$_.Exception.Response.StatusCode + } + $fallbackAllowed = $_.Exception.Data['PTEFallbackAllowed'] -eq $true -or (!$uploadReturned -and ( + $_.Exception.Data['AdminCenterRequestStarted'] -eq $false -or + $statusCode -in 400,401,403,404,405,413,415,422,429)) + $details = Get-AdminCenterApiErrorMessage -errorRecord $_ + $guidance = "For access errors, update your administration center permissions: https://github.com/microsoft/AL-Go/blob/main/Workshop/ContinuousDeployment.md#pte-deployment-authorization" + if (!$fallbackAllowed) { + OutputWarning -message "Admin Center publishing failed for $($appJson.name): $details. $guidance. The installation outcome is unknown or may still be running; stopping without legacy fallback to avoid duplicate installation." + throw [System.Exception]::new("Admin Center publishing stopped without legacy fallback: $details") + } + OutputWarning -message "Admin Center publishing failed for $($appJson.name): $details. $guidance. Falling back to the Automation API for remaining apps." + $useLegacy = $true + # A terminal operation may have changed installed state before failing. + $extensions = @(Get-BcInstalledExtensions -bcAuthContext $bcAuthContext -environment $environment) + $completedExtensions + } + } + if ($useLegacy) { + $installedVersions = @($extensions | Where-Object { $_.id -eq $appJson.id -and $_.isInstalled } | + ForEach-Object { [version]::new($_.versionMajor, $_.versionMinor, $_.versionBuild, $_.versionRevision) }) + if (@($installedVersions | Where-Object { $_ -ge $appVersion }).Count -gt 0) { + Write-Host "App $($appJson.name) v$appVersion or newer is already installed" + if (!$publishingResults.ContainsKey($appJson.id)) { $publishingResults[$appJson.id] = 'Skipped' } + continue + } + Publish-PerTenantExtensionApps -bcAuthContext $bcAuthContext -environment $environment -appFiles @($appFile) -SchemaSyncMode $schemaSyncMode + } + if ($publishingResults[$appJson.id] -ne 'AdminCenter') { + $publishingResults[$appJson.id] = if ($useLegacy) { 'Automation' } else { 'AdminCenter' } + } + $completedExtension = @{ id = $appJson.id displayName = $appJson.name isInstalled = $true @@ -497,6 +509,8 @@ function PublishPTEApps { versionBuild = $appVersion.Build versionRevision = $appVersion.Revision } + $completedExtensions += $completedExtension + $extensions += $completedExtension } } finally { @@ -511,9 +525,10 @@ function PublishPTEApps { After a new version of a Per Tenant Extension is installed, previous versions remain published (but uninstalled) and clutter Extension Management. This function unpublishes those old versions using the automation API v2.0 Microsoft.NAV.unpublish action. Only versions that are not installed AND older than a currently installed version - of the same app (matched by app id) are unpublished. This is only supported for PTE deployments on BC 25.4 - through 29. On BC 30 and later, Business Central manages old-version cleanup in the background. - Explicit unpublish is not supported, so AL-Go skips its cleanup with a warning. Background cleanup may + of the same app (matched by app id) are unpublished. Automation cleanup requires BC 25.4 or later, + including after fallback. On BC 29 and later, only apps successfully published through Automation + and not through Admin Center during this action are eligible. AL-Go skips other apps with a warning. + For Admin Center publishing, Business Central manages cleanup in the background. Background cleanup may be delayed; its timing and retained versions are not guaranteed. Read-only Automation API calls determine the installed Application version. The function is non-fatal: any failure is reported as a warning and never fails the deployment. @@ -525,12 +540,15 @@ function PublishPTEApps { The list of deployed app files. Only the app id is read from these files to identify which apps to clean up; for each such app, published versions are compared against the version currently installed in the environment (not the deployed artifact version), and uninstalled versions older than the installed version are unpublished. + .PARAMETER publishingResults + Caller-owned per-app publishing paths. On BC 29 and later only Automation results allow explicit cleanup. #> function UnpublishOldAppVersions { Param( [hashtable] $bcAuthContext, [string] $environment, - [string[]] $appFiles + [string[]] $appFiles, + [hashtable] $publishingResults = @{} ) OutputDebugFunctionCall @@ -558,9 +576,13 @@ function UnpublishOldAppVersions { $extensions = @((Invoke-RestMethod -Method Get -Uri "$companyUrl/extensions" -Headers $headers -UseBasicParsing).value) $applicationVersion = GetPTEApplicationVersion -extensions $extensions -environment $environment - if ($applicationVersion -ge [version]'30.0.0.0') { - OutputWarning -message "AL-Go cannot explicitly unpublish old PTE versions on Business Central 30 or later; environment $environment is running $applicationVersion. Business Central manages cleanup in the background, which may be delayed; cleanup timing and retained versions are not guaranteed. AL-Go cleanup was skipped; the deployment remains successful." - return + if ($applicationVersion -ge [version]'29.0.0.0') { + $automationApps = @($deployedApps | Where-Object { $publishingResults[$_.Id] -eq 'Automation' }) + if ($automationApps.Count -ne $deployedApps.Count) { + OutputWarning -message "AL-Go skips explicit cleanup for apps without an exclusively Automation publishing outcome in this deployment to $environment. For Admin Center publishing, Business Central manages cleanup in the background, which may be delayed; cleanup timing and retained versions are not guaranteed. The deployment remains successful." + } + $deployedApps = $automationApps + if ($deployedApps.Count -eq 0) { return } } if ($applicationVersion -lt [version]'25.4.0.0') { OutputWarning -message "Unpublishing old app versions requires Business Central 25.4 or later; environment $environment is running $applicationVersion." @@ -615,13 +637,16 @@ function UnpublishOldAppVersions { The list of app files to install or upgrade. .PARAMETER installMode The mode of installation, can be 'ignore', 'upgrade', 'forceUpgrade'. + .PARAMETER publishingResults + Action-scoped per-app publishing paths shared with primary-app publishing and optional cleanup. #> function InstallOrUpgradeApps { Param( [hashtable] $bcAuthContext, [string] $environment, [string[]] $apps, - [string] $installMode + [string] $installMode, + [hashtable] $publishingResults = @{} ) OutputDebugFunctionCall @@ -635,7 +660,7 @@ function InstallOrUpgradeApps { try { Copy-AppFilesToFolder -appFiles $apps -folder $tempPath | Out-Null $apps = @(Get-ChildItem -Path $tempPath -Filter *.app | ForEach-Object { $_.FullName }) - $installedApps = Get-BcInstalledExtensions -bcAuthContext $bcAuthContext -environment $environment | Where-Object { $_.isInstalled } + $installedApps = GetInstalledExtensions -bcAuthContext $bcAuthContext -environment $environment $PTEsToInstall = @() # Run through all apps and install or upgrade AppSource apps first (and collect PTEs) foreach($app in $apps) { @@ -657,13 +682,13 @@ function InstallOrUpgradeApps { else { Install-BcAppFromAppSource -bcAuthContext $bcAuthContext -environment $environment -appId $appJson.id -acceptIsvEula -installOrUpdateNeededDependencies -allowInstallationOnProduction # Update installed apps list as dependencies may have changed / been installed - $installedApps = Get-BcInstalledExtensions -bcAuthContext $bcAuthContext -environment $environment | Where-Object { $_.isInstalled } + $installedApps = GetInstalledExtensions -bcAuthContext $bcAuthContext -environment $environment } } } if ($PTEsToInstall) { # Install or upgrade PTEs - PublishPTEApps -bcAuthContext $bcAuthContext -environment $environment -appFiles $PTEsToInstall -SchemaSyncMode $schemaSyncMode + PublishPTEApps -bcAuthContext $bcAuthContext -environment $environment -appFiles $PTEsToInstall -SchemaSyncMode $schemaSyncMode -publishingResults $publishingResults } } finally { diff --git a/Actions/Deploy/README.md b/Actions/Deploy/README.md index c59d93438c..46413ba66c 100644 --- a/Actions/Deploy/README.md +++ b/Actions/Deploy/README.md @@ -4,9 +4,11 @@ Deploy Apps to online environment ## PTE publishing -PTE deployment installs apps in dependency order and skips app versions that are already installed or superseded by a newer installed version. Deployment waits for installation to complete; installation failures fail the deployment. +Deploys PTEs in dependency order, skipping app versions already installed or superseded. -`unpublishOldVersions` is an optional boolean in `DeployTo` (default `false`). It runs only after successful Scope PTE publishing. On BC 25.4 through 29, only selected apps' uninstalled versions older than the currently installed version are unpublished. On BC 30+, Business Central manages cleanup in the background, which may be delayed; timing and retained versions are not guaranteed. +On BC 29+, PTE deployment prefers the administration center. Configure the [required authorization](../../Workshop/ContinuousDeployment.md#pte-deployment-authorization) to use it; confirmed failures can fall back to the existing deployment method. Primary-app Dev publishing is unchanged. + +Optional `DeployTo.unpublishOldVersions` (default `false`) cleans older, uninstalled versions after Automation deployment on BC 25.4+. Administration center deployments use Business Central's background cleanup. See [cleanup details](../../Workshop/ContinuousDeployment.md#old-published-versions). ## INPUT diff --git a/RELEASENOTES.md b/RELEASENOTES.md index 4b9f465980..2bd791d89a 100644 --- a/RELEASENOTES.md +++ b/RELEASENOTES.md @@ -1,10 +1,10 @@ -### Breaking changes +### Authorization for PTE deployment on BC 29 and later -**PTE deployment to BC 30 and later requires additional authorization.** Earlier, environment-level deployment permissions were sufficient. Existing deployments to BC 30 or later will now fail if the required administration center access has not been granted. +**Update your deployment authorization:** For S2S, add the `AdminCenter.ReadWrite.All` application permission, grant tenant admin consent, and register the client ID under **Authorized Microsoft Entra apps** in the Business Central administration center. See [deployment setup](Workshop/ContinuousDeployment.md#pte-deployment-authorization). -For S2S, add the `AdminCenter.ReadWrite.All` application permission, grant tenant admin consent, and register the client ID under the Business Central administration center's **Authorized Microsoft Entra apps**. Delegated users need appropriate administration center access. Keep the existing environment permissions and AUTHCONTEXT credential structure. See [deployment authorization](Workshop/ContinuousDeployment.md#pte-deployment-authorization). These requirements also apply when a Scope Dev deployment installs or upgrades a PTE dependency on BC 30 or later. Primary-app publishing through the development endpoint does not itself require the additional authorization. Deployments to BC 29 and earlier, custom deployments, and container behavior are unchanged. +On BC 29 and later, AL-Go tries the Admin Center API first and falls back to the existing Automation API with a warning after a confirmed failure. -**Old-version cleanup changes on BC 30 and later.** Business Central manages cleanup in the background rather than AL-Go explicitly unpublishing old versions. Cleanup may be delayed; its timing and retained versions are not guaranteed. `unpublishOldVersions` does not control background cleanup: if enabled, AL-Go warns and skips explicit unpublish without failing deployment. +The Automation API's PTE upload endpoint (`extensionUpload`) is deprecated and planned for removal in 2027 release wave 1; this does not mean all Automation APIs are deprecated. See the [official deprecation notice](https://learn.microsoft.com/en-us/dynamics365/business-central/dev-itpro/administration/resources/dynamics_extensionupload). ### Separate test execution from RunPipeline (PREVIEW) @@ -17,7 +17,7 @@ The action uses AlTool by default, running each app's enabled normal tests in on ### New `unpublishOldVersions` setting for deployment -The `DeployTo` setting now supports an opt-in `unpublishOldVersions` boolean (default `false`). After successful Scope PTE deployment on BC 25.4 through 29, it removes only selected apps' uninstalled versions older than the currently installed version. Cleanup failures remain warnings. For BC 30 and later, see the cleanup behavior under **Breaking changes** above. +The optional `DeployTo.unpublishOldVersions` setting (default `false`) removes older, uninstalled versions after successful Scope PTE deployment through Automation on BC 25.4+, including fallback. Administration center deployments use Business Central's background cleanup instead. See [old published versions](Workshop/ContinuousDeployment.md#old-published-versions) for details. ### Settings sources in workflow logs @@ -64,7 +64,7 @@ AL-Go now supports including pre-release versions of Business Central app packag ### New `unpublishOldVersions` setting for deployment -The `DeployTo` setting now supports an opt-in `unpublishOldVersions` boolean (default `false`). After successful Scope PTE deployment on BC 25.4 through 29, it removes only selected apps' uninstalled versions older than the currently installed version. Cleanup failures remain warnings. For BC 30 and later, see the cleanup behavior under **Breaking changes** above. +The optional `DeployTo.unpublishOldVersions` setting (default `false`) removes older, uninstalled versions after successful Scope PTE deployment through Automation on BC 25.4+, including fallback. Administration center deployments use Business Central's background cleanup instead. See [old published versions](Workshop/ContinuousDeployment.md#old-published-versions) for details. ### Expanded AL-Go telemetry dashboard diff --git a/Scenarios/RegisterProductionEnvironment.md b/Scenarios/RegisterProductionEnvironment.md index 059e52823b..b18d7a1714 100644 --- a/Scenarios/RegisterProductionEnvironment.md +++ b/Scenarios/RegisterProductionEnvironment.md @@ -4,7 +4,7 @@ ## PTE publishing authorization -Before **Scope PTE** deployment to BC 30 or later using S2S, add the **AdminCenter.ReadWrite.All** application permission under **Dynamics 365 Business Central**, grant tenant admin consent, and register the client ID on the Business Central administration center's **Authorized Microsoft Entra apps** page. Existing app registrations may need this additional authorization. Keep the existing environment API permissions and the Microsoft Entra application registration and required permission sets inside the Business Central environment. These additional permissions are not required for deployment to earlier BC versions. +For the preferred PTE publishing path on BC 29 or later using S2S, add the **AdminCenter.ReadWrite.All** application permission under **Dynamics 365 Business Central**, grant tenant admin consent, and register the client ID on the Business Central administration center's **Authorized Microsoft Entra apps** page. Keep the existing environment API permissions and the Microsoft Entra application registration and required permission sets inside the Business Central environment. After a confirmed failure, AL-Go warns with the error and falls back using the existing environment deployment permissions. Update the authorization to use the preferred path. Unknown or still-running outcomes stop deployment to avoid duplicate installation. Deployment to earlier BC versions is unchanged. The **AUTHCONTEXT** credential structure is unchanged, including `TenantID`, `ClientID`, and `ClientSecret` for S2S. See [deployment authorization](../Workshop/ContinuousDeployment.md#pte-deployment-authorization) and the official [Business Central administration center API authentication documentation](https://learn.microsoft.com/en-us/dynamics365/business-central/dev-itpro/administration/administration-center-api). diff --git a/Scenarios/RegisterSandboxEnvironment.md b/Scenarios/RegisterSandboxEnvironment.md index a47a39e3f1..6c7b172b78 100644 --- a/Scenarios/RegisterSandboxEnvironment.md +++ b/Scenarios/RegisterSandboxEnvironment.md @@ -4,9 +4,9 @@ ## PTE publishing authorization -For **Scope PTE** S2S deployment to BC 30 or later, add the **AdminCenter.ReadWrite.All** application permission under **Dynamics 365 Business Central**, grant tenant admin consent, and register the application's client ID on the Business Central administration center's **Authorized Microsoft Entra apps** page. Existing app registrations may need this additional authorization. Retain the existing environment API permissions and Microsoft Entra application registration inside the environment, including the required permission sets. +For the preferred PTE publishing path on BC 29 or later using S2S, add the **AdminCenter.ReadWrite.All** application permission under **Dynamics 365 Business Central**, grant tenant admin consent, and register the application's client ID on the Business Central administration center's **Authorized Microsoft Entra apps** page. Retain the existing environment API permissions and Microsoft Entra application registration inside the environment, including the required permission sets. -The **AUTHCONTEXT** credential structure below is unchanged. See [deployment authorization](../Workshop/ContinuousDeployment.md#pte-deployment-authorization) and the official [Business Central administration center API authentication documentation](https://learn.microsoft.com/en-us/dynamics365/business-central/dev-itpro/administration/administration-center-api). These authorization requirements also apply when a **Scope Dev** deployment installs or upgrades a PTE dependency on BC 30 or later. Publishing primary apps through the development endpoint does not itself require these additional permissions. Deployment to earlier BC versions does not require them. +The **AUTHCONTEXT** credential structure below is unchanged. After a confirmed failure, AL-Go warns with the error and falls back using the existing environment deployment permissions. Update the authorization above to use the preferred path. Unknown or still-running outcomes stop deployment to avoid duplicate installation. See [deployment authorization and fallback](../Workshop/ContinuousDeployment.md#pte-deployment-authorization) and the official [Business Central administration center API authentication documentation](https://learn.microsoft.com/en-us/dynamics365/business-central/dev-itpro/administration/administration-center-api). This also applies when a **Scope Dev** deployment installs or upgrades a PTE dependency on BC 29 or later. Primary-app Dev publishing and deployment to earlier BC versions do not need the additional authorization. ## Register the environment diff --git a/Scenarios/settings.md b/Scenarios/settings.md index f59e13c4ef..398a4a89a8 100644 --- a/Scenarios/settings.md +++ b/Scenarios/settings.md @@ -75,7 +75,7 @@ The repository settings are only read from the repository settings file (.github | githubRunnerShell | Specifies which shell is used for build jobs in workflows including a build job. The default is to use the same as defined in **shell**. If the shell setting isn't defined, **powershell** is the default, which results in using _PowerShell 5.1_. Use **pwsh** for _PowerShell 7_. | | environments | Array of logical environment names. You can specify environments in GitHub environments or in the repo settings file. If you specify environments in the settings file, you can create your AUTHCONTEXT secret using **\\_AUTHCONTEXT**. You can specify additional information about environments in a setting called **DeployTo\** | | DeliverTo\ | Structure with additional properties for the deliveryTarget specified. Some properties are deliveryTarget specific. The structure can contain the following properties:
**Branches** = an array of branch patterns, which are allowed to deliver to this deliveryTarget. (Default main)
**CreateContainerIfNotExist** = *[Only for DeliverToStorage]* Create Blob Storage Container if it doesn't already exist. (Default false)
| -| DeployTo\ | Structure with additional properties for the environment specified. `` refers to the GitHub environment name. The structure can contain the following properties:
**EnvironmentType** = specifies the type of environment. The environment type can be used to invoke a custom deployment. (Default SaaS)
**EnvironmentName** = specifies the "real" name of the environment if it differs from the GitHub environment.
**Branches** = an array of branch patterns, which are allowed to deploy to this environment. These branches can also be defined under the environment in GitHub settings and both settings are honored. If neither setting is defined, the default is the **main** branch only.
**Projects** = In multi-project repositories, this property can be a comma separated list of project patterns to deploy to this environment. (Default \*)
**DependencyInstallMode** = Determines how dependencies are deployed if `GenerateDependencyArtifact` is true. Default value is `install` to install dependencies if not already installed. Other values are `ignore` for ignoring dependencies and `upgrade` or `forceUpgrade` for upgrading dependencies.
**includeTestAppsInSandboxEnvironment** = deploys test apps and their dependencies if the environment type is sandbox (Default is `false`)
**excludeAppIds** = array of app ids to exclude from deployment. (Default is `[]`)
**Scope** = Determines the mechanism for deployment to the environment (Dev or PTE). If not specified, AL-Go for GitHub will always use the Dev Scope for AppSource Apps, but also for PTEs when deploying to sandbox environments when impersonation (refreshtoken) is used for authentication. Scope PTE deployment to BC 30 or later requires additional [deployment authorization](../Workshop/ContinuousDeployment.md#pte-deployment-authorization).
**SyncMode** = ForceSync if deployment to this environment should happen with ForceSync, else Add. If deploying to the development endpoint you can also specify Development or Clean. (Default Add)
**unpublishOldVersions** = Optional boolean (`true` or `false`, default `false`), honored by the standard Deploy action in CI/CD and Publish To Environment for both templates after successful Scope PTE publishing. On BC 25.4 through 29, unpublishes only selected apps' uninstalled versions older than the currently installed version. On BC 30 and later, Business Central manages cleanup in the background, which may be delayed; timing and retained versions are not guaranteed. This setting does not control background cleanup: AL-Go warns and skips explicit unpublish without failing deployment. Cleanup failures are warnings; does not apply to Scope Dev or custom deployments.
**BuildMode** = specifies which buildMode to use for the deployment. Default is to use the Default buildMode
**ContinuousDeployment** = true if this environment should be used for continuous deployment, else false. (Default: AL-Go will continuously deploy to sandbox environments or environments, which doesn't end in (PROD) or (FAT)
**runs-on** = specifies which runner to use when deploying to this environment. (Default is settings.runs-on)
**shell** = specifies which shell to use when deploying to this environment, pwsh or powershell. (Default is settings.shell)
**companyId** = Company Id from Business Central (for PowerPlatform connection)
**ppEnvironmentUrl** = Url of the PowerPlatform environment to deploy to
| +| DeployTo\ | Structure with additional properties for the environment specified. `` refers to the GitHub environment name. The structure can contain the following properties:
**EnvironmentType** = specifies the type of environment. The environment type can be used to invoke a custom deployment. (Default SaaS)
**EnvironmentName** = specifies the "real" name of the environment if it differs from the GitHub environment.
**Branches** = an array of branch patterns, which are allowed to deploy to this environment. These branches can also be defined under the environment in GitHub settings and both settings are honored. If neither setting is defined, the default is the **main** branch only.
**Projects** = In multi-project repositories, this property can be a comma separated list of project patterns to deploy to this environment. (Default \*)
**DependencyInstallMode** = Determines how dependencies are deployed if `GenerateDependencyArtifact` is true. Default value is `install` to install dependencies if not already installed. Other values are `ignore` for ignoring dependencies and `upgrade` or `forceUpgrade` for upgrading dependencies.
**includeTestAppsInSandboxEnvironment** = deploys test apps and their dependencies if the environment type is sandbox (Default is `false`)
**excludeAppIds** = array of app ids to exclude from deployment. (Default is `[]`)
**Scope** = Determines the mechanism for deployment to the environment (Dev or PTE). If not specified, AL-Go for GitHub will always use the Dev Scope for AppSource Apps, but also for PTEs when deploying to sandbox environments when impersonation (refreshtoken) is used for authentication. On BC 29 or later, PTE publishing prefers the administration center and falls back after confirmed failures; unknown or running outcomes stop deployment. See [deployment authorization and fallback](../Workshop/ContinuousDeployment.md#pte-deployment-authorization), including PTE dependencies of Scope Dev deployments.
**SyncMode** = ForceSync if deployment to this environment should happen with ForceSync, else Add. If deploying to the development endpoint you can also specify Development or Clean. (Default Add)
**unpublishOldVersions** = Optional boolean (`true` or `false`, default `false`), honored by the standard Deploy action in CI/CD and Publish To Environment for both templates after successful Scope PTE publishing. For Automation publishing on BC 25.4 or later, including fallback, unpublishes only selected apps' uninstalled versions older than the currently installed version. Apps published through the administration center anywhere in the action are excluded from explicit cleanup; Business Central manages their background cleanup, whose timing and retained versions are not guaranteed. On BC 29+, skipped apps without a recorded Automation success are also excluded. Mixed-path deployments clean only eligible Automation apps. This setting does not control background cleanup. Skipped cleanup and cleanup failures are warnings; does not apply to Scope Dev or custom deployments.
**BuildMode** = specifies which buildMode to use for the deployment. Default is to use the Default buildMode
**ContinuousDeployment** = true if this environment should be used for continuous deployment, else false. (Default: AL-Go will continuously deploy to sandbox environments or environments, which doesn't end in (PROD) or (FAT)
**runs-on** = specifies which runner to use when deploying to this environment. (Default is settings.runs-on)
**shell** = specifies which shell to use when deploying to this environment, pwsh or powershell. (Default is settings.shell)
**companyId** = Company Id from Business Central (for PowerPlatform connection)
**ppEnvironmentUrl** = Url of the PowerPlatform environment to deploy to
| | alDoc | Structure with properties for the aldoc reference document generation. The structure can contain the following properties:
**continuousDeployment** = Determines if reference documentation will be deployed continuously as part of CI/CD. You can run the **Deploy Reference Documentation** workflow to deploy manually or on a schedule. (Default false)
**deployToGitHubPages** = Determines whether or not the reference documentation site should be deployed to GitHub Pages for the repository. In order to deploy to GitHub Pages, GitHub Pages must be enabled and set to GitHub Actuibs. (Default true)
**maxReleases** = Maximum number of releases to include in the reference documentation. (Default 3)
**groupByProject** = Determines whether projects in multi-project repositories are used as folders in reference documentation
**includeProjects** = An array of projects to include in the reference documentation. (Default all)
**excludeProjects** = An array of projects to exclude in the reference documentation. (Default none)
**header** = Header for the documentation site. (Default: Documentation for...)
**footer** = Footer for the documentation site. (Default: Made with...)
**defaultIndexMD** = Markdown for the landing page of the documentation site. (Default: Reference documentation...)
**defaultReleaseMD** = Markdown for the landing page of the release sites. (Default: Release reference documentation...)
*Note that in header, footer, defaultIndexMD and defaultReleaseMD you can use the following placeholders: {REPOSITORY}, {VERSION}, {INDEXTEMPLATERELATIVEPATH}, {RELEASENOTES}* | | useProjectDependencies | Determines whether your projects are built using a multi-stage built workflow or single stage. After setting useProjectDependencies to true, you need to run Update AL-Go System Files and your workflows including a build job will change to have multiple build jobs, depending on each other. The number of build jobs will be determined by the dependency depth in your projects.
You can change dependencies between your projects, but if the dependency **depth** changes, AL-Go will warn you that updates for your AL-Go System Files are available and you will need to run the workflow. | | CICDPushBranches | CICDPushBranches can be specified as an array of branches, which triggers a CI/CD workflow on commit. You need to run the Update AL-Go System Files workflow for the change to take effect.
Default is [ "main", "release/\*", "feature/\*" ]

**Supported release branch naming formats:**
When using release branches, AL-Go supports various naming conventions for matching previous releases during upgrade testing. The following formats are recognized:
• `releases/26` - matches releases with major version 26
• `releases/26.x` - matches releases with major version 26
• `releases/26x` - matches releases with major version 26
• `releases/v26` - matches releases with major version 26
• `releases/v26.x` - matches releases with major version 26
• `releases/v26x` - matches releases with major version 26
• `releases/26.3` - matches releases with major.minor version 26.3
The same patterns work with the singular `release/` prefix. | @@ -572,7 +572,7 @@ Note that changes to AL-Go for GitHub or Run-AlPipeline functionality in the fut | Setting | Description | Default | | :-- | :-- | :-- | | baseUrl | The Base Url for the online Business Central Web Client. This should be changed when targetting embed apps. | [https://businesscentral.dynamics.com](https://businesscentral.dynamics.com) | -| apiBaseUrl | The Base Url for the online Business Central API endpoint. This should be changed when targetting embed apps. | [https://api.businesscentral.dynamics.com](https://api.businesscentral.dynamics.com) | +| apiBaseUrl | The Base Url for the online Business Central API endpoint used by BcContainerHelper. This should be changed when targetting embed apps. This override applies to helper calls, including fallback publishing, but does not change AL-Go's preferred PTE publishing endpoint on BC 29 and later, which uses the standard Business Central service endpoint. | [https://api.businesscentral.dynamics.com](https://api.businesscentral.dynamics.com) | | PartnerTelemetryConnectionString | The Telemetry Connection String for partner telemetry for DevOps telemetry. | | | SendExtendedTelemetryToMicrosoft | Set this value to true if you agree to emit extended DevOps telemetry to Microsoft. | false | | ObjectIdForInternalUse | BcContainerHelper will use this Object ID for internal purposes. Change if the default Object ID is in use. | 88123 | diff --git a/Tests/AdminCenterApi.Test.ps1 b/Tests/AdminCenterApi.Test.ps1 new file mode 100644 index 0000000000..c5603996ec --- /dev/null +++ b/Tests/AdminCenterApi.Test.ps1 @@ -0,0 +1,268 @@ +Import-Module (Join-Path $PSScriptRoot '..\Actions\.Modules\AdminCenterApi.psm1') -DisableNameChecking + +Describe 'AL-Go Admin Center API helpers' { + BeforeAll { + . (Join-Path $PSScriptRoot '..\Actions\AL-Go-Helper.ps1') + DownloadAndImportBcContainerHelper -baseFolder ([IO.Path]::GetTempPath()) + Import-Module (Join-Path $PSScriptRoot '..\Actions\.Modules\AdminCenterApi.psm1') -DisableNameChecking + } + + InModuleScope AdminCenterApi { + Describe 'Admin Center requests and named endpoints' { + BeforeEach { + $script:packagePath = Join-Path $TestDrive 'Binary Package.app' + $script:packageBytes = [byte[]]@(0,128,255,13,10) + [IO.File]::WriteAllBytes($script:packagePath, $script:packageBytes) + Mock Write-Host { } + Mock Renew-BcAuthContext { return @{ AccessToken = 'test-token' } } + Mock Invoke-RestMethod { return @{ id = 'operation-1' } } + } + + It 'Sends binary multipart once to the escaped endpoint with ' -TestCases @( + @{ syncMode = 'Add' }, @{ syncMode = 'ForceSync' } + ) { + param($syncMode) + $script:expectedSyncMode = $syncMode + Mock Invoke-RestMethod { + param($Body, $ContentType) + ,$Body | Should -BeOfType ([byte[]]) + $ContentType | Should -BeLike 'multipart/form-data; boundary=*' + $wire = [Text.Encoding]::GetEncoding(28591).GetString($Body) + $wire | Should -Match 'name="?extensionFile"?; filename="Binary Package.app"' + $wire | Should -Match 'Content-Type: application/octet-stream' + $wire | Should -Match 'name="?deploymentSchedule"?\r\n\r\nImmediate\r\n' + $wire | Should -Match ('name="?syncMode"?\r\n\r\n' + $script:expectedSyncMode + '\r\n') + $wire | Should -Match 'name="?acceptIsvEula"?\r\n\r\ntrue\r\n' + $wire | Should -Match 'name="?installOrUpdateNeededDependencies"?\r\n\r\nfalse\r\n' + $wire.Contains([Text.Encoding]::GetEncoding(28591).GetString($script:packageBytes)) | Should -BeTrue + return @{ id = 'operation-1' } + } + + $result = Install-AdminCenterPTE -bcAuthContext @{ tenantId = 'tenant' } -environment 'QA / East' ` + -applicationFamily 'Family / US' -appFile $script:packagePath -syncMode $syncMode + + $result.id | Should -Be 'operation-1' + Assert-MockCalled Renew-BcAuthContext -Exactly 1 -ParameterFilter { $bcAuthContext.tenantId -eq 'tenant' } + Assert-MockCalled Invoke-RestMethod -Exactly 1 -ParameterFilter { + $Uri -eq 'https://api.businesscentral.dynamics.com/admin/v2.29/applications/Family%20%2F%20US/environments/QA%20%2F%20East/apps/pteInstall' -and + $Method -eq 'Post' -and $Body -is [byte[]] -and + $ContentType -like 'multipart/form-data; boundary=*' -and $TimeoutSec -eq 300 -and + $Headers.Authorization -eq 'Bearer test-token' -and $UseBasicParsing -and $ErrorAction -eq 'Stop' + } + $stream = [IO.File]::Open($script:packagePath, 'Open', 'ReadWrite', 'None') + $stream.Dispose() + } + + It 'Reads the exact escaped app operation without body or content type' { + Mock Invoke-RestMethod { + $PesterBoundParameters.Keys | Should -Not -Contain 'Body' + $PesterBoundParameters.Keys | Should -Not -Contain 'ContentType' + return @{ id = 'operation / 1' } + } + + Get-AdminCenterAppOperation -bcAuthContext @{} -environment Sandbox -appId 'app / 1' -operationId 'operation / 1' -timeoutSeconds 7 + + Assert-MockCalled Invoke-RestMethod -Exactly 1 -ParameterFilter { + $Method -eq 'Get' -and $TimeoutSec -eq 7 -and + $Uri -eq 'https://api.businesscentral.dynamics.com/admin/v2.29/applications/BusinessCentral/environments/Sandbox/apps/app%20%2F%201/operations/operation%20%2F%201' + } + } + + It 'Normalizes and installed apps including scope' -TestCases @( + @{ identityField = 'id'; state = 'installed'; appType = 'global' }, + @{ identityField = 'appId'; state = 'Installed'; appType = 'tenant' }, + @{ identityField = 'id'; state = 'UpdatePending'; appType = 'dev' }, + @{ identityField = 'appId'; state = 'Updating'; appType = 'global' } + ) { + param($identityField, $state, $appType) + $script:appResponse = @{ name = 'Application'; version = '30.0.57777.0'; state = $state; appType = $appType } + $script:appResponse[$identityField] = 'c1335042-3002-4257-bf8a-75c898ccb1b8' + Mock Invoke-RestMethod { return [PSCustomObject]@{ value = @([PSCustomObject]$script:appResponse) } } + + $apps = @(Get-AdminCenterInstalledExtensions -bcAuthContext @{ tenantId = 'tenant' } -environment 'QA / East' -applicationFamily 'Family / US') + + $apps.Count | Should -Be 1 + $apps[0].id | Should -Be 'c1335042-3002-4257-bf8a-75c898ccb1b8' + $apps[0].displayName | Should -Be Application + $apps[0].version | Should -Be '30.0.57777.0' + $apps[0].versionMajor | Should -Be 30 + $apps[0].versionMinor | Should -Be 0 + $apps[0].versionBuild | Should -Be 57777 + $apps[0].versionRevision | Should -Be 0 + $apps[0].isInstalled | Should -BeTrue + $apps[0].state | Should -Be $state + $apps[0].publishedAs | Should -Be $appType + Assert-MockCalled Invoke-RestMethod -Exactly 1 -ParameterFilter { + $Method -eq 'Get' -and $TimeoutSec -eq 30 -and + $Uri -eq 'https://api.businesscentral.dynamics.com/admin/v2.29/applications/Family%20%2F%20US/environments/QA%20%2F%20East/apps' + } + } + + It 'Accepts an empty apps array without inventing installed apps' { + Mock Invoke-RestMethod { return @{ value = @() } } + @(Get-AdminCenterInstalledExtensions -bcAuthContext @{} -environment Sandbox).Count | Should -Be 0 + } + + It 'Rejects malformed installed-app data: ' -TestCases @( + @{ problem = 'missing array' }, @{ problem = 'missing identity' }, @{ problem = 'conflicting identity' }, + @{ problem = 'missing name' }, @{ problem = 'missing state' }, @{ problem = 'unknown state' }, + @{ problem = 'uninstalled' }, @{ problem = 'incomplete version' }, @{ problem = 'invalid version' }, + @{ problem = 'unknown scope' } + ) { + param($problem) + $script:appResponse = @{ id = 'app'; name = 'Application'; version = '30.0.57777.0'; state = 'installed'; appType = 'global' } + switch ($problem) { + 'missing identity' { $script:appResponse.Remove('id') } + 'conflicting identity' { $script:appResponse.appId = 'different-app' } + 'missing name' { $script:appResponse.Remove('name') } + 'missing state' { $script:appResponse.Remove('state') } + 'unknown state' { $script:appResponse.state = 'unknown' } + 'uninstalled' { $script:appResponse.state = 'uninstalled' } + 'incomplete version' { $script:appResponse.version = '30.0' } + 'invalid version' { $script:appResponse.version = 'unknown' } + 'unknown scope' { $script:appResponse.appType = 'unknown' } + } + Mock Invoke-RestMethod { return @{ value = @($script:appResponse) } } + if ($problem -eq 'missing array') { Mock Invoke-RestMethod { return @{} } } + + { Get-AdminCenterInstalledExtensions -bcAuthContext @{} -environment Sandbox } | Should -Throw '*Admin Center*' + Assert-MockCalled Invoke-RestMethod -Exactly 1 + } + + It 'Marks authentication renewal failures as not sent without trying HTTP' { + Mock Renew-BcAuthContext { throw [System.TimeoutException]::new('Renewal failed') } + + try { + Install-AdminCenterPTE -bcAuthContext @{} -environment Sandbox -appFile $script:packagePath + throw 'Expected failure' + } + catch { + $_.Exception | Should -BeOfType ([System.TimeoutException]) + $_.Exception.Message | Should -Be 'Renewal failed' + $_.Exception.Data['AdminCenterRequestStarted'] | Should -BeFalse + } + Assert-MockCalled Invoke-RestMethod -Times 0 + } + + It 'Rejects authentication without a token before sending' { + Mock Renew-BcAuthContext { return @{} } + + try { + Get-AdminCenterAppOperation -bcAuthContext @{} -environment Sandbox -appId app -operationId operation + throw 'Expected failure' + } + catch { + $_.Exception.Message | Should -BeLike '*Authentication failed*' + $_.Exception.Data['AdminCenterRequestStarted'] | Should -BeFalse + } + Assert-MockCalled Invoke-RestMethod -Times 0 + } + + It 'Preserves original HTTP error details and never retries a failed POST or GET' -TestCases @( + @{ method = 'Post' }, @{ method = 'Get' } + ) { + param($method) + Mock Invoke-RestMethod { + $exception = [System.Net.WebException]::new('403 Forbidden') + $exception | Add-Member NoteProperty Response ([PSCustomObject]@{ StatusCode = 403 }) -Force + $record = [System.Management.Automation.ErrorRecord]::new($exception, 'ServiceDenied', 'PermissionDenied', $null) + $record.ErrorDetails = [System.Management.Automation.ErrorDetails]::new('{"error":{"message":"User not authorized"}}') + throw $record + } + + try { + Invoke-AdminCenterApi -bcAuthContext @{} -environment Sandbox -path @('apps','pteInstall') -method $method + throw 'Expected failure' + } + catch { + $_.Exception | Should -BeOfType ([System.Net.WebException]) + $_.Exception.Response.StatusCode | Should -Be 403 + $_.Exception.Data['AdminCenterRequestStarted'] | Should -BeTrue + $_.ErrorDetails.Message | Should -Match 'User not authorized' + } + Assert-MockCalled Invoke-RestMethod -Exactly 1 + } + + It 'Does not retry an ambiguous upload timeout' { + Mock Invoke-RestMethod { throw [System.TimeoutException]::new('Response lost') } + + try { + Install-AdminCenterPTE -bcAuthContext @{} -environment Sandbox -appFile $script:packagePath + throw 'Expected failure' + } + catch { + $_.Exception | Should -BeOfType ([System.TimeoutException]) + $_.Exception.Data['AdminCenterRequestStarted'] | Should -BeTrue + } + Assert-MockCalled Invoke-RestMethod -Exactly 1 + $stream = [IO.File]::Open($script:packagePath, 'Open', 'ReadWrite', 'None') + $stream.Dispose() + } + + It 'Preserves local package failure as not sent and never calls the request wrapper' { + Mock Invoke-AdminCenterApi { throw 'Request must not be called' } + + try { + Install-AdminCenterPTE -bcAuthContext @{} -environment Sandbox -appFile (Join-Path $TestDrive 'Missing.app') + throw 'Expected failure' + } + catch { + $_.Exception.Data['AdminCenterRequestStarted'] | Should -BeFalse + $_.Exception.Message | Should -Match 'Missing.app' + } + Assert-MockCalled Invoke-AdminCenterApi -Times 0 + Assert-MockCalled Invoke-RestMethod -Times 0 + } + } + } + + It 'Pins the tested contract and encodes each environment and family segment' { + Get-AdminCenterApiUrl -environment 'QA / East' -applicationFamily 'Family / US' | + Should -Be 'https://api.businesscentral.dynamics.com/admin/v2.29/applications/Family%20%2F%20US/environments/QA%20%2F%20East' + } + + It 'Defaults to the standard BusinessCentral application family' { + Get-AdminCenterApiUrl -environment Sandbox | + Should -Be 'https://api.businesscentral.dynamics.com/admin/v2.29/applications/BusinessCentral/environments/Sandbox' + } + + It 'Preserves exception and plain service messages on one log line' { + $exception = [System.Exception]::new('403 Forbidden') + $record = [System.Management.Automation.ErrorRecord]::new($exception, 'Denied', 'PermissionDenied', $null) + $record.ErrorDetails = [System.Management.Automation.ErrorDetails]::new("Permission AdminCenter.ReadWrite.All missing.`nUser not authorized.") + + $message = Get-AdminCenterApiErrorMessage -errorRecord $record + + $message | Should -Match '403 Forbidden' + $message | Should -Match 'Permission AdminCenter.ReadWrite.All missing' + $message | Should -Match 'User not authorized' + $message | Should -Not -Match '[\r\n]' + } + + It 'Reads only service error fields rather than arbitrary structured response properties' { + $record = [System.Management.Automation.ErrorRecord]::new( + [System.Exception]::new('403 Forbidden'), + 'Denied', 'PermissionDenied', $null) + $record.ErrorDetails = [System.Management.Automation.ErrorDetails]::new('{"error":{"code":"AuthorizationFailed","message":"access denied"},"credentials":{"value":"private-arbitrary-value"},"headers":{"Authorization":"private-base64"}}') + + $message = Get-AdminCenterApiErrorMessage -errorRecord $record + + $message | Should -Match '403 Forbidden AuthorizationFailed access denied' + $message | Should -Not -Match 'private-arbitrary-value|private-base64|credentials|headers' + } + + It 'Does not accept or inspect an authentication context' { + (Get-Command Get-AdminCenterApiErrorMessage).Parameters.Keys | Should -Not -Contain 'bcAuthContext' + } + + It 'Preserves OAuth error fields without rendering other response properties' { + $record = [System.Management.Automation.ErrorRecord]::new( + [System.Exception]::new('{"error":"invalid_client","error_description":"Client not authorized","request":{"headers":{"Authorization":"private-header"}}}'), + 'Denied', 'PermissionDenied', $null) + + $message = Get-AdminCenterApiErrorMessage -errorRecord $record + + $message | Should -Match 'Client not authorized invalid_client' + $message | Should -Not -Match 'private-header|request|headers' + } +} diff --git a/Tests/Deploy.Action.Test.ps1 b/Tests/Deploy.Action.Test.ps1 index 62a990042d..c9a0c1b252 100644 --- a/Tests/Deploy.Action.Test.ps1 +++ b/Tests/Deploy.Action.Test.ps1 @@ -76,6 +76,29 @@ Describe "Deploy Action Tests" { $script:unpublishAfterPublish | Should -BeTrue } + It 'Shares action-scoped publishing paths across dependencies, primary apps and cleanup' { + Mock GetAppsAndDependenciesFromArtifacts { return @('/tmp/app1.app'), @('/tmp/dependency.app') } + Mock InstallOrUpgradeApps { + $publishingResults.Count | Should -Be 0 + $publishingResults['dependency'] = 'AdminCenter' + } + Mock PublishPTEApps { + $publishingResults['dependency'] | Should -Be 'AdminCenter' + $publishingResults['primary'] = 'Automation' + } + Mock UnpublishOldAppVersions { + $publishingResults['dependency'] | Should -Be 'AdminCenter' + $publishingResults['primary'] | Should -Be 'Automation' + $appFiles | Should -Not -Contain '/tmp/dependency.app' + } + + InvokeDeploy -deploymentSettings @{ "EnvironmentType" = "SaaS"; "EnvironmentName" = "test"; "Branches" = @(); "Projects" = "*"; "DependencyInstallMode" = "upgrade"; "SyncMode" = $null; "Scope" = "PTE"; "continuousDeployment" = $true; "includeTestAppsInSandboxEnvironment" = $false; "excludeAppIds" = @(); "unpublishOldVersions" = $true } + + Assert-MockCalled InstallOrUpgradeApps -Exactly 1 + Assert-MockCalled PublishPTEApps -Exactly 1 + Assert-MockCalled UnpublishOldAppVersions -Exactly 1 + } + It 'Does not invoke cleanup when unpublishOldVersions is not set (default)' { InvokeDeploy -deploymentSettings @{ "EnvironmentType" = "SaaS"; "EnvironmentName" = "test"; "Branches" = @(); "Projects" = "*"; "DependencyInstallMode" = "ignore"; "SyncMode" = $null; "Scope" = "PTE"; "continuousDeployment" = $true; "includeTestAppsInSandboxEnvironment" = $false; "excludeAppIds" = @() } diff --git a/Tests/Deploy.Module.Test.ps1 b/Tests/Deploy.Module.Test.ps1 index fd09d2707f..d00cd7a7de 100644 --- a/Tests/Deploy.Module.Test.ps1 +++ b/Tests/Deploy.Module.Test.ps1 @@ -43,6 +43,7 @@ InModuleScope Deploy { # Allows testing of private functions Mock OutputGroupStart { } Mock OutputGroupEnd { } Mock OutputWarning { } + Mock Get-AdminCenterInstalledExtensions { throw 'Admin Center read unavailable' } Mock Get-AppJsonFromAppFile { param($appFile) switch ($appFile) { @@ -511,6 +512,21 @@ InModuleScope Deploy { # Allows testing of private functions } Describe "CheckInstalledApps" { + It 'Uses the Admin installed snapshot for higher-version warnings without Automation' { + Mock Get-AdminCenterInstalledExtensions { + return [PSCustomObject]@{ + id = 'admin-app'; displayName = 'Admin App'; isInstalled = $true + versionMajor = 2; versionMinor = 1; versionBuild = 3; versionRevision = 4 + } + } + Mock Get-AppJsonFromAppFile { return @{ id = 'admin-app'; name = 'Admin App'; Version = '2.1.3.2' } } + + CheckInstalledApps -bcAuthContext @{} -environment Sandbox -appFiles @('Admin.app') + + Assert-MockCalled Get-AdminCenterInstalledExtensions -Exactly 1 + Assert-MockCalled Get-BcInstalledExtensions -Times 0 + Assert-MockCalled OutputWarning -Exactly 1 -ParameterFilter { $message -like '*2.1.3.4*higher than 2.1.3.2*' } + } It 'Does not warn when app version matches installed version' { $bcAuthContext = @{ tenantId = "test-tenant" } $environment = "test-env" @@ -811,6 +827,47 @@ InModuleScope Deploy { # Allows testing of private functions } } + It 'Uses Admin installed PTE dependency checks without requiring Automation' { + Mock Get-ChildItem { + param($Path) + return @(@{ FullName = Join-Path $Path "PTEApp.app" }) + } + Mock Get-AdminCenterInstalledExtensions { + return [PSCustomObject]@{ + id = $script:pteApp1Id; displayName = 'PTE App'; isInstalled = $true + versionMajor = 1; versionMinor = 0; versionBuild = 0; versionRevision = 0 + publishedAs = 'tenant' + } + } + + InstallOrUpgradeApps -bcAuthContext @{} -environment Sandbox -apps @('PTEApp.app') -installMode upgrade + + Assert-MockCalled Get-AdminCenterInstalledExtensions -Exactly 1 + Assert-MockCalled Get-BcInstalledExtensions -Times 0 + Assert-MockCalled PublishPTEApps -Exactly 1 + } + + It 'Preserves the Dev dependency exclusion using normalized Admin appType' { + Mock Get-ChildItem { + param($Path) + return @(@{ FullName = Join-Path $Path "DevScopeApp.app" }) + } + Mock Get-AdminCenterInstalledExtensions { + return [PSCustomObject]@{ + id = $script:devScopeAppId; displayName = 'Dev Scope App'; isInstalled = $true + versionMajor = 1; versionMinor = 0; versionBuild = 0; versionRevision = 0 + publishedAs = 'dev' + } + } + + InstallOrUpgradeApps -bcAuthContext @{} -environment Sandbox -apps @('DevScopeApp.app') -installMode upgrade + + Assert-MockCalled Get-BcInstalledExtensions -Times 0 + Assert-MockCalled Install-BcAppFromAppSource -Times 0 + Assert-MockCalled PublishPTEApps -Times 0 + Assert-MockCalled OutputWarning -Exactly 1 -ParameterFilter { $message -like '*published in Dev scope*Cannot upgrade*' } + } + It 'Delegates PTE dependency publishing without requesting deferred installation' { Mock Get-ChildItem { param($Path) @@ -818,10 +875,14 @@ InModuleScope Deploy { # Allows testing of private functions } Mock PublishPTEApps { $PesterBoundParameters.Keys | Should -Not -Contain 'schedule' + $publishingResults['primary'] | Should -Be 'AdminCenter' + $publishingResults['dependency'] = 'Automation' } - InstallOrUpgradeApps -bcAuthContext @{ tenantId = "test-tenant" } -environment "test-env" -apps @("PTEApp.app") -installMode "upgrade" + $results = @{ primary = 'AdminCenter' } + InstallOrUpgradeApps -bcAuthContext @{ tenantId = "test-tenant" } -environment "test-env" -apps @("PTEApp.app") -installMode "upgrade" -publishingResults $results + $results['dependency'] | Should -Be 'Automation' Assert-MockCalled PublishPTEApps -Exactly 1 -ParameterFilter { $appFiles.Count -eq 1 -and $appFiles[0] -like "*PTEApp.app" -and $SchemaSyncMode -eq "Add" } diff --git a/Tests/PublishPTEApps.Test.ps1 b/Tests/PublishPTEApps.Test.ps1 index 803af99d3b..50ed64ba76 100644 --- a/Tests/PublishPTEApps.Test.ps1 +++ b/Tests/PublishPTEApps.Test.ps1 @@ -24,6 +24,9 @@ InModuleScope Deploy { Mock OutputWarning { } Mock Renew-BcAuthContext { return @{ AccessToken = 'renewed-test-token' } } Mock Invoke-RestMethod { throw "Unexpected HTTP request" } + Mock Install-AdminCenterPTE { throw 'Unexpected installation request' } + Mock Get-AdminCenterAppOperation { throw 'Unexpected operation request' } + Mock Get-AdminCenterInstalledExtensions { return $script:extensions } Mock Get-BcInstalledExtensions { return $script:extensions } Mock Publish-PerTenantExtensionApps { } } @@ -35,12 +38,12 @@ InModuleScope Deploy { Mock Sort-AppFilesByDependencies { return @('App.app') } Mock Remove-Item { } Mock Get-AppJsonFromAppFile { return @{ id = 'app-1'; name = 'App'; version = '2.0.0.0' } } - Mock InvokePTEUpload { return @{ id = 'operation-1'; appId = 'app-1'; status = 'running' } } + Mock Install-AdminCenterPTE { return @{ id = 'operation-1'; appId = 'app-1'; status = 'running' } } Mock WaitPTEOperation { } } It 'Uses only the released helper for BC and preserves Force and immediate defaults' -TestCases @( - @{ major = 28 }, @{ major = 29 } + @{ major = 27 }, @{ major = 28 } ) { param($major) $script:application.versionMajor = $major @@ -58,7 +61,7 @@ InModuleScope Deploy { $environment -eq 'Sandbox' -and $bcAuthContext.tenantId -eq 'tenant' -and $appFiles[0] -eq 'Apps.zip' -and $schemaSyncMode -eq 'Force' } - Assert-MockCalled InvokePTEUpload -Times 0 + Assert-MockCalled Install-AdminCenterPTE -Times 0 Assert-MockCalled NewTemporaryFolder -Times 0 Assert-MockCalled Invoke-RestMethod -Times 0 } @@ -69,10 +72,12 @@ InModuleScope Deploy { $exports | Should -Not -Contain 'InvokePTEUpload' $exports | Should -Not -Contain 'WaitPTEOperation' $exports | Should -Not -Contain 'GetPTEApplicationVersion' + (Get-Command PublishPTEApps).Parameters.Keys | Should -Not -Contain 'applicationFamily' + (Get-Command WaitPTEOperation).Parameters.Keys | Should -Not -Contain 'applicationFamily' } It 'Uses AL-Go Admin Center publishing for BC ' -TestCases @( - @{ major = 30 }, @{ major = 31 } + @{ major = 29 }, @{ major = 30 }, @{ major = 31 } ) { param($major) $script:application.versionMajor = $major @@ -82,18 +87,89 @@ InModuleScope Deploy { Assert-MockCalled Publish-PerTenantExtensionApps -Times 0 Assert-MockCalled Copy-AppFilesToFolder -Exactly 1 -ParameterFilter { $appFiles[0] -eq 'Apps.zip' } Assert-MockCalled Sort-AppFilesByDependencies -Exactly 1 -ParameterFilter { $excludeRuntimePackages } - Assert-MockCalled InvokePTEUpload -Exactly 1 -ParameterFilter { $syncMode -eq 'Add' } - Assert-MockCalled WaitPTEOperation -Exactly 1 -ParameterFilter { $appId -eq 'app-1' } + Assert-MockCalled Install-AdminCenterPTE -Exactly 1 -ParameterFilter { + $environment -eq 'Sandbox' -and + $syncMode -eq 'Add' + } + Assert-MockCalled WaitPTEOperation -Exactly 1 -ParameterFilter { + $environment -eq 'Sandbox' -and + $appId -eq 'app-1' + } Assert-MockCalled Remove-Item -Exactly 1 -ParameterFilter { $LiteralPath -eq 'test-app-folder' -and $Recurse -and $Force } + Assert-MockCalled Get-AdminCenterInstalledExtensions -Exactly 1 + Assert-MockCalled Get-BcInstalledExtensions -Times 0 } - It 'Uses the configured base URL and escapes environment and application family' { - PublishPTEApps -bcAuthContext @{} -environment 'QA / East' -applicationFamily 'Family / US' -appFiles @('App.app') -schemaSyncMode Force + It 'Uses Automation reads after an Admin without changing write routing' -TestCases @( + @{ problem = 'authorization' }, @{ problem = 'network' }, @{ problem = 'malformed response' }, + @{ problem = 'missing Application' }, @{ problem = 'incomplete Application' }, @{ problem = 'ambiguous Application' } + ) { + param($problem) + switch ($problem) { + authorization { Mock Get-AdminCenterInstalledExtensions { throw '403 Forbidden: User not authorized' } } + network { Mock Get-AdminCenterInstalledExtensions { throw [System.Net.WebException]::new('Connection failed') } } + 'malformed response' { Mock Get-AdminCenterInstalledExtensions { throw 'Admin Center installed app has invalid full version.' } } + 'missing Application' { Mock Get-AdminCenterInstalledExtensions { return @() } } + 'incomplete Application' { + Mock Get-AdminCenterInstalledExtensions { return @{ displayName = 'Application'; isInstalled = $true; versionMajor = 30 } } + } + 'ambiguous Application' { Mock Get-AdminCenterInstalledExtensions { return @($script:application, $script:application.Clone()) } } + } + + PublishPTEApps -bcAuthContext @{} -environment Sandbox -appFiles @('App.app') + + Assert-MockCalled Get-AdminCenterInstalledExtensions -Exactly 1 + Assert-MockCalled Get-BcInstalledExtensions -Exactly 1 + Assert-MockCalled Install-AdminCenterPTE -Exactly 1 + Assert-MockCalled Publish-PerTenantExtensionApps -Times 0 + Assert-MockCalled Write-Host -Exactly 1 -ParameterFilter { $Object -like '*Admin Center installed-app read failed*Using the read-only Automation API*' } + } + + It 'Uses the Automation Application version below 29 when the Admin read fails' { + $script:application.versionMajor = 28 + Mock Get-AdminCenterInstalledExtensions { throw '403 Forbidden' } + + PublishPTEApps -bcAuthContext @{} -environment Sandbox -appFiles @('App.app') + + Assert-MockCalled Get-BcInstalledExtensions -Exactly 1 + Assert-MockCalled Publish-PerTenantExtensionApps -Exactly 1 + Assert-MockCalled Install-AdminCenterPTE -Times 0 + } + + It 'Propagates Automation read failure instead of publishing with a default version' { + Mock Get-AdminCenterInstalledExtensions { throw '403 Forbidden' } + Mock Get-BcInstalledExtensions { throw 'Automation read failed' } + + { PublishPTEApps -bcAuthContext @{} -environment Sandbox -appFiles @('App.app') } | Should -Throw '*Automation read failed*' + + Assert-MockCalled Install-AdminCenterPTE -Times 0 + Assert-MockCalled Publish-PerTenantExtensionApps -Times 0 + } + + It 'Uses the default API family with helper configuration' -TestCases @( + @{ helperConfiguration = 'overridden' }, @{ helperConfiguration = 'missing' } + ) { + param($helperConfiguration) + if ($helperConfiguration -eq 'missing') { + $script:bcContainerHelperConfig = $null + } + + Mock Install-AdminCenterPTE { + $PesterBoundParameters.Keys | Should -Not -Contain 'applicationFamily' + return @{ id = 'operation-1'; appId = 'app-1'; status = 'running' } + } + Mock WaitPTEOperation { + $PesterBoundParameters.Keys | Should -Not -Contain 'applicationFamily' + } + PublishPTEApps -bcAuthContext @{} -environment 'QA / East' -appFiles @('App.app') -schemaSyncMode Force - Assert-MockCalled InvokePTEUpload -Exactly 1 -ParameterFilter { - $uri -eq 'https://api.example.test/admin/v2.29/applications/Family%20%2F%20US/environments/QA%20%2F%20East/apps/pteInstall' -and + Assert-MockCalled Install-AdminCenterPTE -Exactly 1 -ParameterFilter { + $environment -eq 'QA / East' -and $syncMode -eq 'ForceSync' } + Assert-MockCalled WaitPTEOperation -Exactly 1 -ParameterFilter { + $environment -eq 'QA / East' + } } It 'Does not mistake the package version for the target BC version' { @@ -101,7 +177,7 @@ InModuleScope Deploy { PublishPTEApps -bcAuthContext @{} -environment 'Sandbox' -appFiles @('App.app') - Assert-MockCalled InvokePTEUpload -Exactly 1 + Assert-MockCalled Install-AdminCenterPTE -Exactly 1 Assert-MockCalled Publish-PerTenantExtensionApps -Times 0 } @@ -119,7 +195,7 @@ InModuleScope Deploy { { PublishPTEApps -bcAuthContext @{} -environment 'Sandbox' -appFiles @('App.app') } | Should -Throw '*Could not determine the Business Central version*' Assert-MockCalled Publish-PerTenantExtensionApps -Times 0 - Assert-MockCalled InvokePTEUpload -Times 0 + Assert-MockCalled Install-AdminCenterPTE -Times 0 } It 'Ignores uninstalled Application records when detecting the target version' { @@ -130,7 +206,7 @@ InModuleScope Deploy { PublishPTEApps -bcAuthContext @{} -environment 'Sandbox' -appFiles @('App.app') - Assert-MockCalled InvokePTEUpload -Exactly 1 + Assert-MockCalled Install-AdminCenterPTE -Exactly 1 Assert-MockCalled Publish-PerTenantExtensionApps -Times 0 } @@ -145,7 +221,7 @@ InModuleScope Deploy { PublishPTEApps -bcAuthContext @{} -environment 'Sandbox' -appFiles @('App.app') - Assert-MockCalled InvokePTEUpload -Times 0 + Assert-MockCalled Install-AdminCenterPTE -Times 0 Assert-MockCalled WaitPTEOperation -Times 0 } @@ -157,7 +233,7 @@ InModuleScope Deploy { PublishPTEApps -bcAuthContext @{} -environment 'Sandbox' -appFiles @('App.app') - Assert-MockCalled InvokePTEUpload -Exactly 1 + Assert-MockCalled Install-AdminCenterPTE -Exactly 1 Assert-MockCalled WaitPTEOperation -Exactly 1 } @@ -169,7 +245,7 @@ InModuleScope Deploy { return @{ id = $appFile; name = $appFile; version = '2.0.0.0' } } $script:events = @() - Mock InvokePTEUpload { + Mock Install-AdminCenterPTE { param($appFile) $script:events += "upload:$appFile" return @{ id = "operation-$appFile"; appId = $appFile; status = 'running' } @@ -183,7 +259,7 @@ InModuleScope Deploy { ($script:events -join ',') | Should -Be 'upload:Dependency.app,complete:Dependency.app,upload:Dependent.app,complete:Dependent.app' Assert-MockCalled Sort-AppFilesByDependencies -Exactly 1 -ParameterFilter { $excludeRuntimePackages -and $appFiles.Count -eq 3 } - Assert-MockCalled InvokePTEUpload -Times 0 -ParameterFilter { $appFile -eq 'Runtime.app' } + Assert-MockCalled Install-AdminCenterPTE -Times 0 -ParameterFilter { $appFile -eq 'Runtime.app' } } It 'Remembers completed installs when another package for the same app is encountered' { @@ -191,103 +267,249 @@ InModuleScope Deploy { PublishPTEApps -bcAuthContext @{} -environment 'Sandbox' -appFiles @('App.app', 'Duplicate.app') - Assert-MockCalled InvokePTEUpload -Exactly 1 + Assert-MockCalled Install-AdminCenterPTE -Exactly 1 Assert-MockCalled WaitPTEOperation -Exactly 1 } - It 'Does not fall back or continue after failure' -TestCases @( + It 'Does not fall back or continue after an ambiguous failure' -TestCases @( @{ step = 'upload' }, @{ step = 'polling' }, @{ step = 'authorization' } ) { param($step) switch ($step) { - upload { Mock InvokePTEUpload { throw "Package upload failed" } } + upload { Mock Install-AdminCenterPTE { throw "Package upload failed" } } polling { Mock WaitPTEOperation { throw "Installation failed" } } - authorization { Mock InvokePTEUpload { throw "403 Forbidden" } } + authorization { Mock Install-AdminCenterPTE { throw "403 Forbidden" } } } { PublishPTEApps -bcAuthContext @{} -environment 'Sandbox' -appFiles @('App.app') } | Should -Throw Assert-MockCalled Publish-PerTenantExtensionApps -Times 0 - Assert-MockCalled InvokePTEUpload -Exactly 1 + Assert-MockCalled Install-AdminCenterPTE -Exactly 1 Assert-MockCalled Remove-Item -Exactly 1 } - } - Context "Multipart upload" { - BeforeEach { - $script:packagePath = Join-Path $TestDrive 'Binary Package.app' - $script:packageBytes = [byte[]]@(0, 1, 127, 128, 255, 13, 10, 65, 66) - [System.IO.File]::WriteAllBytes($script:packagePath, $script:packageBytes) + It 'Falls back on a confirmed failure with actionable service diagnostics and preserves Force' { + Mock Install-AdminCenterPTE { + $exception = [System.Exception]::new('403 Forbidden: AdminCenter permission missing') + $exception.Data['PTEFallbackAllowed'] = $true + throw $exception + } + + PublishPTEApps -bcAuthContext @{} -environment Sandbox -appFiles @('App.app') -schemaSyncMode Force + + Assert-MockCalled Publish-PerTenantExtensionApps -Exactly 1 -ParameterFilter { + $environment -eq 'Sandbox' -and $appFiles.Count -eq 1 -and $appFiles[0] -eq 'App.app' -and $schemaSyncMode -eq 'Force' + } + Assert-MockCalled OutputWarning -Exactly 1 -ParameterFilter { + $message -like '*403 Forbidden*permission missing*permissions*ContinuousDeployment.md#pte-deployment-authorization*Falling back*' + } + Assert-MockCalled WaitPTEOperation -Times 0 + Assert-MockCalled Get-BcInstalledExtensions -Exactly 1 + } + + It 'Falls back when the helper reports authentication failed before sending an upload' { + Mock Install-AdminCenterPTE { + $exception = [System.Exception]::new('Authentication failed: consent missing') + $exception.Data['AdminCenterRequestStarted'] = $false + throw $exception + } + PublishPTEApps -bcAuthContext @{} -environment Sandbox -appFiles @('App.app') + + Assert-MockCalled Publish-PerTenantExtensionApps -Exactly 1 + Assert-MockCalled OutputWarning -Exactly 1 -ParameterFilter { + $message -like '*Authentication failed: consent missing*permissions*Falling back*' + } + Assert-MockCalled Invoke-RestMethod -Times 0 } - It 'Sends actual multipart fields and unchanged binary bytes using ' -TestCases @( - @{ syncMode = 'Add' }, @{ syncMode = 'ForceSync' } + It 'Classifies installation HTTP without replaying ambiguous requests' -TestCases @( + @{ statusCode = 400; allowed = $true }, + @{ statusCode = 401; allowed = $true }, + @{ statusCode = 403; allowed = $true }, + @{ statusCode = 404; allowed = $true }, + @{ statusCode = 409; allowed = $false }, + @{ statusCode = 429; allowed = $true }, + @{ statusCode = 500; allowed = $false }, + @{ statusCode = 503; allowed = $false } ) { - param($syncMode) - $expectedSyncMode = $syncMode - Mock Invoke-RestMethod { - param($Body, $ContentType) - ,$Body | Should -BeOfType [byte[]] - $ContentType | Should -BeLike 'multipart/form-data; boundary=*' - $wireText = [System.Text.Encoding]::GetEncoding(28591).GetString($Body) - $wireText | Should -Match 'name="?deploymentSchedule"?\r\n\r\nImmediate\r\n' - $wireText | Should -Match ('name="?syncMode"?\r\n\r\n' + $expectedSyncMode + '\r\n') - $wireText | Should -Match 'name="?acceptIsvEula"?\r\n\r\ntrue\r\n' - $wireText | Should -Match 'name="?installOrUpdateNeededDependencies"?\r\n\r\nfalse\r\n' - $wireText | Should -Match 'name="?extensionFile"?; filename="Binary Package.app"' - $wireText | Should -Match 'Content-Type: application/octet-stream' - $wireText.Contains([System.Text.Encoding]::GetEncoding(28591).GetString($script:packageBytes)) | Should -BeTrue - return [PSCustomObject]@{ id = 'operation-1'; appId = 'app-1'; status = 'running' } + param($statusCode, $allowed) + $script:installStatus = $statusCode + Mock Install-AdminCenterPTE { + $exception = [System.Exception]::new("Service HTTP $script:installStatus") + $exception | Add-Member NoteProperty Response ([PSCustomObject]@{ StatusCode = $script:installStatus }) + $exception.Data['AdminCenterRequestStarted'] = $true + throw $exception } - $result = InvokePTEUpload -bcAuthContext @{} -uri 'https://api.example.test/apps/pteInstall' -appFile $script:packagePath -syncMode $syncMode + if ($allowed) { + PublishPTEApps -bcAuthContext @{} -environment Sandbox -appFiles @('App.app') + Assert-MockCalled Publish-PerTenantExtensionApps -Exactly 1 + } + else { + { PublishPTEApps -bcAuthContext @{} -environment Sandbox -appFiles @('App.app') } | Should -Throw "*Service HTTP $statusCode*" + Assert-MockCalled Publish-PerTenantExtensionApps -Times 0 + } + Assert-MockCalled Install-AdminCenterPTE -Exactly 1 + } - $result.id | Should -Be 'operation-1' - Assert-MockCalled Renew-BcAuthContext -Exactly 1 - Assert-MockCalled Invoke-RestMethod -Exactly 1 -ParameterFilter { - $Method -eq 'Post' -and $TimeoutSec -eq 300 -and $ErrorAction -eq 'Stop' -and - $Headers.Authorization -eq 'Bearer renewed-test-token' + It 'Allows fallback for a local file preparation failure reported before sending' { + Mock Install-AdminCenterPTE { + $exception = [IO.FileNotFoundException]::new('Package missing') + $exception.Data['AdminCenterRequestStarted'] = $false + throw $exception } - $stream = [System.IO.File]::Open($script:packagePath, 'Open', 'ReadWrite', 'None') - $stream.Dispose() + + PublishPTEApps -bcAuthContext @{} -environment Sandbox -appFiles @('App.app') + + Assert-MockCalled Publish-PerTenantExtensionApps -Exactly 1 } - It 'Disposes streams and never replays an ambiguous upload failure' { - Mock Invoke-RestMethod { throw [System.TimeoutException]::new('Upload timed out') } + It 'Never treats a status-read rejection or renewal failure as a rejected upload' -TestCases @( + @{ sent = $true }, @{ sent = $false } + ) { + param($sent) + $script:statusRequestSent = $sent + Mock WaitPTEOperation { + $exception = [System.Exception]::new('403 while checking accepted operation') + $exception | Add-Member NoteProperty Response ([PSCustomObject]@{ StatusCode = 403 }) + $exception.Data['AdminCenterRequestStarted'] = $script:statusRequestSent + throw $exception + } - { InvokePTEUpload -bcAuthContext @{} -uri 'https://api.example.test/apps/pteInstall' -appFile $script:packagePath -syncMode Add } | Should -Throw '*Upload timed out*' + { PublishPTEApps -bcAuthContext @{} -environment Sandbox -appFiles @('App.app') } | Should -Throw '*accepted operation*' - Assert-MockCalled Invoke-RestMethod -Exactly 1 - $stream = [System.IO.File]::Open($script:packagePath, 'Open', 'ReadWrite', 'None') - $stream.Dispose() + Assert-MockCalled Publish-PerTenantExtensionApps -Times 0 + Assert-MockCalled Install-AdminCenterPTE -Exactly 1 } - It 'Fails before upload if renewing authentication fails' { - Mock Renew-BcAuthContext { throw 'Authentication failed' } + It 'Does not replay completed apps and uses legacy publishing only for remaining sorted apps' { + Mock Sort-AppFilesByDependencies { return @('First.app', 'Second.app', 'Duplicate.app', 'Third.app') } + Mock Get-AppJsonFromAppFile { + param($appFile) + $id = if ($appFile -eq 'Duplicate.app') { 'First.app' } else { $appFile } + return @{ id = $id; name = $id; version = '2.0.0.0' } + } + Mock Install-AdminCenterPTE { + param($appFile) + if ($appFile -eq 'Second.app') { + $exception = [System.Exception]::new('Package rejected') + $exception.Data['PTEFallbackAllowed'] = $true + throw $exception + } + return @{ id = 'completed'; appId = $appFile; status = 'succeeded' } + } - { InvokePTEUpload -bcAuthContext @{} -uri 'https://api.example.test/apps/pteInstall' -appFile $script:packagePath -syncMode Add } | Should -Throw '*Authentication failed*' + $results = @{} + PublishPTEApps -bcAuthContext @{} -environment Sandbox -appFiles @('Apps.zip') -publishingResults $results + + Assert-MockCalled Install-AdminCenterPTE -Exactly 2 + Assert-MockCalled WaitPTEOperation -Exactly 1 -ParameterFilter { $appId -eq 'First.app' } + Assert-MockCalled Publish-PerTenantExtensionApps -Exactly 2 + Assert-MockCalled Publish-PerTenantExtensionApps -Exactly 1 -ParameterFilter { $appFiles[0] -eq 'Second.app' } + Assert-MockCalled Publish-PerTenantExtensionApps -Exactly 1 -ParameterFilter { $appFiles[0] -eq 'Third.app' } + Assert-MockCalled Publish-PerTenantExtensionApps -Times 0 -ParameterFilter { $appFiles[0] -in 'First.app','Duplicate.app' } + $results['First.app'] | Should -Be 'AdminCenter' + $results['Second.app'] | Should -Be 'Automation' + $results['Third.app'] | Should -Be 'Automation' + } + + It 'Retains Admin Center cleanup protection across dependency and primary batches for the same app' { + $results = @{} + PublishPTEApps -bcAuthContext @{} -environment Sandbox -appFiles @('Dependency.app') -publishingResults $results + $results['app-1'] | Should -Be 'AdminCenter' + Mock Get-AppJsonFromAppFile { return @{ id = 'app-1'; name = 'App'; version = '3.0.0.0' } } + Mock Install-AdminCenterPTE { + $exception = [System.Exception]::new('Confirmed rejection') + $exception.Data['PTEFallbackAllowed'] = $true + throw $exception + } - Assert-MockCalled Invoke-RestMethod -Times 0 + PublishPTEApps -bcAuthContext @{} -environment Sandbox -appFiles @('Primary.app') -publishingResults $results + + Assert-MockCalled Publish-PerTenantExtensionApps -Exactly 1 + $results['app-1'] | Should -Be 'AdminCenter' } - It 'Rejects a renewal response without an access token' { - Mock Renew-BcAuthContext { return @{} } + It 'Does not retain publishing paths from a different action' { + $firstResults = @{} + PublishPTEApps -bcAuthContext @{} -environment Sandbox -appFiles @('App.app') -publishingResults $firstResults + Mock Install-AdminCenterPTE { + $exception = [System.Exception]::new('Confirmed rejection') + $exception.Data['PTEFallbackAllowed'] = $true + throw $exception + } + $secondResults = @{} - { InvokePTEUpload -bcAuthContext @{} -uri 'https://api.example.test/apps/pteInstall' -appFile $script:packagePath -syncMode Add } | Should -Throw '*Authentication failed*' + PublishPTEApps -bcAuthContext @{} -environment Sandbox -appFiles @('App.app') -publishingResults $secondResults - Assert-MockCalled Invoke-RestMethod -Times 0 + $firstResults['app-1'] | Should -Be 'AdminCenter' + $secondResults['app-1'] | Should -Be 'Automation' + } + + It 'Refreshes installed state before fallback and skips a now-installed app' { + Mock Install-AdminCenterPTE { + $script:extensions += @{ + id = 'app-1'; isInstalled = $true; versionMajor = 2; versionMinor = 0; versionBuild = 0; versionRevision = 0 + } + $exception = [System.Exception]::new('Terminal operation failed after installation') + $exception.Data['PTEFallbackAllowed'] = $true + throw $exception + } + + PublishPTEApps -bcAuthContext @{} -environment Sandbox -appFiles @('App.app') + + Assert-MockCalled Publish-PerTenantExtensionApps -Times 0 + Assert-MockCalled Get-BcInstalledExtensions -Exactly 1 + } + + It 'Propagates a legacy fallback failure without continuing or claiming success' { + Mock Install-AdminCenterPTE { + $exception = [System.Exception]::new('Confirmed Admin Center failure') + $exception.Data['PTEFallbackAllowed'] = $true + throw $exception + } + Mock Publish-PerTenantExtensionApps { throw 'Legacy publishing failed' } + + { PublishPTEApps -bcAuthContext @{} -environment Sandbox -appFiles @('App.app') } | Should -Throw '*Legacy publishing failed*' + + Assert-MockCalled Publish-PerTenantExtensionApps -Exactly 1 + Assert-MockCalled Remove-Item -Exactly 1 + } + + It 'Falls back after a terminal operation failure' { + Mock WaitPTEOperation { + $exception = [System.Exception]::new('Operation failed: rejected package') + $exception.Data['PTEFallbackAllowed'] = $true + throw $exception + } + + PublishPTEApps -bcAuthContext @{} -environment Sandbox -appFiles @('App.app') + + Assert-MockCalled Publish-PerTenantExtensionApps -Exactly 1 } - It 'Preserves service upload diagnostics without replaying the upload' { - Mock Invoke-RestMethod { - $record = [System.Management.Automation.ErrorRecord]::new([System.Exception]::new('400 Bad Request'), 'InvalidPackage', 'InvalidData', $null) - $record.ErrorDetails = [System.Management.Automation.ErrorDetails]::new('Service rejected the package signature') - throw $record + It 'Stops after an accepted operation loses polling without replaying completed or later apps' { + Mock Sort-AppFilesByDependencies { return @('First.app', 'Second.app', 'Third.app') } + Mock Get-AppJsonFromAppFile { + param($appFile) + return @{ id = $appFile; name = $appFile; version = '2.0.0.0' } + } + Mock WaitPTEOperation { + param($appId) + if ($appId -eq 'Second.app') { + throw 'Timed out waiting for operation operation-2 for app Second.app; last status running' + } } - { InvokePTEUpload -bcAuthContext @{} -uri 'https://api.example.test/apps/pteInstall' -appFile $script:packagePath -syncMode Add } | Should -Throw '*400 Bad Request*Service rejected the package signature*not be replayed*' + { PublishPTEApps -bcAuthContext @{} -environment Sandbox -appFiles @('Apps.zip') } | + Should -Throw '*operation-2*Second.app*running*' - Assert-MockCalled Invoke-RestMethod -Exactly 1 + Assert-MockCalled Install-AdminCenterPTE -Exactly 2 + Assert-MockCalled Install-AdminCenterPTE -Times 0 -ParameterFilter { $appFile -eq 'Third.app' } + Assert-MockCalled Publish-PerTenantExtensionApps -Times 0 + Assert-MockCalled OutputWarning -Exactly 1 -ParameterFilter { + $message -like '*operation-2*permissions*stopping without legacy fallback*' + } } } @@ -295,43 +517,77 @@ InModuleScope Deploy { BeforeEach { $script:operation = [PSCustomObject]@{ id = 'operation / 1'; appId = 'app-1'; status = 'running'; scheduleKind = 'immediate' } Mock Start-Sleep { } - Mock Invoke-RestMethod { return [PSCustomObject]@{ id = 'operation / 1'; appId = 'app-1'; status = 'succeeded' } } + Mock Get-AdminCenterAppOperation { return [PSCustomObject]@{ id = 'operation / 1'; appId = 'app-1'; status = 'succeeded' } } } It 'Accepts immediate success without polling' { $script:operation.status = 'succeeded' - WaitPTEOperation -bcAuthContext @{} -appsUri 'https://api.example.test/apps' -operation $script:operation -appId 'app-1' + WaitPTEOperation -bcAuthContext @{} -environment Sandbox -operation $script:operation -appId 'app-1' - Assert-MockCalled Invoke-RestMethod -Times 0 + Assert-MockCalled Get-AdminCenterAppOperation -Times 0 + } + + It 'Allows fallback for terminal but not an unrecognized outcome' -TestCases @( + @{ status = 'failed'; allowed = $true }, + @{ status = 'canceled'; allowed = $true }, + @{ status = 'skipped'; allowed = $true }, + @{ status = 'unknown'; allowed = $false } + ) { + param($status, $allowed) + $script:operation.status = $status + $script:operation | Add-Member NoteProperty errorMessage 'Service validation detail' + + try { + WaitPTEOperation -bcAuthContext @{} -environment Sandbox -operation $script:operation -appId 'app-1' + throw 'Expected terminal error' + } + catch { + $_.Exception.Data['PTEFallbackAllowed'] | Should -Be $allowed + $_.Exception.Message | Should -Match 'Service validation detail' + } + } + + It 'Does not dump credentials, headers or arbitrary operation response fields on failure' { + $script:operation.status = 'failed' + $script:operation | Add-Member NoteProperty error (@{ message = 'Package validation failed'; credentials = 'private-credentials' }) + $script:operation | Add-Member NoteProperty headers (@{ Authorization = 'private-header' }) + $script:operation | Add-Member NoteProperty arbitrary 'private-response-field' + + try { + WaitPTEOperation -bcAuthContext @{} -environment Sandbox -operation $script:operation -appId 'app-1' + throw 'Expected failure' + } + catch { + $_.Exception.Message | Should -Match 'Package validation failed' + $_.Exception.Message | Should -Not -Match 'private-credentials|private-header|private-response-field' + } } It 'Polls only the exact returned operation and renews authentication' { - WaitPTEOperation -bcAuthContext @{} -appsUri 'https://api.example.test/apps' -operation $script:operation -appId 'app-1' + WaitPTEOperation -bcAuthContext @{} -environment Sandbox -operation $script:operation -appId 'app-1' - Assert-MockCalled Invoke-RestMethod -Exactly 1 -ParameterFilter { - $Method -eq 'Get' -and $Uri -eq 'https://api.example.test/apps/app-1/operations/operation%20%2F%201' -and - $Headers.Authorization -eq 'Bearer renewed-test-token' -and $TimeoutSec -le 30 + Assert-MockCalled Get-AdminCenterAppOperation -Exactly 1 -ParameterFilter { + $environment -eq 'Sandbox' -and $appId -eq 'app-1' -and $operationId -eq 'operation / 1' -and $timeoutSeconds -le 30 } - Assert-MockCalled Renew-BcAuthContext -Exactly 1 Assert-MockCalled Start-Sleep -Exactly 1 -ParameterFilter { $Milliseconds -eq 30000 } } It 'Uses the requested shorter polling interval without changing the operation endpoint' { - WaitPTEOperation -bcAuthContext @{} -appsUri 'https://api.example.test/apps' -operation $script:operation -appId 'app-1' -pollIntervalSeconds 5 + WaitPTEOperation -bcAuthContext @{} -environment Sandbox -operation $script:operation -appId 'app-1' -pollIntervalSeconds 5 Assert-MockCalled Start-Sleep -Exactly 1 -ParameterFilter { $Milliseconds -eq 5000 } - Assert-MockCalled Invoke-RestMethod -Exactly 1 -ParameterFilter { - $Method -eq 'Get' -and $Uri -eq 'https://api.example.test/apps/app-1/operations/operation%20%2F%201' + Assert-MockCalled Get-AdminCenterAppOperation -Exactly 1 -ParameterFilter { + $environment -eq 'Sandbox' -and $appId -eq 'app-1' -and $operationId -eq 'operation / 1' } } It 'Does not count scheduled immediate installation as success' { $script:operation.status = 'scheduled' - WaitPTEOperation -bcAuthContext @{} -appsUri 'https://api.example.test/apps' -operation $script:operation -appId 'app-1' + WaitPTEOperation -bcAuthContext @{} -environment Sandbox -operation $script:operation -appId 'app-1' - Assert-MockCalled Invoke-RestMethod -Exactly 1 + Assert-MockCalled Get-AdminCenterAppOperation -Exactly 1 } It 'Fails explicitly for terminal or unknown status ' -TestCases @( @@ -341,9 +597,9 @@ InModuleScope Deploy { $script:operation.status = $status $script:operation | Add-Member -NotePropertyName errorMessage -NotePropertyValue 'Service diagnostic' - { WaitPTEOperation -bcAuthContext @{} -appsUri 'https://api.example.test/apps' -operation $script:operation -appId 'app-1' } | Should -Throw '*operation / 1*Service diagnostic*' + { WaitPTEOperation -bcAuthContext @{} -environment Sandbox -operation $script:operation -appId 'app-1' } | Should -Throw '*operation / 1*Service diagnostic*' - Assert-MockCalled Invoke-RestMethod -Times 0 + Assert-MockCalled Get-AdminCenterAppOperation -Times 0 } It 'Rejects upload responses with missing or mismatched ' -TestCases @( @@ -357,9 +613,9 @@ InModuleScope Deploy { empty { $script:operation = $null } } - { WaitPTEOperation -bcAuthContext @{} -appsUri 'https://api.example.test/apps' -operation $script:operation -appId 'app-1' } | Should -Throw '*missing or mismatched*' + { WaitPTEOperation -bcAuthContext @{} -environment Sandbox -operation $script:operation -appId 'app-1' } | Should -Throw '*missing or mismatched*' - Assert-MockCalled Invoke-RestMethod -Times 0 + Assert-MockCalled Get-AdminCenterAppOperation -Times 0 } It 'Rejects missing or unrelated status response ' -TestCases @( @@ -367,7 +623,7 @@ InModuleScope Deploy { ) { param($response) $script:responseKind = $response - Mock Invoke-RestMethod { + Mock Get-AdminCenterAppOperation { switch ($script:responseKind) { empty { return $null } anotherOperation { return [PSCustomObject]@{ id = 'other'; status = 'succeeded' } } @@ -376,30 +632,29 @@ InModuleScope Deploy { } } - { WaitPTEOperation -bcAuthContext @{} -appsUri 'https://api.example.test/apps' -operation $script:operation -appId 'app-1' } | Should -Throw '*Missing or mismatched PTE operation*' + { WaitPTEOperation -bcAuthContext @{} -environment Sandbox -operation $script:operation -appId 'app-1' } | Should -Throw '*Missing or mismatched PTE operation*' } It 'Retries transient status failures and then succeeds without any write' { $script:reads = 0 - Mock Invoke-RestMethod { + Mock Get-AdminCenterAppOperation { $script:reads++ if ($script:reads -lt 3) { throw [System.TimeoutException]::new('Temporary failure') } return [PSCustomObject]@{ id = 'operation / 1'; appId = 'app-1'; status = 'succeeded' } } - WaitPTEOperation -bcAuthContext @{} -appsUri 'https://api.example.test/apps' -operation $script:operation -appId 'app-1' + WaitPTEOperation -bcAuthContext @{} -environment Sandbox -operation $script:operation -appId 'app-1' - Assert-MockCalled Invoke-RestMethod -Exactly 3 -ParameterFilter { $Method -eq 'Get' } - Assert-MockCalled Invoke-RestMethod -Times 0 -ParameterFilter { $Method -ne 'Get' } + Assert-MockCalled Get-AdminCenterAppOperation -Exactly 3 Assert-MockCalled OutputWarning -Exactly 2 } It 'Stops after five consecutive transient retries' { - Mock Invoke-RestMethod { throw [System.TimeoutException]::new('Temporary failure') } + Mock Get-AdminCenterAppOperation { throw [System.TimeoutException]::new('Temporary failure') } - { WaitPTEOperation -bcAuthContext @{} -appsUri 'https://api.example.test/apps' -operation $script:operation -appId 'app-1' } | Should -Throw '*Unable to read PTE operation*Temporary failure*' + { WaitPTEOperation -bcAuthContext @{} -environment Sandbox -operation $script:operation -appId 'app-1' } | Should -Throw '*Unable to read PTE operation*Temporary failure*' - Assert-MockCalled Invoke-RestMethod -Exactly 6 + Assert-MockCalled Get-AdminCenterAppOperation -Exactly 6 Assert-MockCalled OutputWarning -Exactly 5 } @@ -416,7 +671,7 @@ InModuleScope Deploy { param($statusCode, $retry) $script:httpStatus = $statusCode $script:reads = 0 - Mock Invoke-RestMethod { + Mock Get-AdminCenterAppOperation { $script:reads++ if ($script:reads -eq 1) { $exception = [System.Exception]::new("HTTP $script:httpStatus") @@ -427,72 +682,76 @@ InModuleScope Deploy { } if ($retry) { - WaitPTEOperation -bcAuthContext @{} -appsUri 'https://api.example.test/apps' -operation $script:operation -appId 'app-1' - Assert-MockCalled Invoke-RestMethod -Exactly 2 + WaitPTEOperation -bcAuthContext @{} -environment Sandbox -operation $script:operation -appId 'app-1' + Assert-MockCalled Get-AdminCenterAppOperation -Exactly 2 Assert-MockCalled OutputWarning -Exactly 1 } else { - { WaitPTEOperation -bcAuthContext @{} -appsUri 'https://api.example.test/apps' -operation $script:operation -appId 'app-1' } | Should -Throw '*Unable to read PTE operation*' - Assert-MockCalled Invoke-RestMethod -Exactly 1 + { WaitPTEOperation -bcAuthContext @{} -environment Sandbox -operation $script:operation -appId 'app-1' } | Should -Throw '*Unable to read PTE operation*' + Assert-MockCalled Get-AdminCenterAppOperation -Exactly 1 Assert-MockCalled OutputWarning -Times 0 } } It 'Resets the consecutive retry budget after a successful running status read' { $script:reads = 0 - Mock Invoke-RestMethod { + Mock Get-AdminCenterAppOperation { $script:reads++ if ($script:reads -eq 6) { return [PSCustomObject]@{ id = 'operation / 1'; status = 'running' } } if ($script:reads -eq 12) { return [PSCustomObject]@{ id = 'operation / 1'; status = 'succeeded' } } throw [System.TimeoutException]::new('Transient timeout') } - WaitPTEOperation -bcAuthContext @{} -appsUri 'https://api.example.test/apps' -operation $script:operation -appId 'app-1' + WaitPTEOperation -bcAuthContext @{} -environment Sandbox -operation $script:operation -appId 'app-1' - Assert-MockCalled Invoke-RestMethod -Exactly 12 + Assert-MockCalled Get-AdminCenterAppOperation -Exactly 12 Assert-MockCalled OutputWarning -Exactly 10 } It 'Does not retry non-transient errors or renew failures' { - Mock Renew-BcAuthContext { throw '403 Forbidden' } + Mock Get-AdminCenterAppOperation { + $exception = [System.TimeoutException]::new('Authentication renewal failed: 403 Forbidden') + $exception.Data['AdminCenterRequestStarted'] = $false + throw $exception + } - { WaitPTEOperation -bcAuthContext @{} -appsUri 'https://api.example.test/apps' -operation $script:operation -appId 'app-1' } | Should -Throw '*403 Forbidden*' + { WaitPTEOperation -bcAuthContext @{} -environment Sandbox -operation $script:operation -appId 'app-1' } | Should -Throw '*403 Forbidden*' - Assert-MockCalled Invoke-RestMethod -Times 0 + Assert-MockCalled Get-AdminCenterAppOperation -Times 1 Assert-MockCalled OutputWarning -Times 0 } It 'Does not retry an authorization status-read failure' { - Mock Invoke-RestMethod { throw '401 Unauthorized' } + Mock Get-AdminCenterAppOperation { throw '401 Unauthorized' } - { WaitPTEOperation -bcAuthContext @{} -appsUri 'https://api.example.test/apps' -operation $script:operation -appId 'app-1' } | Should -Throw '*Unable to read PTE operation*401 Unauthorized*' + { WaitPTEOperation -bcAuthContext @{} -environment Sandbox -operation $script:operation -appId 'app-1' } | Should -Throw '*Unable to read PTE operation*401 Unauthorized*' - Assert-MockCalled Invoke-RestMethod -Exactly 1 + Assert-MockCalled Get-AdminCenterAppOperation -Exactly 1 Assert-MockCalled OutputWarning -Times 0 } It 'Bounds status attempts even when the operation remains scheduled' { - Mock Invoke-RestMethod { return [PSCustomObject]@{ id = 'operation / 1'; status = 'scheduled' } } + Mock Get-AdminCenterAppOperation { return [PSCustomObject]@{ id = 'operation / 1'; status = 'scheduled' } } - { WaitPTEOperation -bcAuthContext @{} -appsUri 'https://api.example.test/apps' -operation $script:operation -appId 'app-1' -maxStatusRequests 2 } | Should -Throw '*Timed out*2 status requests*' + { WaitPTEOperation -bcAuthContext @{} -environment Sandbox -operation $script:operation -appId 'app-1' -maxStatusRequests 2 } | Should -Throw '*Timed out*2 status requests*' - Assert-MockCalled Invoke-RestMethod -Exactly 2 + Assert-MockCalled Get-AdminCenterAppOperation -Exactly 2 } It 'Limits the default immediate polling to 360 status requests' { - Mock Invoke-RestMethod { return [PSCustomObject]@{ id = 'operation / 1'; status = 'running' } } + Mock Get-AdminCenterAppOperation { return [PSCustomObject]@{ id = 'operation / 1'; status = 'running' } } - { WaitPTEOperation -bcAuthContext @{} -appsUri 'https://api.example.test/apps' -operation $script:operation -appId 'app-1' } | Should -Throw '*Timed out*1800 seconds or 360 status requests*' + { WaitPTEOperation -bcAuthContext @{} -environment Sandbox -operation $script:operation -appId 'app-1' } | Should -Throw '*Timed out*1800 seconds or 360 status requests*' - Assert-MockCalled Invoke-RestMethod -Exactly 360 + Assert-MockCalled Get-AdminCenterAppOperation -Exactly 360 } It 'Honors the elapsed timeout before another status request' { Mock Start-Sleep { [System.Threading.Thread]::Sleep(1100) } - { WaitPTEOperation -bcAuthContext @{} -appsUri 'https://api.example.test/apps' -operation $script:operation -appId 'app-1' -timeoutSeconds 1 } | Should -Throw '*Timed out*1 seconds*' + { WaitPTEOperation -bcAuthContext @{} -environment Sandbox -operation $script:operation -appId 'app-1' -timeoutSeconds 1 } | Should -Throw '*Timed out*1 seconds*' - Assert-MockCalled Invoke-RestMethod -Times 0 + Assert-MockCalled Get-AdminCenterAppOperation -Times 0 Assert-MockCalled Start-Sleep -Exactly 1 -ParameterFilter { $Milliseconds -gt 0 -and $Milliseconds -le 1000 } } } diff --git a/Tests/UnpublishOldAppVersions.Test.ps1 b/Tests/UnpublishOldAppVersions.Test.ps1 index 553b7da0f1..036855a69a 100644 --- a/Tests/UnpublishOldAppVersions.Test.ps1 +++ b/Tests/UnpublishOldAppVersions.Test.ps1 @@ -64,6 +64,8 @@ InModuleScope Deploy { # Allows testing of private functions } It 'Explains delayed service-managed cleanup without any writes on BC .' -TestCases @( + @{ major = 29; minor = 0 }, + @{ major = 29; minor = 9 }, @{ major = 30; minor = 0 }, @{ major = 30; minor = 1 }, @{ major = 31; minor = 0 } @@ -72,19 +74,59 @@ InModuleScope Deploy { # Allows testing of private functions $script:applicationExtension.versionMajor = $major $script:applicationExtension.versionMinor = $minor - { UnpublishOldAppVersions -bcAuthContext @{ tenantId = "test-tenant" } -environment "test-env" -appFiles @("App1.app") } | Should -Not -Throw + { UnpublishOldAppVersions -bcAuthContext @{ tenantId = "test-tenant" } -environment "test-env" -appFiles @("App1.app") -publishingResults @{ $script:appId = 'AdminCenter' } } | Should -Not -Throw Assert-MockCalled OutputWarning -Exactly 1 -ParameterFilter { - $message -like "*cannot explicitly unpublish*Business Central manages cleanup in the background*may be delayed*timing and retained versions are not guaranteed*AL-Go cleanup was skipped*deployment remains successful*" + $message -like "*skips explicit cleanup*Admin Center publishing*Business Central manages cleanup in the background*may be delayed*timing and retained versions are not guaranteed*deployment remains successful*" } Assert-MockCalled Invoke-RestMethod -Times 0 -ParameterFilter { $Method -ne "Get" } } + It 'Uses legacy cleanup after Automation fallback on BC ' -TestCases @( + @{ major = 29 }, @{ major = 30 }, @{ major = 31 } + ) { + param($major) + $script:applicationExtension.versionMajor = $major + + UnpublishOldAppVersions -bcAuthContext @{} -environment test-env -appFiles @('App1.app') -publishingResults @{ $script:appId = 'Automation' } + + Assert-MockCalled Invoke-RestMethod -Exactly 1 -ParameterFilter { + $Method -eq 'Post' -and $Uri -like '*extensions(pkg-app1-v1)/Microsoft.NAV.unpublish' + } + Assert-MockCalled OutputWarning -Times 0 + } + + It 'Only cleans Automation apps in a mixed-path batch and preserves installed and newer packages' { + $script:applicationExtension.versionMajor = 29 + $script:mockExtensions += @( + @{ id = $script:appId; displayName = 'App 1'; packageId = 'pkg-app1-v3'; isInstalled = $false; versionMajor = 3; versionMinor = 0; versionBuild = 0; versionRevision = 0 }, + @{ id = $script:otherAppId; displayName = 'Other App'; packageId = 'pkg-other-v1'; isInstalled = $false; versionMajor = 1; versionMinor = 0; versionBuild = 0; versionRevision = 0 }, + @{ id = $script:otherAppId; displayName = 'Other App'; packageId = 'pkg-other-v2'; isInstalled = $true; versionMajor = 2; versionMinor = 0; versionBuild = 0; versionRevision = 0 } + ) + + UnpublishOldAppVersions -bcAuthContext @{} -environment test-env -appFiles @('App1.app', 'OtherApp.app') -publishingResults @{ + $script:appId = 'Automation' + $script:otherAppId = 'AdminCenter' + } + + Assert-MockCalled Invoke-RestMethod -Exactly 1 -ParameterFilter { $Method -eq 'Post' } + Assert-MockCalled Invoke-RestMethod -Exactly 1 -ParameterFilter { $Method -eq 'Post' -and $Uri -like '*pkg-app1-v1*' } + Assert-MockCalled Invoke-RestMethod -Times 0 -ParameterFilter { $Method -eq 'Post' -and $Uri -like '*pkg-other*' } + } + + It 'Does not infer an Automation outcome from the environment version or a skipped app' { + $script:applicationExtension.versionMajor = 29 + + UnpublishOldAppVersions -bcAuthContext @{} -environment test-env -appFiles @('App1.app') -publishingResults @{ $script:appId = 'Skipped' } + + Assert-MockCalled Invoke-RestMethod -Times 0 -ParameterFilter { $Method -ne 'Get' } + Assert-MockCalled OutputWarning -Exactly 1 + } + It 'Preserves legacy cleanup on BC .' -TestCases @( @{ major = 25; minor = 4 }, @{ major = 28; minor = 9 }, - @{ major = 29; minor = 0 }, - @{ major = 29; minor = 9 } + @{ major = 28; minor = 0 } ) { param($major, $minor) $script:applicationExtension.versionMajor = $major diff --git a/Workshop/ContinuousDeployment.md b/Workshop/ContinuousDeployment.md index 46a09bef26..bcda922395 100644 --- a/Workshop/ContinuousDeployment.md +++ b/Workshop/ContinuousDeployment.md @@ -90,19 +90,21 @@ Paste the value from the clipboard into the "Value" field of the **AuthContext** ## PTE deployment authorization -For **Scope PTE** S2S deployment to **BC 30 or later**, add the **AdminCenter.ReadWrite.All** application permission under **Dynamics 365 Business Central**, grant **tenant admin consent**, and add the client ID to **Authorized Microsoft Entra apps** in the Business Central administration center. Existing app registrations that previously deployed successfully may need this additional authorization. Keep the environment API permissions, such as **Automation.ReadWrite.All** and **API.ReadWrite.All** where required, and the Microsoft Entra application registration and permission sets inside each Business Central environment. +For **BC 29 or later**, AL-Go prefers administration center publishing for PTEs. To enable it with S2S authentication, add the **AdminCenter.ReadWrite.All** application permission under **Dynamics 365 Business Central**, grant **tenant admin consent**, and add the client ID to **Authorized Microsoft Entra apps** in the Business Central administration center. Keep the environment API permissions, such as **Automation.ReadWrite.All** and **API.ReadWrite.All** where required, and the Microsoft Entra application registration and permission sets inside each Business Central environment. -With delegated authentication (impersonation), **Scope PTE** deployment to **BC 30 or later** requires appropriate **Business Central administration center access** as well as the environment permissions. The existing **AUTHCONTEXT** credential structure and the commands above remain unchanged. See the official [Business Central administration center API documentation](https://learn.microsoft.com/en-us/dynamics365/business-central/dev-itpro/administration/administration-center-api) for authentication and authorization details. +With delegated authentication (impersonation), administration center publishing requires appropriate **Business Central administration center access** as well as the environment permissions. The existing **AUTHCONTEXT** credential structure and the commands above remain unchanged. See the official [Business Central administration center API documentation](https://learn.microsoft.com/en-us/dynamics365/business-central/dev-itpro/administration/administration-center-api) for authentication and authorization details. -These authorization requirements also apply when a **Scope Dev** deployment installs or upgrades a PTE dependency on **BC 30 or later**. Publishing primary apps through the sandbox development endpoint does not itself require these additional permissions. Deployment to earlier BC versions does not require them. +After a confirmed publishing failure, including a permissions rejection, AL-Go warns with the error and retries the remaining apps using the existing environment deployment permissions. Update the authorization above to use the preferred publishing path. Apps already installed successfully are not replayed. If an install may still be running or its outcome is unknown, deployment stops instead of submitting it again; check its status before rerunning. A failure of the fallback also fails deployment. + +This behavior also applies when a **Scope Dev** deployment installs or upgrades a PTE dependency on **BC 29 or later**. Publishing primary apps through the sandbox development endpoint does not itself require the additional authorization. Deployment to earlier BC versions is unchanged. ## Old published versions -On **BC 30 and later**, Business Central manages old-version cleanup in the background. Older published versions may remain after deployment until background cleanup runs. Cleanup has been observed after an overnight interval, leaving the installed version and the latest uninstalled version; this is not a guaranteed nightly schedule or retention policy. +For apps published through the administration center, AL-Go leaves old-version cleanup to Business Central. Older published versions may remain after deployment until background cleanup runs. On a BC 30 sandbox, cleanup was observed after an overnight interval, leaving the installed version and the latest uninstalled version; this is not a guaranteed nightly schedule or retention policy. -The optional `DeployTo.unpublishOldVersions` boolean (default `false`) does not control background cleanup. When enabled on **BC 30 and later**, AL-Go warns and skips explicit unpublish without failing deployment. No additional cleanup setting is needed. +The optional `DeployTo.unpublishOldVersions` boolean (default `false`) does not control background cleanup. When enabled, AL-Go warns and skips explicit unpublish for apps published through the administration center without failing deployment. -On **BC 25.4 through 29**, enabling the setting removes only selected apps' uninstalled versions older than their currently installed version after successful **Scope PTE** publishing. Cleanup errors remain warnings, and the setting does not apply to Scope Dev or custom deployments. +For Automation publishing, including fallback on **BC 29 and later**, enabling the setting removes only selected apps' uninstalled versions older than their currently installed version after successful **Scope PTE** publishing. This requires **BC 25.4 or later**. In a mixed-path deployment, only Automation apps are explicitly cleaned. If any version of an app was published through the administration center during the action, that app remains excluded from explicit cleanup, including across dependency and primary-app batches. On BC 29+, apps skipped because an equal or newer version is already installed are excluded unless the action already recorded a successful Automation publish for that app. Cleanup errors remain warnings, and the setting does not apply to Scope Dev or custom deployments. ## Custom Deployments From 46aa4bb415f96c345ef1010fa9546d9607517db7 Mon Sep 17 00:00:00 2001 From: spetersenms Date: Thu, 12 Nov 2026 16:05:26 +0100 Subject: [PATCH 06/12] Various cleanup of logic. --- Actions/.Modules/AdminCenterApi.psm1 | 121 +++- Actions/.Modules/ReadSettings.psm1 | 2 + Actions/.Modules/settings.schema.json | 15 +- Actions/Deploy/Deploy.ps1 | 23 +- Actions/Deploy/Deploy.psm1 | 204 +++---- Actions/Deploy/README.md | 4 +- RELEASENOTES.md | 4 +- Scenarios/RegisterProductionEnvironment.md | 2 +- Scenarios/RegisterSandboxEnvironment.md | 2 +- Scenarios/settings.md | 6 +- Tests/AdminCenterApi.Test.ps1 | 316 ++++++++++- Tests/Deploy.Action.Test.ps1 | 218 +++++++- Tests/Deploy.Module.Test.ps1 | 33 +- Tests/PublishPTEApps.Test.ps1 | 619 ++++++++++++--------- Tests/ReadSettings.Test.ps1 | 12 + Tests/UnpublishOldAppVersions.Test.ps1 | 70 ++- Workshop/ContinuousDeployment.md | 21 +- 17 files changed, 1252 insertions(+), 420 deletions(-) diff --git a/Actions/.Modules/AdminCenterApi.psm1 b/Actions/.Modules/AdminCenterApi.psm1 index 9689936aa8..94a32c73d0 100644 --- a/Actions/.Modules/AdminCenterApi.psm1 +++ b/Actions/.Modules/AdminCenterApi.psm1 @@ -2,6 +2,71 @@ $errorActionPreference = "Stop"; $ProgressPreference = "SilentlyContinue"; Set-S # Pin the contract AL-Go implements; update this with its callers and contract tests. $adminCenterApiVersion = 'v2.29' +$script:adminCenterAuthContext = $null +$script:adminCenterSourceContext = $null +$script:adminCenterTarget = $null + +<# + .SYNOPSIS + Prepare the Admin Center target and authentication context for this Deploy action. + .DESCRIPTION + Native requests using this original BCH context share the owned target and Admin context. + .PARAMETER bcAuthContext + Original BCH authentication context, retained unchanged. + .PARAMETER settings + AL-Go settings containing the native API root and application family. + .PARAMETER preserveScopes + Preserve explicitly supplied AUTHCONTEXT scopes or resource instead of using the native root. +#> +function Initialize-AdminCenterAuthContext { + Param( + [hashtable] $bcAuthContext, + [hashtable] $settings = @{}, + [switch] $preserveScopes + ) + + $target = Get-DeploymentTarget -settings $settings + $adminContext = $bcAuthContext.Clone() + $scopes = if ($preserveScopes) { $adminContext['Scopes'] } else { "$($target.apiBaseUrl)/" } + if ($adminContext['Scopes'] -ne $scopes) { + $adminContext['Scopes'] = $scopes + $adminContext['UtcExpiresOn'] = [DateTime]::MinValue + } + $script:adminCenterAuthContext = $adminContext + $script:adminCenterSourceContext = $bcAuthContext + $script:adminCenterTarget = $target +} + +<# + .SYNOPSIS + Resolve the repository's native Admin Center API root and application family. + .PARAMETER settings + AL-Go repository settings. +#> +function Get-DeploymentTarget { + Param( + [hashtable] $settings = @{} + ) + + $apiBaseUrl = 'https://api.businesscentral.dynamics.com' + if ($settings.ContainsKey('deploymentBaseUrl') -and $settings['deploymentBaseUrl'] -isnot [string]) { + throw 'deploymentBaseUrl must be a string.' + } + if ($settings['deploymentBaseUrl']) { $apiBaseUrl = [string]$settings['deploymentBaseUrl'] } + $uri = $null + if (![Uri]::TryCreate($apiBaseUrl, [UriKind]::Absolute, [ref]$uri) -or + $uri.Scheme -ne 'https' -or $uri.UserInfo -or $uri.Query -or $uri.Fragment) { + throw 'deploymentBaseUrl must be an absolute HTTPS API root without credentials, query or fragment.' + } + $applicationFamily = 'BusinessCentral' + if ($settings.ContainsKey('deploymentApplicationFamily')) { + $applicationFamily = $settings['deploymentApplicationFamily'] + if ($applicationFamily -isnot [string] -or [string]::IsNullOrWhiteSpace($applicationFamily)) { + throw 'deploymentApplicationFamily must be a nonempty string.' + } + } + return @{ apiBaseUrl = $apiBaseUrl.TrimEnd('/'); applicationFamily = $applicationFamily } +} <# .SYNOPSIS @@ -10,15 +75,18 @@ $adminCenterApiVersion = 'v2.29' Application family containing the environment. .PARAMETER environment Target environment name. + .PARAMETER apiBaseUrl + Native Admin Center API root, independent of BcContainerHelper configuration. #> function Get-AdminCenterApiUrl { Param( [string] $applicationFamily = 'BusinessCentral', [Parameter(Mandatory = $true)] - [string] $environment + [string] $environment, + [string] $apiBaseUrl = 'https://api.businesscentral.dynamics.com' ) - return "https://api.businesscentral.dynamics.com/admin/$adminCenterApiVersion/applications/$([Uri]::EscapeDataString($applicationFamily))/environments/$([Uri]::EscapeDataString($environment))" + return "$($apiBaseUrl.TrimEnd('/'))/admin/$adminCenterApiVersion/applications/$([Uri]::EscapeDataString($applicationFamily))/environments/$([Uri]::EscapeDataString($environment))" } <# @@ -63,6 +131,8 @@ function Get-AdminCenterApiErrorMessage { Send one authenticated Admin Center request without retries. .DESCRIPTION Preserves HTTP errors and records whether sending was attempted in Exception.Data. + Uses the initialized Deploy target unless explicitly overridden and retains renewed authentication. + Other callers use standard target defaults and their supplied context without changing action state. .PARAMETER bcAuthContext Authentication context to renew. .PARAMETER environment @@ -79,6 +149,8 @@ function Get-AdminCenterApiErrorMessage { Maximum duration of this request. .PARAMETER applicationFamily Target application family. + .PARAMETER apiBaseUrl + Target API root. #> function Invoke-AdminCenterApi { Param( @@ -91,19 +163,28 @@ function Invoke-AdminCenterApi { [string] $contentType, [ValidateRange(1, 300)] [int] $timeoutSeconds = 30, - [string] $applicationFamily = 'BusinessCentral' + [string] $applicationFamily = 'BusinessCentral', + [string] $apiBaseUrl = 'https://api.businesscentral.dynamics.com' ) $requestStarted = $false try { - $uri = Get-AdminCenterApiUrl -environment $environment -applicationFamily $applicationFamily + $actionContext = $null -ne $script:adminCenterAuthContext -and + [object]::ReferenceEquals($bcAuthContext, $script:adminCenterSourceContext) + if ($actionContext) { + if (!$PSBoundParameters.ContainsKey('apiBaseUrl')) { $apiBaseUrl = $script:adminCenterTarget.apiBaseUrl } + if (!$PSBoundParameters.ContainsKey('applicationFamily')) { $applicationFamily = $script:adminCenterTarget.applicationFamily } + } + $uri = Get-AdminCenterApiUrl -environment $environment -applicationFamily $applicationFamily -apiBaseUrl $apiBaseUrl $uri += '/' + (($path | ForEach-Object { [Uri]::EscapeDataString($_) }) -join '/') - $authContext = Renew-BcAuthContext -bcAuthContext $bcAuthContext + $adminContext = if ($actionContext) { $script:adminCenterAuthContext } else { $bcAuthContext.Clone() } + $authContext = Renew-BcAuthContext -bcAuthContext $adminContext if (!$authContext -or !$authContext['AccessToken']) { throw [System.Management.Automation.ErrorRecord]::new( [System.Security.Authentication.AuthenticationException]::new('Authentication failed before Admin Center request.'), 'AdminCenterAuthenticationFailed', 'AuthenticationError', $null) } + if ($actionContext) { $script:adminCenterAuthContext = $authContext } Write-Host "::add-mask::$($authContext.AccessToken)" $parameters = @{ Uri = $uri @@ -140,6 +221,8 @@ function Invoke-AdminCenterApi { Admin Center schema synchronization mode, Add or ForceSync. .PARAMETER applicationFamily Target application family. + .PARAMETER apiBaseUrl + Target API root. #> function Install-AdminCenterPTE { Param( @@ -148,7 +231,8 @@ function Install-AdminCenterPTE { [string] $appFile, [ValidateSet('Add', 'ForceSync')] [string] $syncMode = 'Add', - [string] $applicationFamily = 'BusinessCentral' + [string] $applicationFamily = 'BusinessCentral', + [string] $apiBaseUrl = 'https://api.businesscentral.dynamics.com' ) $multipart = $null @@ -168,7 +252,10 @@ function Install-AdminCenterPTE { $multipart.Add([System.Net.Http.StringContent]::new($fields[$field]), $field) } $bytes = $multipart.ReadAsByteArrayAsync().GetAwaiter().GetResult() - Invoke-AdminCenterApi -bcAuthContext $bcAuthContext -environment $environment -applicationFamily $applicationFamily ` + $parameters = @{} + $PSBoundParameters + $parameters.Remove('appFile') + $parameters.Remove('syncMode') + Invoke-AdminCenterApi @parameters ` -path @('apps', 'pteInstall') -method Post -body $bytes -contentType $multipart.Headers.ContentType.ToString() -timeoutSeconds 300 } finally { @@ -191,6 +278,8 @@ function Install-AdminCenterPTE { Maximum duration of this status request. .PARAMETER applicationFamily Target application family. + .PARAMETER apiBaseUrl + Target API root. #> function Get-AdminCenterAppOperation { Param( @@ -200,11 +289,14 @@ function Get-AdminCenterAppOperation { [string] $operationId, [ValidateRange(1, 30)] [int] $timeoutSeconds = 30, - [string] $applicationFamily = 'BusinessCentral' + [string] $applicationFamily = 'BusinessCentral', + [string] $apiBaseUrl = 'https://api.businesscentral.dynamics.com' ) - Invoke-AdminCenterApi -bcAuthContext $bcAuthContext -environment $environment -applicationFamily $applicationFamily ` - -path @('apps', $appId, 'operations', $operationId) -timeoutSeconds $timeoutSeconds + $parameters = @{} + $PSBoundParameters + $parameters.Remove('appId') + $parameters.Remove('operationId') + Invoke-AdminCenterApi @parameters -path @('apps', $appId, 'operations', $operationId) } <# @@ -222,15 +314,18 @@ function Get-AdminCenterAppOperation { Target environment. .PARAMETER applicationFamily Target application family. + .PARAMETER apiBaseUrl + Target API root. #> function Get-AdminCenterInstalledExtensions { Param( [hashtable] $bcAuthContext, [string] $environment, - [string] $applicationFamily = 'BusinessCentral' + [string] $applicationFamily = 'BusinessCentral', + [string] $apiBaseUrl = 'https://api.businesscentral.dynamics.com' ) - $response = Invoke-AdminCenterApi -bcAuthContext $bcAuthContext -environment $environment -applicationFamily $applicationFamily -path @('apps') + $response = Invoke-AdminCenterApi @PSBoundParameters -path @('apps') $response = $response | ConvertTo-HashTable -recurse if ($response -isnot [hashtable] -or !$response.ContainsKey('value') -or $response['value'] -isnot [array]) { throw 'Admin Center installed-app response must contain an apps array.' @@ -267,4 +362,4 @@ function Get-AdminCenterInstalledExtensions { } } -Export-ModuleMember -Function Get-AdminCenterApiUrl, Get-AdminCenterApiErrorMessage, Invoke-AdminCenterApi, Install-AdminCenterPTE, Get-AdminCenterAppOperation, Get-AdminCenterInstalledExtensions +Export-ModuleMember -Function Initialize-AdminCenterAuthContext, Get-AdminCenterApiUrl, Get-AdminCenterApiErrorMessage, Invoke-AdminCenterApi, Install-AdminCenterPTE, Get-AdminCenterAppOperation, Get-AdminCenterInstalledExtensions diff --git a/Actions/.Modules/ReadSettings.psm1 b/Actions/.Modules/ReadSettings.psm1 index 8cb88c35ff..c61d846e25 100644 --- a/Actions/.Modules/ReadSettings.psm1 +++ b/Actions/.Modules/ReadSettings.psm1 @@ -322,6 +322,8 @@ function GetDefaultSettings } "pullRequestTrigger" = "pull_request" "skipDraftPullRequests" = $false + "deploymentBaseUrl" = "" + "deploymentApplicationFamily" = "BusinessCentral" "bcptThresholds" = [ordered]@{ "DurationWarning" = 10 "DurationError" = 25 diff --git a/Actions/.Modules/settings.schema.json b/Actions/.Modules/settings.schema.json index 9b75e55c88..1dc04be56c 100644 --- a/Actions/.Modules/settings.schema.json +++ b/Actions/.Modules/settings.schema.json @@ -3,6 +3,19 @@ "description": "Schema for AL-Go settings", "type": "object", "properties": { + "deploymentBaseUrl": { + "type": "string", + "default": "", + "pattern": "^(|https://[^\\s?#]+)$", + "description": "Optional repository API root for native Admin Center reads, PTE publishing and polling in the standard Deploy action in both templates (CI/CD and Publish To Environment). Empty uses https://api.businesscentral.dynamics.com, independently of BcContainerHelper configuration. Sets the default resource for an isolated Admin authentication context; explicit AUTHCONTEXT scopes or resource are preserved. Does not change Automation, AppSource or web-client configuration. See https://aka.ms/ALGoSettings#deploymentBaseUrl" + }, + "deploymentApplicationFamily": { + "type": "string", + "minLength": 1, + "pattern": "\\S", + "default": "BusinessCentral", + "description": "Repository application family used by Admin Center installed-app reads, PTE publishing and operation polling in the standard Deploy action in both templates (CI/CD and Publish To Environment). Independent of deploymentBaseUrl; never inferred from its hostname. Automation URLs do not contain a family segment. See https://aka.ms/ALGoSettings#deploymentApplicationFamily" + }, "type": { "type": "string", "minLength": 1, @@ -990,7 +1003,7 @@ "unpublishOldVersions": { "type": "boolean", "default": false, - "description": "Optional boolean, default false. After successful Scope PTE deployment through Automation on Business Central 25.4 or later, including fallback, unpublishes only selected apps' uninstalled versions older than the currently installed version. Apps published through Admin Center anywhere in the action are excluded from explicit cleanup; Business Central manages their background cleanup, whose timing and retained versions are not guaranteed. On BC 29 and later, skipped apps without a recorded Automation success are also excluded. Mixed-path deployments clean only eligible Automation apps. This setting does not control background cleanup. Skipped cleanup and cleanup failures are warnings; does not apply to Scope Dev or custom deployments. See https://aka.ms/ALGoSettings#deployto" + "description": "Optional boolean, default false. After successful Scope PTE deployment through Automation on Business Central 25.4 or later, unpublishes only selected primary apps' uninstalled versions older than the currently installed version, including apps skipped because the same or a newer version is installed. With the Admin Center route, explicit cleanup is skipped; Business Central manages background cleanup, whose timing and retained versions are not guaranteed. This setting does not control background cleanup. Skipped cleanup and cleanup failures are warnings; does not apply to Scope Dev or custom deployments. See https://aka.ms/ALGoSettings#deployto" } } } diff --git a/Actions/Deploy/Deploy.ps1 b/Actions/Deploy/Deploy.ps1 index 682913568a..1d60d5a1a7 100644 --- a/Actions/Deploy/Deploy.ps1 +++ b/Actions/Deploy/Deploy.ps1 @@ -15,6 +15,7 @@ Param( ) Import-Module (Join-Path -Path $PSScriptRoot "Deploy.psm1") +Import-Module (Join-Path $PSScriptRoot '..\.Modules\AdminCenterApi.psm1') -DisableNameChecking . (Join-Path -Path $PSScriptRoot -ChildPath "..\AL-Go-Helper.ps1" -Resolve) DownloadAndImportBcContainerHelper @@ -124,6 +125,8 @@ else { if ($null -eq $bcAuthContext) { throw "Authentication failed" } + Initialize-AdminCenterAuthContext -bcAuthContext $bcAuthContext -settings $settings ` + -preserveScopes:([bool]($authContextParams['scopes'] -or $authContextParams['resource'])) } catch { throw "Authentication failed. $([environment]::Newline) $($_.exception.message)" } @@ -167,9 +170,21 @@ else { Write-Host "::Warning::Ignoring environment $($deploymentSettings.EnvironmentName), which is a production environment, as deploying from a PR is only supported in sandbox environments" } else { - $publishingResults = @{} + $hasPTEDependencies = $false + if ($scope -eq 'Dev' -and $deploymentSettings.DependencyInstallMode -ne 'ignore') { + foreach ($dependency in $dependencies) { + $appJson = Get-AppJsonFromAppFile -appFile $dependency + if ($appJson.idRanges.from -ge 50000 -and $appJson.idRanges.from -lt 100000) { + $hasPTEDependencies = $true + break + } + } + } + if ($scope -eq 'PTE' -or $hasPTEDependencies) { + Initialize-PTEPublishingApi -bcAuthContext $bcAuthContext -environment $deploymentSettings.EnvironmentName + } if ($dependencies) { - InstallOrUpgradeApps -bcAuthContext $bcAuthContext -environment $deploymentSettings.EnvironmentName -Apps $dependencies -installMode $deploymentSettings.DependencyInstallMode -publishingResults $publishingResults + InstallOrUpgradeApps -bcAuthContext $bcAuthContext -environment $deploymentSettings.EnvironmentName -Apps $dependencies -installMode $deploymentSettings.DependencyInstallMode } if ($unknownDependencies) { InstallUnknownDependencies -bcAuthContext $bcAuthContext -environment $deploymentSettings.EnvironmentName -Apps $unknownDependencies -installMode $deploymentSettings.DependencyInstallMode @@ -194,12 +209,10 @@ else { Publish-BcContainerApp @parameters -useDevEndpoint -checkAlreadyInstalled -excludeRuntimePackages -replacePackageId } else { - # The shared AL-Go publisher selects the API based on the target environment version. $parameters = @{ "bcAuthContext" = $bcAuthContext "environment" = $deploymentSettings.EnvironmentName "appFiles" = $apps - "publishingResults" = $publishingResults } if ($deploymentSettings.SyncMode) { if (@('Add','ForceSync') -notcontains $deploymentSettings.SyncMode) { @@ -218,7 +231,7 @@ else { if (($deploymentSettings['unpublishOldVersions'] -is [bool]) -and $deploymentSettings['unpublishOldVersions']) { Write-Host "Checking cleanup of old app versions" - UnpublishOldAppVersions -bcAuthContext $bcAuthContext -environment $deploymentSettings.EnvironmentName -appFiles $apps -publishingResults $publishingResults + UnpublishOldAppVersions -bcAuthContext $bcAuthContext -environment $deploymentSettings.EnvironmentName -appFiles $apps } } } diff --git a/Actions/Deploy/Deploy.psm1 b/Actions/Deploy/Deploy.psm1 index 9d75751941..8c95683b15 100644 --- a/Actions/Deploy/Deploy.psm1 +++ b/Actions/Deploy/Deploy.psm1 @@ -1,6 +1,19 @@ . (Join-Path -Path $PSScriptRoot -ChildPath "..\AL-Go-Helper.ps1" -Resolve) Import-Module (Join-Path $PSScriptRoot '..\.Modules\AdminCenterApi.psm1') -Force -DisableNameChecking +$script:ptePublishingApi = '' + +function Test-AdminCenterAuthorizationError { + Param([System.Management.Automation.ErrorRecord] $errorRecord) + + $statusCode = 0 + if ($errorRecord.Exception.PSObject.Properties['Response'] -and $errorRecord.Exception.Response) { + $statusCode = [int]$errorRecord.Exception.Response.StatusCode + } + return $statusCode -in 401,403 -or + ($errorRecord.FullyQualifiedErrorId -split ',')[0] -eq 'AdminCenterAuthenticationFailed' +} + <# .SYNOPSIS Get the head ref from a PR @@ -272,33 +285,59 @@ function GetPTEApplicationVersion { <# .SYNOPSIS - Prefer Admin Center installed apps, falling back to the read-only Automation API. + Read installed apps using the selected API, or the original BCH API for non-PTE work. .PARAMETER bcAuthContext Business Central authentication context. .PARAMETER environment Target environment. - .PARAMETER requireApplicationVersion - Validate the unique installed Application version before accepting the Admin snapshot. + .PARAMETER publishingApi + Optional explicit read API. By default uses the selected PTE API, or BCH before selection. #> function GetInstalledExtensions { Param( [hashtable] $bcAuthContext, [string] $environment, - [switch] $requireApplicationVersion + [ValidateSet('', 'AdminCenter', 'Automation')] + [string] $publishingApi = $script:ptePublishingApi + ) + + if ($publishingApi -eq 'AdminCenter') { + return Get-AdminCenterInstalledExtensions -bcAuthContext $bcAuthContext -environment $environment + } + return Get-BcInstalledExtensions -bcAuthContext $bcAuthContext -environment $environment | Where-Object { $_.isInstalled } +} + +<# + .SYNOPSIS + Select the PTE publishing API once, before this action publishes any PTEs. + .PARAMETER bcAuthContext + Business Central authentication context. + .PARAMETER environment + Target environment. +#> +function Initialize-PTEPublishingApi { + Param( + [hashtable] $bcAuthContext, + [string] $environment ) + $publishingApi = 'AdminCenter' try { $extensions = @(Get-AdminCenterInstalledExtensions -bcAuthContext $bcAuthContext -environment $environment) - if ($requireApplicationVersion) { - GetPTEApplicationVersion -extensions $extensions -environment $environment | Out-Null - } - return $extensions } catch { + if (!(Test-AdminCenterAuthorizationError -errorRecord $_)) { throw } $details = Get-AdminCenterApiErrorMessage -errorRecord $_ - Write-Host "Admin Center installed-app read failed: $details. Using the read-only Automation API. For access errors, see https://github.com/microsoft/AL-Go/blob/main/Workshop/ContinuousDeployment.md#pte-deployment-authorization" + OutputWarning -message "Admin Center authorization failed: $details. Update your administration center permissions: https://github.com/microsoft/AL-Go/blob/main/Workshop/ContinuousDeployment.md#pte-deployment-authorization. Using the Automation API for PTE publishing throughout this Deploy action." + $publishingApi = 'Automation' + $extensions = @(GetInstalledExtensions -bcAuthContext $bcAuthContext -environment $environment -publishingApi $publishingApi) } - return Get-BcInstalledExtensions -bcAuthContext $bcAuthContext -environment $environment | Where-Object { $_.isInstalled } + $applicationVersion = GetPTEApplicationVersion -extensions $extensions -environment $environment + if ($applicationVersion -lt [version]'29.0.0.0') { + $publishingApi = 'Automation' + } + Write-Host "Target BC $applicationVersion - using $publishingApi for PTE publishing throughout this Deploy action" + $script:ptePublishingApi = $publishingApi } <# @@ -402,16 +441,10 @@ function WaitPTEOperation { <# .SYNOPSIS - Publish primary apps or PTE dependencies using the target BC version. + Publish primary apps or PTE dependencies through the action-selected API. .DESCRIPTION - Below BC 29, delegates publishing to the released BcContainerHelper Automation implementation. - On BC 29 and later, AL-Go prefers Admin Center publishing and falls back to one Automation - batch only for authentication or authorization failures before any Admin publish succeeds. - Deployment failures and uncertain outcomes stop without fallback. - Existing helper utilities expand packages, exclude runtime - packages and order dependencies. Same or newer installed versions are skipped. - Installed apps and the Application version are read from Admin Center first. A failed - read or invalid Application version falls back to the read-only Automation API. + Delegates the original packages to BcContainerHelper or the Admin Center batch publisher, + as selected at Deploy initialization before PTE operations. Failures never switch APIs. .PARAMETER bcAuthContext Business Central authentication context. .PARAMETER environment @@ -420,9 +453,6 @@ function WaitPTEOperation { App packages or archives to publish. .PARAMETER schemaSyncMode Existing helper-compatible sync mode: Add or Force (mapped to ForceSync for Admin Center). - .PARAMETER publishingResults - Action-scoped map of app IDs to publishing paths, used for optional cleanup. - Any Admin Center success protects that app from explicit cleanup for the rest of the action. #> function PublishPTEApps { Param( @@ -430,76 +460,67 @@ function PublishPTEApps { [string] $environment, [string[]] $appFiles, [ValidateSet('Add', 'Force')] - [string] $schemaSyncMode = 'Add', - [hashtable] $publishingResults = @{} + [string] $schemaSyncMode = 'Add' + ) + + if (!$script:ptePublishingApi) { + throw 'The PTE publishing API must be initialized before publishing.' + } + if ($script:ptePublishingApi -eq 'Automation') { + Publish-PerTenantExtensionApps -bcAuthContext $bcAuthContext -environment $environment -appFiles $appFiles -SchemaSyncMode $schemaSyncMode + } + elseif ($script:ptePublishingApi -eq 'AdminCenter') { + Publish-AdminCenterPTEApps -bcAuthContext $bcAuthContext -environment $environment -appFiles $appFiles -schemaSyncMode $schemaSyncMode + } + else { + throw "Invalid PTE publishing API: $script:ptePublishingApi" + } +} + +<# + .SYNOPSIS + Publish a batch of PTE packages through Admin Center. + .DESCRIPTION + Requires BC 29 or later. Expands packages, excludes runtime packages and orders dependencies. + Skips same or newer installed versions, and waits for each exact install operation before continuing. + .PARAMETER bcAuthContext + Business Central authentication context. + .PARAMETER environment + Target Business Central environment name. + .PARAMETER appFiles + App packages or archives to publish. + .PARAMETER schemaSyncMode + Existing helper-compatible sync mode: Add or Force (mapped to ForceSync). +#> +function Publish-AdminCenterPTEApps { + Param( + [hashtable] $bcAuthContext, + [string] $environment, + [string[]] $appFiles, + [ValidateSet('Add', 'Force')] + [string] $schemaSyncMode = 'Add' ) - $extensions = @(GetInstalledExtensions -bcAuthContext $bcAuthContext -environment $environment -requireApplicationVersion) + $extensions = @(Get-AdminCenterInstalledExtensions -bcAuthContext $bcAuthContext -environment $environment) $applicationVersion = GetPTEApplicationVersion -extensions $extensions -environment $environment if ($applicationVersion -lt [version]'29.0.0.0') { - Write-Host "Target BC $applicationVersion - publishing PTEs using BcContainerHelper Automation API" - Publish-PerTenantExtensionApps -bcAuthContext $bcAuthContext -environment $environment -appFiles $appFiles -SchemaSyncMode $schemaSyncMode - return + throw "Admin Center PTE publishing requires BC 29 or later; the selected API will not be changed." } - Write-Host "Target BC $applicationVersion - publishing PTEs using AL-Go Admin Center API" $tempPath = NewTemporaryFolder try { $copiedApps = @(Copy-AppFilesToFolder -appFiles $appFiles -folder $tempPath) $sortedApps = @(Sort-AppFilesByDependencies -appFiles $copiedApps -excludeRuntimePackages) - $appsToPublish = @() + $syncMode = if ($schemaSyncMode -eq 'Force') { 'ForceSync' } else { 'Add' } foreach ($appFile in $sortedApps) { $appJson = Get-AppJsonFromAppFile -appFile $appFile $appVersion = [version]$appJson.version $installedVersions = @($extensions | Where-Object { $_.id -eq $appJson.id -and $_.isInstalled } | ForEach-Object { [version]::new($_.versionMajor, $_.versionMinor, $_.versionBuild, $_.versionRevision) }) if (@($installedVersions | Where-Object { $_ -ge $appVersion }).Count -gt 0) { - Write-Host "App $($appJson.name) v$appVersion or newer is already installed or selected for this batch" - if (!$publishingResults.ContainsKey($appJson.id)) { $publishingResults[$appJson.id] = 'Skipped' } continue } - $appsToPublish += @{ appFile = $appFile; appJson = $appJson } - # Also skip duplicate versions already selected for this ordered batch. - $extensions += @{ - id = $appJson.id - displayName = $appJson.name - isInstalled = $true - versionMajor = $appVersion.Major - versionMinor = $appVersion.Minor - versionBuild = $appVersion.Build - versionRevision = $appVersion.Revision - } - } - $useLegacy = $false - $adminPublished = $false - foreach ($app in $appsToPublish) { - try { - $syncMode = if ($schemaSyncMode -eq 'Force') { 'ForceSync' } else { 'Add' } - $operation = Install-AdminCenterPTE -bcAuthContext $bcAuthContext -environment $environment -appFile $app.appFile -syncMode $syncMode - } - catch { - $statusCode = 0 - if ($_.Exception.PSObject.Properties['Response'] -and $_.Exception.Response) { - $statusCode = [int]$_.Exception.Response.StatusCode - } - $authFailure = $statusCode -in 401,403 -or - ($_.FullyQualifiedErrorId -split ',')[0] -eq 'AdminCenterAuthenticationFailed' - if ($adminPublished -or !$authFailure) { throw } - $details = Get-AdminCenterApiErrorMessage -errorRecord $_ - OutputWarning -message "Admin Center authorization failed: $details. Update your administration center permissions: https://github.com/microsoft/AL-Go/blob/main/Workshop/ContinuousDeployment.md#pte-deployment-authorization. Falling back to the Automation API for this batch." - $useLegacy = $true - break - } - WaitPTEOperation -bcAuthContext $bcAuthContext -environment $environment -operation $operation -appId $app.appJson.id - $adminPublished = $true - $publishingResults[$app.appJson.id] = 'AdminCenter' - } - if ($useLegacy) { - Publish-PerTenantExtensionApps -bcAuthContext $bcAuthContext -environment $environment -appFiles @($appsToPublish | ForEach-Object { $_.appFile }) -SchemaSyncMode $schemaSyncMode - foreach ($app in $appsToPublish) { - if ($publishingResults[$app.appJson.id] -ne 'AdminCenter') { - $publishingResults[$app.appJson.id] = 'Automation' - } - } + $operation = Install-AdminCenterPTE -bcAuthContext $bcAuthContext -environment $environment -appFile $appFile -syncMode $syncMode + WaitPTEOperation -bcAuthContext $bcAuthContext -environment $environment -operation $operation -appId $appJson.id } } finally { @@ -515,8 +536,7 @@ function PublishPTEApps { and clutter Extension Management. This function unpublishes those old versions using the automation API v2.0 Microsoft.NAV.unpublish action. Only versions that are not installed AND older than a currently installed version of the same app (matched by app id) are unpublished. Automation cleanup requires BC 25.4 or later, - including after fallback. On BC 29 and later, only apps successfully published through Automation - and not through Admin Center during this action are eligible. AL-Go skips other apps with a warning. + including after fallback. For Admin Center publishing, Business Central manages cleanup in the background. Background cleanup may be delayed; its timing and retained versions are not guaranteed. Read-only Automation API calls determine the installed Application version. @@ -529,19 +549,20 @@ function PublishPTEApps { The list of deployed app files. Only the app id is read from these files to identify which apps to clean up; for each such app, published versions are compared against the version currently installed in the environment (not the deployed artifact version), and uninstalled versions older than the installed version are unpublished. - .PARAMETER publishingResults - Caller-owned per-app publishing paths. On BC 29 and later only Automation results allow explicit cleanup. #> function UnpublishOldAppVersions { Param( [hashtable] $bcAuthContext, [string] $environment, - [string[]] $appFiles, - [hashtable] $publishingResults = @{} + [string[]] $appFiles ) OutputDebugFunctionCall try { + if ($script:ptePublishingApi -eq 'AdminCenter') { + OutputWarning -message "AL-Go skips explicit cleanup for Admin Center publishing to $environment. Business Central manages cleanup in the background, which may be delayed; cleanup timing and retained versions are not guaranteed. The deployment remains successful." + return + } # Deployed app ids read from the .app files $deployedApps = @($appFiles | ForEach-Object { $appJson = Get-AppJsonFromAppFile -appFile $_ @@ -565,14 +586,6 @@ function UnpublishOldAppVersions { $extensions = @((Invoke-RestMethod -Method Get -Uri "$companyUrl/extensions" -Headers $headers -UseBasicParsing).value) $applicationVersion = GetPTEApplicationVersion -extensions $extensions -environment $environment - if ($applicationVersion -ge [version]'29.0.0.0') { - $automationApps = @($deployedApps | Where-Object { $publishingResults[$_.Id] -eq 'Automation' }) - if ($automationApps.Count -ne $deployedApps.Count) { - OutputWarning -message "AL-Go skips explicit cleanup for apps without an exclusively Automation publishing outcome in this deployment to $environment. For Admin Center publishing, Business Central manages cleanup in the background, which may be delayed; cleanup timing and retained versions are not guaranteed. The deployment remains successful." - } - $deployedApps = $automationApps - if ($deployedApps.Count -eq 0) { return } - } if ($applicationVersion -lt [version]'25.4.0.0') { OutputWarning -message "Unpublishing old app versions requires Business Central 25.4 or later; environment $environment is running $applicationVersion." return @@ -626,16 +639,13 @@ function UnpublishOldAppVersions { The list of app files to install or upgrade. .PARAMETER installMode The mode of installation, can be 'ignore', 'upgrade', 'forceUpgrade'. - .PARAMETER publishingResults - Action-scoped per-app publishing paths shared with primary-app publishing and optional cleanup. #> function InstallOrUpgradeApps { Param( [hashtable] $bcAuthContext, [string] $environment, [string[]] $apps, - [string] $installMode, - [hashtable] $publishingResults = @{} + [string] $installMode ) OutputDebugFunctionCall @@ -649,7 +659,7 @@ function InstallOrUpgradeApps { try { Copy-AppFilesToFolder -appFiles $apps -folder $tempPath | Out-Null $apps = @(Get-ChildItem -Path $tempPath -Filter *.app | ForEach-Object { $_.FullName }) - $installedApps = GetInstalledExtensions -bcAuthContext $bcAuthContext -environment $environment + $installedApps = @(GetInstalledExtensions -bcAuthContext $bcAuthContext -environment $environment) $PTEsToInstall = @() # Run through all apps and install or upgrade AppSource apps first (and collect PTEs) foreach($app in $apps) { @@ -671,13 +681,13 @@ function InstallOrUpgradeApps { else { Install-BcAppFromAppSource -bcAuthContext $bcAuthContext -environment $environment -appId $appJson.id -acceptIsvEula -installOrUpdateNeededDependencies -allowInstallationOnProduction # Update installed apps list as dependencies may have changed / been installed - $installedApps = GetInstalledExtensions -bcAuthContext $bcAuthContext -environment $environment + $installedApps = @(GetInstalledExtensions -bcAuthContext $bcAuthContext -environment $environment) } } } if ($PTEsToInstall) { # Install or upgrade PTEs - PublishPTEApps -bcAuthContext $bcAuthContext -environment $environment -appFiles $PTEsToInstall -SchemaSyncMode $schemaSyncMode -publishingResults $publishingResults + PublishPTEApps -bcAuthContext $bcAuthContext -environment $environment -appFiles $PTEsToInstall -SchemaSyncMode $schemaSyncMode } } finally { @@ -752,4 +762,4 @@ function InstallUnknownDependencies { } } -Export-ModuleMember -Function GetHeadRefFromPRId, GetAppsAndDependenciesFromArtifacts, CheckIfAppNeedsInstallOrUpgrade, CheckInstalledApps, PublishPTEApps, UnpublishOldAppVersions, InstallOrUpgradeApps, InstallUnknownDependencies +Export-ModuleMember -Function GetHeadRefFromPRId, GetAppsAndDependenciesFromArtifacts, CheckIfAppNeedsInstallOrUpgrade, CheckInstalledApps, Initialize-PTEPublishingApi, PublishPTEApps, UnpublishOldAppVersions, InstallOrUpgradeApps, InstallUnknownDependencies diff --git a/Actions/Deploy/README.md b/Actions/Deploy/README.md index 00bee37470..fc90069de6 100644 --- a/Actions/Deploy/README.md +++ b/Actions/Deploy/README.md @@ -6,10 +6,12 @@ Deploy Apps to online environment Deploys PTEs in dependency order, skipping app versions already installed or superseded. -On BC 29+, PTE deployment prefers the administration center. Configure the [required authorization](../../Workshop/ContinuousDeployment.md#pte-deployment-authorization); authentication or authorization failures can fall back only before any app in the publishing batch succeeds. Primary-app Dev publishing is unchanged. +On BC 29+, PTE deployment checks administration center access first and selects Automation only for authentication or authorization failures. The selected API is used throughout the action. Configure the [required authorization](../../Workshop/ContinuousDeployment.md#pte-deployment-authorization). Primary-app Dev publishing is unchanged. Optional `DeployTo.unpublishOldVersions` (default `false`) cleans older, uninstalled versions after Automation deployment on BC 25.4+. Administration center deployments use Business Central's background cleanup. See [cleanup details](../../Workshop/ContinuousDeployment.md#old-published-versions). +For custom Admin services, use repository settings `deploymentBaseUrl` and `deploymentApplicationFamily`; Automation keeps its BCH configuration. See [target configuration and authentication](../../Workshop/ContinuousDeployment.md#custom-deployment-targets). + ## INPUT ### ENV variables diff --git a/RELEASENOTES.md b/RELEASENOTES.md index d2751648f7..b438bf33ec 100644 --- a/RELEASENOTES.md +++ b/RELEASENOTES.md @@ -2,10 +2,12 @@ **Update your deployment authorization:** For S2S, add the `AdminCenter.ReadWrite.All` application permission, grant tenant admin consent, and register the client ID under **Authorized Microsoft Entra apps** in the Business Central administration center. See [deployment setup](Workshop/ContinuousDeployment.md#pte-deployment-authorization). -On BC 29 and later, AL-Go tries the Admin Center API first and falls back to the existing Automation API with a warning only for authentication or authorization failures before any app in the publishing batch succeeds. +On BC 29 and later, AL-Go checks Admin Center access before publishing and selects the existing Automation API with a warning only if that check fails authentication or authorization. All PTEs in the Deploy action use the selected API; publishing failures stop deployment. The Automation API's PTE upload endpoint (`extensionUpload`) is deprecated and planned for removal in 2027 release wave 1; this does not mean all Automation APIs are deprecated. See the [official deprecation notice](https://learn.microsoft.com/en-us/dynamics365/business-central/dev-itpro/administration/resources/dynamics_extensionupload). +For custom Admin services, configure repository settings `deploymentBaseUrl` and `deploymentApplicationFamily`. Automation keeps its existing BCH settings independently. See [target setup and authorization](Workshop/ContinuousDeployment.md#custom-deployment-targets). + ### Optional draft PR build skipping The new `skipDraftPullRequests` setting (default `false`) lets PTE and AppSource repositories skip AL-Go's built-in PR build jobs while a pull request is draft and build when it is marked ready for review. Custom jobs remain user-managed and are not modified. Default behavior and merge-queue builds are unchanged. Run **Update AL-Go System Files** after changing the setting. See [skipDraftPullRequests](Scenarios/settings.md#skipDraftPullRequests). diff --git a/Scenarios/RegisterProductionEnvironment.md b/Scenarios/RegisterProductionEnvironment.md index 230bf6a294..d4a85ec5fd 100644 --- a/Scenarios/RegisterProductionEnvironment.md +++ b/Scenarios/RegisterProductionEnvironment.md @@ -4,7 +4,7 @@ ## PTE publishing authorization -For the preferred PTE publishing path on BC 29 or later using S2S, add the **AdminCenter.ReadWrite.All** application permission under **Dynamics 365 Business Central**, grant tenant admin consent, and register the client ID on the Business Central administration center's **Authorized Microsoft Entra apps** page. Keep the existing environment API permissions and the Microsoft Entra application registration and required permission sets inside the Business Central environment. AL-Go warns and falls back using those environment permissions only for authentication or authorization failures before any administration center publish succeeds in the batch. Other publishing failures stop deployment. Deployment to earlier BC versions is unchanged. +For the preferred PTE publishing path on BC 29 or later using S2S, add the **AdminCenter.ReadWrite.All** application permission under **Dynamics 365 Business Central**, grant tenant admin consent, and register the client ID on the Business Central administration center's **Authorized Microsoft Entra apps** page. Keep the existing environment API permissions and the Microsoft Entra application registration and required permission sets inside the Business Central environment. AL-Go checks administration center access before PTE publishing and selects Automation with a warning only for authentication or authorization failures. The selected API is used for all PTEs in the action; publishing failures stop deployment. Deployment to earlier BC versions is unchanged. The **AUTHCONTEXT** credential structure is unchanged, including `TenantID`, `ClientID`, and `ClientSecret` for S2S. See [deployment authorization](../Workshop/ContinuousDeployment.md#pte-deployment-authorization) and the official [Business Central administration center API authentication documentation](https://learn.microsoft.com/en-us/dynamics365/business-central/dev-itpro/administration/administration-center-api). diff --git a/Scenarios/RegisterSandboxEnvironment.md b/Scenarios/RegisterSandboxEnvironment.md index ed04f509e4..f6cb894b47 100644 --- a/Scenarios/RegisterSandboxEnvironment.md +++ b/Scenarios/RegisterSandboxEnvironment.md @@ -6,7 +6,7 @@ For the preferred PTE publishing path on BC 29 or later using S2S, add the **AdminCenter.ReadWrite.All** application permission under **Dynamics 365 Business Central**, grant tenant admin consent, and register the application's client ID on the Business Central administration center's **Authorized Microsoft Entra apps** page. Retain the existing environment API permissions and Microsoft Entra application registration inside the environment, including the required permission sets. -The **AUTHCONTEXT** credential structure below is unchanged. AL-Go warns and falls back using the existing environment deployment permissions only for authentication or authorization failures before any administration center publish succeeds in the batch. Other publishing failures stop deployment. See [deployment authorization and fallback](../Workshop/ContinuousDeployment.md#pte-deployment-authorization) and the official [Business Central administration center API authentication documentation](https://learn.microsoft.com/en-us/dynamics365/business-central/dev-itpro/administration/administration-center-api). This also applies when a **Scope Dev** deployment installs or upgrades a PTE dependency on BC 29 or later. Primary-app Dev publishing and deployment to earlier BC versions do not need the additional authorization. +The **AUTHCONTEXT** credential structure below is unchanged. AL-Go checks administration center access before PTE publishing and selects Automation with a warning only for authentication or authorization failures. The selected API is used for all PTEs in the action; publishing failures stop deployment. See [deployment authorization](../Workshop/ContinuousDeployment.md#pte-deployment-authorization) and the official [Business Central administration center API authentication documentation](https://learn.microsoft.com/en-us/dynamics365/business-central/dev-itpro/administration/administration-center-api). This also applies when a **Scope Dev** deployment installs or upgrades a PTE dependency on BC 29 or later. Primary-app Dev publishing and deployment to earlier BC versions do not need the additional authorization. ## Register the environment diff --git a/Scenarios/settings.md b/Scenarios/settings.md index 9dccf20f2c..59ce8be8dd 100644 --- a/Scenarios/settings.md +++ b/Scenarios/settings.md @@ -76,8 +76,10 @@ The repository settings are only read from the repository settings file (.github | githubRunner | Specifies which github runner will be used for the build/test jobs in workflows including a build job. This is the most time consuming task. By default this job uses the _Windows-latest_ github runner (unless overridden by the runs-on setting). This settings takes precedence over runs-on so that you can use different runners for the build job and the housekeeping jobs. See **runs-on** setting. | | githubRunnerShell | Specifies which shell is used for build jobs in workflows including a build job. The default is to use the same as defined in **shell**. If the shell setting isn't defined, **powershell** is the default, which results in using _PowerShell 5.1_. Use **pwsh** for _PowerShell 7_. | | environments | Array of logical environment names. You can specify environments in GitHub environments or in the repo settings file. If you specify environments in the settings file, you can create your AUTHCONTEXT secret using **\\_AUTHCONTEXT**. You can specify additional information about environments in a setting called **DeployTo\** | +| deploymentBaseUrl | Optional string, default `""` (uses `https://api.businesscentral.dynamics.com`). Repository-level HTTPS API root for native Admin Center reads, PTE publishing and polling in the standard Deploy action in CI/CD and Publish To Environment in both templates. Independent of BcContainerHelper settings; Automation, AppSource and web-client configuration are unchanged. No credentials, query or fragment are allowed. Sets the default resource for an isolated Admin authentication context; explicit AUTHCONTEXT scopes or resource are preserved and must authorize the target service. See [custom deployment targets](../Workshop/ContinuousDeployment.md#custom-deployment-targets). | +| deploymentApplicationFamily | Optional nonempty string, default `"BusinessCentral"`. Repository-level application family for Admin Center installed-app reads, PTE publishing and operation polling in the standard Deploy action in CI/CD and Publish To Environment in both templates. Set the service's exact family independently of `deploymentBaseUrl`; it is never inferred from the host. Automation URLs do not contain a family segment. These settings are not properties of `DeployTo`. | | DeliverTo\ | Structure with additional properties for the deliveryTarget specified. Some properties are deliveryTarget specific. The structure can contain the following properties:
**Branches** = an array of branch patterns, which are allowed to deliver to this deliveryTarget. (Default main)
**ContinuousDelivery** = boolean enabling delivery after successful CI/CD builds. Set to false to disable delivery from CI/CD; deliveries explicitly invoked by other workflows are unaffected. Default true for non-AppSource targets; see [deliverToAppSource](#deliverToAppSource) for AppSource.
**CreateContainerIfNotExist** = *[Only for DeliverToStorage]* Create Blob Storage Container if it doesn't already exist. (Default false)
| -| DeployTo\ | Structure with additional properties for the environment specified. `` refers to the GitHub environment name. The structure can contain the following properties:
**EnvironmentType** = specifies the type of environment. The environment type can be used to invoke a custom deployment. (Default SaaS)
**EnvironmentName** = specifies the "real" name of the environment if it differs from the GitHub environment.
**Branches** = an array of branch patterns, which are allowed to deploy to this environment. These branches can also be defined under the environment in GitHub settings and both settings are honored. If neither setting is defined, the default is the **main** branch only.
**Projects** = In multi-project repositories, this property can be a comma separated list of project patterns to deploy to this environment. (Default \*)
**DependencyInstallMode** = Determines how dependencies are deployed if `GenerateDependencyArtifact` is true. Default value is `install` to install dependencies if not already installed. Other values are `ignore` for ignoring dependencies and `upgrade` or `forceUpgrade` for upgrading dependencies.
**includeTestAppsInSandboxEnvironment** = deploys test apps and their dependencies if the environment type is sandbox (Default is `false`)
**excludeAppIds** = array of app ids to exclude from deployment. (Default is `[]`)
**Scope** = Determines the mechanism for deployment to the environment (Dev or PTE). If not specified, AL-Go for GitHub will always use the Dev Scope for AppSource Apps, but also for PTEs when deploying to sandbox environments when impersonation (refreshtoken) is used for authentication. On BC 29 or later, PTE publishing prefers the administration center and falls back only for authentication or authorization failures before any app in the publishing batch succeeds; other publishing failures stop deployment. See [deployment authorization and fallback](../Workshop/ContinuousDeployment.md#pte-deployment-authorization), including PTE dependencies of Scope Dev deployments.
**SyncMode** = ForceSync if deployment to this environment should happen with ForceSync, else Add. If deploying to the development endpoint you can also specify Development or Clean. (Default Add)
**unpublishOldVersions** = Optional boolean (`true` or `false`, default `false`), honored by the standard Deploy action in CI/CD and Publish To Environment for both templates after successful Scope PTE publishing. For Automation publishing on BC 25.4 or later, including fallback, unpublishes only selected apps' uninstalled versions older than the currently installed version. Apps published through the administration center anywhere in the action are excluded from explicit cleanup; Business Central manages their background cleanup, whose timing and retained versions are not guaranteed. On BC 29+, skipped apps without a recorded Automation success are also excluded. Mixed-path deployments clean only eligible Automation apps. This setting does not control background cleanup. Skipped cleanup and cleanup failures are warnings; does not apply to Scope Dev or custom deployments.
**BuildMode** = specifies which buildMode to use for the deployment. Default is to use the Default buildMode
**ContinuousDeployment** = true if this environment should be used for continuous deployment, else false. (Default: AL-Go will continuously deploy to sandbox environments or environments, which doesn't end in (PROD) or (FAT)
**runs-on** = specifies which runner to use when deploying to this environment. (Default is settings.runs-on)
**shell** = specifies which shell to use when deploying to this environment, pwsh or powershell. (Default is settings.shell)
**companyId** = Company Id from Business Central (for PowerPlatform connection)
**ppEnvironmentUrl** = Url of the PowerPlatform environment to deploy to
| +| DeployTo\ | Structure with additional properties for the environment specified. `` refers to the GitHub environment name. The structure can contain the following properties:
**EnvironmentType** = specifies the type of environment. The environment type can be used to invoke a custom deployment. (Default SaaS)
**EnvironmentName** = specifies the "real" name of the environment if it differs from the GitHub environment.
**Branches** = an array of branch patterns, which are allowed to deploy to this environment. These branches can also be defined under the environment in GitHub settings and both settings are honored. If neither setting is defined, the default is the **main** branch only.
**Projects** = In multi-project repositories, this property can be a comma separated list of project patterns to deploy to this environment. (Default \*)
**DependencyInstallMode** = Determines how dependencies are deployed if `GenerateDependencyArtifact` is true. Default value is `install` to install dependencies if not already installed. Other values are `ignore` for ignoring dependencies and `upgrade` or `forceUpgrade` for upgrading dependencies.
**includeTestAppsInSandboxEnvironment** = deploys test apps and their dependencies if the environment type is sandbox (Default is `false`)
**excludeAppIds** = array of app ids to exclude from deployment. (Default is `[]`)
**Scope** = Determines the mechanism for deployment to the environment (Dev or PTE). If not specified, AL-Go for GitHub will always use the Dev Scope for AppSource Apps, but also for PTEs when deploying to sandbox environments when impersonation (refreshtoken) is used for authentication. On BC 29 or later, AL-Go checks administration center access before PTE publishing and selects Automation only for authentication or authorization failures. All PTEs in the action use the selected API; publishing failures stop deployment. See [deployment authorization](../Workshop/ContinuousDeployment.md#pte-deployment-authorization), including PTE dependencies of Scope Dev deployments.
**SyncMode** = ForceSync if deployment to this environment should happen with ForceSync, else Add. If deploying to the development endpoint you can also specify Development or Clean. (Default Add)
**unpublishOldVersions** = Optional boolean (`true` or `false`, default `false`), honored by the standard Deploy action in CI/CD and Publish To Environment for both templates after successful Scope PTE publishing. For Automation publishing on BC 25.4 or later, unpublishes only selected primary apps' uninstalled versions older than the currently installed version, including apps skipped because the same or a newer version is installed. With the administration center route, explicit cleanup is skipped; Business Central manages background cleanup, whose timing and retained versions are not guaranteed. This setting does not control background cleanup. Skipped cleanup and cleanup failures are warnings; does not apply to Scope Dev or custom deployments.
**BuildMode** = specifies which buildMode to use for the deployment. Default is to use the Default buildMode
**ContinuousDeployment** = true if this environment should be used for continuous deployment, else false. (Default: AL-Go will continuously deploy to sandbox environments or environments, which doesn't end in (PROD) or (FAT)
**runs-on** = specifies which runner to use when deploying to this environment. (Default is settings.runs-on)
**shell** = specifies which shell to use when deploying to this environment, pwsh or powershell. (Default is settings.shell)
**companyId** = Company Id from Business Central (for PowerPlatform connection)
**ppEnvironmentUrl** = Url of the PowerPlatform environment to deploy to
| | alDoc | Structure with properties for the aldoc reference document generation. The structure can contain the following properties:
**continuousDeployment** = Determines if reference documentation will be deployed continuously as part of CI/CD. You can run the **Deploy Reference Documentation** workflow to deploy manually or on a schedule. (Default false)
**deployToGitHubPages** = Determines whether or not the reference documentation site should be deployed to GitHub Pages for the repository. In order to deploy to GitHub Pages, GitHub Pages must be enabled and set to GitHub Actuibs. (Default true)
**maxReleases** = Maximum number of releases to include in the reference documentation. (Default 3)
**groupByProject** = Determines whether projects in multi-project repositories are used as folders in reference documentation
**includeProjects** = An array of projects to include in the reference documentation. (Default all)
**excludeProjects** = An array of projects to exclude in the reference documentation. (Default none)
**header** = Header for the documentation site. (Default: Documentation for...)
**footer** = Footer for the documentation site. (Default: Made with...)
**defaultIndexMD** = Markdown for the landing page of the documentation site. (Default: Reference documentation...)
**defaultReleaseMD** = Markdown for the landing page of the release sites. (Default: Release reference documentation...)
*Note that in header, footer, defaultIndexMD and defaultReleaseMD you can use the following placeholders: {REPOSITORY}, {VERSION}, {INDEXTEMPLATERELATIVEPATH}, {RELEASENOTES}* | | useProjectDependencies | Determines whether your projects are built using a multi-stage built workflow or single stage. After setting useProjectDependencies to true, you need to run Update AL-Go System Files and your workflows including a build job will change to have multiple build jobs, depending on each other. The number of build jobs will be determined by the dependency depth in your projects.
You can change dependencies between your projects, but if the dependency **depth** changes, AL-Go will warn you that updates for your AL-Go System Files are available and you will need to run the workflow. | | CICDPushBranches | CICDPushBranches can be specified as an array of branches, which triggers a CI/CD workflow on commit. You need to run the Update AL-Go System Files workflow for the change to take effect.
Default is [ "main", "release/\*", "feature/\*" ]

**Supported release branch naming formats:**
When using release branches, AL-Go supports various naming conventions for matching previous releases during upgrade testing. The following formats are recognized:
• `releases/26` - matches releases with major version 26
• `releases/26.x` - matches releases with major version 26
• `releases/26x` - matches releases with major version 26
• `releases/v26` - matches releases with major version 26
• `releases/v26.x` - matches releases with major version 26
• `releases/v26x` - matches releases with major version 26
• `releases/26.3` - matches releases with major.minor version 26.3
The same patterns work with the singular `release/` prefix. | @@ -579,7 +581,7 @@ Note that changes to AL-Go for GitHub or Run-AlPipeline functionality in the fut | Setting | Description | Default | | :-- | :-- | :-- | | baseUrl | The Base Url for the online Business Central Web Client. This should be changed when targetting embed apps. | [https://businesscentral.dynamics.com](https://businesscentral.dynamics.com) | -| apiBaseUrl | The Base Url for the online Business Central API endpoint used by BcContainerHelper. This should be changed when targetting embed apps. This override applies to helper calls, including fallback publishing, but does not change AL-Go's preferred PTE publishing endpoint on BC 29 and later, which uses the standard Business Central service endpoint. | [https://api.businesscentral.dynamics.com](https://api.businesscentral.dynamics.com) | +| apiBaseUrl | The API root used by BcContainerHelper, including Embed services. Independent of the native Admin Center [deploymentBaseUrl](#deploymentBaseUrl). The web-client/readiness URL remains `baseUrl`. | [https://api.businesscentral.dynamics.com](https://api.businesscentral.dynamics.com) | | PartnerTelemetryConnectionString | The Telemetry Connection String for partner telemetry for DevOps telemetry. | | | SendExtendedTelemetryToMicrosoft | Set this value to true if you agree to emit extended DevOps telemetry to Microsoft. | false | | ObjectIdForInternalUse | BcContainerHelper will use this Object ID for internal purposes. Change if the default Object ID is in use. | 88123 | diff --git a/Tests/AdminCenterApi.Test.ps1 b/Tests/AdminCenterApi.Test.ps1 index df63c07790..8ed5d2b5b2 100644 --- a/Tests/AdminCenterApi.Test.ps1 +++ b/Tests/AdminCenterApi.Test.ps1 @@ -10,6 +10,9 @@ Describe 'AL-Go Admin Center API helpers' { InModuleScope AdminCenterApi { Describe 'Admin Center requests and named endpoints' { BeforeEach { + $script:adminCenterAuthContext = $null + $script:adminCenterSourceContext = $null + $script:adminCenterTarget = $null $script:packagePath = Join-Path $TestDrive 'Binary Package.app' $script:packageBytes = [byte[]]@(0,128,255,13,10) [IO.File]::WriteAllBytes($script:packagePath, $script:packageBytes) @@ -18,6 +21,12 @@ Describe 'AL-Go Admin Center API helpers' { Mock Invoke-RestMethod { return @{ id = 'operation-1' } } } + AfterEach { + $script:adminCenterAuthContext = $null + $script:adminCenterSourceContext = $null + $script:adminCenterTarget = $null + } + It 'Sends binary multipart once to the escaped endpoint with ' -TestCases @( @{ syncMode = 'Add' }, @{ syncMode = 'ForceSync' } ) { @@ -39,12 +48,12 @@ Describe 'AL-Go Admin Center API helpers' { } $result = Install-AdminCenterPTE -bcAuthContext @{ tenantId = 'tenant' } -environment 'QA / East' ` - -applicationFamily 'Family / US' -appFile $script:packagePath -syncMode $syncMode + -apiBaseUrl 'https://api.embed.test/service/' -applicationFamily 'Family / US' -appFile $script:packagePath -syncMode $syncMode $result.id | Should -Be 'operation-1' Assert-MockCalled Renew-BcAuthContext -Exactly 1 -ParameterFilter { $bcAuthContext.tenantId -eq 'tenant' } Assert-MockCalled Invoke-RestMethod -Exactly 1 -ParameterFilter { - $Uri -eq 'https://api.businesscentral.dynamics.com/admin/v2.29/applications/Family%20%2F%20US/environments/QA%20%2F%20East/apps/pteInstall' -and + $Uri -eq 'https://api.embed.test/service/admin/v2.29/applications/Family%20%2F%20US/environments/QA%20%2F%20East/apps/pteInstall' -and $Method -eq 'Post' -and $Body -is [byte[]] -and $ContentType -like 'multipart/form-data; boundary=*' -and $TimeoutSec -eq 300 -and $Headers.Authorization -eq 'Bearer test-token' -and $UseBasicParsing -and $ErrorAction -eq 'Stop' @@ -60,12 +69,256 @@ Describe 'AL-Go Admin Center API helpers' { return @{ id = 'operation / 1' } } - Get-AdminCenterAppOperation -bcAuthContext @{} -environment Sandbox -appId 'app / 1' -operationId 'operation / 1' -timeoutSeconds 7 + Get-AdminCenterAppOperation -bcAuthContext @{} -environment Sandbox -appId 'app / 1' -operationId 'operation / 1' -timeoutSeconds 7 ` + -apiBaseUrl 'https://api.embed.test' -applicationFamily 'Custom Family' Assert-MockCalled Invoke-RestMethod -Exactly 1 -ParameterFilter { $Method -eq 'Get' -and $TimeoutSec -eq 7 -and - $Uri -eq 'https://api.businesscentral.dynamics.com/admin/v2.29/applications/BusinessCentral/environments/Sandbox/apps/app%20%2F%201/operations/operation%20%2F%201' + $Uri -eq 'https://api.embed.test/admin/v2.29/applications/Custom%20Family/environments/Sandbox/apps/app%20%2F%201/operations/operation%20%2F%201' + } + } + + It 'Reads installed apps only from the configured root and explicit family' { + Mock Invoke-RestMethod { return @{ value = @() } } + + @(Get-AdminCenterInstalledExtensions -bcAuthContext @{} -environment 'QA / East' ` + -apiBaseUrl 'https://api.embed.test/service/' -applicationFamily 'Custom / Family').Count | Should -Be 0 + + Assert-MockCalled Invoke-RestMethod -Exactly 1 -ParameterFilter { + $Uri -eq 'https://api.embed.test/service/admin/v2.29/applications/Custom%20%2F%20Family/environments/QA%20%2F%20East/apps' + } + } + + It 'Renews an isolated Admin context without changing the BCH resource or token' { + $original = @{ + tenantId = 'tenant'; Scopes = 'https://legacy.test/'; AccessToken = 'legacy-token' + UtcExpiresOn = [DateTime]::UtcNow.AddHours(1) } + Initialize-AdminCenterAuthContext -bcAuthContext $original -settings @{ deploymentBaseUrl = 'https://admin.test' } + Mock Renew-BcAuthContext { + $bcAuthContext.Scopes | Should -Be 'https://admin.test/' + $bcAuthContext.UtcExpiresOn | Should -Be ([DateTime]::MinValue) + $bcAuthContext.AccessToken = 'admin-token' + return $bcAuthContext + } + + Invoke-AdminCenterApi -bcAuthContext $original -environment Sandbox -path apps -apiBaseUrl 'https://admin.test' + + $original.Scopes | Should -Be 'https://legacy.test/' + $original.AccessToken | Should -Be 'legacy-token' + $original.UtcExpiresOn | Should -BeGreaterThan ([DateTime]::UtcNow) + Assert-MockCalled Renew-BcAuthContext -Exactly 1 + Assert-MockCalled Write-Host -Exactly 1 -ParameterFilter { $Object -eq '::add-mask::admin-token' } + } + + It 'Preserves an explicit scope even when it differs from the Admin endpoint' { + $expires = [DateTime]::UtcNow.AddHours(1) + Mock Renew-BcAuthContext { + $bcAuthContext.Scopes | Should -Be 'https://explicit-resource.test/.default' + $bcAuthContext.UtcExpiresOn | Should -Be $expires + return @{ AccessToken = 'explicit-token' } + } + $original = @{ + Scopes = 'https://explicit-resource.test/.default' + UtcExpiresOn = $expires + } + Initialize-AdminCenterAuthContext -bcAuthContext $original -settings @{ deploymentBaseUrl = 'https://admin.test' } -preserveScopes + Invoke-AdminCenterApi -environment Sandbox -path apps -apiBaseUrl 'https://admin.test' -bcAuthContext $original + Assert-MockCalled Renew-BcAuthContext -Exactly 1 + } + + It 'Does not mutate the BCH context when Admin renewal fails' { + $original = @{ Scopes = 'https://legacy.test/' } + Initialize-AdminCenterAuthContext -bcAuthContext $original -settings @{ deploymentBaseUrl = 'https://admin.test' } + Mock Renew-BcAuthContext { + $bcAuthContext.Scopes = 'changed-copy' + throw [TimeoutException]::new('Renewal timed out') + } + { Invoke-AdminCenterApi -bcAuthContext $original -environment Sandbox -path apps } | Should -Throw '*Renewal timed out*' + $original.Scopes | Should -Be 'https://legacy.test/' + Assert-MockCalled Invoke-RestMethod -Times 0 + } + + It 'Uses the Admin resource in the actual BCH renewal without retargeting its original context' { + Mock Invoke-RestMethod -ModuleName BcContainerHelper { return @{ access_token = 'fake-token' } } + Mock Parse-JWTtoken -ModuleName BcContainerHelper { + return @{ appid = 'fake-client'; exp = 2000000000 } + } + $newContext = Get-Command New-BcAuthContext -Module BcContainerHelper + $original = & $newContext -tenantID fake-tenant -clientID fake-client -clientSecret fake-secret ` + -scopes 'https://legacy.test/' -silent + Initialize-AdminCenterAuthContext -bcAuthContext $original -settings @{ deploymentBaseUrl = 'https://admin.test' } + Mock Renew-BcAuthContext { + $renew = Get-Command Renew-BcAuthContext -Module BcContainerHelper + & $renew -bcAuthContext $bcAuthContext -silent + } + + Invoke-AdminCenterApi -bcAuthContext $original -environment Sandbox -path apps -apiBaseUrl 'https://admin.test' + + Assert-MockCalled Invoke-RestMethod -ModuleName BcContainerHelper -Exactly 1 -ParameterFilter { + $Body.scope -eq 'https://admin.test/.default' + } + Assert-MockCalled Invoke-RestMethod -ModuleName BcContainerHelper -Exactly 1 -ParameterFilter { + $Body.scope -eq 'https://legacy.test/.default' + } + $original.Scopes | Should -Be 'https://legacy.test/' + } + + It 'Reuses renewed native tokens across reads, upload and polling, then renews once on expiry' { + $script:tokenRequests = 0 + Mock Invoke-RestMethod -ModuleName BcContainerHelper { + $script:tokenRequests++ + return @{ access_token = "fake-token-$script:tokenRequests" } + } + Mock Parse-JWTtoken -ModuleName BcContainerHelper { + return @{ appid = 'fake-client'; exp = 2000000000 } + } + $newContext = Get-Command New-BcAuthContext -Module BcContainerHelper + $original = & $newContext -tenantID fake-tenant -clientID fake-client -clientSecret fake-secret ` + -scopes 'https://legacy.test/' -silent + $originalToken = $original.AccessToken + $originalExpiry = $original.UtcExpiresOn + $originalConfig = $bcContainerHelperConfig.apiBaseUrl + $settings = @{ deploymentBaseUrl = 'https://admin.test'; deploymentApplicationFamily = 'Family / US' } + Initialize-AdminCenterAuthContext -bcAuthContext $original -settings $settings + $settings.deploymentBaseUrl = 'https://changed-after-initialization.test' + Mock Renew-BcAuthContext { + $renew = Get-Command Renew-BcAuthContext -Module BcContainerHelper + & $renew -bcAuthContext $bcAuthContext -silent + } + Mock Invoke-RestMethod { return @{ value = @(); id = 'operation-1' } } + + Get-AdminCenterInstalledExtensions -bcAuthContext $original -environment Sandbox | Out-Null + Install-AdminCenterPTE -bcAuthContext $original -environment Sandbox -appFile $script:packagePath | Out-Null + Get-AdminCenterAppOperation -bcAuthContext $original -environment Sandbox -appId app -operationId operation | Out-Null + + Assert-MockCalled Invoke-RestMethod -ModuleName BcContainerHelper -Exactly 1 -ParameterFilter { + $Body.scope -eq 'https://admin.test/.default' + } + Assert-MockCalled Invoke-RestMethod -Exactly 3 -ParameterFilter { + $Headers.Authorization -eq 'Bearer fake-token-2' -and + ([Uri]$Uri).AbsoluteUri -like 'https://admin.test/admin/v2.29/applications/Family%20%2F%20US/environments/Sandbox/apps*' + } + Assert-MockCalled Invoke-RestMethod -Exactly 1 -ParameterFilter { $Uri -like '*/apps' } + Assert-MockCalled Invoke-RestMethod -Exactly 1 -ParameterFilter { $Uri -like '*/apps/pteInstall' } + Assert-MockCalled Invoke-RestMethod -Exactly 1 -ParameterFilter { $Uri -like '*/apps/app/operations/operation' } + $script:adminCenterAuthContext.UtcExpiresOn = [DateTime]::MinValue + Invoke-AdminCenterApi -bcAuthContext $original -environment Sandbox -path apps | Out-Null + Invoke-AdminCenterApi -bcAuthContext $original -environment Sandbox -path apps | Out-Null + + Assert-MockCalled Invoke-RestMethod -ModuleName BcContainerHelper -Exactly 2 -ParameterFilter { + $Body.scope -eq 'https://admin.test/.default' + } + Assert-MockCalled Invoke-RestMethod -Exactly 2 -ParameterFilter { + $Headers.Authorization -eq 'Bearer fake-token-3' + } + $original.AccessToken | Should -Be $originalToken + $original.UtcExpiresOn | Should -Be $originalExpiry + $original.Scopes | Should -Be 'https://legacy.test/' + $bcContainerHelperConfig.apiBaseUrl | Should -Be $originalConfig + } + + It 'Reuses a valid same-resource token without a token exchange' { + Mock Renew-BcAuthContext { + $renew = Get-Command Renew-BcAuthContext -Module BcContainerHelper + & $renew -bcAuthContext $bcAuthContext -silent + } + $newContext = Get-Command New-BcAuthContext -Module BcContainerHelper + Mock Parse-JWTtoken -ModuleName BcContainerHelper { return @{ appid = 'fake-client'; exp = 2000000000 } } + Mock Invoke-RestMethod -ModuleName BcContainerHelper { return @{ access_token = 'valid-token' } } + $original = & $newContext -tenantID fake-tenant -clientID fake-client -clientSecret fake-secret -silent + Initialize-AdminCenterAuthContext -bcAuthContext $original + + Invoke-AdminCenterApi -bcAuthContext $original -environment Sandbox -path apps | Out-Null + Invoke-AdminCenterApi -bcAuthContext $original -environment Sandbox -path apps | Out-Null + + Assert-MockCalled Invoke-RestMethod -ModuleName BcContainerHelper -Exactly 1 + Assert-MockCalled Invoke-RestMethod -Exactly 2 -ParameterFilter { $Headers.Authorization -eq 'Bearer valid-token' } + } + + It 'Overwrites target and auth together on initialization without affecting direct callers' { + $first = @{ Scopes = 'https://first.test/'; AccessToken = 'first-token' } + Initialize-AdminCenterAuthContext -bcAuthContext $first -settings @{ + deploymentBaseUrl = 'https://first-admin.test'; deploymentApplicationFamily = 'FirstFamily' + } + Mock Renew-BcAuthContext { + $bcAuthContext.AccessToken = 'mutated-before-failure' + throw [TimeoutException]::new('Renewal timed out') + } + { Invoke-AdminCenterApi -bcAuthContext $first -environment First -path apps } | Should -Throw '*Renewal timed out*' + $first.AccessToken | Should -Be first-token + Assert-MockCalled Invoke-RestMethod -Times 0 + $second = @{ Scopes = 'https://second.test/'; AccessToken = 'second-token' } + Initialize-AdminCenterAuthContext -bcAuthContext $second -settings @{ + deploymentBaseUrl = 'https://second.test'; deploymentApplicationFamily = 'SecondFamily' + } + [object]::ReferenceEquals($script:adminCenterSourceContext, $second) | Should -BeTrue + [object]::ReferenceEquals($script:adminCenterAuthContext, $second) | Should -BeFalse + Mock Renew-BcAuthContext { return $bcAuthContext } + + Invoke-AdminCenterApi -bcAuthContext $second -environment Second -path apps | Out-Null + Invoke-AdminCenterApi -bcAuthContext $first -environment First -path apps | Out-Null + + Assert-MockCalled Invoke-RestMethod -Exactly 1 -ParameterFilter { + $Uri -like 'https://second.test/admin/v2.29/applications/SecondFamily/*' -and $Headers.Authorization -eq 'Bearer second-token' + } + Assert-MockCalled Invoke-RestMethod -Exactly 1 -ParameterFilter { + $Uri -like 'https://api.businesscentral.dynamics.com/admin/v2.29/applications/BusinessCentral/*' -and $Headers.Authorization -eq 'Bearer first-token' + } + $script:adminCenterAuthContext.AccessToken | Should -Be second-token + $script:adminCenterAuthContext.Scopes | Should -Be 'https://second.test/' + $script:adminCenterTarget.apiBaseUrl | Should -Be 'https://second.test' + } + + It 'Honors explicit native endpoint overrides independently of action target defaults' { + $original = @{ Scopes = 'https://action.test/'; AccessToken = 'action-token' } + Initialize-AdminCenterAuthContext -bcAuthContext $original -settings @{ + deploymentBaseUrl = 'https://action.test'; deploymentApplicationFamily = 'ActionFamily' + } + Mock Renew-BcAuthContext { return $bcAuthContext } + Mock Invoke-RestMethod { return @{ value = @(); id = 'operation' } } + Get-AdminCenterInstalledExtensions -bcAuthContext $original -environment Sandbox ` + -apiBaseUrl 'https://explicit.test' -applicationFamily 'ExplicitFamily' | Out-Null + Install-AdminCenterPTE -bcAuthContext $original -environment Sandbox -appFile $script:packagePath ` + -apiBaseUrl 'https://api.businesscentral.dynamics.com' | Out-Null + Get-AdminCenterAppOperation -bcAuthContext $original -environment Sandbox -appId app -operationId operation ` + -applicationFamily BusinessCentral | Out-Null + Invoke-AdminCenterApi -bcAuthContext $original -environment Sandbox -path apps | Out-Null + + Assert-MockCalled Invoke-RestMethod -Exactly 1 -ParameterFilter { + $Uri -eq 'https://explicit.test/admin/v2.29/applications/ExplicitFamily/environments/Sandbox/apps' + } + Assert-MockCalled Invoke-RestMethod -Exactly 1 -ParameterFilter { + $Uri -eq 'https://api.businesscentral.dynamics.com/admin/v2.29/applications/ActionFamily/environments/Sandbox/apps/pteInstall' + } + Assert-MockCalled Invoke-RestMethod -Exactly 1 -ParameterFilter { + $Uri -eq 'https://action.test/admin/v2.29/applications/BusinessCentral/environments/Sandbox/apps/app/operations/operation' + } + Assert-MockCalled Invoke-RestMethod -Exactly 1 -ParameterFilter { + $Uri -eq 'https://action.test/admin/v2.29/applications/ActionFamily/environments/Sandbox/apps' + } + $script:adminCenterTarget.apiBaseUrl | Should -Be 'https://action.test' + $script:adminCenterAuthContext.Scopes | Should -Be 'https://action.test/' + } + + It 'Keeps an unrelated direct callers explicit target and token separate from action state' { + $original = @{ Scopes = 'https://action.test/'; AccessToken = 'action-token' } + Initialize-AdminCenterAuthContext -bcAuthContext $original -settings @{ + deploymentBaseUrl = 'https://action.test'; deploymentApplicationFamily = 'ActionFamily' + } + $direct = @{ Scopes = 'https://direct.test/'; AccessToken = 'direct-token' } + Mock Renew-BcAuthContext { return $bcAuthContext } + Mock Invoke-RestMethod { return @{ value = @() } } + + Get-AdminCenterInstalledExtensions -bcAuthContext $direct -environment Sandbox ` + -apiBaseUrl 'https://direct.test' -applicationFamily DirectFamily | Out-Null + + Assert-MockCalled Invoke-RestMethod -Exactly 1 -ParameterFilter { + $Uri -eq 'https://direct.test/admin/v2.29/applications/DirectFamily/environments/Sandbox/apps' -and + $Headers.Authorization -eq 'Bearer direct-token' + } + $script:adminCenterAuthContext.AccessToken | Should -Be action-token + $script:adminCenterTarget.apiBaseUrl | Should -Be 'https://action.test' } It 'Normalizes and installed apps including scope' -TestCases @( @@ -226,6 +479,61 @@ Describe 'AL-Go Admin Center API helpers' { Should -Be 'https://api.businesscentral.dynamics.com/admin/v2.29/applications/BusinessCentral/environments/Sandbox' } + InModuleScope AdminCenterApi { + It 'Resolves API root without deriving the family from the hostname' -TestCases @( + @{ source = 'standard default'; settings = @{}; helper = @{}; expected = 'https://api.businesscentral.dynamics.com' }, + @{ source = 'default despite legacy override'; settings = @{}; helper = @{ apiBaseUrl = 'https://legacy.test/' }; expected = 'https://api.businesscentral.dynamics.com' }, + @{ source = 'explicit deployment setting'; settings = @{ deploymentBaseUrl = 'https://deploy.test/root/' }; helper = @{ apiBaseUrl = 'https://legacy.test' }; expected = 'https://deploy.test/root' }, + @{ source = 'empty setting despite legacy override'; settings = @{ deploymentBaseUrl = '' }; helper = @{ apiBaseUrl = 'https://legacy.test/' }; expected = 'https://api.businesscentral.dynamics.com' } + ) { + param($settings, $helper, $expected) + + $bcContainerHelperConfig = $helper + $target = Get-DeploymentTarget -settings $settings + + $target.apiBaseUrl | Should -Be $expected + $target.applicationFamily | Should -Be 'BusinessCentral' + $bcContainerHelperConfig | Should -Be $helper + } + + It 'Resolves family independently and does not retain settings between invocations' { + $settings = @{ deploymentBaseUrl = 'https://custom.test'; deploymentApplicationFamily = 'Family / One' } + $helper = @{ apiBaseUrl = 'https://legacy.test' } + $first = Get-DeploymentTarget -settings $settings + $second = Get-DeploymentTarget + + $first.applicationFamily | Should -Be 'Family / One' + $second.applicationFamily | Should -Be 'BusinessCentral' + $second.apiBaseUrl | Should -Be 'https://api.businesscentral.dynamics.com' + $helper.apiBaseUrl | Should -Be 'https://legacy.test' + $settings.deploymentBaseUrl | Should -Be 'https://custom.test' + } + + It 'Rejects invalid API root without including it in the error' -TestCases @( + @{ root = 'http://custom.test' }, @{ root = 'relative/path' }, @{ root = 'https://user:private@custom.test' }, + @{ root = 'https://custom.test?private=value' }, @{ root = 'https://custom.test#fragment' } + ) { + param($root) + $invalidSettings = @{ deploymentBaseUrl = $root } + { Get-DeploymentTarget -settings $invalidSettings } | + Should -Throw 'deploymentBaseUrl must be an absolute HTTPS API root without credentials, query or fragment.' + } + + It 'Rejects an empty explicit application family' { + { Get-DeploymentTarget -settings @{ deploymentApplicationFamily = ' ' } } | + Should -Throw '*deploymentApplicationFamily must be a nonempty string*' + } + + It 'Rejects non-string explicit settings rather than silently selecting the standard service' { + { Get-DeploymentTarget -settings @{ deploymentBaseUrl = $null } } | Should -Throw '*deploymentBaseUrl must be a string*' + { Get-DeploymentTarget -settings @{ deploymentApplicationFamily = @('One', 'Two') } } | Should -Throw '*deploymentApplicationFamily must be a nonempty string*' + } + } + + It 'Keeps target resolution private to native initialization' { + (Get-Module AdminCenterApi).ExportedFunctions.Keys | Should -Not -Contain 'Get-DeploymentTarget' + } + It 'Preserves exception and plain service messages on one log line' { $exception = [System.Exception]::new('403 Forbidden') $record = [System.Management.Automation.ErrorRecord]::new($exception, 'Denied', 'PermissionDenied', $null) diff --git a/Tests/Deploy.Action.Test.ps1 b/Tests/Deploy.Action.Test.ps1 index c9a0c1b252..edb3c6618a 100644 --- a/Tests/Deploy.Action.Test.ps1 +++ b/Tests/Deploy.Action.Test.ps1 @@ -1,4 +1,4 @@ -Get-Module TestActionsHelper | Remove-Module -Force +Get-Module TestActionsHelper | Remove-Module -Force Import-Module (Join-Path $PSScriptRoot 'TestActionsHelper.psm1') $errorActionPreference = "Stop"; $ProgressPreference = "SilentlyContinue"; Set-StrictMode -Version 2.0 @@ -27,16 +27,19 @@ Describe "Deploy Action Tests" { Context "unpublishOldVersions wiring" { BeforeAll { Import-Module (Join-Path $scriptRoot "Deploy.psm1") -Force + Import-Module (Join-Path $scriptRoot "..\.Modules\AdminCenterApi.psm1") -DisableNameChecking . (Join-Path $PSScriptRoot "..\Actions\AL-Go-Helper.ps1" -Resolve) DownloadAndImportBcContainerHelper -baseFolder $([System.IO.Path]::GetTempPath()) function InvokeDeploy { [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSReviewUnusedParameter', 'sandbox', Justification = 'Used inside the Invoke-RestMethod mock scriptblock')] - Param([bool] $sandbox = $true, [hashtable] $deploymentSettings) + Param([bool] $sandbox = $true, [hashtable] $deploymentSettings, [hashtable] $repositorySettings = @{}, [hashtable] $authParameters = @{ refreshToken = 'dummy' }) $json = @{ "test" = $deploymentSettings } | ConvertTo-Json -Depth 10 -Compress - $authContext = [Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes('{"refreshToken":"dummy"}')) + $authContext = [Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes(($authParameters | ConvertTo-Json -Compress))) $env:Secrets = @{ "test-AuthContext" = ""; "test_AuthContext" = ""; "AuthContext" = $authContext } | ConvertTo-Json -Compress - $env:Settings = @{ "type" = "PTE"; "runs-on" = "ubuntu-latest"; "shell" = "pwsh" } | ConvertTo-Json -Compress + $actionSettings = @{ "type" = "PTE"; "runs-on" = "ubuntu-latest"; "shell" = "pwsh" } + foreach ($name in $repositorySettings.Keys) { $actionSettings[$name] = $repositorySettings[$name] } + $env:Settings = $actionSettings | ConvertTo-Json -Depth 10 -Compress Mock Invoke-RestMethod { return @{ "Status" = "Ready"; "environmentType" = (@{ $true = 1; $false = 0 }[$sandbox]) } } . $scriptPath -token 'dummy' -environmentName 'test' -artifactsFolder 'artifacts' -type 'CD' -deploymentEnvironmentsJson $json } @@ -55,6 +58,8 @@ Describe "Deploy Action Tests" { Mock GetAppsAndDependenciesFromArtifacts { return @('/tmp/app1.app'), @() } Mock Sort-AppFilesByDependencies { } Mock CheckInstalledApps { } + Mock Initialize-AdminCenterAuthContext { } + Mock Initialize-PTEPublishingApi { } Mock PublishPTEApps { $script:publishPTECalled = $true } Mock Publish-PerTenantExtensionApps { throw "The action must use the shared AL-Go publisher" } Mock Publish-BcContainerApp { } @@ -76,27 +81,170 @@ Describe "Deploy Action Tests" { $script:unpublishAfterPublish | Should -BeTrue } - It 'Shares action-scoped publishing paths across dependencies, primary apps and cleanup' { + It 'Initializes the PTE route before dependencies and primary publishing' { + $script:events = @() + Mock Initialize-PTEPublishingApi { $script:events += 'probe' } Mock GetAppsAndDependenciesFromArtifacts { return @('/tmp/app1.app'), @('/tmp/dependency.app') } - Mock InstallOrUpgradeApps { - $publishingResults.Count | Should -Be 0 - $publishingResults['dependency'] = 'AdminCenter' + Mock InstallOrUpgradeApps { $script:events += 'dependency' } + Mock CheckInstalledApps { $script:events += 'preflight' } + Mock PublishPTEApps { $script:events += 'primary' } + Mock UnpublishOldAppVersions { + $script:events += 'cleanup' + ($appFiles -join ',') | Should -Be '/tmp/app1.app' } - Mock PublishPTEApps { - $publishingResults['dependency'] | Should -Be 'AdminCenter' - $publishingResults['primary'] = 'Automation' + + InvokeDeploy -deploymentSettings @{ EnvironmentType = 'SaaS'; EnvironmentName = 'test'; Branches = @(); Projects = '*'; DependencyInstallMode = 'upgrade'; SyncMode = $null; Scope = 'PTE'; continuousDeployment = $true; includeTestAppsInSandboxEnvironment = $false; excludeAppIds = @(); unpublishOldVersions = $true } + + ($script:events -join ',') | Should -Be 'probe,dependency,preflight,primary,cleanup' + } + + It 'Keeps Admin settings separate from BCH authentication, dependencies and cleanup' { + Mock New-BcAuthContext { + $script:deploymentConfig = $bcContainerHelperConfig + $bcContainerHelperConfig.apiBaseUrl | Should -Be 'https://legacy.test' + return @{ tenantId = 'test-tenant' } + } + Mock GetAppsAndDependenciesFromArtifacts { return @('/tmp/app1.app'), @('/tmp/dependency.app') } + Mock Sort-AppFilesByDependencies { + param($unknownDependencies) + $unknownDependencies.Value = @('unknown:Dependency_1.0.0.0.app') + } + Mock InstallOrUpgradeApps { } + Mock InstallUnknownDependencies { + $bcContainerHelperConfig.apiBaseUrl | Should -Be 'https://legacy.test' } Mock UnpublishOldAppVersions { - $publishingResults['dependency'] | Should -Be 'AdminCenter' - $publishingResults['primary'] | Should -Be 'Automation' - $appFiles | Should -Not -Contain '/tmp/dependency.app' + $bcContainerHelperConfig.apiBaseUrl | Should -Be 'https://legacy.test' } - InvokeDeploy -deploymentSettings @{ "EnvironmentType" = "SaaS"; "EnvironmentName" = "test"; "Branches" = @(); "Projects" = "*"; "DependencyInstallMode" = "upgrade"; "SyncMode" = $null; "Scope" = "PTE"; "continuousDeployment" = $true; "includeTestAppsInSandboxEnvironment" = $false; "excludeAppIds" = @(); "unpublishOldVersions" = $true } + InvokeDeploy -repositorySettings @{ + deploymentBaseUrl = 'https://deploy.test/root/' + deploymentApplicationFamily = 'Custom / Family' + apiBaseUrl = 'https://legacy.test' + baseUrl = 'https://web.test' + } -deploymentSettings @{ EnvironmentType = 'SaaS'; EnvironmentName = 'test'; Branches = @(); Projects = '*'; DependencyInstallMode = 'upgrade'; SyncMode = $null; Scope = 'PTE'; continuousDeployment = $true; includeTestAppsInSandboxEnvironment = $false; excludeAppIds = @(); unpublishOldVersions = $true } - Assert-MockCalled InstallOrUpgradeApps -Exactly 1 - Assert-MockCalled PublishPTEApps -Exactly 1 + foreach ($command in @('Initialize-PTEPublishingApi', 'InstallOrUpgradeApps', 'CheckInstalledApps', 'PublishPTEApps')) { + Assert-MockCalled $command -Exactly 1 -ParameterFilter { + !$PesterBoundParameters.ContainsKey('deploymentTarget') + } + } Assert-MockCalled UnpublishOldAppVersions -Exactly 1 + Assert-MockCalled InstallUnknownDependencies -Exactly 1 + Assert-MockCalled Initialize-AdminCenterAuthContext -Exactly 1 -ParameterFilter { + $settings.deploymentBaseUrl -eq 'https://deploy.test/root/' -and + $settings.deploymentApplicationFamily -eq 'Custom / Family' -and !$preserveScopes + } + Assert-MockCalled Invoke-RestMethod -Exactly 1 -ParameterFilter { $Uri -like 'https://web.test/*' } + $script:deploymentConfig.apiBaseUrl | Should -Be 'https://legacy.test' + $script:deploymentConfig.baseUrl | Should -Be 'https://web.test' + } + + It 'Does not retain the explicit target in a following deployment with only the legacy override' { + Mock New-BcAuthContext { + $script:deploymentConfig = $bcContainerHelperConfig + return @{ tenantId = 'test-tenant' } + } + $deployment = @{ EnvironmentType = 'SaaS'; EnvironmentName = 'test'; Branches = @(); Projects = '*'; DependencyInstallMode = 'ignore'; SyncMode = $null; Scope = 'PTE'; continuousDeployment = $true; includeTestAppsInSandboxEnvironment = $false; excludeAppIds = @() } + + InvokeDeploy -deploymentSettings $deployment -repositorySettings @{ + deploymentBaseUrl = 'https://explicit.test'; deploymentApplicationFamily = 'CustomFamily' + apiBaseUrl = 'https://legacy.test' + } + $script:deploymentConfig.apiBaseUrl | Should -Be 'https://legacy.test' + InvokeDeploy -deploymentSettings $deployment -repositorySettings @{ + apiBaseUrl = 'https://legacy.test' + } + + Assert-MockCalled PublishPTEApps -Exactly 2 + Assert-MockCalled Initialize-AdminCenterAuthContext -Exactly 1 -ParameterFilter { + $settings['deploymentBaseUrl'] -eq 'https://explicit.test' -and + $settings['deploymentApplicationFamily'] -eq 'CustomFamily' + } + Assert-MockCalled Initialize-AdminCenterAuthContext -Exactly 1 -ParameterFilter { + !$settings.ContainsKey('deploymentBaseUrl') -and !$settings.ContainsKey('deploymentApplicationFamily') + } + $script:deploymentConfig.apiBaseUrl | Should -Be 'https://legacy.test' + } + + It 'Does not modify the helper API root when authentication fails' { + Mock New-BcAuthContext { + $script:deploymentConfig = $bcContainerHelperConfig + $bcContainerHelperConfig.apiBaseUrl | Should -Be 'https://legacy.test' + throw 'Authentication failed' + } + Mock OutputError { param($message) throw $message } + + { InvokeDeploy -repositorySettings @{ + deploymentBaseUrl = 'https://explicit.test' + apiBaseUrl = 'https://legacy.test' + } -deploymentSettings @{ EnvironmentType = 'SaaS'; EnvironmentName = 'test'; Branches = @(); Projects = '*'; DependencyInstallMode = 'ignore'; SyncMode = $null; Scope = 'PTE'; continuousDeployment = $true; includeTestAppsInSandboxEnvironment = $false; excludeAppIds = @() } } | Should -Throw '*Authentication failed*' + + $script:deploymentConfig.apiBaseUrl | Should -Be 'https://legacy.test' + Assert-MockCalled PublishPTEApps -Times 0 + Assert-MockCalled Initialize-PTEPublishingApi -Times 0 + Assert-MockCalled Initialize-AdminCenterAuthContext -Times 0 + } + + It 'Preserves explicitly supplied OAuth scopes instead of silently retargeting their audience' { + Mock New-BcAuthContext { + return @{ tenantId = 'tenant'; Scopes = 'https://audience.test/.default' } + } + InvokeDeploy -repositorySettings @{ deploymentBaseUrl = 'https://explicit.test' } ` + -authParameters @{ refreshToken = 'dummy'; scopes = @('https://audience.test/.default') } ` + -deploymentSettings @{ EnvironmentType = 'SaaS'; EnvironmentName = 'test'; Branches = @(); Projects = '*'; DependencyInstallMode = 'ignore'; SyncMode = $null; Scope = 'PTE'; continuousDeployment = $true; includeTestAppsInSandboxEnvironment = $false; excludeAppIds = @() } + + Assert-MockCalled New-BcAuthContext -Exactly 1 -ParameterFilter { + $scopes -eq 'https://audience.test/.default' + } + Assert-MockCalled PublishPTEApps -Exactly 1 -ParameterFilter { + $bcAuthContext.Scopes -eq 'https://audience.test/.default' + } + Assert-MockCalled Initialize-AdminCenterAuthContext -Exactly 1 -ParameterFilter { + $preserveScopes -and $bcAuthContext.Scopes -eq 'https://audience.test/.default' -and + $settings.deploymentBaseUrl -eq 'https://explicit.test' + } + } + + It 'Keeps the original BCH token resource when Admin settings differ' { + Mock New-BcAuthContext { + # The action reloads BCH, so mock the current module instance after that import. + Mock Invoke-RestMethod -ModuleName BcContainerHelper { + return @{ access_token = 'fake-token' } + } + Mock Parse-JWTtoken -ModuleName BcContainerHelper { + return @{ appid = 'fake-client'; exp = 2000000000 } + } + $newContext = Get-Command New-BcAuthContext -Module BcContainerHelper + & $newContext -tenantID 'fake-tenant' -clientID 'fake-client' -clientSecret 'fake-secret' -silent + } + + InvokeDeploy -repositorySettings @{ deploymentBaseUrl = 'https://explicit.test'; apiBaseUrl = 'https://legacy.test' } ` + -deploymentSettings @{ EnvironmentType = 'SaaS'; EnvironmentName = 'test'; Branches = @(); Projects = '*'; DependencyInstallMode = 'ignore'; SyncMode = $null; Scope = 'PTE'; continuousDeployment = $true; includeTestAppsInSandboxEnvironment = $false; excludeAppIds = @() } + + Assert-MockCalled Invoke-RestMethod -ModuleName BcContainerHelper -Exactly 1 -ParameterFilter { + $Uri -eq 'https://login.microsoftonline.com/fake-tenant/oauth2/v2.0/token' -and + $Body.scope -eq 'https://legacy.test/.default' + } + } + + It 'Preserves an explicit resource for native authentication and leaves the BCH context unchanged' { + $script:originalAuthContext = @{ + tenantId = 'tenant'; Scopes = 'https://explicit-resource.test/'; AccessToken = 'original-token' + } + Mock New-BcAuthContext { return $script:originalAuthContext } + InvokeDeploy -repositorySettings @{ deploymentBaseUrl = 'https://admin.test' } ` + -authParameters @{ refreshToken = 'dummy'; resource = 'https://explicit-resource.test' } ` + -deploymentSettings @{ EnvironmentType = 'SaaS'; EnvironmentName = 'test'; Branches = @(); Projects = '*'; DependencyInstallMode = 'ignore'; SyncMode = $null; Scope = 'PTE'; continuousDeployment = $true; includeTestAppsInSandboxEnvironment = $false; excludeAppIds = @() } + + Assert-MockCalled PublishPTEApps -Exactly 1 -ParameterFilter { + $bcAuthContext.Scopes -eq 'https://explicit-resource.test/' + } + Assert-MockCalled Initialize-AdminCenterAuthContext -Exactly 1 -ParameterFilter { + $preserveScopes -and $bcAuthContext.Scopes -eq 'https://explicit-resource.test/' -and + [object]::ReferenceEquals($bcAuthContext, $script:originalAuthContext) + } + $script:originalAuthContext.AccessToken | Should -Be 'original-token' } It 'Does not invoke cleanup when unpublishOldVersions is not set (default)' { @@ -154,6 +302,42 @@ Describe "Deploy Action Tests" { Assert-MockCalled PublishPTEApps -Times 0 Assert-MockCalled Publish-PerTenantExtensionApps -Times 0 Assert-MockCalled UnpublishOldAppVersions -Times 0 + Assert-MockCalled Initialize-PTEPublishingApi -Times 0 + } + + It 'Probes before Dev dependency installation only for PTE dependency packages' -TestCases @( + @{ from = 50000; expectedProbes = 1 }, + @{ from = 100000; expectedProbes = 0 } + ) { + param($from, $expectedProbes) + $script:dependencyRange = $from + Mock GetAppsAndDependenciesFromArtifacts { return @('/tmp/app1.app'), @('/tmp/dependency.app') } + Mock Get-AppJsonFromAppFile { return @{ idRanges = @(@{ from = $script:dependencyRange; to = 999999 }) } } + $script:events = @() + Mock Initialize-PTEPublishingApi { $script:events += 'probe' } + Mock InstallOrUpgradeApps { $script:events += 'dependencies' } + + InvokeDeploy -deploymentSettings @{ EnvironmentType = 'SaaS'; EnvironmentName = 'test'; Branches = @(); Projects = '*'; DependencyInstallMode = 'upgrade'; SyncMode = $null; Scope = 'Dev'; continuousDeployment = $true; includeTestAppsInSandboxEnvironment = $false; excludeAppIds = @() } + + Assert-MockCalled Initialize-PTEPublishingApi -Exactly $expectedProbes + Assert-MockCalled PublishPTEApps -Times 0 + Assert-MockCalled Publish-BcContainerApp -Exactly 1 + if ($expectedProbes) { ($script:events -join ',') | Should -Be 'probe,dependencies' } + else { ($script:events -join ',') | Should -Be 'dependencies' } + } + + It 'Stops before publishing when authentication or the route probe fails' { + Mock InstallOrUpgradeApps { } + $deployment = @{ EnvironmentType = 'SaaS'; EnvironmentName = 'test'; Branches = @(); Projects = '*'; DependencyInstallMode = 'ignore'; SyncMode = $null; Scope = 'PTE'; continuousDeployment = $true; includeTestAppsInSandboxEnvironment = $false; excludeAppIds = @() } + Mock New-BcAuthContext { throw 'Authentication failed' } + { InvokeDeploy -deploymentSettings $deployment } | Should -Throw '*Authentication failed*' + + Mock New-BcAuthContext { return @{ tenantId = 'test-tenant' } } + Mock Initialize-PTEPublishingApi { throw 'Probe timeout' } + Mock OutputError { param($message) throw $message } + { InvokeDeploy -deploymentSettings $deployment } | Should -Throw '*Probe timeout*' + Assert-MockCalled PublishPTEApps -Times 0 + Assert-MockCalled InstallOrUpgradeApps -Times 0 } } } diff --git a/Tests/Deploy.Module.Test.ps1 b/Tests/Deploy.Module.Test.ps1 index d00cd7a7de..ce96228b46 100644 --- a/Tests/Deploy.Module.Test.ps1 +++ b/Tests/Deploy.Module.Test.ps1 @@ -19,6 +19,7 @@ InModuleScope Deploy { # Allows testing of private functions } BeforeEach { + $script:ptePublishingApi = '' # Set up common test environment variables $env:GITHUB_WORKSPACE = (Join-Path ([System.IO.Path]::GetTempPath()) "deployModuleTest") $env:GITHUB_REPOSITORY = "test/repo" @@ -43,7 +44,11 @@ InModuleScope Deploy { # Allows testing of private functions Mock OutputGroupStart { } Mock OutputGroupEnd { } Mock OutputWarning { } - Mock Get-AdminCenterInstalledExtensions { throw 'Admin Center read unavailable' } + Mock Get-AdminCenterInstalledExtensions { + $exception = [System.Exception]::new('Admin Center access not configured') + $exception | Add-Member NoteProperty Response ([PSCustomObject]@{ StatusCode = 403 }) + throw $exception + } Mock Get-AppJsonFromAppFile { param($appFile) switch ($appFile) { @@ -161,7 +166,10 @@ InModuleScope Deploy { # Allows testing of private functions ) } Mock Sort-AppFilesByDependencies { } - Mock Install-BcAppFromAppSource { return $true } + Mock Install-BcAppFromAppSource { + $PesterBoundParameters.Keys | Should -Not -Contain 'applicationFamily' + return $true + } Mock PublishPTEApps { return $true } Mock Publish-PerTenantExtensionApps { throw "Dependencies must use the shared AL-Go publisher" } Mock Write-Host { } @@ -513,6 +521,7 @@ InModuleScope Deploy { # Allows testing of private functions Describe "CheckInstalledApps" { It 'Uses the Admin installed snapshot for higher-version warnings without Automation' { + $script:ptePublishingApi = 'AdminCenter' Mock Get-AdminCenterInstalledExtensions { return [PSCustomObject]@{ id = 'admin-app'; displayName = 'Admin App'; isInstalled = $true @@ -523,7 +532,9 @@ InModuleScope Deploy { # Allows testing of private functions CheckInstalledApps -bcAuthContext @{} -environment Sandbox -appFiles @('Admin.app') - Assert-MockCalled Get-AdminCenterInstalledExtensions -Exactly 1 + Assert-MockCalled Get-AdminCenterInstalledExtensions -Exactly 1 -ParameterFilter { + $environment -eq 'Sandbox' + } Assert-MockCalled Get-BcInstalledExtensions -Times 0 Assert-MockCalled OutputWarning -Exactly 1 -ParameterFilter { $message -like '*2.1.3.4*higher than 2.1.3.2*' } } @@ -828,6 +839,7 @@ InModuleScope Deploy { # Allows testing of private functions } It 'Uses Admin installed PTE dependency checks without requiring Automation' { + $script:ptePublishingApi = 'AdminCenter' Mock Get-ChildItem { param($Path) return @(@{ FullName = Join-Path $Path "PTEApp.app" }) @@ -842,12 +854,17 @@ InModuleScope Deploy { # Allows testing of private functions InstallOrUpgradeApps -bcAuthContext @{} -environment Sandbox -apps @('PTEApp.app') -installMode upgrade - Assert-MockCalled Get-AdminCenterInstalledExtensions -Exactly 1 + Assert-MockCalled Get-AdminCenterInstalledExtensions -Exactly 1 -ParameterFilter { + $environment -eq 'Sandbox' + } Assert-MockCalled Get-BcInstalledExtensions -Times 0 - Assert-MockCalled PublishPTEApps -Exactly 1 + Assert-MockCalled PublishPTEApps -Exactly 1 -ParameterFilter { + $environment -eq 'Sandbox' -and !$PesterBoundParameters.ContainsKey('deploymentTarget') + } } It 'Preserves the Dev dependency exclusion using normalized Admin appType' { + $script:ptePublishingApi = 'AdminCenter' Mock Get-ChildItem { param($Path) return @(@{ FullName = Join-Path $Path "DevScopeApp.app" }) @@ -875,14 +892,10 @@ InModuleScope Deploy { # Allows testing of private functions } Mock PublishPTEApps { $PesterBoundParameters.Keys | Should -Not -Contain 'schedule' - $publishingResults['primary'] | Should -Be 'AdminCenter' - $publishingResults['dependency'] = 'Automation' } - $results = @{ primary = 'AdminCenter' } - InstallOrUpgradeApps -bcAuthContext @{ tenantId = "test-tenant" } -environment "test-env" -apps @("PTEApp.app") -installMode "upgrade" -publishingResults $results + InstallOrUpgradeApps -bcAuthContext @{ tenantId = "test-tenant" } -environment "test-env" -apps @("PTEApp.app") -installMode "upgrade" - $results['dependency'] | Should -Be 'Automation' Assert-MockCalled PublishPTEApps -Exactly 1 -ParameterFilter { $appFiles.Count -eq 1 -and $appFiles[0] -like "*PTEApp.app" -and $SchemaSyncMode -eq "Add" } diff --git a/Tests/PublishPTEApps.Test.ps1 b/Tests/PublishPTEApps.Test.ps1 index ee5fc9eb6d..6d5c4c8857 100644 --- a/Tests/PublishPTEApps.Test.ps1 +++ b/Tests/PublishPTEApps.Test.ps1 @@ -20,6 +20,7 @@ InModuleScope Deploy { versionMajor = 30; versionMinor = 0; versionBuild = 0; versionRevision = 0 } $script:extensions = @($script:application) + $script:ptePublishingApi = '' Mock Write-Host { } Mock OutputWarning { } Mock Renew-BcAuthContext { return @{ AccessToken = 'renewed-test-token' } } @@ -31,8 +32,144 @@ InModuleScope Deploy { Mock Publish-PerTenantExtensionApps { } } - Context "Shared router" { + Context "Action route selection" { + It 'Selects Admin on BC through the native request boundary' -TestCases @( + @{ major = 29 }, @{ major = 30 }, @{ major = 31 } + ) { + param($major) + $script:application.versionMajor = $major + Initialize-PTEPublishingApi -bcAuthContext @{} -environment Sandbox + + $script:ptePublishingApi | Should -Be AdminCenter + Assert-MockCalled Get-AdminCenterInstalledExtensions -Exactly 1 -ParameterFilter { + $environment -eq 'Sandbox' -and !$PesterBoundParameters.ContainsKey('apiBaseUrl') -and + !$PesterBoundParameters.ContainsKey('applicationFamily') + } + Assert-MockCalled Get-BcInstalledExtensions -Times 0 + } + + It 'Selects Automation below BC 29 even when Admin access works' { + $script:application.versionMajor = 28 + Initialize-PTEPublishingApi -bcAuthContext @{} -environment Sandbox + + $script:ptePublishingApi | Should -Be Automation + Assert-MockCalled Get-AdminCenterInstalledExtensions -Exactly 1 + Assert-MockCalled Get-BcInstalledExtensions -Times 0 + Assert-MockCalled OutputWarning -Times 0 + } + + It 'Selects Automation once for probe HTTP ' -TestCases @( + @{ statusCode = 401 }, @{ statusCode = 403 } + ) { + param($statusCode) + $script:probeStatus = $statusCode + Mock Get-AdminCenterInstalledExtensions { + $exception = [System.Exception]::new('Admin permission missing') + $exception | Add-Member NoteProperty Response ([PSCustomObject]@{ StatusCode = $script:probeStatus }) + throw $exception + } + + Initialize-PTEPublishingApi -bcAuthContext @{} -environment Sandbox + + $script:ptePublishingApi | Should -Be Automation + Assert-MockCalled Get-AdminCenterInstalledExtensions -Exactly 1 + Assert-MockCalled Get-BcInstalledExtensions -Exactly 1 + Assert-MockCalled OutputWarning -Exactly 1 -ParameterFilter { + $message -like '*Admin permission missing*permissions*ContinuousDeployment.md#pte-deployment-authorization*throughout this Deploy action*' + } + } + + It 'Selects Automation for the helper-owned missing-token error' { + Mock Get-AdminCenterInstalledExtensions { + throw [System.Management.Automation.ErrorRecord]::new( + [System.Security.Authentication.AuthenticationException]::new('Token missing'), + 'AdminCenterAuthenticationFailed', 'AuthenticationError', $null) + } + + Initialize-PTEPublishingApi -bcAuthContext @{} -environment Sandbox + $script:ptePublishingApi | Should -Be Automation + Assert-MockCalled OutputWarning -Exactly 1 + } + + It 'Does not mistake a probe for an authorization setup failure' -TestCases @( + @{ problem = 'network' }, @{ problem = 'timeout' }, @{ problem = 'TLS' }, + @{ problem = 'text-only 403' }, @{ problem = 'malformed' }, @{ problem = 'missing Application' }, + @{ problem = 'incomplete Application' }, @{ problem = 'invalid Application' }, @{ problem = 'ambiguous Application' }, + @{ problem = '404' }, @{ problem = '500' } + ) { + param($problem) + switch ($problem) { + network { Mock Get-AdminCenterInstalledExtensions { throw [System.Net.WebException]::new('Connection failed') } } + timeout { Mock Get-AdminCenterInstalledExtensions { throw [TimeoutException]::new('Timed out') } } + TLS { Mock Get-AdminCenterInstalledExtensions { throw [System.Security.Authentication.AuthenticationException]::new('TLS failed') } } + 'text-only 403' { Mock Get-AdminCenterInstalledExtensions { throw '403 Forbidden' } } + malformed { Mock Get-AdminCenterInstalledExtensions { throw 'Invalid app version' } } + 'missing Application' { Mock Get-AdminCenterInstalledExtensions { return @() } } + 'incomplete Application' { + Mock Get-AdminCenterInstalledExtensions { return @{ displayName = 'Application'; isInstalled = $true; versionMajor = 30 } } + } + 'invalid Application' { $script:application.versionMajor = 'unknown' } + 'ambiguous Application' { Mock Get-AdminCenterInstalledExtensions { return @($script:application, $script:application.Clone()) } } + default { + $script:probeStatus = [int]$problem + Mock Get-AdminCenterInstalledExtensions { + $exception = [System.Exception]::new('Service failure') + $exception | Add-Member NoteProperty Response ([PSCustomObject]@{ StatusCode = $script:probeStatus }) + throw $exception + } + } + } + { Initialize-PTEPublishingApi -bcAuthContext @{} -environment Sandbox } | Should -Throw + $script:ptePublishingApi | Should -Be '' + Assert-MockCalled Get-BcInstalledExtensions -Times 0 + Assert-MockCalled OutputWarning -Times 0 + } + + It 'Fails rather than using a default version if the selected Automation read fails' { + Mock Get-AdminCenterInstalledExtensions { + $exception = [System.Exception]::new('Not authorized') + $exception | Add-Member NoteProperty Response ([PSCustomObject]@{ StatusCode = 403 }) + throw $exception + } + Mock Get-BcInstalledExtensions { throw 'Automation read failed' } + + { Initialize-PTEPublishingApi -bcAuthContext @{} -environment Sandbox } | Should -Throw '*Automation read failed*' + $script:ptePublishingApi | Should -Be '' + } + + It 'Overwrites the previous choice on each initialization' { + Mock Get-AdminCenterInstalledExtensions { + $exception = [System.Exception]::new('Not authorized') + $exception | Add-Member NoteProperty Response ([PSCustomObject]@{ StatusCode = 401 }) + throw $exception + } + Initialize-PTEPublishingApi -bcAuthContext @{} -environment Sandbox + $script:ptePublishingApi | Should -Be Automation + Mock Get-AdminCenterInstalledExtensions { return $script:extensions } + Initialize-PTEPublishingApi -bcAuthContext @{} -environment Sandbox + + $script:ptePublishingApi | Should -Be AdminCenter + } + + It 'Uses the selected read API without repeating the authorization probe or changing routes' { + GetInstalledExtensions -bcAuthContext @{} -environment Sandbox -publishingApi AdminCenter | Out-Null + Assert-MockCalled Get-AdminCenterInstalledExtensions -Exactly 1 -ParameterFilter { + $environment -eq 'Sandbox' + } + Assert-MockCalled Get-BcInstalledExtensions -Times 0 + Mock Get-AdminCenterInstalledExtensions { throw 'Read failed after selection' } + { GetInstalledExtensions -bcAuthContext @{} -environment Sandbox -publishingApi AdminCenter } | + Should -Throw '*Read failed after selection*' + Assert-MockCalled Get-BcInstalledExtensions -Times 0 + GetInstalledExtensions -bcAuthContext @{} -environment Sandbox -publishingApi Automation | Out-Null + Assert-MockCalled Get-BcInstalledExtensions -Exactly 1 + Assert-MockCalled OutputWarning -Times 0 + } + } + + Context "Selected route publishing" { BeforeEach { + $script:ptePublishingApi = 'AdminCenter' Mock NewTemporaryFolder { return 'test-app-folder' } Mock Copy-AppFilesToFolder { return @('App.app') } Mock Sort-AppFilesByDependencies { return @('App.app') } @@ -42,17 +179,119 @@ InModuleScope Deploy { Mock WaitPTEOperation { } } - It 'Uses only the released helper for BC and preserves Force and immediate defaults' -TestCases @( - @{ major = 27 }, @{ major = 28 } + It 'Reuses the initialized Automation route for dependencies and primary publishing' { + Mock Get-AdminCenterInstalledExtensions { + $exception = [System.Exception]::new('Admin permission missing') + $exception | Add-Member NoteProperty Response ([PSCustomObject]@{ StatusCode = 403 }) + throw $exception + } + Initialize-PTEPublishingApi -bcAuthContext @{} -environment Sandbox + PublishPTEApps -bcAuthContext @{} -environment Sandbox -appFiles @('Dependency.app') + $script:ptePublishingApi | Should -Be Automation + PublishPTEApps -bcAuthContext @{} -environment Sandbox -appFiles @('Primary.app') + + Assert-MockCalled Get-AdminCenterInstalledExtensions -Exactly 1 + Assert-MockCalled Get-BcInstalledExtensions -Exactly 1 + Assert-MockCalled Publish-PerTenantExtensionApps -Exactly 2 + Assert-MockCalled Install-AdminCenterPTE -Times 0 + Assert-MockCalled OutputWarning -Exactly 1 + } + + It 'Requires explicit initialization instead of selecting a route while publishing' { + $script:ptePublishingApi = '' + GetInstalledExtensions -bcAuthContext @{} -environment Sandbox | Out-Null + $script:ptePublishingApi | Should -Be '' + { PublishPTEApps -bcAuthContext @{} -environment Sandbox -appFiles @('App.app') } | + Should -Throw '*must be initialized*' + Assert-MockCalled Get-AdminCenterInstalledExtensions -Times 0 + Assert-MockCalled Publish-PerTenantExtensionApps -Times 0 + Assert-MockCalled OutputWarning -Times 0 + } + + It 'Does not switch an Admin route when a later read or write fails authorization' -TestCases @( + @{ step = 'read' }, @{ step = 'write' } + ) { + param($step) + PublishPTEApps -bcAuthContext @{} -environment Sandbox -appFiles @('Dependency.app') + $exception = [System.Exception]::new('Later access rejected') + $exception | Add-Member NoteProperty Response ([PSCustomObject]@{ StatusCode = 403 }) + $script:laterFailure = $exception + if ($step -eq 'read') { + Mock Get-AdminCenterInstalledExtensions { throw $script:laterFailure } + } + else { + Mock Install-AdminCenterPTE { throw $script:laterFailure } + } + { PublishPTEApps -bcAuthContext @{} -environment Sandbox -appFiles @('Primary.app') } | + Should -Throw '*Later access rejected*' + + $script:ptePublishingApi | Should -Be AdminCenter + Assert-MockCalled Get-BcInstalledExtensions -Times 0 + Assert-MockCalled Publish-PerTenantExtensionApps -Times 0 + Assert-MockCalled OutputWarning -Times 0 + } + + It 'Reinitializes the route by probing the next environment' { + Mock Get-AdminCenterInstalledExtensions { + if ($environment -eq 'First') { + $exception = [System.Exception]::new('First target not configured') + $exception | Add-Member NoteProperty Response ([PSCustomObject]@{ StatusCode = 403 }) + throw $exception + } + return $script:extensions + } + Initialize-PTEPublishingApi -bcAuthContext @{} -environment First + $script:ptePublishingApi | Should -Be Automation + Initialize-PTEPublishingApi -bcAuthContext @{} -environment Second + PublishPTEApps -bcAuthContext @{} -environment Second -appFiles @('App.app') + + $script:ptePublishingApi | Should -Be AdminCenter + Assert-MockCalled Get-AdminCenterInstalledExtensions -Exactly 2 -ParameterFilter { + $environment -eq 'Second' + } + Assert-MockCalled Install-AdminCenterPTE -Exactly 1 -ParameterFilter { + $environment -eq 'Second' + } + } + + It 'Does not persist a route when the initial probe fails unexpectedly' { + $script:ptePublishingApi = '' + Mock Get-AdminCenterInstalledExtensions { throw [TimeoutException]::new('Probe timeout') } + { Initialize-PTEPublishingApi -bcAuthContext @{} -environment Sandbox } | Should -Throw '*Probe timeout*' + $script:ptePublishingApi | Should -Be '' + Assert-MockCalled NewTemporaryFolder -Times 0 + Assert-MockCalled Publish-PerTenantExtensionApps -Times 0 + } + + It 'Does not hide an unexpected metadata read failure before publishing' -TestCases @( + @{ problem = 'network' }, @{ problem = 'malformed' } + ) { + param($problem) + if ($problem -eq 'network') { + Mock Get-AdminCenterInstalledExtensions { throw [System.Net.WebException]::new('Connection failed') } + } + else { + Mock Get-AdminCenterInstalledExtensions { throw 'Malformed app response' } + } + { GetInstalledExtensions -bcAuthContext @{} -environment Sandbox } | Should -Throw + $script:ptePublishingApi | Should -Be AdminCenter + Assert-MockCalled Get-BcInstalledExtensions -Times 0 + Assert-MockCalled OutputWarning -Times 0 + } + + It 'Passes original packages to BCH for BC and preserves Force and immediate defaults' -TestCases @( + @{ major = 27 }, @{ major = 28 }, @{ major = 29 }, @{ major = 30 }, @{ major = 31 } ) { param($major) $script:application.versionMajor = $major $script:application.versionMinor = 9 $script:application.versionBuild = 99999 $script:application.versionRevision = 99999 + $script:ptePublishingApi = 'Automation' Mock Publish-PerTenantExtensionApps { $PesterBoundParameters.Keys | Should -Not -Contain 'schedule' $PesterBoundParameters.Keys | Should -Not -Contain 'applicationFamily' + $bcContainerHelperConfig.apiBaseUrl | Should -Be 'https://api.example.test/' } PublishPTEApps -bcAuthContext @{ tenantId = 'tenant' } -environment 'Sandbox' -appFiles @('Apps.zip') -schemaSyncMode Force @@ -63,9 +302,37 @@ InModuleScope Deploy { } Assert-MockCalled Install-AdminCenterPTE -Times 0 Assert-MockCalled NewTemporaryFolder -Times 0 + Assert-MockCalled Get-BcInstalledExtensions -Times 0 + Assert-MockCalled Get-AdminCenterInstalledExtensions -Times 0 Assert-MockCalled Invoke-RestMethod -Times 0 } + It 'Routes one original batch to the Admin publisher without preparing packages in the router' { + Mock Publish-AdminCenterPTEApps { } + + PublishPTEApps -bcAuthContext @{ tenantId = 'tenant' } -environment Sandbox -appFiles @('Apps.zip', 'Other.app') ` + -schemaSyncMode Force + + Assert-MockCalled Publish-AdminCenterPTEApps -Exactly 1 -ParameterFilter { + $bcAuthContext.tenantId -eq 'tenant' -and $environment -eq 'Sandbox' -and + ($appFiles -join ',') -eq 'Apps.zip,Other.app' -and $schemaSyncMode -eq 'Force' + } + Assert-MockCalled Get-AdminCenterInstalledExtensions -Times 0 + Assert-MockCalled Copy-AppFilesToFolder -Times 0 + Assert-MockCalled Publish-PerTenantExtensionApps -Times 0 + } + + It 'Does not silently switch a selected Admin route when the target version changes below BC 29' { + $script:application.versionMajor = 28 + + { PublishPTEApps -bcAuthContext @{} -environment Sandbox -appFiles @('App.app') } | + Should -Throw '*selected API will not be changed*' + + $script:ptePublishingApi | Should -Be AdminCenter + Assert-MockCalled Publish-PerTenantExtensionApps -Times 0 + Assert-MockCalled Install-AdminCenterPTE -Times 0 + } + It 'Keeps API implementation helpers private and exposes the shared publisher' { $exports = (Get-Module Deploy).ExportedFunctions.Keys $exports | Should -Contain 'PublishPTEApps' @@ -100,66 +367,52 @@ InModuleScope Deploy { Assert-MockCalled Get-BcInstalledExtensions -Times 0 } - It 'Uses Automation reads after an Admin without changing write routing' -TestCases @( - @{ problem = 'authorization' }, @{ problem = 'network' }, @{ problem = 'malformed response' }, - @{ problem = 'missing Application' }, @{ problem = 'incomplete Application' }, @{ problem = 'ambiguous Application' } - ) { - param($problem) - switch ($problem) { - authorization { Mock Get-AdminCenterInstalledExtensions { throw '403 Forbidden: User not authorized' } } - network { Mock Get-AdminCenterInstalledExtensions { throw [System.Net.WebException]::new('Connection failed') } } - 'malformed response' { Mock Get-AdminCenterInstalledExtensions { throw 'Admin Center installed app has invalid full version.' } } - 'missing Application' { Mock Get-AdminCenterInstalledExtensions { return @() } } - 'incomplete Application' { - Mock Get-AdminCenterInstalledExtensions { return @{ displayName = 'Application'; isInstalled = $true; versionMajor = 30 } } - } - 'ambiguous Application' { Mock Get-AdminCenterInstalledExtensions { return @($script:application, $script:application.Clone()) } } + It 'Passes the same source auth context through snapshot, upload and exact-operation wait' { + $script:sourceContext = @{ tenantId = 'tenant' } + Mock Get-AdminCenterInstalledExtensions { + [object]::ReferenceEquals($bcAuthContext, $script:sourceContext) | Should -BeTrue + return $script:extensions } - PublishPTEApps -bcAuthContext @{} -environment Sandbox -appFiles @('App.app') + PublishPTEApps -bcAuthContext $script:sourceContext -environment Sandbox -appFiles @('App.app') Assert-MockCalled Get-AdminCenterInstalledExtensions -Exactly 1 - Assert-MockCalled Get-BcInstalledExtensions -Exactly 1 - Assert-MockCalled Install-AdminCenterPTE -Exactly 1 + Assert-MockCalled Install-AdminCenterPTE -Exactly 1 -ParameterFilter { + [object]::ReferenceEquals($bcAuthContext, $script:sourceContext) + } + Assert-MockCalled WaitPTEOperation -Exactly 1 -ParameterFilter { + [object]::ReferenceEquals($bcAuthContext, $script:sourceContext) + } + Assert-MockCalled Get-BcInstalledExtensions -Times 0 Assert-MockCalled Publish-PerTenantExtensionApps -Times 0 - Assert-MockCalled Write-Host -Exactly 1 -ParameterFilter { $Object -like '*Admin Center installed-app read failed*Using the read-only Automation API*' } } - It 'Uses the Automation Application version below 29 when the Admin read fails' { - $script:application.versionMajor = 28 - Mock Get-AdminCenterInstalledExtensions { throw '403 Forbidden' } + It 'Uses the full copied paths throughout Admin batch preparation and upload' { + $script:copiedApp = Join-Path $TestDrive 'expanded packages\Publisher_App_2.0.0.0.app' + Mock Copy-AppFilesToFolder { return @($script:copiedApp) } + Mock Sort-AppFilesByDependencies { return $appFiles } - PublishPTEApps -bcAuthContext @{} -environment Sandbox -appFiles @('App.app') + Publish-AdminCenterPTEApps -bcAuthContext @{} -environment Sandbox -appFiles @('Apps.zip') - Assert-MockCalled Get-BcInstalledExtensions -Exactly 1 - Assert-MockCalled Publish-PerTenantExtensionApps -Exactly 1 - Assert-MockCalled Install-AdminCenterPTE -Times 0 - } - - It 'Propagates Automation read failure instead of publishing with a default version' { - Mock Get-AdminCenterInstalledExtensions { throw '403 Forbidden' } - Mock Get-BcInstalledExtensions { throw 'Automation read failed' } - - { PublishPTEApps -bcAuthContext @{} -environment Sandbox -appFiles @('App.app') } | Should -Throw '*Automation read failed*' - - Assert-MockCalled Install-AdminCenterPTE -Times 0 - Assert-MockCalled Publish-PerTenantExtensionApps -Times 0 - } - - It 'Uses the default API family with helper configuration' -TestCases @( - @{ helperConfiguration = 'overridden' }, @{ helperConfiguration = 'missing' } - ) { - param($helperConfiguration) - if ($helperConfiguration -eq 'missing') { - $script:bcContainerHelperConfig = $null + Assert-MockCalled Sort-AppFilesByDependencies -Exactly 1 -ParameterFilter { + $appFiles.Count -eq 1 -and $appFiles[0] -eq $script:copiedApp -and $excludeRuntimePackages } + Assert-MockCalled Get-AppJsonFromAppFile -Exactly 1 -ParameterFilter { $appFile -eq $script:copiedApp } + Assert-MockCalled Install-AdminCenterPTE -Exactly 1 -ParameterFilter { $appFile -eq $script:copiedApp } + Assert-MockCalled WaitPTEOperation -Exactly 1 -ParameterFilter { + $appId -eq 'app-1' -and $operation.id -eq 'operation-1' + } + Assert-MockCalled Remove-Item -Exactly 1 + } + It 'Leaves native target selection to the request boundary' { Mock Install-AdminCenterPTE { + $PesterBoundParameters.Keys | Should -Not -Contain 'apiBaseUrl' $PesterBoundParameters.Keys | Should -Not -Contain 'applicationFamily' return @{ id = 'operation-1'; appId = 'app-1'; status = 'running' } } Mock WaitPTEOperation { - $PesterBoundParameters.Keys | Should -Not -Contain 'applicationFamily' + $PesterBoundParameters.Keys | Should -Not -Contain 'deploymentTarget' } PublishPTEApps -bcAuthContext @{} -environment 'QA / East' -appFiles @('App.app') -schemaSyncMode Force @@ -181,36 +434,7 @@ InModuleScope Deploy { Assert-MockCalled Publish-PerTenantExtensionApps -Times 0 } - It 'Fails explicitly before any publishing when the target version is ' -TestCases @( - @{ problem = 'missing' }, @{ problem = 'incomplete' }, @{ problem = 'invalid' }, @{ problem = 'ambiguous' } - ) { - param($problem) - switch ($problem) { - missing { $script:extensions = @() } - incomplete { $script:application.Remove('versionMinor') } - invalid { $script:application.versionMajor = 'unknown' } - ambiguous { $script:extensions += $script:application.Clone() } - } - - { PublishPTEApps -bcAuthContext @{} -environment 'Sandbox' -appFiles @('App.app') } | Should -Throw '*Could not determine the Business Central version*' - - Assert-MockCalled Publish-PerTenantExtensionApps -Times 0 - Assert-MockCalled Install-AdminCenterPTE -Times 0 - } - - It 'Ignores uninstalled Application records when detecting the target version' { - $oldApplication = $script:application.Clone() - $oldApplication.isInstalled = $false - $oldApplication.versionMajor = 28 - $script:extensions = @($oldApplication, [PSCustomObject]$script:application) - - PublishPTEApps -bcAuthContext @{} -environment 'Sandbox' -appFiles @('App.app') - - Assert-MockCalled Install-AdminCenterPTE -Exactly 1 - Assert-MockCalled Publish-PerTenantExtensionApps -Times 0 - } - - It 'Skips an installed version but not a newer uninstalled package' -TestCases @( + It 'Skips an installed version through Admin Center' -TestCases @( @{ version = 2 }, @{ version = 3 } ) { param($version) @@ -223,6 +447,9 @@ InModuleScope Deploy { Assert-MockCalled Install-AdminCenterPTE -Times 0 Assert-MockCalled WaitPTEOperation -Times 0 + Assert-MockCalled Publish-PerTenantExtensionApps -Times 0 + Assert-MockCalled OutputWarning -Times 0 + Assert-MockCalled Write-Host -Times 0 -ParameterFilter { $Object -like '*already installed*' } } It 'Upgrades an older installed app even if an uninstalled newer package is present' { @@ -242,6 +469,7 @@ InModuleScope Deploy { Mock Sort-AppFilesByDependencies { return @('Dependency.app', 'Dependent.app') } Mock Get-AppJsonFromAppFile { param($appFile) + $script:events += "read:$appFile" return @{ id = $appFile; name = $appFile; version = '2.0.0.0' } } $script:events = @() @@ -257,20 +485,11 @@ InModuleScope Deploy { PublishPTEApps -bcAuthContext @{} -environment 'Sandbox' -appFiles @('Apps.zip') - ($script:events -join ',') | Should -Be 'upload:Dependency.app,complete:Dependency.app,upload:Dependent.app,complete:Dependent.app' + ($script:events -join ',') | Should -Be 'read:Dependency.app,upload:Dependency.app,complete:Dependency.app,read:Dependent.app,upload:Dependent.app,complete:Dependent.app' Assert-MockCalled Sort-AppFilesByDependencies -Exactly 1 -ParameterFilter { $excludeRuntimePackages -and $appFiles.Count -eq 3 } Assert-MockCalled Install-AdminCenterPTE -Times 0 -ParameterFilter { $appFile -eq 'Runtime.app' } } - It 'Remembers completed installs when another package for the same app is encountered' { - Mock Sort-AppFilesByDependencies { return @('App.app', 'Duplicate.app') } - - PublishPTEApps -bcAuthContext @{} -environment 'Sandbox' -appFiles @('App.app', 'Duplicate.app') - - Assert-MockCalled Install-AdminCenterPTE -Exactly 1 - Assert-MockCalled WaitPTEOperation -Exactly 1 - } - It 'Does not fall back or continue after an ambiguous failure' -TestCases @( @{ step = 'upload' }, @{ step = 'polling' }, @{ step = 'authorization' } ) { @@ -288,72 +507,74 @@ InModuleScope Deploy { Assert-MockCalled Remove-Item -Exactly 1 } - It 'Falls back on an explicit authorization rejection with actionable diagnostics and preserves Force' { + It 'Never changes route after upload HTTP , including the first upload' -TestCases @( + @{ statusCode = 400 }, @{ statusCode = 401 }, @{ statusCode = 403 }, + @{ statusCode = 404 }, @{ statusCode = 409 }, @{ statusCode = 500 } + ) { + param($statusCode) + $script:uploadStatus = $statusCode Mock Install-AdminCenterPTE { - $exception = [System.Exception]::new('403 Forbidden: AdminCenter permission missing') - $exception | Add-Member NoteProperty Response ([PSCustomObject]@{ StatusCode = 403 }) + $exception = [System.Exception]::new('Upload rejected') + $exception | Add-Member NoteProperty Response ([PSCustomObject]@{ StatusCode = $script:uploadStatus }) throw $exception } + { PublishPTEApps -bcAuthContext @{} -environment Sandbox -appFiles @('App.app') } | + Should -Throw '*Upload rejected*' + Assert-MockCalled Publish-PerTenantExtensionApps -Times 0 + Assert-MockCalled OutputWarning -Times 0 + } - PublishPTEApps -bcAuthContext @{} -environment Sandbox -appFiles @('App.app') -schemaSyncMode Force + It 'Leaves Automation package preparation and installed-version skipping entirely to BCH' { + $script:ptePublishingApi = 'Automation' + Mock Sort-AppFilesByDependencies { return @('Installed.app', 'First.app', 'Second.app') } + $script:extensions += @{ + id = 'Installed.app'; displayName = 'Installed'; isInstalled = $true + versionMajor = 3; versionMinor = 0; versionBuild = 0; versionRevision = 0 + } + Mock Get-AppJsonFromAppFile { + param($appFile) + return @{ id = $appFile; name = $appFile; version = '2.0.0.0' } + } + Mock Publish-PerTenantExtensionApps { + $bcContainerHelperConfig.apiBaseUrl | Should -Be 'https://api.example.test/' + } + PublishPTEApps -bcAuthContext @{} -environment Sandbox -appFiles @('Apps.zip', 'Installed.app') ` + -schemaSyncMode Force Assert-MockCalled Publish-PerTenantExtensionApps -Exactly 1 -ParameterFilter { - $environment -eq 'Sandbox' -and $appFiles.Count -eq 1 -and $appFiles[0] -eq 'App.app' -and $schemaSyncMode -eq 'Force' + ($appFiles -join ',') -eq 'Apps.zip,Installed.app' -and $schemaSyncMode -eq 'Force' } - Assert-MockCalled OutputWarning -Exactly 1 -ParameterFilter { - $message -like '*403 Forbidden*permission missing*permissions*ContinuousDeployment.md#pte-deployment-authorization*Falling back*' - } - Assert-MockCalled WaitPTEOperation -Times 0 + Assert-MockCalled Copy-AppFilesToFolder -Times 0 + Assert-MockCalled Sort-AppFilesByDependencies -Times 0 + Assert-MockCalled Get-AppJsonFromAppFile -Times 0 + Assert-MockCalled Install-AdminCenterPTE -Times 0 + Assert-MockCalled Get-AdminCenterInstalledExtensions -Times 0 Assert-MockCalled Get-BcInstalledExtensions -Times 0 } - It 'Falls back when the helper reports authentication failed before sending an upload' { - Mock Install-AdminCenterPTE { - throw [System.Management.Automation.ErrorRecord]::new( - [System.Security.Authentication.AuthenticationException]::new('Authentication failed: token missing'), - 'AdminCenterAuthenticationFailed', 'AuthenticationError', $null) - } - PublishPTEApps -bcAuthContext @{} -environment Sandbox -appFiles @('App.app') - + It 'Propagates Automation batch failures without changing route or preparing packages' { + $script:ptePublishingApi = 'Automation' + Mock Publish-PerTenantExtensionApps { throw 'Batch failed' } + { PublishPTEApps -bcAuthContext @{} -environment Sandbox -appFiles @('App.app') } | + Should -Throw '*Batch failed*' + $script:ptePublishingApi | Should -Be Automation Assert-MockCalled Publish-PerTenantExtensionApps -Exactly 1 - Assert-MockCalled OutputWarning -Exactly 1 -ParameterFilter { - $message -like '*Authentication failed: token missing*permissions*Falling back*' - } - Assert-MockCalled Invoke-RestMethod -Times 0 + Assert-MockCalled NewTemporaryFolder -Times 0 + Assert-MockCalled Remove-Item -Times 0 + Assert-MockCalled Get-AdminCenterInstalledExtensions -Times 0 + Assert-MockCalled Install-AdminCenterPTE -Times 0 } - It 'Classifies installation HTTP without replaying ambiguous requests' -TestCases @( - @{ statusCode = 400; allowed = $false }, - @{ statusCode = 401; allowed = $true }, - @{ statusCode = 403; allowed = $true }, - @{ statusCode = 404; allowed = $false }, - @{ statusCode = 405; allowed = $false }, - @{ statusCode = 409; allowed = $false }, - @{ statusCode = 413; allowed = $false }, - @{ statusCode = 415; allowed = $false }, - @{ statusCode = 422; allowed = $false }, - @{ statusCode = 429; allowed = $false }, - @{ statusCode = 500; allowed = $false }, - @{ statusCode = 503; allowed = $false } - ) { - param($statusCode, $allowed) - $script:installStatus = $statusCode - Mock Install-AdminCenterPTE { - $exception = [System.Exception]::new("Service HTTP $script:installStatus") - $exception | Add-Member NoteProperty Response ([PSCustomObject]@{ StatusCode = $script:installStatus }) - $exception.Data['AdminCenterRequestStarted'] = $true - throw $exception + It 'Preserves distinct versions from the dependency sorter without synthetic installed entries' { + Mock Sort-AppFilesByDependencies { return @('Newer.app', 'Older.app') } + Mock Get-AppJsonFromAppFile { + param($appFile) + return @{ id = 'app-1'; name = 'App'; version = $(if ($appFile -eq 'Newer.app') { '3.0.0.0' } else { '2.0.0.0' }) } } + PublishPTEApps -bcAuthContext @{} -environment Sandbox -appFiles @('Apps.zip') - if ($allowed) { - PublishPTEApps -bcAuthContext @{} -environment Sandbox -appFiles @('App.app') - Assert-MockCalled Publish-PerTenantExtensionApps -Exactly 1 - } - else { - { PublishPTEApps -bcAuthContext @{} -environment Sandbox -appFiles @('App.app') } | Should -Throw "*Service HTTP $statusCode*" - Assert-MockCalled Publish-PerTenantExtensionApps -Times 0 - } - Assert-MockCalled Install-AdminCenterPTE -Exactly 1 + Assert-MockCalled Install-AdminCenterPTE -Exactly 2 + $script:extensions.Count | Should -Be 1 } It 'Does not fall back for a local file preparation failure reported before sending' { @@ -397,119 +618,6 @@ InModuleScope Deploy { Assert-MockCalled Install-AdminCenterPTE -Exactly 1 } - It 'Stops without fallback on an authorization failure after an Admin success' -TestCases @( - @{ statusCode = 401 }, @{ statusCode = 403 } - ) { - param($statusCode) - $script:installStatus = $statusCode - Mock Sort-AppFilesByDependencies { return @('First.app', 'Second.app', 'Duplicate.app', 'Third.app') } - Mock Get-AppJsonFromAppFile { - param($appFile) - $id = if ($appFile -eq 'Duplicate.app') { 'First.app' } else { $appFile } - return @{ id = $id; name = $id; version = '2.0.0.0' } - } - Mock Install-AdminCenterPTE { - param($appFile) - if ($appFile -eq 'Second.app') { - $exception = [System.Exception]::new('Authorization rejected after first app') - $exception | Add-Member NoteProperty Response ([PSCustomObject]@{ StatusCode = $script:installStatus }) - throw $exception - } - return @{ id = 'completed'; appId = $appFile; status = 'succeeded' } - } - - $results = @{} - { PublishPTEApps -bcAuthContext @{} -environment Sandbox -appFiles @('Apps.zip') -publishingResults $results } | - Should -Throw '*Authorization rejected after first app*' - - Assert-MockCalled Install-AdminCenterPTE -Exactly 2 - Assert-MockCalled WaitPTEOperation -Exactly 1 -ParameterFilter { $appId -eq 'First.app' } - Assert-MockCalled Publish-PerTenantExtensionApps -Times 0 - Assert-MockCalled Install-AdminCenterPTE -Times 0 -ParameterFilter { $appFile -in 'Duplicate.app','Third.app' } - $results['First.app'] | Should -Be 'AdminCenter' - $results.ContainsKey('Second.app') | Should -BeFalse - $results.ContainsKey('Third.app') | Should -BeFalse - } - - It 'Falls back once for the ordered eligible batch without retrying Admin for later apps' { - Mock Sort-AppFilesByDependencies { return @('Installed.app', 'First.app', 'Duplicate.app', 'Second.app', 'Third.app') } - $script:extensions += @{ - id = 'Installed.app'; displayName = 'Installed'; isInstalled = $true - versionMajor = 3; versionMinor = 0; versionBuild = 0; versionRevision = 0 - } - Mock Get-AppJsonFromAppFile { - param($appFile) - $id = if ($appFile -eq 'Duplicate.app') { 'First.app' } else { $appFile } - return @{ id = $id; name = $id; version = '2.0.0.0' } - } - Mock Install-AdminCenterPTE { - $exception = [System.Exception]::new('User not authorized') - $exception | Add-Member NoteProperty Response ([PSCustomObject]@{ StatusCode = 403 }) - throw $exception - } - $results = @{} - - PublishPTEApps -bcAuthContext @{} -environment Sandbox -appFiles @('Apps.zip') -publishingResults $results - - Assert-MockCalled Install-AdminCenterPTE -Exactly 1 -ParameterFilter { $appFile -eq 'First.app' } - Assert-MockCalled WaitPTEOperation -Times 0 - Assert-MockCalled Publish-PerTenantExtensionApps -Exactly 1 -ParameterFilter { - ($appFiles -join ',') -eq 'First.app,Second.app,Third.app' - } - Assert-MockCalled Get-BcInstalledExtensions -Times 0 - $results['Installed.app'] | Should -Be 'Skipped' - $results['First.app'] | Should -Be 'Automation' - $results['Second.app'] | Should -Be 'Automation' - $results['Third.app'] | Should -Be 'Automation' - } - - It 'Retains Admin Center cleanup protection across dependency and primary batches for the same app' { - $results = @{} - PublishPTEApps -bcAuthContext @{} -environment Sandbox -appFiles @('Dependency.app') -publishingResults $results - $results['app-1'] | Should -Be 'AdminCenter' - Mock Get-AppJsonFromAppFile { return @{ id = 'app-1'; name = 'App'; version = '3.0.0.0' } } - Mock Install-AdminCenterPTE { - $exception = [System.Exception]::new('Authorization rejected') - $exception | Add-Member NoteProperty Response ([PSCustomObject]@{ StatusCode = 403 }) - throw $exception - } - - PublishPTEApps -bcAuthContext @{} -environment Sandbox -appFiles @('Primary.app') -publishingResults $results - - Assert-MockCalled Publish-PerTenantExtensionApps -Exactly 1 - $results['app-1'] | Should -Be 'AdminCenter' - } - - It 'Does not retain publishing paths from a different action' { - $firstResults = @{} - PublishPTEApps -bcAuthContext @{} -environment Sandbox -appFiles @('App.app') -publishingResults $firstResults - Mock Install-AdminCenterPTE { - $exception = [System.Exception]::new('Authorization rejected') - $exception | Add-Member NoteProperty Response ([PSCustomObject]@{ StatusCode = 403 }) - throw $exception - } - $secondResults = @{} - - PublishPTEApps -bcAuthContext @{} -environment Sandbox -appFiles @('App.app') -publishingResults $secondResults - - $firstResults['app-1'] | Should -Be 'AdminCenter' - $secondResults['app-1'] | Should -Be 'Automation' - } - - It 'Propagates a legacy fallback failure without continuing or claiming success' { - Mock Install-AdminCenterPTE { - $exception = [System.Exception]::new('Authorization rejected') - $exception | Add-Member NoteProperty Response ([PSCustomObject]@{ StatusCode = 403 }) - throw $exception - } - Mock Publish-PerTenantExtensionApps { throw 'Legacy publishing failed' } - - { PublishPTEApps -bcAuthContext @{} -environment Sandbox -appFiles @('App.app') } | Should -Throw '*Legacy publishing failed*' - - Assert-MockCalled Publish-PerTenantExtensionApps -Exactly 1 - Assert-MockCalled Remove-Item -Exactly 1 - } - It 'Stops without fallback after a terminal operation failure' { Mock WaitPTEOperation { throw 'Operation failed: rejected package' @@ -559,6 +667,15 @@ InModuleScope Deploy { Assert-MockCalled Get-AdminCenterAppOperation -Times 0 } + It 'Leaves exact-operation target selection to the native request boundary' { + WaitPTEOperation -bcAuthContext @{} -environment Sandbox -operation $script:operation -appId 'app-1' + + Assert-MockCalled Get-AdminCenterAppOperation -Exactly 1 -ParameterFilter { + !$PesterBoundParameters.ContainsKey('apiBaseUrl') -and !$PesterBoundParameters.ContainsKey('applicationFamily') -and + $appId -eq 'app-1' -and $operationId -eq 'operation / 1' + } + } + It 'Reports terminal or unrecognized without fallback metadata' -TestCases @( @{ status = 'failed' }, @{ status = 'canceled' }, diff --git a/Tests/ReadSettings.Test.ps1 b/Tests/ReadSettings.Test.ps1 index aba354d922..937d873fe5 100644 --- a/Tests/ReadSettings.Test.ps1 +++ b/Tests/ReadSettings.Test.ps1 @@ -27,6 +27,18 @@ InModuleScope ReadSettings { # Allows testing of private functions $settingsSchema.properties.skipDraftPullRequests.default | Should -BeFalse } + It 'Aligns deployment target defaults with the settings schema' { + . (Join-Path $PSScriptRoot '../Actions/AL-Go-Helper.ps1') + $defaults = GetDefaultSettings + $settingsSchema = $schema | ConvertFrom-Json | ConvertTo-HashTable -recurse + $defaults.deploymentBaseUrl | Should -Be '' + $defaults.deploymentApplicationFamily | Should -Be 'BusinessCentral' + foreach ($name in @('deploymentBaseUrl', 'deploymentApplicationFamily')) { + $settingsSchema.properties[$name].type | Should -Be 'string' + $settingsSchema.properties[$name].default | Should -Be $defaults[$name] + } + } + It 'Reads settings from all settings locations' { Mock Write-Host { } Mock Out-Host { } diff --git a/Tests/UnpublishOldAppVersions.Test.ps1 b/Tests/UnpublishOldAppVersions.Test.ps1 index 036855a69a..3cd1bda977 100644 --- a/Tests/UnpublishOldAppVersions.Test.ps1 +++ b/Tests/UnpublishOldAppVersions.Test.ps1 @@ -11,6 +11,7 @@ InModuleScope Deploy { # Allows testing of private functions } BeforeEach { + $script:ptePublishingApi = '' Mock OutputDebugFunctionCall { } Mock OutputWarning { } Mock Write-Host { } @@ -63,6 +64,27 @@ InModuleScope Deploy { # Allows testing of private functions } } + It 'Keeps every cleanup request on the configured deployment API root' { + $originalApiBaseUrl = $bcContainerHelperConfig.apiBaseUrl + try { + $bcContainerHelperConfig.apiBaseUrl = 'https://api.embed.test/service/' + UnpublishOldAppVersions -bcAuthContext @{ tenantId = 'test-tenant' } -environment 'test-env' -appFiles @('App1.app') + + Assert-MockCalled Invoke-RestMethod -Exactly 3 -ParameterFilter { + $Uri -like 'https://api.embed.test/service/v2.0/test-env/api/microsoft/automation/v2.0/*' + } + Assert-MockCalled Invoke-RestMethod -Times 0 -ParameterFilter { + $Uri -notlike 'https://api.embed.test/service/*' + } + Assert-MockCalled Invoke-RestMethod -Exactly 1 -ParameterFilter { + $Method -eq 'Post' -and $Uri -like '*extensions(pkg-app1-v1)/Microsoft.NAV.unpublish' + } + } + finally { + $bcContainerHelperConfig.apiBaseUrl = $originalApiBaseUrl + } + } + It 'Explains delayed service-managed cleanup without any writes on BC .' -TestCases @( @{ major = 29; minor = 0 }, @{ major = 29; minor = 9 }, @@ -73,13 +95,15 @@ InModuleScope Deploy { # Allows testing of private functions param($major, $minor) $script:applicationExtension.versionMajor = $major $script:applicationExtension.versionMinor = $minor + $script:ptePublishingApi = 'AdminCenter' - { UnpublishOldAppVersions -bcAuthContext @{ tenantId = "test-tenant" } -environment "test-env" -appFiles @("App1.app") -publishingResults @{ $script:appId = 'AdminCenter' } } | Should -Not -Throw + { UnpublishOldAppVersions -bcAuthContext @{ tenantId = "test-tenant" } -environment "test-env" -appFiles @("App1.app") } | Should -Not -Throw Assert-MockCalled OutputWarning -Exactly 1 -ParameterFilter { $message -like "*skips explicit cleanup*Admin Center publishing*Business Central manages cleanup in the background*may be delayed*timing and retained versions are not guaranteed*deployment remains successful*" } Assert-MockCalled Invoke-RestMethod -Times 0 -ParameterFilter { $Method -ne "Get" } + Assert-MockCalled Invoke-RestMethod -Times 0 } It 'Uses legacy cleanup after Automation fallback on BC ' -TestCases @( @@ -87,8 +111,9 @@ InModuleScope Deploy { # Allows testing of private functions ) { param($major) $script:applicationExtension.versionMajor = $major + $script:ptePublishingApi = 'Automation' - UnpublishOldAppVersions -bcAuthContext @{} -environment test-env -appFiles @('App1.app') -publishingResults @{ $script:appId = 'Automation' } + UnpublishOldAppVersions -bcAuthContext @{} -environment test-env -appFiles @('App1.app') Assert-MockCalled Invoke-RestMethod -Exactly 1 -ParameterFilter { $Method -eq 'Post' -and $Uri -like '*extensions(pkg-app1-v1)/Microsoft.NAV.unpublish' @@ -96,31 +121,48 @@ InModuleScope Deploy { # Allows testing of private functions Assert-MockCalled OutputWarning -Times 0 } - It 'Only cleans Automation apps in a mixed-path batch and preserves installed and newer packages' { + It 'Cleans all selected primary apps through Automation on BC 29' { $script:applicationExtension.versionMajor = 29 + $script:ptePublishingApi = 'Automation' $script:mockExtensions += @( @{ id = $script:appId; displayName = 'App 1'; packageId = 'pkg-app1-v3'; isInstalled = $false; versionMajor = 3; versionMinor = 0; versionBuild = 0; versionRevision = 0 }, @{ id = $script:otherAppId; displayName = 'Other App'; packageId = 'pkg-other-v1'; isInstalled = $false; versionMajor = 1; versionMinor = 0; versionBuild = 0; versionRevision = 0 }, @{ id = $script:otherAppId; displayName = 'Other App'; packageId = 'pkg-other-v2'; isInstalled = $true; versionMajor = 2; versionMinor = 0; versionBuild = 0; versionRevision = 0 } ) - UnpublishOldAppVersions -bcAuthContext @{} -environment test-env -appFiles @('App1.app', 'OtherApp.app') -publishingResults @{ - $script:appId = 'Automation' - $script:otherAppId = 'AdminCenter' - } + UnpublishOldAppVersions -bcAuthContext @{} -environment test-env -appFiles @('App1.app', 'OtherApp.app') - Assert-MockCalled Invoke-RestMethod -Exactly 1 -ParameterFilter { $Method -eq 'Post' } + Assert-MockCalled Invoke-RestMethod -Exactly 2 -ParameterFilter { $Method -eq 'Post' } Assert-MockCalled Invoke-RestMethod -Exactly 1 -ParameterFilter { $Method -eq 'Post' -and $Uri -like '*pkg-app1-v1*' } - Assert-MockCalled Invoke-RestMethod -Times 0 -ParameterFilter { $Method -eq 'Post' -and $Uri -like '*pkg-other*' } + Assert-MockCalled Invoke-RestMethod -Exactly 1 -ParameterFilter { $Method -eq 'Post' -and $Uri -like '*pkg-other-v1*' } + Assert-MockCalled Invoke-RestMethod -Times 0 -ParameterFilter { + $Method -eq 'Post' -and $Uri -notlike '*pkg-app1-v1*' -and $Uri -notlike '*pkg-other-v1*' + } } - It 'Does not infer an Automation outcome from the environment version or a skipped app' { - $script:applicationExtension.versionMajor = 29 + It 'Cleans stale versions of a skipped primary app on BC without touching installed, current, newer or unselected packages' -TestCases @( + @{ major = 29 }, @{ major = 30 }, @{ major = 31 } + ) { + param($major) + $script:applicationExtension.versionMajor = $major + $script:ptePublishingApi = 'Automation' + $script:mockExtensions = @( + @{ id = $script:appId; displayName = 'App 1'; packageId = 'pkg-app1-v1'; isInstalled = $false; versionMajor = 1; versionMinor = 0; versionBuild = 0; versionRevision = 0 }, + @{ id = $script:appId; displayName = 'App 1'; packageId = 'pkg-app1-v2'; isInstalled = $true; versionMajor = 2; versionMinor = 0; versionBuild = 0; versionRevision = 0 }, + @{ id = $script:appId; displayName = 'App 1'; packageId = 'pkg-app1-v3'; isInstalled = $true; versionMajor = 3; versionMinor = 0; versionBuild = 0; versionRevision = 0 }, + @{ id = $script:appId; displayName = 'App 1'; packageId = 'pkg-app1-v3-copy'; isInstalled = $false; versionMajor = 3; versionMinor = 0; versionBuild = 0; versionRevision = 0 }, + @{ id = $script:appId; displayName = 'App 1'; packageId = 'pkg-app1-v4'; isInstalled = $false; versionMajor = 4; versionMinor = 0; versionBuild = 0; versionRevision = 0 }, + @{ id = $script:otherAppId; displayName = 'Dependency'; packageId = 'pkg-other-v1'; isInstalled = $false; versionMajor = 1; versionMinor = 0; versionBuild = 0; versionRevision = 0 }, + @{ id = $script:otherAppId; displayName = 'Dependency'; packageId = 'pkg-other-v2'; isInstalled = $true; versionMajor = 2; versionMinor = 0; versionBuild = 0; versionRevision = 0 } + ) - UnpublishOldAppVersions -bcAuthContext @{} -environment test-env -appFiles @('App1.app') -publishingResults @{ $script:appId = 'Skipped' } + UnpublishOldAppVersions -bcAuthContext @{} -environment test-env -appFiles @('App1.app') - Assert-MockCalled Invoke-RestMethod -Times 0 -ParameterFilter { $Method -ne 'Get' } - Assert-MockCalled OutputWarning -Exactly 1 + Assert-MockCalled Invoke-RestMethod -Exactly 1 -ParameterFilter { $Method -eq 'Post' } + Assert-MockCalled Invoke-RestMethod -Exactly 1 -ParameterFilter { + $Method -eq 'Post' -and $Uri -like '*extensions(pkg-app1-v1)/Microsoft.NAV.unpublish' + } + Assert-MockCalled OutputWarning -Times 0 } It 'Preserves legacy cleanup on BC .' -TestCases @( diff --git a/Workshop/ContinuousDeployment.md b/Workshop/ContinuousDeployment.md index 340c0f09e8..50a084c288 100644 --- a/Workshop/ContinuousDeployment.md +++ b/Workshop/ContinuousDeployment.md @@ -94,17 +94,34 @@ For **BC 29 or later**, AL-Go prefers administration center publishing for PTEs. With delegated authentication (impersonation), administration center publishing requires appropriate **Business Central administration center access** as well as the environment permissions. The existing **AUTHCONTEXT** credential structure and the commands above remain unchanged. See the official [Business Central administration center API documentation](https://learn.microsoft.com/en-us/dynamics365/business-central/dev-itpro/administration/administration-center-api) for authentication and authorization details. -If authentication or authorization fails before any app in a publishing batch succeeds through the administration center, AL-Go warns and submits the eligible apps together through the existing Automation API. Update the authorization above to use the preferred publishing path. Deployment failures, uncertain outcomes, and any error after an administration center publish succeeds stop the batch without fallback. Dependency and primary-app batches are evaluated separately. A failure of the fallback also fails deployment. +Before dependency installation and primary PTE publishing, AL-Go checks administration center access once by reading the target's installed apps. If this check fails authentication or authorization, AL-Go warns and selects the existing Automation API. Other check failures stop deployment. All PTE publishing and installed-app reads then use the selected API; failures never switch APIs. Dev deployments without PTE dependency packages do not perform this check. + +A successful read does not guarantee permission to install apps. If installation or operation tracking later fails, including an authorization error, deployment stops. Update the authorization above to use the preferred publishing path. This behavior also applies when a **Scope Dev** deployment installs or upgrades a PTE dependency on **BC 29 or later**. Publishing primary apps through the sandbox development endpoint does not itself require the additional authorization. Deployment to earlier BC versions is unchanged. +## Custom deployment targets + +For native Admin Center calls to an Embed or other custom service, set the repository settings `deploymentBaseUrl` (the HTTPS API root) and `deploymentApplicationFamily` (the service's exact application family). These apply to installed-app reads, PTE publishing and operation tracking only. For example: + +```json +{ + "deploymentBaseUrl": "https://api.example.com", + "deploymentApplicationFamily": "YourApplicationFamily" +} +``` + +Empty or omitted `deploymentBaseUrl` uses `https://api.businesscentral.dynamics.com`, regardless of BCH settings. The family defaults to `BusinessCentral` and is never inferred from the host. Automation and AppSource operations keep their existing BCH configuration and authentication; configure `bcContainerHelperConfig.apiBaseUrl` separately if needed. The web-client/readiness URL remains `bcContainerHelperConfig.baseUrl`. + +Each Deploy run maintains a separate Admin authentication context and reuses its renewed tokens, using the Admin API root as the default OAuth resource without changing the BCH context. Explicit `AUTHCONTEXT` scopes or resource values are preserved, not retargeted; they must authorize the Admin service too. Credentials must support token renewal for that resource, and the service must support the corresponding API contracts and authorization. + ## Old published versions For apps published through the administration center, AL-Go leaves old-version cleanup to Business Central. Older published versions may remain after deployment until background cleanup runs. On a BC 30 sandbox, cleanup was observed after an overnight interval, leaving the installed version and the latest uninstalled version; this is not a guaranteed nightly schedule or retention policy. The optional `DeployTo.unpublishOldVersions` boolean (default `false`) does not control background cleanup. When enabled, AL-Go warns and skips explicit unpublish for apps published through the administration center without failing deployment. -For Automation publishing, including fallback on **BC 29 and later**, enabling the setting removes only selected apps' uninstalled versions older than their currently installed version after successful **Scope PTE** publishing. This requires **BC 25.4 or later**. In a mixed-path deployment, only Automation apps are explicitly cleaned. If any version of an app was published through the administration center during the action, that app remains excluded from explicit cleanup, including across dependency and primary-app batches. On BC 29+, apps skipped because an equal or newer version is already installed are excluded unless the action already recorded a successful Automation publish for that app. Cleanup errors remain warnings, and the setting does not apply to Scope Dev or custom deployments. +For Automation publishing, enabling the setting removes only selected primary apps' uninstalled versions older than their currently installed version after successful **Scope PTE** publishing, including apps skipped because the same or a newer version is installed. This requires **BC 25.4 or later**. Cleanup errors remain warnings, and the setting does not apply to Scope Dev or custom deployments. ## Custom Deployments From 79e9e6e6def468bd6e3c0df292de84cc34a17dd6 Mon Sep 17 00:00:00 2001 From: spetersenms Date: Fri, 13 Nov 2026 17:30:15 +0100 Subject: [PATCH 07/12] Smaller fixes --- Actions/.Modules/AdminCenterApi.psm1 | 97 ++++++------- Actions/Deploy/Deploy.ps1 | 6 +- Actions/Deploy/Deploy.psm1 | 49 ++++--- Actions/Deploy/README.md | 2 +- Tests/AdminCenterApi.Test.ps1 | 145 +++++++++---------- Tests/Deploy.Action.Test.ps1 | 165 +++++++++++++++++++++- Tests/PublishPTEApps.Test.ps1 | 201 ++++++++++++++++++++++----- Workshop/ContinuousDeployment.md | 2 + 8 files changed, 471 insertions(+), 196 deletions(-) diff --git a/Actions/.Modules/AdminCenterApi.psm1 b/Actions/.Modules/AdminCenterApi.psm1 index 94a32c73d0..8e755ad5ea 100644 --- a/Actions/.Modules/AdminCenterApi.psm1 +++ b/Actions/.Modules/AdminCenterApi.psm1 @@ -3,16 +3,15 @@ $errorActionPreference = "Stop"; $ProgressPreference = "SilentlyContinue"; Set-S # Pin the contract AL-Go implements; update this with its callers and contract tests. $adminCenterApiVersion = 'v2.29' $script:adminCenterAuthContext = $null -$script:adminCenterSourceContext = $null $script:adminCenterTarget = $null <# .SYNOPSIS Prepare the Admin Center target and authentication context for this Deploy action. .DESCRIPTION - Native requests using this original BCH context share the owned target and Admin context. - .PARAMETER bcAuthContext - Original BCH authentication context, retained unchanged. + Retains the supplied independent context and target for all native requests. + .PARAMETER authContext + Dedicated Admin authentication context supplied by the caller, not the original BCH context. .PARAMETER settings AL-Go settings containing the native API root and application family. .PARAMETER preserveScopes @@ -20,20 +19,19 @@ $script:adminCenterTarget = $null #> function Initialize-AdminCenterAuthContext { Param( - [hashtable] $bcAuthContext, + [Parameter(Mandatory = $true)] + [hashtable] $authContext, [hashtable] $settings = @{}, [switch] $preserveScopes ) $target = Get-DeploymentTarget -settings $settings - $adminContext = $bcAuthContext.Clone() - $scopes = if ($preserveScopes) { $adminContext['Scopes'] } else { "$($target.apiBaseUrl)/" } - if ($adminContext['Scopes'] -ne $scopes) { - $adminContext['Scopes'] = $scopes - $adminContext['UtcExpiresOn'] = [DateTime]::MinValue + $scopes = if ($preserveScopes) { $authContext['Scopes'] } else { "$($target.apiBaseUrl)/" } + if ($authContext['Scopes'] -ne $scopes) { + $authContext['Scopes'] = $scopes + $authContext['UtcExpiresOn'] = [DateTime]::MinValue } - $script:adminCenterAuthContext = $adminContext - $script:adminCenterSourceContext = $bcAuthContext + $script:adminCenterAuthContext = $authContext $script:adminCenterTarget = $target } @@ -131,10 +129,8 @@ function Get-AdminCenterApiErrorMessage { Send one authenticated Admin Center request without retries. .DESCRIPTION Preserves HTTP errors and records whether sending was attempted in Exception.Data. - Uses the initialized Deploy target unless explicitly overridden and retains renewed authentication. - Other callers use standard target defaults and their supplied context without changing action state. - .PARAMETER bcAuthContext - Authentication context to renew. + Requires the dedicated Admin context and target to be initialized before use. + Uses that target unless explicitly overridden and retains renewed authentication. .PARAMETER environment Target environment. .PARAMETER path @@ -154,7 +150,6 @@ function Get-AdminCenterApiErrorMessage { #> function Invoke-AdminCenterApi { Param( - [hashtable] $bcAuthContext, [string] $environment, [string[]] $path, [ValidateSet('Get', 'Post')] @@ -169,22 +164,20 @@ function Invoke-AdminCenterApi { $requestStarted = $false try { - $actionContext = $null -ne $script:adminCenterAuthContext -and - [object]::ReferenceEquals($bcAuthContext, $script:adminCenterSourceContext) - if ($actionContext) { - if (!$PSBoundParameters.ContainsKey('apiBaseUrl')) { $apiBaseUrl = $script:adminCenterTarget.apiBaseUrl } - if (!$PSBoundParameters.ContainsKey('applicationFamily')) { $applicationFamily = $script:adminCenterTarget.applicationFamily } + if ($null -eq $script:adminCenterAuthContext -or $null -eq $script:adminCenterTarget) { + throw 'The Admin Center context and target must be initialized before making requests.' } + if (!$PSBoundParameters.ContainsKey('apiBaseUrl')) { $apiBaseUrl = $script:adminCenterTarget.apiBaseUrl } + if (!$PSBoundParameters.ContainsKey('applicationFamily')) { $applicationFamily = $script:adminCenterTarget.applicationFamily } $uri = Get-AdminCenterApiUrl -environment $environment -applicationFamily $applicationFamily -apiBaseUrl $apiBaseUrl $uri += '/' + (($path | ForEach-Object { [Uri]::EscapeDataString($_) }) -join '/') - $adminContext = if ($actionContext) { $script:adminCenterAuthContext } else { $bcAuthContext.Clone() } - $authContext = Renew-BcAuthContext -bcAuthContext $adminContext + $authContext = Renew-BcAuthContext -bcAuthContext $script:adminCenterAuthContext if (!$authContext -or !$authContext['AccessToken']) { throw [System.Management.Automation.ErrorRecord]::new( [System.Security.Authentication.AuthenticationException]::new('Authentication failed before Admin Center request.'), 'AdminCenterAuthenticationFailed', 'AuthenticationError', $null) } - if ($actionContext) { $script:adminCenterAuthContext = $authContext } + $script:adminCenterAuthContext = $authContext Write-Host "::add-mask::$($authContext.AccessToken)" $parameters = @{ Uri = $uri @@ -210,9 +203,7 @@ function Invoke-AdminCenterApi { Upload an app package for immediate PTE installation. .DESCRIPTION Builds and disposes multipart content using binary serialization supported on PowerShell 5 and 7. - Makes one upload attempt without retries. - .PARAMETER bcAuthContext - Authentication context. + Makes one upload attempt without retries using the initialized Admin context. .PARAMETER environment Target environment. .PARAMETER appFile @@ -226,7 +217,6 @@ function Invoke-AdminCenterApi { #> function Install-AdminCenterPTE { Param( - [hashtable] $bcAuthContext, [string] $environment, [string] $appFile, [ValidateSet('Add', 'ForceSync')] @@ -266,8 +256,8 @@ function Install-AdminCenterPTE { <# .SYNOPSIS Read the exact app operation without polling or retrying. - .PARAMETER bcAuthContext - Authentication context. + .DESCRIPTION + Uses the initialized Admin authentication context and target. .PARAMETER environment Target environment. .PARAMETER appId @@ -283,7 +273,6 @@ function Install-AdminCenterPTE { #> function Get-AdminCenterAppOperation { Param( - [hashtable] $bcAuthContext, [string] $environment, [string] $appId, [string] $operationId, @@ -304,12 +293,12 @@ function Get-AdminCenterAppOperation { Read installed extensions from Admin Center in the deployment extension format. .DESCRIPTION Uses the observed id/name/version/state response and accepts the documented appId identity. - Returns installed apps only, with full version components for existing deployment checks. - Installed, UpdatePending and Updating all describe installed apps. The documented appType - is retained as publishedAs so deployment can preserve its Dev-scope dependency safeguard. - Missing or malformed installed-app data fails explicitly. - .PARAMETER bcAuthContext - Authentication context. + Returns installed-app records with full version components when valid. + The endpoint returns installed apps. The appType is retained as publishedAs so deployment + can preserve its Dev-scope dependency safeguard. Records without an unambiguous identity + fail explicitly. Invalid or incomplete versions retain empty version components so + selected-app version comparisons fail rather than assume a version. + Uses the initialized Admin authentication context and target. .PARAMETER environment Target environment. .PARAMETER applicationFamily @@ -319,7 +308,6 @@ function Get-AdminCenterAppOperation { #> function Get-AdminCenterInstalledExtensions { Param( - [hashtable] $bcAuthContext, [string] $environment, [string] $applicationFamily = 'BusinessCentral', [string] $apiBaseUrl = 'https://api.businesscentral.dynamics.com' @@ -331,30 +319,27 @@ function Get-AdminCenterInstalledExtensions { throw 'Admin Center installed-app response must contain an apps array.' } foreach ($app in $response['value']) { - if ($app -isnot [hashtable] -or $app['state'] -isnot [string] -or !$app['state'].Trim()) { - throw 'Admin Center app is missing its installation state.' - } - if ($app['state'] -notin 'installed', 'updatePending', 'updating') { - throw 'Admin Center app has an unsupported installation state.' + if ($app -isnot [hashtable]) { + throw 'Admin Center installed app has missing or invalid identity.' } $id = if ($app['appId']) { $app['appId'] } else { $app['id'] } - $version = $null if ($id -isnot [string] -or !$id.Trim() -or - ($app['appId'] -and $app['id'] -and $app['appId'] -ne $app['id']) -or - $app['name'] -isnot [string] -or !$app['name'].Trim() -or - $app['version'] -isnot [string] -or - ![version]::TryParse($app['version'], [ref]$version) -or $version.Revision -lt 0 -or - $app['appType'] -notin 'global', 'tenant', 'dev') { - throw 'Admin Center installed app has missing or invalid identity, name, full version or app type.' + ($app['appId'] -and $app['id'] -and $app['appId'] -ne $app['id'])) { + throw 'Admin Center installed app has missing or conflicting identity.' + } + $version = $null + if ($app['version'] -isnot [string] -or + ![version]::TryParse($app['version'], [ref]$version) -or $version.Revision -lt 0) { + $version = $null } [PSCustomObject]@{ id = $id displayName = $app['name'] - version = $version.ToString() - versionMajor = $version.Major - versionMinor = $version.Minor - versionBuild = $version.Build - versionRevision = $version.Revision + version = $app['version'] + versionMajor = if ($version) { $version.Major } else { $null } + versionMinor = if ($version) { $version.Minor } else { $null } + versionBuild = if ($version) { $version.Build } else { $null } + versionRevision = if ($version) { $version.Revision } else { $null } isInstalled = $true state = $app['state'] publishedAs = $app['appType'] diff --git a/Actions/Deploy/Deploy.ps1 b/Actions/Deploy/Deploy.ps1 index 1d60d5a1a7..0fcb6eb2a0 100644 --- a/Actions/Deploy/Deploy.ps1 +++ b/Actions/Deploy/Deploy.ps1 @@ -125,8 +125,6 @@ else { if ($null -eq $bcAuthContext) { throw "Authentication failed" } - Initialize-AdminCenterAuthContext -bcAuthContext $bcAuthContext -settings $settings ` - -preserveScopes:([bool]($authContextParams['scopes'] -or $authContextParams['resource'])) } catch { throw "Authentication failed. $([environment]::Newline) $($_.exception.message)" } @@ -181,6 +179,10 @@ else { } } if ($scope -eq 'PTE' -or $hasPTEDependencies) { + # This copy will eventually be replaced by AL-Go native auth. + $adminAuthContext = $bcAuthContext.Clone() + Initialize-AdminCenterAuthContext -authContext $adminAuthContext -settings $settings ` + -preserveScopes:([bool]($authContextParams['scopes'] -or $authContextParams['resource'])) Initialize-PTEPublishingApi -bcAuthContext $bcAuthContext -environment $deploymentSettings.EnvironmentName } if ($dependencies) { diff --git a/Actions/Deploy/Deploy.psm1 b/Actions/Deploy/Deploy.psm1 index 8c95683b15..94e47ba909 100644 --- a/Actions/Deploy/Deploy.psm1 +++ b/Actions/Deploy/Deploy.psm1 @@ -194,7 +194,7 @@ function CheckIfAppNeedsInstallOrUpgrade { $needsUpgrade = $false if ($installedApp) { $dependencyVersion = [version]::new($appJson.Version) - $installedVersion = [version]::new($installedApp.versionMajor, $installedApp.versionMinor, $installedApp.versionBuild, $installedApp.versionRevision) + $installedVersion = [version]::new("$($installedApp.versionMajor).$($installedApp.versionMinor).$($installedApp.versionBuild).$($installedApp.versionRevision)") if ($dependencyVersion -gt $installedVersion) { $msg = "Dependency app $($appJson.name) is already installed in version $installedVersion, which is lower than $dependencyVersion." if ($installMode -eq 'upgrade') { @@ -246,7 +246,7 @@ function CheckInstalledApps { # Check if the version of the installed app is lower than the version in the app file if ($installedApp) { $currentVersion = [version]::new($appJson.Version) - $installedVersion = [version]::new($installedApp.versionMajor, $installedApp.versionMinor, $installedApp.versionBuild, $installedApp.versionRevision) + $installedVersion = [version]::new("$($installedApp.versionMajor).$($installedApp.versionMinor).$($installedApp.versionBuild).$($installedApp.versionRevision)") if ($currentVersion -lt $installedVersion) { OutputWarning -message "App $($appJson.name) is already installed in version $installedVersion, which is higher than $currentVersion, used in app.json. In order to install version $currentVersion, the higher version must be uninstalled first." @@ -269,7 +269,10 @@ function GetPTEApplicationVersion { [string] $environment ) - $applications = @($extensions | Where-Object { $_.displayName -eq 'Application' -and $_.isInstalled }) + $applications = @($extensions | Where-Object { + $app = $_ | ConvertTo-HashTable -recurse + ($app['displayName'] -eq 'Application' -or $app['id'] -eq $applicationAppId) -and $app['isInstalled'] + }) $version = $null if ($applications.Count -eq 1) { $application = $applications[0] | ConvertTo-HashTable -recurse @@ -287,7 +290,7 @@ function GetPTEApplicationVersion { .SYNOPSIS Read installed apps using the selected API, or the original BCH API for non-PTE work. .PARAMETER bcAuthContext - Business Central authentication context. + Original BCH authentication context, used only for Automation reads. .PARAMETER environment Target environment. .PARAMETER publishingApi @@ -302,7 +305,7 @@ function GetInstalledExtensions { ) if ($publishingApi -eq 'AdminCenter') { - return Get-AdminCenterInstalledExtensions -bcAuthContext $bcAuthContext -environment $environment + return Get-AdminCenterInstalledExtensions -environment $environment } return Get-BcInstalledExtensions -bcAuthContext $bcAuthContext -environment $environment | Where-Object { $_.isInstalled } } @@ -311,7 +314,7 @@ function GetInstalledExtensions { .SYNOPSIS Select the PTE publishing API once, before this action publishes any PTEs. .PARAMETER bcAuthContext - Business Central authentication context. + Original BCH authentication context, used only for the Automation authorization fallback. .PARAMETER environment Target environment. #> @@ -322,13 +325,13 @@ function Initialize-PTEPublishingApi { ) $publishingApi = 'AdminCenter' + $authorizationDetails = '' try { - $extensions = @(Get-AdminCenterInstalledExtensions -bcAuthContext $bcAuthContext -environment $environment) + $extensions = @(Get-AdminCenterInstalledExtensions -environment $environment) } catch { if (!(Test-AdminCenterAuthorizationError -errorRecord $_)) { throw } - $details = Get-AdminCenterApiErrorMessage -errorRecord $_ - OutputWarning -message "Admin Center authorization failed: $details. Update your administration center permissions: https://github.com/microsoft/AL-Go/blob/main/Workshop/ContinuousDeployment.md#pte-deployment-authorization. Using the Automation API for PTE publishing throughout this Deploy action." + $authorizationDetails = Get-AdminCenterApiErrorMessage -errorRecord $_ $publishingApi = 'Automation' $extensions = @(GetInstalledExtensions -bcAuthContext $bcAuthContext -environment $environment -publishingApi $publishingApi) } @@ -336,6 +339,9 @@ function Initialize-PTEPublishingApi { if ($applicationVersion -lt [version]'29.0.0.0') { $publishingApi = 'Automation' } + elseif ($publishingApi -eq 'Automation') { + OutputWarning -message "Admin Center authorization failed: $authorizationDetails. Update your administration center permissions: https://github.com/microsoft/AL-Go/blob/main/Workshop/ContinuousDeployment.md#pte-deployment-authorization. Using the Automation API for PTE publishing throughout this Deploy action. Automation PTE upload is planned for removal in 2027 release wave 1." + } Write-Host "Target BC $applicationVersion - using $publishingApi for PTE publishing throughout this Deploy action" $script:ptePublishingApi = $publishingApi } @@ -346,8 +352,7 @@ function Initialize-PTEPublishingApi { .DESCRIPTION Polls only the returned app and operation IDs. An accepted or scheduled immediate install is not success. Only transient status-read errors are retried, never the upload. - .PARAMETER bcAuthContext - Authentication context to renew for each status request. + Uses the initialized Admin authentication context. .PARAMETER environment Target environment. .PARAMETER operation @@ -363,7 +368,6 @@ function Initialize-PTEPublishingApi { #> function WaitPTEOperation { Param( - [hashtable] $bcAuthContext, [string] $environment, $operation, [string] $appId, @@ -416,7 +420,7 @@ function WaitPTEOperation { $requests++ try { $requestTimeout = [int][Math]::Max(1, [Math]::Min(30, [Math]::Ceiling($timeoutSeconds - $timer.Elapsed.TotalSeconds))) - $operation = Get-AdminCenterAppOperation -bcAuthContext $bcAuthContext -environment $environment ` + $operation = Get-AdminCenterAppOperation -environment $environment ` -appId $appId -operationId $operationId -timeoutSeconds $requestTimeout $operation = $operation | ConvertTo-HashTable -recurse $transientErrors = 0 @@ -446,7 +450,7 @@ function WaitPTEOperation { Delegates the original packages to BcContainerHelper or the Admin Center batch publisher, as selected at Deploy initialization before PTE operations. Failures never switch APIs. .PARAMETER bcAuthContext - Business Central authentication context. + Original BCH authentication context, used only by the Automation publisher. .PARAMETER environment Target Business Central environment name. .PARAMETER appFiles @@ -470,7 +474,7 @@ function PublishPTEApps { Publish-PerTenantExtensionApps -bcAuthContext $bcAuthContext -environment $environment -appFiles $appFiles -SchemaSyncMode $schemaSyncMode } elseif ($script:ptePublishingApi -eq 'AdminCenter') { - Publish-AdminCenterPTEApps -bcAuthContext $bcAuthContext -environment $environment -appFiles $appFiles -schemaSyncMode $schemaSyncMode + Publish-AdminCenterPTEApps -environment $environment -appFiles $appFiles -schemaSyncMode $schemaSyncMode } else { throw "Invalid PTE publishing API: $script:ptePublishingApi" @@ -483,8 +487,7 @@ function PublishPTEApps { .DESCRIPTION Requires BC 29 or later. Expands packages, excludes runtime packages and orders dependencies. Skips same or newer installed versions, and waits for each exact install operation before continuing. - .PARAMETER bcAuthContext - Business Central authentication context. + Uses the initialized Admin authentication context and target. .PARAMETER environment Target Business Central environment name. .PARAMETER appFiles @@ -494,14 +497,13 @@ function PublishPTEApps { #> function Publish-AdminCenterPTEApps { Param( - [hashtable] $bcAuthContext, [string] $environment, [string[]] $appFiles, [ValidateSet('Add', 'Force')] [string] $schemaSyncMode = 'Add' ) - $extensions = @(Get-AdminCenterInstalledExtensions -bcAuthContext $bcAuthContext -environment $environment) + $extensions = @(Get-AdminCenterInstalledExtensions -environment $environment) $applicationVersion = GetPTEApplicationVersion -extensions $extensions -environment $environment if ($applicationVersion -lt [version]'29.0.0.0') { throw "Admin Center PTE publishing requires BC 29 or later; the selected API will not be changed." @@ -514,13 +516,14 @@ function Publish-AdminCenterPTEApps { foreach ($appFile in $sortedApps) { $appJson = Get-AppJsonFromAppFile -appFile $appFile $appVersion = [version]$appJson.version - $installedVersions = @($extensions | Where-Object { $_.id -eq $appJson.id -and $_.isInstalled } | - ForEach-Object { [version]::new($_.versionMajor, $_.versionMinor, $_.versionBuild, $_.versionRevision) }) + $matchingApps = @($extensions | Where-Object { $_.id -eq $appJson.id }) + $installedVersions = @($matchingApps | Where-Object { $_.isInstalled } | + ForEach-Object { [version]::new("$($_.versionMajor).$($_.versionMinor).$($_.versionBuild).$($_.versionRevision)") }) if (@($installedVersions | Where-Object { $_ -ge $appVersion }).Count -gt 0) { continue } - $operation = Install-AdminCenterPTE -bcAuthContext $bcAuthContext -environment $environment -appFile $appFile -syncMode $syncMode - WaitPTEOperation -bcAuthContext $bcAuthContext -environment $environment -operation $operation -appId $appJson.id + $operation = Install-AdminCenterPTE -environment $environment -appFile $appFile -syncMode $syncMode + WaitPTEOperation -environment $environment -operation $operation -appId $appJson.id } } finally { diff --git a/Actions/Deploy/README.md b/Actions/Deploy/README.md index fc90069de6..fab350da88 100644 --- a/Actions/Deploy/README.md +++ b/Actions/Deploy/README.md @@ -10,7 +10,7 @@ On BC 29+, PTE deployment checks administration center access first and selects Optional `DeployTo.unpublishOldVersions` (default `false`) cleans older, uninstalled versions after Automation deployment on BC 25.4+. Administration center deployments use Business Central's background cleanup. See [cleanup details](../../Workshop/ContinuousDeployment.md#old-published-versions). -For custom Admin services, use repository settings `deploymentBaseUrl` and `deploymentApplicationFamily`; Automation keeps its BCH configuration. See [target configuration and authentication](../../Workshop/ContinuousDeployment.md#custom-deployment-targets). +For custom Admin services, use repository settings `deploymentBaseUrl` and `deploymentApplicationFamily`; Automation keeps its BCH configuration. These settings are validated only for PTE work, including PTE dependencies, not pure Dev deployment. See [target configuration and authentication](../../Workshop/ContinuousDeployment.md#custom-deployment-targets). ## INPUT diff --git a/Tests/AdminCenterApi.Test.ps1 b/Tests/AdminCenterApi.Test.ps1 index 8ed5d2b5b2..b8656afd2f 100644 --- a/Tests/AdminCenterApi.Test.ps1 +++ b/Tests/AdminCenterApi.Test.ps1 @@ -10,9 +10,7 @@ Describe 'AL-Go Admin Center API helpers' { InModuleScope AdminCenterApi { Describe 'Admin Center requests and named endpoints' { BeforeEach { - $script:adminCenterAuthContext = $null - $script:adminCenterSourceContext = $null - $script:adminCenterTarget = $null + Initialize-AdminCenterAuthContext -authContext @{ tenantId = 'tenant' } $script:packagePath = Join-Path $TestDrive 'Binary Package.app' $script:packageBytes = [byte[]]@(0,128,255,13,10) [IO.File]::WriteAllBytes($script:packagePath, $script:packageBytes) @@ -23,7 +21,6 @@ Describe 'AL-Go Admin Center API helpers' { AfterEach { $script:adminCenterAuthContext = $null - $script:adminCenterSourceContext = $null $script:adminCenterTarget = $null } @@ -47,7 +44,7 @@ Describe 'AL-Go Admin Center API helpers' { return @{ id = 'operation-1' } } - $result = Install-AdminCenterPTE -bcAuthContext @{ tenantId = 'tenant' } -environment 'QA / East' ` + $result = Install-AdminCenterPTE -environment 'QA / East' ` -apiBaseUrl 'https://api.embed.test/service/' -applicationFamily 'Family / US' -appFile $script:packagePath -syncMode $syncMode $result.id | Should -Be 'operation-1' @@ -69,7 +66,7 @@ Describe 'AL-Go Admin Center API helpers' { return @{ id = 'operation / 1' } } - Get-AdminCenterAppOperation -bcAuthContext @{} -environment Sandbox -appId 'app / 1' -operationId 'operation / 1' -timeoutSeconds 7 ` + Get-AdminCenterAppOperation -environment Sandbox -appId 'app / 1' -operationId 'operation / 1' -timeoutSeconds 7 ` -apiBaseUrl 'https://api.embed.test' -applicationFamily 'Custom Family' Assert-MockCalled Invoke-RestMethod -Exactly 1 -ParameterFilter { @@ -81,7 +78,7 @@ Describe 'AL-Go Admin Center API helpers' { It 'Reads installed apps only from the configured root and explicit family' { Mock Invoke-RestMethod { return @{ value = @() } } - @(Get-AdminCenterInstalledExtensions -bcAuthContext @{} -environment 'QA / East' ` + @(Get-AdminCenterInstalledExtensions -environment 'QA / East' ` -apiBaseUrl 'https://api.embed.test/service/' -applicationFamily 'Custom / Family').Count | Should -Be 0 Assert-MockCalled Invoke-RestMethod -Exactly 1 -ParameterFilter { @@ -94,7 +91,8 @@ Describe 'AL-Go Admin Center API helpers' { tenantId = 'tenant'; Scopes = 'https://legacy.test/'; AccessToken = 'legacy-token' UtcExpiresOn = [DateTime]::UtcNow.AddHours(1) } - Initialize-AdminCenterAuthContext -bcAuthContext $original -settings @{ deploymentBaseUrl = 'https://admin.test' } + $adminContext = $original.Clone() + Initialize-AdminCenterAuthContext -authContext $adminContext -settings @{ deploymentBaseUrl = 'https://admin.test' } Mock Renew-BcAuthContext { $bcAuthContext.Scopes | Should -Be 'https://admin.test/' $bcAuthContext.UtcExpiresOn | Should -Be ([DateTime]::MinValue) @@ -102,7 +100,7 @@ Describe 'AL-Go Admin Center API helpers' { return $bcAuthContext } - Invoke-AdminCenterApi -bcAuthContext $original -environment Sandbox -path apps -apiBaseUrl 'https://admin.test' + Invoke-AdminCenterApi -environment Sandbox -path apps -apiBaseUrl 'https://admin.test' $original.Scopes | Should -Be 'https://legacy.test/' $original.AccessToken | Should -Be 'legacy-token' @@ -122,19 +120,19 @@ Describe 'AL-Go Admin Center API helpers' { Scopes = 'https://explicit-resource.test/.default' UtcExpiresOn = $expires } - Initialize-AdminCenterAuthContext -bcAuthContext $original -settings @{ deploymentBaseUrl = 'https://admin.test' } -preserveScopes - Invoke-AdminCenterApi -environment Sandbox -path apps -apiBaseUrl 'https://admin.test' -bcAuthContext $original + Initialize-AdminCenterAuthContext -authContext $original.Clone() -settings @{ deploymentBaseUrl = 'https://admin.test' } -preserveScopes + Invoke-AdminCenterApi -environment Sandbox -path apps -apiBaseUrl 'https://admin.test' Assert-MockCalled Renew-BcAuthContext -Exactly 1 } It 'Does not mutate the BCH context when Admin renewal fails' { $original = @{ Scopes = 'https://legacy.test/' } - Initialize-AdminCenterAuthContext -bcAuthContext $original -settings @{ deploymentBaseUrl = 'https://admin.test' } + Initialize-AdminCenterAuthContext -authContext $original.Clone() -settings @{ deploymentBaseUrl = 'https://admin.test' } Mock Renew-BcAuthContext { $bcAuthContext.Scopes = 'changed-copy' throw [TimeoutException]::new('Renewal timed out') } - { Invoke-AdminCenterApi -bcAuthContext $original -environment Sandbox -path apps } | Should -Throw '*Renewal timed out*' + { Invoke-AdminCenterApi -environment Sandbox -path apps } | Should -Throw '*Renewal timed out*' $original.Scopes | Should -Be 'https://legacy.test/' Assert-MockCalled Invoke-RestMethod -Times 0 } @@ -147,13 +145,13 @@ Describe 'AL-Go Admin Center API helpers' { $newContext = Get-Command New-BcAuthContext -Module BcContainerHelper $original = & $newContext -tenantID fake-tenant -clientID fake-client -clientSecret fake-secret ` -scopes 'https://legacy.test/' -silent - Initialize-AdminCenterAuthContext -bcAuthContext $original -settings @{ deploymentBaseUrl = 'https://admin.test' } + Initialize-AdminCenterAuthContext -authContext $original.Clone() -settings @{ deploymentBaseUrl = 'https://admin.test' } Mock Renew-BcAuthContext { $renew = Get-Command Renew-BcAuthContext -Module BcContainerHelper & $renew -bcAuthContext $bcAuthContext -silent } - Invoke-AdminCenterApi -bcAuthContext $original -environment Sandbox -path apps -apiBaseUrl 'https://admin.test' + Invoke-AdminCenterApi -environment Sandbox -path apps -apiBaseUrl 'https://admin.test' Assert-MockCalled Invoke-RestMethod -ModuleName BcContainerHelper -Exactly 1 -ParameterFilter { $Body.scope -eq 'https://admin.test/.default' @@ -180,7 +178,7 @@ Describe 'AL-Go Admin Center API helpers' { $originalExpiry = $original.UtcExpiresOn $originalConfig = $bcContainerHelperConfig.apiBaseUrl $settings = @{ deploymentBaseUrl = 'https://admin.test'; deploymentApplicationFamily = 'Family / US' } - Initialize-AdminCenterAuthContext -bcAuthContext $original -settings $settings + Initialize-AdminCenterAuthContext -authContext $original.Clone() -settings $settings $settings.deploymentBaseUrl = 'https://changed-after-initialization.test' Mock Renew-BcAuthContext { $renew = Get-Command Renew-BcAuthContext -Module BcContainerHelper @@ -188,9 +186,9 @@ Describe 'AL-Go Admin Center API helpers' { } Mock Invoke-RestMethod { return @{ value = @(); id = 'operation-1' } } - Get-AdminCenterInstalledExtensions -bcAuthContext $original -environment Sandbox | Out-Null - Install-AdminCenterPTE -bcAuthContext $original -environment Sandbox -appFile $script:packagePath | Out-Null - Get-AdminCenterAppOperation -bcAuthContext $original -environment Sandbox -appId app -operationId operation | Out-Null + Get-AdminCenterInstalledExtensions -environment Sandbox | Out-Null + Install-AdminCenterPTE -environment Sandbox -appFile $script:packagePath | Out-Null + Get-AdminCenterAppOperation -environment Sandbox -appId app -operationId operation | Out-Null Assert-MockCalled Invoke-RestMethod -ModuleName BcContainerHelper -Exactly 1 -ParameterFilter { $Body.scope -eq 'https://admin.test/.default' @@ -203,8 +201,8 @@ Describe 'AL-Go Admin Center API helpers' { Assert-MockCalled Invoke-RestMethod -Exactly 1 -ParameterFilter { $Uri -like '*/apps/pteInstall' } Assert-MockCalled Invoke-RestMethod -Exactly 1 -ParameterFilter { $Uri -like '*/apps/app/operations/operation' } $script:adminCenterAuthContext.UtcExpiresOn = [DateTime]::MinValue - Invoke-AdminCenterApi -bcAuthContext $original -environment Sandbox -path apps | Out-Null - Invoke-AdminCenterApi -bcAuthContext $original -environment Sandbox -path apps | Out-Null + Invoke-AdminCenterApi -environment Sandbox -path apps | Out-Null + Invoke-AdminCenterApi -environment Sandbox -path apps | Out-Null Assert-MockCalled Invoke-RestMethod -ModuleName BcContainerHelper -Exactly 2 -ParameterFilter { $Body.scope -eq 'https://admin.test/.default' @@ -227,44 +225,40 @@ Describe 'AL-Go Admin Center API helpers' { Mock Parse-JWTtoken -ModuleName BcContainerHelper { return @{ appid = 'fake-client'; exp = 2000000000 } } Mock Invoke-RestMethod -ModuleName BcContainerHelper { return @{ access_token = 'valid-token' } } $original = & $newContext -tenantID fake-tenant -clientID fake-client -clientSecret fake-secret -silent - Initialize-AdminCenterAuthContext -bcAuthContext $original + Initialize-AdminCenterAuthContext -authContext $original.Clone() - Invoke-AdminCenterApi -bcAuthContext $original -environment Sandbox -path apps | Out-Null - Invoke-AdminCenterApi -bcAuthContext $original -environment Sandbox -path apps | Out-Null + Invoke-AdminCenterApi -environment Sandbox -path apps | Out-Null + Invoke-AdminCenterApi -environment Sandbox -path apps | Out-Null Assert-MockCalled Invoke-RestMethod -ModuleName BcContainerHelper -Exactly 1 Assert-MockCalled Invoke-RestMethod -Exactly 2 -ParameterFilter { $Headers.Authorization -eq 'Bearer valid-token' } } - It 'Overwrites target and auth together on initialization without affecting direct callers' { + It 'Replaces the supplied Admin context and target together on initialization' { $first = @{ Scopes = 'https://first.test/'; AccessToken = 'first-token' } - Initialize-AdminCenterAuthContext -bcAuthContext $first -settings @{ + Initialize-AdminCenterAuthContext -authContext $first -settings @{ deploymentBaseUrl = 'https://first-admin.test'; deploymentApplicationFamily = 'FirstFamily' } Mock Renew-BcAuthContext { $bcAuthContext.AccessToken = 'mutated-before-failure' throw [TimeoutException]::new('Renewal timed out') } - { Invoke-AdminCenterApi -bcAuthContext $first -environment First -path apps } | Should -Throw '*Renewal timed out*' - $first.AccessToken | Should -Be first-token + { Invoke-AdminCenterApi -environment First -path apps } | Should -Throw '*Renewal timed out*' + $first.AccessToken | Should -Be mutated-before-failure Assert-MockCalled Invoke-RestMethod -Times 0 $second = @{ Scopes = 'https://second.test/'; AccessToken = 'second-token' } - Initialize-AdminCenterAuthContext -bcAuthContext $second -settings @{ + Initialize-AdminCenterAuthContext -authContext $second -settings @{ deploymentBaseUrl = 'https://second.test'; deploymentApplicationFamily = 'SecondFamily' } - [object]::ReferenceEquals($script:adminCenterSourceContext, $second) | Should -BeTrue - [object]::ReferenceEquals($script:adminCenterAuthContext, $second) | Should -BeFalse + [object]::ReferenceEquals($script:adminCenterAuthContext, $second) | Should -BeTrue Mock Renew-BcAuthContext { return $bcAuthContext } - Invoke-AdminCenterApi -bcAuthContext $second -environment Second -path apps | Out-Null - Invoke-AdminCenterApi -bcAuthContext $first -environment First -path apps | Out-Null + Invoke-AdminCenterApi -environment Second -path apps | Out-Null Assert-MockCalled Invoke-RestMethod -Exactly 1 -ParameterFilter { $Uri -like 'https://second.test/admin/v2.29/applications/SecondFamily/*' -and $Headers.Authorization -eq 'Bearer second-token' } - Assert-MockCalled Invoke-RestMethod -Exactly 1 -ParameterFilter { - $Uri -like 'https://api.businesscentral.dynamics.com/admin/v2.29/applications/BusinessCentral/*' -and $Headers.Authorization -eq 'Bearer first-token' - } + Assert-MockCalled Invoke-RestMethod -Exactly 1 $script:adminCenterAuthContext.AccessToken | Should -Be second-token $script:adminCenterAuthContext.Scopes | Should -Be 'https://second.test/' $script:adminCenterTarget.apiBaseUrl | Should -Be 'https://second.test' @@ -272,18 +266,18 @@ Describe 'AL-Go Admin Center API helpers' { It 'Honors explicit native endpoint overrides independently of action target defaults' { $original = @{ Scopes = 'https://action.test/'; AccessToken = 'action-token' } - Initialize-AdminCenterAuthContext -bcAuthContext $original -settings @{ + Initialize-AdminCenterAuthContext -authContext $original.Clone() -settings @{ deploymentBaseUrl = 'https://action.test'; deploymentApplicationFamily = 'ActionFamily' } Mock Renew-BcAuthContext { return $bcAuthContext } Mock Invoke-RestMethod { return @{ value = @(); id = 'operation' } } - Get-AdminCenterInstalledExtensions -bcAuthContext $original -environment Sandbox ` + Get-AdminCenterInstalledExtensions -environment Sandbox ` -apiBaseUrl 'https://explicit.test' -applicationFamily 'ExplicitFamily' | Out-Null - Install-AdminCenterPTE -bcAuthContext $original -environment Sandbox -appFile $script:packagePath ` + Install-AdminCenterPTE -environment Sandbox -appFile $script:packagePath ` -apiBaseUrl 'https://api.businesscentral.dynamics.com' | Out-Null - Get-AdminCenterAppOperation -bcAuthContext $original -environment Sandbox -appId app -operationId operation ` + Get-AdminCenterAppOperation -environment Sandbox -appId app -operationId operation ` -applicationFamily BusinessCentral | Out-Null - Invoke-AdminCenterApi -bcAuthContext $original -environment Sandbox -path apps | Out-Null + Invoke-AdminCenterApi -environment Sandbox -path apps | Out-Null Assert-MockCalled Invoke-RestMethod -Exactly 1 -ParameterFilter { $Uri -eq 'https://explicit.test/admin/v2.29/applications/ExplicitFamily/environments/Sandbox/apps' @@ -301,24 +295,14 @@ Describe 'AL-Go Admin Center API helpers' { $script:adminCenterAuthContext.Scopes | Should -Be 'https://action.test/' } - It 'Keeps an unrelated direct callers explicit target and token separate from action state' { - $original = @{ Scopes = 'https://action.test/'; AccessToken = 'action-token' } - Initialize-AdminCenterAuthContext -bcAuthContext $original -settings @{ - deploymentBaseUrl = 'https://action.test'; deploymentApplicationFamily = 'ActionFamily' - } - $direct = @{ Scopes = 'https://direct.test/'; AccessToken = 'direct-token' } - Mock Renew-BcAuthContext { return $bcAuthContext } - Mock Invoke-RestMethod { return @{ value = @() } } + It 'Fails before renewal or HTTP when the native context has not been initialized' { + $script:adminCenterAuthContext = $null + $script:adminCenterTarget = $null - Get-AdminCenterInstalledExtensions -bcAuthContext $direct -environment Sandbox ` - -apiBaseUrl 'https://direct.test' -applicationFamily DirectFamily | Out-Null + { Get-AdminCenterInstalledExtensions -environment Sandbox } | Should -Throw '*must be initialized*' - Assert-MockCalled Invoke-RestMethod -Exactly 1 -ParameterFilter { - $Uri -eq 'https://direct.test/admin/v2.29/applications/DirectFamily/environments/Sandbox/apps' -and - $Headers.Authorization -eq 'Bearer direct-token' - } - $script:adminCenterAuthContext.AccessToken | Should -Be action-token - $script:adminCenterTarget.apiBaseUrl | Should -Be 'https://action.test' + Assert-MockCalled Renew-BcAuthContext -Times 0 + Assert-MockCalled Invoke-RestMethod -Times 0 } It 'Normalizes and installed apps including scope' -TestCases @( @@ -332,7 +316,7 @@ Describe 'AL-Go Admin Center API helpers' { $script:appResponse[$identityField] = 'c1335042-3002-4257-bf8a-75c898ccb1b8' Mock Invoke-RestMethod { return [PSCustomObject]@{ value = @([PSCustomObject]$script:appResponse) } } - $apps = @(Get-AdminCenterInstalledExtensions -bcAuthContext @{ tenantId = 'tenant' } -environment 'QA / East' -applicationFamily 'Family / US') + $apps = @(Get-AdminCenterInstalledExtensions -environment 'QA / East' -applicationFamily 'Family / US') $apps.Count | Should -Be 1 $apps[0].id | Should -Be 'c1335042-3002-4257-bf8a-75c898ccb1b8' @@ -353,40 +337,49 @@ Describe 'AL-Go Admin Center API helpers' { It 'Accepts an empty apps array without inventing installed apps' { Mock Invoke-RestMethod { return @{ value = @() } } - @(Get-AdminCenterInstalledExtensions -bcAuthContext @{} -environment Sandbox).Count | Should -Be 0 + @(Get-AdminCenterInstalledExtensions -environment Sandbox).Count | Should -Be 0 } It 'Rejects malformed installed-app data: ' -TestCases @( - @{ problem = 'missing array' }, @{ problem = 'missing identity' }, @{ problem = 'conflicting identity' }, - @{ problem = 'missing name' }, @{ problem = 'missing state' }, @{ problem = 'unknown state' }, - @{ problem = 'uninstalled' }, @{ problem = 'incomplete version' }, @{ problem = 'invalid version' }, - @{ problem = 'unknown scope' } + @{ problem = 'missing array' }, @{ problem = 'missing identity' }, @{ problem = 'conflicting identity' } ) { param($problem) $script:appResponse = @{ id = 'app'; name = 'Application'; version = '30.0.57777.0'; state = 'installed'; appType = 'global' } switch ($problem) { 'missing identity' { $script:appResponse.Remove('id') } 'conflicting identity' { $script:appResponse.appId = 'different-app' } - 'missing name' { $script:appResponse.Remove('name') } - 'missing state' { $script:appResponse.Remove('state') } - 'unknown state' { $script:appResponse.state = 'unknown' } - 'uninstalled' { $script:appResponse.state = 'uninstalled' } - 'incomplete version' { $script:appResponse.version = '30.0' } - 'invalid version' { $script:appResponse.version = 'unknown' } - 'unknown scope' { $script:appResponse.appType = 'unknown' } } Mock Invoke-RestMethod { return @{ value = @($script:appResponse) } } if ($problem -eq 'missing array') { Mock Invoke-RestMethod { return @{} } } - { Get-AdminCenterInstalledExtensions -bcAuthContext @{} -environment Sandbox } | Should -Throw '*Admin Center*' + { Get-AdminCenterInstalledExtensions -environment Sandbox } | Should -Throw '*Admin Center*' Assert-MockCalled Invoke-RestMethod -Exactly 1 } + It 'Preserves without inventing full version components' -TestCases @( + @{ version = '30.0' }, @{ version = 'invalid' } + ) { + param($version) + $script:appResponse = @{ id = 'unrelated-app'; version = $version } + Mock Invoke-RestMethod { return @{ value = @($script:appResponse) } } + + $apps = @(Get-AdminCenterInstalledExtensions -environment Sandbox) + + $apps.Count | Should -Be 1 + $apps[0].id | Should -Be 'unrelated-app' + $apps[0].isInstalled | Should -BeTrue + $apps[0].version | Should -Be $version + $apps[0].versionMajor | Should -BeNullOrEmpty + $apps[0].versionMinor | Should -BeNullOrEmpty + $apps[0].versionBuild | Should -BeNullOrEmpty + $apps[0].versionRevision | Should -BeNullOrEmpty + } + It 'Marks authentication renewal failures as not sent without trying HTTP' { Mock Renew-BcAuthContext { throw [System.TimeoutException]::new('Renewal failed') } try { - Install-AdminCenterPTE -bcAuthContext @{} -environment Sandbox -appFile $script:packagePath + Install-AdminCenterPTE -environment Sandbox -appFile $script:packagePath throw 'Expected failure' } catch { @@ -401,7 +394,7 @@ Describe 'AL-Go Admin Center API helpers' { Mock Renew-BcAuthContext { return @{} } try { - Get-AdminCenterAppOperation -bcAuthContext @{} -environment Sandbox -appId app -operationId operation + Get-AdminCenterAppOperation -environment Sandbox -appId app -operationId operation throw 'Expected failure' } catch { @@ -425,7 +418,7 @@ Describe 'AL-Go Admin Center API helpers' { } try { - Invoke-AdminCenterApi -bcAuthContext @{} -environment Sandbox -path @('apps','pteInstall') -method $method + Invoke-AdminCenterApi -environment Sandbox -path @('apps','pteInstall') -method $method throw 'Expected failure' } catch { @@ -441,7 +434,7 @@ Describe 'AL-Go Admin Center API helpers' { Mock Invoke-RestMethod { throw [System.TimeoutException]::new('Response lost') } try { - Install-AdminCenterPTE -bcAuthContext @{} -environment Sandbox -appFile $script:packagePath + Install-AdminCenterPTE -environment Sandbox -appFile $script:packagePath throw 'Expected failure' } catch { @@ -457,7 +450,7 @@ Describe 'AL-Go Admin Center API helpers' { Mock Invoke-AdminCenterApi { throw 'Request must not be called' } try { - Install-AdminCenterPTE -bcAuthContext @{} -environment Sandbox -appFile (Join-Path $TestDrive 'Missing.app') + Install-AdminCenterPTE -environment Sandbox -appFile (Join-Path $TestDrive 'Missing.app') throw 'Expected failure' } catch { diff --git a/Tests/Deploy.Action.Test.ps1 b/Tests/Deploy.Action.Test.ps1 index edb3c6618a..6e148fb6b4 100644 --- a/Tests/Deploy.Action.Test.ps1 +++ b/Tests/Deploy.Action.Test.ps1 @@ -24,10 +24,83 @@ Describe "Deploy Action Tests" { YamlTest -scriptRoot $scriptRoot -actionName $actionName -actionScript $actionScript -outputs $outputs } + It 'Shares custom target and retained native auth through the exact action imports in a fresh host' { + $repro = Join-Path $TestDrive 'ActionImports.ps1' + @' +param([string] $actionPath) +$ErrorActionPreference = 'Stop' +$env:GITHUB_WORKSPACE = Split-Path (Split-Path (Split-Path $actionPath)) +$tokens = $null +$errors = $null +$ast = [System.Management.Automation.Language.Parser]::ParseFile($actionPath, [ref]$tokens, [ref]$errors) +$prefix = ($ast.EndBlock.Statements | Select-Object -First 4 | ForEach-Object { $_.Extent.Text }) -join "`n" +$prefix = $prefix.Replace('$PSScriptRoot', "'$(Split-Path $actionPath)'") +$inspection = { + $expires = [DateTime]::UtcNow.AddHours(1) + $source = @{ Scopes = 'https://legacy.test/'; AccessToken = 'legacy-token'; UtcExpiresOn = $expires } + Initialize-AdminCenterAuthContext -authContext $source.Clone() -settings @{ + deploymentBaseUrl = 'https://native.test/root'; deploymentApplicationFamily = 'Custom Family' + } + $native = (Get-Command Initialize-AdminCenterAuthContext).Module + $deploy = Get-Module Deploy + $nested = & $deploy { (Get-Command Get-AdminCenterInstalledExtensions).Module } + if (![object]::ReferenceEquals($native, $nested)) { throw 'Action and Deploy must share the native module before any requests.' } + & $native { + $script:exchanges = 0 + $script:requests = @() + function script:Renew-BcAuthContext { + param($bcAuthContext) + if ($bcAuthContext.UtcExpiresOn -le [DateTime]::UtcNow) { + $script:exchanges++ + $bcAuthContext = $bcAuthContext.Clone() + $bcAuthContext.AccessToken = 'retained-native-token' + $bcAuthContext.UtcExpiresOn = [DateTime]::UtcNow.AddHours(1) + } + return $bcAuthContext + } + function script:Invoke-RestMethod { + param($Uri, $Method, $Headers, $UseBasicParsing, $TimeoutSec, $ErrorAction) + $script:requests += @{ uri = [string]$Uri; authorization = $Headers.Authorization } + return @{ value = @() } + } + function script:Write-Host { } + } + Get-AdminCenterInstalledExtensions -environment Sandbox | Out-Null + & $deploy { + param($context) + GetInstalledExtensions -bcAuthContext $context -environment Sandbox -publishingApi AdminCenter | Out-Null + } $source + $state = & $native { + @{ exchanges = $script:exchanges; requests = $script:requests; scopes = $script:adminCenterAuthContext.Scopes } + } + $state.sameInstance = [object]::ReferenceEquals($native, $nested) + $state.originalUnchanged = $source.Scopes -eq 'https://legacy.test/' -and + $source.AccessToken -eq 'legacy-token' -and $source.UtcExpiresOn -eq $expires + $state | ConvertTo-Json -Depth 10 -Compress +} +& ([scriptblock]::Create($prefix + "`n" + $inspection.ToString())) +'@ | Set-Content -Path $repro -Encoding UTF8 + + $hostPath = (Get-Process -Id $PID).Path + $output = & $hostPath -NoProfile -NonInteractive -ExecutionPolicy Bypass -File $repro -actionPath $scriptPath + $LASTEXITCODE | Should -Be 0 + $state = $output[-1] | ConvertFrom-Json | ConvertTo-HashTable -recurse + $state.sameInstance | Should -BeTrue + $state.originalUnchanged | Should -BeTrue + $state.exchanges | Should -Be 1 + $state.scopes | Should -Be 'https://native.test/root/' + $state.requests.Count | Should -Be 2 + foreach ($request in $state.requests) { + $request.uri | Should -Be 'https://native.test/root/admin/v2.29/applications/Custom%20Family/environments/Sandbox/apps' + $request.authorization | Should -Be 'Bearer retained-native-token' + } + } + Context "unpublishOldVersions wiring" { BeforeAll { Import-Module (Join-Path $scriptRoot "Deploy.psm1") -Force Import-Module (Join-Path $scriptRoot "..\.Modules\AdminCenterApi.psm1") -DisableNameChecking + $script:nativeInitializer = Get-Command Initialize-AdminCenterAuthContext -Module AdminCenterApi . (Join-Path $PSScriptRoot "..\Actions\AL-Go-Helper.ps1" -Resolve) DownloadAndImportBcContainerHelper -baseFolder $([System.IO.Path]::GetTempPath()) @@ -83,6 +156,7 @@ Describe "Deploy Action Tests" { It 'Initializes the PTE route before dependencies and primary publishing' { $script:events = @() + Mock Initialize-AdminCenterAuthContext { $script:events += 'native-auth' } Mock Initialize-PTEPublishingApi { $script:events += 'probe' } Mock GetAppsAndDependenciesFromArtifacts { return @('/tmp/app1.app'), @('/tmp/dependency.app') } Mock InstallOrUpgradeApps { $script:events += 'dependency' } @@ -95,7 +169,90 @@ Describe "Deploy Action Tests" { InvokeDeploy -deploymentSettings @{ EnvironmentType = 'SaaS'; EnvironmentName = 'test'; Branches = @(); Projects = '*'; DependencyInstallMode = 'upgrade'; SyncMode = $null; Scope = 'PTE'; continuousDeployment = $true; includeTestAppsInSandboxEnvironment = $false; excludeAppIds = @(); unpublishOldVersions = $true } - ($script:events -join ',') | Should -Be 'probe,dependency,preflight,primary,cleanup' + ($script:events -join ',') | Should -Be 'native-auth,probe,dependency,preflight,primary,cleanup' + } + + It 'Supplies a dedicated native context while preserving BCH consumers in scope' -TestCases @( + @{ scope = 'PTE' }, @{ scope = 'Dev' } + ) { + param($scope) + $script:originalAuthContext = @{ + tenantId = 'test-tenant'; Scopes = 'https://legacy.test/'; AccessToken = 'legacy-token' + UtcExpiresOn = [DateTime]::UtcNow.AddHours(1) + } + $originalExpiry = $script:originalAuthContext.UtcExpiresOn + Mock New-BcAuthContext { return $script:originalAuthContext } + Mock GetAppsAndDependenciesFromArtifacts { return @('/tmp/app1.app'), @('/tmp/dependency.app') } + Mock Get-AppJsonFromAppFile { return @{ idRanges = @(@{ from = 50000 }) } } + Mock InstallOrUpgradeApps { } + Mock Initialize-AdminCenterAuthContext { + [object]::ReferenceEquals($authContext, $script:originalAuthContext) | Should -BeFalse + & $script:nativeInitializer -authContext $authContext -settings $settings -preserveScopes:$preserveScopes + $authContext.Scopes | Should -Be 'https://native.test/' + $authContext.UtcExpiresOn | Should -Be ([DateTime]::MinValue) + $authContext.AccessToken = 'native-token' + } + + InvokeDeploy -repositorySettings @{ deploymentBaseUrl = 'https://native.test' } ` + -deploymentSettings @{ EnvironmentType = 'SaaS'; EnvironmentName = 'test'; Branches = @(); Projects = '*'; DependencyInstallMode = 'upgrade'; SyncMode = $null; Scope = $scope; continuousDeployment = $true; includeTestAppsInSandboxEnvironment = $false; excludeAppIds = @() } + + Assert-MockCalled New-BcAuthContext -Exactly 1 + Assert-MockCalled Initialize-AdminCenterAuthContext -Exactly 1 + Assert-MockCalled InstallOrUpgradeApps -Exactly 1 -ParameterFilter { + [object]::ReferenceEquals($bcAuthContext, $script:originalAuthContext) + } + if ($scope -eq 'PTE') { + Assert-MockCalled PublishPTEApps -Exactly 1 -ParameterFilter { + [object]::ReferenceEquals($bcAuthContext, $script:originalAuthContext) + } + } + else { + Assert-MockCalled Publish-BcContainerApp -Exactly 1 -ParameterFilter { + [object]::ReferenceEquals($bcAuthContext, $script:originalAuthContext) + } + } + $script:originalAuthContext.Scopes | Should -Be 'https://legacy.test/' + $script:originalAuthContext.AccessToken | Should -Be 'legacy-token' + $script:originalAuthContext.UtcExpiresOn | Should -Be $originalExpiry + } + + It 'Reports invalid native configuration clearly before PTE work in scope' -TestCases @( + @{ scope = 'PTE' }, @{ scope = 'Dev' } + ) { + param($scope) + Mock Initialize-AdminCenterAuthContext { + & $script:nativeInitializer -authContext $authContext -settings $settings -preserveScopes:$preserveScopes + } + Mock GetAppsAndDependenciesFromArtifacts { return @('/tmp/app1.app'), @('/tmp/dependency.app') } + Mock Get-AppJsonFromAppFile { return @{ idRanges = @(@{ from = 50000 }) } } + Mock InstallOrUpgradeApps { } + Mock OutputError { param($message) throw $message } + + try { + InvokeDeploy -repositorySettings @{ deploymentBaseUrl = 'http://invalid.test' } ` + -deploymentSettings @{ EnvironmentType = 'SaaS'; EnvironmentName = 'test'; Branches = @(); Projects = '*'; DependencyInstallMode = 'upgrade'; SyncMode = $null; Scope = $scope; continuousDeployment = $true; includeTestAppsInSandboxEnvironment = $false; excludeAppIds = @() } + throw 'Expected native configuration validation to fail' + } + catch { + $_.Exception.Message | Should -Match 'deploymentBaseUrl must be an absolute HTTPS API root' + $_.Exception.Message | Should -Not -Match 'Authentication failed' + } + Assert-MockCalled Initialize-PTEPublishingApi -Times 0 + Assert-MockCalled InstallOrUpgradeApps -Times 0 + Assert-MockCalled PublishPTEApps -Times 0 + Assert-MockCalled Publish-BcContainerApp -Times 0 + } + + It 'Does not validate unused native settings for pure Dev deployment' { + Mock Initialize-AdminCenterAuthContext { throw 'Unused native configuration must not be initialized' } + Mock OutputError { param($message) throw $message } + + InvokeDeploy -repositorySettings @{ deploymentBaseUrl = 'http://invalid.test'; deploymentApplicationFamily = '' } ` + -deploymentSettings @{ EnvironmentType = 'SaaS'; EnvironmentName = 'test'; Branches = @(); Projects = '*'; DependencyInstallMode = 'ignore'; SyncMode = $null; Scope = 'Dev'; continuousDeployment = $true; includeTestAppsInSandboxEnvironment = $false; excludeAppIds = @() } + + Assert-MockCalled Initialize-AdminCenterAuthContext -Times 0 + Assert-MockCalled Initialize-PTEPublishingApi -Times 0 + Assert-MockCalled Publish-BcContainerApp -Exactly 1 } It 'Keeps Admin settings separate from BCH authentication, dependencies and cleanup' { @@ -201,7 +358,7 @@ Describe "Deploy Action Tests" { $bcAuthContext.Scopes -eq 'https://audience.test/.default' } Assert-MockCalled Initialize-AdminCenterAuthContext -Exactly 1 -ParameterFilter { - $preserveScopes -and $bcAuthContext.Scopes -eq 'https://audience.test/.default' -and + $preserveScopes -and $authContext.Scopes -eq 'https://audience.test/.default' -and $settings.deploymentBaseUrl -eq 'https://explicit.test' } } @@ -241,8 +398,8 @@ Describe "Deploy Action Tests" { $bcAuthContext.Scopes -eq 'https://explicit-resource.test/' } Assert-MockCalled Initialize-AdminCenterAuthContext -Exactly 1 -ParameterFilter { - $preserveScopes -and $bcAuthContext.Scopes -eq 'https://explicit-resource.test/' -and - [object]::ReferenceEquals($bcAuthContext, $script:originalAuthContext) + $preserveScopes -and $authContext.Scopes -eq 'https://explicit-resource.test/' -and + ![object]::ReferenceEquals($authContext, $script:originalAuthContext) } $script:originalAuthContext.AccessToken | Should -Be 'original-token' } diff --git a/Tests/PublishPTEApps.Test.ps1 b/Tests/PublishPTEApps.Test.ps1 index 6d5c4c8857..4e99bd2ecf 100644 --- a/Tests/PublishPTEApps.Test.ps1 +++ b/Tests/PublishPTEApps.Test.ps1 @@ -75,10 +75,30 @@ InModuleScope Deploy { Assert-MockCalled Get-AdminCenterInstalledExtensions -Exactly 1 Assert-MockCalled Get-BcInstalledExtensions -Exactly 1 Assert-MockCalled OutputWarning -Exactly 1 -ParameterFilter { - $message -like '*Admin permission missing*permissions*ContinuousDeployment.md#pte-deployment-authorization*throughout this Deploy action*' + $message -like '*Admin permission missing*permissions*ContinuousDeployment.md#pte-deployment-authorization*throughout this Deploy action*' -and + $message -like '*planned for removal in 2027 release wave 1*' } } + It 'Does not emit an Admin permission warning below BC 29 after HTTP ' -TestCases @( + @{ statusCode = 401 }, @{ statusCode = 403 } + ) { + param($statusCode) + $script:application.versionMajor = 28 + $script:probeStatus = $statusCode + Mock Get-AdminCenterInstalledExtensions { + $exception = [System.Exception]::new('Admin permission missing') + $exception | Add-Member NoteProperty Response ([PSCustomObject]@{ StatusCode = $script:probeStatus }) + throw $exception + } + + Initialize-PTEPublishingApi -bcAuthContext @{} -environment Sandbox + + $script:ptePublishingApi | Should -Be Automation + Assert-MockCalled Get-BcInstalledExtensions -Exactly 1 + Assert-MockCalled OutputWarning -Times 0 + } + It 'Selects Automation for the helper-owned missing-token error' { Mock Get-AdminCenterInstalledExtensions { throw [System.Management.Automation.ErrorRecord]::new( @@ -135,6 +155,7 @@ InModuleScope Deploy { { Initialize-PTEPublishingApi -bcAuthContext @{} -environment Sandbox } | Should -Throw '*Automation read failed*' $script:ptePublishingApi | Should -Be '' + Assert-MockCalled OutputWarning -Times 0 } It 'Overwrites the previous choice on each initialization' { @@ -314,7 +335,7 @@ InModuleScope Deploy { -schemaSyncMode Force Assert-MockCalled Publish-AdminCenterPTEApps -Exactly 1 -ParameterFilter { - $bcAuthContext.tenantId -eq 'tenant' -and $environment -eq 'Sandbox' -and + !$PesterBoundParameters.ContainsKey('bcAuthContext') -and $environment -eq 'Sandbox' -and ($appFiles -join ',') -eq 'Apps.zip,Other.app' -and $schemaSyncMode -eq 'Force' } Assert-MockCalled Get-AdminCenterInstalledExtensions -Times 0 @@ -367,21 +388,17 @@ InModuleScope Deploy { Assert-MockCalled Get-BcInstalledExtensions -Times 0 } - It 'Passes the same source auth context through snapshot, upload and exact-operation wait' { - $script:sourceContext = @{ tenantId = 'tenant' } - Mock Get-AdminCenterInstalledExtensions { - [object]::ReferenceEquals($bcAuthContext, $script:sourceContext) | Should -BeTrue - return $script:extensions - } + It 'Leaves original BCH credentials out of native snapshot, upload and operation wait calls' { + PublishPTEApps -bcAuthContext @{ tenantId = 'tenant' } -environment Sandbox -appFiles @('App.app') - PublishPTEApps -bcAuthContext $script:sourceContext -environment Sandbox -appFiles @('App.app') - - Assert-MockCalled Get-AdminCenterInstalledExtensions -Exactly 1 + Assert-MockCalled Get-AdminCenterInstalledExtensions -Exactly 1 -ParameterFilter { + !$PesterBoundParameters.ContainsKey('bcAuthContext') + } Assert-MockCalled Install-AdminCenterPTE -Exactly 1 -ParameterFilter { - [object]::ReferenceEquals($bcAuthContext, $script:sourceContext) + !$PesterBoundParameters.ContainsKey('bcAuthContext') } Assert-MockCalled WaitPTEOperation -Exactly 1 -ParameterFilter { - [object]::ReferenceEquals($bcAuthContext, $script:sourceContext) + !$PesterBoundParameters.ContainsKey('bcAuthContext') } Assert-MockCalled Get-BcInstalledExtensions -Times 0 Assert-MockCalled Publish-PerTenantExtensionApps -Times 0 @@ -392,7 +409,7 @@ InModuleScope Deploy { Mock Copy-AppFilesToFolder { return @($script:copiedApp) } Mock Sort-AppFilesByDependencies { return $appFiles } - Publish-AdminCenterPTEApps -bcAuthContext @{} -environment Sandbox -appFiles @('Apps.zip') + Publish-AdminCenterPTEApps -environment Sandbox -appFiles @('Apps.zip') Assert-MockCalled Sort-AppFilesByDependencies -Exactly 1 -ParameterFilter { $appFiles.Count -eq 1 -and $appFiles[0] -eq $script:copiedApp -and $excludeRuntimePackages @@ -652,6 +669,122 @@ InModuleScope Deploy { } } + Context "Native installed-app decision safety" { + BeforeEach { + $script:ptePublishingApi = 'AdminCenter' + $script:rawApplication = @{ + id = $applicationAppId; name = 'Application'; version = '30.0.0.0'; state = 'installed'; appType = 'global' + } + $script:rawApp = @{ id = 'app-1'; name = 'App'; version = '1.0.0.0'; state = 'installed'; appType = 'tenant' } + # Bind the production normalizer to the same module as the API and consumer mocks. + $script:nativeReader = [scriptblock]::Create((Get-Command Get-AdminCenterInstalledExtensions -Module AdminCenterApi).Definition) + $script:installedAppResponse = @($script:rawApplication, $script:rawApp) + Mock Invoke-AdminCenterApi { return @{ value = $script:installedAppResponse } } + Mock Get-AdminCenterInstalledExtensions { + & $script:nativeReader -environment $environment + } + Mock NewTemporaryFolder { return 'test-app-folder' } + Mock Copy-AppFilesToFolder { return @('App.app') } + Mock Get-ChildItem { return [PSCustomObject]@{ FullName = 'App.app' } } + Mock Sort-AppFilesByDependencies { return @('App.app') } + Mock Get-AppJsonFromAppFile { return @{ id = 'app-1'; name = 'App'; version = '2.0.0.0'; idRanges = @(@{ from = 50000 }) } } + Mock Install-AdminCenterPTE { return @{ id = 'operation-1'; appId = 'app-1'; status = 'running' } } + Mock Install-BcAppFromAppSource { } + Mock WaitPTEOperation { } + Mock Remove-Item { } + } + + It 'Does not require unrelated apps to have names, scopes or usable versions' { + $script:installedAppResponse = @($script:rawApplication, @{ id = 'unrelated-app'; version = 'invalid' }) + + Initialize-PTEPublishingApi -bcAuthContext @{} -environment Sandbox + PublishPTEApps -bcAuthContext @{} -environment Sandbox -appFiles @('App.app') + + $script:ptePublishingApi | Should -Be AdminCenter + Assert-MockCalled Install-AdminCenterPTE -Exactly 1 + Assert-MockCalled WaitPTEOperation -Exactly 1 + Assert-MockCalled Publish-PerTenantExtensionApps -Times 0 + Assert-MockCalled OutputWarning -Times 0 + } + + It 'Rejects selected installed version before upload' -TestCases @( + @{ version = '1.0' }, @{ version = 'invalid' } + ) { + param($version) + $script:rawApp.version = $version + + { PublishPTEApps -bcAuthContext @{} -environment Sandbox -appFiles @('App.app') } | Should -Throw + + Assert-MockCalled Install-AdminCenterPTE -Times 0 + Assert-MockCalled Publish-PerTenantExtensionApps -Times 0 + Assert-MockCalled Remove-Item -Exactly 1 + } + + It 'Resolves Application by its known identity when its name is absent' { + $script:rawApplication.Remove('name') + + Initialize-PTEPublishingApi -bcAuthContext @{} -environment Sandbox + + $script:ptePublishingApi | Should -Be AdminCenter + Assert-MockCalled Get-BcInstalledExtensions -Times 0 + } + + It 'Rejects Application version even when its name is absent' -TestCases @( + @{ version = '30.0' }, @{ version = 'invalid' } + ) { + param($version) + $script:rawApplication.Remove('name') + $script:rawApplication.version = $version + $script:ptePublishingApi = '' + + { Initialize-PTEPublishingApi -bcAuthContext @{} -environment Sandbox } | + Should -Throw '*unique installed Application*' + + $script:ptePublishingApi | Should -Be '' + Assert-MockCalled Get-BcInstalledExtensions -Times 0 + Assert-MockCalled Install-AdminCenterPTE -Times 0 + } + + It 'Rejects an invalid selected installed version during primary preflight' { + $script:rawApp.version = 'invalid' + + { CheckInstalledApps -bcAuthContext @{} -environment Sandbox -appFiles @('App.app') } | Should -Throw + + Assert-MockCalled Install-AdminCenterPTE -Times 0 + } + + It 'Rejects an invalid installed version before writing a matched dependency' -TestCases @( + @{ kind = 'PTE'; from = 50000 }, @{ kind = 'AppSource'; from = 100000 } + ) { + param($from) + $script:rawApp.version = 'invalid' + $script:dependencyFrom = $from + Mock Get-AppJsonFromAppFile { + return @{ id = 'app-1'; name = 'App'; version = '2.0.0.0'; idRanges = @(@{ from = $script:dependencyFrom }) } + } + + { InstallOrUpgradeApps -bcAuthContext @{} -environment Sandbox -apps @('App.app') -installMode upgrade } | Should -Throw + + Assert-MockCalled Install-BcAppFromAppSource -Times 0 + Assert-MockCalled Install-AdminCenterPTE -Times 0 + Assert-MockCalled Publish-PerTenantExtensionApps -Times 0 + } + + It 'Keeps the Dev-scope AppSource dependency safeguard after normalization' { + $script:rawApp.appType = 'dev' + Mock Get-AppJsonFromAppFile { + return @{ id = 'app-1'; name = 'App'; version = '2.0.0.0'; idRanges = @(@{ from = 100000 }) } + } + + InstallOrUpgradeApps -bcAuthContext @{} -environment Sandbox -apps @('App.app') -installMode upgrade + + Assert-MockCalled OutputWarning -Exactly 1 -ParameterFilter { $message -like '*published in Dev scope*Cannot upgrade*' } + Assert-MockCalled Install-BcAppFromAppSource -Times 0 + Assert-MockCalled Install-AdminCenterPTE -Times 0 + Assert-MockCalled Publish-PerTenantExtensionApps -Times 0 + } + } + Context "Exact operation polling" { BeforeEach { $script:operation = [PSCustomObject]@{ id = 'operation / 1'; appId = 'app-1'; status = 'running'; scheduleKind = 'immediate' } @@ -662,13 +795,13 @@ InModuleScope Deploy { It 'Accepts immediate success without polling' { $script:operation.status = 'succeeded' - WaitPTEOperation -bcAuthContext @{} -environment Sandbox -operation $script:operation -appId 'app-1' + WaitPTEOperation -environment Sandbox -operation $script:operation -appId 'app-1' Assert-MockCalled Get-AdminCenterAppOperation -Times 0 } It 'Leaves exact-operation target selection to the native request boundary' { - WaitPTEOperation -bcAuthContext @{} -environment Sandbox -operation $script:operation -appId 'app-1' + WaitPTEOperation -environment Sandbox -operation $script:operation -appId 'app-1' Assert-MockCalled Get-AdminCenterAppOperation -Exactly 1 -ParameterFilter { !$PesterBoundParameters.ContainsKey('apiBaseUrl') -and !$PesterBoundParameters.ContainsKey('applicationFamily') -and @@ -687,7 +820,7 @@ InModuleScope Deploy { $script:operation | Add-Member NoteProperty errorMessage 'Service validation detail' try { - WaitPTEOperation -bcAuthContext @{} -environment Sandbox -operation $script:operation -appId 'app-1' + WaitPTEOperation -environment Sandbox -operation $script:operation -appId 'app-1' throw 'Expected terminal error' } catch { @@ -703,7 +836,7 @@ InModuleScope Deploy { $script:operation | Add-Member NoteProperty arbitrary 'private-response-field' try { - WaitPTEOperation -bcAuthContext @{} -environment Sandbox -operation $script:operation -appId 'app-1' + WaitPTEOperation -environment Sandbox -operation $script:operation -appId 'app-1' throw 'Expected failure' } catch { @@ -713,7 +846,7 @@ InModuleScope Deploy { } It 'Polls only the exact returned operation and renews authentication' { - WaitPTEOperation -bcAuthContext @{} -environment Sandbox -operation $script:operation -appId 'app-1' + WaitPTEOperation -environment Sandbox -operation $script:operation -appId 'app-1' Assert-MockCalled Get-AdminCenterAppOperation -Exactly 1 -ParameterFilter { $environment -eq 'Sandbox' -and $appId -eq 'app-1' -and $operationId -eq 'operation / 1' -and $timeoutSeconds -le 30 @@ -722,7 +855,7 @@ InModuleScope Deploy { } It 'Uses the requested shorter polling interval without changing the operation endpoint' { - WaitPTEOperation -bcAuthContext @{} -environment Sandbox -operation $script:operation -appId 'app-1' -pollIntervalSeconds 5 + WaitPTEOperation -environment Sandbox -operation $script:operation -appId 'app-1' -pollIntervalSeconds 5 Assert-MockCalled Start-Sleep -Exactly 1 -ParameterFilter { $Milliseconds -eq 5000 } Assert-MockCalled Get-AdminCenterAppOperation -Exactly 1 -ParameterFilter { @@ -733,7 +866,7 @@ InModuleScope Deploy { It 'Does not count scheduled immediate installation as success' { $script:operation.status = 'scheduled' - WaitPTEOperation -bcAuthContext @{} -environment Sandbox -operation $script:operation -appId 'app-1' + WaitPTEOperation -environment Sandbox -operation $script:operation -appId 'app-1' Assert-MockCalled Get-AdminCenterAppOperation -Exactly 1 } @@ -745,7 +878,7 @@ InModuleScope Deploy { $script:operation.status = $status $script:operation | Add-Member -NotePropertyName errorMessage -NotePropertyValue 'Service diagnostic' - { WaitPTEOperation -bcAuthContext @{} -environment Sandbox -operation $script:operation -appId 'app-1' } | Should -Throw '*operation / 1*Service diagnostic*' + { WaitPTEOperation -environment Sandbox -operation $script:operation -appId 'app-1' } | Should -Throw '*operation / 1*Service diagnostic*' Assert-MockCalled Get-AdminCenterAppOperation -Times 0 } @@ -761,7 +894,7 @@ InModuleScope Deploy { empty { $script:operation = $null } } - { WaitPTEOperation -bcAuthContext @{} -environment Sandbox -operation $script:operation -appId 'app-1' } | Should -Throw '*missing or mismatched*' + { WaitPTEOperation -environment Sandbox -operation $script:operation -appId 'app-1' } | Should -Throw '*missing or mismatched*' Assert-MockCalled Get-AdminCenterAppOperation -Times 0 } @@ -780,7 +913,7 @@ InModuleScope Deploy { } } - { WaitPTEOperation -bcAuthContext @{} -environment Sandbox -operation $script:operation -appId 'app-1' } | Should -Throw '*Missing or mismatched PTE operation*' + { WaitPTEOperation -environment Sandbox -operation $script:operation -appId 'app-1' } | Should -Throw '*Missing or mismatched PTE operation*' } It 'Retries transient status failures and then succeeds without any write' { @@ -791,7 +924,7 @@ InModuleScope Deploy { return [PSCustomObject]@{ id = 'operation / 1'; appId = 'app-1'; status = 'succeeded' } } - WaitPTEOperation -bcAuthContext @{} -environment Sandbox -operation $script:operation -appId 'app-1' + WaitPTEOperation -environment Sandbox -operation $script:operation -appId 'app-1' Assert-MockCalled Get-AdminCenterAppOperation -Exactly 3 Assert-MockCalled OutputWarning -Exactly 2 @@ -800,7 +933,7 @@ InModuleScope Deploy { It 'Stops after five consecutive transient retries' { Mock Get-AdminCenterAppOperation { throw [System.TimeoutException]::new('Temporary failure') } - { WaitPTEOperation -bcAuthContext @{} -environment Sandbox -operation $script:operation -appId 'app-1' } | Should -Throw '*Unable to read PTE operation*Temporary failure*' + { WaitPTEOperation -environment Sandbox -operation $script:operation -appId 'app-1' } | Should -Throw '*Unable to read PTE operation*Temporary failure*' Assert-MockCalled Get-AdminCenterAppOperation -Exactly 6 Assert-MockCalled OutputWarning -Exactly 5 @@ -830,12 +963,12 @@ InModuleScope Deploy { } if ($retry) { - WaitPTEOperation -bcAuthContext @{} -environment Sandbox -operation $script:operation -appId 'app-1' + WaitPTEOperation -environment Sandbox -operation $script:operation -appId 'app-1' Assert-MockCalled Get-AdminCenterAppOperation -Exactly 2 Assert-MockCalled OutputWarning -Exactly 1 } else { - { WaitPTEOperation -bcAuthContext @{} -environment Sandbox -operation $script:operation -appId 'app-1' } | Should -Throw '*Unable to read PTE operation*' + { WaitPTEOperation -environment Sandbox -operation $script:operation -appId 'app-1' } | Should -Throw '*Unable to read PTE operation*' Assert-MockCalled Get-AdminCenterAppOperation -Exactly 1 Assert-MockCalled OutputWarning -Times 0 } @@ -850,7 +983,7 @@ InModuleScope Deploy { throw [System.TimeoutException]::new('Transient timeout') } - WaitPTEOperation -bcAuthContext @{} -environment Sandbox -operation $script:operation -appId 'app-1' + WaitPTEOperation -environment Sandbox -operation $script:operation -appId 'app-1' Assert-MockCalled Get-AdminCenterAppOperation -Exactly 12 Assert-MockCalled OutputWarning -Exactly 10 @@ -863,7 +996,7 @@ InModuleScope Deploy { throw $exception } - { WaitPTEOperation -bcAuthContext @{} -environment Sandbox -operation $script:operation -appId 'app-1' } | Should -Throw '*403 Forbidden*' + { WaitPTEOperation -environment Sandbox -operation $script:operation -appId 'app-1' } | Should -Throw '*403 Forbidden*' Assert-MockCalled Get-AdminCenterAppOperation -Times 1 Assert-MockCalled OutputWarning -Times 0 @@ -872,7 +1005,7 @@ InModuleScope Deploy { It 'Does not retry an authorization status-read failure' { Mock Get-AdminCenterAppOperation { throw '401 Unauthorized' } - { WaitPTEOperation -bcAuthContext @{} -environment Sandbox -operation $script:operation -appId 'app-1' } | Should -Throw '*Unable to read PTE operation*401 Unauthorized*' + { WaitPTEOperation -environment Sandbox -operation $script:operation -appId 'app-1' } | Should -Throw '*Unable to read PTE operation*401 Unauthorized*' Assert-MockCalled Get-AdminCenterAppOperation -Exactly 1 Assert-MockCalled OutputWarning -Times 0 @@ -881,7 +1014,7 @@ InModuleScope Deploy { It 'Bounds status attempts even when the operation remains scheduled' { Mock Get-AdminCenterAppOperation { return [PSCustomObject]@{ id = 'operation / 1'; status = 'scheduled' } } - { WaitPTEOperation -bcAuthContext @{} -environment Sandbox -operation $script:operation -appId 'app-1' -maxStatusRequests 2 } | Should -Throw '*Timed out*2 status requests*' + { WaitPTEOperation -environment Sandbox -operation $script:operation -appId 'app-1' -maxStatusRequests 2 } | Should -Throw '*Timed out*2 status requests*' Assert-MockCalled Get-AdminCenterAppOperation -Exactly 2 } @@ -889,7 +1022,7 @@ InModuleScope Deploy { It 'Limits the default immediate polling to 360 status requests' { Mock Get-AdminCenterAppOperation { return [PSCustomObject]@{ id = 'operation / 1'; status = 'running' } } - { WaitPTEOperation -bcAuthContext @{} -environment Sandbox -operation $script:operation -appId 'app-1' } | Should -Throw '*Timed out*1800 seconds or 360 status requests*' + { WaitPTEOperation -environment Sandbox -operation $script:operation -appId 'app-1' } | Should -Throw '*Timed out*1800 seconds or 360 status requests*' Assert-MockCalled Get-AdminCenterAppOperation -Exactly 360 } @@ -897,7 +1030,7 @@ InModuleScope Deploy { It 'Honors the elapsed timeout before another status request' { Mock Start-Sleep { [System.Threading.Thread]::Sleep(1100) } - { WaitPTEOperation -bcAuthContext @{} -environment Sandbox -operation $script:operation -appId 'app-1' -timeoutSeconds 1 } | Should -Throw '*Timed out*1 seconds*' + { WaitPTEOperation -environment Sandbox -operation $script:operation -appId 'app-1' -timeoutSeconds 1 } | Should -Throw '*Timed out*1 seconds*' Assert-MockCalled Get-AdminCenterAppOperation -Times 0 Assert-MockCalled Start-Sleep -Exactly 1 -ParameterFilter { $Milliseconds -gt 0 -and $Milliseconds -le 1000 } diff --git a/Workshop/ContinuousDeployment.md b/Workshop/ContinuousDeployment.md index 50a084c288..80e3fdad0a 100644 --- a/Workshop/ContinuousDeployment.md +++ b/Workshop/ContinuousDeployment.md @@ -90,6 +90,8 @@ Paste the value from the clipboard into the "Value" field of the **AuthContext** ## PTE deployment authorization +The Automation API's PTE upload (`extensionUpload`) is [deprecated and planned for removal in 2027 release wave 1](https://learn.microsoft.com/en-us/dynamics365/business-central/dev-itpro/administration/resources/dynamics_extensionupload), so configure the Admin API permissions below before removal because AL-Go's fallback depends on this endpoint. + For **BC 29 or later**, AL-Go prefers administration center publishing for PTEs. To enable it with S2S authentication, add the **AdminCenter.ReadWrite.All** application permission under **Dynamics 365 Business Central**, grant **tenant admin consent**, and add the client ID to **Authorized Microsoft Entra apps** in the Business Central administration center. Keep the environment API permissions, such as **Automation.ReadWrite.All** and **API.ReadWrite.All** where required, and the Microsoft Entra application registration and permission sets inside each Business Central environment. With delegated authentication (impersonation), administration center publishing requires appropriate **Business Central administration center access** as well as the environment permissions. The existing **AUTHCONTEXT** credential structure and the commands above remain unchanged. See the official [Business Central administration center API documentation](https://learn.microsoft.com/en-us/dynamics365/business-central/dev-itpro/administration/administration-center-api) for authentication and authorization details. From 9d1c75176786e24122083d2edb096edcc179a047 Mon Sep 17 00:00:00 2001 From: spetersenms Date: Fri, 13 Nov 2026 17:46:15 +0100 Subject: [PATCH 08/12] Simplify error handling --- Actions/.Modules/AdminCenterApi.psm1 | 39 +--------------------------- Actions/Deploy/Deploy.psm1 | 13 +++------- Tests/AdminCenterApi.Test.ps1 | 39 ---------------------------- Tests/PublishPTEApps.Test.ps1 | 5 +++- 4 files changed, 9 insertions(+), 87 deletions(-) diff --git a/Actions/.Modules/AdminCenterApi.psm1 b/Actions/.Modules/AdminCenterApi.psm1 index 8e755ad5ea..5fd0ca03a4 100644 --- a/Actions/.Modules/AdminCenterApi.psm1 +++ b/Actions/.Modules/AdminCenterApi.psm1 @@ -87,43 +87,6 @@ function Get-AdminCenterApiUrl { return "$($apiBaseUrl.TrimEnd('/'))/admin/$adminCenterApiVersion/applications/$([Uri]::EscapeDataString($applicationFamily))/environments/$([Uri]::EscapeDataString($environment))" } -<# - .SYNOPSIS - Read exception and service error messages without dumping response objects. - .PARAMETER errorRecord - Error containing exception and optional service response details. -#> -function Get-AdminCenterApiErrorMessage { - Param( - [Parameter(Mandatory = $true)] - [System.Management.Automation.ErrorRecord] $errorRecord - ) - - $messages = @($errorRecord.Exception.Message) - if ($errorRecord.ErrorDetails) { $messages += $errorRecord.ErrorDetails.Message } - $message = (@(foreach ($text in $messages) { - if ($text.TrimStart().StartsWith('{') -or $text.TrimStart().StartsWith('[')) { - try { - $details = $text | ConvertFrom-Json | ConvertTo-HashTable -recurse - if ($details -is [hashtable]) { - if ($details['error'] -is [hashtable]) { $details = $details['error'] } - foreach ($field in @('code', 'message', 'error_description')) { - if ($details[$field] -is [string]) { $details[$field] } - } - if ($details['error'] -is [string]) { $details['error'] } - } - } - catch { - 'Structured service error details could not be read.' - } - } - else { - $text - } - }) -join ' ') - return ($message -replace '[\r\n]+', ' ') -} - <# .SYNOPSIS Send one authenticated Admin Center request without retries. @@ -347,4 +310,4 @@ function Get-AdminCenterInstalledExtensions { } } -Export-ModuleMember -Function Initialize-AdminCenterAuthContext, Get-AdminCenterApiUrl, Get-AdminCenterApiErrorMessage, Invoke-AdminCenterApi, Install-AdminCenterPTE, Get-AdminCenterAppOperation, Get-AdminCenterInstalledExtensions +Export-ModuleMember -Function Initialize-AdminCenterAuthContext, Get-AdminCenterApiUrl, Invoke-AdminCenterApi, Install-AdminCenterPTE, Get-AdminCenterAppOperation, Get-AdminCenterInstalledExtensions diff --git a/Actions/Deploy/Deploy.psm1 b/Actions/Deploy/Deploy.psm1 index 94e47ba909..3d09dc0c13 100644 --- a/Actions/Deploy/Deploy.psm1 +++ b/Actions/Deploy/Deploy.psm1 @@ -331,7 +331,7 @@ function Initialize-PTEPublishingApi { } catch { if (!(Test-AdminCenterAuthorizationError -errorRecord $_)) { throw } - $authorizationDetails = Get-AdminCenterApiErrorMessage -errorRecord $_ + $authorizationDetails = "$_" $publishingApi = 'Automation' $extensions = @(GetInstalledExtensions -bcAuthContext $bcAuthContext -environment $environment -publishingApi $publishingApi) } @@ -404,11 +404,7 @@ function WaitPTEOperation { $serviceError += $operation['error']['message'] } $serviceError = @($serviceError | Where-Object { $_ -is [string] }) -join ' ' - $record = [System.Management.Automation.ErrorRecord]::new( - [System.Exception]::new("PTE operation $operationId for app $appId did not succeed ($status). $serviceError"), - 'PTEOperationFailed', 'InvalidResult', $null) - $details = Get-AdminCenterApiErrorMessage -errorRecord $record - throw [System.Exception]::new($details) + throw "PTE operation $operationId for app $appId did not succeed ($status). $serviceError" } } if ($requests -ge $maxStatusRequests -or $timer.Elapsed.TotalSeconds -ge $timeoutSeconds) { @@ -433,11 +429,10 @@ function WaitPTEOperation { $transient = $_.Exception.Data['AdminCenterRequestStarted'] -ne $false -and ($statusCode -in 408,429,500,502,503,504 -or (!$statusCode -and ($_.Exception -is [System.Net.WebException] -or $_.Exception -is [System.Net.Http.HttpRequestException] -or $_.Exception -is [System.TimeoutException]))) - $details = Get-AdminCenterApiErrorMessage -errorRecord $_ if (!$transient -or ++$transientErrors -gt 5) { - throw "Unable to read PTE operation $operationId for app ${appId}: $details" + throw "Unable to read PTE operation $operationId for app ${appId}: $_" } - OutputWarning -message "Transient error reading PTE operation ${operationId}: $details. Retrying the status request." + OutputWarning -message "Transient error reading PTE operation ${operationId}: $_. Retrying the status request." } } throw "Timed out waiting for PTE operation $operationId for app $appId after $timeoutSeconds seconds or $maxStatusRequests status requests. The upload will not be replayed." diff --git a/Tests/AdminCenterApi.Test.ps1 b/Tests/AdminCenterApi.Test.ps1 index b8656afd2f..3572283522 100644 --- a/Tests/AdminCenterApi.Test.ps1 +++ b/Tests/AdminCenterApi.Test.ps1 @@ -527,43 +527,4 @@ Describe 'AL-Go Admin Center API helpers' { (Get-Module AdminCenterApi).ExportedFunctions.Keys | Should -Not -Contain 'Get-DeploymentTarget' } - It 'Preserves exception and plain service messages on one log line' { - $exception = [System.Exception]::new('403 Forbidden') - $record = [System.Management.Automation.ErrorRecord]::new($exception, 'Denied', 'PermissionDenied', $null) - $record.ErrorDetails = [System.Management.Automation.ErrorDetails]::new("Permission AdminCenter.ReadWrite.All missing.`nUser not authorized.") - - $message = Get-AdminCenterApiErrorMessage -errorRecord $record - - $message | Should -Match '403 Forbidden' - $message | Should -Match 'Permission AdminCenter.ReadWrite.All missing' - $message | Should -Match 'User not authorized' - $message | Should -Not -Match '[\r\n]' - } - - It 'Reads only service error fields rather than arbitrary structured response properties' { - $record = [System.Management.Automation.ErrorRecord]::new( - [System.Exception]::new('403 Forbidden'), - 'Denied', 'PermissionDenied', $null) - $record.ErrorDetails = [System.Management.Automation.ErrorDetails]::new('{"error":{"code":"AuthorizationFailed","message":"access denied"},"credentials":{"value":"private-arbitrary-value"},"headers":{"Authorization":"private-base64"}}') - - $message = Get-AdminCenterApiErrorMessage -errorRecord $record - - $message | Should -Match '403 Forbidden AuthorizationFailed access denied' - $message | Should -Not -Match 'private-arbitrary-value|private-base64|credentials|headers' - } - - It 'Does not accept or inspect an authentication context' { - (Get-Command Get-AdminCenterApiErrorMessage).Parameters.Keys | Should -Not -Contain 'bcAuthContext' - } - - It 'Preserves OAuth error fields without rendering other response properties' { - $record = [System.Management.Automation.ErrorRecord]::new( - [System.Exception]::new('{"error":"invalid_client","error_description":"Client not authorized","request":{"headers":{"Authorization":"private-header"}}}'), - 'Denied', 'PermissionDenied', $null) - - $message = Get-AdminCenterApiErrorMessage -errorRecord $record - - $message | Should -Match 'Client not authorized invalid_client' - $message | Should -Not -Match 'private-header|request|headers' - } } diff --git a/Tests/PublishPTEApps.Test.ps1 b/Tests/PublishPTEApps.Test.ps1 index 4e99bd2ecf..2df14057eb 100644 --- a/Tests/PublishPTEApps.Test.ps1 +++ b/Tests/PublishPTEApps.Test.ps1 @@ -66,7 +66,9 @@ InModuleScope Deploy { Mock Get-AdminCenterInstalledExtensions { $exception = [System.Exception]::new('Admin permission missing') $exception | Add-Member NoteProperty Response ([PSCustomObject]@{ StatusCode = $script:probeStatus }) - throw $exception + $record = [System.Management.Automation.ErrorRecord]::new($exception, 'ServiceDenied', 'PermissionDenied', $null) + $record.ErrorDetails = [System.Management.Automation.ErrorDetails]::new('{"error":{"message":"Admin permission missing"},"correlationId":"test-correlation"}') + throw $record } Initialize-PTEPublishingApi -bcAuthContext @{} -environment Sandbox @@ -76,6 +78,7 @@ InModuleScope Deploy { Assert-MockCalled Get-BcInstalledExtensions -Exactly 1 Assert-MockCalled OutputWarning -Exactly 1 -ParameterFilter { $message -like '*Admin permission missing*permissions*ContinuousDeployment.md#pte-deployment-authorization*throughout this Deploy action*' -and + $message -like '*"correlationId":"test-correlation"*' -and $message -like '*planned for removal in 2027 release wave 1*' } } From 9c18a1ae3f943dc1349cf5f68ab6fcdc3095d337 Mon Sep 17 00:00:00 2001 From: spetersenms Date: Mon, 16 Nov 2026 15:28:11 +0100 Subject: [PATCH 09/12] Moving functionality to admin helper --- Actions/.Modules/AdminCenterApi.psm1 | 183 +++++++++++- Actions/Deploy/Deploy.psm1 | 175 +----------- Tests/AdminCenterApi.Test.ps1 | 12 +- Tests/PublishPTEApps.Test.ps1 | 407 +++++++++++++++------------ 4 files changed, 419 insertions(+), 358 deletions(-) diff --git a/Actions/.Modules/AdminCenterApi.psm1 b/Actions/.Modules/AdminCenterApi.psm1 index 5fd0ca03a4..f34de5d951 100644 --- a/Actions/.Modules/AdminCenterApi.psm1 +++ b/Actions/.Modules/AdminCenterApi.psm1 @@ -1,5 +1,7 @@ $errorActionPreference = "Stop"; $ProgressPreference = "SilentlyContinue"; Set-StrictMode -Version 2.0 +. (Join-Path $PSScriptRoot '..\AL-Go-Helper.ps1') + # Pin the contract AL-Go implements; update this with its callers and contract tests. $adminCenterApiVersion = 'v2.29' $script:adminCenterAuthContext = $null @@ -7,7 +9,7 @@ $script:adminCenterTarget = $null <# .SYNOPSIS - Prepare the Admin Center target and authentication context for this Deploy action. + Prepare the Admin Center target and authentication context for native requests. .DESCRIPTION Retains the supplied independent context and target for all native requests. .PARAMETER authContext @@ -167,6 +169,7 @@ function Invoke-AdminCenterApi { .DESCRIPTION Builds and disposes multipart content using binary serialization supported on PowerShell 5 and 7. Makes one upload attempt without retries using the initialized Admin context. + Returns the operation without waiting. Use Install-AdminCenterPTEApps to wait for installation. .PARAMETER environment Target environment. .PARAMETER appFile @@ -178,7 +181,7 @@ function Invoke-AdminCenterApi { .PARAMETER apiBaseUrl Target API root. #> -function Install-AdminCenterPTE { +function Install-AdminCenterPTEApp { Param( [string] $environment, [string] $appFile, @@ -310,4 +313,178 @@ function Get-AdminCenterInstalledExtensions { } } -Export-ModuleMember -Function Initialize-AdminCenterAuthContext, Get-AdminCenterApiUrl, Invoke-AdminCenterApi, Install-AdminCenterPTE, Get-AdminCenterAppOperation, Get-AdminCenterInstalledExtensions +<# + .SYNOPSIS + Resolve the target BC version from its installed Application extension. + .PARAMETER extensions + Extensions returned by the read-only environment API. + .PARAMETER environment + Target environment name, used in failure diagnostics. +#> +function GetPTEApplicationVersion { + Param( + [object[]] $extensions, + [string] $environment + ) + + $applications = @($extensions | Where-Object { + $app = $_ | ConvertTo-HashTable -recurse + ($app['displayName'] -eq 'Application' -or $app['id'] -eq $applicationAppId) -and $app['isInstalled'] + }) + $version = $null + if ($applications.Count -eq 1) { + $application = $applications[0] | ConvertTo-HashTable -recurse + $parts = @('versionMajor', 'versionMinor', 'versionBuild', 'versionRevision' | ForEach-Object { + if ($application.ContainsKey($_)) { [string]$application[$_] } + }) + if ($parts.Count -eq 4 -and [version]::TryParse(($parts -join '.'), [ref]$version)) { + return $version + } + } + throw "Could not determine the Business Central version in environment $environment from a unique installed Application extension." +} + +<# + .SYNOPSIS + Wait for the exact Admin Center PTE operation to complete successfully. + .DESCRIPTION + Polls only the returned app and operation IDs. An accepted or scheduled immediate install + is not success. Only transient status-read errors are retried, never the upload. + Uses the initialized Admin authentication context. + .PARAMETER environment + Target environment. + .PARAMETER operation + Upload response containing the operation id, appId and status. + .PARAMETER appId + Expected app ID from the package. + .PARAMETER timeoutSeconds + Maximum elapsed polling time. Defaults to 30 minutes. + .PARAMETER maxStatusRequests + Maximum number of status requests. Defaults to 360. + .PARAMETER pollIntervalSeconds + Delay between status requests. Defaults to 30 seconds, capped by the remaining timeout. +#> +function WaitPTEOperation { + Param( + [string] $environment, + $operation, + [string] $appId, + [ValidateRange(1, 1800)] + [int] $timeoutSeconds = 1800, + [ValidateRange(1, 360)] + [int] $maxStatusRequests = 360, + [ValidateRange(0, 30)] + [int] $pollIntervalSeconds = 30 + ) + + $operation = $operation | ConvertTo-HashTable -recurse + if ($operation -isnot [hashtable] -or !$operation['id'] -or $operation['appId'] -ne $appId) { + throw "PTE upload returned missing or mismatched app/operation details for app $appId. The upload will not be replayed." + } + $operationId = [string]$operation['id'] + $timer = [System.Diagnostics.Stopwatch]::StartNew() + $transientErrors = 0 + $requests = 0 + while ($true) { + if ($operation -isnot [hashtable] -or $operation['id'] -ne $operationId -or + ($operation.ContainsKey('appId') -and $operation['appId'] -ne $appId)) { + throw "Missing or mismatched PTE operation $operationId for app $appId." + } + $status = [string]$operation['status'] + Write-Host "PTE operation $operationId for app ${appId}: $status" + switch ($status) { + 'succeeded' { return } + 'scheduled' {} + 'running' {} + default { + $serviceError = @($operation['errorMessage']) + if ($operation['error'] -is [hashtable]) { + $serviceError += $operation['error']['message'] + } + $serviceError = @($serviceError | Where-Object { $_ -is [string] }) -join ' ' + throw "PTE operation $operationId for app $appId did not succeed ($status). $serviceError" + } + } + if ($requests -ge $maxStatusRequests -or $timer.Elapsed.TotalSeconds -ge $timeoutSeconds) { + break + } + $sleepSeconds = [Math]::Min($pollIntervalSeconds, [Math]::Max(0, $timeoutSeconds - $timer.Elapsed.TotalSeconds)) + Start-Sleep -Milliseconds ([int][Math]::Ceiling($sleepSeconds * 1000)) + if ($timer.Elapsed.TotalSeconds -ge $timeoutSeconds) { break } + $requests++ + try { + $requestTimeout = [int][Math]::Max(1, [Math]::Min(30, [Math]::Ceiling($timeoutSeconds - $timer.Elapsed.TotalSeconds))) + $operation = Get-AdminCenterAppOperation -environment $environment ` + -appId $appId -operationId $operationId -timeoutSeconds $requestTimeout + $operation = $operation | ConvertTo-HashTable -recurse + $transientErrors = 0 + } + catch { + $statusCode = 0 + if ($_.Exception.PSObject.Properties['Response'] -and $_.Exception.Response) { + $statusCode = [int]$_.Exception.Response.StatusCode + } + $transient = $_.Exception.Data['AdminCenterRequestStarted'] -ne $false -and ($statusCode -in 408,429,500,502,503,504 -or + (!$statusCode -and ($_.Exception -is [System.Net.WebException] -or + $_.Exception -is [System.Net.Http.HttpRequestException] -or $_.Exception -is [System.TimeoutException]))) + if (!$transient -or ++$transientErrors -gt 5) { + throw "Unable to read PTE operation $operationId for app ${appId}: $_" + } + OutputWarning -message "Transient error reading PTE operation ${operationId}: $_. Retrying the status request." + } + } + throw "Timed out waiting for PTE operation $operationId for app $appId after $timeoutSeconds seconds or $maxStatusRequests status requests. The upload will not be replayed." +} + +<# + .SYNOPSIS + Publish a batch of PTE packages through Admin Center. + .DESCRIPTION + Requires BC 29 or later. Expands packages, excludes runtime packages and orders dependencies. + Skips same or newer installed versions, and waits for each exact install operation before continuing. + Uses the initialized Admin authentication context and target. + Requires BcContainerHelper package and authentication helpers to be loaded by the caller. + .PARAMETER environment + Target Business Central environment name. + .PARAMETER appFiles + App packages or archives to publish. + .PARAMETER schemaSyncMode + Existing helper-compatible sync mode: Add or Force (mapped to ForceSync). +#> +function Install-AdminCenterPTEApps { + Param( + [string] $environment, + [string[]] $appFiles, + [ValidateSet('Add', 'Force')] + [string] $schemaSyncMode = 'Add' + ) + + $extensions = @(Get-AdminCenterInstalledExtensions -environment $environment) + $applicationVersion = GetPTEApplicationVersion -extensions $extensions -environment $environment + if ($applicationVersion -lt [version]'29.0.0.0') { + throw "Admin Center PTE publishing requires BC 29 or later; the selected API will not be changed." + } + $tempPath = NewTemporaryFolder + try { + $copiedApps = @(Copy-AppFilesToFolder -appFiles $appFiles -folder $tempPath) + $sortedApps = @(Sort-AppFilesByDependencies -appFiles $copiedApps -excludeRuntimePackages) + $syncMode = if ($schemaSyncMode -eq 'Force') { 'ForceSync' } else { 'Add' } + foreach ($appFile in $sortedApps) { + $appJson = Get-AppJsonFromAppFile -appFile $appFile + $appVersion = [version]$appJson.version + $matchingApps = @($extensions | Where-Object { $_.id -eq $appJson.id }) + $installedVersions = @($matchingApps | Where-Object { $_.isInstalled } | + ForEach-Object { [version]::new("$($_.versionMajor).$($_.versionMinor).$($_.versionBuild).$($_.versionRevision)") }) + if (@($installedVersions | Where-Object { $_ -ge $appVersion }).Count -gt 0) { + continue + } + $operation = Install-AdminCenterPTEApp -environment $environment -appFile $appFile -syncMode $syncMode + WaitPTEOperation -environment $environment -operation $operation -appId $appJson.id + } + } + finally { + Remove-Item -LiteralPath $tempPath -Force -Recurse + } +} + +Export-ModuleMember -Function GetPTEApplicationVersion, Install-AdminCenterPTEApps, Initialize-AdminCenterAuthContext, Get-AdminCenterApiUrl, Invoke-AdminCenterApi, Install-AdminCenterPTEApp, Get-AdminCenterAppOperation, Get-AdminCenterInstalledExtensions diff --git a/Actions/Deploy/Deploy.psm1 b/Actions/Deploy/Deploy.psm1 index 3d09dc0c13..8eb2395441 100644 --- a/Actions/Deploy/Deploy.psm1 +++ b/Actions/Deploy/Deploy.psm1 @@ -255,37 +255,6 @@ function CheckInstalledApps { } } -<# - .SYNOPSIS - Resolve the target BC version from its installed Application extension. - .PARAMETER extensions - Extensions returned by the read-only environment API. - .PARAMETER environment - Target environment name, used in failure diagnostics. -#> -function GetPTEApplicationVersion { - Param( - [object[]] $extensions, - [string] $environment - ) - - $applications = @($extensions | Where-Object { - $app = $_ | ConvertTo-HashTable -recurse - ($app['displayName'] -eq 'Application' -or $app['id'] -eq $applicationAppId) -and $app['isInstalled'] - }) - $version = $null - if ($applications.Count -eq 1) { - $application = $applications[0] | ConvertTo-HashTable -recurse - $parts = @('versionMajor', 'versionMinor', 'versionBuild', 'versionRevision' | ForEach-Object { - if ($application.ContainsKey($_)) { [string]$application[$_] } - }) - if ($parts.Count -eq 4 -and [version]::TryParse(($parts -join '.'), [ref]$version)) { - return $version - } - } - throw "Could not determine the Business Central version in environment $environment from a unique installed Application extension." -} - <# .SYNOPSIS Read installed apps using the selected API, or the original BCH API for non-PTE work. @@ -346,98 +315,6 @@ function Initialize-PTEPublishingApi { $script:ptePublishingApi = $publishingApi } -<# - .SYNOPSIS - Wait for the exact Admin Center PTE operation to complete successfully. - .DESCRIPTION - Polls only the returned app and operation IDs. An accepted or scheduled immediate install - is not success. Only transient status-read errors are retried, never the upload. - Uses the initialized Admin authentication context. - .PARAMETER environment - Target environment. - .PARAMETER operation - Upload response containing the operation id, appId and status. - .PARAMETER appId - Expected app ID from the package. - .PARAMETER timeoutSeconds - Maximum elapsed polling time. Defaults to 30 minutes. - .PARAMETER maxStatusRequests - Maximum number of status requests. Defaults to 360. - .PARAMETER pollIntervalSeconds - Delay between status requests. Defaults to 30 seconds, capped by the remaining timeout. -#> -function WaitPTEOperation { - Param( - [string] $environment, - $operation, - [string] $appId, - [ValidateRange(1, 1800)] - [int] $timeoutSeconds = 1800, - [ValidateRange(1, 360)] - [int] $maxStatusRequests = 360, - [ValidateRange(0, 30)] - [int] $pollIntervalSeconds = 30 - ) - - $operation = $operation | ConvertTo-HashTable -recurse - if ($operation -isnot [hashtable] -or !$operation['id'] -or $operation['appId'] -ne $appId) { - throw "PTE upload returned missing or mismatched app/operation details for app $appId. The upload will not be replayed." - } - $operationId = [string]$operation['id'] - $timer = [System.Diagnostics.Stopwatch]::StartNew() - $transientErrors = 0 - $requests = 0 - while ($true) { - if ($operation -isnot [hashtable] -or $operation['id'] -ne $operationId -or - ($operation.ContainsKey('appId') -and $operation['appId'] -ne $appId)) { - throw "Missing or mismatched PTE operation $operationId for app $appId." - } - $status = [string]$operation['status'] - Write-Host "PTE operation $operationId for app ${appId}: $status" - switch ($status) { - 'succeeded' { return } - 'scheduled' {} - 'running' {} - default { - $serviceError = @($operation['errorMessage']) - if ($operation['error'] -is [hashtable]) { - $serviceError += $operation['error']['message'] - } - $serviceError = @($serviceError | Where-Object { $_ -is [string] }) -join ' ' - throw "PTE operation $operationId for app $appId did not succeed ($status). $serviceError" - } - } - if ($requests -ge $maxStatusRequests -or $timer.Elapsed.TotalSeconds -ge $timeoutSeconds) { - break - } - $sleepSeconds = [Math]::Min($pollIntervalSeconds, [Math]::Max(0, $timeoutSeconds - $timer.Elapsed.TotalSeconds)) - Start-Sleep -Milliseconds ([int][Math]::Ceiling($sleepSeconds * 1000)) - if ($timer.Elapsed.TotalSeconds -ge $timeoutSeconds) { break } - $requests++ - try { - $requestTimeout = [int][Math]::Max(1, [Math]::Min(30, [Math]::Ceiling($timeoutSeconds - $timer.Elapsed.TotalSeconds))) - $operation = Get-AdminCenterAppOperation -environment $environment ` - -appId $appId -operationId $operationId -timeoutSeconds $requestTimeout - $operation = $operation | ConvertTo-HashTable -recurse - $transientErrors = 0 - } - catch { - $statusCode = 0 - if ($_.Exception.PSObject.Properties['Response'] -and $_.Exception.Response) { - $statusCode = [int]$_.Exception.Response.StatusCode - } - $transient = $_.Exception.Data['AdminCenterRequestStarted'] -ne $false -and ($statusCode -in 408,429,500,502,503,504 -or - (!$statusCode -and ($_.Exception -is [System.Net.WebException] -or - $_.Exception -is [System.Net.Http.HttpRequestException] -or $_.Exception -is [System.TimeoutException]))) - if (!$transient -or ++$transientErrors -gt 5) { - throw "Unable to read PTE operation $operationId for app ${appId}: $_" - } - OutputWarning -message "Transient error reading PTE operation ${operationId}: $_. Retrying the status request." - } - } - throw "Timed out waiting for PTE operation $operationId for app $appId after $timeoutSeconds seconds or $maxStatusRequests status requests. The upload will not be replayed." -} - <# .SYNOPSIS Publish primary apps or PTE dependencies through the action-selected API. @@ -469,63 +346,13 @@ function PublishPTEApps { Publish-PerTenantExtensionApps -bcAuthContext $bcAuthContext -environment $environment -appFiles $appFiles -SchemaSyncMode $schemaSyncMode } elseif ($script:ptePublishingApi -eq 'AdminCenter') { - Publish-AdminCenterPTEApps -environment $environment -appFiles $appFiles -schemaSyncMode $schemaSyncMode + Install-AdminCenterPTEApps -environment $environment -appFiles $appFiles -schemaSyncMode $schemaSyncMode } else { throw "Invalid PTE publishing API: $script:ptePublishingApi" } } -<# - .SYNOPSIS - Publish a batch of PTE packages through Admin Center. - .DESCRIPTION - Requires BC 29 or later. Expands packages, excludes runtime packages and orders dependencies. - Skips same or newer installed versions, and waits for each exact install operation before continuing. - Uses the initialized Admin authentication context and target. - .PARAMETER environment - Target Business Central environment name. - .PARAMETER appFiles - App packages or archives to publish. - .PARAMETER schemaSyncMode - Existing helper-compatible sync mode: Add or Force (mapped to ForceSync). -#> -function Publish-AdminCenterPTEApps { - Param( - [string] $environment, - [string[]] $appFiles, - [ValidateSet('Add', 'Force')] - [string] $schemaSyncMode = 'Add' - ) - - $extensions = @(Get-AdminCenterInstalledExtensions -environment $environment) - $applicationVersion = GetPTEApplicationVersion -extensions $extensions -environment $environment - if ($applicationVersion -lt [version]'29.0.0.0') { - throw "Admin Center PTE publishing requires BC 29 or later; the selected API will not be changed." - } - $tempPath = NewTemporaryFolder - try { - $copiedApps = @(Copy-AppFilesToFolder -appFiles $appFiles -folder $tempPath) - $sortedApps = @(Sort-AppFilesByDependencies -appFiles $copiedApps -excludeRuntimePackages) - $syncMode = if ($schemaSyncMode -eq 'Force') { 'ForceSync' } else { 'Add' } - foreach ($appFile in $sortedApps) { - $appJson = Get-AppJsonFromAppFile -appFile $appFile - $appVersion = [version]$appJson.version - $matchingApps = @($extensions | Where-Object { $_.id -eq $appJson.id }) - $installedVersions = @($matchingApps | Where-Object { $_.isInstalled } | - ForEach-Object { [version]::new("$($_.versionMajor).$($_.versionMinor).$($_.versionBuild).$($_.versionRevision)") }) - if (@($installedVersions | Where-Object { $_ -ge $appVersion }).Count -gt 0) { - continue - } - $operation = Install-AdminCenterPTE -environment $environment -appFile $appFile -syncMode $syncMode - WaitPTEOperation -environment $environment -operation $operation -appId $appJson.id - } - } - finally { - Remove-Item -LiteralPath $tempPath -Force -Recurse - } -} - <# .SYNOPSIS Unpublish old, uninstalled versions of the deployed apps from a Business Central environment. diff --git a/Tests/AdminCenterApi.Test.ps1 b/Tests/AdminCenterApi.Test.ps1 index 3572283522..c5a36e43fe 100644 --- a/Tests/AdminCenterApi.Test.ps1 +++ b/Tests/AdminCenterApi.Test.ps1 @@ -44,7 +44,7 @@ Describe 'AL-Go Admin Center API helpers' { return @{ id = 'operation-1' } } - $result = Install-AdminCenterPTE -environment 'QA / East' ` + $result = Install-AdminCenterPTEApp -environment 'QA / East' ` -apiBaseUrl 'https://api.embed.test/service/' -applicationFamily 'Family / US' -appFile $script:packagePath -syncMode $syncMode $result.id | Should -Be 'operation-1' @@ -187,7 +187,7 @@ Describe 'AL-Go Admin Center API helpers' { Mock Invoke-RestMethod { return @{ value = @(); id = 'operation-1' } } Get-AdminCenterInstalledExtensions -environment Sandbox | Out-Null - Install-AdminCenterPTE -environment Sandbox -appFile $script:packagePath | Out-Null + Install-AdminCenterPTEApp -environment Sandbox -appFile $script:packagePath | Out-Null Get-AdminCenterAppOperation -environment Sandbox -appId app -operationId operation | Out-Null Assert-MockCalled Invoke-RestMethod -ModuleName BcContainerHelper -Exactly 1 -ParameterFilter { @@ -273,7 +273,7 @@ Describe 'AL-Go Admin Center API helpers' { Mock Invoke-RestMethod { return @{ value = @(); id = 'operation' } } Get-AdminCenterInstalledExtensions -environment Sandbox ` -apiBaseUrl 'https://explicit.test' -applicationFamily 'ExplicitFamily' | Out-Null - Install-AdminCenterPTE -environment Sandbox -appFile $script:packagePath ` + Install-AdminCenterPTEApp -environment Sandbox -appFile $script:packagePath ` -apiBaseUrl 'https://api.businesscentral.dynamics.com' | Out-Null Get-AdminCenterAppOperation -environment Sandbox -appId app -operationId operation ` -applicationFamily BusinessCentral | Out-Null @@ -379,7 +379,7 @@ Describe 'AL-Go Admin Center API helpers' { Mock Renew-BcAuthContext { throw [System.TimeoutException]::new('Renewal failed') } try { - Install-AdminCenterPTE -environment Sandbox -appFile $script:packagePath + Install-AdminCenterPTEApp -environment Sandbox -appFile $script:packagePath throw 'Expected failure' } catch { @@ -434,7 +434,7 @@ Describe 'AL-Go Admin Center API helpers' { Mock Invoke-RestMethod { throw [System.TimeoutException]::new('Response lost') } try { - Install-AdminCenterPTE -environment Sandbox -appFile $script:packagePath + Install-AdminCenterPTEApp -environment Sandbox -appFile $script:packagePath throw 'Expected failure' } catch { @@ -450,7 +450,7 @@ Describe 'AL-Go Admin Center API helpers' { Mock Invoke-AdminCenterApi { throw 'Request must not be called' } try { - Install-AdminCenterPTE -environment Sandbox -appFile (Join-Path $TestDrive 'Missing.app') + Install-AdminCenterPTEApp -environment Sandbox -appFile (Join-Path $TestDrive 'Missing.app') throw 'Expected failure' } catch { diff --git a/Tests/PublishPTEApps.Test.ps1 b/Tests/PublishPTEApps.Test.ps1 index 2df14057eb..27b082159f 100644 --- a/Tests/PublishPTEApps.Test.ps1 +++ b/Tests/PublishPTEApps.Test.ps1 @@ -25,7 +25,7 @@ InModuleScope Deploy { Mock OutputWarning { } Mock Renew-BcAuthContext { return @{ AccessToken = 'renewed-test-token' } } Mock Invoke-RestMethod { throw "Unexpected HTTP request" } - Mock Install-AdminCenterPTE { throw 'Unexpected installation request' } + Mock Install-AdminCenterPTEApps { } Mock Get-AdminCenterAppOperation { throw 'Unexpected operation request' } Mock Get-AdminCenterInstalledExtensions { return $script:extensions } Mock Get-BcInstalledExtensions { return $script:extensions } @@ -199,8 +199,6 @@ InModuleScope Deploy { Mock Sort-AppFilesByDependencies { return @('App.app') } Mock Remove-Item { } Mock Get-AppJsonFromAppFile { return @{ id = 'app-1'; name = 'App'; version = '2.0.0.0' } } - Mock Install-AdminCenterPTE { return @{ id = 'operation-1'; appId = 'app-1'; status = 'running' } } - Mock WaitPTEOperation { } } It 'Reuses the initialized Automation route for dependencies and primary publishing' { @@ -217,7 +215,7 @@ InModuleScope Deploy { Assert-MockCalled Get-AdminCenterInstalledExtensions -Exactly 1 Assert-MockCalled Get-BcInstalledExtensions -Exactly 1 Assert-MockCalled Publish-PerTenantExtensionApps -Exactly 2 - Assert-MockCalled Install-AdminCenterPTE -Times 0 + Assert-MockCalled Install-AdminCenterPTEApps -Times 0 Assert-MockCalled OutputWarning -Exactly 1 } @@ -232,20 +230,12 @@ InModuleScope Deploy { Assert-MockCalled OutputWarning -Times 0 } - It 'Does not switch an Admin route when a later read or write fails authorization' -TestCases @( - @{ step = 'read' }, @{ step = 'write' } - ) { - param($step) + It 'Does not switch an Admin route when a later native batch fails authorization' { PublishPTEApps -bcAuthContext @{} -environment Sandbox -appFiles @('Dependency.app') $exception = [System.Exception]::new('Later access rejected') $exception | Add-Member NoteProperty Response ([PSCustomObject]@{ StatusCode = 403 }) $script:laterFailure = $exception - if ($step -eq 'read') { - Mock Get-AdminCenterInstalledExtensions { throw $script:laterFailure } - } - else { - Mock Install-AdminCenterPTE { throw $script:laterFailure } - } + Mock Install-AdminCenterPTEApps { throw $script:laterFailure } { PublishPTEApps -bcAuthContext @{} -environment Sandbox -appFiles @('Primary.app') } | Should -Throw '*Later access rejected*' @@ -270,10 +260,10 @@ InModuleScope Deploy { PublishPTEApps -bcAuthContext @{} -environment Second -appFiles @('App.app') $script:ptePublishingApi | Should -Be AdminCenter - Assert-MockCalled Get-AdminCenterInstalledExtensions -Exactly 2 -ParameterFilter { + Assert-MockCalled Get-AdminCenterInstalledExtensions -Exactly 1 -ParameterFilter { $environment -eq 'Second' } - Assert-MockCalled Install-AdminCenterPTE -Exactly 1 -ParameterFilter { + Assert-MockCalled Install-AdminCenterPTEApps -Exactly 1 -ParameterFilter { $environment -eq 'Second' } } @@ -324,20 +314,61 @@ InModuleScope Deploy { $environment -eq 'Sandbox' -and $bcAuthContext.tenantId -eq 'tenant' -and $appFiles[0] -eq 'Apps.zip' -and $schemaSyncMode -eq 'Force' } - Assert-MockCalled Install-AdminCenterPTE -Times 0 + Assert-MockCalled Install-AdminCenterPTEApps -Times 0 Assert-MockCalled NewTemporaryFolder -Times 0 Assert-MockCalled Get-BcInstalledExtensions -Times 0 Assert-MockCalled Get-AdminCenterInstalledExtensions -Times 0 Assert-MockCalled Invoke-RestMethod -Times 0 } + It 'Leaves Automation package preparation and installed-version skipping entirely to BCH' { + $script:ptePublishingApi = 'Automation' + Mock Sort-AppFilesByDependencies { return @('Installed.app', 'First.app', 'Second.app') } + $script:extensions += @{ + id = 'Installed.app'; displayName = 'Installed'; isInstalled = $true + versionMajor = 3; versionMinor = 0; versionBuild = 0; versionRevision = 0 + } + Mock Get-AppJsonFromAppFile { + param($appFile) + return @{ id = $appFile; name = $appFile; version = '2.0.0.0' } + } + Mock Publish-PerTenantExtensionApps { + $bcContainerHelperConfig.apiBaseUrl | Should -Be 'https://api.example.test/' + } + PublishPTEApps -bcAuthContext @{} -environment Sandbox -appFiles @('Apps.zip', 'Installed.app') ` + -schemaSyncMode Force + + Assert-MockCalled Publish-PerTenantExtensionApps -Exactly 1 -ParameterFilter { + ($appFiles -join ',') -eq 'Apps.zip,Installed.app' -and $schemaSyncMode -eq 'Force' + } + Assert-MockCalled Copy-AppFilesToFolder -Times 0 + Assert-MockCalled Sort-AppFilesByDependencies -Times 0 + Assert-MockCalled Get-AppJsonFromAppFile -Times 0 + Assert-MockCalled Install-AdminCenterPTEApps -Times 0 + Assert-MockCalled Get-AdminCenterInstalledExtensions -Times 0 + Assert-MockCalled Get-BcInstalledExtensions -Times 0 + } + + It 'Propagates Automation batch failures without changing route or preparing packages' { + $script:ptePublishingApi = 'Automation' + Mock Publish-PerTenantExtensionApps { throw 'Batch failed' } + { PublishPTEApps -bcAuthContext @{} -environment Sandbox -appFiles @('App.app') } | + Should -Throw '*Batch failed*' + $script:ptePublishingApi | Should -Be Automation + Assert-MockCalled Publish-PerTenantExtensionApps -Exactly 1 + Assert-MockCalled NewTemporaryFolder -Times 0 + Assert-MockCalled Remove-Item -Times 0 + Assert-MockCalled Get-AdminCenterInstalledExtensions -Times 0 + Assert-MockCalled Install-AdminCenterPTEApps -Times 0 + } + It 'Routes one original batch to the Admin publisher without preparing packages in the router' { - Mock Publish-AdminCenterPTEApps { } + Mock Install-AdminCenterPTEApps { } PublishPTEApps -bcAuthContext @{ tenantId = 'tenant' } -environment Sandbox -appFiles @('Apps.zip', 'Other.app') ` -schemaSyncMode Force - Assert-MockCalled Publish-AdminCenterPTEApps -Exactly 1 -ParameterFilter { + Assert-MockCalled Install-AdminCenterPTEApps -Exactly 1 -ParameterFilter { !$PesterBoundParameters.ContainsKey('bcAuthContext') -and $environment -eq 'Sandbox' -and ($appFiles -join ',') -eq 'Apps.zip,Other.app' -and $schemaSyncMode -eq 'Force' } @@ -346,15 +377,15 @@ InModuleScope Deploy { Assert-MockCalled Publish-PerTenantExtensionApps -Times 0 } - It 'Does not silently switch a selected Admin route when the target version changes below BC 29' { - $script:application.versionMajor = 28 + It 'Propagates a native version rejection without switching the selected Admin route' { + Mock Install-AdminCenterPTEApps { throw 'The selected API will not be changed.' } { PublishPTEApps -bcAuthContext @{} -environment Sandbox -appFiles @('App.app') } | Should -Throw '*selected API will not be changed*' $script:ptePublishingApi | Should -Be AdminCenter Assert-MockCalled Publish-PerTenantExtensionApps -Times 0 - Assert-MockCalled Install-AdminCenterPTE -Times 0 + Assert-MockCalled Install-AdminCenterPTEApps -Exactly 1 } It 'Keeps API implementation helpers private and exposes the shared publisher' { @@ -362,9 +393,144 @@ InModuleScope Deploy { $exports | Should -Contain 'PublishPTEApps' $exports | Should -Not -Contain 'InvokePTEUpload' $exports | Should -Not -Contain 'WaitPTEOperation' - $exports | Should -Not -Contain 'GetPTEApplicationVersion' + $exports | Should -Not -Contain 'Install-AdminCenterPTEApps' (Get-Command PublishPTEApps).Parameters.Keys | Should -Not -Contain 'applicationFamily' - (Get-Command WaitPTEOperation).Parameters.Keys | Should -Not -Contain 'applicationFamily' + (Get-Module AdminCenterApi).ExportedFunctions.Keys | Should -Contain 'Install-AdminCenterPTEApps' + } + + } + + Context "Native installed-app decision safety" { + BeforeEach { + $script:ptePublishingApi = 'AdminCenter' + $script:rawApplication = @{ + id = $applicationAppId; name = 'Application'; version = '30.0.0.0'; state = 'installed'; appType = 'global' + } + $script:rawApp = @{ id = 'app-1'; name = 'App'; version = '1.0.0.0'; state = 'installed'; appType = 'tenant' } + # Bind the production normalizer to the same module as the API and consumer mocks. + $script:nativeReader = [scriptblock]::Create((Get-Command Get-AdminCenterInstalledExtensions -Module AdminCenterApi).Definition) + $script:installedAppResponse = @($script:rawApplication, $script:rawApp) + Mock Invoke-AdminCenterApi { return @{ value = $script:installedAppResponse } } + Mock Get-AdminCenterInstalledExtensions { + & $script:nativeReader -environment $environment + } + Mock NewTemporaryFolder { return 'test-app-folder' } + Mock Copy-AppFilesToFolder { return @('App.app') } + Mock Get-ChildItem { return [PSCustomObject]@{ FullName = 'App.app' } } + Mock Sort-AppFilesByDependencies { return @('App.app') } + Mock Get-AppJsonFromAppFile { return @{ id = 'app-1'; name = 'App'; version = '2.0.0.0'; idRanges = @(@{ from = 50000 }) } } + Mock Install-AdminCenterPTEApp { return @{ id = 'operation-1'; appId = 'app-1'; status = 'running' } } + Mock Install-BcAppFromAppSource { } + Mock Remove-Item { } + } + + It 'Resolves Application by its known identity when its name is absent' { + $script:rawApplication.Remove('name') + + Initialize-PTEPublishingApi -bcAuthContext @{} -environment Sandbox + + $script:ptePublishingApi | Should -Be AdminCenter + Assert-MockCalled Get-BcInstalledExtensions -Times 0 + } + + It 'Rejects Application version even when its name is absent' -TestCases @( + @{ version = '30.0' }, @{ version = 'invalid' } + ) { + param($version) + $script:rawApplication.Remove('name') + $script:rawApplication.version = $version + $script:ptePublishingApi = '' + + { Initialize-PTEPublishingApi -bcAuthContext @{} -environment Sandbox } | + Should -Throw '*unique installed Application*' + + $script:ptePublishingApi | Should -Be '' + Assert-MockCalled Get-BcInstalledExtensions -Times 0 + Assert-MockCalled Install-AdminCenterPTEApps -Times 0 + } + + It 'Rejects an invalid selected installed version during primary preflight' { + $script:rawApp.version = 'invalid' + + { CheckInstalledApps -bcAuthContext @{} -environment Sandbox -appFiles @('App.app') } | Should -Throw + + Assert-MockCalled Install-AdminCenterPTEApps -Times 0 + } + + It 'Rejects an invalid installed version before writing a matched dependency' -TestCases @( + @{ kind = 'PTE'; from = 50000 }, @{ kind = 'AppSource'; from = 100000 } + ) { + param($from) + $script:rawApp.version = 'invalid' + $script:dependencyFrom = $from + Mock Get-AppJsonFromAppFile { + return @{ id = 'app-1'; name = 'App'; version = '2.0.0.0'; idRanges = @(@{ from = $script:dependencyFrom }) } + } + + { InstallOrUpgradeApps -bcAuthContext @{} -environment Sandbox -apps @('App.app') -installMode upgrade } | Should -Throw + + Assert-MockCalled Install-BcAppFromAppSource -Times 0 + Assert-MockCalled Install-AdminCenterPTEApps -Times 0 + Assert-MockCalled Publish-PerTenantExtensionApps -Times 0 + } + + It 'Keeps the Dev-scope AppSource dependency safeguard after normalization' { + $script:rawApp.appType = 'dev' + Mock Get-AppJsonFromAppFile { + return @{ id = 'app-1'; name = 'App'; version = '2.0.0.0'; idRanges = @(@{ from = 100000 }) } + } + + InstallOrUpgradeApps -bcAuthContext @{} -environment Sandbox -apps @('App.app') -installMode upgrade + + Assert-MockCalled OutputWarning -Exactly 1 -ParameterFilter { $message -like '*published in Dev scope*Cannot upgrade*' } + Assert-MockCalled Install-BcAppFromAppSource -Times 0 + Assert-MockCalled Install-AdminCenterPTEApps -Times 0 + Assert-MockCalled Publish-PerTenantExtensionApps -Times 0 + } + } + + + } +} + + +InModuleScope AdminCenterApi { + Describe 'Native Admin Center PTE installation' { + BeforeAll { + DownloadAndImportBcContainerHelper -baseFolder ([IO.Path]::GetTempPath()) + $script:nativeReader = [scriptblock]::Create((Get-Command Get-AdminCenterInstalledExtensions -Module AdminCenterApi).Definition) + } + BeforeEach { + $script:application = @{ + id = 'application'; displayName = 'Application'; isInstalled = $true + versionMajor = 30; versionMinor = 0; versionBuild = 0; versionRevision = 0 + } + $script:extensions = @($script:application) + Mock Write-Host { } + Mock OutputWarning { } + Mock Get-AdminCenterInstalledExtensions { return $script:extensions } + Mock Get-BcInstalledExtensions { throw 'Unexpected Automation read' } + Mock Publish-PerTenantExtensionApps { throw 'Unexpected Automation publish' } + Mock Install-AdminCenterPTEApp { return @{ id = 'operation-1'; appId = 'app-1'; status = 'running' } } + Mock Get-AdminCenterAppOperation { throw 'Unexpected operation read' } + } + Context 'Native batch preparation and installation' { + BeforeEach { + Mock NewTemporaryFolder { return 'test-app-folder' } + Mock Copy-AppFilesToFolder { return @('App.app') } + Mock Sort-AppFilesByDependencies { return @('App.app') } + Mock Remove-Item { } + Mock Get-AppJsonFromAppFile { return @{ id = 'app-1'; name = 'App'; version = '2.0.0.0' } } + Mock WaitPTEOperation { } + } + It 'Rejects targets below BC 29 before package preparation or upload' { + $script:application.versionMajor = 28 + + { Install-AdminCenterPTEApps -environment Sandbox -appFiles @('App.app') } | + Should -Throw '*requires BC 29*selected API will not be changed*' + + Assert-MockCalled NewTemporaryFolder -Times 0 + Assert-MockCalled Install-AdminCenterPTEApp -Times 0 } It 'Uses AL-Go Admin Center publishing for BC ' -TestCases @( @@ -373,12 +539,12 @@ InModuleScope Deploy { param($major) $script:application.versionMajor = $major - PublishPTEApps -bcAuthContext @{} -environment 'Sandbox' -appFiles @('Apps.zip') + Install-AdminCenterPTEApps -environment 'Sandbox' -appFiles @('Apps.zip') Assert-MockCalled Publish-PerTenantExtensionApps -Times 0 Assert-MockCalled Copy-AppFilesToFolder -Exactly 1 -ParameterFilter { $appFiles[0] -eq 'Apps.zip' } Assert-MockCalled Sort-AppFilesByDependencies -Exactly 1 -ParameterFilter { $excludeRuntimePackages } - Assert-MockCalled Install-AdminCenterPTE -Exactly 1 -ParameterFilter { + Assert-MockCalled Install-AdminCenterPTEApp -Exactly 1 -ParameterFilter { $environment -eq 'Sandbox' -and $syncMode -eq 'Add' } @@ -392,12 +558,12 @@ InModuleScope Deploy { } It 'Leaves original BCH credentials out of native snapshot, upload and operation wait calls' { - PublishPTEApps -bcAuthContext @{ tenantId = 'tenant' } -environment Sandbox -appFiles @('App.app') + Install-AdminCenterPTEApps -environment Sandbox -appFiles @('App.app') Assert-MockCalled Get-AdminCenterInstalledExtensions -Exactly 1 -ParameterFilter { !$PesterBoundParameters.ContainsKey('bcAuthContext') } - Assert-MockCalled Install-AdminCenterPTE -Exactly 1 -ParameterFilter { + Assert-MockCalled Install-AdminCenterPTEApp -Exactly 1 -ParameterFilter { !$PesterBoundParameters.ContainsKey('bcAuthContext') } Assert-MockCalled WaitPTEOperation -Exactly 1 -ParameterFilter { @@ -412,13 +578,13 @@ InModuleScope Deploy { Mock Copy-AppFilesToFolder { return @($script:copiedApp) } Mock Sort-AppFilesByDependencies { return $appFiles } - Publish-AdminCenterPTEApps -environment Sandbox -appFiles @('Apps.zip') + Install-AdminCenterPTEApps -environment Sandbox -appFiles @('Apps.zip') Assert-MockCalled Sort-AppFilesByDependencies -Exactly 1 -ParameterFilter { $appFiles.Count -eq 1 -and $appFiles[0] -eq $script:copiedApp -and $excludeRuntimePackages } Assert-MockCalled Get-AppJsonFromAppFile -Exactly 1 -ParameterFilter { $appFile -eq $script:copiedApp } - Assert-MockCalled Install-AdminCenterPTE -Exactly 1 -ParameterFilter { $appFile -eq $script:copiedApp } + Assert-MockCalled Install-AdminCenterPTEApp -Exactly 1 -ParameterFilter { $appFile -eq $script:copiedApp } Assert-MockCalled WaitPTEOperation -Exactly 1 -ParameterFilter { $appId -eq 'app-1' -and $operation.id -eq 'operation-1' } @@ -426,7 +592,7 @@ InModuleScope Deploy { } It 'Leaves native target selection to the request boundary' { - Mock Install-AdminCenterPTE { + Mock Install-AdminCenterPTEApp { $PesterBoundParameters.Keys | Should -Not -Contain 'apiBaseUrl' $PesterBoundParameters.Keys | Should -Not -Contain 'applicationFamily' return @{ id = 'operation-1'; appId = 'app-1'; status = 'running' } @@ -434,9 +600,9 @@ InModuleScope Deploy { Mock WaitPTEOperation { $PesterBoundParameters.Keys | Should -Not -Contain 'deploymentTarget' } - PublishPTEApps -bcAuthContext @{} -environment 'QA / East' -appFiles @('App.app') -schemaSyncMode Force + Install-AdminCenterPTEApps -environment 'QA / East' -appFiles @('App.app') -schemaSyncMode Force - Assert-MockCalled Install-AdminCenterPTE -Exactly 1 -ParameterFilter { + Assert-MockCalled Install-AdminCenterPTEApp -Exactly 1 -ParameterFilter { $environment -eq 'QA / East' -and $syncMode -eq 'ForceSync' } @@ -448,9 +614,9 @@ InModuleScope Deploy { It 'Does not mistake the package version for the target BC version' { Mock Get-AppJsonFromAppFile { return @{ id = 'app-1'; name = 'App'; version = '28.0.0.0' } } - PublishPTEApps -bcAuthContext @{} -environment 'Sandbox' -appFiles @('App.app') + Install-AdminCenterPTEApps -environment 'Sandbox' -appFiles @('App.app') - Assert-MockCalled Install-AdminCenterPTE -Exactly 1 + Assert-MockCalled Install-AdminCenterPTEApp -Exactly 1 Assert-MockCalled Publish-PerTenantExtensionApps -Times 0 } @@ -463,9 +629,9 @@ InModuleScope Deploy { versionMajor = $version; versionMinor = 0; versionBuild = 0; versionRevision = 0 } - PublishPTEApps -bcAuthContext @{} -environment 'Sandbox' -appFiles @('App.app') + Install-AdminCenterPTEApps -environment 'Sandbox' -appFiles @('App.app') - Assert-MockCalled Install-AdminCenterPTE -Times 0 + Assert-MockCalled Install-AdminCenterPTEApp -Times 0 Assert-MockCalled WaitPTEOperation -Times 0 Assert-MockCalled Publish-PerTenantExtensionApps -Times 0 Assert-MockCalled OutputWarning -Times 0 @@ -478,9 +644,9 @@ InModuleScope Deploy { @{ id = 'app-1'; displayName = 'App'; isInstalled = $false; versionMajor = 3; versionMinor = 0; versionBuild = 0; versionRevision = 0 } ) - PublishPTEApps -bcAuthContext @{} -environment 'Sandbox' -appFiles @('App.app') + Install-AdminCenterPTEApps -environment 'Sandbox' -appFiles @('App.app') - Assert-MockCalled Install-AdminCenterPTE -Exactly 1 + Assert-MockCalled Install-AdminCenterPTEApp -Exactly 1 Assert-MockCalled WaitPTEOperation -Exactly 1 } @@ -493,7 +659,7 @@ InModuleScope Deploy { return @{ id = $appFile; name = $appFile; version = '2.0.0.0' } } $script:events = @() - Mock Install-AdminCenterPTE { + Mock Install-AdminCenterPTEApp { param($appFile) $script:events += "upload:$appFile" return @{ id = "operation-$appFile"; appId = $appFile; status = 'running' } @@ -503,11 +669,11 @@ InModuleScope Deploy { $script:events += "complete:$appId" } - PublishPTEApps -bcAuthContext @{} -environment 'Sandbox' -appFiles @('Apps.zip') + Install-AdminCenterPTEApps -environment 'Sandbox' -appFiles @('Apps.zip') ($script:events -join ',') | Should -Be 'read:Dependency.app,upload:Dependency.app,complete:Dependency.app,read:Dependent.app,upload:Dependent.app,complete:Dependent.app' Assert-MockCalled Sort-AppFilesByDependencies -Exactly 1 -ParameterFilter { $excludeRuntimePackages -and $appFiles.Count -eq 3 } - Assert-MockCalled Install-AdminCenterPTE -Times 0 -ParameterFilter { $appFile -eq 'Runtime.app' } + Assert-MockCalled Install-AdminCenterPTEApp -Times 0 -ParameterFilter { $appFile -eq 'Runtime.app' } } It 'Does not fall back or continue after an ambiguous failure' -TestCases @( @@ -515,15 +681,15 @@ InModuleScope Deploy { ) { param($step) switch ($step) { - upload { Mock Install-AdminCenterPTE { throw "Package upload failed" } } + upload { Mock Install-AdminCenterPTEApp { throw "Package upload failed" } } polling { Mock WaitPTEOperation { throw "Installation failed" } } - authorization { Mock Install-AdminCenterPTE { throw "403 Forbidden" } } + authorization { Mock Install-AdminCenterPTEApp { throw "403 Forbidden" } } } - { PublishPTEApps -bcAuthContext @{} -environment 'Sandbox' -appFiles @('App.app') } | Should -Throw + { Install-AdminCenterPTEApps -environment 'Sandbox' -appFiles @('App.app') } | Should -Throw Assert-MockCalled Publish-PerTenantExtensionApps -Times 0 - Assert-MockCalled Install-AdminCenterPTE -Exactly 1 + Assert-MockCalled Install-AdminCenterPTEApp -Exactly 1 Assert-MockCalled Remove-Item -Exactly 1 } @@ -533,88 +699,47 @@ InModuleScope Deploy { ) { param($statusCode) $script:uploadStatus = $statusCode - Mock Install-AdminCenterPTE { + Mock Install-AdminCenterPTEApp { $exception = [System.Exception]::new('Upload rejected') $exception | Add-Member NoteProperty Response ([PSCustomObject]@{ StatusCode = $script:uploadStatus }) throw $exception } - { PublishPTEApps -bcAuthContext @{} -environment Sandbox -appFiles @('App.app') } | + { Install-AdminCenterPTEApps -environment Sandbox -appFiles @('App.app') } | Should -Throw '*Upload rejected*' Assert-MockCalled Publish-PerTenantExtensionApps -Times 0 Assert-MockCalled OutputWarning -Times 0 } - It 'Leaves Automation package preparation and installed-version skipping entirely to BCH' { - $script:ptePublishingApi = 'Automation' - Mock Sort-AppFilesByDependencies { return @('Installed.app', 'First.app', 'Second.app') } - $script:extensions += @{ - id = 'Installed.app'; displayName = 'Installed'; isInstalled = $true - versionMajor = 3; versionMinor = 0; versionBuild = 0; versionRevision = 0 - } - Mock Get-AppJsonFromAppFile { - param($appFile) - return @{ id = $appFile; name = $appFile; version = '2.0.0.0' } - } - Mock Publish-PerTenantExtensionApps { - $bcContainerHelperConfig.apiBaseUrl | Should -Be 'https://api.example.test/' - } - PublishPTEApps -bcAuthContext @{} -environment Sandbox -appFiles @('Apps.zip', 'Installed.app') ` - -schemaSyncMode Force - - Assert-MockCalled Publish-PerTenantExtensionApps -Exactly 1 -ParameterFilter { - ($appFiles -join ',') -eq 'Apps.zip,Installed.app' -and $schemaSyncMode -eq 'Force' - } - Assert-MockCalled Copy-AppFilesToFolder -Times 0 - Assert-MockCalled Sort-AppFilesByDependencies -Times 0 - Assert-MockCalled Get-AppJsonFromAppFile -Times 0 - Assert-MockCalled Install-AdminCenterPTE -Times 0 - Assert-MockCalled Get-AdminCenterInstalledExtensions -Times 0 - Assert-MockCalled Get-BcInstalledExtensions -Times 0 - } - - It 'Propagates Automation batch failures without changing route or preparing packages' { - $script:ptePublishingApi = 'Automation' - Mock Publish-PerTenantExtensionApps { throw 'Batch failed' } - { PublishPTEApps -bcAuthContext @{} -environment Sandbox -appFiles @('App.app') } | - Should -Throw '*Batch failed*' - $script:ptePublishingApi | Should -Be Automation - Assert-MockCalled Publish-PerTenantExtensionApps -Exactly 1 - Assert-MockCalled NewTemporaryFolder -Times 0 - Assert-MockCalled Remove-Item -Times 0 - Assert-MockCalled Get-AdminCenterInstalledExtensions -Times 0 - Assert-MockCalled Install-AdminCenterPTE -Times 0 - } - It 'Preserves distinct versions from the dependency sorter without synthetic installed entries' { Mock Sort-AppFilesByDependencies { return @('Newer.app', 'Older.app') } Mock Get-AppJsonFromAppFile { param($appFile) return @{ id = 'app-1'; name = 'App'; version = $(if ($appFile -eq 'Newer.app') { '3.0.0.0' } else { '2.0.0.0' }) } } - PublishPTEApps -bcAuthContext @{} -environment Sandbox -appFiles @('Apps.zip') + Install-AdminCenterPTEApps -environment Sandbox -appFiles @('Apps.zip') - Assert-MockCalled Install-AdminCenterPTE -Exactly 2 + Assert-MockCalled Install-AdminCenterPTEApp -Exactly 2 $script:extensions.Count | Should -Be 1 } It 'Does not fall back for a local file preparation failure reported before sending' { - Mock Install-AdminCenterPTE { + Mock Install-AdminCenterPTEApp { $exception = [IO.FileNotFoundException]::new('Package missing') $exception.Data['AdminCenterRequestStarted'] = $false throw $exception } - { PublishPTEApps -bcAuthContext @{} -environment Sandbox -appFiles @('App.app') } | Should -Throw '*Package missing*' + { Install-AdminCenterPTEApps -environment Sandbox -appFiles @('App.app') } | Should -Throw '*Package missing*' Assert-MockCalled Publish-PerTenantExtensionApps -Times 0 } It 'Does not mistake a TLS authentication exception for a deployment authorization rejection' { - Mock Install-AdminCenterPTE { + Mock Install-AdminCenterPTEApp { throw [System.Security.Authentication.AuthenticationException]::new('TLS handshake failed') } - { PublishPTEApps -bcAuthContext @{} -environment Sandbox -appFiles @('App.app') } | + { Install-AdminCenterPTEApps -environment Sandbox -appFiles @('App.app') } | Should -Throw '*TLS handshake failed*' Assert-MockCalled Publish-PerTenantExtensionApps -Times 0 @@ -632,10 +757,10 @@ InModuleScope Deploy { throw $exception } - { PublishPTEApps -bcAuthContext @{} -environment Sandbox -appFiles @('App.app') } | Should -Throw '*accepted operation*' + { Install-AdminCenterPTEApps -environment Sandbox -appFiles @('App.app') } | Should -Throw '*accepted operation*' Assert-MockCalled Publish-PerTenantExtensionApps -Times 0 - Assert-MockCalled Install-AdminCenterPTE -Exactly 1 + Assert-MockCalled Install-AdminCenterPTEApp -Exactly 1 } It 'Stops without fallback after a terminal operation failure' { @@ -643,7 +768,7 @@ InModuleScope Deploy { throw 'Operation failed: rejected package' } - { PublishPTEApps -bcAuthContext @{} -environment Sandbox -appFiles @('App.app') } | + { Install-AdminCenterPTEApps -environment Sandbox -appFiles @('App.app') } | Should -Throw '*Operation failed: rejected package*' Assert-MockCalled Publish-PerTenantExtensionApps -Times 0 @@ -662,11 +787,11 @@ InModuleScope Deploy { } } - { PublishPTEApps -bcAuthContext @{} -environment Sandbox -appFiles @('Apps.zip') } | + { Install-AdminCenterPTEApps -environment Sandbox -appFiles @('Apps.zip') } | Should -Throw '*operation-2*Second.app*running*' - Assert-MockCalled Install-AdminCenterPTE -Exactly 2 - Assert-MockCalled Install-AdminCenterPTE -Times 0 -ParameterFilter { $appFile -eq 'Third.app' } + Assert-MockCalled Install-AdminCenterPTEApp -Exactly 2 + Assert-MockCalled Install-AdminCenterPTEApp -Times 0 -ParameterFilter { $appFile -eq 'Third.app' } Assert-MockCalled Publish-PerTenantExtensionApps -Times 0 Assert-MockCalled OutputWarning -Times 0 } @@ -680,18 +805,15 @@ InModuleScope Deploy { } $script:rawApp = @{ id = 'app-1'; name = 'App'; version = '1.0.0.0'; state = 'installed'; appType = 'tenant' } # Bind the production normalizer to the same module as the API and consumer mocks. - $script:nativeReader = [scriptblock]::Create((Get-Command Get-AdminCenterInstalledExtensions -Module AdminCenterApi).Definition) $script:installedAppResponse = @($script:rawApplication, $script:rawApp) Mock Invoke-AdminCenterApi { return @{ value = $script:installedAppResponse } } - Mock Get-AdminCenterInstalledExtensions { - & $script:nativeReader -environment $environment - } + Mock Get-AdminCenterInstalledExtensions { & $script:nativeReader -environment $environment } Mock NewTemporaryFolder { return 'test-app-folder' } Mock Copy-AppFilesToFolder { return @('App.app') } Mock Get-ChildItem { return [PSCustomObject]@{ FullName = 'App.app' } } Mock Sort-AppFilesByDependencies { return @('App.app') } Mock Get-AppJsonFromAppFile { return @{ id = 'app-1'; name = 'App'; version = '2.0.0.0'; idRanges = @(@{ from = 50000 }) } } - Mock Install-AdminCenterPTE { return @{ id = 'operation-1'; appId = 'app-1'; status = 'running' } } + Mock Install-AdminCenterPTEApp { return @{ id = 'operation-1'; appId = 'app-1'; status = 'running' } } Mock Install-BcAppFromAppSource { } Mock WaitPTEOperation { } Mock Remove-Item { } @@ -700,11 +822,9 @@ InModuleScope Deploy { It 'Does not require unrelated apps to have names, scopes or usable versions' { $script:installedAppResponse = @($script:rawApplication, @{ id = 'unrelated-app'; version = 'invalid' }) - Initialize-PTEPublishingApi -bcAuthContext @{} -environment Sandbox - PublishPTEApps -bcAuthContext @{} -environment Sandbox -appFiles @('App.app') + Install-AdminCenterPTEApps -environment Sandbox -appFiles @('App.app') - $script:ptePublishingApi | Should -Be AdminCenter - Assert-MockCalled Install-AdminCenterPTE -Exactly 1 + Assert-MockCalled Install-AdminCenterPTEApp -Exactly 1 Assert-MockCalled WaitPTEOperation -Exactly 1 Assert-MockCalled Publish-PerTenantExtensionApps -Times 0 Assert-MockCalled OutputWarning -Times 0 @@ -716,76 +836,13 @@ InModuleScope Deploy { param($version) $script:rawApp.version = $version - { PublishPTEApps -bcAuthContext @{} -environment Sandbox -appFiles @('App.app') } | Should -Throw + { Install-AdminCenterPTEApps -environment Sandbox -appFiles @('App.app') } | Should -Throw - Assert-MockCalled Install-AdminCenterPTE -Times 0 + Assert-MockCalled Install-AdminCenterPTEApp -Times 0 Assert-MockCalled Publish-PerTenantExtensionApps -Times 0 Assert-MockCalled Remove-Item -Exactly 1 } - It 'Resolves Application by its known identity when its name is absent' { - $script:rawApplication.Remove('name') - - Initialize-PTEPublishingApi -bcAuthContext @{} -environment Sandbox - - $script:ptePublishingApi | Should -Be AdminCenter - Assert-MockCalled Get-BcInstalledExtensions -Times 0 - } - - It 'Rejects Application version even when its name is absent' -TestCases @( - @{ version = '30.0' }, @{ version = 'invalid' } - ) { - param($version) - $script:rawApplication.Remove('name') - $script:rawApplication.version = $version - $script:ptePublishingApi = '' - - { Initialize-PTEPublishingApi -bcAuthContext @{} -environment Sandbox } | - Should -Throw '*unique installed Application*' - - $script:ptePublishingApi | Should -Be '' - Assert-MockCalled Get-BcInstalledExtensions -Times 0 - Assert-MockCalled Install-AdminCenterPTE -Times 0 - } - - It 'Rejects an invalid selected installed version during primary preflight' { - $script:rawApp.version = 'invalid' - - { CheckInstalledApps -bcAuthContext @{} -environment Sandbox -appFiles @('App.app') } | Should -Throw - - Assert-MockCalled Install-AdminCenterPTE -Times 0 - } - - It 'Rejects an invalid installed version before writing a matched dependency' -TestCases @( - @{ kind = 'PTE'; from = 50000 }, @{ kind = 'AppSource'; from = 100000 } - ) { - param($from) - $script:rawApp.version = 'invalid' - $script:dependencyFrom = $from - Mock Get-AppJsonFromAppFile { - return @{ id = 'app-1'; name = 'App'; version = '2.0.0.0'; idRanges = @(@{ from = $script:dependencyFrom }) } - } - - { InstallOrUpgradeApps -bcAuthContext @{} -environment Sandbox -apps @('App.app') -installMode upgrade } | Should -Throw - - Assert-MockCalled Install-BcAppFromAppSource -Times 0 - Assert-MockCalled Install-AdminCenterPTE -Times 0 - Assert-MockCalled Publish-PerTenantExtensionApps -Times 0 - } - - It 'Keeps the Dev-scope AppSource dependency safeguard after normalization' { - $script:rawApp.appType = 'dev' - Mock Get-AppJsonFromAppFile { - return @{ id = 'app-1'; name = 'App'; version = '2.0.0.0'; idRanges = @(@{ from = 100000 }) } - } - - InstallOrUpgradeApps -bcAuthContext @{} -environment Sandbox -apps @('App.app') -installMode upgrade - - Assert-MockCalled OutputWarning -Exactly 1 -ParameterFilter { $message -like '*published in Dev scope*Cannot upgrade*' } - Assert-MockCalled Install-BcAppFromAppSource -Times 0 - Assert-MockCalled Install-AdminCenterPTE -Times 0 - Assert-MockCalled Publish-PerTenantExtensionApps -Times 0 - } } Context "Exact operation polling" { From b730909fd352f547c77dc570bbfafb7995e612d8 Mon Sep 17 00:00:00 2001 From: spetersenms Date: Mon, 16 Nov 2026 20:15:27 +0100 Subject: [PATCH 10/12] Fixing ps5 bug --- Actions/.Modules/AdminCenterApi.psm1 | 14 +++--- Actions/Deploy/Deploy.psm1 | 3 +- Tests/AdminCenterApi.Test.ps1 | 15 ++++-- Tests/PublishPTEApps.Test.ps1 | 71 ++++++++++++++++++++++++++-- 4 files changed, 86 insertions(+), 17 deletions(-) diff --git a/Actions/.Modules/AdminCenterApi.psm1 b/Actions/.Modules/AdminCenterApi.psm1 index f34de5d951..df2de89e71 100644 --- a/Actions/.Modules/AdminCenterApi.psm1 +++ b/Actions/.Modules/AdminCenterApi.psm1 @@ -138,9 +138,7 @@ function Invoke-AdminCenterApi { $uri += '/' + (($path | ForEach-Object { [Uri]::EscapeDataString($_) }) -join '/') $authContext = Renew-BcAuthContext -bcAuthContext $script:adminCenterAuthContext if (!$authContext -or !$authContext['AccessToken']) { - throw [System.Management.Automation.ErrorRecord]::new( - [System.Security.Authentication.AuthenticationException]::new('Authentication failed before Admin Center request.'), - 'AdminCenterAuthenticationFailed', 'AuthenticationError', $null) + throw 'Admin Center token renewal returned no access token before sending the request.' } $script:adminCenterAuthContext = $authContext Write-Host "::add-mask::$($authContext.AccessToken)" @@ -327,10 +325,12 @@ function GetPTEApplicationVersion { [string] $environment ) - $applications = @($extensions | Where-Object { - $app = $_ | ConvertTo-HashTable -recurse - ($app['displayName'] -eq 'Application' -or $app['id'] -eq $applicationAppId) -and $app['isInstalled'] - }) + $installedApps = @($extensions | ForEach-Object { $_ | ConvertTo-HashTable -recurse } | + Where-Object { $_['isInstalled'] }) + $applications = @($installedApps | Where-Object { $_['id'] -eq $applicationAppId }) + if (!$applications.Count) { + $applications = @($installedApps | Where-Object { $_['displayName'] -eq 'Application' }) + } $version = $null if ($applications.Count -eq 1) { $application = $applications[0] | ConvertTo-HashTable -recurse diff --git a/Actions/Deploy/Deploy.psm1 b/Actions/Deploy/Deploy.psm1 index 8eb2395441..9b65f4680c 100644 --- a/Actions/Deploy/Deploy.psm1 +++ b/Actions/Deploy/Deploy.psm1 @@ -10,8 +10,7 @@ function Test-AdminCenterAuthorizationError { if ($errorRecord.Exception.PSObject.Properties['Response'] -and $errorRecord.Exception.Response) { $statusCode = [int]$errorRecord.Exception.Response.StatusCode } - return $statusCode -in 401,403 -or - ($errorRecord.FullyQualifiedErrorId -split ',')[0] -eq 'AdminCenterAuthenticationFailed' + return $statusCode -in 401,403 } <# diff --git a/Tests/AdminCenterApi.Test.ps1 b/Tests/AdminCenterApi.Test.ps1 index c5a36e43fe..f1314345f2 100644 --- a/Tests/AdminCenterApi.Test.ps1 +++ b/Tests/AdminCenterApi.Test.ps1 @@ -390,16 +390,23 @@ Describe 'AL-Go Admin Center API helpers' { Assert-MockCalled Invoke-RestMethod -Times 0 } - It 'Rejects authentication without a token before sending' { - Mock Renew-BcAuthContext { return @{} } + It 'Rejects renewal result without a token before sending' -TestCases @( + @{ result = 'null' }, @{ result = 'empty context' } + ) { + param($result) + $script:renewalResult = $result + Mock Renew-BcAuthContext { + if ($script:renewalResult -eq 'null') { return $null } + return @{} + } try { Get-AdminCenterAppOperation -environment Sandbox -appId app -operationId operation throw 'Expected failure' } catch { - $_.Exception.Message | Should -BeLike '*Authentication failed*' - ($_.FullyQualifiedErrorId -split ',')[0] | Should -Be 'AdminCenterAuthenticationFailed' + $_.Exception.Message | Should -BeLike '*token renewal returned no access token*' + $_.Exception | Should -Not -BeOfType ([System.Security.Authentication.AuthenticationException]) $_.Exception.Data['AdminCenterRequestStarted'] | Should -BeFalse } Assert-MockCalled Invoke-RestMethod -Times 0 diff --git a/Tests/PublishPTEApps.Test.ps1 b/Tests/PublishPTEApps.Test.ps1 index 27b082159f..95fa65c0c7 100644 --- a/Tests/PublishPTEApps.Test.ps1 +++ b/Tests/PublishPTEApps.Test.ps1 @@ -102,16 +102,32 @@ InModuleScope Deploy { Assert-MockCalled OutputWarning -Times 0 } - It 'Selects Automation for the helper-owned missing-token error' { + It 'Does not classify an unexplained missing token as authorization rejection' { Mock Get-AdminCenterInstalledExtensions { throw [System.Management.Automation.ErrorRecord]::new( [System.Security.Authentication.AuthenticationException]::new('Token missing'), 'AdminCenterAuthenticationFailed', 'AuthenticationError', $null) } - Initialize-PTEPublishingApi -bcAuthContext @{} -environment Sandbox - $script:ptePublishingApi | Should -Be Automation - Assert-MockCalled OutputWarning -Exactly 1 + { Initialize-PTEPublishingApi -bcAuthContext @{} -environment Sandbox } | + Should -Throw '*Token missing*' + $script:ptePublishingApi | Should -Be '' + Assert-MockCalled Get-BcInstalledExtensions -Times 0 + Assert-MockCalled OutputWarning -Times 0 + } + + It 'Stops the initial probe when BCH renewal returns no token' { + Mock Get-AdminCenterInstalledExtensions { + throw 'Admin Center token renewal returned no access token before sending the request.' + } + + { Initialize-PTEPublishingApi -bcAuthContext @{} -environment Sandbox } | + Should -Throw '*token renewal returned no access token*' + + $script:ptePublishingApi | Should -Be '' + Assert-MockCalled Get-BcInstalledExtensions -Times 0 + Assert-MockCalled OutputWarning -Times 0 + Assert-MockCalled Invoke-RestMethod -Times 0 } It 'Does not mistake a probe for an authorization setup failure' -TestCases @( @@ -514,6 +530,53 @@ InModuleScope AdminCenterApi { Mock Install-AdminCenterPTEApp { return @{ id = 'operation-1'; appId = 'app-1'; status = 'running' } } Mock Get-AdminCenterAppOperation { throw 'Unexpected operation read' } } + Context 'Application version resolution' { + BeforeEach { + $script:application.id = $applicationAppId + } + + It 'Prefers the known Application ID over an unrelated app with the same name' { + $unrelated = $script:application.Clone() + $unrelated.id = 'unrelated-app' + $unrelated.versionMajor = 28 + + GetPTEApplicationVersion -extensions @($unrelated, $script:application) -environment Sandbox | + Should -Be ([version]'30.0.0.0') + } + + It 'Retains name-only compatibility when the known Application ID is absent' { + $script:application.id = 'legacy-id' + + GetPTEApplicationVersion -extensions @($script:application) -environment Sandbox | + Should -Be ([version]'30.0.0.0') + } + + It 'Rejects duplicate known Application IDs despite an unambiguous name-only record' { + $named = $script:application.Clone() + $named.id = 'other-id' + + { GetPTEApplicationVersion -extensions @($script:application, $script:application.Clone(), $named) -environment Sandbox } | + Should -Throw '*unique installed Application*' + } + + It 'Rejects authoritative version instead of using a valid name-only record' -TestCases @( + @{ version = 'invalid' }, @{ version = 'incomplete' } + ) { + param($version) + $named = $script:application.Clone() + $named.id = 'other-id' + if ($version -eq 'invalid') { + $script:application.versionMajor = 'invalid' + } + else { + $script:application.Remove('versionRevision') + } + + { GetPTEApplicationVersion -extensions @($script:application, $named) -environment Sandbox } | + Should -Throw '*unique installed Application*' + } + } + Context 'Native batch preparation and installation' { BeforeEach { Mock NewTemporaryFolder { return 'test-app-folder' } From 205ed892a98db366927bd60fe1ce6ef7378b3b19 Mon Sep 17 00:00:00 2001 From: spetersenms Date: Tue, 17 Nov 2026 09:44:17 +0100 Subject: [PATCH 11/12] More logging --- Actions/.Modules/AdminCenterApi.psm1 | 3 +++ Actions/Deploy/README.md | 1 + Tests/PublishPTEApps.Test.ps1 | 13 +++++++++++-- 3 files changed, 15 insertions(+), 2 deletions(-) diff --git a/Actions/.Modules/AdminCenterApi.psm1 b/Actions/.Modules/AdminCenterApi.psm1 index df2de89e71..a02f371645 100644 --- a/Actions/.Modules/AdminCenterApi.psm1 +++ b/Actions/.Modules/AdminCenterApi.psm1 @@ -476,10 +476,13 @@ function Install-AdminCenterPTEApps { $installedVersions = @($matchingApps | Where-Object { $_.isInstalled } | ForEach-Object { [version]::new("$($_.versionMajor).$($_.versionMinor).$($_.versionBuild).$($_.versionRevision)") }) if (@($installedVersions | Where-Object { $_ -ge $appVersion }).Count -gt 0) { + Write-Host "Skipping $($appJson.name) v${appVersion}: version $($installedVersions | Sort-Object -Descending | Select-Object -First 1) is already installed." continue } + Write-Host "Publishing and installing $($appJson.name) v$appVersion" $operation = Install-AdminCenterPTEApp -environment $environment -appFile $appFile -syncMode $syncMode WaitPTEOperation -environment $environment -operation $operation -appId $appJson.id + Write-Host "Successfully installed $($appJson.name) v$appVersion" } } finally { diff --git a/Actions/Deploy/README.md b/Actions/Deploy/README.md index fab350da88..eeaf09ae6e 100644 --- a/Actions/Deploy/README.md +++ b/Actions/Deploy/README.md @@ -5,6 +5,7 @@ Deploy Apps to online environment ## PTE publishing Deploys PTEs in dependency order, skipping app versions already installed or superseded. +Native publishing logs each app's name and version when installation starts and succeeds, or the installed version when it skips the app. On BC 29+, PTE deployment checks administration center access first and selects Automation only for authentication or authorization failures. The selected API is used throughout the action. Configure the [required authorization](../../Workshop/ContinuousDeployment.md#pte-deployment-authorization). Primary-app Dev publishing is unchanged. diff --git a/Tests/PublishPTEApps.Test.ps1 b/Tests/PublishPTEApps.Test.ps1 index 95fa65c0c7..b18674aab7 100644 --- a/Tests/PublishPTEApps.Test.ps1 +++ b/Tests/PublishPTEApps.Test.ps1 @@ -698,7 +698,10 @@ InModuleScope AdminCenterApi { Assert-MockCalled WaitPTEOperation -Times 0 Assert-MockCalled Publish-PerTenantExtensionApps -Times 0 Assert-MockCalled OutputWarning -Times 0 - Assert-MockCalled Write-Host -Times 0 -ParameterFilter { $Object -like '*already installed*' } + Assert-MockCalled Write-Host -Exactly 1 -ParameterFilter { + $Object -eq "Skipping App v2.0.0.0: version $version.0.0.0 is already installed." + } + Assert-MockCalled Write-Host -Times 0 -ParameterFilter { $Object -like 'Successfully installed*' } } It 'Upgrades an older installed app even if an uninstalled newer package is present' { @@ -731,10 +734,14 @@ InModuleScope AdminCenterApi { param($appId) $script:events += "complete:$appId" } + Mock Write-Host { + param($Object) + $script:events += "log:$Object" + } Install-AdminCenterPTEApps -environment 'Sandbox' -appFiles @('Apps.zip') - ($script:events -join ',') | Should -Be 'read:Dependency.app,upload:Dependency.app,complete:Dependency.app,read:Dependent.app,upload:Dependent.app,complete:Dependent.app' + ($script:events -join ',') | Should -Be 'read:Dependency.app,log:Publishing and installing Dependency.app v2.0.0.0,upload:Dependency.app,complete:Dependency.app,log:Successfully installed Dependency.app v2.0.0.0,read:Dependent.app,log:Publishing and installing Dependent.app v2.0.0.0,upload:Dependent.app,complete:Dependent.app,log:Successfully installed Dependent.app v2.0.0.0' Assert-MockCalled Sort-AppFilesByDependencies -Exactly 1 -ParameterFilter { $excludeRuntimePackages -and $appFiles.Count -eq 3 } Assert-MockCalled Install-AdminCenterPTEApp -Times 0 -ParameterFilter { $appFile -eq 'Runtime.app' } } @@ -754,6 +761,8 @@ InModuleScope AdminCenterApi { Assert-MockCalled Publish-PerTenantExtensionApps -Times 0 Assert-MockCalled Install-AdminCenterPTEApp -Exactly 1 Assert-MockCalled Remove-Item -Exactly 1 + Assert-MockCalled Write-Host -Exactly 1 -ParameterFilter { $Object -eq 'Publishing and installing App v2.0.0.0' } + Assert-MockCalled Write-Host -Times 0 -ParameterFilter { $Object -like 'Successfully installed*' } } It 'Never changes route after upload HTTP , including the first upload' -TestCases @( From 2bb5cebe016b3112e5a64e52887b6c90fc9d0380 Mon Sep 17 00:00:00 2001 From: spetersenms Date: Thu, 26 Nov 2026 17:42:07 +0100 Subject: [PATCH 12/12] Changes new setting to complex object and removes unneeded inline script test. --- Actions/.Modules/AdminCenterApi.psm1 | 21 ++++-- Actions/.Modules/ReadSettings.psm1 | 6 +- Actions/.Modules/settings.schema.json | 34 ++++++--- Actions/Deploy/README.md | 2 +- RELEASENOTES.md | 13 +++- Scenarios/settings.md | 5 +- Tests/AdminCenterApi.Test.ps1 | 53 ++++++++----- Tests/Deploy.Action.Test.ps1 | 105 ++++---------------------- Tests/ReadSettings.Test.ps1 | 54 +++++++++++-- Workshop/ContinuousDeployment.md | 10 ++- 10 files changed, 160 insertions(+), 143 deletions(-) diff --git a/Actions/.Modules/AdminCenterApi.psm1 b/Actions/.Modules/AdminCenterApi.psm1 index e0d685d61d..54b908848b 100644 --- a/Actions/.Modules/AdminCenterApi.psm1 +++ b/Actions/.Modules/AdminCenterApi.psm1 @@ -48,21 +48,28 @@ function Get-DeploymentTarget { [hashtable] $settings = @{} ) + $adminCenterApi = @{} + if ($settings.ContainsKey('adminCenterApi')) { + if ($settings['adminCenterApi'] -isnot [System.Collections.IDictionary]) { + throw 'adminCenterApi must be an object.' + } + $adminCenterApi = $settings['adminCenterApi'] + } $apiBaseUrl = 'https://api.businesscentral.dynamics.com' - if ($settings.ContainsKey('deploymentBaseUrl') -and $settings['deploymentBaseUrl'] -isnot [string]) { - throw 'deploymentBaseUrl must be a string.' + if ($adminCenterApi.Contains('baseUrl') -and $adminCenterApi['baseUrl'] -isnot [string]) { + throw 'adminCenterApi.baseUrl must be a string.' } - if ($settings['deploymentBaseUrl']) { $apiBaseUrl = [string]$settings['deploymentBaseUrl'] } + if ($adminCenterApi['baseUrl']) { $apiBaseUrl = [string]$adminCenterApi['baseUrl'] } $uri = $null if (![Uri]::TryCreate($apiBaseUrl, [UriKind]::Absolute, [ref]$uri) -or $uri.Scheme -ne 'https' -or $uri.UserInfo -or $uri.Query -or $uri.Fragment) { - throw 'deploymentBaseUrl must be an absolute HTTPS API root without credentials, query or fragment.' + throw 'adminCenterApi.baseUrl must be an absolute HTTPS API root without credentials, query or fragment.' } $applicationFamily = 'BusinessCentral' - if ($settings.ContainsKey('deploymentApplicationFamily')) { - $applicationFamily = $settings['deploymentApplicationFamily'] + if ($adminCenterApi.Contains('applicationFamily')) { + $applicationFamily = $adminCenterApi['applicationFamily'] if ($applicationFamily -isnot [string] -or [string]::IsNullOrWhiteSpace($applicationFamily)) { - throw 'deploymentApplicationFamily must be a nonempty string.' + throw 'adminCenterApi.applicationFamily must be a nonempty string.' } } return @{ apiBaseUrl = $apiBaseUrl.TrimEnd('/'); applicationFamily = $applicationFamily } diff --git a/Actions/.Modules/ReadSettings.psm1 b/Actions/.Modules/ReadSettings.psm1 index c61d846e25..736a219042 100644 --- a/Actions/.Modules/ReadSettings.psm1 +++ b/Actions/.Modules/ReadSettings.psm1 @@ -322,8 +322,10 @@ function GetDefaultSettings } "pullRequestTrigger" = "pull_request" "skipDraftPullRequests" = $false - "deploymentBaseUrl" = "" - "deploymentApplicationFamily" = "BusinessCentral" + "adminCenterApi" = [ordered]@{ + "baseUrl" = "https://api.businesscentral.dynamics.com" + "applicationFamily" = "BusinessCentral" + } "bcptThresholds" = [ordered]@{ "DurationWarning" = 10 "DurationError" = 25 diff --git a/Actions/.Modules/settings.schema.json b/Actions/.Modules/settings.schema.json index 1dc04be56c..068c763dbc 100644 --- a/Actions/.Modules/settings.schema.json +++ b/Actions/.Modules/settings.schema.json @@ -3,18 +3,28 @@ "description": "Schema for AL-Go settings", "type": "object", "properties": { - "deploymentBaseUrl": { - "type": "string", - "default": "", - "pattern": "^(|https://[^\\s?#]+)$", - "description": "Optional repository API root for native Admin Center reads, PTE publishing and polling in the standard Deploy action in both templates (CI/CD and Publish To Environment). Empty uses https://api.businesscentral.dynamics.com, independently of BcContainerHelper configuration. Sets the default resource for an isolated Admin authentication context; explicit AUTHCONTEXT scopes or resource are preserved. Does not change Automation, AppSource or web-client configuration. See https://aka.ms/ALGoSettings#deploymentBaseUrl" - }, - "deploymentApplicationFamily": { - "type": "string", - "minLength": 1, - "pattern": "\\S", - "default": "BusinessCentral", - "description": "Repository application family used by Admin Center installed-app reads, PTE publishing and operation polling in the standard Deploy action in both templates (CI/CD and Publish To Environment). Independent of deploymentBaseUrl; never inferred from its hostname. Automation URLs do not contain a family segment. See https://aka.ms/ALGoSettings#deploymentApplicationFamily" + "adminCenterApi": { + "type": "object", + "default": { + "baseUrl": "https://api.businesscentral.dynamics.com", + "applicationFamily": "BusinessCentral" + }, + "description": "Optional repository target for native Admin Center reads, PTE publishing and polling in the standard Deploy action in both templates (CI/CD and Publish To Environment). Independent of BcContainerHelper configuration. Does not change Automation, AppSource or web-client configuration. See https://aka.ms/ALGoSettings#adminCenterApi", + "properties": { + "baseUrl": { + "type": "string", + "default": "https://api.businesscentral.dynamics.com", + "pattern": "^(|https://[^\\s?#]+)$", + "description": "HTTPS API root without credentials, query or fragment. Defaults to https://api.businesscentral.dynamics.com; an explicit empty string also uses this endpoint. Sets the default resource for an isolated Admin authentication context; explicit AUTHCONTEXT scopes or resource are preserved." + }, + "applicationFamily": { + "type": "string", + "minLength": 1, + "pattern": "\\S", + "default": "BusinessCentral", + "description": "Application family used by Admin Center installed-app reads, PTE publishing and operation polling. Never inferred from baseUrl. Automation URLs do not contain a family segment." + } + } }, "type": { "type": "string", diff --git a/Actions/Deploy/README.md b/Actions/Deploy/README.md index cf2eb70875..de9bd2f2e9 100644 --- a/Actions/Deploy/README.md +++ b/Actions/Deploy/README.md @@ -13,7 +13,7 @@ If the Admin check fails for another reason, a read-only Automation version chec Optional `DeployTo.unpublishOldVersions` (default `false`) cleans older, uninstalled versions after Automation deployment on BC 25.4+. Administration center deployments use Business Central's background cleanup. See [cleanup details](../../Workshop/ContinuousDeployment.md#old-published-versions). -For custom Admin services, use repository settings `deploymentBaseUrl` and `deploymentApplicationFamily`; Automation keeps its BCH configuration. These settings are validated only for PTE work, including PTE dependencies, not pure Dev deployment. See [target configuration and authentication](../../Workshop/ContinuousDeployment.md#custom-deployment-targets). +For custom Admin services, use the repository setting `adminCenterApi` with `baseUrl` and `applicationFamily`; Automation keeps its BCH configuration. These settings are validated only for PTE work, including PTE dependencies, not pure Dev deployment. See [target configuration and authentication](../../Workshop/ContinuousDeployment.md#custom-deployment-targets). ## INPUT diff --git a/RELEASENOTES.md b/RELEASENOTES.md index abfe2adf9c..f33ca0c161 100644 --- a/RELEASENOTES.md +++ b/RELEASENOTES.md @@ -8,7 +8,18 @@ Targets below BC 29 continue through Automation after other Admin check failures The Automation API's PTE upload endpoint (`extensionUpload`) is deprecated and planned for removal in 2027 release wave 1; this does not mean all Automation APIs are deprecated. See the [official deprecation notice](https://learn.microsoft.com/en-us/dynamics365/business-central/dev-itpro/administration/resources/dynamics_extensionupload). -For custom Admin services, configure repository settings `deploymentBaseUrl` and `deploymentApplicationFamily`. Automation keeps its existing BCH settings independently. See [target setup and authorization](Workshop/ContinuousDeployment.md#custom-deployment-targets). +For custom Admin services, configure repository setting `adminCenterApi` with `baseUrl` and `applicationFamily`. Automation keeps its existing BCH settings independently. See [target setup and authorization](Workshop/ContinuousDeployment.md#custom-deployment-targets). + +The defaults below require no configuration for ordinary deployments. An explicit empty `baseUrl` also uses the standard endpoint. + +```json +{ + "adminCenterApi": { + "baseUrl": "https://api.businesscentral.dynamics.com", + "applicationFamily": "BusinessCentral" + } +} +``` The optional `DeployTo.unpublishOldVersions` setting (default `false`) removes older, uninstalled versions after successful Scope PTE deployment through Automation on BC 25.4+, including fallback. Administration center deployments use Business Central's background cleanup instead. See [old published versions](Workshop/ContinuousDeployment.md#old-published-versions) for details. diff --git a/Scenarios/settings.md b/Scenarios/settings.md index 59ce8be8dd..e41d352495 100644 --- a/Scenarios/settings.md +++ b/Scenarios/settings.md @@ -76,8 +76,7 @@ The repository settings are only read from the repository settings file (.github | githubRunner | Specifies which github runner will be used for the build/test jobs in workflows including a build job. This is the most time consuming task. By default this job uses the _Windows-latest_ github runner (unless overridden by the runs-on setting). This settings takes precedence over runs-on so that you can use different runners for the build job and the housekeeping jobs. See **runs-on** setting. | | githubRunnerShell | Specifies which shell is used for build jobs in workflows including a build job. The default is to use the same as defined in **shell**. If the shell setting isn't defined, **powershell** is the default, which results in using _PowerShell 5.1_. Use **pwsh** for _PowerShell 7_. | | environments | Array of logical environment names. You can specify environments in GitHub environments or in the repo settings file. If you specify environments in the settings file, you can create your AUTHCONTEXT secret using **\\_AUTHCONTEXT**. You can specify additional information about environments in a setting called **DeployTo\** | -| deploymentBaseUrl | Optional string, default `""` (uses `https://api.businesscentral.dynamics.com`). Repository-level HTTPS API root for native Admin Center reads, PTE publishing and polling in the standard Deploy action in CI/CD and Publish To Environment in both templates. Independent of BcContainerHelper settings; Automation, AppSource and web-client configuration are unchanged. No credentials, query or fragment are allowed. Sets the default resource for an isolated Admin authentication context; explicit AUTHCONTEXT scopes or resource are preserved and must authorize the target service. See [custom deployment targets](../Workshop/ContinuousDeployment.md#custom-deployment-targets). | -| deploymentApplicationFamily | Optional nonempty string, default `"BusinessCentral"`. Repository-level application family for Admin Center installed-app reads, PTE publishing and operation polling in the standard Deploy action in CI/CD and Publish To Environment in both templates. Set the service's exact family independently of `deploymentBaseUrl`; it is never inferred from the host. Automation URLs do not contain a family segment. These settings are not properties of `DeployTo`. | +| adminCenterApi | Optional repository-level object, default `{ "baseUrl": "https://api.businesscentral.dynamics.com", "applicationFamily": "BusinessCentral" }`. Honored by native Admin Center installed-app reads, PTE publishing and polling in the standard Deploy action in CI/CD and Publish To Environment in both templates. **baseUrl**: optional string, default `"https://api.businesscentral.dynamics.com"`; HTTPS API root without credentials, query or fragment. An explicit empty string also uses the standard endpoint. Sets the default resource for an isolated Admin authentication context; explicit AUTHCONTEXT scopes or resource are preserved and must authorize the target service. **applicationFamily**: optional nonempty string, default `"BusinessCentral"`; set the service's exact family independently of the URL, never inferred from its hostname. Partial objects merge with defaults. Independent of BcContainerHelper settings; Automation, AppSource and web-client configuration are unchanged. This is not a property of `DeployTo`. See [custom deployment targets](../Workshop/ContinuousDeployment.md#custom-deployment-targets). | | DeliverTo\ | Structure with additional properties for the deliveryTarget specified. Some properties are deliveryTarget specific. The structure can contain the following properties:
**Branches** = an array of branch patterns, which are allowed to deliver to this deliveryTarget. (Default main)
**ContinuousDelivery** = boolean enabling delivery after successful CI/CD builds. Set to false to disable delivery from CI/CD; deliveries explicitly invoked by other workflows are unaffected. Default true for non-AppSource targets; see [deliverToAppSource](#deliverToAppSource) for AppSource.
**CreateContainerIfNotExist** = *[Only for DeliverToStorage]* Create Blob Storage Container if it doesn't already exist. (Default false)
| | DeployTo\ | Structure with additional properties for the environment specified. `` refers to the GitHub environment name. The structure can contain the following properties:
**EnvironmentType** = specifies the type of environment. The environment type can be used to invoke a custom deployment. (Default SaaS)
**EnvironmentName** = specifies the "real" name of the environment if it differs from the GitHub environment.
**Branches** = an array of branch patterns, which are allowed to deploy to this environment. These branches can also be defined under the environment in GitHub settings and both settings are honored. If neither setting is defined, the default is the **main** branch only.
**Projects** = In multi-project repositories, this property can be a comma separated list of project patterns to deploy to this environment. (Default \*)
**DependencyInstallMode** = Determines how dependencies are deployed if `GenerateDependencyArtifact` is true. Default value is `install` to install dependencies if not already installed. Other values are `ignore` for ignoring dependencies and `upgrade` or `forceUpgrade` for upgrading dependencies.
**includeTestAppsInSandboxEnvironment** = deploys test apps and their dependencies if the environment type is sandbox (Default is `false`)
**excludeAppIds** = array of app ids to exclude from deployment. (Default is `[]`)
**Scope** = Determines the mechanism for deployment to the environment (Dev or PTE). If not specified, AL-Go for GitHub will always use the Dev Scope for AppSource Apps, but also for PTEs when deploying to sandbox environments when impersonation (refreshtoken) is used for authentication. On BC 29 or later, AL-Go checks administration center access before PTE publishing and selects Automation only for authentication or authorization failures. All PTEs in the action use the selected API; publishing failures stop deployment. See [deployment authorization](../Workshop/ContinuousDeployment.md#pte-deployment-authorization), including PTE dependencies of Scope Dev deployments.
**SyncMode** = ForceSync if deployment to this environment should happen with ForceSync, else Add. If deploying to the development endpoint you can also specify Development or Clean. (Default Add)
**unpublishOldVersions** = Optional boolean (`true` or `false`, default `false`), honored by the standard Deploy action in CI/CD and Publish To Environment for both templates after successful Scope PTE publishing. For Automation publishing on BC 25.4 or later, unpublishes only selected primary apps' uninstalled versions older than the currently installed version, including apps skipped because the same or a newer version is installed. With the administration center route, explicit cleanup is skipped; Business Central manages background cleanup, whose timing and retained versions are not guaranteed. This setting does not control background cleanup. Skipped cleanup and cleanup failures are warnings; does not apply to Scope Dev or custom deployments.
**BuildMode** = specifies which buildMode to use for the deployment. Default is to use the Default buildMode
**ContinuousDeployment** = true if this environment should be used for continuous deployment, else false. (Default: AL-Go will continuously deploy to sandbox environments or environments, which doesn't end in (PROD) or (FAT)
**runs-on** = specifies which runner to use when deploying to this environment. (Default is settings.runs-on)
**shell** = specifies which shell to use when deploying to this environment, pwsh or powershell. (Default is settings.shell)
**companyId** = Company Id from Business Central (for PowerPlatform connection)
**ppEnvironmentUrl** = Url of the PowerPlatform environment to deploy to
| | alDoc | Structure with properties for the aldoc reference document generation. The structure can contain the following properties:
**continuousDeployment** = Determines if reference documentation will be deployed continuously as part of CI/CD. You can run the **Deploy Reference Documentation** workflow to deploy manually or on a schedule. (Default false)
**deployToGitHubPages** = Determines whether or not the reference documentation site should be deployed to GitHub Pages for the repository. In order to deploy to GitHub Pages, GitHub Pages must be enabled and set to GitHub Actuibs. (Default true)
**maxReleases** = Maximum number of releases to include in the reference documentation. (Default 3)
**groupByProject** = Determines whether projects in multi-project repositories are used as folders in reference documentation
**includeProjects** = An array of projects to include in the reference documentation. (Default all)
**excludeProjects** = An array of projects to exclude in the reference documentation. (Default none)
**header** = Header for the documentation site. (Default: Documentation for...)
**footer** = Footer for the documentation site. (Default: Made with...)
**defaultIndexMD** = Markdown for the landing page of the documentation site. (Default: Reference documentation...)
**defaultReleaseMD** = Markdown for the landing page of the release sites. (Default: Release reference documentation...)
*Note that in header, footer, defaultIndexMD and defaultReleaseMD you can use the following placeholders: {REPOSITORY}, {VERSION}, {INDEXTEMPLATERELATIVEPATH}, {RELEASENOTES}* | @@ -581,7 +580,7 @@ Note that changes to AL-Go for GitHub or Run-AlPipeline functionality in the fut | Setting | Description | Default | | :-- | :-- | :-- | | baseUrl | The Base Url for the online Business Central Web Client. This should be changed when targetting embed apps. | [https://businesscentral.dynamics.com](https://businesscentral.dynamics.com) | -| apiBaseUrl | The API root used by BcContainerHelper, including Embed services. Independent of the native Admin Center [deploymentBaseUrl](#deploymentBaseUrl). The web-client/readiness URL remains `baseUrl`. | [https://api.businesscentral.dynamics.com](https://api.businesscentral.dynamics.com) | +| apiBaseUrl | The API root used by BcContainerHelper, including Embed services. Independent of the native [adminCenterApi.baseUrl](#adminCenterApi). The web-client/readiness URL remains `baseUrl`. | [https://api.businesscentral.dynamics.com](https://api.businesscentral.dynamics.com) | | PartnerTelemetryConnectionString | The Telemetry Connection String for partner telemetry for DevOps telemetry. | | | SendExtendedTelemetryToMicrosoft | Set this value to true if you agree to emit extended DevOps telemetry to Microsoft. | false | | ObjectIdForInternalUse | BcContainerHelper will use this Object ID for internal purposes. Change if the default Object ID is in use. | 88123 | diff --git a/Tests/AdminCenterApi.Test.ps1 b/Tests/AdminCenterApi.Test.ps1 index f1314345f2..5734ef7bde 100644 --- a/Tests/AdminCenterApi.Test.ps1 +++ b/Tests/AdminCenterApi.Test.ps1 @@ -92,7 +92,7 @@ Describe 'AL-Go Admin Center API helpers' { UtcExpiresOn = [DateTime]::UtcNow.AddHours(1) } $adminContext = $original.Clone() - Initialize-AdminCenterAuthContext -authContext $adminContext -settings @{ deploymentBaseUrl = 'https://admin.test' } + Initialize-AdminCenterAuthContext -authContext $adminContext -settings @{ adminCenterApi = @{ baseUrl = 'https://admin.test' } } Mock Renew-BcAuthContext { $bcAuthContext.Scopes | Should -Be 'https://admin.test/' $bcAuthContext.UtcExpiresOn | Should -Be ([DateTime]::MinValue) @@ -120,14 +120,14 @@ Describe 'AL-Go Admin Center API helpers' { Scopes = 'https://explicit-resource.test/.default' UtcExpiresOn = $expires } - Initialize-AdminCenterAuthContext -authContext $original.Clone() -settings @{ deploymentBaseUrl = 'https://admin.test' } -preserveScopes + Initialize-AdminCenterAuthContext -authContext $original.Clone() -settings @{ adminCenterApi = @{ baseUrl = 'https://admin.test' } } -preserveScopes Invoke-AdminCenterApi -environment Sandbox -path apps -apiBaseUrl 'https://admin.test' Assert-MockCalled Renew-BcAuthContext -Exactly 1 } It 'Does not mutate the BCH context when Admin renewal fails' { $original = @{ Scopes = 'https://legacy.test/' } - Initialize-AdminCenterAuthContext -authContext $original.Clone() -settings @{ deploymentBaseUrl = 'https://admin.test' } + Initialize-AdminCenterAuthContext -authContext $original.Clone() -settings @{ adminCenterApi = @{ baseUrl = 'https://admin.test' } } Mock Renew-BcAuthContext { $bcAuthContext.Scopes = 'changed-copy' throw [TimeoutException]::new('Renewal timed out') @@ -145,7 +145,7 @@ Describe 'AL-Go Admin Center API helpers' { $newContext = Get-Command New-BcAuthContext -Module BcContainerHelper $original = & $newContext -tenantID fake-tenant -clientID fake-client -clientSecret fake-secret ` -scopes 'https://legacy.test/' -silent - Initialize-AdminCenterAuthContext -authContext $original.Clone() -settings @{ deploymentBaseUrl = 'https://admin.test' } + Initialize-AdminCenterAuthContext -authContext $original.Clone() -settings @{ adminCenterApi = @{ baseUrl = 'https://admin.test' } } Mock Renew-BcAuthContext { $renew = Get-Command Renew-BcAuthContext -Module BcContainerHelper & $renew -bcAuthContext $bcAuthContext -silent @@ -177,9 +177,9 @@ Describe 'AL-Go Admin Center API helpers' { $originalToken = $original.AccessToken $originalExpiry = $original.UtcExpiresOn $originalConfig = $bcContainerHelperConfig.apiBaseUrl - $settings = @{ deploymentBaseUrl = 'https://admin.test'; deploymentApplicationFamily = 'Family / US' } + $settings = @{ adminCenterApi = @{ baseUrl = 'https://admin.test'; applicationFamily = 'Family / US' } } Initialize-AdminCenterAuthContext -authContext $original.Clone() -settings $settings - $settings.deploymentBaseUrl = 'https://changed-after-initialization.test' + $settings.adminCenterApi.baseUrl = 'https://changed-after-initialization.test' Mock Renew-BcAuthContext { $renew = Get-Command Renew-BcAuthContext -Module BcContainerHelper & $renew -bcAuthContext $bcAuthContext -silent @@ -237,7 +237,7 @@ Describe 'AL-Go Admin Center API helpers' { It 'Replaces the supplied Admin context and target together on initialization' { $first = @{ Scopes = 'https://first.test/'; AccessToken = 'first-token' } Initialize-AdminCenterAuthContext -authContext $first -settings @{ - deploymentBaseUrl = 'https://first-admin.test'; deploymentApplicationFamily = 'FirstFamily' + adminCenterApi = @{ baseUrl = 'https://first-admin.test'; applicationFamily = 'FirstFamily' } } Mock Renew-BcAuthContext { $bcAuthContext.AccessToken = 'mutated-before-failure' @@ -248,7 +248,7 @@ Describe 'AL-Go Admin Center API helpers' { Assert-MockCalled Invoke-RestMethod -Times 0 $second = @{ Scopes = 'https://second.test/'; AccessToken = 'second-token' } Initialize-AdminCenterAuthContext -authContext $second -settings @{ - deploymentBaseUrl = 'https://second.test'; deploymentApplicationFamily = 'SecondFamily' + adminCenterApi = @{ baseUrl = 'https://second.test'; applicationFamily = 'SecondFamily' } } [object]::ReferenceEquals($script:adminCenterAuthContext, $second) | Should -BeTrue Mock Renew-BcAuthContext { return $bcAuthContext } @@ -267,7 +267,7 @@ Describe 'AL-Go Admin Center API helpers' { It 'Honors explicit native endpoint overrides independently of action target defaults' { $original = @{ Scopes = 'https://action.test/'; AccessToken = 'action-token' } Initialize-AdminCenterAuthContext -authContext $original.Clone() -settings @{ - deploymentBaseUrl = 'https://action.test'; deploymentApplicationFamily = 'ActionFamily' + adminCenterApi = @{ baseUrl = 'https://action.test'; applicationFamily = 'ActionFamily' } } Mock Renew-BcAuthContext { return $bcAuthContext } Mock Invoke-RestMethod { return @{ value = @(); id = 'operation' } } @@ -483,8 +483,9 @@ Describe 'AL-Go Admin Center API helpers' { It 'Resolves API root without deriving the family from the hostname' -TestCases @( @{ source = 'standard default'; settings = @{}; helper = @{}; expected = 'https://api.businesscentral.dynamics.com' }, @{ source = 'default despite legacy override'; settings = @{}; helper = @{ apiBaseUrl = 'https://legacy.test/' }; expected = 'https://api.businesscentral.dynamics.com' }, - @{ source = 'explicit deployment setting'; settings = @{ deploymentBaseUrl = 'https://deploy.test/root/' }; helper = @{ apiBaseUrl = 'https://legacy.test' }; expected = 'https://deploy.test/root' }, - @{ source = 'empty setting despite legacy override'; settings = @{ deploymentBaseUrl = '' }; helper = @{ apiBaseUrl = 'https://legacy.test/' }; expected = 'https://api.businesscentral.dynamics.com' } + @{ source = 'explicit deployment setting'; settings = @{ adminCenterApi = @{ baseUrl = 'https://deploy.test/root/' } }; helper = @{ apiBaseUrl = 'https://legacy.test' }; expected = 'https://deploy.test/root' }, + @{ source = 'empty setting despite legacy override'; settings = @{ adminCenterApi = @{ baseUrl = '' } }; helper = @{ apiBaseUrl = 'https://legacy.test/' }; expected = 'https://api.businesscentral.dynamics.com' }, + @{ source = 'empty target'; settings = @{ adminCenterApi = @{} }; helper = @{}; expected = 'https://api.businesscentral.dynamics.com' } ) { param($settings, $helper, $expected) @@ -497,7 +498,7 @@ Describe 'AL-Go Admin Center API helpers' { } It 'Resolves family independently and does not retain settings between invocations' { - $settings = @{ deploymentBaseUrl = 'https://custom.test'; deploymentApplicationFamily = 'Family / One' } + $settings = @{ adminCenterApi = @{ baseUrl = 'https://custom.test'; applicationFamily = 'Family / One' } } $helper = @{ apiBaseUrl = 'https://legacy.test' } $first = Get-DeploymentTarget -settings $settings $second = Get-DeploymentTarget @@ -506,7 +507,7 @@ Describe 'AL-Go Admin Center API helpers' { $second.applicationFamily | Should -Be 'BusinessCentral' $second.apiBaseUrl | Should -Be 'https://api.businesscentral.dynamics.com' $helper.apiBaseUrl | Should -Be 'https://legacy.test' - $settings.deploymentBaseUrl | Should -Be 'https://custom.test' + $settings.adminCenterApi.baseUrl | Should -Be 'https://custom.test' } It 'Rejects invalid API root without including it in the error' -TestCases @( @@ -514,19 +515,33 @@ Describe 'AL-Go Admin Center API helpers' { @{ root = 'https://custom.test?private=value' }, @{ root = 'https://custom.test#fragment' } ) { param($root) - $invalidSettings = @{ deploymentBaseUrl = $root } + $invalidSettings = @{ adminCenterApi = @{ baseUrl = $root } } { Get-DeploymentTarget -settings $invalidSettings } | - Should -Throw 'deploymentBaseUrl must be an absolute HTTPS API root without credentials, query or fragment.' + Should -Throw 'adminCenterApi.baseUrl must be an absolute HTTPS API root without credentials, query or fragment.' } It 'Rejects an empty explicit application family' { - { Get-DeploymentTarget -settings @{ deploymentApplicationFamily = ' ' } } | - Should -Throw '*deploymentApplicationFamily must be a nonempty string*' + { Get-DeploymentTarget -settings @{ adminCenterApi = @{ applicationFamily = ' ' } } } | + Should -Throw '*adminCenterApi.applicationFamily must be a nonempty string*' } It 'Rejects non-string explicit settings rather than silently selecting the standard service' { - { Get-DeploymentTarget -settings @{ deploymentBaseUrl = $null } } | Should -Throw '*deploymentBaseUrl must be a string*' - { Get-DeploymentTarget -settings @{ deploymentApplicationFamily = @('One', 'Two') } } | Should -Throw '*deploymentApplicationFamily must be a nonempty string*' + { Get-DeploymentTarget -settings @{ adminCenterApi = @{ baseUrl = $null } } } | Should -Throw '*adminCenterApi.baseUrl must be a string*' + { Get-DeploymentTarget -settings @{ adminCenterApi = @{ applicationFamily = @('One', 'Two') } } } | Should -Throw '*adminCenterApi.applicationFamily must be a nonempty string*' + } + + It 'Rejects a non-object target ' -TestCases @( + @{ target = $null }, @{ target = 'https://admin.test' }, @{ target = @('One', 'Two') } + ) { + param($target) + $settings = @{ adminCenterApi = $target } + { Get-DeploymentTarget -settings $settings } | Should -Throw '*adminCenterApi must be an object*' + } + + It 'Accepts an ordered target with only an application family' { + $target = Get-DeploymentTarget -settings @{ adminCenterApi = [ordered]@{ applicationFamily = 'CustomFamily' } } + $target.apiBaseUrl | Should -Be 'https://api.businesscentral.dynamics.com' + $target.applicationFamily | Should -Be CustomFamily } } diff --git a/Tests/Deploy.Action.Test.ps1 b/Tests/Deploy.Action.Test.ps1 index 2a357fcbe0..24ce274935 100644 --- a/Tests/Deploy.Action.Test.ps1 +++ b/Tests/Deploy.Action.Test.ps1 @@ -24,78 +24,6 @@ Describe "Deploy Action Tests" { YamlTest -scriptRoot $scriptRoot -actionName $actionName -actionScript $actionScript -outputs $outputs } - It 'Shares custom target and retained native auth through the exact action imports in a fresh host' { - $repro = Join-Path $TestDrive 'ActionImports.ps1' - @' -param([string] $actionPath) -$ErrorActionPreference = 'Stop' -$env:GITHUB_WORKSPACE = Split-Path (Split-Path (Split-Path $actionPath)) -$tokens = $null -$errors = $null -$ast = [System.Management.Automation.Language.Parser]::ParseFile($actionPath, [ref]$tokens, [ref]$errors) -$prefix = ($ast.EndBlock.Statements | Select-Object -First 4 | ForEach-Object { $_.Extent.Text }) -join "`n" -$prefix = $prefix.Replace('$PSScriptRoot', "'$(Split-Path $actionPath)'") -$inspection = { - $expires = [DateTime]::UtcNow.AddHours(1) - $source = @{ Scopes = 'https://legacy.test/'; AccessToken = 'legacy-token'; UtcExpiresOn = $expires } - Initialize-AdminCenterAuthContext -authContext $source.Clone() -settings @{ - deploymentBaseUrl = 'https://native.test/root'; deploymentApplicationFamily = 'Custom Family' - } - $native = (Get-Command Initialize-AdminCenterAuthContext).Module - $deploy = Get-Module Deploy - $nested = & $deploy { (Get-Command Get-AdminCenterInstalledExtensions).Module } - if (![object]::ReferenceEquals($native, $nested)) { throw 'Action and Deploy must share the native module before any requests.' } - & $native { - $script:exchanges = 0 - $script:requests = @() - function script:Renew-BcAuthContext { - param($bcAuthContext) - if ($bcAuthContext.UtcExpiresOn -le [DateTime]::UtcNow) { - $script:exchanges++ - $bcAuthContext = $bcAuthContext.Clone() - $bcAuthContext.AccessToken = 'retained-native-token' - $bcAuthContext.UtcExpiresOn = [DateTime]::UtcNow.AddHours(1) - } - return $bcAuthContext - } - function script:Invoke-RestMethod { - param($Uri, $Method, $Headers, $UseBasicParsing, $TimeoutSec, $ErrorAction) - $script:requests += @{ uri = [string]$Uri; authorization = $Headers.Authorization } - return @{ value = @() } - } - function script:Write-Host { } - } - Get-AdminCenterInstalledExtensions -environment Sandbox | Out-Null - & $deploy { - param($context) - GetInstalledExtensions -bcAuthContext $context -environment Sandbox -publishingApi AdminCenter | Out-Null - } $source - $state = & $native { - @{ exchanges = $script:exchanges; requests = $script:requests; scopes = $script:adminCenterAuthContext.Scopes } - } - $state.sameInstance = [object]::ReferenceEquals($native, $nested) - $state.originalUnchanged = $source.Scopes -eq 'https://legacy.test/' -and - $source.AccessToken -eq 'legacy-token' -and $source.UtcExpiresOn -eq $expires - $state | ConvertTo-Json -Depth 10 -Compress -} -& ([scriptblock]::Create($prefix + "`n" + $inspection.ToString())) -'@ | Set-Content -Path $repro -Encoding UTF8 - - $hostPath = (Get-Process -Id $PID).Path - $output = & $hostPath -NoProfile -NonInteractive -ExecutionPolicy Bypass -File $repro -actionPath $scriptPath - $LASTEXITCODE | Should -Be 0 - $state = $output[-1] | ConvertFrom-Json | ConvertTo-HashTable -recurse - $state.sameInstance | Should -BeTrue - $state.originalUnchanged | Should -BeTrue - $state.exchanges | Should -Be 1 - $state.scopes | Should -Be 'https://native.test/root/' - $state.requests.Count | Should -Be 2 - foreach ($request in $state.requests) { - $request.uri | Should -Be 'https://native.test/root/admin/v2.29/applications/Custom%20Family/environments/Sandbox/apps' - $request.authorization | Should -Be 'Bearer retained-native-token' - } - } - Context "unpublishOldVersions wiring" { BeforeAll { Import-Module (Join-Path $scriptRoot "Deploy.psm1") -Force @@ -193,7 +121,7 @@ $inspection = { $authContext.AccessToken = 'native-token' } - InvokeDeploy -repositorySettings @{ deploymentBaseUrl = 'https://native.test' } ` + InvokeDeploy -repositorySettings @{ adminCenterApi = @{ baseUrl = 'https://native.test' } } ` -deploymentSettings @{ EnvironmentType = 'SaaS'; EnvironmentName = 'test'; Branches = @(); Projects = '*'; DependencyInstallMode = 'upgrade'; SyncMode = $null; Scope = $scope; continuousDeployment = $true; includeTestAppsInSandboxEnvironment = $false; excludeAppIds = @() } Assert-MockCalled New-BcAuthContext -Exactly 1 @@ -229,12 +157,12 @@ $inspection = { Mock OutputError { param($message) throw $message } try { - InvokeDeploy -repositorySettings @{ deploymentBaseUrl = 'http://invalid.test' } ` + InvokeDeploy -repositorySettings @{ adminCenterApi = @{ baseUrl = 'http://invalid.test' } } ` -deploymentSettings @{ EnvironmentType = 'SaaS'; EnvironmentName = 'test'; Branches = @(); Projects = '*'; DependencyInstallMode = 'upgrade'; SyncMode = $null; Scope = $scope; continuousDeployment = $true; includeTestAppsInSandboxEnvironment = $false; excludeAppIds = @() } throw 'Expected native configuration validation to fail' } catch { - $_.Exception.Message | Should -Match 'deploymentBaseUrl must be an absolute HTTPS API root' + $_.Exception.Message | Should -Match 'adminCenterApi.baseUrl must be an absolute HTTPS API root' $_.Exception.Message | Should -Not -Match 'Authentication failed' } Assert-MockCalled Initialize-PTEPublishingApi -Times 0 @@ -247,7 +175,7 @@ $inspection = { Mock Initialize-AdminCenterAuthContext { throw 'Unused native configuration must not be initialized' } Mock OutputError { param($message) throw $message } - InvokeDeploy -repositorySettings @{ deploymentBaseUrl = 'http://invalid.test'; deploymentApplicationFamily = '' } ` + InvokeDeploy -repositorySettings @{ adminCenterApi = @{ baseUrl = 'http://invalid.test'; applicationFamily = '' } } ` -deploymentSettings @{ EnvironmentType = 'SaaS'; EnvironmentName = 'test'; Branches = @(); Projects = '*'; DependencyInstallMode = 'ignore'; SyncMode = $null; Scope = 'Dev'; continuousDeployment = $true; includeTestAppsInSandboxEnvironment = $false; excludeAppIds = @() } Assert-MockCalled Initialize-AdminCenterAuthContext -Times 0 @@ -275,8 +203,7 @@ $inspection = { } InvokeDeploy -repositorySettings @{ - deploymentBaseUrl = 'https://deploy.test/root/' - deploymentApplicationFamily = 'Custom / Family' + adminCenterApi = @{ baseUrl = 'https://deploy.test/root/'; applicationFamily = 'Custom / Family' } apiBaseUrl = 'https://legacy.test' baseUrl = 'https://web.test' } -deploymentSettings @{ EnvironmentType = 'SaaS'; EnvironmentName = 'test'; Branches = @(); Projects = '*'; DependencyInstallMode = 'upgrade'; SyncMode = $null; Scope = 'PTE'; continuousDeployment = $true; includeTestAppsInSandboxEnvironment = $false; excludeAppIds = @(); unpublishOldVersions = $true } @@ -289,8 +216,8 @@ $inspection = { Assert-MockCalled UnpublishOldAppVersions -Exactly 1 Assert-MockCalled InstallUnknownDependencies -Exactly 1 Assert-MockCalled Initialize-AdminCenterAuthContext -Exactly 1 -ParameterFilter { - $settings.deploymentBaseUrl -eq 'https://deploy.test/root/' -and - $settings.deploymentApplicationFamily -eq 'Custom / Family' -and !$preserveScopes + $settings.adminCenterApi.baseUrl -eq 'https://deploy.test/root/' -and + $settings.adminCenterApi.applicationFamily -eq 'Custom / Family' -and !$preserveScopes } Assert-MockCalled Invoke-RestMethod -Exactly 1 -ParameterFilter { $Uri -like 'https://web.test/*' } $script:deploymentConfig.apiBaseUrl | Should -Be 'https://legacy.test' @@ -305,7 +232,7 @@ $inspection = { $deployment = @{ EnvironmentType = 'SaaS'; EnvironmentName = 'test'; Branches = @(); Projects = '*'; DependencyInstallMode = 'ignore'; SyncMode = $null; Scope = 'PTE'; continuousDeployment = $true; includeTestAppsInSandboxEnvironment = $false; excludeAppIds = @() } InvokeDeploy -deploymentSettings $deployment -repositorySettings @{ - deploymentBaseUrl = 'https://explicit.test'; deploymentApplicationFamily = 'CustomFamily' + adminCenterApi = @{ baseUrl = 'https://explicit.test'; applicationFamily = 'CustomFamily' } apiBaseUrl = 'https://legacy.test' } $script:deploymentConfig.apiBaseUrl | Should -Be 'https://legacy.test' @@ -315,11 +242,11 @@ $inspection = { Assert-MockCalled PublishPTEApps -Exactly 2 Assert-MockCalled Initialize-AdminCenterAuthContext -Exactly 1 -ParameterFilter { - $settings['deploymentBaseUrl'] -eq 'https://explicit.test' -and - $settings['deploymentApplicationFamily'] -eq 'CustomFamily' + $settings.ContainsKey('adminCenterApi') -and $settings['adminCenterApi']['baseUrl'] -eq 'https://explicit.test' -and + $settings['adminCenterApi']['applicationFamily'] -eq 'CustomFamily' } Assert-MockCalled Initialize-AdminCenterAuthContext -Exactly 1 -ParameterFilter { - !$settings.ContainsKey('deploymentBaseUrl') -and !$settings.ContainsKey('deploymentApplicationFamily') + !$settings.ContainsKey('adminCenterApi') } $script:deploymentConfig.apiBaseUrl | Should -Be 'https://legacy.test' } @@ -333,7 +260,7 @@ $inspection = { Mock OutputError { param($message) throw $message } { InvokeDeploy -repositorySettings @{ - deploymentBaseUrl = 'https://explicit.test' + adminCenterApi = @{ baseUrl = 'https://explicit.test' } apiBaseUrl = 'https://legacy.test' } -deploymentSettings @{ EnvironmentType = 'SaaS'; EnvironmentName = 'test'; Branches = @(); Projects = '*'; DependencyInstallMode = 'ignore'; SyncMode = $null; Scope = 'PTE'; continuousDeployment = $true; includeTestAppsInSandboxEnvironment = $false; excludeAppIds = @() } } | Should -Throw '*Authentication failed*' @@ -347,7 +274,7 @@ $inspection = { Mock New-BcAuthContext { return @{ tenantId = 'tenant'; Scopes = 'https://audience.test/.default' } } - InvokeDeploy -repositorySettings @{ deploymentBaseUrl = 'https://explicit.test' } ` + InvokeDeploy -repositorySettings @{ adminCenterApi = @{ baseUrl = 'https://explicit.test' } } ` -authParameters @{ refreshToken = 'dummy'; scopes = @('https://audience.test/.default') } ` -deploymentSettings @{ EnvironmentType = 'SaaS'; EnvironmentName = 'test'; Branches = @(); Projects = '*'; DependencyInstallMode = 'ignore'; SyncMode = $null; Scope = 'PTE'; continuousDeployment = $true; includeTestAppsInSandboxEnvironment = $false; excludeAppIds = @() } @@ -359,7 +286,7 @@ $inspection = { } Assert-MockCalled Initialize-AdminCenterAuthContext -Exactly 1 -ParameterFilter { $preserveScopes -and $authContext.Scopes -eq 'https://audience.test/.default' -and - $settings.deploymentBaseUrl -eq 'https://explicit.test' + $settings.adminCenterApi.baseUrl -eq 'https://explicit.test' } } @@ -376,7 +303,7 @@ $inspection = { & $newContext -tenantID 'fake-tenant' -clientID 'fake-client' -clientSecret 'fake-secret' -silent } - InvokeDeploy -repositorySettings @{ deploymentBaseUrl = 'https://explicit.test'; apiBaseUrl = 'https://legacy.test' } ` + InvokeDeploy -repositorySettings @{ adminCenterApi = @{ baseUrl = 'https://explicit.test' }; apiBaseUrl = 'https://legacy.test' } ` -deploymentSettings @{ EnvironmentType = 'SaaS'; EnvironmentName = 'test'; Branches = @(); Projects = '*'; DependencyInstallMode = 'ignore'; SyncMode = $null; Scope = 'PTE'; continuousDeployment = $true; includeTestAppsInSandboxEnvironment = $false; excludeAppIds = @() } Assert-MockCalled Invoke-RestMethod -ModuleName BcContainerHelper -Exactly 1 -ParameterFilter { @@ -390,7 +317,7 @@ $inspection = { tenantId = 'tenant'; Scopes = 'https://explicit-resource.test/'; AccessToken = 'original-token' } Mock New-BcAuthContext { return $script:originalAuthContext } - InvokeDeploy -repositorySettings @{ deploymentBaseUrl = 'https://admin.test' } ` + InvokeDeploy -repositorySettings @{ adminCenterApi = @{ baseUrl = 'https://admin.test' } } ` -authParameters @{ refreshToken = 'dummy'; resource = 'https://explicit-resource.test' } ` -deploymentSettings @{ EnvironmentType = 'SaaS'; EnvironmentName = 'test'; Branches = @(); Projects = '*'; DependencyInstallMode = 'ignore'; SyncMode = $null; Scope = 'PTE'; continuousDeployment = $true; includeTestAppsInSandboxEnvironment = $false; excludeAppIds = @() } diff --git a/Tests/ReadSettings.Test.ps1 b/Tests/ReadSettings.Test.ps1 index 937d873fe5..12957ecbf8 100644 --- a/Tests/ReadSettings.Test.ps1 +++ b/Tests/ReadSettings.Test.ps1 @@ -31,11 +31,55 @@ InModuleScope ReadSettings { # Allows testing of private functions . (Join-Path $PSScriptRoot '../Actions/AL-Go-Helper.ps1') $defaults = GetDefaultSettings $settingsSchema = $schema | ConvertFrom-Json | ConvertTo-HashTable -recurse - $defaults.deploymentBaseUrl | Should -Be '' - $defaults.deploymentApplicationFamily | Should -Be 'BusinessCentral' - foreach ($name in @('deploymentBaseUrl', 'deploymentApplicationFamily')) { - $settingsSchema.properties[$name].type | Should -Be 'string' - $settingsSchema.properties[$name].default | Should -Be $defaults[$name] + $defaults.adminCenterApi.baseUrl | Should -Be 'https://api.businesscentral.dynamics.com' + $defaults.adminCenterApi.applicationFamily | Should -Be 'BusinessCentral' + $settingsSchema.properties.adminCenterApi.type | Should -Be 'object' + foreach ($name in @('baseUrl', 'applicationFamily')) { + $settingsSchema.properties.adminCenterApi.properties[$name].type | Should -Be 'string' + $settingsSchema.properties.adminCenterApi.properties[$name].default | Should -Be $defaults.adminCenterApi[$name] + $settingsSchema.properties.adminCenterApi.default[$name] | Should -Be $defaults.adminCenterApi[$name] + } + } + + It 'Merges partial Admin targets across settings sources without losing defaults' { + . (Join-Path $PSScriptRoot '../Actions/AL-Go-Helper.ps1') + $settings = GetDefaultSettings + $first = '{"adminCenterApi":{"baseUrl":"https://admin.test"}}' | ConvertFrom-Json + $second = '{"adminCenterApi":{"applicationFamily":"CustomFamily"}}' | ConvertFrom-Json + + MergeCustomObjectIntoOrderedDictionary -dst $settings -src $first + $settings.adminCenterApi.applicationFamily | Should -Be BusinessCentral + MergeCustomObjectIntoOrderedDictionary -dst $settings -src $second + + $settings.adminCenterApi.baseUrl | Should -Be 'https://admin.test' + $settings.adminCenterApi.applicationFamily | Should -Be CustomFamily + } + + It 'Rejects a non-object Admin target during settings merging' { + . (Join-Path $PSScriptRoot '../Actions/AL-Go-Helper.ps1') + $settings = GetDefaultSettings + $source = '{"adminCenterApi":"https://admin.test"}' | ConvertFrom-Json + + { MergeCustomObjectIntoOrderedDictionary -dst $settings -src $source } | + Should -Throw '*property adminCenterApi should be of type OrderedDictionary, is String*' + } + + It 'Validates grouped Admin target fields in the schema' -Skip:($PSVersionTable.PSVersion.Major -lt 7) { + foreach ($json in @( + '{"adminCenterApi":{}}', + '{"adminCenterApi":{"baseUrl":"https://admin.test"}}', + '{"adminCenterApi":{"applicationFamily":"CustomFamily"}}' + )) { + Test-Json -Json $json -Schema $schema | Should -BeTrue + } + foreach ($json in @( + '{"adminCenterApi":"https://admin.test"}', + '{"adminCenterApi":{"baseUrl":29}}', + '{"adminCenterApi":{"baseUrl":"http://admin.test"}}', + '{"adminCenterApi":{"applicationFamily":""}}', + '{"adminCenterApi":{"applicationFamily":" "}}' + )) { + Test-Json -Json $json -Schema $schema -ErrorAction SilentlyContinue | Should -BeFalse } } diff --git a/Workshop/ContinuousDeployment.md b/Workshop/ContinuousDeployment.md index 9d5657654a..09bd223c8e 100644 --- a/Workshop/ContinuousDeployment.md +++ b/Workshop/ContinuousDeployment.md @@ -104,16 +104,18 @@ This behavior also applies when a **Scope Dev** deployment installs or upgrades ## Custom deployment targets -For native Admin Center calls to an Embed or other custom service, set the repository settings `deploymentBaseUrl` (the HTTPS API root) and `deploymentApplicationFamily` (the service's exact application family). These apply to installed-app reads, PTE publishing and operation tracking only. For example: +For native Admin Center calls to an Embed or other custom service, set the repository-level `adminCenterApi` object with `baseUrl` (the HTTPS API root) and `applicationFamily` (the service's exact application family). These apply to installed-app reads, PTE publishing and operation tracking only. Both fields are optional and can be overridden independently. For example: ```json { - "deploymentBaseUrl": "https://api.example.com", - "deploymentApplicationFamily": "YourApplicationFamily" + "adminCenterApi": { + "baseUrl": "https://api.example.com", + "applicationFamily": "YourApplicationFamily" + } } ``` -Empty or omitted `deploymentBaseUrl` uses `https://api.businesscentral.dynamics.com`, regardless of BCH settings. The family defaults to `BusinessCentral` and is never inferred from the host. Automation and AppSource operations keep their existing BCH configuration and authentication; configure `bcContainerHelperConfig.apiBaseUrl` separately if needed. The web-client/readiness URL remains `bcContainerHelperConfig.baseUrl`. +The default `adminCenterApi.baseUrl` is `https://api.businesscentral.dynamics.com`, regardless of BCH settings; an explicit empty string also uses this endpoint. The family defaults to `BusinessCentral` and is never inferred from the host. Automation and AppSource operations keep their existing BCH configuration and authentication; configure `bcContainerHelperConfig.apiBaseUrl` separately if needed. The web-client/readiness URL remains `bcContainerHelperConfig.baseUrl`. Each Deploy run maintains a separate Admin authentication context and reuses its renewed tokens, using the Admin API root as the default OAuth resource without changing the BCH context. Explicit `AUTHCONTEXT` scopes or resource values are preserved, not retargeted; they must authorize the Admin service too. Credentials must support token renewal for that resource, and the service must support the corresponding API contracts and authorization.