SignPathDocker.psm1

#Requires -PSEdition Core
#Requires -Modules SignPath

Set-StrictMode -Version Latest
$ErrorActionPreference = "Stop"

################################################################################
# Initialize-DockerSigning
################################################################################

function Initialize-DockerSigning (
  # The name of the Docker repository (<registry>/<namespace>/<name>).
  [Parameter(Mandatory)]
  [ValidateNotNullOrEmpty()]
  [string] $Repository,

  # Delegation name
  [Parameter()]
  [ValidateNotNullOrEmpty()]
  [string] $DelegationName = "signpath",

  # If a certificate is given, Add-DelegationCertificate will also be executed.
  [ValidateNotNullOrEmpty()]
  [string] $DelegationCertificatePath,

  # The URL to the Notary Service. If empty, the environment variable DOCKER_CONTENT_TRUST_SERVER is used as a
  # fallback, if also empty, the Docker Notary Service URL 'https://notary.docker.io' is used.
  [Parameter()]
  [string] $NotaryUrl,

  # A username authorized to push to the given Docker repository. If not set, the NOTARY_AUTH environment variable
  # is used as a fallback.
  [Parameter()]
  [string] $NotaryUsername,

  # The password for the given NotaryUsername. If not set, the NOTARY_AUTH environment variable is used as a
  # fallback.
  [Parameter()]
  [SecureString] $NotaryPassword,

  # Provide this to always overwrite the resulting root certificate file for the repository, if it already exists
  [Parameter()]
  [switch] $ForceOverwriteRootCertificate = $false,

  # If the flag is set and the repository already exists at the Notary Service, the repository is re-initialized (i.e., deleted and recreated).
  [Parameter()]
  [switch] $ForceReinitializeRepository = $false
) {
<#
  .SYNOPSIS
    Initializes a new Notary repository.
  .DESCRIPTION
    Initializes a Notary repository with the given repository name. If an existing Notary root key is found locally it is reused.
    If you provide -DelegationCertificatePath, the behavior of the command Add-DelegationCertificate will be executed after a successfull initialization.
    You can delete and reinitialize an existing Notary repository by specifying -ForceReinitializeRepository. Mind that existing signatures are dropped when doing so.
    After the repository was created successfully, the root certificate is extracted (see the Get-RootCertificate command for details).
  .EXAMPLE
  Initialize-DockerSigning `
      -Repository "docker.io/namespace/imagename" `
      -NotaryUsername "username" `
      -NotaryPassword (ConvertTo-SecureString -string "password" -AsPlainText)
  .OUTPUTS
    After a successfull creation of the Notary repository its root certificate will be extracted and saved to a file.
  .NOTES
    Author: SignPath GmbH
  #>


  $repositoryInfo = ParseRepository $Repository
  $notaryUrl = GetNotaryUrl $NotaryUrl
  $notaryBasicAuthCredentials = PrepareNotaryCredentials $NotaryUsername $NotaryPassword
  $trustDir = GetTrustDir

  Write-Verbose "Notary URL: $notaryUrl"

  $rootCertificateFilePath = GetRootCertificateFilePath $repositoryInfo
  if((Test-Path $rootCertificateFilePath -PathType Leaf) -and -not $ForceOverwriteRootCertificate) {
    throw "$rootCertificateFilePath already exists. Provide -ForceOverwriteRootCertificate if you want to replace it"
  }

  try {
    PrepareNotaryAuthentication $notaryBasicAuthCredentials

    $repositoryExists = CheckIfRepositoryExists $notaryUrl $trustDir $repositoryInfo

    if ($repositoryExists -and -not $ForceReinitializeRepository) {
      throw "Repository '$($repositoryInfo.FullName)' already exists. Recreating it would remove the existing keys. Use -ForceReinitializeRepository to init anyways."
    }

    if ($repositoryExists -and $ForceReinitializeRepository) {
      Write-Host "Repository '$($repositoryInfo.FullName)' will be reinitialized"
      dockernotary $notaryUrl $trustDir @{} "delete" $repositoryInfo.FullName "--remote"
      $pathToLocalRepository = Join-Path $trustDir "tuf" $repositoryInfo.Registry $repositoryInfo.Namespace $repositoryInfo.Name
    }

    dockernotary $notaryUrl $trustDir @{} "init" $repositoryInfo.FullName

    Write-Host "`nRotate snapshot key responsibility to the notary server"
    dockernotary $notaryUrl $trustDir @{ 1 = "Could not rotate the snapshot key. Does the repository exist?" } "key" "rotate" $repositoryInfo.FullName "snapshot" "-r"

    Write-Host "`nPublish the newly created repository to the notary"
    dockernotary $notaryUrl $trustDir @{} "publish" $repositoryInfo.FullName

    ExtractRootCertificate $trustDir $repositoryInfo $ForceOverwriteRootCertificate
  } finally {
    CleanupNotaryAuthentication
  }

  if(-not [string]::IsNullOrEmpty($DelegationCertificatePath)) {
    Add-DelegationCertificate `
      -Repository $Repository `
      -DelegationName $DelegationName `
      -NotaryUsername $NotaryUsername `
      -NotaryPassword $NotaryPassword `
      -DelegationCertificatePath $DelegationCertificatePath `
      -NotaryUrl $NotaryUrl
  }
}

################################################################################
# Add-DelegationCertificate
################################################################################

