# Installer of the Repsy CLI for Windows (RPS-1919): installs rp.exe and docker-credential-repsy.exe from # cli.repsy.io. It does the same as install.sh, in the same order, on Windows PowerShell 5.1 and PowerShell 7. # # irm https://cli.repsy.io/install.ps1 | iex # # That form takes its options from the environment: RP_VERSION, RP_INSTALL_DIR, RP_FORCE=1, RP_REQUIRE_SIGNATURE=1, # RP_ADD_TO_PATH=1. To pass parameters instead: # # & ([scriptblock]::Create((irm https://cli.repsy.io/install.ps1))) -Version 1.2.3 -InstallDir C:\Tools\rp -AddToPath # # Parameters: # -Version X.Y.Z install this version instead of the one in latest.json # -InstallDir DIR default $env:LOCALAPPDATA\Programs\repsy-cli # -Force overwrite an existing rp # -RequireSignature fail unless the signature of the checksums is verified (needs cosign) # -AddToPath add the install directory to the PATH of the current user (otherwise only printed) # # Exit codes: 0 success, 1 general failure, 2 usage error, 3 existing installation, 4 verification failure. # Run as a file the script ends with `exit `; through `iex` it only sets $LASTEXITCODE, so it does not # close your shell. # # What is verified: the SHA-256 of the archive against checksums.txt always, and the cosign signature of # checksums.txt when cosign is installed. The script and the archive come from the same server over HTTPS, so # on this path the root of trust is TLS; the signature protects the checksums, not the script. # # The body is one function that is called on the last line, so a download cut short runs nothing. param( [string]$Version = $env:RP_VERSION, [string]$InstallDir = $env:RP_INSTALL_DIR, [switch]$Force, [switch]$RequireSignature, [switch]$AddToPath ) function Install-RepsyCli { [CmdletBinding()] param( [string]$Version, [string]$InstallDir, [bool]$Force, [bool]$RequireSignature, [bool]$AddToPath ) $ErrorActionPreference = 'Stop' $ProgressPreference = 'SilentlyContinue' $baseUrlDefault = 'https://cli.repsy.io' $certIssuer = 'https://token.actions.githubusercontent.com' $certIdentityPrefix = 'https://github.com/repsyio/repsy-cli/.github/workflows/release.yml@refs/tags/v' $testBaseUrl = $env:RP_BASE_URL # A failure carries its exit code; the caller turns it into the exit code of the script. function Stop-Install([int]$Code, [string]$Message) { $e = New-Object System.Exception($Message) $e.Data['RpExitCode'] = $Code throw $e } function Write-Warn([string]$Message) { [Console]::Error.WriteLine("rp install: warning: $Message") } # TLS 1.2 is not on by default in Windows PowerShell 5.1. try { [Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol -bor [Net.SecurityProtocolType]::Tls12 } catch { Write-Verbose 'Could not set TLS 1.2 explicitly' } if (-not $Force -and $env:RP_FORCE -eq '1') { $Force = $true } if (-not $RequireSignature -and $env:RP_REQUIRE_SIGNATURE -eq '1') { $RequireSignature = $true } if (-not $AddToPath -and $env:RP_ADD_TO_PATH -eq '1') { $AddToPath = $true } # A base URL other than the default is for tests: https, or http on the loopback only. $baseUrl = $baseUrlDefault if ($testBaseUrl) { $baseUrl = $testBaseUrl.TrimEnd('/') if ($baseUrl -notmatch '^https://.+' -and $baseUrl -notmatch '^http://(127\.0\.0\.1|localhost|\[::1\])([:/]|$)') { Stop-Install 2 "RP_BASE_URL must be https, or http on the loopback (got '$baseUrl')" } } function Get-RpFile([string]$Url, [string]$OutFile) { try { $response = Invoke-WebRequest -UseBasicParsing -Uri $Url -OutFile $OutFile -PassThru } catch { if (Test-Path -LiteralPath $OutFile) { Remove-Item -LiteralPath $OutFile -Force } throw (New-Object System.IO.IOException("download failed: $Url ($($_.Exception.Message))")) } # Redirects must not leave HTTPS (the loopback of a test is exempt). $finalUri = $null if ($response.BaseResponse.ResponseUri) { $finalUri = $response.BaseResponse.ResponseUri } elseif ($response.BaseResponse.RequestMessage) { $finalUri = $response.BaseResponse.RequestMessage.RequestUri } if ($finalUri -and -not $testBaseUrl -and $finalUri.Scheme -ne 'https') { Remove-Item -LiteralPath $OutFile -Force throw (New-Object System.IO.IOException("download of $Url ended on $finalUri, which is not HTTPS")) } } # Platform. The test override only works in test mode. $platform = $null if ($testBaseUrl -and $env:RP_TEST_PLATFORM) { $platform = $env:RP_TEST_PLATFORM } else { if ($PSVersionTable.PSEdition -eq 'Core' -and -not $IsWindows) { Stop-Install 1 'this is not Windows; use install.sh instead' } $arch = $env:PROCESSOR_ARCHITEW6432 if (-not $arch) { $arch = $env:PROCESSOR_ARCHITECTURE } switch ($arch) { 'AMD64' { $platform = 'windows_amd64' } 'ARM64' { $platform = 'windows_arm64' } default { Stop-Install 1 "unsupported architecture: $arch" } } } $work = Join-Path ([IO.Path]::GetTempPath()) ('rp-install-' + [Guid]::NewGuid().ToString('N')) New-Item -ItemType Directory -Path $work | Out-Null try { # Version. if ($Version) { $Version = $Version -replace '^v', '' if ($Version -notmatch '^[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.-]+)?$') { Stop-Install 2 "'$Version' is not a version like 1.2.3" } } else { $latestPath = Join-Path $work 'latest.json' Get-RpFile "$baseUrl/latest.json" $latestPath $raw = (Get-Content -LiteralPath $latestPath -Raw) try { $latest = $raw | ConvertFrom-Json } catch { Stop-Install 1 'latest.json is incomplete or not JSON; try again' } if ($latest.schemaVersion -ne 1) { Stop-Install 1 "latest.json has schemaVersion '$($latest.schemaVersion)', this installer reads 1; download a newer install.ps1" } $Version = [string]$latest.version if (-not $Version) { Stop-Install 1 'latest.json has no version' } if ($Version -notmatch '^[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.-]+)?$') { Stop-Install 1 "latest.json has an invalid version '$Version'" } } # Install directory and an existing installation. if (-not $InstallDir) { if (-not $env:LOCALAPPDATA) { Stop-Install 2 'LOCALAPPDATA is not set; pass -InstallDir' } $InstallDir = Join-Path $env:LOCALAPPDATA 'Programs\repsy-cli' } $InstallDir = $InstallDir.TrimEnd('\', '/') $exeName = 'rp.exe' $credName = 'docker-credential-repsy.exe' $existing = $null $onPath = Get-Command rp -CommandType Application -ErrorAction SilentlyContinue | Select-Object -First 1 if ($onPath) { $existing = $onPath.Source } if (-not $existing) { foreach ($candidate in @((Join-Path $InstallDir $exeName), (Join-Path $InstallDir $credName))) { if (Test-Path -LiteralPath $candidate) { $existing = $candidate; break } } } if ($existing) { if ($Force) { Write-Warn "overwriting $existing" } else { $owner = 'unknown' if ($existing -match '\\scoop\\') { $owner = 'Scoop (scoop update repsy-cli)' } [Console]::Error.WriteLine("rp install: rp is already installed: $existing") [Console]::Error.WriteLine(" installed by: $owner") [Console]::Error.WriteLine(" Nothing was changed. To replace it with $Version, run again with -Force.") $e = New-Object System.Exception('existing installation') $e.Data['RpExitCode'] = 3 $e.Data['RpQuiet'] = $true throw $e } } $archive = "repsy-cli_${Version}_${platform}.zip" $sumsName = "repsy-cli_${Version}_checksums.txt" Write-Host "Installing rp $Version ($platform) into $InstallDir" Get-RpFile "$baseUrl/releases/$Version/$archive" (Join-Path $work $archive) Get-RpFile "$baseUrl/releases/$Version/$sumsName" (Join-Path $work $sumsName) # Signature: cosign verifies the bundle of checksums.txt against the identity of this version's release # workflow. The identity is stated here, never read from the server. $signatureState = 'not verified' $cosign = Get-Command cosign -CommandType Application -ErrorAction SilentlyContinue | Select-Object -First 1 if (-not $cosign) { if ($RequireSignature) { Stop-Install 4 '-RequireSignature was given but cosign is not installed (https://docs.sigstore.dev/cosign/system_config/installation/)' } Write-Warn 'cosign is not installed: the signature of checksums.txt was NOT verified.' Write-Warn 'Only the SHA-256 checksum is checked. That catches a damaged download, not a tampered server.' Write-Warn 'Install cosign and run again, or pass -RequireSignature to make this an error.' } else { $bundle = Join-Path $work "$sumsName.sigstore.json" try { Get-RpFile "$baseUrl/releases/$Version/$sumsName.sigstore.json" $bundle } catch { Stop-Install 4 'the signature of checksums.txt could not be downloaded; nothing was installed' } $identity = "$certIdentityPrefix$Version" # RP_COSIGN_PUBLIC_KEY lets the tests sign with a throwaway key; it is ignored outside test mode. if ($testBaseUrl -and $env:RP_COSIGN_PUBLIC_KEY) { $cosignArgs = @('verify-blob', '--bundle', $bundle, '--key', $env:RP_COSIGN_PUBLIC_KEY, '--insecure-ignore-tlog', (Join-Path $work $sumsName)) } else { $cosignArgs = @('verify-blob', '--bundle', $bundle, '--certificate-identity', $identity, '--certificate-oidc-issuer', $certIssuer, (Join-Path $work $sumsName)) } $cosignOut = & $cosign.Source @cosignArgs 2>&1 if ($LASTEXITCODE -ne 0) { [Console]::Error.WriteLine(($cosignOut | Out-String)) Stop-Install 4 "the signature of checksums.txt is not valid for $identity; nothing was installed" } if ($testBaseUrl -and $env:RP_COSIGN_PUBLIC_KEY) { $signatureState = "verified (cosign, test key $($env:RP_COSIGN_PUBLIC_KEY))" } else { $signatureState = "verified (cosign, $identity)" } } # Checksum: exactly one line for this archive, never "the first line". $lines = @(Get-Content -LiteralPath (Join-Path $work $sumsName) | Where-Object { $_.Trim() }) $matched = @() foreach ($line in $lines) { $parts = $line.Trim() -split '\s+', 2 if ($parts.Count -eq 2 -and ($parts[1] -ceq $archive -or $parts[1] -ceq "*$archive")) { $matched += $parts[0] } } if ($matched.Count -ne 1) { Stop-Install 4 "checksums.txt has $($matched.Count) lines for $archive, expected exactly 1; nothing was installed" } if ($matched[0] -notmatch '^[0-9a-fA-F]{64}$') { Stop-Install 4 "checksums.txt has a malformed checksum for $archive; nothing was installed" } $actual = (Get-FileHash -Algorithm SHA256 -LiteralPath (Join-Path $work $archive)).Hash if ($actual -ne $matched[0]) { Stop-Install 4 "the SHA-256 of $archive does not match checksums.txt (expected $($matched[0].ToLower()), got $($actual.ToLower())); nothing was installed" } # Extract only the two executables, after every entry name is checked. Add-Type -AssemblyName System.IO.Compression.FileSystem $extractDir = Join-Path $work 'extract' New-Item -ItemType Directory -Path $extractDir | Out-Null $zip = [IO.Compression.ZipFile]::OpenRead((Join-Path $work $archive)) try { foreach ($entry in $zip.Entries) { $name = $entry.FullName if ($name.StartsWith('/') -or $name.StartsWith('\') -or $name -match '^[A-Za-z]:' -or ($name -split '[\\/]') -contains '..') { Stop-Install 4 "$archive has an unsafe path '$name'; nothing was installed" } } foreach ($want in @($exeName, $credName)) { $entry = $zip.Entries | Where-Object { $_.FullName -eq $want } | Select-Object -First 1 if (-not $entry) { Stop-Install 1 "$archive does not contain $want" } [IO.Compression.ZipFileExtensions]::ExtractToFile($entry, (Join-Path $extractDir $want)) } } finally { $zip.Dispose() } # Install: copy next to the target under a temporary name, then rename. New-Item -ItemType Directory -Force -Path $InstallDir | Out-Null foreach ($bin in @($exeName, $credName)) { $staged = Join-Path $InstallDir (".$bin.new." + [Guid]::NewGuid().ToString('N')) try { Copy-Item -LiteralPath (Join-Path $extractDir $bin) -Destination $staged Move-Item -LiteralPath $staged -Destination (Join-Path $InstallDir $bin) -Force } catch { if (Test-Path -LiteralPath $staged) { Remove-Item -LiteralPath $staged -Force } Stop-Install 1 "cannot replace $(Join-Path $InstallDir $bin); if rp is running, close it and run again ($($_.Exception.Message))" } } # Only reached by the tests on Linux, where an extracted file is not executable. if ($PSVersionTable.PSEdition -eq 'Core' -and -not $IsWindows) { foreach ($bin in @($exeName, $credName)) { & chmod 0755 (Join-Path $InstallDir $bin) } } # The installed rp reports the version that was asked for. $reported = $null try { $reported = ((& (Join-Path $InstallDir $exeName) version --output json) | Out-String | ConvertFrom-Json).version } catch { Write-Verbose "rp version failed: $($_.Exception.Message)" } if ($reported -ne $Version) { $shown = $reported if (-not $shown) { $shown = 'nothing' } Stop-Install 1 "$(Join-Path $InstallDir $exeName) reports version '$shown', expected $Version; the files were left in place" } # PATH: printed, and changed only on request. $pathNote = '' $userPath = [Environment]::GetEnvironmentVariable('Path', 'User') $entries = @() if ($userPath) { $entries = $userPath -split ';' | Where-Object { $_ } } $inUserPath = $entries -contains $InstallDir if ($AddToPath -and -not $inUserPath) { [Environment]::SetEnvironmentVariable('Path', (($entries + $InstallDir) -join ';'), 'User') $pathNote = "Added $InstallDir to your user PATH. Open a new terminal to use it." } else { $found = Get-Command rp -CommandType Application -ErrorAction SilentlyContinue | Select-Object -First 1 if (-not $found) { $pathNote = "$InstallDir is not on your PATH. For this session:`n `$env:Path = `"$InstallDir;`$env:Path`"`n To keep it, run this script again with -AddToPath. This script does not change your PATH otherwise." } elseif ($found.Source -ne (Join-Path $InstallDir $exeName)) { $pathNote = "warning: 'rp' on your PATH is $($found.Source), not the one just installed; another directory comes first in PATH." } } Write-Host '' Write-Host "rp $Version is installed in $InstallDir ($exeName, $credName)." Write-Host " checksum: verified (sha256, $archive)" Write-Host " signature: $signatureState" if ($pathNote) { Write-Host '' Write-Host $pathNote } return 0 } finally { if (Test-Path -LiteralPath $work) { Remove-Item -LiteralPath $work -Recurse -Force -ErrorAction SilentlyContinue } } } $rpExit = 1 try { $rpExit = [int](@(Install-RepsyCli -Version $Version -InstallDir $InstallDir -Force ([bool]$Force) -RequireSignature ([bool]$RequireSignature) -AddToPath ([bool]$AddToPath))[-1]) } catch { $rpExit = 1 if ($_.Exception.Data.Contains('RpExitCode')) { $rpExit = [int]$_.Exception.Data['RpExitCode'] } if (-not $_.Exception.Data.Contains('RpQuiet')) { [Console]::Error.WriteLine("rp install: $($_.Exception.Message)") } } if ($MyInvocation.MyCommand.Path) { exit $rpExit } $global:LASTEXITCODE = $rpExit