SignPath.psm1

#Requires -Version 3.0
# Also requires .NET Version 4.7.2 or above

$ServiceUnavailableRetryTimeoutInSeconds = 30
$WaitForCompletionRetryTimeoutInSeconds = 5
$DefaultHttpClientTimeoutInSeconds = 100

function Submit-SigningRequest (
# The URL to the API, e.g. 'https://app.signpath.io/api/'.
  [Parameter()]
  [ValidateNotNullOrEmpty()]
  [string] $ApiUrl = "https://app.signpath.io/api/",

# The API token you retrieve when adding a new CI user.
  [Parameter(Mandatory)]
  [ValidateNotNullOrEmpty()]
  [string] $CIUserToken,

# The ID of the organization containing the signing policy.
# Go to "Project > Signing policy" in the web client and copy the first ID from the url to retrieve this value (e.g. https://app.signpath.io/<OrganizationId>/SigningPolicies/<SigningPolicyId>).
  [Parameter(Mandatory)]
  [ValidateNotNullOrEmpty()]
  [string] $OrganizationId,

# If you use IDs to reference the artifact configuration and signing policy: this is the ID of the artifact configuration you want to use for
# signing. If not given, the default artifact configuration will be used instead.
# Go to "Project -> Artifact configuration" in the web client and copy the last ID from the url to retrieve this value (e.g. https://app.signpath.io/<OrganizationId>/ArtifactConfigurations/<ArtifactConfigurationId>).
  [Parameter()]
  [string] $ArtifactConfigurationId,

# If you use IDs to reference the artifact configuration and signing policy: this is the ID of the signing policy you want to use for signing.
# Go to "Project > Signing policy" in the web client and copy the last ID from the url to retrieve this value (e.g. https://app.signpath.io/<OrganizationId>/SigningPolicies/<SigningPolicyId>).
  [Parameter()]
  [string] $SigningPolicyId,

# If you use slugs to reference the artifact configuration and signing policy: this is the project in which the artifact configuration and signing
# policy reside in.
  [Parameter()]
  [Alias("ProjectKey")]
  [string] $ProjectSlug,

# If you use slugs to reference the artifact configuration and signing policy: this is the slug of the artifact configuration you want to use for
# signing. If not given, the default artifact configuration will be used instead.
  [Parameter()]
  [Alias("ArtifactConfigurationKey")]
  [string] $ArtifactConfigurationSlug,

# If you use slugs to reference the artifact configuration and signing policy: this is the slug of the signing policy you want to use for signing.
  [Parameter()]
  [Alias("SigningPolicyKey")]
  [string] $SigningPolicySlug,

# Specifies the path of the artifact that you want to be signed.
  [Parameter(Mandatory)]
  [ValidateNotNullOrEmpty()]
  [string] $InputArtifactPath,

# An optional description of the uploaded artifact that could be helpful to the approver.
  [Parameter()]
  [string] $Description,

# Information about the origin of the artifact (e.g. source code repository, commit ID, etc). See https://about.signpath.io/documentation/powershell#submit-signingrequest
  [Parameter()]
  [Hashtable] $Origin,

# Provide values for parameters defined in the artifact configuration. See https://about.signpath.io/documentation/artifact-configuration#user-defined-parameters
  [Parameter()]
  [Hashtable] $Parameters,

# Client certificate that's used for a secure Web API request. Not supported by SignPath.io directly, use for proxies.
  [Parameter()]
  [System.Security.Cryptography.X509Certificates.X509Certificate2] $ClientCertificate,

# The total time in seconds that the cmdlet will wait for a single service call to succeed (across several retries). Defaults to 600 seconds.
  [Parameter()]
  [int] $ServiceUnavailableTimeoutInSeconds = 600,

# The HTTP timeout used for upload and download HTTP requests. Defaults to 300 seconds.
  [Parameter()]
  [int] $UploadAndDownloadRequestTimeoutInSeconds = 300,

  [Parameter(ParameterSetName = "WaitForCompletion")]
  [switch] $WaitForCompletion,

# Specifies the path of the downloaded signed artifact (result file). If this is not given, the InputArtifactPath with an added ".signed" extension is used (e.g. "Input.dll" => "Input.signed.dll").
  [Parameter(ParameterSetName = "WaitForCompletion")]
  [ValidateNotNullOrEmpty()]
  [string] $OutputArtifactPath,

# The maximum time in seconds that the cmdlet will wait for the signing request to complete (upload and download have no specific timeouts). Defaults to 600 seconds.
  [Parameter(ParameterSetName = "WaitForCompletion")]
  [int] $WaitForCompletionTimeoutInSeconds = 600,

# Allows the cmdlet to overwrite the file at OutputArtifactPath.
  [Parameter(ParameterSetName = "WaitForCompletion")]
  [switch] $Force) {

  <#
  .SYNOPSIS
    Submits a signing request via the SignPath REST API.
  .DESCRIPTION
    The Submit-SigningRequest cmdlet submits a signing request with the specified InputArtifactPath via the SignPath REST API.
    When passing the -WaitForCompletion switch the command also waits for the signing request to complete, downloads the signed file and stores it in the path specified by the OutputArtifactPath argument.
    Otherwise the result of the submitted signing request can be downloaded with the Get-SignedArtifact command.
 
    To tweak timing issues use the parameters ServiceUnavailableTimeoutInSeconds, UploadAndDownloadRequestTimeoutInSeconds and WaitForCompletionTimeoutInSeconds
  .EXAMPLE
    Submit-SigningRequest
      -InputArtifactPath Program.exe
      -CIUserToken /Joe3s2m7hkhVyoba4H4weqj9UxIk6nKRXGhGbH7nv4=
      -OrganizationId 1c0ab26c-12f3-4c6e-a043-2568e133d2de
      -ProjectSlug myProject
      -SigningPolicySlug testSigning
      -OutputArtifactPath Program.signed.exe
      -WaitForCompletion
  .OUTPUTS
    Returns the SigningRequestId which can be used with Get-SignedArtifact
  .NOTES
    Author: SignPath GmbH
  #>


  Set-StrictMode -Version 2.0

  $ApiUrl = GetVersionedApiUrl($ApiUrl)
  Write-Verbose "Using versioned API URL: $ApiUrl"

  $InputArtifactPath = PrepareInputArtifactPath $InputArtifactPath
  Write-Verbose "Using input artifact: $InputArtifactPath"

  CreateAndUseAuthorizedHttpClient $CIUserToken -ClientCertificate $ClientCertificate -Timeout $DefaultHttpClientTimeoutInSeconds {
    Param ([System.Net.Http.HttpClient] $defaultHttpClient)

    CreateAndUseAuthorizedHttpClient $CIUserToken -ClientCertificate $ClientCertificate -Timeout $UploadAndDownloadRequestTimeoutInSeconds {
      Param ([System.Net.Http.HttpClient] $uploadAndDownloadHttpClient)

      if (-not $OutputArtifactPath) {
        $extension = [System.IO.Path]::GetExtension($InputArtifactPath)
        $OutputArtifactPath = [System.IO.Path]::ChangeExtension($InputArtifactPath, "signed$extension")
      }

      $OutputArtifactPath = PrepareOutputArtifactPath $Force $OutputArtifactPath
      Write-Verbose "Will write output artifact to: $OutputArtifactPath"

      $submitUrl = [string]::Join("/", @($ApiUrl.Trim("/"), $OrganizationId, "SigningRequests"))
      $getUrl = SubmitVia `
        -HttpClient $uploadAndDownloadHttpClient `
        -Url $submitUrl `
        -ArtifactConfigurationId $ArtifactConfigurationId `
        -SigningPolicyId $SigningPolicyId `
        -ProjectSlug $ProjectSlug `
        -ArtifactConfigurationSlug $ArtifactConfigurationSlug `
        -SigningPolicySlug $SigningPolicySlug `
        -InputArtifactPath $InputArtifactPath `
        -Description $Description `
        -Origin $Origin `
        -Parameters $Parameters

      if ($WaitForCompletion.IsPresent) {
        $downloadUrl = WaitForCompletion `
          -HttpClient $defaultHttpClient `
          -Url $getUrl `
          -WaitForCompletionTimeoutInSeconds $WaitForCompletionTimeoutInSeconds `
          -ServiceUnavailableRetryTimeoutInSeconds $ServiceUnavailableRetryTimeoutInSeconds

        DownloadArtifact `
          -HttpClient $uploadAndDownloadHttpClient `
          -Url $downloadUrl `
          -Path $OutputArtifactPath `
          -ServiceUnavailableRetryTimeoutInSeconds $ServiceUnavailableRetryTimeoutInSeconds
      }

      $guidRegex = "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}"
      $pattern = [regex]"SigningRequests/($guidRegex)"
      $getUrl -match $pattern | Out-Null
      $signingRequestId = $matches[1]
      Write-Verbose "Parsed signing request ID: $signingRequestId"
      return $signingRequestId
    }
  }
}

function Get-SignedArtifact (
# The URL to the API, e.g. https://app.signpath.io/api/.
  [Parameter()]
  [ValidateNotNullOrEmpty()]
  [string] $ApiUrl = "https://app.signpath.io/api/",

# The API token you retrieve when adding a new CI user.
  [Parameter(Mandatory)]
  [ValidateNotNullOrEmpty()]
  [string] $CIUserToken,

# The ID of the organization containing the signing policy.
# Go to "Project > Signing policy" in the web client and copy the first ID from the url to retrieve this value (e.g. https://app.signpath.io/<OrganizationId>/SigningPolicies/<SigningPolicyId>).
  [Parameter(Mandatory)]
  [ValidateNotNullOrEmpty()]
  [string] $OrganizationId,

# The ID of the SigningRequest that contains the desired artifact
  [Parameter(Mandatory)]
  [ValidateNotNullOrEmpty()]
  [string] $SigningRequestId,

# Specifies the path of the downloaded signed artifact (result file).
  [Parameter(Mandatory)]
  [ValidateNotNullOrEmpty()]
  [string] $OutputArtifactPath,

# Client certificate that's used for a secure Web API request. Not supported by SignPath.io directly, use for proxies.
  [Parameter()]
  [System.Security.Cryptography.X509Certificates.X509Certificate2] $ClientCertificate,

# The total time in seconds that the cmdlet will wait for a service call to succeed (across several retries). Defaults to 600 seconds.
  [Parameter()]
  [int] $ServiceUnavailableTimeoutInSeconds = 600,

# The HTTP timeout used for upload and download HTTP requests. Defaults to 300 seconds.
  [Parameter()]
  [int] $UploadAndDownloadRequestTimeoutInSeconds = 300,

# The maximum time in seconds that the cmdlet will wait for the signing request to complete. Defaults to 600 seconds.
  [Parameter()]
  [int] $WaitForCompletionTimeoutInSeconds = 600,

# Allows the cmdlet to overwrite the file at OutputArtifactPath.
  [Parameter()]
  [switch] $Force) {

  <#
  .SYNOPSIS
     Tries to download a signed artifact based on a SigningRequestId.
  .DESCRIPTION
     Waits for a given signing request until its processing has finished and downloads the resultiung artifact.
     If the request couldn't be downloaded in time, because the processing took to long or the request is invalid,
     this function throws exceptions.
 
     To tweak timing issues use the parameters ServiceUnavailableTimeoutInSeconds, UploadAndDownloadRequestTimeoutInSeconds and WaitForCompletionTimeoutInSeconds
  .EXAMPLE
     Get-SignedArtifact
        -OutputArtifactPath Program.exe
        -CIUserToken /Joe3s2m7hkhVyoba4H4weqj9UxIk6nKRXGhGbH7nv4=
        -OrganizationId 1c0ab26c-12f3-4c6e-a043-2568e133d2de
        -SigningRequestId 711960ed-bdb8-41cd-a6bf-a10d0ae3cfcd
  .OUTPUTS
     Returns void but creates a file in the given OutputArtifactPath on success.
  .NOTES
    Author: SignPath GmbH
  #>


  Set-StrictMode -Version 2.0

  $ApiUrl = GetVersionedApiUrl $ApiUrl
  Write-Verbose "Using versioned API URL: $ApiUrl"

  $OutputArtifactPath = PrepareOutputArtifactPath $Force $OutputArtifactPath
  Write-Verbose "Will write signed artifact to: $OutputArtifactPath"

  CreateAndUseAuthorizedHttpClient $CIUserToken -ClientCertificate $ClientCertificate -Timeout $DefaultHttpClientTimeoutInSeconds {
    Param ([System.Net.Http.HttpClient] $defaultHttpClient)

    CreateAndUseAuthorizedHttpClient $CIUserToken -Timeout $UploadAndDownloadRequestTimeoutInSeconds {
      Param ([System.Net.Http.HttpClient] $uploadAndDownloadHttpClient)

      $expectedSigningRequestUrl = [string]::Join("/", @($ApiUrl.Trim("/"), $OrganizationId, "SigningRequests", $SigningRequestId))

      $downloadUrl = WaitForCompletion `
        -httpClient $defaultHttpClient `
        -url $expectedSigningRequestUrl `
        -WaitForCompletionTimeoutInSeconds $WaitForCompletionTimeoutInSeconds `
        -ServiceUnavailableRetryTimeoutInSeconds $ServiceUnavailableRetryTimeoutInSeconds

      DownloadArtifact `
        -HttpClient $uploadAndDownloadHttpClient `
        -Url $downloadUrl `
        -Path $OutputArtifactPath `
        -ServiceUnavailableRetryTimeoutInSeconds $ServiceUnavailableRetryTimeoutInSeconds
    }
  }
}

function GetVersionedApiUrl ([string] $ApiUrl) {
  $supportedApiVersion = "v1"
  return [string]::Join("/", @($ApiUrl.Trim("/"), $supportedApiVersion))
}

function SubmitVia (
  [System.Net.Http.HttpClient] $HttpClient,
  [string] $Url,
  [string] $ArtifactConfigurationId,
  [string] $SigningPolicyId,
  [string] $ProjectSlug,
  [string] $ArtifactConfigurationSlug,
  [string] $SigningPolicySlug,
  [string] $InputArtifactPath,
  [string] $Description,
  [Hashtable] $Origin,
  [Hashtable] $Parameters) {

  Write-Verbose "Submitting signing request..."

  # Copy variables to local scope to allow capturing them in a closure
  $local:ArtifactConfigurationId = $ArtifactConfigurationId
  $local:SigningPolicyId = $SigningPolicyId
  $local:ProjectSlug = $ProjectSlug
  $local:ArtifactConfigurationSlug = $ArtifactConfigurationSlug
  $local:SigningPolicySlug = $SigningPolicySlug
  $local:Description = $Description
  $local:InputArtifactPath = $InputArtifactPath

  $local:Hash = (Get-FileHash -Path $InputArtifactPath -Algorithm "SHA256").Hash
  Write-Host "SHA256 hash: $Hash"

  $local:IsVerboseEnabled = $null -ne $PSCmdlet.MyInvocation.BoundParameters["Verbose"] -and $PSCmdlet.MyInvocation.BoundParameters["Verbose"].IsPresent

  $requestFactory = {
    if ($IsVerboseEnabled) {
      $VerbosePreference = "Continue"
    }

    function AddContent ($content, $baseKey, $key, $value) {
      # All parameters ending in "File" are interpreted as streams
      if ( $key.ToLower().EndsWith("file")) {
        if ( $value.StartsWith("@")) {
          $filePath = $value.Substring(1)
          $packageFileStream = New-Object System.IO.FileStream ($filePath, [System.IO.FileMode]::Open)
          $streamContent = New-Object System.Net.Http.StreamContent $packageFileStream
          # PLANNED SIGN-988 This shouldn't be needed anymore
          $streamContent.Headers.ContentType = New-Object System.Net.Http.Headers.MediaTypeHeaderValue "application/octet-stream"
          $fileName = [System.IO.Path]::GetFileName($filePath)
          $content.Add($streamContent, "$baseKey.$key", $fileName)
          Write-Verbose "Adding file content to origin: $baseKey.$key = $fileName"
        } else {
          # IDEA: We will later on support non-file parameter values here too, for now we throw
          throw "*File origin parameters must start with @ to indicate a file path"
        }
      } else {
        $stringContent = New-Object System.Net.Http.StringContent $value
        $content.Add($stringContent, "$baseKey.$key")
        Write-Verbose "Add normal content to origin: $baseKey.$key = $value"
      }
    }

    function AddAllHashTableContent ($content, $hashtable, $baseKey) {
      Write-Verbose "Recursive add origin base key: $baseKey"
      foreach ($kvp in $hashtable.GetEnumerator()) {
        if ($kvp.Value.GetType().Name -eq "Hashtable") {
          Write-Verbose "$($kvp.Key) is a Hashtable, enter next recursion level"
          AddAllHashTableContent $content $kvp.Value "$baseKey.$($kvp.Key)"
        }
        else {
          AddContent $content $baseKey $kvp.Key $kvp.Value
        }
      }
    }

    function AddAllHashTableParameters ($content, $hashtable, $baseKey) {
      foreach ($kvp in $hashtable.GetEnumerator()) {
        $parameterContent = New-Object System.Net.Http.StringContent $kvp.Value
        $content.Add($parameterContent, "$baseKey.$($kvp.Key)")
      }
    }

    $content = New-Object System.Net.Http.MultipartFormDataContent

    try {
      if ($ArtifactConfigurationId) {
        Write-Verbose "ArtifactConfigurationId: $ArtifactConfigurationId"
        $artifactConfigurationIdContent = New-Object System.Net.Http.StringContent $ArtifactConfigurationId
        $content.Add($artifactConfigurationIdContent, "ArtifactConfigurationId")
      }

      if ($SigningPolicyId) {
        Write-Verbose "SigningPolicyId: $SigningPolicyId"
        $signingPolicyIdContent = New-Object System.Net.Http.StringContent $SigningPolicyId
        $content.Add($signingPolicyIdContent, "SigningPolicyId")
      }

      if ($ProjectSlug) {
        Write-Verbose "ProjectSlug: $ProjectSlug"
        $projectSlugContent = New-Object System.Net.Http.StringContent $ProjectSlug
        $content.Add($projectSlugContent, "ProjectSlug")
      }

      if ($ArtifactConfigurationSlug) {
        Write-Verbose "ArtifactConfigurationSlug: $ArtifactConfigurationSlug"
        $artifactConfigurationSlugContent = New-Object System.Net.Http.StringContent $ArtifactConfigurationSlug
        $content.Add($artifactConfigurationSlugContent, "ArtifactConfigurationSlug")
      }

      if ($SigningPolicySlug) {
        Write-Verbose "SigningPolicySlug: $SigningPolicySlug"
        $signingPolicySlugContent = New-Object System.Net.Http.StringContent $SigningPolicySlug
        $content.Add($signingPolicySlugContent, "SigningPolicySlug")
      }

      Write-Verbose "Description: $Description"
      $descriptionContent = New-Object System.Net.Http.StringContent $Description
      $content.Add($descriptionContent, "Description")

      $packageFileStream = New-Object System.IO.FileStream ($InputArtifactPath, [System.IO.FileMode]::Open)
      $streamContent = New-Object System.Net.Http.StreamContent $packageFileStream
      # PLANNED SIGN-988 This shouldn't be needed anymore
      $streamContent.Headers.ContentType = New-Object System.Net.Http.Headers.MediaTypeHeaderValue "application/octet-stream"
      $fileName = [System.IO.Path]::GetFileName($InputArtifactPath)
      $content.Add($streamContent, "Artifact", $fileName)
      Write-Verbose "Artifact: $fileName"

      if ($Origin) {
        Write-Verbose "Adding all origin parameters..."
        AddAllHashTableContent $content $Origin "Origin"
      }

      if ($Parameters) {
        Write-Verbose "Adding all signing request parameters..."
        AddAllHashTableParameters $content $Parameters "Parameters"
      }

      $request = New-Object System.Net.Http.HttpRequestMessage Post, $Url
      $request.Content = $content

      Write-Verbose "Request URL: $Url"
      return $request
      # Only dispose the content in case of exceptions, otherwise the caller is responsible for disposing the whole request after it has been performed.
    } catch {
      $content.Dispose()
      throw
    }
  }.GetNewClosure()

  $submitResponse = $null
  try {
    $submitResponse = SendWithRetry `
      -HttpClient $HttpClient `
      -RequestFactory $requestFactory `
      -ServiceUnavailableRetryTimeoutInSeconds $ServiceUnavailableRetryTimeoutInSeconds
    CheckResponse $submitResponse

    $getUrl = $submitResponse.Headers.Location.AbsoluteUri
    Write-Host "Submitted signing request at '$getUrl'"
    return $getUrl
  } finally {
    if ((Test-Path variable:submitResponse) -and $null -ne $submitResponse) {
      $submitResponse.Dispose()
    }
  }
}

function GetWithRetry ([System.Net.Http.HttpClient] $httpClient, [string] $url, [int] $serviceUnavailableRetryTimeoutInSeconds) {
  $response = SendWithRetry `
    -HttpClient $httpClient `
    -RequestFactory { New-Object System.Net.Http.HttpRequestMessage Get, $url }.GetNewClosure() `
    -ServiceUnavailableRetryTimeoutInSeconds $serviceUnavailableRetryTimeoutInSeconds
  return $response
}

function SendWithRetry (
  [System.Net.Http.HttpClient] $httpClient,
  [ScriptBlock] $requestFactory,
  [int] $serviceUnavailableRetryTimeoutInSeconds) {

  $sw = [System.Diagnostics.Stopwatch]::StartNew()
  $retry = 0

  while ($true) {
    $retryReason = $null

    if ($retry -gt 0) {
      Write-Host "Retry $retry..."
    }

    $request = $null
    try {
      Write-Verbose "Generating request..."
      $request = & $requestFactory

      Write-Verbose "HttpClient timeout: $($httpClient.Timeout)"
      Write-Verbose "Sending request..."
      $response = $httpClient.SendAsync($request, [System.Net.Http.HttpCompletionOption]::ResponseHeadersRead).GetAwaiter().GetResult()

      Write-Verbose "Response status code: $($response.StatusCode)"
      if (503 -eq $response.StatusCode) {
        $retryReason = "SignPath REST API is temporarily unavailable. Please try again in a few moments."
      } elseif(500 -le $response.StatusCode -and 600 -gt $response.StatusCode) {
        $retryReason = "SignPath REST API returned an unexpected status code ($($response.StatusCode))"
      } else {
        return $response
      }
    } catch [System.Net.Http.HttpRequestException] {
      Write-Verbose "Request failed with HttpRequestException"
      $retryReason = $_
      Write-Host "URL: " $request.RequestUri
      Write-Host "EXCEPTION: " $_.Exception
    } catch [System.Threading.Tasks.TaskCanceledException] {
      Write-Verbose "Request failed with TaskCanceledException"
      $retryReason = "SignPath REST API answer time exceeded the timeout ($($HttpClient.Timeout))"
      Write-Host "URL: " $request.RequestUri
      Write-Host "EXCEPTION: " $_.Exception
    } finally {
      Write-Verbose "Disposing request"
      if ($null -ne $request) {
        $request.Dispose()
      }
    }

    Write-Verbose "Retry reason: $retryReason"

    if (($sw.Elapsed.TotalSeconds + $serviceUnavailableRetryTimeoutInSeconds) -lt $ServiceUnavailableTimeoutInSeconds) {
      Write-Host "SignPath REST API call failed. Retrying in ${serviceUnavailableRetryTimeoutInSeconds}s..."
      Start-Sleep -Seconds $serviceUnavailableRetryTimeoutInSeconds
    } else {
      Write-Host "SignPath REST API could not be called successfully in $($retry + 1) tries. Aborting"
      throw $retryReason
    }

    $retry++
  }
}

function DownloadArtifact (
  [System.Net.Http.HttpClient] $httpClient,
  [string] $url,
  [string] $path,
  [int] $serviceUnavailableRetryTimeoutInSeconds) {

  $downloadResponse = $null
  $streamToWriteTo = $null
  try {
    Write-Host "Downloading signed artifact..."
    $downloadResponse = GetWithRetry `
      -HttpClient $httpClient `
      -Url $url `
      -ServiceUnavailableRetryTimeoutInSeconds $serviceUnavailableRetryTimeoutInSeconds
    CheckResponse $downloadResponse

    $pathWithoutFile = [System.IO.Path]::GetDirectoryName($path)
    [System.IO.Directory]::CreateDirectory($pathWithoutFile) | Out-Null

    $stream = $downloadResponse.Content.ReadAsStreamAsync().GetAwaiter().GetResult()
    $streamToWriteTo = [System.IO.File]::Open($path, 'Create')
    $stream.CopyToAsync($streamToWriteTo).GetAwaiter().GetResult() | Out-Null
    Write-Host "Downloaded signed artifact and saved at '$path'"
  } finally {
    if ((Test-Path variable:downloadResponse) -and $null -ne $downloadResponse) {
      $downloadResponse.Dispose()
    }

    if ((Test-Path variable:stream) -and $null -ne $stream) {
      $stream.Dispose()
    }

    if ((Test-Path variable:streamToWriteTo) -and $null -ne $streamToWriteTo) {
      $streamToWriteTo.Dispose()
    }
  }
}