function Add-DelegationCertificate (
  # The name of the Docker repository (<registry>/<namespace>/<name>).
  [Parameter(Mandatory)]
  [ValidateNotNullOrEmpty()]
  [string] $Repository,

  # Delegation name
  [Parameter()]
  [ValidateNotNullOrEmpty()]
  [string] $DelegationName = "signpath",

  # The given certificate will be registered as the delegation key for the roles 'targets/<DelegationName>' and 'targets/releases' in the given repository.
  [Parameter(Mandatory)]
  [ValidateNotNullOrEmpty()]
  [string] $DelegationCertificatePath,

  # The URL to the Notary Service. If empty, the environment variable DOCKER_CONTENT_TRUST_SERVER is used as a
  # fallback, if also empty, the Docker Notary Service URL 'https://notary.docker.io' is used.
  [Parameter()]
  [string] $NotaryUrl,

  # A username authorized to push to the given Docker repository. If not set, the NOTARY_AUTH environment variable
  # is used as a fallback.
  [Parameter()]
  [string] $NotaryUsername,

  # The password for the given NotaryUsername. If not set, the NOTARY_AUTH environment variable is used as a
  # fallback.
  [Parameter()]
  [SecureString] $NotaryPassword
) {
<#
  .SYNOPSIS
    Adds a delegation certificate to an existing notary repository, so the referenced private key can be used for signing docker images.
  .DESCRIPTION
    Adds the certificate provided with -DelegationCertificatePath to the given Notary repository as a delegation, if the repository exists.
    Based on how docker expects delegations to be set up, there will be two delegations: the delegation will be added to the 'targets/releases' role
    and the 'targets/<DelegationName>' role.
    The provided certificate file can either be in the DER format or the PEM format.
  .EXAMPLE
    Add-DelegationCertificate `
      -Repository "docker.io/namespace/imagename" `
      -NotaryUsername "username" `
      -NotaryPassword (ConvertTo-SecureString -string "password" -AsPlainText) `
      -DelegationCertificatePath "path/to/certificatefile"
  .OUTPUTS
    If the command succeeded, the two delegations are listed.
  .NOTES
    Author: SignPath GmbH
  #>


  $repositoryInfo = ParseRepository $Repository
  $notaryUrl = GetNotaryUrl $NotaryUrl
  $notaryBasicAuthCredentials = PrepareNotaryCredentials $NotaryUsername $NotaryPassword
  $trustDir = GetTrustDir

  $validDelegationCertificatePath = PrepareDelegationCertificate $DelegationCertificatePath

  try {

    PrepareNotaryAuthentication $notaryBasicAuthCredentials

    dockernotary $notaryUrl $trustDir @{} -SuppressOutput "delegation" "add" $repositoryInfo.FullName "targets/releases" $validDelegationCertificatePath "--all-paths"
    dockernotary $notaryUrl $trustDir @{} -SuppressOutput "delegation" "add" $repositoryInfo.FullName "targets/$DelegationName" $validDelegationCertificatePath "--all-paths"

    Write-Host "$([Environment]::NewLine)Publish the newly created two delegation keys to the notary"
    dockernotary $notaryUrl $trustDir @{} "publish" $repositoryInfo.FullName
    dockernotary $notaryUrl $trustDir @{} -SuppressOutput "delegation" "list" $repositoryInfo.FullName
  } finally {
    CleanupNotaryAuthentication
  }
}

################################################################################
# Get-RootCertificate
################################################################################

