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,

  # 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

      if($WaitForCompletion.IsPresent) {

        $downloadUrl = WaitForCompletion `
          -HttpClient $defaultHttpClient `
          -Url $getUrl `
          -WaitForCompletionTimeoutInSeconds $WaitForCompletionTimeoutInSeconds `
          -ServiceUnavailableRetryTimeoutInSeconds $ServiceUnavailableRetryTimeoutInSeconds

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

      $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 `
        -UploadAndDownloadRequestTimeoutInSeconds $UploadAndDownloadRequestTimeoutInSeconds
    }
  }
}

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) {

  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"

  $requestFactory = {
    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
        }
      }
    }

    $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"
      }

      $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,
  [int] $UploadAndDownloadRequestTimeoutInSeconds) {

  $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 $WaitForCompletionRetryTimeoutInSeconds
    } 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?";
    }

    $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
# MIIiTgYJKoZIhvcNAQcCoIIiPzCCIjsCAQExDzANBglghkgBZQMEAgEFADB5Bgor
# BgEEAYI3AgEEoGswaTA0BgorBgEEAYI3AgEeMCYCAwEAAAQQH8w7YFlLCE63JNLG
# KX7zUQIBAAIBAAIBAAIBAAIBADAxMA0GCWCGSAFlAwQCAQUABCD2NSPtFqeUN7js
# w6ZIduXNWbD7tTdSpALAldx+6NE6maCCEhEwggN1MIICXaADAgECAgsEAAAAAAEV
# S1rDlDANBgkqhkiG9w0BAQUFADBXMQswCQYDVQQGEwJCRTEZMBcGA1UEChMQR2xv
# YmFsU2lnbiBudi1zYTEQMA4GA1UECxMHUm9vdCBDQTEbMBkGA1UEAxMSR2xvYmFs
# U2lnbiBSb290IENBMB4XDTk4MDkwMTEyMDAwMFoXDTI4MDEyODEyMDAwMFowVzEL
# MAkGA1UEBhMCQkUxGTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsT
# B1Jvb3QgQ0ExGzAZBgNVBAMTEkdsb2JhbFNpZ24gUm9vdCBDQTCCASIwDQYJKoZI
# hvcNAQEBBQADggEPADCCAQoCggEBANoO5pmNzqPjT4p++/GLgyVr6kgf8SqwuZUR
# BL3wY9HiZ2bPHN3PG0gr7o2JjpqvKYBlq+nHLRLLqxxMcAehPQowzRWNT/jd1IxQ
# FRzvUO7ELvf86VLykX3gbdU1MI5eQ3PyQenVauOyiTpWOThvBjyIaVsqTcWnVLhs
# icyb+TzK5f2J9RI8kniW1tx0bpNEYdGNx0aydQ6G6BmK1W1s1X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