diff --git a/Actions/.Modules/AdminCenterApi.psm1 b/Actions/.Modules/AdminCenterApi.psm1 new file mode 100644 index 0000000000..a02f371645 --- /dev/null +++ b/Actions/.Modules/AdminCenterApi.psm1 @@ -0,0 +1,493 @@ +$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 +$script:adminCenterTarget = $null + +<# + .SYNOPSIS + 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 + 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 + Preserve explicitly supplied AUTHCONTEXT scopes or resource instead of using the native root. +#> +function Initialize-AdminCenterAuthContext { + Param( + [Parameter(Mandatory = $true)] + [hashtable] $authContext, + [hashtable] $settings = @{}, + [switch] $preserveScopes + ) + + $target = Get-DeploymentTarget -settings $settings + $scopes = if ($preserveScopes) { $authContext['Scopes'] } else { "$($target.apiBaseUrl)/" } + if ($authContext['Scopes'] -ne $scopes) { + $authContext['Scopes'] = $scopes + $authContext['UtcExpiresOn'] = [DateTime]::MinValue + } + $script:adminCenterAuthContext = $authContext + $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 + Build an AL-Go-owned Business Central Admin Center environment URL. + .PARAMETER applicationFamily + 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] $apiBaseUrl = 'https://api.businesscentral.dynamics.com' + ) + + return "$($apiBaseUrl.TrimEnd('/'))/admin/$adminCenterApiVersion/applications/$([Uri]::EscapeDataString($applicationFamily))/environments/$([Uri]::EscapeDataString($environment))" +} + +<# + .SYNOPSIS + Send one authenticated Admin Center request without retries. + .DESCRIPTION + Preserves HTTP errors and records whether sending was attempted in Exception.Data. + 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 + 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. + .PARAMETER apiBaseUrl + Target API root. +#> +function Invoke-AdminCenterApi { + Param( + [string] $environment, + [string[]] $path, + [ValidateSet('Get', 'Post')] + [string] $method = 'Get', + [byte[]] $body, + [string] $contentType, + [ValidateRange(1, 300)] + [int] $timeoutSeconds = 30, + [string] $applicationFamily = 'BusinessCentral', + [string] $apiBaseUrl = 'https://api.businesscentral.dynamics.com' + ) + + $requestStarted = $false + try { + 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 '/') + $authContext = Renew-BcAuthContext -bcAuthContext $script:adminCenterAuthContext + if (!$authContext -or !$authContext['AccessToken']) { + throw 'Admin Center token renewal returned no access token before sending the request.' + } + $script:adminCenterAuthContext = $authContext + 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 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 + App package to upload. + .PARAMETER syncMode + Admin Center schema synchronization mode, Add or ForceSync. + .PARAMETER applicationFamily + Target application family. + .PARAMETER apiBaseUrl + Target API root. +#> +function Install-AdminCenterPTEApp { + Param( + [string] $environment, + [string] $appFile, + [ValidateSet('Add', 'ForceSync')] + [string] $syncMode = 'Add', + [string] $applicationFamily = 'BusinessCentral', + [string] $apiBaseUrl = 'https://api.businesscentral.dynamics.com' + ) + + $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() + $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 { + if ($multipart) { $multipart.Dispose() } + } +} + +<# + .SYNOPSIS + Read the exact app operation without polling or retrying. + .DESCRIPTION + Uses the initialized Admin authentication context and target. + .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. + .PARAMETER apiBaseUrl + Target API root. +#> +function Get-AdminCenterAppOperation { + Param( + [string] $environment, + [string] $appId, + [string] $operationId, + [ValidateRange(1, 30)] + [int] $timeoutSeconds = 30, + [string] $applicationFamily = 'BusinessCentral', + [string] $apiBaseUrl = 'https://api.businesscentral.dynamics.com' + ) + + $parameters = @{} + $PSBoundParameters + $parameters.Remove('appId') + $parameters.Remove('operationId') + Invoke-AdminCenterApi @parameters -path @('apps', $appId, 'operations', $operationId) +} + +<# + .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-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 + Target application family. + .PARAMETER apiBaseUrl + Target API root. +#> +function Get-AdminCenterInstalledExtensions { + Param( + [string] $environment, + [string] $applicationFamily = 'BusinessCentral', + [string] $apiBaseUrl = 'https://api.businesscentral.dynamics.com' + ) + + $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.' + } + foreach ($app in $response['value']) { + if ($app -isnot [hashtable]) { + throw 'Admin Center installed app has missing or invalid identity.' + } + $id = if ($app['appId']) { $app['appId'] } else { $app['id'] } + if ($id -isnot [string] -or !$id.Trim() -or + ($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 = $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'] + } + } +} + +<# + .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 + ) + + $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 + $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) { + 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 { + 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/.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 27781556c2..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": "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 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 c3f6d0527f..0fcb6eb2a0 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 @@ -167,6 +168,23 @@ 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 { + $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) { + # 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) { InstallOrUpgradeApps -bcAuthContext $bcAuthContext -environment $deploymentSettings.EnvironmentName -Apps $dependencies -installMode $deploymentSettings.DependencyInstallMode } @@ -193,7 +211,6 @@ else { Publish-BcContainerApp @parameters -useDevEndpoint -checkAlreadyInstalled -excludeRuntimePackages -replacePackageId } else { - # Use automation API for production environments (Publish-PerTenantExtensionApps) $parameters = @{ "bcAuthContext" = $bcAuthContext "environment" = $deploymentSettings.EnvironmentName @@ -201,7 +218,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 +228,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 c32a0c20df..9b65f4680c 100644 --- a/Actions/Deploy/Deploy.psm1 +++ b/Actions/Deploy/Deploy.psm1 @@ -1,4 +1,17 @@ . (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 +} <# .SYNOPSIS @@ -180,7 +193,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') { @@ -205,7 +218,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. @@ -224,7 +236,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 @@ -233,7 +245,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." @@ -242,6 +254,104 @@ function CheckInstalledApps { } } +<# + .SYNOPSIS + Read installed apps using the selected API, or the original BCH API for non-PTE work. + .PARAMETER bcAuthContext + Original BCH authentication context, used only for Automation reads. + .PARAMETER environment + Target environment. + .PARAMETER publishingApi + Optional explicit read API. By default uses the selected PTE API, or BCH before selection. +#> +function GetInstalledExtensions { + Param( + [hashtable] $bcAuthContext, + [string] $environment, + [ValidateSet('', 'AdminCenter', 'Automation')] + [string] $publishingApi = $script:ptePublishingApi + ) + + if ($publishingApi -eq 'AdminCenter') { + return Get-AdminCenterInstalledExtensions -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 + Original BCH authentication context, used only for the Automation authorization fallback. + .PARAMETER environment + Target environment. +#> +function Initialize-PTEPublishingApi { + Param( + [hashtable] $bcAuthContext, + [string] $environment + ) + + $publishingApi = 'AdminCenter' + $authorizationDetails = '' + try { + $extensions = @(Get-AdminCenterInstalledExtensions -environment $environment) + } + catch { + if (!(Test-AdminCenterAuthorizationError -errorRecord $_)) { throw } + $authorizationDetails = "$_" + $publishingApi = 'Automation' + $extensions = @(GetInstalledExtensions -bcAuthContext $bcAuthContext -environment $environment -publishingApi $publishingApi) + } + $applicationVersion = GetPTEApplicationVersion -extensions $extensions -environment $environment + 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 +} + +<# + .SYNOPSIS + Publish primary apps or PTE dependencies through the action-selected API. + .DESCRIPTION + 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 + Original BCH authentication context, used only by the Automation publisher. + .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). +#> +function PublishPTEApps { + Param( + [hashtable] $bcAuthContext, + [string] $environment, + [string[]] $appFiles, + [ValidateSet('Add', 'Force')] + [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') { + Install-AdminCenterPTEApps -environment $environment -appFiles $appFiles -schemaSyncMode $schemaSyncMode + } + else { + throw "Invalid PTE publishing API: $script:ptePublishingApi" + } +} + <# .SYNOPSIS Unpublish old, uninstalled versions of the deployed apps from a Business Central environment. @@ -249,7 +359,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. Automation cleanup requires BC 25.4 or later, + 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. The function is non-fatal: any failure is reported as a warning and never fails the deployment. .PARAMETER bcAuthContext The Business Central authentication context. @@ -269,6 +383,10 @@ function UnpublishOldAppVersions { 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 $_ @@ -291,12 +409,7 @@ 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." - return - } - $applicationVersion = [version]::new($application.versionMajor, $application.versionMinor, $application.versionBuild, $application.versionRevision) + $applicationVersion = GetPTEApplicationVersion -extensions $extensions -environment $environment 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 +423,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 @@ -370,7 +483,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) { @@ -392,13 +505,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 - Publish-PerTenantExtensionApps -bcAuthContext $bcAuthContext -environment $environment -appFiles $PTEsToInstall -SchemaSyncMode $schemaSyncMode + PublishPTEApps -bcAuthContext $bcAuthContext -environment $environment -appFiles $PTEsToInstall -SchemaSyncMode $schemaSyncMode } } finally { @@ -472,3 +585,5 @@ function InstallUnknownDependencies { Write-Host "Unknown dependencies installed or upgraded" } } + +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 c0fe51d2bc..eeaf09ae6e 100644 --- a/Actions/Deploy/README.md +++ b/Actions/Deploy/README.md @@ -2,6 +2,17 @@ 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. + +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). + ## INPUT ### ENV variables diff --git a/RELEASENOTES.md b/RELEASENOTES.md index df0c250311..9e0ed7acea 100644 --- a/RELEASENOTES.md +++ b/RELEASENOTES.md @@ -1,3 +1,13 @@ +### Authorization for PTE deployment on BC 29 and later + +**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 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). @@ -13,7 +23,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`). 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 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 @@ -68,7 +78,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`). 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 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 29b65afff8..d4a85ec5fd 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 + +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). + +## 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..f6cb894b47 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 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 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 + > [!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 f3b5fe7629..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.
**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. 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. This should be changed when targetting embed apps. | [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 new file mode 100644 index 0000000000..f1314345f2 --- /dev/null +++ b/Tests/AdminCenterApi.Test.ps1 @@ -0,0 +1,537 @@ +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 { + 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) + Mock Write-Host { } + Mock Renew-BcAuthContext { return @{ AccessToken = 'test-token' } } + Mock Invoke-RestMethod { return @{ id = 'operation-1' } } + } + + AfterEach { + $script:adminCenterAuthContext = $null + $script:adminCenterTarget = $null + } + + 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-AdminCenterPTEApp -environment 'QA / East' ` + -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.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' + } + $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 -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.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 -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) + } + $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) + $bcAuthContext.AccessToken = 'admin-token' + return $bcAuthContext + } + + Invoke-AdminCenterApi -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 -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 -authContext $original.Clone() -settings @{ deploymentBaseUrl = 'https://admin.test' } + Mock Renew-BcAuthContext { + $bcAuthContext.Scopes = 'changed-copy' + throw [TimeoutException]::new('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 + } + + 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 -authContext $original.Clone() -settings @{ deploymentBaseUrl = 'https://admin.test' } + Mock Renew-BcAuthContext { + $renew = Get-Command Renew-BcAuthContext -Module BcContainerHelper + & $renew -bcAuthContext $bcAuthContext -silent + } + + 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' + } + 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 -authContext $original.Clone() -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 -environment Sandbox | 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 { + $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 -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' + } + 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 -authContext $original.Clone() + + 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 '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' + } + Mock Renew-BcAuthContext { + $bcAuthContext.AccessToken = 'mutated-before-failure' + throw [TimeoutException]::new('Renewal timed out') + } + { 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 -authContext $second -settings @{ + deploymentBaseUrl = 'https://second.test'; deploymentApplicationFamily = 'SecondFamily' + } + [object]::ReferenceEquals($script:adminCenterAuthContext, $second) | Should -BeTrue + Mock Renew-BcAuthContext { return $bcAuthContext } + + 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 + $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 -authContext $original.Clone() -settings @{ + deploymentBaseUrl = 'https://action.test'; deploymentApplicationFamily = 'ActionFamily' + } + Mock Renew-BcAuthContext { return $bcAuthContext } + Mock Invoke-RestMethod { return @{ value = @(); id = 'operation' } } + Get-AdminCenterInstalledExtensions -environment Sandbox ` + -apiBaseUrl 'https://explicit.test' -applicationFamily 'ExplicitFamily' | Out-Null + 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 + 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' + } + 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 'Fails before renewal or HTTP when the native context has not been initialized' { + $script:adminCenterAuthContext = $null + $script:adminCenterTarget = $null + + { Get-AdminCenterInstalledExtensions -environment Sandbox } | Should -Throw '*must be initialized*' + + Assert-MockCalled Renew-BcAuthContext -Times 0 + Assert-MockCalled Invoke-RestMethod -Times 0 + } + + 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 -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 -environment Sandbox).Count | Should -Be 0 + } + + It 'Rejects malformed installed-app data: ' -TestCases @( + @{ 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' } + } + Mock Invoke-RestMethod { return @{ value = @($script:appResponse) } } + if ($problem -eq 'missing array') { Mock Invoke-RestMethod { return @{} } } + + { 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-AdminCenterPTEApp -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 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 '*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 + } + + 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 -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-AdminCenterPTEApp -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 and never calls the request wrapper' { + Mock Invoke-AdminCenterApi { throw 'Request must not be called' } + + try { + Install-AdminCenterPTEApp -environment Sandbox -appFile (Join-Path $TestDrive 'Missing.app') + throw 'Expected failure' + } + catch { + $_.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' + } + + 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' + } + +} diff --git a/Tests/Deploy.Action.Test.ps1 b/Tests/Deploy.Action.Test.ps1 index f1517cd820..6e148fb6b4 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 @@ -24,19 +24,95 @@ 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()) 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,9 +131,13 @@ Describe "Deploy Action Tests" { Mock GetAppsAndDependenciesFromArtifacts { return @('/tmp/app1.app'), @() } Mock Sort-AppFilesByDependencies { } Mock CheckInstalledApps { } - Mock Publish-PerTenantExtensionApps { $script:publishPTECalled = $true } + 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 { } Mock UnpublishOldAppVersions { $script:unpublishAfterPublish = $script:publishPTECalled } + Mock OutputWarning { } } AfterEach { @@ -69,15 +149,306 @@ 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 } + 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' } + Mock CheckInstalledApps { $script:events += 'preflight' } + Mock PublishPTEApps { $script:events += 'primary' } + Mock UnpublishOldAppVersions { + $script:events += 'cleanup' + ($appFiles -join ',') | Should -Be '/tmp/app1.app' + } + + 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 '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' { + 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 { + $bcContainerHelperConfig.apiBaseUrl | Should -Be 'https://legacy.test' + } + + 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 } + + 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 $authContext.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 $authContext.Scopes -eq 'https://explicit-resource.test/' -and + ![object]::ReferenceEquals($authContext, $script:originalAuthContext) + } + $script:originalAuthContext.AccessToken | Should -Be 'original-token' + } + 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,8 +456,45 @@ 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 + 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 c1be130086..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,6 +44,11 @@ InModuleScope Deploy { # Allows testing of private functions Mock OutputGroupStart { } Mock OutputGroupEnd { } Mock OutputWarning { } + 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) { @@ -160,8 +166,12 @@ InModuleScope Deploy { # Allows testing of private functions ) } Mock Sort-AppFilesByDependencies { } - Mock Install-BcAppFromAppSource { return $true } - Mock Publish-PerTenantExtensionApps { 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 { } } @@ -510,6 +520,24 @@ 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 + 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 -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*' } + } It 'Does not warn when app version matches installed version' { $bcAuthContext = @{ tenantId = "test-tenant" } $environment = "test-env" @@ -785,7 +813,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' { @@ -804,9 +832,74 @@ 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 'Uses Admin installed PTE dependency checks without requiring Automation' { + $script:ptePublishingApi = 'AdminCenter' + 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 -ParameterFilter { + $environment -eq 'Sandbox' + } + Assert-MockCalled Get-BcInstalledExtensions -Times 0 + 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" }) + } + 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) + 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' { @@ -824,11 +917,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) @@ -864,7 +972,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 } } @@ -878,7 +986,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' { @@ -897,7 +1005,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..b18674aab7 --- /dev/null +++ b/Tests/PublishPTEApps.Test.ps1 @@ -0,0 +1,1172 @@ +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 = 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' } } + Mock Invoke-RestMethod { throw "Unexpected HTTP request" } + Mock Install-AdminCenterPTEApps { } + Mock Get-AdminCenterAppOperation { throw 'Unexpected operation request' } + Mock Get-AdminCenterInstalledExtensions { return $script:extensions } + Mock Get-BcInstalledExtensions { return $script:extensions } + Mock Publish-PerTenantExtensionApps { } + } + + 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 }) + $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 + + $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*' -and + $message -like '*"correlationId":"test-correlation"*' -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 '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 } | + 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 @( + @{ 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 '' + Assert-MockCalled OutputWarning -Times 0 + } + + 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') } + Mock Remove-Item { } + Mock Get-AppJsonFromAppFile { return @{ id = 'app-1'; name = 'App'; version = '2.0.0.0' } } + } + + 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-AdminCenterPTEApps -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 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 + Mock Install-AdminCenterPTEApps { 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 1 -ParameterFilter { + $environment -eq 'Second' + } + Assert-MockCalled Install-AdminCenterPTEApps -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 + + 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 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 Install-AdminCenterPTEApps { } + + PublishPTEApps -bcAuthContext @{ tenantId = 'tenant' } -environment Sandbox -appFiles @('Apps.zip', 'Other.app') ` + -schemaSyncMode Force + + 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' + } + Assert-MockCalled Get-AdminCenterInstalledExtensions -Times 0 + Assert-MockCalled Copy-AppFilesToFolder -Times 0 + Assert-MockCalled Publish-PerTenantExtensionApps -Times 0 + } + + 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-AdminCenterPTEApps -Exactly 1 + } + + 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 'Install-AdminCenterPTEApps' + (Get-Command PublishPTEApps).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 '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' } + 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 @( + @{ major = 29 }, @{ major = 30 }, @{ major = 31 } + ) { + param($major) + $script:application.versionMajor = $major + + 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-AdminCenterPTEApp -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 'Leaves original BCH credentials out of native snapshot, upload and operation wait calls' { + Install-AdminCenterPTEApps -environment Sandbox -appFiles @('App.app') + + Assert-MockCalled Get-AdminCenterInstalledExtensions -Exactly 1 -ParameterFilter { + !$PesterBoundParameters.ContainsKey('bcAuthContext') + } + Assert-MockCalled Install-AdminCenterPTEApp -Exactly 1 -ParameterFilter { + !$PesterBoundParameters.ContainsKey('bcAuthContext') + } + Assert-MockCalled WaitPTEOperation -Exactly 1 -ParameterFilter { + !$PesterBoundParameters.ContainsKey('bcAuthContext') + } + Assert-MockCalled Get-BcInstalledExtensions -Times 0 + Assert-MockCalled Publish-PerTenantExtensionApps -Times 0 + } + + 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 } + + 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-AdminCenterPTEApp -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-AdminCenterPTEApp { + $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 'deploymentTarget' + } + Install-AdminCenterPTEApps -environment 'QA / East' -appFiles @('App.app') -schemaSyncMode Force + + Assert-MockCalled Install-AdminCenterPTEApp -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' { + Mock Get-AppJsonFromAppFile { return @{ id = 'app-1'; name = 'App'; version = '28.0.0.0' } } + + Install-AdminCenterPTEApps -environment 'Sandbox' -appFiles @('App.app') + + Assert-MockCalled Install-AdminCenterPTEApp -Exactly 1 + Assert-MockCalled Publish-PerTenantExtensionApps -Times 0 + } + + It 'Skips an installed version through Admin Center' -TestCases @( + @{ version = 2 }, @{ version = 3 } + ) { + param($version) + $script:extensions += @{ + id = 'app-1'; displayName = 'App'; isInstalled = $true + versionMajor = $version; versionMinor = 0; versionBuild = 0; versionRevision = 0 + } + + Install-AdminCenterPTEApps -environment 'Sandbox' -appFiles @('App.app') + + Assert-MockCalled Install-AdminCenterPTEApp -Times 0 + Assert-MockCalled WaitPTEOperation -Times 0 + Assert-MockCalled Publish-PerTenantExtensionApps -Times 0 + Assert-MockCalled OutputWarning -Times 0 + 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' { + $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 } + ) + + Install-AdminCenterPTEApps -environment 'Sandbox' -appFiles @('App.app') + + Assert-MockCalled Install-AdminCenterPTEApp -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) + $script:events += "read:$appFile" + return @{ id = $appFile; name = $appFile; version = '2.0.0.0' } + } + $script:events = @() + Mock Install-AdminCenterPTEApp { + param($appFile) + $script:events += "upload:$appFile" + return @{ id = "operation-$appFile"; appId = $appFile; status = 'running' } + } + Mock WaitPTEOperation { + 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,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' } + } + + It 'Does not fall back or continue after an ambiguous failure' -TestCases @( + @{ step = 'upload' }, @{ step = 'polling' }, @{ step = 'authorization' } + ) { + param($step) + switch ($step) { + upload { Mock Install-AdminCenterPTEApp { throw "Package upload failed" } } + polling { Mock WaitPTEOperation { throw "Installation failed" } } + authorization { Mock Install-AdminCenterPTEApp { throw "403 Forbidden" } } + } + + { Install-AdminCenterPTEApps -environment 'Sandbox' -appFiles @('App.app') } | Should -Throw + + 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 @( + @{ statusCode = 400 }, @{ statusCode = 401 }, @{ statusCode = 403 }, + @{ statusCode = 404 }, @{ statusCode = 409 }, @{ statusCode = 500 } + ) { + param($statusCode) + $script:uploadStatus = $statusCode + Mock Install-AdminCenterPTEApp { + $exception = [System.Exception]::new('Upload rejected') + $exception | Add-Member NoteProperty Response ([PSCustomObject]@{ StatusCode = $script:uploadStatus }) + throw $exception + } + { Install-AdminCenterPTEApps -environment Sandbox -appFiles @('App.app') } | + Should -Throw '*Upload rejected*' + Assert-MockCalled Publish-PerTenantExtensionApps -Times 0 + Assert-MockCalled OutputWarning -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' }) } + } + Install-AdminCenterPTEApps -environment Sandbox -appFiles @('Apps.zip') + + 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-AdminCenterPTEApp { + $exception = [IO.FileNotFoundException]::new('Package missing') + $exception.Data['AdminCenterRequestStarted'] = $false + throw $exception + } + + { 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-AdminCenterPTEApp { + throw [System.Security.Authentication.AuthenticationException]::new('TLS handshake failed') + } + + { Install-AdminCenterPTEApps -environment Sandbox -appFiles @('App.app') } | + Should -Throw '*TLS handshake failed*' + + Assert-MockCalled Publish-PerTenantExtensionApps -Times 0 + } + + 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 + } + + { Install-AdminCenterPTEApps -environment Sandbox -appFiles @('App.app') } | Should -Throw '*accepted operation*' + + Assert-MockCalled Publish-PerTenantExtensionApps -Times 0 + Assert-MockCalled Install-AdminCenterPTEApp -Exactly 1 + } + + It 'Stops without fallback after a terminal operation failure' { + Mock WaitPTEOperation { + throw 'Operation failed: rejected package' + } + + { Install-AdminCenterPTEApps -environment Sandbox -appFiles @('App.app') } | + Should -Throw '*Operation failed: rejected package*' + + Assert-MockCalled Publish-PerTenantExtensionApps -Times 0 + } + + 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' + } + } + + { Install-AdminCenterPTEApps -environment Sandbox -appFiles @('Apps.zip') } | + Should -Throw '*operation-2*Second.app*running*' + + 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 + } + } + + 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: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 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' }) + + Install-AdminCenterPTEApps -environment Sandbox -appFiles @('App.app') + + Assert-MockCalled Install-AdminCenterPTEApp -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 + + { Install-AdminCenterPTEApps -environment Sandbox -appFiles @('App.app') } | Should -Throw + + Assert-MockCalled Install-AdminCenterPTEApp -Times 0 + Assert-MockCalled Publish-PerTenantExtensionApps -Times 0 + Assert-MockCalled Remove-Item -Exactly 1 + } + + } + + Context "Exact operation polling" { + BeforeEach { + $script:operation = [PSCustomObject]@{ id = 'operation / 1'; appId = 'app-1'; status = 'running'; scheduleKind = 'immediate' } + Mock Start-Sleep { } + Mock Get-AdminCenterAppOperation { return [PSCustomObject]@{ id = 'operation / 1'; appId = 'app-1'; status = 'succeeded' } } + } + + It 'Accepts immediate success without polling' { + $script:operation.status = 'succeeded' + + 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 -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' }, + @{ status = 'skipped' }, + @{ status = 'unknown' } + ) { + param($status) + $script:operation.status = $status + $script:operation | Add-Member NoteProperty errorMessage 'Service validation detail' + + try { + WaitPTEOperation -environment Sandbox -operation $script:operation -appId 'app-1' + throw 'Expected terminal error' + } + catch { + $_.Exception.Data.Count | Should -Be 0 + $_.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 -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 -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 + } + Assert-MockCalled Start-Sleep -Exactly 1 -ParameterFilter { $Milliseconds -eq 30000 } + } + + It 'Uses the requested shorter polling interval without changing the operation endpoint' { + 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 { + $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 -environment Sandbox -operation $script:operation -appId 'app-1' + + Assert-MockCalled Get-AdminCenterAppOperation -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 -environment Sandbox -operation $script:operation -appId 'app-1' } | Should -Throw '*operation / 1*Service diagnostic*' + + Assert-MockCalled Get-AdminCenterAppOperation -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 -environment Sandbox -operation $script:operation -appId 'app-1' } | Should -Throw '*missing or mismatched*' + + Assert-MockCalled Get-AdminCenterAppOperation -Times 0 + } + + It 'Rejects missing or unrelated status response ' -TestCases @( + @{ response = 'empty' }, @{ response = 'anotherOperation' }, @{ response = 'anotherApp' }, @{ response = 'collection' } + ) { + param($response) + $script:responseKind = $response + Mock Get-AdminCenterAppOperation { + 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 -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 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 -environment Sandbox -operation $script:operation -appId 'app-1' + + Assert-MockCalled Get-AdminCenterAppOperation -Exactly 3 + Assert-MockCalled OutputWarning -Exactly 2 + } + + It 'Stops after five consecutive transient retries' { + Mock Get-AdminCenterAppOperation { throw [System.TimeoutException]::new('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 + } + + 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 Get-AdminCenterAppOperation { + $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 -environment Sandbox -operation $script:operation -appId 'app-1' + Assert-MockCalled Get-AdminCenterAppOperation -Exactly 2 + Assert-MockCalled OutputWarning -Exactly 1 + } + else { + { 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 + } + } + + It 'Resets the consecutive retry budget after a successful running status read' { + $script:reads = 0 + 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 -environment Sandbox -operation $script:operation -appId 'app-1' + + Assert-MockCalled Get-AdminCenterAppOperation -Exactly 12 + Assert-MockCalled OutputWarning -Exactly 10 + } + + It 'Does not retry non-transient errors or renew failures' { + Mock Get-AdminCenterAppOperation { + $exception = [System.TimeoutException]::new('Authentication renewal failed: 403 Forbidden') + $exception.Data['AdminCenterRequestStarted'] = $false + throw $exception + } + + { WaitPTEOperation -environment Sandbox -operation $script:operation -appId 'app-1' } | Should -Throw '*403 Forbidden*' + + Assert-MockCalled Get-AdminCenterAppOperation -Times 1 + Assert-MockCalled OutputWarning -Times 0 + } + + It 'Does not retry an authorization status-read failure' { + Mock Get-AdminCenterAppOperation { throw '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 + } + + It 'Bounds status attempts even when the operation remains scheduled' { + Mock Get-AdminCenterAppOperation { return [PSCustomObject]@{ id = 'operation / 1'; status = 'scheduled' } } + + { WaitPTEOperation -environment Sandbox -operation $script:operation -appId 'app-1' -maxStatusRequests 2 } | Should -Throw '*Timed out*2 status requests*' + + Assert-MockCalled Get-AdminCenterAppOperation -Exactly 2 + } + + It 'Limits the default immediate polling to 360 status requests' { + Mock Get-AdminCenterAppOperation { return [PSCustomObject]@{ id = 'operation / 1'; status = 'running' } } + + { 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 + } + + It 'Honors the elapsed timeout before another status request' { + Mock Start-Sleep { [System.Threading.Thread]::Sleep(1100) } + + { 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/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/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 diff --git a/Tests/UnpublishOldAppVersions.Test.ps1 b/Tests/UnpublishOldAppVersions.Test.ps1 index 9220ef074b..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,133 @@ 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 }, + @{ major = 30; minor = 0 }, + @{ major = 30; minor = 1 }, + @{ major = 31; minor = 0 } + ) { + 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") } | 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 @( + @{ major = 29 }, @{ major = 30 }, @{ major = 31 } + ) { + param($major) + $script:applicationExtension.versionMajor = $major + $script:ptePublishingApi = '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' + } + Assert-MockCalled OutputWarning -Times 0 + } + + 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') + + 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 -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 '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') + + 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 @( + @{ major = 25; minor = 4 }, + @{ major = 28; minor = 9 }, + @{ major = 28; minor = 0 } + ) { + 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..80e3fdad0a 100644 --- a/Workshop/ContinuousDeployment.md +++ b/Workshop/ContinuousDeployment.md @@ -88,6 +88,43 @@ 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 + +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. + +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, 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 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.