function WaitForCompletion (
  [System.Net.Http.HttpClient] $httpClient,
  [string] $url,
  [int] $waitForCompletionTimeoutInSeconds,
  [int] $serviceUnavailableRetryTimeoutInSeconds) {

  $StatusComplete = "Completed"
  $StatusFailed = "Failed"
  $StatusDenied = "Denied"
  $StatusCanceled = "Canceled"
  $StatusArtifactRetrievalFailed = "ArtifactRetrievalFailed"

  $getResponse = $null
  try {
    $resultJson = $null
    $status = $null
    $sw = [System.Diagnostics.Stopwatch]::StartNew()
    do {
      Write-Host "Checking status... " -NoNewline

      $getResponse = GetWithRetry -HttpClient $httpClient -Url $url -ServiceUnavailableRetryTimeoutInSeconds $serviceUnavailableRetryTimeoutInSeconds

      CheckResponse $getResponse
      $resultJson = $getResponse.Content.ReadAsStringAsync().GetAwaiter().GetResult() | ConvertFrom-Json
      $status = $resultJson.status
      Write-Host $status

      if ($resultJson.isFinalStatus) {
        break
      }
      Start-Sleep -Seconds $waitForCompletionTimeoutInSeconds
    } while ($sw.Elapsed.TotalSeconds -lt $waitForCompletionTimeoutInSeconds)

    $timeoutExpired = $sw.Elapsed.TotalSeconds -ge $waitForCompletionTimeoutInSeconds
    if ($status -ne $StatusComplete) {
      if ($status -eq $StatusFailed) {
        throw "Terminating because signing request failed"
      } elseif($status -eq $StatusDenied) {
        throw "Terminating because signing request was denied"
      } elseif($status -eq $StatusCanceled) {
        throw "Terminating because signing request was canceled"
      } elseif($status -eq $StatusArtifactRetrievalFailed) {
        throw "Terminating because artifact retrieval failed"
      } elseif($timeoutExpired) {
        throw "Timeout expired while waiting for signing request to complete"
      } else {
        throw "Terminating because of unexpected signing request status: $status"
      }
    }

    return $resultJson.signedArtifactLink
  } finally {
    if ((Test-Path variable:getResponse) -and $null -ne $getResponse) {
      $getResponse.Dispose()
    }
  }
}