function Get-RootCertificate (
  # The name of the Docker repository (<registry>/<namespace>/<name>).
  [Parameter(Mandatory)]
  [ValidateNotNullOrEmpty()]
  [string] $Repository,

  # The URL to the Notary Service. If empty, the environment variable DOCKER_CONTENT_TRUST_SERVER is used as a
  # fallback, if also empty, the Docker Notary Service URL 'https://notary.docker.io' is used.
  [Parameter()]
  [string] $NotaryUrl,

  # A username authorized to push to the given Docker repository. If not set, the NOTARY_AUTH environment variable
  # is used as a fallback.
  [Parameter()]
  [string] $NotaryUsername,

  # The password for the given NotaryUsername. If not set, the NOTARY_AUTH environment variable is used as a
  # fallback.
  [Parameter()]
  [SecureString] $NotaryPassword,

  # Provide this to always overwrite the root certificate of the repository, if it already exists.
  [Parameter()]
  [switch] $ForceOverwriteRootCertificate = $false
) {
<#
  .SYNOPSIS
    Extracts the root certificate as a PEM-formatted file from an existing notary repository.
  .DESCRIPTION
    You can use this command to retrieve the repository's root certificate.
    It downloads the current state of the Notary repository and extracts the certificate in the PEM format into the current directory.
    If you want to overwrite a file with the same name, provide the switch -ForceOverwriteRootCertificate.
  .EXAMPLE
  Get-RootCertificate `
      -Repository "docker.io/namespace/imagename" `
      -NotaryUsername "username" `
      -NotaryPassword (ConvertTo-SecureString -string "password" -AsPlainText)
  .OUTPUTS
    A file with the name <registry>_<namespace>_<name>.RootCertificate.pem, which contains the Notary repository root certificate encoded as PEM.
  .NOTES
    Author: SignPath GmbH
  #>


  $repositoryInfo = ParseRepository $Repository
  $notaryUrl = GetNotaryUrl $NotaryUrl
  $notaryBasicAuthCredentials = PrepareNotaryCredentials $NotaryUsername $NotaryPassword
  $trustDir = GetTrustDir

  $rootCertificateFilePath = GetRootCertificateFilePath $repositoryInfo
  if((Test-Path $rootCertificateFilePath -PathType Leaf) -and -not $ForceOverwriteRootCertificate) {
    throw "$rootCertificateFilePath already exists. Provide -ForceOverwriteRootCertificate if you want to replace it"
  }

  try {
    PrepareNotaryAuthentication $notaryBasicAuthCredentials

    $repositoryExists = CheckIfRepositoryExists $notaryUrl $trustDir $repositoryInfo

    if (-not $repositoryExists) {
      throw "Repository '$($repositoryInfo.FullName)' does not exist."
    }

    Write-Host "Loading repository $($repositoryInfo.FullName)"
    dockernotary $notaryUrl $trustDir @{} "list" $repositoryInfo.FullName

    ExtractRootCertificate $trustDir $repositoryInfo $ForceOverwriteRootCertificate
  } finally {
    CleanupNotaryAuthentication
  }
}

################################################################################
# Invoke-DockerSigning
################################################################################

function Invoke-DockerSigning (
  # The name of the Docker repository (<registry>/<namespace>/<name>).
  [Parameter(Mandatory)]
  [ValidateNotNullOrEmpty()]
  [string] $Repository,

  # All Docker image tags that you want to sign, at least 1 (all of them must point to the same image)
  [Parameter(Mandatory)]
  [ValidateNotNullOrEmpty()]
  [string[]] $Tags,

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

  # The URL to the Docker Registry. If empty it is extracted from the $Repository parameter. If the repository
  # states "docker.io" as registry, we hardcode the URL to 'https://registry-1.docker.io'.
  [Parameter()]
  [string] $RegistryUrl,

  # A username authorized to read metadata of the given Docker repository. If not set, the REGISTRY_AUTH
  # environment variable is used as a fallback.
  [Parameter()]
  [string] $RegistryUsername,

  # The password for the given RegistryUsername. If not set, the REGISTRY_AUTH environment variable is used as a
  # fallback.
  [Parameter()]
  [SecureString] $RegistryPassword,

  # The URL to the Notary Service. If empty, the environment variable DOCKER_CONTENT_TRUST_SERVER is used as a
  # fallback, if also empty, the Docker Notary Service URL 'https://notary.docker.io' is used.
  [Parameter()]
  [string] $NotaryUrl,

  # A username authorized to push to the given Docker repository. If not set, the NOTARY_AUTH environment variable
  # is used as a fallback.
  [Parameter()]
  [string] $NotaryUsername,

  # The password for the given NotaryUsername. If not set, the NOTARY_AUTH environment variable is used as a
  # fallback.
  [Parameter()]
  [SecureString] $NotaryPassword,

  # The SignPath CI user's API token.
  [Parameter(Mandatory)]
  [ValidateNotNullOrEmpty()]
  [string] $CIUserToken,

  # The ID of your SignPath organization.
  # 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 slug of your SignPath project.
  [Parameter(Mandatory)]
  [string] $ProjectSlug,

  # Allows you to override the default artifact configuration of the project.
  [Parameter()]
  [string] $ArtifactConfigurationSlug,

  # The slug of your SignPath signing policy.
  [Parameter(Mandatory)]
  [string] $SigningPolicySlug,

  # An optional description of the signing operation that could be helpful for the approver.
  [Parameter()]
  [string] $Description,

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

  # The HTTP timeout used for the upload and download SignPath 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 (upload and download
  # have no specific timeouts). Defaults to 600 seconds.
  [Parameter()]
  [int] $WaitForCompletionTimeoutInSeconds = 600
) {
  <#
  .SYNOPSIS
    Creates signed Docker TUF metadata via the SignPath REST API and pushes it to the given Notary Service.
  .DESCRIPTION
    The Invoke-DockerSigning cmdlet
     - creates a SignPath Docker signing data file
     - submits a SignPath signing request with the created SignPath Docker signing data file (via the SignPath REST
       API)
     - downloads the resulting signed artifact
     - extracts the signed Docker TUF metadata and pushes it to the Notary Service
    The New-DockerSigningData, Submit-SigningRequest and Push-SignedDockerSigningData can also be used individually
    for more detailed control over the process.
 
    To tweak HTTP related timing issues with the SignPath REST API use the parameters
    ServiceUnavailableNumberOfRetries and ServiceUnavailableRetryTimeoutInSeconds.
  .EXAMPLE
  Invoke-DockerSigning `
      -Repository "docker.io/library/alpine" `
      -Tags "latest" `
      -CIUserToken "aJoe3s2m7hkhVyoba4H4weqj9UxIk6nKRXGhGbH7nv4x2" `
      -OrganizationId "1c0ab26c-12f3-4c6e-a043-2568e133d2de" `
      -ProjectSlug "MyDockerProject" `
      -SigningPolicySlug "TestSigning"
  .OUTPUTS
    You can verify the results by setting DOCKER_CONTENT_TRUST=1 and performing a docker pull of the specified
    repository and tag. The latest signed image as stated by the Notary Service should be pulled, the image ID
    should match the image's ID you just signed.
  .NOTES
    Author: SignPath GmbH
  #>

  $ErrorActionPreference = "Stop"

  $tempDirectory = NewTemporaryDirectory
  try {
    $unsignedPackagePath = Join-Path $tempDirectory "docker-signing-data-file.zip"
    $signedPackagePath = Join-Path $tempDirectory "signed.zip"

    New-DockerSigningData -Repository $Repository `
                          -OutputArtifactPath $unsignedPackagePath `
                          -Tags $Tags `
                          -RegistryUrl $RegistryUrl `
                          -RegistryUsername $RegistryUsername `
                          -RegistryPassword $RegistryPassword `
                          -NotaryUrl $NotaryUrl `
                          -NotaryUsername $NotaryUsername `
                          -NotaryPassword $NotaryPassword

    Submit-SigningRequest -ApiUrl $ApiUrl `
                          -CiUserToken $CIUserToken `
                          -OrganizationId $OrganizationId `
                          -ProjectSlug $ProjectSlug `
                          -ArtifactConfigurationSlug $ArtifactConfigurationSlug `
                          -SigningPolicySlug $SigningPolicySlug `
                          -InputArtifactPath $unsignedPackagePath `
                          -OutputArtifactPath $signedPackagePath `
                          -Description $Description `
                          -ServiceUnavailableTimeoutInSeconds $ServiceUnavailableTimeoutInSeconds `
                          -UploadAndDownloadRequestTimeoutInSeconds $UploadAndDownloadRequestTimeoutInSeconds `
                          -WaitForCompletionTimeoutInSeconds $WaitForCompletionTimeoutInSeconds `
                          -WaitForCompletion

    Push-SignedDockerSigningData -Repository $Repository `
                                 -InputArtifactPath $signedPackagePath `
                                 -NotaryUrl $NotaryUrl `
                                 -NotaryUsername $NotaryUsername `
                                 -NotaryPassword $NotaryPassword
  }
  finally {
    Remove-Item $tempDirectory -Recurse -Force
  }
}

################################################################################
# New-DockerSigningData
################################################################################

function New-DockerSigningData (
  # The name of the docker repository (<registry>/<namespace>/<name>).
  [Parameter(Mandatory)]
  [ValidateNotNullOrEmpty()]
  [string] $Repository,

  # Specifies the path of the resulting SignPath Docker signing data file.
  [Parameter(Mandatory)]
  [ValidateNotNullOrEmpty()]
  [string] $OutputArtifactPath,

  # All Docker image tags that you want to sign, at least 1 (all of them must point to the same image)
  [Parameter(Mandatory)]
  [ValidateNotNullOrEmpty()]
  [string[]] $Tags,

  # The URL to the Docker Registry. If empty it is extracted from the $Repository parameter. If the repository
  # states "docker.io" as registry, we hardcode the URL to 'https://registry-1.docker.io'.
  [Parameter()]
  [string] $RegistryUrl,

  # A username authorized to read metadata of the given Docker repository. If not set, the REGISTRY_AUTH
  # environment variable is used as a fallback.
  [Parameter()]
  [string] $RegistryUsername,

  # The password for the given RegistryUsername. If not set, the REGISTRY_AUTH environment variable is used as a
  # fallback.
  [Parameter()]
  [SecureString] $RegistryPassword,

  # The URL to the Notary Service. If empty, the environment variable DOCKER_CONTENT_TRUST_SERVER is used as a
  # fallback, if also empty, the Docker Notary Service URL 'https://notary.docker.io' is used.
  [Parameter()]
  [string] $NotaryUrl,

  # A username authorized to push to the given Docker repository. If not set, the NOTARY_AUTH environment variable
  # is used as a fallback.
  [Parameter()]
  [string] $NotaryUsername,

  # The password for the given NotaryUsername. If not set, the NOTARY_AUTH environment variable is used as a
  # fallback.
  [Parameter()]
  [SecureString] $NotaryPassword
) {
  <#
  .SYNOPSIS
    Creates a SignPath Docker signing data file.
  .DESCRIPTION
    The New-DockerSigningData cmdlet creates a SignPath Docker signing data file ready for signing with SignPath.
  .EXAMPLE
  New-DockerSigningData
    -Repository "docker.io/library/alpine" `
    -OutputArtifactPath "MyDockerSigningData.zip"
    -Tags "latest"
  .OUTPUTS
    A SignPath Docker signing data file at the given OutputArtifactPath that is ready for signing with SignPath.
  .NOTES
    Author: SignPath GmbH
  #>

  $ErrorActionPreference = "Stop"

  $repositoryInfo = ParseRepository $Repository
  $outputArtifactPath = PrepareOutputArtifactPath $OutputArtifactPath
  $registryBasicAuthCredentails = PrepareRegistryCredentials $RegistryUsername $RegistryPassword $NotaryUsername $NotaryPassword
  $notaryBasicAuthCredentials = PrepareNotaryCredentials $NotaryUsername $NotaryPassword
  EnsureIsZipFile $outputArtifactPath

  UpdateLocalDockerTrustData $repositoryInfo $NotaryUrl $notaryBasicAuthCredentials

  $metadataFiles = [System.Collections.Generic.List[string]](CollectExistingMetadataFiles $Repository)

  $temporaryDockerSigningDataDirectory = NewTemporaryDirectory
  try {
    CopyMetadataFilesToDirectory $metadataFiles $temporaryDockerSigningDataDirectory

    $signingMetadataJson = Join-Path $temporaryDockerSigningDataDirectory "signingmetadata.json"
    $registryUrl = GetRegistryUrl $repositoryInfo $RegistryUrl
    Write-Verbose "Registry URL: $registryUrl"

    GenerateSigningMetadata $signingMetadataJson $Tags $repositoryInfo $registryUrl $registryBasicAuthCredentails

    Write-Verbose "Creating SignPath Docker signing data file from collected files..."
    $temporaryDockerSigningDataDirectoryWithoutRoot = Join-Path $temporaryDockerSigningDataDirectory "*"
    Compress-Archive -Path $temporaryDockerSigningDataDirectoryWithoutRoot -DestinationPath $outputArtifactPath
  }
  finally {
    # Note: this code path is uncovered, as we cannot know in a test which directory is created by the script
    Remove-Item $temporaryDockerSigningDataDirectory -Recurse -Force
  }

  Write-Host "Successfully created SignPath Docker signing data file '$outputArtifactPath'."
}

