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

    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
  } 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 $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
  } 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 ([Hashtable] $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 ([Hashtable] $repositoryInfo, [string] $notaryUrl, [string] $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 ([System.Collections.Generic.List[string]] $metadataFiles, [string] $targetDirectory) {
  $tempTargetsDir = Join-Path $targetDirectory "targets"

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

    if ( $filePath.Contains("targets$([System.IO.Path]::DirectorySeparatorChar)")) {
      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, [System.Collections.Generic.List[string]] $tags, [Hashtable] $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 -AsUTC).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, [Hashtable] $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, [Hashtable] $repositoryInfo, [string] $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."

    if ($authResponse.PSObject.Properties.Name -contains "token") {
      return "Bearer $($authResponse.token)"
    } else {
      return "Bearer $($authResponse.'access_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, [Hashtable] $repositoryInfo, [System.Collections.Generic.List[Hashtable]] $files, [string] $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, [Hashtable] $repositoryInfo, [System.Collections.Generic.List[Hashtable]] $files, [string] $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 ([System.Collections.Generic.List[Hashtable]] $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("application/octet-stream")

    $multipartContent.Add($fileContent)
  }

  return @{ Content = $multipartContent }
}

function EnsureSuccessStatusCode ([string] $requestUrl, [Microsoft.PowerShell.Commands.WebResponseObject] $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 ([string] $notaryUrl, [Hashtable] $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, [Hashtable] $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 ([string] $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 ([string] $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 ([string] $trustDir, [Hashtable] $repositoryInfo) {
  $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 ([Hashtable] $repositoryInfo) {
  return NormalizePath "$($repositoryInfo.Registry)_$($repositoryInfo.Namespace)_$($repositoryInfo.Name).RootCertificate.pem"
}

function PrepareDelegationCertificate ([string] $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 ([string] $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
# MIIvcAYJKoZIhvcNAQcCoIIvYTCCL10CAQExDzANBglghkgBZQMEAgEFADB5Bgor
# BgEEAYI3AgEEoGswaTA0BgorBgEEAYI3AgEeMCY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