function CreateAndUseAuthorizedHttpClient ([string] $cIUserToken, [int] $timeout, [ScriptBlock] $scriptBlock, [System.Security.Cryptography.X509Certificates.X509Certificate2] $clientCertificate) {
  Add-Type -AssemblyName System.IO
  Add-Type -AssemblyName System.Net.Http

  $previousSecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol
  [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.SecurityProtocolType]::Tls12

  $httpClientHandler = New-Object System.Net.Http.HttpClientHandler
  if ($null -ne $clientCertificate) {
    if (-not $clientCertificate.HasPrivateKey) {
      throw "The given client certificate has not private key and therefore cannot be used as client certificate."
    }

    Write-Verbose "Adding HttpClient client certificate: $clientCertificate"
    $httpClientHandler.ClientCertificates.Add($clientCertificate) | Out-Null
  }

  $httpClient = New-Object System.Net.Http.HttpClient $httpClientHandler
  $httpClient.Timeout = [TimeSpan]::FromSeconds($timeout)
  $httpClient.DefaultRequestHeaders.Authorization = New-Object System.Net.Http.Headers.AuthenticationHeaderValue @("Bearer", $cIUserToken)

  try {
    & $scriptBlock $httpClient
  } finally {
    if ($null -ne $httpClient) {
      $httpClient.Dispose()
    }
    [System.Net.ServicePointManager]::SecurityProtocol = $previousSecurityProtocol
  }
}