################################################################################
# Push-SignedDockerSigningData
################################################################################

function Push-SignedDockerSigningData (
  # The name of the Docker repository (<registry>/<namespace>/<name>).
  [Parameter(Mandatory)]
  [ValidateNotNullOrEmpty()]
  [string] $Repository,

  # Specifies the path of the signed SignPath Docker signing data file.
  [Parameter(Mandatory)]
  [ValidateNotNullOrEmpty()]
  [string] $InputArtifactPath,

  # The URL to the Notary Service. If empty, the environment variable DOCKER_CONTENT_TRUST_SERVER is used as a
  # fallback, if also empty, the Docker Notary Service URL 'https://notary.docker.io' is used.
  [Parameter()]
  [string] $NotaryUrl,

  # A username authorized to push to the given Docker repository. If not set, the NOTARY_AUTH environment variable
  # is used as a fallback.
  [Parameter()]
  [string] $NotaryUsername,

  # The password for the given NotaryUsername. If not set, the NOTARY_AUTH environment variable is used as a
  # fallback.
  [Parameter()]
  [SecureString] $NotaryPassword
) {
  <#
  .SYNOPSIS
    Extracts signed Docker TUF metadata out of a signed SignPath Docker signing data file and pushes it to a Notary
    Service.
  .DESCRIPTION
    The Push-SignedDockerSigningData cmdlet pushes signed Docker TUF metadata to the Notary Service and thereby
    updates the up-to-date image versions for clients that have DOCKER_CONTENT_TRUST set to 1.
  .EXAMPLE
  Push-SignedDockerSigningData `
      -Repository $repository `
      -InputArtifactPath "signed.zip"
  .OUTPUTS
    You can verify the results by setting DOCKER_CONTENT_TRUST=1 and performing a docker pull of the specified
    repository and tag. The latest signed image as stated by the Notary Service should be pulled, the image ID
    should match the image's ID you just signed.
  .NOTES
    Author: SignPath GmbH
  #>

  $ErrorActionPreference = "Stop"

  $repositoryInfo = ParseRepository $Repository
  $inputArtifactPath = PrepareInputArtifactPath $InputArtifactPath
  $notaryUrl = GetNotaryUrl $NotaryUrl
  $notaryBasicAuthCredentials = PrepareNotaryCredentials $NotaryUsername $NotaryPassword
  Write-Verbose "Notary URL: $notaryUrl"

  $tempDirectory = NewTemporaryDirectory
  try {
    Write-Verbose "Extracting signed SignPath Docker signing data file..."
    Expand-Archive $inputArtifactPath -DestinationPath $tempDirectory

    $targetsDirectory = Join-Path $tempDirectory "targets"

    if (-not (Test-Path $targetsDirectory)) {
      throw "Could not find targets files in signed package"
    }

    $delegationFiles = @()
    foreach ($file in (Get-ChildItem $targetsDirectory)) {
      $delegationName = $file.Name -replace ".json", ""
      $delegationFile = @{
        Path = $file.FullName
        Name = "targets/$delegationName"
      }
      $delegationFiles += $delegationFile
    }

    Write-Verbose "Pushing signed metadata files to Notary service..."
    PushFiles $notaryUrl $repositoryInfo $delegationFiles $notaryBasicAuthCredentials
  }
  finally {
    Remove-Item $tempDirectory -Recurse -Force
  }

  Write-Host "Successfully pushed signed metadata to Notary service."
}

################################################################################
# HELPER FUNCTIONS
################################################################################

function NewTemporaryDirectory {
  Write-Verbose "Creating temporary directory..."

  $parent = [System.IO.Path]::GetTempPath()
  [string] $name = [System.Guid]::NewGuid()
  $path = Join-Path $parent $name

  Write-Verbose "Temporary directory path: $path"
  return New-Item -ItemType Directory -Path $path
}

