From 99a9746fc0d8699340b19cfdedfa0451dead76d6 Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Wed, 18 Nov 2026 21:11:09 +0000 Subject: [PATCH 1/3] refactor(cli): make the install scripts readable top to bottom Restructure both installers around a short happy path: bash main() and PowerShell Invoke-Install now read as the list of install steps, and each step is a small named helper with a comment saying what it does and why. Nested branches become guard clauses, repeated failure handling becomes one helper, and the bash script runs main on its last line so a truncated download executes nothing. Behavior, messages, telemetry steps, and setup arguments are unchanged. The only test change follows from the trap now naming main() as the function. Co-Authored-By: Evan Purkhiser <1421724+evanpurkhiser@users.noreply.github.com> --- packages/cli/install | 1145 ++++++++++-------- packages/cli/install.ps1 | 435 ++++--- packages/cli/test/lib/install-script.test.ts | 4 +- 3 files changed, 876 insertions(+), 708 deletions(-) diff --git a/packages/cli/install b/packages/cli/install index 41450729c..b8bb4b2a6 100755 --- a/packages/cli/install +++ b/packages/cli/install @@ -1,83 +1,212 @@ #!/bin/bash +# Sentry CLI installer. +# +# curl -fsSL https://cli.sentry.dev/install | bash +# +# This script only fetches the right `sentry` binary for this machine. The +# binary installs itself: `sentry cli setup` picks the install directory, +# updates PATH, and installs shell completions and agent skills. +# +# The steps, in order (see main() below): +# +# 1. Read the command-line flags. +# 2. Work out which build this machine needs (OS, CPU, libc). +# 3. Find that build for the requested version (stable or nightly). +# 4. Download it to a temporary file and verify it. +# 5. Hand off to `sentry cli setup`, and optionally `sentry init`. +# +# Everything is a function, and main() runs on the last line. If the download +# of this script is cut off, bash runs nothing instead of half an installer. set -euo pipefail RED='\033[0;31m' MUTED='\033[0;2m' NC='\033[0m' -# Sentry error telemetry — fire-and-forget error reporting via envelope API. -# Uses the CLI's public write-only DSN. No PII collected. -# Opt-out: SENTRY_CLI_NO_TELEMETRY=1 +# Installer errors go to Sentry through the envelope API, using the CLI's +# public write-only DSN. No PII is collected. Opt out: SENTRY_CLI_NO_TELEMETRY=1 SENTRY_DSN_KEY="1188a86f3f8168f089450587b00bca66" SENTRY_INGEST="https://o1.ingest.us.sentry.io" SENTRY_PROJECT_ID="4510776311808000" -# Generate a UUID for the event. Tries /proc, uuidgen, then awk fallback. -gen_uuid() { - if [[ -r /proc/sys/kernel/random/uuid ]]; then - cat /proc/sys/kernel/random/uuid - elif command -v uuidgen >/dev/null 2>&1; then - uuidgen | tr '[:upper:]' '[:lower:]' +REGISTRY_URL="https://release-registry.services.sentry.io/apps/sentry" +GITHUB_REPO="getsentry/toolkit" +GHCR_REPO="ghcr.io/v2/getsentry/toolkit" + +# Retry transient network failures (timeouts, refused connections, HTTP 408, +# 429, and 5xx) with curl's exponential backoff. The binary needs glibc 2.28 +# or macOS 11, whose curl (7.61, 7.64) has --retry-connrefused (7.52) but not +# --retry-all-errors (7.71). +curl_retry=(--retry 3 --retry-connrefused --retry-max-time 60) + +no_room_message="There is not enough room to stage sentry (about 140 MB): the temporary directory and the install directory are both full or not writable. Free up space or set TMPDIR to another directory, then retry." + +# Installer state. The steps below fill these in; error reports read them. +requested_version="${SENTRY_VERSION:-}" # "", "nightly", or a version +no_modify_path=false +no_completions=false +no_agent_skills=false +os="" # darwin, linux, or windows +arch="" # x64 or arm64 +libc_variant="" # set to musl only to report why the install stopped +suffix="" # ".exe" on Windows +asset="" # release file name, such as sentry-linux-x64 +version="" # the exact version being installed +gz_url="" # release downloads and their SHA-256 checksums +gz_sha="" +raw_url="" +raw_sha="" +registry_status="" # HTTP status of the release registry lookup + +# Download paths. plan_staging_paths sets them. When the temp directory is +# full, write_staged moves tmp_binary and blob_file to their setup_* fallbacks. +tmp_binary="" # the downloaded binary +blob_file="" # the downloaded .gz, before unpacking +init_binary="" # hard link to the binary for `sentry init` +setup_binary="" # fallback for tmp_binary in the install directory +setup_blob="" # fallback for blob_file in the install directory + +main() { + parse_args "$@" + detect_platform + plan_staging_paths + + if [[ "$requested_version" == "nightly" ]]; then + download_nightly else - awk 'BEGIN{srand();for(i=1;i<=32;i++)printf "%c",substr("0123456789abcdef",int(rand()*16)+1,1);print ""}' + resolve_stable_release + download_stable + fi + chmod +x "$tmp_binary" + link_init_binary + + # From here on, a failure belongs to sentry itself, not to the installer: + # exit with its status instead of reporting it as an installer bug. + trap - ERR + run_setup + if [[ "${SENTRY_INIT:-}" == "1" ]]; then + # `sentry init` only prints the agent setup guide, so it needs no terminal. + "$init_binary" init fi } -# Send an error event to Sentry. Runs in a subshell in the background so it -# never blocks installation or propagates failures. -# Usage: report_error "message" "step-name" +# --------------------------------------------------------------------------- +# Command line +# --------------------------------------------------------------------------- + +usage() { + cat < Install a specific version (e.g., 0.2.0) or "nightly" + --no-modify-path Don't modify shell config files (.zshrc, .bashrc, etc.) + --no-completions Don't install shell completions + --no-agent-skills Don't install agent skills + +Environment Variables: + SENTRY_INSTALL_DIR Override the installation directory + SENTRY_VERSION Install a specific version (e.g., 0.42.2, nightly) + SENTRY_INIT Set to 1 to run \`sentry init\` after installing + SENTRY_CLI_NO_TELEMETRY Set to 1 to disable installer error reporting + +Examples: + curl -fsSL https://cli.sentry.dev/install | bash + curl -fsSL https://cli.sentry.dev/install | SENTRY_INIT=1 bash + curl -fsSL https://cli.sentry.dev/install | bash -s -- --version nightly + curl -fsSL https://cli.sentry.dev/install | bash -s -- --version 0.42.2 + curl -fsSL https://cli.sentry.dev/install | SENTRY_VERSION=nightly bash + curl -fsSL https://cli.sentry.dev/install | SENTRY_INSTALL_DIR="$HOME/.local/bin" bash +EOF +} + +# Unknown arguments are ignored. +parse_args() { + while [[ $# -gt 0 ]]; do + case "$1" in + -h|--help) usage; exit 0 ;; + -v|--version) + [[ -n "${2:-}" ]] || die "Error: --version requires a version argument" "args" + requested_version="$2" + shift 2 + ;; + --no-modify-path) no_modify_path=true; shift ;; + --no-completions) no_completions=true; shift ;; + --no-agent-skills) no_agent_skills=true; shift ;; + *) shift ;; + esac + done +} + +# --------------------------------------------------------------------------- +# Output and error reporting +# --------------------------------------------------------------------------- + +# Usage: muted . Prints a dimmed progress line. +muted() { + printf '%b%s%b\n' "$MUTED" "$*" "$NC" +} + +# Usage: die . Prints the message, reports it, and exits. +die() { + printf '%b%s%b\n' "$RED" "$1" "$NC" >&2 + report_error "$1" "${2:-unknown}" + exit 1 +} + +# Usage: report_error . Sends an error event to Sentry in a +# background subshell, so it never slows down or fails the install. report_error() { - # Respect the same opt-out as the CLI binary + # Respect the same opt-out as the CLI binary. [[ "${SENTRY_CLI_NO_TELEMETRY:-}" == "1" ]] && return 0 ( # Telemetry must never fail the script or report its own failures. set +e trap - ERR - local msg="${1:-unknown error}" - local step="${2:-unknown}" - local event_id - event_id=$(gen_uuid | tr -d '-') - local timestamp - timestamp=$(date -u +"%Y-%m-%dT%H:%M:%SZ" 2>/dev/null || echo "") - # Escape a value for safe JSON string interpolation + # Escape a value for safe JSON string interpolation. _esc() { printf '%s' "$1" | sed 's/\\/\\\\/g;s/"/\\"/g' | tr '\n' ' '; } - local json_msg; json_msg=$(_esc "$msg") - local json_step; json_step=$(_esc "$step") - local json_channel; json_channel=$(_esc "${requested_version:-stable}") - local json_version; json_version=$(_esc "${version:-unknown}") + local event_id timestamp msg step channel install_version + event_id=$(gen_uuid | tr -d '-') + timestamp=$(date -u +"%Y-%m-%dT%H:%M:%SZ" 2>/dev/null || echo "") + msg=$(_esc "${1:-unknown error}") + step=$(_esc "${2:-unknown}") + channel=$(_esc "${requested_version:-stable}") + install_version=$(_esc "${version:-unknown}") - local envelope - envelope=$(printf '%s\n%s\n%s' \ - "{\"event_id\":\"${event_id}\",\"dsn\":\"https://${SENTRY_DSN_KEY}@o1.ingest.us.sentry.io/${SENTRY_PROJECT_ID}\"}" \ - '{"type":"event"}' \ - "{\"event_id\":\"${event_id}\",\"timestamp\":\"${timestamp}\",\"platform\":\"other\",\"level\":\"error\",\"logger\":\"install\",\"server_name\":\"install-script\",\"message\":{\"formatted\":\"${json_msg}\"},\"tags\":{\"os\":\"${os:-unknown}\",\"arch\":\"${arch:-unknown}\",\"libc\":\"${libc_variant:-glibc}\",\"channel\":\"${json_channel}\",\"step\":\"${json_step}\",\"install.version\":\"${json_version}\"},\"contexts\":{\"runtime\":{\"name\":\"bash\",\"version\":\"${BASH_VERSION:-unknown}\"}}}") + local header item event + header="{\"event_id\":\"${event_id}\",\"dsn\":\"https://${SENTRY_DSN_KEY}@o1.ingest.us.sentry.io/${SENTRY_PROJECT_ID}\"}" + item='{"type":"event"}' + event="{\"event_id\":\"${event_id}\",\"timestamp\":\"${timestamp}\",\"platform\":\"other\",\"level\":\"error\",\"logger\":\"install\",\"server_name\":\"install-script\",\"message\":{\"formatted\":\"${msg}\"},\"tags\":{\"os\":\"${os:-unknown}\",\"arch\":\"${arch:-unknown}\",\"libc\":\"${libc_variant:-glibc}\",\"channel\":\"${channel}\",\"step\":\"${step}\",\"install.version\":\"${install_version}\"},\"contexts\":{\"runtime\":{\"name\":\"bash\",\"version\":\"${BASH_VERSION:-unknown}\"}}}" curl -sf --max-time 2 \ -H "Content-Type: application/x-sentry-envelope" \ -H "X-Sentry-Auth: Sentry sentry_key=${SENTRY_DSN_KEY},sentry_version=7" \ - -d "$envelope" \ + -d "$(printf '%s\n%s\n%s' "$header" "$item" "$event")" \ "${SENTRY_INGEST}/api/${SENTRY_PROJECT_ID}/envelope/" \ >/dev/null 2>&1 ) & } -# Print error message, report to Sentry, and exit. -# Usage: die "message" "step-name" -die() { - echo -e "${RED}$1${NC}" >&2 - report_error "$1" "${2:-unknown}" - exit 1 +# Prints a random UUID. Tries /proc, then uuidgen, then awk. +gen_uuid() { + if [[ -r /proc/sys/kernel/random/uuid ]]; then + cat /proc/sys/kernel/random/uuid + elif command -v uuidgen >/dev/null 2>&1; then + uuidgen | tr '[:upper:]' '[:lower:]' + else + awk 'BEGIN{srand();for(i=1;i<=32;i++)printf "%c",substr("0123456789abcdef",int(rand()*16)+1,1);print ""}' + fi } -# Catch unexpected failures from set -e / pipefail. errtrace (-E) makes -# functions and command substitutions inherit the trap; without it, a failure -# inside a function exits without a message or a report. $BASH_COMMAND is the -# failing command's unexpanded source text, so the report names the command -# without the paths or values it ran with. -set -E +# The ERR trap: reports any failure that no `die` call explains. +# $BASH_COMMAND is the failing command's unexpanded source text, so the report +# names the command without the paths or values it ran with. on_unexpected_failure() { local status=$1 line=$2 failed_command=$3 function_name=$4 # A failing command substitution also fails the command that contains it, @@ -91,138 +220,107 @@ on_unexpected_failure() { fi die "Unexpected failure at ${where} (exit ${status}): ${failed_command:0:200}" "trap" } -trap 'on_unexpected_failure "$?" "$LINENO" "$BASH_COMMAND" "${FUNCNAME[0]:-}"' ERR -usage() { - cat < Install a specific version (e.g., 0.2.0) or "nightly" - --no-modify-path Don't modify shell config files (.zshrc, .bashrc, etc.) - --no-completions Don't install shell completions - --no-agent-skills Don't install agent skills + arch=$(uname -m) + case "$arch" in + x86_64) arch="x64" ;; + aarch64|arm64) arch="arm64" ;; + *) die "Unsupported architecture: $arch" "detect-arch" ;; + esac -Environment Variables: - SENTRY_INSTALL_DIR Override the installation directory - SENTRY_VERSION Install a specific version (e.g., 0.42.2, nightly) - SENTRY_INIT Set to 1 to run \`sentry init\` after installing - SENTRY_CLI_NO_TELEMETRY Set to 1 to disable installer error reporting + # The standalone binary is a Node.js SEA, and official Node.js builds + # target glibc. + if [[ "$os" == "linux" ]] && is_musl; then + libc_variant="musl" + die "The standalone binary requires glibc. On musl (Alpine), install Node.js and run: npm install -g sentry" "detect-libc" + fi -Examples: - curl -fsSL https://cli.sentry.dev/install | bash - curl -fsSL https://cli.sentry.dev/install | SENTRY_INIT=1 bash - curl -fsSL https://cli.sentry.dev/install | bash -s -- --version nightly - curl -fsSL https://cli.sentry.dev/install | bash -s -- --version 0.42.2 - curl -fsSL https://cli.sentry.dev/install | SENTRY_VERSION=nightly bash - curl -fsSL https://cli.sentry.dev/install | SENTRY_INSTALL_DIR="$HOME/.local/bin" bash -EOF + if [[ "$os" == "windows" ]]; then + suffix=".exe" + [[ "$arch" == "x64" ]] || die "Unsupported: windows-$arch (only windows-x64 is supported)" "detect-arch" + fi + + asset="sentry-${os}-${arch}${suffix}" } -requested_version="${SENTRY_VERSION:-}" -no_modify_path=false -no_completions=false -no_agent_skills=false -while [[ $# -gt 0 ]]; do - case "$1" in - -h|--help) usage; exit 0 ;; - -v|--version) - if [[ -n "${2:-}" ]]; then - requested_version="$2" - shift 2 - else - die "Error: --version requires a version argument" "args" - fi - ;; - --no-modify-path) - no_modify_path=true - shift - ;; - --no-completions) - no_completions=true - shift - ;; - --no-agent-skills) - no_agent_skills=true - shift - ;; - *) shift ;; +# Succeeds on musl-based Linux, such as Alpine. +is_musl() { + # `ldd --version` names the running libc, so trust it when it exists. + # musl's ldd exits non-zero, so capture its output instead of piping it + # under pipefail. + if command -v ldd >/dev/null 2>&1; then + grep -qi musl <<<"$(ldd --version 2>&1 || true)" + return + fi + + # Without ldd, look for the musl dynamic linker. glibc systems can have it + # too when the musl package is installed. + local musl_arch + case "$arch" in + x64) musl_arch="x86_64" ;; + arm64) musl_arch="aarch64" ;; esac -done - -# Detect OS -case "$(uname -s)" in - Darwin*) os="darwin" ;; - Linux*) os="linux" ;; - MINGW*|MSYS*|CYGWIN*) os="windows" ;; - *) die "Unsupported OS: $(uname -s)" "detect-os" ;; -esac - -# Detect architecture -arch=$(uname -m) -case "$arch" in - x86_64) arch="x64" ;; - aarch64|arm64) arch="arm64" ;; - *) die "Unsupported architecture: $arch" "detect-arch" ;; -esac - -# Official Node.js SEA binaries target glibc, not musl. -if [[ "$os" == "linux" ]]; then - detect_musl() { - # Heuristic 1: ldd --version outputs "musl libc" on musl systems. It reports - # the running libc, so it wins over the loader file below. musl's ldd exits - # non-zero, so capture its output instead of piping it under pipefail. - if command -v ldd >/dev/null 2>&1; then - grep -qi musl <<<"$(ldd --version 2>&1 || true)" - return - fi + [ -f "/lib/ld-musl-${musl_arch}.so.1" ] +} - # Heuristic 2: without ldd, check for the musl dynamic linker. glibc systems - # can have it too when the musl package is installed. - local musl_arch - case "$arch" in - x64) musl_arch="x86_64" ;; - arm64) musl_arch="aarch64" ;; - esac - [ -f "/lib/ld-musl-${musl_arch}.so.1" ] - } +# --------------------------------------------------------------------------- +# Where downloads go +# --------------------------------------------------------------------------- + +# Downloads go to the temporary directory. When it is full or not writable, +# they go to the directory setup will install into instead (see +# write_staged). There the binary takes the name of setup's own temp file, +# so setup renames it into place instead of copying it. +plan_staging_paths() { + local tmpdir="${TMPDIR:-${TMP:-${TEMP:-/tmp}}}" + tmp_binary="${tmpdir}/sentry-install-$$${suffix}" + blob_file="${tmpdir}/sentry-install-blob-$$" + init_binary="${tmpdir}/sentry-install-init-$$${suffix}" + trap 'rm -f "$tmp_binary" "$blob_file" "$init_binary"' EXIT + + local setup_dir + setup_dir=$(setup_install_dir) + if [[ -n "$setup_dir" ]]; then + setup_binary="${setup_dir}/sentry${suffix}.download" + setup_blob="${setup_dir}/sentry-install-blob-$$" + fi +} - if detect_musl; then - libc_variant="musl" - die "The standalone binary requires glibc. On musl (Alpine), install Node.js and run: npm install -g sentry" "detect-libc" +# Prints the directory `sentry cli setup` will install into. Keep this in +# sync with determineInstallDir in src/lib/binary.ts. +setup_install_dir() { + if [[ -n "${SENTRY_INSTALL_DIR:-}" ]]; then + printf '%s\n' "$SENTRY_INSTALL_DIR" + return fi -fi - -# Validate supported combinations -suffix="" -if [[ "$os" == "windows" ]]; then - suffix=".exe" - if [[ "$arch" != "x64" ]]; then - die "Unsupported: windows-$arch (only windows-x64 is supported)" "detect-arch" + if [[ "${XDG_BIN_HOME:-}" == /* || "${XDG_BIN_HOME:-}" =~ ^[A-Za-z]:[\\/] ]]; then + printf '%s\n' "$XDG_BIN_HOME" + return fi -fi - -# Download binary to a temp location -tmpdir="${TMPDIR:-${TMP:-${TEMP:-/tmp}}}" -tmp_binary="${tmpdir}/sentry-install-$$${suffix}" -blob_file="${tmpdir}/sentry-install-blob-$$" -init_binary="${tmpdir}/sentry-install-init-$$${suffix}" -version="" - -# Clean up temporary files after setup or on failure. -trap 'rm -f "$tmp_binary" "$blob_file" "$init_binary"' EXIT - -# When the temp directory is full or not writable, stage downloads in the -# directory setup installs into instead (determineInstallDir in -# src/lib/binary.ts). The binary takes the name of setup's own temp file -# there, so setup renames it into place instead of copying it. -setup_dir="${SENTRY_INSTALL_DIR:-}" -if [[ -z "$setup_dir" && ( "${XDG_BIN_HOME:-}" == /* || "${XDG_BIN_HOME:-}" =~ ^[A-Za-z]:[\\/] ) ]]; then - setup_dir="$XDG_BIN_HOME" -fi + [[ -n "${HOME:-}" ]] || return 0 + + local dir + for dir in "${HOME}/.local/bin" "${HOME}/bin"; do + if [[ -d "$dir" ]] && in_path "$dir"; then + printf '%s\n' "$dir" + return + fi + done + printf '%s\n' "${HOME}/.local/bin" +} + # Usage: in_path . Compares PATH entries like samePath: one trailing # slash is ignored, and so is case on macOS and Windows. The subshell keeps # nocasematch local. @@ -241,36 +339,30 @@ in_path() ( done return 1 ) -if [[ -z "$setup_dir" && -n "${HOME:-}" ]]; then - setup_dir="${HOME}/.local/bin" - for dir in "${HOME}/.local/bin" "${HOME}/bin"; do - if [[ -d "$dir" ]] && in_path "$dir"; then - setup_dir="$dir" - break - fi - done -fi -setup_binary="" -setup_blob="" -if [[ -n "$setup_dir" ]]; then - setup_binary="${setup_dir}/sentry${suffix}.download" - setup_blob="${setup_dir}/sentry-install-blob-$$" -fi -# Retry transient network failures (timeouts, refused connections, HTTP 408, -# 429, and 5xx) with curl's exponential backoff. The binary needs glibc 2.28 -# or macOS 11, whose curl (7.61, 7.64) has --retry-connrefused (7.52) but not -# --retry-all-errors (7.71). -curl_retry=(--retry 3 --retry-connrefused --retry-max-time 60) +# `sentry init` runs from a hard link to the downloaded binary: setup removes +# the temp binary after installing it, and the link means the installer never +# has to know which directory setup chose. +link_init_binary() { + init_binary="${tmp_binary%/*}/sentry-install-init-$$${suffix}" + [[ "${SENTRY_INIT:-}" == "1" ]] || return 0 + ln -f "$tmp_binary" "$init_binary" 2>/dev/null || cp "$tmp_binary" "$init_binary" +} -# Usage: download_to . Exits with curl's status: 22 for an HTTP -# error, 23 when the file cannot be written. +# --------------------------------------------------------------------------- +# Download building blocks +# +# Each one returns curl's convention for failures: 22 for an HTTP error and +# 23 when the file cannot be written. +# --------------------------------------------------------------------------- + +# Usage: download_to . download_to() { curl -fsSL "${curl_retry[@]}" -o "$2" "$1" } # Usage: unpack_to . gzip_intact has already checked the -# archive, so a failure here means the file could not be written (23). +# archive, so a failure here means the file could not be written. unpack_to() { gunzip -c "$1" > "$2" || return 23 } @@ -280,9 +372,10 @@ gzip_intact() { gunzip -t "$1" 2>/dev/null } -# Usage: write_staged [args...]. Runs -# ` [args...] ` for the path in . When the writer cannot -# write there (exit 23), points at and runs it again. +# Usage: write_staged [args...]. +# Runs ` [args...] ` for the path held in the variable named +# . When there is no room there (exit 23), points at +# and runs the writer again. write_staged() { local var=$1 fallback=$2 status shift 2 @@ -293,7 +386,7 @@ write_staged() { || ! mkdir -p "${fallback%/*}" 2>/dev/null; then return "$status" fi - echo -e "${MUTED}Not enough room in the temporary directory; using ${fallback%/*} instead.${NC}" >&2 + muted "Not enough room in the temporary directory; using ${fallback%/*} instead." >&2 printf -v "$var" '%s' "$fallback" "$@" "$fallback" && return 0 status=$? @@ -302,7 +395,7 @@ write_staged() { } # Usage: checksum_matches . A missing checksum or a -# missing hash tool counts as a match; a mismatch records the actual hash in +# missing hash tool counts as a match. A mismatch records the actual hash in # bad_checksum. bad_checksum="" checksum_matches() { @@ -313,7 +406,7 @@ checksum_matches() { elif command -v shasum >/dev/null 2>&1; then actual=$(shasum -a 256 "$1" | awk '{print $1}') || actual="" else - echo -e "${MUTED}Warning: sha256sum and shasum are unavailable; skipping checksum verification.${NC}" >&2 + muted "Warning: sha256sum and shasum are unavailable; skipping checksum verification." >&2 return 0 fi # Callers run this as a condition, where set -e and the ERR trap are off, so @@ -325,13 +418,13 @@ checksum_matches() { } # Usage: download_verified [check]. -# Downloads to the path in (see write_staged), and downloads it -# once more when the transfer breaks, the checksum does not match, or -# rejects the file. Returns curl's status for an HTTP error (22) or nowhere to -# write (23), since another try cannot help, and 1 when both copies are bad. +# Downloads to the path in (see write_staged). Tries once more +# when the transfer breaks, the checksum does not match, or rejects +# the file. Returns 22 or 23 right away, since another try cannot help, and 1 +# when both copies are bad. download_verified() { local var=$1 fallback=$2 url=$3 sha=$4 check=${5:-} attempt status=0 name - # Drop the query string: GHCR redirects to a signed URL. + # Name the file without the query string: GHCR redirects to a signed URL. name="${url%%\?*}" name="${name##*/}" for attempt in 1 2; do @@ -348,366 +441,380 @@ download_verified() { fi fi if [[ "$attempt" == 1 ]]; then - echo -e "${MUTED}The download of ${name} was incomplete or corrupt. Downloading it again...${NC}" >&2 + muted "The download of ${name} was incomplete or corrupt. Downloading it again..." >&2 fi done return "$status" } -no_room_message="There is not enough room to stage sentry (about 140 MB): the temporary directory and the install directory are both full or not writable. Free up space or set TMPDIR to another directory, then retry." +# Usage: require_download . Dies unless +# is 0, with the out-of-space message for 23 and otherwise. +require_download() { + case "$1" in + 0) return 0 ;; + 23) die "$no_room_message" "$3" ;; + *) die "$2" "$3" ;; + esac +} + +# Usage: require_good_checksum . Dies when the last download +# did not match its checksum. +require_good_checksum() { + [[ -z "$bad_checksum" ]] \ + || die "Checksum mismatch for ${asset} ${version}: expected $1, got ${bad_checksum}" "checksum" +} -# Usage: unpack_binary . +# Usage: unpack_binary . Unpacks the download to tmp_binary. unpack_binary() { write_staged tmp_binary "$setup_binary" unpack_to "$1" \ || die "$no_room_message" "unpack" } -if [[ "$requested_version" == "nightly" ]]; then - # Nightly build: download from GHCR via OCI blob protocol. - # No jq needed — parse JSON with awk. - # ghcr.io blob downloads redirect to Azure Blob Storage. curl -L would - # forward the Authorization header to Azure, which returns 404. Instead, - # extract the redirect URL and follow it without the auth header. +# --------------------------------------------------------------------------- +# Steps 3 and 4, stable: find the release and download it +# +# Sentry's release registry is the source of truth for versions, download +# URLs, and checksums. GitHub releases are only a fallback for registry +# outages, and they have no checksums. +# --------------------------------------------------------------------------- - echo -e "${MUTED}Fetching nightly build from GHCR...${NC}" +resolve_stable_release() { + local registry_path="latest" + if [[ -n "$requested_version" ]]; then + version="${requested_version#cli@}" + version="${version#v}" + [[ "$version" =~ ^[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.-]+)?$ ]] \ + || die "Invalid release version: ${version}" "resolve-version" + registry_path="$version" + fi - # Step 1: Get anonymous pull token - if ! GHCR_TOKEN=$(curl -sf "${curl_retry[@]}" \ - "https://ghcr.io/token?scope=repository:getsentry/toolkit:pull" \ - | awk -F'"' '{for(i=1;i<=NF;i++) if($i=="token"){print $(i+2);exit}}'); then - die "Failed to get GHCR token" "ghcr-token" + if fetch_registry_release "$registry_path"; then + return fi - if [[ -z "$GHCR_TOKEN" ]]; then - die "Failed to get GHCR token" "ghcr-token" + if [[ "$registry_status" == "404" && "$registry_path" != "latest" ]]; then + die "Unknown Sentry CLI version: ${version}" "resolve-version" fi - # Step 2: Fetch the OCI manifest for the :nightly tag - if ! MANIFEST=$(curl -sf "${curl_retry[@]}" \ - -H "Authorization: Bearer $GHCR_TOKEN" \ - -H "Accept: application/vnd.oci.image.manifest.v1+json" \ - "https://ghcr.io/v2/getsentry/toolkit/manifests/nightly"); then - die "Failed to fetch nightly manifest from GHCR" "ghcr-manifest" + muted "Could not resolve ${registry_path} from Sentry's release registry. Trying GitHub..." >&2 + if [[ -z "$version" ]]; then + find_latest_github_version fi - if [[ -z "$MANIFEST" ]]; then - die "Failed to fetch nightly manifest from GHCR" "ghcr-manifest" + gz_url="https://github.com/${GITHUB_REPO}/releases/download/cli@${version}/${asset}.gz" + raw_url="${gz_url%.gz}" + muted "Warning: GitHub fallback downloads are not checksum-verified." >&2 +} + +# Usage: fetch_registry_release . On success, sets version +# and the download URLs and checksums. Otherwise sets registry_status (000 +# when the registry is unreachable) and fails. +fetch_registry_release() { + local response metadata registry_version + # Read the body from curl's stdout, not a temp file: on some Windows shells, + # bash could not read the file that curl had just written. The status code + # follows the body on its own line. + response=$(curl -sS --max-time 10 "${curl_retry[@]}" -w '\n%{http_code}' \ + "${REGISTRY_URL}/$1" 2>/dev/null) || response="000" + registry_status="${response##*$'\n'}" + [[ "$registry_status" == "200" ]] || return 1 + + # Asset names, URLs, and checksums contain no whitespace, so stripping it + # lets the parsers below treat compact and pretty-printed JSON the same. + metadata=$(tr -d ' \t\r\n' <<< "${response%$'\n'*}") + registry_version=$(sed -n 's/.*"version":"\([^"]*\)".*/\1/p' <<< "$metadata") + + # Ignore an answer that is not the release that was asked for. + if [[ "$1" == "latest" ]]; then + [[ "$registry_version" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]] || return 1 + else + [[ "$registry_version" == "$version" ]] || return 1 fi - # Step 3: Extract version from manifest annotation - version=$(echo "$MANIFEST" \ - | awk -F'"' '{for(i=1;i<=NF;i++) if($i=="version"){print $(i+2);exit}}') - if [[ -z "$version" ]]; then - die "Failed to extract version from nightly manifest" "ghcr-version" + version="$registry_version" + { read -r gz_url; read -r gz_sha; } <<< "$(registry_file "$metadata" "${asset}.gz")" || true + { read -r raw_url; read -r raw_sha; } <<< "$(registry_file "$metadata" "$asset")" || true + if [[ -z "$gz_url" && -z "$raw_url" ]]; then + die "Sentry CLI ${version} has no ${asset} build" "resolve-asset" fi +} + +# Usage: registry_file . Prints the url and then the +# sha256 of one entry in the registry's `files` object, one per line (empty +# lines when the entry is missing). Expects whitespace-free JSON. +registry_file() { + awk -v key="\"$2\":{" ' + { + # Find "":{ and cut out its object by counting braces. + i = index($0, key) + if (!i) exit + s = substr($0, i + length(key) - 1) + n = length(s) + depth = 0 + for (j = 1; j <= n; j++) { + c = substr(s, j, 1) + if (c == "{") depth++ + else if (c == "}" && --depth == 0) break + } + obj = substr(s, 1, j) + + url = "" + sha = "" + if (match(obj, /"url":"https:\/\/[^"]*"/)) url = substr(obj, RSTART + 7, RLENGTH - 8) + if (match(obj, /"sha256-hex":"[0-9a-f]+"/)) sha = substr(obj, RSTART + 14, RLENGTH - 15) + print url + print sha + }' <<< "$1" +} + +# Registry outage fallback: sets version to the newest stable `cli@x.y.z` +# release. The repo also publishes MCP releases, so this may page through +# several pages of those first. +find_latest_github_version() { + local page releases release_tag="" + for page in {1..20}; do + releases=$(github_api "https://api.github.com/repos/${GITHUB_REPO}/releases?per_page=100&page=${page}") \ + || die "Failed to list Toolkit releases" "gh-version" + release_tag=$(newest_stable_cli_tag <<< "$releases") + if [[ -n "$release_tag" || "$releases" == "[]" ]]; then + break + fi + done + [[ -n "$release_tag" ]] \ + || die "Failed to fetch latest stable version from Sentry's release registry and GitHub. Retry or install a specific version with --version ." "resolve-version" + version="${release_tag#cli@}" +} - echo -e "${MUTED}Installing nightly sentry ${version}...${NC}" - - # Step 4: Find the blob digest for this platform's .gz file. - # Each OCI layer has "digest" before "org.opencontainers.image.title". - # Track the last-seen digest and print it when the target filename matches. - # This avoids sed newline replacement which differs between GNU and BSD. - gz_filename="sentry-${os}-${arch}${suffix}.gz" - digest=$(echo "$MANIFEST" \ - | awk -F'"' -v target="$gz_filename" '{ - for(i=1;i<=NF;i++){ - if($i=="digest") d=$(i+2) - if($i=="org.opencontainers.image.title"&&$(i+2)==target){print d;exit} +# Reads a page of GitHub releases (a JSON array) and prints the tag_name of +# the first non-prerelease `cli@x.y.z` release, or nothing. +# +# There is no jq, so this is a tiny JSON scanner. It tracks string quoting and +# brace depth so that only top-level fields of each release count, whatever +# the whitespace, field order, or nested assets. It reads the whole page: +# exiting early could SIGPIPE the writer under pipefail. +newest_stable_cli_tag() { + awk ' + function consider() { + if (selected == "" && !prerelease && tag ~ /^cli@[0-9]+\.[0-9]+\.[0-9]+$/) selected=tag + } + { + for (i=1; i<=length($0); i++) { + c=substr($0,i,1) + + # Inside a string: collect keys, and the value of tag_name. + if (quoted) { + if (escaped) { escaped=0; continue } + if (c == "\\") { escaped=1; invalid=1; continue } + if (c == "\"") { + quoted=0 + if (depth == 1 && !invalid) { + if (key == "") key=token + else if (key == "tag_name") tag=token + } + continue + } + if (depth == 1 && (key == "" || key == "tag_name")) { + if (length(token) < 128) token=token c + else invalid=1 + } + continue + } + + # Outside strings: track objects, field boundaries, and prerelease. + if (c == "\"") { quoted=1; token=""; invalid=0; continue } + if (c == "{") { + depth++ + if (depth == 1) { key=""; tag=""; prerelease=1 } + } else if (c == "}") { + if (depth == 1) consider() + depth-- + } else if (depth == 1) { + if (c == ",") key="" + else if (key == "prerelease" && c == "f" && substr($0,i,5) == "false") prerelease=0 } - }') - if [[ -z "$digest" ]]; then - die "No nightly build found for ${gz_filename}" "ghcr-digest" + } + } + END { print selected } + ' +} + +# Usage: github_api . Prints the response body. Runners that share an +# IP exhaust GitHub's anonymous rate limit, so send GITHUB_TOKEN or GH_TOKEN +# when one is set. The header goes through stdin, so the token stays out of +# the process list and of $BASH_COMMAND in error reports. Rate-limited +# responses (403, 429) are retried with a growing delay. +github_api() { + local token="${GITHUB_TOKEN:-${GH_TOKEN:-}}" response status attempt + for attempt in 1 2 3; do + if [[ -n "$token" ]]; then + response=$(curl -sSL "${curl_retry[@]}" -w '\n%{http_code}' -H @- "$1" \ + <<< "Authorization: Bearer ${token}") || return + else + response=$(curl -sSL "${curl_retry[@]}" -w '\n%{http_code}' "$1") || return + fi + status="${response##*$'\n'}" + case "$status" in + 200) + printf '%s\n' "${response%$'\n'*}" + return 0 + ;; + 403|429) ;; + *) return 22 ;; + esac + if [[ "$attempt" != 3 ]]; then + muted "GitHub rate-limited the request; retrying in $((attempt * 2))s..." >&2 + sleep $((attempt * 2)) + fi + done + if [[ -z "$token" ]]; then + muted "GitHub rate-limited this machine. Setting GITHUB_TOKEN raises the limit." >&2 fi + return 22 +} - # Step 5: Fetch the blob. GHCR normally redirects to Azure, but it can also - # return the blob directly with HTTP 200. Do not forward the auth header to - # the redirect target. The headers and then the status code go to stdout, - # so only the body needs room on disk (see write_staged). - # Usage: fetch_ghcr_blob . Sets blob_response. - fetch_ghcr_blob() { - blob_response=$(curl -sS "${curl_retry[@]}" -D - -o "$1" -w '%{http_code}' \ - -H "Authorization: Bearer $GHCR_TOKEN" \ - "https://ghcr.io/v2/getsentry/toolkit/blobs/${digest}") - } - blob_response="" - fetch_status=0 - write_staged blob_file "$setup_blob" fetch_ghcr_blob || fetch_status=$? - if [[ "$fetch_status" == 23 ]]; then - die "$no_room_message" "ghcr-blob" - elif [[ "$fetch_status" != 0 ]]; then - die "Failed to fetch nightly blob from GHCR" "ghcr-blob" +# Prefers the gzip asset (~37 MB instead of ~99 MB) and falls back to the raw +# binary when it is missing or unusable. A checksum mismatch on both tries is +# fatal, never a reason to fall back. +download_stable() { + muted "Downloading sentry v${version}..." + + if [[ -n "$gz_url" ]] \ + && download_verified blob_file "$setup_blob" "$gz_url" "$gz_sha" gzip_intact; then + unpack_binary "$blob_file" + return fi - blob_status="${blob_response##*$'\n'}" + require_good_checksum "$gz_sha" + [[ -n "$raw_url" ]] || die "Failed to download ${gz_url}" "download" + + rm -f "$blob_file" + local status=0 + download_verified tmp_binary "$setup_binary" "$raw_url" "$raw_sha" || status=$? + require_good_checksum "$raw_sha" + require_download "$status" "Failed to download ${raw_url}" "download" +} + +# --------------------------------------------------------------------------- +# Steps 3 and 4, nightly: find the build in GHCR and download it +# +# Each nightly is an OCI artifact tagged :nightly, with one gzip layer per +# platform. There is no jq, so the JSON is read with awk. +# --------------------------------------------------------------------------- + +download_nightly() { + muted "Fetching nightly build from GHCR..." + + local token_response token manifest digest + token_response=$(curl -sf "${curl_retry[@]}" \ + "https://ghcr.io/token?scope=repository:getsentry/toolkit:pull") \ + || die "Failed to get GHCR token" "ghcr-token" + token=$(json_field token <<< "$token_response") + [[ -n "$token" ]] || die "Failed to get GHCR token" "ghcr-token" + + manifest=$(curl -sf "${curl_retry[@]}" \ + -H "Authorization: Bearer $token" \ + -H "Accept: application/vnd.oci.image.manifest.v1+json" \ + "https://${GHCR_REPO}/manifests/nightly") \ + || die "Failed to fetch nightly manifest from GHCR" "ghcr-manifest" + [[ -n "$manifest" ]] || die "Failed to fetch nightly manifest from GHCR" "ghcr-manifest" + + version=$(json_field version <<< "$manifest") + [[ -n "$version" ]] || die "Failed to extract version from nightly manifest" "ghcr-version" + muted "Installing nightly sentry ${version}..." + + digest=$(layer_digest "${asset}.gz" <<< "$manifest") + [[ -n "$digest" ]] || die "No nightly build found for ${asset}.gz" "ghcr-digest" + + download_nightly_blob "$token" "$digest" + unpack_binary "$blob_file" +} + +# Usage: json_field . Prints the first string value of in the JSON +# on stdin. +json_field() { + awk -F'"' -v key="$1" '{for(i=1;i<=NF;i++) if($i==key){print $(i+2);exit}}' +} + +# Usage: layer_digest . Prints the digest of the manifest layer +# (on stdin) titled . Each layer has "digest" before +# "org.opencontainers.image.title", so remember the last digest and print it +# when the title matches. +layer_digest() { + awk -F'"' -v target="$1" '{ + for(i=1;i<=NF;i++){ + if($i=="digest") d=$(i+2) + if($i=="org.opencontainers.image.title"&&$(i+2)==target){print d;exit} + } + }' +} + +# Usage: download_nightly_blob . Downloads the layer to +# blob_file. GHCR usually redirects to Azure Blob Storage, but it can also +# return the blob directly with HTTP 200. curl -L would forward the +# Authorization header to Azure, which then returns 404, so follow the +# redirect by hand without it. +download_nightly_blob() { + local status=0 http_status redirect_url + blob_response="" + write_staged blob_file "$setup_blob" fetch_ghcr_blob "$1" "$2" || status=$? + require_download "$status" "Failed to fetch nightly blob from GHCR" "ghcr-blob" + http_status="${blob_response##*$'\n'}" - case "$blob_status" in + case "$http_status" in 200) gzip_intact "$blob_file" || die "The nightly blob from GHCR is corrupt" "ghcr-blob" - unpack_binary "$blob_file" ;; 3??) - redir_url=$(awk '/^[Ll][Oo][Cc][Aa][Tt][Ii][Oo][Nn]:[[:space:]]*/ { sub(/^[^:]*:[[:space:]]*/, ""); sub(/\r$/, ""); print; exit }' <<< "$blob_response") - if [[ -z "$redir_url" ]]; then - die "Failed to get blob redirect URL from GHCR" "ghcr-redirect" - fi - fetch_status=0 - download_verified blob_file "$setup_blob" "$redir_url" "" gzip_intact || fetch_status=$? - if [[ "$fetch_status" == 23 ]]; then - die "$no_room_message" "ghcr-blob" - elif [[ "$fetch_status" != 0 ]]; then - die "Failed to download nightly blob" "ghcr-blob" - fi - unpack_binary "$blob_file" + redirect_url=$(awk '/^[Ll][Oo][Cc][Aa][Tt][Ii][Oo][Nn]:[[:space:]]*/ { sub(/^[^:]*:[[:space:]]*/, ""); sub(/\r$/, ""); print; exit }' <<< "$blob_response") + [[ -n "$redirect_url" ]] || die "Failed to get blob redirect URL from GHCR" "ghcr-redirect" + status=0 + download_verified blob_file "$setup_blob" "$redirect_url" "" gzip_intact || status=$? + require_download "$status" "Failed to download nightly blob" "ghcr-blob" ;; *) - die "Failed to fetch nightly blob from GHCR (HTTP ${blob_status})" "ghcr-blob" + die "Failed to fetch nightly blob from GHCR (HTTP ${http_status})" "ghcr-blob" ;; esac +} -else - # Stable build. Sentry's release registry is the source of truth for - # versions, download URLs, and checksums. GitHub is only a fallback for - # registry outages. - if [[ -n "$requested_version" ]]; then - version="${requested_version#cli@}" - version="${version#v}" - if [[ ! "$version" =~ ^[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.-]+)?$ ]]; then - die "Invalid release version: ${version}" "resolve-version" - fi - registry_path="$version" - else - registry_path="latest" - fi - - asset="sentry-${os}-${arch}${suffix}" - gz_url="" - gz_sha="" - raw_url="" - raw_sha="" - registry_version="" - # Read the body from curl's stdout, not a temp file: on some Windows shells, - # bash could not read the file that curl had just written. The status code - # follows the body on its own line. - registry_response=$(curl -sS --max-time 10 "${curl_retry[@]}" -w '\n%{http_code}' \ - "https://release-registry.services.sentry.io/apps/sentry/${registry_path}" 2>/dev/null) \ - || registry_response="000" - registry_status="${registry_response##*$'\n'}" - if [[ "$registry_status" == "200" ]]; then - # Asset names, URLs, and checksums contain no whitespace, so stripping it - # lets the parser below treat compact and pretty-printed JSON the same. - metadata=$(tr -d ' \t\r\n' <<< "${registry_response%$'\n'*}") - registry_version=$(printf '%s\n' "$metadata" \ - | sed -n 's/.*"version":"\([^"]*\)".*/\1/p') - if [[ "$registry_path" == "latest" && ! "$registry_version" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then - registry_version="" - elif [[ "$registry_path" != "latest" && "$registry_version" != "$version" ]]; then - registry_version="" - fi - fi - - if [[ -n "$registry_version" ]]; then - version="$registry_version" - # Print the url and sha256 of one `files` entry, one per line. - registry_file() { - printf '%s\n' "$metadata" | awk -v key="\"$1\":{" ' - { - i = index($0, key) - if (!i) exit - s = substr($0, i + length(key) - 1) - n = length(s) - depth = 0 - for (j = 1; j <= n; j++) { - c = substr(s, j, 1) - if (c == "{") depth++ - else if (c == "}" && --depth == 0) break - } - obj = substr(s, 1, j) - url = "" - sha = "" - if (match(obj, /"url":"https:\/\/[^"]*"/)) url = substr(obj, RSTART + 7, RLENGTH - 8) - if (match(obj, /"sha256-hex":"[0-9a-f]+"/)) sha = substr(obj, RSTART + 14, RLENGTH - 15) - print url - print sha - }' - } - { read -r gz_url || true; read -r gz_sha || true; } <<< "$(registry_file "${asset}.gz")" - { read -r raw_url || true; read -r raw_sha || true; } <<< "$(registry_file "$asset")" - if [[ -z "$gz_url" && -z "$raw_url" ]]; then - die "Sentry CLI ${version} has no ${asset} build" "resolve-asset" - fi - elif [[ "$registry_status" == "404" && "$registry_path" != "latest" ]]; then - die "Unknown Sentry CLI version: ${version}" "resolve-version" - else - echo -e "${MUTED}Could not resolve ${registry_path} from Sentry's release registry. Trying GitHub...${NC}" >&2 - # Usage: github_api . Prints the response body. Runners that share an - # IP exhaust GitHub's anonymous rate limit, so send GITHUB_TOKEN or - # GH_TOKEN when one is set. The header goes through stdin, so the token - # stays out of the process list and of $BASH_COMMAND in error reports. - # Rate-limited responses (403, 429) are retried with a growing delay. - github_api() { - local token="${GITHUB_TOKEN:-${GH_TOKEN:-}}" response status attempt - for attempt in 1 2 3; do - if [[ -n "$token" ]]; then - response=$(curl -sSL "${curl_retry[@]}" -w '\n%{http_code}' -H @- "$1" \ - <<< "Authorization: Bearer ${token}") || return - else - response=$(curl -sSL "${curl_retry[@]}" -w '\n%{http_code}' "$1") || return - fi - status="${response##*$'\n'}" - case "$status" in - 200) - printf '%s\n' "${response%$'\n'*}" - return 0 - ;; - 403|429) ;; - *) return 22 ;; - esac - if [[ "$attempt" != 3 ]]; then - echo -e "${MUTED}GitHub rate-limited the request; retrying in $((attempt * 2))s...${NC}" >&2 - sleep $((attempt * 2)) - fi - done - if [[ -z "$token" ]]; then - echo -e "${MUTED}GitHub rate-limited this machine. Setting GITHUB_TOKEN raises the limit.${NC}" >&2 - fi - return 22 - } - if [[ "$registry_path" == "latest" ]]; then - release_tag="" - for page in {1..20}; do - if ! releases=$(github_api "https://api.github.com/repos/getsentry/toolkit/releases?per_page=100&page=${page}"); then - die "Failed to list Toolkit releases" "gh-version" - fi - # Read the full page: exiting awk early can SIGPIPE printf under pipefail. - # Match top-level release fields regardless of whitespace, field order, or nested assets. - release_tag=$(printf '%s\n' "$releases" \ - | awk ' - function consider() { - if (selected == "" && !prerelease && tag ~ /^cli@[0-9]+\.[0-9]+\.[0-9]+$/) selected=tag - } - { - for (i=1; i<=length($0); i++) { - c=substr($0,i,1) - if (quoted) { - if (escaped) { escaped=0; continue } - if (c == "\\") { escaped=1; invalid=1; continue } - if (c == "\"") { - quoted=0 - if (depth == 1 && !invalid) { - if (key == "") key=token - else if (key == "tag_name") tag=token - } - continue - } - if (depth == 1 && (key == "" || key == "tag_name")) { - if (length(token) < 128) token=token c - else invalid=1 - } - continue - } - if (c == "\"") { quoted=1; token=""; invalid=0; continue } - if (c == "{") { - depth++ - if (depth == 1) { key=""; tag=""; prerelease=1 } - } else if (c == "}") { - if (depth == 1) consider() - depth-- - } else if (depth == 1) { - if (c == ",") key="" - else if (key == "prerelease" && c == "f" && substr($0,i,5) == "false") prerelease=0 - } - } - } - END { print selected } - ') - if [[ -n "$release_tag" || "$releases" == "[]" ]]; then - break - fi - done - if [[ -z "$release_tag" ]]; then - die "Failed to fetch latest stable version from Sentry's release registry and GitHub. Retry or install a specific version with --version ." "resolve-version" - fi - version="${release_tag#cli@}" - fi - gz_url="https://github.com/getsentry/toolkit/releases/download/cli@${version}/${asset}.gz" - raw_url="${gz_url%.gz}" - echo -e "${MUTED}Warning: GitHub fallback downloads are not checksum-verified.${NC}" >&2 - fi - - echo -e "${MUTED}Downloading sentry v${version}...${NC}" +# Usage: fetch_ghcr_blob . Writes the body to +# and sets blob_response to the response headers followed by the status +# code. Those go to stdout, so only the body needs room on disk. +fetch_ghcr_blob() { + blob_response=$(curl -sS "${curl_retry[@]}" -D - -o "$3" -w '%{http_code}' \ + -H "Authorization: Bearer $1" \ + "https://${GHCR_REPO}/blobs/$2") +} - # Prefer the gzip asset (~60% smaller, ~37 MB vs ~99 MB); fall back to the - # raw binary when it is missing or unusable. A checksum mismatch on both - # tries is fatal, never a reason to fall back. - gz_status=1 - if [[ -n "$gz_url" ]]; then - download_verified blob_file "$setup_blob" "$gz_url" "$gz_sha" gzip_intact \ - && gz_status=0 || gz_status=$? +# --------------------------------------------------------------------------- +# Step 5: hand off to the binary +# --------------------------------------------------------------------------- + +# `sentry cli setup --install` places the binary and sets up PATH, +# completions, agent skills, and the welcome message. --channel makes later +# `sentry cli upgrade` calls track the same channel. +run_setup() { + local channel="stable" + if [[ "$requested_version" == "nightly" ]]; then + channel="nightly" fi - if [[ -n "$bad_checksum" ]]; then - die "Checksum mismatch for ${asset} ${version}: expected ${gz_sha}, got ${bad_checksum}" "checksum" - fi - if [[ "$gz_status" == 0 ]]; then - unpack_binary "$blob_file" - elif [[ -n "$raw_url" ]]; then - rm -f "$blob_file" - raw_status=0 - download_verified tmp_binary "$setup_binary" "$raw_url" "$raw_sha" || raw_status=$? - if [[ -n "$bad_checksum" ]]; then - die "Checksum mismatch for ${asset} ${version}: expected ${raw_sha}, got ${bad_checksum}" "checksum" - elif [[ "$raw_status" == 23 ]]; then - die "$no_room_message" "download" - elif [[ "$raw_status" != 0 ]]; then - die "Failed to download ${raw_url}" "download" - fi + local args=(--install --method curl --channel "$channel") + if $no_modify_path; then args+=(--no-modify-path); fi + if $no_completions; then args+=(--no-completions); fi + if $no_agent_skills; then args+=(--no-agent-skills); fi + + # curl | bash leaves stdin on the script pipe. Give setup the controlling + # terminal only when both output streams are interactive; setup checks + # whether this is a fresh human install before starting login. + if [[ -t 1 && -t 2 ]] && { exec 3/dev/null; then + "$tmp_binary" cli setup "${args[@]}" <&3 3<&- + exec 3<&- else - die "Failed to download ${gz_url}" "download" + "$tmp_binary" cli setup "${args[@]}" fi -fi +} -chmod +x "$tmp_binary" -init_binary="${tmp_binary%/*}/sentry-install-init-$$${suffix}" +# errtrace (-E) makes functions and command substitutions inherit the ERR +# trap; without it, a failure inside a function exits without a message or a +# report. +set -E +trap 'on_unexpected_failure "$?" "$LINENO" "$BASH_COMMAND" "${FUNCNAME[0]:-}"' ERR -# `sentry init` runs from a hard link to the downloaded binary: setup removes -# the temp binary after installing it, and the link means the installer never -# has to know which directory setup chose. -if [[ "${SENTRY_INIT:-}" == "1" ]]; then - ln -f "$tmp_binary" "$init_binary" 2>/dev/null || cp "$tmp_binary" "$init_binary" -fi - -# Delegate installation and configuration to the binary itself. -# setup --install handles: directory selection, binary placement, PATH, -# completions, agent skills, and the welcome message. -# --channel persists the release channel so future `sentry cli upgrade` -# calls track the same channel without requiring a flag. -if [[ "$requested_version" == "nightly" ]]; then - channel="nightly" -else - channel="stable" -fi -setup_args="--install --method curl --channel $channel" -if [[ "$no_modify_path" == "true" ]]; then - setup_args="$setup_args --no-modify-path" -fi -if [[ "$no_completions" == "true" ]]; then - setup_args="$setup_args --no-completions" -fi -if [[ "$no_agent_skills" == "true" ]]; then - setup_args="$setup_args --no-agent-skills" -fi - -# curl | bash leaves stdin on the script pipe. Give setup the controlling -# terminal only when both output streams are interactive; setup checks whether -# this is a fresh human install before starting login. -trap - ERR -if [[ -t 1 && -t 2 ]] && { exec 3/dev/null; then - # shellcheck disable=SC2086 - "$tmp_binary" cli setup $setup_args <&3 3<&- - exec 3<&- -else - # shellcheck disable=SC2086 - "$tmp_binary" cli setup $setup_args -fi - -# Optionally print the agent setup guide after install. `sentry init` only -# writes text, so it needs no terminal. -if [[ "${SENTRY_INIT:-}" == "1" ]]; then - "$init_binary" init -fi +main "$@" diff --git a/packages/cli/install.ps1 b/packages/cli/install.ps1 index f97f460a9..2aa5c9710 100644 --- a/packages/cli/install.ps1 +++ b/packages/cli/install.ps1 @@ -25,6 +25,9 @@ # Everything runs inside a function so `irm ... | iex` never changes the # caller's session preferences, and failures throw instead of calling `exit` # (which would close the user's terminal when run through iex). +# +# Invoke-Install, right below, is the whole install from start to finish. +# Every other function is a helper for one of its steps. function Install-SentryCli { $ErrorActionPreference = 'Stop' # Invoke-WebRequest progress rendering makes downloads dramatically slower @@ -38,67 +41,100 @@ function Install-SentryCli { Write-Verbose "Could not enable TLS 1.2: $_" } + $asset = 'sentry-windows-x64.exe' + # What error reports say about the install. Each step updates it. $state = @{ Step = 'start'; Version = 'unknown'; Arch = 'unknown' } - # Fire-and-forget error report via the envelope API, mirroring the bash - # installer. Uses the CLI's public write-only DSN. No PII collected. - function Send-InstallError([string]$Message) { - if ($env:SENTRY_CLI_NO_TELEMETRY -eq '1') { return } + function Invoke-Install { + Assert-WindowsX64 + $release = Resolve-Release + $binary = Save-Binary $release try { - $dsnKey = '1188a86f3f8168f089450587b00bca66' - $projectId = '4510776311808000' - $eventId = [guid]::NewGuid().ToString('N') - $header = @{ - event_id = $eventId - dsn = "https://$dsnKey@o1.ingest.us.sentry.io/$projectId" - } | ConvertTo-Json -Compress - $sentryEvent = @{ - event_id = $eventId - timestamp = [DateTime]::UtcNow.ToString('yyyy-MM-ddTHH:mm:ssZ') - platform = 'other' - level = 'error' - logger = 'install' - server_name = 'install-script' - message = @{ formatted = $Message } - tags = @{ - os = 'windows' - arch = $state.Arch - channel = 'stable' - step = $state.Step - 'install.version' = $state.Version - } - contexts = @{ - runtime = @{ name = 'powershell'; version = "$($PSVersionTable.PSVersion)" } - } - } | ConvertTo-Json -Compress -Depth 5 - $envelope = "$header`n{`"type`":`"event`"}`n$sentryEvent" - Invoke-WebRequest -UseBasicParsing -Method Post -TimeoutSec 2 ` - -Uri "https://o1.ingest.us.sentry.io/api/$projectId/envelope/" ` - -ContentType 'application/x-sentry-envelope' ` - -Headers @{ 'X-Sentry-Auth' = "Sentry sentry_key=$dsnKey,sentry_version=7" } ` - -Body $envelope | Out-Null - } catch { - Write-Verbose "Failed to report installer error: $_" + Invoke-Setup $binary + if ($env:SENTRY_INIT -eq '1') { Invoke-Init $binary } + } finally { + # The running temp binary cannot always be deleted on Windows; try anyway. + Remove-Item -LiteralPath $binary -Force -ErrorAction SilentlyContinue } } - function Stop-Install([string]$Message) { - Send-InstallError $Message - throw $Message + # ------------------------------------------------------------------------- + # Step 1: check that this machine can run the binary + # ------------------------------------------------------------------------- + + function Assert-WindowsX64 { + $state.Step = 'detect-os' + if ($env:OS -ne 'Windows_NT') { + Stop-Install 'This installer is for Windows. On macOS and Linux, run: curl https://cli.sentry.dev/install -fsS | bash' + } + + $state.Step = 'detect-arch' + # 32-bit PowerShell on 64-bit Windows reports x86 here and sets + # PROCESSOR_ARCHITEW6432 to the real architecture. + $arch = if ($env:PROCESSOR_ARCHITEW6432) { $env:PROCESSOR_ARCHITEW6432 } else { $env:PROCESSOR_ARCHITECTURE } + $state.Arch = "$arch" + if ($arch -ne 'AMD64') { + Stop-Install "Unsupported: windows-$arch (only windows-x64 is supported). Install Node.js and run: npm install -g sentry" + } + $state.Arch = 'x64' } - # Returns the HTTP status of a failed web request, or 0 without a response. - function Get-ErrorStatus($ErrorRecord) { - $response = $ErrorRecord.Exception.Response - if ($null -ne $response -and $null -ne $response.StatusCode) { - return [int]$response.StatusCode + # ------------------------------------------------------------------------- + # Step 2: find the release to install + # + # Sentry's release registry is the source of truth for versions, download + # URLs, and checksums. GitHub releases are only a fallback for registry + # outages, and they have no checksums. + # ------------------------------------------------------------------------- + + # Returns @{ Version; Gz; Raw }, where Gz and Raw are the compressed and + # plain downloads as @{ Url; Sha256 }, or $null when the release lacks one. + function Resolve-Release { + $state.Step = 'resolve-version' + if ($env:SENTRY_VERSION -eq 'nightly') { + Stop-Install 'The PowerShell installer only installs stable releases. Install stable, then run: sentry cli upgrade nightly' + } + + $version = '' + $registryPath = 'latest' + if ($env:SENTRY_VERSION) { + $version = $env:SENTRY_VERSION -replace '^cli@', '' -replace '^v', '' + $state.Version = $version + if ($version -notmatch '^\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?$') { + Stop-Install "Invalid release version: $version" + } + $registryPath = $version + } + + $metadata = Get-RegistryRelease $registryPath + if ($null -ne $metadata) { + $release = @{ + Version = "$($metadata.version)" + Gz = Get-RegistryFile $metadata "$asset.gz" + Raw = Get-RegistryFile $metadata $asset + } + $state.Version = $release.Version + if ($null -eq $release.Gz -and $null -eq $release.Raw) { + Stop-Install "Sentry CLI $($release.Version) has no $asset build" + } + return $release + } + + Write-Host "Could not resolve $registryPath from Sentry's release registry. Trying GitHub..." -ForegroundColor DarkGray + if (-not $version) { $version = Find-LatestToolkitVersion } + $state.Version = $version + Write-Warning 'GitHub fallback downloads are not checksum-verified.' + $base = "https://github.com/getsentry/toolkit/releases/download/cli@$version/$asset" + return @{ + Version = $version + Gz = @{ Url = "$base.gz"; Sha256 = '' } + Raw = @{ Url = $base; Sha256 = '' } } - return 0 } - # Fetch release metadata (download URLs and checksums) from Sentry's release - # registry. Returns $null when the registry is unreachable or returns - # something unusable; stops when a pinned version does not exist. + # Returns the registry's metadata for 'latest' or a version, or $null when + # the registry is unreachable or answers with something unusable. Stops + # when a pinned version does not exist. function Get-RegistryRelease([string]$Path) { try { $metadata = Invoke-RestMethod -UseBasicParsing -TimeoutSec 10 ` @@ -110,49 +146,25 @@ function Install-SentryCli { Write-Verbose "Release registry lookup failed: $_" return $null } + + # Ignore an answer that is not the release that was asked for. $registryVersion = "$($metadata.version)" if ($Path -eq 'latest' -and $registryVersion -notmatch '^\d+\.\d+\.\d+$') { return $null } if ($Path -ne 'latest' -and $registryVersion -ne $Path) { return $null } return $metadata } - # Returns @{ Url; Sha256 } for one registry file entry, or $null. + # Returns @{ Url; Sha256 } for one entry in the registry's `files`, or $null. function Get-RegistryFile($Metadata, [string]$Name) { $entry = $Metadata.files.PSObject.Properties[$Name] if ($null -eq $entry -or "$($entry.Value.url)" -notmatch '^https://') { return $null } return @{ Url = "$($entry.Value.url)"; Sha256 = "$($entry.Value.checksums.'sha256-hex')" } } - # Usage: Test-Sha256 ; a missing checksum matches. - function Test-Sha256([string]$Path, [string]$Expected) { - if (-not $Expected) { return $true } - $actual = (Get-FileHash -Algorithm SHA256 -LiteralPath $Path).Hash.ToLowerInvariant() - return $actual -eq $Expected.ToLowerInvariant() - } - - # Usage: Assert-Sha256 ; a missing checksum is a no-op. - function Assert-Sha256([string]$Path, [string]$Expected) { - if (Test-Sha256 $Path $Expected) { return } - $actual = (Get-FileHash -Algorithm SHA256 -LiteralPath $Path).Hash.ToLowerInvariant() - Stop-Install "Checksum mismatch for $asset ${version}: expected $Expected, got $actual" - } - - # Usage: Repair-Download . Downloads the file once - # more when it does not match its checksum, like the bash installer, since - # a broken transfer or proxy can corrupt the first copy. - function Repair-Download([string]$Path, [string]$Url, [string]$Expected) { - if (Test-Sha256 $Path $Expected) { return } - Write-Host 'The download was incomplete or corrupt. Downloading it again...' -ForegroundColor DarkGray - try { - Invoke-WebRequest -UseBasicParsing -Uri $Url -OutFile $Path - } catch { - Stop-Install "Failed to download $Url" - } - } - - # Registry outage fallback: the newest `cli@x.y.z` Toolkit release. + # Registry outage fallback: the newest stable `cli@x.y.z` release. The repo + # also publishes MCP releases, so this may page through several pages of + # those first. function Find-LatestToolkitVersion { - # GitHub may have many pages of MCP releases before its newest CLI release. for ($page = 1; $page -le 20; $page++) { try { # Windows PowerShell 5.1 emits a JSON array as one object; piping @@ -164,6 +176,7 @@ function Install-SentryCli { Stop-Install 'Failed to list Toolkit releases' } if ($releases.Count -eq 0) { break } + foreach ($release in $releases) { if (-not $release.prerelease -and "$($release.tag_name)" -match '^cli@\d+\.\d+\.\d+$') { return "$($release.tag_name)".Substring(4) @@ -173,143 +186,189 @@ function Install-SentryCli { Stop-Install "Failed to fetch latest stable version from Sentry's release registry and GitHub. Retry or set SENTRY_VERSION to install a specific version." } - # Entries of the persisted user PATH, expanded. Empty on non-Windows hosts. - function Get-UserPathEntries { - return @("$([Environment]::GetEnvironmentVariable('Path', 'User'))" -split ';' | Where-Object { $_ }) - } + # ------------------------------------------------------------------------- + # Step 3: download and verify the binary + # ------------------------------------------------------------------------- - $state.Step = 'detect-os' - if ($env:OS -ne 'Windows_NT') { - Stop-Install 'This installer is for Windows. On macOS and Linux, run: curl https://cli.sentry.dev/install -fsS | bash' - } + # Downloads the release to a temporary .exe and returns its path. Prefers + # the gzip download (~60% smaller) and falls back to the plain binary when + # it is missing. A checksum mismatch is fatal, never a reason to fall back. + function Save-Binary($Release) { + $state.Step = 'download' + $binary = Join-Path ([System.IO.Path]::GetTempPath()) "sentry-install-$([guid]::NewGuid().ToString('N')).exe" + $archive = "$binary.gz" - $state.Step = 'detect-arch' - # 32-bit PowerShell on 64-bit Windows reports x86 here and sets - # PROCESSOR_ARCHITEW6432 to the real architecture. - $arch = if ($env:PROCESSOR_ARCHITEW6432) { $env:PROCESSOR_ARCHITEW6432 } else { $env:PROCESSOR_ARCHITECTURE } - $state.Arch = "$arch" - if ($arch -ne 'AMD64') { - Stop-Install "Unsupported: windows-$arch (only windows-x64 is supported). Install Node.js and run: npm install -g sentry" + Write-Host "Downloading sentry v$($Release.Version)..." -ForegroundColor DarkGray + try { + if ($null -ne $Release.Gz -and (Save-Download $Release.Gz $archive)) { + Confirm-Download $Release.Gz $archive + Expand-Gzip $archive $binary + } elseif ($null -ne $Release.Raw) { + if (-not (Save-Download $Release.Raw $binary)) { + Stop-Install "Failed to download $($Release.Raw.Url)" + } + Confirm-Download $Release.Raw $binary + } else { + Stop-Install "Failed to download $($Release.Gz.Url)" + } + } catch { + Remove-Item -LiteralPath $binary -Force -ErrorAction SilentlyContinue + throw + } finally { + Remove-Item -LiteralPath $archive -Force -ErrorAction SilentlyContinue + } + return $binary } - $state.Arch = 'x64' - # Sentry's release registry is the source of truth for versions, download - # URLs, and checksums. GitHub is only a fallback for registry outages. - $state.Step = 'resolve-version' - if ($env:SENTRY_VERSION -eq 'nightly') { - Stop-Install 'The PowerShell installer only installs stable releases. Install stable, then run: sentry cli upgrade nightly' - } - $registryPath = 'latest' - $version = '' - if ($env:SENTRY_VERSION) { - $version = $env:SENTRY_VERSION -replace '^cli@', '' -replace '^v', '' - $state.Version = $version - if ($version -notmatch '^\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?$') { - Stop-Install "Invalid release version: $version" + # Downloads $File.Url to $Path. Returns $false when the download fails. + function Save-Download($File, [string]$Path) { + try { + Invoke-WebRequest -UseBasicParsing -Uri $File.Url -OutFile $Path + return $true + } catch { + Write-Verbose "Download of $($File.Url) failed: $_" + return $false } - $registryPath = $version } - $asset = 'sentry-windows-x64.exe' - $metadata = Get-RegistryRelease $registryPath - if ($null -ne $metadata) { - $version = "$($metadata.version)" - $gz = Get-RegistryFile $metadata "$asset.gz" - $raw = Get-RegistryFile $metadata $asset - if ($null -eq $gz -and $null -eq $raw) { - Stop-Install "Sentry CLI $version has no $asset build" + # Checks the download against its checksum, if it has one. A broken + # transfer or proxy can corrupt the first copy, so a mismatch downloads it + # once more before giving up. + function Confirm-Download($File, [string]$Path) { + if (Test-Sha256 $Path $File.Sha256) { return } + + Write-Host 'The download was incomplete or corrupt. Downloading it again...' -ForegroundColor DarkGray + if (-not (Save-Download $File $Path)) { + Stop-Install "Failed to download $($File.Url)" } - } else { - Write-Host "Could not resolve $registryPath from Sentry's release registry. Trying GitHub..." -ForegroundColor DarkGray - if (-not $version) { $version = Find-LatestToolkitVersion } - $base = "https://github.com/getsentry/toolkit/releases/download/cli@$version/$asset" - $gz = @{ Url = "$base.gz"; Sha256 = '' } - $raw = @{ Url = $base; Sha256 = '' } - Write-Warning 'GitHub fallback downloads are not checksum-verified.' + if (Test-Sha256 $Path $File.Sha256) { return } + + $actual = (Get-FileHash -Algorithm SHA256 -LiteralPath $Path).Hash.ToLowerInvariant() + Stop-Install "Checksum mismatch for $asset $($state.Version): expected $($File.Sha256), got $actual" } - $state.Version = $version - $state.Step = 'download' - $tmpBinary = Join-Path ([System.IO.Path]::GetTempPath()) "sentry-install-$([guid]::NewGuid().ToString('N')).exe" - $tmpArchive = "$tmpBinary.gz" + # True when the file matches the SHA-256 hex digest, or there is none. + function Test-Sha256([string]$Path, [string]$Expected) { + if (-not $Expected) { return $true } + $actual = (Get-FileHash -Algorithm SHA256 -LiteralPath $Path).Hash.ToLowerInvariant() + return $actual -eq $Expected.ToLowerInvariant() + } - Write-Host "Downloading sentry v$version..." -ForegroundColor DarkGray - try { - # Prefer the gzip asset (~60% smaller); fall back to the raw binary when it - # is missing. A checksum mismatch that a second download does not fix is - # fatal, never a reason to fall back. - $downloaded = $false - if ($null -ne $gz) { - try { - Invoke-WebRequest -UseBasicParsing -Uri $gz.Url -OutFile $tmpArchive - $downloaded = $true - } catch { - Write-Verbose "Compressed download failed, trying raw binary: $_" - } - } - if ($downloaded) { - Repair-Download $tmpArchive $gz.Url $gz.Sha256 - Assert-Sha256 $tmpArchive $gz.Sha256 - $source = [System.IO.File]::OpenRead($tmpArchive) - try { - $gzip = New-Object System.IO.Compression.GZipStream($source, [System.IO.Compression.CompressionMode]::Decompress) - $target = [System.IO.File]::Create($tmpBinary) - try { $gzip.CopyTo($target) } finally { $target.Dispose(); $gzip.Dispose() } - } finally { - $source.Dispose() - } - } elseif ($null -ne $raw) { - try { - Invoke-WebRequest -UseBasicParsing -Uri $raw.Url -OutFile $tmpBinary - } catch { - Stop-Install "Failed to download $($raw.Url)" - } - Repair-Download $tmpBinary $raw.Url $raw.Sha256 - Assert-Sha256 $tmpBinary $raw.Sha256 - } else { - Stop-Install "Failed to download $($gz.Url)" + function Expand-Gzip([string]$Archive, [string]$Destination) { + $source = [System.IO.File]::OpenRead($Archive) + try { + $gzip = New-Object System.IO.Compression.GZipStream($source, [System.IO.Compression.CompressionMode]::Decompress) + $target = [System.IO.File]::Create($Destination) + try { $gzip.CopyTo($target) } finally { $target.Dispose(); $gzip.Dispose() } + } finally { + $source.Dispose() } - } catch { - Remove-Item -LiteralPath $tmpBinary -Force -ErrorAction SilentlyContinue - throw - } finally { - Remove-Item -LiteralPath $tmpArchive -Force -ErrorAction SilentlyContinue } - try { - # Delegate placement, PATH, completions, agent skills, install-method - # recording, and first-run login to the binary itself. + # ------------------------------------------------------------------------- + # Step 4: hand off to the binary + # ------------------------------------------------------------------------- + + # `sentry cli setup --install` places the binary and handles the user PATH, + # completions, agent skills, install-method recording, and first-run login. + function Invoke-Setup([string]$Binary) { $state.Step = 'setup' $setupArgs = @('cli', 'setup', '--install', '--method', 'curl', '--channel', 'stable') if ($env:SENTRY_NO_MODIFY_PATH -eq '1') { $setupArgs += '--no-modify-path' } + $userPathBefore = Get-UserPathEntries - & $tmpBinary @setupArgs + & $Binary @setupArgs if ($LASTEXITCODE -ne 0) { Stop-Install "sentry cli setup failed with exit code $LASTEXITCODE" } - # Setup persists the install directory on the user PATH, which only new - # terminals pick up. Mirror what it added into this session too. + # Setup saves the install directory to the user PATH, which only new + # terminals pick up. Add what it added to this session too. $added = @(Get-UserPathEntries | Where-Object { $userPathBefore -notcontains $_ }) if ($added.Count -gt 0) { $env:PATH = (@($added) + @("$env:PATH")) -join [System.IO.Path]::PathSeparator } + } - if ($env:SENTRY_INIT -eq '1') { - # Run init from the downloaded binary, which is the one setup just - # installed, so the installer never has to know where setup put it. - $state.Step = 'init' - & $tmpBinary init - if ($LASTEXITCODE -ne 0) { - # Like the bash installer, report init failures to the caller but not - # to installer telemetry: init errors are not installation failures. - throw "sentry init failed with exit code $LASTEXITCODE" - } + # Runs init from the downloaded binary, which is the one setup just + # installed, so the installer never has to know where setup put it. + function Invoke-Init([string]$Binary) { + $state.Step = 'init' + & $Binary init + if ($LASTEXITCODE -ne 0) { + # Like the bash installer, report init failures to the caller but not + # to installer telemetry: init errors are not installation failures. + throw "sentry init failed with exit code $LASTEXITCODE" } - } finally { - # The running temp binary cannot always be deleted on Windows; try anyway. - Remove-Item -LiteralPath $tmpBinary -Force -ErrorAction SilentlyContinue } + + # Entries of the persisted user PATH, expanded. Empty on non-Windows hosts. + function Get-UserPathEntries { + return @("$([Environment]::GetEnvironmentVariable('Path', 'User'))" -split ';' | Where-Object { $_ }) + } + + # ------------------------------------------------------------------------- + # Errors + # ------------------------------------------------------------------------- + + # Reports the error, then throws it. + function Stop-Install([string]$Message) { + Send-InstallError $Message + throw $Message + } + + # Returns the HTTP status of a failed web request, or 0 without a response. + function Get-ErrorStatus($ErrorRecord) { + $response = $ErrorRecord.Exception.Response + if ($null -ne $response -and $null -ne $response.StatusCode) { + return [int]$response.StatusCode + } + return 0 + } + + # Fire-and-forget error report via the envelope API, mirroring the bash + # installer. Uses the CLI's public write-only DSN. No PII collected. + function Send-InstallError([string]$Message) { + if ($env:SENTRY_CLI_NO_TELEMETRY -eq '1') { return } + try { + $dsnKey = '1188a86f3f8168f089450587b00bca66' + $projectId = '4510776311808000' + $eventId = [guid]::NewGuid().ToString('N') + $header = @{ + event_id = $eventId + dsn = "https://$dsnKey@o1.ingest.us.sentry.io/$projectId" + } | ConvertTo-Json -Compress + $sentryEvent = @{ + event_id = $eventId + timestamp = [DateTime]::UtcNow.ToString('yyyy-MM-ddTHH:mm:ssZ') + platform = 'other' + level = 'error' + logger = 'install' + server_name = 'install-script' + message = @{ formatted = $Message } + tags = @{ + os = 'windows' + arch = $state.Arch + channel = 'stable' + step = $state.Step + 'install.version' = $state.Version + } + contexts = @{ + runtime = @{ name = 'powershell'; version = "$($PSVersionTable.PSVersion)" } + } + } | ConvertTo-Json -Compress -Depth 5 + $envelope = "$header`n{`"type`":`"event`"}`n$sentryEvent" + Invoke-WebRequest -UseBasicParsing -Method Post -TimeoutSec 2 ` + -Uri "https://o1.ingest.us.sentry.io/api/$projectId/envelope/" ` + -ContentType 'application/x-sentry-envelope' ` + -Headers @{ 'X-Sentry-Auth' = "Sentry sentry_key=$dsnKey,sentry_version=7" } ` + -Body $envelope | Out-Null + } catch { + Write-Verbose "Failed to report installer error: $_" + } + } + + Invoke-Install } Install-SentryCli diff --git a/packages/cli/test/lib/install-script.test.ts b/packages/cli/test/lib/install-script.test.ts index ced2aa609..86dc21ebd 100644 --- a/packages/cli/test/lib/install-script.test.ts +++ b/packages/cli/test/lib/install-script.test.ts @@ -862,7 +862,9 @@ exec /usr/bin/gunzip "$@" const failure = '(exit 1): chmod +x "$tmp_binary"'; expect(result.status).not.toBe(0); - expect(result.output).toMatch(/Unexpected failure at line \d+ \(exit 1\)/); + expect(result.output).toMatch( + /Unexpected failure at line \d+ in main\(\) \(exit 1\)/, + ); expect(result.output).toContain(failure); // spawnSync returns only after the backgrounded report_error subshell // exits, because it keeps the installer's stdout and stderr open. From b79298c3339c35d623d05ceb44d37b265ad3032c Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Wed, 18 Nov 2026 21:55:55 +0000 Subject: [PATCH 2/3] refactor(cli): download straight into the install directory The bash installer now downloads into the directory `sentry cli setup` installs into, as setup's own temp file (sentry.download), instead of $TMPDIR with a fallback to that directory when the temp directory is full. Setup renames the download into place, a small or full /tmp no longer matters, and write_staged and the fallback paths go away. Co-Authored-By: Evan Purkhiser <1421724+evanpurkhiser@users.noreply.github.com> --- packages/cli/install | 119 +++++++------------ packages/cli/test/lib/install-script.test.ts | 54 ++++----- 2 files changed, 64 insertions(+), 109 deletions(-) diff --git a/packages/cli/install b/packages/cli/install index b8bb4b2a6..e16ab0f9b 100755 --- a/packages/cli/install +++ b/packages/cli/install @@ -12,7 +12,7 @@ # 1. Read the command-line flags. # 2. Work out which build this machine needs (OS, CPU, libc). # 3. Find that build for the requested version (stable or nightly). -# 4. Download it to a temporary file and verify it. +# 4. Download it into the install directory and verify it. # 5. Hand off to `sentry cli setup`, and optionally `sentry init`. # # Everything is a function, and main() runs on the last line. If the download @@ -39,7 +39,7 @@ GHCR_REPO="ghcr.io/v2/getsentry/toolkit" # --retry-all-errors (7.71). curl_retry=(--retry 3 --retry-connrefused --retry-max-time 60) -no_room_message="There is not enough room to stage sentry (about 140 MB): the temporary directory and the install directory are both full or not writable. Free up space or set TMPDIR to another directory, then retry." +no_room_message="There is not enough room to download sentry (about 140 MB) into the install directory, or it is not writable. Free up space or set SENTRY_INSTALL_DIR to another directory, then retry." # Installer state. The steps below fill these in; error reports read them. requested_version="${SENTRY_VERSION:-}" # "", "nightly", or a version @@ -58,18 +58,15 @@ raw_url="" raw_sha="" registry_status="" # HTTP status of the release registry lookup -# Download paths. plan_staging_paths sets them. When the temp directory is -# full, write_staged moves tmp_binary and blob_file to their setup_* fallbacks. -tmp_binary="" # the downloaded binary +# Download paths, all in the install directory. plan_download_paths sets them. +binary="" # the downloaded binary blob_file="" # the downloaded .gz, before unpacking init_binary="" # hard link to the binary for `sentry init` -setup_binary="" # fallback for tmp_binary in the install directory -setup_blob="" # fallback for blob_file in the install directory main() { parse_args "$@" detect_platform - plan_staging_paths + plan_download_paths if [[ "$requested_version" == "nightly" ]]; then download_nightly @@ -77,7 +74,7 @@ main() { resolve_stable_release download_stable fi - chmod +x "$tmp_binary" + chmod +x "$binary" link_init_binary # From here on, a failure belongs to sentry itself, not to the installer: @@ -279,23 +276,23 @@ is_musl() { # Where downloads go # --------------------------------------------------------------------------- -# Downloads go to the temporary directory. When it is full or not writable, -# they go to the directory setup will install into instead (see -# write_staged). There the binary takes the name of setup's own temp file, -# so setup renames it into place instead of copying it. -plan_staging_paths() { - local tmpdir="${TMPDIR:-${TMP:-${TEMP:-/tmp}}}" - tmp_binary="${tmpdir}/sentry-install-$$${suffix}" - blob_file="${tmpdir}/sentry-install-blob-$$" - init_binary="${tmpdir}/sentry-install-init-$$${suffix}" - trap 'rm -f "$tmp_binary" "$blob_file" "$init_binary"' EXIT - - local setup_dir - setup_dir=$(setup_install_dir) - if [[ -n "$setup_dir" ]]; then - setup_binary="${setup_dir}/sentry${suffix}.download" - setup_blob="${setup_dir}/sentry-install-blob-$$" +# Downloads go straight into the directory `sentry cli setup` will install +# into, and the binary takes the name of setup's own temp file. Setup then +# renames it into place instead of copying it, and a small or full /tmp does +# not matter. The EXIT trap removes whatever setup did not take. +plan_download_paths() { + local dir + dir=$(setup_install_dir) + if [[ -z "$dir" ]]; then + dir="${TMPDIR:-${TMP:-${TEMP:-/tmp}}}" fi + mkdir -p "$dir" 2>/dev/null \ + || die "Could not create the install directory. Set SENTRY_INSTALL_DIR to a writable directory, then retry." "download-dir" + + binary="${dir}/sentry${suffix}.download" + blob_file="${dir}/sentry-install-blob-$$" + init_binary="${dir}/sentry-install-init-$$${suffix}" + trap 'rm -f "$binary" "$blob_file" "$init_binary"' EXIT } # Prints the directory `sentry cli setup` will install into. Keep this in @@ -340,13 +337,11 @@ in_path() ( return 1 ) -# `sentry init` runs from a hard link to the downloaded binary: setup removes -# the temp binary after installing it, and the link means the installer never -# has to know which directory setup chose. +# `sentry init` runs from a hard link to the downloaded binary, because setup +# renames the binary away when it installs it. link_init_binary() { - init_binary="${tmp_binary%/*}/sentry-install-init-$$${suffix}" [[ "${SENTRY_INIT:-}" == "1" ]] || return 0 - ln -f "$tmp_binary" "$init_binary" 2>/dev/null || cp "$tmp_binary" "$init_binary" + ln -f "$binary" "$init_binary" 2>/dev/null || cp "$binary" "$init_binary" } # --------------------------------------------------------------------------- @@ -361,39 +356,11 @@ download_to() { curl -fsSL "${curl_retry[@]}" -o "$2" "$1" } -# Usage: unpack_to . gzip_intact has already checked the -# archive, so a failure here means the file could not be written. -unpack_to() { - gunzip -c "$1" > "$2" || return 23 -} - # Usage: gzip_intact . gzip_intact() { gunzip -t "$1" 2>/dev/null } -# Usage: write_staged [args...]. -# Runs ` [args...] ` for the path held in the variable named -# . When there is no room there (exit 23), points at -# and runs the writer again. -write_staged() { - local var=$1 fallback=$2 status - shift 2 - "$@" "${!var}" && return 0 - status=$? - rm -f "${!var}" - if [[ "$status" != 23 || -z "$fallback" || "${!var}" == "$fallback" ]] \ - || ! mkdir -p "${fallback%/*}" 2>/dev/null; then - return "$status" - fi - muted "Not enough room in the temporary directory; using ${fallback%/*} instead." >&2 - printf -v "$var" '%s' "$fallback" - "$@" "$fallback" && return 0 - status=$? - rm -f "$fallback" - return "$status" -} - # Usage: checksum_matches . A missing checksum or a # missing hash tool counts as a match. A mismatch records the actual hash in # bad_checksum. @@ -417,25 +384,25 @@ checksum_matches() { return 1 } -# Usage: download_verified [check]. -# Downloads to the path in (see write_staged). Tries once more -# when the transfer breaks, the checksum does not match, or rejects -# the file. Returns 22 or 23 right away, since another try cannot help, and 1 -# when both copies are bad. +# Usage: download_verified [check]. Downloads to +# . Tries once more when the transfer breaks, the checksum does not +# match, or rejects the file. Returns 22 or 23 right away, since +# another try cannot help, and 1 when both copies are bad. download_verified() { - local var=$1 fallback=$2 url=$3 sha=$4 check=${5:-} attempt status=0 name + local file=$1 url=$2 sha=$3 check=${4:-} attempt status=0 name # Name the file without the query string: GHCR redirects to a signed URL. name="${url%%\?*}" name="${name##*/}" for attempt in 1 2; do bad_checksum="" - if write_staged "$var" "$fallback" download_to "$url"; then - if checksum_matches "${!var}" "$sha" && { [[ -z "$check" ]] || "$check" "${!var}"; }; then + if download_to "$url" "$file"; then + if checksum_matches "$file" "$sha" && { [[ -z "$check" ]] || "$check" "$file"; }; then return 0 fi status=1 else status=$? + rm -f "$file" if [[ "$status" == 22 || "$status" == 23 ]]; then return "$status" fi @@ -464,10 +431,12 @@ require_good_checksum() { || die "Checksum mismatch for ${asset} ${version}: expected $1, got ${bad_checksum}" "checksum" } -# Usage: unpack_binary . Unpacks the download to tmp_binary. +# Usage: unpack_binary . Unpacks the download to binary, then +# deletes the archive. gzip_intact has already checked the archive, so a +# failure here means the binary could not be written. unpack_binary() { - write_staged tmp_binary "$setup_binary" unpack_to "$1" \ - || die "$no_room_message" "unpack" + gunzip -c "$1" > "$binary" || die "$no_room_message" "unpack" + rm -f "$1" } # --------------------------------------------------------------------------- @@ -677,7 +646,7 @@ download_stable() { muted "Downloading sentry v${version}..." if [[ -n "$gz_url" ]] \ - && download_verified blob_file "$setup_blob" "$gz_url" "$gz_sha" gzip_intact; then + && download_verified "$blob_file" "$gz_url" "$gz_sha" gzip_intact; then unpack_binary "$blob_file" return fi @@ -686,7 +655,7 @@ download_stable() { rm -f "$blob_file" local status=0 - download_verified tmp_binary "$setup_binary" "$raw_url" "$raw_sha" || status=$? + download_verified "$binary" "$raw_url" "$raw_sha" || status=$? require_good_checksum "$raw_sha" require_download "$status" "Failed to download ${raw_url}" "download" } @@ -753,7 +722,7 @@ layer_digest() { download_nightly_blob() { local status=0 http_status redirect_url blob_response="" - write_staged blob_file "$setup_blob" fetch_ghcr_blob "$1" "$2" || status=$? + fetch_ghcr_blob "$1" "$2" "$blob_file" || status=$? require_download "$status" "Failed to fetch nightly blob from GHCR" "ghcr-blob" http_status="${blob_response##*$'\n'}" @@ -765,7 +734,7 @@ download_nightly_blob() { redirect_url=$(awk '/^[Ll][Oo][Cc][Aa][Tt][Ii][Oo][Nn]:[[:space:]]*/ { sub(/^[^:]*:[[:space:]]*/, ""); sub(/\r$/, ""); print; exit }' <<< "$blob_response") [[ -n "$redirect_url" ]] || die "Failed to get blob redirect URL from GHCR" "ghcr-redirect" status=0 - download_verified blob_file "$setup_blob" "$redirect_url" "" gzip_intact || status=$? + download_verified "$blob_file" "$redirect_url" "" gzip_intact || status=$? require_download "$status" "Failed to download nightly blob" "ghcr-blob" ;; *) @@ -804,10 +773,10 @@ run_setup() { # terminal only when both output streams are interactive; setup checks # whether this is a fresh human install before starting login. if [[ -t 1 && -t 2 ]] && { exec 3/dev/null; then - "$tmp_binary" cli setup "${args[@]}" <&3 3<&- + "$binary" cli setup "${args[@]}" <&3 3<&- exec 3<&- else - "$tmp_binary" cli setup "${args[@]}" + "$binary" cli setup "${args[@]}" fi } diff --git a/packages/cli/test/lib/install-script.test.ts b/packages/cli/test/lib/install-script.test.ts index 86dc21ebd..957a619dc 100644 --- a/packages/cli/test/lib/install-script.test.ts +++ b/packages/cli/test/lib/install-script.test.ts @@ -238,9 +238,12 @@ esac : []; } + /** Installer files left behind in the temp or install directory. */ function installerTempFiles(): string[] { - return readdirSync(testDir).filter((name) => - name.startsWith("sentry-install-"), + const installed = existsSync(installDir) ? readdirSync(installDir) : []; + return [...readdirSync(testDir), ...installed].filter( + (name) => + name.startsWith("sentry-install-") || name.endsWith(".download"), ); } @@ -456,7 +459,7 @@ process.exitCode = result.status ?? 1; { response: "direct HTTP 200 response", redirect: false }, { response: "HTTP redirect", redirect: true }, ])( - "stages nightly from a $response in the install directory without a temp directory", + "downloads nightly from a $response into the install directory", ({ redirect }) => { configureNightlyDownload(redirect); env.TMPDIR = join(testDir, "deleted"); @@ -733,45 +736,26 @@ exec ${realCurl} "\${args[@]}" expect(existsSync(join(installDir, "sentry"))).toBe(true); }); - // CLI-BJ: a full temporary directory made gunzip hit the generic ERR trap. - test("unpacks into the install directory when the temp directory is full", () => { - // The first unpack fails like a full disk; later ones work. - writeFileSync( - join(binDir, "gunzip"), - `#!/usr/bin/env bash -if [[ "$1" == "-c" && ! -e "$SENTRY_TEST_DIR/unpacked-once" ]]; then - touch "$SENTRY_TEST_DIR/unpacked-once" - echo 'gzip: stdout: No space left on device' >&2 - exit 1 -fi -exec /usr/bin/gunzip "$@" -`, - { mode: 0o755 }, - ); + test("downloads into the install directory as setup's own temp file", () => { const result = install(); expect(result.status, result.output).toBe(0); - expect(result.output).not.toContain("Unexpected failure"); - // Staged under setup's own temp name, which setup renames into place. + // Setup renames sentry.download into place instead of copying it. expect(recorded("setup-binary")).toEqual([ join(installDir, "sentry.download"), ]); - expect(existsSync(join(installDir, "sentry"))).toBe(true); - expect(installerTempFiles()).toEqual([]); + expect(readdirSync(installDir)).toEqual(["sentry"]); }); - test("downloads into the install directory when the temp directory is missing", () => { + test("does not need the temp directory", () => { env.TMPDIR = join(testDir, "deleted"); const result = install(); expect(result.status, result.output).toBe(0); - expect(recorded("setup-binary")).toEqual([ - join(installDir, "sentry.download"), - ]); expect(readdirSync(installDir)).toEqual(["sentry"]); }); - test("stages in a home bin directory listed in PATH with a trailing slash", () => { + test("downloads into a home bin directory listed in PATH with a trailing slash", () => { const homeBin = join(testDir, "home", "bin"); mkdirSync(homeBin); delete env.SENTRY_INSTALL_DIR; @@ -781,13 +765,13 @@ exec /usr/bin/gunzip "$@" expect(result.status, result.output).toBe(0); // Setup's determineInstallDir picks the same directory, so it can rename - // the staged binary instead of copying it. + // the download instead of copying it. expect(recorded("setup-binary")).toEqual([ join(homeBin, "sentry.download"), ]); }); - test("names the full disk only when no directory has room", () => { + test("names a full install directory", () => { writeFileSync( join(binDir, "gunzip"), `#!/usr/bin/env bash @@ -802,7 +786,9 @@ exec /usr/bin/gunzip "$@" const result = install(); expect(result.status).not.toBe(0); - expect(result.output).toContain("There is not enough room to stage sentry"); + expect(result.output).toContain( + "There is not enough room to download sentry", + ); expect(result.output).not.toContain("Unexpected failure"); expect(recorded("setup-args")).toEqual([]); expect(installerTempFiles()).toEqual([]); @@ -860,7 +846,7 @@ exec /usr/bin/gunzip "$@" delete env.SENTRY_CLI_NO_TELEMETRY; const result = install(); - const failure = '(exit 1): chmod +x "$tmp_binary"'; + const failure = '(exit 1): chmod +x "$binary"'; expect(result.status).not.toBe(0); expect(result.output).toMatch( /Unexpected failure at line \d+ in main\(\) \(exit 1\)/, @@ -956,9 +942,9 @@ exec /usr/bin/gunzip "$@" expect(recorded("setup-args")).toContain("setup"); expect(recorded("post-args")).toEqual(["init"]); const [initBinary] = recorded("post-binary"); - expect(initBinary?.startsWith(join(testDir, "sentry-install-init-"))).toBe( - true, - ); + expect( + initBinary?.startsWith(join(installDir, "sentry-install-init-")), + ).toBe(true); expect(installerTempFiles()).toEqual([]); }); From 086b2a42184502deae701ac5f930535b4adaac60 Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Wed, 18 Nov 2026 21:59:05 +0000 Subject: [PATCH 3/3] refactor(cli): drop the GitHub fallback for latest in both installers When Sentry's release registry is down, an unpinned install now fails with "Failed to fetch latest stable version... install a specific version" instead of paging through GitHub releases for the newest stable cli@ tag. A pinned version still downloads from its GitHub release. This removes the GitHub API client, its rate-limit and token handling, and the release-page parsing from install, and Find-LatestToolkitVersion from install.ps1. Co-Authored-By: BYK <126780+BYK@users.noreply.github.com> --- packages/cli/install | 115 +----------- packages/cli/install.ps1 | 34 +--- .../cli/test/lib/install-ps1-script.test.ts | 7 - packages/cli/test/lib/install-scenarios.ts | 33 +--- packages/cli/test/lib/install-script.test.ts | 169 ------------------ 5 files changed, 12 insertions(+), 346 deletions(-) diff --git a/packages/cli/install b/packages/cli/install index e16ab0f9b..2bf7c74f0 100755 --- a/packages/cli/install +++ b/packages/cli/install @@ -443,8 +443,8 @@ unpack_binary() { # Steps 3 and 4, stable: find the release and download it # # Sentry's release registry is the source of truth for versions, download -# URLs, and checksums. GitHub releases are only a fallback for registry -# outages, and they have no checksums. +# URLs, and checksums. When it is down, a pinned version still downloads from +# its GitHub release, without checksums; "latest" needs the registry. # --------------------------------------------------------------------------- resolve_stable_release() { @@ -464,10 +464,10 @@ resolve_stable_release() { die "Unknown Sentry CLI version: ${version}" "resolve-version" fi + [[ -n "$version" ]] \ + || die "Failed to fetch latest stable version from Sentry's release registry. Retry or install a specific version with --version ." "resolve-version" + muted "Could not resolve ${registry_path} from Sentry's release registry. Trying GitHub..." >&2 - if [[ -z "$version" ]]; then - find_latest_github_version - fi gz_url="https://github.com/${GITHUB_REPO}/releases/download/cli@${version}/${asset}.gz" raw_url="${gz_url%.gz}" muted "Warning: GitHub fallback downloads are not checksum-verified." >&2 @@ -534,111 +534,6 @@ registry_file() { }' <<< "$1" } -# Registry outage fallback: sets version to the newest stable `cli@x.y.z` -# release. The repo also publishes MCP releases, so this may page through -# several pages of those first. -find_latest_github_version() { - local page releases release_tag="" - for page in {1..20}; do - releases=$(github_api "https://api.github.com/repos/${GITHUB_REPO}/releases?per_page=100&page=${page}") \ - || die "Failed to list Toolkit releases" "gh-version" - release_tag=$(newest_stable_cli_tag <<< "$releases") - if [[ -n "$release_tag" || "$releases" == "[]" ]]; then - break - fi - done - [[ -n "$release_tag" ]] \ - || die "Failed to fetch latest stable version from Sentry's release registry and GitHub. Retry or install a specific version with --version ." "resolve-version" - version="${release_tag#cli@}" -} - -# Reads a page of GitHub releases (a JSON array) and prints the tag_name of -# the first non-prerelease `cli@x.y.z` release, or nothing. -# -# There is no jq, so this is a tiny JSON scanner. It tracks string quoting and -# brace depth so that only top-level fields of each release count, whatever -# the whitespace, field order, or nested assets. It reads the whole page: -# exiting early could SIGPIPE the writer under pipefail. -newest_stable_cli_tag() { - awk ' - function consider() { - if (selected == "" && !prerelease && tag ~ /^cli@[0-9]+\.[0-9]+\.[0-9]+$/) selected=tag - } - { - for (i=1; i<=length($0); i++) { - c=substr($0,i,1) - - # Inside a string: collect keys, and the value of tag_name. - if (quoted) { - if (escaped) { escaped=0; continue } - if (c == "\\") { escaped=1; invalid=1; continue } - if (c == "\"") { - quoted=0 - if (depth == 1 && !invalid) { - if (key == "") key=token - else if (key == "tag_name") tag=token - } - continue - } - if (depth == 1 && (key == "" || key == "tag_name")) { - if (length(token) < 128) token=token c - else invalid=1 - } - continue - } - - # Outside strings: track objects, field boundaries, and prerelease. - if (c == "\"") { quoted=1; token=""; invalid=0; continue } - if (c == "{") { - depth++ - if (depth == 1) { key=""; tag=""; prerelease=1 } - } else if (c == "}") { - if (depth == 1) consider() - depth-- - } else if (depth == 1) { - if (c == ",") key="" - else if (key == "prerelease" && c == "f" && substr($0,i,5) == "false") prerelease=0 - } - } - } - END { print selected } - ' -} - -# Usage: github_api . Prints the response body. Runners that share an -# IP exhaust GitHub's anonymous rate limit, so send GITHUB_TOKEN or GH_TOKEN -# when one is set. The header goes through stdin, so the token stays out of -# the process list and of $BASH_COMMAND in error reports. Rate-limited -# responses (403, 429) are retried with a growing delay. -github_api() { - local token="${GITHUB_TOKEN:-${GH_TOKEN:-}}" response status attempt - for attempt in 1 2 3; do - if [[ -n "$token" ]]; then - response=$(curl -sSL "${curl_retry[@]}" -w '\n%{http_code}' -H @- "$1" \ - <<< "Authorization: Bearer ${token}") || return - else - response=$(curl -sSL "${curl_retry[@]}" -w '\n%{http_code}' "$1") || return - fi - status="${response##*$'\n'}" - case "$status" in - 200) - printf '%s\n' "${response%$'\n'*}" - return 0 - ;; - 403|429) ;; - *) return 22 ;; - esac - if [[ "$attempt" != 3 ]]; then - muted "GitHub rate-limited the request; retrying in $((attempt * 2))s..." >&2 - sleep $((attempt * 2)) - fi - done - if [[ -z "$token" ]]; then - muted "GitHub rate-limited this machine. Setting GITHUB_TOKEN raises the limit." >&2 - fi - return 22 -} - # Prefers the gzip asset (~37 MB instead of ~99 MB) and falls back to the raw # binary when it is missing or unusable. A checksum mismatch on both tries is # fatal, never a reason to fall back. diff --git a/packages/cli/install.ps1 b/packages/cli/install.ps1 index 2aa5c9710..8f9bec0df 100644 --- a/packages/cli/install.ps1 +++ b/packages/cli/install.ps1 @@ -83,8 +83,8 @@ function Install-SentryCli { # Step 2: find the release to install # # Sentry's release registry is the source of truth for versions, download - # URLs, and checksums. GitHub releases are only a fallback for registry - # outages, and they have no checksums. + # URLs, and checksums. When it is down, a pinned version still downloads + # from its GitHub release, without checksums; "latest" needs the registry. # ------------------------------------------------------------------------- # Returns @{ Version; Gz; Raw }, where Gz and Raw are the compressed and @@ -120,9 +120,10 @@ function Install-SentryCli { return $release } + if (-not $version) { + Stop-Install "Failed to fetch latest stable version from Sentry's release registry. Retry or set SENTRY_VERSION to install a specific version." + } Write-Host "Could not resolve $registryPath from Sentry's release registry. Trying GitHub..." -ForegroundColor DarkGray - if (-not $version) { $version = Find-LatestToolkitVersion } - $state.Version = $version Write-Warning 'GitHub fallback downloads are not checksum-verified.' $base = "https://github.com/getsentry/toolkit/releases/download/cli@$version/$asset" return @{ @@ -161,31 +162,6 @@ function Install-SentryCli { return @{ Url = "$($entry.Value.url)"; Sha256 = "$($entry.Value.checksums.'sha256-hex')" } } - # Registry outage fallback: the newest stable `cli@x.y.z` release. The repo - # also publishes MCP releases, so this may page through several pages of - # those first. - function Find-LatestToolkitVersion { - for ($page = 1; $page -le 20; $page++) { - try { - # Windows PowerShell 5.1 emits a JSON array as one object; piping - # through ForEach-Object flattens it so an empty page has no items. - $releases = @(Invoke-RestMethod -UseBasicParsing -TimeoutSec 30 ` - -Uri "https://api.github.com/repos/getsentry/toolkit/releases?per_page=100&page=$page" | - ForEach-Object { $_ }) - } catch { - Stop-Install 'Failed to list Toolkit releases' - } - if ($releases.Count -eq 0) { break } - - foreach ($release in $releases) { - if (-not $release.prerelease -and "$($release.tag_name)" -match '^cli@\d+\.\d+\.\d+$') { - return "$($release.tag_name)".Substring(4) - } - } - } - Stop-Install "Failed to fetch latest stable version from Sentry's release registry and GitHub. Retry or set SENTRY_VERSION to install a specific version." - } - # ------------------------------------------------------------------------- # Step 3: download and verify the binary # ------------------------------------------------------------------------- diff --git a/packages/cli/test/lib/install-ps1-script.test.ts b/packages/cli/test/lib/install-ps1-script.test.ts index 56412df8b..68cc2e07c 100644 --- a/packages/cli/test/lib/install-ps1-script.test.ts +++ b/packages/cli/test/lib/install-ps1-script.test.ts @@ -70,13 +70,6 @@ function Invoke-RestMethod { $body = (Get-Content -Raw -LiteralPath $env:SENTRY_TEST_REGISTRY_BODY).Replace('__VERSION__', $version) return ($body | ConvertFrom-Json) } - if ($Uri -like 'https://api.github.com/repos/getsentry/toolkit/releases?per_page=100&page=*') { - $page = $Uri.Split('=')[-1] - $file = [Environment]::GetEnvironmentVariable("SENTRY_TEST_RELEASES_PAGE_$page") - # Like Windows PowerShell 5.1, emit each JSON array as a single object. - if ($file) { return ,(Get-Content -Raw -LiteralPath $file | ConvertFrom-Json -NoEnumerate) } - return ,@() - } throw "Unexpected Invoke-RestMethod $Uri" } function Invoke-WebRequest { diff --git a/packages/cli/test/lib/install-scenarios.ts b/packages/cli/test/lib/install-scenarios.ts index 402332a61..b9bac2c70 100644 --- a/packages/cli/test/lib/install-scenarios.ts +++ b/packages/cli/test/lib/install-scenarios.ts @@ -9,7 +9,6 @@ * - SENTRY_TEST_REGISTRY_BODY: path to a registry response template; every * `__VERSION__` is replaced by the requested version (or * SENTRY_TEST_LATEST_VERSION for `latest`) - * - SENTRY_TEST_RELEASES_PAGE_: path to GitHub releases page n (else `[]`) * - SENTRY_TEST_GZ_MISSING=1: gzip asset downloads fail * - SENTRY_TEST_GZ_FILE / SENTRY_TEST_RAW_FILE: bytes served for downloads * Every requested URL is recorded, in order, for `requests` assertions. @@ -21,8 +20,6 @@ import { join } from "node:path"; export const LATEST_VERSION = "0.47.0"; const REGISTRY = "https://release-registry.services.sentry.io/apps/sentry"; -const RELEASES_PAGE = - "https://api.github.com/repos/getsentry/toolkit/releases?per_page=100&page="; export function toolkitDownload(version: string, asset: string): string { return `https://github.com/getsentry/toolkit/releases/download/cli@${version}/${asset}`; @@ -54,8 +51,6 @@ export interface InstallScenario { /** Value of SENTRY_VERSION, if any. */ version?: string; registry: RegistryResponse; - /** GitHub releases pages served during a registry outage. */ - releases?: { tag_name: string; prerelease: boolean }[][]; gzMissing?: boolean; ok: boolean; /** Every URL the installer requests, in order. */ @@ -126,11 +121,6 @@ export function applyScenario( : "", ); env.SENTRY_TEST_REGISTRY_BODY = body; - for (const [index, page] of (scenario.releases ?? []).entries()) { - const file = join(dir, `releases-${index + 1}.json`); - writeFileSync(file, JSON.stringify(page, null, 2)); - env[`SENTRY_TEST_RELEASES_PAGE_${index + 1}`] = file; - } if (scenario.gzMissing) { env.SENTRY_TEST_GZ_MISSING = "1"; } @@ -205,25 +195,6 @@ export const INSTALL_SCENARIOS: InstallScenario[] = [ output: ["Invalid release version: 1.2"], requests: () => [], }, - { - name: "falls back to the newest stable Toolkit CLI release when the registry is down", - registry: { status: 503 }, - releases: [ - [ - { tag_name: "mcp@1.2.3", prerelease: false }, - { tag_name: "cli@0.48.0", prerelease: true }, - ], - [{ tag_name: "cli@0.46.0", prerelease: false }], - ], - ok: true, - output: ["Trying GitHub", "not checksum-verified"], - requests: (asset) => [ - `${REGISTRY}/latest`, - `${RELEASES_PAGE}1`, - `${RELEASES_PAGE}2`, - toolkitDownload("0.46.0", `${asset}.gz`), - ], - }, { name: "uses the pinned Toolkit release when the registry is down", version: "0.46.0", @@ -236,10 +207,10 @@ export const INSTALL_SCENARIOS: InstallScenario[] = [ ], }, { - name: "stops when neither the registry nor GitHub has a stable release", + name: "stops when the registry is down and no version is pinned", registry: { status: 503 }, ok: false, output: ["Failed to fetch latest stable version"], - requests: () => [`${REGISTRY}/latest`, `${RELEASES_PAGE}1`], + requests: () => [`${REGISTRY}/latest`], }, ]; diff --git a/packages/cli/test/lib/install-script.test.ts b/packages/cli/test/lib/install-script.test.ts index 957a619dc..0d224be71 100644 --- a/packages/cli/test/lib/install-script.test.ts +++ b/packages/cli/test/lib/install-script.test.ts @@ -140,17 +140,6 @@ case "$url" in https://o1.ingest.us.sentry.io/api/*/envelope/) printf '%s\\n' "$data" > "$SENTRY_TEST_DIR/error-report" ;; - *"/repos/getsentry/toolkit/releases?per_page=100&page="*) - if [[ " $* " == *" -H @- "* ]]; then cat >> "$SENTRY_TEST_DIR/github-headers"; fi - if (( $(nth github) <= \${SENTRY_TEST_GITHUB_RATE_LIMITED:-0} )); then - printf '{"message":"API rate limit exceeded"}' - printf "\${write_out//'%{http_code}'/403}" - exit 0 - fi - page_file="SENTRY_TEST_RELEASES_PAGE_\${url##*=}" - if [[ -n "\${!page_file:-}" ]]; then cat "\${!page_file}"; else printf '[]'; fi - printf "\${write_out//'%{http_code}'/200}" - ;; https://github.com/*/releases/download/*.gz) if [[ "\${SENTRY_TEST_GZ_MISSING:-}" == "1" ]]; then exit 22; fi if (( $(nth gz) <= \${SENTRY_TEST_GZ_CORRUPT:-0} )); then @@ -515,124 +504,6 @@ process.exitCode = result.status ?? 1; }, ); - test("checks further release pages before selecting a stable Toolkit CLI", () => { - const firstPage = join(testDir, "releases-1.json"); - const secondPage = join(testDir, "releases-2.json"); - writeFileSync( - firstPage, - '[\n {\n "tag_name": "mcp@1.0.0",\n "prerelease": false\n }\n]\n', - ); - writeFileSync( - secondPage, - '[\n {\n "tag_name": "cli@0.46.0",\n "prerelease": false\n }\n]\n', - ); - env.SENTRY_TEST_RELEASES_PAGE_1 = firstPage; - env.SENTRY_TEST_RELEASES_PAGE_2 = secondPage; - env.SENTRY_TEST_REGISTRY_STATUS = "503"; - const result = spawnSync("bash", [installScript, "--no-modify-path"], { - env, - encoding: "utf8", - timeout: 10_000, - }); - - expect(result.status, result.stdout + result.stderr).toBe(0); - expect(recorded("curl-urls").slice(0, 3)).toEqual([ - "https://release-registry.services.sentry.io/apps/sentry/latest", - "https://api.github.com/repos/getsentry/toolkit/releases?per_page=100&page=1", - "https://api.github.com/repos/getsentry/toolkit/releases?per_page=100&page=2", - ]); - expect(recorded("curl-urls")[3]).toBe( - toolkitDownload("0.46.0", `${hostAsset}.gz`), - ); - }); - - test("skips SemVer prereleases even when GitHub marks them stable", () => { - const firstPage = join(testDir, "releases-1.json"); - writeFileSync( - firstPage, - '[\n {\n "tag_name": "cli@0.47.0-dev.1",\n "prerelease": false\n },\n {\n "tag_name": "cli@0.46.0",\n "prerelease": false\n }\n]\n', - ); - env.SENTRY_TEST_RELEASES_PAGE_1 = firstPage; - env.SENTRY_TEST_REGISTRY_STATUS = "503"; - const result = spawnSync("bash", [installScript, "--no-modify-path"], { - env, - encoding: "utf8", - timeout: 10_000, - }); - - expect(result.status, result.stdout + result.stderr).toBe(0); - expect(recorded("curl-urls")[2]).toBe( - toolkitDownload("0.46.0", `${hostAsset}.gz`), - ); - expect(recorded("setup-args")).toContain("stable"); - }); - - test("selects the first stable CLI release from compact GitHub JSON", () => { - const firstPage = join(testDir, "releases-1.json"); - writeFileSync( - firstPage, - JSON.stringify([ - { - tag_name: "mcp@0.42.0", - prerelease: false, - body: 'A quoted "tag_name" in the release notes', - }, - { - prerelease: false, - tag_name: "cli@0.47.0-dev.1", - }, - { - prerelease: false, - assets: [{ tag_name: "cli@99.0.0", prerelease: false }], - tag_name: "cli@0.46.0", - }, - ]), - ); - env.SENTRY_TEST_RELEASES_PAGE_1 = firstPage; - env.SENTRY_TEST_REGISTRY_STATUS = "503"; - const result = spawnSync("bash", [installScript, "--no-modify-path"], { - env, - encoding: "utf8", - timeout: 10_000, - }); - - expect(result.status, result.stdout + result.stderr).toBe(0); - expect(recorded("curl-urls")[2]).toBe( - toolkitDownload("0.46.0", `${hostAsset}.gz`), - ); - }); - - test("reads a large releases page without SIGPIPE and selects its first stable CLI", () => { - const firstPage = join(testDir, "releases-large.json"); - writeFileSync( - firstPage, - `[ - { - "tag_name": "cli@0.46.0", - "prerelease": false - }, - { - "tag_name": "cli@0.45.0", - "prerelease": false, - "body": "${"x".repeat(256 * 1024)}" - } -]`, - ); - env.SENTRY_TEST_RELEASES_PAGE_1 = firstPage; - env.SENTRY_TEST_REGISTRY_STATUS = "503"; - const result = spawnSync("bash", [installScript, "--no-modify-path"], { - env, - encoding: "utf8", - timeout: 10_000, - }); - - expect(result.status, result.stdout + result.stderr).toBe(0); - expect(recorded("curl-urls")).toContain( - toolkitDownload("0.46.0", `${hostAsset}.gz`), - ); - expect(existsSync(join(installDir, "sentry"))).toBe(true); - }); - test("directs musl users to the npm package before downloading a glibc binary", () => { writeFileSync( join(binDir, "uname"), @@ -795,46 +666,6 @@ exec /usr/bin/gunzip "$@" expect(readdirSync(installDir)).toEqual([]); }); - describe("when the registry is down", () => { - beforeEach(() => { - env.SENTRY_TEST_REGISTRY_STATUS = "503"; - const page = join(testDir, "releases-1.json"); - writeFileSync( - page, - JSON.stringify([{ tag_name: "cli@0.46.0", prerelease: false }]), - ); - env.SENTRY_TEST_RELEASES_PAGE_1 = page; - }); - - test("authenticates to GitHub without exposing the token", () => { - env.GITHUB_TOKEN = "test-token-value"; - delete env.SENTRY_CLI_NO_TELEMETRY; - const result = install(); - - expect(result.status, result.output).toBe(0); - expect(recorded("github-headers")).toEqual([ - "Authorization: Bearer test-token-value", - ]); - expect(recorded("curl-args").join("\n")).not.toContain( - "test-token-value", - ); - expect(result.output).not.toContain("test-token-value"); - }); - - test("waits out a GitHub rate limit", () => { - env.SENTRY_TEST_GITHUB_RATE_LIMITED = "1"; - const result = install(); - - expect(result.status, result.output).toBe(0); - const firstPage = - "https://api.github.com/repos/getsentry/toolkit/releases?per_page=100&page=1"; - expect( - recorded("curl-urls").filter((url) => url === firstPage), - ).toHaveLength(2); - expect(existsSync(join(installDir, "sentry"))).toBe(true); - }); - }); - // CLI-BJ: the trap reported only a line number, which bash 3.2 sets to the // closing `fi` of the enclosing block. test("reports the failing command of an unexpected failure without local paths", () => {