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"

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

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

  $submitUrl = [string]::Join("/", @($ApiUrl.Trim("/"), $OrganizationId, "SigningRequests"))
  $requestFactory = CreateSubmitRequestFactory `
    -url $submitUrl `
    -artifactConfigurationId $ArtifactConfigurationId `
    -signingPolicyId $SigningPolicyId `
    -projectSlug $ProjectSlug `
    -artifactConfigurationSlug $ArtifactConfigurationSlug `
    -signingPolicySlug $SigningPolicySlug `
    -description $Description `
    -inputArtifactPath $InputArtifactPath `
    -origin $Origin `
    -parameters $Parameters

  return SubmitHelper "Submit" "Submitted" $requestFactory `
    -ciUserToken $CIUserToken `
    -clientCertificate $ClientCertificate `
    -defaultHttpClientTimeoutInSeconds $DefaultHttpClientTimeoutInSeconds `
    -uploadAndDownloadRequestTimeoutInSeconds $UploadAndDownloadRequestTimeoutInSeconds `
    -waitForCompletionTimeoutInSeconds $WaitForCompletionTimeoutInSeconds `
    -waitForCompletion $WaitForCompletion.IsPresent `
    -outputArtifactPath $OutputArtifactPath `
    -force $Force.IsPresent
}