function PrepareInputArtifactPath ([string] $inputArtifactPath) {
  $inputArtifactPath = NormalizePath $inputArtifactPath

  if (-not (Test-Path -Path $inputArtifactPath)) {
    throw "The input artifact path '$inputArtifactPath' does not exist"
  }
  return $inputArtifactPath
}

function PrepareOutputArtifactPath ([bool] $force, [string] $outputArtifactPath) {
  $outputArtifactPath = NormalizePath $outputArtifactPath

  if (-not $force -and (Test-Path -Path $outputArtifactPath)) {
    throw "There is already a file at '$outputArtifactPath'. If you want to overwrite it use the -Force switch"
  }
  return $outputArtifactPath
}

function NormalizePath ([string] $path) {
  if (-not [System.IO.Path]::IsPathRooted($path)) {
    return Join-Path $PWD $path
  }
  return $path
}

function CheckResponse ([System.Net.Http.HttpResponseMessage] $response) {
  Write-Verbose "Checking response: $response"
  if (-not $response.IsSuccessStatusCode) {
    Write-Verbose "No success response."
    $responseBody = $response.Content.ReadAsStringAsync().GetAwaiter().GetResult()

    $additionalReason = ""
    if (401 -eq $response.StatusCode) {
      $additionalReason = " Did you provide the correct CIUserToken?"
    }
    elseif(403 -eq $response.StatusCode) {
      $additionalReason = " Did you add the CI user to the list of submitters in the specified signing policy? Did you provide the correct OrganizationId? In case you are using a trusted build system, did you link it to the specified project?"
    }

    $serverMessage = ""
    if ($responseBody -ne "") {
      $serverMessage = " (Server reported the following message: '" + $responseBody + "')"
    }

    $errorMessage = "Error {0} {1}.{2}{3}" -f $response.StatusCode.value__, $response.ReasonPhrase, $additionalReason, $serverMessage

    throw [System.Net.Http.HttpRequestException]$errorMessage
  }
}