function ParseRepository ([string] $repository) {
  Write-Verbose "Parsing repository '$repository'..."

  $repositoryRegexResult = $repository | Select-String -Pattern "(?<registry>.*?)/((?<namespace>.*)/)?(?<name>.*)"
  if(!$repositoryRegexResult -or $repositoryRegexResult.Matches.Count -eq 0) {
    throw "Repository needs to be in format '<registry>/<namespace(s)>/<name>'."
  }

  $registry = $repositoryRegexResult.Matches[0].Groups["registry"].Value
  $namespace = $repositoryRegexResult.Matches[0].Groups["namespace"].Value
  $name = $repositoryRegexResult.Matches[0].Groups["name"].Value

  if([string]::IsNullOrEmpty($namespace)) {
    $namespaceUrlPart = "";
  } else {
    $namespaceUrlPart = "$namespace/"
  }

  Write-Verbose "Parsed registry: $registry"
  Write-Verbose "Parsed namespace: $namespace"
  Write-Verbose "Parsed name: $name"

  return @{
    Registry = $registry
    Namespace = $namespace
    NamespaceUrlPart = $namespaceUrlPart
    Name = $name
    FullName = $repository
  }
}

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

  if(Test-Path -Path $outputArtifactPath) {
    throw "There is already a file at '$outputArtifactPath'."
  }

  return $outputArtifactPath
}

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 NormalizePath ([string] $path) {
  if(-not [System.IO.Path]::IsPathRooted($path)) {
    # Note: this code path is uncovered, as we do not want to write to the $PWD directory (= current directory).
    return Join-Path $PWD $path
  }
  return $path
}

function EnsureIsZipFile ([string] $path) {
  if(-not $path.EndsWith(".zip")) {
    throw "The output artifact path must be a ZIP file."
  }
}

function GetRegistryUrl ($repositoryInfo, [string] $registryUrl) {
  if(-not [string]::IsNullOrEmpty($registryUrl)) {
    return $registryUrl
  } elseif ($repositoryInfo.Registry -eq "docker.io") {
    # Note: this code path is uncovered, as we cannot test that the real Registry is contacted by the script.
    return "https://registry-1.docker.io"
  } else {
    return "https://$($repositoryInfo.Registry)"
  }
}

function GetNotaryUrl ([string] $notaryUrl) {
  if(-not [string]::IsNullOrEmpty($notaryUrl)) {
    return $notaryUrl
  } elseif(-not [string]::IsNullOrEmpty($env:DOCKER_CONTENT_TRUST_SERVER)) {
    return $env:DOCKER_CONTENT_TRUST_SERVER
  } else {
    # Note: this code path is uncovered, as we cannot test that the real Notary is contacted by the script.
    return "https://notary.docker.io"
  }
}

function UpdateLocalDockerTrustData ($repositoryInfo, $notaryUrl, $notaryBasicAuthCredentials) {
  $notaryUrl = GetNotaryUrl $notaryUrl
  try {
    SetDockerContentTrustServerEnvironmentVariable $notaryUrl
    PrepareNotaryAuthentication $notaryBasicAuthCredentials

    docker trust inspect $repositoryInfo.FullName | Out-Null
  } finally {
    CleanupNotaryAuthentication
    CleanupDockerContentTrustServerEnvironmentVariable
  }
}

function CollectExistingMetadataFiles ([string] $repository) {
  Write-Verbose "Collecting existing metadata files..."

  $trustDir = GetTrustDir
  $tufDirectory = Join-Path $trustDir "tuf"
  if(-not [string]::IsNullOrEmpty($env:SignPathDockerSigningMetadataDirectory)) {
    $metadataDirectory = $env:SignPathDockerSigningMetadataDirectory
  } else {
    $metadataDirectory = Join-Path $tufDirectory $repository "metadata"
  }

  $metadataFiles = New-Object System.Collections.Generic.List[string]

  $rootJson = Join-Path $metadataDirectory "root.json"
  if(-not (Test-Path -Path $rootJson)) {
    throw "Required root.json file not found at '$rootJson'."
  }
  Write-Verbose "Collected root.json"
  $metadataFiles.Add($rootJson) | Out-Null

  $targetsJson = Join-Path $metadataDirectory "targets.json"
  if(-not (Test-Path -Path $targetsJson)) {
    throw "Required targets.json file not found at '$targetsJson'."
  }
  Write-Verbose "Collected targets.json"
  $metadataFiles.Add($targetsJson) | Out-Null

  $targetsDirectory = Join-Path $metadataDirectory "targets"

  if(Test-Path -Path $targetsDirectory) {
    $files = Get-ChildItem $targetsDirectory
    foreach ($file in $files) {
      $metadataFiles.Add($file.FullName) | Out-Null
      Write-Verbose "Collected $($file.Name)"
    }
  }

  return $metadataFiles
}