function Submit-SigningRequestResubmit (
# 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 original signing request's ID of that should be resubmitted.
  [Parameter(Mandatory)]
  [ValidateNotNullOrEmpty()]
  [string] $OriginalSigningRequestId,

# The new signing policy to be used for the resubmitted signing request. The most common use case is to resubmit a test-signed signing request with a release signing policy in order to apply a release certificate.
  [Parameter(Mandatory)]
  [ValidateNotNullOrEmpty()]
  [string] $SigningPolicySlug,

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

# 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).
  [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
    Resubmits a signing request that already exists via the SignPath REST API.
  .DESCRIPTION
    The Submit-SigningRequestResubmit cmdlet resubmits an existing signing request on SignPath.
    Usually you use it to resubmit a signing request originally signed with a test signing policy to be signed with a release signing policy.
 
    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-SigningRequestResubmit
      -CIUserToken /Joe3s2m7hkhVyoba4H4weqj9UxIk6nKRXGhGbH7nv4=
      -OrganizationId 1c0ab26c-12f3-4c6e-a043-2568e133d2de
      -OriginalSigningRequestId acac9100-45a3-4a79-a5a0-bf9066f0fe84
      -SigningPolicySlug ReleaseSigningPolicy
      -WaitForCompletion
      -OutputArtifactPath MyApplication.signed.msi
  .OUTPUTS
    Returns the SigningRequestId which can be used with Get-SignedArtifact
  .NOTES
    Author: SignPath GmbH
  #>


  Set-StrictMode -Version 2.0

  if ($WaitForCompletion.IsPresent -and $OutputArtifactPath.Length -eq 0) {
    throw "If you wait for completion and download the signed artifact you must pass in an OutputArtifactPath"
  }

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

  $resubmitUrl = [string]::Join("/", @($ApiUrl.Trim("/"), $OrganizationId, "SigningRequests", "Resubmit"))
  $requestFactory = CreateResubmitRequestFactory `
    -url $resubmitUrl `
    -originalSigningRequestId $OriginalSigningRequestId `
    -signingPolicySlug $SigningPolicySlug `
    -description $Description

  return SubmitHelper "Resubmit" "Resubmitted" $requestFactory `
    -ciUserToken $CIUserToken `
    -clientCertificate $ClientCertificate `
    -defaultHttpClientTimeoutInSeconds $DefaultHttpClientTimeoutInSeconds `
    -uploadAndDownloadRequestTimeoutInSeconds $UploadAndDownloadRequestTimeoutInSeconds `
    -waitForCompletionTimeoutInSeconds $WaitForCompletionTimeoutInSeconds `
    -waitForCompletion $WaitForCompletion.IsPresent `
    -outputArtifactPath $OutputArtifactPath `
    -force $Force.IsPresent
}

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 `
        -WaitForCompletionRetryTimeoutInSeconds $WaitForCompletionRetryTimeoutInSeconds `
        -ServiceUnavailableRetryTimeoutInSeconds $ServiceUnavailableRetryTimeoutInSeconds

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

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

function SubmitHelper ([string] $verb,
                       [string] $verbPastTense,
                       [ScriptBlock] $requestFactory,
                       [string] $ciUserToken,
                       [System.Security.Cryptography.X509Certificates.X509Certificate2] $clientCertificate,
                       [int] $defaultHttpClientTimeoutInSeconds,
                       [int] $uploadAndDownloadRequestTimeoutInSeconds,
                       [int] $waitForCompletionTimeoutInSeconds,
                       [bool] $waitForCompletion,
                       [string] $outputArtifactPath,
                       [bool] $force) {
  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 ($waitForCompletion) {
        $outputArtifactPath = PrepareOutputArtifactPath $force $outputArtifactPath
        Write-Verbose "Will write output artifact to: $outputArtifactPath"
      }

      $response = $null
      try {
        Write-Verbose "$verb signing request..."
        $response = SendWithRetry `
          -HttpClient $HttpClient `
          -RequestFactory $requestFactory `
          -ServiceUnavailableRetryTimeoutInSeconds $ServiceUnavailableRetryTimeoutInSeconds
        CheckResponse $response

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

      if ($waitForCompletion) {
        $downloadUrl = WaitForCompletion `
          -HttpClient $defaultHttpClient `
          -Url $getUrl `
          -WaitForCompletionTimeoutInSeconds $waitForCompletionTimeoutInSeconds `
          -WaitForCompletionRetryTimeoutInSeconds $WaitForCompletionRetryTimeoutInSeconds `
          -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 CreateSubmitRequestFactory (
  [string] $url,
  [string] $artifactConfigurationId,
  [string] $signingPolicyId,
  [string] $projectSlug,
  [string] $artifactConfigurationSlug,
  [string] $signingPolicySlug,
  [string] $description,
  [string] $inputArtifactPath,
  [Hashtable] $origin,
  [Hashtable] $parameters
) {
  $local:IsVerboseEnabled = $null -ne $PSCmdlet.MyInvocation.BoundParameters["Verbose"] -and $PSCmdlet.MyInvocation.BoundParameters["Verbose"].IsPresent

  return {
    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()
}

function CreateResubmitRequestFactory (
  [string] $url,
  [string] $originalSigningRequestId,
  [string] $signingPolicySlug,
  [string] $description
) {
  $local:IsVerboseEnabled = $null -ne $PSCmdlet.MyInvocation.BoundParameters["Verbose"] -and $PSCmdlet.MyInvocation.BoundParameters["Verbose"].IsPresent

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

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

    try {

      Write-Verbose "OriginalSigningRequestId: $originalSigningRequestId"
      $originalSigningRequestIdContent = New-Object System.Net.Http.StringContent $originalSigningRequestId
      $content.Add($originalSigningRequestIdContent, "OriginalSigningRequestId")

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

      $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()
}

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

  $StatusComplete = "Completed"
  $StatusFailed = "Failed"
  $StatusDenied = "Denied"
  $StatusCanceled = "Canceled"
  $WorkflowStatusArtifactRetrievalFailed = "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
      $workflowStatus = $resultJson.workflowStatus
      Write-Host $status

      if ($resultJson.isFinalStatus) {
        break
      }

      Write-Verbose "Waiting for $waitForCompletionRetryTimeoutInSeconds seconds until checking again..."
      Start-Sleep -Seconds $waitForCompletionRetryTimeoutInSeconds
    } while ($sw.Elapsed.TotalSeconds -lt $waitForCompletionTimeoutInSeconds)

    $timeoutExpired = $sw.Elapsed.TotalSeconds -ge $waitForCompletionTimeoutInSeconds
    if ($status -ne $StatusComplete) {
      if ($status -eq $StatusDenied) {
        throw "Terminating because signing request was denied"
      } elseif ($status -eq $StatusCanceled) {
        throw "Terminating because signing request was canceled"
      } elseif ($workflowStatus -eq $WorkflowStatusArtifactRetrievalFailed) {
        throw "Terminating because artifact retrieval failed"
      } elseif ($status -eq $StatusFailed) {
        throw "Terminating because signing request 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 Submit-SigningRequestResubmit
Export-ModuleMember Get-SignedArtifact
# SIG # Begin signature block
# MIIiggYJKoZIhvcNAQcCoIIiczCCIm8CAQExDzANBglghkgBZQMEAgEFADB5Bgor
# BgEEAYI3AgEEoGswaTA0BgorBgEEAYI3AgEeMCYCAwEAAAQQH8w7YFlLCE63JNLG
# KX7zUQIBAAIBAAIBAAIBAAIBADAxMA0GCWCGSAFlAwQCAQUABCDz7ONc1hWrsR5P
# GlIZxB7waaS87pTyRdHHj61djpNt26CCEhEwggN1MIICXaADAgECAgsEAAAAAAEV
# S1rDlDANBgkqhkiG9w0BAQUFADBXMQswCQYDVQQGEwJCRTEZMBcGA1UEChMQR2xv
# YmFsU2lnbiBudi1zYTEQMA4GA1UECxMHUm9vdCBDQTEbMBkGA1UEAxMSR2xvYmFs
#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