Export-ModuleMember Submit-SigningRequest
Export-ModuleMember Get-SignedArtifact
# SIG # Begin signature block
# MIIeGgYJKoZIhvcNAQcCoIIeCzCCHgcCAQExDzANBglghkgBZQMEAgEFADB5Bgor
# BgEEAYI3AgEEoGswaTA0BgorBgEEAYI3AgEeMCYCAwEAAAQQH8w7YFlLCE63JNLG
# KX7zUQIBAAIBAAIBAAIBAAIBADAxMA0GCWCGSAFlAwQCAQUABCBa6APjriHomUqr
# qGqmoGViwzg8FW5/NkW03fuFqUgOm6CCDakwggNfMIICR6ADAgECAgsEAAAAAAEh
# WFMIojANBgkqhkiG9w0BAQsFADBMMSAwHgYDVQQLExdHbG9iYWxTaWduIFJvb3Qg
# Q0EgLSBSMzETMBEGA1UEChMKR2xvYmFsU2lnbjETMBEGA1UEAxMKR2xvYmFsU2ln
# bjAeFw0wOTAzMTgxMDAwMDBaFw0yOTAzMTgxMDAwMDBaMEwxIDAeBgNVBAsTF0ds
# b2JhbFNpZ24gUm9vdCBDQSAtIFIzMRMwEQYDVQQKEwpHbG9iYWxTaWduMRMwEQYD
# VQQDEwpHbG9iYWxTaWduMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA
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