function CopyMetadataFilesToDirectory ($metadataFiles, $targetDirectory){
  $tempTargetsDir = Join-Path $targetDirectory "targets"

  foreach ($filePath in $metadataFiles) {
    if ((Get-Item $filePath) -is [System.IO.DirectoryInfo]) { continue }

    if ($filePath.Contains("targets\")) {
      if(-not (Test-Path $tempTargetsDir)) {
        New-Item -Path $tempTargetsDir -Type Directory | Out-Null
      }
      $tempTargetsFilePath = Join-Path $tempTargetsDir ([System.IO.Path]::GetFileName($filePath))
      Copy-Item $filePath $tempTargetsFilePath | Out-Null
    } else {
      Copy-Item $filePath $targetDirectory | Out-Null
    }
  }
}

function GenerateSigningMetadata ([string] $signingMetadataJson, $tags, $repositoryInfo, [string] $registryUrl, [string] $registryBasicAuthCredentials) {
  Write-Verbose "Generating JSON for signingmetadata.json..."

  $tagObjects = $tags | %{
    $manifest = GetManifest $registryUrl $repositoryInfo $_ $registryBasicAuthCredentials
    $hash = ParseDockerContentDigestHeader $manifest.Headers["Docker-Content-Digest"]
    $length = $manifest.Headers["Content-Length"]

    return "{ ""Name"": ""$_"", ""Hash"": ""$hash"", ""Length"": $length }"
  }
  $tagString = ($tagObjects -join ',' + [System.Environment]::NewLine + ' ')

  $expiresDate = (Get-Date).AddYears(3)
  $expiresDateString = Get-Date $expiresDate -format o

  $signingMetadataContent = @"
{
  "Tags": [
    $tagString
  ],
  "Expires": "$expiresDateString",
  "Repository": "$($repositoryInfo.FullName)",
  "SchemaVersion": "1.0"
}
"@


  Write-Verbose "Writing JSON to signingmetadata.json..."
  Write-Verbose $signingMetadataContent
  Set-Content $signingMetadataJson $signingMetadataContent
}

function GetManifest ([string] $registryUrl, $repositoryInfo, [string] $tag, [string] $registryAuth) {
  $authorization = ""

  Write-Verbose "Trying to obtain manifest (list.v2 format) without authentication..."
  $listContentType = "application/vnd.docker.distribution.manifest.list.v2+json"
  $listManifestInfo = GetManifestWithContentType $registryUrl $repositoryInfo $tag $listContentType $authorization
  if($listManifestInfo.StatusCode -eq 401) {
    Write-Verbose "Challenged received"
    $repositoryForScope = "$($repositoryInfo.NamespaceUrlPart)$($repositoryInfo.Name)"
    $authorization = DockerAuth $listManifestInfo $repositoryForScope $registryAuth
    Write-Verbose "Trying to obtain manifest (list.v2 format) with authentication..."
    $listManifestInfo = GetManifestWithContentType $registryUrl $repositoryInfo $tag $listContentType $authorization
  }

  if($listManifestInfo.Headers["Content-Type"] -eq $listContentType) {
    Write-Verbose "Succeeded."
    return $listManifestInfo
  }

  Write-Verbose "Failed."

  Write-Verbose "Trying to obtain manifest (v2 format) instead..."
  $contentTypeV2 = "application/vnd.docker.distribution.manifest.v2+json"
  $manifestInfo = GetManifestWithContentType  $registryUrl $repositoryInfo $tag $contentTypeV2 $authorization
  if($manifestInfo.Headers["Content-Type"] -eq $contentTypeV2) {
    Write-Verbose "Succeeded."
    return $manifestInfo
  }

  Write-Verbose "Failed."

  throw "The manifest format '$($manifestInfo.Headers["Content-Type"])' is not supported."
}

function GetManifestWithContentType ([string] $registryUrl, $repositoryInfo, $tag, [string] $contentType , [string] $authorization) {
  $headers = @{}
  $headers["Accept"] = $contentType

  $allowUnauthorized = $True
  if(-not [string]::IsNullOrEmpty($authorization)) {
    $headers["Authorization"] = "$authorization"
    $allowUnauthorized = $False
  }

  $manifestUrl = "$registryUrl/v2/$($repositoryInfo.NamespaceUrlPart)$($repositoryInfo.Name)/manifests/$($tag)"
  Write-Verbose "URL: $manifestUrl"
  $response = Invoke-WebRequest -Headers $headers $manifestUrl -SkipHttpErrorCheck
  EnsureSuccessStatusCode $manifestUrl $response $allowUnauthorized
  return $response
}

function DockerAuth ($challenge, $repositoryForScope, [string] $basicAuthCredentials) {
  Write-Verbose "Trying to authenticate... (repository for scope: $repositoryForScope)"

  if(!$challenge.Headers["WWW-Authenticate"]) {
    throw "WWW-Authenticate header in authorization challenge expected but it's missing.";
  }

  $wwwAuthenticateHeader = $challenge.Headers["WWW-Authenticate"][0]
  Write-Verbose "WWW-Authenticate header received: $wwwAuthenticateHeader"

  if($wwwAuthenticateHeader -like "Basic*") {
    return "Basic $basicAuthCredentials"
  }

  if($wwwAuthenticateHeader -like "Bearer*") {
    Write-Verbose "Parsing Bearer WWW-Authenticate header..."
    $realmRegexResult =   $wwwAuthenticateHeader | Select-String -Pattern "realm=""(?<realm>.*?)"""
    $serviceRegexResult = $wwwAuthenticateHeader | Select-String -Pattern "service=""(?<service>.*?)"""
    $realm = $realmRegexResult.Matches[0].Groups["realm"].Value
    $service = $serviceRegexResult.Matches[0].Groups["service"].Value
    $scope = "repository:$($repositoryForScope):push,pull" # do not parse from realm, not useful for self-hosted registries
    Write-Verbose "Realm: $realm"
    Write-Verbose "Service: $service"
    Write-Verbose "Scope: $scope"

    $authEndpointUrl = "$($realm)?scope=$scope&service=$service"
    $headers = @{}
    if (-not([string]::IsNullOrEmpty($basicAuthCredentials))) {
      $headers["Authorization"] = "Basic $basicAuthCredentials"
    }

    Write-Verbose "Authenticating against $authEndpointUrl"
    $authResponse = Invoke-RestMethod -Headers $headers $authEndpointUrl
    Write-Verbose "Authentication succeeded."

    return "Bearer $($authResponse.token)"
  }

  throw "WWW-Authenticate header '$wwwAuthenticateHeader' not supported."
}

function ParseDockerContentDigestHeader ([string] $dockerContentDigestHeader) {
  try {
    $hexString = $dockerContentDigestHeader -replace "sha256:", ""
    $bytes = [byte[]]::new($hexString.Length / 2)

    for($i = 0; $i -lt $hexString.Length; $i += 2) {
      $bytes[$i/2] = [convert]::ToByte($hexString.Substring($i, 2), 16)
    }

    return [Convert]::ToBase64String($bytes)
  }
  catch {
    throw "Could not parse Docker-Content-Digest header '$dockerContentDigestHeader'.";
  }
}

function PushFiles ([string] $notaryUrl, $repositoryInfo, $files, $notaryBasicAuthCredentials) {
  $initialResponse = PushFilesInternal $notaryUrl $repositoryInfo -Files $files
  if($initialResponse.StatusCode -eq 401) {
    Write-Verbose "Received challenge result, we need to authenticate"
    $authorization = DockerAuth $initialResponse $repositoryInfo.FullName $notaryBasicAuthCredentials
    PushFilesInternal $notaryUrl $repositoryInfo -Files $files -Authorization $authorization | Out-Null
  }
}

function PushFilesInternal ([string] $notaryUrl, $repositoryInfo, $files, $authorization) {
  $normalizedNotaryUrl = $notaryUrl.Trim("/")
  $pushUrl = "$normalizedNotaryUrl/v2/$($repositoryInfo.FullName)/_trust/tuf/"
  $headers = @{}
  $allowUnauthorized = $True
  if(-not [string]::IsNullOrEmpty($authorization)) {
    $headers["Authorization"] = "$authorization"
    $allowUnauthorized = $False
    Write-Verbose "Pushing metadata files to Notary service (with authorization)..."
  } else {
    Write-Verbose "Pushing metadata files to Notary service (without authorization)..."
  }

  $multipartContent = BuildMultipartContent $files
  try {
    Write-Verbose "URL: $pushUrl"
    $response = Invoke-WebRequest -Method Post -Headers $headers -ContentType "multipart/form-data" -Body $multipartContent.Content $pushUrl -SkipHttpErrorCheck
    EnsureSuccessStatusCode $pushUrl $response $allowUnauthorized
    return $response
  }
  finally {
    $multipartContent.Content.Dispose()
  }
}

function BuildMultipartContent ($files) {
  Write-Verbose "Building multipart content..."
  $multipartContent = [System.Net.Http.MultipartFormDataContent]::new()

  foreach($file in $files) {
    Write-Verbose "Building multipart content for file '$($file.Name)'..."
    $fileStream = [System.IO.FileStream]::new($file.Path, [System.IO.FileMode]::Open)

    $fileHeader = [System.Net.Http.Headers.ContentDispositionHeaderValue]::new("form-data")
    $fileHeader.Name = "files"
    $fileHeader.FileName = $file.Name

    $fileContent = [System.Net.Http.StreamContent]::new($fileStream)
    $fileContent.Headers.ContentDisposition = $fileHeader
    $fileContent.Headers.ContentType = [System.Net.Http.Headers.MediaTypeHeaderValue]::Parse("text/octet-stream")

    $multipartContent.Add($fileContent)
  }

  return @{ Content = $multipartContent }
}

function EnsureSuccessStatusCode([string] $requestUrl, $response, [boolean] $allowUnauthorized) {
  $statusCode = $response.StatusCode
  Write-Verbose "Status code: $statusCode"
  if($statusCode -lt 200 -or $statusCode -ge 300) {
    if($allowUnauthorized -and $statusCode -eq 401) {
      return;
    }
    $content = $response.Content
    throw "Response status code $statusCode indicates failure. Request '$requestUrl'. Response: '$content'.";
  }
}

function CheckIfRepositoryExists($notaryUrl, $trustDir, $repositoryInfo) {
  # it is not possible to call the notary cli to check if a repo does exist, because you can't known if $LASTEXITCODE == 1 means its not there or
  # the http request within the cli failed. So use Invoke-WebRequest.

  $response = TryGetNotaryRepositoryRootJson $notaryUrl $repositoryInfo $env:NOTARY_AUTH

  $statusCode = $response.StatusCode

  if ($statusCode -eq 200) {
    return $True
  }

  if ($statusCode -eq 404) {
    return $False
  }

  throw "Could not determin if repository '$($repositoryInfo.FullName)' already exists. Is there a connection issue to $notaryUrl ? StatusCode: $statusCode"
}

function TryGetNotaryRepositoryRootJson ([string] $notaryUrl, $repositoryInfo, [string] $notaryAuth) {
  $headers = @{}
  $headers["Authorization"] = "Basic $notaryAuth"

  $normalizedNotaryUrl = $notaryUrl.Trim("/")
  $requestUrl = "$normalizedNotaryUrl/v2/$($repositoryInfo.FullName)/_trust/tuf/root.json"

  Write-Verbose "challenge URL: $requestUrl"
  $response = Invoke-WebRequest -Headers $headers $requestUrl -SkipHttpErrorCheck
  Write-Verbose "Challenge response: $response"
  if($response.StatusCode -eq 401) {

    $repositoryForScope = $repositoryInfo.FullName
    $authorization = DockerAuth $response $repositoryForScope $notaryAuth

    $headers["Authorization"] = "$authorization"
    Write-Verbose "Check repo exists URL: $requestUrl"
    $response = Invoke-WebRequest -Headers $headers $requestUrl -SkipHttpErrorCheck
  }
  Write-Verbose $response
  return $response
}

function dockernotary (
  [Parameter(Mandatory)]
  [string] $notaryUrl,

  [Parameter(Mandatory)]
  [string] $trustDir,

  [Parameter(Mandatory)]
  [Hashtable] $errorMessages,

  [Parameter()]
  [Switch] $SuppressOutput,

  [Parameter(ValueFromRemainingArguments = $true)]
  [string[]] $passthrough
  )
{
  if($SuppressOutput.IsPresent) {
    notary @passthrough --server $notaryUrl --trustDir $trustDir | Out-Null
  } else {
    notary @passthrough --server $notaryUrl --trustDir $trustDir
  }

  #This notary cli call can't be wrapped into another caller, as the notary then has issues with its user input

  if ($LASTEXITCODE -ne 0) {
    if($errorMessages.ContainsKey($LASTEXITCODE)) {
      throw $errorMessages[$LASTEXITCODE]
    } else {
      throw "notary command failed with error code $LASTEXITCODE. Aborting."
    }
  }
}

function PrepareRegistryCredentials ([string] $registryUsername, [SecureString] $registryPassword, [string] $notaryUsername, [SecureString] $notaryPassword) {
  Write-Verbose "Preparing Registry credentials..."
  if(-not [string]::IsNullOrEmpty($registryUsername) -and -not [string]::IsNullOrEmpty((ConvertTo-PlainText $registryPassword))) {
    Write-Verbose "Using RegistryUsername/RegistryPassword combination."
    return BuildBasicAuthCredentialsFromUsernameAndPassword $registryUsername $registryPassword
  } elseif (-not [string]::IsNullOrEmpty($env:REGISTRY_AUTH)) {
    Write-Verbose "Using REGISTRY_AUTH environment variable."
    return $env:REGISTRY_AUTH
  } else {
    Write-Verbose "Neither RegistryUsername/RegistryPassword nor REGISTRY_AUTH set, going for Notary credentials instead..."
    return PrepareNotaryCredentials $notaryUsername $notaryPassword
  }
}

function PrepareNotaryCredentials ([string] $notaryUsername, [SecureString] $notaryPassword) {
  Write-Verbose "Preparing Notary credentials..."
  if([string]::IsNullOrEmpty($notaryUsername) -or [string]::IsNullOrEmpty((ConvertTo-PlainText $notaryPassword))) {
    Write-Verbose "Using NOTARY_AUTH environment variable."

    if([string]::IsNullOrEmpty($env:NOTARY_AUTH)) {
      Write-Verbose "No credentials found => executing unauthenticated."
    }

    return $env:NOTARY_AUTH
  }

  Write-Verbose "Using NotaryUsername/NotaryPassword combination."
  return BuildBasicAuthCredentialsFromUsernameAndPassword $notaryUsername $notaryPassword
}

function BuildBasicAuthCredentialsFromUsernameAndPassword ([string] $username, [SecureString] $password) {
  $plainTextPassword = ConvertTo-PlainText $password
  $basicAuthUnencoded = "${username}:${plainTextPassword}"
  $bytes = [System.Text.Encoding]::UTF8.GetBytes($basicAuthUnencoded)
  return [System.Convert]::ToBase64String($bytes)
}

function ConvertTo-PlainText([SecureString] $secureString) {
  return [System.Net.NetworkCredential]::new("", $secureString).Password
}

function SetDockerContentTrustServerEnvironmentVariable ($notaryUrl) {
  $originalDockerContentTrustServerValue = $env:DOCKER_CONTENT_TRUST_SERVER
  [Environment]::SetEnvironmentVariable("DOCKER_CONTENT_TRUST_SERVER_BAK", $originalDockerContentTrustServerValue, "Process")

  [Environment]::SetEnvironmentVariable("DOCKER_CONTENT_TRUST_SERVER", $notaryUrl, "Process")
}

function CleanupDockerContentTrustServerEnvironmentVariable {
  $originalDockerContentTrustServerValue = $env:DOCKER_CONTENT_TRUST_SERVER_BAK
  [Environment]::SetEnvironmentVariable("DOCKER_CONTENT_TRUST_SERVER", $originalDockerContentTrustServerValue, "Process")

  Remove-Item -ErrorAction SilentlyContinue Env:\DOCKER_CONTENT_TRUST_SERVER_BAK
}

function PrepareNotaryAuthentication ($notaryBasicAuthCredentials) {
  $originalNotaryAuthValue = $env:NOTARY_AUTH
  [Environment]::SetEnvironmentVariable("NOTARY_AUTH_BAK", $originalNotaryAuthValue, "Process")

  [Environment]::SetEnvironmentVariable("NOTARY_AUTH", $notaryBasicAuthCredentials, "Process")
}

function CleanupNotaryAuthentication {
  $originalNotaryAuthValue = $env:NOTARY_AUTH_BAK
  [Environment]::SetEnvironmentVariable("NOTARY_AUTH", $originalNotaryAuthValue, "Process")

  Remove-Item -ErrorAction SilentlyContinue Env:\NOTARY_AUTH_BAK
}

function GetTrustDir {
  if([string]::IsNullOrEmpty($env:DOCKER_CONFIG)) {
    return Join-Path "$HOME" ".docker" "trust"
  } else {
    return Join-Path $env:DOCKER_CONFIG "trust"
  }
}

function ExtractRootCertificate ($trustDir, $repositoryInfo, $forceOverwriteRootCertificate) {
  $rootJsonPath = Join-Path $trustDir "tuf" $repositoryInfo.FullName "metadata" "root.json"

  if(-not (Test-Path $rootJsonPath -PathType Leaf)) {
    throw "Could not find root.json to extract root certificate at $rootJsonPath"
  }

  $rootJsonObject = Get-Content $rootJsonPath | ConvertFrom-Json

  $keyCount = $rootJsonObject.signed.roles.root.keyids.Length
  if ($keyCount -ne 1) {
    throw "Assertion: There is more than one root key. We didn't expect that."
  }

  $rootKeyId = $rootJsonObject.signed.roles.root.keyids[0]
  $rootCertEncoded = $rootJsonObject.signed.keys.$rootKeyId.keyval.public

  $decodedBytes = [System.Convert]::FromBase64String($rootCertEncoded);
  $rootCertPemString = [System.Text.Encoding]::ASCII.GetString($decodedBytes);

  $outputFilePath = GetRootCertificateFilePath $repositoryInfo

  [System.IO.File]::WriteAllText($outputFilePath, $rootCertPemString)
  Write-Host "Created file $outputFilePath"
}

function GetRootCertificateFilePath ($repositoryInfo) {
  return NormalizePath "$($repositoryInfo.Registry)_$($repositoryInfo.Namespace)_$($repositoryInfo.Name).RootCertificate.pem"
}

function PrepareDelegationCertificate ($delegationCertificatePath) {
  $normalizedPath = NormalizePath $delegationCertificatePath

  if(-not (Test-Path $normalizedPath -PathType Leaf)) {
    throw "Could not find a delegation certificate at $normalizedPath"
  }

  if (-not ((Get-Content -Raw $normalizedPath).Contains("--BEGIN CERTIFICATE"))) {
    $normalizedPath = ConvertToNewPemFile $normalizedPath
  }

  return $normalizedPath
}

function ConvertToNewPemFile ($path) {
  try {
    $cert = [System.Security.Cryptography.X509Certificates.X509Certificate2]::New($path)

    $pem = [System.Convert]::ToBase64String($cert.Export([System.Security.Cryptography.X509Certificates.X509ContentType]::Cert), [System.Base64FormattingOptions]::InsertLineBreaks)

    $sb = [System.Text.StringBuilder]::New()

    $sb.AppendLine("-----BEGIN CERTIFICATE-----") | Out-Null
    $sb.AppendLine($pem) | Out-Null
    $sb.AppendLine("-----END CERTIFICATE-----") | Out-Null

    $tempFileName = "$([Guid]::NewGuid()).pem"
    $tempDir = [System.IO.Path]::GetTempPath()
    $resultingFilePath = Join-Path $tempDir $tempFileName

    [System.IO.File]::WriteAllText($resultingFilePath, $sb.ToString())

    return $resultingFilePath
  } finally {
    $cert.Dispose()
  }
}

Export-ModuleMember Initialize-DockerSigning
Export-ModuleMember Add-DelegationCertificate
Export-ModuleMember Get-RootCertificate
Export-ModuleMember Invoke-DockerSigning
Export-ModuleMember New-DockerSigningData
Export-ModuleMember Push-SignedDockerSigningData

# SIG # Begin signature block
# MIIj3gYJKoZIhvcNAQcCoIIjzzCCI8sCAQExDzANBglghkgBZQMEAgEFADB5Bgor
# BgEEAYI3AgEEoGswaTA0BgorBgEEAYI3AgEeMCYCAwEAAAQQH8w7YFlLCE63JNLG
# KX7zUQIBAAIBAAIBAAIBAAIBADAxMA0GCWCGSAFlAwQCAQUABCAZnVhtoIWDcEdH
# G/va/ZB9EVxkvLJi73LwnBDyiEI/qKCCEhEwggN1MIICXaADAgECAgsEAAAAAAEV
# S1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